r14457: Add a few more special cases for RID 513 in the samr code.
[kai/samba.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 2 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, write to the Free Software
23    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 */
25
26 #include "includes.h"
27
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_PASSDB
30
31 /******************************************************************
32  get the default domain/netbios name to be used when 
33  testing authentication.  For example, if you connect
34  to a Windows member server using a bogus domain name, the
35  Windows box will map the BOGUS\user to DOMAIN\user.  A 
36  standalone box will map to WKS\user.
37 ******************************************************************/
38
39 const char *my_sam_name(void)
40 {
41         /* standalone servers can only use the local netbios name */
42         if ( lp_server_role() == ROLE_STANDALONE )
43                 return global_myname();
44
45         /* Windows domain members default to the DOMAIN
46            name when not specified */
47         return lp_workgroup();
48 }
49
50 /**********************************************************************
51 ***********************************************************************/
52
53 static int samu_destroy(void *p) 
54 {
55         struct samu *user = p;
56
57         data_blob_clear_free( &user->lm_pw );
58         data_blob_clear_free( &user->nt_pw );
59
60         if ( user->plaintext_pw )
61                 memset( user->plaintext_pw, 0x0, strlen(user->plaintext_pw) );
62
63         return 0;
64 }
65
66 /**********************************************************************
67  generate a new struct samuser
68 ***********************************************************************/
69
70 struct samu* samu_new( TALLOC_CTX *ctx )
71 {
72         struct samu *user;
73         
74         if ( !(user = TALLOC_ZERO_P( ctx, struct samu )) ) {
75                 DEBUG(0,("samuser_new: Talloc failed!\n"));
76                 return NULL;
77         }
78         
79         talloc_set_destructor( user, samu_destroy );
80         
81         /* no initial methods */
82         
83         user->methods = NULL;
84
85         /* Don't change these timestamp settings without a good reason.
86            They are important for NT member server compatibility. */
87
88         user->logon_time            = (time_t)0;
89         user->pass_last_set_time    = (time_t)0;
90         user->pass_can_change_time  = (time_t)0;
91         user->logoff_time           = get_time_t_max();
92         user->kickoff_time          = get_time_t_max();
93         user->pass_must_change_time = get_time_t_max();
94         user->fields_present        = 0x00ffffff;
95         user->logon_divs = 168;         /* hours per week */
96         user->hours_len = 21;           /* 21 times 8 bits = 168 */
97         memset(user->hours, 0xff, user->hours_len); /* available at all hours */
98         user->bad_password_count = 0;
99         user->logon_count = 0;
100         user->unknown_6 = 0x000004ec; /* don't know */
101
102         /* Some parts of samba strlen their pdb_get...() returns, 
103            so this keeps the interface unchanged for now. */
104            
105         user->username = "";
106         user->domain = "";
107         user->nt_username = "";
108         user->full_name = "";
109         user->home_dir = "";
110         user->logon_script = "";
111         user->profile_path = "";
112         user->acct_desc = "";
113         user->workstations = "";
114         user->unknown_str = "";
115         user->munged_dial = "";
116
117         user->plaintext_pw = NULL;
118
119         /* Unless we know otherwise have a Account Control Bit
120            value of 'normal user'.  This helps User Manager, which
121            asks for a filtered list of users. */
122
123         user->acct_ctrl = ACB_NORMAL;
124         
125         
126         return user;
127 }
128
129 /*********************************************************************
130  Initialize a struct samu from a struct passwd including the user 
131  and group SIDs.  The *user structure is filled out with the Unix
132  attributes and a user SID.
133 *********************************************************************/
134
135 static NTSTATUS samu_set_unix_internal(struct samu *user, const struct passwd *pwd, BOOL create)
136 {
137         const char *guest_account = lp_guestaccount();
138         const char *domain = global_myname();
139         uint32 urid;
140
141         if ( !pwd ) {
142                 return NT_STATUS_NO_SUCH_USER;
143         }
144
145         /* Basic properties based upon the Unix account information */
146         
147         pdb_set_username(user, pwd->pw_name, PDB_SET);
148         pdb_set_fullname(user, pwd->pw_gecos, PDB_SET);
149         pdb_set_domain (user, get_global_sam_name(), PDB_DEFAULT);
150         
151         /* save the password structure for later use */
152         
153         user->unix_pw = tcopy_passwd( user, pwd );
154
155         /* Special case for the guest account which must have a RID of 501 */
156         
157         if ( strequal( pwd->pw_name, guest_account ) ) {
158                 if ( !pdb_set_user_sid_from_rid(user, DOMAIN_USER_RID_GUEST, PDB_DEFAULT)) {
159                         return NT_STATUS_NO_SUCH_USER;
160                 }
161                 return NT_STATUS_OK;
162         }
163         
164         /* Non-guest accounts...Check for a workstation or user account */
165
166         if (pwd->pw_name[strlen(pwd->pw_name)-1] == '$') {
167                 /* workstation */
168                 
169                 if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_DEFAULT)) {
170                         DEBUG(1, ("Failed to set 'workstation account' flags for user %s.\n", 
171                                 pwd->pw_name));
172                         return NT_STATUS_INVALID_COMPUTER_NAME;
173                 }       
174         } 
175         else {
176                 /* user */
177                 
178                 if (!pdb_set_acct_ctrl(user, ACB_NORMAL, PDB_DEFAULT)) {
179                         DEBUG(1, ("Failed to set 'normal account' flags for user %s.\n", 
180                                 pwd->pw_name));
181                         return NT_STATUS_INVALID_ACCOUNT_NAME;
182                 }
183                 
184                 /* set some basic attributes */
185         
186                 pdb_set_profile_path(user, talloc_sub_specified(user, 
187                         lp_logon_path(), pwd->pw_name, domain, pwd->pw_uid, pwd->pw_gid), 
188                         PDB_DEFAULT);           
189                 pdb_set_homedir(user, talloc_sub_specified(user, 
190                         lp_logon_home(), pwd->pw_name, domain, pwd->pw_uid, pwd->pw_gid),
191                         PDB_DEFAULT);
192                 pdb_set_dir_drive(user, talloc_sub_specified(user, 
193                         lp_logon_drive(), pwd->pw_name, domain, pwd->pw_uid, pwd->pw_gid),
194                         PDB_DEFAULT);
195                 pdb_set_logon_script(user, talloc_sub_specified(user, 
196                         lp_logon_script(), pwd->pw_name, domain, pwd->pw_uid, pwd->pw_gid), 
197                         PDB_DEFAULT);
198         }
199         
200         /* Now deal with the user SID.  If we have a backend that can generate 
201            RIDs, then do so.  But sometimes the caller just wanted a structure 
202            initialized and will fill in these fields later (such as from a 
203            NET_USER_INFO_3 structure) */
204
205         if ( create && !pdb_rid_algorithm() ) {
206                 uint32 user_rid;
207                 DOM_SID user_sid;
208                 
209                 if ( !pdb_new_rid( &user_rid ) ) {
210                         DEBUG(3, ("Could not allocate a new RID\n"));
211                         return NT_STATUS_ACCESS_DENIED;
212                 }
213
214                 sid_copy( &user_sid, get_global_sam_sid() );
215                 sid_append_rid( &user_sid, user_rid );
216
217                 if ( !pdb_set_user_sid(user, &user_sid, PDB_SET) ) {
218                         DEBUG(3, ("pdb_set_user_sid failed\n"));
219                         return NT_STATUS_INTERNAL_ERROR;
220                 }
221                 
222                 return NT_STATUS_OK;
223         }
224
225         /* generate a SID for the user with the RID algorithm */
226         
227         urid = algorithmic_pdb_uid_to_user_rid( user->unix_pw->pw_uid );
228                 
229         if ( !pdb_set_user_sid_from_rid( user, urid, PDB_SET) ) {
230                 return NT_STATUS_INTERNAL_ERROR;
231         }
232         
233         return NT_STATUS_OK;
234 }
235
236 /********************************************************************
237  Set the Unix user attributes
238 ********************************************************************/
239
240 NTSTATUS samu_set_unix(struct samu *user, const struct passwd *pwd)
241 {
242         return samu_set_unix_internal( user, pwd, False );
243 }
244
245 NTSTATUS samu_alloc_rid_unix(struct samu *user, const struct passwd *pwd)
246 {
247         return samu_set_unix_internal( user, pwd, True );
248 }
249
250 /**********************************************************
251  Encode the account control bits into a string.
252  length = length of string to encode into (including terminating
253  null). length *MUST BE MORE THAN 2* !
254  **********************************************************/
255
256 char *pdb_encode_acct_ctrl(uint32 acct_ctrl, size_t length)
257 {
258         static fstring acct_str;
259
260         size_t i = 0;
261
262         SMB_ASSERT(length <= sizeof(acct_str));
263
264         acct_str[i++] = '[';
265
266         if (acct_ctrl & ACB_PWNOTREQ ) acct_str[i++] = 'N';
267         if (acct_ctrl & ACB_DISABLED ) acct_str[i++] = 'D';
268         if (acct_ctrl & ACB_HOMDIRREQ) acct_str[i++] = 'H';
269         if (acct_ctrl & ACB_TEMPDUP  ) acct_str[i++] = 'T'; 
270         if (acct_ctrl & ACB_NORMAL   ) acct_str[i++] = 'U';
271         if (acct_ctrl & ACB_MNS      ) acct_str[i++] = 'M';
272         if (acct_ctrl & ACB_WSTRUST  ) acct_str[i++] = 'W';
273         if (acct_ctrl & ACB_SVRTRUST ) acct_str[i++] = 'S';
274         if (acct_ctrl & ACB_AUTOLOCK ) acct_str[i++] = 'L';
275         if (acct_ctrl & ACB_PWNOEXP  ) acct_str[i++] = 'X';
276         if (acct_ctrl & ACB_DOMTRUST ) acct_str[i++] = 'I';
277
278         for ( ; i < length - 2 ; i++ )
279                 acct_str[i] = ' ';
280
281         i = length - 2;
282         acct_str[i++] = ']';
283         acct_str[i++] = '\0';
284
285         return acct_str;
286 }     
287
288 /**********************************************************
289  Decode the account control bits from a string.
290  **********************************************************/
291
292 uint32 pdb_decode_acct_ctrl(const char *p)
293 {
294         uint32 acct_ctrl = 0;
295         BOOL finished = False;
296
297         /*
298          * Check if the account type bits have been encoded after the
299          * NT password (in the form [NDHTUWSLXI]).
300          */
301
302         if (*p != '[')
303                 return 0;
304
305         for (p++; *p && !finished; p++) {
306                 switch (*p) {
307                         case 'N': { acct_ctrl |= ACB_PWNOTREQ ; break; /* 'N'o password. */ }
308                         case 'D': { acct_ctrl |= ACB_DISABLED ; break; /* 'D'isabled. */ }
309                         case 'H': { acct_ctrl |= ACB_HOMDIRREQ; break; /* 'H'omedir required. */ }
310                         case 'T': { acct_ctrl |= ACB_TEMPDUP  ; break; /* 'T'emp account. */ } 
311                         case 'U': { acct_ctrl |= ACB_NORMAL   ; break; /* 'U'ser account (normal). */ } 
312                         case 'M': { acct_ctrl |= ACB_MNS      ; break; /* 'M'NS logon user account. What is this ? */ } 
313                         case 'W': { acct_ctrl |= ACB_WSTRUST  ; break; /* 'W'orkstation account. */ } 
314                         case 'S': { acct_ctrl |= ACB_SVRTRUST ; break; /* 'S'erver account. */ } 
315                         case 'L': { acct_ctrl |= ACB_AUTOLOCK ; break; /* 'L'ocked account. */ } 
316                         case 'X': { acct_ctrl |= ACB_PWNOEXP  ; break; /* No 'X'piry on password */ } 
317                         case 'I': { acct_ctrl |= ACB_DOMTRUST ; break; /* 'I'nterdomain trust account. */ }
318             case ' ': { break; }
319                         case ':':
320                         case '\n':
321                         case '\0': 
322                         case ']':
323                         default:  { finished = True; }
324                 }
325         }
326
327         return acct_ctrl;
328 }
329
330 /*************************************************************
331  Routine to set 32 hex password characters from a 16 byte array.
332 **************************************************************/
333
334 void pdb_sethexpwd(char *p, const unsigned char *pwd, uint32 acct_ctrl)
335 {
336         if (pwd != NULL) {
337                 int i;
338                 for (i = 0; i < 16; i++)
339                         slprintf(&p[i*2], 3, "%02X", pwd[i]);
340         } else {
341                 if (acct_ctrl & ACB_PWNOTREQ)
342                         safe_strcpy(p, "NO PASSWORDXXXXXXXXXXXXXXXXXXXXX", 33);
343                 else
344                         safe_strcpy(p, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 33);
345         }
346 }
347
348 /*************************************************************
349  Routine to get the 32 hex characters and turn them
350  into a 16 byte array.
351 **************************************************************/
352
353 BOOL pdb_gethexpwd(const char *p, unsigned char *pwd)
354 {
355         int i;
356         unsigned char   lonybble, hinybble;
357         const char      *hexchars = "0123456789ABCDEF";
358         char           *p1, *p2;
359         
360         if (!p)
361                 return (False);
362         
363         for (i = 0; i < 32; i += 2) {
364                 hinybble = toupper_ascii(p[i]);
365                 lonybble = toupper_ascii(p[i + 1]);
366
367                 p1 = strchr(hexchars, hinybble);
368                 p2 = strchr(hexchars, lonybble);
369
370                 if (!p1 || !p2)
371                         return (False);
372
373                 hinybble = PTR_DIFF(p1, hexchars);
374                 lonybble = PTR_DIFF(p2, hexchars);
375
376                 pwd[i / 2] = (hinybble << 4) | lonybble;
377         }
378         return (True);
379 }
380
381 /*************************************************************
382  Routine to set 42 hex hours characters from a 21 byte array.
383 **************************************************************/
384
385 void pdb_sethexhours(char *p, const unsigned char *hours)
386 {
387         if (hours != NULL) {
388                 int i;
389                 for (i = 0; i < 21; i++) {
390                         slprintf(&p[i*2], 3, "%02X", hours[i]);
391                 }
392         } else {
393                 safe_strcpy(p, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 43);
394         }
395 }
396
397 /*************************************************************
398  Routine to get the 42 hex characters and turn them
399  into a 21 byte array.
400 **************************************************************/
401
402 BOOL pdb_gethexhours(const char *p, unsigned char *hours)
403 {
404         int i;
405         unsigned char   lonybble, hinybble;
406         const char      *hexchars = "0123456789ABCDEF";
407         char           *p1, *p2;
408
409         if (!p) {
410                 return (False);
411         }
412
413         for (i = 0; i < 42; i += 2) {
414                 hinybble = toupper_ascii(p[i]);
415                 lonybble = toupper_ascii(p[i + 1]);
416
417                 p1 = strchr(hexchars, hinybble);
418                 p2 = strchr(hexchars, lonybble);
419
420                 if (!p1 || !p2) {
421                         return (False);
422                 }
423
424                 hinybble = PTR_DIFF(p1, hexchars);
425                 lonybble = PTR_DIFF(p2, hexchars);
426
427                 hours[i / 2] = (hinybble << 4) | lonybble;
428         }
429         return (True);
430 }
431
432 /********************************************************************
433 ********************************************************************/
434
435 int algorithmic_rid_base(void)
436 {
437         static int rid_offset = 0;
438
439         if (rid_offset != 0)
440                 return rid_offset;
441
442         rid_offset = lp_algorithmic_rid_base();
443
444         if (rid_offset < BASE_RID) {  
445                 /* Try to prevent admin foot-shooting, we can't put algorithmic
446                    rids below 1000, that's the 'well known RIDs' on NT */
447                 DEBUG(0, ("'algorithmic rid base' must be equal to or above %ld\n", BASE_RID));
448                 rid_offset = BASE_RID;
449         }
450         if (rid_offset & 1) {
451                 DEBUG(0, ("algorithmic rid base must be even\n"));
452                 rid_offset += 1;
453         }
454         return rid_offset;
455 }
456
457 /*******************************************************************
458  Converts NT user RID to a UNIX uid.
459  ********************************************************************/
460
461 uid_t algorithmic_pdb_user_rid_to_uid(uint32 user_rid)
462 {
463         int rid_offset = algorithmic_rid_base();
464         return (uid_t)(((user_rid & (~USER_RID_TYPE)) - rid_offset)/RID_MULTIPLIER);
465 }
466
467 uid_t max_algorithmic_uid(void)
468 {
469         return algorithmic_pdb_user_rid_to_uid(0xfffffffe);
470 }
471
472 /*******************************************************************
473  converts UNIX uid to an NT User RID.
474  ********************************************************************/
475
476 uint32 algorithmic_pdb_uid_to_user_rid(uid_t uid)
477 {
478         int rid_offset = algorithmic_rid_base();
479         return (((((uint32)uid)*RID_MULTIPLIER) + rid_offset) | USER_RID_TYPE);
480 }
481
482 /*******************************************************************
483  Converts NT group RID to a UNIX gid.
484  ********************************************************************/
485
486 gid_t pdb_group_rid_to_gid(uint32 group_rid)
487 {
488         int rid_offset = algorithmic_rid_base();
489         return (gid_t)(((group_rid & (~GROUP_RID_TYPE))- rid_offset)/RID_MULTIPLIER);
490 }
491
492 gid_t max_algorithmic_gid(void)
493 {
494         return pdb_group_rid_to_gid(0xffffffff);
495 }
496
497 /*******************************************************************
498  converts NT Group RID to a UNIX uid.
499  
500  warning: you must not call that function only
501  you must do a call to the group mapping first.
502  there is not anymore a direct link between the gid and the rid.
503  ********************************************************************/
504
505 uint32 pdb_gid_to_group_rid(gid_t gid)
506 {
507         int rid_offset = algorithmic_rid_base();
508         return (((((uint32)gid)*RID_MULTIPLIER) + rid_offset) | GROUP_RID_TYPE);
509 }
510
511 /*******************************************************************
512  Decides if a RID is a well known RID.
513  ********************************************************************/
514
515 static BOOL rid_is_well_known(uint32 rid)
516 {
517         /* Not using rid_offset here, because this is the actual
518            NT fixed value (1000) */
519
520         return (rid < BASE_RID);
521 }
522
523 /*******************************************************************
524  Decides if a RID is a user or group RID.
525  ********************************************************************/
526
527 BOOL algorithmic_pdb_rid_is_user(uint32 rid)
528 {
529         if ( rid_is_well_known(rid) ) {
530                 /*
531                  * The only well known user RIDs are DOMAIN_USER_RID_ADMIN
532                  * and DOMAIN_USER_RID_GUEST.
533                  */
534                 if(rid == DOMAIN_USER_RID_ADMIN || rid == DOMAIN_USER_RID_GUEST)
535                         return True;
536         } else if((rid & RID_TYPE_MASK) == USER_RID_TYPE) {
537                 return True;
538         }
539         return False;
540 }
541
542 /*******************************************************************
543  Convert a name into a SID. Used in the lookup name rpc.
544  ********************************************************************/
545
546 BOOL lookup_global_sam_name(const char *user, int flags, uint32_t *rid,
547                             enum SID_NAME_USE *type)
548 {
549         GROUP_MAP map;
550         BOOL ret;
551         
552         /* Windows treats "MACHINE\None" as a special name for 
553            rid 513 on non-DCs.  You cannot create a user or group
554            name "None" on Windows.  You will get an error that 
555            the group already exists. */
556            
557         if ( strequal( user, "None" ) ) {
558                 *rid = DOMAIN_GROUP_RID_USERS;
559                 *type = SID_NAME_DOM_GRP;
560                 
561                 return True;
562         }
563
564         /* LOOKUP_NAME_GROUP is a hack to allow valid users = @foo to work
565          * correctly in the case where foo also exists as a user. If the flag
566          * is set, don't look for users at all. */
567
568         if ((flags & LOOKUP_NAME_GROUP) == 0) {
569                 struct samu *sam_account = NULL;
570                 DOM_SID user_sid;
571
572                 if ( !(sam_account = samu_new( NULL )) ) {
573                         return False;
574                 }
575         
576                 become_root();
577                 ret =  pdb_getsampwnam(sam_account, user);
578                 unbecome_root();
579
580                 if (ret) {
581                         sid_copy(&user_sid, pdb_get_user_sid(sam_account));
582                 }
583                 
584                 TALLOC_FREE(sam_account);
585
586                 if (ret) {
587                         if (!sid_check_is_in_our_domain(&user_sid)) {
588                                 DEBUG(0, ("User %s with invalid SID %s in passdb\n",
589                                           user, sid_string_static(&user_sid)));
590                                 return False;
591                         }
592
593                         sid_peek_rid(&user_sid, rid);
594                         *type = SID_NAME_USER;
595                         return True;
596                 }
597         }
598
599         /*
600          * Maybe it is a group ?
601          */
602
603         become_root();
604         ret = pdb_getgrnam(&map, user);
605         unbecome_root();
606
607         if (!ret) {
608                 return False;
609         }
610
611         /* BUILTIN groups are looked up elsewhere */
612         if (!sid_check_is_in_our_domain(&map.sid)) {
613                 DEBUG(10, ("Found group %s (%s) not in our domain -- "
614                            "ignoring.", user,
615                            sid_string_static(&map.sid)));
616                 return False;
617         }
618
619         /* yes it's a mapped group */
620         sid_peek_rid(&map.sid, rid);
621         *type = map.sid_name_use;
622         return True;
623 }
624
625 /*************************************************************
626  Change a password entry in the local smbpasswd file.
627  *************************************************************/
628
629 NTSTATUS local_password_change(const char *user_name, int local_flags,
630                            const char *new_passwd, 
631                            char *err_str, size_t err_str_len,
632                            char *msg_str, size_t msg_str_len)
633 {
634         struct samu     *sam_pass=NULL;
635         uint32 other_acb;
636         NTSTATUS result;
637
638         *err_str = '\0';
639         *msg_str = '\0';
640
641         /* Get the smb passwd entry for this user */
642
643         if ( !(sam_pass = samu_new( NULL )) ) {
644                 return NT_STATUS_NO_MEMORY;
645         }
646
647         become_root();
648         if(!pdb_getsampwnam(sam_pass, user_name)) {
649                 unbecome_root();
650                 TALLOC_FREE(sam_pass);
651                 
652                 if ((local_flags & LOCAL_ADD_USER) || (local_flags & LOCAL_DELETE_USER)) {
653                         int tmp_debug = DEBUGLEVEL;
654                         struct passwd *pwd;
655
656                         /* Might not exist in /etc/passwd. */
657
658                         if (tmp_debug < 1) {
659                                 DEBUGLEVEL = 1;
660                         }
661
662                         if ( !(pwd = getpwnam_alloc( NULL, user_name)) ) {
663                                 return NT_STATUS_NO_SUCH_USER;
664                         }
665
666                         /* create the struct samu and initialize the basic Unix properties */
667
668                         if ( !(sam_pass = samu_new( NULL )) ) {
669                                 return NT_STATUS_NO_MEMORY;
670                         }
671
672                         result = samu_set_unix( sam_pass, pwd );
673
674                         DEBUGLEVEL = tmp_debug;
675
676                         TALLOC_FREE( pwd );
677
678                         if (NT_STATUS_EQUAL(result, NT_STATUS_INVALID_PRIMARY_GROUP)) {
679                                 return result;
680                         }
681
682                         if (!NT_STATUS_IS_OK(result)) {
683                                 slprintf(err_str, err_str_len-1, "Failed to " "initialize account for user %s: %s\n",
684                                         user_name, nt_errstr(result));
685                                 return result;
686                         }
687                 } else {
688                         slprintf(err_str, err_str_len-1,"Failed to find entry for user %s.\n", user_name);
689                         return NT_STATUS_NO_SUCH_USER;
690                 }
691         } else {
692                 unbecome_root();
693                 /* the entry already existed */
694                 local_flags &= ~LOCAL_ADD_USER;
695         }
696
697         /* the 'other' acb bits not being changed here */
698         other_acb =  (pdb_get_acct_ctrl(sam_pass) & (!(ACB_WSTRUST|ACB_DOMTRUST|ACB_SVRTRUST|ACB_NORMAL)));
699         if (local_flags & LOCAL_TRUST_ACCOUNT) {
700                 if (!pdb_set_acct_ctrl(sam_pass, ACB_WSTRUST | other_acb, PDB_CHANGED) ) {
701                         slprintf(err_str, err_str_len - 1, "Failed to set 'trusted workstation account' flags for user %s.\n", user_name);
702                         TALLOC_FREE(sam_pass);
703                         return NT_STATUS_UNSUCCESSFUL;
704                 }
705         } else if (local_flags & LOCAL_INTERDOM_ACCOUNT) {
706                 if (!pdb_set_acct_ctrl(sam_pass, ACB_DOMTRUST | other_acb, PDB_CHANGED)) {
707                         slprintf(err_str, err_str_len - 1, "Failed to set 'domain trust account' flags for user %s.\n", user_name);
708                         TALLOC_FREE(sam_pass);
709                         return NT_STATUS_UNSUCCESSFUL;
710                 }
711         } else {
712                 if (!pdb_set_acct_ctrl(sam_pass, ACB_NORMAL | other_acb, PDB_CHANGED)) {
713                         slprintf(err_str, err_str_len - 1, "Failed to set 'normal account' flags for user %s.\n", user_name);
714                         TALLOC_FREE(sam_pass);
715                         return NT_STATUS_UNSUCCESSFUL;
716                 }
717         }
718
719         /*
720          * We are root - just write the new password
721          * and the valid last change time.
722          */
723
724         if (local_flags & LOCAL_DISABLE_USER) {
725                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_DISABLED, PDB_CHANGED)) {
726                         slprintf(err_str, err_str_len-1, "Failed to set 'disabled' flag for user %s.\n", user_name);
727                         TALLOC_FREE(sam_pass);
728                         return NT_STATUS_UNSUCCESSFUL;
729                 }
730         } else if (local_flags & LOCAL_ENABLE_USER) {
731                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
732                         slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
733                         TALLOC_FREE(sam_pass);
734                         return NT_STATUS_UNSUCCESSFUL;
735                 }
736         }
737         
738         if (local_flags & LOCAL_SET_NO_PASSWORD) {
739                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_PWNOTREQ, PDB_CHANGED)) {
740                         slprintf(err_str, err_str_len-1, "Failed to set 'no password required' flag for user %s.\n", user_name);
741                         TALLOC_FREE(sam_pass);
742                         return NT_STATUS_UNSUCCESSFUL;
743                 }
744         } else if (local_flags & LOCAL_SET_PASSWORD) {
745                 /*
746                  * If we're dealing with setting a completely empty user account
747                  * ie. One with a password of 'XXXX', but not set disabled (like
748                  * an account created from scratch) then if the old password was
749                  * 'XX's then getsmbpwent will have set the ACB_DISABLED flag.
750                  * We remove that as we're giving this user their first password
751                  * and the decision hasn't really been made to disable them (ie.
752                  * don't create them disabled). JRA.
753                  */
754                 if ((pdb_get_lanman_passwd(sam_pass)==NULL) && (pdb_get_acct_ctrl(sam_pass)&ACB_DISABLED)) {
755                         if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
756                                 slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
757                                 TALLOC_FREE(sam_pass);
758                                 return NT_STATUS_UNSUCCESSFUL;
759                         }
760                 }
761                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_PWNOTREQ), PDB_CHANGED)) {
762                         slprintf(err_str, err_str_len-1, "Failed to unset 'no password required' flag for user %s.\n", user_name);
763                         TALLOC_FREE(sam_pass);
764                         return NT_STATUS_UNSUCCESSFUL;
765                 }
766                 
767                 if (!pdb_set_plaintext_passwd (sam_pass, new_passwd)) {
768                         slprintf(err_str, err_str_len-1, "Failed to set password for user %s.\n", user_name);
769                         TALLOC_FREE(sam_pass);
770                         return NT_STATUS_UNSUCCESSFUL;
771                 }
772         }       
773
774         if (local_flags & LOCAL_ADD_USER) {
775                 if (NT_STATUS_IS_OK(pdb_add_sam_account(sam_pass))) {
776                         slprintf(msg_str, msg_str_len-1, "Added user %s.\n", user_name);
777                         TALLOC_FREE(sam_pass);
778                         return NT_STATUS_OK;
779                 } else {
780                         slprintf(err_str, err_str_len-1, "Failed to add entry for user %s.\n", user_name);
781                         TALLOC_FREE(sam_pass);
782                         return NT_STATUS_UNSUCCESSFUL;
783                 }
784         } else if (local_flags & LOCAL_DELETE_USER) {
785                 if (!NT_STATUS_IS_OK(pdb_delete_sam_account(sam_pass))) {
786                         slprintf(err_str,err_str_len-1, "Failed to delete entry for user %s.\n", user_name);
787                         TALLOC_FREE(sam_pass);
788                         return NT_STATUS_UNSUCCESSFUL;
789                 }
790                 slprintf(msg_str, msg_str_len-1, "Deleted user %s.\n", user_name);
791         } else {
792                 result = pdb_update_sam_account(sam_pass);
793                 if(!NT_STATUS_IS_OK(result)) {
794                         slprintf(err_str, err_str_len-1, "Failed to modify entry for user %s.\n", user_name);
795                         TALLOC_FREE(sam_pass);
796                         return result;
797                 }
798                 if(local_flags & LOCAL_DISABLE_USER)
799                         slprintf(msg_str, msg_str_len-1, "Disabled user %s.\n", user_name);
800                 else if (local_flags & LOCAL_ENABLE_USER)
801                         slprintf(msg_str, msg_str_len-1, "Enabled user %s.\n", user_name);
802                 else if (local_flags & LOCAL_SET_NO_PASSWORD)
803                         slprintf(msg_str, msg_str_len-1, "User %s password set to none.\n", user_name);
804         }
805
806         TALLOC_FREE(sam_pass);
807         return NT_STATUS_OK;
808 }
809
810 /**********************************************************************
811  Marshall/unmarshall struct samu structs.
812  *********************************************************************/
813
814 #define TDB_FORMAT_STRING_V3       "dddddddBBBBBBBBBBBBddBBBdwdBwwd"
815
816 /*********************************************************************
817 *********************************************************************/
818
819 BOOL init_sam_from_buffer_v3(struct samu *sampass, uint8 *buf, uint32 buflen)
820 {
821
822         /* times are stored as 32bit integer
823            take care on system with 64bit wide time_t
824            --SSS */
825         uint32  logon_time,
826                 logoff_time,
827                 kickoff_time,
828                 bad_password_time,
829                 pass_last_set_time,
830                 pass_can_change_time,
831                 pass_must_change_time;
832         char *username = NULL;
833         char *domain = NULL;
834         char *nt_username = NULL;
835         char *dir_drive = NULL;
836         char *unknown_str = NULL;
837         char *munged_dial = NULL;
838         char *fullname = NULL;
839         char *homedir = NULL;
840         char *logon_script = NULL;
841         char *profile_path = NULL;
842         char *acct_desc = NULL;
843         char *workstations = NULL;
844         uint32  username_len, domain_len, nt_username_len,
845                 dir_drive_len, unknown_str_len, munged_dial_len,
846                 fullname_len, homedir_len, logon_script_len,
847                 profile_path_len, acct_desc_len, workstations_len;
848                 
849         uint32  user_rid, group_rid, hours_len, unknown_6, acct_ctrl;
850         uint16  logon_divs;
851         uint16  bad_password_count, logon_count;
852         uint8   *hours = NULL;
853         uint8   *lm_pw_ptr = NULL, *nt_pw_ptr = NULL, *nt_pw_hist_ptr = NULL;
854         uint32          len = 0;
855         uint32          lm_pw_len, nt_pw_len, nt_pw_hist_len, hourslen;
856         uint32 pwHistLen = 0;
857         BOOL ret = True;
858         fstring tmpstring;
859         BOOL expand_explicit = lp_passdb_expand_explicit();
860         
861         if(sampass == NULL || buf == NULL) {
862                 DEBUG(0, ("init_sam_from_buffer_v3: NULL parameters found!\n"));
863                 return False;
864         }
865                                                                         
866 /* TDB_FORMAT_STRING_V3       "dddddddBBBBBBBBBBBBddBBBdwdBwwd" */
867
868         /* unpack the buffer into variables */
869         len = tdb_unpack ((char *)buf, buflen, TDB_FORMAT_STRING_V3,
870                 &logon_time,                                            /* d */
871                 &logoff_time,                                           /* d */
872                 &kickoff_time,                                          /* d */
873                 &bad_password_time,                                     /* d */
874                 &pass_last_set_time,                                    /* d */
875                 &pass_can_change_time,                                  /* d */
876                 &pass_must_change_time,                                 /* d */
877                 &username_len, &username,                               /* B */
878                 &domain_len, &domain,                                   /* B */
879                 &nt_username_len, &nt_username,                         /* B */
880                 &fullname_len, &fullname,                               /* B */
881                 &homedir_len, &homedir,                                 /* B */
882                 &dir_drive_len, &dir_drive,                             /* B */
883                 &logon_script_len, &logon_script,                       /* B */
884                 &profile_path_len, &profile_path,                       /* B */
885                 &acct_desc_len, &acct_desc,                             /* B */
886                 &workstations_len, &workstations,                       /* B */
887                 &unknown_str_len, &unknown_str,                         /* B */
888                 &munged_dial_len, &munged_dial,                         /* B */
889                 &user_rid,                                              /* d */
890                 &group_rid,                                             /* d */
891                 &lm_pw_len, &lm_pw_ptr,                                 /* B */
892                 &nt_pw_len, &nt_pw_ptr,                                 /* B */
893                 /* Change from V1 is addition of password history field. */
894                 &nt_pw_hist_len, &nt_pw_hist_ptr,                       /* B */
895                 /* Change from V2 is the uint32 acb_mask */
896                 &acct_ctrl,                                             /* d */
897                 /* Also "remove_me" field was removed. */
898                 &logon_divs,                                            /* w */
899                 &hours_len,                                             /* d */
900                 &hourslen, &hours,                                      /* B */
901                 &bad_password_count,                                    /* w */
902                 &logon_count,                                           /* w */
903                 &unknown_6);                                            /* d */
904                 
905         if (len == (uint32) -1)  {
906                 ret = False;
907                 goto done;
908         }
909
910         pdb_set_logon_time(sampass, logon_time, PDB_SET);
911         pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
912         pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
913         pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
914         pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
915         pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
916         pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
917
918         pdb_set_username(sampass, username, PDB_SET); 
919         pdb_set_domain(sampass, domain, PDB_SET);
920         pdb_set_nt_username(sampass, nt_username, PDB_SET);
921         pdb_set_fullname(sampass, fullname, PDB_SET);
922
923         if (homedir) {
924                 fstrcpy( tmpstring, homedir );
925                 if (expand_explicit) {
926                         standard_sub_basic( username, tmpstring,
927                                             sizeof(tmpstring) );
928                 }
929                 pdb_set_homedir(sampass, tmpstring, PDB_SET);
930         }
931         else {
932                 pdb_set_homedir(sampass, 
933                         talloc_sub_basic(sampass, username, lp_logon_home()),
934                         PDB_DEFAULT);
935         }
936
937         if (dir_drive)  
938                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
939         else
940                 pdb_set_dir_drive(sampass, lp_logon_drive(), PDB_DEFAULT );
941
942         if (logon_script) {
943                 fstrcpy( tmpstring, logon_script );
944                 if (expand_explicit) {
945                         standard_sub_basic( username, tmpstring,
946                                             sizeof(tmpstring) );
947                 }
948                 pdb_set_logon_script(sampass, tmpstring, PDB_SET);
949         }
950         else {
951                 pdb_set_logon_script(sampass, 
952                         talloc_sub_basic(sampass, username, lp_logon_script()),
953                         PDB_DEFAULT);
954         }
955         
956         if (profile_path) {     
957                 fstrcpy( tmpstring, profile_path );
958                 if (expand_explicit) {
959                         standard_sub_basic( username, tmpstring,
960                                             sizeof(tmpstring) );
961                 }
962                 pdb_set_profile_path(sampass, tmpstring, PDB_SET);
963         } 
964         else {
965                 pdb_set_profile_path(sampass, 
966                         talloc_sub_basic(sampass, username, lp_logon_path()),
967                         PDB_DEFAULT);
968         }
969
970         pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
971         pdb_set_workstations(sampass, workstations, PDB_SET);
972         pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
973
974         if (lm_pw_ptr && lm_pw_len == LM_HASH_LEN) {
975                 if (!pdb_set_lanman_passwd(sampass, lm_pw_ptr, PDB_SET)) {
976                         ret = False;
977                         goto done;
978                 }
979         }
980
981         if (nt_pw_ptr && nt_pw_len == NT_HASH_LEN) {
982                 if (!pdb_set_nt_passwd(sampass, nt_pw_ptr, PDB_SET)) {
983                         ret = False;
984                         goto done;
985                 }
986         }
987
988         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
989         if (pwHistLen) {
990                 uint8 *pw_hist = SMB_MALLOC(pwHistLen * PW_HISTORY_ENTRY_LEN);
991                 if (!pw_hist) {
992                         ret = False;
993                         goto done;
994                 }
995                 memset(pw_hist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
996                 if (nt_pw_hist_ptr && nt_pw_hist_len) {
997                         int i;
998                         SMB_ASSERT((nt_pw_hist_len % PW_HISTORY_ENTRY_LEN) == 0);
999                         nt_pw_hist_len /= PW_HISTORY_ENTRY_LEN;
1000                         for (i = 0; (i < pwHistLen) && (i < nt_pw_hist_len); i++) {
1001                                 memcpy(&pw_hist[i*PW_HISTORY_ENTRY_LEN],
1002                                         &nt_pw_hist_ptr[i*PW_HISTORY_ENTRY_LEN],
1003                                         PW_HISTORY_ENTRY_LEN);
1004                         }
1005                 }
1006                 if (!pdb_set_pw_history(sampass, pw_hist, pwHistLen, PDB_SET)) {
1007                         SAFE_FREE(pw_hist);
1008                         ret = False;
1009                         goto done;
1010                 }
1011                 SAFE_FREE(pw_hist);
1012         } else {
1013                 pdb_set_pw_history(sampass, NULL, 0, PDB_SET);
1014         }
1015
1016         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
1017         pdb_set_hours_len(sampass, hours_len, PDB_SET);
1018         pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
1019         pdb_set_logon_count(sampass, logon_count, PDB_SET);
1020         pdb_set_unknown_6(sampass, unknown_6, PDB_SET);
1021         /* Change from V2 is the uint32 acct_ctrl */
1022         pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
1023         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
1024         pdb_set_hours(sampass, hours, PDB_SET);
1025
1026 done:
1027
1028         SAFE_FREE(username);
1029         SAFE_FREE(domain);
1030         SAFE_FREE(nt_username);
1031         SAFE_FREE(fullname);
1032         SAFE_FREE(homedir);
1033         SAFE_FREE(dir_drive);
1034         SAFE_FREE(logon_script);
1035         SAFE_FREE(profile_path);
1036         SAFE_FREE(acct_desc);
1037         SAFE_FREE(workstations);
1038         SAFE_FREE(munged_dial);
1039         SAFE_FREE(unknown_str);
1040         SAFE_FREE(lm_pw_ptr);
1041         SAFE_FREE(nt_pw_ptr);
1042         SAFE_FREE(nt_pw_hist_ptr);
1043         SAFE_FREE(hours);
1044
1045         return ret;
1046 }
1047
1048 /*********************************************************************
1049 *********************************************************************/
1050
1051 uint32 init_buffer_from_sam_v3 (uint8 **buf, struct samu *sampass, BOOL size_only)
1052 {
1053         size_t len, buflen;
1054
1055         /* times are stored as 32bit integer
1056            take care on system with 64bit wide time_t
1057            --SSS */
1058         uint32  logon_time,
1059                 logoff_time,
1060                 kickoff_time,
1061                 bad_password_time,
1062                 pass_last_set_time,
1063                 pass_can_change_time,
1064                 pass_must_change_time;
1065
1066         uint32  user_rid, group_rid;
1067
1068         const char *username;
1069         const char *domain;
1070         const char *nt_username;
1071         const char *dir_drive;
1072         const char *unknown_str;
1073         const char *munged_dial;
1074         const char *fullname;
1075         const char *homedir;
1076         const char *logon_script;
1077         const char *profile_path;
1078         const char *acct_desc;
1079         const char *workstations;
1080         uint32  username_len, domain_len, nt_username_len,
1081                 dir_drive_len, unknown_str_len, munged_dial_len,
1082                 fullname_len, homedir_len, logon_script_len,
1083                 profile_path_len, acct_desc_len, workstations_len;
1084
1085         const uint8 *lm_pw;
1086         const uint8 *nt_pw;
1087         const uint8 *nt_pw_hist;
1088         uint32  lm_pw_len = 16;
1089         uint32  nt_pw_len = 16;
1090         uint32  nt_pw_hist_len;
1091         uint32 pwHistLen = 0;
1092
1093         /* do we have a valid struct samu pointer? */
1094         if (sampass == NULL) {
1095                 DEBUG(0, ("init_buffer_from_sam: struct samu is NULL!\n"));
1096                 return -1;
1097         }
1098         
1099         *buf = NULL;
1100         buflen = 0;
1101
1102         logon_time = (uint32)pdb_get_logon_time(sampass);
1103         logoff_time = (uint32)pdb_get_logoff_time(sampass);
1104         kickoff_time = (uint32)pdb_get_kickoff_time(sampass);
1105         bad_password_time = (uint32)pdb_get_bad_password_time(sampass);
1106         pass_can_change_time = (uint32)pdb_get_pass_can_change_time(sampass);
1107         pass_must_change_time = (uint32)pdb_get_pass_must_change_time(sampass);
1108         pass_last_set_time = (uint32)pdb_get_pass_last_set_time(sampass);
1109
1110         user_rid = pdb_get_user_rid(sampass);
1111         group_rid = pdb_get_group_rid(sampass);
1112
1113         username = pdb_get_username(sampass);
1114         if (username) {
1115                 username_len = strlen(username) +1;
1116         } else {
1117                 username_len = 0;
1118         }
1119
1120         domain = pdb_get_domain(sampass);
1121         if (domain) {
1122                 domain_len = strlen(domain) +1;
1123         } else {
1124                 domain_len = 0;
1125         }
1126
1127         nt_username = pdb_get_nt_username(sampass);
1128         if (nt_username) {
1129                 nt_username_len = strlen(nt_username) +1;
1130         } else {
1131                 nt_username_len = 0;
1132         }
1133
1134         fullname = pdb_get_fullname(sampass);
1135         if (fullname) {
1136                 fullname_len = strlen(fullname) +1;
1137         } else {
1138                 fullname_len = 0;
1139         }
1140
1141         /*
1142          * Only updates fields which have been set (not defaults from smb.conf)
1143          */
1144
1145         if (!IS_SAM_DEFAULT(sampass, PDB_DRIVE)) {
1146                 dir_drive = pdb_get_dir_drive(sampass);
1147         } else {
1148                 dir_drive = NULL;
1149         }
1150         if (dir_drive) {
1151                 dir_drive_len = strlen(dir_drive) +1;
1152         } else {
1153                 dir_drive_len = 0;
1154         }
1155
1156         if (!IS_SAM_DEFAULT(sampass, PDB_SMBHOME)) {
1157                 homedir = pdb_get_homedir(sampass);
1158         } else {
1159                 homedir = NULL;
1160         }
1161         if (homedir) {
1162                 homedir_len = strlen(homedir) +1;
1163         } else {
1164                 homedir_len = 0;
1165         }
1166
1167         if (!IS_SAM_DEFAULT(sampass, PDB_LOGONSCRIPT)) {
1168                 logon_script = pdb_get_logon_script(sampass);
1169         } else {
1170                 logon_script = NULL;
1171         }
1172         if (logon_script) {
1173                 logon_script_len = strlen(logon_script) +1;
1174         } else {
1175                 logon_script_len = 0;
1176         }
1177
1178         if (!IS_SAM_DEFAULT(sampass, PDB_PROFILE)) {
1179                 profile_path = pdb_get_profile_path(sampass);
1180         } else {
1181                 profile_path = NULL;
1182         }
1183         if (profile_path) {
1184                 profile_path_len = strlen(profile_path) +1;
1185         } else {
1186                 profile_path_len = 0;
1187         }
1188         
1189         lm_pw = pdb_get_lanman_passwd(sampass);
1190         if (!lm_pw) {
1191                 lm_pw_len = 0;
1192         }
1193         
1194         nt_pw = pdb_get_nt_passwd(sampass);
1195         if (!nt_pw) {
1196                 nt_pw_len = 0;
1197         }
1198
1199         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
1200         nt_pw_hist =  pdb_get_pw_history(sampass, &nt_pw_hist_len);
1201         if (pwHistLen && nt_pw_hist && nt_pw_hist_len) {
1202                 nt_pw_hist_len *= PW_HISTORY_ENTRY_LEN;
1203         } else {
1204                 nt_pw_hist_len = 0;
1205         }
1206
1207         acct_desc = pdb_get_acct_desc(sampass);
1208         if (acct_desc) {
1209                 acct_desc_len = strlen(acct_desc) +1;
1210         } else {
1211                 acct_desc_len = 0;
1212         }
1213
1214         workstations = pdb_get_workstations(sampass);
1215         if (workstations) {
1216                 workstations_len = strlen(workstations) +1;
1217         } else {
1218                 workstations_len = 0;
1219         }
1220
1221         unknown_str = NULL;
1222         unknown_str_len = 0;
1223
1224         munged_dial = pdb_get_munged_dial(sampass);
1225         if (munged_dial) {
1226                 munged_dial_len = strlen(munged_dial) +1;
1227         } else {
1228                 munged_dial_len = 0;    
1229         }
1230
1231 /* TDB_FORMAT_STRING_V3       "dddddddBBBBBBBBBBBBddBBBdwdBwwd" */
1232
1233         /* one time to get the size needed */
1234         len = tdb_pack(NULL, 0,  TDB_FORMAT_STRING_V3,
1235                 logon_time,                             /* d */
1236                 logoff_time,                            /* d */
1237                 kickoff_time,                           /* d */
1238                 bad_password_time,                      /* d */
1239                 pass_last_set_time,                     /* d */
1240                 pass_can_change_time,                   /* d */
1241                 pass_must_change_time,                  /* d */
1242                 username_len, username,                 /* B */
1243                 domain_len, domain,                     /* B */
1244                 nt_username_len, nt_username,           /* B */
1245                 fullname_len, fullname,                 /* B */
1246                 homedir_len, homedir,                   /* B */
1247                 dir_drive_len, dir_drive,               /* B */
1248                 logon_script_len, logon_script,         /* B */
1249                 profile_path_len, profile_path,         /* B */
1250                 acct_desc_len, acct_desc,               /* B */
1251                 workstations_len, workstations,         /* B */
1252                 unknown_str_len, unknown_str,           /* B */
1253                 munged_dial_len, munged_dial,           /* B */
1254                 user_rid,                               /* d */
1255                 group_rid,                              /* d */
1256                 lm_pw_len, lm_pw,                       /* B */
1257                 nt_pw_len, nt_pw,                       /* B */
1258                 nt_pw_hist_len, nt_pw_hist,             /* B */
1259                 pdb_get_acct_ctrl(sampass),             /* d */
1260                 pdb_get_logon_divs(sampass),            /* w */
1261                 pdb_get_hours_len(sampass),             /* d */
1262                 MAX_HOURS_LEN, pdb_get_hours(sampass),  /* B */
1263                 pdb_get_bad_password_count(sampass),    /* w */
1264                 pdb_get_logon_count(sampass),           /* w */
1265                 pdb_get_unknown_6(sampass));            /* d */
1266
1267         if (size_only) {
1268                 return buflen;
1269         }
1270
1271         /* malloc the space needed */
1272         if ( (*buf=(uint8*)SMB_MALLOC(len)) == NULL) {
1273                 DEBUG(0,("init_buffer_from_sam_v3: Unable to malloc() memory for buffer!\n"));
1274                 return (-1);
1275         }
1276         
1277         /* now for the real call to tdb_pack() */
1278         buflen = tdb_pack((char *)*buf, len,  TDB_FORMAT_STRING_V3,
1279                 logon_time,                             /* d */
1280                 logoff_time,                            /* d */
1281                 kickoff_time,                           /* d */
1282                 bad_password_time,                      /* d */
1283                 pass_last_set_time,                     /* d */
1284                 pass_can_change_time,                   /* d */
1285                 pass_must_change_time,                  /* d */
1286                 username_len, username,                 /* B */
1287                 domain_len, domain,                     /* B */
1288                 nt_username_len, nt_username,           /* B */
1289                 fullname_len, fullname,                 /* B */
1290                 homedir_len, homedir,                   /* B */
1291                 dir_drive_len, dir_drive,               /* B */
1292                 logon_script_len, logon_script,         /* B */
1293                 profile_path_len, profile_path,         /* B */
1294                 acct_desc_len, acct_desc,               /* B */
1295                 workstations_len, workstations,         /* B */
1296                 unknown_str_len, unknown_str,           /* B */
1297                 munged_dial_len, munged_dial,           /* B */
1298                 user_rid,                               /* d */
1299                 group_rid,                              /* d */
1300                 lm_pw_len, lm_pw,                       /* B */
1301                 nt_pw_len, nt_pw,                       /* B */
1302                 nt_pw_hist_len, nt_pw_hist,             /* B */
1303                 pdb_get_acct_ctrl(sampass),             /* d */
1304                 pdb_get_logon_divs(sampass),            /* w */
1305                 pdb_get_hours_len(sampass),             /* d */
1306                 MAX_HOURS_LEN, pdb_get_hours(sampass),  /* B */
1307                 pdb_get_bad_password_count(sampass),    /* w */
1308                 pdb_get_logon_count(sampass),           /* w */
1309                 pdb_get_unknown_6(sampass));            /* d */
1310         
1311         /* check to make sure we got it correct */
1312         if (buflen != len) {
1313                 DEBUG(0, ("init_buffer_from_sam_v3: somthing odd is going on here: bufflen (%lu) != len (%lu) in tdb_pack operations!\n", 
1314                           (unsigned long)buflen, (unsigned long)len));  
1315                 /* error */
1316                 SAFE_FREE (*buf);
1317                 return (-1);
1318         }
1319
1320         return (buflen);
1321 }
1322
1323
1324 /*********************************************************************
1325 *********************************************************************/
1326
1327 BOOL pdb_copy_sam_account(struct samu *dst, struct samu *src )
1328 {
1329         BOOL result;
1330         uint8 *buf;
1331         int len;
1332
1333         if ( !dst )
1334                 return False;
1335
1336         len = init_buffer_from_sam_v3(&buf, src, False);
1337
1338         if (len == -1)
1339                 return False;
1340
1341         result = init_sam_from_buffer_v3( dst, buf, len );
1342         dst->methods = src->methods;
1343         
1344         if ( src->unix_pw )
1345                 dst->unix_pw = tcopy_passwd( dst, src->unix_pw );
1346
1347         free(buf);
1348
1349         return result;
1350 }
1351
1352 /*********************************************************************
1353  Update the bad password count checking the AP_RESET_COUNT_TIME 
1354 *********************************************************************/
1355
1356 BOOL pdb_update_bad_password_count(struct samu *sampass, BOOL *updated)
1357 {
1358         time_t LastBadPassword;
1359         uint16 BadPasswordCount;
1360         uint32 resettime; 
1361
1362         if (!sampass) return False;
1363         
1364         BadPasswordCount = pdb_get_bad_password_count(sampass);
1365         if (!BadPasswordCount) {
1366                 DEBUG(9, ("No bad password attempts.\n"));
1367                 return True;
1368         }
1369
1370         if (!pdb_get_account_policy(AP_RESET_COUNT_TIME, &resettime)) {
1371                 DEBUG(0, ("pdb_update_bad_password_count: pdb_get_account_policy failed.\n"));
1372                 return False;
1373         }
1374
1375         /* First, check if there is a reset time to compare */
1376         if ((resettime == (uint32) -1) || (resettime == 0)) {
1377                 DEBUG(9, ("No reset time, can't reset bad pw count\n"));
1378                 return True;
1379         }
1380
1381         LastBadPassword = pdb_get_bad_password_time(sampass);
1382         DEBUG(7, ("LastBadPassword=%d, resettime=%d, current time=%d.\n", 
1383                    (uint32) LastBadPassword, resettime, (uint32)time(NULL)));
1384         if (time(NULL) > (LastBadPassword + (time_t)resettime*60)){
1385                 pdb_set_bad_password_count(sampass, 0, PDB_CHANGED);
1386                 pdb_set_bad_password_time(sampass, 0, PDB_CHANGED);
1387                 if (updated) {
1388                         *updated = True;
1389                 }
1390         }
1391
1392         return True;
1393 }
1394
1395 /*********************************************************************
1396  Update the ACB_AUTOLOCK flag checking the AP_LOCK_ACCOUNT_DURATION 
1397 *********************************************************************/
1398
1399 BOOL pdb_update_autolock_flag(struct samu *sampass, BOOL *updated)
1400 {
1401         uint32 duration;
1402         time_t LastBadPassword;
1403
1404         if (!sampass) return False;
1405  
1406         if (!(pdb_get_acct_ctrl(sampass) & ACB_AUTOLOCK)) {
1407                 DEBUG(9, ("pdb_update_autolock_flag: Account %s not autolocked, no check needed\n",
1408                         pdb_get_username(sampass)));
1409                 return True;
1410         }
1411
1412         if (!pdb_get_account_policy(AP_LOCK_ACCOUNT_DURATION, &duration)) {
1413                 DEBUG(0, ("pdb_update_autolock_flag: pdb_get_account_policy failed.\n"));
1414                 return False;
1415         }
1416
1417         /* First, check if there is a duration to compare */
1418         if ((duration == (uint32) -1)  || (duration == 0)) {
1419                 DEBUG(9, ("pdb_update_autolock_flag: No reset duration, can't reset autolock\n"));
1420                 return True;
1421         }
1422                       
1423         LastBadPassword = pdb_get_bad_password_time(sampass);
1424         DEBUG(7, ("pdb_update_autolock_flag: Account %s, LastBadPassword=%d, duration=%d, current time =%d.\n",
1425                   pdb_get_username(sampass), (uint32)LastBadPassword, duration*60, (uint32)time(NULL)));
1426
1427         if (LastBadPassword == (time_t)0) {
1428                 DEBUG(1,("pdb_update_autolock_flag: Account %s administratively locked out with no \
1429 bad password time. Leaving locked out.\n",
1430                         pdb_get_username(sampass) ));
1431                         return True;
1432         }
1433
1434         if ((time(NULL) > (LastBadPassword + (time_t) duration * 60))) {
1435                 pdb_set_acct_ctrl(sampass,
1436                                   pdb_get_acct_ctrl(sampass) & ~ACB_AUTOLOCK,
1437                                   PDB_CHANGED);
1438                 pdb_set_bad_password_count(sampass, 0, PDB_CHANGED);
1439                 pdb_set_bad_password_time(sampass, 0, PDB_CHANGED);
1440                 if (updated) {
1441                         *updated = True;
1442                 }
1443         }
1444         
1445         return True;
1446 }
1447
1448 /*********************************************************************
1449  Increment the bad_password_count 
1450 *********************************************************************/
1451
1452 BOOL pdb_increment_bad_password_count(struct samu *sampass)
1453 {
1454         uint32 account_policy_lockout;
1455         BOOL autolock_updated = False, badpw_updated = False;
1456         BOOL ret;
1457
1458         if (!sampass)
1459                 return False;
1460
1461         /* Retrieve the account lockout policy */
1462         become_root();
1463         ret = pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &account_policy_lockout);
1464         unbecome_root();
1465         if ( !ret ) {
1466                 DEBUG(0, ("pdb_increment_bad_password_count: pdb_get_account_policy failed.\n"));
1467                 return False;
1468         }
1469
1470         /* If there is no policy, we don't need to continue checking */
1471         if (!account_policy_lockout) {
1472                 DEBUG(9, ("No lockout policy, don't track bad passwords\n"));
1473                 return True;
1474         }
1475
1476         /* Check if the autolock needs to be cleared */
1477         if (!pdb_update_autolock_flag(sampass, &autolock_updated))
1478                 return False;
1479
1480         /* Check if the badpw count needs to be reset */
1481         if (!pdb_update_bad_password_count(sampass, &badpw_updated))
1482                 return False;
1483
1484         /*
1485           Ok, now we can assume that any resetting that needs to be 
1486           done has been done, and just get on with incrementing
1487           and autolocking if necessary
1488         */
1489
1490         pdb_set_bad_password_count(sampass, 
1491                                    pdb_get_bad_password_count(sampass)+1,
1492                                    PDB_CHANGED);
1493         pdb_set_bad_password_time(sampass, time(NULL), PDB_CHANGED);
1494
1495
1496         if (pdb_get_bad_password_count(sampass) < account_policy_lockout) 
1497                 return True;
1498
1499         if (!pdb_set_acct_ctrl(sampass,
1500                                pdb_get_acct_ctrl(sampass) | ACB_AUTOLOCK,
1501                                PDB_CHANGED)) {
1502                 DEBUG(1, ("pdb_increment_bad_password_count:failed to set 'autolock' flag. \n")); 
1503                 return False;
1504         }
1505
1506         return True;
1507 }