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