s3-passdb: Convert lm_pw and nt_pw to python string using length
[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    Copyright (C) Tim Potter           2001
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
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 #include "system/filesys.h"
27 #include "passdb.h"
28 #include "../libcli/auth/libcli_auth.h"
29 #include "librpc/gen_ndr/ndr_secrets.h"
30 #include "secrets.h"
31 #include "dbwrap/dbwrap.h"
32 #include "dbwrap/dbwrap_open.h"
33 #include "../libcli/security/security.h"
34 #include "util_tdb.h"
35
36 #undef DBGC_CLASS
37 #define DBGC_CLASS DBGC_PASSDB
38
39 static struct db_context *db_ctx;
40
41 /**
42  * Use a TDB to store an incrementing random seed.
43  *
44  * Initialised to the current pid, the very first time Samba starts,
45  * and incremented by one each time it is needed.
46  *
47  * @note Not called by systems with a working /dev/urandom.
48  */
49 static void get_rand_seed(void *userdata, int *new_seed)
50 {
51         *new_seed = sys_getpid();
52         if (db_ctx) {
53                 dbwrap_trans_change_int32_atomic(db_ctx, "INFO/random_seed",
54                                                  new_seed, 1);
55         }
56 }
57
58 /* open up the secrets database with specified private_dir path */
59 bool secrets_init_path(const char *private_dir)
60 {
61         char *fname = NULL;
62         unsigned char dummy;
63
64         if (db_ctx != NULL) {
65                 return True;
66         }
67
68         if (private_dir == NULL) {
69                 return False;
70         }
71
72         fname = talloc_asprintf(talloc_tos(), "%s/secrets.tdb",
73                                 private_dir);
74         if (fname == NULL) {
75                 return False;
76         }
77
78         db_ctx = db_open(NULL, fname, 0,
79                          TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
80
81         if (db_ctx == NULL) {
82                 DEBUG(0,("Failed to open %s\n", fname));
83                 return False;
84         }
85
86         TALLOC_FREE(fname);
87
88         /**
89          * Set a reseed function for the crypto random generator
90          *
91          * This avoids a problem where systems without /dev/urandom
92          * could send the same challenge to multiple clients
93          */
94         set_rand_reseed_callback(get_rand_seed, NULL);
95
96         /* Ensure that the reseed is done now, while we are root, etc */
97         generate_random_buffer(&dummy, sizeof(dummy));
98
99         return True;
100 }
101
102 /* open up the secrets database */
103 bool secrets_init(void)
104 {
105         return secrets_init_path(lp_private_dir());
106 }
107
108 struct db_context *secrets_db_ctx(void)
109 {
110         if (!secrets_init()) {
111                 return NULL;
112         }
113
114         return db_ctx;
115 }
116
117 /*
118  * close secrets.tdb
119  */
120 void secrets_shutdown(void)
121 {
122         TALLOC_FREE(db_ctx);
123 }
124
125 /* read a entry from the secrets database - the caller must free the result
126    if size is non-null then the size of the entry is put in there
127  */
128 void *secrets_fetch(const char *key, size_t *size)
129 {
130         TDB_DATA dbuf;
131         void *result;
132
133         if (!secrets_init()) {
134                 return NULL;
135         }
136
137         if (db_ctx->fetch(db_ctx, talloc_tos(), string_tdb_data(key),
138                           &dbuf) != 0) {
139                 return NULL;
140         }
141
142         result = memdup(dbuf.dptr, dbuf.dsize);
143         if (result == NULL) {
144                 return NULL;
145         }
146         TALLOC_FREE(dbuf.dptr);
147
148         if (size) {
149                 *size = dbuf.dsize;
150         }
151
152         return result;
153 }
154
155 /* store a secrets entry
156  */
157 bool secrets_store(const char *key, const void *data, size_t size)
158 {
159         NTSTATUS status;
160
161         if (!secrets_init()) {
162                 return false;
163         }
164
165         status = dbwrap_trans_store(db_ctx, string_tdb_data(key),
166                                     make_tdb_data((const uint8 *)data, size),
167                                     TDB_REPLACE);
168         return NT_STATUS_IS_OK(status);
169 }
170
171
172 /* delete a secets database entry
173  */
174 bool secrets_delete(const char *key)
175 {
176         NTSTATUS status;
177         if (!secrets_init()) {
178                 return false;
179         }
180
181         status = dbwrap_trans_delete(db_ctx, string_tdb_data(key));
182
183         return NT_STATUS_IS_OK(status);
184 }
185
186 /**
187  * Form a key for fetching a trusted domain password
188  *
189  * @param domain trusted domain name
190  *
191  * @return stored password's key
192  **/
193 static char *trustdom_keystr(const char *domain)
194 {
195         char *keystr;
196
197         keystr = talloc_asprintf_strupper_m(talloc_tos(), "%s/%s",
198                                             SECRETS_DOMTRUST_ACCT_PASS,
199                                             domain);
200         SMB_ASSERT(keystr != NULL);
201         return keystr;
202 }
203
204 /************************************************************************
205  Routine to get account password to trusted domain
206 ************************************************************************/
207
208 bool secrets_fetch_trusted_domain_password(const char *domain, char** pwd,
209                                            struct dom_sid *sid, time_t *pass_last_set_time)
210 {
211         struct TRUSTED_DOM_PASS pass;
212         enum ndr_err_code ndr_err;
213
214         /* unpacking structures */
215         DATA_BLOB blob;
216
217         /* fetching trusted domain password structure */
218         if (!(blob.data = (uint8_t *)secrets_fetch(trustdom_keystr(domain),
219                                                    &blob.length))) {
220                 DEBUG(5, ("secrets_fetch failed!\n"));
221                 return False;
222         }
223
224         /* unpack trusted domain password */
225         ndr_err = ndr_pull_struct_blob(&blob, talloc_tos(), &pass,
226                         (ndr_pull_flags_fn_t)ndr_pull_TRUSTED_DOM_PASS);
227
228         SAFE_FREE(blob.data);
229
230         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
231                 return false;
232         }
233
234
235         /* the trust's password */
236         if (pwd) {
237                 *pwd = SMB_STRDUP(pass.pass);
238                 if (!*pwd) {
239                         return False;
240                 }
241         }
242
243         /* last change time */
244         if (pass_last_set_time) *pass_last_set_time = pass.mod_time;
245
246         /* domain sid */
247         if (sid != NULL) sid_copy(sid, &pass.domain_sid);
248
249         return True;
250 }
251
252 /**
253  * Routine to store the password for trusted domain
254  *
255  * @param domain remote domain name
256  * @param pwd plain text password of trust relationship
257  * @param sid remote domain sid
258  *
259  * @return true if succeeded
260  **/
261
262 bool secrets_store_trusted_domain_password(const char* domain, const char* pwd,
263                                            const struct dom_sid *sid)
264 {
265         bool ret;
266
267         /* packing structures */
268         DATA_BLOB blob;
269         enum ndr_err_code ndr_err;
270         struct TRUSTED_DOM_PASS pass;
271         ZERO_STRUCT(pass);
272
273         pass.uni_name = domain;
274         pass.uni_name_len = strlen(domain)+1;
275
276         /* last change time */
277         pass.mod_time = time(NULL);
278
279         /* password of the trust */
280         pass.pass_len = strlen(pwd);
281         pass.pass = pwd;
282
283         /* domain sid */
284         sid_copy(&pass.domain_sid, sid);
285
286         ndr_err = ndr_push_struct_blob(&blob, talloc_tos(), &pass,
287                         (ndr_push_flags_fn_t)ndr_push_TRUSTED_DOM_PASS);
288         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
289                 return false;
290         }
291
292         ret = secrets_store(trustdom_keystr(domain), blob.data, blob.length);
293
294         data_blob_free(&blob);
295
296         return ret;
297 }
298
299 /************************************************************************
300  Routine to delete the password for trusted domain
301 ************************************************************************/
302
303 bool trusted_domain_password_delete(const char *domain)
304 {
305         return secrets_delete(trustdom_keystr(domain));
306 }
307
308 bool secrets_store_ldap_pw(const char* dn, char* pw)
309 {
310         char *key = NULL;
311         bool ret;
312
313         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, dn) < 0) {
314                 DEBUG(0, ("secrets_store_ldap_pw: asprintf failed!\n"));
315                 return False;
316         }
317
318         ret = secrets_store(key, pw, strlen(pw)+1);
319
320         SAFE_FREE(key);
321         return ret;
322 }
323
324 /*******************************************************************
325  Find the ldap password.
326 ******************************************************************/
327
328 bool fetch_ldap_pw(char **dn, char** pw)
329 {
330         char *key = NULL;
331         size_t size = 0;
332
333         *dn = smb_xstrdup(lp_ldap_admin_dn());
334
335         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, *dn) < 0) {
336                 SAFE_FREE(*dn);
337                 DEBUG(0, ("fetch_ldap_pw: asprintf failed!\n"));
338                 return false;
339         }
340
341         *pw=(char *)secrets_fetch(key, &size);
342         SAFE_FREE(key);
343
344         if (!size) {
345                 /* Upgrade 2.2 style entry */
346                 char *p;
347                 char* old_style_key = SMB_STRDUP(*dn);
348                 char *data;
349                 fstring old_style_pw;
350
351                 if (!old_style_key) {
352                         DEBUG(0, ("fetch_ldap_pw: strdup failed!\n"));
353                         return False;
354                 }
355
356                 for (p=old_style_key; *p; p++)
357                         if (*p == ',') *p = '/';
358
359                 data=(char *)secrets_fetch(old_style_key, &size);
360                 if ((data == NULL) || (size < sizeof(old_style_pw))) {
361                         DEBUG(0,("fetch_ldap_pw: neither ldap secret retrieved!\n"));
362                         SAFE_FREE(old_style_key);
363                         SAFE_FREE(*dn);
364                         SAFE_FREE(data);
365                         return False;
366                 }
367
368                 size = MIN(size, sizeof(fstring)-1);
369                 strncpy(old_style_pw, data, size);
370                 old_style_pw[size] = 0;
371
372                 SAFE_FREE(data);
373
374                 if (!secrets_store_ldap_pw(*dn, old_style_pw)) {
375                         DEBUG(0,("fetch_ldap_pw: ldap secret could not be upgraded!\n"));
376                         SAFE_FREE(old_style_key);
377                         SAFE_FREE(*dn);
378                         return False;
379                 }
380                 if (!secrets_delete(old_style_key)) {
381                         DEBUG(0,("fetch_ldap_pw: old ldap secret could not be deleted!\n"));
382                 }
383
384                 SAFE_FREE(old_style_key);
385
386                 *pw = smb_xstrdup(old_style_pw);
387         }
388
389         return True;
390 }
391
392 /**
393  * Get trusted domains info from secrets.tdb.
394  **/
395
396 struct list_trusted_domains_state {
397         uint32 num_domains;
398         struct trustdom_info **domains;
399 };
400
401 static int list_trusted_domain(struct db_record *rec, void *private_data)
402 {
403         const size_t prefix_len = strlen(SECRETS_DOMTRUST_ACCT_PASS);
404         struct TRUSTED_DOM_PASS pass;
405         enum ndr_err_code ndr_err;
406         DATA_BLOB blob;
407         struct trustdom_info *dom_info;
408
409         struct list_trusted_domains_state *state =
410                 (struct list_trusted_domains_state *)private_data;
411
412         if ((rec->key.dsize < prefix_len)
413             || (strncmp((char *)rec->key.dptr, SECRETS_DOMTRUST_ACCT_PASS,
414                         prefix_len) != 0)) {
415                 return 0;
416         }
417
418         blob = data_blob_const(rec->value.dptr, rec->value.dsize);
419
420         ndr_err = ndr_pull_struct_blob(&blob, talloc_tos(), &pass,
421                         (ndr_pull_flags_fn_t)ndr_pull_TRUSTED_DOM_PASS);
422         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
423                 return false;
424         }
425
426         if (pass.domain_sid.num_auths != 4) {
427                 DEBUG(0, ("SID %s is not a domain sid, has %d "
428                           "auths instead of 4\n",
429                           sid_string_dbg(&pass.domain_sid),
430                           pass.domain_sid.num_auths));
431                 return 0;
432         }
433
434         if (!(dom_info = talloc(state->domains, struct trustdom_info))) {
435                 DEBUG(0, ("talloc failed\n"));
436                 return 0;
437         }
438
439         dom_info->name = talloc_strdup(dom_info, pass.uni_name);
440         if (!dom_info->name) {
441                 TALLOC_FREE(dom_info);
442                 return 0;
443         }
444
445         sid_copy(&dom_info->sid, &pass.domain_sid);
446
447         ADD_TO_ARRAY(state->domains, struct trustdom_info *, dom_info,
448                      &state->domains, &state->num_domains);
449
450         if (state->domains == NULL) {
451                 state->num_domains = 0;
452                 return -1;
453         }
454         return 0;
455 }
456
457 NTSTATUS secrets_trusted_domains(TALLOC_CTX *mem_ctx, uint32 *num_domains,
458                                  struct trustdom_info ***domains)
459 {
460         struct list_trusted_domains_state state;
461
462         if (!secrets_init()) {
463                 return NT_STATUS_ACCESS_DENIED;
464         }
465
466         state.num_domains = 0;
467
468         /*
469          * Make sure that a talloc context for the trustdom_info structs
470          * exists
471          */
472
473         if (!(state.domains = talloc_array(
474                       mem_ctx, struct trustdom_info *, 1))) {
475                 return NT_STATUS_NO_MEMORY;
476         }
477
478         db_ctx->traverse_read(db_ctx, list_trusted_domain, (void *)&state);
479
480         *num_domains = state.num_domains;
481         *domains = state.domains;
482         return NT_STATUS_OK;
483 }
484
485 /*******************************************************************************
486  Store a complete AFS keyfile into secrets.tdb.
487 *******************************************************************************/
488
489 bool secrets_store_afs_keyfile(const char *cell, const struct afs_keyfile *keyfile)
490 {
491         fstring key;
492
493         if ((cell == NULL) || (keyfile == NULL))
494                 return False;
495
496         if (ntohl(keyfile->nkeys) > SECRETS_AFS_MAXKEYS)
497                 return False;
498
499         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_AFS_KEYFILE, cell);
500         return secrets_store(key, keyfile, sizeof(struct afs_keyfile));
501 }
502
503 /*******************************************************************************
504  Fetch the current (highest) AFS key from secrets.tdb
505 *******************************************************************************/
506 bool secrets_fetch_afs_key(const char *cell, struct afs_key *result)
507 {
508         fstring key;
509         struct afs_keyfile *keyfile;
510         size_t size = 0;
511         uint32 i;
512
513         slprintf(key, sizeof(key)-1, "%s/%s", SECRETS_AFS_KEYFILE, cell);
514
515         keyfile = (struct afs_keyfile *)secrets_fetch(key, &size);
516
517         if (keyfile == NULL)
518                 return False;
519
520         if (size != sizeof(struct afs_keyfile)) {
521                 SAFE_FREE(keyfile);
522                 return False;
523         }
524
525         i = ntohl(keyfile->nkeys);
526
527         if (i > SECRETS_AFS_MAXKEYS) {
528                 SAFE_FREE(keyfile);
529                 return False;
530         }
531
532         *result = keyfile->entry[i-1];
533
534         result->kvno = ntohl(result->kvno);
535
536         SAFE_FREE(keyfile);
537
538         return True;
539 }
540
541 /******************************************************************************
542   When kerberos is not available, choose between anonymous or
543   authenticated connections.
544
545   We need to use an authenticated connection if DCs have the
546   RestrictAnonymous registry entry set > 0, or the "Additional
547   restrictions for anonymous connections" set in the win2k Local
548   Security Policy.
549
550   Caller to free() result in domain, username, password
551 *******************************************************************************/
552 void secrets_fetch_ipc_userpass(char **username, char **domain, char **password)
553 {
554         *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
555         *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
556         *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
557
558         if (*username && **username) {
559
560                 if (!*domain || !**domain)
561                         *domain = smb_xstrdup(lp_workgroup());
562
563                 if (!*password || !**password)
564                         *password = smb_xstrdup("");
565
566                 DEBUG(3, ("IPC$ connections done by user %s\\%s\n",
567                           *domain, *username));
568
569         } else {
570                 DEBUG(3, ("IPC$ connections done anonymously\n"));
571                 *username = smb_xstrdup("");
572                 *domain = smb_xstrdup("");
573                 *password = smb_xstrdup("");
574         }
575 }
576
577 bool secrets_store_generic(const char *owner, const char *key, const char *secret)
578 {
579         char *tdbkey = NULL;
580         bool ret;
581
582         if (asprintf(&tdbkey, "SECRETS/GENERIC/%s/%s", owner, key) < 0) {
583                 DEBUG(0, ("asprintf failed!\n"));
584                 return False;
585         }
586
587         ret = secrets_store(tdbkey, secret, strlen(secret)+1);
588
589         SAFE_FREE(tdbkey);
590         return ret;
591 }
592
593 bool secrets_delete_generic(const char *owner, const char *key)
594 {
595         char *tdbkey = NULL;
596         bool ret;
597
598         if (asprintf(&tdbkey, "SECRETS/GENERIC/%s/%s", owner, key) < 0) {
599                 DEBUG(0, ("asprintf failed!\n"));
600                 return False;
601         }
602
603         ret = secrets_delete(tdbkey);
604
605         SAFE_FREE(tdbkey);
606         return ret;
607 }
608
609 /*******************************************************************
610  Find the ldap password.
611 ******************************************************************/
612
613 char *secrets_fetch_generic(const char *owner, const char *key)
614 {
615         char *secret = NULL;
616         char *tdbkey = NULL;
617
618         if (( ! owner) || ( ! key)) {
619                 DEBUG(1, ("Invalid Parameters"));
620                 return NULL;
621         }
622
623         if (asprintf(&tdbkey, "SECRETS/GENERIC/%s/%s", owner, key) < 0) {
624                 DEBUG(0, ("Out of memory!\n"));
625                 return NULL;
626         }
627
628         secret = (char *)secrets_fetch(tdbkey, NULL);
629         SAFE_FREE(tdbkey);
630
631         return secret;
632 }
633