*id_to_*id call reshape to return NTSTATUS errors
[ira/wip.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 static 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, becouse 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                 /* this is a hack this thing should not be set
295                    here --SSS */
296
297                 /* set Domain Users by default ! */
298                 sid_copy(&g_sid, get_global_sam_sid());
299                 sid_append_rid(&g_sid,  DOMAIN_GROUP_RID_USERS);
300                 pdb_set_group_sid(*new_sam_acct, &g_sid, PDB_SET);
301         }
302         return NT_STATUS_OK;
303 }
304
305
306 /**
307  * Free the contets of the SAM_ACCOUNT, but not the structure.
308  *
309  * Also wipes the LM and NT hashes and plaintext password from 
310  * memory.
311  *
312  * @param user SAM_ACCOUNT to free members of.
313  **/
314
315 static void pdb_free_sam_contents(SAM_ACCOUNT *user)
316 {
317
318         /* Kill off sensitive data.  Free()ed by the
319            talloc mechinism */
320
321         data_blob_clear_free(&(user->private.lm_pw));
322         data_blob_clear_free(&(user->private.nt_pw));
323         if (user->private.plaintext_pw!=NULL)
324                 memset(user->private.plaintext_pw,'\0',strlen(user->private.plaintext_pw));
325 }
326
327
328 /************************************************************
329  Reset the SAM_ACCOUNT and free the NT/LM hashes.
330  ***********************************************************/
331
332 NTSTATUS pdb_reset_sam(SAM_ACCOUNT *user)
333 {
334         if (user == NULL) {
335                 DEBUG(0,("pdb_reset_sam: SAM_ACCOUNT was NULL\n"));
336 #if 0
337                 smb_panic("NULL pointer passed to pdb_free_sam\n");
338 #endif
339                 return NT_STATUS_UNSUCCESSFUL;
340         }
341         
342         pdb_free_sam_contents(user);
343
344         pdb_fill_default_sam(user);
345
346         return NT_STATUS_OK;
347 }
348
349
350 /************************************************************
351  Free the SAM_ACCOUNT and the member pointers.
352  ***********************************************************/
353
354 NTSTATUS pdb_free_sam(SAM_ACCOUNT **user)
355 {
356         if (*user == NULL) {
357                 DEBUG(0,("pdb_free_sam: SAM_ACCOUNT was NULL\n"));
358 #if 0
359                 smb_panic("NULL pointer passed to pdb_free_sam\n");
360 #endif
361                 return NT_STATUS_UNSUCCESSFUL;
362         }
363
364         pdb_free_sam_contents(*user);
365         
366         if ((*user)->free_fn) {
367                 (*user)->free_fn(user);
368         }
369
370         return NT_STATUS_OK;    
371 }
372
373 /**************************************************************************
374  * This function will take care of all the steps needed to correctly
375  * allocate and set the user SID, please do use this function to create new
376  * users, messing with SIDs is not good.
377  *
378  * account_data must be provided initialized, pwd may be null.
379  *                                                                      SSS
380  ***************************************************************************/
381
382 NTSTATUS pdb_set_sam_sids(SAM_ACCOUNT *account_data, const struct passwd *pwd)
383 {
384         const char *guest_account = lp_guestaccount();
385         GROUP_MAP map;
386         
387         if (!account_data || !pwd) {
388                 return NT_STATUS_INVALID_PARAMETER;
389         }
390
391         /* this is a hack this thing should not be set
392            this way --SSS */
393         if (!(guest_account && *guest_account)) {
394                 DEBUG(1, ("NULL guest account!?!?\n"));
395                 return NT_STATUS_UNSUCCESSFUL;
396         } else {
397                 /* Ensure this *must* be set right */
398                 if (strcmp(pwd->pw_name, guest_account) == 0) {
399                         if (!pdb_set_user_sid_from_rid(account_data, DOMAIN_USER_RID_GUEST, PDB_DEFAULT)) {
400                                 return NT_STATUS_UNSUCCESSFUL;
401                         }
402                         if (!pdb_set_group_sid_from_rid(account_data, DOMAIN_GROUP_RID_GUESTS, PDB_DEFAULT)) {
403                                 return NT_STATUS_UNSUCCESSFUL;
404                         }
405                         return NT_STATUS_OK;
406                 }
407         }
408
409         if (!pdb_set_user_sid_from_rid(account_data, fallback_pdb_uid_to_user_rid(pwd->pw_uid), PDB_SET)) {
410                 DEBUG(0,("Can't set User SID from RID!\n"));
411                 return NT_STATUS_INVALID_PARAMETER;
412         }
413         
414         /* call the mapping code here */
415         if(pdb_getgrgid(&map, pwd->pw_gid, MAPPING_WITHOUT_PRIV)) {
416                 if (!pdb_set_group_sid(account_data, &map.sid, PDB_SET)){
417                         DEBUG(0,("Can't set Group SID!\n"));
418                         return NT_STATUS_INVALID_PARAMETER;
419                 }
420         } 
421         else {
422                 if (!pdb_set_group_sid_from_rid(account_data, pdb_gid_to_group_rid(pwd->pw_gid), PDB_SET)) {
423                         DEBUG(0,("Can't set Group SID\n"));
424                         return NT_STATUS_INVALID_PARAMETER;
425                 }
426         }
427
428         return NT_STATUS_OK;
429 }
430
431 /**********************************************************
432  Encode the account control bits into a string.
433  length = length of string to encode into (including terminating
434  null). length *MUST BE MORE THAN 2* !
435  **********************************************************/
436
437 char *pdb_encode_acct_ctrl(uint16 acct_ctrl, size_t length)
438 {
439         static fstring acct_str;
440         size_t i = 0;
441
442         acct_str[i++] = '[';
443
444         if (acct_ctrl & ACB_PWNOTREQ ) acct_str[i++] = 'N';
445         if (acct_ctrl & ACB_DISABLED ) acct_str[i++] = 'D';
446         if (acct_ctrl & ACB_HOMDIRREQ) acct_str[i++] = 'H';
447         if (acct_ctrl & ACB_TEMPDUP  ) acct_str[i++] = 'T'; 
448         if (acct_ctrl & ACB_NORMAL   ) acct_str[i++] = 'U';
449         if (acct_ctrl & ACB_MNS      ) acct_str[i++] = 'M';
450         if (acct_ctrl & ACB_WSTRUST  ) acct_str[i++] = 'W';
451         if (acct_ctrl & ACB_SVRTRUST ) acct_str[i++] = 'S';
452         if (acct_ctrl & ACB_AUTOLOCK ) acct_str[i++] = 'L';
453         if (acct_ctrl & ACB_PWNOEXP  ) acct_str[i++] = 'X';
454         if (acct_ctrl & ACB_DOMTRUST ) acct_str[i++] = 'I';
455
456         for ( ; i < length - 2 ; i++ )
457                 acct_str[i] = ' ';
458
459         i = length - 2;
460         acct_str[i++] = ']';
461         acct_str[i++] = '\0';
462
463         return acct_str;
464 }     
465
466 /**********************************************************
467  Decode the account control bits from a string.
468  **********************************************************/
469
470 uint16 pdb_decode_acct_ctrl(const char *p)
471 {
472         uint16 acct_ctrl = 0;
473         BOOL finished = False;
474
475         /*
476          * Check if the account type bits have been encoded after the
477          * NT password (in the form [NDHTUWSLXI]).
478          */
479
480         if (*p != '[')
481                 return 0;
482
483         for (p++; *p && !finished; p++) {
484                 switch (*p) {
485                         case 'N': { acct_ctrl |= ACB_PWNOTREQ ; break; /* 'N'o password. */ }
486                         case 'D': { acct_ctrl |= ACB_DISABLED ; break; /* 'D'isabled. */ }
487                         case 'H': { acct_ctrl |= ACB_HOMDIRREQ; break; /* 'H'omedir required. */ }
488                         case 'T': { acct_ctrl |= ACB_TEMPDUP  ; break; /* 'T'emp account. */ } 
489                         case 'U': { acct_ctrl |= ACB_NORMAL   ; break; /* 'U'ser account (normal). */ } 
490                         case 'M': { acct_ctrl |= ACB_MNS      ; break; /* 'M'NS logon user account. What is this ? */ } 
491                         case 'W': { acct_ctrl |= ACB_WSTRUST  ; break; /* 'W'orkstation account. */ } 
492                         case 'S': { acct_ctrl |= ACB_SVRTRUST ; break; /* 'S'erver account. */ } 
493                         case 'L': { acct_ctrl |= ACB_AUTOLOCK ; break; /* 'L'ocked account. */ } 
494                         case 'X': { acct_ctrl |= ACB_PWNOEXP  ; break; /* No 'X'piry on password */ } 
495                         case 'I': { acct_ctrl |= ACB_DOMTRUST ; break; /* 'I'nterdomain trust account. */ }
496             case ' ': { break; }
497                         case ':':
498                         case '\n':
499                         case '\0': 
500                         case ']':
501                         default:  { finished = True; }
502                 }
503         }
504
505         return acct_ctrl;
506 }
507
508 /*************************************************************
509  Routine to set 32 hex password characters from a 16 byte array.
510 **************************************************************/
511
512 void pdb_sethexpwd(char *p, const unsigned char *pwd, uint16 acct_ctrl)
513 {
514         if (pwd != NULL) {
515                 int i;
516                 for (i = 0; i < 16; i++)
517                         slprintf(&p[i*2], 3, "%02X", pwd[i]);
518         } else {
519                 if (acct_ctrl & ACB_PWNOTREQ)
520                         safe_strcpy(p, "NO PASSWORDXXXXXXXXXXXXXXXXXXXXX", 33);
521                 else
522                         safe_strcpy(p, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 33);
523         }
524 }
525
526 /*************************************************************
527  Routine to get the 32 hex characters and turn them
528  into a 16 byte array.
529 **************************************************************/
530
531 BOOL pdb_gethexpwd(const char *p, unsigned char *pwd)
532 {
533         int i;
534         unsigned char   lonybble, hinybble;
535         const char      *hexchars = "0123456789ABCDEF";
536         char           *p1, *p2;
537         
538         if (!p)
539                 return (False);
540         
541         for (i = 0; i < 32; i += 2) {
542                 hinybble = toupper(p[i]);
543                 lonybble = toupper(p[i + 1]);
544
545                 p1 = strchr(hexchars, hinybble);
546                 p2 = strchr(hexchars, lonybble);
547
548                 if (!p1 || !p2)
549                         return (False);
550
551                 hinybble = PTR_DIFF(p1, hexchars);
552                 lonybble = PTR_DIFF(p2, hexchars);
553
554                 pwd[i / 2] = (hinybble << 4) | lonybble;
555         }
556         return (True);
557 }
558
559 static int algorithmic_rid_base(void)
560 {
561         static int rid_offset = 0;
562
563         if (rid_offset != 0)
564                 return rid_offset;
565
566         rid_offset = lp_algorithmic_rid_base();
567
568         if (rid_offset < BASE_RID) {  
569                 /* Try to prevent admin foot-shooting, we can't put algorithmic
570                    rids below 1000, that's the 'well known RIDs' on NT */
571                 DEBUG(0, ("'algorithmic rid base' must be equal to or above %ld\n", BASE_RID));
572                 rid_offset = BASE_RID;
573         }
574         if (rid_offset & 1) {
575                 DEBUG(0, ("algorithmic rid base must be even\n"));
576                 rid_offset += 1;
577         }
578         return rid_offset;
579 }
580
581 /*******************************************************************
582  Converts NT user RID to a UNIX uid.
583  ********************************************************************/
584
585 uid_t fallback_pdb_user_rid_to_uid(uint32 user_rid)
586 {
587         int rid_offset = algorithmic_rid_base();
588         return (uid_t)(((user_rid & (~USER_RID_TYPE)) - rid_offset)/RID_MULTIPLIER);
589 }
590
591 /*******************************************************************
592  converts UNIX uid to an NT User RID.
593  ********************************************************************/
594
595 uint32 fallback_pdb_uid_to_user_rid(uid_t uid)
596 {
597         int rid_offset = algorithmic_rid_base();
598         return (((((uint32)uid)*RID_MULTIPLIER) + rid_offset) | USER_RID_TYPE);
599 }
600
601 /*******************************************************************
602  Converts NT group RID to a UNIX gid.
603  ********************************************************************/
604
605 gid_t pdb_group_rid_to_gid(uint32 group_rid)
606 {
607         int rid_offset = algorithmic_rid_base();
608         return (gid_t)(((group_rid & (~GROUP_RID_TYPE))- rid_offset)/RID_MULTIPLIER);
609 }
610
611 /*******************************************************************
612  converts NT Group RID to a UNIX uid.
613  
614  warning: you must not call that function only
615  you must do a call to the group mapping first.
616  there is not anymore a direct link between the gid and the rid.
617  ********************************************************************/
618
619 uint32 pdb_gid_to_group_rid(gid_t gid)
620 {
621         int rid_offset = algorithmic_rid_base();
622         return (((((uint32)gid)*RID_MULTIPLIER) + rid_offset) | GROUP_RID_TYPE);
623 }
624
625 /*******************************************************************
626  Decides if a RID is a well known RID.
627  ********************************************************************/
628
629 static BOOL pdb_rid_is_well_known(uint32 rid)
630 {
631         /* Not using rid_offset here, becouse this is the actual
632            NT fixed value (1000) */
633
634         return (rid < BASE_RID);
635 }
636
637 /*******************************************************************
638  Decides if a RID is a user or group RID.
639  ********************************************************************/
640
641 BOOL fallback_pdb_rid_is_user(uint32 rid)
642 {
643   /* lkcl i understand that NT attaches an enumeration to a RID
644    * such that it can be identified as either a user, group etc
645    * type.  there are 5 such categories, and they are documented.
646    */
647         /* However, they are not in the RID, just somthing you can query
648            seperatly.  Sorry luke :-) */
649
650    if(pdb_rid_is_well_known(rid)) {
651       /*
652        * The only well known user RIDs are DOMAIN_USER_RID_ADMIN
653        * and DOMAIN_USER_RID_GUEST.
654        */
655      if(rid == DOMAIN_USER_RID_ADMIN || rid == DOMAIN_USER_RID_GUEST)
656        return True;
657    } else if((rid & RID_TYPE_MASK) == USER_RID_TYPE) {
658      return True;
659    }
660    return False;
661 }
662
663 /*******************************************************************
664  Convert a rid into a name. Used in the lookup SID rpc.
665  ********************************************************************/
666
667 BOOL local_lookup_sid(DOM_SID *sid, char *name, enum SID_NAME_USE *psid_name_use)
668 {
669         uint32 rid;
670         SAM_ACCOUNT *sam_account = NULL;
671         GROUP_MAP map;
672
673         if (!sid_peek_check_rid(get_global_sam_sid(), sid, &rid)){
674                 DEBUG(0,("local_sid_to_gid: sid_peek_check_rid return False! SID: %s\n",
675                         sid_string_static(&map.sid)));
676                 return False;
677         }       
678         *psid_name_use = SID_NAME_UNKNOWN;
679         
680         DEBUG(5,("local_lookup_sid: looking up RID %u.\n", (unsigned int)rid));
681         
682         if (rid == DOMAIN_USER_RID_ADMIN) {
683                 const char **admin_list = lp_admin_users(-1);
684                 *psid_name_use = SID_NAME_USER;
685                 if (admin_list) {
686                         const char *p = *admin_list;
687                         if(!next_token(&p, name, NULL, sizeof(fstring)))
688                                 fstrcpy(name, "Administrator");
689                 } else {
690                         fstrcpy(name, "Administrator");
691                 }
692                 return True;
693         }
694
695         /*
696          * Don't try to convert the rid to a name if 
697          * running in appliance mode
698          */
699
700         if (lp_hide_local_users())
701                 return False;
702                 
703         if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_account))) {
704                 return False;
705         }
706         
707         /* see if the passdb can help us with the name of the user */
708         if (pdb_getsampwsid(sam_account, sid)) {
709                 fstrcpy(name, pdb_get_username(sam_account));
710                 *psid_name_use = SID_NAME_USER;
711
712                 pdb_free_sam(&sam_account);
713                         
714                 return True;
715         }
716
717         pdb_free_sam(&sam_account);
718                 
719         if (pdb_getgrsid(&map, *sid, MAPPING_WITHOUT_PRIV)) {
720                 if (map.gid!=(gid_t)-1) {
721                         DEBUG(5,("local_lookup_sid: mapped group %s to gid %u\n", map.nt_name, (unsigned int)map.gid));
722                 } else {
723                         DEBUG(5,("local_lookup_sid: mapped group %s to no unix gid.  Returning name.\n", map.nt_name));
724                 }
725
726                 fstrcpy(name, map.nt_name);
727                 *psid_name_use = map.sid_name_use;
728                 return True;
729         }
730
731         if (fallback_pdb_rid_is_user(rid)) {
732                 uid_t uid;
733
734                 DEBUG(5, ("assuming RID %u is a user\n", (unsigned)rid));
735
736                 uid = fallback_pdb_user_rid_to_uid(rid);
737                 slprintf(name, sizeof(fstring)-1, "unix_user.%u", (unsigned int)uid);   
738
739                 return False;  /* Indicates that this user was 'not mapped' */
740         } else {
741                 gid_t gid;
742                 struct group *gr; 
743                         
744                 DEBUG(5, ("assuming RID %u is a group\n", (unsigned)rid));
745
746                 gid = pdb_group_rid_to_gid(rid);
747                 gr = getgrgid(gid);
748                         
749                 *psid_name_use = SID_NAME_ALIAS;
750                         
751                 DEBUG(5,("local_lookup_sid: looking up gid %u %s\n", (unsigned int)gid,
752                          gr ? "succeeded" : "failed" ));
753                         
754                 if(!gr) {
755                         slprintf(name, sizeof(fstring)-1, "unix_group.%u", (unsigned int)gid);
756                         return False; /* Indicates that this group was 'not mapped' */
757                 }
758                         
759                 fstrcpy( name, gr->gr_name);
760                         
761                 DEBUG(5,("local_lookup_sid: found group %s for rid %u\n", name,
762                          (unsigned int)rid ));
763                 return True;   
764         }
765 }
766
767 /*******************************************************************
768  Convert a name into a SID. Used in the lookup name rpc.
769  ********************************************************************/
770
771 BOOL local_lookup_name(const char *c_user, DOM_SID *psid, enum SID_NAME_USE *psid_name_use)
772 {
773         extern DOM_SID global_sid_World_Domain;
774         DOM_SID local_sid;
775         fstring user;
776         SAM_ACCOUNT *sam_account = NULL;
777         struct group *grp;
778         GROUP_MAP map;
779                 
780         *psid_name_use = SID_NAME_UNKNOWN;
781
782         /*
783          * user may be quoted a const string, and map_username and
784          * friends can modify it. Make a modifiable copy. JRA.
785          */
786
787         fstrcpy(user, c_user);
788
789         sid_copy(&local_sid, get_global_sam_sid());
790
791         /*
792          * Special case for MACHINE\Everyone. Map to the world_sid.
793          */
794
795         if(strequal(user, "Everyone")) {
796                 sid_copy( psid, &global_sid_World_Domain);
797                 sid_append_rid(psid, 0);
798                 *psid_name_use = SID_NAME_ALIAS;
799                 return True;
800         }
801
802         /* 
803          * Don't lookup local unix users if running in appliance mode
804          */
805         if (lp_hide_local_users()) 
806                 return False;
807
808         (void)map_username(user);
809
810         if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_account))) {
811                 return False;
812         }
813         
814         if (pdb_getsampwnam(sam_account, user)) {
815                 sid_copy(psid, pdb_get_user_sid(sam_account));
816                 *psid_name_use = SID_NAME_USER;
817                 
818                 pdb_free_sam(&sam_account);
819                 return True;
820         }
821
822         pdb_free_sam(&sam_account);
823
824         /*
825          * Maybe it was a group ?
826          */
827
828         /* check if it's a mapped group */
829         if (pdb_getgrnam(&map, user, MAPPING_WITHOUT_PRIV)) {
830                 /* yes it's a mapped group */
831                 sid_copy(&local_sid, &map.sid);
832                 *psid_name_use = map.sid_name_use;
833         } else {
834                 /* it's not a mapped group */
835                 grp = getgrnam(user);
836                 if(!grp)
837                         return False;
838                 
839                 /* 
840                  *check if it's mapped, if it is reply it doesn't exist
841                  *
842                  * that's to prevent this case:
843                  *
844                  * unix group ug is mapped to nt group ng
845                  * someone does a lookup on ug
846                  * we must not reply as it doesn't "exist" anymore
847                  * for NT. For NT only ng exists.
848                  * JFM, 30/11/2001
849                  */
850                 
851                 if (pdb_getgrgid(&map, grp->gr_gid, MAPPING_WITHOUT_PRIV)){
852                         return False;
853                 }
854                 
855                 sid_append_rid( &local_sid, pdb_gid_to_group_rid(grp->gr_gid));
856                 *psid_name_use = SID_NAME_ALIAS;
857         }
858
859         sid_copy( psid, &local_sid);
860
861         return True;
862 }
863
864 /*************************************************************
865  Change a password entry in the local smbpasswd file.
866
867 It is currently being called by SWAT and by smbpasswd.
868  
869  --jerry
870  *************************************************************/
871
872 BOOL local_password_change(const char *user_name, int local_flags,
873                            const char *new_passwd, 
874                            char *err_str, size_t err_str_len,
875                            char *msg_str, size_t msg_str_len)
876 {
877         SAM_ACCOUNT     *sam_pass=NULL;
878         uint16 other_acb;
879
880         *err_str = '\0';
881         *msg_str = '\0';
882
883         /* Get the smb passwd entry for this user */
884         pdb_init_sam(&sam_pass);
885         if(!pdb_getsampwnam(sam_pass, user_name)) {
886                 pdb_free_sam(&sam_pass);
887                 
888                 if ((local_flags & LOCAL_ADD_USER) || (local_flags & LOCAL_DELETE_USER)) {
889                         /* Might not exist in /etc/passwd */
890                         if (!NT_STATUS_IS_OK(pdb_init_sam_new(&sam_pass, user_name))) {
891                                 slprintf(err_str, err_str_len-1, "Failed initialise SAM_ACCOUNT for user %s.\n", user_name);
892                                 return False;
893                         }
894                 } else {
895                         slprintf(err_str, err_str_len-1,"Failed to find entry for user %s.\n", user_name);
896                         return False;
897                 }
898         } else {
899                 /* the entry already existed */
900                 local_flags &= ~LOCAL_ADD_USER;
901         }
902
903         /* the 'other' acb bits not being changed here */
904         other_acb =  (pdb_get_acct_ctrl(sam_pass) & (!(ACB_WSTRUST|ACB_DOMTRUST|ACB_SVRTRUST|ACB_NORMAL)));
905         if (local_flags & LOCAL_TRUST_ACCOUNT) {
906                 if (!pdb_set_acct_ctrl(sam_pass, ACB_WSTRUST | other_acb, PDB_CHANGED) ) {
907                         slprintf(err_str, err_str_len - 1, "Failed to set 'trusted workstation account' flags for user %s.\n", user_name);
908                         pdb_free_sam(&sam_pass);
909                         return False;
910                 }
911         } else if (local_flags & LOCAL_INTERDOM_ACCOUNT) {
912                 if (!pdb_set_acct_ctrl(sam_pass, ACB_DOMTRUST | other_acb, PDB_CHANGED)) {
913                         slprintf(err_str, err_str_len - 1, "Failed to set 'domain trust account' flags for user %s.\n", user_name);
914                         pdb_free_sam(&sam_pass);
915                         return False;
916                 }
917         } else {
918                 if (!pdb_set_acct_ctrl(sam_pass, ACB_NORMAL | other_acb, PDB_CHANGED)) {
919                         slprintf(err_str, err_str_len - 1, "Failed to set 'normal account' flags for user %s.\n", user_name);
920                         pdb_free_sam(&sam_pass);
921                         return False;
922                 }
923         }
924
925         /*
926          * We are root - just write the new password
927          * and the valid last change time.
928          */
929
930         if (local_flags & LOCAL_DISABLE_USER) {
931                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_DISABLED, PDB_CHANGED)) {
932                         slprintf(err_str, err_str_len-1, "Failed to set 'disabled' flag for user %s.\n", user_name);
933                         pdb_free_sam(&sam_pass);
934                         return False;
935                 }
936         } else if (local_flags & LOCAL_ENABLE_USER) {
937                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
938                         slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
939                         pdb_free_sam(&sam_pass);
940                         return False;
941                 }
942         }
943         
944         if (local_flags & LOCAL_SET_NO_PASSWORD) {
945                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_PWNOTREQ, PDB_CHANGED)) {
946                         slprintf(err_str, err_str_len-1, "Failed to set 'no password required' flag for user %s.\n", user_name);
947                         pdb_free_sam(&sam_pass);
948                         return False;
949                 }
950         } else if (local_flags & LOCAL_SET_PASSWORD) {
951                 /*
952                  * If we're dealing with setting a completely empty user account
953                  * ie. One with a password of 'XXXX', but not set disabled (like
954                  * an account created from scratch) then if the old password was
955                  * 'XX's then getsmbpwent will have set the ACB_DISABLED flag.
956                  * We remove that as we're giving this user their first password
957                  * and the decision hasn't really been made to disable them (ie.
958                  * don't create them disabled). JRA.
959                  */
960                 if ((pdb_get_lanman_passwd(sam_pass)==NULL) && (pdb_get_acct_ctrl(sam_pass)&ACB_DISABLED)) {
961                         if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
962                                 slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
963                                 pdb_free_sam(&sam_pass);
964                                 return False;
965                         }
966                 }
967                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_PWNOTREQ), PDB_CHANGED)) {
968                         slprintf(err_str, err_str_len-1, "Failed to unset 'no password required' flag for user %s.\n", user_name);
969                         pdb_free_sam(&sam_pass);
970                         return False;
971                 }
972                 
973                 if (!pdb_set_plaintext_passwd (sam_pass, new_passwd)) {
974                         slprintf(err_str, err_str_len-1, "Failed to set password for user %s.\n", user_name);
975                         pdb_free_sam(&sam_pass);
976                         return False;
977                 }
978         }       
979
980         if (local_flags & LOCAL_ADD_USER) {
981                 if (pdb_add_sam_account(sam_pass)) {
982                         slprintf(msg_str, msg_str_len-1, "Added user %s.\n", user_name);
983                         pdb_free_sam(&sam_pass);
984                         return True;
985                 } else {
986                         slprintf(err_str, err_str_len-1, "Failed to add entry for user %s.\n", user_name);
987                         pdb_free_sam(&sam_pass);
988                         return False;
989                 }
990         } else if (local_flags & LOCAL_DELETE_USER) {
991                 if (!pdb_delete_sam_account(sam_pass)) {
992                         slprintf(err_str,err_str_len-1, "Failed to delete entry for user %s.\n", user_name);
993                         pdb_free_sam(&sam_pass);
994                         return False;
995                 }
996                 slprintf(msg_str, msg_str_len-1, "Deleted user %s.\n", user_name);
997         } else {
998                 if(!pdb_update_sam_account(sam_pass)) {
999                         slprintf(err_str, err_str_len-1, "Failed to modify entry for user %s.\n", user_name);
1000                         pdb_free_sam(&sam_pass);
1001                         return False;
1002                 }
1003                 if(local_flags & LOCAL_DISABLE_USER)
1004                         slprintf(msg_str, msg_str_len-1, "Disabled user %s.\n", user_name);
1005                 else if (local_flags & LOCAL_ENABLE_USER)
1006                         slprintf(msg_str, msg_str_len-1, "Enabled user %s.\n", user_name);
1007                 else if (local_flags & LOCAL_SET_NO_PASSWORD)
1008                         slprintf(msg_str, msg_str_len-1, "User %s password set to none.\n", user_name);
1009         }
1010
1011         pdb_free_sam(&sam_pass);
1012         return True;
1013 }