more access fixes for group enumeration in LDAP; bug 281
[metze/samba/wip.git] / source3 / passdb / passdb.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Password and authentication handling
4    Copyright (C) Jeremy Allison                 1996-2001
5    Copyright (C) Luke Kenneth Casson Leighton   1996-1998
6    Copyright (C) Gerald (Jerry) Carter          2000-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.unknown_3 = 0x00ffffff;   /* don't know */
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  Alloc 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  Alloc 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 /*************************************************************
194  Initialises a struct sam_passwd with sane values.
195  ************************************************************/
196
197 NTSTATUS pdb_fill_sam_pw(SAM_ACCOUNT *sam_account, const struct passwd *pwd)
198 {
199         NTSTATUS ret;
200
201         if (!pwd) {
202                 return NT_STATUS_UNSUCCESSFUL;
203         }
204
205         pdb_fill_default_sam(sam_account);
206
207         pdb_set_username(sam_account, pwd->pw_name, PDB_SET);
208         pdb_set_fullname(sam_account, pwd->pw_gecos, PDB_SET);
209
210         pdb_set_unix_homedir(sam_account, pwd->pw_dir, PDB_SET);
211
212         pdb_set_domain (sam_account, get_global_sam_name(), PDB_DEFAULT);
213         
214         /* When we get a proper uid -> SID and SID -> uid allocation
215            mechinism, we should call it here.  
216            
217            We can't just set this to 0 or allow it only to be filled
218            in when added to the backend, because the user's SID 
219            may already be in security descriptors etc.
220            
221            -- abartlet 11-May-02
222         */
223
224         ret = pdb_set_sam_sids(sam_account, pwd);
225         if (!NT_STATUS_IS_OK(ret)) return ret;
226
227         /* check if this is a user account or a machine account */
228         if (pwd->pw_name[strlen(pwd->pw_name)-1] != '$')
229         {
230                 pdb_set_profile_path(sam_account, 
231                                      talloc_sub_specified((sam_account)->mem_ctx, 
232                                                             lp_logon_path(), 
233                                                             pwd->pw_name, global_myname(), 
234                                                             pwd->pw_uid, pwd->pw_gid), 
235                                      PDB_DEFAULT);
236                 
237                 pdb_set_homedir(sam_account, 
238                                 talloc_sub_specified((sam_account)->mem_ctx, 
239                                                        lp_logon_home(),
240                                                        pwd->pw_name, global_myname(), 
241                                                        pwd->pw_uid, pwd->pw_gid),
242                                 PDB_DEFAULT);
243                 
244                 pdb_set_dir_drive(sam_account, 
245                                   talloc_sub_specified((sam_account)->mem_ctx, 
246                                                          lp_logon_drive(),
247                                                          pwd->pw_name, global_myname(), 
248                                                          pwd->pw_uid, pwd->pw_gid),
249                                   PDB_DEFAULT);
250                 
251                 pdb_set_logon_script(sam_account, 
252                                      talloc_sub_specified((sam_account)->mem_ctx, 
253                                                             lp_logon_script(),
254                                                             pwd->pw_name, global_myname(), 
255                                                             pwd->pw_uid, pwd->pw_gid), 
256                                      PDB_DEFAULT);
257                 if (!pdb_set_acct_ctrl(sam_account, ACB_NORMAL, PDB_DEFAULT)) {
258                         DEBUG(1, ("Failed to set 'normal account' flags for user %s.\n", pwd->pw_name));
259                         return NT_STATUS_UNSUCCESSFUL;
260                 }
261         } else {
262                 if (!pdb_set_acct_ctrl(sam_account, ACB_WSTRUST, PDB_DEFAULT)) {
263                         DEBUG(1, ("Failed to set 'trusted workstation account' flags for user %s.\n", pwd->pw_name));
264                         return NT_STATUS_UNSUCCESSFUL;
265                 }
266         }
267         return NT_STATUS_OK;
268 }
269
270
271 /*************************************************************
272  Initialises a struct sam_passwd with sane values.
273  ************************************************************/
274
275 NTSTATUS pdb_init_sam_pw(SAM_ACCOUNT **new_sam_acct, const struct passwd *pwd)
276 {
277         NTSTATUS nt_status;
278
279         if (!pwd) {
280                 new_sam_acct = NULL;
281                 return NT_STATUS_INVALID_PARAMETER;
282         }
283
284         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam(new_sam_acct))) {
285                 new_sam_acct = NULL;
286                 return nt_status;
287         }
288
289         if (!NT_STATUS_IS_OK(nt_status = pdb_fill_sam_pw(*new_sam_acct, pwd))) {
290                 pdb_free_sam(new_sam_acct);
291                 new_sam_acct = NULL;
292                 return nt_status;
293         }
294
295         return NT_STATUS_OK;
296 }
297
298
299 /*************************************************************
300  Initialises a SAM_ACCOUNT ready to add a new account, based
301  on the UNIX user.  Pass in a RID if you have one
302  ************************************************************/
303
304 NTSTATUS pdb_init_sam_new(SAM_ACCOUNT **new_sam_acct, const char *username,
305                           uint32 rid)
306 {
307         NTSTATUS        nt_status = NT_STATUS_NO_MEMORY;
308         struct passwd   *pwd;
309         BOOL            ret;
310         
311         pwd = Get_Pwnam(username);
312
313         if (!pwd) 
314                 return NT_STATUS_NO_SUCH_USER;
315         
316         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_pw(new_sam_acct, pwd))) {
317                 *new_sam_acct = NULL;
318                 return nt_status;
319         }
320         
321         /* see if we need to generate a new rid using the 2.2 algorithm */
322         if ( rid == 0 && lp_enable_rid_algorithm() ) {
323                 DEBUG(10,("pdb_init_sam_new: no RID specified.  Generating one via old algorithm\n"));
324                 rid = fallback_pdb_uid_to_user_rid(pwd->pw_uid);
325         }
326         
327         /* set the new SID */
328         
329         ret = pdb_set_user_sid_from_rid( *new_sam_acct, rid, PDB_SET );
330          
331         return (ret ? NT_STATUS_OK : NT_STATUS_NO_SUCH_USER);
332 }
333
334
335 /**
336  * Free the contets of the SAM_ACCOUNT, but not the structure.
337  *
338  * Also wipes the LM and NT hashes and plaintext password from 
339  * memory.
340  *
341  * @param user SAM_ACCOUNT to free members of.
342  **/
343
344 static void pdb_free_sam_contents(SAM_ACCOUNT *user)
345 {
346
347         /* Kill off sensitive data.  Free()ed by the
348            talloc mechinism */
349
350         data_blob_clear_free(&(user->private.lm_pw));
351         data_blob_clear_free(&(user->private.nt_pw));
352         if (user->private.plaintext_pw!=NULL)
353                 memset(user->private.plaintext_pw,'\0',strlen(user->private.plaintext_pw));
354
355         if (user->private.backend_private_data && user->private.backend_private_data_free_fn) {
356                 user->private.backend_private_data_free_fn(&user->private.backend_private_data);
357         }
358 }
359
360
361 /************************************************************
362  Reset the SAM_ACCOUNT and free the NT/LM hashes.
363  ***********************************************************/
364
365 NTSTATUS pdb_reset_sam(SAM_ACCOUNT *user)
366 {
367         if (user == NULL) {
368                 DEBUG(0,("pdb_reset_sam: SAM_ACCOUNT was NULL\n"));
369 #if 0
370                 smb_panic("NULL pointer passed to pdb_free_sam\n");
371 #endif
372                 return NT_STATUS_UNSUCCESSFUL;
373         }
374         
375         pdb_free_sam_contents(user);
376
377         pdb_fill_default_sam(user);
378
379         return NT_STATUS_OK;
380 }
381
382
383 /************************************************************
384  Free the SAM_ACCOUNT and the member pointers.
385  ***********************************************************/
386
387 NTSTATUS pdb_free_sam(SAM_ACCOUNT **user)
388 {
389         if (*user == NULL) {
390                 DEBUG(0,("pdb_free_sam: SAM_ACCOUNT was NULL\n"));
391 #if 0
392                 smb_panic("NULL pointer passed to pdb_free_sam\n");
393 #endif
394                 return NT_STATUS_UNSUCCESSFUL;
395         }
396
397         pdb_free_sam_contents(*user);
398         
399         if ((*user)->free_fn) {
400                 (*user)->free_fn(user);
401         }
402
403         return NT_STATUS_OK;    
404 }
405
406 /**************************************************************************
407  * This function will take care of all the steps needed to correctly
408  * allocate and set the user SID, please do use this function to create new
409  * users, messing with SIDs is not good.
410  *
411  * account_data must be provided initialized, pwd may be null.
412  *                                                                      SSS
413  ***************************************************************************/
414
415 NTSTATUS pdb_set_sam_sids(SAM_ACCOUNT *account_data, const struct passwd *pwd)
416 {
417         const char *guest_account = lp_guestaccount();
418         GROUP_MAP map;
419         BOOL ret;
420         
421         if (!account_data || !pwd) {
422                 return NT_STATUS_INVALID_PARAMETER;
423         }
424
425         /* this is a hack this thing should not be set
426            this way --SSS */
427         if (!(guest_account && *guest_account)) {
428                 DEBUG(1, ("NULL guest account!?!?\n"));
429                 return NT_STATUS_UNSUCCESSFUL;
430         } else {
431                 /* Ensure this *must* be set right */
432                 if (strcmp(pwd->pw_name, guest_account) == 0) {
433                         if (!pdb_set_user_sid_from_rid(account_data, DOMAIN_USER_RID_GUEST, PDB_DEFAULT)) {
434                                 return NT_STATUS_UNSUCCESSFUL;
435                         }
436                         if (!pdb_set_group_sid_from_rid(account_data, DOMAIN_GROUP_RID_GUESTS, PDB_DEFAULT)) {
437                                 return NT_STATUS_UNSUCCESSFUL;
438                         }
439                         return NT_STATUS_OK;
440                 }
441         }
442
443         if (!pdb_set_user_sid_from_rid(account_data, fallback_pdb_uid_to_user_rid(pwd->pw_uid), PDB_SET)) {
444                 DEBUG(0,("Can't set User SID from RID!\n"));
445                 return NT_STATUS_INVALID_PARAMETER;
446         }
447         
448         /* call the mapping code here */
449         become_root();
450         ret = pdb_getgrgid(&map, pwd->pw_gid);
451         unbecome_root();
452         
453         if( ret ) {
454                 if (!pdb_set_group_sid(account_data, &map.sid, PDB_SET)){
455                         DEBUG(0,("Can't set Group SID!\n"));
456                         return NT_STATUS_INVALID_PARAMETER;
457                 }
458         } 
459         else {
460                 if (!pdb_set_group_sid_from_rid(account_data, pdb_gid_to_group_rid(pwd->pw_gid), PDB_SET)) {
461                         DEBUG(0,("Can't set Group SID\n"));
462                         return NT_STATUS_INVALID_PARAMETER;
463                 }
464         }
465
466         return NT_STATUS_OK;
467 }
468
469 /**********************************************************
470  Encode the account control bits into a string.
471  length = length of string to encode into (including terminating
472  null). length *MUST BE MORE THAN 2* !
473  **********************************************************/
474
475 char *pdb_encode_acct_ctrl(uint16 acct_ctrl, size_t length)
476 {
477         static fstring acct_str;
478         size_t i = 0;
479
480         acct_str[i++] = '[';
481
482         if (acct_ctrl & ACB_PWNOTREQ ) acct_str[i++] = 'N';
483         if (acct_ctrl & ACB_DISABLED ) acct_str[i++] = 'D';
484         if (acct_ctrl & ACB_HOMDIRREQ) acct_str[i++] = 'H';
485         if (acct_ctrl & ACB_TEMPDUP  ) acct_str[i++] = 'T'; 
486         if (acct_ctrl & ACB_NORMAL   ) acct_str[i++] = 'U';
487         if (acct_ctrl & ACB_MNS      ) acct_str[i++] = 'M';
488         if (acct_ctrl & ACB_WSTRUST  ) acct_str[i++] = 'W';
489         if (acct_ctrl & ACB_SVRTRUST ) acct_str[i++] = 'S';
490         if (acct_ctrl & ACB_AUTOLOCK ) acct_str[i++] = 'L';
491         if (acct_ctrl & ACB_PWNOEXP  ) acct_str[i++] = 'X';
492         if (acct_ctrl & ACB_DOMTRUST ) acct_str[i++] = 'I';
493
494         for ( ; i < length - 2 ; i++ )
495                 acct_str[i] = ' ';
496
497         i = length - 2;
498         acct_str[i++] = ']';
499         acct_str[i++] = '\0';
500
501         return acct_str;
502 }     
503
504 /**********************************************************
505  Decode the account control bits from a string.
506  **********************************************************/
507
508 uint16 pdb_decode_acct_ctrl(const char *p)
509 {
510         uint16 acct_ctrl = 0;
511         BOOL finished = False;
512
513         /*
514          * Check if the account type bits have been encoded after the
515          * NT password (in the form [NDHTUWSLXI]).
516          */
517
518         if (*p != '[')
519                 return 0;
520
521         for (p++; *p && !finished; p++) {
522                 switch (*p) {
523                         case 'N': { acct_ctrl |= ACB_PWNOTREQ ; break; /* 'N'o password. */ }
524                         case 'D': { acct_ctrl |= ACB_DISABLED ; break; /* 'D'isabled. */ }
525                         case 'H': { acct_ctrl |= ACB_HOMDIRREQ; break; /* 'H'omedir required. */ }
526                         case 'T': { acct_ctrl |= ACB_TEMPDUP  ; break; /* 'T'emp account. */ } 
527                         case 'U': { acct_ctrl |= ACB_NORMAL   ; break; /* 'U'ser account (normal). */ } 
528                         case 'M': { acct_ctrl |= ACB_MNS      ; break; /* 'M'NS logon user account. What is this ? */ } 
529                         case 'W': { acct_ctrl |= ACB_WSTRUST  ; break; /* 'W'orkstation account. */ } 
530                         case 'S': { acct_ctrl |= ACB_SVRTRUST ; break; /* 'S'erver account. */ } 
531                         case 'L': { acct_ctrl |= ACB_AUTOLOCK ; break; /* 'L'ocked account. */ } 
532                         case 'X': { acct_ctrl |= ACB_PWNOEXP  ; break; /* No 'X'piry on password */ } 
533                         case 'I': { acct_ctrl |= ACB_DOMTRUST ; break; /* 'I'nterdomain trust account. */ }
534             case ' ': { break; }
535                         case ':':
536                         case '\n':
537                         case '\0': 
538                         case ']':
539                         default:  { finished = True; }
540                 }
541         }
542
543         return acct_ctrl;
544 }
545
546 /*************************************************************
547  Routine to set 32 hex password characters from a 16 byte array.
548 **************************************************************/
549
550 void pdb_sethexpwd(char *p, const unsigned char *pwd, uint16 acct_ctrl)
551 {
552         if (pwd != NULL) {
553                 int i;
554                 for (i = 0; i < 16; i++)
555                         slprintf(&p[i*2], 3, "%02X", pwd[i]);
556         } else {
557                 if (acct_ctrl & ACB_PWNOTREQ)
558                         safe_strcpy(p, "NO PASSWORDXXXXXXXXXXXXXXXXXXXXX", 33);
559                 else
560                         safe_strcpy(p, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 33);
561         }
562 }
563
564 /*************************************************************
565  Routine to get the 32 hex characters and turn them
566  into a 16 byte array.
567 **************************************************************/
568
569 BOOL pdb_gethexpwd(const char *p, unsigned char *pwd)
570 {
571         int i;
572         unsigned char   lonybble, hinybble;
573         const char      *hexchars = "0123456789ABCDEF";
574         char           *p1, *p2;
575         
576         if (!p)
577                 return (False);
578         
579         for (i = 0; i < 32; i += 2) {
580                 hinybble = toupper(p[i]);
581                 lonybble = toupper(p[i + 1]);
582
583                 p1 = strchr(hexchars, hinybble);
584                 p2 = strchr(hexchars, lonybble);
585
586                 if (!p1 || !p2)
587                         return (False);
588
589                 hinybble = PTR_DIFF(p1, hexchars);
590                 lonybble = PTR_DIFF(p2, hexchars);
591
592                 pwd[i / 2] = (hinybble << 4) | lonybble;
593         }
594         return (True);
595 }
596
597 int algorithmic_rid_base(void)
598 {
599         static int rid_offset = 0;
600
601         if (rid_offset != 0)
602                 return rid_offset;
603
604         rid_offset = lp_algorithmic_rid_base();
605
606         if (rid_offset < BASE_RID) {  
607                 /* Try to prevent admin foot-shooting, we can't put algorithmic
608                    rids below 1000, that's the 'well known RIDs' on NT */
609                 DEBUG(0, ("'algorithmic rid base' must be equal to or above %ld\n", BASE_RID));
610                 rid_offset = BASE_RID;
611         }
612         if (rid_offset & 1) {
613                 DEBUG(0, ("algorithmic rid base must be even\n"));
614                 rid_offset += 1;
615         }
616         return rid_offset;
617 }
618
619 /*******************************************************************
620  Converts NT user RID to a UNIX uid.
621  ********************************************************************/
622
623 uid_t fallback_pdb_user_rid_to_uid(uint32 user_rid)
624 {
625         int rid_offset = algorithmic_rid_base();
626         return (uid_t)(((user_rid & (~USER_RID_TYPE)) - rid_offset)/RID_MULTIPLIER);
627 }
628
629 /*******************************************************************
630  converts UNIX uid to an NT User RID.
631  ********************************************************************/
632
633 uint32 fallback_pdb_uid_to_user_rid(uid_t uid)
634 {
635         int rid_offset = algorithmic_rid_base();
636         return (((((uint32)uid)*RID_MULTIPLIER) + rid_offset) | USER_RID_TYPE);
637 }
638
639 /*******************************************************************
640  Converts NT group RID to a UNIX gid.
641  ********************************************************************/
642
643 gid_t pdb_group_rid_to_gid(uint32 group_rid)
644 {
645         int rid_offset = algorithmic_rid_base();
646         return (gid_t)(((group_rid & (~GROUP_RID_TYPE))- rid_offset)/RID_MULTIPLIER);
647 }
648
649 /*******************************************************************
650  converts NT Group RID to a UNIX uid.
651  
652  warning: you must not call that function only
653  you must do a call to the group mapping first.
654  there is not anymore a direct link between the gid and the rid.
655  ********************************************************************/
656
657 uint32 pdb_gid_to_group_rid(gid_t gid)
658 {
659         int rid_offset = algorithmic_rid_base();
660         return (((((uint32)gid)*RID_MULTIPLIER) + rid_offset) | GROUP_RID_TYPE);
661 }
662
663 /*******************************************************************
664  Decides if a RID is a well known RID.
665  ********************************************************************/
666
667 static BOOL pdb_rid_is_well_known(uint32 rid)
668 {
669         /* Not using rid_offset here, because this is the actual
670            NT fixed value (1000) */
671
672         return (rid < BASE_RID);
673 }
674
675 /*******************************************************************
676  Decides if a RID is a user or group RID.
677  ********************************************************************/
678
679 BOOL fallback_pdb_rid_is_user(uint32 rid)
680 {
681   /* lkcl i understand that NT attaches an enumeration to a RID
682    * such that it can be identified as either a user, group etc
683    * type.  there are 5 such categories, and they are documented.
684    */
685         /* However, they are not in the RID, just somthing you can query
686            seperatly.  Sorry luke :-) */
687
688    if(pdb_rid_is_well_known(rid)) {
689       /*
690        * The only well known user RIDs are DOMAIN_USER_RID_ADMIN
691        * and DOMAIN_USER_RID_GUEST.
692        */
693      if(rid == DOMAIN_USER_RID_ADMIN || rid == DOMAIN_USER_RID_GUEST)
694        return True;
695    } else if((rid & RID_TYPE_MASK) == USER_RID_TYPE) {
696      return True;
697    }
698    return False;
699 }
700
701 /*******************************************************************
702  Convert a rid into a name. Used in the lookup SID rpc.
703  ********************************************************************/
704
705 BOOL local_lookup_sid(DOM_SID *sid, char *name, enum SID_NAME_USE *psid_name_use)
706 {
707         uint32 rid;
708         SAM_ACCOUNT *sam_account = NULL;
709         GROUP_MAP map;
710
711         if (!sid_peek_check_rid(get_global_sam_sid(), sid, &rid)){
712                 DEBUG(0,("local_lookup_sid: sid_peek_check_rid return False! SID: %s\n",
713                         sid_string_static(&map.sid)));
714                 return False;
715         }       
716         *psid_name_use = SID_NAME_UNKNOWN;
717         
718         DEBUG(5,("local_lookup_sid: looking up RID %u.\n", (unsigned int)rid));
719         
720         if (rid == DOMAIN_USER_RID_ADMIN) {
721                 const char **admin_list = lp_admin_users(-1);
722                 *psid_name_use = SID_NAME_USER;
723                 if (admin_list) {
724                         const char *p = *admin_list;
725                         if(!next_token(&p, name, NULL, sizeof(fstring)))
726                                 fstrcpy(name, "Administrator");
727                 } else {
728                         fstrcpy(name, "Administrator");
729                 }
730                 return True;
731         }
732
733         if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_account))) {
734                 return False;
735         }
736         
737         /* see if the passdb can help us with the name of the user */
738
739         become_root();
740         if (pdb_getsampwsid(sam_account, sid)) {
741                 unbecome_root();
742                 fstrcpy(name, pdb_get_username(sam_account));
743                 *psid_name_use = SID_NAME_USER;
744
745                 pdb_free_sam(&sam_account);
746                         
747                 return True;
748         }
749         unbecome_root();
750         pdb_free_sam(&sam_account);
751                 
752         if (pdb_getgrsid(&map, *sid)) {
753                 if (map.gid!=(gid_t)-1) {
754                         DEBUG(5,("local_lookup_sid: mapped group %s to gid %u\n", map.nt_name, (unsigned int)map.gid));
755                 } else {
756                         DEBUG(5,("local_lookup_sid: mapped group %s to no unix gid.  Returning name.\n", map.nt_name));
757                 }
758
759                 fstrcpy(name, map.nt_name);
760                 *psid_name_use = map.sid_name_use;
761                 return True;
762         }
763
764         if (fallback_pdb_rid_is_user(rid)) {
765                 uid_t uid;
766                 struct passwd *pw = NULL;
767
768                 DEBUG(5, ("assuming RID %u is a user\n", (unsigned)rid));
769
770                 uid = fallback_pdb_user_rid_to_uid(rid);
771                 pw = sys_getpwuid( uid );
772                 
773                 DEBUG(5,("local_lookup_sid: looking up uid %u %s\n", (unsigned int)uid,
774                          pw ? "succeeded" : "failed" ));
775                          
776                 if ( !pw )
777                         fstr_sprintf(name, "unix_user.%u", (unsigned int)uid);  
778                 else 
779                         fstrcpy( name, pw->pw_name );
780                         
781                 DEBUG(5,("local_lookup_sid: found user %s for rid %u\n", name,
782                          (unsigned int)rid ));
783                          
784                 *psid_name_use = SID_NAME_USER;
785                 
786                 return ( pw != NULL );
787         } else {
788                 gid_t gid;
789                 struct group *gr; 
790                         
791                 DEBUG(5, ("assuming RID %u is a group\n", (unsigned)rid));
792
793                 gid = pdb_group_rid_to_gid(rid);
794                 gr = getgrgid(gid);
795                         
796                 *psid_name_use = SID_NAME_ALIAS;
797                         
798                 DEBUG(5,("local_lookup_sid: looking up gid %u %s\n", (unsigned int)gid,
799                          gr ? "succeeded" : "failed" ));
800                         
801                 if( !gr )
802                         fstr_sprintf(name, "unix_group.%u", (unsigned int)gid);
803                 else
804                         fstrcpy( name, gr->gr_name);
805                         
806                 DEBUG(5,("local_lookup_sid: found group %s for rid %u\n", name,
807                          (unsigned int)rid ));
808                 
809                 /* assume fallback groups aer domain global groups */
810                 
811                 *psid_name_use = SID_NAME_DOM_GRP;
812                 
813                 return ( gr != NULL );
814         }
815 }
816
817 /*******************************************************************
818  Convert a name into a SID. Used in the lookup name rpc.
819  ********************************************************************/
820
821 BOOL local_lookup_name(const char *c_user, DOM_SID *psid, enum SID_NAME_USE *psid_name_use)
822 {
823         extern DOM_SID global_sid_World_Domain;
824         DOM_SID local_sid;
825         fstring user;
826         SAM_ACCOUNT *sam_account = NULL;
827         struct group *grp;
828         GROUP_MAP map;
829                 
830         *psid_name_use = SID_NAME_UNKNOWN;
831
832         /*
833          * user may be quoted a const string, and map_username and
834          * friends can modify it. Make a modifiable copy. JRA.
835          */
836
837         fstrcpy(user, c_user);
838
839         sid_copy(&local_sid, get_global_sam_sid());
840
841         /*
842          * Special case for MACHINE\Everyone. Map to the world_sid.
843          */
844
845         if(strequal(user, "Everyone")) {
846                 sid_copy( psid, &global_sid_World_Domain);
847                 sid_append_rid(psid, 0);
848                 *psid_name_use = SID_NAME_ALIAS;
849                 return True;
850         }
851
852         (void)map_username(user);
853
854         if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_account))) {
855                 return False;
856         }
857         
858         /* BEGIN ROOT BLOCK */
859         
860         become_root();
861         if (pdb_getsampwnam(sam_account, user)) {
862                 unbecome_root();
863                 sid_copy(psid, pdb_get_user_sid(sam_account));
864                 *psid_name_use = SID_NAME_USER;
865                 
866                 pdb_free_sam(&sam_account);
867                 return True;
868         }
869
870         pdb_free_sam(&sam_account);
871
872         /*
873          * Maybe it was a group ?
874          */
875
876         /* check if it's a mapped group */
877         if (pdb_getgrnam(&map, user)) {
878                 /* yes it's a mapped group */
879                 sid_copy(&local_sid, &map.sid);
880                 *psid_name_use = map.sid_name_use;
881         } else {
882                 /* it's not a mapped group */
883                 grp = getgrnam(user);
884                 if(!grp) {
885                         unbecome_root();                /* ---> exit form block */      
886                         return False;
887                 }
888                 
889                 /* 
890                  *check if it's mapped, if it is reply it doesn't exist
891                  *
892                  * that's to prevent this case:
893                  *
894                  * unix group ug is mapped to nt group ng
895                  * someone does a lookup on ug
896                  * we must not reply as it doesn't "exist" anymore
897                  * for NT. For NT only ng exists.
898                  * JFM, 30/11/2001
899                  */
900                 
901                 if (pdb_getgrgid(&map, grp->gr_gid)){
902                         unbecome_root();                /* ---> exit form block */
903                         return False;
904                 }
905                 
906                 sid_append_rid( &local_sid, pdb_gid_to_group_rid(grp->gr_gid));
907                 *psid_name_use = SID_NAME_ALIAS;
908         }
909         unbecome_root();
910         /* END ROOT BLOCK */
911
912         sid_copy( psid, &local_sid);
913
914         return True;
915 }
916
917 /*************************************************************
918  Change a password entry in the local smbpasswd file.
919  *************************************************************/
920
921 BOOL local_password_change(const char *user_name, int local_flags,
922                            const char *new_passwd, 
923                            char *err_str, size_t err_str_len,
924                            char *msg_str, size_t msg_str_len)
925 {
926         SAM_ACCOUNT     *sam_pass=NULL;
927         uint16 other_acb;
928
929         *err_str = '\0';
930         *msg_str = '\0';
931
932         /* Get the smb passwd entry for this user */
933         pdb_init_sam(&sam_pass);
934
935         become_root();
936         if(!pdb_getsampwnam(sam_pass, user_name)) {
937                 unbecome_root();
938                 pdb_free_sam(&sam_pass);
939                 
940                 if ((local_flags & LOCAL_ADD_USER) || (local_flags & LOCAL_DELETE_USER)) {
941                         /* Might not exist in /etc/passwd.  Use rid algorithm here */
942                         if (!NT_STATUS_IS_OK(pdb_init_sam_new(&sam_pass, user_name, 0))) {
943                                 slprintf(err_str, err_str_len-1, "Failed to initialise SAM_ACCOUNT for user %s.\n", user_name);
944                                 return False;
945                         }
946                 } else {
947                         slprintf(err_str, err_str_len-1,"Failed to find entry for user %s.\n", user_name);
948                         return False;
949                 }
950         } else {
951                 unbecome_root();
952                 /* the entry already existed */
953                 local_flags &= ~LOCAL_ADD_USER;
954         }
955
956         /* the 'other' acb bits not being changed here */
957         other_acb =  (pdb_get_acct_ctrl(sam_pass) & (!(ACB_WSTRUST|ACB_DOMTRUST|ACB_SVRTRUST|ACB_NORMAL)));
958         if (local_flags & LOCAL_TRUST_ACCOUNT) {
959                 if (!pdb_set_acct_ctrl(sam_pass, ACB_WSTRUST | other_acb, PDB_CHANGED) ) {
960                         slprintf(err_str, err_str_len - 1, "Failed to set 'trusted workstation account' flags for user %s.\n", user_name);
961                         pdb_free_sam(&sam_pass);
962                         return False;
963                 }
964         } else if (local_flags & LOCAL_INTERDOM_ACCOUNT) {
965                 if (!pdb_set_acct_ctrl(sam_pass, ACB_DOMTRUST | other_acb, PDB_CHANGED)) {
966                         slprintf(err_str, err_str_len - 1, "Failed to set 'domain trust account' flags for user %s.\n", user_name);
967                         pdb_free_sam(&sam_pass);
968                         return False;
969                 }
970         } else {
971                 if (!pdb_set_acct_ctrl(sam_pass, ACB_NORMAL | other_acb, PDB_CHANGED)) {
972                         slprintf(err_str, err_str_len - 1, "Failed to set 'normal account' flags for user %s.\n", user_name);
973                         pdb_free_sam(&sam_pass);
974                         return False;
975                 }
976         }
977
978         /*
979          * We are root - just write the new password
980          * and the valid last change time.
981          */
982
983         if (local_flags & LOCAL_DISABLE_USER) {
984                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_DISABLED, PDB_CHANGED)) {
985                         slprintf(err_str, err_str_len-1, "Failed to set 'disabled' flag for user %s.\n", user_name);
986                         pdb_free_sam(&sam_pass);
987                         return False;
988                 }
989         } else if (local_flags & LOCAL_ENABLE_USER) {
990                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
991                         slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
992                         pdb_free_sam(&sam_pass);
993                         return False;
994                 }
995         }
996         
997         if (local_flags & LOCAL_SET_NO_PASSWORD) {
998                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_PWNOTREQ, PDB_CHANGED)) {
999                         slprintf(err_str, err_str_len-1, "Failed to set 'no password required' flag for user %s.\n", user_name);
1000                         pdb_free_sam(&sam_pass);
1001                         return False;
1002                 }
1003         } else if (local_flags & LOCAL_SET_PASSWORD) {
1004                 /*
1005                  * If we're dealing with setting a completely empty user account
1006                  * ie. One with a password of 'XXXX', but not set disabled (like
1007                  * an account created from scratch) then if the old password was
1008                  * 'XX's then getsmbpwent will have set the ACB_DISABLED flag.
1009                  * We remove that as we're giving this user their first password
1010                  * and the decision hasn't really been made to disable them (ie.
1011                  * don't create them disabled). JRA.
1012                  */
1013                 if ((pdb_get_lanman_passwd(sam_pass)==NULL) && (pdb_get_acct_ctrl(sam_pass)&ACB_DISABLED)) {
1014                         if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
1015                                 slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
1016                                 pdb_free_sam(&sam_pass);
1017                                 return False;
1018                         }
1019                 }
1020                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_PWNOTREQ), PDB_CHANGED)) {
1021                         slprintf(err_str, err_str_len-1, "Failed to unset 'no password required' flag for user %s.\n", user_name);
1022                         pdb_free_sam(&sam_pass);
1023                         return False;
1024                 }
1025                 
1026                 if (!pdb_set_plaintext_passwd (sam_pass, new_passwd)) {
1027                         slprintf(err_str, err_str_len-1, "Failed to set password for user %s.\n", user_name);
1028                         pdb_free_sam(&sam_pass);
1029                         return False;
1030                 }
1031         }       
1032
1033         if (local_flags & LOCAL_ADD_USER) {
1034                 if (pdb_add_sam_account(sam_pass)) {
1035                         slprintf(msg_str, msg_str_len-1, "Added user %s.\n", user_name);
1036                         pdb_free_sam(&sam_pass);
1037                         return True;
1038                 } else {
1039                         slprintf(err_str, err_str_len-1, "Failed to add entry for user %s.\n", user_name);
1040                         pdb_free_sam(&sam_pass);
1041                         return False;
1042                 }
1043         } else if (local_flags & LOCAL_DELETE_USER) {
1044                 if (!pdb_delete_sam_account(sam_pass)) {
1045                         slprintf(err_str,err_str_len-1, "Failed to delete entry for user %s.\n", user_name);
1046                         pdb_free_sam(&sam_pass);
1047                         return False;
1048                 }
1049                 slprintf(msg_str, msg_str_len-1, "Deleted user %s.\n", user_name);
1050         } else {
1051                 if(!pdb_update_sam_account(sam_pass)) {
1052                         slprintf(err_str, err_str_len-1, "Failed to modify entry for user %s.\n", user_name);
1053                         pdb_free_sam(&sam_pass);
1054                         return False;
1055                 }
1056                 if(local_flags & LOCAL_DISABLE_USER)
1057                         slprintf(msg_str, msg_str_len-1, "Disabled user %s.\n", user_name);
1058                 else if (local_flags & LOCAL_ENABLE_USER)
1059                         slprintf(msg_str, msg_str_len-1, "Enabled user %s.\n", user_name);
1060                 else if (local_flags & LOCAL_SET_NO_PASSWORD)
1061                         slprintf(msg_str, msg_str_len-1, "User %s password set to none.\n", user_name);
1062         }
1063
1064         pdb_free_sam(&sam_pass);
1065         return True;
1066 }
1067
1068 /****************************************************************************
1069  Convert a uid to SID - algorithmic.
1070 ****************************************************************************/
1071
1072 static DOM_SID *algorithmic_uid_to_sid(DOM_SID *psid, uid_t uid)
1073 {
1074         if ( !lp_enable_rid_algorithm() )
1075                 return NULL;
1076
1077         DEBUG(8,("algorithmic_uid_to_sid: falling back to RID algorithm\n"));
1078         sid_copy( psid, get_global_sam_sid() );
1079         sid_append_rid( psid, fallback_pdb_uid_to_user_rid(uid) );
1080         DEBUG(10,("algorithmic_uid_to_sid:  uid (%d) -> SID %s.\n",
1081                 (unsigned int)uid, sid_string_static(psid) ));
1082
1083         return psid;
1084 }
1085
1086 /****************************************************************************
1087  Convert a uid to SID - locally.
1088 ****************************************************************************/
1089
1090 DOM_SID *local_uid_to_sid(DOM_SID *psid, uid_t uid)
1091 {
1092         SAM_ACCOUNT *sampw = NULL;
1093         struct passwd *unix_pw;
1094         BOOL ret;
1095         
1096         unix_pw = sys_getpwuid( uid );
1097
1098         if ( !unix_pw ) {
1099                 DEBUG(4,("local_uid_to_sid: host has no idea of uid %lu\n", (unsigned long)uid));
1100                 return algorithmic_uid_to_sid( psid, uid);
1101         }
1102         
1103         if ( !NT_STATUS_IS_OK(pdb_init_sam(&sampw)) ) {
1104                 DEBUG(0,("local_uid_to_sid: failed to allocate SAM_ACCOUNT object\n"));
1105                 return NULL;
1106         }
1107         
1108         become_root();
1109         ret = pdb_getsampwnam( sampw, unix_pw->pw_name );
1110         unbecome_root();
1111         
1112         if ( ret )
1113                 sid_copy( psid, pdb_get_user_sid(sampw) );
1114         else {
1115                 DEBUG(4,("local_uid_to_sid: User %s [uid == %lu] has no samba account\n",
1116                         unix_pw->pw_name, (unsigned long)uid));
1117
1118                 return algorithmic_uid_to_sid( psid, uid);
1119         }
1120
1121         DEBUG(10,("local_uid_to_sid:  uid (%d) -> SID %s (%s).\n", 
1122                 (unsigned int)uid, sid_string_static(psid), unix_pw->pw_name));
1123         
1124         return psid;
1125 }
1126
1127 /****************************************************************************
1128  Convert a SID to uid - locally.
1129 ****************************************************************************/
1130
1131 BOOL local_sid_to_uid(uid_t *puid, const DOM_SID *psid, enum SID_NAME_USE *name_type)
1132 {
1133         SAM_ACCOUNT *sampw = NULL;      
1134         struct passwd *unix_pw;
1135         const char *user_name;
1136
1137         *name_type = SID_NAME_UNKNOWN;
1138
1139         /*
1140          * We can only convert to a uid if this is our local
1141          * Domain SID (ie. we are the controling authority).
1142          */
1143         if (!sid_check_is_in_our_domain(psid) ) {
1144                 DEBUG(5,("local_sid_to_uid: this SID (%s) is not from our domain\n", sid_string_static(psid)));
1145                 return False;
1146         }
1147
1148         /* lookup the user account */
1149         
1150         if ( !NT_STATUS_IS_OK(pdb_init_sam(&sampw)) ) {
1151                 DEBUG(0,("local_sid_to_uid: Failed to allocate memory for SAM_ACCOUNT object\n"));
1152                 return False;
1153         }
1154                 
1155         become_root();
1156         if ( !pdb_getsampwsid(sampw, psid) ) {
1157                 unbecome_root();
1158                 DEBUG(8,("local_sid_to_uid: Could not find SID %s in passdb\n",
1159                         sid_string_static(psid)));
1160                 return False;
1161         }
1162         unbecome_root();
1163         
1164         user_name = pdb_get_username(sampw);
1165
1166         unix_pw = sys_getpwnam( user_name );
1167
1168         if ( !unix_pw ) {
1169                 DEBUG(0,("local_sid_to_uid: %s found in passdb but getpwnam() return NULL!\n",
1170                         user_name));
1171                 pdb_free_sam( &sampw );
1172                 return False;
1173         }
1174                 
1175         *puid = unix_pw->pw_uid;
1176         
1177         DEBUG(10,("local_sid_to_uid: SID %s -> uid (%u) (%s).\n", sid_string_static(psid),
1178                 (unsigned int)*puid, user_name ));
1179
1180         *name_type = SID_NAME_USER;
1181         
1182         return True;
1183 }
1184
1185 /****************************************************************************
1186  Convert a gid to SID - locally.
1187 ****************************************************************************/
1188
1189 DOM_SID *local_gid_to_sid(DOM_SID *psid, gid_t gid)
1190 {
1191         GROUP_MAP group;
1192         BOOL ret;
1193         
1194         /* we don't need to disable winbindd since the gid is stored in 
1195            the GROUP_MAP object */
1196            
1197         /* done as root since ldap backend requires root to open a connection */
1198
1199         become_root();
1200         ret = pdb_getgrgid( &group, gid );
1201         unbecome_root();
1202         
1203         if ( !ret ) {
1204
1205                 /* fallback to rid mapping if enabled */
1206
1207                 if ( lp_enable_rid_algorithm() ) {
1208                         sid_copy(psid, get_global_sam_sid());
1209                         sid_append_rid(psid, pdb_gid_to_group_rid(gid));
1210
1211                         DEBUG(10,("local_gid_to_sid: Fall back to algorithmic mapping: %u -> %s\n", 
1212                                 (unsigned int)gid, sid_string_static(psid)));
1213                                 
1214                         return psid;
1215                 }
1216                 else
1217                         return NULL;
1218         }
1219         
1220         sid_copy( psid, &group.sid );
1221         
1222         DEBUG(10,("local_gid_to_sid:  gid (%d) -> SID %s.\n", 
1223                 (unsigned int)gid, sid_string_static(psid)));   
1224         
1225         return psid;
1226 }
1227
1228 /****************************************************************************
1229  Convert a SID to gid - locally.
1230 ****************************************************************************/
1231
1232 BOOL local_sid_to_gid(gid_t *pgid, const DOM_SID *psid, enum SID_NAME_USE *name_type)
1233 {
1234         uint32 rid;
1235         GROUP_MAP group;
1236
1237         *name_type = SID_NAME_UNKNOWN;
1238
1239         /* This call can enumerate group mappings for foreign sids as well.
1240            So don't check for a match against our domain SID */
1241
1242         /* we don't need to disable winbindd since the gid is stored in 
1243            the GROUP_MAP object */
1244
1245         if ( !pdb_getgrsid(&group, *psid) ) {
1246
1247                 /* fallback to rid mapping if enabled */
1248
1249                 if ( lp_enable_rid_algorithm() ) {
1250
1251                         if (!sid_check_is_in_our_domain(psid) ) {
1252                                 DEBUG(5,("local_sid_to_gid: RID algorithm only supported for our domain (%s is not)\n", sid_string_static(psid)));
1253                                 return False;
1254                         }
1255
1256                         if (!sid_peek_rid(psid, &rid)) {
1257                                 DEBUG(10,("local_sid_to_uid: invalid SID!\n"));
1258                                         return False;
1259                         }
1260
1261                         DEBUG(10,("local_sid_to_gid: Fall back to algorithmic mapping\n"));
1262
1263                         if (fallback_pdb_rid_is_user(rid)) {
1264                                 DEBUG(3, ("local_sid_to_gid: SID %s is *NOT* a group\n", sid_string_static(psid)));
1265                                 return False;
1266                         } else {
1267                                 *pgid = pdb_group_rid_to_gid(rid);
1268                                 DEBUG(10,("local_sid_to_gid: mapping: %s -> %u\n", sid_string_static(psid), (unsigned int)(*pgid)));
1269                                 return True;
1270                         }
1271                 }
1272                 
1273                 return False;
1274         }
1275
1276         *pgid = group.gid;
1277
1278         DEBUG(10,("local_sid_to_gid: SID %s -> gid (%u)\n", sid_string_static(psid),
1279                 (unsigned int)*pgid));
1280
1281         return True;
1282 }
1283
1284 /**********************************************************************
1285  Marshall/unmarshall SAM_ACCOUNT structs.
1286  *********************************************************************/
1287
1288 #define TDB_FORMAT_STRING       "ddddddBBBBBBBBBBBBddBBwdwdBwwd"
1289
1290 /**********************************************************************
1291  Intialize a SAM_ACCOUNT struct from a BYTE buffer of size len
1292  *********************************************************************/
1293
1294 BOOL init_sam_from_buffer(SAM_ACCOUNT *sampass, uint8 *buf, uint32 buflen)
1295 {
1296
1297         /* times are stored as 32bit integer
1298            take care on system with 64bit wide time_t
1299            --SSS */
1300         uint32  logon_time,
1301                 logoff_time,
1302                 kickoff_time,
1303                 pass_last_set_time,
1304                 pass_can_change_time,
1305                 pass_must_change_time;
1306         char *username;
1307         char *domain;
1308         char *nt_username;
1309         char *dir_drive;
1310         char *unknown_str;
1311         char *munged_dial;
1312         char *fullname;
1313         char *homedir;
1314         char *logon_script;
1315         char *profile_path;
1316         char *acct_desc;
1317         char *workstations;
1318         uint32  username_len, domain_len, nt_username_len,
1319                 dir_drive_len, unknown_str_len, munged_dial_len,
1320                 fullname_len, homedir_len, logon_script_len,
1321                 profile_path_len, acct_desc_len, workstations_len;
1322                 
1323         uint32  user_rid, group_rid, unknown_3, hours_len, unknown_6;
1324         uint16  acct_ctrl, logon_divs;
1325         uint16  bad_password_count, logon_count;
1326         uint8   *hours;
1327         static uint8    *lm_pw_ptr, *nt_pw_ptr;
1328         uint32          len = 0;
1329         uint32          lm_pw_len, nt_pw_len, hourslen;
1330         BOOL ret = True;
1331         
1332         if(sampass == NULL || buf == NULL) {
1333                 DEBUG(0, ("init_sam_from_buffer: NULL parameters found!\n"));
1334                 return False;
1335         }
1336                                                                         
1337         /* unpack the buffer into variables */
1338         len = tdb_unpack ((char *)buf, buflen, TDB_FORMAT_STRING,
1339                 &logon_time,
1340                 &logoff_time,
1341                 &kickoff_time,
1342                 &pass_last_set_time,
1343                 &pass_can_change_time,
1344                 &pass_must_change_time,
1345                 &username_len, &username,
1346                 &domain_len, &domain,
1347                 &nt_username_len, &nt_username,
1348                 &fullname_len, &fullname,
1349                 &homedir_len, &homedir,
1350                 &dir_drive_len, &dir_drive,
1351                 &logon_script_len, &logon_script,
1352                 &profile_path_len, &profile_path,
1353                 &acct_desc_len, &acct_desc,
1354                 &workstations_len, &workstations,
1355                 &unknown_str_len, &unknown_str,
1356                 &munged_dial_len, &munged_dial,
1357                 &user_rid,
1358                 &group_rid,
1359                 &lm_pw_len, &lm_pw_ptr,
1360                 &nt_pw_len, &nt_pw_ptr,
1361                 &acct_ctrl,
1362                 &unknown_3,
1363                 &logon_divs,
1364                 &hours_len,
1365                 &hourslen, &hours,
1366                 &bad_password_count,
1367                 &logon_count,
1368                 &unknown_6);
1369                 
1370         if (len == -1)  {
1371                 ret = False;
1372                 goto done;
1373         }
1374
1375         pdb_set_logon_time(sampass, logon_time, PDB_SET);
1376         pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
1377         pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
1378         pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
1379         pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
1380         pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
1381
1382         pdb_set_username(sampass, username, PDB_SET); 
1383         pdb_set_domain(sampass, domain, PDB_SET);
1384         pdb_set_nt_username(sampass, nt_username, PDB_SET);
1385         pdb_set_fullname(sampass, fullname, PDB_SET);
1386
1387         if (homedir) {
1388                 pdb_set_homedir(sampass, homedir, PDB_SET);
1389         }
1390         else {
1391                 pdb_set_homedir(sampass, 
1392                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_home()),
1393                         PDB_DEFAULT);
1394         }
1395
1396         if (dir_drive)  
1397                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
1398         else {
1399                 pdb_set_dir_drive(sampass, 
1400                         talloc_sub_basic(sampass->mem_ctx,  username, lp_logon_drive()),
1401                         PDB_DEFAULT);
1402         }
1403
1404         if (logon_script) 
1405                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
1406         else {
1407                 pdb_set_logon_script(sampass, 
1408                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_script()),
1409                         PDB_DEFAULT);
1410         }
1411         
1412         if (profile_path) {     
1413                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
1414         } else {
1415                 pdb_set_profile_path(sampass, 
1416                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_path()),
1417                         PDB_DEFAULT);
1418         }
1419
1420         pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
1421         pdb_set_workstations(sampass, workstations, PDB_SET);
1422         pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
1423
1424         if (lm_pw_ptr && lm_pw_len == LM_HASH_LEN) {
1425                 if (!pdb_set_lanman_passwd(sampass, lm_pw_ptr, PDB_SET)) {
1426                         ret = False;
1427                         goto done;
1428                 }
1429         }
1430
1431         if (nt_pw_ptr && nt_pw_len == NT_HASH_LEN) {
1432                 if (!pdb_set_nt_passwd(sampass, nt_pw_ptr, PDB_SET)) {
1433                         ret = False;
1434                         goto done;
1435                 }
1436         }
1437
1438         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
1439         pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
1440         pdb_set_unknown_3(sampass, unknown_3, PDB_SET);
1441         pdb_set_hours_len(sampass, hours_len, PDB_SET);
1442         pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
1443         pdb_set_logon_count(sampass, logon_count, PDB_SET);
1444         pdb_set_unknown_6(sampass, unknown_6, PDB_SET);
1445         pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
1446         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
1447         pdb_set_hours(sampass, hours, PDB_SET);
1448
1449 done:
1450
1451         SAFE_FREE(username);
1452         SAFE_FREE(domain);
1453         SAFE_FREE(nt_username);
1454         SAFE_FREE(fullname);
1455         SAFE_FREE(homedir);
1456         SAFE_FREE(dir_drive);
1457         SAFE_FREE(logon_script);
1458         SAFE_FREE(profile_path);
1459         SAFE_FREE(acct_desc);
1460         SAFE_FREE(workstations);
1461         SAFE_FREE(munged_dial);
1462         SAFE_FREE(unknown_str);
1463         SAFE_FREE(hours);
1464
1465         return ret;
1466 }
1467
1468 /**********************************************************************
1469  Intialize a BYTE buffer from a SAM_ACCOUNT struct
1470  *********************************************************************/
1471
1472 uint32 init_buffer_from_sam (uint8 **buf, const SAM_ACCOUNT *sampass, BOOL size_only)
1473 {
1474         size_t len, buflen;
1475
1476         /* times are stored as 32bit integer
1477            take care on system with 64bit wide time_t
1478            --SSS */
1479         uint32  logon_time,
1480                 logoff_time,
1481                 kickoff_time,
1482                 pass_last_set_time,
1483                 pass_can_change_time,
1484                 pass_must_change_time;
1485
1486         uint32  user_rid, group_rid;
1487
1488         const char *username;
1489         const char *domain;
1490         const char *nt_username;
1491         const char *dir_drive;
1492         const char *unknown_str;
1493         const char *munged_dial;
1494         const char *fullname;
1495         const char *homedir;
1496         const char *logon_script;
1497         const char *profile_path;
1498         const char *acct_desc;
1499         const char *workstations;
1500         uint32  username_len, domain_len, nt_username_len,
1501                 dir_drive_len, unknown_str_len, munged_dial_len,
1502                 fullname_len, homedir_len, logon_script_len,
1503                 profile_path_len, acct_desc_len, workstations_len;
1504
1505         const uint8 *lm_pw;
1506         const uint8 *nt_pw;
1507         uint32  lm_pw_len = 16;
1508         uint32  nt_pw_len = 16;
1509
1510         /* do we have a valid SAM_ACCOUNT pointer? */
1511         if (sampass == NULL) {
1512                 DEBUG(0, ("init_buffer_from_sam: SAM_ACCOUNT is NULL!\n"));
1513                 return -1;
1514         }
1515         
1516         *buf = NULL;
1517         buflen = 0;
1518
1519         logon_time = (uint32)pdb_get_logon_time(sampass);
1520         logoff_time = (uint32)pdb_get_logoff_time(sampass);
1521         kickoff_time = (uint32)pdb_get_kickoff_time(sampass);
1522         pass_can_change_time = (uint32)pdb_get_pass_can_change_time(sampass);
1523         pass_must_change_time = (uint32)pdb_get_pass_must_change_time(sampass);
1524         pass_last_set_time = (uint32)pdb_get_pass_last_set_time(sampass);
1525
1526         user_rid = pdb_get_user_rid(sampass);
1527         group_rid = pdb_get_group_rid(sampass);
1528
1529         username = pdb_get_username(sampass);
1530         if (username)
1531                 username_len = strlen(username) +1;
1532         else
1533                 username_len = 0;
1534
1535         domain = pdb_get_domain(sampass);
1536         if (domain)
1537                 domain_len = strlen(domain) +1;
1538         else
1539                 domain_len = 0;
1540
1541         nt_username = pdb_get_nt_username(sampass);
1542         if (nt_username)
1543                 nt_username_len = strlen(nt_username) +1;
1544         else
1545                 nt_username_len = 0;
1546
1547         fullname = pdb_get_fullname(sampass);
1548         if (fullname)
1549                 fullname_len = strlen(fullname) +1;
1550         else
1551                 fullname_len = 0;
1552
1553         /*
1554          * Only updates fields which have been set (not defaults from smb.conf)
1555          */
1556
1557         if (!IS_SAM_DEFAULT(sampass, PDB_DRIVE)) 
1558                 dir_drive = pdb_get_dir_drive(sampass);
1559         else
1560                 dir_drive = NULL;
1561         if (dir_drive)
1562                 dir_drive_len = strlen(dir_drive) +1;
1563         else
1564                 dir_drive_len = 0;
1565
1566         if (!IS_SAM_DEFAULT(sampass, PDB_SMBHOME))
1567                 homedir = pdb_get_homedir(sampass);
1568         else
1569                 homedir = NULL;
1570         if (homedir)
1571                 homedir_len = strlen(homedir) +1;
1572         else
1573                 homedir_len = 0;
1574
1575         if (!IS_SAM_DEFAULT(sampass, PDB_LOGONSCRIPT))
1576                 logon_script = pdb_get_logon_script(sampass);
1577         else
1578                 logon_script = NULL;
1579         if (logon_script)
1580                 logon_script_len = strlen(logon_script) +1;
1581         else
1582                 logon_script_len = 0;
1583
1584         if (!IS_SAM_DEFAULT(sampass, PDB_PROFILE))
1585                 profile_path = pdb_get_profile_path(sampass);
1586         else
1587                 profile_path = NULL;
1588         if (profile_path)
1589                 profile_path_len = strlen(profile_path) +1;
1590         else
1591                 profile_path_len = 0;
1592         
1593         lm_pw = pdb_get_lanman_passwd(sampass);
1594         if (!lm_pw)
1595                 lm_pw_len = 0;
1596         
1597         nt_pw = pdb_get_nt_passwd(sampass);
1598         if (!nt_pw)
1599                 nt_pw_len = 0;
1600                 
1601         acct_desc = pdb_get_acct_desc(sampass);
1602         if (acct_desc)
1603                 acct_desc_len = strlen(acct_desc) +1;
1604         else
1605                 acct_desc_len = 0;
1606
1607         workstations = pdb_get_workstations(sampass);
1608         if (workstations)
1609                 workstations_len = strlen(workstations) +1;
1610         else
1611                 workstations_len = 0;
1612
1613         unknown_str = NULL;
1614         unknown_str_len = 0;
1615
1616         munged_dial = pdb_get_munged_dial(sampass);
1617         if (munged_dial)
1618                 munged_dial_len = strlen(munged_dial) +1;
1619         else
1620                 munged_dial_len = 0;    
1621                 
1622         /* one time to get the size needed */
1623         len = tdb_pack(NULL, 0,  TDB_FORMAT_STRING,
1624                 logon_time,
1625                 logoff_time,
1626                 kickoff_time,
1627                 pass_last_set_time,
1628                 pass_can_change_time,
1629                 pass_must_change_time,
1630                 username_len, username,
1631                 domain_len, domain,
1632                 nt_username_len, nt_username,
1633                 fullname_len, fullname,
1634                 homedir_len, homedir,
1635                 dir_drive_len, dir_drive,
1636                 logon_script_len, logon_script,
1637                 profile_path_len, profile_path,
1638                 acct_desc_len, acct_desc,
1639                 workstations_len, workstations,
1640                 unknown_str_len, unknown_str,
1641                 munged_dial_len, munged_dial,
1642                 user_rid,
1643                 group_rid,
1644                 lm_pw_len, lm_pw,
1645                 nt_pw_len, nt_pw,
1646                 pdb_get_acct_ctrl(sampass),
1647                 pdb_get_unknown_3(sampass),
1648                 pdb_get_logon_divs(sampass),
1649                 pdb_get_hours_len(sampass),
1650                 MAX_HOURS_LEN, pdb_get_hours(sampass),
1651                 pdb_get_bad_password_count(sampass),
1652                 pdb_get_logon_count(sampass),
1653                 pdb_get_unknown_6(sampass));
1654
1655
1656         if (size_only)
1657                 return buflen;
1658
1659         /* malloc the space needed */
1660         if ( (*buf=(uint8*)malloc(len)) == NULL) {
1661                 DEBUG(0,("init_buffer_from_sam: Unable to malloc() memory for buffer!\n"));
1662                 return (-1);
1663         }
1664         
1665         /* now for the real call to tdb_pack() */
1666         buflen = tdb_pack((char *)*buf, len,  TDB_FORMAT_STRING,
1667                 logon_time,
1668                 logoff_time,
1669                 kickoff_time,
1670                 pass_last_set_time,
1671                 pass_can_change_time,
1672                 pass_must_change_time,
1673                 username_len, username,
1674                 domain_len, domain,
1675                 nt_username_len, nt_username,
1676                 fullname_len, fullname,
1677                 homedir_len, homedir,
1678                 dir_drive_len, dir_drive,
1679                 logon_script_len, logon_script,
1680                 profile_path_len, profile_path,
1681                 acct_desc_len, acct_desc,
1682                 workstations_len, workstations,
1683                 unknown_str_len, unknown_str,
1684                 munged_dial_len, munged_dial,
1685                 user_rid,
1686                 group_rid,
1687                 lm_pw_len, lm_pw,
1688                 nt_pw_len, nt_pw,
1689                 pdb_get_acct_ctrl(sampass),
1690                 pdb_get_unknown_3(sampass),
1691                 pdb_get_logon_divs(sampass),
1692                 pdb_get_hours_len(sampass),
1693                 MAX_HOURS_LEN, pdb_get_hours(sampass),
1694                 pdb_get_bad_password_count(sampass),
1695                 pdb_get_logon_count(sampass),
1696                 pdb_get_unknown_6(sampass));
1697         
1698         
1699         /* check to make sure we got it correct */
1700         if (buflen != len) {
1701                 DEBUG(0, ("init_buffer_from_sam: somthing odd is going on here: bufflen (%lu) != len (%lu) in tdb_pack operations!\n", 
1702                           (unsigned long)buflen, (unsigned long)len));  
1703                 /* error */
1704                 SAFE_FREE (*buf);
1705                 return (-1);
1706         }
1707
1708         return (buflen);
1709 }
1710
1711
1712 /**********************************************************************
1713 **********************************************************************/
1714
1715 static BOOL get_free_ugid_range(uint32 *low, uint32 *high)
1716 {
1717         uid_t u_low, u_high;
1718         gid_t g_low, g_high;
1719
1720         if (!lp_idmap_uid(&u_low, &u_high) || !lp_idmap_gid(&g_low, &g_high)) {
1721                 return False;
1722         }
1723         
1724         *low  = (u_low < g_low)   ? u_low  : g_low;
1725         *high = (u_high < g_high) ? u_high : g_high;
1726         
1727         return True;
1728 }
1729
1730 /******************************************************************
1731  Get the the non-algorithmic RID range if idmap range are defined
1732 ******************************************************************/
1733
1734 BOOL get_free_rid_range(uint32 *low, uint32 *high)
1735 {
1736         uint32 id_low, id_high;
1737
1738         if (!lp_enable_rid_algorithm()) {
1739                 *low = BASE_RID;
1740                 *high = (uint32)-1;
1741         }
1742
1743         if (!get_free_ugid_range(&id_low, &id_high)) {
1744                 return False;
1745         }
1746
1747         *low = fallback_pdb_uid_to_user_rid(id_low);
1748         if (fallback_pdb_user_rid_to_uid((uint32)-1) < id_high) {
1749                 *high = (uint32)-1;
1750         } else {
1751                 *high = fallback_pdb_uid_to_user_rid(id_high);
1752         }
1753
1754         return True;
1755 }
1756
1757