This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.(This used to...
[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       
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25
26 #undef DBGC_CLASS
27 #define DBGC_CLASS DBGC_PASSDB
28
29 /*
30  * This is set on startup - it defines the SID for this
31  * machine, and therefore the SAM database for which it is
32  * responsible.
33  */
34
35 /************************************************************
36  Fill the SAM_ACCOUNT with default values.
37  ***********************************************************/
38
39 static void pdb_fill_default_sam(SAM_ACCOUNT *user)
40 {
41         ZERO_STRUCT(user->private); /* Don't touch the talloc context */
42
43         /* no initial methods */
44         user->methods = NULL;
45
46         /* Don't change these timestamp settings without a good reason.
47            They are important for NT member server compatibility. */
48
49         user->private.uid = user->private.gid       = -1;
50
51         user->private.logon_time            = (time_t)0;
52         user->private.pass_last_set_time    = (time_t)0;
53         user->private.pass_can_change_time  = (time_t)0;
54         user->private.logoff_time           = 
55         user->private.kickoff_time          = 
56         user->private.pass_must_change_time = get_time_t_max();
57         user->private.unknown_3 = 0x00ffffff;   /* don't know */
58         user->private.logon_divs = 168;         /* hours per week */
59         user->private.hours_len = 21;           /* 21 times 8 bits = 168 */
60         memset(user->private.hours, 0xff, user->private.hours_len); /* available at all hours */
61         user->private.unknown_5 = 0x00000000; /* don't know */
62         user->private.unknown_6 = 0x000004ec; /* don't know */
63
64         /* Some parts of samba strlen their pdb_get...() returns, 
65            so this keeps the interface unchanged for now. */
66            
67         user->private.username = "";
68         user->private.domain = "";
69         user->private.nt_username = "";
70         user->private.full_name = "";
71         user->private.home_dir = "";
72         user->private.logon_script = "";
73         user->private.profile_path = "";
74         user->private.acct_desc = "";
75         user->private.workstations = "";
76         user->private.unknown_str = "";
77         user->private.munged_dial = "";
78
79         user->private.plaintext_pw = NULL;
80
81 }       
82
83 static void destroy_pdb_talloc(SAM_ACCOUNT **user) 
84 {
85         if (*user) {
86                 data_blob_clear_free(&((*user)->private.lm_pw));
87                 data_blob_clear_free(&((*user)->private.nt_pw));
88
89                 if((*user)->private.plaintext_pw!=NULL)
90                         memset((*user)->private.plaintext_pw,'\0',strlen((*user)->private.plaintext_pw));
91                 talloc_destroy((*user)->mem_ctx);
92                 *user = NULL;
93         }
94 }
95
96
97 /**********************************************************************
98  Alloc memory and initialises a struct sam_passwd on supplied mem_ctx.
99 ***********************************************************************/
100
101 NTSTATUS pdb_init_sam_talloc(TALLOC_CTX *mem_ctx, SAM_ACCOUNT **user)
102 {
103         if (*user != NULL) {
104                 DEBUG(0,("pdb_init_sam_talloc: SAM_ACCOUNT was non NULL\n"));
105 #if 0
106                 smb_panic("non-NULL pointer passed to pdb_init_sam\n");
107 #endif
108                 return NT_STATUS_UNSUCCESSFUL;
109         }
110
111         if (!mem_ctx) {
112                 DEBUG(0,("pdb_init_sam_talloc: mem_ctx was NULL!\n"));
113                 return NT_STATUS_UNSUCCESSFUL;
114         }
115
116         *user=(SAM_ACCOUNT *)talloc(mem_ctx, sizeof(SAM_ACCOUNT));
117
118         if (*user==NULL) {
119                 DEBUG(0,("pdb_init_sam_talloc: error while allocating memory\n"));
120                 return NT_STATUS_NO_MEMORY;
121         }
122
123         (*user)->mem_ctx = mem_ctx;
124
125         (*user)->free_fn = NULL;
126
127         pdb_fill_default_sam(*user);
128         
129         return NT_STATUS_OK;
130 }
131
132
133 /*************************************************************
134  Alloc memory and initialises a struct sam_passwd.
135  ************************************************************/
136
137 NTSTATUS pdb_init_sam(SAM_ACCOUNT **user)
138 {
139         TALLOC_CTX *mem_ctx;
140         NTSTATUS nt_status;
141         
142         mem_ctx = talloc_init("passdb internal SAM_ACCOUNT allocation");
143
144         if (!mem_ctx) {
145                 DEBUG(0,("pdb_init_sam: error while doing talloc_init()\n"));
146                 return NT_STATUS_NO_MEMORY;
147         }
148
149         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_talloc(mem_ctx, user))) {
150                 talloc_destroy(mem_ctx);
151                 return nt_status;
152         }
153         
154         (*user)->free_fn = destroy_pdb_talloc;
155
156         return NT_STATUS_OK;
157 }
158
159
160 /*************************************************************
161  Initialises a struct sam_passwd with sane values.
162  ************************************************************/
163
164 NTSTATUS pdb_fill_sam_pw(SAM_ACCOUNT *sam_account, const struct passwd *pwd)
165 {
166         GROUP_MAP map;
167
168         const char *guest_account = lp_guestaccount();
169         if (!(guest_account && *guest_account)) {
170                 DEBUG(1, ("NULL guest account!?!?\n"));
171                 return NT_STATUS_UNSUCCESSFUL;
172         }
173
174         if (!pwd) {
175                 return NT_STATUS_UNSUCCESSFUL;
176         }
177
178         pdb_fill_default_sam(sam_account);
179
180         pdb_set_username(sam_account, pwd->pw_name, PDB_SET);
181         pdb_set_fullname(sam_account, pwd->pw_gecos, PDB_SET);
182
183         pdb_set_unix_homedir(sam_account, pwd->pw_dir, PDB_SET);
184
185         pdb_set_domain (sam_account, lp_workgroup(), PDB_DEFAULT);
186
187         pdb_set_uid(sam_account, pwd->pw_uid, PDB_SET);
188         pdb_set_gid(sam_account, pwd->pw_gid, PDB_SET);
189         
190         /* When we get a proper uid -> SID and SID -> uid allocation
191            mechinism, we should call it here.  
192            
193            We can't just set this to 0 or allow it only to be filled
194            in when added to the backend, becouse the user's SID 
195            may already be in security descriptors etc.
196            
197            -- abartlet 11-May-02
198         */
199
200
201         /* Ensure this *must* be set right */
202         if (strcmp(pwd->pw_name, guest_account) == 0) {
203                 if (!pdb_set_user_sid_from_rid(sam_account, DOMAIN_USER_RID_GUEST, PDB_SET)) {
204                         return NT_STATUS_UNSUCCESSFUL;
205                 }
206                 if (!pdb_set_group_sid_from_rid(sam_account, DOMAIN_GROUP_RID_GUESTS, PDB_SET)) {
207                         return NT_STATUS_UNSUCCESSFUL;
208                 }
209         } else {
210
211                 if (!pdb_set_user_sid_from_rid(sam_account, 
212                                                fallback_pdb_uid_to_user_rid(pwd->pw_uid), PDB_SET)) {
213                         DEBUG(0,("Can't set User SID from RID!\n"));
214                         return NT_STATUS_INVALID_PARAMETER;
215                 }
216                 
217                 /* call the mapping code here */
218                 if(pdb_getgrgid(&map, pwd->pw_gid, MAPPING_WITHOUT_PRIV)) {
219                         if (!pdb_set_group_sid(sam_account,&map.sid, PDB_SET)){
220                                 DEBUG(0,("Can't set Group SID!\n"));
221                                 return NT_STATUS_INVALID_PARAMETER;
222                         }
223                 } 
224                 else {
225                         if (!pdb_set_group_sid_from_rid(sam_account,pdb_gid_to_group_rid(pwd->pw_gid), PDB_SET)) {
226                                 DEBUG(0,("Can't set Group SID\n"));
227                                 return NT_STATUS_INVALID_PARAMETER;
228                         }
229                 }
230         }
231
232         /* check if this is a user account or a machine account */
233         if (pwd->pw_name[strlen(pwd->pw_name)-1] != '$')
234         {
235                 pdb_set_profile_path(sam_account, 
236                                      talloc_sub_specified((sam_account)->mem_ctx, 
237                                                             lp_logon_path(), 
238                                                             pwd->pw_name, global_myname(), 
239                                                             pwd->pw_uid, pwd->pw_gid), 
240                                      PDB_DEFAULT);
241                 
242                 pdb_set_homedir(sam_account, 
243                                 talloc_sub_specified((sam_account)->mem_ctx, 
244                                                        lp_logon_home(),
245                                                        pwd->pw_name, global_myname(), 
246                                                        pwd->pw_uid, pwd->pw_gid),
247                                 PDB_DEFAULT);
248                 
249                 pdb_set_dir_drive(sam_account, 
250                                   talloc_sub_specified((sam_account)->mem_ctx, 
251                                                          lp_logon_drive(),
252                                                          pwd->pw_name, global_myname(), 
253                                                          pwd->pw_uid, pwd->pw_gid),
254                                   PDB_DEFAULT);
255                 
256                 pdb_set_logon_script(sam_account, 
257                                      talloc_sub_specified((sam_account)->mem_ctx, 
258                                                             lp_logon_script(),
259                                                             pwd->pw_name, global_myname(), 
260                                                             pwd->pw_uid, pwd->pw_gid), 
261                                      PDB_DEFAULT);
262                 if (!pdb_set_acct_ctrl(sam_account, ACB_NORMAL, PDB_DEFAULT)) {
263                         DEBUG(1, ("Failed to set 'normal account' flags for user %s.\n", pwd->pw_name));
264                         return NT_STATUS_UNSUCCESSFUL;
265                 }
266         } else {
267                 if (!pdb_set_acct_ctrl(sam_account, ACB_WSTRUST, PDB_DEFAULT)) {
268                         DEBUG(1, ("Failed to set 'trusted workstation account' flags for user %s.\n", pwd->pw_name));
269                         return NT_STATUS_UNSUCCESSFUL;
270                 }
271         }
272         return NT_STATUS_OK;
273 }
274
275
276 /*************************************************************
277  Initialises a struct sam_passwd with sane values.
278  ************************************************************/
279
280 NTSTATUS pdb_init_sam_pw(SAM_ACCOUNT **new_sam_acct, const struct passwd *pwd)
281 {
282         NTSTATUS nt_status;
283
284         if (!pwd) {
285                 new_sam_acct = NULL;
286                 return NT_STATUS_INVALID_PARAMETER;
287         }
288
289         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam(new_sam_acct))) {
290                 new_sam_acct = NULL;
291                 return nt_status;
292         }
293
294         if (!NT_STATUS_IS_OK(nt_status = pdb_fill_sam_pw(*new_sam_acct, pwd))) {
295                 pdb_free_sam(new_sam_acct);
296                 new_sam_acct = NULL;
297                 return nt_status;
298         }
299
300         return NT_STATUS_OK;
301 }
302
303
304 /*************************************************************
305  Initialises a SAM_ACCOUNT ready to add a new account, based
306  on the unix user if possible.
307  ************************************************************/
308
309 NTSTATUS pdb_init_sam_new(SAM_ACCOUNT **new_sam_acct, const char *username)
310 {
311         NTSTATUS nt_status = NT_STATUS_NO_MEMORY;
312
313         struct passwd *pwd;
314         
315         pwd = Get_Pwnam(username);
316
317         if (pwd) {
318                 if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_pw(new_sam_acct, pwd))) {
319                         *new_sam_acct = NULL;
320                         return nt_status;
321                 }
322         } else {
323                 if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam(new_sam_acct))) {
324                         *new_sam_acct = NULL;
325                         return nt_status;
326                 }
327                 if (!pdb_set_username(*new_sam_acct, username, PDB_SET)) {
328                         pdb_free_sam(new_sam_acct);
329                         return nt_status;
330                 }
331         }
332         return NT_STATUS_OK;
333 }
334
335
336 /**
337  * Free the contets of the SAM_ACCOUNT, but not the structure.
338  *
339  * Also wipes the LM and NT hashes and plaintext password from 
340  * memory.
341  *
342  * @param user SAM_ACCOUNT to free members of.
343  **/
344
345 static void pdb_free_sam_contents(SAM_ACCOUNT *user)
346 {
347
348         /* Kill off sensitive data.  Free()ed by the
349            talloc mechinism */
350
351         data_blob_clear_free(&(user->private.lm_pw));
352         data_blob_clear_free(&(user->private.nt_pw));
353         if (user->private.plaintext_pw!=NULL)
354                 memset(user->private.plaintext_pw,'\0',strlen(user->private.plaintext_pw));
355 }
356
357
358 /************************************************************
359  Reset the SAM_ACCOUNT and free the NT/LM hashes.
360  ***********************************************************/
361
362 NTSTATUS pdb_reset_sam(SAM_ACCOUNT *user)
363 {
364         if (user == NULL) {
365                 DEBUG(0,("pdb_reset_sam: SAM_ACCOUNT was NULL\n"));
366 #if 0
367                 smb_panic("NULL pointer passed to pdb_free_sam\n");
368 #endif
369                 return NT_STATUS_UNSUCCESSFUL;
370         }
371         
372         pdb_free_sam_contents(user);
373
374         pdb_fill_default_sam(user);
375
376         return NT_STATUS_OK;
377 }
378
379
380 /************************************************************
381  Free the SAM_ACCOUNT and the member pointers.
382  ***********************************************************/
383
384 NTSTATUS pdb_free_sam(SAM_ACCOUNT **user)
385 {
386         if (*user == NULL) {
387                 DEBUG(0,("pdb_free_sam: SAM_ACCOUNT was NULL\n"));
388 #if 0
389                 smb_panic("NULL pointer passed to pdb_free_sam\n");
390 #endif
391                 return NT_STATUS_UNSUCCESSFUL;
392         }
393
394         pdb_free_sam_contents(*user);
395         
396         if ((*user)->free_fn) {
397                 (*user)->free_fn(user);
398         }
399
400         return NT_STATUS_OK;    
401 }
402
403
404 /**********************************************************
405  Encode the account control bits into a string.
406  length = length of string to encode into (including terminating
407  null). length *MUST BE MORE THAN 2* !
408  **********************************************************/
409
410 char *pdb_encode_acct_ctrl(uint16 acct_ctrl, size_t length)
411 {
412         static fstring acct_str;
413         size_t i = 0;
414
415         acct_str[i++] = '[';
416
417         if (acct_ctrl & ACB_PWNOTREQ ) acct_str[i++] = 'N';
418         if (acct_ctrl & ACB_DISABLED ) acct_str[i++] = 'D';
419         if (acct_ctrl & ACB_HOMDIRREQ) acct_str[i++] = 'H';
420         if (acct_ctrl & ACB_TEMPDUP  ) acct_str[i++] = 'T'; 
421         if (acct_ctrl & ACB_NORMAL   ) acct_str[i++] = 'U';
422         if (acct_ctrl & ACB_MNS      ) acct_str[i++] = 'M';
423         if (acct_ctrl & ACB_WSTRUST  ) acct_str[i++] = 'W';
424         if (acct_ctrl & ACB_SVRTRUST ) acct_str[i++] = 'S';
425         if (acct_ctrl & ACB_AUTOLOCK ) acct_str[i++] = 'L';
426         if (acct_ctrl & ACB_PWNOEXP  ) acct_str[i++] = 'X';
427         if (acct_ctrl & ACB_DOMTRUST ) acct_str[i++] = 'I';
428
429         for ( ; i < length - 2 ; i++ )
430                 acct_str[i] = ' ';
431
432         i = length - 2;
433         acct_str[i++] = ']';
434         acct_str[i++] = '\0';
435
436         return acct_str;
437 }     
438
439 /**********************************************************
440  Decode the account control bits from a string.
441  **********************************************************/
442
443 uint16 pdb_decode_acct_ctrl(const char *p)
444 {
445         uint16 acct_ctrl = 0;
446         BOOL finished = False;
447
448         /*
449          * Check if the account type bits have been encoded after the
450          * NT password (in the form [NDHTUWSLXI]).
451          */
452
453         if (*p != '[')
454                 return 0;
455
456         for (p++; *p && !finished; p++) {
457                 switch (*p) {
458                         case 'N': { acct_ctrl |= ACB_PWNOTREQ ; break; /* 'N'o password. */ }
459                         case 'D': { acct_ctrl |= ACB_DISABLED ; break; /* 'D'isabled. */ }
460                         case 'H': { acct_ctrl |= ACB_HOMDIRREQ; break; /* 'H'omedir required. */ }
461                         case 'T': { acct_ctrl |= ACB_TEMPDUP  ; break; /* 'T'emp account. */ } 
462                         case 'U': { acct_ctrl |= ACB_NORMAL   ; break; /* 'U'ser account (normal). */ } 
463                         case 'M': { acct_ctrl |= ACB_MNS      ; break; /* 'M'NS logon user account. What is this ? */ } 
464                         case 'W': { acct_ctrl |= ACB_WSTRUST  ; break; /* 'W'orkstation account. */ } 
465                         case 'S': { acct_ctrl |= ACB_SVRTRUST ; break; /* 'S'erver account. */ } 
466                         case 'L': { acct_ctrl |= ACB_AUTOLOCK ; break; /* 'L'ocked account. */ } 
467                         case 'X': { acct_ctrl |= ACB_PWNOEXP  ; break; /* No 'X'piry on password */ } 
468                         case 'I': { acct_ctrl |= ACB_DOMTRUST ; break; /* 'I'nterdomain trust account. */ }
469             case ' ': { break; }
470                         case ':':
471                         case '\n':
472                         case '\0': 
473                         case ']':
474                         default:  { finished = True; }
475                 }
476         }
477
478         return acct_ctrl;
479 }
480
481 /*************************************************************
482  Routine to set 32 hex password characters from a 16 byte array.
483 **************************************************************/
484
485 void pdb_sethexpwd(char *p, const unsigned char *pwd, uint16 acct_ctrl)
486 {
487         if (pwd != NULL) {
488                 int i;
489                 for (i = 0; i < 16; i++)
490                         slprintf(&p[i*2], 3, "%02X", pwd[i]);
491         } else {
492                 if (acct_ctrl & ACB_PWNOTREQ)
493                         safe_strcpy(p, "NO PASSWORDXXXXXXXXXXXXXXXXXXXXX", 33);
494                 else
495                         safe_strcpy(p, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 33);
496         }
497 }
498
499 /*************************************************************
500  Routine to get the 32 hex characters and turn them
501  into a 16 byte array.
502 **************************************************************/
503
504 BOOL pdb_gethexpwd(const char *p, unsigned char *pwd)
505 {
506         int i;
507         unsigned char   lonybble, hinybble;
508         const char      *hexchars = "0123456789ABCDEF";
509         char           *p1, *p2;
510         
511         if (!p)
512                 return (False);
513         
514         for (i = 0; i < 32; i += 2) {
515                 hinybble = toupper(p[i]);
516                 lonybble = toupper(p[i + 1]);
517
518                 p1 = strchr(hexchars, hinybble);
519                 p2 = strchr(hexchars, lonybble);
520
521                 if (!p1 || !p2)
522                         return (False);
523
524                 hinybble = PTR_DIFF(p1, hexchars);
525                 lonybble = PTR_DIFF(p2, hexchars);
526
527                 pwd[i / 2] = (hinybble << 4) | lonybble;
528         }
529         return (True);
530 }
531
532 /*******************************************************************
533  Converts NT user RID to a UNIX uid.
534  ********************************************************************/
535
536 static int algorithmic_rid_base(void)
537 {
538         static int rid_offset = 0;
539
540         if (rid_offset != 0)
541                 return rid_offset;
542
543         rid_offset = lp_algorithmic_rid_base();
544
545         if (rid_offset < BASE_RID) {  
546                 /* Try to prevent admin foot-shooting, we can't put algorithmic
547                    rids below 1000, that's the 'well known RIDs' on NT */
548                 DEBUG(0, ("'algorithmic rid base' must be equal to or above %ld\n", BASE_RID));
549                 rid_offset = BASE_RID;
550         }
551         if (rid_offset & 1) {
552                 DEBUG(0, ("algorithmic rid base must be even\n"));
553                 rid_offset += 1;
554         }
555         return rid_offset;
556 }
557
558
559 uid_t fallback_pdb_user_rid_to_uid(uint32 user_rid)
560 {
561         int rid_offset = algorithmic_rid_base();
562         return (uid_t)(((user_rid & (~USER_RID_TYPE))- rid_offset)/RID_MULTIPLIER);
563 }
564
565
566 /*******************************************************************
567  converts UNIX uid to an NT User RID.
568  ********************************************************************/
569
570 uint32 fallback_pdb_uid_to_user_rid(uid_t uid)
571 {
572         int rid_offset = algorithmic_rid_base();
573         return (((((uint32)uid)*RID_MULTIPLIER) + rid_offset) | USER_RID_TYPE);
574 }
575
576 /*******************************************************************
577  Converts NT group RID to a UNIX gid.
578  ********************************************************************/
579
580 gid_t pdb_group_rid_to_gid(uint32 group_rid)
581 {
582         int rid_offset = algorithmic_rid_base();
583         return (gid_t)(((group_rid & (~GROUP_RID_TYPE))- rid_offset)/RID_MULTIPLIER);
584 }
585
586 /*******************************************************************
587  converts NT Group RID to a UNIX uid.
588  
589  warning: you must not call that function only
590  you must do a call to the group mapping first.
591  there is not anymore a direct link between the gid and the rid.
592  ********************************************************************/
593
594 uint32 pdb_gid_to_group_rid(gid_t gid)
595 {
596         int rid_offset = algorithmic_rid_base();
597         return (((((uint32)gid)*RID_MULTIPLIER) + rid_offset) | GROUP_RID_TYPE);
598 }
599
600 /*******************************************************************
601  Decides if a RID is a well known RID.
602  ********************************************************************/
603
604 static BOOL pdb_rid_is_well_known(uint32 rid)
605 {
606         /* Not using rid_offset here, becouse this is the actual
607            NT fixed value (1000) */
608
609         return (rid < BASE_RID);
610 }
611
612 /*******************************************************************
613  Decides if a RID is a user or group RID.
614  ********************************************************************/
615
616 BOOL pdb_rid_is_user(uint32 rid)
617 {
618   /* lkcl i understand that NT attaches an enumeration to a RID
619    * such that it can be identified as either a user, group etc
620    * type.  there are 5 such categories, and they are documented.
621    */
622         /* However, they are not in the RID, just somthing you can query
623            seperatly.  Sorry luke :-) */
624
625    if(pdb_rid_is_well_known(rid)) {
626       /*
627        * The only well known user RIDs are DOMAIN_USER_RID_ADMIN
628        * and DOMAIN_USER_RID_GUEST.
629        */
630      if(rid == DOMAIN_USER_RID_ADMIN || rid == DOMAIN_USER_RID_GUEST)
631        return True;
632    } else if((rid & RID_TYPE_MASK) == USER_RID_TYPE) {
633      return True;
634    }
635    return False;
636 }
637
638 /*******************************************************************
639  Convert a rid into a name. Used in the lookup SID rpc.
640  ********************************************************************/
641
642 BOOL local_lookup_sid(DOM_SID *sid, char *name, enum SID_NAME_USE *psid_name_use)
643 {
644         uint32 rid;
645         SAM_ACCOUNT *sam_account = NULL;
646         GROUP_MAP map;
647
648         if (!sid_peek_check_rid(get_global_sam_sid(), sid, &rid)){
649                 DEBUG(0,("local_sid_to_gid: sid_peek_check_rid return False! SID: %s\n",
650                         sid_string_static(&map.sid)));
651                 return False;
652         }       
653         *psid_name_use = SID_NAME_UNKNOWN;
654         
655         DEBUG(5,("local_lookup_sid: looking up RID %u.\n", (unsigned int)rid));
656         
657         if (rid == DOMAIN_USER_RID_ADMIN) {
658                 const char **admin_list = lp_admin_users(-1);
659                 *psid_name_use = SID_NAME_USER;
660                 if (admin_list) {
661                         const char *p = *admin_list;
662                         if(!next_token(&p, name, NULL, sizeof(fstring)))
663                                 fstrcpy(name, "Administrator");
664                 } else {
665                         fstrcpy(name, "Administrator");
666                 }
667                 return True;
668         }
669
670         /*
671          * Don't try to convert the rid to a name if 
672          * running in appliance mode
673          */
674
675         if (lp_hide_local_users())
676                 return False;
677                 
678         if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_account))) {
679                 return False;
680         }
681         
682         /* see if the passdb can help us with the name of the user */
683         if (pdb_getsampwsid(sam_account, sid)) {
684                 fstrcpy(name, pdb_get_username(sam_account));
685                 *psid_name_use = SID_NAME_USER;
686
687                 pdb_free_sam(&sam_account);
688                         
689                 return True;
690         }
691
692         pdb_free_sam(&sam_account);
693                 
694         if (pdb_getgrsid(&map, *sid, MAPPING_WITHOUT_PRIV)) {
695                 if (map.gid!=(gid_t)-1) {
696                         DEBUG(5,("local_lookup_sid: mapped group %s to gid %u\n", map.nt_name, (unsigned int)map.gid));
697                 } else {
698                         DEBUG(5,("local_lookup_sid: mapped group %s to no unix gid.  Returning name.\n", map.nt_name));
699                 }
700
701                 fstrcpy(name, map.nt_name);
702                 *psid_name_use = map.sid_name_use;
703                 return True;
704         }
705
706         if (pdb_rid_is_user(rid)) {
707                 uid_t uid;
708
709                 DEBUG(5, ("assuming RID %u is a user\n", (unsigned)rid));
710
711                 uid = fallback_pdb_user_rid_to_uid(rid);
712                 slprintf(name, sizeof(fstring)-1, "unix_user.%u", (unsigned int)uid);   
713
714                 return False;  /* Indicates that this user was 'not mapped' */
715         } else {
716                 gid_t gid;
717                 struct group *gr; 
718                         
719                 DEBUG(5, ("assuming RID %u is a group\n", (unsigned)rid));
720
721                 gid = pdb_group_rid_to_gid(rid);
722                 gr = getgrgid(gid);
723                         
724                 *psid_name_use = SID_NAME_ALIAS;
725                         
726                 DEBUG(5,("local_lookup_sid: looking up gid %u %s\n", (unsigned int)gid,
727                          gr ? "succeeded" : "failed" ));
728                         
729                 if(!gr) {
730                         slprintf(name, sizeof(fstring)-1, "unix_group.%u", (unsigned int)gid);
731                         return False; /* Indicates that this group was 'not mapped' */
732                 }
733                         
734                 fstrcpy( name, gr->gr_name);
735                         
736                 DEBUG(5,("local_lookup_sid: found group %s for rid %u\n", name,
737                          (unsigned int)rid ));
738                 return True;   
739         }
740 }
741
742 /*******************************************************************
743  Convert a name into a SID. Used in the lookup name rpc.
744  ********************************************************************/
745
746 BOOL local_lookup_name(const char *c_user, DOM_SID *psid, enum SID_NAME_USE *psid_name_use)
747 {
748         extern DOM_SID global_sid_World_Domain;
749         DOM_SID local_sid;
750         fstring user;
751         SAM_ACCOUNT *sam_account = NULL;
752         struct group *grp;
753         GROUP_MAP map;
754                 
755         *psid_name_use = SID_NAME_UNKNOWN;
756
757         /*
758          * user may be quoted a const string, and map_username and
759          * friends can modify it. Make a modifiable copy. JRA.
760          */
761
762         fstrcpy(user, c_user);
763
764         sid_copy(&local_sid, get_global_sam_sid());
765
766         /*
767          * Special case for MACHINE\Everyone. Map to the world_sid.
768          */
769
770         if(strequal(user, "Everyone")) {
771                 sid_copy( psid, &global_sid_World_Domain);
772                 sid_append_rid(psid, 0);
773                 *psid_name_use = SID_NAME_ALIAS;
774                 return True;
775         }
776
777         /* 
778          * Don't lookup local unix users if running in appliance mode
779          */
780         if (lp_hide_local_users()) 
781                 return False;
782
783         (void)map_username(user);
784
785         if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_account))) {
786                 return False;
787         }
788         
789         if (pdb_getsampwnam(sam_account, user)) {
790                 sid_copy(psid, pdb_get_user_sid(sam_account));
791                 *psid_name_use = SID_NAME_USER;
792                 
793                 pdb_free_sam(&sam_account);
794                 return True;
795         }
796
797         pdb_free_sam(&sam_account);
798
799         /*
800          * Maybe it was a group ?
801          */
802
803         /* check if it's a mapped group */
804         if (pdb_getgrnam(&map, user, MAPPING_WITHOUT_PRIV)) {
805                 /* yes it's a mapped group */
806                 sid_copy(&local_sid, &map.sid);
807                 *psid_name_use = map.sid_name_use;
808         } else {
809                 /* it's not a mapped group */
810                 grp = getgrnam(user);
811                 if(!grp)
812                         return False;
813                 
814                 /* 
815                  *check if it's mapped, if it is reply it doesn't exist
816                  *
817                  * that's to prevent this case:
818                  *
819                  * unix group ug is mapped to nt group ng
820                  * someone does a lookup on ug
821                  * we must not reply as it doesn't "exist" anymore
822                  * for NT. For NT only ng exists.
823                  * JFM, 30/11/2001
824                  */
825                 
826                 if (pdb_getgrgid(&map, grp->gr_gid, MAPPING_WITHOUT_PRIV)){
827                         return False;
828                 }
829                 
830                 sid_append_rid( &local_sid, pdb_gid_to_group_rid(grp->gr_gid));
831                 *psid_name_use = SID_NAME_ALIAS;
832         }
833
834         sid_copy( psid, &local_sid);
835
836         return True;
837 }
838
839 /****************************************************************************
840  Convert a uid to SID - locally.
841 ****************************************************************************/
842
843 DOM_SID *local_uid_to_sid(DOM_SID *psid, uid_t uid)
844 {
845         struct passwd *pass;
846         SAM_ACCOUNT *sam_user = NULL;
847         fstring str; /* sid string buffer */
848
849         sid_copy(psid, get_global_sam_sid());
850
851         if((pass = getpwuid_alloc(uid))) {
852
853                 if (NT_STATUS_IS_ERR(pdb_init_sam(&sam_user))) {
854                         passwd_free(&pass);
855                         return NULL;
856                 }
857                 
858                 if (pdb_getsampwnam(sam_user, pass->pw_name)) {
859                         sid_copy(psid, pdb_get_user_sid(sam_user));
860                 } else {
861                         sid_append_rid(psid, fallback_pdb_uid_to_user_rid(uid));
862                 }
863
864                 DEBUG(10,("local_uid_to_sid: uid %u -> SID (%s) (%s).\n", 
865                           (unsigned)uid, sid_to_string( str, psid),
866                           pass->pw_name ));
867
868                 passwd_free(&pass);
869                 pdb_free_sam(&sam_user);
870         
871         } else {
872                 sid_append_rid(psid, fallback_pdb_uid_to_user_rid(uid));
873
874                 DEBUG(10,("local_uid_to_sid: uid %u -> SID (%s) (unknown user).\n", 
875                           (unsigned)uid, sid_to_string( str, psid)));
876         }
877
878         return psid;
879 }
880
881 /****************************************************************************
882  Convert a SID to uid - locally.
883 ****************************************************************************/
884
885 BOOL local_sid_to_uid(uid_t *puid, const DOM_SID *psid, enum SID_NAME_USE *name_type)
886 {
887         fstring str;
888         SAM_ACCOUNT *sam_user = NULL;
889
890         *name_type = SID_NAME_UNKNOWN;
891
892         if (NT_STATUS_IS_ERR(pdb_init_sam(&sam_user)))
893                 return False;
894         
895         if (pdb_getsampwsid(sam_user, psid)) {
896                 
897                 if (!IS_SAM_SET(sam_user,PDB_UID)&&!IS_SAM_CHANGED(sam_user,PDB_UID)) {
898                         pdb_free_sam(&sam_user);
899                         return False;
900                 }
901
902                 *puid = pdb_get_uid(sam_user);
903                         
904                 DEBUG(10,("local_sid_to_uid: SID %s -> uid (%u) (%s).\n", sid_to_string( str, psid),
905                           (unsigned int)*puid, pdb_get_username(sam_user)));
906                 pdb_free_sam(&sam_user);
907         } else {
908
909                 DOM_SID dom_sid;
910                 uint32 rid;
911                 GROUP_MAP map;
912
913                 pdb_free_sam(&sam_user);  
914
915                 if (pdb_getgrsid(&map, *psid, MAPPING_WITHOUT_PRIV)) {
916                         DEBUG(3, ("local_sid_to_uid: SID '%s' is a group, not a user... \n", sid_to_string(str, psid)));
917                         /* It's a group, not a user... */
918                         return False;
919                 }
920
921                 sid_copy(&dom_sid, psid);
922                 if (!sid_peek_check_rid(get_global_sam_sid(), psid, &rid)) {
923                         DEBUG(3, ("sid_peek_rid failed - sid '%s' is not in our domain\n", sid_to_string(str, psid)));
924                         return False;
925                 }
926
927                 if (!pdb_rid_is_user(rid)) {
928                         DEBUG(3, ("local_sid_to_uid: sid '%s' cannot be mapped to a uid algorithmicly becouse it is a group\n", sid_to_string(str, psid)));
929                         return False;
930                 }
931                 
932                 *puid = fallback_pdb_user_rid_to_uid(rid);
933                 
934                 DEBUG(5,("local_sid_to_uid: SID %s algorithmicly mapped to %ld mapped becouse SID was not found in passdb.\n", 
935                          sid_to_string(str, psid), (signed long int)(*puid)));
936         }
937
938         *name_type = SID_NAME_USER;
939
940         return True;
941 }
942
943 /****************************************************************************
944  Convert a gid to SID - locally.
945 ****************************************************************************/
946
947 DOM_SID *local_gid_to_sid(DOM_SID *psid, gid_t gid)
948 {
949         GROUP_MAP map;
950
951         sid_copy(psid, get_global_sam_sid());
952         
953         if (pdb_getgrgid(&map, gid, MAPPING_WITHOUT_PRIV)) {
954                 sid_copy(psid, &map.sid);
955         } 
956         else {
957                 sid_append_rid(psid, pdb_gid_to_group_rid(gid));
958         }
959
960         return psid;
961 }
962
963 /****************************************************************************
964  Convert a SID to gid - locally.
965 ****************************************************************************/
966
967 BOOL local_sid_to_gid(gid_t *pgid, const DOM_SID *psid, enum SID_NAME_USE *name_type)
968 {
969         fstring str;
970         GROUP_MAP map;
971
972         *name_type = SID_NAME_UNKNOWN;
973
974         /*
975          * We can only convert to a gid if this is our local
976          * Domain SID (ie. we are the controling authority).
977          *
978          * Or in the Builtin SID too. JFM, 11/30/2001
979          */
980
981         if (pdb_getgrsid(&map, *psid, MAPPING_WITHOUT_PRIV)) {
982                 
983                 /* the SID is in the mapping table but not mapped */
984                 if (map.gid==(gid_t)-1)
985                         return False;
986
987                 *pgid = map.gid;
988                 *name_type = map.sid_name_use;
989                 DEBUG(10,("local_sid_to_gid: mapped SID %s (%s) -> gid (%u).\n", 
990                           sid_to_string( str, psid),
991                           map.nt_name, (unsigned int)*pgid));
992
993         } else {
994                 uint32 rid;
995                 SAM_ACCOUNT *sam_user = NULL;
996                 if (NT_STATUS_IS_ERR(pdb_init_sam(&sam_user)))
997                         return False;
998                 
999                 if (pdb_getsampwsid(sam_user, psid)) {
1000                         return False;
1001                         pdb_free_sam(&sam_user);
1002                 }
1003
1004                 pdb_free_sam(&sam_user);
1005
1006                 if (!sid_peek_check_rid(get_global_sam_sid(), psid, &rid)) {
1007                         DEBUG(3, ("sid_peek_rid failed - sid '%s' is not in our domain\n", sid_to_string(str, psid)));
1008                         return False;
1009                 }
1010
1011                 if (pdb_rid_is_user(rid))
1012                         return False;
1013                 
1014                 *pgid = pdb_group_rid_to_gid(rid);
1015                 *name_type = SID_NAME_ALIAS;
1016                 DEBUG(10,("local_sid_to_gid: SID %s -> gid (%u).\n", sid_to_string( str, psid),
1017                           (unsigned int)*pgid));
1018         }
1019         
1020         return True;
1021 }
1022
1023 /*************************************************************
1024  Change a password entry in the local smbpasswd file.
1025
1026 It is currently being called by SWAT and by smbpasswd.
1027  
1028  --jerry
1029  *************************************************************/
1030
1031 BOOL local_password_change(const char *user_name, int local_flags,
1032                            const char *new_passwd, 
1033                            char *err_str, size_t err_str_len,
1034                            char *msg_str, size_t msg_str_len)
1035 {
1036         SAM_ACCOUNT     *sam_pass=NULL;
1037         uint16 other_acb;
1038
1039         *err_str = '\0';
1040         *msg_str = '\0';
1041
1042         /* Get the smb passwd entry for this user */
1043         pdb_init_sam(&sam_pass);
1044         if(!pdb_getsampwnam(sam_pass, user_name)) {
1045                 pdb_free_sam(&sam_pass);
1046                 
1047                 if ((local_flags & LOCAL_ADD_USER) || (local_flags & LOCAL_DELETE_USER)) {
1048                         /* Might not exist in /etc/passwd */
1049                         if (!NT_STATUS_IS_OK(pdb_init_sam_new(&sam_pass, user_name))) {
1050                                 slprintf(err_str, err_str_len-1, "Failed initialise SAM_ACCOUNT for user %s.\n", user_name);
1051                                 return False;
1052                         }
1053                 } else {
1054                         slprintf(err_str, err_str_len-1,"Failed to find entry for user %s.\n", user_name);
1055                         return False;
1056                 }
1057         } else {
1058                 /* the entry already existed */
1059                 local_flags &= ~LOCAL_ADD_USER;
1060         }
1061
1062         /* the 'other' acb bits not being changed here */
1063         other_acb =  (pdb_get_acct_ctrl(sam_pass) & (!(ACB_WSTRUST|ACB_DOMTRUST|ACB_SVRTRUST|ACB_NORMAL)));
1064         if (local_flags & LOCAL_TRUST_ACCOUNT) {
1065                 if (!pdb_set_acct_ctrl(sam_pass, ACB_WSTRUST | other_acb, PDB_CHANGED) ) {
1066                         slprintf(err_str, err_str_len - 1, "Failed to set 'trusted workstation account' flags for user %s.\n", user_name);
1067                         pdb_free_sam(&sam_pass);
1068                         return False;
1069                 }
1070         } else if (local_flags & LOCAL_INTERDOM_ACCOUNT) {
1071                 if (!pdb_set_acct_ctrl(sam_pass, ACB_DOMTRUST | other_acb, PDB_CHANGED)) {
1072                         slprintf(err_str, err_str_len - 1, "Failed to set 'domain trust account' flags for user %s.\n", user_name);
1073                         pdb_free_sam(&sam_pass);
1074                         return False;
1075                 }
1076         } else {
1077                 if (!pdb_set_acct_ctrl(sam_pass, ACB_NORMAL | other_acb, PDB_CHANGED)) {
1078                         slprintf(err_str, err_str_len - 1, "Failed to set 'normal account' flags for user %s.\n", user_name);
1079                         pdb_free_sam(&sam_pass);
1080                         return False;
1081                 }
1082         }
1083
1084         /*
1085          * We are root - just write the new password
1086          * and the valid last change time.
1087          */
1088
1089         if (local_flags & LOCAL_DISABLE_USER) {
1090                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_DISABLED, PDB_CHANGED)) {
1091                         slprintf(err_str, err_str_len-1, "Failed to set 'disabled' flag for user %s.\n", user_name);
1092                         pdb_free_sam(&sam_pass);
1093                         return False;
1094                 }
1095         } else if (local_flags & LOCAL_ENABLE_USER) {
1096                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
1097                         slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
1098                         pdb_free_sam(&sam_pass);
1099                         return False;
1100                 }
1101         }
1102         
1103         if (local_flags & LOCAL_SET_NO_PASSWORD) {
1104                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_PWNOTREQ, PDB_CHANGED)) {
1105                         slprintf(err_str, err_str_len-1, "Failed to set 'no password required' flag for user %s.\n", user_name);
1106                         pdb_free_sam(&sam_pass);
1107                         return False;
1108                 }
1109         } else if (local_flags & LOCAL_SET_PASSWORD) {
1110                 /*
1111                  * If we're dealing with setting a completely empty user account
1112                  * ie. One with a password of 'XXXX', but not set disabled (like
1113                  * an account created from scratch) then if the old password was
1114                  * 'XX's then getsmbpwent will have set the ACB_DISABLED flag.
1115                  * We remove that as we're giving this user their first password
1116                  * and the decision hasn't really been made to disable them (ie.
1117                  * don't create them disabled). JRA.
1118                  */
1119                 if ((pdb_get_lanman_passwd(sam_pass)==NULL) && (pdb_get_acct_ctrl(sam_pass)&ACB_DISABLED)) {
1120                         if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
1121                                 slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
1122                                 pdb_free_sam(&sam_pass);
1123                                 return False;
1124                         }
1125                 }
1126                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_PWNOTREQ), PDB_CHANGED)) {
1127                         slprintf(err_str, err_str_len-1, "Failed to unset 'no password required' flag for user %s.\n", user_name);
1128                         pdb_free_sam(&sam_pass);
1129                         return False;
1130                 }
1131                 
1132                 if (!pdb_set_plaintext_passwd (sam_pass, new_passwd)) {
1133                         slprintf(err_str, err_str_len-1, "Failed to set password for user %s.\n", user_name);
1134                         pdb_free_sam(&sam_pass);
1135                         return False;
1136                 }
1137         }       
1138
1139         if (local_flags & LOCAL_ADD_USER) {
1140                 if (pdb_add_sam_account(sam_pass)) {
1141                         slprintf(msg_str, msg_str_len-1, "Added user %s.\n", user_name);
1142                         pdb_free_sam(&sam_pass);
1143                         return True;
1144                 } else {
1145                         slprintf(err_str, err_str_len-1, "Failed to add entry for user %s.\n", user_name);
1146                         pdb_free_sam(&sam_pass);
1147                         return False;
1148                 }
1149         } else if (local_flags & LOCAL_DELETE_USER) {
1150                 if (!pdb_delete_sam_account(sam_pass)) {
1151                         slprintf(err_str,err_str_len-1, "Failed to delete entry for user %s.\n", user_name);
1152                         pdb_free_sam(&sam_pass);
1153                         return False;
1154                 }
1155                 slprintf(msg_str, msg_str_len-1, "Deleted user %s.\n", user_name);
1156         } else {
1157                 if(!pdb_update_sam_account(sam_pass)) {
1158                         slprintf(err_str, err_str_len-1, "Failed to modify entry for user %s.\n", user_name);
1159                         pdb_free_sam(&sam_pass);
1160                         return False;
1161                 }
1162                 if(local_flags & LOCAL_DISABLE_USER)
1163                         slprintf(msg_str, msg_str_len-1, "Disabled user %s.\n", user_name);
1164                 else if (local_flags & LOCAL_ENABLE_USER)
1165                         slprintf(msg_str, msg_str_len-1, "Enabled user %s.\n", user_name);
1166                 else if (local_flags & LOCAL_SET_NO_PASSWORD)
1167                         slprintf(msg_str, msg_str_len-1, "User %s password set to none.\n", user_name);
1168         }
1169
1170         pdb_free_sam(&sam_pass);
1171         return True;
1172 }