first public release of samba4 code
[samba.git] / source4 / 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) == 0;
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, GUID *guid)
145 {
146         fstring key;
147
148         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_GUID, domain);
149         strupper(key);
150         return secrets_store(key, guid, sizeof(GUID));
151 }
152
153 BOOL secrets_fetch_domain_guid(const char *domain, GUID *guid)
154 {
155         GUID *dyn_guid;
156         fstring key;
157         size_t size;
158         GUID new_guid;
159
160         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_GUID, domain);
161         strupper(key);
162         dyn_guid = (GUID *)secrets_fetch(key, &size);
163
164         DEBUG(6,("key is %s, size is %d\n", key, (int)size));
165
166         if ((NULL == dyn_guid) && (ROLE_DOMAIN_PDC == lp_server_role())) {
167                 uuid_generate_random(&new_guid);
168                 if (!secrets_store_domain_guid(domain, &new_guid))
169                         return False;
170                 dyn_guid = (GUID *)secrets_fetch(key, &size);
171                 if (dyn_guid == NULL)
172                         return False;
173         }
174
175         if (size != sizeof(GUID))
176         { 
177                 SAFE_FREE(dyn_guid);
178                 return False;
179         }
180
181         *guid = *dyn_guid;
182         SAFE_FREE(dyn_guid);
183         return True;
184 }
185
186 /**
187  * Form a key for fetching the machine trust account password
188  *
189  * @param domain domain name
190  *
191  * @return stored password's key
192  **/
193 const char *trust_keystr(const char *domain)
194 {
195         static fstring keystr;
196
197         slprintf(keystr,sizeof(keystr)-1,"%s/%s", 
198                  SECRETS_MACHINE_ACCT_PASS, domain);
199         strupper(keystr);
200
201         return keystr;
202 }
203
204 /**
205  * Form a key for fetching a trusted domain password
206  *
207  * @param domain trusted domain name
208  *
209  * @return stored password's key
210  **/
211 char *trustdom_keystr(const char *domain)
212 {
213         static char* keystr;
214
215         asprintf(&keystr, "%s/%s", SECRETS_DOMTRUST_ACCT_PASS, domain);
216         strupper(keystr);
217                 
218         return keystr;
219 }
220
221 /************************************************************************
222  Lock the trust password entry.
223 ************************************************************************/
224
225 BOOL secrets_lock_trust_account_password(const char *domain, BOOL dolock)
226 {
227         if (!tdb)
228                 return False;
229
230         if (dolock)
231                 return (tdb_lock_bystring(tdb, trust_keystr(domain),0) == 0);
232         else
233                 tdb_unlock_bystring(tdb, trust_keystr(domain));
234         return True;
235 }
236
237 /************************************************************************
238  Routine to get the trust account password for a domain.
239  The user of this function must have locked the trust password file using
240  the above call.
241 ************************************************************************/
242
243 BOOL secrets_fetch_trust_account_password(const char *domain, uint8 ret_pwd[16],
244                                           time_t *pass_last_set_time)
245 {
246         struct machine_acct_pass *pass;
247         char *plaintext;
248         size_t size;
249
250         plaintext = secrets_fetch_machine_password();
251         if (plaintext) {
252                 /* we have an ADS password - use that */
253                 DEBUG(4,("Using ADS machine password\n"));
254                 E_md4hash(plaintext, ret_pwd);
255                 SAFE_FREE(plaintext);
256                 pass_last_set_time = 0;
257                 return True;
258         }
259
260         if (!(pass = secrets_fetch(trust_keystr(domain), &size))) {
261                 DEBUG(5, ("secrets_fetch failed!\n"));
262                 return False;
263         }
264         
265         if (size != sizeof(*pass)) {
266                 DEBUG(0, ("secrets were of incorrect size!\n"));
267                 return False;
268         }
269
270         if (pass_last_set_time) *pass_last_set_time = pass->mod_time;
271         memcpy(ret_pwd, pass->hash, 16);
272         SAFE_FREE(pass);
273         return True;
274 }
275
276 /************************************************************************
277  Routine to get account password to trusted domain
278 ************************************************************************/
279
280 BOOL secrets_fetch_trusted_domain_password(const char *domain, char** pwd,
281                                            DOM_SID *sid, time_t *pass_last_set_time)
282 {
283         struct trusted_dom_pass *pass;
284         size_t size;
285
286         /* fetching trusted domain password structure */
287         if (!(pass = secrets_fetch(trustdom_keystr(domain), &size))) {
288                 DEBUG(5, ("secrets_fetch failed!\n"));
289                 return False;
290         }
291
292         if (size != sizeof(*pass)) {
293                 DEBUG(0, ("secrets were of incorrect size!\n"));
294                 return False;
295         }
296
297         /* the trust's password */      
298         if (pwd) {
299                 *pwd = strdup(pass->pass);
300                 if (!*pwd) {
301                         return False;
302                 }
303         }
304
305         /* last change time */
306         if (pass_last_set_time) *pass_last_set_time = pass->mod_time;
307
308         /* domain sid */
309         memcpy(&sid, &(pass->domain_sid), sizeof(sid));
310         
311         SAFE_FREE(pass);
312         
313         return True;
314 }
315
316 /************************************************************************
317  Routine to set the trust account password for a domain.
318 ************************************************************************/
319
320 BOOL secrets_store_trust_account_password(const char *domain, uint8 new_pwd[16])
321 {
322         struct machine_acct_pass pass;
323
324         pass.mod_time = time(NULL);
325         memcpy(pass.hash, new_pwd, 16);
326
327         return secrets_store(trust_keystr(domain), (void *)&pass, sizeof(pass));
328 }
329
330 /**
331  * Routine to set the password for trusted domain
332  *
333  * @param domain remote domain name
334  * @param pwd plain text password of trust relationship
335  * @param sid remote domain sid
336  *
337  * @return true if succeeded
338  **/
339
340 BOOL secrets_store_trusted_domain_password(const char* domain, smb_ucs2_t *uni_dom_name,
341                                            size_t uni_name_len, const char* pwd,
342                                            DOM_SID sid)
343 {
344         struct trusted_dom_pass pass;
345         ZERO_STRUCT(pass);
346
347         /* unicode domain name and its length */
348         if (!uni_dom_name)
349                 return False;
350                 
351         strncpy_w(pass.uni_name, uni_dom_name, sizeof(pass.uni_name) - 1);
352         pass.uni_name_len = uni_name_len;
353
354         /* last change time */
355         pass.mod_time = time(NULL);
356
357         /* password of the trust */
358         pass.pass_len = strlen(pwd);
359         fstrcpy(pass.pass, pwd);
360
361         /* domain sid */
362         memcpy(&(pass.domain_sid), &sid, sizeof(sid));
363
364         return secrets_store(trustdom_keystr(domain), (void *)&pass, sizeof(pass));
365 }
366
367 /************************************************************************
368  Routine to set the plaintext machine account password for a realm
369 the password is assumed to be a null terminated ascii string
370 ************************************************************************/
371
372 BOOL secrets_store_machine_password(const char *pass)
373 {
374         char *key;
375         BOOL ret;
376         asprintf(&key, "%s/%s", SECRETS_MACHINE_PASSWORD, lp_workgroup());
377         strupper(key);
378         ret = secrets_store(key, pass, strlen(pass)+1);
379         free(key);
380         return ret;
381 }
382
383
384 /************************************************************************
385  Routine to fetch the plaintext machine account password for a realm
386 the password is assumed to be a null terminated ascii string
387 ************************************************************************/
388 char *secrets_fetch_machine_password(void)
389 {
390         char *key;
391         char *ret;
392         asprintf(&key, "%s/%s", SECRETS_MACHINE_PASSWORD, lp_workgroup());
393         strupper(key);
394         ret = (char *)secrets_fetch(key, NULL);
395         free(key);
396         return ret;
397 }
398
399
400
401 /************************************************************************
402  Routine to delete the machine trust account password file for a domain.
403 ************************************************************************/
404
405 BOOL trust_password_delete(const char *domain)
406 {
407         return secrets_delete(trust_keystr(domain));
408 }
409
410 /************************************************************************
411  Routine to delete the password for trusted domain
412 ************************************************************************/
413
414 BOOL trusted_domain_password_delete(const char *domain)
415 {
416         return secrets_delete(trustdom_keystr(domain));
417 }
418
419
420 BOOL secrets_store_ldap_pw(const char* dn, char* pw)
421 {
422         char *key = NULL;
423         BOOL ret;
424         
425         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, dn) < 0) {
426                 DEBUG(0, ("secrets_store_ldap_pw: asprintf failed!\n"));
427                 return False;
428         }
429                 
430         ret = secrets_store(key, pw, strlen(pw)+1);
431         
432         SAFE_FREE(key);
433         return ret;
434 }
435
436
437 /**
438  * Get trusted domains info from secrets.tdb.
439  *
440  * The linked list is allocated on the supplied talloc context, caller gets to destroy
441  * when done.
442  *
443  * @param ctx Allocation context
444  * @param enum_ctx Starting index, eg. we can start fetching at third
445  *        or sixth trusted domain entry. Zero is the first index.
446  *        Value it is set to is the enum context for the next enumeration.
447  * @param num_domains Number of domain entries to fetch at one call
448  * @param domains Pointer to array of trusted domain structs to be filled up
449  *
450  * @return nt status code of rpc response
451  **/ 
452
453 NTSTATUS secrets_get_trusted_domains(TALLOC_CTX* ctx, int* enum_ctx, unsigned int max_num_domains, int *num_domains, TRUSTDOM ***domains)
454 {
455         TDB_LIST_NODE *keys, *k;
456         TRUSTDOM *dom = NULL;
457         char *pattern;
458         unsigned int start_idx;
459         uint32 idx = 0;
460         size_t size;
461         fstring dom_name;
462         struct trusted_dom_pass *pass;
463         NTSTATUS status;
464
465         if (!secrets_init()) return NT_STATUS_ACCESS_DENIED;
466
467         *num_domains = 0;
468         start_idx = *enum_ctx;
469
470         /* generate searching pattern */
471         if (!(pattern = talloc_asprintf(ctx, "%s/*", SECRETS_DOMTRUST_ACCT_PASS))) {
472                 DEBUG(0, ("secrets_get_trusted_domains: talloc_asprintf() failed!\n"));
473                 return NT_STATUS_NO_MEMORY;
474         }
475
476         DEBUG(5, ("secrets_get_trusted_domains: looking for %d domains, starting at index %d\n", 
477                   max_num_domains, *enum_ctx));
478
479         *domains = talloc_zero(ctx, sizeof(**domains)*max_num_domains);
480
481         /* fetching trusted domains' data and collecting them in a list */
482         keys = tdb_search_keys(tdb, pattern);
483
484         /* 
485          * if there's no keys returned ie. no trusted domain,
486          * return "no more entries" code
487          */
488         status = NT_STATUS_NO_MORE_ENTRIES;
489
490         /* searching for keys in sectrets db -- way to go ... */
491         for (k = keys; k; k = k->next) {
492                 char *secrets_key;
493                 
494                 /* important: ensure null-termination of the key string */
495                 secrets_key = strndup(k->node_key.dptr, k->node_key.dsize);
496                 if (!secrets_key) {
497                         DEBUG(0, ("strndup failed!\n"));
498                         return NT_STATUS_NO_MEMORY;
499                 }
500                                 
501                 pass = secrets_fetch(secrets_key, &size);
502                 
503                 if (size != sizeof(*pass)) {
504                         DEBUG(2, ("Secrets record %s is invalid!\n", secrets_key));
505                         SAFE_FREE(pass);
506                         continue;
507                 }
508                 
509                 pull_ucs2_fstring(dom_name, pass->uni_name);
510                 DEBUG(18, ("Fetched secret record num %d.\nDomain name: %s, SID: %s\n",
511                            idx, dom_name, sid_string_talloc(ctx, &pass->domain_sid)));
512
513                 SAFE_FREE(secrets_key);
514
515                 if (idx >= start_idx && idx < start_idx + max_num_domains) {
516                         dom = talloc_zero(ctx, sizeof(*dom));
517                         if (!dom) {
518                                 /* free returned tdb record */
519                                 SAFE_FREE(pass);
520                                 
521                                 return NT_STATUS_NO_MEMORY;
522                         }
523                         
524                         /* copy domain sid */
525                         SMB_ASSERT(sizeof(dom->sid) == sizeof(pass->domain_sid));
526                         memcpy(&(dom->sid), &(pass->domain_sid), sizeof(dom->sid));
527                         
528                         /* copy unicode domain name */
529                         dom->name = talloc_strdup_w(ctx, pass->uni_name);
530                         
531                         (*domains)[idx - start_idx] = dom;
532                         
533                         DEBUG(18, ("Secret record is in required range.\n \
534                                    start_idx = %d, max_num_domains = %d. Added to returned array.\n",
535                                    start_idx, max_num_domains));
536
537                         *enum_ctx = idx + 1;
538                         (*num_domains)++;
539                 
540                         /* set proper status code to return */
541                         if (k->next) {
542                                 /* there are yet some entries to enumerate */
543                                 status = STATUS_MORE_ENTRIES;
544                         } else {
545                                 /* this is the last entry in the whole enumeration */
546                                 status = NT_STATUS_OK;
547                         }
548                 } else {
549                         DEBUG(18, ("Secret is outside the required range.\n \
550                                    start_idx = %d, max_num_domains = %d. Not added to returned array\n",
551                                    start_idx, max_num_domains));
552                 }
553                 
554                 idx++;
555                 
556                 /* free returned tdb record */
557                 SAFE_FREE(pass);
558         }
559         
560         DEBUG(5, ("secrets_get_trusted_domains: got %d domains\n", *num_domains));
561
562         /* free the results of searching the keys */
563         tdb_search_list_free(keys);
564
565         return status;
566 }
567
568 /*******************************************************************************
569  Lock the secrets tdb based on a string - this is used as a primitive form of mutex
570  between smbd instances.
571 *******************************************************************************/
572
573 BOOL secrets_named_mutex(const char *name, unsigned int timeout, size_t *p_ref_count)
574 {
575         size_t ref_count = *p_ref_count;
576         int ret = 0;
577
578         if (!message_init())
579                 return False;
580
581         if (ref_count == 0) {
582                 ret = tdb_lock_bystring(tdb, name, timeout);
583                 if (ret == 0)
584                         DEBUG(10,("secrets_named_mutex: got mutex for %s\n", name ));
585         }
586
587         if (ret == 0) {
588                 *p_ref_count = ++ref_count;
589                 DEBUG(10,("secrets_named_mutex: ref_count for mutex %s = %u\n", name, (unsigned int)ref_count ));
590         }
591         return (ret == 0);
592 }
593
594 /*******************************************************************************
595  Unlock a named mutex.
596 *******************************************************************************/
597
598 void secrets_named_mutex_release(const char *name, size_t *p_ref_count)
599 {
600         size_t ref_count = *p_ref_count;
601
602         SMB_ASSERT(ref_count != 0);
603
604         if (ref_count == 1) {
605                 tdb_unlock_bystring(tdb, name);
606                 DEBUG(10,("secrets_named_mutex: released mutex for %s\n", name ));
607         }
608
609         *p_ref_count = --ref_count;
610         DEBUG(10,("secrets_named_mutex_release: ref_count for mutex %s = %u\n", name, (unsigned int)ref_count ));
611 }
612