This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.
[sfrench/samba-autobuild/.git] / source / passdb / passdb.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Password and authentication handling
4    Copyright (C) Jeremy Allison                 1996-2001
5    Copyright (C) Luke Kenneth Casson Leighton   1996-1998
6    Copyright (C) Gerald (Jerry) Carter          2000-2001
7    Copyright (C) Andrew Bartlett                2001-2002
8       
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 static uid_t fallback_pdb_user_rid_to_uid(uint32 user_rid)
440 {
441         return (uid_t)(((user_rid & (~USER_RID_TYPE))- 1000)/RID_MULTIPLIER);
442 }
443
444
445 /*******************************************************************
446  converts UNIX uid to an NT User RID.
447  ********************************************************************/
448
449 static uint32 fallback_pdb_uid_to_user_rid(uid_t uid)
450 {
451         return (((((uint32)uid)*RID_MULTIPLIER) + 1000) | USER_RID_TYPE);
452 }
453
454 /*******************************************************************
455  Converts NT group RID to a UNIX gid.
456  ********************************************************************/
457
458 gid_t pdb_group_rid_to_gid(uint32 group_rid)
459 {
460         return (gid_t)(((group_rid & (~GROUP_RID_TYPE))- 1000)/RID_MULTIPLIER);
461 }
462
463 /*******************************************************************
464  converts NT Group RID to a UNIX uid.
465  
466  warning: you must not call that function only
467  you must do a call to the group mapping first.
468  there is not anymore a direct link between the gid and the rid.
469  ********************************************************************/
470
471 uint32 pdb_gid_to_group_rid(gid_t gid)
472 {
473   return (((((uint32)gid)*RID_MULTIPLIER) + 1000) | GROUP_RID_TYPE);
474 }
475
476 /*******************************************************************
477  Decides if a RID is a well known RID.
478  ********************************************************************/
479
480 static BOOL pdb_rid_is_well_known(uint32 rid)
481 {
482   return (rid < 1000);
483 }
484
485 /*******************************************************************
486  Decides if a RID is a user or group RID.
487  ********************************************************************/
488
489 BOOL pdb_rid_is_user(uint32 rid)
490 {
491   /* lkcl i understand that NT attaches an enumeration to a RID
492    * such that it can be identified as either a user, group etc
493    * type.  there are 5 such categories, and they are documented.
494    */
495    if(pdb_rid_is_well_known(rid)) {
496       /*
497        * The only well known user RIDs are DOMAIN_USER_RID_ADMIN
498        * and DOMAIN_USER_RID_GUEST.
499        */
500      if(rid == DOMAIN_USER_RID_ADMIN || rid == DOMAIN_USER_RID_GUEST)
501        return True;
502    } else if((rid & RID_TYPE_MASK) == USER_RID_TYPE) {
503      return True;
504    }
505    return False;
506 }
507
508 /*******************************************************************
509  Convert a rid into a name. Used in the lookup SID rpc.
510  ********************************************************************/
511
512 BOOL local_lookup_sid(DOM_SID *sid, char *name, enum SID_NAME_USE *psid_name_use)
513 {
514         uint32 rid;
515         BOOL is_user;
516         SAM_ACCOUNT *sam_account = NULL;
517         BOOL found = False;
518
519         sid_peek_rid(sid, &rid);
520         is_user = pdb_rid_is_user(rid);
521         *psid_name_use = SID_NAME_UNKNOWN;
522
523         DEBUG(5,("local_lookup_sid: looking up %s RID %u.\n", is_user ? "user" :
524                         "group", (unsigned int)rid));
525
526         if(is_user) {
527                 if(rid == DOMAIN_USER_RID_ADMIN) {
528                         char **admin_list = lp_admin_users(-1);
529                         *psid_name_use = SID_NAME_USER;
530                         if (admin_list) {
531                                 char *p = *admin_list;
532                                 if(!next_token(&p, name, NULL, sizeof(fstring)))
533                                         fstrcpy(name, "Administrator");
534                         } else {
535                                 fstrcpy(name, "Administrator");
536                         }
537                 } else if (rid == DOMAIN_USER_RID_GUEST) {
538                         char *p = lp_guestaccount();
539                         *psid_name_use = SID_NAME_USER;
540                         if(!next_token(&p, name, NULL, sizeof(fstring)))
541                                 fstrcpy(name, "Guest");
542                 } else {
543                         uid_t uid;
544                         struct passwd *pass;
545                         
546                         /*
547                          * Don't try to convert the rid to a name if 
548                          * running in appliance mode
549                          */
550                         if (lp_hide_local_users())
551                                 return False;
552
553                         if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_account))) {
554                                 return False;
555                         }
556                         
557                         if (pdb_getsampwrid(sam_account, rid)) {
558                                 fstrcpy(name, pdb_get_username(sam_account));
559                                 *psid_name_use = SID_NAME_USER;
560                                 found = True;
561                         }
562                         
563                         pdb_free_sam(&sam_account);
564                         
565                         if (found) {
566                                 return True;
567                         }
568                         
569                         uid = fallback_pdb_user_rid_to_uid(rid);
570                         pass = getpwuid_alloc(uid);
571                         
572                         *psid_name_use = SID_NAME_USER;
573                         
574                         DEBUG(5,("local_lookup_sid: looking up uid %u %s\n", (unsigned int)uid,
575                                  pass ? "succeeded" : "failed" ));
576                         
577                         if(!pass) {
578                                 slprintf(name, sizeof(fstring)-1, "unix_user.%u", (unsigned int)uid);
579                                 return True;
580                         }
581                         
582                         fstrcpy(name, pass->pw_name);
583                         
584                         DEBUG(5,("local_lookup_sid: found user %s for rid %u\n", name,
585                                  (unsigned int)rid ));
586                         
587                         passwd_free(&pass);
588                 }
589                 
590         } else {
591                 gid_t gid;
592                 struct group *gr; 
593                 GROUP_MAP map;
594                 
595                 /* 
596                  * Don't try to convert the rid to a name if running
597                  * in appliance mode
598                  */
599                 
600                 if (lp_hide_local_users()) 
601                         return False;
602
603                 /* check if it's a mapped group */
604                 if (get_group_map_from_sid(*sid, &map, MAPPING_WITHOUT_PRIV)) {
605                         if (map.gid!=-1) {
606                                 DEBUG(5,("local_lookup_sid: mapped group %s to gid %u\n", map.nt_name, (unsigned int)map.gid));
607                                 fstrcpy(name, map.nt_name);
608                                 *psid_name_use = map.sid_name_use;
609                                 return True;
610                         }
611                 }
612                 
613                 gid = pdb_group_rid_to_gid(rid);
614                 gr = getgrgid(gid);
615
616                 *psid_name_use = SID_NAME_ALIAS;
617
618                 DEBUG(5,("local_lookup_sid: looking up gid %u %s\n", (unsigned int)gid,
619                         gr ? "succeeded" : "failed" ));
620
621                 if(!gr) {
622                         slprintf(name, sizeof(fstring)-1, "unix_group.%u", (unsigned int)gid);
623                         return False;
624                 }
625
626                 fstrcpy( name, gr->gr_name);
627
628                 DEBUG(5,("local_lookup_sid: found group %s for rid %u\n", name,
629                         (unsigned int)rid ));
630         }
631
632         return True;
633 }
634
635 /*******************************************************************
636  Convert a name into a SID. Used in the lookup name rpc.
637  ********************************************************************/
638
639 BOOL local_lookup_name(const char *c_user, DOM_SID *psid, enum SID_NAME_USE *psid_name_use)
640 {
641         extern DOM_SID global_sid_World_Domain;
642         struct passwd *pass = NULL;
643         DOM_SID local_sid;
644         fstring user;
645         SAM_ACCOUNT *sam_account = NULL;
646         BOOL found = False;
647         
648         *psid_name_use = SID_NAME_UNKNOWN;
649
650         /*
651          * user may be quoted a const string, and map_username and
652          * friends can modify it. Make a modifiable copy. JRA.
653          */
654
655         fstrcpy(user, c_user);
656
657         sid_copy(&local_sid, &global_sam_sid);
658
659         /*
660          * Special case for MACHINE\Everyone. Map to the world_sid.
661          */
662
663         if(strequal(user, "Everyone")) {
664                 sid_copy( psid, &global_sid_World_Domain);
665                 sid_append_rid(psid, 0);
666                 *psid_name_use = SID_NAME_ALIAS;
667                 return True;
668         }
669
670         /* 
671          * Don't lookup local unix users if running in appliance mode
672          */
673         if (lp_hide_local_users()) 
674                 return False;
675
676         (void)map_username(user);
677
678         if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_account))) {
679                 return False;
680         }
681         
682         if (pdb_getsampwnam(sam_account, user)) {
683                 sid_append_rid( &local_sid, pdb_get_user_rid(sam_account));
684                 *psid_name_use = SID_NAME_USER;
685                 
686                 sid_copy( psid, &local_sid);
687                 found = True;
688         }
689
690         pdb_free_sam(&sam_account);
691
692         if (!found && (pass = Get_Pwnam(user))) {
693                 sid_append_rid( &local_sid, fallback_pdb_uid_to_user_rid(pass->pw_uid));
694                 *psid_name_use = SID_NAME_USER;
695                 pdb_free_sam(&sam_account);
696
697         } else if (!found) {
698                 /*
699                  * Maybe it was a group ?
700                  */
701                 struct group *grp;
702                 GROUP_MAP map;
703                 
704                 pdb_free_sam(&sam_account);
705
706                 /* check if it's a mapped group */
707                 if (get_group_map_from_ntname(user, &map, MAPPING_WITHOUT_PRIV)) {
708                         if (map.gid!=-1) {
709                                 /* yes it's a mapped group to a valid unix group */
710                                 sid_copy(&local_sid, &map.sid);
711                                 *psid_name_use = map.sid_name_use;
712                         }
713                         else
714                                 /* it's a correct name but not mapped so it points to nothing*/
715                                 return False;
716                 } else {
717                         /* it's not a mapped group */
718                         grp = getgrnam(user);
719                         if(!grp)
720                                 return False;
721
722                         /* 
723                          *check if it's mapped, if it is reply it doesn't exist
724                          *
725                          * that's to prevent this case:
726                          *
727                          * unix group ug is mapped to nt group ng
728                          * someone does a lookup on ug
729                          * we must not reply as it doesn't "exist" anymore
730                          * for NT. For NT only ng exists.
731                          * JFM, 30/11/2001
732                          */
733                         
734                         if(get_group_map_from_gid(grp->gr_gid, &map, MAPPING_WITHOUT_PRIV)){
735                                 return False;
736                         }
737
738                         sid_append_rid( &local_sid, pdb_gid_to_group_rid(grp->gr_gid));
739                         *psid_name_use = SID_NAME_ALIAS;
740                 }
741         }
742
743         sid_copy( psid, &local_sid);
744
745         return True;
746 }
747
748 /****************************************************************************
749  Convert a uid to SID - locally.
750 ****************************************************************************/
751
752 DOM_SID *local_uid_to_sid(DOM_SID *psid, uid_t uid)
753 {
754         extern DOM_SID global_sam_sid;
755         struct passwd *pass;
756         SAM_ACCOUNT *sam_user = NULL;
757
758         sid_copy(psid, &global_sam_sid);
759
760         if(!(pass = getpwuid_alloc(uid)))
761                 return NULL;
762
763         if (NT_STATUS_IS_ERR(pdb_init_sam(&sam_user))) {
764                 passwd_free(&pass);
765                 return NULL;
766         }
767         
768         if (!pdb_getsampwnam(sam_user, pass->pw_name)) {
769                 pdb_free_sam(&sam_user);
770                 return NULL;
771         }
772
773         passwd_free(&pass);
774
775         sid_append_rid(psid, pdb_get_user_rid(sam_user));
776
777         pdb_free_sam(&sam_user);
778
779         return psid;
780 }
781
782 /****************************************************************************
783  Convert a SID to uid - locally.
784 ****************************************************************************/
785
786 BOOL local_sid_to_uid(uid_t *puid, DOM_SID *psid, enum SID_NAME_USE *name_type)
787 {
788         extern DOM_SID global_sam_sid;
789
790         DOM_SID dom_sid;
791         uint32 rid;
792         fstring str;
793         struct passwd *pass;
794         SAM_ACCOUNT *sam_user = NULL;
795
796         *name_type = SID_NAME_UNKNOWN;
797
798         sid_copy(&dom_sid, psid);
799         sid_split_rid(&dom_sid, &rid);
800
801         if (!pdb_rid_is_user(rid))
802                 return False;
803
804         /*
805          * We can only convert to a uid if this is our local
806          * Domain SID (ie. we are the controling authority).
807          */
808         if (!sid_equal(&global_sam_sid, &dom_sid))
809                 return False;
810
811         if (NT_STATUS_IS_ERR(pdb_init_sam(&sam_user)))
812                 return False;
813         
814         if (!pdb_getsampwrid(sam_user, rid)) {
815                 pdb_free_sam(&sam_user);
816                 return False;
817         }
818         
819         *puid = pdb_get_uid(sam_user);
820         if (*puid == -1)
821                 return False;
822
823         pdb_free_sam(&sam_user);
824
825         /*
826          * Ensure this uid really does exist.
827          */
828         if(!(pass = getpwuid_alloc(*puid)))
829                 return False;
830
831         DEBUG(10,("local_sid_to_uid: SID %s -> uid (%u) (%s).\n", sid_to_string( str, psid),
832                 (unsigned int)*puid, pass->pw_name ));
833
834         passwd_free(&pass);
835
836         *name_type = SID_NAME_USER;
837
838         return True;
839 }
840
841 /****************************************************************************
842  Convert a gid to SID - locally.
843 ****************************************************************************/
844
845 DOM_SID *local_gid_to_sid(DOM_SID *psid, gid_t gid)
846 {
847         extern DOM_SID global_sam_sid;
848         GROUP_MAP map;
849
850         sid_copy(psid, &global_sam_sid);
851         
852         if (get_group_map_from_gid(gid, &map, MAPPING_WITHOUT_PRIV)) {
853                 sid_copy(psid, &map.sid);
854         }
855         else {
856                 sid_append_rid(psid, pdb_gid_to_group_rid(gid));
857         }
858
859         return psid;
860 }
861
862 /****************************************************************************
863  Convert a SID to gid - locally.
864 ****************************************************************************/
865
866 BOOL local_sid_to_gid(gid_t *pgid, DOM_SID *psid, enum SID_NAME_USE *name_type)
867 {
868         extern DOM_SID global_sam_sid;
869         DOM_SID dom_sid;
870         uint32 rid;
871         fstring str;
872         struct group *grp;
873         GROUP_MAP map;
874
875         *name_type = SID_NAME_UNKNOWN;
876
877         sid_copy(&dom_sid, psid);
878         sid_split_rid(&dom_sid, &rid);
879
880         /*
881          * We can only convert to a gid if this is our local
882          * Domain SID (ie. we are the controling authority).
883          *
884          * Or in the Builtin SID too. JFM, 11/30/2001
885          */
886
887         if (!sid_equal(&global_sam_sid, &dom_sid))
888                 return False;
889
890         if (pdb_rid_is_user(rid))
891                 return False;
892
893         if (get_group_map_from_sid(*psid, &map, MAPPING_WITHOUT_PRIV)) {
894                 
895                 /* the SID is in the mapping table but not mapped */
896                 if (map.gid==-1)
897                         return False;
898
899                 sid_peek_rid(&map.sid, &rid);
900                 *pgid = rid;
901                 *name_type = map.sid_name_use;
902         } else {
903                 *pgid = pdb_group_rid_to_gid(rid);
904                 *name_type = SID_NAME_ALIAS;
905         }
906
907         /*
908          * Ensure this gid really does exist.
909          */
910
911         if(!(grp = getgrgid(*pgid)))
912                 return False;
913
914         DEBUG(10,("local_sid_to_gid: SID %s -> gid (%u) (%s).\n", sid_to_string( str, psid),
915                 (unsigned int)*pgid, grp->gr_name ));
916
917         return True;
918 }
919
920 /** 
921  * Quick hack to do an easy ucs2 -> mulitbyte conversion 
922  * @return static buffer containing the converted string
923  **/
924
925 static char *pdb_convert(const UNISTR2 *from)
926 {
927         static pstring convert_buffer;
928         *convert_buffer = 0;
929         if (!from) {
930                 return convert_buffer;
931         }
932
933         unistr2_to_ascii(convert_buffer, from, sizeof(pstring));
934         return convert_buffer;
935 }
936
937 /*************************************************************
938  Copies a SAM_USER_INFO_23 to a SAM_ACCOUNT
939  **************************************************************/
940
941 void copy_id23_to_sam_passwd(SAM_ACCOUNT *to, SAM_USER_INFO_23 *from)
942 {
943
944         if (from == NULL || to == NULL) 
945                 return;
946
947         pdb_set_logon_time(to,nt_time_to_unix(&from->logon_time), True);
948         pdb_set_logoff_time(to,nt_time_to_unix(&from->logoff_time), True);
949         pdb_set_kickoff_time(to, nt_time_to_unix(&from->kickoff_time), True);
950         pdb_set_pass_can_change_time(to, nt_time_to_unix(&from->pass_can_change_time), True);
951         pdb_set_pass_must_change_time(to, nt_time_to_unix(&from->pass_must_change_time), True);
952
953         pdb_set_pass_last_set_time(to, nt_time_to_unix(&from->pass_last_set_time));
954
955         if (from->uni_user_name.buffer)
956                 pdb_set_username(to      , pdb_convert(&from->uni_user_name   ));
957         if (from->uni_full_name.buffer)
958                 pdb_set_fullname(to      , pdb_convert(&from->uni_full_name   ));
959         if (from->uni_home_dir.buffer)
960                 pdb_set_homedir(to       , pdb_convert(&from->uni_home_dir    ), True);
961         if (from->uni_dir_drive.buffer)
962                 pdb_set_dir_drive(to     , pdb_convert(&from->uni_dir_drive   ), True);
963         if (from->uni_logon_script.buffer)
964                 pdb_set_logon_script(to  , pdb_convert(&from->uni_logon_script), True);
965         if (from->uni_profile_path.buffer)
966                 pdb_set_profile_path(to  , pdb_convert(&from->uni_profile_path), True);
967         if (from->uni_acct_desc.buffer)
968                 pdb_set_acct_desc(to     , pdb_convert(&from->uni_acct_desc   ));
969         if (from->uni_workstations.buffer)
970                 pdb_set_workstations(to  , pdb_convert(&from->uni_workstations));
971         if (from->uni_unknown_str.buffer)
972                 pdb_set_unknown_str(to   , pdb_convert(&from->uni_unknown_str ));
973         if (from->uni_munged_dial.buffer)
974                 pdb_set_munged_dial(to   , pdb_convert(&from->uni_munged_dial ));
975
976         if (from->user_rid)
977                 pdb_set_user_rid(to, from->user_rid);
978         if (from->group_rid)
979                 pdb_set_group_rid(to, from->group_rid);
980
981         pdb_set_acct_ctrl(to, from->acb_info);
982         pdb_set_unknown_3(to, from->unknown_3);
983
984         pdb_set_logon_divs(to, from->logon_divs);
985         pdb_set_hours_len(to, from->logon_hrs.len);
986         pdb_set_hours(to, from->logon_hrs.hours);
987
988         pdb_set_unknown_5(to, from->unknown_5);
989         pdb_set_unknown_6(to, from->unknown_6);
990 }
991
992
993 /*************************************************************
994  Copies a sam passwd.
995  **************************************************************/
996
997 void copy_id21_to_sam_passwd(SAM_ACCOUNT *to, SAM_USER_INFO_21 *from)
998 {
999         if (from == NULL || to == NULL) 
1000                 return;
1001
1002         pdb_set_logon_time(to,nt_time_to_unix(&from->logon_time), True);
1003         pdb_set_logoff_time(to,nt_time_to_unix(&from->logoff_time), True);
1004         pdb_set_kickoff_time(to, nt_time_to_unix(&from->kickoff_time), True);
1005         pdb_set_pass_can_change_time(to, nt_time_to_unix(&from->pass_can_change_time), True);
1006         pdb_set_pass_must_change_time(to, nt_time_to_unix(&from->pass_must_change_time), True);
1007
1008         pdb_set_pass_last_set_time(to, nt_time_to_unix(&from->pass_last_set_time));
1009
1010         if (from->uni_user_name.buffer)
1011                 pdb_set_username(to      , pdb_convert(&from->uni_user_name   ));
1012         if (from->uni_full_name.buffer)
1013                 pdb_set_fullname(to      , pdb_convert(&from->uni_full_name   ));
1014         if (from->uni_home_dir.buffer)
1015                 pdb_set_homedir(to       , pdb_convert(&from->uni_home_dir    ), True);
1016         if (from->uni_dir_drive.buffer)
1017                 pdb_set_dir_drive(to     , pdb_convert(&from->uni_dir_drive   ), True);
1018         if (from->uni_logon_script.buffer)
1019                 pdb_set_logon_script(to  , pdb_convert(&from->uni_logon_script), True);
1020         if (from->uni_profile_path.buffer)
1021                 pdb_set_profile_path(to  , pdb_convert(&from->uni_profile_path), True);
1022         if (from->uni_acct_desc.buffer)
1023                 pdb_set_acct_desc(to     , pdb_convert(&from->uni_acct_desc   ));
1024         if (from->uni_workstations.buffer)
1025                 pdb_set_workstations(to  , pdb_convert(&from->uni_workstations));
1026         if (from->uni_unknown_str.buffer)
1027                 pdb_set_unknown_str(to   , pdb_convert(&from->uni_unknown_str ));
1028         if (from->uni_munged_dial.buffer)
1029                 pdb_set_munged_dial(to   , pdb_convert(&from->uni_munged_dial ));
1030
1031         if (from->user_rid)
1032                 pdb_set_user_rid(to, from->user_rid);
1033         if (from->group_rid)
1034                 pdb_set_group_rid(to, from->group_rid);
1035
1036         /* FIXME!!  Do we need to copy the passwords here as well?
1037            I don't know.  Need to figure this out   --jerry */
1038
1039         /* Passwords dealt with in caller --abartlet */
1040
1041         pdb_set_acct_ctrl(to, from->acb_info);
1042         pdb_set_unknown_3(to, from->unknown_3);
1043
1044         pdb_set_logon_divs(to, from->logon_divs);
1045         pdb_set_hours_len(to, from->logon_hrs.len);
1046         pdb_set_hours(to, from->logon_hrs.hours);
1047
1048         pdb_set_unknown_5(to, from->unknown_5);
1049         pdb_set_unknown_6(to, from->unknown_6);
1050 }
1051
1052
1053 /*************************************************************
1054  Change a password entry in the local smbpasswd file.
1055
1056  FIXME!!  The function needs to be abstracted into the
1057  passdb interface or something.  It is currently being called
1058  by _api_samr_create_user() in rpc_server/srv_samr.c,
1059  in SWAT and by smbpasswd/pdbedit.
1060  
1061  --jerry
1062  *************************************************************/
1063
1064 BOOL local_password_change(const char *user_name, int local_flags,
1065                            const char *new_passwd, 
1066                            char *err_str, size_t err_str_len,
1067                            char *msg_str, size_t msg_str_len)
1068 {
1069         struct passwd  *pwd = NULL;
1070         SAM_ACCOUNT     *sam_pass=NULL;
1071
1072         *err_str = '\0';
1073         *msg_str = '\0';
1074
1075         /* Get the smb passwd entry for this user */
1076         pdb_init_sam(&sam_pass);
1077         if(!pdb_getsampwnam(sam_pass, user_name)) {
1078                 pdb_free_sam(&sam_pass);
1079                 
1080                 if (local_flags & LOCAL_ADD_USER) {
1081                         pwd = getpwnam_alloc(user_name);
1082                 } else if (local_flags & LOCAL_DELETE_USER) {
1083                         /* Might not exist in /etc/passwd */
1084                 } else {
1085                         slprintf(err_str, err_str_len-1,"Failed to find entry for user %s.\n", user_name);
1086                         return False;
1087                 }
1088                 
1089                 if (pwd) {
1090                         /* Local user found, so init from this */
1091                         if (!NT_STATUS_IS_OK(pdb_init_sam_pw(&sam_pass, pwd))){
1092                                 slprintf(err_str, err_str_len-1, "Failed initialise SAM_ACCOUNT for user %s.\n", user_name);
1093                                 passwd_free(&pwd);
1094                                 return False;
1095                         }
1096                 
1097                         passwd_free(&pwd);
1098                 } else {
1099                         if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_pass))){
1100                                 slprintf(err_str, err_str_len-1, "Failed initialise SAM_ACCOUNT for user %s.\n", user_name);
1101                                 return False;
1102                         }
1103
1104                         if (!pdb_set_username(sam_pass, user_name)) {
1105                                 slprintf(err_str, err_str_len - 1, "Failed to set username for user %s.\n", user_name);
1106                                 pdb_free_sam(&sam_pass);
1107                                 return False;
1108                         }
1109                 }
1110                 if (local_flags & LOCAL_TRUST_ACCOUNT) {
1111                         if (!pdb_set_acct_ctrl(sam_pass, ACB_WSTRUST)) {
1112                                 slprintf(err_str, err_str_len - 1, "Failed to set 'trusted workstation account' flags for user %s.\n", user_name);
1113                                 pdb_free_sam(&sam_pass);
1114                                 return False;
1115                         }
1116                 } else if (local_flags & LOCAL_INTERDOM_ACCOUNT) {
1117                         if (!pdb_set_acct_ctrl(sam_pass, ACB_DOMTRUST)) {
1118                                 slprintf(err_str, err_str_len - 1, "Failed to set 'domain trust account' flags for user %s.\n", user_name);
1119                                 pdb_free_sam(&sam_pass);
1120                                 return False;
1121                         }
1122                 } else {
1123                         if (!pdb_set_acct_ctrl(sam_pass, ACB_NORMAL)) {
1124                                 slprintf(err_str, err_str_len - 1, "Failed to set 'normal account' flags for user %s.\n", user_name);
1125                                 pdb_free_sam(&sam_pass);
1126                                 return False;
1127                         }
1128                 }
1129
1130         } else {
1131                 /* the entry already existed */
1132                 local_flags &= ~LOCAL_ADD_USER;
1133         }
1134
1135         /*
1136          * We are root - just write the new password
1137          * and the valid last change time.
1138          */
1139
1140         if (local_flags & LOCAL_DISABLE_USER) {
1141                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_DISABLED)) {
1142                         slprintf(err_str, err_str_len-1, "Failed to set 'disabled' flag for user %s.\n", user_name);
1143                         pdb_free_sam(&sam_pass);
1144                         return False;
1145                 }
1146         } else if (local_flags & LOCAL_ENABLE_USER) {
1147                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED))) {
1148                         slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
1149                         pdb_free_sam(&sam_pass);
1150                         return False;
1151                 }
1152         }
1153         
1154         if (local_flags & LOCAL_SET_NO_PASSWORD) {
1155                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_PWNOTREQ)) {
1156                         slprintf(err_str, err_str_len-1, "Failed to set 'no password required' flag for user %s.\n", user_name);
1157                         pdb_free_sam(&sam_pass);
1158                         return False;
1159                 }
1160         } else if (local_flags & LOCAL_SET_PASSWORD) {
1161                 /*
1162                  * If we're dealing with setting a completely empty user account
1163                  * ie. One with a password of 'XXXX', but not set disabled (like
1164                  * an account created from scratch) then if the old password was
1165                  * 'XX's then getsmbpwent will have set the ACB_DISABLED flag.
1166                  * We remove that as we're giving this user their first password
1167                  * and the decision hasn't really been made to disable them (ie.
1168                  * don't create them disabled). JRA.
1169                  */
1170                 if ((pdb_get_lanman_passwd(sam_pass)==NULL) && (pdb_get_acct_ctrl(sam_pass)&ACB_DISABLED)) {
1171                         if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED))) {
1172                                 slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
1173                                 pdb_free_sam(&sam_pass);
1174                                 return False;
1175                         }
1176                 }
1177                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_PWNOTREQ))) {
1178                         slprintf(err_str, err_str_len-1, "Failed to unset 'no password required' flag for user %s.\n", user_name);
1179                         pdb_free_sam(&sam_pass);
1180                         return False;
1181                 }
1182                 
1183                 if (!pdb_set_plaintext_passwd (sam_pass, new_passwd)) {
1184                         slprintf(err_str, err_str_len-1, "Failed to set password for user %s.\n", user_name);
1185                         pdb_free_sam(&sam_pass);
1186                         return False;
1187                 }
1188         }       
1189
1190         if (local_flags & LOCAL_ADD_USER) {
1191                 if (pdb_add_sam_account(sam_pass)) {
1192                         slprintf(msg_str, msg_str_len-1, "Added user %s.\n", user_name);
1193                         pdb_free_sam(&sam_pass);
1194                         return True;
1195                 } else {
1196                         slprintf(err_str, err_str_len-1, "Failed to add entry for user %s.\n", user_name);
1197                         pdb_free_sam(&sam_pass);
1198                         return False;
1199                 }
1200         } else if (local_flags & LOCAL_DELETE_USER) {
1201                 if (!pdb_delete_sam_account(sam_pass)) {
1202                         slprintf(err_str,err_str_len-1, "Failed to delete entry for user %s.\n", user_name);
1203                         pdb_free_sam(&sam_pass);
1204                         return False;
1205                 }
1206                 slprintf(msg_str, msg_str_len-1, "Deleted user %s.\n", user_name);
1207         } else {
1208                 if(!pdb_update_sam_account(sam_pass)) {
1209                         slprintf(err_str, err_str_len-1, "Failed to modify entry for user %s.\n", user_name);
1210                         pdb_free_sam(&sam_pass);
1211                         return False;
1212                 }
1213                 if(local_flags & LOCAL_DISABLE_USER)
1214                         slprintf(msg_str, msg_str_len-1, "Disabled user %s.\n", user_name);
1215                 else if (local_flags & LOCAL_ENABLE_USER)
1216                         slprintf(msg_str, msg_str_len-1, "Enabled user %s.\n", user_name);
1217                 else if (local_flags & LOCAL_SET_NO_PASSWORD)
1218                         slprintf(msg_str, msg_str_len-1, "User %s password set to none.\n", user_name);
1219         }
1220
1221         pdb_free_sam(&sam_pass);
1222         return True;
1223 }