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