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