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