c0cf3f2a23a83a8baf5a81b8b81d1b5274ff9b57
[ira/wip.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 ewith 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(uint16 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 uint16 pdb_decode_acct_ctrl(const char *p)
293 {
294         uint16 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, uint16 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         /* LOOKUP_NAME_GROUP is a hack to allow valid users = @foo to work
553          * correctly in the case where foo also exists as a user. If the flag
554          * is set, don't look for users at all. */
555
556         if ((flags & LOOKUP_NAME_GROUP) == 0) {
557                 struct samu *sam_account = NULL;
558                 DOM_SID user_sid;
559
560                 if ( !(sam_account = samu_new( NULL )) ) {
561                         return False;
562                 }
563         
564                 become_root();
565                 ret =  pdb_getsampwnam(sam_account, user);
566                 unbecome_root();
567
568                 if (ret) {
569                         sid_copy(&user_sid, pdb_get_user_sid(sam_account));
570                 }
571                 
572                 TALLOC_FREE(sam_account);
573
574                 if (ret) {
575                         if (!sid_check_is_in_our_domain(&user_sid)) {
576                                 DEBUG(0, ("User %s with invalid SID %s in passdb\n",
577                                           user, sid_string_static(&user_sid)));
578                                 return False;
579                         }
580
581                         sid_peek_rid(&user_sid, rid);
582                         *type = SID_NAME_USER;
583                         return True;
584                 }
585         }
586
587         /*
588          * Maybe it is a group ?
589          */
590
591         become_root();
592         ret = pdb_getgrnam(&map, user);
593         unbecome_root();
594
595         if (!ret) {
596                 return False;
597         }
598
599         /* BUILTIN groups are looked up elsewhere */
600         if (!sid_check_is_in_our_domain(&map.sid)) {
601                 DEBUG(10, ("Found group %s (%s) not in our domain -- "
602                            "ignoring.", user,
603                            sid_string_static(&map.sid)));
604                 return False;
605         }
606
607         /* yes it's a mapped group */
608         sid_peek_rid(&map.sid, rid);
609         *type = map.sid_name_use;
610         return True;
611 }
612
613 /*************************************************************
614  Change a password entry in the local smbpasswd file.
615  *************************************************************/
616
617 NTSTATUS local_password_change(const char *user_name, int local_flags,
618                            const char *new_passwd, 
619                            char *err_str, size_t err_str_len,
620                            char *msg_str, size_t msg_str_len)
621 {
622         struct samu     *sam_pass=NULL;
623         uint16 other_acb;
624         NTSTATUS result;
625
626         *err_str = '\0';
627         *msg_str = '\0';
628
629         /* Get the smb passwd entry for this user */
630
631         if ( !(sam_pass = samu_new( NULL )) ) {
632                 return NT_STATUS_NO_MEMORY;
633         }
634
635         become_root();
636         if(!pdb_getsampwnam(sam_pass, user_name)) {
637                 unbecome_root();
638                 TALLOC_FREE(sam_pass);
639                 
640                 if ((local_flags & LOCAL_ADD_USER) || (local_flags & LOCAL_DELETE_USER)) {
641                         int tmp_debug = DEBUGLEVEL;
642                         struct passwd *pwd;
643
644                         /* Might not exist in /etc/passwd. */
645
646                         if (tmp_debug < 1) {
647                                 DEBUGLEVEL = 1;
648                         }
649
650                         if ( !(pwd = getpwnam_alloc( NULL, user_name)) ) {
651                                 return NT_STATUS_NO_SUCH_USER;
652                         }
653
654                         /* create the struct samu and initialize the basic Unix properties */
655
656                         if ( !(sam_pass = samu_new( NULL )) ) {
657                                 return NT_STATUS_NO_MEMORY;
658                         }
659
660                         result = samu_set_unix( sam_pass, pwd );
661
662                         DEBUGLEVEL = tmp_debug;
663
664                         TALLOC_FREE( pwd );
665
666                         if (NT_STATUS_EQUAL(result, NT_STATUS_INVALID_PRIMARY_GROUP)) {
667                                 return result;
668                         }
669
670                         if (!NT_STATUS_IS_OK(result)) {
671                                 slprintf(err_str, err_str_len-1, "Failed to " "initialize account for user %s: %s\n",
672                                         user_name, nt_errstr(result));
673                                 return result;
674                         }
675                 } else {
676                         slprintf(err_str, err_str_len-1,"Failed to find entry for user %s.\n", user_name);
677                         return NT_STATUS_NO_SUCH_USER;
678                 }
679         } else {
680                 unbecome_root();
681                 /* the entry already existed */
682                 local_flags &= ~LOCAL_ADD_USER;
683         }
684
685         /* the 'other' acb bits not being changed here */
686         other_acb =  (pdb_get_acct_ctrl(sam_pass) & (!(ACB_WSTRUST|ACB_DOMTRUST|ACB_SVRTRUST|ACB_NORMAL)));
687         if (local_flags & LOCAL_TRUST_ACCOUNT) {
688                 if (!pdb_set_acct_ctrl(sam_pass, ACB_WSTRUST | other_acb, PDB_CHANGED) ) {
689                         slprintf(err_str, err_str_len - 1, "Failed to set 'trusted workstation account' flags for user %s.\n", user_name);
690                         TALLOC_FREE(sam_pass);
691                         return NT_STATUS_UNSUCCESSFUL;
692                 }
693         } else if (local_flags & LOCAL_INTERDOM_ACCOUNT) {
694                 if (!pdb_set_acct_ctrl(sam_pass, ACB_DOMTRUST | other_acb, PDB_CHANGED)) {
695                         slprintf(err_str, err_str_len - 1, "Failed to set 'domain trust account' flags for user %s.\n", user_name);
696                         TALLOC_FREE(sam_pass);
697                         return NT_STATUS_UNSUCCESSFUL;
698                 }
699         } else {
700                 if (!pdb_set_acct_ctrl(sam_pass, ACB_NORMAL | other_acb, PDB_CHANGED)) {
701                         slprintf(err_str, err_str_len - 1, "Failed to set 'normal account' flags for user %s.\n", user_name);
702                         TALLOC_FREE(sam_pass);
703                         return NT_STATUS_UNSUCCESSFUL;
704                 }
705         }
706
707         /*
708          * We are root - just write the new password
709          * and the valid last change time.
710          */
711
712         if (local_flags & LOCAL_DISABLE_USER) {
713                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_DISABLED, PDB_CHANGED)) {
714                         slprintf(err_str, err_str_len-1, "Failed to set 'disabled' flag for user %s.\n", user_name);
715                         TALLOC_FREE(sam_pass);
716                         return NT_STATUS_UNSUCCESSFUL;
717                 }
718         } else if (local_flags & LOCAL_ENABLE_USER) {
719                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
720                         slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
721                         TALLOC_FREE(sam_pass);
722                         return NT_STATUS_UNSUCCESSFUL;
723                 }
724         }
725         
726         if (local_flags & LOCAL_SET_NO_PASSWORD) {
727                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_PWNOTREQ, PDB_CHANGED)) {
728                         slprintf(err_str, err_str_len-1, "Failed to set 'no password required' flag for user %s.\n", user_name);
729                         TALLOC_FREE(sam_pass);
730                         return NT_STATUS_UNSUCCESSFUL;
731                 }
732         } else if (local_flags & LOCAL_SET_PASSWORD) {
733                 /*
734                  * If we're dealing with setting a completely empty user account
735                  * ie. One with a password of 'XXXX', but not set disabled (like
736                  * an account created from scratch) then if the old password was
737                  * 'XX's then getsmbpwent will have set the ACB_DISABLED flag.
738                  * We remove that as we're giving this user their first password
739                  * and the decision hasn't really been made to disable them (ie.
740                  * don't create them disabled). JRA.
741                  */
742                 if ((pdb_get_lanman_passwd(sam_pass)==NULL) && (pdb_get_acct_ctrl(sam_pass)&ACB_DISABLED)) {
743                         if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
744                                 slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
745                                 TALLOC_FREE(sam_pass);
746                                 return NT_STATUS_UNSUCCESSFUL;
747                         }
748                 }
749                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_PWNOTREQ), PDB_CHANGED)) {
750                         slprintf(err_str, err_str_len-1, "Failed to unset 'no password required' flag for user %s.\n", user_name);
751                         TALLOC_FREE(sam_pass);
752                         return NT_STATUS_UNSUCCESSFUL;
753                 }
754                 
755                 if (!pdb_set_plaintext_passwd (sam_pass, new_passwd)) {
756                         slprintf(err_str, err_str_len-1, "Failed to set password for user %s.\n", user_name);
757                         TALLOC_FREE(sam_pass);
758                         return NT_STATUS_UNSUCCESSFUL;
759                 }
760         }       
761
762         if (local_flags & LOCAL_ADD_USER) {
763                 if (NT_STATUS_IS_OK(pdb_add_sam_account(sam_pass))) {
764                         slprintf(msg_str, msg_str_len-1, "Added user %s.\n", user_name);
765                         TALLOC_FREE(sam_pass);
766                         return NT_STATUS_OK;
767                 } else {
768                         slprintf(err_str, err_str_len-1, "Failed to add entry for user %s.\n", user_name);
769                         TALLOC_FREE(sam_pass);
770                         return NT_STATUS_UNSUCCESSFUL;
771                 }
772         } else if (local_flags & LOCAL_DELETE_USER) {
773                 if (!NT_STATUS_IS_OK(pdb_delete_sam_account(sam_pass))) {
774                         slprintf(err_str,err_str_len-1, "Failed to delete entry for user %s.\n", user_name);
775                         TALLOC_FREE(sam_pass);
776                         return NT_STATUS_UNSUCCESSFUL;
777                 }
778                 slprintf(msg_str, msg_str_len-1, "Deleted user %s.\n", user_name);
779         } else {
780                 result = pdb_update_sam_account(sam_pass);
781                 if(!NT_STATUS_IS_OK(result)) {
782                         slprintf(err_str, err_str_len-1, "Failed to modify entry for user %s.\n", user_name);
783                         TALLOC_FREE(sam_pass);
784                         return result;
785                 }
786                 if(local_flags & LOCAL_DISABLE_USER)
787                         slprintf(msg_str, msg_str_len-1, "Disabled user %s.\n", user_name);
788                 else if (local_flags & LOCAL_ENABLE_USER)
789                         slprintf(msg_str, msg_str_len-1, "Enabled user %s.\n", user_name);
790                 else if (local_flags & LOCAL_SET_NO_PASSWORD)
791                         slprintf(msg_str, msg_str_len-1, "User %s password set to none.\n", user_name);
792         }
793
794         TALLOC_FREE(sam_pass);
795         return NT_STATUS_OK;
796 }
797
798 /**********************************************************************
799  Marshall/unmarshall struct samu structs.
800  *********************************************************************/
801
802 #define TDB_FORMAT_STRING_V2       "dddddddBBBBBBBBBBBBddBBBwwdBwwd"
803
804 /*********************************************************************
805 *********************************************************************/
806
807 BOOL init_sam_from_buffer_v2(struct samu *sampass, uint8 *buf, uint32 buflen)
808 {
809
810         /* times are stored as 32bit integer
811            take care on system with 64bit wide time_t
812            --SSS */
813         uint32  logon_time,
814                 logoff_time,
815                 kickoff_time,
816                 bad_password_time,
817                 pass_last_set_time,
818                 pass_can_change_time,
819                 pass_must_change_time;
820         char *username = NULL;
821         char *domain = NULL;
822         char *nt_username = NULL;
823         char *dir_drive = NULL;
824         char *unknown_str = NULL;
825         char *munged_dial = NULL;
826         char *fullname = NULL;
827         char *homedir = NULL;
828         char *logon_script = NULL;
829         char *profile_path = NULL;
830         char *acct_desc = NULL;
831         char *workstations = NULL;
832         uint32  username_len, domain_len, nt_username_len,
833                 dir_drive_len, unknown_str_len, munged_dial_len,
834                 fullname_len, homedir_len, logon_script_len,
835                 profile_path_len, acct_desc_len, workstations_len;
836                 
837         uint32  user_rid, group_rid, hours_len, unknown_6;
838         uint16  acct_ctrl, logon_divs;
839         uint16  bad_password_count, logon_count;
840         uint8   *hours = NULL;
841         uint8   *lm_pw_ptr = NULL, *nt_pw_ptr = NULL, *nt_pw_hist_ptr = NULL;
842         uint32          len = 0;
843         uint32          lm_pw_len, nt_pw_len, nt_pw_hist_len, hourslen;
844         uint32 pwHistLen = 0;
845         BOOL ret = True;
846         fstring tmpstring;
847         BOOL expand_explicit = lp_passdb_expand_explicit();
848         
849         if(sampass == NULL || buf == NULL) {
850                 DEBUG(0, ("init_sam_from_buffer_v2: NULL parameters found!\n"));
851                 return False;
852         }
853                                                                         
854 /* TDB_FORMAT_STRING_V2       "dddddddBBBBBBBBBBBBddBBBwwdBwwd" */
855
856         /* unpack the buffer into variables */
857         len = tdb_unpack ((char *)buf, buflen, TDB_FORMAT_STRING_V2,
858                 &logon_time,                                            /* d */
859                 &logoff_time,                                           /* d */
860                 &kickoff_time,                                          /* d */
861                 &bad_password_time,                                     /* d */
862                 &pass_last_set_time,                                    /* d */
863                 &pass_can_change_time,                                  /* d */
864                 &pass_must_change_time,                                 /* d */
865                 &username_len, &username,                               /* B */
866                 &domain_len, &domain,                                   /* B */
867                 &nt_username_len, &nt_username,                         /* B */
868                 &fullname_len, &fullname,                               /* B */
869                 &homedir_len, &homedir,                                 /* B */
870                 &dir_drive_len, &dir_drive,                             /* B */
871                 &logon_script_len, &logon_script,                       /* B */
872                 &profile_path_len, &profile_path,                       /* B */
873                 &acct_desc_len, &acct_desc,                             /* B */
874                 &workstations_len, &workstations,                       /* B */
875                 &unknown_str_len, &unknown_str,                         /* B */
876                 &munged_dial_len, &munged_dial,                         /* B */
877                 &user_rid,                                              /* d */
878                 &group_rid,                                             /* d */
879                 &lm_pw_len, &lm_pw_ptr,                                 /* B */
880                 &nt_pw_len, &nt_pw_ptr,                                 /* B */
881                 /* Change from V1 is addition of password history field. */
882                 &nt_pw_hist_len, &nt_pw_hist_ptr,                       /* B */
883                 &acct_ctrl,                                             /* w */
884                 /* Also "remove_me" field was removed. */
885                 &logon_divs,                                            /* w */
886                 &hours_len,                                             /* d */
887                 &hourslen, &hours,                                      /* B */
888                 &bad_password_count,                                    /* w */
889                 &logon_count,                                           /* w */
890                 &unknown_6);                                            /* d */
891                 
892         if (len == (uint32) -1)  {
893                 ret = False;
894                 goto done;
895         }
896
897         pdb_set_logon_time(sampass, logon_time, PDB_SET);
898         pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
899         pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
900         pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
901         pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
902         pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
903         pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
904
905         pdb_set_username(sampass, username, PDB_SET); 
906         pdb_set_domain(sampass, domain, PDB_SET);
907         pdb_set_nt_username(sampass, nt_username, PDB_SET);
908         pdb_set_fullname(sampass, fullname, PDB_SET);
909
910         if (homedir) {
911                 fstrcpy( tmpstring, homedir );
912                 if (expand_explicit) {
913                         standard_sub_basic( username, tmpstring,
914                                             sizeof(tmpstring) );
915                 }
916                 pdb_set_homedir(sampass, tmpstring, PDB_SET);
917         }
918         else {
919                 pdb_set_homedir(sampass, 
920                         talloc_sub_basic(sampass, username, lp_logon_home()),
921                         PDB_DEFAULT);
922         }
923
924         if (dir_drive)  
925                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
926         else
927                 pdb_set_dir_drive(sampass, lp_logon_drive(), PDB_DEFAULT );
928
929         if (logon_script) {
930                 fstrcpy( tmpstring, logon_script );
931                 if (expand_explicit) {
932                         standard_sub_basic( username, tmpstring,
933                                             sizeof(tmpstring) );
934                 }
935                 pdb_set_logon_script(sampass, tmpstring, PDB_SET);
936         }
937         else {
938                 pdb_set_logon_script(sampass, 
939                         talloc_sub_basic(sampass, username, lp_logon_script()),
940                         PDB_DEFAULT);
941         }
942         
943         if (profile_path) {     
944                 fstrcpy( tmpstring, profile_path );
945                 if (expand_explicit) {
946                         standard_sub_basic( username, tmpstring,
947                                             sizeof(tmpstring) );
948                 }
949                 pdb_set_profile_path(sampass, tmpstring, PDB_SET);
950         } 
951         else {
952                 pdb_set_profile_path(sampass, 
953                         talloc_sub_basic(sampass, username, lp_logon_path()),
954                         PDB_DEFAULT);
955         }
956
957         pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
958         pdb_set_workstations(sampass, workstations, PDB_SET);
959         pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
960
961         if (lm_pw_ptr && lm_pw_len == LM_HASH_LEN) {
962                 if (!pdb_set_lanman_passwd(sampass, lm_pw_ptr, PDB_SET)) {
963                         ret = False;
964                         goto done;
965                 }
966         }
967
968         if (nt_pw_ptr && nt_pw_len == NT_HASH_LEN) {
969                 if (!pdb_set_nt_passwd(sampass, nt_pw_ptr, PDB_SET)) {
970                         ret = False;
971                         goto done;
972                 }
973         }
974
975         /* Change from V1 is addition of password history field. */
976         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
977         if (pwHistLen) {
978                 uint8 *pw_hist = SMB_MALLOC(pwHistLen * PW_HISTORY_ENTRY_LEN);
979                 if (!pw_hist) {
980                         ret = False;
981                         goto done;
982                 }
983                 memset(pw_hist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
984                 if (nt_pw_hist_ptr && nt_pw_hist_len) {
985                         int i;
986                         SMB_ASSERT((nt_pw_hist_len % PW_HISTORY_ENTRY_LEN) == 0);
987                         nt_pw_hist_len /= PW_HISTORY_ENTRY_LEN;
988                         for (i = 0; (i < pwHistLen) && (i < nt_pw_hist_len); i++) {
989                                 memcpy(&pw_hist[i*PW_HISTORY_ENTRY_LEN],
990                                         &nt_pw_hist_ptr[i*PW_HISTORY_ENTRY_LEN],
991                                         PW_HISTORY_ENTRY_LEN);
992                         }
993                 }
994                 if (!pdb_set_pw_history(sampass, pw_hist, pwHistLen, PDB_SET)) {
995                         SAFE_FREE(pw_hist);
996                         ret = False;
997                         goto done;
998                 }
999                 SAFE_FREE(pw_hist);
1000         } else {
1001                 pdb_set_pw_history(sampass, NULL, 0, PDB_SET);
1002         }
1003
1004         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
1005         pdb_set_hours_len(sampass, hours_len, PDB_SET);
1006         pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
1007         pdb_set_logon_count(sampass, logon_count, PDB_SET);
1008         pdb_set_unknown_6(sampass, unknown_6, PDB_SET);
1009         pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
1010         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
1011         pdb_set_hours(sampass, hours, PDB_SET);
1012
1013 done:
1014
1015         SAFE_FREE(username);
1016         SAFE_FREE(domain);
1017         SAFE_FREE(nt_username);
1018         SAFE_FREE(fullname);
1019         SAFE_FREE(homedir);
1020         SAFE_FREE(dir_drive);
1021         SAFE_FREE(logon_script);
1022         SAFE_FREE(profile_path);
1023         SAFE_FREE(acct_desc);
1024         SAFE_FREE(workstations);
1025         SAFE_FREE(munged_dial);
1026         SAFE_FREE(unknown_str);
1027         SAFE_FREE(lm_pw_ptr);
1028         SAFE_FREE(nt_pw_ptr);
1029         SAFE_FREE(nt_pw_hist_ptr);
1030         SAFE_FREE(hours);
1031
1032         return ret;
1033 }
1034
1035 /*********************************************************************
1036 *********************************************************************/
1037
1038 uint32 init_buffer_from_sam_v2 (uint8 **buf, struct samu *sampass, BOOL size_only)
1039 {
1040         size_t len, buflen;
1041
1042         /* times are stored as 32bit integer
1043            take care on system with 64bit wide time_t
1044            --SSS */
1045         uint32  logon_time,
1046                 logoff_time,
1047                 kickoff_time,
1048                 bad_password_time,
1049                 pass_last_set_time,
1050                 pass_can_change_time,
1051                 pass_must_change_time;
1052
1053         uint32  user_rid, group_rid;
1054
1055         const char *username;
1056         const char *domain;
1057         const char *nt_username;
1058         const char *dir_drive;
1059         const char *unknown_str;
1060         const char *munged_dial;
1061         const char *fullname;
1062         const char *homedir;
1063         const char *logon_script;
1064         const char *profile_path;
1065         const char *acct_desc;
1066         const char *workstations;
1067         uint32  username_len, domain_len, nt_username_len,
1068                 dir_drive_len, unknown_str_len, munged_dial_len,
1069                 fullname_len, homedir_len, logon_script_len,
1070                 profile_path_len, acct_desc_len, workstations_len;
1071
1072         const uint8 *lm_pw;
1073         const uint8 *nt_pw;
1074         const uint8 *nt_pw_hist;
1075         uint32  lm_pw_len = 16;
1076         uint32  nt_pw_len = 16;
1077         uint32  nt_pw_hist_len;
1078         uint32 pwHistLen = 0;
1079
1080         /* do we have a valid struct samu pointer? */
1081         if (sampass == NULL) {
1082                 DEBUG(0, ("init_buffer_from_sam: struct samu is NULL!\n"));
1083                 return -1;
1084         }
1085         
1086         *buf = NULL;
1087         buflen = 0;
1088
1089         logon_time = (uint32)pdb_get_logon_time(sampass);
1090         logoff_time = (uint32)pdb_get_logoff_time(sampass);
1091         kickoff_time = (uint32)pdb_get_kickoff_time(sampass);
1092         bad_password_time = (uint32)pdb_get_bad_password_time(sampass);
1093         pass_can_change_time = (uint32)pdb_get_pass_can_change_time(sampass);
1094         pass_must_change_time = (uint32)pdb_get_pass_must_change_time(sampass);
1095         pass_last_set_time = (uint32)pdb_get_pass_last_set_time(sampass);
1096
1097         user_rid = pdb_get_user_rid(sampass);
1098         group_rid = pdb_get_group_rid(sampass);
1099
1100         username = pdb_get_username(sampass);
1101         if (username) {
1102                 username_len = strlen(username) +1;
1103         } else {
1104                 username_len = 0;
1105         }
1106
1107         domain = pdb_get_domain(sampass);
1108         if (domain) {
1109                 domain_len = strlen(domain) +1;
1110         } else {
1111                 domain_len = 0;
1112         }
1113
1114         nt_username = pdb_get_nt_username(sampass);
1115         if (nt_username) {
1116                 nt_username_len = strlen(nt_username) +1;
1117         } else {
1118                 nt_username_len = 0;
1119         }
1120
1121         fullname = pdb_get_fullname(sampass);
1122         if (fullname) {
1123                 fullname_len = strlen(fullname) +1;
1124         } else {
1125                 fullname_len = 0;
1126         }
1127
1128         /*
1129          * Only updates fields which have been set (not defaults from smb.conf)
1130          */
1131
1132         if (!IS_SAM_DEFAULT(sampass, PDB_DRIVE)) {
1133                 dir_drive = pdb_get_dir_drive(sampass);
1134         } else {
1135                 dir_drive = NULL;
1136         }
1137         if (dir_drive) {
1138                 dir_drive_len = strlen(dir_drive) +1;
1139         } else {
1140                 dir_drive_len = 0;
1141         }
1142
1143         if (!IS_SAM_DEFAULT(sampass, PDB_SMBHOME)) {
1144                 homedir = pdb_get_homedir(sampass);
1145         } else {
1146                 homedir = NULL;
1147         }
1148         if (homedir) {
1149                 homedir_len = strlen(homedir) +1;
1150         } else {
1151                 homedir_len = 0;
1152         }
1153
1154         if (!IS_SAM_DEFAULT(sampass, PDB_LOGONSCRIPT)) {
1155                 logon_script = pdb_get_logon_script(sampass);
1156         } else {
1157                 logon_script = NULL;
1158         }
1159         if (logon_script) {
1160                 logon_script_len = strlen(logon_script) +1;
1161         } else {
1162                 logon_script_len = 0;
1163         }
1164
1165         if (!IS_SAM_DEFAULT(sampass, PDB_PROFILE)) {
1166                 profile_path = pdb_get_profile_path(sampass);
1167         } else {
1168                 profile_path = NULL;
1169         }
1170         if (profile_path) {
1171                 profile_path_len = strlen(profile_path) +1;
1172         } else {
1173                 profile_path_len = 0;
1174         }
1175         
1176         lm_pw = pdb_get_lanman_passwd(sampass);
1177         if (!lm_pw) {
1178                 lm_pw_len = 0;
1179         }
1180         
1181         nt_pw = pdb_get_nt_passwd(sampass);
1182         if (!nt_pw) {
1183                 nt_pw_len = 0;
1184         }
1185
1186         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
1187         nt_pw_hist =  pdb_get_pw_history(sampass, &nt_pw_hist_len);
1188         if (pwHistLen && nt_pw_hist && nt_pw_hist_len) {
1189                 nt_pw_hist_len *= PW_HISTORY_ENTRY_LEN;
1190         } else {
1191                 nt_pw_hist_len = 0;
1192         }
1193
1194         acct_desc = pdb_get_acct_desc(sampass);
1195         if (acct_desc) {
1196                 acct_desc_len = strlen(acct_desc) +1;
1197         } else {
1198                 acct_desc_len = 0;
1199         }
1200
1201         workstations = pdb_get_workstations(sampass);
1202         if (workstations) {
1203                 workstations_len = strlen(workstations) +1;
1204         } else {
1205                 workstations_len = 0;
1206         }
1207
1208         unknown_str = NULL;
1209         unknown_str_len = 0;
1210
1211         munged_dial = pdb_get_munged_dial(sampass);
1212         if (munged_dial) {
1213                 munged_dial_len = strlen(munged_dial) +1;
1214         } else {
1215                 munged_dial_len = 0;    
1216         }
1217
1218 /* TDB_FORMAT_STRING_V2       "dddddddBBBBBBBBBBBBddBBBwwdBwwd" */
1219
1220         /* one time to get the size needed */
1221         len = tdb_pack(NULL, 0,  TDB_FORMAT_STRING_V2,
1222                 logon_time,                             /* d */
1223                 logoff_time,                            /* d */
1224                 kickoff_time,                           /* d */
1225                 bad_password_time,                      /* d */
1226                 pass_last_set_time,                     /* d */
1227                 pass_can_change_time,                   /* d */
1228                 pass_must_change_time,                  /* d */
1229                 username_len, username,                 /* B */
1230                 domain_len, domain,                     /* B */
1231                 nt_username_len, nt_username,           /* B */
1232                 fullname_len, fullname,                 /* B */
1233                 homedir_len, homedir,                   /* B */
1234                 dir_drive_len, dir_drive,               /* B */
1235                 logon_script_len, logon_script,         /* B */
1236                 profile_path_len, profile_path,         /* B */
1237                 acct_desc_len, acct_desc,               /* B */
1238                 workstations_len, workstations,         /* B */
1239                 unknown_str_len, unknown_str,           /* B */
1240                 munged_dial_len, munged_dial,           /* B */
1241                 user_rid,                               /* d */
1242                 group_rid,                              /* d */
1243                 lm_pw_len, lm_pw,                       /* B */
1244                 nt_pw_len, nt_pw,                       /* B */
1245                 nt_pw_hist_len, nt_pw_hist,             /* B */
1246                 pdb_get_acct_ctrl(sampass),             /* w */
1247                 pdb_get_logon_divs(sampass),            /* w */
1248                 pdb_get_hours_len(sampass),             /* d */
1249                 MAX_HOURS_LEN, pdb_get_hours(sampass),  /* B */
1250                 pdb_get_bad_password_count(sampass),    /* w */
1251                 pdb_get_logon_count(sampass),           /* w */
1252                 pdb_get_unknown_6(sampass));            /* d */
1253
1254         if (size_only) {
1255                 return buflen;
1256         }
1257
1258         /* malloc the space needed */
1259         if ( (*buf=(uint8*)SMB_MALLOC(len)) == NULL) {
1260                 DEBUG(0,("init_buffer_from_sam_v2: Unable to malloc() memory for buffer!\n"));
1261                 return (-1);
1262         }
1263         
1264         /* now for the real call to tdb_pack() */
1265         buflen = tdb_pack((char *)*buf, len,  TDB_FORMAT_STRING_V2,
1266                 logon_time,                             /* d */
1267                 logoff_time,                            /* d */
1268                 kickoff_time,                           /* d */
1269                 bad_password_time,                      /* d */
1270                 pass_last_set_time,                     /* d */
1271                 pass_can_change_time,                   /* d */
1272                 pass_must_change_time,                  /* d */
1273                 username_len, username,                 /* B */
1274                 domain_len, domain,                     /* B */
1275                 nt_username_len, nt_username,           /* B */
1276                 fullname_len, fullname,                 /* B */
1277                 homedir_len, homedir,                   /* B */
1278                 dir_drive_len, dir_drive,               /* B */
1279                 logon_script_len, logon_script,         /* B */
1280                 profile_path_len, profile_path,         /* B */
1281                 acct_desc_len, acct_desc,               /* B */
1282                 workstations_len, workstations,         /* B */
1283                 unknown_str_len, unknown_str,           /* B */
1284                 munged_dial_len, munged_dial,           /* B */
1285                 user_rid,                               /* d */
1286                 group_rid,                              /* d */
1287                 lm_pw_len, lm_pw,                       /* B */
1288                 nt_pw_len, nt_pw,                       /* B */
1289                 nt_pw_hist_len, nt_pw_hist,             /* B */
1290                 pdb_get_acct_ctrl(sampass),             /* w */
1291                 pdb_get_logon_divs(sampass),            /* w */
1292                 pdb_get_hours_len(sampass),             /* d */
1293                 MAX_HOURS_LEN, pdb_get_hours(sampass),  /* B */
1294                 pdb_get_bad_password_count(sampass),    /* w */
1295                 pdb_get_logon_count(sampass),           /* w */
1296                 pdb_get_unknown_6(sampass));            /* d */
1297         
1298         /* check to make sure we got it correct */
1299         if (buflen != len) {
1300                 DEBUG(0, ("init_buffer_from_sam_v2: somthing odd is going on here: bufflen (%lu) != len (%lu) in tdb_pack operations!\n", 
1301                           (unsigned long)buflen, (unsigned long)len));  
1302                 /* error */
1303                 SAFE_FREE (*buf);
1304                 return (-1);
1305         }
1306
1307         return (buflen);
1308 }
1309
1310
1311 /*********************************************************************
1312 *********************************************************************/
1313
1314 BOOL pdb_copy_sam_account(struct samu *dst, struct samu *src )
1315 {
1316         BOOL result;
1317         uint8 *buf;
1318         int len;
1319
1320         if ( !dst )
1321                 return False;
1322
1323         len = init_buffer_from_sam_v2(&buf, src, False);
1324
1325         if (len == -1)
1326                 return False;
1327
1328         result = init_sam_from_buffer_v2( dst, buf, len );
1329         dst->methods = src->methods;
1330         
1331         if ( src->unix_pw )
1332                 dst->unix_pw = tcopy_passwd( dst, src->unix_pw );
1333
1334         free(buf);
1335
1336         return result;
1337 }
1338
1339 /*********************************************************************
1340  Update the bad password count checking the AP_RESET_COUNT_TIME 
1341 *********************************************************************/
1342
1343 BOOL pdb_update_bad_password_count(struct samu *sampass, BOOL *updated)
1344 {
1345         time_t LastBadPassword;
1346         uint16 BadPasswordCount;
1347         uint32 resettime; 
1348
1349         if (!sampass) return False;
1350         
1351         BadPasswordCount = pdb_get_bad_password_count(sampass);
1352         if (!BadPasswordCount) {
1353                 DEBUG(9, ("No bad password attempts.\n"));
1354                 return True;
1355         }
1356
1357         if (!pdb_get_account_policy(AP_RESET_COUNT_TIME, &resettime)) {
1358                 DEBUG(0, ("pdb_update_bad_password_count: pdb_get_account_policy failed.\n"));
1359                 return False;
1360         }
1361
1362         /* First, check if there is a reset time to compare */
1363         if ((resettime == (uint32) -1) || (resettime == 0)) {
1364                 DEBUG(9, ("No reset time, can't reset bad pw count\n"));
1365                 return True;
1366         }
1367
1368         LastBadPassword = pdb_get_bad_password_time(sampass);
1369         DEBUG(7, ("LastBadPassword=%d, resettime=%d, current time=%d.\n", 
1370                    (uint32) LastBadPassword, resettime, (uint32)time(NULL)));
1371         if (time(NULL) > (LastBadPassword + (time_t)resettime*60)){
1372                 pdb_set_bad_password_count(sampass, 0, PDB_CHANGED);
1373                 pdb_set_bad_password_time(sampass, 0, PDB_CHANGED);
1374                 if (updated) {
1375                         *updated = True;
1376                 }
1377         }
1378
1379         return True;
1380 }
1381
1382 /*********************************************************************
1383  Update the ACB_AUTOLOCK flag checking the AP_LOCK_ACCOUNT_DURATION 
1384 *********************************************************************/
1385
1386 BOOL pdb_update_autolock_flag(struct samu *sampass, BOOL *updated)
1387 {
1388         uint32 duration;
1389         time_t LastBadPassword;
1390
1391         if (!sampass) return False;
1392  
1393         if (!(pdb_get_acct_ctrl(sampass) & ACB_AUTOLOCK)) {
1394                 DEBUG(9, ("pdb_update_autolock_flag: Account %s not autolocked, no check needed\n",
1395                         pdb_get_username(sampass)));
1396                 return True;
1397         }
1398
1399         if (!pdb_get_account_policy(AP_LOCK_ACCOUNT_DURATION, &duration)) {
1400                 DEBUG(0, ("pdb_update_autolock_flag: pdb_get_account_policy failed.\n"));
1401                 return False;
1402         }
1403
1404         /* First, check if there is a duration to compare */
1405         if ((duration == (uint32) -1)  || (duration == 0)) {
1406                 DEBUG(9, ("pdb_update_autolock_flag: No reset duration, can't reset autolock\n"));
1407                 return True;
1408         }
1409                       
1410         LastBadPassword = pdb_get_bad_password_time(sampass);
1411         DEBUG(7, ("pdb_update_autolock_flag: Account %s, LastBadPassword=%d, duration=%d, current time =%d.\n",
1412                   pdb_get_username(sampass), (uint32)LastBadPassword, duration*60, (uint32)time(NULL)));
1413
1414         if (LastBadPassword == (time_t)0) {
1415                 DEBUG(1,("pdb_update_autolock_flag: Account %s administratively locked out with no \
1416 bad password time. Leaving locked out.\n",
1417                         pdb_get_username(sampass) ));
1418                         return True;
1419         }
1420
1421         if ((time(NULL) > (LastBadPassword + (time_t) duration * 60))) {
1422                 pdb_set_acct_ctrl(sampass,
1423                                   pdb_get_acct_ctrl(sampass) & ~ACB_AUTOLOCK,
1424                                   PDB_CHANGED);
1425                 pdb_set_bad_password_count(sampass, 0, PDB_CHANGED);
1426                 pdb_set_bad_password_time(sampass, 0, PDB_CHANGED);
1427                 if (updated) {
1428                         *updated = True;
1429                 }
1430         }
1431         
1432         return True;
1433 }
1434
1435 /*********************************************************************
1436  Increment the bad_password_count 
1437 *********************************************************************/
1438
1439 BOOL pdb_increment_bad_password_count(struct samu *sampass)
1440 {
1441         uint32 account_policy_lockout;
1442         BOOL autolock_updated = False, badpw_updated = False;
1443         BOOL ret;
1444
1445         if (!sampass)
1446                 return False;
1447
1448         /* Retrieve the account lockout policy */
1449         become_root();
1450         ret = pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &account_policy_lockout);
1451         unbecome_root();
1452         if ( !ret ) {
1453                 DEBUG(0, ("pdb_increment_bad_password_count: pdb_get_account_policy failed.\n"));
1454                 return False;
1455         }
1456
1457         /* If there is no policy, we don't need to continue checking */
1458         if (!account_policy_lockout) {
1459                 DEBUG(9, ("No lockout policy, don't track bad passwords\n"));
1460                 return True;
1461         }
1462
1463         /* Check if the autolock needs to be cleared */
1464         if (!pdb_update_autolock_flag(sampass, &autolock_updated))
1465                 return False;
1466
1467         /* Check if the badpw count needs to be reset */
1468         if (!pdb_update_bad_password_count(sampass, &badpw_updated))
1469                 return False;
1470
1471         /*
1472           Ok, now we can assume that any resetting that needs to be 
1473           done has been done, and just get on with incrementing
1474           and autolocking if necessary
1475         */
1476
1477         pdb_set_bad_password_count(sampass, 
1478                                    pdb_get_bad_password_count(sampass)+1,
1479                                    PDB_CHANGED);
1480         pdb_set_bad_password_time(sampass, time(NULL), PDB_CHANGED);
1481
1482
1483         if (pdb_get_bad_password_count(sampass) < account_policy_lockout) 
1484                 return True;
1485
1486         if (!pdb_set_acct_ctrl(sampass,
1487                                pdb_get_acct_ctrl(sampass) | ACB_AUTOLOCK,
1488                                PDB_CHANGED)) {
1489                 DEBUG(1, ("pdb_increment_bad_password_count:failed to set 'autolock' flag. \n")); 
1490                 return False;
1491         }
1492
1493         return True;
1494 }