Store the type of 'sec channel' that we establish to the DC. If we are a
[samba.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, 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 default secure channel type for trust accounts
226 ************************************************************************/
227
228 uint32 get_default_sec_channel(void) 
229 {
230         if (lp_server_role() == ROLE_DOMAIN_BDC || 
231             lp_server_role() == ROLE_DOMAIN_PDC) {
232                 return SEC_CHAN_BDC;
233         } else {
234                 return SEC_CHAN_WKSTA;
235         }
236 }
237
238 /************************************************************************
239  Routine to get the trust account password for a domain.
240  The user of this function must have locked the trust password file using
241  the above call.
242 ************************************************************************/
243
244 BOOL secrets_fetch_trust_account_password(const char *domain, uint8 ret_pwd[16],
245                                           time_t *pass_last_set_time,
246                                           uint32 *channel)
247 {
248         struct machine_acct_pass *pass;
249         char *plaintext;
250         size_t size;
251
252         plaintext = secrets_fetch_machine_password(domain, pass_last_set_time, 
253                                                    channel);
254         if (plaintext) {
255                 /* we have an ADS password - use that */
256                 DEBUG(4,("Using ADS machine password\n"));
257                 E_md4hash(plaintext, ret_pwd);
258                 SAFE_FREE(plaintext);
259                 return True;
260         }
261
262         if (!(pass = secrets_fetch(trust_keystr(domain), &size))) {
263                 DEBUG(5, ("secrets_fetch failed!\n"));
264                 return False;
265         }
266         
267         if (size != sizeof(*pass)) {
268                 DEBUG(0, ("secrets were of incorrect size!\n"));
269                 return False;
270         }
271
272         if (pass_last_set_time) *pass_last_set_time = pass->mod_time;
273         memcpy(ret_pwd, pass->hash, 16);
274         SAFE_FREE(pass);
275
276         if (channel) 
277                 *channel = get_default_sec_channel();
278
279         return True;
280 }
281
282 /************************************************************************
283  Routine to get account password to trusted domain
284 ************************************************************************/
285
286 BOOL secrets_fetch_trusted_domain_password(const char *domain, char** pwd,
287                                            DOM_SID *sid, time_t *pass_last_set_time)
288 {
289         struct trusted_dom_pass pass;
290         size_t size;
291         
292         /* unpacking structures */
293         char* pass_buf;
294         int pass_len = 0;
295
296         ZERO_STRUCT(pass);
297
298         /* fetching trusted domain password structure */
299         if (!(pass_buf = secrets_fetch(trustdom_keystr(domain), &size))) {
300                 DEBUG(5, ("secrets_fetch failed!\n"));
301                 return False;
302         }
303
304         /* unpack trusted domain password */
305         pass_len = tdb_trusted_dom_pass_unpack(pass_buf, size, &pass);
306         if (pass_len != size) {
307                 DEBUG(5, ("Invalid secrets size. Unpacked data doesn't match trusted_dom_pass structure.\n"));
308                 return False;
309         }
310                         
311         /* the trust's password */      
312         if (pwd) {
313                 *pwd = strdup(pass.pass);
314                 if (!*pwd) {
315                         return False;
316                 }
317         }
318
319         /* last change time */
320         if (pass_last_set_time) *pass_last_set_time = pass.mod_time;
321
322         /* domain sid */
323         sid_copy(sid, &pass.domain_sid);
324                 
325         return True;
326 }
327
328 /************************************************************************
329  Routine to set the trust account password for a domain.
330 ************************************************************************/
331
332 BOOL secrets_store_trust_account_password(const char *domain, uint8 new_pwd[16])
333 {
334         struct machine_acct_pass pass;
335
336         pass.mod_time = time(NULL);
337         memcpy(pass.hash, new_pwd, 16);
338
339         return secrets_store(trust_keystr(domain), (void *)&pass, sizeof(pass));
340 }
341
342 /**
343  * Routine to store the password for trusted domain
344  *
345  * @param domain remote domain name
346  * @param pwd plain text password of trust relationship
347  * @param sid remote domain sid
348  *
349  * @return true if succeeded
350  **/
351
352 BOOL secrets_store_trusted_domain_password(const char* domain, smb_ucs2_t *uni_dom_name,
353                                            size_t uni_name_len, const char* pwd,
354                                            DOM_SID sid)
355 {       
356         /* packing structures */
357         pstring pass_buf;
358         int pass_len = 0;
359         int pass_buf_len = sizeof(pass_buf);
360         
361         struct trusted_dom_pass pass;
362         ZERO_STRUCT(pass);
363         
364         /* unicode domain name and its length */
365         if (!uni_dom_name)
366                 return False;
367                 
368         strncpy_w(pass.uni_name, uni_dom_name, sizeof(pass.uni_name) - 1);
369         pass.uni_name_len = uni_name_len;
370
371         /* last change time */
372         pass.mod_time = time(NULL);
373
374         /* password of the trust */
375         pass.pass_len = strlen(pwd);
376         fstrcpy(pass.pass, pwd);
377
378         /* domain sid */
379         sid_copy(&pass.domain_sid, &sid);
380         
381         pass_len = tdb_trusted_dom_pass_pack(pass_buf, pass_buf_len, &pass);
382
383         return secrets_store(trustdom_keystr(domain), (void *)&pass_buf, pass_len);
384 }
385
386 /************************************************************************
387  Routine to set the plaintext machine account password for a realm
388 the password is assumed to be a null terminated ascii string
389 ************************************************************************/
390
391 BOOL secrets_store_machine_password(const char *pass, const char *domain, uint32 sec_channel)
392 {
393         char *key = NULL;
394         BOOL ret;
395         uint32 last_change_time;
396         uint32 sec_channel_type;
397
398         asprintf(&key, "%s/%s", SECRETS_MACHINE_PASSWORD, domain);
399         if (!key) 
400                 return False;
401         strupper(key);
402
403         ret = secrets_store(key, pass, strlen(pass)+1);
404         SAFE_FREE(key);
405
406         if (!ret)
407                 return ret;
408         
409         asprintf(&key, "%s/%s", SECRETS_MACHINE_LAST_CHANGE_TIME, domain);
410         if (!key) 
411                 return False;
412         strupper(key);
413
414         SIVAL(&last_change_time, 0, time(NULL));
415         ret = secrets_store(key, &last_change_time, sizeof(last_change_time));
416         SAFE_FREE(key);
417
418         asprintf(&key, "%s/%s", SECRETS_MACHINE_SEC_CHANNEL_TYPE, domain);
419         if (!key) 
420                 return False;
421         strupper(key);
422
423         SIVAL(&sec_channel_type, 0, sec_channel);
424         ret = secrets_store(key, &sec_channel_type, sizeof(sec_channel_type));
425         SAFE_FREE(key);
426
427         return ret;
428 }
429
430
431 /************************************************************************
432  Routine to fetch the plaintext machine account password for a realm
433 the password is assumed to be a null terminated ascii string
434 ************************************************************************/
435 char *secrets_fetch_machine_password(const char *domain, 
436                                      time_t *pass_last_set_time,
437                                      uint32 *channel)
438 {
439         char *key = NULL;
440         char *ret;
441         asprintf(&key, "%s/%s", SECRETS_MACHINE_PASSWORD, domain);
442         strupper(key);
443         ret = (char *)secrets_fetch(key, NULL);
444         SAFE_FREE(key);
445         
446         if (pass_last_set_time) {
447                 size_t size;
448                 uint32 *last_set_time;
449                 asprintf(&key, "%s/%s", SECRETS_MACHINE_LAST_CHANGE_TIME, domain);
450                 strupper(key);
451                 last_set_time = secrets_fetch(key, &size);
452                 if (last_set_time) {
453                         *pass_last_set_time = IVAL(last_set_time,0);
454                 } else {
455                         *pass_last_set_time = 0;
456                 }
457                 SAFE_FREE(key);
458         }
459         
460         if (channel) {
461                 size_t size;
462                 uint32 *channel_type;
463                 asprintf(&key, "%s/%s", SECRETS_MACHINE_SEC_CHANNEL_TYPE, domain);
464                 strupper(key);
465                 channel_type = secrets_fetch(key, &size);
466                 if (channel_type) {
467                         *channel = IVAL(channel_type,0);
468                 } else {
469                         *channel = get_default_sec_channel();
470                 }
471                 SAFE_FREE(key);
472         }
473         
474         return ret;
475 }
476
477
478
479 /************************************************************************
480  Routine to delete the machine trust account password file for a domain.
481 ************************************************************************/
482
483 BOOL trust_password_delete(const char *domain)
484 {
485         return secrets_delete(trust_keystr(domain));
486 }
487
488 /************************************************************************
489  Routine to delete the password for trusted domain
490 ************************************************************************/
491
492 BOOL trusted_domain_password_delete(const char *domain)
493 {
494         return secrets_delete(trustdom_keystr(domain));
495 }
496
497
498 /*******************************************************************
499  Reset the 'done' variables so after a client process is created
500  from a fork call these calls will be re-done. This should be
501  expanded if more variables need reseting.
502  ******************************************************************/
503
504 void reset_globals_after_fork(void)
505 {
506         unsigned char dummy;
507
508         secrets_init();
509
510         /*
511          * Increment the global seed value to ensure every smbd starts
512          * with a new random seed.
513          */
514
515         if (tdb) {
516                 uint32 initial_val = sys_getpid();
517                 tdb_change_int32_atomic(tdb, "INFO/random_seed", (int *)&initial_val, 1);
518                 set_rand_reseed_data((unsigned char *)&initial_val, sizeof(initial_val));
519         }
520
521         /*
522          * Re-seed the random crypto generator, so all smbd's
523          * started from the same parent won't generate the same
524          * sequence.
525          */
526         generate_random_buffer( &dummy, 1, True);
527 }
528
529 BOOL secrets_store_ldap_pw(const char* dn, char* pw)
530 {
531         char *key = NULL;
532         BOOL ret;
533         
534         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, dn) < 0) {
535                 DEBUG(0, ("secrets_store_ldap_pw: asprintf failed!\n"));
536                 return False;
537         }
538                 
539         ret = secrets_store(key, pw, strlen(pw)+1);
540         
541         SAFE_FREE(key);
542         return ret;
543 }
544
545
546 /**
547  * Get trusted domains info from secrets.tdb.
548  *
549  * The linked list is allocated on the supplied talloc context, caller gets to destroy
550  * when done.
551  *
552  * @param ctx Allocation context
553  * @param enum_ctx Starting index, eg. we can start fetching at third
554  *        or sixth trusted domain entry. Zero is the first index.
555  *        Value it is set to is the enum context for the next enumeration.
556  * @param num_domains Number of domain entries to fetch at one call
557  * @param domains Pointer to array of trusted domain structs to be filled up
558  *
559  * @return nt status code of rpc response
560  **/ 
561
562 NTSTATUS secrets_get_trusted_domains(TALLOC_CTX* ctx, int* enum_ctx, unsigned int max_num_domains, int *num_domains, TRUSTDOM ***domains)
563 {
564         TDB_LIST_NODE *keys, *k;
565         TRUSTDOM *dom = NULL;
566         char *pattern;
567         unsigned int start_idx;
568         uint32 idx = 0;
569         size_t size, packed_size = 0;
570         fstring dom_name;
571         char *packed_pass;
572         struct trusted_dom_pass *pass = talloc_zero(ctx, sizeof(struct trusted_dom_pass));
573         NTSTATUS status;
574
575         if (!secrets_init()) return NT_STATUS_ACCESS_DENIED;
576
577         *num_domains = 0;
578         start_idx = *enum_ctx;
579
580         /* generate searching pattern */
581         if (!(pattern = talloc_asprintf(ctx, "%s/*", SECRETS_DOMTRUST_ACCT_PASS))) {
582                 DEBUG(0, ("secrets_get_trusted_domains: talloc_asprintf() failed!\n"));
583                 return NT_STATUS_NO_MEMORY;
584         }
585
586         DEBUG(5, ("secrets_get_trusted_domains: looking for %d domains, starting at index %d\n", 
587                   max_num_domains, *enum_ctx));
588
589         *domains = talloc_zero(ctx, sizeof(**domains)*max_num_domains);
590
591         /* fetching trusted domains' data and collecting them in a list */
592         keys = tdb_search_keys(tdb, pattern);
593
594         /* 
595          * if there's no keys returned ie. no trusted domain,
596          * return "no more entries" code
597          */
598         status = NT_STATUS_NO_MORE_ENTRIES;
599
600         /* searching for keys in secrets db -- way to go ... */
601         for (k = keys; k; k = k->next) {
602                 char *secrets_key;
603                 
604                 /* important: ensure null-termination of the key string */
605                 secrets_key = strndup(k->node_key.dptr, k->node_key.dsize);
606                 if (!secrets_key) {
607                         DEBUG(0, ("strndup failed!\n"));
608                         return NT_STATUS_NO_MEMORY;
609                 }
610                                 
611                 packed_pass = secrets_fetch(secrets_key, &size);
612                 packed_size = tdb_trusted_dom_pass_unpack(packed_pass, size, pass);
613
614                 if (size != packed_size) {
615                         DEBUG(2, ("Secrets record %s is invalid!\n", secrets_key));
616                         if (size) SAFE_FREE(packed_pass);
617
618                         continue;
619                 }
620                 
621                 /* packed representation isn't needed anymore */
622                 SAFE_FREE(packed_pass);
623                 
624                 pull_ucs2_fstring(dom_name, pass->uni_name);
625                 DEBUG(18, ("Fetched secret record num %d.\nDomain name: %s, SID: %s\n",
626                            idx, dom_name, sid_string_static(&pass->domain_sid)));
627
628                 SAFE_FREE(secrets_key);
629
630                 if (idx >= start_idx && idx < start_idx + max_num_domains) {
631                         dom = talloc_zero(ctx, sizeof(*dom));
632                         if (!dom) {
633                                 /* free returned tdb record */
634                                 return NT_STATUS_NO_MEMORY;
635                         }
636                         
637                         /* copy domain sid */
638                         SMB_ASSERT(sizeof(dom->sid) == sizeof(pass->domain_sid));
639                         memcpy(&(dom->sid), &(pass->domain_sid), sizeof(dom->sid));
640                         
641                         /* copy unicode domain name */
642                         dom->name = talloc_strdup_w(ctx, pass->uni_name);
643                         
644                         (*domains)[idx - start_idx] = dom;
645                         
646                         DEBUG(18, ("Secret record is in required range.\n \
647                                    start_idx = %d, max_num_domains = %d. Added to returned array.\n",
648                                    start_idx, max_num_domains));
649
650                         *enum_ctx = idx + 1;
651                         (*num_domains)++;
652                 
653                         /* set proper status code to return */
654                         if (k->next) {
655                                 /* there are yet some entries to enumerate */
656                                 status = STATUS_MORE_ENTRIES;
657                         } else {
658                                 /* this is the last entry in the whole enumeration */
659                                 status = NT_STATUS_OK;
660                         }
661                 } else {
662                         DEBUG(18, ("Secret is outside the required range.\n \
663                                    start_idx = %d, max_num_domains = %d. Not added to returned array\n",
664                                    start_idx, max_num_domains));
665                 }
666                 
667                 idx++;          
668         }
669         
670         DEBUG(5, ("secrets_get_trusted_domains: got %d domains\n", *num_domains));
671
672         /* free the results of searching the keys */
673         tdb_search_list_free(keys);
674
675         return status;
676 }
677
678 /*******************************************************************************
679  Lock the secrets tdb based on a string - this is used as a primitive form of mutex
680  between smbd instances.
681 *******************************************************************************/
682
683 BOOL secrets_named_mutex(const char *name, unsigned int timeout)
684 {
685         int ret = 0;
686
687         if (!message_init())
688                 return False;
689
690         ret = tdb_lock_bystring(tdb, name, timeout);
691         if (ret == 0)
692                 DEBUG(10,("secrets_named_mutex: got mutex for %s\n", name ));
693
694         return (ret == 0);
695 }
696
697 /*******************************************************************************
698  Unlock a named mutex.
699 *******************************************************************************/
700
701 void secrets_named_mutex_release(const char *name)
702 {
703         tdb_unlock_bystring(tdb, name);
704         DEBUG(10,("secrets_named_mutex: released mutex for %s\n", name ));
705 }
706
707 /*********************************************************
708  Check to see if we must talk to the PDC to avoid sam 
709  sync delays
710  ********************************************************/
711  
712 BOOL must_use_pdc( const char *domain )
713 {
714         time_t  now = time(NULL);
715         time_t  last_change_time;
716         unsigned char   passwd[16];   
717         
718         if ( !secrets_fetch_trust_account_password(domain, passwd, &last_change_time, NULL) )
719                 return False;
720                 
721         /*
722          * If the time the machine password has changed
723          * was less than about 15 minutes then we need to contact
724          * the PDC only, as we cannot be sure domain replication
725          * has yet taken place. Bug found by Gerald (way to go
726          * Gerald !). JRA.
727          */
728          
729         if ( now - last_change_time < SAM_SYNC_WINDOW )
730                 return True;
731                 
732         return False;
733
734 }
735