auth/credentials: Better integrate fetch of secrets.tdb and secrets.ldb records
[metze/samba/wip.git] / auth / credentials / credentials_secrets.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    User credentials handling (as regards on-disk files)
5
6    Copyright (C) Jelmer Vernooij 2005
7    Copyright (C) Tim Potter 2001
8    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "lib/events/events.h"
26 #include <ldb.h>
27 #include "librpc/gen_ndr/samr.h" /* for struct samrPassword */
28 #include "param/secrets.h"
29 #include "system/filesys.h"
30 #include "auth/credentials/credentials.h"
31 #include "auth/credentials/credentials_proto.h"
32 #include "auth/credentials/credentials_krb5.h"
33 #include "auth/kerberos/kerberos_util.h"
34 #include "param/param.h"
35 #include "lib/events/events.h"
36 #include "dsdb/samdb/samdb.h"
37 #include "source3/include/secrets.h"
38 #include "dbwrap/dbwrap.h"
39 #include "dbwrap/dbwrap_open.h"
40 #include "lib/util/util_tdb.h"
41
42
43 /**
44  * Fill in credentials for the machine trust account, from the secrets database.
45  * 
46  * @param cred Credentials structure to fill in
47  * @retval NTSTATUS error detailing any failure
48  */
49 static NTSTATUS cli_credentials_set_secrets_lct(struct cli_credentials *cred, 
50                                                 struct loadparm_context *lp_ctx,
51                                                 struct ldb_context *ldb,
52                                                 const char *base,
53                                                 const char *filter, 
54                                                 time_t secrets_tdb_last_change_time,
55                                                 const char *secrets_tdb_password,
56                                                 char **error_string)
57 {
58         TALLOC_CTX *mem_ctx;
59         
60         int ldb_ret;
61         struct ldb_message *msg;
62         
63         const char *machine_account;
64         const char *password;
65         const char *domain;
66         const char *realm;
67         enum netr_SchannelType sct;
68         const char *salt_principal;
69         char *keytab;
70         const struct ldb_val *whenChanged;
71         time_t lct;
72
73         /* ok, we are going to get it now, don't recurse back here */
74         cred->machine_account_pending = false;
75
76         /* some other parts of the system will key off this */
77         cred->machine_account = true;
78
79         mem_ctx = talloc_named(cred, 0, "cli_credentials_set_secrets from ldb");
80
81         if (!ldb) {
82                 /* Local secrets are stored in secrets.ldb */
83                 ldb = secrets_db_connect(mem_ctx, lp_ctx);
84                 if (!ldb) {
85                         *error_string = talloc_strdup(cred, "Could not open secrets.ldb");
86                         talloc_free(mem_ctx);
87                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
88                 }
89         }
90
91         ldb_ret = dsdb_search_one(ldb, mem_ctx, &msg,
92                                   ldb_dn_new(mem_ctx, ldb, base),
93                                   LDB_SCOPE_SUBTREE,
94                                   NULL, 0, "%s", filter);
95
96         if (ldb_ret != LDB_SUCCESS) {
97                 *error_string = talloc_asprintf(cred, "Could not find entry to match filter: '%s' base: '%s': %s: %s",
98                                                 filter, base ? base : "",
99                                                 ldb_strerror(ldb_ret), ldb_errstring(ldb));
100                 talloc_free(mem_ctx);
101                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
102         }
103
104         password = ldb_msg_find_attr_as_string(msg, "secret", NULL);
105
106         whenChanged = ldb_msg_find_ldb_val(msg, "whenChanged");
107         if (!whenChanged || ldb_val_to_time(whenChanged, &lct) != LDB_SUCCESS) {
108                 /* This attribute is mandetory */
109                 talloc_free(mem_ctx);
110                 return NT_STATUS_NOT_FOUND;
111         }
112
113         /* Don't set secrets.ldb info if the secrets.tdb entry was more recent */
114         if (lct < secrets_tdb_last_change_time) {
115                 talloc_free(mem_ctx);
116                 return NT_STATUS_NOT_FOUND;
117         }
118         
119         if (lct == secrets_tdb_last_change_time && secrets_tdb_password && strcmp(password, secrets_tdb_password) != 0) {
120                 talloc_free(mem_ctx);
121                 return NT_STATUS_NOT_FOUND;
122         }
123         
124         cli_credentials_set_password_last_changed_time(cred, lct);
125         
126         machine_account = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
127
128         if (!machine_account) {
129                 machine_account = ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL);
130                 
131                 if (!machine_account) {
132                         const char *ldap_bind_dn = ldb_msg_find_attr_as_string(msg, "ldapBindDn", NULL);
133                         if (!ldap_bind_dn) {
134                                 *error_string = talloc_asprintf(cred, 
135                                                                 "Could not find 'samAccountName', "
136                                                                 "'servicePrincipalName' or "
137                                                                 "'ldapBindDn' in secrets record: %s",
138                                                                 ldb_dn_get_linearized(msg->dn));
139                                 talloc_free(mem_ctx);
140                                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
141                         } else {
142                                 /* store bind dn in credentials */
143                                 cli_credentials_set_bind_dn(cred, ldap_bind_dn);
144                         }
145                 }
146         }
147
148         salt_principal = ldb_msg_find_attr_as_string(msg, "saltPrincipal", NULL);
149         cli_credentials_set_salt_principal(cred, salt_principal);
150         
151         sct = ldb_msg_find_attr_as_int(msg, "secureChannelType", 0);
152         if (sct) { 
153                 cli_credentials_set_secure_channel_type(cred, sct);
154         }
155         
156         if (!password) {
157                 const struct ldb_val *nt_password_hash = ldb_msg_find_ldb_val(msg, "unicodePwd");
158                 struct samr_Password hash;
159                 ZERO_STRUCT(hash);
160                 if (nt_password_hash) {
161                         memcpy(hash.hash, nt_password_hash->data, 
162                                MIN(nt_password_hash->length, sizeof(hash.hash)));
163                 
164                         cli_credentials_set_nt_hash(cred, &hash, CRED_SPECIFIED);
165                 } else {
166                         cli_credentials_set_password(cred, NULL, CRED_SPECIFIED);
167                 }
168         } else {
169                 cli_credentials_set_password(cred, password, CRED_SPECIFIED);
170         }
171
172         
173         domain = ldb_msg_find_attr_as_string(msg, "flatname", NULL);
174         if (domain) {
175                 cli_credentials_set_domain(cred, domain, CRED_SPECIFIED);
176         }
177
178         realm = ldb_msg_find_attr_as_string(msg, "realm", NULL);
179         if (realm) {
180                 cli_credentials_set_realm(cred, realm, CRED_SPECIFIED);
181         }
182
183         if (machine_account) {
184                 cli_credentials_set_username(cred, machine_account, CRED_SPECIFIED);
185         }
186
187         cli_credentials_set_kvno(cred, ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0));
188
189         /* If there was an external keytab specified by reference in
190          * the LDB, then use this.  Otherwise we will make one up
191          * (chewing CPU time) from the password */
192         keytab = keytab_name_from_msg(cred, ldb, msg);
193         if (keytab) {
194                 cli_credentials_set_keytab_name(cred, lp_ctx, keytab, CRED_SPECIFIED);
195                 talloc_free(keytab);
196         }
197         talloc_free(mem_ctx);
198         
199         return NT_STATUS_OK;
200 }
201
202
203 /**
204  * Fill in credentials for the machine trust account, from the secrets database.
205  * 
206  * @param cred Credentials structure to fill in
207  * @retval NTSTATUS error detailing any failure
208  */
209 _PUBLIC_ NTSTATUS cli_credentials_set_secrets(struct cli_credentials *cred, 
210                                               struct loadparm_context *lp_ctx,
211                                               struct ldb_context *ldb,
212                                               const char *base,
213                                               const char *filter, 
214                                               char **error_string)
215 {
216         NTSTATUS status = cli_credentials_set_secrets_lct(cred, lp_ctx, ldb, base, filter, 0, NULL, error_string);
217         if (!NT_STATUS_IS_OK(status)) {
218                 /* set anonymous as the fallback, if the machine account won't work */
219                 cli_credentials_set_anonymous(cred);
220         }
221         return status;
222 }
223
224 /**
225  * Fill in credentials for the machine trust account, from the secrets database.
226  * 
227  * @param cred Credentials structure to fill in
228  * @retval NTSTATUS error detailing any failure
229  */
230 _PUBLIC_ NTSTATUS cli_credentials_set_machine_account(struct cli_credentials *cred,
231                                                       struct loadparm_context *lp_ctx)
232 {
233         NTSTATUS status;
234         char *filter;
235         char *error_string;
236         const char *domain;
237         bool secrets_tdb_password_more_recent;
238         time_t secrets_tdb_lct = 0;
239         char *secrets_tdb_password = NULL;
240         char *keystr;
241         char *keystr_upper = NULL;
242         char *secrets_tdb;
243         struct db_context *db_ctx;
244         TALLOC_CTX *tmp_ctx = talloc_named(cred, 0, "cli_credentials_set_secrets from ldb");
245         if (!tmp_ctx) {
246                 return NT_STATUS_NO_MEMORY;
247         }
248         secrets_tdb = lpcfg_private_path(cred, lp_ctx, "secrets.tdb");
249         if (!secrets_tdb) {
250                 TALLOC_FREE(tmp_ctx);
251                 return NT_STATUS_NO_MEMORY;
252         }
253                 
254         db_ctx = dbwrap_local_open(cred, lp_ctx, secrets_tdb, 0,
255                                    TDB_DEFAULT, O_RDWR, 0600,
256                                    DBWRAP_LOCK_ORDER_1);
257         /* Bleh, nasty recursion issues: We are setting a machine
258          * account here, so we don't want the 'pending' flag around
259          * any more */
260         cred->machine_account_pending = false;
261
262         /* We have to do this, as the fallback in
263          * cli_credentials_set_secrets is to run as anonymous, so the domain is wiped */
264         domain = cli_credentials_get_domain(cred);
265
266         if (db_ctx) {
267                 TDB_DATA dbuf;
268                 keystr = talloc_asprintf(tmp_ctx, "%s/%s",
269                                          SECRETS_MACHINE_LAST_CHANGE_TIME,
270                                          domain);
271                 keystr_upper = strupper_talloc(tmp_ctx, keystr);
272                 status = dbwrap_fetch(db_ctx, tmp_ctx, string_tdb_data(keystr_upper),
273                                       &dbuf);
274                 if (NT_STATUS_IS_OK(status) && dbuf.dsize == 4) {
275                         secrets_tdb_lct = IVAL(dbuf.dptr,0);
276                 }
277
278                 keystr = talloc_asprintf(tmp_ctx, "%s/%s",
279                                          SECRETS_MACHINE_PASSWORD,
280                                          domain);
281                 keystr_upper = strupper_talloc(tmp_ctx, keystr);
282                 status = dbwrap_fetch(db_ctx, tmp_ctx, string_tdb_data(keystr_upper),
283                                       &dbuf);
284                 if (NT_STATUS_IS_OK(status)) {
285                         secrets_tdb_password = (char *)dbuf.dptr;
286                 }
287         }
288
289         filter = talloc_asprintf(cred, SECRETS_PRIMARY_DOMAIN_FILTER, 
290                                  domain);
291         status = cli_credentials_set_secrets_lct(cred, lp_ctx, NULL,
292                                                  SECRETS_PRIMARY_DOMAIN_DN,
293                                                  filter, secrets_tdb_lct, secrets_tdb_password, &error_string);
294         if (secrets_tdb_password == NULL) {
295                 secrets_tdb_password_more_recent = false;
296         } else if (NT_STATUS_EQUAL(NT_STATUS_CANT_ACCESS_DOMAIN_INFO, status)
297             || NT_STATUS_EQUAL(NT_STATUS_NOT_FOUND, status)) {
298                 secrets_tdb_password_more_recent = true;
299         } else if (secrets_tdb_lct > cli_credentials_get_password_last_changed_time(cred)) {
300                 secrets_tdb_password_more_recent = true;
301         } else if (secrets_tdb_lct == cli_credentials_get_password_last_changed_time(cred)) {
302                 secrets_tdb_password_more_recent = strcmp(secrets_tdb_password, cli_credentials_get_password(cred)) != 0;
303         } else {
304                 secrets_tdb_password_more_recent = false;
305         }
306
307         if (secrets_tdb_password_more_recent) {
308                 char *machine_account = talloc_asprintf(tmp_ctx, "%s$", lpcfg_netbios_name(lp_ctx));
309                 cli_credentials_set_password(cred, secrets_tdb_password, CRED_SPECIFIED);
310                 cli_credentials_set_domain(cred, domain, CRED_SPECIFIED);
311                 cli_credentials_set_username(cred, machine_account, CRED_SPECIFIED);
312         } else if (!NT_STATUS_IS_OK(status)) {
313                 if (db_ctx) {
314                         error_string = talloc_asprintf(cred,
315                                                        "Failed to fetch machine account password from "
316                                                        "secrets.ldb: %s and failed to fetch %s from %s",
317                                                        error_string, keystr_upper, secrets_tdb);
318                 } else {
319                         error_string = talloc_asprintf(cred,
320                                                        "Failed to fetch machine account password from "
321                                                        "secrets.ldb: %s and failed to open %s",
322                                                        error_string, secrets_tdb);
323                 }
324                 DEBUG(1, ("Could not find machine account in secrets database: %s: %s\n", 
325                           error_string, nt_errstr(status)));
326                 /* set anonymous as the fallback, if the machine account won't work */
327                 cli_credentials_set_anonymous(cred);
328         }
329         
330         TALLOC_FREE(tmp_ctx);
331         return status;
332 }
333
334 /**
335  * Fill in credentials for the machine trust account, from the secrets database.
336  * 
337  * @param cred Credentials structure to fill in
338  * @retval NTSTATUS error detailing any failure
339  */
340 NTSTATUS cli_credentials_set_krbtgt(struct cli_credentials *cred,
341                                     struct loadparm_context *lp_ctx)
342 {
343         NTSTATUS status;
344         char *filter;
345         char *error_string;
346         /* Bleh, nasty recursion issues: We are setting a machine
347          * account here, so we don't want the 'pending' flag around
348          * any more */
349         cred->machine_account_pending = false;
350         filter = talloc_asprintf(cred, SECRETS_KRBTGT_SEARCH,
351                                        cli_credentials_get_realm(cred),
352                                        cli_credentials_get_domain(cred));
353         status = cli_credentials_set_secrets_lct(cred, lp_ctx, NULL,
354                                                  SECRETS_PRINCIPALS_DN,
355                                                  filter, 0, NULL, &error_string);
356         if (!NT_STATUS_IS_OK(status)) {
357                 DEBUG(1, ("Could not find krbtgt (master Kerberos) account in secrets database: %s: %s\n", nt_errstr(status), error_string));
358                 talloc_free(error_string);
359         }
360         return status;
361 }
362
363 /**
364  * Fill in credentials for a particular prinicpal, from the secrets database.
365  * 
366  * @param cred Credentials structure to fill in
367  * @retval NTSTATUS error detailing any failure
368  */
369 _PUBLIC_ NTSTATUS cli_credentials_set_stored_principal(struct cli_credentials *cred,
370                                               struct loadparm_context *lp_ctx,
371                                               const char *serviceprincipal)
372 {
373         NTSTATUS status;
374         char *filter;
375         char *error_string;
376         /* Bleh, nasty recursion issues: We are setting a machine
377          * account here, so we don't want the 'pending' flag around
378          * any more */
379         cred->machine_account_pending = false;
380         filter = talloc_asprintf(cred, SECRETS_PRINCIPAL_SEARCH,
381                                  cli_credentials_get_realm(cred),
382                                  cli_credentials_get_domain(cred),
383                                  serviceprincipal);
384         status = cli_credentials_set_secrets_lct(cred, lp_ctx, NULL,
385                                              SECRETS_PRINCIPALS_DN, filter,
386                                              0, NULL, &error_string);
387         if (!NT_STATUS_IS_OK(status)) {
388                 DEBUG(1, ("Could not find %s principal in secrets database: %s: %s\n", serviceprincipal, nt_errstr(status), error_string));
389         }
390         return status;
391 }
392
393 /**
394  * Ask that when required, the credentials system will be filled with
395  * machine trust account, from the secrets database.
396  * 
397  * @param cred Credentials structure to fill in
398  * @note This function is used to call the above function after, rather 
399  *       than during, popt processing.
400  *
401  */
402 _PUBLIC_ void cli_credentials_set_machine_account_pending(struct cli_credentials *cred,
403                                                  struct loadparm_context *lp_ctx)
404 {
405         cred->machine_account_pending = true;
406         cred->machine_account_pending_lp_ctx = lp_ctx;
407 }
408
409