a fairly large commit!
[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    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
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 /* open up the secrets database */
33 BOOL secrets_init(void)
34 {
35         pstring fname;
36
37         if (tdb)
38                 return True;
39
40         pstrcpy(fname, lp_private_dir());
41         pstrcat(fname,"/secrets.tdb");
42
43         tdb = tdb_open_log(fname, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
44
45         if (!tdb) {
46                 DEBUG(0,("Failed to open %s\n", fname));
47                 return False;
48         }
49         return True;
50 }
51
52 /* read a entry from the secrets database - the caller must free the result
53    if size is non-null then the size of the entry is put in there
54  */
55 void *secrets_fetch(const char *key, size_t *size)
56 {
57         TDB_DATA kbuf, dbuf;
58         secrets_init();
59         if (!tdb)
60                 return NULL;
61         kbuf.dptr = strdup(key);
62         kbuf.dsize = strlen(key);
63         dbuf = tdb_fetch(tdb, kbuf);
64         if (size)
65                 *size = dbuf.dsize;
66         free(kbuf.dptr);
67         return dbuf.dptr;
68 }
69
70 /* store a secrets entry 
71  */
72 BOOL secrets_store(const char *key, const void *data, size_t size)
73 {
74         TDB_DATA kbuf, dbuf;
75         int ret;
76
77         secrets_init();
78         if (!tdb)
79                 return False;
80         kbuf.dptr = strdup(key);
81         kbuf.dsize = strlen(key);
82         dbuf.dptr = memdup(data, size);
83         dbuf.dsize = size;
84
85         ret = tdb_store(tdb, kbuf, dbuf, TDB_REPLACE);
86
87         free(kbuf.dptr);
88         free(dbuf.dptr);
89
90         return ret == 0;
91 }
92
93
94 /* delete a secets database entry
95  */
96 BOOL secrets_delete(const char *key)
97 {
98         TDB_DATA kbuf;
99         int ret;
100
101         secrets_init();
102         if (!tdb)
103                 return False;
104         kbuf.dptr = strdup(key);
105         kbuf.dsize = strlen(key);
106         ret = tdb_delete(tdb, kbuf);
107         free(kbuf.dptr);
108         return ret == 0;
109 }
110
111 BOOL secrets_store_domain_sid(const char *domain, const DOM_SID *sid)
112 {
113         fstring key;
114
115         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_SID, domain);
116         strupper(key);
117         return secrets_store(key, sid, sizeof(DOM_SID));
118 }
119
120 BOOL secrets_fetch_domain_sid(const char *domain, DOM_SID *sid)
121 {
122         DOM_SID *dyn_sid;
123         fstring key;
124         size_t size;
125
126         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_SID, domain);
127         strupper(key);
128         dyn_sid = (DOM_SID *)secrets_fetch(key, &size);
129
130         if (dyn_sid == NULL)
131                 return False;
132
133         if (size != sizeof(DOM_SID))
134         { 
135                 SAFE_FREE(dyn_sid);
136                 return False;
137         }
138
139         *sid = *dyn_sid;
140         SAFE_FREE(dyn_sid);
141         return True;
142 }
143
144 BOOL secrets_store_domain_guid(const char *domain, struct GUID *guid)
145 {
146         const char *s;
147         fstring key;
148         TALLOC_CTX *mem_ctx;
149         BOOL ret;
150         
151         mem_ctx = talloc_init("secrets_store_domain_guid");
152         if (!mem_ctx) {
153                 return False;
154         }
155
156         s = GUID_string(mem_ctx, guid);
157         if (!s) {
158                 talloc_destroy(mem_ctx);
159                 return False;
160         }
161
162
163         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_GUID, domain);
164         strupper(key);
165         ret = secrets_store(key, s, strlen(s)+1);
166         
167         talloc_destroy(mem_ctx);
168         return ret;
169 }
170
171 BOOL secrets_fetch_domain_guid(const char *domain, struct GUID *guid)
172 {
173         char *dyn_guid;
174         fstring key;
175         size_t size;
176         struct GUID new_guid;
177         NTSTATUS status;
178
179         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_GUID, domain);
180         strupper(key);
181         dyn_guid = secrets_fetch(key, &size);
182
183         DEBUG(6,("key is %s, size is %d\n", key, (int)size));
184
185         if ((NULL == dyn_guid) && (ROLE_DOMAIN_PDC == lp_server_role())) {
186                 uuid_generate_random(&new_guid);
187                 if (!secrets_store_domain_guid(domain, &new_guid))
188                         return False;
189                 dyn_guid = secrets_fetch(key, &size);
190                 if (dyn_guid == NULL)
191                         return False;
192         }
193
194         status = GUID_from_string(dyn_guid, guid);
195         SAFE_FREE(dyn_guid);
196
197         if (!NT_STATUS_IS_OK(status)) {
198                 return False;
199         }
200
201         return True;
202 }
203
204 /**
205  * Form a key for fetching the machine trust account password
206  *
207  * @param domain domain name
208  *
209  * @return stored password's key
210  **/
211 const char *trust_keystr(const char *domain)
212 {
213         static fstring keystr;
214
215         slprintf(keystr,sizeof(keystr)-1,"%s/%s", 
216                  SECRETS_MACHINE_ACCT_PASS, domain);
217         strupper(keystr);
218
219         return keystr;
220 }
221
222 /**
223  * Form a key for fetching a trusted domain password
224  *
225  * @param domain trusted domain name
226  *
227  * @return stored password's key
228  **/
229 char *trustdom_keystr(const char *domain)
230 {
231         static char* keystr;
232
233         asprintf(&keystr, "%s/%s", SECRETS_DOMTRUST_ACCT_PASS, domain);
234         strupper(keystr);
235                 
236         return keystr;
237 }
238
239 /************************************************************************
240  Lock the trust password entry.
241 ************************************************************************/
242
243 BOOL secrets_lock_trust_account_password(const char *domain, BOOL dolock)
244 {
245         if (!tdb)
246                 return False;
247
248         if (dolock)
249                 return (tdb_lock_bystring(tdb, trust_keystr(domain),0) == 0);
250         else
251                 tdb_unlock_bystring(tdb, trust_keystr(domain));
252         return True;
253 }
254
255 /************************************************************************
256  Routine to get the trust account password for a domain.
257  The user of this function must have locked the trust password file using
258  the above call.
259 ************************************************************************/
260
261 BOOL secrets_fetch_trust_account_password(const char *domain, uint8 ret_pwd[16],
262                                           time_t *pass_last_set_time)
263 {
264         struct machine_acct_pass *pass;
265         char *plaintext;
266         size_t size;
267
268         plaintext = secrets_fetch_machine_password();
269         if (plaintext) {
270                 /* we have an ADS password - use that */
271                 DEBUG(4,("Using ADS machine password\n"));
272                 E_md4hash(plaintext, ret_pwd);
273                 SAFE_FREE(plaintext);
274                 pass_last_set_time = 0;
275                 return True;
276         }
277
278         if (!(pass = secrets_fetch(trust_keystr(domain), &size))) {
279                 DEBUG(5, ("secrets_fetch failed!\n"));
280                 return False;
281         }
282         
283         if (size != sizeof(*pass)) {
284                 DEBUG(0, ("secrets were of incorrect size!\n"));
285                 return False;
286         }
287
288         if (pass_last_set_time) *pass_last_set_time = pass->mod_time;
289         memcpy(ret_pwd, pass->hash, 16);
290         SAFE_FREE(pass);
291         return True;
292 }
293
294 /************************************************************************
295  Routine to get account password to trusted domain
296 ************************************************************************/
297
298 BOOL secrets_fetch_trusted_domain_password(const char *domain, char** pwd,
299                                            DOM_SID *sid, time_t *pass_last_set_time)
300 {
301         struct trusted_dom_pass *pass;
302         size_t size;
303
304         /* fetching trusted domain password structure */
305         if (!(pass = secrets_fetch(trustdom_keystr(domain), &size))) {
306                 DEBUG(5, ("secrets_fetch failed!\n"));
307                 return False;
308         }
309
310         if (size != sizeof(*pass)) {
311                 DEBUG(0, ("secrets were of incorrect size!\n"));
312                 return False;
313         }
314
315         /* the trust's password */      
316         if (pwd) {
317                 *pwd = strdup(pass->pass);
318                 if (!*pwd) {
319                         return False;
320                 }
321         }
322
323         /* last change time */
324         if (pass_last_set_time) *pass_last_set_time = pass->mod_time;
325
326         /* domain sid */
327         memcpy(&sid, &(pass->domain_sid), sizeof(sid));
328         
329         SAFE_FREE(pass);
330         
331         return True;
332 }
333
334 /************************************************************************
335  Routine to set the trust account password for a domain.
336 ************************************************************************/
337
338 BOOL secrets_store_trust_account_password(const char *domain, uint8 new_pwd[16])
339 {
340         struct machine_acct_pass pass;
341
342         pass.mod_time = time(NULL);
343         memcpy(pass.hash, new_pwd, 16);
344
345         return secrets_store(trust_keystr(domain), (void *)&pass, sizeof(pass));
346 }
347
348 /**
349  * Routine to set the password for trusted domain
350  *
351  * @param domain remote domain name
352  * @param pwd plain text password of trust relationship
353  * @param sid remote domain sid
354  *
355  * @return true if succeeded
356  **/
357
358 BOOL secrets_store_trusted_domain_password(const char* domain, smb_ucs2_t *uni_dom_name,
359                                            size_t uni_name_len, const char* pwd,
360                                            DOM_SID sid)
361 {
362         struct trusted_dom_pass pass;
363         ZERO_STRUCT(pass);
364
365         /* unicode domain name and its length */
366         if (!uni_dom_name)
367                 return False;
368                 
369         strncpy_w(pass.uni_name, uni_dom_name, sizeof(pass.uni_name) - 1);
370         pass.uni_name_len = uni_name_len;
371
372         /* last change time */
373         pass.mod_time = time(NULL);
374
375         /* password of the trust */
376         pass.pass_len = strlen(pwd);
377         fstrcpy(pass.pass, pwd);
378
379         /* domain sid */
380         memcpy(&(pass.domain_sid), &sid, sizeof(sid));
381
382         return secrets_store(trustdom_keystr(domain), (void *)&pass, sizeof(pass));
383 }
384
385 /************************************************************************
386  Routine to set the plaintext machine account password for a realm
387 the password is assumed to be a null terminated ascii string
388 ************************************************************************/
389
390 BOOL secrets_store_machine_password(const char *pass)
391 {
392         char *key;
393         BOOL ret;
394         asprintf(&key, "%s/%s", SECRETS_MACHINE_PASSWORD, lp_workgroup());
395         strupper(key);
396         ret = secrets_store(key, pass, strlen(pass)+1);
397         free(key);
398         return ret;
399 }
400
401
402 /************************************************************************
403  Routine to fetch the plaintext machine account password for a realm
404 the password is assumed to be a null terminated ascii string
405 ************************************************************************/
406 char *secrets_fetch_machine_password(void)
407 {
408         char *key;
409         char *ret;
410         asprintf(&key, "%s/%s", SECRETS_MACHINE_PASSWORD, lp_workgroup());
411         strupper(key);
412         ret = (char *)secrets_fetch(key, NULL);
413         free(key);
414         return ret;
415 }
416
417
418
419 /************************************************************************
420  Routine to delete the machine trust account password file for a domain.
421 ************************************************************************/
422
423 BOOL trust_password_delete(const char *domain)
424 {
425         return secrets_delete(trust_keystr(domain));
426 }
427
428 /************************************************************************
429  Routine to delete the password for trusted domain
430 ************************************************************************/
431
432 BOOL trusted_domain_password_delete(const char *domain)
433 {
434         return secrets_delete(trustdom_keystr(domain));
435 }
436
437
438 BOOL secrets_store_ldap_pw(const char* dn, char* pw)
439 {
440         char *key = NULL;
441         BOOL ret;
442         
443         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, dn) < 0) {
444                 DEBUG(0, ("secrets_store_ldap_pw: asprintf failed!\n"));
445                 return False;
446         }
447                 
448         ret = secrets_store(key, pw, strlen(pw)+1);
449         
450         SAFE_FREE(key);
451         return ret;
452 }
453
454
455 /**
456  * Get trusted domains info from secrets.tdb.
457  *
458  * The linked list is allocated on the supplied talloc context, caller gets to destroy
459  * when done.
460  *
461  * @param ctx Allocation context
462  * @param enum_ctx Starting index, eg. we can start fetching at third
463  *        or sixth trusted domain entry. Zero is the first index.
464  *        Value it is set to is the enum context for the next enumeration.
465  * @param num_domains Number of domain entries to fetch at one call
466  * @param domains Pointer to array of trusted domain structs to be filled up
467  *
468  * @return nt status code of rpc response
469  **/ 
470
471 NTSTATUS secrets_get_trusted_domains(TALLOC_CTX* ctx, int* enum_ctx, unsigned int max_num_domains, int *num_domains, TRUSTDOM ***domains)
472 {
473         TDB_LIST_NODE *keys, *k;
474         TRUSTDOM *dom = NULL;
475         char *pattern;
476         unsigned int start_idx;
477         uint32 idx = 0;
478         size_t size;
479         fstring dom_name;
480         struct trusted_dom_pass *pass;
481         NTSTATUS status;
482
483         if (!secrets_init()) return NT_STATUS_ACCESS_DENIED;
484
485         *num_domains = 0;
486         start_idx = *enum_ctx;
487
488         /* generate searching pattern */
489         if (!(pattern = talloc_asprintf(ctx, "%s/*", SECRETS_DOMTRUST_ACCT_PASS))) {
490                 DEBUG(0, ("secrets_get_trusted_domains: talloc_asprintf() failed!\n"));
491                 return NT_STATUS_NO_MEMORY;
492         }
493
494         DEBUG(5, ("secrets_get_trusted_domains: looking for %d domains, starting at index %d\n", 
495                   max_num_domains, *enum_ctx));
496
497         *domains = talloc_zero(ctx, sizeof(**domains)*max_num_domains);
498
499         /* fetching trusted domains' data and collecting them in a list */
500         keys = tdb_search_keys(tdb, pattern);
501
502         /* 
503          * if there's no keys returned ie. no trusted domain,
504          * return "no more entries" code
505          */
506         status = NT_STATUS_NO_MORE_ENTRIES;
507
508         /* searching for keys in sectrets db -- way to go ... */
509         for (k = keys; k; k = k->next) {
510                 char *secrets_key;
511                 
512                 /* important: ensure null-termination of the key string */
513                 secrets_key = strndup(k->node_key.dptr, k->node_key.dsize);
514                 if (!secrets_key) {
515                         DEBUG(0, ("strndup failed!\n"));
516                         return NT_STATUS_NO_MEMORY;
517                 }
518                                 
519                 pass = secrets_fetch(secrets_key, &size);
520                 
521                 if (size != sizeof(*pass)) {
522                         DEBUG(2, ("Secrets record %s is invalid!\n", secrets_key));
523                         SAFE_FREE(pass);
524                         continue;
525                 }
526                 
527                 pull_ucs2_fstring(dom_name, pass->uni_name);
528                 DEBUG(18, ("Fetched secret record num %d.\nDomain name: %s, SID: %s\n",
529                            idx, dom_name, sid_string_talloc(ctx, &pass->domain_sid)));
530
531                 SAFE_FREE(secrets_key);
532
533                 if (idx >= start_idx && idx < start_idx + max_num_domains) {
534                         dom = talloc_zero(ctx, sizeof(*dom));
535                         if (!dom) {
536                                 /* free returned tdb record */
537                                 SAFE_FREE(pass);
538                                 
539                                 return NT_STATUS_NO_MEMORY;
540                         }
541                         
542                         /* copy domain sid */
543                         SMB_ASSERT(sizeof(dom->sid) == sizeof(pass->domain_sid));
544                         memcpy(&(dom->sid), &(pass->domain_sid), sizeof(dom->sid));
545                         
546                         /* copy unicode domain name */
547                         dom->name = talloc_strdup_w(ctx, pass->uni_name);
548                         
549                         (*domains)[idx - start_idx] = dom;
550                         
551                         DEBUG(18, ("Secret record is in required range.\n \
552                                    start_idx = %d, max_num_domains = %d. Added to returned array.\n",
553                                    start_idx, max_num_domains));
554
555                         *enum_ctx = idx + 1;
556                         (*num_domains)++;
557                 
558                         /* set proper status code to return */
559                         if (k->next) {
560                                 /* there are yet some entries to enumerate */
561                                 status = STATUS_MORE_ENTRIES;
562                         } else {
563                                 /* this is the last entry in the whole enumeration */
564                                 status = NT_STATUS_OK;
565                         }
566                 } else {
567                         DEBUG(18, ("Secret is outside the required range.\n \
568                                    start_idx = %d, max_num_domains = %d. Not added to returned array\n",
569                                    start_idx, max_num_domains));
570                 }
571                 
572                 idx++;
573                 
574                 /* free returned tdb record */
575                 SAFE_FREE(pass);
576         }
577         
578         DEBUG(5, ("secrets_get_trusted_domains: got %d domains\n", *num_domains));
579
580         /* free the results of searching the keys */
581         tdb_search_list_free(keys);
582
583         return status;
584 }
585
586 /*******************************************************************************
587  Lock the secrets tdb based on a string - this is used as a primitive form of mutex
588  between smbd instances.
589 *******************************************************************************/
590
591 BOOL secrets_named_mutex(const char *name, unsigned int timeout, size_t *p_ref_count)
592 {
593         size_t ref_count = *p_ref_count;
594         int ret = 0;
595
596         if (!message_init())
597                 return False;
598
599         if (ref_count == 0) {
600                 ret = tdb_lock_bystring(tdb, name, timeout);
601                 if (ret == 0)
602                         DEBUG(10,("secrets_named_mutex: got mutex for %s\n", name ));
603         }
604
605         if (ret == 0) {
606                 *p_ref_count = ++ref_count;
607                 DEBUG(10,("secrets_named_mutex: ref_count for mutex %s = %u\n", name, (unsigned int)ref_count ));
608         }
609         return (ret == 0);
610 }
611
612 /*******************************************************************************
613  Unlock a named mutex.
614 *******************************************************************************/
615
616 void secrets_named_mutex_release(const char *name, size_t *p_ref_count)
617 {
618         size_t ref_count = *p_ref_count;
619
620         SMB_ASSERT(ref_count != 0);
621
622         if (ref_count == 1) {
623                 tdb_unlock_bystring(tdb, name);
624                 DEBUG(10,("secrets_named_mutex: released mutex for %s\n", name ));
625         }
626
627         *p_ref_count = --ref_count;
628         DEBUG(10,("secrets_named_mutex_release: ref_count for mutex %s = %u\n", name, (unsigned int)ref_count ));
629 }
630