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