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