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