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