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