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