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