More printf portability fixes. Got caught out by some gcc'isms last
[tprouty/samba.git] / source / 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  get the default domain/netbios name to be used when 
32  testing authentication.  For example, if you connect
33  to a Windows member server using a bogus domain name, the
34  Windows box will map the BOGUS\user to DOMAIN\user.  A 
35  standalone box will map to WKS\user.
36 ******************************************************************/
37
38 const char *get_default_sam_name(void)
39 {
40         /* standalone servers can only use the local netbios name */
41         if ( lp_server_role() == ROLE_STANDALONE )
42                 return global_myname();
43
44         /* Windows domain members default to the DOMAIN
45            name when not specified */
46         return lp_workgroup();
47 }
48
49 /******************************************************************
50  get the default domain/netbios name to be used when dealing 
51  with our passdb list of accounts
52 ******************************************************************/
53
54 const char *get_global_sam_name(void) 
55 {
56         if ((lp_server_role() == ROLE_DOMAIN_PDC) || (lp_server_role() == ROLE_DOMAIN_BDC)) {
57                 return lp_workgroup();
58         }
59         return global_myname();
60 }
61
62 /************************************************************
63  Fill the SAM_ACCOUNT with default values.
64  ***********************************************************/
65
66 void pdb_fill_default_sam(SAM_ACCOUNT *user)
67 {
68         ZERO_STRUCT(user->private); /* Don't touch the talloc context */
69
70         /* no initial methods */
71         user->methods = NULL;
72
73         /* Don't change these timestamp settings without a good reason.
74            They are important for NT member server compatibility. */
75
76         user->private.logon_time            = (time_t)0;
77         user->private.pass_last_set_time    = (time_t)0;
78         user->private.pass_can_change_time  = (time_t)0;
79         user->private.logoff_time           = 
80         user->private.kickoff_time          = 
81         user->private.pass_must_change_time = get_time_t_max();
82         user->private.unknown_3 = 0x00ffffff;   /* don't know */
83         user->private.logon_divs = 168;         /* hours per week */
84         user->private.hours_len = 21;           /* 21 times 8 bits = 168 */
85         memset(user->private.hours, 0xff, user->private.hours_len); /* available at all hours */
86         user->private.unknown_5 = 0x00000000; /* don't know */
87         user->private.unknown_6 = 0x000004ec; /* don't know */
88
89         /* Some parts of samba strlen their pdb_get...() returns, 
90            so this keeps the interface unchanged for now. */
91            
92         user->private.username = "";
93         user->private.domain = "";
94         user->private.nt_username = "";
95         user->private.full_name = "";
96         user->private.home_dir = "";
97         user->private.logon_script = "";
98         user->private.profile_path = "";
99         user->private.acct_desc = "";
100         user->private.workstations = "";
101         user->private.unknown_str = "";
102         user->private.munged_dial = "";
103
104         user->private.plaintext_pw = NULL;
105
106 }       
107
108 static void destroy_pdb_talloc(SAM_ACCOUNT **user) 
109 {
110         if (*user) {
111                 data_blob_clear_free(&((*user)->private.lm_pw));
112                 data_blob_clear_free(&((*user)->private.nt_pw));
113
114                 if((*user)->private.plaintext_pw!=NULL)
115                         memset((*user)->private.plaintext_pw,'\0',strlen((*user)->private.plaintext_pw));
116                 talloc_destroy((*user)->mem_ctx);
117                 *user = NULL;
118         }
119 }
120
121
122 /**********************************************************************
123  Alloc memory and initialises a struct sam_passwd on supplied mem_ctx.
124 ***********************************************************************/
125
126 NTSTATUS pdb_init_sam_talloc(TALLOC_CTX *mem_ctx, SAM_ACCOUNT **user)
127 {
128         if (*user != NULL) {
129                 DEBUG(0,("pdb_init_sam_talloc: SAM_ACCOUNT was non NULL\n"));
130 #if 0
131                 smb_panic("non-NULL pointer passed to pdb_init_sam\n");
132 #endif
133                 return NT_STATUS_UNSUCCESSFUL;
134         }
135
136         if (!mem_ctx) {
137                 DEBUG(0,("pdb_init_sam_talloc: mem_ctx was NULL!\n"));
138                 return NT_STATUS_UNSUCCESSFUL;
139         }
140
141         *user=(SAM_ACCOUNT *)talloc(mem_ctx, sizeof(SAM_ACCOUNT));
142
143         if (*user==NULL) {
144                 DEBUG(0,("pdb_init_sam_talloc: error while allocating memory\n"));
145                 return NT_STATUS_NO_MEMORY;
146         }
147
148         (*user)->mem_ctx = mem_ctx;
149
150         (*user)->free_fn = NULL;
151
152         pdb_fill_default_sam(*user);
153         
154         return NT_STATUS_OK;
155 }
156
157
158 /*************************************************************
159  Alloc memory and initialises a struct sam_passwd.
160  ************************************************************/
161
162 NTSTATUS pdb_init_sam(SAM_ACCOUNT **user)
163 {
164         TALLOC_CTX *mem_ctx;
165         NTSTATUS nt_status;
166         
167         mem_ctx = talloc_init("passdb internal SAM_ACCOUNT allocation");
168
169         if (!mem_ctx) {
170                 DEBUG(0,("pdb_init_sam: error while doing talloc_init()\n"));
171                 return NT_STATUS_NO_MEMORY;
172         }
173
174         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_talloc(mem_ctx, user))) {
175                 talloc_destroy(mem_ctx);
176                 return nt_status;
177         }
178         
179         (*user)->free_fn = destroy_pdb_talloc;
180
181         return NT_STATUS_OK;
182 }
183
184
185 /*************************************************************
186  Initialises a struct sam_passwd with sane values.
187  ************************************************************/
188
189 NTSTATUS pdb_fill_sam_pw(SAM_ACCOUNT *sam_account, const struct passwd *pwd)
190 {
191         NTSTATUS ret;
192
193         if (!pwd) {
194                 return NT_STATUS_UNSUCCESSFUL;
195         }
196
197         pdb_fill_default_sam(sam_account);
198
199         pdb_set_username(sam_account, pwd->pw_name, PDB_SET);
200         pdb_set_fullname(sam_account, pwd->pw_gecos, PDB_SET);
201
202         pdb_set_unix_homedir(sam_account, pwd->pw_dir, PDB_SET);
203
204         pdb_set_domain (sam_account, get_global_sam_name(), PDB_DEFAULT);
205         
206         /* When we get a proper uid -> SID and SID -> uid allocation
207            mechinism, we should call it here.  
208            
209            We can't just set this to 0 or allow it only to be filled
210            in when added to the backend, because the user's SID 
211            may already be in security descriptors etc.
212            
213            -- abartlet 11-May-02
214         */
215
216         ret = pdb_set_sam_sids(sam_account, pwd);
217         if (!NT_STATUS_IS_OK(ret)) return ret;
218
219         /* check if this is a user account or a machine account */
220         if (pwd->pw_name[strlen(pwd->pw_name)-1] != '$')
221         {
222                 pdb_set_profile_path(sam_account, 
223                                      talloc_sub_specified((sam_account)->mem_ctx, 
224                                                             lp_logon_path(), 
225                                                             pwd->pw_name, global_myname(), 
226                                                             pwd->pw_uid, pwd->pw_gid), 
227                                      PDB_DEFAULT);
228                 
229                 pdb_set_homedir(sam_account, 
230                                 talloc_sub_specified((sam_account)->mem_ctx, 
231                                                        lp_logon_home(),
232                                                        pwd->pw_name, global_myname(), 
233                                                        pwd->pw_uid, pwd->pw_gid),
234                                 PDB_DEFAULT);
235                 
236                 pdb_set_dir_drive(sam_account, 
237                                   talloc_sub_specified((sam_account)->mem_ctx, 
238                                                          lp_logon_drive(),
239                                                          pwd->pw_name, global_myname(), 
240                                                          pwd->pw_uid, pwd->pw_gid),
241                                   PDB_DEFAULT);
242                 
243                 pdb_set_logon_script(sam_account, 
244                                      talloc_sub_specified((sam_account)->mem_ctx, 
245                                                             lp_logon_script(),
246                                                             pwd->pw_name, global_myname(), 
247                                                             pwd->pw_uid, pwd->pw_gid), 
248                                      PDB_DEFAULT);
249                 if (!pdb_set_acct_ctrl(sam_account, ACB_NORMAL, PDB_DEFAULT)) {
250                         DEBUG(1, ("Failed to set 'normal account' flags for user %s.\n", pwd->pw_name));
251                         return NT_STATUS_UNSUCCESSFUL;
252                 }
253         } else {
254                 if (!pdb_set_acct_ctrl(sam_account, ACB_WSTRUST, PDB_DEFAULT)) {
255                         DEBUG(1, ("Failed to set 'trusted workstation account' flags for user %s.\n", pwd->pw_name));
256                         return NT_STATUS_UNSUCCESSFUL;
257                 }
258         }
259         return NT_STATUS_OK;
260 }
261
262
263 /*************************************************************
264  Initialises a struct sam_passwd with sane values.
265  ************************************************************/
266
267 NTSTATUS pdb_init_sam_pw(SAM_ACCOUNT **new_sam_acct, const struct passwd *pwd)
268 {
269         NTSTATUS nt_status;
270
271         if (!pwd) {
272                 new_sam_acct = NULL;
273                 return NT_STATUS_INVALID_PARAMETER;
274         }
275
276         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam(new_sam_acct))) {
277                 new_sam_acct = NULL;
278                 return nt_status;
279         }
280
281         if (!NT_STATUS_IS_OK(nt_status = pdb_fill_sam_pw(*new_sam_acct, pwd))) {
282                 pdb_free_sam(new_sam_acct);
283                 new_sam_acct = NULL;
284                 return nt_status;
285         }
286
287         return NT_STATUS_OK;
288 }
289
290
291 /*************************************************************
292  Initialises a SAM_ACCOUNT ready to add a new account, based
293  on the UNIX user.  Pass in a RID if you have one
294  ************************************************************/
295
296 NTSTATUS pdb_init_sam_new(SAM_ACCOUNT **new_sam_acct, const char *username,
297                           uint32 rid)
298 {
299         NTSTATUS        nt_status = NT_STATUS_NO_MEMORY;
300         struct passwd   *pwd;
301         BOOL            ret;
302         
303         pwd = Get_Pwnam(username);
304
305         if (!pwd) 
306                 return NT_STATUS_NO_SUCH_USER;
307         
308         if (!NT_STATUS_IS_OK(nt_status = pdb_init_sam_pw(new_sam_acct, pwd))) {
309                 *new_sam_acct = NULL;
310                 return nt_status;
311         }
312         
313         /* see if we need to generate a new rid using the 2.2 algorithm */
314         if ( rid == 0 && lp_enable_rid_algorithm() ) {
315                 DEBUG(10,("pdb_init_sam_new: no RID specified.  Generating one via old algorithm\n"));
316                 rid = fallback_pdb_uid_to_user_rid(pwd->pw_uid);
317         }
318         
319         /* set the new SID */
320         
321         ret = pdb_set_user_sid_from_rid( *new_sam_acct, rid, PDB_SET );
322          
323         return (ret ? NT_STATUS_OK : NT_STATUS_NO_SUCH_USER);
324 }
325
326
327 /**
328  * Free the contets of the SAM_ACCOUNT, but not the structure.
329  *
330  * Also wipes the LM and NT hashes and plaintext password from 
331  * memory.
332  *
333  * @param user SAM_ACCOUNT to free members of.
334  **/
335
336 static void pdb_free_sam_contents(SAM_ACCOUNT *user)
337 {
338
339         /* Kill off sensitive data.  Free()ed by the
340            talloc mechinism */
341
342         data_blob_clear_free(&(user->private.lm_pw));
343         data_blob_clear_free(&(user->private.nt_pw));
344         if (user->private.plaintext_pw!=NULL)
345                 memset(user->private.plaintext_pw,'\0',strlen(user->private.plaintext_pw));
346
347         if (user->private.backend_private_data && user->private.backend_private_data_free_fn) {
348                 user->private.backend_private_data_free_fn(&user->private.backend_private_data);
349         }
350 }
351
352
353 /************************************************************
354  Reset the SAM_ACCOUNT and free the NT/LM hashes.
355  ***********************************************************/
356
357 NTSTATUS pdb_reset_sam(SAM_ACCOUNT *user)
358 {
359         if (user == NULL) {
360                 DEBUG(0,("pdb_reset_sam: SAM_ACCOUNT was NULL\n"));
361 #if 0
362                 smb_panic("NULL pointer passed to pdb_free_sam\n");
363 #endif
364                 return NT_STATUS_UNSUCCESSFUL;
365         }
366         
367         pdb_free_sam_contents(user);
368
369         pdb_fill_default_sam(user);
370
371         return NT_STATUS_OK;
372 }
373
374
375 /************************************************************
376  Free the SAM_ACCOUNT and the member pointers.
377  ***********************************************************/
378
379 NTSTATUS pdb_free_sam(SAM_ACCOUNT **user)
380 {
381         if (*user == NULL) {
382                 DEBUG(0,("pdb_free_sam: SAM_ACCOUNT was NULL\n"));
383 #if 0
384                 smb_panic("NULL pointer passed to pdb_free_sam\n");
385 #endif
386                 return NT_STATUS_UNSUCCESSFUL;
387         }
388
389         pdb_free_sam_contents(*user);
390         
391         if ((*user)->free_fn) {
392                 (*user)->free_fn(user);
393         }
394
395         return NT_STATUS_OK;    
396 }
397
398 /**************************************************************************
399  * This function will take care of all the steps needed to correctly
400  * allocate and set the user SID, please do use this function to create new
401  * users, messing with SIDs is not good.
402  *
403  * account_data must be provided initialized, pwd may be null.
404  *                                                                      SSS
405  ***************************************************************************/
406
407 NTSTATUS pdb_set_sam_sids(SAM_ACCOUNT *account_data, const struct passwd *pwd)
408 {
409         const char *guest_account = lp_guestaccount();
410         GROUP_MAP map;
411         
412         if (!account_data || !pwd) {
413                 return NT_STATUS_INVALID_PARAMETER;
414         }
415
416         /* this is a hack this thing should not be set
417            this way --SSS */
418         if (!(guest_account && *guest_account)) {
419                 DEBUG(1, ("NULL guest account!?!?\n"));
420                 return NT_STATUS_UNSUCCESSFUL;
421         } else {
422                 /* Ensure this *must* be set right */
423                 if (strcmp(pwd->pw_name, guest_account) == 0) {
424                         if (!pdb_set_user_sid_from_rid(account_data, DOMAIN_USER_RID_GUEST, PDB_DEFAULT)) {
425                                 return NT_STATUS_UNSUCCESSFUL;
426                         }
427                         if (!pdb_set_group_sid_from_rid(account_data, DOMAIN_GROUP_RID_GUESTS, PDB_DEFAULT)) {
428                                 return NT_STATUS_UNSUCCESSFUL;
429                         }
430                         return NT_STATUS_OK;
431                 }
432         }
433
434         if (!pdb_set_user_sid_from_rid(account_data, fallback_pdb_uid_to_user_rid(pwd->pw_uid), PDB_SET)) {
435                 DEBUG(0,("Can't set User SID from RID!\n"));
436                 return NT_STATUS_INVALID_PARAMETER;
437         }
438         
439         /* call the mapping code here */
440         if(pdb_getgrgid(&map, pwd->pw_gid)) {
441                 if (!pdb_set_group_sid(account_data, &map.sid, PDB_SET)){
442                         DEBUG(0,("Can't set Group SID!\n"));
443                         return NT_STATUS_INVALID_PARAMETER;
444                 }
445         } 
446         else {
447                 if (!pdb_set_group_sid_from_rid(account_data, pdb_gid_to_group_rid(pwd->pw_gid), PDB_SET)) {
448                         DEBUG(0,("Can't set Group SID\n"));
449                         return NT_STATUS_INVALID_PARAMETER;
450                 }
451         }
452
453         return NT_STATUS_OK;
454 }
455
456 /**********************************************************
457  Encode the account control bits into a string.
458  length = length of string to encode into (including terminating
459  null). length *MUST BE MORE THAN 2* !
460  **********************************************************/
461
462 char *pdb_encode_acct_ctrl(uint16 acct_ctrl, size_t length)
463 {
464         static fstring acct_str;
465         size_t i = 0;
466
467         acct_str[i++] = '[';
468
469         if (acct_ctrl & ACB_PWNOTREQ ) acct_str[i++] = 'N';
470         if (acct_ctrl & ACB_DISABLED ) acct_str[i++] = 'D';
471         if (acct_ctrl & ACB_HOMDIRREQ) acct_str[i++] = 'H';
472         if (acct_ctrl & ACB_TEMPDUP  ) acct_str[i++] = 'T'; 
473         if (acct_ctrl & ACB_NORMAL   ) acct_str[i++] = 'U';
474         if (acct_ctrl & ACB_MNS      ) acct_str[i++] = 'M';
475         if (acct_ctrl & ACB_WSTRUST  ) acct_str[i++] = 'W';
476         if (acct_ctrl & ACB_SVRTRUST ) acct_str[i++] = 'S';
477         if (acct_ctrl & ACB_AUTOLOCK ) acct_str[i++] = 'L';
478         if (acct_ctrl & ACB_PWNOEXP  ) acct_str[i++] = 'X';
479         if (acct_ctrl & ACB_DOMTRUST ) acct_str[i++] = 'I';
480
481         for ( ; i < length - 2 ; i++ )
482                 acct_str[i] = ' ';
483
484         i = length - 2;
485         acct_str[i++] = ']';
486         acct_str[i++] = '\0';
487
488         return acct_str;
489 }     
490
491 /**********************************************************
492  Decode the account control bits from a string.
493  **********************************************************/
494
495 uint16 pdb_decode_acct_ctrl(const char *p)
496 {
497         uint16 acct_ctrl = 0;
498         BOOL finished = False;
499
500         /*
501          * Check if the account type bits have been encoded after the
502          * NT password (in the form [NDHTUWSLXI]).
503          */
504
505         if (*p != '[')
506                 return 0;
507
508         for (p++; *p && !finished; p++) {
509                 switch (*p) {
510                         case 'N': { acct_ctrl |= ACB_PWNOTREQ ; break; /* 'N'o password. */ }
511                         case 'D': { acct_ctrl |= ACB_DISABLED ; break; /* 'D'isabled. */ }
512                         case 'H': { acct_ctrl |= ACB_HOMDIRREQ; break; /* 'H'omedir required. */ }
513                         case 'T': { acct_ctrl |= ACB_TEMPDUP  ; break; /* 'T'emp account. */ } 
514                         case 'U': { acct_ctrl |= ACB_NORMAL   ; break; /* 'U'ser account (normal). */ } 
515                         case 'M': { acct_ctrl |= ACB_MNS      ; break; /* 'M'NS logon user account. What is this ? */ } 
516                         case 'W': { acct_ctrl |= ACB_WSTRUST  ; break; /* 'W'orkstation account. */ } 
517                         case 'S': { acct_ctrl |= ACB_SVRTRUST ; break; /* 'S'erver account. */ } 
518                         case 'L': { acct_ctrl |= ACB_AUTOLOCK ; break; /* 'L'ocked account. */ } 
519                         case 'X': { acct_ctrl |= ACB_PWNOEXP  ; break; /* No 'X'piry on password */ } 
520                         case 'I': { acct_ctrl |= ACB_DOMTRUST ; break; /* 'I'nterdomain trust account. */ }
521             case ' ': { break; }
522                         case ':':
523                         case '\n':
524                         case '\0': 
525                         case ']':
526                         default:  { finished = True; }
527                 }
528         }
529
530         return acct_ctrl;
531 }
532
533 /*************************************************************
534  Routine to set 32 hex password characters from a 16 byte array.
535 **************************************************************/
536
537 void pdb_sethexpwd(char *p, const unsigned char *pwd, uint16 acct_ctrl)
538 {
539         if (pwd != NULL) {
540                 int i;
541                 for (i = 0; i < 16; i++)
542                         slprintf(&p[i*2], 3, "%02X", pwd[i]);
543         } else {
544                 if (acct_ctrl & ACB_PWNOTREQ)
545                         safe_strcpy(p, "NO PASSWORDXXXXXXXXXXXXXXXXXXXXX", 33);
546                 else
547                         safe_strcpy(p, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 33);
548         }
549 }
550
551 /*************************************************************
552  Routine to get the 32 hex characters and turn them
553  into a 16 byte array.
554 **************************************************************/
555
556 BOOL pdb_gethexpwd(const char *p, unsigned char *pwd)
557 {
558         int i;
559         unsigned char   lonybble, hinybble;
560         const char      *hexchars = "0123456789ABCDEF";
561         char           *p1, *p2;
562         
563         if (!p)
564                 return (False);
565         
566         for (i = 0; i < 32; i += 2) {
567                 hinybble = toupper(p[i]);
568                 lonybble = toupper(p[i + 1]);
569
570                 p1 = strchr(hexchars, hinybble);
571                 p2 = strchr(hexchars, lonybble);
572
573                 if (!p1 || !p2)
574                         return (False);
575
576                 hinybble = PTR_DIFF(p1, hexchars);
577                 lonybble = PTR_DIFF(p2, hexchars);
578
579                 pwd[i / 2] = (hinybble << 4) | lonybble;
580         }
581         return (True);
582 }
583
584 int algorithmic_rid_base(void)
585 {
586         static int rid_offset = 0;
587
588         if (rid_offset != 0)
589                 return rid_offset;
590
591         rid_offset = lp_algorithmic_rid_base();
592
593         if (rid_offset < BASE_RID) {  
594                 /* Try to prevent admin foot-shooting, we can't put algorithmic
595                    rids below 1000, that's the 'well known RIDs' on NT */
596                 DEBUG(0, ("'algorithmic rid base' must be equal to or above %ld\n", BASE_RID));
597                 rid_offset = BASE_RID;
598         }
599         if (rid_offset & 1) {
600                 DEBUG(0, ("algorithmic rid base must be even\n"));
601                 rid_offset += 1;
602         }
603         return rid_offset;
604 }
605
606 /*******************************************************************
607  Converts NT user RID to a UNIX uid.
608  ********************************************************************/
609
610 uid_t fallback_pdb_user_rid_to_uid(uint32 user_rid)
611 {
612         int rid_offset = algorithmic_rid_base();
613         return (uid_t)(((user_rid & (~USER_RID_TYPE)) - rid_offset)/RID_MULTIPLIER);
614 }
615
616 /*******************************************************************
617  converts UNIX uid to an NT User RID.
618  ********************************************************************/
619
620 uint32 fallback_pdb_uid_to_user_rid(uid_t uid)
621 {
622         int rid_offset = algorithmic_rid_base();
623         return (((((uint32)uid)*RID_MULTIPLIER) + rid_offset) | USER_RID_TYPE);
624 }
625
626 /*******************************************************************
627  Converts NT group RID to a UNIX gid.
628  ********************************************************************/
629
630 gid_t pdb_group_rid_to_gid(uint32 group_rid)
631 {
632         int rid_offset = algorithmic_rid_base();
633         return (gid_t)(((group_rid & (~GROUP_RID_TYPE))- rid_offset)/RID_MULTIPLIER);
634 }
635
636 /*******************************************************************
637  converts NT Group RID to a UNIX uid.
638  
639  warning: you must not call that function only
640  you must do a call to the group mapping first.
641  there is not anymore a direct link between the gid and the rid.
642  ********************************************************************/
643
644 uint32 pdb_gid_to_group_rid(gid_t gid)
645 {
646         int rid_offset = algorithmic_rid_base();
647         return (((((uint32)gid)*RID_MULTIPLIER) + rid_offset) | GROUP_RID_TYPE);
648 }
649
650 /*******************************************************************
651  Decides if a RID is a well known RID.
652  ********************************************************************/
653
654 static BOOL pdb_rid_is_well_known(uint32 rid)
655 {
656         /* Not using rid_offset here, because this is the actual
657            NT fixed value (1000) */
658
659         return (rid < BASE_RID);
660 }
661
662 /*******************************************************************
663  Decides if a RID is a user or group RID.
664  ********************************************************************/
665
666 BOOL fallback_pdb_rid_is_user(uint32 rid)
667 {
668   /* lkcl i understand that NT attaches an enumeration to a RID
669    * such that it can be identified as either a user, group etc
670    * type.  there are 5 such categories, and they are documented.
671    */
672         /* However, they are not in the RID, just somthing you can query
673            seperatly.  Sorry luke :-) */
674
675    if(pdb_rid_is_well_known(rid)) {
676       /*
677        * The only well known user RIDs are DOMAIN_USER_RID_ADMIN
678        * and DOMAIN_USER_RID_GUEST.
679        */
680      if(rid == DOMAIN_USER_RID_ADMIN || rid == DOMAIN_USER_RID_GUEST)
681        return True;
682    } else if((rid & RID_TYPE_MASK) == USER_RID_TYPE) {
683      return True;
684    }
685    return False;
686 }
687
688 /*******************************************************************
689  Convert a rid into a name. Used in the lookup SID rpc.
690  ********************************************************************/
691
692 BOOL local_lookup_sid(DOM_SID *sid, char *name, enum SID_NAME_USE *psid_name_use)
693 {
694         uint32 rid;
695         SAM_ACCOUNT *sam_account = NULL;
696         GROUP_MAP map;
697
698         if (!sid_peek_check_rid(get_global_sam_sid(), sid, &rid)){
699                 DEBUG(0,("local_lookup_sid: sid_peek_check_rid return False! SID: %s\n",
700                         sid_string_static(&map.sid)));
701                 return False;
702         }       
703         *psid_name_use = SID_NAME_UNKNOWN;
704         
705         DEBUG(5,("local_lookup_sid: looking up RID %u.\n", (unsigned int)rid));
706         
707         if (rid == DOMAIN_USER_RID_ADMIN) {
708                 const char **admin_list = lp_admin_users(-1);
709                 *psid_name_use = SID_NAME_USER;
710                 if (admin_list) {
711                         const char *p = *admin_list;
712                         if(!next_token(&p, name, NULL, sizeof(fstring)))
713                                 fstrcpy(name, "Administrator");
714                 } else {
715                         fstrcpy(name, "Administrator");
716                 }
717                 return True;
718         }
719
720         /*
721          * Don't try to convert the rid to a name if 
722          * running in appliance mode
723          */
724
725         if (lp_hide_local_users())
726                 return False;
727                 
728         if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_account))) {
729                 return False;
730         }
731         
732         /* see if the passdb can help us with the name of the user */
733
734         become_root();
735         if (pdb_getsampwsid(sam_account, sid)) {
736                 unbecome_root();
737                 fstrcpy(name, pdb_get_username(sam_account));
738                 *psid_name_use = SID_NAME_USER;
739
740                 pdb_free_sam(&sam_account);
741                         
742                 return True;
743         }
744         unbecome_root();
745         pdb_free_sam(&sam_account);
746                 
747         if (pdb_getgrsid(&map, *sid)) {
748                 if (map.gid!=(gid_t)-1) {
749                         DEBUG(5,("local_lookup_sid: mapped group %s to gid %u\n", map.nt_name, (unsigned int)map.gid));
750                 } else {
751                         DEBUG(5,("local_lookup_sid: mapped group %s to no unix gid.  Returning name.\n", map.nt_name));
752                 }
753
754                 fstrcpy(name, map.nt_name);
755                 *psid_name_use = map.sid_name_use;
756                 return True;
757         }
758
759         if (fallback_pdb_rid_is_user(rid)) {
760                 uid_t uid;
761
762                 DEBUG(5, ("assuming RID %u is a user\n", (unsigned)rid));
763
764                 uid = fallback_pdb_user_rid_to_uid(rid);
765                 slprintf(name, sizeof(fstring)-1, "unix_user.%u", (unsigned int)uid);   
766
767                 return False;  /* Indicates that this user was 'not mapped' */
768         } else {
769                 gid_t gid;
770                 struct group *gr; 
771                         
772                 DEBUG(5, ("assuming RID %u is a group\n", (unsigned)rid));
773
774                 gid = pdb_group_rid_to_gid(rid);
775                 gr = getgrgid(gid);
776                         
777                 *psid_name_use = SID_NAME_ALIAS;
778                         
779                 DEBUG(5,("local_lookup_sid: looking up gid %u %s\n", (unsigned int)gid,
780                          gr ? "succeeded" : "failed" ));
781                         
782                 if(!gr) {
783                         slprintf(name, sizeof(fstring)-1, "unix_group.%u", (unsigned int)gid);
784                         return False; /* Indicates that this group was 'not mapped' */
785                 }
786                         
787                 fstrcpy( name, gr->gr_name);
788                         
789                 DEBUG(5,("local_lookup_sid: found group %s for rid %u\n", name,
790                          (unsigned int)rid ));
791                 return True;   
792         }
793 }
794
795 /*******************************************************************
796  Convert a name into a SID. Used in the lookup name rpc.
797  ********************************************************************/
798
799 BOOL local_lookup_name(const char *c_user, DOM_SID *psid, enum SID_NAME_USE *psid_name_use)
800 {
801         extern DOM_SID global_sid_World_Domain;
802         DOM_SID local_sid;
803         fstring user;
804         SAM_ACCOUNT *sam_account = NULL;
805         struct group *grp;
806         GROUP_MAP map;
807                 
808         *psid_name_use = SID_NAME_UNKNOWN;
809
810         /*
811          * user may be quoted a const string, and map_username and
812          * friends can modify it. Make a modifiable copy. JRA.
813          */
814
815         fstrcpy(user, c_user);
816
817         sid_copy(&local_sid, get_global_sam_sid());
818
819         /*
820          * Special case for MACHINE\Everyone. Map to the world_sid.
821          */
822
823         if(strequal(user, "Everyone")) {
824                 sid_copy( psid, &global_sid_World_Domain);
825                 sid_append_rid(psid, 0);
826                 *psid_name_use = SID_NAME_ALIAS;
827                 return True;
828         }
829
830         /* 
831          * Don't lookup local unix users if running in appliance mode
832          */
833         if (lp_hide_local_users()) 
834                 return False;
835
836         (void)map_username(user);
837
838         if (!NT_STATUS_IS_OK(pdb_init_sam(&sam_account))) {
839                 return False;
840         }
841         
842         become_root();
843         if (pdb_getsampwnam(sam_account, user)) {
844                 unbecome_root();
845                 sid_copy(psid, pdb_get_user_sid(sam_account));
846                 *psid_name_use = SID_NAME_USER;
847                 
848                 pdb_free_sam(&sam_account);
849                 return True;
850         }
851         unbecome_root();
852
853         pdb_free_sam(&sam_account);
854
855         /*
856          * Maybe it was a group ?
857          */
858
859         /* check if it's a mapped group */
860         if (pdb_getgrnam(&map, user)) {
861                 /* yes it's a mapped group */
862                 sid_copy(&local_sid, &map.sid);
863                 *psid_name_use = map.sid_name_use;
864         } else {
865                 /* it's not a mapped group */
866                 grp = getgrnam(user);
867                 if(!grp)
868                         return False;
869                 
870                 /* 
871                  *check if it's mapped, if it is reply it doesn't exist
872                  *
873                  * that's to prevent this case:
874                  *
875                  * unix group ug is mapped to nt group ng
876                  * someone does a lookup on ug
877                  * we must not reply as it doesn't "exist" anymore
878                  * for NT. For NT only ng exists.
879                  * JFM, 30/11/2001
880                  */
881                 
882                 if (pdb_getgrgid(&map, grp->gr_gid)){
883                         return False;
884                 }
885                 
886                 sid_append_rid( &local_sid, pdb_gid_to_group_rid(grp->gr_gid));
887                 *psid_name_use = SID_NAME_ALIAS;
888         }
889
890         sid_copy( psid, &local_sid);
891
892         return True;
893 }
894
895 /*************************************************************
896  Change a password entry in the local smbpasswd file.
897  *************************************************************/
898
899 BOOL local_password_change(const char *user_name, int local_flags,
900                            const char *new_passwd, 
901                            char *err_str, size_t err_str_len,
902                            char *msg_str, size_t msg_str_len)
903 {
904         SAM_ACCOUNT     *sam_pass=NULL;
905         uint16 other_acb;
906
907         *err_str = '\0';
908         *msg_str = '\0';
909
910         /* Get the smb passwd entry for this user */
911         pdb_init_sam(&sam_pass);
912
913         become_root();
914         if(!pdb_getsampwnam(sam_pass, user_name)) {
915                 unbecome_root();
916                 pdb_free_sam(&sam_pass);
917                 
918                 if ((local_flags & LOCAL_ADD_USER) || (local_flags & LOCAL_DELETE_USER)) {
919                         /* Might not exist in /etc/passwd.  Use rid algorithm here */
920                         if (!NT_STATUS_IS_OK(pdb_init_sam_new(&sam_pass, user_name, 0))) {
921                                 slprintf(err_str, err_str_len-1, "Failed initialise SAM_ACCOUNT for user %s.\n", user_name);
922                                 return False;
923                         }
924                 } else {
925                         slprintf(err_str, err_str_len-1,"Failed to find entry for user %s.\n", user_name);
926                         return False;
927                 }
928         } else {
929                 unbecome_root();
930                 /* the entry already existed */
931                 local_flags &= ~LOCAL_ADD_USER;
932         }
933
934         /* the 'other' acb bits not being changed here */
935         other_acb =  (pdb_get_acct_ctrl(sam_pass) & (!(ACB_WSTRUST|ACB_DOMTRUST|ACB_SVRTRUST|ACB_NORMAL)));
936         if (local_flags & LOCAL_TRUST_ACCOUNT) {
937                 if (!pdb_set_acct_ctrl(sam_pass, ACB_WSTRUST | other_acb, PDB_CHANGED) ) {
938                         slprintf(err_str, err_str_len - 1, "Failed to set 'trusted workstation account' flags for user %s.\n", user_name);
939                         pdb_free_sam(&sam_pass);
940                         return False;
941                 }
942         } else if (local_flags & LOCAL_INTERDOM_ACCOUNT) {
943                 if (!pdb_set_acct_ctrl(sam_pass, ACB_DOMTRUST | other_acb, PDB_CHANGED)) {
944                         slprintf(err_str, err_str_len - 1, "Failed to set 'domain trust account' flags for user %s.\n", user_name);
945                         pdb_free_sam(&sam_pass);
946                         return False;
947                 }
948         } else {
949                 if (!pdb_set_acct_ctrl(sam_pass, ACB_NORMAL | other_acb, PDB_CHANGED)) {
950                         slprintf(err_str, err_str_len - 1, "Failed to set 'normal account' flags for user %s.\n", user_name);
951                         pdb_free_sam(&sam_pass);
952                         return False;
953                 }
954         }
955
956         /*
957          * We are root - just write the new password
958          * and the valid last change time.
959          */
960
961         if (local_flags & LOCAL_DISABLE_USER) {
962                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_DISABLED, PDB_CHANGED)) {
963                         slprintf(err_str, err_str_len-1, "Failed to set 'disabled' flag for user %s.\n", user_name);
964                         pdb_free_sam(&sam_pass);
965                         return False;
966                 }
967         } else if (local_flags & LOCAL_ENABLE_USER) {
968                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
969                         slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
970                         pdb_free_sam(&sam_pass);
971                         return False;
972                 }
973         }
974         
975         if (local_flags & LOCAL_SET_NO_PASSWORD) {
976                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)|ACB_PWNOTREQ, PDB_CHANGED)) {
977                         slprintf(err_str, err_str_len-1, "Failed to set 'no password required' flag for user %s.\n", user_name);
978                         pdb_free_sam(&sam_pass);
979                         return False;
980                 }
981         } else if (local_flags & LOCAL_SET_PASSWORD) {
982                 /*
983                  * If we're dealing with setting a completely empty user account
984                  * ie. One with a password of 'XXXX', but not set disabled (like
985                  * an account created from scratch) then if the old password was
986                  * 'XX's then getsmbpwent will have set the ACB_DISABLED flag.
987                  * We remove that as we're giving this user their first password
988                  * and the decision hasn't really been made to disable them (ie.
989                  * don't create them disabled). JRA.
990                  */
991                 if ((pdb_get_lanman_passwd(sam_pass)==NULL) && (pdb_get_acct_ctrl(sam_pass)&ACB_DISABLED)) {
992                         if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_DISABLED), PDB_CHANGED)) {
993                                 slprintf(err_str, err_str_len-1, "Failed to unset 'disabled' flag for user %s.\n", user_name);
994                                 pdb_free_sam(&sam_pass);
995                                 return False;
996                         }
997                 }
998                 if (!pdb_set_acct_ctrl (sam_pass, pdb_get_acct_ctrl(sam_pass)&(~ACB_PWNOTREQ), PDB_CHANGED)) {
999                         slprintf(err_str, err_str_len-1, "Failed to unset 'no password required' flag for user %s.\n", user_name);
1000                         pdb_free_sam(&sam_pass);
1001                         return False;
1002                 }
1003                 
1004                 if (!pdb_set_plaintext_passwd (sam_pass, new_passwd)) {
1005                         slprintf(err_str, err_str_len-1, "Failed to set password for user %s.\n", user_name);
1006                         pdb_free_sam(&sam_pass);
1007                         return False;
1008                 }
1009         }       
1010
1011         if (local_flags & LOCAL_ADD_USER) {
1012                 if (pdb_add_sam_account(sam_pass)) {
1013                         slprintf(msg_str, msg_str_len-1, "Added user %s.\n", user_name);
1014                         pdb_free_sam(&sam_pass);
1015                         return True;
1016                 } else {
1017                         slprintf(err_str, err_str_len-1, "Failed to add entry for user %s.\n", user_name);
1018                         pdb_free_sam(&sam_pass);
1019                         return False;
1020                 }
1021         } else if (local_flags & LOCAL_DELETE_USER) {
1022                 if (!pdb_delete_sam_account(sam_pass)) {
1023                         slprintf(err_str,err_str_len-1, "Failed to delete entry for user %s.\n", user_name);
1024                         pdb_free_sam(&sam_pass);
1025                         return False;
1026                 }
1027                 slprintf(msg_str, msg_str_len-1, "Deleted user %s.\n", user_name);
1028         } else {
1029                 if(!pdb_update_sam_account(sam_pass)) {
1030                         slprintf(err_str, err_str_len-1, "Failed to modify entry for user %s.\n", user_name);
1031                         pdb_free_sam(&sam_pass);
1032                         return False;
1033                 }
1034                 if(local_flags & LOCAL_DISABLE_USER)
1035                         slprintf(msg_str, msg_str_len-1, "Disabled user %s.\n", user_name);
1036                 else if (local_flags & LOCAL_ENABLE_USER)
1037                         slprintf(msg_str, msg_str_len-1, "Enabled user %s.\n", user_name);
1038                 else if (local_flags & LOCAL_SET_NO_PASSWORD)
1039                         slprintf(msg_str, msg_str_len-1, "User %s password set to none.\n", user_name);
1040         }
1041
1042         pdb_free_sam(&sam_pass);
1043         return True;
1044 }
1045
1046 /****************************************************************************
1047  Convert a uid to SID - locally.
1048 ****************************************************************************/
1049
1050 DOM_SID *local_uid_to_sid(DOM_SID *psid, uid_t uid)
1051 {
1052         SAM_ACCOUNT *sampw = NULL;
1053         struct passwd *unix_pw;
1054         BOOL ret;
1055         
1056         unix_pw = sys_getpwuid( uid );
1057
1058         if ( !unix_pw ) {
1059                 DEBUG(4,("local_uid_to_sid: host has know idea of uid %lu\n", (unsigned long)uid));
1060                 return NULL;
1061         }
1062         
1063         if ( !NT_STATUS_IS_OK(pdb_init_sam(&sampw)) ) {
1064                 DEBUG(0,("local_uid_to_sid: failed to allocate SAM_ACCOUNT object\n"));
1065                 return NULL;
1066         }
1067         
1068         become_root();
1069         ret = pdb_getsampwnam( sampw, unix_pw->pw_name );
1070         unbecome_root();
1071         
1072         if ( ret )
1073                 sid_copy( psid, pdb_get_user_sid(sampw) );
1074         else {
1075                 DEBUG(4,("local_uid_to_sid: User %s [uid == %lu] has no samba account\n",
1076                         unix_pw->pw_name, (unsigned long)uid));
1077                         
1078                 if ( !lp_enable_rid_algorithm() ) 
1079                         return NULL;
1080
1081                 DEBUG(8,("local_uid_to_sid: falling back to RID algorithm\n"));
1082                 
1083                 sid_copy( psid, get_global_sam_sid() );
1084                 sid_append_rid( psid, fallback_pdb_uid_to_user_rid(uid) );
1085         }
1086
1087         
1088         DEBUG(10,("local_uid_to_sid:  uid (%d) -> SID %s (%s).\n", 
1089                 (unsigned int)uid, sid_string_static(psid), unix_pw->pw_name));
1090         
1091         return psid;
1092 }
1093
1094 /****************************************************************************
1095  Convert a SID to uid - locally.
1096 ****************************************************************************/
1097
1098 BOOL local_sid_to_uid(uid_t *puid, const DOM_SID *psid, enum SID_NAME_USE *name_type)
1099 {
1100         SAM_ACCOUNT *sampw = NULL;      
1101         struct passwd *unix_pw;
1102         const char *user_name;
1103
1104         *name_type = SID_NAME_UNKNOWN;
1105
1106         /*
1107          * We can only convert to a uid if this is our local
1108          * Domain SID (ie. we are the controling authority).
1109          */
1110         if (!sid_check_is_in_our_domain(psid) ) {
1111                 DEBUG(5,("local_sid_to_uid: this SID (%s) is not from our domain\n", sid_string_static(psid)));
1112                 return False;
1113         }
1114
1115         /* lookup the user account */
1116         
1117         if ( !NT_STATUS_IS_OK(pdb_init_sam(&sampw)) ) {
1118                 DEBUG(0,("local_sid_to_uid: Failed to allocate memory for SAM_ACCOUNT object\n"));
1119                 return False;
1120         }
1121                 
1122         become_root();
1123         if ( !pdb_getsampwsid(sampw, psid) ) {
1124                 unbecome_root();
1125                 DEBUG(8,("local_sid_to_uid: Could not find SID %s in passdb\n",
1126                         sid_string_static(psid)));
1127                 return False;
1128         }
1129         unbecome_root();
1130         
1131         user_name = pdb_get_username(sampw);
1132
1133         unix_pw = sys_getpwnam( user_name );
1134
1135         if ( !unix_pw ) {
1136                 DEBUG(0,("local_sid_to_uid: %s found in passdb but getpwnam() return NULL!\n",
1137                         user_name));
1138                 pdb_free_sam( &sampw );
1139                 return False;
1140         }
1141                 
1142         *puid = unix_pw->pw_uid;
1143         
1144         DEBUG(10,("local_sid_to_uid: SID %s -> uid (%u) (%s).\n", sid_string_static(psid),
1145                 (unsigned int)*puid, user_name ));
1146
1147         *name_type = SID_NAME_USER;
1148         
1149         return True;
1150 }
1151
1152 /****************************************************************************
1153  Convert a gid to SID - locally.
1154 ****************************************************************************/
1155
1156 DOM_SID *local_gid_to_sid(DOM_SID *psid, gid_t gid)
1157 {
1158         GROUP_MAP group;
1159         
1160         /* we don't need to disable winbindd since the gid is stored in 
1161            the GROUP_MAP object */
1162
1163         if ( !pdb_getgrgid( &group, gid ) ) {
1164
1165                 /* fallback to rid mapping if enabled */
1166
1167                 if ( lp_enable_rid_algorithm() ) {
1168                         sid_copy(psid, get_global_sam_sid());
1169                         sid_append_rid(psid, pdb_gid_to_group_rid(gid));
1170
1171                         DEBUG(10,("local_gid_to_sid: Fall back to algorithmic mapping: %u -> %s\n", 
1172                                 (unsigned int)gid, sid_string_static(psid)));
1173                                 
1174                         return psid;
1175                 }
1176                 else
1177                         return NULL;
1178         }
1179         
1180         sid_copy( psid, &group.sid );
1181         
1182         DEBUG(10,("local_gid_to_sid:  gid (%d) -> SID %s.\n", 
1183                 (unsigned int)gid, sid_string_static(psid)));   
1184         
1185         return psid;
1186 }
1187
1188 /****************************************************************************
1189  Convert a SID to gid - locally.
1190 ****************************************************************************/
1191
1192 BOOL local_sid_to_gid(gid_t *pgid, const DOM_SID *psid, enum SID_NAME_USE *name_type)
1193 {
1194         uint32 rid;
1195         GROUP_MAP group;
1196
1197         *name_type = SID_NAME_UNKNOWN;
1198
1199         /* This call can enumerate group mappings for foreign sids as well.
1200            So don't check for a match against our domain SID */
1201
1202         /* we don't need to disable winbindd since the gid is stored in 
1203            the GROUP_MAP object */
1204
1205         if ( !pdb_getgrsid(&group, *psid) ) {
1206
1207                 /* fallback to rid mapping if enabled */
1208
1209                 if ( lp_enable_rid_algorithm() ) {
1210
1211                         if (!sid_check_is_in_our_domain(psid) ) {
1212                                 DEBUG(5,("local_sid_to_gid: RID algorithm only supported for our domain (%s is not)\n", sid_string_static(psid)));
1213                                 return False;
1214                         }
1215
1216                         if (!sid_peek_rid(psid, &rid)) {
1217                                 DEBUG(10,("local_sid_to_uid: invalid SID!\n"));
1218                                         return False;
1219                         }
1220
1221                         DEBUG(10,("local_sid_to_gid: Fall back to algorithmic mapping\n"));
1222
1223                         if (fallback_pdb_rid_is_user(rid)) {
1224                                 DEBUG(3, ("local_sid_to_gid: SID %s is *NOT* a group\n", sid_string_static(psid)));
1225                                 return False;
1226                         } else {
1227                                 *pgid = pdb_group_rid_to_gid(rid);
1228                                 DEBUG(10,("local_sid_to_gid: mapping: %s -> %u\n", sid_string_static(psid), (unsigned int)(*pgid)));
1229                                 return True;
1230                         }
1231                 }
1232                 
1233                 return False;
1234         }
1235
1236         *pgid = group.gid;
1237
1238         DEBUG(10,("local_sid_to_gid: SID %s -> gid (%u)\n", sid_string_static(psid),
1239                 (unsigned int)*pgid));
1240
1241         return True;
1242 }
1243
1244 /**********************************************************************
1245  Marshall/unmarshall SAM_ACCOUNT structs.
1246  *********************************************************************/
1247
1248 #define TDB_FORMAT_STRING       "ddddddBBBBBBBBBBBBddBBwdwdBdd"
1249
1250 /**********************************************************************
1251  Intialize a SAM_ACCOUNT struct from a BYTE buffer of size len
1252  *********************************************************************/
1253
1254 BOOL init_sam_from_buffer(SAM_ACCOUNT *sampass, uint8 *buf, uint32 buflen)
1255 {
1256
1257         /* times are stored as 32bit integer
1258            take care on system with 64bit wide time_t
1259            --SSS */
1260         uint32  logon_time,
1261                 logoff_time,
1262                 kickoff_time,
1263                 pass_last_set_time,
1264                 pass_can_change_time,
1265                 pass_must_change_time;
1266         char *username;
1267         char *domain;
1268         char *nt_username;
1269         char *dir_drive;
1270         char *unknown_str;
1271         char *munged_dial;
1272         char *fullname;
1273         char *homedir;
1274         char *logon_script;
1275         char *profile_path;
1276         char *acct_desc;
1277         char *workstations;
1278         uint32  username_len, domain_len, nt_username_len,
1279                 dir_drive_len, unknown_str_len, munged_dial_len,
1280                 fullname_len, homedir_len, logon_script_len,
1281                 profile_path_len, acct_desc_len, workstations_len;
1282                 
1283         uint32  user_rid, group_rid, unknown_3, hours_len, unknown_5, unknown_6;
1284         uint16  acct_ctrl, logon_divs;
1285         uint8   *hours;
1286         static uint8    *lm_pw_ptr, *nt_pw_ptr;
1287         uint32          len = 0;
1288         uint32          lm_pw_len, nt_pw_len, hourslen;
1289         BOOL ret = True;
1290         uid_t uid = -1;
1291         gid_t gid = -1;
1292         
1293         if(sampass == NULL || buf == NULL) {
1294                 DEBUG(0, ("init_sam_from_buffer: NULL parameters found!\n"));
1295                 return False;
1296         }
1297                                                                         
1298         /* unpack the buffer into variables */
1299         len = tdb_unpack (buf, buflen, TDB_FORMAT_STRING,
1300                 &logon_time,
1301                 &logoff_time,
1302                 &kickoff_time,
1303                 &pass_last_set_time,
1304                 &pass_can_change_time,
1305                 &pass_must_change_time,
1306                 &username_len, &username,
1307                 &domain_len, &domain,
1308                 &nt_username_len, &nt_username,
1309                 &fullname_len, &fullname,
1310                 &homedir_len, &homedir,
1311                 &dir_drive_len, &dir_drive,
1312                 &logon_script_len, &logon_script,
1313                 &profile_path_len, &profile_path,
1314                 &acct_desc_len, &acct_desc,
1315                 &workstations_len, &workstations,
1316                 &unknown_str_len, &unknown_str,
1317                 &munged_dial_len, &munged_dial,
1318                 &user_rid,
1319                 &group_rid,
1320                 &lm_pw_len, &lm_pw_ptr,
1321                 &nt_pw_len, &nt_pw_ptr,
1322                 &acct_ctrl,
1323                 &unknown_3,
1324                 &logon_divs,
1325                 &hours_len,
1326                 &hourslen, &hours,
1327                 &unknown_5,
1328                 &unknown_6);
1329                 
1330         if (len == -1)  {
1331                 ret = False;
1332                 goto done;
1333         }
1334
1335         pdb_set_logon_time(sampass, logon_time, PDB_SET);
1336         pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
1337         pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
1338         pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
1339         pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
1340         pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
1341
1342         pdb_set_username(sampass, username, PDB_SET); 
1343         pdb_set_domain(sampass, domain, PDB_SET);
1344         pdb_set_nt_username(sampass, nt_username, PDB_SET);
1345         pdb_set_fullname(sampass, fullname, PDB_SET);
1346
1347         if (homedir) {
1348                 pdb_set_homedir(sampass, homedir, PDB_SET);
1349         }
1350         else {
1351                 pdb_set_homedir(sampass, 
1352                                 talloc_sub_specified(sampass->mem_ctx, 
1353                                                        lp_logon_home(),
1354                                                        username, domain, 
1355                                                        uid, gid),
1356                                 PDB_DEFAULT);
1357         }
1358
1359         if (dir_drive)  
1360                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
1361         else {
1362                 pdb_set_dir_drive(sampass, 
1363                                   talloc_sub_specified(sampass->mem_ctx, 
1364                                                          lp_logon_drive(),
1365                                                          username, domain, 
1366                                                          uid, gid),
1367                                   PDB_DEFAULT);
1368         }
1369
1370         if (logon_script) 
1371                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
1372         else {
1373                 pdb_set_logon_script(sampass, 
1374                                      talloc_sub_specified(sampass->mem_ctx, 
1375                                                             lp_logon_script(),
1376                                                             username, domain, 
1377                                                             uid, gid),
1378                                   PDB_DEFAULT);
1379         }
1380         
1381         if (profile_path) {     
1382                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
1383         } else {
1384                 pdb_set_profile_path(sampass, 
1385                                      talloc_sub_specified(sampass->mem_ctx, 
1386                                                             lp_logon_path(),
1387                                                             username, domain, 
1388                                                             uid, gid),
1389                                      PDB_DEFAULT);
1390         }
1391
1392         pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
1393         pdb_set_workstations(sampass, workstations, PDB_SET);
1394         pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
1395
1396         if (lm_pw_ptr && lm_pw_len == LM_HASH_LEN) {
1397                 if (!pdb_set_lanman_passwd(sampass, lm_pw_ptr, PDB_SET)) {
1398                         ret = False;
1399                         goto done;
1400                 }
1401         }
1402
1403         if (nt_pw_ptr && nt_pw_len == NT_HASH_LEN) {
1404                 if (!pdb_set_nt_passwd(sampass, nt_pw_ptr, PDB_SET)) {
1405                         ret = False;
1406                         goto done;
1407                 }
1408         }
1409
1410         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
1411         pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
1412         pdb_set_unknown_3(sampass, unknown_3, PDB_SET);
1413         pdb_set_hours_len(sampass, hours_len, PDB_SET);
1414         pdb_set_unknown_5(sampass, unknown_5, PDB_SET);
1415         pdb_set_unknown_6(sampass, unknown_6, PDB_SET);
1416         pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
1417         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
1418         pdb_set_hours(sampass, hours, PDB_SET);
1419
1420 done:
1421
1422         SAFE_FREE(username);
1423         SAFE_FREE(domain);
1424         SAFE_FREE(nt_username);
1425         SAFE_FREE(fullname);
1426         SAFE_FREE(homedir);
1427         SAFE_FREE(dir_drive);
1428         SAFE_FREE(logon_script);
1429         SAFE_FREE(profile_path);
1430         SAFE_FREE(acct_desc);
1431         SAFE_FREE(workstations);
1432         SAFE_FREE(munged_dial);
1433         SAFE_FREE(unknown_str);
1434         SAFE_FREE(hours);
1435
1436         return ret;
1437 }
1438
1439 /**********************************************************************
1440  Intialize a BYTE buffer from a SAM_ACCOUNT struct
1441  *********************************************************************/
1442
1443 uint32 init_buffer_from_sam (uint8 **buf, const SAM_ACCOUNT *sampass, BOOL size_only)
1444 {
1445         size_t len, buflen;
1446
1447         /* times are stored as 32bit integer
1448            take care on system with 64bit wide time_t
1449            --SSS */
1450         uint32  logon_time,
1451                 logoff_time,
1452                 kickoff_time,
1453                 pass_last_set_time,
1454                 pass_can_change_time,
1455                 pass_must_change_time;
1456
1457         uint32  user_rid, group_rid;
1458
1459         const char *username;
1460         const char *domain;
1461         const char *nt_username;
1462         const char *dir_drive;
1463         const char *unknown_str;
1464         const char *munged_dial;
1465         const char *fullname;
1466         const char *homedir;
1467         const char *logon_script;
1468         const char *profile_path;
1469         const char *acct_desc;
1470         const char *workstations;
1471         uint32  username_len, domain_len, nt_username_len,
1472                 dir_drive_len, unknown_str_len, munged_dial_len,
1473                 fullname_len, homedir_len, logon_script_len,
1474                 profile_path_len, acct_desc_len, workstations_len;
1475
1476         const uint8 *lm_pw;
1477         const uint8 *nt_pw;
1478         uint32  lm_pw_len = 16;
1479         uint32  nt_pw_len = 16;
1480
1481         /* do we have a valid SAM_ACCOUNT pointer? */
1482         if (sampass == NULL) {
1483                 DEBUG(0, ("init_buffer_from_sam: SAM_ACCOUNT is NULL!\n"));
1484                 return -1;
1485         }
1486         
1487         *buf = NULL;
1488         buflen = 0;
1489
1490         logon_time = (uint32)pdb_get_logon_time(sampass);
1491         logoff_time = (uint32)pdb_get_logoff_time(sampass);
1492         kickoff_time = (uint32)pdb_get_kickoff_time(sampass);
1493         pass_can_change_time = (uint32)pdb_get_pass_can_change_time(sampass);
1494         pass_must_change_time = (uint32)pdb_get_pass_must_change_time(sampass);
1495         pass_last_set_time = (uint32)pdb_get_pass_last_set_time(sampass);
1496
1497         user_rid = pdb_get_user_rid(sampass);
1498         group_rid = pdb_get_group_rid(sampass);
1499
1500         username = pdb_get_username(sampass);
1501         if (username)
1502                 username_len = strlen(username) +1;
1503         else
1504                 username_len = 0;
1505
1506         domain = pdb_get_domain(sampass);
1507         if (domain)
1508                 domain_len = strlen(domain) +1;
1509         else
1510                 domain_len = 0;
1511
1512         nt_username = pdb_get_nt_username(sampass);
1513         if (nt_username)
1514                 nt_username_len = strlen(nt_username) +1;
1515         else
1516                 nt_username_len = 0;
1517
1518         fullname = pdb_get_fullname(sampass);
1519         if (fullname)
1520                 fullname_len = strlen(fullname) +1;
1521         else
1522                 fullname_len = 0;
1523
1524         /*
1525          * Only updates fields which have been set (not defaults from smb.conf)
1526          */
1527
1528         if (!IS_SAM_DEFAULT(sampass, PDB_DRIVE)) 
1529                 dir_drive = pdb_get_dir_drive(sampass);
1530         else
1531                 dir_drive = NULL;
1532         if (dir_drive)
1533                 dir_drive_len = strlen(dir_drive) +1;
1534         else
1535                 dir_drive_len = 0;
1536
1537         if (!IS_SAM_DEFAULT(sampass, PDB_SMBHOME))
1538                 homedir = pdb_get_homedir(sampass);
1539         else
1540                 homedir = NULL;
1541         if (homedir)
1542                 homedir_len = strlen(homedir) +1;
1543         else
1544                 homedir_len = 0;
1545
1546         if (!IS_SAM_DEFAULT(sampass, PDB_LOGONSCRIPT))
1547                 logon_script = pdb_get_logon_script(sampass);
1548         else
1549                 logon_script = NULL;
1550         if (logon_script)
1551                 logon_script_len = strlen(logon_script) +1;
1552         else
1553                 logon_script_len = 0;
1554
1555         if (!IS_SAM_DEFAULT(sampass, PDB_PROFILE))
1556                 profile_path = pdb_get_profile_path(sampass);
1557         else
1558                 profile_path = NULL;
1559         if (profile_path)
1560                 profile_path_len = strlen(profile_path) +1;
1561         else
1562                 profile_path_len = 0;
1563         
1564         lm_pw = pdb_get_lanman_passwd(sampass);
1565         if (!lm_pw)
1566                 lm_pw_len = 0;
1567         
1568         nt_pw = pdb_get_nt_passwd(sampass);
1569         if (!nt_pw)
1570                 nt_pw_len = 0;
1571                 
1572         acct_desc = pdb_get_acct_desc(sampass);
1573         if (acct_desc)
1574                 acct_desc_len = strlen(acct_desc) +1;
1575         else
1576                 acct_desc_len = 0;
1577
1578         workstations = pdb_get_workstations(sampass);
1579         if (workstations)
1580                 workstations_len = strlen(workstations) +1;
1581         else
1582                 workstations_len = 0;
1583
1584         unknown_str = NULL;
1585         unknown_str_len = 0;
1586
1587         munged_dial = pdb_get_munged_dial(sampass);
1588         if (munged_dial)
1589                 munged_dial_len = strlen(munged_dial) +1;
1590         else
1591                 munged_dial_len = 0;    
1592                 
1593         /* one time to get the size needed */
1594         len = tdb_pack(NULL, 0,  TDB_FORMAT_STRING,
1595                 logon_time,
1596                 logoff_time,
1597                 kickoff_time,
1598                 pass_last_set_time,
1599                 pass_can_change_time,
1600                 pass_must_change_time,
1601                 username_len, username,
1602                 domain_len, domain,
1603                 nt_username_len, nt_username,
1604                 fullname_len, fullname,
1605                 homedir_len, homedir,
1606                 dir_drive_len, dir_drive,
1607                 logon_script_len, logon_script,
1608                 profile_path_len, profile_path,
1609                 acct_desc_len, acct_desc,
1610                 workstations_len, workstations,
1611                 unknown_str_len, unknown_str,
1612                 munged_dial_len, munged_dial,
1613                 user_rid,
1614                 group_rid,
1615                 lm_pw_len, lm_pw,
1616                 nt_pw_len, nt_pw,
1617                 pdb_get_acct_ctrl(sampass),
1618                 pdb_get_unknown_3(sampass),
1619                 pdb_get_logon_divs(sampass),
1620                 pdb_get_hours_len(sampass),
1621                 MAX_HOURS_LEN, pdb_get_hours(sampass),
1622                 pdb_get_unknown_5(sampass),
1623                 pdb_get_unknown_6(sampass));
1624
1625
1626         if (size_only)
1627                 return buflen;
1628
1629         /* malloc the space needed */
1630         if ( (*buf=(uint8*)malloc(len)) == NULL) {
1631                 DEBUG(0,("init_buffer_from_sam: Unable to malloc() memory for buffer!\n"));
1632                 return (-1);
1633         }
1634         
1635         /* now for the real call to tdb_pack() */
1636         buflen = tdb_pack(*buf, len,  TDB_FORMAT_STRING,
1637                 logon_time,
1638                 logoff_time,
1639                 kickoff_time,
1640                 pass_last_set_time,
1641                 pass_can_change_time,
1642                 pass_must_change_time,
1643                 username_len, username,
1644                 domain_len, domain,
1645                 nt_username_len, nt_username,
1646                 fullname_len, fullname,
1647                 homedir_len, homedir,
1648                 dir_drive_len, dir_drive,
1649                 logon_script_len, logon_script,
1650                 profile_path_len, profile_path,
1651                 acct_desc_len, acct_desc,
1652                 workstations_len, workstations,
1653                 unknown_str_len, unknown_str,
1654                 munged_dial_len, munged_dial,
1655                 user_rid,
1656                 group_rid,
1657                 lm_pw_len, lm_pw,
1658                 nt_pw_len, nt_pw,
1659                 pdb_get_acct_ctrl(sampass),
1660                 pdb_get_unknown_3(sampass),
1661                 pdb_get_logon_divs(sampass),
1662                 pdb_get_hours_len(sampass),
1663                 MAX_HOURS_LEN, pdb_get_hours(sampass),
1664                 pdb_get_unknown_5(sampass),
1665                 pdb_get_unknown_6(sampass));
1666         
1667         
1668         /* check to make sure we got it correct */
1669         if (buflen != len) {
1670                 DEBUG(0, ("init_buffer_from_sam: somthing odd is going on here: bufflen (%lu) != len (%lu) in tdb_pack operations!\n", 
1671                           (unsigned long)buflen, (unsigned long)len));  
1672                 /* error */
1673                 SAFE_FREE (*buf);
1674                 return (-1);
1675         }
1676
1677         return (buflen);
1678 }