8ba90d6630742d0b61adc32883c474700f277ee6
[import/samba-svnimport.git] / source / passdb / secrets.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Copyright (C) Andrew Tridgell 1992-2001
4    Copyright (C) Andrew Bartlett      2002
5    Copyright (C) Rafal Szczesniak     2002
6    Copyright (C) Tim Potter           2001
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 /* the Samba secrets database stores any generated, private information
24    such as the local SID and machine trust password */
25
26 #include "includes.h"
27
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_PASSDB
30
31 static TDB_CONTEXT *tdb;
32
33 /* Urrrg. global.... */
34 BOOL global_machine_password_needs_changing;
35
36 /**
37  * Use a TDB to store an incrementing random seed.
38  *
39  * Initialised to the current pid, the very first time Samba starts,
40  * and incremented by one each time it is needed.  
41  * 
42  * @note Not called by systems with a working /dev/urandom.
43  */
44 static void get_rand_seed(int *new_seed) 
45 {
46         *new_seed = sys_getpid();
47         if (tdb) {
48                 tdb_change_int32_atomic(tdb, "INFO/random_seed", new_seed, 1);
49         }
50 }
51
52 /* open up the secrets database */
53 BOOL secrets_init(void)
54 {
55         pstring fname;
56         unsigned char dummy;
57
58         if (tdb)
59                 return True;
60
61         pstrcpy(fname, lp_private_dir());
62         pstrcat(fname,"/secrets.tdb");
63
64         tdb = tdb_open_log(fname, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
65
66         if (!tdb) {
67                 DEBUG(0,("Failed to open %s\n", fname));
68                 return False;
69         }
70
71         /**
72          * Set a reseed function for the crypto random generator 
73          * 
74          * This avoids a problem where systems without /dev/urandom
75          * could send the same challenge to multiple clients
76          */
77         set_rand_reseed_callback(get_rand_seed);
78
79         /* Ensure that the reseed is done now, while we are root, etc */
80         generate_random_buffer(&dummy, sizeof(dummy));
81
82         return True;
83 }
84
85 /* read a entry from the secrets database - the caller must free the result
86    if size is non-null then the size of the entry is put in there
87  */
88 void *secrets_fetch(const char *key, size_t *size)
89 {
90         TDB_DATA dbuf;
91         secrets_init();
92         if (!tdb)
93                 return NULL;
94         dbuf = tdb_fetch(tdb, string_tdb_data(key));
95         if (size)
96                 *size = dbuf.dsize;
97         return dbuf.dptr;
98 }
99
100 /* store a secrets entry 
101  */
102 BOOL secrets_store(const char *key, const void *data, size_t size)
103 {
104         secrets_init();
105         if (!tdb)
106                 return False;
107         return tdb_trans_store(tdb, string_tdb_data(key),
108                                make_tdb_data(data, size), TDB_REPLACE) == 0;
109 }
110
111
112 /* delete a secets database entry
113  */
114 BOOL secrets_delete(const char *key)
115 {
116         secrets_init();
117         if (!tdb)
118                 return False;
119         return tdb_delete(tdb, string_tdb_data(key)) == 0;
120 }
121
122 BOOL secrets_store_domain_sid(const char *domain, const DOM_SID *sid)
123 {
124         fstring key;
125         BOOL ret;
126
127         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_SID, domain);
128         strupper_m(key);
129         ret = secrets_store(key, sid, sizeof(DOM_SID));
130
131         /* Force a re-query, in case we modified our domain */
132         if (ret)
133                 reset_global_sam_sid();
134         return ret;
135 }
136
137 BOOL secrets_fetch_domain_sid(const char *domain, DOM_SID *sid)
138 {
139         DOM_SID *dyn_sid;
140         fstring key;
141         size_t size = 0;
142
143         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_SID, domain);
144         strupper_m(key);
145         dyn_sid = (DOM_SID *)secrets_fetch(key, &size);
146
147         if (dyn_sid == NULL)
148                 return False;
149
150         if (size != sizeof(DOM_SID)) { 
151                 SAFE_FREE(dyn_sid);
152                 return False;
153         }
154
155         *sid = *dyn_sid;
156         SAFE_FREE(dyn_sid);
157         return True;
158 }
159
160 BOOL secrets_store_domain_guid(const char *domain, struct uuid *guid)
161 {
162         fstring key;
163
164         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_GUID, domain);
165         strupper_m(key);
166         return secrets_store(key, guid, sizeof(struct uuid));
167 }
168
169 BOOL secrets_fetch_domain_guid(const char *domain, struct uuid *guid)
170 {
171         struct uuid *dyn_guid;
172         fstring key;
173         size_t size = 0;
174         struct uuid new_guid;
175
176         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_GUID, domain);
177         strupper_m(key);
178         dyn_guid = (struct uuid *)secrets_fetch(key, &size);
179
180         if (!dyn_guid) {
181                 if (lp_server_role() == ROLE_DOMAIN_PDC) {
182                         smb_uuid_generate_random(&new_guid);
183                         if (!secrets_store_domain_guid(domain, &new_guid))
184                                 return False;
185                         dyn_guid = (struct uuid *)secrets_fetch(key, &size);
186                 }
187                 if (dyn_guid == NULL) {
188                         return False;
189                 }
190         }
191
192         if (size != sizeof(struct uuid)) { 
193                 DEBUG(1,("UUID size %d is wrong!\n", (int)size));
194                 SAFE_FREE(dyn_guid);
195                 return False;
196         }
197
198         *guid = *dyn_guid;
199         SAFE_FREE(dyn_guid);
200         return True;
201 }
202
203 /**
204  * Form a key for fetching the machine trust account password
205  *
206  * @param domain domain name
207  *
208  * @return stored password's key
209  **/
210 const char *trust_keystr(const char *domain)
211 {
212         static fstring keystr;
213
214         slprintf(keystr,sizeof(keystr)-1,"%s/%s", 
215                  SECRETS_MACHINE_ACCT_PASS, domain);
216         strupper_m(keystr);
217
218         return keystr;
219 }
220
221 /**
222  * Form a key for fetching a trusted domain password
223  *
224  * @param domain trusted domain name
225  *
226  * @return stored password's key
227  **/
228 static char *trustdom_keystr(const char *domain)
229 {
230         static pstring keystr;
231
232         pstr_sprintf(keystr, "%s/%s", SECRETS_DOMTRUST_ACCT_PASS, domain);
233         strupper_m(keystr);
234                 
235         return keystr;
236 }
237
238 /************************************************************************
239  Lock the trust password entry.
240 ************************************************************************/
241
242 BOOL secrets_lock_trust_account_password(const char *domain, BOOL dolock)
243 {
244         if (!tdb)
245                 return False;
246
247         if (dolock)
248                 return (tdb_lock_bystring(tdb, trust_keystr(domain)) == 0);
249         else
250                 tdb_unlock_bystring(tdb, trust_keystr(domain));
251         return True;
252 }
253
254 /************************************************************************
255  Routine to get the default secure channel type for trust accounts
256 ************************************************************************/
257
258 uint32 get_default_sec_channel(void) 
259 {
260         if (lp_server_role() == ROLE_DOMAIN_BDC || 
261             lp_server_role() == ROLE_DOMAIN_PDC) {
262                 return SEC_CHAN_BDC;
263         } else {
264                 return SEC_CHAN_WKSTA;
265         }
266 }
267
268 /************************************************************************
269  Routine to get the trust account password for a domain.
270  The user of this function must have locked the trust password file using
271  the above secrets_lock_trust_account_password().
272 ************************************************************************/
273
274 BOOL secrets_fetch_trust_account_password(const char *domain, uint8 ret_pwd[16],
275                                           time_t *pass_last_set_time,
276                                           uint32 *channel)
277 {
278         struct machine_acct_pass *pass;
279         char *plaintext;
280         size_t size = 0;
281
282         plaintext = secrets_fetch_machine_password(domain, pass_last_set_time, 
283                                                    channel);
284         if (plaintext) {
285                 DEBUG(4,("Using cleartext machine password\n"));
286                 E_md4hash(plaintext, ret_pwd);
287                 SAFE_FREE(plaintext);
288                 return True;
289         }
290
291         if (!(pass = secrets_fetch(trust_keystr(domain), &size))) {
292                 DEBUG(5, ("secrets_fetch failed!\n"));
293                 return False;
294         }
295         
296         if (size != sizeof(*pass)) {
297                 DEBUG(0, ("secrets were of incorrect size!\n"));
298                 return False;
299         }
300
301         if (pass_last_set_time) {
302                 *pass_last_set_time = pass->mod_time;
303         }
304         memcpy(ret_pwd, pass->hash, 16);
305
306         if (channel) {
307                 *channel = get_default_sec_channel();
308         }
309
310         /* Test if machine password has expired and needs to be changed */
311         if (lp_machine_password_timeout()) {
312                 if (pass->mod_time > 0 && time(NULL) > (pass->mod_time +
313                                 (time_t)lp_machine_password_timeout())) {
314                         global_machine_password_needs_changing = True;
315                 }
316         }
317
318         SAFE_FREE(pass);
319         return True;
320 }
321
322 /**
323  * Pack SID passed by pointer
324  *
325  * @param pack_buf pointer to buffer which is to be filled with packed data
326  * @param bufsize size of packing buffer
327  * @param sid pointer to sid to be packed
328  *
329  * @return length of the packed representation of the whole structure
330  **/
331 static size_t tdb_sid_pack(char* pack_buf, int bufsize, DOM_SID* sid)
332 {
333         int idx;
334         size_t len = 0;
335         
336         if (!sid || !pack_buf) return -1;
337         
338         len += tdb_pack(pack_buf + len, bufsize - len, "bb", sid->sid_rev_num,
339                         sid->num_auths);
340         
341         for (idx = 0; idx < 6; idx++) {
342                 len += tdb_pack(pack_buf + len, bufsize - len, "b",
343                                 sid->id_auth[idx]);
344         }
345         
346         for (idx = 0; idx < MAXSUBAUTHS; idx++) {
347                 len += tdb_pack(pack_buf + len, bufsize - len, "d",
348                                 sid->sub_auths[idx]);
349         }
350         
351         return len;
352 }
353
354 /**
355  * Unpack SID into a pointer
356  *
357  * @param pack_buf pointer to buffer with packed representation
358  * @param bufsize size of the buffer
359  * @param sid pointer to sid structure to be filled with unpacked data
360  *
361  * @return size of structure unpacked from buffer
362  **/
363 static size_t tdb_sid_unpack(char* pack_buf, int bufsize, DOM_SID* sid)
364 {
365         int idx, len = 0;
366         
367         if (!sid || !pack_buf) return -1;
368
369         len += tdb_unpack(pack_buf + len, bufsize - len, "bb",
370                           &sid->sid_rev_num, &sid->num_auths);
371                           
372         for (idx = 0; idx < 6; idx++) {
373                 len += tdb_unpack(pack_buf + len, bufsize - len, "b",
374                                   &sid->id_auth[idx]);
375         }
376         
377         for (idx = 0; idx < MAXSUBAUTHS; idx++) {
378                 len += tdb_unpack(pack_buf + len, bufsize - len, "d",
379                                   &sid->sub_auths[idx]);
380         }
381         
382         return len;
383 }
384
385 /**
386  * Pack TRUSTED_DOM_PASS passed by pointer
387  *
388  * @param pack_buf pointer to buffer which is to be filled with packed data
389  * @param bufsize size of the buffer
390  * @param pass pointer to trusted domain password to be packed
391  *
392  * @return length of the packed representation of the whole structure
393  **/
394 static size_t tdb_trusted_dom_pass_pack(char* pack_buf, int bufsize,
395                                         TRUSTED_DOM_PASS* pass)
396 {
397         int idx, len = 0;
398         
399         if (!pack_buf || !pass) return -1;
400         
401         /* packing unicode domain name and password */
402         len += tdb_pack(pack_buf + len, bufsize - len, "d",
403                         pass->uni_name_len);
404         
405         for (idx = 0; idx < 32; idx++)
406                 len +=  tdb_pack(pack_buf + len, bufsize - len, "w",
407                                  pass->uni_name[idx]);
408         
409         len += tdb_pack(pack_buf + len, bufsize - len, "dPd", pass->pass_len,
410                              pass->pass, pass->mod_time);
411
412         /* packing SID structure */
413         len += tdb_sid_pack(pack_buf + len, bufsize - len, &pass->domain_sid);
414
415         return len;
416 }
417
418
419 /**
420  * Unpack TRUSTED_DOM_PASS passed by pointer
421  *
422  * @param pack_buf pointer to buffer with packed representation
423  * @param bufsize size of the buffer
424  * @param pass pointer to trusted domain password to be filled with unpacked data
425  *
426  * @return size of structure unpacked from buffer
427  **/
428 size_t tdb_trusted_dom_pass_unpack(char* pack_buf, int bufsize,
429                                    TRUSTED_DOM_PASS* pass)
430 {
431         int idx, len = 0;
432         
433         if (!pack_buf || !pass) return -1;
434
435         /* unpack unicode domain name and plaintext password */
436         len += tdb_unpack(pack_buf, bufsize - len, "d", &pass->uni_name_len);
437         
438         for (idx = 0; idx < 32; idx++)
439                 len +=  tdb_unpack(pack_buf + len, bufsize - len, "w",
440                                    &pass->uni_name[idx]);
441
442         len += tdb_unpack(pack_buf + len, bufsize - len, "dPd",
443                           &pass->pass_len, &pass->pass, &pass->mod_time);
444         
445         /* unpack domain sid */
446         len += tdb_sid_unpack(pack_buf + len, bufsize - len,
447                               &pass->domain_sid);
448         
449         return len;     
450 }
451
452 /************************************************************************
453  Routine to get account password to trusted domain
454 ************************************************************************/
455
456 BOOL secrets_fetch_trusted_domain_password(const char *domain, char** pwd,
457                                            DOM_SID *sid, time_t *pass_last_set_time)
458 {
459         struct trusted_dom_pass pass;
460         size_t size = 0;
461         
462         /* unpacking structures */
463         char* pass_buf;
464         int pass_len = 0;
465
466         ZERO_STRUCT(pass);
467
468         /* fetching trusted domain password structure */
469         if (!(pass_buf = secrets_fetch(trustdom_keystr(domain), &size))) {
470                 DEBUG(5, ("secrets_fetch failed!\n"));
471                 return False;
472         }
473
474         /* unpack trusted domain password */
475         pass_len = tdb_trusted_dom_pass_unpack(pass_buf, size, &pass);
476         SAFE_FREE(pass_buf);
477
478         if (pass_len != size) {
479                 DEBUG(5, ("Invalid secrets size. Unpacked data doesn't match trusted_dom_pass structure.\n"));
480                 return False;
481         }
482                         
483         /* the trust's password */      
484         if (pwd) {
485                 *pwd = SMB_STRDUP(pass.pass);
486                 if (!*pwd) {
487                         return False;
488                 }
489         }
490
491         /* last change time */
492         if (pass_last_set_time) *pass_last_set_time = pass.mod_time;
493
494         /* domain sid */
495         if (sid != NULL) sid_copy(sid, &pass.domain_sid);
496                 
497         return True;
498 }
499
500 /************************************************************************
501  Routine to set the trust account password for a domain.
502 ************************************************************************/
503
504 BOOL secrets_store_trust_account_password(const char *domain, uint8 new_pwd[16])
505 {
506         struct machine_acct_pass pass;
507
508         pass.mod_time = time(NULL);
509         memcpy(pass.hash, new_pwd, 16);
510
511         return secrets_store(trust_keystr(domain), (void *)&pass, sizeof(pass));
512 }
513
514 /**
515  * Routine to store the password for trusted domain
516  *
517  * @param domain remote domain name
518  * @param pwd plain text password of trust relationship
519  * @param sid remote domain sid
520  *
521  * @return true if succeeded
522  **/
523
524 BOOL secrets_store_trusted_domain_password(const char* domain, const char* pwd,
525                                            const DOM_SID *sid)
526 {
527         smb_ucs2_t *uni_dom_name;
528
529         /* packing structures */
530         pstring pass_buf;
531         int pass_len = 0;
532         int pass_buf_len = sizeof(pass_buf);
533         
534         struct trusted_dom_pass pass;
535         ZERO_STRUCT(pass);
536
537         if (push_ucs2_allocate(&uni_dom_name, domain) == (size_t)-1) {
538                 DEBUG(0, ("Could not convert domain name %s to unicode\n",
539                           domain));
540                 return False;
541         }
542         
543         strncpy_w(pass.uni_name, uni_dom_name, sizeof(pass.uni_name) - 1);
544         pass.uni_name_len = strlen_w(uni_dom_name)+1;
545         SAFE_FREE(uni_dom_name);
546
547         /* last change time */
548         pass.mod_time = time(NULL);
549
550         /* password of the trust */
551         pass.pass_len = strlen(pwd);
552         fstrcpy(pass.pass, pwd);
553
554         /* domain sid */
555         sid_copy(&pass.domain_sid, sid);
556         
557         pass_len = tdb_trusted_dom_pass_pack(pass_buf, pass_buf_len, &pass);
558
559         return secrets_store(trustdom_keystr(domain), (void *)&pass_buf, pass_len);
560 }
561
562 /************************************************************************
563  Routine to set the plaintext machine account password for a realm
564 the password is assumed to be a null terminated ascii string
565 ************************************************************************/
566
567 BOOL secrets_store_machine_password(const char *pass, const char *domain, uint32 sec_channel)
568 {
569         char *key = NULL;
570         BOOL ret;
571         uint32 last_change_time;
572         uint32 sec_channel_type;
573
574         asprintf(&key, "%s/%s", SECRETS_MACHINE_PASSWORD, domain);
575         if (!key) 
576                 return False;
577         strupper_m(key);
578
579         ret = secrets_store(key, pass, strlen(pass)+1);
580         SAFE_FREE(key);
581
582         if (!ret)
583                 return ret;
584         
585         asprintf(&key, "%s/%s", SECRETS_MACHINE_LAST_CHANGE_TIME, domain);
586         if (!key) 
587                 return False;
588         strupper_m(key);
589
590         SIVAL(&last_change_time, 0, time(NULL));
591         ret = secrets_store(key, &last_change_time, sizeof(last_change_time));
592         SAFE_FREE(key);
593
594         asprintf(&key, "%s/%s", SECRETS_MACHINE_SEC_CHANNEL_TYPE, domain);
595         if (!key) 
596                 return False;
597         strupper_m(key);
598
599         SIVAL(&sec_channel_type, 0, sec_channel);
600         ret = secrets_store(key, &sec_channel_type, sizeof(sec_channel_type));
601         SAFE_FREE(key);
602
603         return ret;
604 }
605
606 /************************************************************************
607  Routine to fetch the plaintext machine account password for a realm
608  the password is assumed to be a null terminated ascii string.
609 ************************************************************************/
610
611 char *secrets_fetch_machine_password(const char *domain, 
612                                      time_t *pass_last_set_time,
613                                      uint32 *channel)
614 {
615         char *key = NULL;
616         char *ret;
617         asprintf(&key, "%s/%s", SECRETS_MACHINE_PASSWORD, domain);
618         strupper_m(key);
619         ret = (char *)secrets_fetch(key, NULL);
620         SAFE_FREE(key);
621         
622         if (pass_last_set_time) {
623                 size_t size;
624                 uint32 *last_set_time;
625                 asprintf(&key, "%s/%s", SECRETS_MACHINE_LAST_CHANGE_TIME, domain);
626                 strupper_m(key);
627                 last_set_time = secrets_fetch(key, &size);
628                 if (last_set_time) {
629                         *pass_last_set_time = IVAL(last_set_time,0);
630                         SAFE_FREE(last_set_time);
631                 } else {
632                         *pass_last_set_time = 0;
633                 }
634                 SAFE_FREE(key);
635         }
636         
637         if (channel) {
638                 size_t size;
639                 uint32 *channel_type;
640                 asprintf(&key, "%s/%s", SECRETS_MACHINE_SEC_CHANNEL_TYPE, domain);
641                 strupper_m(key);
642                 channel_type = secrets_fetch(key, &size);
643                 if (channel_type) {
644                         *channel = IVAL(channel_type,0);
645                         SAFE_FREE(channel_type);
646                 } else {
647                         *channel = get_default_sec_channel();
648                 }
649                 SAFE_FREE(key);
650         }
651         
652         return ret;
653 }
654
655 /*******************************************************************
656  Wrapper around retrieving the trust account password
657 *******************************************************************/
658                                                                                                                      
659 BOOL get_trust_pw(const char *domain, uint8 ret_pwd[16], uint32 *channel)
660 {
661         DOM_SID sid;
662         char *pwd;
663         time_t last_set_time;
664                                                                                                                      
665         /* if we are a DC and this is not our domain, then lookup an account
666                 for the domain trust */
667                                                                                                                      
668         if ( IS_DC && !strequal(domain, lp_workgroup()) && lp_allow_trusted_domains() ) {
669                 if (!secrets_fetch_trusted_domain_password(domain, &pwd, &sid,
670                                                         &last_set_time)) {
671                         DEBUG(0, ("get_trust_pw: could not fetch trust "
672                                 "account password for trusted domain %s\n",
673                                 domain));
674                         return False;
675                 }
676                                                                                                                      
677                 *channel = SEC_CHAN_DOMAIN;
678                 E_md4hash(pwd, ret_pwd);
679                 SAFE_FREE(pwd);
680
681                 return True;
682         }
683                                                                                                                      
684         /* Just get the account for the requested domain. In the future this
685          * might also cover to be member of more than one domain. */
686                                                                                                                      
687         if (secrets_fetch_trust_account_password(domain, ret_pwd,
688                                                 &last_set_time, channel))
689                 return True;
690
691         DEBUG(5, ("get_trust_pw: could not fetch trust account "
692                 "password for domain %s\n", domain));
693         return False;
694 }
695
696 /************************************************************************
697  Routine to delete the machine trust account password file for a domain.
698 ************************************************************************/
699
700 BOOL trust_password_delete(const char *domain)
701 {
702         return secrets_delete(trust_keystr(domain));
703 }
704
705 /************************************************************************
706  Routine to delete the password for trusted domain
707 ************************************************************************/
708
709 BOOL trusted_domain_password_delete(const char *domain)
710 {
711         return secrets_delete(trustdom_keystr(domain));
712 }
713
714 BOOL secrets_store_ldap_pw(const char* dn, char* pw)
715 {
716         char *key = NULL;
717         BOOL ret;
718         
719         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, dn) < 0) {
720                 DEBUG(0, ("secrets_store_ldap_pw: asprintf failed!\n"));
721                 return False;
722         }
723                 
724         ret = secrets_store(key, pw, strlen(pw)+1);
725         
726         SAFE_FREE(key);
727         return ret;
728 }
729
730 /*******************************************************************
731  Find the ldap password.
732 ******************************************************************/
733
734 BOOL fetch_ldap_pw(char **dn, char** pw)
735 {
736         char *key = NULL;
737         size_t size = 0;
738         
739         *dn = smb_xstrdup(lp_ldap_admin_dn());
740         
741         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, *dn) < 0) {
742                 SAFE_FREE(*dn);
743                 DEBUG(0, ("fetch_ldap_pw: asprintf failed!\n"));
744         }
745         
746         *pw=secrets_fetch(key, &size);
747         SAFE_FREE(key);
748
749         if (!size) {
750                 /* Upgrade 2.2 style entry */
751                 char *p;
752                 char* old_style_key = SMB_STRDUP(*dn);
753                 char *data;
754                 fstring old_style_pw;
755                 
756                 if (!old_style_key) {
757                         DEBUG(0, ("fetch_ldap_pw: strdup failed!\n"));
758                         return False;
759                 }
760
761                 for (p=old_style_key; *p; p++)
762                         if (*p == ',') *p = '/';
763         
764                 data=secrets_fetch(old_style_key, &size);
765                 if (!size && size < sizeof(old_style_pw)) {
766                         DEBUG(0,("fetch_ldap_pw: neither ldap secret retrieved!\n"));
767                         SAFE_FREE(old_style_key);
768                         SAFE_FREE(*dn);
769                         return False;
770                 }
771
772                 size = MIN(size, sizeof(fstring)-1);
773                 strncpy(old_style_pw, data, size);
774                 old_style_pw[size] = 0;
775
776                 SAFE_FREE(data);
777
778                 if (!secrets_store_ldap_pw(*dn, old_style_pw)) {
779                         DEBUG(0,("fetch_ldap_pw: ldap secret could not be upgraded!\n"));
780                         SAFE_FREE(old_style_key);
781                         SAFE_FREE(*dn);
782                         return False;                   
783                 }
784                 if (!secrets_delete(old_style_key)) {
785                         DEBUG(0,("fetch_ldap_pw: old ldap secret could not be deleted!\n"));
786                 }
787
788                 SAFE_FREE(old_style_key);
789
790                 *pw = smb_xstrdup(old_style_pw);                
791         }
792         
793         return True;
794 }
795
796 /**
797  * Get trusted domains info from secrets.tdb.
798  **/ 
799
800 NTSTATUS secrets_trusted_domains(TALLOC_CTX *mem_ctx, uint32 *num_domains,
801                                  struct trustdom_info ***domains)
802 {
803         TDB_LIST_NODE *keys, *k;
804         char *pattern;
805         TALLOC_CTX *tmp_ctx;
806
807         if (!(tmp_ctx = talloc_new(mem_ctx))) {
808                 return NT_STATUS_NO_MEMORY;
809         }
810
811         if (!secrets_init()) return NT_STATUS_ACCESS_DENIED;
812         
813         /* generate searching pattern */
814         pattern = talloc_asprintf(tmp_ctx, "%s/*", SECRETS_DOMTRUST_ACCT_PASS);
815         if (pattern == NULL) {
816                 DEBUG(0, ("secrets_trusted_domains: talloc_asprintf() "
817                           "failed!\n"));
818                 TALLOC_FREE(tmp_ctx);
819                 return NT_STATUS_NO_MEMORY;
820         }
821
822         *num_domains = 0;
823
824         /*
825          * Make sure that a talloc context for the trustdom_info structs
826          * exists
827          */
828
829         if (!(*domains = TALLOC_ARRAY(mem_ctx, struct trustdom_info *, 1))) {
830                 TALLOC_FREE(tmp_ctx);
831                 return NT_STATUS_NO_MEMORY;
832         }
833
834         /* fetching trusted domains' data and collecting them in a list */
835         keys = tdb_search_keys(tdb, pattern);
836
837         /* searching for keys in secrets db -- way to go ... */
838         for (k = keys; k; k = k->next) {
839                 char *packed_pass;
840                 size_t size = 0, packed_size = 0;
841                 struct trusted_dom_pass pass;
842                 char *secrets_key;
843                 struct trustdom_info *dom_info;
844                 
845                 /* important: ensure null-termination of the key string */
846                 secrets_key = talloc_strndup(tmp_ctx,
847                                              k->node_key.dptr,
848                                              k->node_key.dsize);
849                 if (!secrets_key) {
850                         DEBUG(0, ("strndup failed!\n"));
851                         tdb_search_list_free(keys);
852                         TALLOC_FREE(tmp_ctx);
853                         return NT_STATUS_NO_MEMORY;
854                 }
855
856                 packed_pass = secrets_fetch(secrets_key, &size);
857                 packed_size = tdb_trusted_dom_pass_unpack(packed_pass, size,
858                                                           &pass);
859                 /* packed representation isn't needed anymore */
860                 SAFE_FREE(packed_pass);
861                 
862                 if (size != packed_size) {
863                         DEBUG(2, ("Secrets record %s is invalid!\n",
864                                   secrets_key));
865                         continue;
866                 }
867
868                 if (pass.domain_sid.num_auths != 4) {
869                         DEBUG(0, ("SID %s is not a domain sid, has %d "
870                                   "auths instead of 4\n",
871                                   sid_string_static(&pass.domain_sid),
872                                   pass.domain_sid.num_auths));
873                         continue;
874                 }
875
876                 if (!(dom_info = TALLOC_P(*domains, struct trustdom_info))) {
877                         DEBUG(0, ("talloc failed\n"));
878                         tdb_search_list_free(keys);
879                         TALLOC_FREE(tmp_ctx);
880                         return NT_STATUS_NO_MEMORY;
881                 }
882
883                 if (pull_ucs2_talloc(dom_info, &dom_info->name,
884                                      pass.uni_name) == (size_t)-1) {
885                         DEBUG(2, ("pull_ucs2_talloc failed\n"));
886                         tdb_search_list_free(keys);
887                         TALLOC_FREE(tmp_ctx);
888                         return NT_STATUS_NO_MEMORY;
889                 }
890
891                 sid_copy(&dom_info->sid, &pass.domain_sid);
892
893                 ADD_TO_ARRAY(*domains, struct trustdom_info *, dom_info,
894                              domains, num_domains);
895
896                 if (*domains == NULL) {
897                         tdb_search_list_free(keys);
898                         TALLOC_FREE(tmp_ctx);
899                         return NT_STATUS_NO_MEMORY;
900                 }
901         }
902         
903         DEBUG(5, ("secrets_get_trusted_domains: got %d domains\n",
904                   *num_domains));
905
906         /* free the results of searching the keys */
907         tdb_search_list_free(keys);
908         TALLOC_FREE(tmp_ctx);
909
910         return NT_STATUS_OK;
911 }
912
913 /*******************************************************************************
914  Lock the secrets tdb based on a string - this is used as a primitive form of mutex
915  between smbd instances.
916 *******************************************************************************/
917
918 BOOL secrets_named_mutex(const char *name, unsigned int timeout)
919 {
920         int ret = 0;
921
922         if (!secrets_init())
923                 return False;
924
925         ret = tdb_lock_bystring_with_timeout(tdb, name, timeout);
926         if (ret == 0)
927                 DEBUG(10,("secrets_named_mutex: got mutex for %s\n", name ));
928
929         return (ret == 0);
930 }
931
932 /*******************************************************************************
933  Unlock a named mutex.
934 *******************************************************************************/
935
936 void secrets_named_mutex_release(const char *name)
937 {
938         tdb_unlock_bystring(tdb, name);
939         DEBUG(10,("secrets_named_mutex: released mutex for %s\n", name ));
940 }
941
942 /*******************************************************************************
943  Store a complete AFS keyfile into secrets.tdb.
944 *******************************************************************************/
945
946 BOOL secrets_store_afs_keyfile(const char *cell, const struct afs_keyfile *keyfile)
947 {
948         fstring key;
949
950         if ((cell == NULL) || (keyfile == NULL))
951                 return False;
952
953         if (ntohl(keyfile->nkeys) > SECRETS_AFS_MAXKEYS)
954                 return False;
955
956         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_AFS_KEYFILE, cell);
957         return secrets_store(key, keyfile, sizeof(struct afs_keyfile));
958 }
959
960 /*******************************************************************************
961  Fetch the current (highest) AFS key from secrets.tdb
962 *******************************************************************************/
963 BOOL secrets_fetch_afs_key(const char *cell, struct afs_key *result)
964 {
965         fstring key;
966         struct afs_keyfile *keyfile;
967         size_t size = 0;
968         uint32 i;
969
970         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_AFS_KEYFILE, cell);
971
972         keyfile = (struct afs_keyfile *)secrets_fetch(key, &size);
973
974         if (keyfile == NULL)
975                 return False;
976
977         if (size != sizeof(struct afs_keyfile)) {
978                 SAFE_FREE(keyfile);
979                 return False;
980         }
981
982         i = ntohl(keyfile->nkeys);
983
984         if (i > SECRETS_AFS_MAXKEYS) {
985                 SAFE_FREE(keyfile);
986                 return False;
987         }
988
989         *result = keyfile->entry[i-1];
990
991         result->kvno = ntohl(result->kvno);
992
993         return True;
994 }
995
996 /******************************************************************************
997   When kerberos is not available, choose between anonymous or
998   authenticated connections.  
999
1000   We need to use an authenticated connection if DCs have the
1001   RestrictAnonymous registry entry set > 0, or the "Additional
1002   restrictions for anonymous connections" set in the win2k Local
1003   Security Policy.
1004
1005   Caller to free() result in domain, username, password
1006 *******************************************************************************/
1007 void secrets_fetch_ipc_userpass(char **username, char **domain, char **password)
1008 {
1009         *username = secrets_fetch(SECRETS_AUTH_USER, NULL);
1010         *domain = secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
1011         *password = secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
1012         
1013         if (*username && **username) {
1014
1015                 if (!*domain || !**domain)
1016                         *domain = smb_xstrdup(lp_workgroup());
1017                 
1018                 if (!*password || !**password)
1019                         *password = smb_xstrdup("");
1020
1021                 DEBUG(3, ("IPC$ connections done by user %s\\%s\n", 
1022                           *domain, *username));
1023
1024         } else {
1025                 DEBUG(3, ("IPC$ connections done anonymously\n"));
1026                 *username = smb_xstrdup("");
1027                 *domain = smb_xstrdup("");
1028                 *password = smb_xstrdup("");
1029         }
1030 }
1031
1032 /******************************************************************************
1033  Open or create the schannel session store tdb.
1034 *******************************************************************************/
1035
1036 static TDB_CONTEXT *open_schannel_session_store(TALLOC_CTX *mem_ctx)
1037 {
1038         TDB_DATA vers;
1039         uint32 ver;
1040         TDB_CONTEXT *tdb_sc = NULL;
1041         char *fname = talloc_asprintf(mem_ctx, "%s/schannel_store.tdb", lp_private_dir());
1042
1043         if (!fname) {
1044                 return NULL;
1045         }
1046
1047         tdb_sc = tdb_open_log(fname, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
1048
1049         if (!tdb_sc) {
1050                 DEBUG(0,("open_schannel_session_store: Failed to open %s\n", fname));
1051                 TALLOC_FREE(fname);
1052                 return NULL;
1053         }
1054
1055         vers = tdb_fetch_bystring(tdb_sc, "SCHANNEL_STORE_VERSION");
1056         if (vers.dptr == NULL) {
1057                 /* First opener, no version. */
1058                 SIVAL(&ver,0,1);
1059                 vers.dptr = (char *)&ver;
1060                 vers.dsize = 4;
1061                 tdb_store_bystring(tdb_sc, "SCHANNEL_STORE_VERSION", vers, TDB_REPLACE);
1062                 vers.dptr = NULL;
1063         } else if (vers.dsize == 4) {
1064                 ver = IVAL(vers.dptr,0);
1065                 if (ver != 1) {
1066                         tdb_close(tdb_sc);
1067                         tdb_sc = NULL;
1068                         DEBUG(0,("open_schannel_session_store: wrong version number %d in %s\n",
1069                                 (int)ver, fname ));
1070                 }
1071         } else {
1072                 tdb_close(tdb_sc);
1073                 tdb_sc = NULL;
1074                 DEBUG(0,("open_schannel_session_store: wrong version number size %d in %s\n",
1075                         (int)vers.dsize, fname ));
1076         }
1077
1078         SAFE_FREE(vers.dptr);
1079         TALLOC_FREE(fname);
1080
1081         return tdb_sc;
1082 }
1083
1084 /******************************************************************************
1085  Store the schannel state after an AUTH2 call.
1086  Note we must be root here.
1087 *******************************************************************************/
1088
1089 BOOL secrets_store_schannel_session_info(TALLOC_CTX *mem_ctx,
1090                                 const char *remote_machine,
1091                                 const struct dcinfo *pdc)
1092 {
1093         TDB_CONTEXT *tdb_sc = NULL;
1094         TDB_DATA value;
1095         BOOL ret;
1096         char *keystr = talloc_asprintf(mem_ctx, "%s/%s", SECRETS_SCHANNEL_STATE,
1097                                 remote_machine);
1098         if (!keystr) {
1099                 return False;
1100         }
1101
1102         strupper_m(keystr);
1103
1104         /* Work out how large the record is. */
1105         value.dsize = tdb_pack(NULL, 0, "dBBBBBfff",
1106                                 pdc->sequence,
1107                                 8, pdc->seed_chal.data,
1108                                 8, pdc->clnt_chal.data,
1109                                 8, pdc->srv_chal.data,
1110                                 16, pdc->sess_key,
1111                                 16, pdc->mach_pw,
1112                                 pdc->mach_acct,
1113                                 pdc->remote_machine,
1114                                 pdc->domain);
1115
1116         value.dptr = TALLOC(mem_ctx, value.dsize);
1117         if (!value.dptr) {
1118                 TALLOC_FREE(keystr);
1119                 return False;
1120         }
1121
1122         value.dsize = tdb_pack(value.dptr, value.dsize, "dBBBBBfff",
1123                                 pdc->sequence,
1124                                 8, pdc->seed_chal.data,
1125                                 8, pdc->clnt_chal.data,
1126                                 8, pdc->srv_chal.data,
1127                                 16, pdc->sess_key,
1128                                 16, pdc->mach_pw,
1129                                 pdc->mach_acct,
1130                                 pdc->remote_machine,
1131                                 pdc->domain);
1132
1133         tdb_sc = open_schannel_session_store(mem_ctx);
1134         if (!tdb_sc) {
1135                 TALLOC_FREE(keystr);
1136                 TALLOC_FREE(value.dptr);
1137                 return False;
1138         }
1139
1140         ret = (tdb_store_bystring(tdb_sc, keystr, value, TDB_REPLACE) == 0 ? True : False);
1141
1142         DEBUG(3,("secrets_store_schannel_session_info: stored schannel info with key %s\n",
1143                 keystr ));
1144
1145         tdb_close(tdb_sc);
1146         TALLOC_FREE(keystr);
1147         TALLOC_FREE(value.dptr);
1148         return ret;
1149 }
1150
1151 /******************************************************************************
1152  Restore the schannel state on a client reconnect.
1153  Note we must be root here.
1154 *******************************************************************************/
1155
1156 BOOL secrets_restore_schannel_session_info(TALLOC_CTX *mem_ctx,
1157                                 const char *remote_machine,
1158                                 struct dcinfo **ppdc)
1159 {
1160         TDB_CONTEXT *tdb_sc = NULL;
1161         TDB_DATA value;
1162         unsigned char *pseed_chal = NULL;
1163         unsigned char *pclnt_chal = NULL;
1164         unsigned char *psrv_chal = NULL;
1165         unsigned char *psess_key = NULL;
1166         unsigned char *pmach_pw = NULL;
1167         uint32 l1, l2, l3, l4, l5;
1168         int ret;
1169         struct dcinfo *pdc = NULL;
1170         char *keystr = talloc_asprintf(mem_ctx, "%s/%s", SECRETS_SCHANNEL_STATE,
1171                                 remote_machine);
1172
1173         *ppdc = NULL;
1174
1175         if (!keystr) {
1176                 return False;
1177         }
1178
1179         strupper_m(keystr);
1180
1181         tdb_sc = open_schannel_session_store(mem_ctx);
1182         if (!tdb_sc) {
1183                 TALLOC_FREE(keystr);
1184                 return False;
1185         }
1186
1187         value = tdb_fetch_bystring(tdb_sc, keystr);
1188         if (!value.dptr) {
1189                 DEBUG(0,("secrets_restore_schannel_session_info: Failed to find entry with key %s\n",
1190                         keystr ));
1191                 tdb_close(tdb_sc);
1192                 return False;
1193         }
1194
1195         pdc = TALLOC_ZERO_P(mem_ctx, struct dcinfo);
1196
1197         /* Retrieve the record. */
1198         ret = tdb_unpack(value.dptr, value.dsize, "dBBBBBfff",
1199                                 &pdc->sequence,
1200                                 &l1, &pseed_chal,
1201                                 &l2, &pclnt_chal,
1202                                 &l3, &psrv_chal,
1203                                 &l4, &psess_key,
1204                                 &l5, &pmach_pw,
1205                                 &pdc->mach_acct,
1206                                 &pdc->remote_machine,
1207                                 &pdc->domain);
1208
1209         if (ret == -1 || l1 != 8 || l2 != 8 || l3 != 8 || l4 != 16 || l5 != 16) {
1210                 /* Bad record - delete it. */
1211                 tdb_delete_bystring(tdb_sc, keystr);
1212                 tdb_close(tdb_sc);
1213                 TALLOC_FREE(keystr);
1214                 TALLOC_FREE(pdc);
1215                 SAFE_FREE(pseed_chal);
1216                 SAFE_FREE(pclnt_chal);
1217                 SAFE_FREE(psrv_chal);
1218                 SAFE_FREE(psess_key);
1219                 SAFE_FREE(pmach_pw);
1220                 SAFE_FREE(value.dptr);
1221                 return False;
1222         }
1223
1224         tdb_close(tdb_sc);
1225
1226         memcpy(pdc->seed_chal.data, pseed_chal, 8);
1227         memcpy(pdc->clnt_chal.data, pclnt_chal, 8);
1228         memcpy(pdc->srv_chal.data, psrv_chal, 8);
1229         memcpy(pdc->sess_key, psess_key, 16);
1230         memcpy(pdc->mach_pw, pmach_pw, 16);
1231
1232         /* We know these are true so didn't bother to store them. */
1233         pdc->challenge_sent = True;
1234         pdc->authenticated = True;
1235
1236         DEBUG(3,("secrets_restore_schannel_session_info: restored schannel info key %s\n",
1237                 keystr ));
1238
1239         SAFE_FREE(pseed_chal);
1240         SAFE_FREE(pclnt_chal);
1241         SAFE_FREE(psrv_chal);
1242         SAFE_FREE(psess_key);
1243         SAFE_FREE(pmach_pw);
1244
1245         TALLOC_FREE(keystr);
1246         SAFE_FREE(value.dptr);
1247
1248         *ppdc = pdc;
1249
1250         return True;
1251 }