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