This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.
[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 = key;
62         kbuf.dsize = strlen(key);
63         dbuf = tdb_fetch(tdb, kbuf);
64         if (size)
65                 *size = dbuf.dsize;
66         return dbuf.dptr;
67 }
68
69 /* store a secrets entry 
70  */
71 BOOL secrets_store(const char *key, const void *data, size_t size)
72 {
73         TDB_DATA kbuf, dbuf;
74         secrets_init();
75         if (!tdb)
76                 return False;
77         kbuf.dptr = key;
78         kbuf.dsize = strlen(key);
79         dbuf.dptr = data;
80         dbuf.dsize = size;
81         return tdb_store(tdb, kbuf, dbuf, TDB_REPLACE) == 0;
82 }
83
84
85 /* delete a secets database entry
86  */
87 BOOL secrets_delete(const char *key)
88 {
89         TDB_DATA kbuf;
90         secrets_init();
91         if (!tdb)
92                 return False;
93         kbuf.dptr = key;
94         kbuf.dsize = strlen(key);
95         return tdb_delete(tdb, kbuf) == 0;
96 }
97
98 BOOL secrets_store_domain_sid(const char *domain, const DOM_SID *sid)
99 {
100         fstring key;
101
102         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_SID, domain);
103         strupper(key);
104         return secrets_store(key, sid, sizeof(DOM_SID));
105 }
106
107 BOOL secrets_fetch_domain_sid(const char *domain, DOM_SID *sid)
108 {
109         DOM_SID *dyn_sid;
110         fstring key;
111         size_t size;
112
113         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_SID, domain);
114         strupper(key);
115         dyn_sid = (DOM_SID *)secrets_fetch(key, &size);
116
117         if (dyn_sid == NULL)
118                 return False;
119
120         if (size != sizeof(DOM_SID))
121         { 
122                 SAFE_FREE(dyn_sid);
123                 return False;
124         }
125
126         *sid = *dyn_sid;
127         SAFE_FREE(dyn_sid);
128         return True;
129 }
130
131 BOOL secrets_store_domain_guid(const char *domain, GUID *guid)
132 {
133         fstring key;
134
135         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_GUID, domain);
136         strupper(key);
137         return secrets_store(key, guid, sizeof(GUID));
138 }
139
140 BOOL secrets_fetch_domain_guid(const char *domain, GUID *guid)
141 {
142         GUID *dyn_guid;
143         fstring key;
144         size_t size;
145         GUID new_guid;
146
147         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_DOMAIN_GUID, domain);
148         strupper(key);
149         dyn_guid = (GUID *)secrets_fetch(key, &size);
150
151         DEBUG(6,("key is %s, size is %d\n", key, (int)size));
152
153         if ((NULL == dyn_guid) && (ROLE_DOMAIN_PDC == lp_server_role())) {
154                 uuid_generate_random(&new_guid);
155                 if (!secrets_store_domain_guid(domain, &new_guid))
156                         return False;
157                 dyn_guid = (GUID *)secrets_fetch(key, &size);
158                 if (dyn_guid == NULL)
159                         return False;
160         }
161
162         if (size != sizeof(GUID))
163         { 
164                 SAFE_FREE(dyn_guid);
165                 return False;
166         }
167
168         *guid = *dyn_guid;
169         SAFE_FREE(dyn_guid);
170         return True;
171 }
172
173 /**
174  * Form a key for fetching the machine trust account password
175  *
176  * @param domain domain name
177  *
178  * @return stored password's key
179  **/
180 const char *trust_keystr(const char *domain)
181 {
182         static fstring keystr;
183
184         slprintf(keystr,sizeof(keystr)-1,"%s/%s", 
185                  SECRETS_MACHINE_ACCT_PASS, domain);
186         strupper(keystr);
187
188         return keystr;
189 }
190
191 /**
192  * Form a key for fetching a trusted domain password
193  *
194  * @param domain trusted domain name
195  *
196  * @return stored password's key
197  **/
198 char *trustdom_keystr(const char *domain)
199 {
200         static char* keystr;
201
202         asprintf(&keystr, "%s/%s", SECRETS_DOMTRUST_ACCT_PASS, domain);
203         strupper(keystr);
204                 
205         return keystr;
206 }
207
208 /************************************************************************
209  Lock the trust password entry.
210 ************************************************************************/
211
212 BOOL secrets_lock_trust_account_password(const char *domain, BOOL dolock)
213 {
214         if (!tdb)
215                 return False;
216
217         if (dolock)
218                 return (tdb_lock_bystring(tdb, trust_keystr(domain),0) == 0);
219         else
220                 tdb_unlock_bystring(tdb, trust_keystr(domain));
221         return True;
222 }
223
224 /************************************************************************
225  Routine to get the trust account password for a domain.
226  The user of this function must have locked the trust password file using
227  the above call.
228 ************************************************************************/
229
230 BOOL secrets_fetch_trust_account_password(const char *domain, uint8 ret_pwd[16],
231                                           time_t *pass_last_set_time)
232 {
233         struct machine_acct_pass *pass;
234         char *plaintext;
235         size_t size;
236
237         plaintext = secrets_fetch_machine_password();
238         if (plaintext) {
239                 /* we have an ADS password - use that */
240                 DEBUG(4,("Using ADS machine password\n"));
241                 E_md4hash(plaintext, ret_pwd);
242                 SAFE_FREE(plaintext);
243                 pass_last_set_time = 0;
244                 return True;
245         }
246
247         if (!(pass = secrets_fetch(trust_keystr(domain), &size))) {
248                 DEBUG(5, ("secrets_fetch failed!\n"));
249                 return False;
250         }
251         
252         if (size != sizeof(*pass)) {
253                 DEBUG(0, ("secrets were of incorrect size!\n"));
254                 return False;
255         }
256
257         if (pass_last_set_time) *pass_last_set_time = pass->mod_time;
258         memcpy(ret_pwd, pass->hash, 16);
259         SAFE_FREE(pass);
260         return True;
261 }
262
263 /************************************************************************
264  Routine to get account password to trusted domain
265 ************************************************************************/
266
267 BOOL secrets_fetch_trusted_domain_password(const char *domain, char** pwd,
268                                            DOM_SID *sid, time_t *pass_last_set_time)
269 {
270         struct trusted_dom_pass *pass;
271         size_t size;
272
273         /* fetching trusted domain password structure */
274         if (!(pass = secrets_fetch(trustdom_keystr(domain), &size))) {
275                 DEBUG(5, ("secrets_fetch failed!\n"));
276                 return False;
277         }
278
279         if (size != sizeof(*pass)) {
280                 DEBUG(0, ("secrets were of incorrect size!\n"));
281                 return False;
282         }
283
284         /* the trust's password */      
285         if (pwd) {
286                 *pwd = strdup(pass->pass);
287                 if (!*pwd) {
288                         return False;
289                 }
290         }
291
292         /* last change time */
293         if (pass_last_set_time) *pass_last_set_time = pass->mod_time;
294
295         /* domain sid */
296         memcpy(&sid, &(pass->domain_sid), sizeof(sid));
297         
298         SAFE_FREE(pass);
299         
300         return True;
301 }
302
303 /************************************************************************
304  Routine to set the trust account password for a domain.
305 ************************************************************************/
306
307 BOOL secrets_store_trust_account_password(const char *domain, uint8 new_pwd[16])
308 {
309         struct machine_acct_pass pass;
310
311         pass.mod_time = time(NULL);
312         memcpy(pass.hash, new_pwd, 16);
313
314         return secrets_store(trust_keystr(domain), (void *)&pass, sizeof(pass));
315 }
316
317 /**
318  * Routine to set the password for trusted domain
319  *
320  * @param domain remote domain name
321  * @param pwd plain text password of trust relationship
322  * @param sid remote domain sid
323  *
324  * @return true if succeeded
325  **/
326
327 BOOL secrets_store_trusted_domain_password(const char* domain, smb_ucs2_t *uni_dom_name,
328                                            size_t uni_name_len, const char* pwd,
329                                            DOM_SID sid)
330 {
331         struct trusted_dom_pass pass;
332         ZERO_STRUCT(pass);
333
334         /* unicode domain name and its length */
335         if (!uni_dom_name)
336                 return False;
337                 
338         strncpy_w(pass.uni_name, uni_dom_name, sizeof(pass.uni_name) - 1);
339         pass.uni_name_len = uni_name_len;
340
341         /* last change time */
342         pass.mod_time = time(NULL);
343
344         /* password of the trust */
345         pass.pass_len = strlen(pwd);
346         fstrcpy(pass.pass, pwd);
347
348         /* domain sid */
349         memcpy(&(pass.domain_sid), &sid, sizeof(sid));
350
351         return secrets_store(trustdom_keystr(domain), (void *)&pass, sizeof(pass));
352 }
353
354 /************************************************************************
355  Routine to set the plaintext machine account password for a realm
356 the password is assumed to be a null terminated ascii string
357 ************************************************************************/
358
359 BOOL secrets_store_machine_password(const char *pass)
360 {
361         char *key;
362         BOOL ret;
363         asprintf(&key, "%s/%s", SECRETS_MACHINE_PASSWORD, lp_workgroup());
364         strupper(key);
365         ret = secrets_store(key, pass, strlen(pass)+1);
366         free(key);
367         return ret;
368 }
369
370
371 /************************************************************************
372  Routine to fetch the plaintext machine account password for a realm
373 the password is assumed to be a null terminated ascii string
374 ************************************************************************/
375 char *secrets_fetch_machine_password(void)
376 {
377         char *key;
378         char *ret;
379         asprintf(&key, "%s/%s", SECRETS_MACHINE_PASSWORD, lp_workgroup());
380         strupper(key);
381         ret = (char *)secrets_fetch(key, NULL);
382         free(key);
383         return ret;
384 }
385
386
387
388 /************************************************************************
389  Routine to delete the machine trust account password file for a domain.
390 ************************************************************************/
391
392 BOOL trust_password_delete(const char *domain)
393 {
394         return secrets_delete(trust_keystr(domain));
395 }
396
397 /************************************************************************
398  Routine to delete the password for trusted domain
399 ************************************************************************/
400
401 BOOL trusted_domain_password_delete(const char *domain)
402 {
403         return secrets_delete(trustdom_keystr(domain));
404 }
405
406
407 /*******************************************************************
408  Reset the 'done' variables so after a client process is created
409  from a fork call these calls will be re-done. This should be
410  expanded if more variables need reseting.
411  ******************************************************************/
412
413 void reset_globals_after_fork(void)
414 {
415         unsigned char dummy;
416
417         secrets_init();
418
419         /*
420          * Increment the global seed value to ensure every smbd starts
421          * with a new random seed.
422          */
423
424         if (tdb) {
425                 uint32 initial_val = sys_getpid();
426                 tdb_change_int32_atomic(tdb, "INFO/random_seed", (int *)&initial_val, 1);
427                 set_rand_reseed_data((unsigned char *)&initial_val, sizeof(initial_val));
428         }
429
430         /*
431          * Re-seed the random crypto generator, so all smbd's
432          * started from the same parent won't generate the same
433          * sequence.
434          */
435         generate_random_buffer( &dummy, 1, True);
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_static(&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)
592 {
593         int ret = 0;
594
595         if (!message_init())
596                 return False;
597
598                 ret = tdb_lock_bystring(tdb, name, timeout);
599                 if (ret == 0)
600                         DEBUG(10,("secrets_named_mutex: got mutex for %s\n", name ));
601
602         return (ret == 0);
603 }
604
605 /*******************************************************************************
606  Unlock a named mutex.
607 *******************************************************************************/
608
609 void secrets_named_mutex_release(const char *name)
610 {
611                 tdb_unlock_bystring(tdb, name);
612                 DEBUG(10,("secrets_named_mutex: released mutex for %s\n", name ));
613 }
614
615 /*********************************************************
616  Check to see if we must talk to the PDC to avoid sam 
617  sync delays
618  ********************************************************/
619  
620 BOOL must_use_pdc( const char *domain )
621 {
622         time_t  now = time(NULL);
623         time_t  last_change_time;
624         unsigned char   passwd[16];   
625         
626         if ( !secrets_fetch_trust_account_password(domain, passwd, &last_change_time) )
627                 return False;
628                 
629         /*
630          * If the time the machine password has changed
631          * was less than about 15 minutes then we need to contact
632          * the PDC only, as we cannot be sure domain replication
633          * has yet taken place. Bug found by Gerald (way to go
634          * Gerald !). JRA.
635          */
636          
637         if ( now - last_change_time < SAM_SYNC_WINDOW )
638                 return True;
639                 
640         return False;
641
642 }
643