libreplace: added likely()/unlikely() macros for gcc
[Samba/aatanasov.git] / source4 / kdc / hdb-samba4.c
blob502b4e0903ecfbef6e1f5237452b450ee908cfb2
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) {
399 if (key.salt) {
400 free_Salt(key.salt);
401 free(key.salt);
402 key.salt = NULL;
404 goto out;
407 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
408 entry_ex->entry.keys.len++;
410 } else if (pkb3) {
411 for (i=0; i < pkb3->num_keys; i++) {
412 bool use = true;
413 Key key;
415 if (!pkb3->keys[i].value) continue;
417 if (userAccountControl & UF_USE_DES_KEY_ONLY) {
418 switch (pkb3->keys[i].keytype) {
419 case ENCTYPE_DES_CBC_CRC:
420 case ENCTYPE_DES_CBC_MD5:
421 break;
422 default:
423 use = false;
424 break;
428 if (!use) continue;
430 key.mkvno = 0;
431 key.salt = NULL;
433 if (pkb3->salt.string) {
434 DATA_BLOB salt;
436 salt = data_blob_string_const(pkb3->salt.string);
438 key.salt = calloc(1, sizeof(*key.salt));
439 if (key.salt == NULL) {
440 ret = ENOMEM;
441 goto out;
444 key.salt->type = hdb_pw_salt;
446 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
447 if (ret) {
448 free(key.salt);
449 key.salt = NULL;
450 goto out;
454 ret = krb5_keyblock_init(context,
455 pkb3->keys[i].keytype,
456 pkb3->keys[i].value->data,
457 pkb3->keys[i].value->length,
458 &key.key);
459 if (ret) {
460 if (key.salt) {
461 free_Salt(key.salt);
462 free(key.salt);
463 key.salt = NULL;
465 goto out;
468 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
469 entry_ex->entry.keys.len++;
473 out:
474 if (ret != 0) {
475 entry_ex->entry.keys.len = 0;
477 if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
478 free(entry_ex->entry.keys.val);
479 entry_ex->entry.keys.val = NULL;
481 return ret;
485 * Construct an hdb_entry from a directory entry.
487 static krb5_error_code hdb_samba4_message2entry(krb5_context context, HDB *db,
488 struct loadparm_context *lp_ctx,
489 TALLOC_CTX *mem_ctx, krb5_const_principal principal,
490 enum hdb_samba4_ent_type ent_type,
491 struct ldb_dn *realm_dn,
492 struct ldb_message *msg,
493 hdb_entry_ex *entry_ex)
495 unsigned int userAccountControl;
496 int i;
497 krb5_error_code ret = 0;
498 krb5_boolean is_computer = FALSE;
499 char *realm = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
501 struct hdb_samba4_private *p;
502 NTTIME acct_expiry;
503 NTSTATUS status;
505 uint32_t rid;
506 struct ldb_message_element *objectclasses;
507 struct ldb_val computer_val;
508 const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
509 computer_val.data = discard_const_p(uint8_t,"computer");
510 computer_val.length = strlen((const char *)computer_val.data);
512 if (!samAccountName) {
513 ret = ENOENT;
514 krb5_set_error_message(context, ret, "hdb_samba4_message2entry: no samAccountName present");
515 goto out;
518 objectclasses = ldb_msg_find_element(msg, "objectClass");
520 if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
521 is_computer = TRUE;
524 memset(entry_ex, 0, sizeof(*entry_ex));
526 if (!realm) {
527 ret = ENOMEM;
528 krb5_set_error_message(context, ret, "talloc_strdup: out of memory");
529 goto out;
532 p = talloc(mem_ctx, struct hdb_samba4_private);
533 if (!p) {
534 ret = ENOMEM;
535 goto out;
538 p->entry_ex = entry_ex;
539 p->iconv_convenience = lp_iconv_convenience(lp_ctx);
540 p->lp_ctx = lp_ctx;
541 p->realm_dn = talloc_reference(p, realm_dn);
542 if (!p->realm_dn) {
543 ret = ENOMEM;
544 goto out;
547 talloc_set_destructor(p, hdb_samba4_destructor);
549 entry_ex->ctx = p;
550 entry_ex->free_entry = hdb_samba4_free_entry;
552 userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
555 entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
556 if (ent_type == HDB_SAMBA4_ENT_TYPE_ANY && principal == NULL) {
557 krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL);
558 } else {
559 ret = copy_Principal(principal, entry_ex->entry.principal);
560 if (ret) {
561 krb5_clear_error_message(context);
562 goto out;
565 /* While we have copied the client principal, tests
566 * show that Win2k3 returns the 'corrected' realm, not
567 * the client-specified realm. This code attempts to
568 * replace the client principal's realm with the one
569 * we determine from our records */
571 /* this has to be with malloc() */
572 krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
575 /* First try and figure out the flags based on the userAccountControl */
576 entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
578 /* Windows 2008 seems to enforce this (very sensible) rule by
579 * default - don't allow offline attacks on a user's password
580 * by asking for a ticket to them as a service (encrypted with
581 * their probably patheticly insecure password) */
583 if (entry_ex->entry.flags.server
584 && lp_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
585 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
586 entry_ex->entry.flags.server = 0;
591 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
592 * of the Heimdal KDC. They are stored in a the traditional
593 * DB for audit purposes, and still form part of the structure
594 * we must return */
596 /* use 'whenCreated' */
597 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
598 /* use '???' */
599 entry_ex->entry.created_by.principal = NULL;
601 entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
602 if (entry_ex->entry.modified_by == NULL) {
603 ret = ENOMEM;
604 krb5_set_error_message(context, ret, "malloc: out of memory");
605 goto out;
608 /* use 'whenChanged' */
609 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
610 /* use '???' */
611 entry_ex->entry.modified_by->principal = NULL;
615 /* The lack of password controls etc applies to krbtgt by
616 * virtue of being that particular RID */
617 status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
619 if (!NT_STATUS_IS_OK(status)) {
620 ret = EINVAL;
621 goto out;
624 if (rid == DOMAIN_RID_KRBTGT) {
625 entry_ex->entry.valid_end = NULL;
626 entry_ex->entry.pw_end = NULL;
628 entry_ex->entry.flags.invalid = 0;
629 entry_ex->entry.flags.server = 1;
631 /* Don't mark all requests for the krbtgt/realm as
632 * 'change password', as otherwise we could get into
633 * trouble, and not enforce the password expirty.
634 * Instead, only do it when request is for the kpasswd service */
635 if (ent_type == HDB_SAMBA4_ENT_TYPE_SERVER
636 && principal->name.name_string.len == 2
637 && (strcmp(principal->name.name_string.val[0], "kadmin") == 0)
638 && (strcmp(principal->name.name_string.val[1], "changepw") == 0)
639 && lp_is_my_domain_or_realm(lp_ctx, principal->realm)) {
640 entry_ex->entry.flags.change_pw = 1;
642 entry_ex->entry.flags.client = 0;
643 entry_ex->entry.flags.forwardable = 1;
644 entry_ex->entry.flags.ok_as_delegate = 1;
645 } else if (entry_ex->entry.flags.server && ent_type == HDB_SAMBA4_ENT_TYPE_SERVER) {
646 /* The account/password expiry only applies when the account is used as a
647 * client (ie password login), not when used as a server */
649 /* Make very well sure we don't use this for a client,
650 * it could bypass the password restrictions */
651 entry_ex->entry.flags.client = 0;
653 entry_ex->entry.valid_end = NULL;
654 entry_ex->entry.pw_end = NULL;
656 } else {
657 NTTIME must_change_time
658 = samdb_result_force_password_change((struct ldb_context *)db->hdb_db, mem_ctx,
659 realm_dn, msg);
660 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
661 entry_ex->entry.pw_end = NULL;
662 } else {
663 entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
664 if (entry_ex->entry.pw_end == NULL) {
665 ret = ENOMEM;
666 goto out;
668 *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
671 acct_expiry = samdb_result_account_expires(msg);
672 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
673 entry_ex->entry.valid_end = NULL;
674 } else {
675 entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
676 if (entry_ex->entry.valid_end == NULL) {
677 ret = ENOMEM;
678 goto out;
680 *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
684 entry_ex->entry.valid_start = NULL;
686 entry_ex->entry.max_life = NULL;
688 entry_ex->entry.max_renew = NULL;
690 entry_ex->entry.generation = NULL;
692 /* Get keys from the db */
693 ret = hdb_samba4_message2entry_keys(context, p->iconv_convenience, p, msg, userAccountControl, entry_ex);
694 if (ret) {
695 /* Could be bougus data in the entry, or out of memory */
696 goto out;
699 entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
700 if (entry_ex->entry.etypes == NULL) {
701 krb5_clear_error_message(context);
702 ret = ENOMEM;
703 goto out;
705 entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
706 entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
707 if (entry_ex->entry.etypes->val == NULL) {
708 krb5_clear_error_message(context);
709 ret = ENOMEM;
710 goto out;
712 for (i=0; i < entry_ex->entry.etypes->len; i++) {
713 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
717 p->msg = talloc_steal(p, msg);
718 p->samdb = (struct ldb_context *)db->hdb_db;
720 out:
721 if (ret != 0) {
722 /* This doesn't free ent itself, that is for the eventual caller to do */
723 hdb_free_entry(context, entry_ex);
724 } else {
725 talloc_steal(db, entry_ex->ctx);
728 return ret;
732 * Construct an hdb_entry from a directory entry.
734 static krb5_error_code hdb_samba4_trust_message2entry(krb5_context context, HDB *db,
735 struct loadparm_context *lp_ctx,
736 TALLOC_CTX *mem_ctx, krb5_const_principal principal,
737 enum trust_direction direction,
738 struct ldb_dn *realm_dn,
739 struct ldb_message *msg,
740 hdb_entry_ex *entry_ex)
743 const char *dnsdomain;
744 char *realm;
745 DATA_BLOB password_utf16;
746 struct samr_Password password_hash;
747 const struct ldb_val *password_val;
748 struct trustAuthInOutBlob password_blob;
749 struct hdb_samba4_private *p;
751 enum ndr_err_code ndr_err;
752 int i, ret, trust_direction_flags;
754 p = talloc(mem_ctx, struct hdb_samba4_private);
755 if (!p) {
756 ret = ENOMEM;
757 goto out;
760 p->entry_ex = entry_ex;
761 p->iconv_convenience = lp_iconv_convenience(lp_ctx);
762 p->lp_ctx = lp_ctx;
763 p->realm_dn = realm_dn;
765 talloc_set_destructor(p, hdb_samba4_destructor);
767 entry_ex->ctx = p;
768 entry_ex->free_entry = hdb_samba4_free_entry;
770 /* use 'whenCreated' */
771 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
772 /* use '???' */
773 entry_ex->entry.created_by.principal = NULL;
775 entry_ex->entry.valid_start = NULL;
777 trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
779 if (direction == INBOUND) {
780 realm = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
781 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
783 } else { /* OUTBOUND */
784 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
785 realm = strupper_talloc(mem_ctx, dnsdomain);
786 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
789 if (!password_val || !(trust_direction_flags & direction)) {
790 ret = ENOENT;
791 goto out;
794 ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, p->iconv_convenience, &password_blob,
795 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
796 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
797 ret = EINVAL;
798 goto out;
801 entry_ex->entry.kvno = -1;
802 for (i=0; i < password_blob.count; i++) {
803 if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_VERSION) {
804 entry_ex->entry.kvno = password_blob.current->array[i].AuthInfo.version.version;
808 for (i=0; i < password_blob.count; i++) {
809 if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
810 password_utf16 = data_blob_const(password_blob.current->array[i].AuthInfo.clear.password,
811 password_blob.current->array[i].AuthInfo.clear.size);
812 /* In the future, generate all sorts of
813 * hashes, but for now we can't safely convert
814 * the random strings windows uses into
815 * utf8 */
817 /* but as it is utf16 already, we can get the NT password/arcfour-hmac-md5 key */
818 mdfour(password_hash.hash, password_utf16.data, password_utf16.length);
819 break;
820 } else if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
821 password_hash = password_blob.current->array[i].AuthInfo.nt4owf.password;
822 break;
825 entry_ex->entry.keys.len = 0;
826 entry_ex->entry.keys.val = NULL;
828 if (i < password_blob.count) {
829 Key key;
830 /* Must have found a cleartext or MD4 password */
831 entry_ex->entry.keys.val = calloc(1, sizeof(Key));
833 key.mkvno = 0;
834 key.salt = NULL; /* No salt for this enc type */
836 if (entry_ex->entry.keys.val == NULL) {
837 ret = ENOMEM;
838 goto out;
841 ret = krb5_keyblock_init(context,
842 ENCTYPE_ARCFOUR_HMAC,
843 password_hash.hash, sizeof(password_hash.hash),
844 &key.key);
846 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
847 entry_ex->entry.keys.len++;
850 entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
852 ret = copy_Principal(principal, entry_ex->entry.principal);
853 if (ret) {
854 krb5_clear_error_message(context);
855 goto out;
858 /* While we have copied the client principal, tests
859 * show that Win2k3 returns the 'corrected' realm, not
860 * the client-specified realm. This code attempts to
861 * replace the client principal's realm with the one
862 * we determine from our records */
864 krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
865 entry_ex->entry.flags = int2HDBFlags(0);
866 entry_ex->entry.flags.immutable = 1;
867 entry_ex->entry.flags.invalid = 0;
868 entry_ex->entry.flags.server = 1;
869 entry_ex->entry.flags.require_preauth = 1;
871 entry_ex->entry.pw_end = NULL;
873 entry_ex->entry.max_life = NULL;
875 entry_ex->entry.max_renew = NULL;
877 entry_ex->entry.generation = NULL;
879 entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
880 if (entry_ex->entry.etypes == NULL) {
881 krb5_clear_error_message(context);
882 ret = ENOMEM;
883 goto out;
885 entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
886 entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
887 if (entry_ex->entry.etypes->val == NULL) {
888 krb5_clear_error_message(context);
889 ret = ENOMEM;
890 goto out;
892 for (i=0; i < entry_ex->entry.etypes->len; i++) {
893 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
897 p->msg = talloc_steal(p, msg);
898 p->samdb = (struct ldb_context *)db->hdb_db;
900 out:
901 if (ret != 0) {
902 /* This doesn't free ent itself, that is for the eventual caller to do */
903 hdb_free_entry(context, entry_ex);
904 } else {
905 talloc_steal(db, entry_ex->ctx);
908 return ret;
912 static krb5_error_code hdb_samba4_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
913 TALLOC_CTX *mem_ctx,
914 const char *realm,
915 struct ldb_dn *realm_dn,
916 struct ldb_message **pmsg)
918 int lret;
919 krb5_error_code ret;
920 char *filter = NULL;
921 const char * const *attrs = trust_attrs;
923 struct ldb_result *res = NULL;
924 filter = talloc_asprintf(mem_ctx, "(&(objectClass=trustedDomain)(|(flatname=%s)(trustPartner=%s)))", realm, realm);
926 if (!filter) {
927 ret = ENOMEM;
928 krb5_set_error_message(context, ret, "talloc_asprintf: out of memory");
929 return ret;
932 lret = ldb_search(ldb_ctx, mem_ctx, &res,
933 ldb_get_default_basedn(ldb_ctx),
934 LDB_SCOPE_SUBTREE, attrs, "%s", filter);
935 if (lret != LDB_SUCCESS) {
936 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
937 return HDB_ERR_NOENTRY;
938 } else if (res->count == 0 || res->count > 1) {
939 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
940 talloc_free(res);
941 return HDB_ERR_NOENTRY;
943 talloc_steal(mem_ctx, res->msgs);
944 *pmsg = res->msgs[0];
945 talloc_free(res);
946 return 0;
949 static krb5_error_code hdb_samba4_open(krb5_context context, HDB *db, int flags, mode_t mode)
951 if (db->hdb_master_key_set) {
952 krb5_error_code ret = HDB_ERR_NOENTRY;
953 krb5_warnx(context, "hdb_samba4_open: use of a master key incompatible with LDB\n");
954 krb5_set_error_message(context, ret, "hdb_samba4_open: use of a master key incompatible with LDB\n");
955 return ret;
958 return 0;
961 static krb5_error_code hdb_samba4_close(krb5_context context, HDB *db)
963 return 0;
966 static krb5_error_code hdb_samba4_lock(krb5_context context, HDB *db, int operation)
968 return 0;
971 static krb5_error_code hdb_samba4_unlock(krb5_context context, HDB *db)
973 return 0;
976 static krb5_error_code hdb_samba4_rename(krb5_context context, HDB *db, const char *new_name)
978 return HDB_ERR_DB_INUSE;
981 static krb5_error_code hdb_samba4_lookup_client(krb5_context context, HDB *db,
982 struct loadparm_context *lp_ctx,
983 TALLOC_CTX *mem_ctx,
984 krb5_const_principal principal,
985 const char **attrs,
986 struct ldb_dn **realm_dn,
987 struct ldb_message **msg) {
988 NTSTATUS nt_status;
989 char *principal_string;
990 krb5_error_code ret;
992 ret = krb5_unparse_name(context, principal, &principal_string);
994 if (ret != 0) {
995 return ret;
998 nt_status = sam_get_results_principal((struct ldb_context *)db->hdb_db,
999 mem_ctx, principal_string, attrs,
1000 realm_dn, msg);
1001 free(principal_string);
1002 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1003 return HDB_ERR_NOENTRY;
1004 } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1005 return ENOMEM;
1006 } else if (!NT_STATUS_IS_OK(nt_status)) {
1007 return EINVAL;
1010 return ret;
1013 static krb5_error_code hdb_samba4_fetch_client(krb5_context context, HDB *db,
1014 struct loadparm_context *lp_ctx,
1015 TALLOC_CTX *mem_ctx,
1016 krb5_const_principal principal,
1017 unsigned flags,
1018 hdb_entry_ex *entry_ex) {
1019 struct ldb_dn *realm_dn;
1020 krb5_error_code ret;
1021 struct ldb_message *msg = NULL;
1023 ret = hdb_samba4_lookup_client(context, db, lp_ctx,
1024 mem_ctx, principal, user_attrs,
1025 &realm_dn, &msg);
1026 if (ret != 0) {
1027 return ret;
1030 ret = hdb_samba4_message2entry(context, db, lp_ctx, mem_ctx,
1031 principal, HDB_SAMBA4_ENT_TYPE_CLIENT,
1032 realm_dn, msg, entry_ex);
1033 return ret;
1036 static krb5_error_code hdb_samba4_fetch_krbtgt(krb5_context context, HDB *db,
1037 struct loadparm_context *lp_ctx,
1038 TALLOC_CTX *mem_ctx,
1039 krb5_const_principal principal,
1040 unsigned flags,
1041 hdb_entry_ex *entry_ex)
1043 krb5_error_code ret;
1044 struct ldb_message *msg = NULL;
1045 struct ldb_dn *realm_dn = ldb_get_default_basedn(db->hdb_db);
1046 const char *realm;
1048 krb5_principal alloc_principal = NULL;
1049 if (principal->name.name_string.len != 2
1050 || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
1051 /* Not a krbtgt */
1052 return HDB_ERR_NOENTRY;
1055 /* krbtgt case. Either us or a trusted realm */
1057 if (lp_is_my_domain_or_realm(lp_ctx, principal->realm)
1058 && lp_is_my_domain_or_realm(lp_ctx, principal->name.name_string.val[1])) {
1059 /* us */
1060 /* Cludge, cludge cludge. If the realm part of krbtgt/realm,
1061 * is in our db, then direct the caller at our primary
1062 * krbtgt */
1064 int lret;
1065 char *realm_fixed;
1067 lret = gendb_search_single_extended_dn(db->hdb_db, mem_ctx,
1068 realm_dn, LDB_SCOPE_SUBTREE,
1069 &msg, krbtgt_attrs,
1070 "(&(objectClass=user)(samAccountName=krbtgt))");
1071 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1072 krb5_warnx(context, "hdb_samba4_fetch: could not find own KRBTGT in DB!");
1073 krb5_set_error_message(context, HDB_ERR_NOENTRY, "hdb_samba4_fetch: could not find own KRBTGT in DB!");
1074 return HDB_ERR_NOENTRY;
1075 } else if (lret != LDB_SUCCESS) {
1076 krb5_warnx(context, "hdb_samba4_fetch: could not find own KRBTGT in DB: %s", ldb_errstring(db->hdb_db));
1077 krb5_set_error_message(context, HDB_ERR_NOENTRY, "hdb_samba4_fetch: could not find own KRBTGT in DB: %s", ldb_errstring(db->hdb_db));
1078 return HDB_ERR_NOENTRY;
1081 realm_fixed = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
1082 if (!realm_fixed) {
1083 ret = ENOMEM;
1084 krb5_set_error_message(context, ret, "strupper_talloc: out of memory");
1085 return ret;
1088 ret = krb5_copy_principal(context, principal, &alloc_principal);
1089 if (ret) {
1090 return ret;
1093 free(alloc_principal->name.name_string.val[1]);
1094 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
1095 talloc_free(realm_fixed);
1096 if (!alloc_principal->name.name_string.val[1]) {
1097 ret = ENOMEM;
1098 krb5_set_error_message(context, ret, "hdb_samba4_fetch: strdup() failed!");
1099 return ret;
1101 principal = alloc_principal;
1103 ret = hdb_samba4_message2entry(context, db, lp_ctx, mem_ctx,
1104 principal, HDB_SAMBA4_ENT_TYPE_KRBTGT,
1105 realm_dn, msg, entry_ex);
1106 if (ret != 0) {
1107 krb5_warnx(context, "hdb_samba4_fetch: self krbtgt message2entry failed");
1109 return ret;
1111 } else {
1112 enum trust_direction direction = UNKNOWN;
1114 /* Either an inbound or outbound trust */
1116 if (strcasecmp(lp_realm(lp_ctx), principal->realm) == 0) {
1117 /* look for inbound trust */
1118 direction = INBOUND;
1119 realm = principal->name.name_string.val[1];
1122 if (strcasecmp(lp_realm(lp_ctx), principal->name.name_string.val[1]) == 0) {
1123 /* look for outbound trust */
1124 direction = OUTBOUND;
1125 realm = principal->realm;
1128 /* Trusted domains are under CN=system */
1130 ret = hdb_samba4_lookup_trust(context, (struct ldb_context *)db->hdb_db,
1131 mem_ctx,
1132 realm, realm_dn, &msg);
1134 if (ret != 0) {
1135 krb5_warnx(context, "hdb_samba4_fetch: could not find principal in DB");
1136 krb5_set_error_message(context, ret, "hdb_samba4_fetch: could not find principal in DB");
1137 return ret;
1140 ret = hdb_samba4_trust_message2entry(context, db, lp_ctx, mem_ctx,
1141 principal, direction,
1142 realm_dn, msg, entry_ex);
1143 if (ret != 0) {
1144 krb5_warnx(context, "hdb_samba4_fetch: trust_message2entry failed");
1146 return ret;
1149 /* we should lookup trusted domains */
1150 return HDB_ERR_NOENTRY;
1155 static krb5_error_code hdb_samba4_lookup_server(krb5_context context, HDB *db,
1156 struct loadparm_context *lp_ctx,
1157 TALLOC_CTX *mem_ctx,
1158 krb5_const_principal principal,
1159 const char **attrs,
1160 struct ldb_dn **realm_dn,
1161 struct ldb_message **msg)
1163 krb5_error_code ret;
1164 const char *realm;
1165 if (principal->name.name_string.len >= 2) {
1166 /* 'normal server' case */
1167 int ldb_ret;
1168 NTSTATUS nt_status;
1169 struct ldb_dn *user_dn;
1170 char *principal_string;
1172 ret = krb5_unparse_name_flags(context, principal,
1173 KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1174 &principal_string);
1175 if (ret != 0) {
1176 return ret;
1179 /* At this point we may find the host is known to be
1180 * in a different realm, so we should generate a
1181 * referral instead */
1182 nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db,
1183 mem_ctx, principal_string,
1184 &user_dn, realm_dn);
1185 free(principal_string);
1187 if (!NT_STATUS_IS_OK(nt_status)) {
1188 return HDB_ERR_NOENTRY;
1191 ldb_ret = gendb_search_single_extended_dn((struct ldb_context *)db->hdb_db,
1192 mem_ctx,
1193 user_dn, LDB_SCOPE_BASE,
1194 msg, attrs,
1195 "(objectClass=*)");
1196 if (ldb_ret != LDB_SUCCESS) {
1197 return HDB_ERR_NOENTRY;
1200 } else {
1201 int lret;
1202 char *filter = NULL;
1203 char *short_princ;
1204 /* server as client principal case, but we must not lookup userPrincipalNames */
1205 *realm_dn = ldb_get_default_basedn(db->hdb_db);
1206 realm = krb5_principal_get_realm(context, principal);
1208 /* TODO: Check if it is our realm, otherwise give referall */
1210 ret = krb5_unparse_name_flags(context, principal, KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
1212 if (ret != 0) {
1213 krb5_set_error_message(context, ret, "hdb_samba4_lookup_principal: could not parse principal");
1214 krb5_warnx(context, "hdb_samba4_lookup_principal: could not parse principal");
1215 return ret;
1218 lret = gendb_search_single_extended_dn(db->hdb_db, mem_ctx,
1219 *realm_dn, LDB_SCOPE_SUBTREE,
1220 msg, attrs, "(&(objectClass=user)(samAccountName=%s))",
1221 ldb_binary_encode_string(mem_ctx, short_princ));
1222 free(short_princ);
1223 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1224 DEBUG(3, ("Failed find a entry for %s\n", filter));
1225 return HDB_ERR_NOENTRY;
1227 if (lret != LDB_SUCCESS) {
1228 DEBUG(3, ("Failed single search for for %s - %s\n",
1229 filter, ldb_errstring(db->hdb_db)));
1230 return HDB_ERR_NOENTRY;
1234 return 0;
1237 static krb5_error_code hdb_samba4_fetch_server(krb5_context context, HDB *db,
1238 struct loadparm_context *lp_ctx,
1239 TALLOC_CTX *mem_ctx,
1240 krb5_const_principal principal,
1241 unsigned flags,
1242 hdb_entry_ex *entry_ex)
1244 krb5_error_code ret;
1245 struct ldb_dn *realm_dn;
1246 struct ldb_message *msg;
1248 ret = hdb_samba4_lookup_server(context, db, lp_ctx, mem_ctx, principal,
1249 server_attrs, &realm_dn, &msg);
1250 if (ret != 0) {
1251 return ret;
1254 ret = hdb_samba4_message2entry(context, db, lp_ctx, mem_ctx,
1255 principal, HDB_SAMBA4_ENT_TYPE_SERVER,
1256 realm_dn, msg, entry_ex);
1257 if (ret != 0) {
1258 krb5_warnx(context, "hdb_samba4_fetch: message2entry failed");
1261 return ret;
1264 static krb5_error_code hdb_samba4_fetch(krb5_context context, HDB *db,
1265 krb5_const_principal principal,
1266 unsigned flags,
1267 hdb_entry_ex *entry_ex)
1269 krb5_error_code ret = HDB_ERR_NOENTRY;
1270 TALLOC_CTX *mem_ctx = talloc_named(db, 0, "hdb_samba4_fetch context");
1271 struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(db->hdb_db, "loadparm"), struct loadparm_context);
1273 if (!mem_ctx) {
1274 ret = ENOMEM;
1275 krb5_set_error_message(context, ret, "hdb_samba4_fetch: talloc_named() failed!");
1276 return ret;
1279 if (flags & HDB_F_GET_CLIENT) {
1280 ret = hdb_samba4_fetch_client(context, db, lp_ctx, mem_ctx, principal, flags, entry_ex);
1281 if (ret != HDB_ERR_NOENTRY) goto done;
1283 if (flags & HDB_F_GET_SERVER) {
1284 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1285 ret = hdb_samba4_fetch_krbtgt(context, db, lp_ctx, mem_ctx, principal, flags, entry_ex);
1286 if (ret != HDB_ERR_NOENTRY) goto done;
1288 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1289 ret = hdb_samba4_fetch_server(context, db, lp_ctx, mem_ctx, principal, flags, entry_ex);
1290 if (ret != HDB_ERR_NOENTRY) goto done;
1292 if (flags & HDB_F_GET_KRBTGT) {
1293 ret = hdb_samba4_fetch_krbtgt(context, db, lp_ctx, mem_ctx, principal, flags, entry_ex);
1294 if (ret != HDB_ERR_NOENTRY) goto done;
1297 done:
1298 talloc_free(mem_ctx);
1299 return ret;
1302 static krb5_error_code hdb_samba4_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
1304 return HDB_ERR_DB_INUSE;
1307 static krb5_error_code hdb_samba4_remove(krb5_context context, HDB *db, krb5_const_principal principal)
1309 return HDB_ERR_DB_INUSE;
1312 struct hdb_samba4_seq {
1313 struct ldb_context *ctx;
1314 struct loadparm_context *lp_ctx;
1315 int index;
1316 int count;
1317 struct ldb_message **msgs;
1318 struct ldb_dn *realm_dn;
1321 static krb5_error_code hdb_samba4_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
1323 krb5_error_code ret;
1324 struct hdb_samba4_seq *priv = (struct hdb_samba4_seq *)db->hdb_dbc;
1325 TALLOC_CTX *mem_ctx;
1326 hdb_entry_ex entry_ex;
1327 memset(&entry_ex, '\0', sizeof(entry_ex));
1329 if (!priv) {
1330 return HDB_ERR_NOENTRY;
1333 mem_ctx = talloc_named(priv, 0, "hdb_samba4_seq context");
1335 if (!mem_ctx) {
1336 ret = ENOMEM;
1337 krb5_set_error_message(context, ret, "hdb_samba4_seq: talloc_named() failed!");
1338 return ret;
1341 if (priv->index < priv->count) {
1342 ret = hdb_samba4_message2entry(context, db, priv->lp_ctx,
1343 mem_ctx,
1344 NULL, HDB_SAMBA4_ENT_TYPE_ANY,
1345 priv->realm_dn, priv->msgs[priv->index++], entry);
1346 } else {
1347 ret = HDB_ERR_NOENTRY;
1350 if (ret != 0) {
1351 db->hdb_dbc = NULL;
1352 } else {
1353 talloc_free(mem_ctx);
1356 return ret;
1359 static krb5_error_code hdb_samba4_firstkey(krb5_context context, HDB *db, unsigned flags,
1360 hdb_entry_ex *entry)
1362 struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
1363 struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(ldb_ctx, "loadparm"),
1364 struct loadparm_context);
1365 struct hdb_samba4_seq *priv = (struct hdb_samba4_seq *)db->hdb_dbc;
1366 char *realm;
1367 struct ldb_result *res = NULL;
1368 krb5_error_code ret;
1369 TALLOC_CTX *mem_ctx;
1370 int lret;
1372 if (priv) {
1373 talloc_free(priv);
1374 db->hdb_dbc = NULL;
1377 priv = (struct hdb_samba4_seq *) talloc(db, struct hdb_samba4_seq);
1378 if (!priv) {
1379 ret = ENOMEM;
1380 krb5_set_error_message(context, ret, "talloc: out of memory");
1381 return ret;
1384 priv->ctx = ldb_ctx;
1385 priv->lp_ctx = lp_ctx;
1386 priv->index = 0;
1387 priv->msgs = NULL;
1388 priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
1389 priv->count = 0;
1391 mem_ctx = talloc_named(priv, 0, "hdb_samba4_firstkey context");
1393 if (!mem_ctx) {
1394 ret = ENOMEM;
1395 krb5_set_error_message(context, ret, "hdb_samba4_firstkey: talloc_named() failed!");
1396 return ret;
1399 ret = krb5_get_default_realm(context, &realm);
1400 if (ret != 0) {
1401 talloc_free(priv);
1402 return ret;
1405 lret = ldb_search(ldb_ctx, priv, &res,
1406 priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
1407 "(objectClass=user)");
1409 if (lret != LDB_SUCCESS) {
1410 talloc_free(priv);
1411 return HDB_ERR_NOENTRY;
1414 priv->count = res->count;
1415 priv->msgs = talloc_steal(priv, res->msgs);
1416 talloc_free(res);
1418 db->hdb_dbc = priv;
1420 ret = hdb_samba4_seq(context, db, flags, entry);
1422 if (ret != 0) {
1423 talloc_free(priv);
1424 db->hdb_dbc = NULL;
1425 } else {
1426 talloc_free(mem_ctx);
1428 return ret;
1431 static krb5_error_code hdb_samba4_nextkey(krb5_context context, HDB *db, unsigned flags,
1432 hdb_entry_ex *entry)
1434 return hdb_samba4_seq(context, db, flags, entry);
1437 static krb5_error_code hdb_samba4_destroy(krb5_context context, HDB *db)
1439 talloc_free(db);
1440 return 0;
1444 /* Check if a given entry may delegate to this target principal
1446 * This is currently a very nasty hack - allowing only delegation to itself.
1448 krb5_error_code hdb_samba4_check_constrained_delegation(krb5_context context, HDB *db,
1449 hdb_entry_ex *entry,
1450 krb5_const_principal target_principal)
1452 struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
1453 struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(ldb_ctx, "loadparm"),
1454 struct loadparm_context);
1455 krb5_error_code ret;
1456 krb5_principal enterprise_prinicpal = NULL;
1457 struct ldb_dn *realm_dn;
1458 struct ldb_message *msg;
1459 struct dom_sid *orig_sid;
1460 struct dom_sid *target_sid;
1461 struct hdb_samba4_private *p = talloc_get_type(entry->ctx, struct hdb_samba4_private);
1462 const char *delegation_check_attrs[] = {
1463 "objectSid", NULL
1466 TALLOC_CTX *mem_ctx = talloc_named(db, 0, "hdb_samba4_check_constrained_delegation");
1468 if (!mem_ctx) {
1469 ret = ENOMEM;
1470 krb5_set_error_message(context, ret, "hdb_samba4_fetch: talloc_named() failed!");
1471 return ret;
1474 if (target_principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1475 /* Need to reparse the enterprise principal to find the real target */
1476 if (target_principal->name.name_string.len != 1) {
1477 ret = KRB5_PARSE_MALFORMED;
1478 krb5_set_error_message(context, ret, "hdb_samba4_check_constrained_delegation: request for delegation to enterprise principal with wrong (%d) number of components",
1479 target_principal->name.name_string.len);
1480 talloc_free(mem_ctx);
1481 return ret;
1483 ret = krb5_parse_name(context, target_principal->name.name_string.val[0],
1484 &enterprise_prinicpal);
1485 if (ret) {
1486 talloc_free(mem_ctx);
1487 return ret;
1489 target_principal = enterprise_prinicpal;
1492 ret = hdb_samba4_lookup_server(context, db, lp_ctx, mem_ctx, target_principal,
1493 delegation_check_attrs, &realm_dn, &msg);
1495 krb5_free_principal(context, enterprise_prinicpal);
1497 if (ret != 0) {
1498 talloc_free(mem_ctx);
1499 return ret;
1502 orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1503 target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1505 /* Allow delegation to the same principal, even if by a different
1506 * name. The easy and safe way to prove this is by SID
1507 * comparison */
1508 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1509 talloc_free(mem_ctx);
1510 return KRB5KDC_ERR_BADOPTION;
1513 talloc_free(mem_ctx);
1514 return ret;
1517 /* Certificates printed by a the Certificate Authority might have a
1518 * slightly different form of the user principal name to that in the
1519 * database. Allow a mismatch where they both refer to the same
1520 * SID */
1522 krb5_error_code hdb_samba4_check_pkinit_ms_upn_match(krb5_context context, HDB *db,
1523 hdb_entry_ex *entry,
1524 krb5_const_principal certificate_principal)
1526 struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
1527 struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(ldb_ctx, "loadparm"),
1528 struct loadparm_context);
1529 krb5_error_code ret;
1530 struct ldb_dn *realm_dn;
1531 struct ldb_message *msg;
1532 struct dom_sid *orig_sid;
1533 struct dom_sid *target_sid;
1534 struct hdb_samba4_private *p = talloc_get_type(entry->ctx, struct hdb_samba4_private);
1535 const char *ms_upn_check_attrs[] = {
1536 "objectSid", NULL
1539 TALLOC_CTX *mem_ctx = talloc_named(db, 0, "hdb_samba4_check_constrained_delegation");
1541 if (!mem_ctx) {
1542 ret = ENOMEM;
1543 krb5_set_error_message(context, ret, "hdb_samba4_fetch: talloc_named() failed!");
1544 return ret;
1547 ret = hdb_samba4_lookup_client(context, db, lp_ctx,
1548 mem_ctx, certificate_principal,
1549 ms_upn_check_attrs, &realm_dn, &msg);
1551 if (ret != 0) {
1552 talloc_free(mem_ctx);
1553 return ret;
1556 orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1557 target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1559 /* Consider these to be the same principal, even if by a different
1560 * name. The easy and safe way to prove this is by SID
1561 * comparison */
1562 if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1563 talloc_free(mem_ctx);
1564 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1567 talloc_free(mem_ctx);
1568 return ret;
1571 /* This interface is to be called by the KDC and libnet_keytab_dump, which is expecting Samba
1572 * calling conventions. It is also called by a wrapper
1573 * (hdb_samba4_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb
1574 * code */
1576 NTSTATUS hdb_samba4_create_kdc(TALLOC_CTX *mem_ctx,
1577 struct tevent_context *ev_ctx,
1578 struct loadparm_context *lp_ctx,
1579 krb5_context context, struct HDB **db)
1581 NTSTATUS nt_status;
1582 struct auth_session_info *session_info;
1583 *db = talloc(mem_ctx, HDB);
1584 if (!*db) {
1585 krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
1586 return NT_STATUS_NO_MEMORY;
1589 (*db)->hdb_master_key_set = 0;
1590 (*db)->hdb_db = NULL;
1591 (*db)->hdb_capability_flags = 0;
1593 nt_status = auth_system_session_info(*db, lp_ctx, &session_info);
1594 if (!NT_STATUS_IS_OK(nt_status)) {
1595 return nt_status;
1598 /* The idea here is very simple. Using Kerberos to
1599 * authenticate the KDC to the LDAP server is higly likely to
1600 * be circular.
1602 * In future we may set this up to use EXERNAL and SSL
1603 * certificates, for now it will almost certainly be NTLMSSP
1606 cli_credentials_set_kerberos_state(session_info->credentials,
1607 CRED_DONT_USE_KERBEROS);
1609 /* Setup the link to LDB */
1610 (*db)->hdb_db = samdb_connect(*db, ev_ctx, lp_ctx, session_info);
1611 if ((*db)->hdb_db == NULL) {
1612 DEBUG(1, ("hdb_samba4_create: Cannot open samdb for KDC backend!"));
1613 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1616 (*db)->hdb_dbc = NULL;
1617 (*db)->hdb_open = hdb_samba4_open;
1618 (*db)->hdb_close = hdb_samba4_close;
1619 (*db)->hdb_fetch = hdb_samba4_fetch;
1620 (*db)->hdb_store = hdb_samba4_store;
1621 (*db)->hdb_remove = hdb_samba4_remove;
1622 (*db)->hdb_firstkey = hdb_samba4_firstkey;
1623 (*db)->hdb_nextkey = hdb_samba4_nextkey;
1624 (*db)->hdb_lock = hdb_samba4_lock;
1625 (*db)->hdb_unlock = hdb_samba4_unlock;
1626 (*db)->hdb_rename = hdb_samba4_rename;
1627 /* we don't implement these, as we are not a lockable database */
1628 (*db)->hdb__get = NULL;
1629 (*db)->hdb__put = NULL;
1630 /* kadmin should not be used for deletes - use other tools instead */
1631 (*db)->hdb__del = NULL;
1632 (*db)->hdb_destroy = hdb_samba4_destroy;
1634 (*db)->hdb_auth_status = NULL;
1635 (*db)->hdb_check_constrained_delegation = hdb_samba4_check_constrained_delegation;
1636 (*db)->hdb_check_pkinit_ms_upn_match = hdb_samba4_check_pkinit_ms_upn_match;
1638 return NT_STATUS_OK;
1641 static krb5_error_code hdb_samba4_create(krb5_context context, struct HDB **db, const char *arg)
1643 NTSTATUS nt_status;
1644 void *ptr;
1645 struct hdb_samba4_context *hdb_samba4_context;
1646 if (sscanf(arg, "&%p", &ptr) != 1) {
1647 return EINVAL;
1649 hdb_samba4_context = talloc_get_type_abort(ptr, struct hdb_samba4_context);
1650 /* The global kdc_mem_ctx and kdc_lp_ctx, Disgusting, ugly hack, but it means one less private hook */
1651 nt_status = hdb_samba4_create_kdc(hdb_samba4_context, hdb_samba4_context->ev_ctx, hdb_samba4_context->lp_ctx,
1652 context, db);
1654 if (NT_STATUS_IS_OK(nt_status)) {
1655 return 0;
1657 return EINVAL;
1660 /* Only used in the hdb-backed keytab code
1661 * for a keytab of 'samba4&<address>', to find
1662 * kpasswd's key in the main DB, and to
1663 * copy all the keys into a file (libnet_keytab_export)
1665 * The <address> is the string form of a pointer to a talloced struct hdb_samba_context
1667 struct hdb_method hdb_samba4 = {
1668 .interface_version = HDB_INTERFACE_VERSION,
1669 .prefix = "samba4",
1670 .create = hdb_samba4_create