r26227: Make loadparm_context part of a server task, move loadparm_contexts further...
[jelmer/samba4-debian.git] / source / auth / sam.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Password and authentication handling
4    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2001-2004
5    Copyright (C) Gerald Carter                             2003
6    Copyright (C) Stefan Metzmacher                         2005
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "system/time.h"
24 #include "auth/auth.h"
25 #include <ldb.h>
26 #include "util/util_ldb.h"
27 #include "dsdb/samdb/samdb.h"
28 #include "libcli/security/security.h"
29 #include "libcli/ldap/ldap.h"
30 #include "librpc/gen_ndr/ndr_netlogon.h"
31 #include "param/param.h"
32
33 const char *user_attrs[] = {
34         /* required for the krb5 kdc */
35         "objectClass",
36         "sAMAccountName",
37         "userPrincipalName",
38         "servicePrincipalName",
39         "msDS-KeyVersionNumber",
40         "supplementalCredentials",
41
42         /* passwords */
43         "dBCSPwd", 
44         "unicodePwd",
45
46         "userAccountControl",
47
48         "pwdLastSet",
49         "accountExpires",
50         "logonHours",
51         "objectSid",
52
53         /* check 'allowed workstations' */
54         "userWorkstations",
55                        
56         /* required for server_info, not access control: */
57         "displayName",
58         "scriptPath",
59         "profilePath",
60         "homeDirectory",
61         "homeDrive",
62         "lastLogon",
63         "lastLogoff",
64         "accountExpires",
65         "badPwdCount",
66         "logonCount",
67         "primaryGroupID",
68         NULL,
69 };
70
71 const char *domain_ref_attrs[] =  {"nETBIOSName", "nCName", 
72                                    "dnsRoot", "objectClass", NULL};
73
74 /****************************************************************************
75  Check if a user is allowed to logon at this time. Note this is the
76  servers local time, as logon hours are just specified as a weekly
77  bitmask.
78 ****************************************************************************/
79                                                                                                               
80 static bool logon_hours_ok(struct ldb_message *msg, const char *name_for_logs)
81 {
82         /* In logon hours first bit is Sunday from 12AM to 1AM */
83         const struct ldb_val *hours;
84         struct tm *utctime;
85         time_t lasttime;
86         const char *asct;
87         uint8_t bitmask, bitpos;
88
89         hours = ldb_msg_find_ldb_val(msg, "logonHours");
90         if (!hours) {
91                 DEBUG(5,("logon_hours_ok: No hours restrictions for user %s\n", name_for_logs));
92                 return true;
93         }
94
95         if (hours->length != 168/8) {
96                 DEBUG(5,("logon_hours_ok: malformed logon hours restrictions for user %s\n", name_for_logs));
97                 return true;            
98         }
99
100         lasttime = time(NULL);
101         utctime = gmtime(&lasttime);
102         if (!utctime) {
103                 DEBUG(1, ("logon_hours_ok: failed to get gmtime. Failing logon for user %s\n",
104                         name_for_logs));
105                 return false;
106         }
107
108         /* find the corresponding byte and bit */
109         bitpos = (utctime->tm_wday * 24 + utctime->tm_hour) % 168;
110         bitmask = 1 << (bitpos % 8);
111
112         if (! (hours->data[bitpos/8] & bitmask)) {
113                 struct tm *t = localtime(&lasttime);
114                 if (!t) {
115                         asct = "INVALID TIME";
116                 } else {
117                         asct = asctime(t);
118                         if (!asct) {
119                                 asct = "INVALID TIME";
120                         }
121                 }
122                 
123                 DEBUG(1, ("logon_hours_ok: Account for user %s not allowed to "
124                           "logon at this time (%s).\n",
125                           name_for_logs, asct ));
126                 return false;
127         }
128
129         asct = asctime(utctime);
130         DEBUG(5,("logon_hours_ok: user %s allowed to logon at this time (%s)\n",
131                 name_for_logs, asct ? asct : "UNKNOWN TIME" ));
132
133         return true;
134 }
135
136 /****************************************************************************
137  Do a specific test for a SAM_ACCOUNT being vaild for this connection 
138  (ie not disabled, expired and the like).
139 ****************************************************************************/
140 _PUBLIC_ NTSTATUS authsam_account_ok(TALLOC_CTX *mem_ctx,
141                             struct ldb_context *sam_ctx,
142                             uint32_t logon_parameters,
143                             struct ldb_message *msg,
144                             struct ldb_message *msg_domain_ref,
145                             const char *logon_workstation,
146                             const char *name_for_logs)
147 {
148         uint16_t acct_flags;
149         const char *workstation_list;
150         NTTIME acct_expiry;
151         NTTIME must_change_time;
152         NTTIME last_set_time;
153
154         struct ldb_dn *domain_dn = samdb_result_dn(sam_ctx, mem_ctx, msg_domain_ref, "nCName", ldb_dn_new(mem_ctx, sam_ctx, NULL));
155
156         NTTIME now;
157         DEBUG(4,("authsam_account_ok: Checking SMB password for user %s\n", name_for_logs));
158
159         acct_flags = samdb_result_acct_flags(msg, "userAccountControl");
160         
161         acct_expiry = samdb_result_nttime(msg, "accountExpires", 0);
162         must_change_time = samdb_result_force_password_change(sam_ctx, mem_ctx, 
163                                                               domain_dn, msg);
164         last_set_time = samdb_result_nttime(msg, "pwdLastSet", 0);
165
166         workstation_list = samdb_result_string(msg, "userWorkstations", NULL);
167
168         /* Quit if the account was disabled. */
169         if (acct_flags & ACB_DISABLED) {
170                 DEBUG(1,("authsam_account_ok: Account for user '%s' was disabled.\n", name_for_logs));
171                 return NT_STATUS_ACCOUNT_DISABLED;
172         }
173
174         /* Quit if the account was locked out. */
175         if (acct_flags & ACB_AUTOLOCK) {
176                 DEBUG(1,("authsam_account_ok: Account for user %s was locked out.\n", name_for_logs));
177                 return NT_STATUS_ACCOUNT_LOCKED_OUT;
178         }
179
180         /* Test account expire time */
181         unix_to_nt_time(&now, time(NULL));
182         if (now > acct_expiry) {
183                 DEBUG(1,("authsam_account_ok: Account for user '%s' has expired.\n", name_for_logs));
184                 DEBUG(3,("authsam_account_ok: Account expired at '%s'.\n", 
185                          nt_time_string(mem_ctx, acct_expiry)));
186                 return NT_STATUS_ACCOUNT_EXPIRED;
187         }
188
189         if (!(acct_flags & ACB_PWNOEXP)) {
190                 /* check for immediate expiry "must change at next logon" */
191                 if (must_change_time == 0 && last_set_time != 0) {
192                         DEBUG(1,("sam_account_ok: Account for user '%s' password must change!.\n", 
193                                  name_for_logs));
194                         return NT_STATUS_PASSWORD_MUST_CHANGE;
195                 }
196
197                 /* check for expired password */
198                 if ((must_change_time != 0) && (must_change_time < now)) {
199                         DEBUG(1,("sam_account_ok: Account for user '%s' password expired!.\n", 
200                                  name_for_logs));
201                         DEBUG(1,("sam_account_ok: Password expired at '%s' unix time.\n", 
202                                  nt_time_string(mem_ctx, must_change_time)));
203                         return NT_STATUS_PASSWORD_EXPIRED;
204                 }
205         }
206
207         /* Test workstation. Workstation list is comma separated. */
208         if (logon_workstation && workstation_list && *workstation_list) {
209                 bool invalid_ws = true;
210                 int i;
211                 const char **workstations = str_list_make(mem_ctx, workstation_list, ",");
212                 
213                 for (i = 0; workstations && workstations[i]; i++) {
214                         DEBUG(10,("sam_account_ok: checking for workstation match '%s' and '%s'\n",
215                                   workstations[i], logon_workstation));
216
217                         if (strequal(workstations[i], logon_workstation)) {
218                                 invalid_ws = false;
219                                 break;
220                         }
221                 }
222
223                 talloc_free(workstations);
224
225                 if (invalid_ws) {
226                         return NT_STATUS_INVALID_WORKSTATION;
227                 }
228         }
229         
230         if (!logon_hours_ok(msg, name_for_logs)) {
231                 return NT_STATUS_INVALID_LOGON_HOURS;
232         }
233         
234         if (acct_flags & ACB_DOMTRUST) {
235                 DEBUG(2,("sam_account_ok: Domain trust account %s denied by server\n", name_for_logs));
236                 return NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT;
237         }
238         
239         if (!(logon_parameters & MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT)) {
240                 if (acct_flags & ACB_SVRTRUST) {
241                         DEBUG(2,("sam_account_ok: Server trust account %s denied by server\n", name_for_logs));
242                         return NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT;
243                 }
244         }
245         if (!(logon_parameters & MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT)) {
246                 if (acct_flags & ACB_WSTRUST) {
247                         DEBUG(4,("sam_account_ok: Wksta trust account %s denied by server\n", name_for_logs));
248                         return NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT;
249                 }
250         }
251
252         return NT_STATUS_OK;
253 }
254
255 _PUBLIC_ NTSTATUS authsam_make_server_info(TALLOC_CTX *mem_ctx, struct ldb_context *sam_ctx,
256                                   struct ldb_message *msg,
257                                   struct ldb_message *msg_domain_ref,
258                                   DATA_BLOB user_sess_key, DATA_BLOB lm_sess_key,
259                                   struct auth_serversupplied_info **_server_info)
260 {
261         struct auth_serversupplied_info *server_info;
262         struct ldb_message **group_msgs;
263         int group_ret;
264         const char *group_attrs[3] = { "sAMAccountType", "objectSid", NULL }; 
265         /* find list of sids */
266         struct dom_sid **groupSIDs = NULL;
267         struct dom_sid *account_sid;
268         struct dom_sid *primary_group_sid;
269         const char *str;
270         struct ldb_dn *ncname;
271         int i;
272         uint_t rid;
273         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
274
275         group_ret = gendb_search(sam_ctx,
276                                  tmp_ctx, NULL, &group_msgs, group_attrs,
277                                  "(&(member=%s)(sAMAccountType=*))", 
278                                  ldb_dn_get_linearized(msg->dn));
279         if (group_ret == -1) {
280                 talloc_free(tmp_ctx);
281                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
282         }
283
284         server_info = talloc(mem_ctx, struct auth_serversupplied_info);
285         NT_STATUS_HAVE_NO_MEMORY(server_info);
286         
287         if (group_ret > 0) {
288                 groupSIDs = talloc_array(server_info, struct dom_sid *, group_ret);
289                 NT_STATUS_HAVE_NO_MEMORY(groupSIDs);
290         }
291
292         /* Need to unroll some nested groups, but not aliases */
293         for (i = 0; i < group_ret; i++) {
294                 groupSIDs[i] = samdb_result_dom_sid(groupSIDs, 
295                                                     group_msgs[i], "objectSid");
296                 NT_STATUS_HAVE_NO_MEMORY(groupSIDs[i]);
297         }
298
299         talloc_free(tmp_ctx);
300
301         account_sid = samdb_result_dom_sid(server_info, msg, "objectSid");
302         NT_STATUS_HAVE_NO_MEMORY(account_sid);
303
304         primary_group_sid = dom_sid_dup(server_info, account_sid);
305         NT_STATUS_HAVE_NO_MEMORY(primary_group_sid);
306
307         rid = samdb_result_uint(msg, "primaryGroupID", ~0);
308         if (rid == ~0) {
309                 if (group_ret > 0) {
310                         primary_group_sid = groupSIDs[0];
311                 } else {
312                         primary_group_sid = NULL;
313                 }
314         } else {
315                 primary_group_sid->sub_auths[primary_group_sid->num_auths-1] = rid;
316         }
317
318         server_info->account_sid = account_sid;
319         server_info->primary_group_sid = primary_group_sid;
320         
321         server_info->n_domain_groups = group_ret;
322         server_info->domain_groups = groupSIDs;
323
324         server_info->account_name = talloc_steal(server_info, samdb_result_string(msg, "sAMAccountName", NULL));
325
326         server_info->domain_name = talloc_steal(server_info, samdb_result_string(msg_domain_ref, "nETBIOSName", NULL));
327
328         str = samdb_result_string(msg, "displayName", "");
329         server_info->full_name = talloc_strdup(server_info, str);
330         NT_STATUS_HAVE_NO_MEMORY(server_info->full_name);
331
332         str = samdb_result_string(msg, "scriptPath", "");
333         server_info->logon_script = talloc_strdup(server_info, str);
334         NT_STATUS_HAVE_NO_MEMORY(server_info->logon_script);
335
336         str = samdb_result_string(msg, "profilePath", "");
337         server_info->profile_path = talloc_strdup(server_info, str);
338         NT_STATUS_HAVE_NO_MEMORY(server_info->profile_path);
339
340         str = samdb_result_string(msg, "homeDirectory", "");
341         server_info->home_directory = talloc_strdup(server_info, str);
342         NT_STATUS_HAVE_NO_MEMORY(server_info->home_directory);
343
344         str = samdb_result_string(msg, "homeDrive", "");
345         server_info->home_drive = talloc_strdup(server_info, str);
346         NT_STATUS_HAVE_NO_MEMORY(server_info->home_drive);
347
348         server_info->logon_server = talloc_strdup(server_info, lp_netbios_name(global_loadparm));
349         NT_STATUS_HAVE_NO_MEMORY(server_info->logon_server);
350
351         server_info->last_logon = samdb_result_nttime(msg, "lastLogon", 0);
352         server_info->last_logoff = samdb_result_nttime(msg, "lastLogoff", 0);
353         server_info->acct_expiry = samdb_result_nttime(msg, "accountExpires", 0);
354         server_info->last_password_change = samdb_result_nttime(msg, "pwdLastSet", 0);
355
356         ncname = samdb_result_dn(sam_ctx, mem_ctx, msg_domain_ref, "nCName", NULL);
357         if (!ncname) {
358                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
359         }
360         server_info->allow_password_change
361                 = samdb_result_allow_password_change(sam_ctx, mem_ctx, 
362                                                      ncname, msg, "pwdLastSet");
363         server_info->force_password_change
364                 = samdb_result_force_password_change(sam_ctx, mem_ctx, 
365                                                      ncname, msg);
366         
367         server_info->logon_count = samdb_result_uint(msg, "logonCount", 0);
368         server_info->bad_password_count = samdb_result_uint(msg, "badPwdCount", 0);
369
370         server_info->acct_flags = samdb_result_acct_flags(msg, "userAccountControl");
371
372         server_info->user_session_key = user_sess_key;
373         server_info->lm_session_key = lm_sess_key;
374
375         server_info->authenticated = true;
376
377         *_server_info = server_info;
378
379         return NT_STATUS_OK;
380 }
381
382 _PUBLIC_ NTSTATUS sam_get_results_principal(struct ldb_context *sam_ctx,
383                                    TALLOC_CTX *mem_ctx, const char *principal,
384                                    struct ldb_message ***msgs,
385                                    struct ldb_message ***msgs_domain_ref)
386 {                          
387         struct ldb_dn *user_dn, *domain_dn;
388         NTSTATUS nt_status;
389         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
390         int ret;
391         struct ldb_dn *partitions_basedn = samdb_partitions_dn(sam_ctx, mem_ctx);
392
393         if (!tmp_ctx) {
394                 return NT_STATUS_NO_MEMORY;
395         }
396
397         nt_status = crack_user_principal_name(sam_ctx, tmp_ctx, principal, &user_dn, &domain_dn);
398         if (!NT_STATUS_IS_OK(nt_status)) {
399                 talloc_free(tmp_ctx);
400                 return nt_status;
401         }
402         
403         /* grab domain info from the reference */
404         ret = gendb_search(sam_ctx, tmp_ctx, partitions_basedn, msgs_domain_ref, domain_ref_attrs,
405                            "(ncName=%s)", ldb_dn_get_linearized(domain_dn));
406
407         if (ret != 1) {
408                 talloc_free(tmp_ctx);
409                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
410         }
411         
412         /* pull the user attributes */
413         ret = gendb_search_dn(sam_ctx, tmp_ctx, user_dn, msgs, user_attrs);
414         if (ret != 1) {
415                 talloc_free(tmp_ctx);
416                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
417         }
418         talloc_steal(mem_ctx, *msgs);
419         talloc_steal(mem_ctx, *msgs_domain_ref);
420         talloc_free(tmp_ctx);
421         
422         return NT_STATUS_OK;
423 }
424                                    
425 /* Used in the gensec_gssapi and gensec_krb5 server-side code, where the PAC isn't available */
426 NTSTATUS sam_get_server_info_principal(TALLOC_CTX *mem_ctx, const char *principal,
427                                        struct auth_serversupplied_info **server_info)
428 {
429         NTSTATUS nt_status;
430         DATA_BLOB user_sess_key = data_blob(NULL, 0);
431         DATA_BLOB lm_sess_key = data_blob(NULL, 0);
432
433         struct ldb_message **msgs;
434         struct ldb_message **msgs_domain_ref;
435         struct ldb_context *sam_ctx;
436
437         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
438         if (!tmp_ctx) {
439                 return NT_STATUS_NO_MEMORY;
440         }
441
442         sam_ctx = samdb_connect(tmp_ctx, global_loadparm, system_session(tmp_ctx));
443         if (sam_ctx == NULL) {
444                 talloc_free(tmp_ctx);
445                 return NT_STATUS_INVALID_SYSTEM_SERVICE;
446         }
447
448         nt_status = sam_get_results_principal(sam_ctx, tmp_ctx, principal, 
449                                               &msgs, &msgs_domain_ref);
450         if (!NT_STATUS_IS_OK(nt_status)) {
451                 return nt_status;
452         }
453
454         nt_status = authsam_make_server_info(tmp_ctx, sam_ctx, msgs[0], msgs_domain_ref[0],
455                                              user_sess_key, lm_sess_key,
456                                              server_info);
457         if (NT_STATUS_IS_OK(nt_status)) {
458                 talloc_steal(mem_ctx, *server_info);
459         }
460         talloc_free(tmp_ctx);
461         return nt_status;
462 }