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