import HEAD into svn+ssh://svn.samba.org/home/svn/samba/trunk
[metze/old/v3-2-winbind-ndr.git] / source / 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(const 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                 DEBUG(5,("local_lookup_sid: looking up gid %u %s\n", (unsigned int)gid,
804                          gr ? "succeeded" : "failed" ));
805                         
806                 if( !gr )
807                         fstr_sprintf(name, "unix_group.%u", (unsigned int)gid);
808                 else
809                         fstrcpy( name, gr->gr_name);
810                         
811                 DEBUG(5,("local_lookup_sid: found group %s for rid %u\n", name,
812                          (unsigned int)rid ));
813                 
814                 /* assume fallback groups aer domain global groups */
815                 
816                 *psid_name_use = SID_NAME_DOM_GRP;
817                 
818                 return ( gr != NULL );
819         }
820 }
821
822 /*******************************************************************
823  Convert a name into a SID. Used in the lookup name rpc.
824  ********************************************************************/
825
826 BOOL local_lookup_name(const char *c_user, DOM_SID *psid, enum SID_NAME_USE *psid_name_use)
827 {
828         extern DOM_SID global_sid_World_Domain;
829         DOM_SID local_sid;
830         fstring user;
831         SAM_ACCOUNT *sam_account = NULL;
832         struct group *grp;
833         GROUP_MAP map;
834                 
835         *psid_name_use = SID_NAME_UNKNOWN;
836
837         /*
838          * user may be quoted a const string, and map_username and
839          * friends can modify it. Make a modifiable copy. JRA.
840          */
841
842         fstrcpy(user, c_user);
843
844         sid_copy(&local_sid, get_global_sam_sid());
845
846         /*
847          * Special case for MACHINE\Everyone. Map to the world_sid.
848          */
849
850         if(strequal(user, "Everyone")) {
851                 sid_copy( psid, &global_sid_World_Domain);
852                 sid_append_rid(psid, 0);
853                 *psid_name_use = SID_NAME_ALIAS;
854                 return True;
855         }
856
857         (void)map_username(user);
858
859         if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_account))) {
860                 return False;
861         }
862         
863         /* BEGIN ROOT BLOCK */
864         
865         become_root();
866         if (pdb_getsampwnam(sam_account, user)) {
867                 unbecome_root();
868                 sid_copy(psid, pdb_get_user_sid(sam_account));
869                 *psid_name_use = SID_NAME_USER;
870                 
871                 pdb_free_sam(&sam_account);
872                 return True;
873         }
874
875         pdb_free_sam(&sam_account);
876
877         /*
878          * Maybe it was a group ?
879          */
880
881         /* check if it's a mapped group */
882         if (pdb_getgrnam(&map, user)) {
883                 /* yes it's a mapped group */
884                 sid_copy(&local_sid, &map.sid);
885                 *psid_name_use = map.sid_name_use;
886         } else {
887                 /* it's not a mapped group */
888                 grp = getgrnam(user);
889                 if(!grp) {
890                         unbecome_root();                /* ---> exit form block */      
891                         return False;
892                 }
893                 
894                 /* 
895                  *check if it's mapped, if it is reply it doesn't exist
896                  *
897                  * that's to prevent this case:
898                  *
899                  * unix group ug is mapped to nt group ng
900                  * someone does a lookup on ug
901                  * we must not reply as it doesn't "exist" anymore
902                  * for NT. For NT only ng exists.
903                  * JFM, 30/11/2001
904                  */
905                 
906                 if (pdb_getgrgid(&map, grp->gr_gid)){
907                         unbecome_root();                /* ---> exit form block */
908                         return False;
909                 }
910                 
911                 sid_append_rid( &local_sid, pdb_gid_to_group_rid(grp->gr_gid));
912                 *psid_name_use = SID_NAME_ALIAS;
913         }
914         unbecome_root();
915         /* END ROOT BLOCK */
916
917         sid_copy( psid, &local_sid);
918
919         return True;
920 }
921
922 /*************************************************************
923  Change a password entry in the local smbpasswd file.
924  *************************************************************/
925
926 BOOL local_password_change(const char *user_name, int local_flags,
927                            const char *new_passwd, 
928                            char *err_str, size_t err_str_len,
929                            char *msg_str, size_t msg_str_len)
930 {
931         SAM_ACCOUNT     *sam_pass=NULL;
932         uint16 other_acb;
933
934         *err_str = '\0';
935         *msg_str = '\0';
936
937         /* Get the smb passwd entry for this user */
938         pdb_init_sam(&sam_pass);
939
940         become_root();
941         if(!pdb_getsampwnam(sam_pass, user_name)) {
942                 unbecome_root();
943                 pdb_free_sam(&sam_pass);
944                 
945                 if ((local_flags & LOCAL_ADD_USER) || (local_flags & LOCAL_DELETE_USER)) {
946                         /* Might not exist in /etc/passwd.  Use rid algorithm here */
947                         if (!NT_STATUS_IS_OK(pdb_init_sam_new(&sam_pass, user_name, 0))) {
948                                 slprintf(err_str, err_str_len-1, "Failed to initialise SAM_ACCOUNT for user %s.\n", user_name);
949                                 return False;
950                         }
951                 } else {
952                         slprintf(err_str, err_str_len-1,"Failed to find entry for user %s.\n", user_name);
953                         return False;
954                 }
955         } else {
956                 unbecome_root();
957                 /* the entry already existed */
958                 local_flags &= ~LOCAL_ADD_USER;
959         }
960
961         /* the 'other' acb bits not being changed here */
962         other_acb =  (pdb_get_acct_ctrl(sam_pass) & (!(ACB_WSTRUST|ACB_DOMTRUST|ACB_SVRTRUST|ACB_NORMAL)));
963         if (local_flags & LOCAL_TRUST_ACCOUNT) {
964                 if (!pdb_set_acct_ctrl(sam_pass, ACB_WSTRUST | other_acb, PDB_CHANGED) ) {
965                         slprintf(err_str, err_str_len - 1, "Failed to set 'trusted workstation account' flags for user %s.\n", user_name);
966                         pdb_free_sam(&sam_pass);
967                         return False;
968                 }
969         } else if (local_flags & LOCAL_INTERDOM_ACCOUNT) {
970                 if (!pdb_set_acct_ctrl(sam_pass, ACB_DOMTRUST | other_acb, PDB_CHANGED)) {
971                         slprintf(err_str, err_str_len - 1, "Failed to set 'domain trust account' flags for user %s.\n", user_name);
972                         pdb_free_sam(&sam_pass);
973                         return False;
974                 }
975         } else {
976                 if (!pdb_set_acct_ctrl(sam_pass, ACB_NORMAL | other_acb, PDB_CHANGED)) {
977                         slprintf(err_str, err_str_len - 1, "Failed to set 'normal account' flags for user %s.\n", user_name);
978                         pdb_free_sam(&sam_pass);
979                         return False;
980                 }
981         }
982
983         /*
984          * We are root - just write the new password
985          * and the valid last change time.
986          */
987
988         if (local_flags & LOCAL_DISABLE_USER) {
989                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_DISABLED, PDB_CHANGED)) {
990                         slprintf(err_str, err_str_len-1, "Failed to set 'disabled' flag for user %s.\n", user_name);
991                         pdb_free_sam(&sam_pass);
992                         return False;
993                 }
994         } else if (local_flags & LOCAL_ENABLE_USER) {
995                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
996                         slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
997                         pdb_free_sam(&sam_pass);
998                         return False;
999                 }
1000         }
1001         
1002         if (local_flags & LOCAL_SET_NO_PASSWORD) {
1003                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_PWNOTREQ, PDB_CHANGED)) {
1004                         slprintf(err_str, err_str_len-1, "Failed to set 'no password required' flag for user %s.\n", user_name);
1005                         pdb_free_sam(&sam_pass);
1006                         return False;
1007                 }
1008         } else if (local_flags & LOCAL_SET_PASSWORD) {
1009                 /*
1010                  * If we're dealing with setting a completely empty user account
1011                  * ie. One with a password of 'XXXX', but not set disabled (like
1012                  * an account created from scratch) then if the old password was
1013                  * 'XX's then getsmbpwent will have set the ACB_DISABLED flag.
1014                  * We remove that as we're giving this user their first password
1015                  * and the decision hasn't really been made to disable them (ie.
1016                  * don't create them disabled). JRA.
1017                  */
1018                 if ((pdb_get_lanman_passwd(sam_pass)==NULL) && (pdb_get_acct_ctrl(sam_pass)&ACB_DISABLED)) {
1019                         if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
1020                                 slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
1021                                 pdb_free_sam(&sam_pass);
1022                                 return False;
1023                         }
1024                 }
1025                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_PWNOTREQ), PDB_CHANGED)) {
1026                         slprintf(err_str, err_str_len-1, "Failed to unset 'no password required' flag for user %s.\n", user_name);
1027                         pdb_free_sam(&sam_pass);
1028                         return False;
1029                 }
1030                 
1031                 if (!pdb_set_plaintext_passwd (sam_pass, new_passwd)) {
1032                         slprintf(err_str, err_str_len-1, "Failed to set password for user %s.\n", user_name);
1033                         pdb_free_sam(&sam_pass);
1034                         return False;
1035                 }
1036         }       
1037
1038         if (local_flags & LOCAL_ADD_USER) {
1039                 if (pdb_add_sam_account(sam_pass)) {
1040                         slprintf(msg_str, msg_str_len-1, "Added user %s.\n", user_name);
1041                         pdb_free_sam(&sam_pass);
1042                         return True;
1043                 } else {
1044                         slprintf(err_str, err_str_len-1, "Failed to add entry for user %s.\n", user_name);
1045                         pdb_free_sam(&sam_pass);
1046                         return False;
1047                 }
1048         } else if (local_flags & LOCAL_DELETE_USER) {
1049                 if (!pdb_delete_sam_account(sam_pass)) {
1050                         slprintf(err_str,err_str_len-1, "Failed to delete entry for user %s.\n", user_name);
1051                         pdb_free_sam(&sam_pass);
1052                         return False;
1053                 }
1054                 slprintf(msg_str, msg_str_len-1, "Deleted user %s.\n", user_name);
1055         } else {
1056                 if(!pdb_update_sam_account(sam_pass)) {
1057                         slprintf(err_str, err_str_len-1, "Failed to modify entry for user %s.\n", user_name);
1058                         pdb_free_sam(&sam_pass);
1059                         return False;
1060                 }
1061                 if(local_flags & LOCAL_DISABLE_USER)
1062                         slprintf(msg_str, msg_str_len-1, "Disabled user %s.\n", user_name);
1063                 else if (local_flags & LOCAL_ENABLE_USER)
1064                         slprintf(msg_str, msg_str_len-1, "Enabled user %s.\n", user_name);
1065                 else if (local_flags & LOCAL_SET_NO_PASSWORD)
1066                         slprintf(msg_str, msg_str_len-1, "User %s password set to none.\n", user_name);
1067         }
1068
1069         pdb_free_sam(&sam_pass);
1070         return True;
1071 }
1072
1073 /****************************************************************************
1074  Convert a uid to SID - algorithmic.
1075 ****************************************************************************/
1076
1077 DOM_SID *algorithmic_uid_to_sid(DOM_SID *psid, uid_t uid)
1078 {
1079         if ( !lp_enable_rid_algorithm() )
1080                 return NULL;
1081
1082         DEBUG(8,("algorithmic_uid_to_sid: falling back to RID algorithm\n"));
1083         sid_copy( psid, get_global_sam_sid() );
1084         sid_append_rid( psid, fallback_pdb_uid_to_user_rid(uid) );
1085         DEBUG(10,("algorithmic_uid_to_sid:  uid (%d) -> SID %s.\n",
1086                 (unsigned int)uid, sid_string_static(psid) ));
1087
1088         return psid;
1089 }
1090
1091 /****************************************************************************
1092  Convert a uid to SID - locally.
1093 ****************************************************************************/
1094
1095 DOM_SID *local_uid_to_sid(DOM_SID *psid, uid_t uid)
1096 {
1097         SAM_ACCOUNT *sampw = NULL;
1098         struct passwd *unix_pw;
1099         BOOL ret;
1100         
1101         unix_pw = sys_getpwuid( uid );
1102
1103         if ( !unix_pw ) {
1104                 DEBUG(4,("local_uid_to_sid: host has no idea of uid %lu\n", (unsigned long)uid));
1105                 return algorithmic_uid_to_sid( psid, uid);
1106         }
1107         
1108         if ( !NT_STATUS_IS_OK(pdb_init_sam(&sampw)) ) {
1109                 DEBUG(0,("local_uid_to_sid: failed to allocate SAM_ACCOUNT object\n"));
1110                 return NULL;
1111         }
1112         
1113         become_root();
1114         ret = pdb_getsampwnam( sampw, unix_pw->pw_name );
1115         unbecome_root();
1116         
1117         if ( ret )
1118                 sid_copy( psid, pdb_get_user_sid(sampw) );
1119         else {
1120                 DEBUG(4,("local_uid_to_sid: User %s [uid == %lu] has no samba account\n",
1121                         unix_pw->pw_name, (unsigned long)uid));
1122
1123                 return algorithmic_uid_to_sid( psid, uid);
1124         }
1125
1126         DEBUG(10,("local_uid_to_sid:  uid (%d) -> SID %s (%s).\n", 
1127                 (unsigned int)uid, sid_string_static(psid), unix_pw->pw_name));
1128         
1129         return psid;
1130 }
1131
1132 /****************************************************************************
1133  Convert a SID to uid - locally.
1134 ****************************************************************************/
1135
1136 BOOL local_sid_to_uid(uid_t *puid, const DOM_SID *psid, enum SID_NAME_USE *name_type)
1137 {
1138         SAM_ACCOUNT *sampw = NULL;      
1139         struct passwd *unix_pw;
1140         const char *user_name;
1141
1142         *name_type = SID_NAME_UNKNOWN;
1143
1144         /*
1145          * We can only convert to a uid if this is our local
1146          * Domain SID (ie. we are the controling authority).
1147          */
1148         if (!sid_check_is_in_our_domain(psid) ) {
1149                 DEBUG(5,("local_sid_to_uid: this SID (%s) is not from our domain\n", sid_string_static(psid)));
1150                 return False;
1151         }
1152
1153         /* lookup the user account */
1154         
1155         if ( !NT_STATUS_IS_OK(pdb_init_sam(&sampw)) ) {
1156                 DEBUG(0,("local_sid_to_uid: Failed to allocate memory for SAM_ACCOUNT object\n"));
1157                 return False;
1158         }
1159                 
1160         become_root();
1161         if ( !pdb_getsampwsid(sampw, psid) ) {
1162                 unbecome_root();
1163                 DEBUG(8,("local_sid_to_uid: Could not find SID %s in passdb\n",
1164                         sid_string_static(psid)));
1165                 return False;
1166         }
1167         unbecome_root();
1168         
1169         user_name = pdb_get_username(sampw);
1170
1171         unix_pw = sys_getpwnam( user_name );
1172
1173         if ( !unix_pw ) {
1174                 DEBUG(0,("local_sid_to_uid: %s found in passdb but getpwnam() return NULL!\n",
1175                         user_name));
1176                 pdb_free_sam( &sampw );
1177                 return False;
1178         }
1179                 
1180         *puid = unix_pw->pw_uid;
1181         
1182         DEBUG(10,("local_sid_to_uid: SID %s -> uid (%u) (%s).\n", sid_string_static(psid),
1183                 (unsigned int)*puid, user_name ));
1184
1185         *name_type = SID_NAME_USER;
1186         
1187         return True;
1188 }
1189
1190 /****************************************************************************
1191  Convert a gid to SID - locally.
1192 ****************************************************************************/
1193
1194 DOM_SID *local_gid_to_sid(DOM_SID *psid, gid_t gid)
1195 {
1196         GROUP_MAP group;
1197         BOOL ret;
1198         
1199         /* we don't need to disable winbindd since the gid is stored in 
1200            the GROUP_MAP object */
1201            
1202         /* done as root since ldap backend requires root to open a connection */
1203
1204         become_root();
1205         ret = pdb_getgrgid( &group, gid );
1206         unbecome_root();
1207         
1208         if ( !ret ) {
1209
1210                 /* fallback to rid mapping if enabled */
1211
1212                 if ( lp_enable_rid_algorithm() ) {
1213                         sid_copy(psid, get_global_sam_sid());
1214                         sid_append_rid(psid, pdb_gid_to_group_rid(gid));
1215
1216                         DEBUG(10,("local_gid_to_sid: Fall back to algorithmic mapping: %u -> %s\n", 
1217                                 (unsigned int)gid, sid_string_static(psid)));
1218                                 
1219                         return psid;
1220                 }
1221                 else
1222                         return NULL;
1223         }
1224         
1225         sid_copy( psid, &group.sid );
1226         
1227         DEBUG(10,("local_gid_to_sid:  gid (%d) -> SID %s.\n", 
1228                 (unsigned int)gid, sid_string_static(psid)));   
1229         
1230         return psid;
1231 }
1232
1233 /****************************************************************************
1234  Convert a SID to gid - locally.
1235 ****************************************************************************/
1236
1237 BOOL local_sid_to_gid(gid_t *pgid, const DOM_SID *psid, enum SID_NAME_USE *name_type)
1238 {
1239         uint32 rid;
1240         GROUP_MAP group;
1241         BOOL ret;
1242
1243         *name_type = SID_NAME_UNKNOWN;
1244
1245         /* This call can enumerate group mappings for foreign sids as well.
1246            So don't check for a match against our domain SID */
1247
1248         /* we don't need to disable winbindd since the gid is stored in 
1249            the GROUP_MAP object */
1250            
1251         become_root();
1252         ret = pdb_getgrsid(&group, *psid);
1253         unbecome_root();
1254         
1255         if ( !ret ) {
1256
1257                 /* fallback to rid mapping if enabled */
1258
1259                 if ( lp_enable_rid_algorithm() ) {
1260
1261                         if (!sid_check_is_in_our_domain(psid) ) {
1262                                 DEBUG(5,("local_sid_to_gid: RID algorithm only supported for our domain (%s is not)\n", sid_string_static(psid)));
1263                                 return False;
1264                         }
1265
1266                         if (!sid_peek_rid(psid, &rid)) {
1267                                 DEBUG(10,("local_sid_to_uid: invalid SID!\n"));
1268                                         return False;
1269                         }
1270
1271                         DEBUG(10,("local_sid_to_gid: Fall back to algorithmic mapping\n"));
1272
1273                         if (fallback_pdb_rid_is_user(rid)) {
1274                                 DEBUG(3, ("local_sid_to_gid: SID %s is *NOT* a group\n", sid_string_static(psid)));
1275                                 return False;
1276                         } else {
1277                                 *pgid = pdb_group_rid_to_gid(rid);
1278                                 DEBUG(10,("local_sid_to_gid: mapping: %s -> %u\n", sid_string_static(psid), (unsigned int)(*pgid)));
1279                                 return True;
1280                         }
1281                 }
1282                 
1283                 return False;
1284         }
1285
1286         *pgid = group.gid;
1287
1288         DEBUG(10,("local_sid_to_gid: SID %s -> gid (%u)\n", sid_string_static(psid),
1289                 (unsigned int)*pgid));
1290
1291         return True;
1292 }
1293
1294 /**********************************************************************
1295  Marshall/unmarshall SAM_ACCOUNT structs.
1296  *********************************************************************/
1297
1298 #define TDB_FORMAT_STRING_V0       "ddddddBBBBBBBBBBBBddBBwdwdBwwd"
1299 #define TDB_FORMAT_STRING_V1       "dddddddBBBBBBBBBBBBddBBwdwdBwwd"
1300
1301 /**********************************************************************
1302  Intialize a SAM_ACCOUNT struct from a BYTE buffer of size len
1303  *********************************************************************/
1304
1305 BOOL init_sam_from_buffer(SAM_ACCOUNT *sampass, uint8 *buf, uint32 buflen)
1306 {
1307         return(init_sam_from_buffer_v1(sampass, buf, buflen));
1308 }
1309
1310 /**********************************************************************
1311  Intialize a BYTE buffer from a SAM_ACCOUNT struct
1312  *********************************************************************/
1313
1314 uint32 init_buffer_from_sam (uint8 **buf, const SAM_ACCOUNT *sampass, BOOL size_only)
1315 {
1316         return(init_buffer_from_sam_v1(buf, sampass, size_only));
1317 }
1318
1319
1320 BOOL init_sam_from_buffer_v0(SAM_ACCOUNT *sampass, uint8 *buf, uint32 buflen)
1321 {
1322
1323         /* times are stored as 32bit integer
1324            take care on system with 64bit wide time_t
1325            --SSS */
1326         uint32  logon_time,
1327                 logoff_time,
1328                 kickoff_time,
1329                 pass_last_set_time,
1330                 pass_can_change_time,
1331                 pass_must_change_time;
1332         char *username;
1333         char *domain;
1334         char *nt_username;
1335         char *dir_drive;
1336         char *unknown_str;
1337         char *munged_dial;
1338         char *fullname;
1339         char *homedir;
1340         char *logon_script;
1341         char *profile_path;
1342         char *acct_desc;
1343         char *workstations;
1344         uint32  username_len, domain_len, nt_username_len,
1345                 dir_drive_len, unknown_str_len, munged_dial_len,
1346                 fullname_len, homedir_len, logon_script_len,
1347                 profile_path_len, acct_desc_len, workstations_len;
1348                 
1349         uint32  user_rid, group_rid, remove_me, hours_len, unknown_6;
1350         uint16  acct_ctrl, logon_divs;
1351         uint16  bad_password_count, logon_count;
1352         uint8   *hours;
1353         static uint8    *lm_pw_ptr, *nt_pw_ptr;
1354         uint32          len = 0;
1355         uint32          lm_pw_len, nt_pw_len, hourslen;
1356         BOOL ret = True;
1357         
1358         if(sampass == NULL || buf == NULL) {
1359                 DEBUG(0, ("init_sam_from_buffer: NULL parameters found!\n"));
1360                 return False;
1361         }
1362                                                                         
1363         /* unpack the buffer into variables */
1364         len = tdb_unpack ((char *)buf, buflen, TDB_FORMAT_STRING_V0,
1365                 &logon_time,
1366                 &logoff_time,
1367                 &kickoff_time,
1368                 &pass_last_set_time,
1369                 &pass_can_change_time,
1370                 &pass_must_change_time,
1371                 &username_len, &username,
1372                 &domain_len, &domain,
1373                 &nt_username_len, &nt_username,
1374                 &fullname_len, &fullname,
1375                 &homedir_len, &homedir,
1376                 &dir_drive_len, &dir_drive,
1377                 &logon_script_len, &logon_script,
1378                 &profile_path_len, &profile_path,
1379                 &acct_desc_len, &acct_desc,
1380                 &workstations_len, &workstations,
1381                 &unknown_str_len, &unknown_str,
1382                 &munged_dial_len, &munged_dial,
1383                 &user_rid,
1384                 &group_rid,
1385                 &lm_pw_len, &lm_pw_ptr,
1386                 &nt_pw_len, &nt_pw_ptr,
1387                 &acct_ctrl,
1388                 &remove_me, /* remove on the next TDB_FORMAT upgarde */
1389                 &logon_divs,
1390                 &hours_len,
1391                 &hourslen, &hours,
1392                 &bad_password_count,
1393                 &logon_count,
1394                 &unknown_6);
1395                 
1396         if (len == (uint32) -1)  {
1397                 ret = False;
1398                 goto done;
1399         }
1400
1401         pdb_set_logon_time(sampass, logon_time, PDB_SET);
1402         pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
1403         pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
1404         pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
1405         pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
1406         pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
1407
1408         pdb_set_username(sampass, username, PDB_SET); 
1409         pdb_set_domain(sampass, domain, PDB_SET);
1410         pdb_set_nt_username(sampass, nt_username, PDB_SET);
1411         pdb_set_fullname(sampass, fullname, PDB_SET);
1412
1413         if (homedir) {
1414                 pdb_set_homedir(sampass, homedir, PDB_SET);
1415         }
1416         else {
1417                 pdb_set_homedir(sampass, 
1418                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_home()),
1419                         PDB_DEFAULT);
1420         }
1421
1422         if (dir_drive)  
1423                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
1424         else {
1425                 pdb_set_dir_drive(sampass, 
1426                         talloc_sub_basic(sampass->mem_ctx,  username, lp_logon_drive()),
1427                         PDB_DEFAULT);
1428         }
1429
1430         if (logon_script) 
1431                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
1432         else {
1433                 pdb_set_logon_script(sampass, 
1434                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_script()),
1435                         PDB_DEFAULT);
1436         }
1437         
1438         if (profile_path) {     
1439                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
1440         } else {
1441                 pdb_set_profile_path(sampass, 
1442                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_path()),
1443                         PDB_DEFAULT);
1444         }
1445
1446         pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
1447         pdb_set_workstations(sampass, workstations, PDB_SET);
1448         pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
1449
1450         if (lm_pw_ptr && lm_pw_len == LM_HASH_LEN) {
1451                 if (!pdb_set_lanman_passwd(sampass, lm_pw_ptr, PDB_SET)) {
1452                         ret = False;
1453                         goto done;
1454                 }
1455         }
1456
1457         if (nt_pw_ptr && nt_pw_len == NT_HASH_LEN) {
1458                 if (!pdb_set_nt_passwd(sampass, nt_pw_ptr, PDB_SET)) {
1459                         ret = False;
1460                         goto done;
1461                 }
1462         }
1463
1464         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
1465         pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
1466         pdb_set_hours_len(sampass, hours_len, PDB_SET);
1467         pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
1468         pdb_set_logon_count(sampass, logon_count, PDB_SET);
1469         pdb_set_unknown_6(sampass, unknown_6, PDB_SET);
1470         pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
1471         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
1472         pdb_set_hours(sampass, hours, PDB_SET);
1473
1474 done:
1475
1476         SAFE_FREE(username);
1477         SAFE_FREE(domain);
1478         SAFE_FREE(nt_username);
1479         SAFE_FREE(fullname);
1480         SAFE_FREE(homedir);
1481         SAFE_FREE(dir_drive);
1482         SAFE_FREE(logon_script);
1483         SAFE_FREE(profile_path);
1484         SAFE_FREE(acct_desc);
1485         SAFE_FREE(workstations);
1486         SAFE_FREE(munged_dial);
1487         SAFE_FREE(unknown_str);
1488         SAFE_FREE(hours);
1489
1490         return ret;
1491 }
1492
1493
1494 uint32 init_buffer_from_sam_v0 (uint8 **buf, const SAM_ACCOUNT *sampass, BOOL size_only)
1495 {
1496         size_t len, buflen;
1497
1498         /* times are stored as 32bit integer
1499            take care on system with 64bit wide time_t
1500            --SSS */
1501         uint32  logon_time,
1502                 logoff_time,
1503                 kickoff_time,
1504                 pass_last_set_time,
1505                 pass_can_change_time,
1506                 pass_must_change_time;
1507
1508         uint32  user_rid, group_rid;
1509
1510         const char *username;
1511         const char *domain;
1512         const char *nt_username;
1513         const char *dir_drive;
1514         const char *unknown_str;
1515         const char *munged_dial;
1516         const char *fullname;
1517         const char *homedir;
1518         const char *logon_script;
1519         const char *profile_path;
1520         const char *acct_desc;
1521         const char *workstations;
1522         uint32  username_len, domain_len, nt_username_len,
1523                 dir_drive_len, unknown_str_len, munged_dial_len,
1524                 fullname_len, homedir_len, logon_script_len,
1525                 profile_path_len, acct_desc_len, workstations_len;
1526
1527         const uint8 *lm_pw;
1528         const uint8 *nt_pw;
1529         uint32  lm_pw_len = 16;
1530         uint32  nt_pw_len = 16;
1531
1532         /* do we have a valid SAM_ACCOUNT pointer? */
1533         if (sampass == NULL) {
1534                 DEBUG(0, ("init_buffer_from_sam: SAM_ACCOUNT is NULL!\n"));
1535                 return -1;
1536         }
1537         
1538         *buf = NULL;
1539         buflen = 0;
1540
1541         logon_time = (uint32)pdb_get_logon_time(sampass);
1542         logoff_time = (uint32)pdb_get_logoff_time(sampass);
1543         kickoff_time = (uint32)pdb_get_kickoff_time(sampass);
1544         pass_can_change_time = (uint32)pdb_get_pass_can_change_time(sampass);
1545         pass_must_change_time = (uint32)pdb_get_pass_must_change_time(sampass);
1546         pass_last_set_time = (uint32)pdb_get_pass_last_set_time(sampass);
1547
1548         user_rid = pdb_get_user_rid(sampass);
1549         group_rid = pdb_get_group_rid(sampass);
1550
1551         username = pdb_get_username(sampass);
1552         if (username)
1553                 username_len = strlen(username) +1;
1554         else
1555                 username_len = 0;
1556
1557         domain = pdb_get_domain(sampass);
1558         if (domain)
1559                 domain_len = strlen(domain) +1;
1560         else
1561                 domain_len = 0;
1562
1563         nt_username = pdb_get_nt_username(sampass);
1564         if (nt_username)
1565                 nt_username_len = strlen(nt_username) +1;
1566         else
1567                 nt_username_len = 0;
1568
1569         fullname = pdb_get_fullname(sampass);
1570         if (fullname)
1571                 fullname_len = strlen(fullname) +1;
1572         else
1573                 fullname_len = 0;
1574
1575         /*
1576          * Only updates fields which have been set (not defaults from smb.conf)
1577          */
1578
1579         if (!IS_SAM_DEFAULT(sampass, PDB_DRIVE)) 
1580                 dir_drive = pdb_get_dir_drive(sampass);
1581         else
1582                 dir_drive = NULL;
1583         if (dir_drive)
1584                 dir_drive_len = strlen(dir_drive) +1;
1585         else
1586                 dir_drive_len = 0;
1587
1588         if (!IS_SAM_DEFAULT(sampass, PDB_SMBHOME))
1589                 homedir = pdb_get_homedir(sampass);
1590         else
1591                 homedir = NULL;
1592         if (homedir)
1593                 homedir_len = strlen(homedir) +1;
1594         else
1595                 homedir_len = 0;
1596
1597         if (!IS_SAM_DEFAULT(sampass, PDB_LOGONSCRIPT))
1598                 logon_script = pdb_get_logon_script(sampass);
1599         else
1600                 logon_script = NULL;
1601         if (logon_script)
1602                 logon_script_len = strlen(logon_script) +1;
1603         else
1604                 logon_script_len = 0;
1605
1606         if (!IS_SAM_DEFAULT(sampass, PDB_PROFILE))
1607                 profile_path = pdb_get_profile_path(sampass);
1608         else
1609                 profile_path = NULL;
1610         if (profile_path)
1611                 profile_path_len = strlen(profile_path) +1;
1612         else
1613                 profile_path_len = 0;
1614         
1615         lm_pw = pdb_get_lanman_passwd(sampass);
1616         if (!lm_pw)
1617                 lm_pw_len = 0;
1618         
1619         nt_pw = pdb_get_nt_passwd(sampass);
1620         if (!nt_pw)
1621                 nt_pw_len = 0;
1622                 
1623         acct_desc = pdb_get_acct_desc(sampass);
1624         if (acct_desc)
1625                 acct_desc_len = strlen(acct_desc) +1;
1626         else
1627                 acct_desc_len = 0;
1628
1629         workstations = pdb_get_workstations(sampass);
1630         if (workstations)
1631                 workstations_len = strlen(workstations) +1;
1632         else
1633                 workstations_len = 0;
1634
1635         unknown_str = NULL;
1636         unknown_str_len = 0;
1637
1638         munged_dial = pdb_get_munged_dial(sampass);
1639         if (munged_dial)
1640                 munged_dial_len = strlen(munged_dial) +1;
1641         else
1642                 munged_dial_len = 0;    
1643                 
1644         /* one time to get the size needed */
1645         len = tdb_pack(NULL, 0,  TDB_FORMAT_STRING_V0,
1646                 logon_time,
1647                 logoff_time,
1648                 kickoff_time,
1649                 pass_last_set_time,
1650                 pass_can_change_time,
1651                 pass_must_change_time,
1652                 username_len, username,
1653                 domain_len, domain,
1654                 nt_username_len, nt_username,
1655                 fullname_len, fullname,
1656                 homedir_len, homedir,
1657                 dir_drive_len, dir_drive,
1658                 logon_script_len, logon_script,
1659                 profile_path_len, profile_path,
1660                 acct_desc_len, acct_desc,
1661                 workstations_len, workstations,
1662                 unknown_str_len, unknown_str,
1663                 munged_dial_len, munged_dial,
1664                 user_rid,
1665                 group_rid,
1666                 lm_pw_len, lm_pw,
1667                 nt_pw_len, nt_pw,
1668                 pdb_get_acct_ctrl(sampass),
1669                 0, /* was: fileds_present, to be removed on format change */
1670                 pdb_get_logon_divs(sampass),
1671                 pdb_get_hours_len(sampass),
1672                 MAX_HOURS_LEN, pdb_get_hours(sampass),
1673                 pdb_get_bad_password_count(sampass),
1674                 pdb_get_logon_count(sampass),
1675                 pdb_get_unknown_6(sampass));
1676
1677
1678         if (size_only)
1679                 return buflen;
1680
1681         /* malloc the space needed */
1682         if ( (*buf=(uint8*)malloc(len)) == NULL) {
1683                 DEBUG(0,("init_buffer_from_sam: Unable to malloc() memory for buffer!\n"));
1684                 return (-1);
1685         }
1686         
1687         /* now for the real call to tdb_pack() */
1688         buflen = tdb_pack((char *)*buf, len,  TDB_FORMAT_STRING_V0,
1689                 logon_time,
1690                 logoff_time,
1691                 kickoff_time,
1692                 pass_last_set_time,
1693                 pass_can_change_time,
1694                 pass_must_change_time,
1695                 username_len, username,
1696                 domain_len, domain,
1697                 nt_username_len, nt_username,
1698                 fullname_len, fullname,
1699                 homedir_len, homedir,
1700                 dir_drive_len, dir_drive,
1701                 logon_script_len, logon_script,
1702                 profile_path_len, profile_path,
1703                 acct_desc_len, acct_desc,
1704                 workstations_len, workstations,
1705                 unknown_str_len, unknown_str,
1706                 munged_dial_len, munged_dial,
1707                 user_rid,
1708                 group_rid,
1709                 lm_pw_len, lm_pw,
1710                 nt_pw_len, nt_pw,
1711                 pdb_get_acct_ctrl(sampass),
1712                 0, /* was: fileds_present, to be removed on format change */
1713                 pdb_get_logon_divs(sampass),
1714                 pdb_get_hours_len(sampass),
1715                 MAX_HOURS_LEN, pdb_get_hours(sampass),
1716                 pdb_get_bad_password_count(sampass),
1717                 pdb_get_logon_count(sampass),
1718                 pdb_get_unknown_6(sampass));
1719         
1720         
1721         /* check to make sure we got it correct */
1722         if (buflen != len) {
1723                 DEBUG(0, ("init_buffer_from_sam: somthing odd is going on here: bufflen (%lu) != len (%lu) in tdb_pack operations!\n", 
1724                           (unsigned long)buflen, (unsigned long)len));  
1725                 /* error */
1726                 SAFE_FREE (*buf);
1727                 return (-1);
1728         }
1729
1730         return (buflen);
1731 }
1732
1733
1734 BOOL init_sam_from_buffer_v1(SAM_ACCOUNT *sampass, uint8 *buf, uint32 buflen)
1735 {
1736
1737         /* times are stored as 32bit integer
1738            take care on system with 64bit wide time_t
1739            --SSS */
1740         uint32  logon_time,
1741                 logoff_time,
1742                 kickoff_time,
1743                 bad_password_time,
1744                 pass_last_set_time,
1745                 pass_can_change_time,
1746                 pass_must_change_time;
1747         char *username;
1748         char *domain;
1749         char *nt_username;
1750         char *dir_drive;
1751         char *unknown_str;
1752         char *munged_dial;
1753         char *fullname;
1754         char *homedir;
1755         char *logon_script;
1756         char *profile_path;
1757         char *acct_desc;
1758         char *workstations;
1759         uint32  username_len, domain_len, nt_username_len,
1760                 dir_drive_len, unknown_str_len, munged_dial_len,
1761                 fullname_len, homedir_len, logon_script_len,
1762                 profile_path_len, acct_desc_len, workstations_len;
1763                 
1764         uint32  user_rid, group_rid, remove_me, hours_len, unknown_6;
1765         uint16  acct_ctrl, logon_divs;
1766         uint16  bad_password_count, logon_count;
1767         uint8   *hours;
1768         static uint8    *lm_pw_ptr, *nt_pw_ptr;
1769         uint32          len = 0;
1770         uint32          lm_pw_len, nt_pw_len, hourslen;
1771         BOOL ret = True;
1772         
1773         if(sampass == NULL || buf == NULL) {
1774                 DEBUG(0, ("init_sam_from_buffer: NULL parameters found!\n"));
1775                 return False;
1776         }
1777                                                                         
1778         /* unpack the buffer into variables */
1779         len = tdb_unpack ((char *)buf, buflen, TDB_FORMAT_STRING_V1,
1780                 &logon_time,
1781                 &logoff_time,
1782                 &kickoff_time,
1783                 &bad_password_time,
1784                 &pass_last_set_time,
1785                 &pass_can_change_time,
1786                 &pass_must_change_time,
1787                 &username_len, &username,
1788                 &domain_len, &domain,
1789                 &nt_username_len, &nt_username,
1790                 &fullname_len, &fullname,
1791                 &homedir_len, &homedir,
1792                 &dir_drive_len, &dir_drive,
1793                 &logon_script_len, &logon_script,
1794                 &profile_path_len, &profile_path,
1795                 &acct_desc_len, &acct_desc,
1796                 &workstations_len, &workstations,
1797                 &unknown_str_len, &unknown_str,
1798                 &munged_dial_len, &munged_dial,
1799                 &user_rid,
1800                 &group_rid,
1801                 &lm_pw_len, &lm_pw_ptr,
1802                 &nt_pw_len, &nt_pw_ptr,
1803                 &acct_ctrl,
1804                 &remove_me,
1805                 &logon_divs,
1806                 &hours_len,
1807                 &hourslen, &hours,
1808                 &bad_password_count,
1809                 &logon_count,
1810                 &unknown_6);
1811                 
1812         if (len == (uint32) -1)  {
1813                 ret = False;
1814                 goto done;
1815         }
1816
1817         pdb_set_logon_time(sampass, logon_time, PDB_SET);
1818         pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
1819         pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
1820         pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
1821         pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
1822         pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
1823         pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
1824
1825         pdb_set_username(sampass, username, PDB_SET); 
1826         pdb_set_domain(sampass, domain, PDB_SET);
1827         pdb_set_nt_username(sampass, nt_username, PDB_SET);
1828         pdb_set_fullname(sampass, fullname, PDB_SET);
1829
1830         if (homedir) {
1831                 pdb_set_homedir(sampass, homedir, PDB_SET);
1832         }
1833         else {
1834                 pdb_set_homedir(sampass, 
1835                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_home()),
1836                         PDB_DEFAULT);
1837         }
1838
1839         if (dir_drive)  
1840                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
1841         else {
1842                 pdb_set_dir_drive(sampass, 
1843                         talloc_sub_basic(sampass->mem_ctx,  username, lp_logon_drive()),
1844                         PDB_DEFAULT);
1845         }
1846
1847         if (logon_script) 
1848                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
1849         else {
1850                 pdb_set_logon_script(sampass, 
1851                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_script()),
1852                         PDB_DEFAULT);
1853         }
1854         
1855         if (profile_path) {     
1856                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
1857         } else {
1858                 pdb_set_profile_path(sampass, 
1859                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_path()),
1860                         PDB_DEFAULT);
1861         }
1862
1863         pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
1864         pdb_set_workstations(sampass, workstations, PDB_SET);
1865         pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
1866
1867         if (lm_pw_ptr && lm_pw_len == LM_HASH_LEN) {
1868                 if (!pdb_set_lanman_passwd(sampass, lm_pw_ptr, PDB_SET)) {
1869                         ret = False;
1870                         goto done;
1871                 }
1872         }
1873
1874         if (nt_pw_ptr && nt_pw_len == NT_HASH_LEN) {
1875                 if (!pdb_set_nt_passwd(sampass, nt_pw_ptr, PDB_SET)) {
1876                         ret = False;
1877                         goto done;
1878                 }
1879         }
1880
1881         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
1882         pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
1883         pdb_set_hours_len(sampass, hours_len, PDB_SET);
1884         pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
1885         pdb_set_logon_count(sampass, logon_count, PDB_SET);
1886         pdb_set_unknown_6(sampass, unknown_6, PDB_SET);
1887         pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
1888         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
1889         pdb_set_hours(sampass, hours, PDB_SET);
1890
1891 done:
1892
1893         SAFE_FREE(lm_pw_ptr);
1894         SAFE_FREE(nt_pw_ptr);
1895         SAFE_FREE(username);
1896         SAFE_FREE(domain);
1897         SAFE_FREE(nt_username);
1898         SAFE_FREE(fullname);
1899         SAFE_FREE(homedir);
1900         SAFE_FREE(dir_drive);
1901         SAFE_FREE(logon_script);
1902         SAFE_FREE(profile_path);
1903         SAFE_FREE(acct_desc);
1904         SAFE_FREE(workstations);
1905         SAFE_FREE(munged_dial);
1906         SAFE_FREE(unknown_str);
1907         SAFE_FREE(hours);
1908
1909         return ret;
1910 }
1911
1912
1913 uint32 init_buffer_from_sam_v1 (uint8 **buf, const SAM_ACCOUNT *sampass, BOOL size_only)
1914 {
1915         size_t len, buflen;
1916
1917         /* times are stored as 32bit integer
1918            take care on system with 64bit wide time_t
1919            --SSS */
1920         uint32  logon_time,
1921                 logoff_time,
1922                 kickoff_time,
1923                 bad_password_time,
1924                 pass_last_set_time,
1925                 pass_can_change_time,
1926                 pass_must_change_time;
1927
1928         uint32  user_rid, group_rid;
1929
1930         const char *username;
1931         const char *domain;
1932         const char *nt_username;
1933         const char *dir_drive;
1934         const char *unknown_str;
1935         const char *munged_dial;
1936         const char *fullname;
1937         const char *homedir;
1938         const char *logon_script;
1939         const char *profile_path;
1940         const char *acct_desc;
1941         const char *workstations;
1942         uint32  username_len, domain_len, nt_username_len,
1943                 dir_drive_len, unknown_str_len, munged_dial_len,
1944                 fullname_len, homedir_len, logon_script_len,
1945                 profile_path_len, acct_desc_len, workstations_len;
1946
1947         const uint8 *lm_pw;
1948         const uint8 *nt_pw;
1949         uint32  lm_pw_len = 16;
1950         uint32  nt_pw_len = 16;
1951
1952         /* do we have a valid SAM_ACCOUNT pointer? */
1953         if (sampass == NULL) {
1954                 DEBUG(0, ("init_buffer_from_sam: SAM_ACCOUNT is NULL!\n"));
1955                 return -1;
1956         }
1957         
1958         *buf = NULL;
1959         buflen = 0;
1960
1961         logon_time = (uint32)pdb_get_logon_time(sampass);
1962         logoff_time = (uint32)pdb_get_logoff_time(sampass);
1963         kickoff_time = (uint32)pdb_get_kickoff_time(sampass);
1964         bad_password_time = (uint32)pdb_get_bad_password_time(sampass);
1965         pass_can_change_time = (uint32)pdb_get_pass_can_change_time(sampass);
1966         pass_must_change_time = (uint32)pdb_get_pass_must_change_time(sampass);
1967         pass_last_set_time = (uint32)pdb_get_pass_last_set_time(sampass);
1968
1969         user_rid = pdb_get_user_rid(sampass);
1970         group_rid = pdb_get_group_rid(sampass);
1971
1972         username = pdb_get_username(sampass);
1973         if (username)
1974                 username_len = strlen(username) +1;
1975         else
1976                 username_len = 0;
1977
1978         domain = pdb_get_domain(sampass);
1979         if (domain)
1980                 domain_len = strlen(domain) +1;
1981         else
1982                 domain_len = 0;
1983
1984         nt_username = pdb_get_nt_username(sampass);
1985         if (nt_username)
1986                 nt_username_len = strlen(nt_username) +1;
1987         else
1988                 nt_username_len = 0;
1989
1990         fullname = pdb_get_fullname(sampass);
1991         if (fullname)
1992                 fullname_len = strlen(fullname) +1;
1993         else
1994                 fullname_len = 0;
1995
1996         /*
1997          * Only updates fields which have been set (not defaults from smb.conf)
1998          */
1999
2000         if (!IS_SAM_DEFAULT(sampass, PDB_DRIVE)) 
2001                 dir_drive = pdb_get_dir_drive(sampass);
2002         else
2003                 dir_drive = NULL;
2004         if (dir_drive)
2005                 dir_drive_len = strlen(dir_drive) +1;
2006         else
2007                 dir_drive_len = 0;
2008
2009         if (!IS_SAM_DEFAULT(sampass, PDB_SMBHOME))
2010                 homedir = pdb_get_homedir(sampass);
2011         else
2012                 homedir = NULL;
2013         if (homedir)
2014                 homedir_len = strlen(homedir) +1;
2015         else
2016                 homedir_len = 0;
2017
2018         if (!IS_SAM_DEFAULT(sampass, PDB_LOGONSCRIPT))
2019                 logon_script = pdb_get_logon_script(sampass);
2020         else
2021                 logon_script = NULL;
2022         if (logon_script)
2023                 logon_script_len = strlen(logon_script) +1;
2024         else
2025                 logon_script_len = 0;
2026
2027         if (!IS_SAM_DEFAULT(sampass, PDB_PROFILE))
2028                 profile_path = pdb_get_profile_path(sampass);
2029         else
2030                 profile_path = NULL;
2031         if (profile_path)
2032                 profile_path_len = strlen(profile_path) +1;
2033         else
2034                 profile_path_len = 0;
2035         
2036         lm_pw = pdb_get_lanman_passwd(sampass);
2037         if (!lm_pw)
2038                 lm_pw_len = 0;
2039         
2040         nt_pw = pdb_get_nt_passwd(sampass);
2041         if (!nt_pw)
2042                 nt_pw_len = 0;
2043                 
2044         acct_desc = pdb_get_acct_desc(sampass);
2045         if (acct_desc)
2046                 acct_desc_len = strlen(acct_desc) +1;
2047         else
2048                 acct_desc_len = 0;
2049
2050         workstations = pdb_get_workstations(sampass);
2051         if (workstations)
2052                 workstations_len = strlen(workstations) +1;
2053         else
2054                 workstations_len = 0;
2055
2056         unknown_str = NULL;
2057         unknown_str_len = 0;
2058
2059         munged_dial = pdb_get_munged_dial(sampass);
2060         if (munged_dial)
2061                 munged_dial_len = strlen(munged_dial) +1;
2062         else
2063                 munged_dial_len = 0;    
2064                 
2065         /* one time to get the size needed */
2066         len = tdb_pack(NULL, 0,  TDB_FORMAT_STRING_V1,
2067                 logon_time,
2068                 logoff_time,
2069                 kickoff_time,
2070                 bad_password_time,
2071                 pass_last_set_time,
2072                 pass_can_change_time,
2073                 pass_must_change_time,
2074                 username_len, username,
2075                 domain_len, domain,
2076                 nt_username_len, nt_username,
2077                 fullname_len, fullname,
2078                 homedir_len, homedir,
2079                 dir_drive_len, dir_drive,
2080                 logon_script_len, logon_script,
2081                 profile_path_len, profile_path,
2082                 acct_desc_len, acct_desc,
2083                 workstations_len, workstations,
2084                 unknown_str_len, unknown_str,
2085                 munged_dial_len, munged_dial,
2086                 user_rid,
2087                 group_rid,
2088                 lm_pw_len, lm_pw,
2089                 nt_pw_len, nt_pw,
2090                 pdb_get_acct_ctrl(sampass),
2091                 0,
2092                 pdb_get_logon_divs(sampass),
2093                 pdb_get_hours_len(sampass),
2094                 MAX_HOURS_LEN, pdb_get_hours(sampass),
2095                 pdb_get_bad_password_count(sampass),
2096                 pdb_get_logon_count(sampass),
2097                 pdb_get_unknown_6(sampass));
2098
2099
2100         if (size_only)
2101                 return buflen;
2102
2103         /* malloc the space needed */
2104         if ( (*buf=(uint8*)malloc(len)) == NULL) {
2105                 DEBUG(0,("init_buffer_from_sam: Unable to malloc() memory for buffer!\n"));
2106                 return (-1);
2107         }
2108         
2109         /* now for the real call to tdb_pack() */
2110         buflen = tdb_pack((char *)*buf, len,  TDB_FORMAT_STRING_V1,
2111                 logon_time,
2112                 logoff_time,
2113                 kickoff_time,
2114                 bad_password_time,
2115                 pass_last_set_time,
2116                 pass_can_change_time,
2117                 pass_must_change_time,
2118                 username_len, username,
2119                 domain_len, domain,
2120                 nt_username_len, nt_username,
2121                 fullname_len, fullname,
2122                 homedir_len, homedir,
2123                 dir_drive_len, dir_drive,
2124                 logon_script_len, logon_script,
2125                 profile_path_len, profile_path,
2126                 acct_desc_len, acct_desc,
2127                 workstations_len, workstations,
2128                 unknown_str_len, unknown_str,
2129                 munged_dial_len, munged_dial,
2130                 user_rid,
2131                 group_rid,
2132                 lm_pw_len, lm_pw,
2133                 nt_pw_len, nt_pw,
2134                 pdb_get_acct_ctrl(sampass),
2135                 0,
2136                 pdb_get_logon_divs(sampass),
2137                 pdb_get_hours_len(sampass),
2138                 MAX_HOURS_LEN, pdb_get_hours(sampass),
2139                 pdb_get_bad_password_count(sampass),
2140                 pdb_get_logon_count(sampass),
2141                 pdb_get_unknown_6(sampass));
2142         
2143         
2144         /* check to make sure we got it correct */
2145         if (buflen != len) {
2146                 DEBUG(0, ("init_buffer_from_sam: somthing odd is going on here: bufflen (%lu) != len (%lu) in tdb_pack operations!\n", 
2147                           (unsigned long)buflen, (unsigned long)len));  
2148                 /* error */
2149                 SAFE_FREE (*buf);
2150                 return (-1);
2151         }
2152
2153         return (buflen);
2154 }
2155
2156
2157 /**********************************************************************
2158 **********************************************************************/
2159
2160 static BOOL get_free_ugid_range(uint32 *low, uint32 *high)
2161 {
2162         uid_t u_low, u_high;
2163         gid_t g_low, g_high;
2164
2165         if (!lp_idmap_uid(&u_low, &u_high) || !lp_idmap_gid(&g_low, &g_high)) {
2166                 return False;
2167         }
2168         
2169         *low  = (u_low < g_low)   ? u_low  : g_low;
2170         *high = (u_high < g_high) ? u_high : g_high;
2171         
2172         return True;
2173 }
2174
2175 /******************************************************************
2176  Get the the non-algorithmic RID range if idmap range are defined
2177 ******************************************************************/
2178
2179 BOOL get_free_rid_range(uint32 *low, uint32 *high)
2180 {
2181         uint32 id_low, id_high;
2182
2183         if (!lp_enable_rid_algorithm()) {
2184                 *low = BASE_RID;
2185                 *high = (uint32)-1;
2186         }
2187
2188         if (!get_free_ugid_range(&id_low, &id_high)) {
2189                 return False;
2190         }
2191
2192         *low = fallback_pdb_uid_to_user_rid(id_low);
2193         if (fallback_pdb_user_rid_to_uid((uint32)-1) < id_high) {
2194                 *high = (uint32)-1;
2195         } else {
2196                 *high = fallback_pdb_uid_to_user_rid(id_high);
2197         }
2198
2199         return True;
2200 }
2201
2202 /*********************************************************************
2203  Update the bad password count checking the AP_RESET_COUNT_TIME 
2204 *********************************************************************/
2205
2206 BOOL pdb_update_bad_password_count(SAM_ACCOUNT *sampass, BOOL *updated)
2207 {
2208         time_t LastBadPassword;
2209         uint16 BadPasswordCount;
2210         uint32 resettime; 
2211
2212         if (!sampass) return False;
2213         
2214         BadPasswordCount = pdb_get_bad_password_count(sampass);
2215         if (!BadPasswordCount) {
2216                 DEBUG(9, ("No bad password attempts.\n"));
2217                 return True;
2218         }
2219
2220         if (!account_policy_get(AP_RESET_COUNT_TIME, &resettime)) {
2221                 DEBUG(0, ("pdb_update_bad_password_count: account_policy_get failed.\n"));
2222                 return False;
2223         }
2224
2225         /* First, check if there is a reset time to compare */
2226         if ((resettime == (uint32) -1) || (resettime == 0)) {
2227                 DEBUG(9, ("No reset time, can't reset bad pw count\n"));
2228                 return True;
2229         }
2230
2231         LastBadPassword = pdb_get_bad_password_time(sampass);
2232         DEBUG(7, ("LastBadPassword=%d, resettime=%d, current time=%d.\n", 
2233                    (uint32) LastBadPassword, resettime, (uint32)time(NULL)));
2234         if (time(NULL) > (LastBadPassword + (time_t)resettime*60)){
2235                 pdb_set_bad_password_count(sampass, 0, PDB_CHANGED);
2236                 pdb_set_bad_password_time(sampass, 0, PDB_CHANGED);
2237                 if (updated) *updated = True;
2238         }
2239
2240         return True;
2241 }
2242
2243 /*********************************************************************
2244  Update the ACB_AUTOLOCK flag checking the AP_LOCK_ACCOUNT_DURATION 
2245 *********************************************************************/
2246
2247 BOOL pdb_update_autolock_flag(SAM_ACCOUNT *sampass, BOOL *updated)
2248 {
2249         uint32 duration;
2250         time_t LastBadPassword;
2251
2252         if (!sampass) return False;
2253  
2254         if (!(pdb_get_acct_ctrl(sampass) & ACB_AUTOLOCK)) {
2255                 DEBUG(9, ("Account not autolocked, no check needed\n"));
2256                 return True;
2257         }
2258
2259         if (!account_policy_get(AP_LOCK_ACCOUNT_DURATION, &duration)) {
2260                 DEBUG(0, ("pdb_update_autolock_flag: account_policy_get failed.\n"));
2261                 return False;
2262         }
2263
2264         /* First, check if there is a duration to compare */
2265         if ((duration == (uint32) -1)  || (duration == 0)) {
2266                 DEBUG(9, ("No reset duration, can't reset autolock\n"));
2267                 return True;
2268         }
2269                       
2270         LastBadPassword = pdb_get_bad_password_time(sampass);
2271         DEBUG(7, ("LastBadPassword=%d, duration=%d, current time =%d.\n",
2272                   (uint32)LastBadPassword, duration*60, (uint32)time(NULL)));
2273         if ((time(NULL) > (LastBadPassword + (time_t) duration * 60))) {
2274                 pdb_set_acct_ctrl(sampass,
2275                                   pdb_get_acct_ctrl(sampass) & ~ACB_AUTOLOCK,
2276                                   PDB_CHANGED);
2277                 pdb_set_bad_password_count(sampass, 0, PDB_CHANGED);
2278                 pdb_set_bad_password_time(sampass, 0, PDB_CHANGED);
2279                 if (updated) *updated = True;
2280         }
2281         
2282         return True;
2283 }
2284
2285 /*********************************************************************
2286  Increment the bad_password_count 
2287 *********************************************************************/
2288
2289 BOOL pdb_increment_bad_password_count(SAM_ACCOUNT *sampass)
2290 {
2291         uint32 account_policy_lockout;
2292         BOOL autolock_updated = False, badpw_updated = False;
2293
2294         if (!sampass)
2295                 return False;
2296
2297         /* Retrieve the account lockout policy */
2298         if (!account_policy_get(AP_BAD_ATTEMPT_LOCKOUT,
2299                                 &account_policy_lockout)) {
2300                 DEBUG(0, ("pdb_increment_bad_password_count: account_policy_get failed.\n"));
2301                 return False;
2302         }
2303
2304         /* If there is no policy, we don't need to continue checking */
2305         if (!account_policy_lockout) {
2306                 DEBUG(9, ("No lockout policy, don't track bad passwords\n"));
2307                 return True;
2308         }
2309
2310         /* Check if the autolock needs to be cleared */
2311         if (!pdb_update_autolock_flag(sampass, &autolock_updated))
2312                 return False;
2313
2314         /* Check if the badpw count needs to be reset */
2315         if (!pdb_update_bad_password_count(sampass, &badpw_updated))
2316                 return False;
2317
2318         /*
2319           Ok, now we can assume that any resetting that needs to be 
2320           done has been done, and just get on with incrementing
2321           and autolocking if necessary
2322         */
2323
2324         pdb_set_bad_password_count(sampass, 
2325                                    pdb_get_bad_password_count(sampass)+1,
2326                                    PDB_CHANGED);
2327         pdb_set_bad_password_time(sampass, time(NULL), PDB_CHANGED);
2328
2329
2330         if (pdb_get_bad_password_count(sampass) < account_policy_lockout) 
2331                 return True;
2332
2333         if (!pdb_set_acct_ctrl(sampass,
2334                                pdb_get_acct_ctrl(sampass) | ACB_AUTOLOCK,
2335                                PDB_CHANGED)) {
2336                 DEBUG(1, ("pdb_increment_bad_password_count:failed to set 'autolock' flag. \n")); 
2337                 return False;
2338         }
2339
2340         return True;
2341 }
2342
2343 BOOL get_sids_from_priv(const char *privname, DOM_SID **sids, int *num)
2344 {
2345         char *sids_string;
2346         char *s;
2347         fstring tok;
2348
2349         if (!pdb_get_privilege_entry(privname, &sids_string))
2350                 return False;
2351
2352         s = sids_string;
2353
2354         while (next_token(&s, tok, ",", sizeof(tok))) {
2355                 DOM_SID sid;
2356                 DEBUG(10, ("converting SID %s\n", tok));
2357
2358                 if (!string_to_sid(&sid, tok)) {
2359                         DEBUG(3, ("Could not convert SID\n"));
2360                         continue;
2361                 }
2362
2363                 add_sid_to_array(&sid, sids, num);
2364         }
2365
2366         SAFE_FREE(sids_string);
2367         return True;
2368 }
2369
2370 BOOL get_priv_for_sid(const DOM_SID *sid, PRIVILEGE_SET *priv)
2371 {
2372         extern PRIVS privs[];
2373         int i;
2374         for (i=1; i<PRIV_ALL_INDEX-1; i++) {
2375                 DOM_SID *sids;
2376                 int j, num;
2377
2378                 if (!get_sids_from_priv(privs[i].priv, &sids, &num))
2379                         continue;
2380
2381                 for (j=0; j<num; j++) {
2382                         if (sid_compare(sid, &sids[j]) == 0)
2383                                 add_privilege_by_name(priv, privs[i].priv);
2384                 }
2385                 SAFE_FREE(sids);
2386         }
2387         return True;
2388 }