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