This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.(This used to...
[sfrench/samba-autobuild/.git] / source3 / 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, 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(char *domain, 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(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(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(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, guid is at %x, size is %d\n", key, dyn_guid, 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  Routine to get the machine trust account password for a domain.
210 ************************************************************************/
211 BOOL secrets_fetch_trust_account_password(char *domain, uint8 ret_pwd[16],
212                                           time_t *pass_last_set_time)
213 {
214         struct machine_acct_pass *pass;
215         char *plaintext;
216         size_t size;
217
218         plaintext = secrets_fetch_machine_password();
219         if (plaintext) {
220                 /* we have an ADS password - use that */
221                 DEBUG(4,("Using ADS machine password\n"));
222                 E_md4hash(plaintext, ret_pwd);
223                 SAFE_FREE(plaintext);
224                 return True;
225         }
226
227         if (!(pass = secrets_fetch(trust_keystr(domain), &size))) {
228                 DEBUG(5, ("secrets_fetch failed!\n"));
229                 return False;
230         }
231         
232         if (size != sizeof(*pass)) {
233                 DEBUG(0, ("secrets were of incorrect size!\n"));
234                 return False;
235         }
236
237         if (pass_last_set_time) *pass_last_set_time = pass->mod_time;
238         memcpy(ret_pwd, pass->hash, 16);
239         SAFE_FREE(pass);
240         return True;
241 }
242
243 /************************************************************************
244  Routine to get account password to trusted domain
245 ************************************************************************/
246 BOOL secrets_fetch_trusted_domain_password(char *domain, char** pwd,
247                                            DOM_SID *sid, time_t *pass_last_set_time)
248 {
249         struct trusted_dom_pass *pass;
250         size_t size;
251
252         /* fetching trusted domain password structure */
253         if (!(pass = secrets_fetch(trustdom_keystr(domain), &size))) {
254                 DEBUG(5, ("secrets_fetch failed!\n"));
255                 return False;
256         }
257
258         if (size != sizeof(*pass)) {
259                 DEBUG(0, ("secrets were of incorrect size!\n"));
260                 return False;
261         }
262
263         /* the trust's password */      
264         if (pwd) {
265                 *pwd = strdup(pass->pass);
266                 if (!*pwd) {
267                         return False;
268                 }
269         }
270
271         /* last change time */
272         if (pass_last_set_time) *pass_last_set_time = pass->mod_time;
273
274         /* domain sid */
275         memcpy(&sid, &(pass->domain_sid), sizeof(sid));
276         
277         SAFE_FREE(pass);
278         
279         return True;
280 }
281
282 /************************************************************************
283  Routine to set the trust account password for a domain.
284 ************************************************************************/
285 BOOL secrets_store_trust_account_password(char *domain, uint8 new_pwd[16])
286 {
287         struct machine_acct_pass pass;
288
289         pass.mod_time = time(NULL);
290         memcpy(pass.hash, new_pwd, 16);
291
292         return secrets_store(trust_keystr(domain), (void *)&pass, sizeof(pass));
293 }
294
295 /**
296  * Routine to set the password for trusted domain
297  *
298  * @param domain remote domain name
299  * @param pwd plain text password of trust relationship
300  * @param sid remote domain sid
301  *
302  * @return true if succeeded
303  **/
304
305 BOOL secrets_store_trusted_domain_password(char* domain, smb_ucs2_t *uni_dom_name,
306                                            size_t uni_name_len, char* pwd,
307                                            DOM_SID sid)
308 {
309         struct trusted_dom_pass pass;
310         ZERO_STRUCT(pass);
311
312         /* unicode domain name and its length */
313         if (!uni_dom_name)
314                 return False;
315                 
316         strncpy_w(pass.uni_name, uni_dom_name, sizeof(pass.uni_name) - 1);
317         pass.uni_name_len = uni_name_len;
318
319         /* last change time */
320         pass.mod_time = time(NULL);
321
322         /* password of the trust */
323         pass.pass_len = strlen(pwd);
324         fstrcpy(pass.pass, pwd);
325
326         /* domain sid */
327         memcpy(&(pass.domain_sid), &sid, sizeof(sid));
328
329         return secrets_store(trustdom_keystr(domain), (void *)&pass, sizeof(pass));
330 }
331
332 /************************************************************************
333  Routine to set the plaintext machine account password for a realm
334 the password is assumed to be a null terminated ascii string
335 ************************************************************************/
336 BOOL secrets_store_machine_password(char *pass)
337 {
338         char *key;
339         BOOL ret;
340         asprintf(&key, "%s/%s", SECRETS_MACHINE_PASSWORD, lp_workgroup());
341         strupper(key);
342         ret = secrets_store(key, pass, strlen(pass)+1);
343         free(key);
344         return ret;
345 }
346
347
348 /************************************************************************
349  Routine to fetch the plaintext machine account password for a realm
350 the password is assumed to be a null terminated ascii string
351 ************************************************************************/
352 char *secrets_fetch_machine_password(void)
353 {
354         char *key;
355         char *ret;
356         asprintf(&key, "%s/%s", SECRETS_MACHINE_PASSWORD, lp_workgroup());
357         strupper(key);
358         ret = (char *)secrets_fetch(key, NULL);
359         free(key);
360         return ret;
361 }
362
363
364
365 /************************************************************************
366  Routine to delete the machine trust account password file for a domain.
367 ************************************************************************/
368
369 BOOL trust_password_delete(const char *domain)
370 {
371         return secrets_delete(trust_keystr(domain));
372 }
373
374 /************************************************************************
375  Routine to delete the password for trusted domain
376 ************************************************************************/
377 BOOL trusted_domain_password_delete(const char *domain)
378 {
379         return secrets_delete(trustdom_keystr(domain));
380 }
381
382
383 /*******************************************************************
384  Reset the 'done' variables so after a client process is created
385  from a fork call these calls will be re-done. This should be
386  expanded if more variables need reseting.
387  ******************************************************************/
388
389 void reset_globals_after_fork(void)
390 {
391         unsigned char dummy;
392
393         secrets_init();
394
395         /*
396          * Increment the global seed value to ensure every smbd starts
397          * with a new random seed.
398          */
399
400         if (tdb) {
401                 uint32 initial_val = sys_getpid();
402                 tdb_change_int32_atomic(tdb, "INFO/random_seed", (int *)&initial_val, 1);
403                 set_rand_reseed_data((unsigned char *)&initial_val, sizeof(initial_val));
404         }
405
406         /*
407          * Re-seed the random crypto generator, so all smbd's
408          * started from the same parent won't generate the same
409          * sequence.
410          */
411         generate_random_buffer( &dummy, 1, True);
412 }
413
414 BOOL secrets_store_ldap_pw(const char* dn, char* pw)
415 {
416         char *key = NULL;
417         BOOL ret;
418         
419         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, dn) < 0) {
420                 DEBUG(0, ("secrets_store_ldap_pw: asprintf failed!\n"));
421                 return False;
422         }
423                 
424         ret = secrets_store(key, pw, strlen(pw)+1);
425         
426         SAFE_FREE(key);
427         return ret;
428 }
429
430
431 /**
432  * Get trusted domains info from secrets.tdb.
433  *
434  * The linked list is allocated on the supplied talloc context, caller gets to destroy
435  * when done.
436  *
437  * @param ctx Allocation context
438  * @param enum_ctx Starting index, eg. we can start fetching at third
439  *        or sixth trusted domain entry. Zero is the first index.
440  *        Value it is set to is the enum context for the next enumeration.
441  * @param num_domains Number of domain entries to fetch at one call
442  * @param domains Pointer to array of trusted domain structs to be filled up
443  *
444  * @return nt status code of rpc response
445  **/ 
446
447 NTSTATUS secrets_get_trusted_domains(TALLOC_CTX* ctx, int* enum_ctx, int max_num_domains, int *num_domains, TRUSTDOM ***domains)
448 {
449         TDB_LIST_NODE *keys, *k;
450         TRUSTDOM *dom = NULL;
451         char *pattern;
452         int start_idx;
453         uint32 idx = 0;
454         size_t size;
455         fstring dom_name;
456         struct trusted_dom_pass *pass;
457         NTSTATUS status;
458
459         if (!secrets_init()) return NT_STATUS_ACCESS_DENIED;
460
461         *num_domains = 0;
462         start_idx = *enum_ctx;
463
464         /* generate searching pattern */
465         if (!(pattern = talloc_asprintf(ctx, "%s/*", SECRETS_DOMTRUST_ACCT_PASS))) {
466                 DEBUG(0, ("secrets_get_trusted_domains: talloc_asprintf() failed!\n"));
467                 return NT_STATUS_NO_MEMORY;
468         }
469
470         DEBUG(5, ("secrets_get_trusted_domains: looking for %d domains, starting at index %d\n", 
471                   max_num_domains, *enum_ctx));
472
473         *domains = talloc_zero(ctx, sizeof(**domains)*max_num_domains);
474
475         /* fetching trusted domains' data and collecting them in a list */
476         keys = tdb_search_keys(tdb, pattern);
477
478         /* 
479          * if there's no keys returned ie. no trusted domain,
480          * return "no more entries" code
481          */
482         status = NT_STATUS_NO_MORE_ENTRIES;
483
484         /* searching for keys in sectrets db -- way to go ... */
485         for (k = keys; k; k = k->next) {
486                 char *secrets_key;
487                 
488                 /* important: ensure null-termination of the key string */
489                 secrets_key = strndup(k->node_key.dptr, k->node_key.dsize);
490                 if (!secrets_key) {
491                         DEBUG(0, ("strndup failed!\n"));
492                         return NT_STATUS_NO_MEMORY;
493                 }
494                                 
495                 pass = secrets_fetch(secrets_key, &size);
496                 
497                 if (size != sizeof(*pass)) {
498                         DEBUG(2, ("Secrets record %s is invalid!\n", secrets_key));
499                         SAFE_FREE(pass);
500                         continue;
501                 }
502                 
503                 pull_ucs2_fstring(dom_name, pass->uni_name);
504                 DEBUG(18, ("Fetched secret record num %d.\nDomain name: %s, SID: %s\n",
505                            idx, dom_name, sid_string_static(&pass->domain_sid)));
506
507                 SAFE_FREE(secrets_key);
508
509                 if (idx >= start_idx && idx < start_idx + max_num_domains) {
510                         dom = talloc_zero(ctx, sizeof(*dom));
511                         if (!dom) {
512                                 /* free returned tdb record */
513                                 SAFE_FREE(pass);
514                                 
515                                 return NT_STATUS_NO_MEMORY;
516                         }
517                         
518                         /* copy domain sid */
519                         SMB_ASSERT(sizeof(dom->sid) == sizeof(pass->domain_sid));
520                         memcpy(&(dom->sid), &(pass->domain_sid), sizeof(dom->sid));
521                         
522                         /* copy unicode domain name */
523                         dom->name = talloc_strdup_w(ctx, pass->uni_name);
524                         
525                         (*domains)[idx - start_idx] = dom;
526                         
527                         DEBUG(18, ("Secret record is in required range.\n \
528                                    start_idx = %d, max_num_domains = %d. Added to returned array.\n",
529                                    start_idx, max_num_domains));
530
531                         *enum_ctx = idx + 1;
532                         (*num_domains)++;
533                 
534                         /* set proper status code to return */
535                         if (k->next) {
536                                 /* there are yet some entries to enumerate */
537                                 status = STATUS_MORE_ENTRIES;
538                         } else {
539                                 /* this is the last entry in the whole enumeration */
540                                 status = NT_STATUS_OK;
541                         }
542                 } else {
543                         DEBUG(18, ("Secret is outside the required range.\n \
544                                    start_idx = %d, max_num_domains = %d. Not added to returned array\n",
545                                    start_idx, max_num_domains));
546                 }
547                 
548                 idx++;
549                 
550                 /* free returned tdb record */
551                 SAFE_FREE(pass);
552         }
553         
554         DEBUG(5, ("secrets_get_trusted_domains: got %d domains\n", *num_domains));
555
556         /* free the results of searching the keys */
557         tdb_search_list_free(keys);
558
559         return status;
560 }
561