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