s4:kdc Use better db context structure
[Samba.git] / source4 / kdc / hdb-samba4.c
blob33575bd8ea4106cad511c3b68d368094f5166300
1 /*
2 * Copyright (c) 1999-2001, 2003, PADL Software Pty Ltd.
3 * Copyright (c) 2004-2009, Andrew Bartlett <abartlet@samba.org>.
4 * Copyright (c) 2004, Stefan Metzmacher <metze@samba.org>
5 * All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of PADL Software nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
35 #include "includes.h"
36 #include "system/time.h"
37 #include "../libds/common/flags.h"
38 #include "lib/ldb/include/ldb.h"
39 #include "lib/ldb/include/ldb_errors.h"
40 #include "librpc/gen_ndr/netlogon.h"
41 #include "libcli/security/security.h"
42 #include "auth/auth.h"
43 #include "auth/credentials/credentials.h"
44 #include "auth/auth_sam.h"
45 #include "../lib/util/util_ldb.h"
46 #include "dsdb/samdb/samdb.h"
47 #include "librpc/ndr/libndr.h"
48 #include "librpc/gen_ndr/ndr_drsblobs.h"
49 #include "librpc/gen_ndr/lsa.h"
50 #include "libcli/auth/libcli_auth.h"
51 #include "param/param.h"
52 #include "events/events.h"
53 #include "kdc/kdc.h"
54 #include "../lib/crypto/md4.h"
56 enum hdb_samba4_ent_type
57 { HDB_SAMBA4_ENT_TYPE_CLIENT, HDB_SAMBA4_ENT_TYPE_SERVER,
58 HDB_SAMBA4_ENT_TYPE_KRBTGT, HDB_SAMBA4_ENT_TYPE_TRUST, HDB_SAMBA4_ENT_TYPE_ANY };
60 enum trust_direction {
61 UNKNOWN = 0,
62 INBOUND = LSA_TRUST_DIRECTION_INBOUND,
63 OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
66 static const char *trust_attrs[] = {
67 "trustPartner",
68 "trustAuthIncoming",
69 "trustAuthOutgoing",
70 "whenCreated",
71 "msDS-SupportedEncryptionTypes",
72 "trustAttributes",
73 "trustDirection",
74 "trustType",
75 NULL
78 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
80 const char *tmp;
81 const char *gentime;
82 struct tm tm;
84 gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
85 if (!gentime)
86 return default_val;
88 tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
89 if (tmp == NULL) {
90 return default_val;
93 return timegm(&tm);
96 static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_samba4_ent_type ent_type)
98 HDBFlags flags = int2HDBFlags(0);
100 /* we don't allow kadmin deletes */
101 flags.immutable = 1;
103 /* mark the principal as invalid to start with */
104 flags.invalid = 1;
106 flags.renewable = 1;
108 /* All accounts are servers, but this may be disabled again in the caller */
109 flags.server = 1;
111 /* Account types - clear the invalid bit if it turns out to be valid */
112 if (userAccountControl & UF_NORMAL_ACCOUNT) {
113 if (ent_type == HDB_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) {
114 flags.client = 1;
116 flags.invalid = 0;
119 if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
120 if (ent_type == HDB_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) {
121 flags.client = 1;
123 flags.invalid = 0;
125 if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
126 if (ent_type == HDB_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) {
127 flags.client = 1;
129 flags.invalid = 0;
131 if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
132 if (ent_type == HDB_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) {
133 flags.client = 1;
135 flags.invalid = 0;
138 /* Not permitted to act as a client if disabled */
139 if (userAccountControl & UF_ACCOUNTDISABLE) {
140 flags.client = 0;
142 if (userAccountControl & UF_LOCKOUT) {
143 flags.invalid = 1;
146 if (userAccountControl & UF_PASSWORD_NOTREQD) {
147 flags.invalid = 1;
151 UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
153 if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
154 flags.invalid = 1;
157 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in hdb_samba4_message2entry() */
160 if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
161 flags.invalid = 1;
164 if (userAccountControl & UF_SMARTCARD_REQUIRED) {
165 flags.require_hwauth = 1;
167 if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
168 flags.ok_as_delegate = 1;
170 if (!(userAccountControl & UF_NOT_DELEGATED)) {
171 flags.forwardable = 1;
172 flags.proxiable = 1;
175 if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
176 flags.require_preauth = 0;
177 } else {
178 flags.require_preauth = 1;
181 return flags;
184 static int hdb_samba4_destructor(struct hdb_samba4_private *p)
186 hdb_entry_ex *entry_ex = p->entry_ex;
187 free_hdb_entry(&entry_ex->entry);
188 return 0;
191 static void hdb_samba4_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
193 talloc_free(entry_ex->ctx);
196 static krb5_error_code hdb_samba4_message2entry_keys(krb5_context context,
197 struct smb_iconv_convenience *iconv_convenience,
198 TALLOC_CTX *mem_ctx,
199 struct ldb_message *msg,
200 unsigned int userAccountControl,
201 hdb_entry_ex *entry_ex)
203 krb5_error_code ret = 0;
204 enum ndr_err_code ndr_err;
205 struct samr_Password *hash;
206 const struct ldb_val *sc_val;
207 struct supplementalCredentialsBlob scb;
208 struct supplementalCredentialsPackage *scpk = NULL;
209 bool newer_keys = false;
210 struct package_PrimaryKerberosBlob _pkb;
211 struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
212 struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
213 uint32_t i;
214 uint32_t allocated_keys = 0;
216 entry_ex->entry.keys.val = NULL;
217 entry_ex->entry.keys.len = 0;
219 entry_ex->entry.kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
221 /* Get keys from the db */
223 hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
224 sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
226 /* unicodePwd for enctype 0x17 (23) if present */
227 if (hash) {
228 allocated_keys++;
231 /* supplementalCredentials if present */
232 if (sc_val) {
233 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, iconv_convenience, &scb,
234 (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
235 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
236 dump_data(0, sc_val->data, sc_val->length);
237 ret = EINVAL;
238 goto out;
241 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
242 NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
243 ret = EINVAL;
244 goto out;
247 for (i=0; i < scb.sub.num_packages; i++) {
248 if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
249 scpk = &scb.sub.packages[i];
250 if (!scpk->data || !scpk->data[0]) {
251 scpk = NULL;
252 continue;
254 newer_keys = true;
255 break;
256 } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
257 scpk = &scb.sub.packages[i];
258 if (!scpk->data || !scpk->data[0]) {
259 scpk = NULL;
262 * we don't break here in hope to find
263 * a Kerberos-Newer-Keys package
269 * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
270 * of supplementalCredentials
272 if (scpk) {
273 DATA_BLOB blob;
275 blob = strhex_to_data_blob(mem_ctx, scpk->data);
276 if (!blob.data) {
277 ret = ENOMEM;
278 goto out;
281 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
282 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, iconv_convenience, &_pkb,
283 (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
284 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
285 ret = EINVAL;
286 krb5_set_error_message(context, ret, "hdb_samba4_message2entry_keys: could not parse package_PrimaryKerberosBlob");
287 krb5_warnx(context, "hdb_samba4_message2entry_keys: could not parse package_PrimaryKerberosBlob");
288 goto out;
291 if (newer_keys && _pkb.version != 4) {
292 ret = EINVAL;
293 krb5_set_error_message(context, ret, "hdb_samba4_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
294 krb5_warnx(context, "hdb_samba4_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
295 goto out;
298 if (!newer_keys && _pkb.version != 3) {
299 ret = EINVAL;
300 krb5_set_error_message(context, ret, "hdb_samba4_message2entry_keys: could not parse Primary:Kerberos not version 3");
301 krb5_warnx(context, "hdb_samba4_message2entry_keys: could not parse Primary:Kerberos not version 3");
302 goto out;
305 if (_pkb.version == 4) {
306 pkb4 = &_pkb.ctr.ctr4;
307 allocated_keys += pkb4->num_keys;
308 } else if (_pkb.version == 3) {
309 pkb3 = &_pkb.ctr.ctr3;
310 allocated_keys += pkb3->num_keys;
314 if (allocated_keys == 0) {
315 /* oh, no password. Apparently (comment in
316 * hdb-ldap.c) this violates the ASN.1, but this
317 * allows an entry with no keys (yet). */
318 return 0;
321 /* allocate space to decode into */
322 entry_ex->entry.keys.len = 0;
323 entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
324 if (entry_ex->entry.keys.val == NULL) {
325 ret = ENOMEM;
326 goto out;
329 if (hash && !(userAccountControl & UF_USE_DES_KEY_ONLY)) {
330 Key key;
332 key.mkvno = 0;
333 key.salt = NULL; /* No salt for this enc type */
335 ret = krb5_keyblock_init(context,
336 ENCTYPE_ARCFOUR_HMAC,
337 hash->hash, sizeof(hash->hash),
338 &key.key);
339 if (ret) {
340 goto out;
343 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
344 entry_ex->entry.keys.len++;
347 if (pkb4) {
348 for (i=0; i < pkb4->num_keys; i++) {
349 bool use = true;
350 Key key;
352 if (!pkb4->keys[i].value) continue;
354 if (userAccountControl & UF_USE_DES_KEY_ONLY) {
355 switch (pkb4->keys[i].keytype) {
356 case ENCTYPE_DES_CBC_CRC:
357 case ENCTYPE_DES_CBC_MD5:
358 break;
359 default:
360 use = false;
361 break;
365 if (!use) continue;
367 key.mkvno = 0;
368 key.salt = NULL;
370 if (pkb4->salt.string) {
371 DATA_BLOB salt;
373 salt = data_blob_string_const(pkb4->salt.string);
375 key.salt = calloc(1, sizeof(*key.salt));
376 if (key.salt == NULL) {
377 ret = ENOMEM;
378 goto out;
381 key.salt->type = hdb_pw_salt;
383 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
384 if (ret) {
385 free(key.salt);
386 key.salt = NULL;
387 goto out;
391 /* TODO: maybe pass the iteration_count somehow... */
393 ret = krb5_keyblock_init(context,
394 pkb4->keys[i].keytype,
395 pkb4->keys[i].value->data,
396 pkb4->keys[i].value->length,
397 &key.key);
398 if (ret == KRB5_PROG_ETYPE_NOSUPP) {
399 DEBUG(2,("Unsupported keytype ignored - type %u\n",
400 pkb4->keys[i].keytype));
401 ret = 0;
402 continue;
404 if (ret) {
405 if (key.salt) {
406 free_Salt(key.salt);
407 free(key.salt);
408 key.salt = NULL;
410 goto out;
413 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
414 entry_ex->entry.keys.len++;
416 } else if (pkb3) {
417 for (i=0; i < pkb3->num_keys; i++) {
418 bool use = true;
419 Key key;
421 if (!pkb3->keys[i].value) continue;
423 if (userAccountControl & UF_USE_DES_KEY_ONLY) {
424 switch (pkb3->keys[i].keytype) {
425 case ENCTYPE_DES_CBC_CRC:
426 case ENCTYPE_DES_CBC_MD5:
427 break;
428 default:
429 use = false;
430 break;
434 if (!use) continue;
436 key.mkvno = 0;
437 key.salt = NULL;
439 if (pkb3->salt.string) {
440 DATA_BLOB salt;
442 salt = data_blob_string_const(pkb3->salt.string);
444 key.salt = calloc(1, sizeof(*key.salt));
445 if (key.salt == NULL) {
446 ret = ENOMEM;
447 goto out;
450 key.salt->type = hdb_pw_salt;
452 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
453 if (ret) {
454 free(key.salt);
455 key.salt = NULL;
456 goto out;
460 ret = krb5_keyblock_init(context,
461 pkb3->keys[i].keytype,
462 pkb3->keys[i].value->data,
463 pkb3->keys[i].value->length,
464 &key.key);
465 if (ret) {
466 if (key.salt) {
467 free_Salt(key.salt);
468 free(key.salt);
469 key.salt = NULL;
471 goto out;
474 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
475 entry_ex->entry.keys.len++;
479 out:
480 if (ret != 0) {
481 entry_ex->entry.keys.len = 0;
483 if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
484 free(entry_ex->entry.keys.val);
485 entry_ex->entry.keys.val = NULL;
487 return ret;
491 * Construct an hdb_entry from a directory entry.
493 static krb5_error_code hdb_samba4_message2entry(krb5_context context,
494 struct samba_kdc_db_context *kdc_db_ctx,
495 struct loadparm_context *lp_ctx,
496 TALLOC_CTX *mem_ctx, krb5_const_principal principal,
497 enum hdb_samba4_ent_type ent_type,
498 struct ldb_dn *realm_dn,
499 struct ldb_message *msg,
500 hdb_entry_ex *entry_ex)
502 unsigned int userAccountControl;
503 int i;
504 krb5_error_code ret = 0;
505 krb5_boolean is_computer = FALSE;
506 char *realm = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
508 struct hdb_samba4_private *p;
509 NTTIME acct_expiry;
510 NTSTATUS status;
512 uint32_t rid;
513 struct ldb_message_element *objectclasses;
514 struct ldb_val computer_val;
515 const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
516 computer_val.data = discard_const_p(uint8_t,"computer");
517 computer_val.length = strlen((const char *)computer_val.data);
519 if (!samAccountName) {
520 ret = ENOENT;
521 krb5_set_error_message(context, ret, "hdb_samba4_message2entry: no samAccountName present");
522 goto out;
525 objectclasses = ldb_msg_find_element(msg, "objectClass");
527 if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
528 is_computer = TRUE;
531 memset(entry_ex, 0, sizeof(*entry_ex));
533 if (!realm) {
534 ret = ENOMEM;
535 krb5_set_error_message(context, ret, "talloc_strdup: out of memory");
536 goto out;
539 p = talloc(mem_ctx, struct hdb_samba4_private);
540 if (!p) {
541 ret = ENOMEM;
542 goto out;
545 p->entry_ex = entry_ex;
546 p->iconv_convenience = lp_iconv_convenience(lp_ctx);
547 p->lp_ctx = lp_ctx;
548 p->realm_dn = talloc_reference(p, realm_dn);
549 if (!p->realm_dn) {
550 ret = ENOMEM;
551 goto out;
554 talloc_set_destructor(p, hdb_samba4_destructor);
556 entry_ex->ctx = p;
557 entry_ex->free_entry = hdb_samba4_free_entry;
559 userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
562 entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
563 if (ent_type == HDB_SAMBA4_ENT_TYPE_ANY && principal == NULL) {
564 krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL);
565 } else {
566 ret = copy_Principal(principal, entry_ex->entry.principal);
567 if (ret) {
568 krb5_clear_error_message(context);
569 goto out;
572 /* While we have copied the client principal, tests
573 * show that Win2k3 returns the 'corrected' realm, not
574 * the client-specified realm. This code attempts to
575 * replace the client principal's realm with the one
576 * we determine from our records */
578 /* this has to be with malloc() */
579 krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
582 /* First try and figure out the flags based on the userAccountControl */
583 entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
585 /* Windows 2008 seems to enforce this (very sensible) rule by
586 * default - don't allow offline attacks on a user's password
587 * by asking for a ticket to them as a service (encrypted with
588 * their probably patheticly insecure password) */
590 if (entry_ex->entry.flags.server
591 && lp_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
592 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
593 entry_ex->entry.flags.server = 0;
598 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
599 * of the Heimdal KDC. They are stored in a the traditional
600 * DB for audit purposes, and still form part of the structure
601 * we must return */
603 /* use 'whenCreated' */
604 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
605 /* use '???' */
606 entry_ex->entry.created_by.principal = NULL;
608 entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
609 if (entry_ex->entry.modified_by == NULL) {
610 ret = ENOMEM;
611 krb5_set_error_message(context, ret, "malloc: out of memory");
612 goto out;
615 /* use 'whenChanged' */
616 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
617 /* use '???' */
618 entry_ex->entry.modified_by->principal = NULL;
622 /* The lack of password controls etc applies to krbtgt by
623 * virtue of being that particular RID */
624 status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
626 if (!NT_STATUS_IS_OK(status)) {
627 ret = EINVAL;
628 goto out;
631 if (rid == DOMAIN_RID_KRBTGT) {
632 entry_ex->entry.valid_end = NULL;
633 entry_ex->entry.pw_end = NULL;
635 entry_ex->entry.flags.invalid = 0;
636 entry_ex->entry.flags.server = 1;
638 /* Don't mark all requests for the krbtgt/realm as
639 * 'change password', as otherwise we could get into
640 * trouble, and not enforce the password expirty.
641 * Instead, only do it when request is for the kpasswd service */
642 if (ent_type == HDB_SAMBA4_ENT_TYPE_SERVER
643 && principal->name.name_string.len == 2
644 && (strcmp(principal->name.name_string.val[0], "kadmin") == 0)
645 && (strcmp(principal->name.name_string.val[1], "changepw") == 0)
646 && lp_is_my_domain_or_realm(lp_ctx, principal->realm)) {
647 entry_ex->entry.flags.change_pw = 1;
649 entry_ex->entry.flags.client = 0;
650 entry_ex->entry.flags.forwardable = 1;
651 entry_ex->entry.flags.ok_as_delegate = 1;
652 } else if (entry_ex->entry.flags.server && ent_type == HDB_SAMBA4_ENT_TYPE_SERVER) {
653 /* The account/password expiry only applies when the account is used as a
654 * client (ie password login), not when used as a server */
656 /* Make very well sure we don't use this for a client,
657 * it could bypass the password restrictions */
658 entry_ex->entry.flags.client = 0;
660 entry_ex->entry.valid_end = NULL;
661 entry_ex->entry.pw_end = NULL;
663 } else {
664 NTTIME must_change_time
665 = samdb_result_force_password_change(kdc_db_ctx->samdb, mem_ctx,
666 realm_dn, msg);
667 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
668 entry_ex->entry.pw_end = NULL;
669 } else {
670 entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
671 if (entry_ex->entry.pw_end == NULL) {
672 ret = ENOMEM;
673 goto out;
675 *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
678 acct_expiry = samdb_result_account_expires(msg);
679 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
680 entry_ex->entry.valid_end = NULL;
681 } else {
682 entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
683 if (entry_ex->entry.valid_end == NULL) {
684 ret = ENOMEM;
685 goto out;
687 *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
691 entry_ex->entry.valid_start = NULL;
693 entry_ex->entry.max_life = NULL;
695 entry_ex->entry.max_renew = NULL;
697 entry_ex->entry.generation = NULL;
699 /* Get keys from the db */
700 ret = hdb_samba4_message2entry_keys(context, p->iconv_convenience, p, msg, userAccountControl, entry_ex);
701 if (ret) {
702 /* Could be bougus data in the entry, or out of memory */
703 goto out;
706 entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
707 if (entry_ex->entry.etypes == NULL) {
708 krb5_clear_error_message(context);
709 ret = ENOMEM;
710 goto out;
712 entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
713 entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
714 if (entry_ex->entry.etypes->val == NULL) {
715 krb5_clear_error_message(context);
716 ret = ENOMEM;
717 goto out;
719 for (i=0; i < entry_ex->entry.etypes->len; i++) {
720 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
724 p->msg = talloc_steal(p, msg);
725 p->samdb = kdc_db_ctx->samdb;
727 out:
728 if (ret != 0) {
729 /* This doesn't free ent itself, that is for the eventual caller to do */
730 hdb_free_entry(context, entry_ex);
731 } else {
732 talloc_steal(kdc_db_ctx, entry_ex->ctx);
735 return ret;
739 * Construct an hdb_entry from a directory entry.
741 static krb5_error_code hdb_samba4_trust_message2entry(krb5_context context,
742 struct samba_kdc_db_context *kdc_db_ctx,
743 struct loadparm_context *lp_ctx,
744 TALLOC_CTX *mem_ctx, krb5_const_principal principal,
745 enum trust_direction direction,
746 struct ldb_dn *realm_dn,
747 struct ldb_message *msg,
748 hdb_entry_ex *entry_ex)
751 const char *dnsdomain;
752 char *realm;
753 DATA_BLOB password_utf16;
754 struct samr_Password password_hash;
755 const struct ldb_val *password_val;
756 struct trustAuthInOutBlob password_blob;
757 struct hdb_samba4_private *p;
759 enum ndr_err_code ndr_err;
760 int i, ret, trust_direction_flags;
762 p = talloc(mem_ctx, struct hdb_samba4_private);
763 if (!p) {
764 ret = ENOMEM;
765 goto out;
768 p->entry_ex = entry_ex;
769 p->iconv_convenience = lp_iconv_convenience(lp_ctx);
770 p->lp_ctx = lp_ctx;
771 p->realm_dn = realm_dn;
773 talloc_set_destructor(p, hdb_samba4_destructor);
775 entry_ex->ctx = p;
776 entry_ex->free_entry = hdb_samba4_free_entry;
778 /* use 'whenCreated' */
779 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
780 /* use '???' */
781 entry_ex->entry.created_by.principal = NULL;
783 entry_ex->entry.valid_start = NULL;
785 trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
787 if (direction == INBOUND) {
788 realm = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
789 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
791 } else { /* OUTBOUND */
792 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
793 realm = strupper_talloc(mem_ctx, dnsdomain);
794 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
797 if (!password_val || !(trust_direction_flags & direction)) {
798 ret = ENOENT;
799 goto out;
802 ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, p->iconv_convenience, &password_blob,
803 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
804 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
805 ret = EINVAL;
806 goto out;
809 entry_ex->entry.kvno = -1;
810 for (i=0; i < password_blob.count; i++) {
811 if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_VERSION) {
812 entry_ex->entry.kvno = password_blob.current->array[i].AuthInfo.version.version;
816 for (i=0; i < password_blob.count; i++) {
817 if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
818 password_utf16 = data_blob_const(password_blob.current->array[i].AuthInfo.clear.password,
819 password_blob.current->array[i].AuthInfo.clear.size);
820 /* In the future, generate all sorts of
821 * hashes, but for now we can't safely convert
822 * the random strings windows uses into
823 * utf8 */
825 /* but as it is utf16 already, we can get the NT password/arcfour-hmac-md5 key */
826 mdfour(password_hash.hash, password_utf16.data, password_utf16.length);
827 break;
828 } else if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
829 password_hash = password_blob.current->array[i].AuthInfo.nt4owf.password;
830 break;
833 entry_ex->entry.keys.len = 0;
834 entry_ex->entry.keys.val = NULL;
836 if (i < password_blob.count) {
837 Key key;
838 /* Must have found a cleartext or MD4 password */
839 entry_ex->entry.keys.val = calloc(1, sizeof(Key));
841 key.mkvno = 0;
842 key.salt = NULL; /* No salt for this enc type */
844 if (entry_ex->entry.keys.val == NULL) {
845 ret = ENOMEM;
846 goto out;
849 ret = krb5_keyblock_init(context,
850 ENCTYPE_ARCFOUR_HMAC,
851 password_hash.hash, sizeof(password_hash.hash),
852 &key.key);
854 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
855 entry_ex->entry.keys.len++;
858 entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
860 ret = copy_Principal(principal, entry_ex->entry.principal);
861 if (ret) {
862 krb5_clear_error_message(context);
863 goto out;
866 /* While we have copied the client principal, tests
867 * show that Win2k3 returns the 'corrected' realm, not
868 * the client-specified realm. This code attempts to
869 * replace the client principal's realm with the one
870 * we determine from our records */
872 krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
873 entry_ex->entry.flags = int2HDBFlags(0);
874 entry_ex->entry.flags.immutable = 1;
875 entry_ex->entry.flags.invalid = 0;
876 entry_ex->entry.flags.server = 1;
877 entry_ex->entry.flags.require_preauth = 1;
879 entry_ex->entry.pw_end = NULL;
881 entry_ex->entry.max_life = NULL;
883 entry_ex->entry.max_renew = NULL;
885 entry_ex->entry.generation = NULL;
887 entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
888 if (entry_ex->entry.etypes == NULL) {
889 krb5_clear_error_message(context);
890 ret = ENOMEM;
891 goto out;
893 entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
894 entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
895 if (entry_ex->entry.etypes->val == NULL) {
896 krb5_clear_error_message(context);
897 ret = ENOMEM;
898 goto out;
900 for (i=0; i < entry_ex->entry.etypes->len; i++) {
901 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
905 p->msg = talloc_steal(p, msg);
906 p->samdb = kdc_db_ctx->samdb;
908 out:
909 if (ret != 0) {
910 /* This doesn't free ent itself, that is for the eventual caller to do */
911 hdb_free_entry(context, entry_ex);
912 } else {
913 talloc_steal(kdc_db_ctx, entry_ex->ctx);
916 return ret;
920 static krb5_error_code hdb_samba4_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
921 TALLOC_CTX *mem_ctx,
922 const char *realm,
923 struct ldb_dn *realm_dn,
924 struct ldb_message **pmsg)
926 int lret;
927 krb5_error_code ret;
928 char *filter = NULL;
929 const char * const *attrs = trust_attrs;
931 struct ldb_result *res = NULL;
932 filter = talloc_asprintf(mem_ctx, "(&(objectClass=trustedDomain)(|(flatname=%s)(trustPartner=%s)))", realm, realm);
934 if (!filter) {
935 ret = ENOMEM;
936 krb5_set_error_message(context, ret, "talloc_asprintf: out of memory");
937 return ret;
940 lret = ldb_search(ldb_ctx, mem_ctx, &res,
941 ldb_get_default_basedn(ldb_ctx),
942 LDB_SCOPE_SUBTREE, attrs, "%s", filter);
943 if (lret != LDB_SUCCESS) {
944 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
945 return HDB_ERR_NOENTRY;
946 } else if (res->count == 0 || res->count > 1) {
947 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
948 talloc_free(res);
949 return HDB_ERR_NOENTRY;
951 talloc_steal(mem_ctx, res->msgs);
952 *pmsg = res->msgs[0];
953 talloc_free(res);
954 return 0;
957 static krb5_error_code hdb_samba4_open(krb5_context context, HDB *db, int flags, mode_t mode)
959 if (db->hdb_master_key_set) {
960 krb5_error_code ret = HDB_ERR_NOENTRY;
961 krb5_warnx(context, "hdb_samba4_open: use of a master key incompatible with LDB\n");
962 krb5_set_error_message(context, ret, "hdb_samba4_open: use of a master key incompatible with LDB\n");
963 return ret;
966 return 0;
969 static krb5_error_code hdb_samba4_close(krb5_context context, HDB *db)
971 return 0;
974 static krb5_error_code hdb_samba4_lock(krb5_context context, HDB *db, int operation)
976 return 0;
979 static krb5_error_code hdb_samba4_unlock(krb5_context context, HDB *db)
981 return 0;
984 static krb5_error_code hdb_samba4_rename(krb5_context context, HDB *db, const char *new_name)
986 return HDB_ERR_DB_INUSE;
989 static krb5_error_code hdb_samba4_lookup_client(krb5_context context,
990 struct samba_kdc_db_context *kdc_db_ctx,
991 struct loadparm_context *lp_ctx,
992 TALLOC_CTX *mem_ctx,
993 krb5_const_principal principal,
994 const char **attrs,
995 struct ldb_dn **realm_dn,
996 struct ldb_message **msg) {
997 NTSTATUS nt_status;
998 char *principal_string;
999 krb5_error_code ret;
1001 ret = krb5_unparse_name(context, principal, &principal_string);
1003 if (ret != 0) {
1004 return ret;
1007 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1008 mem_ctx, principal_string, attrs,
1009 realm_dn, msg);
1010 free(principal_string);
1011 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1012 return HDB_ERR_NOENTRY;
1013 } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1014 return ENOMEM;
1015 } else if (!NT_STATUS_IS_OK(nt_status)) {
1016 return EINVAL;
1019 return ret;
1022 static krb5_error_code hdb_samba4_fetch_client(krb5_context context,
1023 struct samba_kdc_db_context *kdc_db_ctx,
1024 struct loadparm_context *lp_ctx,
1025 TALLOC_CTX *mem_ctx,
1026 krb5_const_principal principal,
1027 unsigned flags,
1028 hdb_entry_ex *entry_ex) {
1029 struct ldb_dn *realm_dn;
1030 krb5_error_code ret;
1031 struct ldb_message *msg = NULL;
1033 ret = hdb_samba4_lookup_client(context, kdc_db_ctx, lp_ctx,
1034 mem_ctx, principal, user_attrs,
1035 &realm_dn, &msg);
1036 if (ret != 0) {
1037 return ret;
1040 ret = hdb_samba4_message2entry(context, kdc_db_ctx, lp_ctx, mem_ctx,
1041 principal, HDB_SAMBA4_ENT_TYPE_CLIENT,
1042 realm_dn, msg, entry_ex);
1043 return ret;
1046 static krb5_error_code hdb_samba4_fetch_krbtgt(krb5_context context,
1047 struct samba_kdc_db_context *kdc_db_ctx,
1048 struct loadparm_context *lp_ctx,
1049 TALLOC_CTX *mem_ctx,
1050 krb5_const_principal principal,
1051 unsigned flags,
1052 hdb_entry_ex *entry_ex)
1054 krb5_error_code ret;
1055 struct ldb_message *msg = NULL;
1056 struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1057 const char *realm;
1059 krb5_principal alloc_principal = NULL;
1060 if (principal->name.name_string.len != 2
1061 || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
1062 /* Not a krbtgt */
1063 return HDB_ERR_NOENTRY;
1066 /* krbtgt case. Either us or a trusted realm */
1068 if (lp_is_my_domain_or_realm(lp_ctx, principal->realm)
1069 && lp_is_my_domain_or_realm(lp_ctx, principal->name.name_string.val[1])) {
1070 /* us */
1071 /* Cludge, cludge cludge. If the realm part of krbtgt/realm,
1072 * is in our db, then direct the caller at our primary
1073 * krbtgt */
1075 int lret;
1076 char *realm_fixed;
1078 lret = gendb_search_single_extended_dn(kdc_db_ctx->samdb, mem_ctx,
1079 realm_dn, LDB_SCOPE_SUBTREE,
1080 &msg, krbtgt_attrs,
1081 "(&(objectClass=user)(samAccountName=krbtgt))");
1082 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1083 krb5_warnx(context, "hdb_samba4_fetch: could not find own KRBTGT in DB!");
1084 krb5_set_error_message(context, HDB_ERR_NOENTRY, "hdb_samba4_fetch: could not find own KRBTGT in DB!");
1085 return HDB_ERR_NOENTRY;
1086 } else if (lret != LDB_SUCCESS) {
1087 krb5_warnx(context, "hdb_samba4_fetch: could not find own KRBTGT in DB: %s", ldb_errstring(kdc_db_ctx->samdb));
1088 krb5_set_error_message(context, HDB_ERR_NOENTRY, "hdb_samba4_fetch: could not find own KRBTGT in DB: %s", ldb_errstring(kdc_db_ctx->samdb));
1089 return HDB_ERR_NOENTRY;
1092 realm_fixed = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
1093 if (!realm_fixed) {
1094 ret = ENOMEM;
1095 krb5_set_error_message(context, ret, "strupper_talloc: out of memory");
1096 return ret;
1099 ret = krb5_copy_principal(context, principal, &alloc_principal);
1100 if (ret) {
1101 return ret;
1104 free(alloc_principal->name.name_string.val[1]);
1105 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
1106 talloc_free(realm_fixed);
1107 if (!alloc_principal->name.name_string.val[1]) {
1108 ret = ENOMEM;
1109 krb5_set_error_message(context, ret, "hdb_samba4_fetch: strdup() failed!");
1110 return ret;
1112 principal = alloc_principal;
1114 ret = hdb_samba4_message2entry(context, kdc_db_ctx, lp_ctx, mem_ctx,
1115 principal, HDB_SAMBA4_ENT_TYPE_KRBTGT,
1116 realm_dn, msg, entry_ex);
1117 if (ret != 0) {
1118 krb5_warnx(context, "hdb_samba4_fetch: self krbtgt message2entry failed");
1120 return ret;
1122 } else {
1123 enum trust_direction direction = UNKNOWN;
1125 /* Either an inbound or outbound trust */
1127 if (strcasecmp(lp_realm(lp_ctx), principal->realm) == 0) {
1128 /* look for inbound trust */
1129 direction = INBOUND;
1130 realm = principal->name.name_string.val[1];
1133 if (strcasecmp(lp_realm(lp_ctx), principal->name.name_string.val[1]) == 0) {
1134 /* look for outbound trust */
1135 direction = OUTBOUND;
1136 realm = principal->realm;
1139 /* Trusted domains are under CN=system */
1141 ret = hdb_samba4_lookup_trust(context, kdc_db_ctx->samdb,
1142 mem_ctx,
1143 realm, realm_dn, &msg);
1145 if (ret != 0) {
1146 krb5_warnx(context, "hdb_samba4_fetch: could not find principal in DB");
1147 krb5_set_error_message(context, ret, "hdb_samba4_fetch: could not find principal in DB");
1148 return ret;
1151 ret = hdb_samba4_trust_message2entry(context, kdc_db_ctx, lp_ctx, mem_ctx,
1152 principal, direction,
1153 realm_dn, msg, entry_ex);
1154 if (ret != 0) {
1155 krb5_warnx(context, "hdb_samba4_fetch: trust_message2entry failed");
1157 return ret;
1160 /* we should lookup trusted domains */
1161 return HDB_ERR_NOENTRY;
1166 static krb5_error_code hdb_samba4_lookup_server(krb5_context context,
1167 struct samba_kdc_db_context *kdc_db_ctx,
1168 struct loadparm_context *lp_ctx,
1169 TALLOC_CTX *mem_ctx,
1170 krb5_const_principal principal,
1171 const char **attrs,
1172 struct ldb_dn **realm_dn,
1173 struct ldb_message **msg)
1175 krb5_error_code ret;
1176 const char *realm;
1177 if (principal->name.name_string.len >= 2) {
1178 /* 'normal server' case */
1179 int ldb_ret;
1180 NTSTATUS nt_status;
1181 struct ldb_dn *user_dn;
1182 char *principal_string;
1184 ret = krb5_unparse_name_flags(context, principal,
1185 KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1186 &principal_string);
1187 if (ret != 0) {
1188 return ret;
1191 /* At this point we may find the host is known to be
1192 * in a different realm, so we should generate a
1193 * referral instead */
1194 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
1195 mem_ctx, principal_string,
1196 &user_dn, realm_dn);
1197 free(principal_string);
1199 if (!NT_STATUS_IS_OK(nt_status)) {
1200 return HDB_ERR_NOENTRY;
1203 ldb_ret = gendb_search_single_extended_dn(kdc_db_ctx->samdb,
1204 mem_ctx,
1205 user_dn, LDB_SCOPE_BASE,
1206 msg, attrs,
1207 "(objectClass=*)");
1208 if (ldb_ret != LDB_SUCCESS) {
1209 return HDB_ERR_NOENTRY;
1212 } else {
1213 int lret;
1214 char *filter = NULL;
1215 char *short_princ;
1216 /* server as client principal case, but we must not lookup userPrincipalNames */
1217 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1218 realm = krb5_principal_get_realm(context, principal);
1220 /* TODO: Check if it is our realm, otherwise give referall */
1222 ret = krb5_unparse_name_flags(context, principal, KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
1224 if (ret != 0) {
1225 krb5_set_error_message(context, ret, "hdb_samba4_lookup_principal: could not parse principal");
1226 krb5_warnx(context, "hdb_samba4_lookup_principal: could not parse principal");
1227 return ret;
1230 lret = gendb_search_single_extended_dn(kdc_db_ctx->samdb, mem_ctx,
1231 *realm_dn, LDB_SCOPE_SUBTREE,
1232 msg, attrs, "(&(objectClass=user)(samAccountName=%s))",
1233 ldb_binary_encode_string(mem_ctx, short_princ));
1234 free(short_princ);
1235 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1236 DEBUG(3, ("Failed find a entry for %s\n", filter));
1237 return HDB_ERR_NOENTRY;
1239 if (lret != LDB_SUCCESS) {
1240 DEBUG(3, ("Failed single search for for %s - %s\n",
1241 filter, ldb_errstring(kdc_db_ctx->samdb)));
1242 return HDB_ERR_NOENTRY;
1246 return 0;
1249 static krb5_error_code hdb_samba4_fetch_server(krb5_context context,
1250 struct samba_kdc_db_context *kdc_db_ctx,
1251 struct loadparm_context *lp_ctx,
1252 TALLOC_CTX *mem_ctx,
1253 krb5_const_principal principal,
1254 unsigned flags,
1255 hdb_entry_ex *entry_ex)
1257 krb5_error_code ret;
1258 struct ldb_dn *realm_dn;
1259 struct ldb_message *msg;
1261 ret = hdb_samba4_lookup_server(context, kdc_db_ctx, lp_ctx, mem_ctx, principal,
1262 server_attrs, &realm_dn, &msg);
1263 if (ret != 0) {
1264 return ret;
1267 ret = hdb_samba4_message2entry(context, kdc_db_ctx, lp_ctx, mem_ctx,
1268 principal, HDB_SAMBA4_ENT_TYPE_SERVER,
1269 realm_dn, msg, entry_ex);
1270 if (ret != 0) {
1271 krb5_warnx(context, "hdb_samba4_fetch: message2entry failed");
1274 return ret;
1277 static krb5_error_code hdb_samba4_fetch(krb5_context context, HDB *db,
1278 krb5_const_principal principal,
1279 unsigned flags,
1280 hdb_entry_ex *entry_ex)
1282 struct samba_kdc_db_context *kdc_db_ctx = (struct samba_kdc_db_context *)db->hdb_db;
1283 krb5_error_code ret = HDB_ERR_NOENTRY;
1284 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "hdb_samba4_fetch context");
1285 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1287 if (!mem_ctx) {
1288 ret = ENOMEM;
1289 krb5_set_error_message(context, ret, "hdb_samba4_fetch: talloc_named() failed!");
1290 return ret;
1293 if (flags & HDB_F_GET_CLIENT) {
1294 ret = hdb_samba4_fetch_client(context, kdc_db_ctx, lp_ctx, mem_ctx, principal, flags, entry_ex);
1295 if (ret != HDB_ERR_NOENTRY) goto done;
1297 if (flags & HDB_F_GET_SERVER) {
1298 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1299 ret = hdb_samba4_fetch_krbtgt(context, kdc_db_ctx, lp_ctx, mem_ctx, principal, flags, entry_ex);
1300 if (ret != HDB_ERR_NOENTRY) goto done;
1302 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1303 ret = hdb_samba4_fetch_server(context, kdc_db_ctx, lp_ctx, mem_ctx, principal, flags, entry_ex);
1304 if (ret != HDB_ERR_NOENTRY) goto done;
1306 if (flags & HDB_F_GET_KRBTGT) {
1307 ret = hdb_samba4_fetch_krbtgt(context, kdc_db_ctx, lp_ctx, mem_ctx, principal, flags, entry_ex);
1308 if (ret != HDB_ERR_NOENTRY) goto done;
1311 done:
1312 talloc_free(mem_ctx);
1313 return ret;
1316 static krb5_error_code hdb_samba4_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
1318 return HDB_ERR_DB_INUSE;
1321 static krb5_error_code hdb_samba4_remove(krb5_context context, HDB *db, krb5_const_principal principal)
1323 return HDB_ERR_DB_INUSE;
1326 struct hdb_samba4_seq {
1327 struct ldb_context *ctx;
1328 struct loadparm_context *lp_ctx;
1329 int index;
1330 int count;
1331 struct ldb_message **msgs;
1332 struct ldb_dn *realm_dn;
1335 static krb5_error_code hdb_samba4_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
1337 struct samba_kdc_db_context *kdc_db_ctx = (struct samba_kdc_db_context *)db->hdb_db;
1338 krb5_error_code ret;
1339 struct hdb_samba4_seq *priv = (struct hdb_samba4_seq *)db->hdb_dbc;
1340 TALLOC_CTX *mem_ctx;
1341 hdb_entry_ex entry_ex;
1342 memset(&entry_ex, '\0', sizeof(entry_ex));
1344 if (!priv) {
1345 return HDB_ERR_NOENTRY;
1348 mem_ctx = talloc_named(priv, 0, "hdb_samba4_seq context");
1350 if (!mem_ctx) {
1351 ret = ENOMEM;
1352 krb5_set_error_message(context, ret, "hdb_samba4_seq: talloc_named() failed!");
1353 return ret;
1356 if (priv->index < priv->count) {
1357 ret = hdb_samba4_message2entry(context, kdc_db_ctx, priv->lp_ctx,
1358 mem_ctx,
1359 NULL, HDB_SAMBA4_ENT_TYPE_ANY,
1360 priv->realm_dn, priv->msgs[priv->index++], entry);
1361 } else {
1362 ret = HDB_ERR_NOENTRY;
1365 if (ret != 0) {
1366 db->hdb_dbc = NULL;
1367 } else {
1368 talloc_free(mem_ctx);
1371 return ret;
1374 static krb5_error_code hdb_samba4_firstkey(krb5_context context, HDB *db, unsigned flags,
1375 hdb_entry_ex *entry)
1377 struct samba_kdc_db_context *kdc_db_ctx = (struct samba_kdc_db_context *)db->hdb_db;
1378 struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
1379 struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(ldb_ctx, "loadparm"),
1380 struct loadparm_context);
1381 struct hdb_samba4_seq *priv = (struct hdb_samba4_seq *)db->hdb_dbc;
1382 char *realm;
1383 struct ldb_result *res = NULL;
1384 krb5_error_code ret;
1385 TALLOC_CTX *mem_ctx;
1386 int lret;
1388 if (priv) {
1389 talloc_free(priv);
1390 db->hdb_dbc = NULL;
1393 priv = (struct hdb_samba4_seq *) talloc(db, struct hdb_samba4_seq);
1394 if (!priv) {
1395 ret = ENOMEM;
1396 krb5_set_error_message(context, ret, "talloc: out of memory");
1397 return ret;
1400 priv->ctx = ldb_ctx;
1401 priv->lp_ctx = lp_ctx;
1402 priv->index = 0;
1403 priv->msgs = NULL;
1404 priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
1405 priv->count = 0;
1407 mem_ctx = talloc_named(priv, 0, "hdb_samba4_firstkey context");
1409 if (!mem_ctx) {
1410 ret = ENOMEM;
1411 krb5_set_error_message(context, ret, "hdb_samba4_firstkey: talloc_named() failed!");
1412 return ret;
1415 ret = krb5_get_default_realm(context, &realm);
1416 if (ret != 0) {
1417 talloc_free(priv);
1418 return ret;
1421 lret = ldb_search(ldb_ctx, priv, &res,
1422 priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
1423 "(objectClass=user)");
1425 if (lret != LDB_SUCCESS) {
1426 talloc_free(priv);
1427 return HDB_ERR_NOENTRY;
1430 priv->count = res->count;
1431 priv->msgs = talloc_steal(priv, res->msgs);
1432 talloc_free(res);
1434 db->hdb_dbc = priv;
1436 ret = hdb_samba4_seq(context, db, flags, entry);
1438 if (ret != 0) {
1439 talloc_free(priv);
1440 db->hdb_dbc = NULL;
1441 } else {
1442 talloc_free(mem_ctx);
1444 return ret;
1447 static krb5_error_code hdb_samba4_nextkey(krb5_context context, HDB *db, unsigned flags,
1448 hdb_entry_ex *entry)
1450 return hdb_samba4_seq(context, db, flags, entry);
1453 static krb5_error_code hdb_samba4_destroy(krb5_context context, HDB *db)
1455 talloc_free(db);
1456 return 0;
1460 /* Check if a given entry may delegate to this target principal
1462 * This is currently a very nasty hack - allowing only delegation to itself.
1464 static krb5_error_code
1465 hdb_samba4_check_constrained_delegation(krb5_context context, HDB *db,
1466 hdb_entry_ex *entry,
1467 krb5_const_principal target_principal)
1469 struct samba_kdc_db_context *kdc_db_ctx = (struct samba_kdc_db_context *)db->hdb_db;
1470 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1471 krb5_error_code ret;
1472 krb5_principal enterprise_prinicpal = NULL;
1473 struct ldb_dn *realm_dn;
1474 struct ldb_message *msg;
1475 struct dom_sid *orig_sid;
1476 struct dom_sid *target_sid;
1477 struct hdb_samba4_private *p = talloc_get_type(entry->ctx, struct hdb_samba4_private);
1478 const char *delegation_check_attrs[] = {
1479 "objectSid", NULL
1482 TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "hdb_samba4_check_constrained_delegation");
1484 if (!mem_ctx) {
1485 ret = ENOMEM;
1486 krb5_set_error_message(context, ret, "hdb_samba4_fetch: talloc_named() failed!");
1487 return ret;
1490 if (target_principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1491 /* Need to reparse the enterprise principal to find the real target */
1492 if (target_principal->name.name_string.len != 1) {
1493 ret = KRB5_PARSE_MALFORMED;
1494 krb5_set_error_message(context, ret, "hdb_samba4_check_constrained_delegation: request for delegation to enterprise principal with wrong (%d) number of components",
1495 target_principal->name.name_string.len);
1496 talloc_free(mem_ctx);
1497 return ret;
1499 ret = krb5_parse_name(context, target_principal->name.name_string.val[0],
1500 &enterprise_prinicpal);
1501 if (ret) {
1502 talloc_free(mem_ctx);
1503 return ret;
1505 target_principal = enterprise_prinicpal;
1508 ret = hdb_samba4_lookup_server(context, kdc_db_ctx, lp_ctx, mem_ctx, target_principal,
1509 delegation_check_attrs, &realm_dn, &msg);
1511 krb5_free_principal(context, enterprise_prinicpal);
1513 if (ret != 0) {
1514 talloc_free(mem_ctx);
1515 return ret;
1518 orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1519 target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1521 /* Allow delegation to the same principal, even if by a different
1522 * name. The easy and safe way to prove this is by SID
1523 * comparison */
1524 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1525 talloc_free(mem_ctx);
1526 return KRB5KDC_ERR_BADOPTION;
1529 talloc_free(mem_ctx);
1530 return ret;
1533 /* Certificates printed by a the Certificate Authority might have a
1534 * slightly different form of the user principal name to that in the
1535 * database. Allow a mismatch where they both refer to the same
1536 * SID */
1538 static krb5_error_code
1539 hdb_samba4_check_pkinit_ms_upn_match(krb5_context context, HDB *db,
1540 hdb_entry_ex *entry,
1541 krb5_const_principal certificate_principal)
1543 struct samba_kdc_db_context *kdc_db_ctx = (struct samba_kdc_db_context *)db->hdb_db;
1544 struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1545 krb5_error_code ret;
1546 struct ldb_dn *realm_dn;
1547 struct ldb_message *msg;
1548 struct dom_sid *orig_sid;
1549 struct dom_sid *target_sid;
1550 struct hdb_samba4_private *p = talloc_get_type(entry->ctx, struct hdb_samba4_private);
1551 const char *ms_upn_check_attrs[] = {
1552 "objectSid", NULL
1555 TALLOC_CTX *mem_ctx = talloc_named(db, 0, "hdb_samba4_check_pkinit_ms_upn_match");
1557 if (!mem_ctx) {
1558 ret = ENOMEM;
1559 krb5_set_error_message(context, ret, "hdb_samba4_fetch: talloc_named() failed!");
1560 return ret;
1563 ret = hdb_samba4_lookup_client(context, kdc_db_ctx, lp_ctx,
1564 mem_ctx, certificate_principal,
1565 ms_upn_check_attrs, &realm_dn, &msg);
1567 if (ret != 0) {
1568 talloc_free(mem_ctx);
1569 return ret;
1572 orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1573 target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1575 /* Consider these to be the same principal, even if by a different
1576 * name. The easy and safe way to prove this is by SID
1577 * comparison */
1578 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1579 talloc_free(mem_ctx);
1580 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1583 talloc_free(mem_ctx);
1584 return ret;
1587 /* This interface is to be called by the KDC and libnet_keytab_dump, which is expecting Samba
1588 * calling conventions. It is also called by a wrapper
1589 * (hdb_samba4_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb
1590 * code */
1592 NTSTATUS hdb_samba4_create_kdc(struct samba_kdc_base_context *base_ctx,
1593 krb5_context context, struct HDB **db)
1595 struct samba_kdc_db_context *kdc_db_ctx;
1596 struct auth_session_info *session_info;
1597 NTSTATUS nt_status;
1599 *db = talloc(base_ctx, HDB);
1600 if (!*db) {
1601 krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
1602 return NT_STATUS_NO_MEMORY;
1605 (*db)->hdb_master_key_set = 0;
1606 (*db)->hdb_db = NULL;
1607 (*db)->hdb_capability_flags = 0;
1609 #if 1
1610 /* we would prefer to use system_session(), as that would
1611 * allow us to share the samdb backend context with other parts of the
1612 * system. For now we can't as we need to override the
1613 * credentials to set CRED_DONT_USE_KERBEROS, which would
1614 * break other users of the system_session */
1615 DEBUG(0,("FIXME: Using new system session for hdb\n"));
1616 nt_status = auth_system_session_info(*db, base_ctx->lp_ctx, &session_info);
1617 if (!NT_STATUS_IS_OK(nt_status)) {
1618 return nt_status;
1620 #else
1621 session_info = system_session(kdc_db_ctx->lp_ctx);
1622 if (session_info == NULL) {
1623 return NT_STATUS_INTERNAL_ERROR;
1625 #endif
1627 /* The idea here is very simple. Using Kerberos to
1628 * authenticate the KDC to the LDAP server is higly likely to
1629 * be circular.
1631 * In future we may set this up to use EXERNAL and SSL
1632 * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
1635 cli_credentials_set_kerberos_state(session_info->credentials,
1636 CRED_DONT_USE_KERBEROS);
1638 kdc_db_ctx = talloc_zero(*db, struct samba_kdc_db_context);
1639 if (kdc_db_ctx == NULL) {
1640 return NT_STATUS_NO_MEMORY;
1642 kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
1643 kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
1645 /* Setup the link to LDB */
1646 kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx, base_ctx->ev_ctx,
1647 base_ctx->lp_ctx, session_info);
1648 if (kdc_db_ctx->samdb == NULL) {
1649 DEBUG(1, ("hdb_samba4_create: Cannot open samdb for KDC backend!"));
1650 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1653 (*db)->hdb_db = kdc_db_ctx;
1655 (*db)->hdb_dbc = NULL;
1656 (*db)->hdb_open = hdb_samba4_open;
1657 (*db)->hdb_close = hdb_samba4_close;
1658 (*db)->hdb_fetch = hdb_samba4_fetch;
1659 (*db)->hdb_store = hdb_samba4_store;
1660 (*db)->hdb_remove = hdb_samba4_remove;
1661 (*db)->hdb_firstkey = hdb_samba4_firstkey;
1662 (*db)->hdb_nextkey = hdb_samba4_nextkey;
1663 (*db)->hdb_lock = hdb_samba4_lock;
1664 (*db)->hdb_unlock = hdb_samba4_unlock;
1665 (*db)->hdb_rename = hdb_samba4_rename;
1666 /* we don't implement these, as we are not a lockable database */
1667 (*db)->hdb__get = NULL;
1668 (*db)->hdb__put = NULL;
1669 /* kadmin should not be used for deletes - use other tools instead */
1670 (*db)->hdb__del = NULL;
1671 (*db)->hdb_destroy = hdb_samba4_destroy;
1673 (*db)->hdb_auth_status = NULL;
1674 (*db)->hdb_check_constrained_delegation = hdb_samba4_check_constrained_delegation;
1675 (*db)->hdb_check_pkinit_ms_upn_match = hdb_samba4_check_pkinit_ms_upn_match;
1677 return NT_STATUS_OK;
1680 static krb5_error_code hdb_samba4_create(krb5_context context, struct HDB **db, const char *arg)
1682 NTSTATUS nt_status;
1683 void *ptr;
1684 struct samba_kdc_base_context *base_ctx;
1686 if (sscanf(arg, "&%p", &ptr) != 1) {
1687 return EINVAL;
1689 base_ctx = talloc_get_type_abort(ptr, struct samba_kdc_base_context);
1690 /* The global kdc_mem_ctx and kdc_lp_ctx, Disgusting, ugly hack, but it means one less private hook */
1691 nt_status = hdb_samba4_create_kdc(base_ctx, context, db);
1693 if (NT_STATUS_IS_OK(nt_status)) {
1694 return 0;
1696 return EINVAL;
1699 /* Only used in the hdb-backed keytab code
1700 * for a keytab of 'samba4&<address>', to find
1701 * kpasswd's key in the main DB, and to
1702 * copy all the keys into a file (libnet_keytab_export)
1704 * The <address> is the string form of a pointer to a talloced struct hdb_samba_context
1706 struct hdb_method hdb_samba4 = {
1707 .interface_version = HDB_INTERFACE_VERSION,
1708 .prefix = "samba4",
1709 .create = hdb_samba4_create