debug auth_system_session
[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_internal.h"
32 #include "auth/credentials/credentials_proto.h"
33 #include "auth/credentials/credentials_krb5.h"
34 #include "auth/kerberos/kerberos_util.h"
35 #include "param/param.h"
36 #include "lib/events/events.h"
37 #include "dsdb/samdb/samdb.h"
38 #include "source3/include/secrets.h"
39 #include "dbwrap/dbwrap.h"
40 #include "dbwrap/dbwrap_open.h"
41 #include "lib/util/util_tdb.h"
42 #include "libds/common/roles.h"
43
44 #undef DBGC_CLASS
45 #define DBGC_CLASS DBGC_AUTH
46
47 /**
48  * Fill in credentials for the machine trust account, from the secrets database.
49  *
50  * @param cred Credentials structure to fill in
51  * @retval NTSTATUS error detailing any failure
52  */
53 static NTSTATUS cli_credentials_set_secrets_lct(struct cli_credentials *cred,
54                                                 struct loadparm_context *lp_ctx,
55                                                 struct ldb_context *ldb,
56                                                 const char *base,
57                                                 const char *filter,
58                                                 time_t secrets_tdb_last_change_time,
59                                                 const char *secrets_tdb_password,
60                                                 char **error_string)
61 {
62         TALLOC_CTX *mem_ctx;
63
64         int ldb_ret;
65         struct ldb_message *msg;
66
67         const char *machine_account;
68         const char *password;
69         const char *domain;
70         const char *realm;
71         enum netr_SchannelType sct;
72         const char *salt_principal;
73         char *keytab;
74         const struct ldb_val *whenChanged;
75         time_t lct;
76
77         /* ok, we are going to get it now, don't recurse back here */
78         cred->machine_account_pending = false;
79
80         /* some other parts of the system will key off this */
81         cred->machine_account = true;
82
83         mem_ctx = talloc_named(cred, 0, "cli_credentials_set_secrets from ldb");
84
85         if (!ldb) {
86                 /* Local secrets are stored in secrets.ldb */
87                 ldb = secrets_db_connect(mem_ctx, lp_ctx);
88                 if (!ldb) {
89                         *error_string = talloc_strdup(cred, "Could not open secrets.ldb");
90                         talloc_free(mem_ctx);
91                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
92                 }
93         }
94
95         ldb_ret = dsdb_search_one(ldb, mem_ctx, &msg,
96                                   ldb_dn_new(mem_ctx, ldb, base),
97                                   LDB_SCOPE_SUBTREE,
98                                   NULL, 0, "%s", filter);
99
100         if (ldb_ret != LDB_SUCCESS) {
101                 *error_string = talloc_asprintf(cred, "Could not find entry to match filter: '%s' base: '%s': %s: %s",
102                                                 filter, base ? base : "",
103                                                 ldb_strerror(ldb_ret), ldb_errstring(ldb));
104                 talloc_free(mem_ctx);
105                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
106         }
107
108         password = ldb_msg_find_attr_as_string(msg, "secret", NULL);
109
110         whenChanged = ldb_msg_find_ldb_val(msg, "whenChanged");
111         if (!whenChanged || ldb_val_to_time(whenChanged, &lct) != LDB_SUCCESS) {
112                 /* This attribute is mandatory */
113                 talloc_free(mem_ctx);
114                 return NT_STATUS_NOT_FOUND;
115         }
116
117         /* Don't set secrets.ldb info if the secrets.tdb entry was more recent */
118         if (lct < secrets_tdb_last_change_time) {
119                 talloc_free(mem_ctx);
120                 return NT_STATUS_NOT_FOUND;
121         }
122
123         if ((lct == secrets_tdb_last_change_time) &&
124             (secrets_tdb_password != NULL) &&
125             (password != NULL) &&
126             (strcmp(password, secrets_tdb_password) != 0)) {
127                 talloc_free(mem_ctx);
128                 return NT_STATUS_NOT_FOUND;
129         }
130
131         cli_credentials_set_password_last_changed_time(cred, lct);
132
133         machine_account = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
134
135         if (!machine_account) {
136                 machine_account = ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL);
137
138                 if (!machine_account) {
139                         const char *ldap_bind_dn = ldb_msg_find_attr_as_string(msg, "ldapBindDn", NULL);
140                         if (!ldap_bind_dn) {
141                                 *error_string = talloc_asprintf(cred,
142                                                                 "Could not find 'samAccountName', "
143                                                                 "'servicePrincipalName' or "
144                                                                 "'ldapBindDn' in secrets record: %s",
145                                                                 ldb_dn_get_linearized(msg->dn));
146                                 talloc_free(mem_ctx);
147                                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
148                         } else {
149                                 /* store bind dn in credentials */
150                                 cli_credentials_set_bind_dn(cred, ldap_bind_dn);
151                         }
152                 }
153         }
154
155         salt_principal = ldb_msg_find_attr_as_string(msg, "saltPrincipal", NULL);
156         cli_credentials_set_salt_principal(cred, salt_principal);
157
158         sct = ldb_msg_find_attr_as_int(msg, "secureChannelType", 0);
159         if (sct) {
160                 cli_credentials_set_secure_channel_type(cred, sct);
161         }
162
163         if (!password) {
164                 const struct ldb_val *nt_password_hash = ldb_msg_find_ldb_val(msg, "unicodePwd");
165                 struct samr_Password hash;
166                 ZERO_STRUCT(hash);
167                 if (nt_password_hash) {
168                         memcpy(hash.hash, nt_password_hash->data,
169                                MIN(nt_password_hash->length, sizeof(hash.hash)));
170
171                         cli_credentials_set_nt_hash(cred, &hash, CRED_SPECIFIED);
172                 } else {
173                         cli_credentials_set_password(cred, NULL, CRED_SPECIFIED);
174                 }
175         } else {
176                 cli_credentials_set_password(cred, password, CRED_SPECIFIED);
177         }
178
179         domain = ldb_msg_find_attr_as_string(msg, "flatname", NULL);
180         if (domain) {
181                 cli_credentials_set_domain(cred, domain, CRED_SPECIFIED);
182         }
183
184         realm = ldb_msg_find_attr_as_string(msg, "realm", NULL);
185         if (realm) {
186                 cli_credentials_set_realm(cred, realm, CRED_SPECIFIED);
187         }
188
189         if (machine_account) {
190                 cli_credentials_set_username(cred, machine_account, CRED_SPECIFIED);
191         }
192
193         cli_credentials_set_kvno(cred, ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0));
194
195         /* If there was an external keytab specified by reference in
196          * the LDB, then use this.  Otherwise we will make one up
197          * (chewing CPU time) from the password */
198         keytab = keytab_name_from_msg(cred, ldb, msg);
199         if (keytab) {
200                 cli_credentials_set_keytab_name(cred, lp_ctx, keytab, CRED_SPECIFIED);
201                 talloc_free(keytab);
202         }
203         talloc_free(mem_ctx);
204
205         return NT_STATUS_OK;
206 }
207
208
209 /**
210  * Fill in credentials for the machine trust account, from the secrets database.
211  *
212  * @param cred Credentials structure to fill in
213  * @retval NTSTATUS error detailing any failure
214  */
215 _PUBLIC_ NTSTATUS cli_credentials_set_secrets(struct cli_credentials *cred,
216                                               struct loadparm_context *lp_ctx,
217                                               struct ldb_context *ldb,
218                                               const char *base,
219                                               const char *filter,
220                                               char **error_string)
221 {
222         NTSTATUS status = cli_credentials_set_secrets_lct(cred, lp_ctx, ldb, base, filter, 0, NULL, error_string);
223         if (!NT_STATUS_IS_OK(status)) {
224                 /* set anonymous as the fallback, if the machine account won't work */
225                 cli_credentials_set_anonymous(cred);
226         }
227         return status;
228 }
229
230 /**
231  * Fill in credentials for the machine trust account, from the secrets database.
232  *
233  * @param cred Credentials structure to fill in
234  * @retval NTSTATUS error detailing any failure
235  */
236 _PUBLIC_ NTSTATUS cli_credentials_set_machine_account(struct cli_credentials *cred,
237                                                       struct loadparm_context *lp_ctx)
238 {
239         struct db_context *db_ctx;
240         char *secrets_tdb_path;
241         int hash_size, tdb_flags;
242
243         secrets_tdb_path = lpcfg_private_db_path(cred, lp_ctx, "secrets");
244         if (secrets_tdb_path == NULL) {
245                 return NT_STATUS_NO_MEMORY;
246         }
247
248         hash_size = lpcfg_tdb_hash_size(lp_ctx, secrets_tdb_path);
249         tdb_flags = lpcfg_tdb_flags(lp_ctx, TDB_DEFAULT);
250
251         db_ctx = dbwrap_local_open(
252                 cred,
253                 secrets_tdb_path,
254                 hash_size,
255                 tdb_flags,
256                 O_RDWR,
257                 0600,
258                 DBWRAP_LOCK_ORDER_1,
259                 DBWRAP_FLAG_NONE);
260         TALLOC_FREE(secrets_tdb_path);
261
262         /*
263          * We do not check for errors here, we might not have a
264          * secrets.tdb at all, and so we just need to check the
265          * secrets.ldb
266          */
267         return cli_credentials_set_machine_account_db_ctx(cred, lp_ctx, db_ctx);
268 }
269
270 /**
271  * Fill in credentials for the machine trust account, from the
272  * secrets.ldb or passed in handle to secrets.tdb (perhaps in CTDB).
273  *
274  * This version is used in parts of the code that can link in the
275  * CTDB dbwrap backend, by passing down the already open handle.
276  *
277  * @param cred Credentials structure to fill in
278  * @param db_ctx dbwrap context for secrets.tdb
279  * @retval NTSTATUS error detailing any failure
280  */
281 _PUBLIC_ NTSTATUS cli_credentials_set_machine_account_db_ctx(struct cli_credentials *cred,
282                                                              struct loadparm_context *lp_ctx,
283                                                              struct db_context *db_ctx)
284 {
285         NTSTATUS status;
286         char *filter;
287         char *error_string = NULL;
288         const char *domain;
289         bool secrets_tdb_password_more_recent;
290         time_t secrets_tdb_lct = 0;
291         char *secrets_tdb_password = NULL;
292         char *secrets_tdb_old_password = NULL;
293         uint32_t secrets_tdb_secure_channel_type = SEC_CHAN_NULL;
294         int server_role = lpcfg_server_role(lp_ctx);
295         int security = lpcfg_security(lp_ctx);
296         char *keystr;
297         char *keystr_upper = NULL;
298         TALLOC_CTX *tmp_ctx = talloc_named(cred, 0, "cli_credentials_set_secrets from ldb");
299         if (!tmp_ctx) {
300                 return NT_STATUS_NO_MEMORY;
301         }
302
303         /* Bleh, nasty recursion issues: We are setting a machine
304          * account here, so we don't want the 'pending' flag around
305          * any more */
306         SMB_ASSERT(cred->machine_account_pending == false);
307         cred->machine_account_pending = false;
308
309         /* We have to do this, as the fallback in
310          * cli_credentials_set_secrets is to run as anonymous, so the domain is wiped */
311         domain = cli_credentials_get_domain(cred);
312
313         if (db_ctx) {
314                 TDB_DATA dbuf;
315                 keystr = talloc_asprintf(tmp_ctx, "%s/%s",
316                                          SECRETS_MACHINE_LAST_CHANGE_TIME,
317                                          domain);
318                 keystr_upper = strupper_talloc(tmp_ctx, keystr);
319                 status = dbwrap_fetch(db_ctx, tmp_ctx, string_tdb_data(keystr_upper),
320                                       &dbuf);
321                 if (NT_STATUS_IS_OK(status) && dbuf.dsize == 4) {
322                         secrets_tdb_lct = IVAL(dbuf.dptr,0);
323                 }
324
325                 keystr = talloc_asprintf(tmp_ctx, "%s/%s",
326                                          SECRETS_MACHINE_PASSWORD,
327                                          domain);
328                 keystr_upper = strupper_talloc(tmp_ctx, keystr);
329                 status = dbwrap_fetch(db_ctx, tmp_ctx, string_tdb_data(keystr_upper),
330                                       &dbuf);
331                 if (NT_STATUS_IS_OK(status)) {
332                         secrets_tdb_password = (char *)dbuf.dptr;
333                 }
334
335                 keystr = talloc_asprintf(tmp_ctx, "%s/%s",
336                                          SECRETS_MACHINE_PASSWORD_PREV,
337                                          domain);
338                 keystr_upper = strupper_talloc(tmp_ctx, keystr);
339                 status = dbwrap_fetch(db_ctx, tmp_ctx, string_tdb_data(keystr_upper),
340                                       &dbuf);
341                 if (NT_STATUS_IS_OK(status)) {
342                         secrets_tdb_old_password = (char *)dbuf.dptr;
343                 }
344
345                 keystr = talloc_asprintf(tmp_ctx, "%s/%s",
346                                          SECRETS_MACHINE_SEC_CHANNEL_TYPE,
347                                          domain);
348                 keystr_upper = strupper_talloc(tmp_ctx, keystr);
349                 status = dbwrap_fetch(db_ctx, tmp_ctx, string_tdb_data(keystr_upper),
350                                       &dbuf);
351                 if (NT_STATUS_IS_OK(status) && dbuf.dsize == 4) {
352                         secrets_tdb_secure_channel_type = IVAL(dbuf.dptr,0);
353                 }
354         }
355
356         filter = talloc_asprintf(cred, SECRETS_PRIMARY_DOMAIN_FILTER, 
357                                  domain);
358         status = cli_credentials_set_secrets_lct(cred, lp_ctx, NULL,
359                                                  SECRETS_PRIMARY_DOMAIN_DN,
360                                                  filter, secrets_tdb_lct, secrets_tdb_password, &error_string);
361         if (secrets_tdb_password == NULL) {
362                 secrets_tdb_password_more_recent = false;
363         } else if (NT_STATUS_EQUAL(NT_STATUS_CANT_ACCESS_DOMAIN_INFO, status)
364             || NT_STATUS_EQUAL(NT_STATUS_NOT_FOUND, status)) {
365                 secrets_tdb_password_more_recent = true;
366         } else if (secrets_tdb_lct > cli_credentials_get_password_last_changed_time(cred)) {
367                 secrets_tdb_password_more_recent = true;
368         } else if (secrets_tdb_lct == cli_credentials_get_password_last_changed_time(cred)) {
369                 secrets_tdb_password_more_recent = strcmp(secrets_tdb_password, cli_credentials_get_password(cred)) != 0;
370         } else {
371                 secrets_tdb_password_more_recent = false;
372         }
373
374         if (secrets_tdb_password_more_recent) {
375                 enum credentials_use_kerberos use_kerberos = CRED_DONT_USE_KERBEROS;
376                 char *machine_account = talloc_asprintf(tmp_ctx, "%s$", lpcfg_netbios_name(lp_ctx));
377                 cli_credentials_set_password(cred, secrets_tdb_password, CRED_SPECIFIED);
378                 cli_credentials_set_old_password(cred, secrets_tdb_old_password, CRED_SPECIFIED);
379                 cli_credentials_set_domain(cred, domain, CRED_SPECIFIED);
380                 if (strequal(domain, lpcfg_workgroup(lp_ctx))) {
381                         cli_credentials_set_realm(cred, lpcfg_realm(lp_ctx), CRED_SPECIFIED);
382
383                         switch (server_role) {
384                         case ROLE_DOMAIN_MEMBER:
385                                 if (security != SEC_ADS) {
386                                         break;
387                                 }
388
389                                 FALL_THROUGH;
390                         case ROLE_ACTIVE_DIRECTORY_DC:
391                                 use_kerberos = CRED_AUTO_USE_KERBEROS;
392                                 break;
393                         }
394                 }
395                 cli_credentials_set_kerberos_state(cred, use_kerberos);
396                 cli_credentials_set_username(cred, machine_account, CRED_SPECIFIED);
397                 cli_credentials_set_password_last_changed_time(cred, secrets_tdb_lct);
398                 cli_credentials_set_secure_channel_type(cred, secrets_tdb_secure_channel_type);
399                 status = NT_STATUS_OK;
400         } else if (!NT_STATUS_IS_OK(status)) {
401                 if (db_ctx) {
402                         error_string
403                                 = talloc_asprintf(cred,
404                                                   "Failed to fetch machine account password for %s from both "
405                                                   "secrets.ldb (%s) and from %s",
406                                                   domain,
407                                                   error_string == NULL ? "error" : error_string,
408                                                   dbwrap_name(db_ctx));
409                 } else {
410                         char *secrets_tdb_path;
411
412                         secrets_tdb_path = lpcfg_private_db_path(tmp_ctx,
413                                                                  lp_ctx,
414                                                                  "secrets");
415                         if (secrets_tdb_path == NULL) {
416                                 return NT_STATUS_NO_MEMORY;
417                         }
418
419                         error_string = talloc_asprintf(cred,
420                                                        "Failed to fetch machine account password from "
421                                                        "secrets.ldb: %s and failed to open %s",
422                                                        error_string == NULL ? "error" : error_string,
423                                                        secrets_tdb_path);
424                 }
425                 DEBUG(1, ("Could not find machine account in secrets database: %s: %s\n",
426                           error_string == NULL ? "error" : error_string,
427                           nt_errstr(status)));
428                 /* set anonymous as the fallback, if the machine account won't work */
429                 cli_credentials_set_anonymous(cred);
430         }
431
432         TALLOC_FREE(tmp_ctx);
433         return status;
434 }
435
436 /**
437  * Fill in credentials for a particular principal, from the secrets database.
438  *
439  * @param cred Credentials structure to fill in
440  * @retval NTSTATUS error detailing any failure
441  */
442 _PUBLIC_ NTSTATUS cli_credentials_set_stored_principal(struct cli_credentials *cred,
443                                               struct loadparm_context *lp_ctx,
444                                               const char *serviceprincipal)
445 {
446         NTSTATUS status;
447         char *filter;
448         char *error_string = NULL;
449         /* Bleh, nasty recursion issues: We are setting a machine
450          * account here, so we don't want the 'pending' flag around
451          * any more */
452         cred->machine_account_pending = false;
453         filter = talloc_asprintf(cred, SECRETS_PRINCIPAL_SEARCH,
454                                  cli_credentials_get_realm(cred),
455                                  cli_credentials_get_domain(cred),
456                                  serviceprincipal);
457         status = cli_credentials_set_secrets_lct(cred, lp_ctx, NULL,
458                                              SECRETS_PRINCIPALS_DN, filter,
459                                              0, NULL, &error_string);
460         if (!NT_STATUS_IS_OK(status)) {
461                 DEBUG(1, ("Could not find %s principal in secrets database: %s: %s\n",
462                           serviceprincipal, nt_errstr(status),
463                           error_string ? error_string : "<no error>"));
464         }
465         return status;
466 }
467
468 /**
469  * Ask that when required, the credentials system will be filled with
470  * machine trust account, from the secrets database.
471  *
472  * @param cred Credentials structure to fill in
473  * @note This function is used to call the above function after, rather
474  *       than during, popt processing.
475  *
476  */
477 _PUBLIC_ void cli_credentials_set_machine_account_pending(struct cli_credentials *cred,
478                                                  struct loadparm_context *lp_ctx)
479 {
480         cred->machine_account_pending = true;
481         cred->machine_account_pending_lp_ctx = lp_ctx;
482 }
483
484