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