s4:auth/sam: don't update lastLogon just because it's 0 currently
[sfrench/samba-autobuild/.git] / source4 / auth / sam.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Password and authentication handling
4    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2001-2010
5    Copyright (C) Gerald Carter                             2003
6    Copyright (C) Stefan Metzmacher                         2005
7    Copyright (C) Matthias Dieter Wallnöfer                 2009
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "system/time.h"
25 #include "auth/auth.h"
26 #include <ldb.h>
27 #include "dsdb/samdb/samdb.h"
28 #include "libcli/security/security.h"
29 #include "auth/auth_sam.h"
30 #include "dsdb/common/util.h"
31 #include "libcli/ldap/ldap_ndr.h"
32 #include "param/param.h"
33
34 #define KRBTGT_ATTRS \
35         /* required for the krb5 kdc */         \
36         "objectClass",                          \
37         "sAMAccountName",                       \
38         "userPrincipalName",                    \
39         "servicePrincipalName",                 \
40         "msDS-KeyVersionNumber",                \
41         "msDS-SecondaryKrbTgtNumber",           \
42         "msDS-SupportedEncryptionTypes",        \
43         "supplementalCredentials",              \
44         "msDS-AllowedToDelegateTo",             \
45                                                 \
46         /* passwords */                         \
47         "dBCSPwd",                              \
48         "unicodePwd",                           \
49                                                 \
50         "userAccountControl",                   \
51         "msDS-User-Account-Control-Computed",   \
52         "objectSid",                            \
53                                                 \
54         "pwdLastSet",                           \
55         "msDS-UserPasswordExpiryTimeComputed",  \
56         "accountExpires"
57
58 const char *krbtgt_attrs[] = {
59         KRBTGT_ATTRS, NULL
60 };
61
62 const char *server_attrs[] = {
63         KRBTGT_ATTRS, NULL
64 };
65
66 const char *user_attrs[] = {
67         KRBTGT_ATTRS,
68
69         "logonHours",
70
71         /*
72          * To allow us to zero the badPwdCount and lockoutTime on
73          * successful logon, without database churn
74          */
75         "lockoutTime",
76
77         /* check 'allowed workstations' */
78         "userWorkstations",
79                        
80         /* required for user_info_dc, not access control: */
81         "displayName",
82         "scriptPath",
83         "profilePath",
84         "homeDirectory",
85         "homeDrive",
86         "lastLogon",
87         "lastLogonTimestamp",
88         "lastLogoff",
89         "accountExpires",
90         "badPwdCount",
91         "logonCount",
92         "primaryGroupID",
93         "memberOf",
94         "badPasswordTime",
95         "lmPwdHistory",
96         "ntPwdHistory",
97         NULL,
98 };
99
100 /****************************************************************************
101  Check if a user is allowed to logon at this time. Note this is the
102  servers local time, as logon hours are just specified as a weekly
103  bitmask.
104 ****************************************************************************/
105                                                                                                               
106 static bool logon_hours_ok(struct ldb_message *msg, const char *name_for_logs)
107 {
108         /* In logon hours first bit is Sunday from 12AM to 1AM */
109         const struct ldb_val *hours;
110         struct tm *utctime;
111         time_t lasttime;
112         const char *asct;
113         uint8_t bitmask, bitpos;
114
115         hours = ldb_msg_find_ldb_val(msg, "logonHours");
116         if (!hours) {
117                 DEBUG(5,("logon_hours_ok: No hours restrictions for user %s\n", name_for_logs));
118                 return true;
119         }
120
121         if (hours->length != 168/8) {
122                 DEBUG(5,("logon_hours_ok: malformed logon hours restrictions for user %s\n", name_for_logs));
123                 return true;            
124         }
125
126         lasttime = time(NULL);
127         utctime = gmtime(&lasttime);
128         if (!utctime) {
129                 DEBUG(1, ("logon_hours_ok: failed to get gmtime. Failing logon for user %s\n",
130                         name_for_logs));
131                 return false;
132         }
133
134         /* find the corresponding byte and bit */
135         bitpos = (utctime->tm_wday * 24 + utctime->tm_hour) % 168;
136         bitmask = 1 << (bitpos % 8);
137
138         if (! (hours->data[bitpos/8] & bitmask)) {
139                 struct tm *t = localtime(&lasttime);
140                 if (!t) {
141                         asct = "INVALID TIME";
142                 } else {
143                         asct = asctime(t);
144                         if (!asct) {
145                                 asct = "INVALID TIME";
146                         }
147                 }
148                 
149                 DEBUG(1, ("logon_hours_ok: Account for user %s not allowed to "
150                           "logon at this time (%s).\n",
151                           name_for_logs, asct ));
152                 return false;
153         }
154
155         asct = asctime(utctime);
156         DEBUG(5,("logon_hours_ok: user %s allowed to logon at this time (%s)\n",
157                 name_for_logs, asct ? asct : "UNKNOWN TIME" ));
158
159         return true;
160 }
161
162 /****************************************************************************
163  Do a specific test for a SAM_ACCOUNT being valid for this connection
164  (ie not disabled, expired and the like).
165 ****************************************************************************/
166 _PUBLIC_ NTSTATUS authsam_account_ok(TALLOC_CTX *mem_ctx,
167                                      struct ldb_context *sam_ctx,
168                                      uint32_t logon_parameters,
169                                      struct ldb_dn *domain_dn,
170                                      struct ldb_message *msg,
171                                      const char *logon_workstation,
172                                      const char *name_for_logs,
173                                      bool allow_domain_trust,
174                                      bool password_change)
175 {
176         uint16_t acct_flags;
177         const char *workstation_list;
178         NTTIME acct_expiry;
179         NTTIME must_change_time;
180         struct timeval tv_now = timeval_current();
181         NTTIME now = timeval_to_nttime(&tv_now);
182
183         DEBUG(4,("authsam_account_ok: Checking SMB password for user %s\n", name_for_logs));
184
185         acct_flags = samdb_result_acct_flags(msg, "msDS-User-Account-Control-Computed");
186         
187         acct_expiry = samdb_result_account_expires(msg);
188
189         /* Check for when we must change this password, taking the
190          * userAccountControl flags into account */
191         must_change_time = samdb_result_nttime(msg,
192                         "msDS-UserPasswordExpiryTimeComputed", 0);
193
194         workstation_list = ldb_msg_find_attr_as_string(msg, "userWorkstations", NULL);
195
196         /* Quit if the account was disabled. */
197         if (acct_flags & ACB_DISABLED) {
198                 DEBUG(2,("authsam_account_ok: Account for user '%s' was disabled.\n", name_for_logs));
199                 return NT_STATUS_ACCOUNT_DISABLED;
200         }
201
202         /* Quit if the account was locked out. */
203         if (acct_flags & ACB_AUTOLOCK) {
204                 DEBUG(2,("authsam_account_ok: Account for user %s was locked out.\n", name_for_logs));
205                 return NT_STATUS_ACCOUNT_LOCKED_OUT;
206         }
207
208         /* Test account expire time */
209         if (now > acct_expiry) {
210                 DEBUG(2,("authsam_account_ok: Account for user '%s' has expired.\n", name_for_logs));
211                 DEBUG(3,("authsam_account_ok: Account expired at '%s'.\n", 
212                          nt_time_string(mem_ctx, acct_expiry)));
213                 return NT_STATUS_ACCOUNT_EXPIRED;
214         }
215
216         /* check for immediate expiry "must change at next logon" (but not if this is a password change request) */
217         if ((must_change_time == 0) && !password_change) {
218                 DEBUG(2,("sam_account_ok: Account for user '%s' password must change!.\n",
219                          name_for_logs));
220                 return NT_STATUS_PASSWORD_MUST_CHANGE;
221         }
222
223         /* check for expired password (but not if this is a password change request) */
224         if ((must_change_time < now) && !password_change) {
225                 DEBUG(2,("sam_account_ok: Account for user '%s' password expired!.\n",
226                          name_for_logs));
227                 DEBUG(2,("sam_account_ok: Password expired at '%s' unix time.\n",
228                          nt_time_string(mem_ctx, must_change_time)));
229                 return NT_STATUS_PASSWORD_EXPIRED;
230         }
231
232         /* Test workstation. Workstation list is comma separated. */
233         if (logon_workstation && workstation_list && *workstation_list) {
234                 bool invalid_ws = true;
235                 int i;
236                 char **workstations = str_list_make(mem_ctx, workstation_list, ",");
237
238                 for (i = 0; workstations && workstations[i]; i++) {
239                         DEBUG(10,("sam_account_ok: checking for workstation match '%s' and '%s'\n",
240                                   workstations[i], logon_workstation));
241
242                         if (strequal(workstations[i], logon_workstation)) {
243                                 invalid_ws = false;
244                                 break;
245                         }
246                 }
247
248                 talloc_free(workstations);
249
250                 if (invalid_ws) {
251                         return NT_STATUS_INVALID_WORKSTATION;
252                 }
253         }
254         
255         if (!logon_hours_ok(msg, name_for_logs)) {
256                 return NT_STATUS_INVALID_LOGON_HOURS;
257         }
258         
259         if (!allow_domain_trust) {
260                 if (acct_flags & ACB_DOMTRUST) {
261                         DEBUG(2,("sam_account_ok: Domain trust account %s denied by server\n", name_for_logs));
262                         return NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT;
263                 }
264         }
265         if (!(logon_parameters & MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT)) {
266                 if (acct_flags & ACB_SVRTRUST) {
267                         DEBUG(2,("sam_account_ok: Server trust account %s denied by server\n", name_for_logs));
268                         return NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT;
269                 }
270         }
271         if (!(logon_parameters & MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT)) {
272                 /* TODO: this fails with current solaris client. We
273                    need to work with Gordon to work out why */
274                 if (acct_flags & ACB_WSTRUST) {
275                         DEBUG(4,("sam_account_ok: Wksta trust account %s denied by server\n", name_for_logs));
276                         return NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT;
277                 }
278         }
279
280         return NT_STATUS_OK;
281 }
282
283 _PUBLIC_ NTSTATUS authsam_make_user_info_dc(TALLOC_CTX *mem_ctx,
284                                            struct ldb_context *sam_ctx,
285                                            const char *netbios_name,
286                                            const char *domain_name,
287                                            struct ldb_dn *domain_dn, 
288                                            struct ldb_message *msg,
289                                            DATA_BLOB user_sess_key,
290                                            DATA_BLOB lm_sess_key,
291                                            struct auth_user_info_dc **_user_info_dc)
292 {
293         NTSTATUS status;
294         struct auth_user_info_dc *user_info_dc;
295         struct auth_user_info *info;
296         const char *str, *filter;
297         /* SIDs for the account and his primary group */
298         struct dom_sid *account_sid;
299         const char *primary_group_string;
300         const char *primary_group_dn;
301         DATA_BLOB primary_group_blob;
302         /* SID structures for the expanded group memberships */
303         struct dom_sid *sids = NULL;
304         unsigned int num_sids = 0, i;
305         struct dom_sid *domain_sid;
306         TALLOC_CTX *tmp_ctx;
307         struct ldb_message_element *el;
308
309         user_info_dc = talloc(mem_ctx, struct auth_user_info_dc);
310         NT_STATUS_HAVE_NO_MEMORY(user_info_dc);
311
312         tmp_ctx = talloc_new(user_info_dc);
313         if (user_info_dc == NULL) {
314                 TALLOC_FREE(user_info_dc);
315                 return NT_STATUS_NO_MEMORY;
316         }
317
318         sids = talloc_array(user_info_dc, struct dom_sid, 2);
319         if (sids == NULL) {
320                 TALLOC_FREE(user_info_dc);
321                 return NT_STATUS_NO_MEMORY;
322         }
323
324         num_sids = 2;
325
326         account_sid = samdb_result_dom_sid(user_info_dc, msg, "objectSid");
327         if (account_sid == NULL) {
328                 TALLOC_FREE(user_info_dc);
329                 return NT_STATUS_NO_MEMORY;
330         }
331
332         status = dom_sid_split_rid(tmp_ctx, account_sid, &domain_sid, NULL);
333         if (!NT_STATUS_IS_OK(status)) {
334                 talloc_free(user_info_dc);
335                 return status;
336         }
337
338         sids[PRIMARY_USER_SID_INDEX] = *account_sid;
339         sids[PRIMARY_GROUP_SID_INDEX] = *domain_sid;
340         sid_append_rid(&sids[PRIMARY_GROUP_SID_INDEX], ldb_msg_find_attr_as_uint(msg, "primaryGroupID", ~0));
341
342         /* Filter out builtin groups from this token.  We will search
343          * for builtin groups later, and not include them in the PAC
344          * on SamLogon validation info */
345         filter = talloc_asprintf(tmp_ctx, "(&(objectClass=group)(!(groupType:1.2.840.113556.1.4.803:=%u))(groupType:1.2.840.113556.1.4.803:=%u))", GROUP_TYPE_BUILTIN_LOCAL_GROUP, GROUP_TYPE_SECURITY_ENABLED);
346         if (filter == NULL) {
347                 TALLOC_FREE(user_info_dc);
348                 return NT_STATUS_NO_MEMORY;
349         }
350
351         primary_group_string = dom_sid_string(tmp_ctx, &sids[PRIMARY_GROUP_SID_INDEX]);
352         if (primary_group_string == NULL) {
353                 TALLOC_FREE(user_info_dc);
354                 return NT_STATUS_NO_MEMORY;
355         }
356
357         primary_group_dn = talloc_asprintf(tmp_ctx, "<SID=%s>", primary_group_string);
358         if (primary_group_dn == NULL) {
359                 TALLOC_FREE(user_info_dc);
360                 return NT_STATUS_NO_MEMORY;
361         }
362
363         primary_group_blob = data_blob_string_const(primary_group_dn);
364
365         /* Expands the primary group - this function takes in
366          * memberOf-like values, so we fake one up with the
367          * <SID=S-...> format of DN and then let it expand
368          * them, as long as they meet the filter - so only
369          * domain groups, not builtin groups
370          *
371          * The primary group is still treated specially, so we set the
372          * 'only childs' flag to true
373          */
374         status = dsdb_expand_nested_groups(sam_ctx, &primary_group_blob, true, filter,
375                                            user_info_dc, &sids, &num_sids);
376         if (!NT_STATUS_IS_OK(status)) {
377                 talloc_free(user_info_dc);
378                 return status;
379         }
380
381         /* Expands the additional groups */
382         el = ldb_msg_find_element(msg, "memberOf");
383         for (i = 0; el && i < el->num_values; i++) {
384                 /* This function takes in memberOf values and expands
385                  * them, as long as they meet the filter - so only
386                  * domain groups, not builtin groups */
387                 status = dsdb_expand_nested_groups(sam_ctx, &el->values[i], false, filter,
388                                                    user_info_dc, &sids, &num_sids);
389                 if (!NT_STATUS_IS_OK(status)) {
390                         talloc_free(user_info_dc);
391                         return status;
392                 }
393         }
394
395         user_info_dc->sids = sids;
396         user_info_dc->num_sids = num_sids;
397
398         user_info_dc->info = info = talloc_zero(user_info_dc, struct auth_user_info);
399         NT_STATUS_HAVE_NO_MEMORY(user_info_dc->info);
400
401         info->account_name = talloc_steal(info,
402                 ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL));
403
404         info->domain_name = talloc_strdup(info, domain_name);
405         if (info->domain_name == NULL) {
406                 TALLOC_FREE(user_info_dc);
407                 return NT_STATUS_NO_MEMORY;
408         }
409
410         str = ldb_msg_find_attr_as_string(msg, "displayName", "");
411         info->full_name = talloc_strdup(info, str);
412         if (info->full_name == NULL) {
413                 TALLOC_FREE(user_info_dc);
414                 return NT_STATUS_NO_MEMORY;
415         }
416
417         str = ldb_msg_find_attr_as_string(msg, "scriptPath", "");
418         info->logon_script = talloc_strdup(info, str);
419         if (info->logon_script == NULL) {
420                 TALLOC_FREE(user_info_dc);
421                 return NT_STATUS_NO_MEMORY;
422         }
423
424         str = ldb_msg_find_attr_as_string(msg, "profilePath", "");
425         info->profile_path = talloc_strdup(info, str);
426         if (info->profile_path == NULL) {
427                 TALLOC_FREE(user_info_dc);
428                 return NT_STATUS_NO_MEMORY;
429         }
430
431         str = ldb_msg_find_attr_as_string(msg, "homeDirectory", "");
432         info->home_directory = talloc_strdup(info, str);
433         if (info->home_directory == NULL) {
434                 TALLOC_FREE(user_info_dc);
435                 return NT_STATUS_NO_MEMORY;
436         }
437
438         str = ldb_msg_find_attr_as_string(msg, "homeDrive", "");
439         info->home_drive = talloc_strdup(info, str);
440         if (info->home_drive == NULL) {
441                 TALLOC_FREE(user_info_dc);
442                 return NT_STATUS_NO_MEMORY;
443         }
444
445         info->logon_server = talloc_strdup(info, netbios_name);
446         if (info->logon_server == NULL) {
447                 TALLOC_FREE(user_info_dc);
448                 return NT_STATUS_NO_MEMORY;
449         }
450
451         info->last_logon = samdb_result_nttime(msg, "lastLogon", 0);
452         info->last_logoff = samdb_result_last_logoff(msg);
453         info->acct_expiry = samdb_result_account_expires(msg);
454         info->last_password_change = samdb_result_nttime(msg,
455                 "pwdLastSet", 0);
456         info->allow_password_change
457                 = samdb_result_allow_password_change(sam_ctx, mem_ctx, 
458                         domain_dn, msg, "pwdLastSet");
459         info->force_password_change = samdb_result_nttime(msg,
460                 "msDS-UserPasswordExpiryTimeComputed", 0);
461         info->logon_count = ldb_msg_find_attr_as_uint(msg, "logonCount", 0);
462         info->bad_password_count = ldb_msg_find_attr_as_uint(msg, "badPwdCount",
463                 0);
464
465         info->acct_flags = samdb_result_acct_flags(msg, "msDS-User-Account-Control-Computed");
466
467         user_info_dc->user_session_key = data_blob_talloc(user_info_dc,
468                                                          user_sess_key.data,
469                                                          user_sess_key.length);
470         if (user_sess_key.data) {
471                 if (user_info_dc->user_session_key.data == NULL) {
472                         TALLOC_FREE(user_info_dc);
473                         return NT_STATUS_NO_MEMORY;
474                 }
475         }
476         user_info_dc->lm_session_key = data_blob_talloc(user_info_dc,
477                                                        lm_sess_key.data,
478                                                        lm_sess_key.length);
479         if (lm_sess_key.data) {
480                 if (user_info_dc->lm_session_key.data == NULL) {
481                         TALLOC_FREE(user_info_dc);
482                         return NT_STATUS_NO_MEMORY;
483                 }
484         }
485
486         if (info->acct_flags & ACB_SVRTRUST) {
487                 /* the SID_NT_ENTERPRISE_DCS SID gets added into the
488                    PAC */
489                 user_info_dc->sids = talloc_realloc(user_info_dc,
490                                                    user_info_dc->sids,
491                                                    struct dom_sid,
492                                                    user_info_dc->num_sids+1);
493                 if (user_info_dc->sids == NULL) {
494                         TALLOC_FREE(user_info_dc);
495                         return NT_STATUS_NO_MEMORY;
496                 }
497                 user_info_dc->sids[user_info_dc->num_sids] = global_sid_Enterprise_DCs;
498                 user_info_dc->num_sids++;
499         }
500
501         if ((info->acct_flags & (ACB_PARTIAL_SECRETS_ACCOUNT | ACB_WSTRUST)) ==
502             (ACB_PARTIAL_SECRETS_ACCOUNT | ACB_WSTRUST)) {
503                 /* the DOMAIN_RID_ENTERPRISE_READONLY_DCS PAC */
504                 user_info_dc->sids = talloc_realloc(user_info_dc,
505                                                    user_info_dc->sids,
506                                                    struct dom_sid,
507                                                    user_info_dc->num_sids+1);
508                 if (user_info_dc->sids == NULL) {
509                         TALLOC_FREE(user_info_dc);
510                         return NT_STATUS_NO_MEMORY;
511                 }
512                 user_info_dc->sids[user_info_dc->num_sids] = *domain_sid;
513                 sid_append_rid(&user_info_dc->sids[user_info_dc->num_sids],
514                             DOMAIN_RID_ENTERPRISE_READONLY_DCS);
515                 user_info_dc->num_sids++;
516         }
517
518         info->authenticated = true;
519
520         talloc_free(tmp_ctx);
521         *_user_info_dc = user_info_dc;
522
523         return NT_STATUS_OK;
524 }
525
526 NTSTATUS sam_get_results_principal(struct ldb_context *sam_ctx,
527                                    TALLOC_CTX *mem_ctx, const char *principal,
528                                    const char **attrs,
529                                    struct ldb_dn **domain_dn,
530                                    struct ldb_message **msg)
531 {                          
532         struct ldb_dn *user_dn;
533         NTSTATUS nt_status;
534         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
535         int ret;
536
537         if (!tmp_ctx) {
538                 return NT_STATUS_NO_MEMORY;
539         }
540
541         nt_status = crack_user_principal_name(sam_ctx, tmp_ctx, principal, 
542                                               &user_dn, domain_dn);
543         if (!NT_STATUS_IS_OK(nt_status)) {
544                 talloc_free(tmp_ctx);
545                 return nt_status;
546         }
547         
548         /* pull the user attributes */
549         ret = dsdb_search_one(sam_ctx, tmp_ctx, msg, user_dn,
550                               LDB_SCOPE_BASE, attrs,
551                               DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
552                               "(objectClass=*)");
553         if (ret != LDB_SUCCESS) {
554                 talloc_free(tmp_ctx);
555                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
556         }
557         talloc_steal(mem_ctx, *msg);
558         talloc_steal(mem_ctx, *domain_dn);
559         talloc_free(tmp_ctx);
560         
561         return NT_STATUS_OK;
562 }
563
564 /* Used in the gensec_gssapi and gensec_krb5 server-side code, where the PAC isn't available, and for tokenGroups in the DSDB stack.
565
566  Supply either a principal or a DN
567 */
568 NTSTATUS authsam_get_user_info_dc_principal(TALLOC_CTX *mem_ctx,
569                                            struct loadparm_context *lp_ctx,
570                                            struct ldb_context *sam_ctx,
571                                            const char *principal,
572                                            struct ldb_dn *user_dn,
573                                            struct auth_user_info_dc **user_info_dc)
574 {
575         NTSTATUS nt_status;
576         DATA_BLOB user_sess_key = data_blob(NULL, 0);
577         DATA_BLOB lm_sess_key = data_blob(NULL, 0);
578
579         struct ldb_message *msg;
580         struct ldb_dn *domain_dn;
581
582         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
583         if (!tmp_ctx) {
584                 return NT_STATUS_NO_MEMORY;
585         }
586
587         if (principal) {
588                 nt_status = sam_get_results_principal(sam_ctx, tmp_ctx, principal,
589                                                       user_attrs, &domain_dn, &msg);
590                 if (!NT_STATUS_IS_OK(nt_status)) {
591                         talloc_free(tmp_ctx);
592                         return nt_status;
593                 }
594         } else if (user_dn) {
595                 struct dom_sid *user_sid, *domain_sid;
596                 int ret;
597                 /* pull the user attributes */
598                 ret = dsdb_search_one(sam_ctx, tmp_ctx, &msg, user_dn,
599                                       LDB_SCOPE_BASE, user_attrs,
600                                       DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
601                                       "(objectClass=*)");
602                 if (ret == LDB_ERR_NO_SUCH_OBJECT) {
603                         talloc_free(tmp_ctx);
604                         return NT_STATUS_NO_SUCH_USER;
605                 } else if (ret != LDB_SUCCESS) {
606                         talloc_free(tmp_ctx);
607                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
608                 }
609
610                 user_sid = samdb_result_dom_sid(msg, msg, "objectSid");
611
612                 nt_status = dom_sid_split_rid(tmp_ctx, user_sid, &domain_sid, NULL);
613                 if (!NT_STATUS_IS_OK(nt_status)) {
614                         return nt_status;
615                 }
616
617                 domain_dn = samdb_search_dn(sam_ctx, mem_ctx, NULL,
618                                           "(&(objectSid=%s)(objectClass=domain))",
619                                             ldap_encode_ndr_dom_sid(tmp_ctx, domain_sid));
620                 if (!domain_dn) {
621                         DEBUG(3, ("authsam_get_user_info_dc_principal: Failed to find domain with: SID %s\n",
622                                   dom_sid_string(tmp_ctx, domain_sid)));
623                         return NT_STATUS_NO_SUCH_USER;
624                 }
625
626         } else {
627                 return NT_STATUS_INVALID_PARAMETER;
628         }
629
630         nt_status = authsam_make_user_info_dc(tmp_ctx, sam_ctx,
631                                              lpcfg_netbios_name(lp_ctx),
632                                              lpcfg_workgroup(lp_ctx),
633                                              domain_dn,
634                                              msg,
635                                              user_sess_key, lm_sess_key,
636                                              user_info_dc);
637         if (!NT_STATUS_IS_OK(nt_status)) {
638                 talloc_free(tmp_ctx);
639                 return nt_status;
640         }
641
642         talloc_steal(mem_ctx, *user_info_dc);
643         talloc_free(tmp_ctx);
644
645         return NT_STATUS_OK;
646 }
647
648 NTSTATUS authsam_update_bad_pwd_count(struct ldb_context *sam_ctx,
649                                       struct ldb_message *msg,
650                                       struct ldb_dn *domain_dn)
651 {
652         const char *attrs[] = { "lockoutThreshold",
653                                 "lockOutObservationWindow",
654                                 "lockoutDuration",
655                                 "pwdProperties",
656                                 NULL };
657         int ret;
658         NTSTATUS status;
659         struct ldb_result *domain_res;
660         struct ldb_message *msg_mod = NULL;
661         TALLOC_CTX *mem_ctx;
662
663         mem_ctx = talloc_new(msg);
664         if (mem_ctx == NULL) {
665                 return NT_STATUS_NO_MEMORY;
666         }
667
668         ret = dsdb_search_dn(sam_ctx, mem_ctx, &domain_res, domain_dn, attrs, 0);
669         if (ret != LDB_SUCCESS) {
670                 TALLOC_FREE(mem_ctx);
671                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
672         }
673
674         status = dsdb_update_bad_pwd_count(mem_ctx, sam_ctx,
675                                            msg, domain_res->msgs[0], &msg_mod);
676         if (!NT_STATUS_IS_OK(status)) {
677                 TALLOC_FREE(mem_ctx);
678                 return status;
679         }
680
681         if (msg_mod != NULL) {
682                 ret = dsdb_modify(sam_ctx, msg_mod, 0);
683                 if (ret != LDB_SUCCESS) {
684                         DEBUG(0, ("Failed to update badPwdCount, badPasswordTime or set lockoutTime on %s: %s\n",
685                                   ldb_dn_get_linearized(msg_mod->dn), ldb_errstring(sam_ctx)));
686                         TALLOC_FREE(mem_ctx);
687                         return NT_STATUS_INTERNAL_ERROR;
688                 }
689         }
690
691         TALLOC_FREE(mem_ctx);
692         return NT_STATUS_OK;
693 }
694
695
696 static NTSTATUS authsam_update_lastlogon_timestamp(struct ldb_context *sam_ctx,
697                                             struct ldb_message *msg_mod,
698                                             struct ldb_dn *domain_dn,
699                                             NTTIME old_timestamp,
700                                             NTTIME now)
701 {
702         /*
703          * We only set lastLogonTimestamp if the current value is older than
704          * now - msDS-LogonTimeSyncInterval days.
705          *
706          * msDS-LogonTimeSyncInterval is an int32_t number of days, while
707          * lastLogonTimestamp is in the 64 bit 100ns NTTIME format.
708          *
709          * The docs say: "the initial update, after the domain functional
710          * level is raised to DS_BEHAVIOR_WIN2003 or higher, is calculated as
711          * 14 days minus a random percentage of 5 days", but we aren't doing
712          * that. The blogosphere seems to think that this randomised update
713          * happens everytime, but [MS-ADA1] doesn't agree.
714          *
715          * Dochelp referred us to the following blog post:
716          * http://blogs.technet.com/b/askds/archive/2009/04/15/the-lastlogontimestamp-attribute-what-it-was-designed-for-and-how-it-works.aspx
717          *
718          * en msDS-LogonTimeSyncInterval is zero, the lastLogonTimestamp is
719          * not changed.
720          */
721         static const char *attrs[] = { "msDS-LogonTimeSyncInterval",
722                                         NULL };
723         int ret;
724         struct ldb_result *domain_res = NULL;
725         TALLOC_CTX *mem_ctx = NULL;
726         int32_t sync_interval;
727         NTTIME sync_interval_nt;
728
729         mem_ctx = talloc_new(msg_mod);
730         if (mem_ctx == NULL) {
731                 return NT_STATUS_NO_MEMORY;
732         }
733
734         ret = dsdb_search_dn(sam_ctx, mem_ctx, &domain_res, domain_dn, attrs,
735                              0);
736         if (ret != LDB_SUCCESS || domain_res->count != 1) {
737                 TALLOC_FREE(mem_ctx);
738                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
739         }
740
741         sync_interval = ldb_msg_find_attr_as_int(domain_res->msgs[0],
742                                                  "msDS-LogonTimeSyncInterval",
743                                                  14);
744         DEBUG(5, ("sync interval is %d\n", sync_interval));
745         if (sync_interval == 0){
746                 /*
747                  * Setting msDS-LogonTimeSyncInterval to zero is how you ask
748                  * that nothing happens here.
749                  */
750                 TALLOC_FREE(mem_ctx);
751                 return NT_STATUS_OK;
752         }
753         else if (sync_interval >= 5){
754                 /*
755                  * Subtract "a random percentage of 5" days. Presumably this
756                  * percentage is between 0 and 100, and modulus is accurate
757                  * enough.
758                  */
759                 uint32_t r = generate_random() % 6;
760                 sync_interval -= r;
761                 DEBUG(5, ("randomised sync interval is %d (-%d)\n", sync_interval, r));
762         }
763         /* In the case where sync_interval < 5 there is no randomisation */
764
765         sync_interval_nt = sync_interval * 24LL * 3600LL * 10000000LL;
766
767         DEBUG(5, ("old timestamp is %lld, threshold %lld, diff %lld\n",
768                   (long long int)old_timestamp,
769                   (long long int)(now - sync_interval_nt),
770                   (long long int)(old_timestamp - now + sync_interval_nt)));
771
772         if (old_timestamp > now){
773                 DEBUG(0, ("lastLogonTimestamp is in the future! (%lld > %lld)\n",
774                           (long long int)old_timestamp, (long long int)now));
775                 /* then what? */
776
777         } else if (old_timestamp < now - sync_interval_nt){
778                 DEBUG(5, ("updating lastLogonTimestamp to %lld\n",
779                           (long long int)now));
780
781                 /* The time has come to update lastLogonTimestamp */
782                 ret = samdb_msg_add_int64(sam_ctx, msg_mod, msg_mod,
783                                           "lastLogonTimestamp", now);
784
785                 if (ret != LDB_SUCCESS) {
786                         TALLOC_FREE(mem_ctx);
787                         return NT_STATUS_NO_MEMORY;
788                 }
789         }
790         TALLOC_FREE(mem_ctx);
791         return NT_STATUS_OK;
792 }
793
794
795
796 /* Reset the badPwdCount to zero and update the lastLogon time. */
797 NTSTATUS authsam_logon_success_accounting(struct ldb_context *sam_ctx,
798                                           const struct ldb_message *msg,
799                                           struct ldb_dn *domain_dn,
800                                           bool interactive_or_kerberos)
801 {
802         int ret;
803         NTSTATUS status;
804         int badPwdCount;
805         int64_t lockoutTime;
806         struct ldb_message *msg_mod;
807         TALLOC_CTX *mem_ctx;
808         struct timeval tv_now;
809         NTTIME now;
810         NTTIME lastLogonTimestamp;
811
812         mem_ctx = talloc_new(msg);
813         if (mem_ctx == NULL) {
814                 return NT_STATUS_NO_MEMORY;
815         }
816
817         lockoutTime = ldb_msg_find_attr_as_int64(msg, "lockoutTime", 0);
818         if (interactive_or_kerberos) {
819                 badPwdCount = ldb_msg_find_attr_as_int(msg, "badPwdCount", 0);
820         } else {
821                 badPwdCount = samdb_result_effective_badPwdCount(sam_ctx, mem_ctx,
822                                                                  domain_dn, msg);
823         }
824         lastLogonTimestamp =
825                 ldb_msg_find_attr_as_int64(msg, "lastLogonTimestamp", 0);
826
827         DEBUG(5, ("lastLogonTimestamp is %lld\n",
828                   (long long int)lastLogonTimestamp));
829
830         msg_mod = ldb_msg_new(mem_ctx);
831         if (msg_mod == NULL) {
832                 TALLOC_FREE(mem_ctx);
833                 return NT_STATUS_NO_MEMORY;
834         }
835         msg_mod->dn = msg->dn;
836
837         if (lockoutTime != 0) {
838                 /*
839                  * This implies "badPwdCount" = 0, see samldb_lockout_time()
840                  */
841                 ret = samdb_msg_add_int(sam_ctx, msg_mod, msg_mod, "lockoutTime", 0);
842                 if (ret != LDB_SUCCESS) {
843                         TALLOC_FREE(mem_ctx);
844                         return NT_STATUS_NO_MEMORY;
845                 }
846         } else if (badPwdCount != 0) {
847                 ret = samdb_msg_add_int(sam_ctx, msg_mod, msg_mod, "badPwdCount", 0);
848                 if (ret != LDB_SUCCESS) {
849                         TALLOC_FREE(mem_ctx);
850                         return NT_STATUS_NO_MEMORY;
851                 }
852         }
853
854         tv_now = timeval_current();
855         now = timeval_to_nttime(&tv_now);
856
857         if (interactive_or_kerberos ||
858             (badPwdCount != 0 && lockoutTime == 0)) {
859                 ret = samdb_msg_add_int64(sam_ctx, msg_mod, msg_mod,
860                                           "lastLogon", now);
861                 if (ret != LDB_SUCCESS) {
862                         TALLOC_FREE(mem_ctx);
863                         return NT_STATUS_NO_MEMORY;
864                 }
865         }
866         status = authsam_update_lastlogon_timestamp(sam_ctx, msg_mod, domain_dn,
867                                                     lastLogonTimestamp, now);
868         if (!NT_STATUS_IS_OK(status)) {
869                 TALLOC_FREE(mem_ctx);
870                 return NT_STATUS_NO_MEMORY;
871         }
872
873         if (msg_mod->num_elements > 0) {
874                 ret = dsdb_replace(sam_ctx, msg_mod, 0);
875                 if (ret != LDB_SUCCESS) {
876                         DEBUG(0, ("Failed to set badPwdCount and lockoutTime "
877                                   "to 0 and/or  lastlogon to now (%lld) "
878                                   "%s: %s\n", (long long int)now,
879                                   ldb_dn_get_linearized(msg_mod->dn),
880                                   ldb_errstring(sam_ctx)));
881                         TALLOC_FREE(mem_ctx);
882                         return NT_STATUS_INTERNAL_ERROR;
883                 }
884         }
885         TALLOC_FREE(mem_ctx);
886         return NT_STATUS_OK;
887 }