lib/util/util_pw: share more code between lib/util/util_pw.c and source3/lib/username.c
[bbaumbach/samba-autobuild/.git] / source3 / passdb / passdb.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Password and authentication handling
4    Copyright (C) Jeremy Allison                 1996-2001
5    Copyright (C) Luke Kenneth Casson Leighton   1996-1998
6    Copyright (C) Gerald (Jerry) Carter          2000-2006
7    Copyright (C) Andrew Bartlett                2001-2002
8    Copyright (C) Simo Sorce                     2003
9    Copyright (C) Volker Lendecke                2006
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "../libcli/auth/libcli_auth.h"
27 #include "secrets.h"
28 #include "../libcli/security/security.h"
29 #include "../lib/util/util_pw.h"
30
31 #undef DBGC_CLASS
32 #define DBGC_CLASS DBGC_PASSDB
33
34 /******************************************************************
35  Get the default domain/netbios name to be used when
36  testing authentication.
37
38  LEGACY: this function provides the legacy domain mapping used with
39          the lp_map_untrusted_to_domain() parameter
40 ******************************************************************/
41
42 const char *my_sam_name(void)
43 {
44        /* Standalone servers can only use the local netbios name */
45        if ( lp_server_role() == ROLE_STANDALONE )
46                return global_myname();
47
48        /* Default to the DOMAIN name when not specified */
49        return lp_workgroup();
50 }
51
52 /**********************************************************************
53 ***********************************************************************/
54
55 static int samu_destroy(struct samu *user) 
56 {
57         data_blob_clear_free( &user->lm_pw );
58         data_blob_clear_free( &user->nt_pw );
59
60         if ( user->plaintext_pw )
61                 memset( user->plaintext_pw, 0x0, strlen(user->plaintext_pw) );
62
63         return 0;
64 }
65
66 /**********************************************************************
67  generate a new struct samuser
68 ***********************************************************************/
69
70 struct samu *samu_new( TALLOC_CTX *ctx )
71 {
72         struct samu *user;
73
74         if ( !(user = TALLOC_ZERO_P( ctx, struct samu )) ) {
75                 DEBUG(0,("samuser_new: Talloc failed!\n"));
76                 return NULL;
77         }
78
79         talloc_set_destructor( user, samu_destroy );
80
81         /* no initial methods */
82
83         user->methods = NULL;
84
85         /* Don't change these timestamp settings without a good reason.
86            They are important for NT member server compatibility. */
87
88         user->logon_time            = (time_t)0;
89         user->pass_last_set_time    = (time_t)0;
90         user->pass_can_change_time  = (time_t)0;
91         user->logoff_time           = get_time_t_max();
92         user->kickoff_time          = get_time_t_max();
93         user->pass_must_change_time = get_time_t_max();
94         user->fields_present        = 0x00ffffff;
95         user->logon_divs = 168;         /* hours per week */
96         user->hours_len = 21;           /* 21 times 8 bits = 168 */
97         memset(user->hours, 0xff, user->hours_len); /* available at all hours */
98         user->bad_password_count = 0;
99         user->logon_count = 0;
100         user->unknown_6 = 0x000004ec; /* don't know */
101
102         /* Some parts of samba strlen their pdb_get...() returns, 
103            so this keeps the interface unchanged for now. */
104
105         user->username = "";
106         user->domain = "";
107         user->nt_username = "";
108         user->full_name = "";
109         user->home_dir = "";
110         user->logon_script = "";
111         user->profile_path = "";
112         user->acct_desc = "";
113         user->workstations = "";
114         user->comment = "";
115         user->munged_dial = "";
116
117         user->plaintext_pw = NULL;
118
119         /* Unless we know otherwise have a Account Control Bit
120            value of 'normal user'.  This helps User Manager, which
121            asks for a filtered list of users. */
122
123         user->acct_ctrl = ACB_NORMAL;
124
125         return user;
126 }
127
128 static int count_commas(const char *str)
129 {
130         int num_commas = 0;
131         const char *comma = str;
132
133         while ((comma = strchr(comma, ',')) != NULL) {
134                 comma += 1;
135                 num_commas += 1;
136         }
137         return num_commas;
138 }
139
140 /*********************************************************************
141  Initialize a struct samu from a struct passwd including the user 
142  and group SIDs.  The *user structure is filled out with the Unix
143  attributes and a user SID.
144 *********************************************************************/
145
146 static NTSTATUS samu_set_unix_internal(struct samu *user, const struct passwd *pwd, bool create)
147 {
148         const char *guest_account = lp_guestaccount();
149         const char *domain = global_myname();
150         char *fullname;
151         uint32_t urid;
152
153         if ( !pwd ) {
154                 return NT_STATUS_NO_SUCH_USER;
155         }
156
157         /* Basic properties based upon the Unix account information */
158
159         pdb_set_username(user, pwd->pw_name, PDB_SET);
160
161         fullname = NULL;
162
163         if (count_commas(pwd->pw_gecos) == 3) {
164                 /*
165                  * Heuristic: This seems to be a gecos field that has been
166                  * edited by chfn(1). Only use the part before the first
167                  * comma. Fixes bug 5198.
168                  */
169                 fullname = talloc_strndup(
170                         talloc_tos(), pwd->pw_gecos,
171                         strchr(pwd->pw_gecos, ',') - pwd->pw_gecos);
172         }
173
174         if (fullname != NULL) {
175                 pdb_set_fullname(user, fullname, PDB_SET);
176         } else {
177                 pdb_set_fullname(user, pwd->pw_gecos, PDB_SET);
178         }
179         TALLOC_FREE(fullname);
180
181         pdb_set_domain (user, get_global_sam_name(), PDB_DEFAULT);
182 #if 0
183         /* This can lead to a primary group of S-1-22-2-XX which 
184            will be rejected by other parts of the Samba code. 
185            Rely on pdb_get_group_sid() to "Do The Right Thing" (TM)  
186            --jerry */
187
188         gid_to_sid(&group_sid, pwd->pw_gid);
189         pdb_set_group_sid(user, &group_sid, PDB_SET);
190 #endif
191
192         /* save the password structure for later use */
193
194         user->unix_pw = tcopy_passwd( user, pwd );
195
196         /* Special case for the guest account which must have a RID of 501 */
197
198         if ( strequal( pwd->pw_name, guest_account ) ) {
199                 if ( !pdb_set_user_sid_from_rid(user, DOMAIN_RID_GUEST, PDB_DEFAULT)) {
200                         return NT_STATUS_NO_SUCH_USER;
201                 }
202                 return NT_STATUS_OK;
203         }
204
205         /* Non-guest accounts...Check for a workstation or user account */
206
207         if (pwd->pw_name[strlen(pwd->pw_name)-1] == '$') {
208                 /* workstation */
209
210                 if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_DEFAULT)) {
211                         DEBUG(1, ("Failed to set 'workstation account' flags for user %s.\n", 
212                                 pwd->pw_name));
213                         return NT_STATUS_INVALID_COMPUTER_NAME;
214                 }       
215         } 
216         else {
217                 /* user */
218
219                 if (!pdb_set_acct_ctrl(user, ACB_NORMAL, PDB_DEFAULT)) {
220                         DEBUG(1, ("Failed to set 'normal account' flags for user %s.\n", 
221                                 pwd->pw_name));
222                         return NT_STATUS_INVALID_ACCOUNT_NAME;
223                 }
224
225                 /* set some basic attributes */
226
227                 pdb_set_profile_path(user, talloc_sub_specified(user, 
228                         lp_logon_path(), pwd->pw_name, domain, pwd->pw_uid, pwd->pw_gid), 
229                         PDB_DEFAULT);           
230                 pdb_set_homedir(user, talloc_sub_specified(user, 
231                         lp_logon_home(), pwd->pw_name, domain, pwd->pw_uid, pwd->pw_gid),
232                         PDB_DEFAULT);
233                 pdb_set_dir_drive(user, talloc_sub_specified(user, 
234                         lp_logon_drive(), pwd->pw_name, domain, pwd->pw_uid, pwd->pw_gid),
235                         PDB_DEFAULT);
236                 pdb_set_logon_script(user, talloc_sub_specified(user, 
237                         lp_logon_script(), pwd->pw_name, domain, pwd->pw_uid, pwd->pw_gid), 
238                         PDB_DEFAULT);
239         }
240
241         /* Now deal with the user SID.  If we have a backend that can generate 
242            RIDs, then do so.  But sometimes the caller just wanted a structure 
243            initialized and will fill in these fields later (such as from a 
244            netr_SamInfo3 structure) */
245
246         if ( create && (pdb_capabilities() & PDB_CAP_STORE_RIDS)) {
247                 uint32_t user_rid;
248                 struct dom_sid user_sid;
249
250                 if ( !pdb_new_rid( &user_rid ) ) {
251                         DEBUG(3, ("Could not allocate a new RID\n"));
252                         return NT_STATUS_ACCESS_DENIED;
253                 }
254
255                 sid_compose(&user_sid, get_global_sam_sid(), user_rid);
256
257                 if ( !pdb_set_user_sid(user, &user_sid, PDB_SET) ) {
258                         DEBUG(3, ("pdb_set_user_sid failed\n"));
259                         return NT_STATUS_INTERNAL_ERROR;
260                 }
261
262                 return NT_STATUS_OK;
263         }
264
265         /* generate a SID for the user with the RID algorithm */
266
267         urid = algorithmic_pdb_uid_to_user_rid( user->unix_pw->pw_uid );
268
269         if ( !pdb_set_user_sid_from_rid( user, urid, PDB_SET) ) {
270                 return NT_STATUS_INTERNAL_ERROR;
271         }
272
273         return NT_STATUS_OK;
274 }
275
276 /********************************************************************
277  Set the Unix user attributes
278 ********************************************************************/
279
280 NTSTATUS samu_set_unix(struct samu *user, const struct passwd *pwd)
281 {
282         return samu_set_unix_internal( user, pwd, False );
283 }
284
285 NTSTATUS samu_alloc_rid_unix(struct samu *user, const struct passwd *pwd)
286 {
287         return samu_set_unix_internal( user, pwd, True );
288 }
289
290 /**********************************************************
291  Encode the account control bits into a string.
292  length = length of string to encode into (including terminating
293  null). length *MUST BE MORE THAN 2* !
294  **********************************************************/
295
296 char *pdb_encode_acct_ctrl(uint32_t acct_ctrl, size_t length)
297 {
298         fstring acct_str;
299         char *result;
300
301         size_t i = 0;
302
303         SMB_ASSERT(length <= sizeof(acct_str));
304
305         acct_str[i++] = '[';
306
307         if (acct_ctrl & ACB_PWNOTREQ ) acct_str[i++] = 'N';
308         if (acct_ctrl & ACB_DISABLED ) acct_str[i++] = 'D';
309         if (acct_ctrl & ACB_HOMDIRREQ) acct_str[i++] = 'H';
310         if (acct_ctrl & ACB_TEMPDUP  ) acct_str[i++] = 'T'; 
311         if (acct_ctrl & ACB_NORMAL   ) acct_str[i++] = 'U';
312         if (acct_ctrl & ACB_MNS      ) acct_str[i++] = 'M';
313         if (acct_ctrl & ACB_WSTRUST  ) acct_str[i++] = 'W';
314         if (acct_ctrl & ACB_SVRTRUST ) acct_str[i++] = 'S';
315         if (acct_ctrl & ACB_AUTOLOCK ) acct_str[i++] = 'L';
316         if (acct_ctrl & ACB_PWNOEXP  ) acct_str[i++] = 'X';
317         if (acct_ctrl & ACB_DOMTRUST ) acct_str[i++] = 'I';
318
319         for ( ; i < length - 2 ; i++ )
320                 acct_str[i] = ' ';
321
322         i = length - 2;
323         acct_str[i++] = ']';
324         acct_str[i++] = '\0';
325
326         result = talloc_strdup(talloc_tos(), acct_str);
327         SMB_ASSERT(result != NULL);
328         return result;
329 }     
330
331 /**********************************************************
332  Decode the account control bits from a string.
333  **********************************************************/
334
335 uint32_t pdb_decode_acct_ctrl(const char *p)
336 {
337         uint32_t acct_ctrl = 0;
338         bool finished = false;
339
340         /*
341          * Check if the account type bits have been encoded after the
342          * NT password (in the form [NDHTUWSLXI]).
343          */
344
345         if (*p != '[')
346                 return 0;
347
348         for (p++; *p && !finished; p++) {
349                 switch (*p) {
350                         case 'N': { acct_ctrl |= ACB_PWNOTREQ ; break; /* 'N'o password. */ }
351                         case 'D': { acct_ctrl |= ACB_DISABLED ; break; /* 'D'isabled. */ }
352                         case 'H': { acct_ctrl |= ACB_HOMDIRREQ; break; /* 'H'omedir required. */ }
353                         case 'T': { acct_ctrl |= ACB_TEMPDUP  ; break; /* 'T'emp account. */ } 
354                         case 'U': { acct_ctrl |= ACB_NORMAL   ; break; /* 'U'ser account (normal). */ } 
355                         case 'M': { acct_ctrl |= ACB_MNS      ; break; /* 'M'NS logon user account. What is this ? */ } 
356                         case 'W': { acct_ctrl |= ACB_WSTRUST  ; break; /* 'W'orkstation account. */ } 
357                         case 'S': { acct_ctrl |= ACB_SVRTRUST ; break; /* 'S'erver account. */ } 
358                         case 'L': { acct_ctrl |= ACB_AUTOLOCK ; break; /* 'L'ocked account. */ } 
359                         case 'X': { acct_ctrl |= ACB_PWNOEXP  ; break; /* No 'X'piry on password */ } 
360                         case 'I': { acct_ctrl |= ACB_DOMTRUST ; break; /* 'I'nterdomain trust account. */ }
361             case ' ': { break; }
362                         case ':':
363                         case '\n':
364                         case '\0': 
365                         case ']':
366                         default:  { finished = true; }
367                 }
368         }
369
370         return acct_ctrl;
371 }
372
373 /*************************************************************
374  Routine to set 32 hex password characters from a 16 byte array.
375 **************************************************************/
376
377 void pdb_sethexpwd(char p[33], const unsigned char *pwd, uint32_t acct_ctrl)
378 {
379         if (pwd != NULL) {
380                 int i;
381                 for (i = 0; i < 16; i++)
382                         slprintf(&p[i*2], 3, "%02X", pwd[i]);
383         } else {
384                 if (acct_ctrl & ACB_PWNOTREQ)
385                         safe_strcpy(p, "NO PASSWORDXXXXXXXXXXXXXXXXXXXXX", 32);
386                 else
387                         safe_strcpy(p, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 32);
388         }
389 }
390
391 /*************************************************************
392  Routine to get the 32 hex characters and turn them
393  into a 16 byte array.
394 **************************************************************/
395
396 bool pdb_gethexpwd(const char *p, unsigned char *pwd)
397 {
398         int i;
399         unsigned char   lonybble, hinybble;
400         const char      *hexchars = "0123456789ABCDEF";
401         char           *p1, *p2;
402
403         if (!p)
404                 return false;
405
406         for (i = 0; i < 32; i += 2) {
407                 hinybble = toupper_ascii(p[i]);
408                 lonybble = toupper_ascii(p[i + 1]);
409
410                 p1 = strchr(hexchars, hinybble);
411                 p2 = strchr(hexchars, lonybble);
412
413                 if (!p1 || !p2)
414                         return false;
415
416                 hinybble = PTR_DIFF(p1, hexchars);
417                 lonybble = PTR_DIFF(p2, hexchars);
418
419                 pwd[i / 2] = (hinybble << 4) | lonybble;
420         }
421         return true;
422 }
423
424 /*************************************************************
425  Routine to set 42 hex hours characters from a 21 byte array.
426 **************************************************************/
427
428 void pdb_sethexhours(char *p, const unsigned char *hours)
429 {
430         if (hours != NULL) {
431                 int i;
432                 for (i = 0; i < 21; i++) {
433                         slprintf(&p[i*2], 3, "%02X", hours[i]);
434                 }
435         } else {
436                 safe_strcpy(p, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 43);
437         }
438 }
439
440 /*************************************************************
441  Routine to get the 42 hex characters and turn them
442  into a 21 byte array.
443 **************************************************************/
444
445 bool pdb_gethexhours(const char *p, unsigned char *hours)
446 {
447         int i;
448         unsigned char   lonybble, hinybble;
449         const char      *hexchars = "0123456789ABCDEF";
450         char           *p1, *p2;
451
452         if (!p) {
453                 return (False);
454         }
455
456         for (i = 0; i < 42; i += 2) {
457                 hinybble = toupper_ascii(p[i]);
458                 lonybble = toupper_ascii(p[i + 1]);
459
460                 p1 = strchr(hexchars, hinybble);
461                 p2 = strchr(hexchars, lonybble);
462
463                 if (!p1 || !p2) {
464                         return (False);
465                 }
466
467                 hinybble = PTR_DIFF(p1, hexchars);
468                 lonybble = PTR_DIFF(p2, hexchars);
469
470                 hours[i / 2] = (hinybble << 4) | lonybble;
471         }
472         return (True);
473 }
474
475 /********************************************************************
476 ********************************************************************/
477
478 int algorithmic_rid_base(void)
479 {
480         int rid_offset;
481
482         rid_offset = lp_algorithmic_rid_base();
483
484         if (rid_offset < BASE_RID) {  
485                 /* Try to prevent admin foot-shooting, we can't put algorithmic
486                    rids below 1000, that's the 'well known RIDs' on NT */
487                 DEBUG(0, ("'algorithmic rid base' must be equal to or above %ld\n", BASE_RID));
488                 rid_offset = BASE_RID;
489         }
490         if (rid_offset & 1) {
491                 DEBUG(0, ("algorithmic rid base must be even\n"));
492                 rid_offset += 1;
493         }
494         return rid_offset;
495 }
496
497 /*******************************************************************
498  Converts NT user RID to a UNIX uid.
499  ********************************************************************/
500
501 uid_t algorithmic_pdb_user_rid_to_uid(uint32_t user_rid)
502 {
503         int rid_offset = algorithmic_rid_base();
504         return (uid_t)(((user_rid & (~USER_RID_TYPE)) - rid_offset)/RID_MULTIPLIER);
505 }
506
507 uid_t max_algorithmic_uid(void)
508 {
509         return algorithmic_pdb_user_rid_to_uid(0xfffffffe);
510 }
511
512 /*******************************************************************
513  converts UNIX uid to an NT User RID.
514  ********************************************************************/
515
516 uint32_t algorithmic_pdb_uid_to_user_rid(uid_t uid)
517 {
518         int rid_offset = algorithmic_rid_base();
519         return (((((uint32_t)uid)*RID_MULTIPLIER) + rid_offset) | USER_RID_TYPE);
520 }
521
522 /*******************************************************************
523  Converts NT group RID to a UNIX gid.
524  ********************************************************************/
525
526 gid_t pdb_group_rid_to_gid(uint32_t group_rid)
527 {
528         int rid_offset = algorithmic_rid_base();
529         return (gid_t)(((group_rid & (~GROUP_RID_TYPE))- rid_offset)/RID_MULTIPLIER);
530 }
531
532 gid_t max_algorithmic_gid(void)
533 {
534         return pdb_group_rid_to_gid(0xffffffff);
535 }
536
537 /*******************************************************************
538  converts NT Group RID to a UNIX uid.
539  
540  warning: you must not call that function only
541  you must do a call to the group mapping first.
542  there is not anymore a direct link between the gid and the rid.
543  ********************************************************************/
544
545 uint32_t algorithmic_pdb_gid_to_group_rid(gid_t gid)
546 {
547         int rid_offset = algorithmic_rid_base();
548         return (((((uint32_t)gid)*RID_MULTIPLIER) + rid_offset) | GROUP_RID_TYPE);
549 }
550
551 /*******************************************************************
552  Decides if a RID is a well known RID.
553  ********************************************************************/
554
555 static bool rid_is_well_known(uint32_t rid)
556 {
557         /* Not using rid_offset here, because this is the actual
558            NT fixed value (1000) */
559
560         return (rid < BASE_RID);
561 }
562
563 /*******************************************************************
564  Decides if a RID is a user or group RID.
565  ********************************************************************/
566
567 bool algorithmic_pdb_rid_is_user(uint32_t rid)
568 {
569         if ( rid_is_well_known(rid) ) {
570                 /*
571                  * The only well known user RIDs are DOMAIN_RID_ADMINISTRATOR
572                  * and DOMAIN_RID_GUEST.
573                  */
574                 if(rid == DOMAIN_RID_ADMINISTRATOR || rid == DOMAIN_RID_GUEST)
575                         return True;
576         } else if((rid & RID_TYPE_MASK) == USER_RID_TYPE) {
577                 return True;
578         }
579         return False;
580 }
581
582 /*******************************************************************
583  Convert a name into a SID. Used in the lookup name rpc.
584  ********************************************************************/
585
586 bool lookup_global_sam_name(const char *name, int flags, uint32_t *rid,
587                             enum lsa_SidType *type)
588 {
589         GROUP_MAP map;
590         bool ret;
591
592         /* Windows treats "MACHINE\None" as a special name for 
593            rid 513 on non-DCs.  You cannot create a user or group
594            name "None" on Windows.  You will get an error that 
595            the group already exists. */
596
597         if ( strequal( name, "None" ) ) {
598                 *rid = DOMAIN_RID_USERS;
599                 *type = SID_NAME_DOM_GRP;
600
601                 return True;
602         }
603
604         /* LOOKUP_NAME_GROUP is a hack to allow valid users = @foo to work
605          * correctly in the case where foo also exists as a user. If the flag
606          * is set, don't look for users at all. */
607
608         if ((flags & LOOKUP_NAME_GROUP) == 0) {
609                 struct samu *sam_account = NULL;
610                 struct dom_sid user_sid;
611
612                 if ( !(sam_account = samu_new( NULL )) ) {
613                         return False;
614                 }
615
616                 become_root();
617                 ret =  pdb_getsampwnam(sam_account, name);
618                 unbecome_root();
619
620                 if (ret) {
621                         sid_copy(&user_sid, pdb_get_user_sid(sam_account));
622                 }
623
624                 TALLOC_FREE(sam_account);
625
626                 if (ret) {
627                         if (!sid_check_is_in_our_domain(&user_sid)) {
628                                 DEBUG(0, ("User %s with invalid SID %s in passdb\n",
629                                           name, sid_string_dbg(&user_sid)));
630                                 return False;
631                         }
632
633                         sid_peek_rid(&user_sid, rid);
634                         *type = SID_NAME_USER;
635                         return True;
636                 }
637         }
638
639         /*
640          * Maybe it is a group ?
641          */
642
643         become_root();
644         ret = pdb_getgrnam(&map, name);
645         unbecome_root();
646
647         if (!ret) {
648                 return False;
649         }
650
651         /* BUILTIN groups are looked up elsewhere */
652         if (!sid_check_is_in_our_domain(&map.sid)) {
653                 DEBUG(10, ("Found group %s (%s) not in our domain -- "
654                            "ignoring.", name, sid_string_dbg(&map.sid)));
655                 return False;
656         }
657
658         /* yes it's a mapped group */
659         sid_peek_rid(&map.sid, rid);
660         *type = map.sid_name_use;
661         return True;
662 }
663
664 /*************************************************************
665  Change a password entry in the local passdb backend.
666
667  Assumptions:
668   - always called as root
669   - ignores the account type except when adding a new account
670   - will create/delete the unix account if the relative
671     add/delete user script is configured
672
673  *************************************************************/
674
675 NTSTATUS local_password_change(const char *user_name,
676                                 int local_flags,
677                                 const char *new_passwd, 
678                                 char **pp_err_str,
679                                 char **pp_msg_str)
680 {
681         TALLOC_CTX *tosctx;
682         struct samu *sam_pass;
683         uint32_t acb;
684         uint32_t rid;
685         NTSTATUS result;
686         bool user_exists;
687         int ret = -1;
688
689         *pp_err_str = NULL;
690         *pp_msg_str = NULL;
691
692         tosctx = talloc_tos();
693
694         sam_pass = samu_new(tosctx);
695         if (!sam_pass) {
696                 result = NT_STATUS_NO_MEMORY;
697                 goto done;
698         }
699
700         /* Get the smb passwd entry for this user */
701         user_exists = pdb_getsampwnam(sam_pass, user_name);
702
703         /* Check delete first, we don't need to do anything else if we
704          * are going to delete the acocunt */
705         if (user_exists && (local_flags & LOCAL_DELETE_USER)) {
706
707                 result = pdb_delete_user(tosctx, sam_pass);
708                 if (!NT_STATUS_IS_OK(result)) {
709                         ret = asprintf(pp_err_str,
710                                         "Failed to delete entry for user %s.\n",
711                                         user_name);
712                         if (ret < 0) {
713                                 *pp_err_str = NULL;
714                         }
715                         result = NT_STATUS_UNSUCCESSFUL;
716                 } else {
717                         ret = asprintf(pp_msg_str,
718                                         "Deleted user %s.\n",
719                                         user_name);
720                         if (ret < 0) {
721                                 *pp_msg_str = NULL;
722                         }
723                 }
724                 goto done;
725         }
726
727         if (user_exists && (local_flags & LOCAL_ADD_USER)) {
728                 /* the entry already existed */
729                 local_flags &= ~LOCAL_ADD_USER;
730         }
731
732         if (!user_exists && !(local_flags & LOCAL_ADD_USER)) {
733                 ret = asprintf(pp_err_str,
734                                 "Failed to find entry for user %s.\n",
735                                 user_name);
736                 if (ret < 0) {
737                         *pp_err_str = NULL;
738                 }
739                 result = NT_STATUS_NO_SUCH_USER;
740                 goto done;
741         }
742
743         /* First thing add the new user if we are required to do so */
744         if (local_flags & LOCAL_ADD_USER) {
745
746                 if (local_flags & LOCAL_TRUST_ACCOUNT) {
747                         acb = ACB_WSTRUST;
748                 } else if (local_flags & LOCAL_INTERDOM_ACCOUNT) {
749                         acb = ACB_DOMTRUST;
750                 } else {
751                         acb = ACB_NORMAL;
752                 }
753
754                 result = pdb_create_user(tosctx, user_name, acb, &rid);
755                 if (!NT_STATUS_IS_OK(result)) {
756                         ret = asprintf(pp_err_str,
757                                         "Failed to add entry for user %s.\n",
758                                         user_name);
759                         if (ret < 0) {
760                                 *pp_err_str = NULL;
761                         }
762                         result = NT_STATUS_UNSUCCESSFUL;
763                         goto done;
764                 }
765
766                 sam_pass = samu_new(tosctx);
767                 if (!sam_pass) {
768                         result = NT_STATUS_NO_MEMORY;
769                         goto done;
770                 }
771
772                 /* Now get back the smb passwd entry for this new user */
773                 user_exists = pdb_getsampwnam(sam_pass, user_name);
774                 if (!user_exists) {
775                         ret = asprintf(pp_err_str,
776                                         "Failed to add entry for user %s.\n",
777                                         user_name);
778                         if (ret < 0) {
779                                 *pp_err_str = NULL;
780                         }
781                         result = NT_STATUS_UNSUCCESSFUL;
782                         goto done;
783                 }
784         }
785
786         acb = pdb_get_acct_ctrl(sam_pass);
787
788         /*
789          * We are root - just write the new password
790          * and the valid last change time.
791          */
792         if ((local_flags & LOCAL_SET_NO_PASSWORD) && !(acb & ACB_PWNOTREQ)) {
793                 acb |= ACB_PWNOTREQ;
794                 if (!pdb_set_acct_ctrl(sam_pass, acb, PDB_CHANGED)) {
795                         ret = asprintf(pp_err_str,
796                                         "Failed to set 'no password required' "
797                                         "flag for user %s.\n", user_name);
798                         if (ret < 0) {
799                                 *pp_err_str = NULL;
800                         }
801                         result = NT_STATUS_UNSUCCESSFUL;
802                         goto done;
803                 }
804         }
805
806         if (local_flags & LOCAL_SET_PASSWORD) {
807                 /*
808                  * If we're dealing with setting a completely empty user account
809                  * ie. One with a password of 'XXXX', but not set disabled (like
810                  * an account created from scratch) then if the old password was
811                  * 'XX's then getsmbpwent will have set the ACB_DISABLED flag.
812                  * We remove that as we're giving this user their first password
813                  * and the decision hasn't really been made to disable them (ie.
814                  * don't create them disabled). JRA.
815                  */
816                 if ((pdb_get_lanman_passwd(sam_pass) == NULL) &&
817                     (acb & ACB_DISABLED)) {
818                         acb &= (~ACB_DISABLED);
819                         if (!pdb_set_acct_ctrl(sam_pass, acb, PDB_CHANGED)) {
820                                 ret = asprintf(pp_err_str,
821                                                 "Failed to unset 'disabled' "
822                                                 "flag for user %s.\n",
823                                                 user_name);
824                                 if (ret < 0) {
825                                         *pp_err_str = NULL;
826                                 }
827                                 result = NT_STATUS_UNSUCCESSFUL;
828                                 goto done;
829                         }
830                 }
831
832                 acb &= (~ACB_PWNOTREQ);
833                 if (!pdb_set_acct_ctrl(sam_pass, acb, PDB_CHANGED)) {
834                         ret = asprintf(pp_err_str,
835                                         "Failed to unset 'no password required'"
836                                         " flag for user %s.\n", user_name);
837                         if (ret < 0) {
838                                 *pp_err_str = NULL;
839                         }
840                         result = NT_STATUS_UNSUCCESSFUL;
841                         goto done;
842                 }
843
844                 if (!pdb_set_plaintext_passwd(sam_pass, new_passwd)) {
845                         ret = asprintf(pp_err_str,
846                                         "Failed to set password for "
847                                         "user %s.\n", user_name);
848                                 if (ret < 0) {
849                                 *pp_err_str = NULL;
850                         }
851                         result = NT_STATUS_UNSUCCESSFUL;
852                         goto done;
853                 }
854         }
855
856         if ((local_flags & LOCAL_DISABLE_USER) && !(acb & ACB_DISABLED)) {
857                 acb |= ACB_DISABLED;
858                 if (!pdb_set_acct_ctrl(sam_pass, acb, PDB_CHANGED)) {
859                         ret = asprintf(pp_err_str,
860                                         "Failed to set 'disabled' flag for "
861                                         "user %s.\n", user_name);
862                         if (ret < 0) {
863                                 *pp_err_str = NULL;
864                         }
865                         result = NT_STATUS_UNSUCCESSFUL;
866                         goto done;
867                 }
868         }
869
870         if ((local_flags & LOCAL_ENABLE_USER) && (acb & ACB_DISABLED)) {
871                 acb &= (~ACB_DISABLED);
872                 if (!pdb_set_acct_ctrl(sam_pass, acb, PDB_CHANGED)) {
873                         ret = asprintf(pp_err_str,
874                                         "Failed to unset 'disabled' flag for "
875                                         "user %s.\n", user_name);
876                         if (ret < 0) {
877                                 *pp_err_str = NULL;
878                         }
879                         result = NT_STATUS_UNSUCCESSFUL;
880                         goto done;
881                 }
882         }
883
884         /* now commit changes if any */
885         result = pdb_update_sam_account(sam_pass);
886         if (!NT_STATUS_IS_OK(result)) {
887                 ret = asprintf(pp_err_str,
888                                 "Failed to modify entry for user %s.\n",
889                                 user_name);
890                 if (ret < 0) {
891                         *pp_err_str = NULL;
892                 }
893                 goto done;
894         }
895
896         if (local_flags & LOCAL_ADD_USER) {
897                 ret = asprintf(pp_msg_str, "Added user %s.\n", user_name);
898         } else if (local_flags & LOCAL_DISABLE_USER) {
899                 ret = asprintf(pp_msg_str, "Disabled user %s.\n", user_name);
900         } else if (local_flags & LOCAL_ENABLE_USER) {
901                 ret = asprintf(pp_msg_str, "Enabled user %s.\n", user_name);
902         } else if (local_flags & LOCAL_SET_NO_PASSWORD) {
903                 ret = asprintf(pp_msg_str,
904                                 "User %s password set to none.\n", user_name);
905         }
906
907         if (ret < 0) {
908                 *pp_msg_str = NULL;
909         }
910
911         result = NT_STATUS_OK;
912
913 done:
914         TALLOC_FREE(sam_pass);
915         return result;
916 }
917
918 /**********************************************************************
919  Marshall/unmarshall struct samu structs.
920  *********************************************************************/
921
922 #define SAMU_BUFFER_FORMAT_V0       "ddddddBBBBBBBBBBBBddBBwdwdBwwd"
923 #define SAMU_BUFFER_FORMAT_V1       "dddddddBBBBBBBBBBBBddBBwdwdBwwd"
924 #define SAMU_BUFFER_FORMAT_V2       "dddddddBBBBBBBBBBBBddBBBwwdBwwd"
925 #define SAMU_BUFFER_FORMAT_V3       "dddddddBBBBBBBBBBBBddBBBdwdBwwd"
926 /* nothing changed between V3 and V4 */
927
928 /*********************************************************************
929 *********************************************************************/
930
931 static bool init_samu_from_buffer_v0(struct samu *sampass, uint8_t *buf, uint32_t buflen)
932 {
933
934         /* times are stored as 32bit integer
935            take care on system with 64bit wide time_t
936            --SSS */
937         uint32_t        logon_time,
938                 logoff_time,
939                 kickoff_time,
940                 pass_last_set_time,
941                 pass_can_change_time,
942                 pass_must_change_time;
943         char *username = NULL;
944         char *domain = NULL;
945         char *nt_username = NULL;
946         char *dir_drive = NULL;
947         char *unknown_str = NULL;
948         char *munged_dial = NULL;
949         char *fullname = NULL;
950         char *homedir = NULL;
951         char *logon_script = NULL;
952         char *profile_path = NULL;
953         char *acct_desc = NULL;
954         char *workstations = NULL;
955         uint32_t        username_len, domain_len, nt_username_len,
956                 dir_drive_len, unknown_str_len, munged_dial_len,
957                 fullname_len, homedir_len, logon_script_len,
958                 profile_path_len, acct_desc_len, workstations_len;
959
960         uint32_t        user_rid, group_rid, remove_me, hours_len, unknown_6;
961         uint16_t        acct_ctrl, logon_divs;
962         uint16_t        bad_password_count, logon_count;
963         uint8_t *hours = NULL;
964         uint8_t *lm_pw_ptr = NULL, *nt_pw_ptr = NULL;
965         uint32_t                len = 0;
966         uint32_t                lm_pw_len, nt_pw_len, hourslen;
967         bool ret = True;
968
969         if(sampass == NULL || buf == NULL) {
970                 DEBUG(0, ("init_samu_from_buffer_v0: NULL parameters found!\n"));
971                 return False;
972         }
973
974 /* SAMU_BUFFER_FORMAT_V0       "ddddddBBBBBBBBBBBBddBBwdwdBwwd" */
975
976         /* unpack the buffer into variables */
977         len = tdb_unpack (buf, buflen, SAMU_BUFFER_FORMAT_V0,
978                 &logon_time,                                            /* d */
979                 &logoff_time,                                           /* d */
980                 &kickoff_time,                                          /* d */
981                 &pass_last_set_time,                                    /* d */
982                 &pass_can_change_time,                                  /* d */
983                 &pass_must_change_time,                                 /* d */
984                 &username_len, &username,                               /* B */
985                 &domain_len, &domain,                                   /* B */
986                 &nt_username_len, &nt_username,                         /* B */
987                 &fullname_len, &fullname,                               /* B */
988                 &homedir_len, &homedir,                                 /* B */
989                 &dir_drive_len, &dir_drive,                             /* B */
990                 &logon_script_len, &logon_script,                       /* B */
991                 &profile_path_len, &profile_path,                       /* B */
992                 &acct_desc_len, &acct_desc,                             /* B */
993                 &workstations_len, &workstations,                       /* B */
994                 &unknown_str_len, &unknown_str,                         /* B */
995                 &munged_dial_len, &munged_dial,                         /* B */
996                 &user_rid,                                              /* d */
997                 &group_rid,                                             /* d */
998                 &lm_pw_len, &lm_pw_ptr,                                 /* B */
999                 &nt_pw_len, &nt_pw_ptr,                                 /* B */
1000                 &acct_ctrl,                                             /* w */
1001                 &remove_me, /* remove on the next TDB_FORMAT upgarde */ /* d */
1002                 &logon_divs,                                            /* w */
1003                 &hours_len,                                             /* d */
1004                 &hourslen, &hours,                                      /* B */
1005                 &bad_password_count,                                    /* w */
1006                 &logon_count,                                           /* w */
1007                 &unknown_6);                                            /* d */
1008
1009         if (len == (uint32_t) -1)  {
1010                 ret = False;
1011                 goto done;
1012         }
1013
1014         pdb_set_logon_time(sampass, logon_time, PDB_SET);
1015         pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
1016         pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
1017         pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
1018         pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
1019         pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
1020
1021         pdb_set_username(sampass, username, PDB_SET); 
1022         pdb_set_domain(sampass, domain, PDB_SET);
1023         pdb_set_nt_username(sampass, nt_username, PDB_SET);
1024         pdb_set_fullname(sampass, fullname, PDB_SET);
1025
1026         if (homedir) {
1027                 pdb_set_homedir(sampass, homedir, PDB_SET);
1028         }
1029         else {
1030                 pdb_set_homedir(sampass, 
1031                         talloc_sub_basic(sampass, username, domain,
1032                                          lp_logon_home()),
1033                         PDB_DEFAULT);
1034         }
1035
1036         if (dir_drive)  
1037                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
1038         else {
1039                 pdb_set_dir_drive(sampass, 
1040                         talloc_sub_basic(sampass, username, domain,
1041                                          lp_logon_drive()),
1042                         PDB_DEFAULT);
1043         }
1044
1045         if (logon_script) 
1046                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
1047         else {
1048                 pdb_set_logon_script(sampass, 
1049                         talloc_sub_basic(sampass, username, domain,
1050                                          lp_logon_script()),
1051                         PDB_DEFAULT);
1052         }
1053
1054         if (profile_path) {     
1055                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
1056         } else {
1057                 pdb_set_profile_path(sampass, 
1058                         talloc_sub_basic(sampass, username, domain,
1059                                          lp_logon_path()),
1060                         PDB_DEFAULT);
1061         }
1062
1063         pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
1064         pdb_set_workstations(sampass, workstations, PDB_SET);
1065         pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
1066
1067         if (lm_pw_ptr && lm_pw_len == LM_HASH_LEN) {
1068                 if (!pdb_set_lanman_passwd(sampass, lm_pw_ptr, PDB_SET)) {
1069                         ret = False;
1070                         goto done;
1071                 }
1072         }
1073
1074         if (nt_pw_ptr && nt_pw_len == NT_HASH_LEN) {
1075                 if (!pdb_set_nt_passwd(sampass, nt_pw_ptr, PDB_SET)) {
1076                         ret = False;
1077                         goto done;
1078                 }
1079         }
1080
1081         pdb_set_pw_history(sampass, NULL, 0, PDB_SET);
1082         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
1083         pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
1084         pdb_set_hours_len(sampass, hours_len, PDB_SET);
1085         pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
1086         pdb_set_logon_count(sampass, logon_count, PDB_SET);
1087         pdb_set_unknown_6(sampass, unknown_6, PDB_SET);
1088         pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
1089         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
1090         pdb_set_hours(sampass, hours, hours_len, PDB_SET);
1091
1092 done:
1093
1094         SAFE_FREE(username);
1095         SAFE_FREE(domain);
1096         SAFE_FREE(nt_username);
1097         SAFE_FREE(fullname);
1098         SAFE_FREE(homedir);
1099         SAFE_FREE(dir_drive);
1100         SAFE_FREE(logon_script);
1101         SAFE_FREE(profile_path);
1102         SAFE_FREE(acct_desc);
1103         SAFE_FREE(workstations);
1104         SAFE_FREE(munged_dial);
1105         SAFE_FREE(unknown_str);
1106         SAFE_FREE(lm_pw_ptr);
1107         SAFE_FREE(nt_pw_ptr);
1108         SAFE_FREE(hours);
1109
1110         return ret;
1111 }
1112
1113 /*********************************************************************
1114 *********************************************************************/
1115
1116 static bool init_samu_from_buffer_v1(struct samu *sampass, uint8_t *buf, uint32_t buflen)
1117 {
1118
1119         /* times are stored as 32bit integer
1120            take care on system with 64bit wide time_t
1121            --SSS */
1122         uint32_t        logon_time,
1123                 logoff_time,
1124                 kickoff_time,
1125                 bad_password_time,
1126                 pass_last_set_time,
1127                 pass_can_change_time,
1128                 pass_must_change_time;
1129         char *username = NULL;
1130         char *domain = NULL;
1131         char *nt_username = NULL;
1132         char *dir_drive = NULL;
1133         char *unknown_str = NULL;
1134         char *munged_dial = NULL;
1135         char *fullname = NULL;
1136         char *homedir = NULL;
1137         char *logon_script = NULL;
1138         char *profile_path = NULL;
1139         char *acct_desc = NULL;
1140         char *workstations = NULL;
1141         uint32_t        username_len, domain_len, nt_username_len,
1142                 dir_drive_len, unknown_str_len, munged_dial_len,
1143                 fullname_len, homedir_len, logon_script_len,
1144                 profile_path_len, acct_desc_len, workstations_len;
1145
1146         uint32_t        user_rid, group_rid, remove_me, hours_len, unknown_6;
1147         uint16_t        acct_ctrl, logon_divs;
1148         uint16_t        bad_password_count, logon_count;
1149         uint8_t *hours = NULL;
1150         uint8_t *lm_pw_ptr = NULL, *nt_pw_ptr = NULL;
1151         uint32_t                len = 0;
1152         uint32_t                lm_pw_len, nt_pw_len, hourslen;
1153         bool ret = True;
1154
1155         if(sampass == NULL || buf == NULL) {
1156                 DEBUG(0, ("init_samu_from_buffer_v1: NULL parameters found!\n"));
1157                 return False;
1158         }
1159
1160 /* SAMU_BUFFER_FORMAT_V1       "dddddddBBBBBBBBBBBBddBBwdwdBwwd" */
1161
1162         /* unpack the buffer into variables */
1163         len = tdb_unpack (buf, buflen, SAMU_BUFFER_FORMAT_V1,
1164                 &logon_time,                                            /* d */
1165                 &logoff_time,                                           /* d */
1166                 &kickoff_time,                                          /* d */
1167                 /* Change from V0 is addition of bad_password_time field. */
1168                 &bad_password_time,                                     /* d */
1169                 &pass_last_set_time,                                    /* d */
1170                 &pass_can_change_time,                                  /* d */
1171                 &pass_must_change_time,                                 /* d */
1172                 &username_len, &username,                               /* B */
1173                 &domain_len, &domain,                                   /* B */
1174                 &nt_username_len, &nt_username,                         /* B */
1175                 &fullname_len, &fullname,                               /* B */
1176                 &homedir_len, &homedir,                                 /* B */
1177                 &dir_drive_len, &dir_drive,                             /* B */
1178                 &logon_script_len, &logon_script,                       /* B */
1179                 &profile_path_len, &profile_path,                       /* B */
1180                 &acct_desc_len, &acct_desc,                             /* B */
1181                 &workstations_len, &workstations,                       /* B */
1182                 &unknown_str_len, &unknown_str,                         /* B */
1183                 &munged_dial_len, &munged_dial,                         /* B */
1184                 &user_rid,                                              /* d */
1185                 &group_rid,                                             /* d */
1186                 &lm_pw_len, &lm_pw_ptr,                                 /* B */
1187                 &nt_pw_len, &nt_pw_ptr,                                 /* B */
1188                 &acct_ctrl,                                             /* w */
1189                 &remove_me,                                             /* d */
1190                 &logon_divs,                                            /* w */
1191                 &hours_len,                                             /* d */
1192                 &hourslen, &hours,                                      /* B */
1193                 &bad_password_count,                                    /* w */
1194                 &logon_count,                                           /* w */
1195                 &unknown_6);                                            /* d */
1196
1197         if (len == (uint32_t) -1)  {
1198                 ret = False;
1199                 goto done;
1200         }
1201
1202         pdb_set_logon_time(sampass, logon_time, PDB_SET);
1203         pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
1204         pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
1205
1206         /* Change from V0 is addition of bad_password_time field. */
1207         pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
1208         pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
1209         pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
1210         pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
1211
1212         pdb_set_username(sampass, username, PDB_SET); 
1213         pdb_set_domain(sampass, domain, PDB_SET);
1214         pdb_set_nt_username(sampass, nt_username, PDB_SET);
1215         pdb_set_fullname(sampass, fullname, PDB_SET);
1216
1217         if (homedir) {
1218                 pdb_set_homedir(sampass, homedir, PDB_SET);
1219         }
1220         else {
1221                 pdb_set_homedir(sampass, 
1222                         talloc_sub_basic(sampass, username, domain,
1223                                          lp_logon_home()),
1224                         PDB_DEFAULT);
1225         }
1226
1227         if (dir_drive)  
1228                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
1229         else {
1230                 pdb_set_dir_drive(sampass, 
1231                         talloc_sub_basic(sampass, username, domain,
1232                                          lp_logon_drive()),
1233                         PDB_DEFAULT);
1234         }
1235
1236         if (logon_script) 
1237                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
1238         else {
1239                 pdb_set_logon_script(sampass, 
1240                         talloc_sub_basic(sampass, username, domain,
1241                                          lp_logon_script()),
1242                         PDB_DEFAULT);
1243         }
1244
1245         if (profile_path) {     
1246                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
1247         } else {
1248                 pdb_set_profile_path(sampass, 
1249                         talloc_sub_basic(sampass, username, domain,
1250                                          lp_logon_path()),
1251                         PDB_DEFAULT);
1252         }
1253
1254         pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
1255         pdb_set_workstations(sampass, workstations, PDB_SET);
1256         pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
1257
1258         if (lm_pw_ptr && lm_pw_len == LM_HASH_LEN) {
1259                 if (!pdb_set_lanman_passwd(sampass, lm_pw_ptr, PDB_SET)) {
1260                         ret = False;
1261                         goto done;
1262                 }
1263         }
1264
1265         if (nt_pw_ptr && nt_pw_len == NT_HASH_LEN) {
1266                 if (!pdb_set_nt_passwd(sampass, nt_pw_ptr, PDB_SET)) {
1267                         ret = False;
1268                         goto done;
1269                 }
1270         }
1271
1272         pdb_set_pw_history(sampass, NULL, 0, PDB_SET);
1273
1274         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
1275         pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
1276         pdb_set_hours_len(sampass, hours_len, PDB_SET);
1277         pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
1278         pdb_set_logon_count(sampass, logon_count, PDB_SET);
1279         pdb_set_unknown_6(sampass, unknown_6, PDB_SET);
1280         pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
1281         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
1282         pdb_set_hours(sampass, hours, hours_len, PDB_SET);
1283
1284 done:
1285
1286         SAFE_FREE(username);
1287         SAFE_FREE(domain);
1288         SAFE_FREE(nt_username);
1289         SAFE_FREE(fullname);
1290         SAFE_FREE(homedir);
1291         SAFE_FREE(dir_drive);
1292         SAFE_FREE(logon_script);
1293         SAFE_FREE(profile_path);
1294         SAFE_FREE(acct_desc);
1295         SAFE_FREE(workstations);
1296         SAFE_FREE(munged_dial);
1297         SAFE_FREE(unknown_str);
1298         SAFE_FREE(lm_pw_ptr);
1299         SAFE_FREE(nt_pw_ptr);
1300         SAFE_FREE(hours);
1301
1302         return ret;
1303 }
1304
1305 static bool init_samu_from_buffer_v2(struct samu *sampass, uint8_t *buf, uint32_t buflen)
1306 {
1307
1308         /* times are stored as 32bit integer
1309            take care on system with 64bit wide time_t
1310            --SSS */
1311         uint32_t        logon_time,
1312                 logoff_time,
1313                 kickoff_time,
1314                 bad_password_time,
1315                 pass_last_set_time,
1316                 pass_can_change_time,
1317                 pass_must_change_time;
1318         char *username = NULL;
1319         char *domain = NULL;
1320         char *nt_username = NULL;
1321         char *dir_drive = NULL;
1322         char *unknown_str = NULL;
1323         char *munged_dial = NULL;
1324         char *fullname = NULL;
1325         char *homedir = NULL;
1326         char *logon_script = NULL;
1327         char *profile_path = NULL;
1328         char *acct_desc = NULL;
1329         char *workstations = NULL;
1330         uint32_t        username_len, domain_len, nt_username_len,
1331                 dir_drive_len, unknown_str_len, munged_dial_len,
1332                 fullname_len, homedir_len, logon_script_len,
1333                 profile_path_len, acct_desc_len, workstations_len;
1334
1335         uint32_t        user_rid, group_rid, hours_len, unknown_6;
1336         uint16_t        acct_ctrl, logon_divs;
1337         uint16_t        bad_password_count, logon_count;
1338         uint8_t *hours = NULL;
1339         uint8_t *lm_pw_ptr = NULL, *nt_pw_ptr = NULL, *nt_pw_hist_ptr = NULL;
1340         uint32_t                len = 0;
1341         uint32_t                lm_pw_len, nt_pw_len, nt_pw_hist_len, hourslen;
1342         uint32_t pwHistLen = 0;
1343         bool ret = True;
1344         fstring tmp_string;
1345         bool expand_explicit = lp_passdb_expand_explicit();
1346
1347         if(sampass == NULL || buf == NULL) {
1348                 DEBUG(0, ("init_samu_from_buffer_v2: NULL parameters found!\n"));
1349                 return False;
1350         }
1351
1352 /* SAMU_BUFFER_FORMAT_V2       "dddddddBBBBBBBBBBBBddBBBwwdBwwd" */
1353
1354         /* unpack the buffer into variables */
1355         len = tdb_unpack (buf, buflen, SAMU_BUFFER_FORMAT_V2,
1356                 &logon_time,                                            /* d */
1357                 &logoff_time,                                           /* d */
1358                 &kickoff_time,                                          /* d */
1359                 &bad_password_time,                                     /* d */
1360                 &pass_last_set_time,                                    /* d */
1361                 &pass_can_change_time,                                  /* d */
1362                 &pass_must_change_time,                                 /* d */
1363                 &username_len, &username,                               /* B */
1364                 &domain_len, &domain,                                   /* B */
1365                 &nt_username_len, &nt_username,                         /* B */
1366                 &fullname_len, &fullname,                               /* B */
1367                 &homedir_len, &homedir,                                 /* B */
1368                 &dir_drive_len, &dir_drive,                             /* B */
1369                 &logon_script_len, &logon_script,                       /* B */
1370                 &profile_path_len, &profile_path,                       /* B */
1371                 &acct_desc_len, &acct_desc,                             /* B */
1372                 &workstations_len, &workstations,                       /* B */
1373                 &unknown_str_len, &unknown_str,                         /* B */
1374                 &munged_dial_len, &munged_dial,                         /* B */
1375                 &user_rid,                                              /* d */
1376                 &group_rid,                                             /* d */
1377                 &lm_pw_len, &lm_pw_ptr,                                 /* B */
1378                 &nt_pw_len, &nt_pw_ptr,                                 /* B */
1379                 /* Change from V1 is addition of password history field. */
1380                 &nt_pw_hist_len, &nt_pw_hist_ptr,                       /* B */
1381                 &acct_ctrl,                                             /* w */
1382                 /* Also "remove_me" field was removed. */
1383                 &logon_divs,                                            /* w */
1384                 &hours_len,                                             /* d */
1385                 &hourslen, &hours,                                      /* B */
1386                 &bad_password_count,                                    /* w */
1387                 &logon_count,                                           /* w */
1388                 &unknown_6);                                            /* d */
1389
1390         if (len == (uint32_t) -1)  {
1391                 ret = False;
1392                 goto done;
1393         }
1394
1395         pdb_set_logon_time(sampass, logon_time, PDB_SET);
1396         pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
1397         pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
1398         pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
1399         pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
1400         pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
1401         pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
1402
1403         pdb_set_username(sampass, username, PDB_SET); 
1404         pdb_set_domain(sampass, domain, PDB_SET);
1405         pdb_set_nt_username(sampass, nt_username, PDB_SET);
1406         pdb_set_fullname(sampass, fullname, PDB_SET);
1407
1408         if (homedir) {
1409                 fstrcpy( tmp_string, homedir );
1410                 if (expand_explicit) {
1411                         standard_sub_basic( username, domain, tmp_string,
1412                                             sizeof(tmp_string) );
1413                 }
1414                 pdb_set_homedir(sampass, tmp_string, PDB_SET);
1415         }
1416         else {
1417                 pdb_set_homedir(sampass, 
1418                         talloc_sub_basic(sampass, username, domain,
1419                                          lp_logon_home()),
1420                         PDB_DEFAULT);
1421         }
1422
1423         if (dir_drive)  
1424                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
1425         else
1426                 pdb_set_dir_drive(sampass, lp_logon_drive(), PDB_DEFAULT );
1427
1428         if (logon_script) {
1429                 fstrcpy( tmp_string, logon_script );
1430                 if (expand_explicit) {
1431                         standard_sub_basic( username, domain, tmp_string,
1432                                             sizeof(tmp_string) );
1433                 }
1434                 pdb_set_logon_script(sampass, tmp_string, PDB_SET);
1435         }
1436         else {
1437                 pdb_set_logon_script(sampass, 
1438                         talloc_sub_basic(sampass, username, domain,
1439                                          lp_logon_script()),
1440                         PDB_DEFAULT);
1441         }
1442
1443         if (profile_path) {     
1444                 fstrcpy( tmp_string, profile_path );
1445                 if (expand_explicit) {
1446                         standard_sub_basic( username, domain, tmp_string,
1447                                             sizeof(tmp_string) );
1448                 }
1449                 pdb_set_profile_path(sampass, tmp_string, PDB_SET);
1450         } 
1451         else {
1452                 pdb_set_profile_path(sampass, 
1453                         talloc_sub_basic(sampass, username, domain,
1454                                          lp_logon_path()),
1455                         PDB_DEFAULT);
1456         }
1457
1458         pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
1459         pdb_set_workstations(sampass, workstations, PDB_SET);
1460         pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
1461
1462         if (lm_pw_ptr && lm_pw_len == LM_HASH_LEN) {
1463                 if (!pdb_set_lanman_passwd(sampass, lm_pw_ptr, PDB_SET)) {
1464                         ret = False;
1465                         goto done;
1466                 }
1467         }
1468
1469         if (nt_pw_ptr && nt_pw_len == NT_HASH_LEN) {
1470                 if (!pdb_set_nt_passwd(sampass, nt_pw_ptr, PDB_SET)) {
1471                         ret = False;
1472                         goto done;
1473                 }
1474         }
1475
1476         /* Change from V1 is addition of password history field. */
1477         pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
1478         if (pwHistLen) {
1479                 uint8_t *pw_hist = SMB_MALLOC_ARRAY(uint8_t, pwHistLen * PW_HISTORY_ENTRY_LEN);
1480                 if (!pw_hist) {
1481                         ret = False;
1482                         goto done;
1483                 }
1484                 memset(pw_hist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
1485                 if (nt_pw_hist_ptr && nt_pw_hist_len) {
1486                         int i;
1487                         SMB_ASSERT((nt_pw_hist_len % PW_HISTORY_ENTRY_LEN) == 0);
1488                         nt_pw_hist_len /= PW_HISTORY_ENTRY_LEN;
1489                         for (i = 0; (i < pwHistLen) && (i < nt_pw_hist_len); i++) {
1490                                 memcpy(&pw_hist[i*PW_HISTORY_ENTRY_LEN],
1491                                         &nt_pw_hist_ptr[i*PW_HISTORY_ENTRY_LEN],
1492                                         PW_HISTORY_ENTRY_LEN);
1493                         }
1494                 }
1495                 if (!pdb_set_pw_history(sampass, pw_hist, pwHistLen, PDB_SET)) {
1496                         SAFE_FREE(pw_hist);
1497                         ret = False;
1498                         goto done;
1499                 }
1500                 SAFE_FREE(pw_hist);
1501         } else {
1502                 pdb_set_pw_history(sampass, NULL, 0, PDB_SET);
1503         }
1504
1505         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
1506         pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
1507         pdb_set_hours_len(sampass, hours_len, PDB_SET);
1508         pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
1509         pdb_set_logon_count(sampass, logon_count, PDB_SET);
1510         pdb_set_unknown_6(sampass, unknown_6, PDB_SET);
1511         pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
1512         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
1513         pdb_set_hours(sampass, hours, hours_len, PDB_SET);
1514
1515 done:
1516
1517         SAFE_FREE(username);
1518         SAFE_FREE(domain);
1519         SAFE_FREE(nt_username);
1520         SAFE_FREE(fullname);
1521         SAFE_FREE(homedir);
1522         SAFE_FREE(dir_drive);
1523         SAFE_FREE(logon_script);
1524         SAFE_FREE(profile_path);
1525         SAFE_FREE(acct_desc);
1526         SAFE_FREE(workstations);
1527         SAFE_FREE(munged_dial);
1528         SAFE_FREE(unknown_str);
1529         SAFE_FREE(lm_pw_ptr);
1530         SAFE_FREE(nt_pw_ptr);
1531         SAFE_FREE(nt_pw_hist_ptr);
1532         SAFE_FREE(hours);
1533
1534         return ret;
1535 }
1536
1537 /*********************************************************************
1538 *********************************************************************/
1539
1540 static bool init_samu_from_buffer_v3(struct samu *sampass, uint8_t *buf, uint32_t buflen)
1541 {
1542
1543         /* times are stored as 32bit integer
1544            take care on system with 64bit wide time_t
1545            --SSS */
1546         uint32_t        logon_time,
1547                 logoff_time,
1548                 kickoff_time,
1549                 bad_password_time,
1550                 pass_last_set_time,
1551                 pass_can_change_time,
1552                 pass_must_change_time;
1553         char *username = NULL;
1554         char *domain = NULL;
1555         char *nt_username = NULL;
1556         char *dir_drive = NULL;
1557         char *comment = NULL;
1558         char *munged_dial = NULL;
1559         char *fullname = NULL;
1560         char *homedir = NULL;
1561         char *logon_script = NULL;
1562         char *profile_path = NULL;
1563         char *acct_desc = NULL;
1564         char *workstations = NULL;
1565         uint32_t        username_len, domain_len, nt_username_len,
1566                 dir_drive_len, comment_len, munged_dial_len,
1567                 fullname_len, homedir_len, logon_script_len,
1568                 profile_path_len, acct_desc_len, workstations_len;
1569
1570         uint32_t        user_rid, group_rid, hours_len, unknown_6, acct_ctrl;
1571         uint16_t  logon_divs;
1572         uint16_t        bad_password_count, logon_count;
1573         uint8_t *hours = NULL;
1574         uint8_t *lm_pw_ptr = NULL, *nt_pw_ptr = NULL, *nt_pw_hist_ptr = NULL;
1575         uint32_t                len = 0;
1576         uint32_t                lm_pw_len, nt_pw_len, nt_pw_hist_len, hourslen;
1577         uint32_t pwHistLen = 0;
1578         bool ret = True;
1579         fstring tmp_string;
1580         bool expand_explicit = lp_passdb_expand_explicit();
1581
1582         if(sampass == NULL || buf == NULL) {
1583                 DEBUG(0, ("init_samu_from_buffer_v3: NULL parameters found!\n"));
1584                 return False;
1585         }
1586
1587 /* SAMU_BUFFER_FORMAT_V3       "dddddddBBBBBBBBBBBBddBBBdwdBwwd" */
1588
1589         /* unpack the buffer into variables */
1590         len = tdb_unpack (buf, buflen, SAMU_BUFFER_FORMAT_V3,
1591                 &logon_time,                                            /* d */
1592                 &logoff_time,                                           /* d */
1593                 &kickoff_time,                                          /* d */
1594                 &bad_password_time,                                     /* d */
1595                 &pass_last_set_time,                                    /* d */
1596                 &pass_can_change_time,                                  /* d */
1597                 &pass_must_change_time,                                 /* d */
1598                 &username_len, &username,                               /* B */
1599                 &domain_len, &domain,                                   /* B */
1600                 &nt_username_len, &nt_username,                         /* B */
1601                 &fullname_len, &fullname,                               /* B */
1602                 &homedir_len, &homedir,                                 /* B */
1603                 &dir_drive_len, &dir_drive,                             /* B */
1604                 &logon_script_len, &logon_script,                       /* B */
1605                 &profile_path_len, &profile_path,                       /* B */
1606                 &acct_desc_len, &acct_desc,                             /* B */
1607                 &workstations_len, &workstations,                       /* B */
1608                 &comment_len, &comment,                                 /* B */
1609                 &munged_dial_len, &munged_dial,                         /* B */
1610                 &user_rid,                                              /* d */
1611                 &group_rid,                                             /* d */
1612                 &lm_pw_len, &lm_pw_ptr,                                 /* B */
1613                 &nt_pw_len, &nt_pw_ptr,                                 /* B */
1614                 /* Change from V1 is addition of password history field. */
1615                 &nt_pw_hist_len, &nt_pw_hist_ptr,                       /* B */
1616                 /* Change from V2 is the uint32_t acb_mask */
1617                 &acct_ctrl,                                             /* d */
1618                 /* Also "remove_me" field was removed. */
1619                 &logon_divs,                                            /* w */
1620                 &hours_len,                                             /* d */
1621                 &hourslen, &hours,                                      /* B */
1622                 &bad_password_count,                                    /* w */
1623                 &logon_count,                                           /* w */
1624                 &unknown_6);                                            /* d */
1625
1626         if (len == (uint32_t) -1)  {
1627                 ret = False;
1628                 goto done;
1629         }
1630
1631         pdb_set_logon_time(sampass, convert_uint32_t_to_time_t(logon_time), PDB_SET);
1632         pdb_set_logoff_time(sampass, convert_uint32_t_to_time_t(logoff_time), PDB_SET);
1633         pdb_set_kickoff_time(sampass, convert_uint32_t_to_time_t(kickoff_time), PDB_SET);
1634         pdb_set_bad_password_time(sampass, convert_uint32_t_to_time_t(bad_password_time), PDB_SET);
1635         pdb_set_pass_can_change_time(sampass, convert_uint32_t_to_time_t(pass_can_change_time), PDB_SET);
1636         pdb_set_pass_must_change_time(sampass, convert_uint32_t_to_time_t(pass_must_change_time), PDB_SET);
1637         pdb_set_pass_last_set_time(sampass, convert_uint32_t_to_time_t(pass_last_set_time), PDB_SET);
1638
1639         pdb_set_username(sampass, username, PDB_SET); 
1640         pdb_set_domain(sampass, domain, PDB_SET);
1641         pdb_set_nt_username(sampass, nt_username, PDB_SET);
1642         pdb_set_fullname(sampass, fullname, PDB_SET);
1643
1644         if (homedir) {
1645                 fstrcpy( tmp_string, homedir );
1646                 if (expand_explicit) {
1647                         standard_sub_basic( username, domain, tmp_string,
1648                                             sizeof(tmp_string) );
1649                 }
1650                 pdb_set_homedir(sampass, tmp_string, PDB_SET);
1651         }
1652         else {
1653                 pdb_set_homedir(sampass, 
1654                         talloc_sub_basic(sampass, username, domain,
1655                                          lp_logon_home()),
1656                         PDB_DEFAULT);
1657         }
1658
1659         if (dir_drive)  
1660                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
1661         else
1662                 pdb_set_dir_drive(sampass, lp_logon_drive(), PDB_DEFAULT );
1663
1664         if (logon_script) {
1665                 fstrcpy( tmp_string, logon_script );
1666                 if (expand_explicit) {
1667                         standard_sub_basic( username, domain, tmp_string,
1668                                             sizeof(tmp_string) );
1669                 }
1670                 pdb_set_logon_script(sampass, tmp_string, PDB_SET);
1671         }
1672         else {
1673                 pdb_set_logon_script(sampass, 
1674                         talloc_sub_basic(sampass, username, domain,
1675                                          lp_logon_script()),
1676                         PDB_DEFAULT);
1677         }
1678
1679         if (profile_path) {     
1680                 fstrcpy( tmp_string, profile_path );
1681                 if (expand_explicit) {
1682                         standard_sub_basic( username, domain, tmp_string,
1683                                             sizeof(tmp_string) );
1684                 }
1685                 pdb_set_profile_path(sampass, tmp_string, PDB_SET);
1686         } 
1687         else {
1688                 pdb_set_profile_path(sampass, 
1689                         talloc_sub_basic(sampass, username, domain, lp_logon_path()),
1690                         PDB_DEFAULT);
1691         }
1692
1693         pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
1694         pdb_set_comment(sampass, comment, PDB_SET);
1695         pdb_set_workstations(sampass, workstations, PDB_SET);
1696         pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
1697
1698         if (lm_pw_ptr && lm_pw_len == LM_HASH_LEN) {
1699                 if (!pdb_set_lanman_passwd(sampass, lm_pw_ptr, PDB_SET)) {
1700                         ret = False;
1701                         goto done;
1702                 }
1703         }
1704
1705         if (nt_pw_ptr && nt_pw_len == NT_HASH_LEN) {
1706                 if (!pdb_set_nt_passwd(sampass, nt_pw_ptr, PDB_SET)) {
1707                         ret = False;
1708                         goto done;
1709                 }
1710         }
1711
1712         pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
1713         if (pwHistLen) {
1714                 uint8_t *pw_hist = (uint8_t *)SMB_MALLOC(pwHistLen * PW_HISTORY_ENTRY_LEN);
1715                 if (!pw_hist) {
1716                         ret = False;
1717                         goto done;
1718                 }
1719                 memset(pw_hist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
1720                 if (nt_pw_hist_ptr && nt_pw_hist_len) {
1721                         int i;
1722                         SMB_ASSERT((nt_pw_hist_len % PW_HISTORY_ENTRY_LEN) == 0);
1723                         nt_pw_hist_len /= PW_HISTORY_ENTRY_LEN;
1724                         for (i = 0; (i < pwHistLen) && (i < nt_pw_hist_len); i++) {
1725                                 memcpy(&pw_hist[i*PW_HISTORY_ENTRY_LEN],
1726                                         &nt_pw_hist_ptr[i*PW_HISTORY_ENTRY_LEN],
1727                                         PW_HISTORY_ENTRY_LEN);
1728                         }
1729                 }
1730                 if (!pdb_set_pw_history(sampass, pw_hist, pwHistLen, PDB_SET)) {
1731                         SAFE_FREE(pw_hist);
1732                         ret = False;
1733                         goto done;
1734                 }
1735                 SAFE_FREE(pw_hist);
1736         } else {
1737                 pdb_set_pw_history(sampass, NULL, 0, PDB_SET);
1738         }
1739
1740         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
1741         pdb_set_hours_len(sampass, hours_len, PDB_SET);
1742         pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
1743         pdb_set_logon_count(sampass, logon_count, PDB_SET);
1744         pdb_set_unknown_6(sampass, unknown_6, PDB_SET);
1745         /* Change from V2 is the uint32_t acct_ctrl */
1746         pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
1747         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
1748         pdb_set_hours(sampass, hours, hours_len, PDB_SET);
1749
1750 done:
1751
1752         SAFE_FREE(username);
1753         SAFE_FREE(domain);
1754         SAFE_FREE(nt_username);
1755         SAFE_FREE(fullname);
1756         SAFE_FREE(homedir);
1757         SAFE_FREE(dir_drive);
1758         SAFE_FREE(logon_script);
1759         SAFE_FREE(profile_path);
1760         SAFE_FREE(acct_desc);
1761         SAFE_FREE(workstations);
1762         SAFE_FREE(munged_dial);
1763         SAFE_FREE(comment);
1764         SAFE_FREE(lm_pw_ptr);
1765         SAFE_FREE(nt_pw_ptr);
1766         SAFE_FREE(nt_pw_hist_ptr);
1767         SAFE_FREE(hours);
1768
1769         return ret;
1770 }
1771
1772 /*********************************************************************
1773 *********************************************************************/
1774
1775 static uint32_t init_buffer_from_samu_v3 (uint8_t **buf, struct samu *sampass, bool size_only)
1776 {
1777         size_t len, buflen;
1778
1779         /* times are stored as 32bit integer
1780            take care on system with 64bit wide time_t
1781            --SSS */
1782         uint32_t        logon_time,
1783                 logoff_time,
1784                 kickoff_time,
1785                 bad_password_time,
1786                 pass_last_set_time,
1787                 pass_can_change_time,
1788                 pass_must_change_time;
1789
1790         uint32_t  user_rid, group_rid;
1791
1792         const char *username;
1793         const char *domain;
1794         const char *nt_username;
1795         const char *dir_drive;
1796         const char *comment;
1797         const char *munged_dial;
1798         const char *fullname;
1799         const char *homedir;
1800         const char *logon_script;
1801         const char *profile_path;
1802         const char *acct_desc;
1803         const char *workstations;
1804         uint32_t        username_len, domain_len, nt_username_len,
1805                 dir_drive_len, comment_len, munged_dial_len,
1806                 fullname_len, homedir_len, logon_script_len,
1807                 profile_path_len, acct_desc_len, workstations_len;
1808
1809         const uint8_t *lm_pw;
1810         const uint8_t *nt_pw;
1811         const uint8_t *nt_pw_hist;
1812         uint32_t        lm_pw_len = 16;
1813         uint32_t        nt_pw_len = 16;
1814         uint32_t  nt_pw_hist_len;
1815         uint32_t pwHistLen = 0;
1816
1817         *buf = NULL;
1818         buflen = 0;
1819
1820         logon_time = convert_time_t_to_uint32_t(pdb_get_logon_time(sampass));
1821         logoff_time = convert_time_t_to_uint32_t(pdb_get_logoff_time(sampass));
1822         kickoff_time = convert_time_t_to_uint32_t(pdb_get_kickoff_time(sampass));
1823         bad_password_time = convert_time_t_to_uint32_t(pdb_get_bad_password_time(sampass));
1824         pass_can_change_time = convert_time_t_to_uint32_t(pdb_get_pass_can_change_time_noncalc(sampass));
1825         pass_must_change_time = convert_time_t_to_uint32_t(pdb_get_pass_must_change_time(sampass));
1826         pass_last_set_time = convert_time_t_to_uint32_t(pdb_get_pass_last_set_time(sampass));
1827
1828         user_rid = pdb_get_user_rid(sampass);
1829         group_rid = pdb_get_group_rid(sampass);
1830
1831         username = pdb_get_username(sampass);
1832         if (username) {
1833                 username_len = strlen(username) +1;
1834         } else {
1835                 username_len = 0;
1836         }
1837
1838         domain = pdb_get_domain(sampass);
1839         if (domain) {
1840                 domain_len = strlen(domain) +1;
1841         } else {
1842                 domain_len = 0;
1843         }
1844
1845         nt_username = pdb_get_nt_username(sampass);
1846         if (nt_username) {
1847                 nt_username_len = strlen(nt_username) +1;
1848         } else {
1849                 nt_username_len = 0;
1850         }
1851
1852         fullname = pdb_get_fullname(sampass);
1853         if (fullname) {
1854                 fullname_len = strlen(fullname) +1;
1855         } else {
1856                 fullname_len = 0;
1857         }
1858
1859         /*
1860          * Only updates fields which have been set (not defaults from smb.conf)
1861          */
1862
1863         if (!IS_SAM_DEFAULT(sampass, PDB_DRIVE)) {
1864                 dir_drive = pdb_get_dir_drive(sampass);
1865         } else {
1866                 dir_drive = NULL;
1867         }
1868         if (dir_drive) {
1869                 dir_drive_len = strlen(dir_drive) +1;
1870         } else {
1871                 dir_drive_len = 0;
1872         }
1873
1874         if (!IS_SAM_DEFAULT(sampass, PDB_SMBHOME)) {
1875                 homedir = pdb_get_homedir(sampass);
1876         } else {
1877                 homedir = NULL;
1878         }
1879         if (homedir) {
1880                 homedir_len = strlen(homedir) +1;
1881         } else {
1882                 homedir_len = 0;
1883         }
1884
1885         if (!IS_SAM_DEFAULT(sampass, PDB_LOGONSCRIPT)) {
1886                 logon_script = pdb_get_logon_script(sampass);
1887         } else {
1888                 logon_script = NULL;
1889         }
1890         if (logon_script) {
1891                 logon_script_len = strlen(logon_script) +1;
1892         } else {
1893                 logon_script_len = 0;
1894         }
1895
1896         if (!IS_SAM_DEFAULT(sampass, PDB_PROFILE)) {
1897                 profile_path = pdb_get_profile_path(sampass);
1898         } else {
1899                 profile_path = NULL;
1900         }
1901         if (profile_path) {
1902                 profile_path_len = strlen(profile_path) +1;
1903         } else {
1904                 profile_path_len = 0;
1905         }
1906
1907         lm_pw = pdb_get_lanman_passwd(sampass);
1908         if (!lm_pw) {
1909                 lm_pw_len = 0;
1910         }
1911
1912         nt_pw = pdb_get_nt_passwd(sampass);
1913         if (!nt_pw) {
1914                 nt_pw_len = 0;
1915         }
1916
1917         pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
1918         nt_pw_hist =  pdb_get_pw_history(sampass, &nt_pw_hist_len);
1919         if (pwHistLen && nt_pw_hist && nt_pw_hist_len) {
1920                 nt_pw_hist_len *= PW_HISTORY_ENTRY_LEN;
1921         } else {
1922                 nt_pw_hist_len = 0;
1923         }
1924
1925         acct_desc = pdb_get_acct_desc(sampass);
1926         if (acct_desc) {
1927                 acct_desc_len = strlen(acct_desc) +1;
1928         } else {
1929                 acct_desc_len = 0;
1930         }
1931
1932         workstations = pdb_get_workstations(sampass);
1933         if (workstations) {
1934                 workstations_len = strlen(workstations) +1;
1935         } else {
1936                 workstations_len = 0;
1937         }
1938
1939         comment = pdb_get_comment(sampass);
1940         if (comment) {
1941                 comment_len = strlen(comment) +1;
1942         } else {
1943                 comment_len = 0;
1944         }
1945
1946         munged_dial = pdb_get_munged_dial(sampass);
1947         if (munged_dial) {
1948                 munged_dial_len = strlen(munged_dial) +1;
1949         } else {
1950                 munged_dial_len = 0;    
1951         }
1952
1953 /* SAMU_BUFFER_FORMAT_V3       "dddddddBBBBBBBBBBBBddBBBdwdBwwd" */
1954
1955         /* one time to get the size needed */
1956         len = tdb_pack(NULL, 0,  SAMU_BUFFER_FORMAT_V3,
1957                 logon_time,                             /* d */
1958                 logoff_time,                            /* d */
1959                 kickoff_time,                           /* d */
1960                 bad_password_time,                      /* d */
1961                 pass_last_set_time,                     /* d */
1962                 pass_can_change_time,                   /* d */
1963                 pass_must_change_time,                  /* d */
1964                 username_len, username,                 /* B */
1965                 domain_len, domain,                     /* B */
1966                 nt_username_len, nt_username,           /* B */
1967                 fullname_len, fullname,                 /* B */
1968                 homedir_len, homedir,                   /* B */
1969                 dir_drive_len, dir_drive,               /* B */
1970                 logon_script_len, logon_script,         /* B */
1971                 profile_path_len, profile_path,         /* B */
1972                 acct_desc_len, acct_desc,               /* B */
1973                 workstations_len, workstations,         /* B */
1974                 comment_len, comment,                   /* B */
1975                 munged_dial_len, munged_dial,           /* B */
1976                 user_rid,                               /* d */
1977                 group_rid,                              /* d */
1978                 lm_pw_len, lm_pw,                       /* B */
1979                 nt_pw_len, nt_pw,                       /* B */
1980                 nt_pw_hist_len, nt_pw_hist,             /* B */
1981                 pdb_get_acct_ctrl(sampass),             /* d */
1982                 pdb_get_logon_divs(sampass),            /* w */
1983                 pdb_get_hours_len(sampass),             /* d */
1984                 MAX_HOURS_LEN, pdb_get_hours(sampass),  /* B */
1985                 pdb_get_bad_password_count(sampass),    /* w */
1986                 pdb_get_logon_count(sampass),           /* w */
1987                 pdb_get_unknown_6(sampass));            /* d */
1988
1989         if (size_only) {
1990                 return buflen;
1991         }
1992
1993         /* malloc the space needed */
1994         if ( (*buf=(uint8_t*)SMB_MALLOC(len)) == NULL) {
1995                 DEBUG(0,("init_buffer_from_samu_v3: Unable to malloc() memory for buffer!\n"));
1996                 return (-1);
1997         }
1998
1999         /* now for the real call to tdb_pack() */
2000         buflen = tdb_pack(*buf, len,  SAMU_BUFFER_FORMAT_V3,
2001                 logon_time,                             /* d */
2002                 logoff_time,                            /* d */
2003                 kickoff_time,                           /* d */
2004                 bad_password_time,                      /* d */
2005                 pass_last_set_time,                     /* d */
2006                 pass_can_change_time,                   /* d */
2007                 pass_must_change_time,                  /* d */
2008                 username_len, username,                 /* B */
2009                 domain_len, domain,                     /* B */
2010                 nt_username_len, nt_username,           /* B */
2011                 fullname_len, fullname,                 /* B */
2012                 homedir_len, homedir,                   /* B */
2013                 dir_drive_len, dir_drive,               /* B */
2014                 logon_script_len, logon_script,         /* B */
2015                 profile_path_len, profile_path,         /* B */
2016                 acct_desc_len, acct_desc,               /* B */
2017                 workstations_len, workstations,         /* B */
2018                 comment_len, comment,                   /* B */
2019                 munged_dial_len, munged_dial,           /* B */
2020                 user_rid,                               /* d */
2021                 group_rid,                              /* d */
2022                 lm_pw_len, lm_pw,                       /* B */
2023                 nt_pw_len, nt_pw,                       /* B */
2024                 nt_pw_hist_len, nt_pw_hist,             /* B */
2025                 pdb_get_acct_ctrl(sampass),             /* d */
2026                 pdb_get_logon_divs(sampass),            /* w */
2027                 pdb_get_hours_len(sampass),             /* d */
2028                 MAX_HOURS_LEN, pdb_get_hours(sampass),  /* B */
2029                 pdb_get_bad_password_count(sampass),    /* w */
2030                 pdb_get_logon_count(sampass),           /* w */
2031                 pdb_get_unknown_6(sampass));            /* d */
2032
2033         /* check to make sure we got it correct */
2034         if (buflen != len) {
2035                 DEBUG(0, ("init_buffer_from_samu_v3: somthing odd is going on here: bufflen (%lu) != len (%lu) in tdb_pack operations!\n", 
2036                           (unsigned long)buflen, (unsigned long)len));  
2037                 /* error */
2038                 SAFE_FREE (*buf);
2039                 return (-1);
2040         }
2041
2042         return (buflen);
2043 }
2044
2045 static bool init_samu_from_buffer_v4(struct samu *sampass, uint8_t *buf, uint32_t buflen)
2046 {
2047         /* nothing changed between V3 and V4 */
2048         return init_samu_from_buffer_v3(sampass, buf, buflen);
2049 }
2050
2051 static uint32_t init_buffer_from_samu_v4(uint8_t **buf, struct samu *sampass, bool size_only)
2052 {
2053         /* nothing changed between V3 and V4 */
2054         return init_buffer_from_samu_v3(buf, sampass, size_only);
2055 }
2056
2057 /**********************************************************************
2058  Intialize a struct samu struct from a BYTE buffer of size len
2059  *********************************************************************/
2060
2061 bool init_samu_from_buffer(struct samu *sampass, uint32_t level,
2062                            uint8_t *buf, uint32_t buflen)
2063 {
2064         switch (level) {
2065         case SAMU_BUFFER_V0:
2066                 return init_samu_from_buffer_v0(sampass, buf, buflen);
2067         case SAMU_BUFFER_V1:
2068                 return init_samu_from_buffer_v1(sampass, buf, buflen);
2069         case SAMU_BUFFER_V2:
2070                 return init_samu_from_buffer_v2(sampass, buf, buflen);
2071         case SAMU_BUFFER_V3:
2072                 return init_samu_from_buffer_v3(sampass, buf, buflen);
2073         case SAMU_BUFFER_V4:
2074                 return init_samu_from_buffer_v4(sampass, buf, buflen);
2075         }
2076
2077         return false;
2078 }
2079
2080 /**********************************************************************
2081  Intialize a BYTE buffer from a struct samu struct
2082  *********************************************************************/
2083
2084 uint32_t init_buffer_from_samu (uint8_t **buf, struct samu *sampass, bool size_only)
2085 {
2086         return init_buffer_from_samu_v4(buf, sampass, size_only);
2087 }
2088
2089 /*********************************************************************
2090 *********************************************************************/
2091
2092 bool pdb_copy_sam_account(struct samu *dst, struct samu *src )
2093 {
2094         uint8_t *buf = NULL;
2095         int len;
2096
2097         len = init_buffer_from_samu(&buf, src, False);
2098         if (len == -1 || !buf) {
2099                 SAFE_FREE(buf);
2100                 return False;
2101         }
2102
2103         if (!init_samu_from_buffer( dst, SAMU_BUFFER_LATEST, buf, len )) {
2104                 free(buf);
2105                 return False;
2106         }
2107
2108         dst->methods = src->methods;
2109
2110         if ( src->unix_pw ) {
2111                 dst->unix_pw = tcopy_passwd( dst, src->unix_pw );
2112                 if (!dst->unix_pw) {
2113                         free(buf);
2114                         return False;
2115                 }
2116         }
2117
2118         if (src->group_sid) {
2119                 pdb_set_group_sid(dst, src->group_sid, PDB_SET);
2120         }
2121
2122         free(buf);
2123         return True;
2124 }
2125
2126 /*********************************************************************
2127  Update the bad password count checking the PDB_POLICY_RESET_COUNT_TIME
2128 *********************************************************************/
2129
2130 bool pdb_update_bad_password_count(struct samu *sampass, bool *updated)
2131 {
2132         time_t LastBadPassword;
2133         uint16_t BadPasswordCount;
2134         uint32_t resettime;
2135         bool res;
2136
2137         BadPasswordCount = pdb_get_bad_password_count(sampass);
2138         if (!BadPasswordCount) {
2139                 DEBUG(9, ("No bad password attempts.\n"));
2140                 return True;
2141         }
2142
2143         become_root();
2144         res = pdb_get_account_policy(PDB_POLICY_RESET_COUNT_TIME, &resettime);
2145         unbecome_root();
2146
2147         if (!res) {
2148                 DEBUG(0, ("pdb_update_bad_password_count: pdb_get_account_policy failed.\n"));
2149                 return False;
2150         }
2151
2152         /* First, check if there is a reset time to compare */
2153         if ((resettime == (uint32_t) -1) || (resettime == 0)) {
2154                 DEBUG(9, ("No reset time, can't reset bad pw count\n"));
2155                 return True;
2156         }
2157
2158         LastBadPassword = pdb_get_bad_password_time(sampass);
2159         DEBUG(7, ("LastBadPassword=%d, resettime=%d, current time=%d.\n", 
2160                    (uint32_t) LastBadPassword, resettime, (uint32_t)time(NULL)));
2161         if (time(NULL) > (LastBadPassword + convert_uint32_t_to_time_t(resettime)*60)){
2162                 pdb_set_bad_password_count(sampass, 0, PDB_CHANGED);
2163                 pdb_set_bad_password_time(sampass, 0, PDB_CHANGED);
2164                 if (updated) {
2165                         *updated = True;
2166                 }
2167         }
2168
2169         return True;
2170 }
2171
2172 /*********************************************************************
2173  Update the ACB_AUTOLOCK flag checking the PDB_POLICY_LOCK_ACCOUNT_DURATION
2174 *********************************************************************/
2175
2176 bool pdb_update_autolock_flag(struct samu *sampass, bool *updated)
2177 {
2178         uint32_t duration;
2179         time_t LastBadPassword;
2180         bool res;
2181
2182         if (!(pdb_get_acct_ctrl(sampass) & ACB_AUTOLOCK)) {
2183                 DEBUG(9, ("pdb_update_autolock_flag: Account %s not autolocked, no check needed\n",
2184                         pdb_get_username(sampass)));
2185                 return True;
2186         }
2187
2188         become_root();
2189         res = pdb_get_account_policy(PDB_POLICY_LOCK_ACCOUNT_DURATION, &duration);
2190         unbecome_root();
2191
2192         if (!res) {
2193                 DEBUG(0, ("pdb_update_autolock_flag: pdb_get_account_policy failed.\n"));
2194                 return False;
2195         }
2196
2197         /* First, check if there is a duration to compare */
2198         if ((duration == (uint32_t) -1)  || (duration == 0)) {
2199                 DEBUG(9, ("pdb_update_autolock_flag: No reset duration, can't reset autolock\n"));
2200                 return True;
2201         }
2202
2203         LastBadPassword = pdb_get_bad_password_time(sampass);
2204         DEBUG(7, ("pdb_update_autolock_flag: Account %s, LastBadPassword=%d, duration=%d, current time =%d.\n",
2205                   pdb_get_username(sampass), (uint32_t)LastBadPassword, duration*60, (uint32_t)time(NULL)));
2206
2207         if (LastBadPassword == (time_t)0) {
2208                 DEBUG(1,("pdb_update_autolock_flag: Account %s "
2209                          "administratively locked out with no bad password "
2210                          "time. Leaving locked out.\n",
2211                          pdb_get_username(sampass) ));
2212                 return True;
2213         }
2214
2215         if ((time(NULL) > (LastBadPassword + convert_uint32_t_to_time_t(duration) * 60))) {
2216                 pdb_set_acct_ctrl(sampass,
2217                                   pdb_get_acct_ctrl(sampass) & ~ACB_AUTOLOCK,
2218                                   PDB_CHANGED);
2219                 pdb_set_bad_password_count(sampass, 0, PDB_CHANGED);
2220                 pdb_set_bad_password_time(sampass, 0, PDB_CHANGED);
2221                 if (updated) {
2222                         *updated = True;
2223                 }
2224         }
2225
2226         return True;
2227 }
2228
2229 /*********************************************************************
2230  Increment the bad_password_count 
2231 *********************************************************************/
2232
2233 bool pdb_increment_bad_password_count(struct samu *sampass)
2234 {
2235         uint32_t account_policy_lockout;
2236         bool autolock_updated = False, badpw_updated = False;
2237         bool ret;
2238
2239         /* Retrieve the account lockout policy */
2240         become_root();
2241         ret = pdb_get_account_policy(PDB_POLICY_BAD_ATTEMPT_LOCKOUT, &account_policy_lockout);
2242         unbecome_root();
2243         if ( !ret ) {
2244                 DEBUG(0, ("pdb_increment_bad_password_count: pdb_get_account_policy failed.\n"));
2245                 return False;
2246         }
2247
2248         /* If there is no policy, we don't need to continue checking */
2249         if (!account_policy_lockout) {
2250                 DEBUG(9, ("No lockout policy, don't track bad passwords\n"));
2251                 return True;
2252         }
2253
2254         /* Check if the autolock needs to be cleared */
2255         if (!pdb_update_autolock_flag(sampass, &autolock_updated))
2256                 return False;
2257
2258         /* Check if the badpw count needs to be reset */
2259         if (!pdb_update_bad_password_count(sampass, &badpw_updated))
2260                 return False;
2261
2262         /*
2263           Ok, now we can assume that any resetting that needs to be 
2264           done has been done, and just get on with incrementing
2265           and autolocking if necessary
2266         */
2267
2268         pdb_set_bad_password_count(sampass, 
2269                                    pdb_get_bad_password_count(sampass)+1,
2270                                    PDB_CHANGED);
2271         pdb_set_bad_password_time(sampass, time(NULL), PDB_CHANGED);
2272
2273
2274         if (pdb_get_bad_password_count(sampass) < account_policy_lockout) 
2275                 return True;
2276
2277         if (!pdb_set_acct_ctrl(sampass,
2278                                pdb_get_acct_ctrl(sampass) | ACB_AUTOLOCK,
2279                                PDB_CHANGED)) {
2280                 DEBUG(1, ("pdb_increment_bad_password_count:failed to set 'autolock' flag. \n")); 
2281                 return False;
2282         }
2283
2284         return True;
2285 }
2286
2287 bool is_dc_trusted_domain_situation(const char *domain_name)
2288 {
2289         return IS_DC && !strequal(domain_name, lp_workgroup());
2290 }
2291
2292 /*******************************************************************
2293  Wrapper around retrieving the clear text trust account password.
2294  appropriate account name is stored in account_name.
2295  Caller must free password, but not account_name.
2296 *******************************************************************/
2297
2298 bool get_trust_pw_clear(const char *domain, char **ret_pwd,
2299                         const char **account_name,
2300                         enum netr_SchannelType *channel)
2301 {
2302         char *pwd;
2303         time_t last_set_time;
2304
2305         /* if we are a DC and this is not our domain, then lookup an account
2306          * for the domain trust */
2307
2308         if (is_dc_trusted_domain_situation(domain)) {
2309                 if (!lp_allow_trusted_domains()) {
2310                         return false;
2311                 }
2312
2313                 if (!pdb_get_trusteddom_pw(domain, ret_pwd, NULL,
2314                                            &last_set_time))
2315                 {
2316                         DEBUG(0, ("get_trust_pw: could not fetch trust "
2317                                 "account password for trusted domain %s\n",
2318                                 domain));
2319                         return false;
2320                 }
2321
2322                 if (channel != NULL) {
2323                         *channel = SEC_CHAN_DOMAIN;
2324                 }
2325
2326                 if (account_name != NULL) {
2327                         *account_name = lp_workgroup();
2328                 }
2329
2330                 return true;
2331         }
2332
2333         /*
2334          * Since we can only be member of one single domain, we are now
2335          * in a member situation:
2336          *
2337          *  -  Either we are a DC (selfjoined) and the domain is our
2338          *     own domain.
2339          *  -  Or we are on a member and the domain is our own or some
2340          *     other (potentially trusted) domain.
2341          *
2342          * In both cases, we can only get the machine account password
2343          * for our own domain to connect to our own dc. (For a member,
2344          * request to trusted domains are performed through our dc.)
2345          *
2346          * So we simply use our own domain name to retrieve the
2347          * machine account passowrd and ignore the request domain here.
2348          */
2349
2350         pwd = secrets_fetch_machine_password(lp_workgroup(), &last_set_time, channel);
2351
2352         if (pwd != NULL) {
2353                 *ret_pwd = pwd;
2354                 if (account_name != NULL) {
2355                         *account_name = global_myname();
2356                 }
2357
2358                 return true;
2359         }
2360
2361         DEBUG(5, ("get_trust_pw_clear: could not fetch clear text trust "
2362                   "account password for domain %s\n", domain));
2363         return false;
2364 }
2365
2366 /*******************************************************************
2367  Wrapper around retrieving the trust account password.
2368  appropriate account name is stored in account_name.
2369 *******************************************************************/
2370
2371 bool get_trust_pw_hash(const char *domain, uint8_t ret_pwd[16],
2372                        const char **account_name,
2373                        enum netr_SchannelType *channel)
2374 {
2375         char *pwd = NULL;
2376         time_t last_set_time;
2377
2378         if (get_trust_pw_clear(domain, &pwd, account_name, channel)) {
2379                 E_md4hash(pwd, ret_pwd);
2380                 SAFE_FREE(pwd);
2381                 return true;
2382         } else if (is_dc_trusted_domain_situation(domain)) {
2383                 return false;
2384         }
2385
2386         /* as a fallback, try to get the hashed pwd directly from the tdb... */
2387
2388         if (secrets_fetch_trust_account_password_legacy(domain, ret_pwd,
2389                                                         &last_set_time,
2390                                                         channel))
2391         {
2392                 if (account_name != NULL) {
2393                         *account_name = global_myname();
2394                 }
2395
2396                 return true;
2397         }
2398
2399         DEBUG(5, ("get_trust_pw_hash: could not fetch trust account "
2400                 "password for domain %s\n", domain));
2401         return False;
2402 }