s4-lsa Implement kerberos ticket life policy
[metze/samba/wip.git] / source4 / kdc / db-glue.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Database Glue between Samba and the KDC
5
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2009
7    Copyright (C) Simo Sorce <idra@samba.org> 2010
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "system/time.h"
26 #include "../libds/common/flags.h"
27 #include "lib/ldb/include/ldb.h"
28 #include "librpc/gen_ndr/netlogon.h"
29 #include "libcli/security/security.h"
30 #include "auth/auth.h"
31 #include "auth/credentials/credentials.h"
32 #include "auth/auth_sam.h"
33 #include "dsdb/samdb/samdb.h"
34 #include "dsdb/common/util.h"
35 #include "librpc/ndr/libndr.h"
36 #include "librpc/gen_ndr/ndr_drsblobs.h"
37 #include "librpc/gen_ndr/lsa.h"
38 #include "libcli/auth/libcli_auth.h"
39 #include "param/param.h"
40 #include "../lib/crypto/md4.h"
41 #include "system/kerberos.h"
42 #include "auth/kerberos/kerberos.h"
43 #include <hdb.h>
44 #include "kdc/samba_kdc.h"
45 #include "kdc/db-glue.h"
46 #include "kdc/kdc-policy.h"
47
48 enum samba_kdc_ent_type
49 { SAMBA_KDC_ENT_TYPE_CLIENT, SAMBA_KDC_ENT_TYPE_SERVER,
50   SAMBA_KDC_ENT_TYPE_KRBTGT, SAMBA_KDC_ENT_TYPE_TRUST, SAMBA_KDC_ENT_TYPE_ANY };
51
52 enum trust_direction {
53         UNKNOWN = 0,
54         INBOUND = LSA_TRUST_DIRECTION_INBOUND,
55         OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
56 };
57
58 static const char *trust_attrs[] = {
59         "trustPartner",
60         "trustAuthIncoming",
61         "trustAuthOutgoing",
62         "whenCreated",
63         "msDS-SupportedEncryptionTypes",
64         "trustAttributes",
65         "trustDirection",
66         "trustType",
67         NULL
68 };
69
70 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
71 {
72     const char *tmp;
73     const char *gentime;
74     struct tm tm;
75
76     gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
77     if (!gentime)
78         return default_val;
79
80     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
81     if (tmp == NULL) {
82             return default_val;
83     }
84
85     return timegm(&tm);
86 }
87
88 static HDBFlags uf2HDBFlags(krb5_context context, uint32_t userAccountControl, enum samba_kdc_ent_type ent_type)
89 {
90         HDBFlags flags = int2HDBFlags(0);
91
92         /* we don't allow kadmin deletes */
93         flags.immutable = 1;
94
95         /* mark the principal as invalid to start with */
96         flags.invalid = 1;
97
98         flags.renewable = 1;
99
100         /* All accounts are servers, but this may be disabled again in the caller */
101         flags.server = 1;
102
103         /* Account types - clear the invalid bit if it turns out to be valid */
104         if (userAccountControl & UF_NORMAL_ACCOUNT) {
105                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
106                         flags.client = 1;
107                 }
108                 flags.invalid = 0;
109         }
110
111         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
112                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
113                         flags.client = 1;
114                 }
115                 flags.invalid = 0;
116         }
117         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
118                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
119                         flags.client = 1;
120                 }
121                 flags.invalid = 0;
122         }
123         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
124                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
125                         flags.client = 1;
126                 }
127                 flags.invalid = 0;
128         }
129
130         /* Not permitted to act as a client if disabled */
131         if (userAccountControl & UF_ACCOUNTDISABLE) {
132                 flags.client = 0;
133         }
134         if (userAccountControl & UF_LOCKOUT) {
135                 flags.invalid = 1;
136         }
137 /*
138         if (userAccountControl & UF_PASSWORD_NOTREQD) {
139                 flags.invalid = 1;
140         }
141 */
142 /*
143         UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
144 */
145         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
146                 flags.invalid = 1;
147         }
148
149 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in samba_kdc_message2entry() */
150
151 /*
152         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
153                 flags.invalid = 1;
154         }
155 */
156         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
157                 flags.require_hwauth = 1;
158         }
159         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
160                 flags.ok_as_delegate = 1;
161         }
162         if (!(userAccountControl & UF_NOT_DELEGATED)) {
163                 flags.forwardable = 1;
164                 flags.proxiable = 1;
165         }
166
167         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
168                 flags.require_preauth = 0;
169         } else {
170                 flags.require_preauth = 1;
171
172         }
173         return flags;
174 }
175
176 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
177 {
178     hdb_entry_ex *entry_ex = p->entry_ex;
179     free_hdb_entry(&entry_ex->entry);
180     return 0;
181 }
182
183 static void samba_kdc_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
184 {
185         /* this function is called only from hdb_free_entry().
186          * Make sure we neutralize the destructor or we will
187          * get a double free later when hdb_free_entry() will
188          * try to call free_hdb_entry() */
189         talloc_set_destructor(entry_ex->ctx, NULL);
190
191         /* now proceed to free the talloc part */
192         talloc_free(entry_ex->ctx);
193 }
194
195 static krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
196                                                     struct samba_kdc_db_context *kdc_db_ctx,
197                                                     TALLOC_CTX *mem_ctx,
198                                                     struct ldb_message *msg,
199                                                     uint32_t rid,
200                                                     bool is_rodc,
201                                                     uint32_t userAccountControl,
202                                                     enum samba_kdc_ent_type ent_type,
203                                                     hdb_entry_ex *entry_ex)
204 {
205         krb5_error_code ret = 0;
206         enum ndr_err_code ndr_err;
207         struct samr_Password *hash;
208         const struct ldb_val *sc_val;
209         struct supplementalCredentialsBlob scb;
210         struct supplementalCredentialsPackage *scpk = NULL;
211         bool newer_keys = false;
212         struct package_PrimaryKerberosBlob _pkb;
213         struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
214         struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
215         uint16_t i;
216         uint16_t allocated_keys = 0;
217         int rodc_krbtgt_number = 0;
218         uint32_t supported_enctypes
219                 = ldb_msg_find_attr_as_uint(msg,
220                                             "msDS-SupportedEncryptionTypes",
221                                             0);
222
223         if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
224                 /* KDCs (and KDCs on RODCs) use AES */
225                 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
226         } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
227                 /* DCs and RODCs comptuer accounts use AES */
228                 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
229         } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
230                    (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
231                 /* for AS-REQ the client chooses the enc types it
232                  * supports, and this will vary between computers a
233                  * user logs in from.
234                  *
235                  * likewise for 'any' return as much as is supported,
236                  * to export into a keytab */
237                 supported_enctypes = ENC_ALL_TYPES;
238         }
239
240         /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
241         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
242                 supported_enctypes = ENC_CRC32|ENC_RSA_MD5;
243         } else {
244                 /* Otherwise, add in the default enc types */
245                 supported_enctypes |= ENC_CRC32 | ENC_RSA_MD5 | ENC_RC4_HMAC_MD5;
246         }
247
248         /* Is this the krbtgt or a RODC krbtgt */
249         if (is_rodc) {
250                 rodc_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
251
252                 if (rodc_krbtgt_number == -1) {
253                         return EINVAL;
254                 }
255         }
256
257
258         entry_ex->entry.keys.val = NULL;
259         entry_ex->entry.keys.len = 0;
260
261         entry_ex->entry.kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
262         if (is_rodc) {
263                 entry_ex->entry.kvno |= (rodc_krbtgt_number << 16);
264         }
265
266         /* Get keys from the db */
267
268         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
269         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
270
271         /* unicodePwd for enctype 0x17 (23) if present */
272         if (hash) {
273                 allocated_keys++;
274         }
275
276         /* supplementalCredentials if present */
277         if (sc_val) {
278                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
279                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
280                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
281                         dump_data(0, sc_val->data, sc_val->length);
282                         ret = EINVAL;
283                         goto out;
284                 }
285
286                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
287                         NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
288                         ret = EINVAL;
289                         goto out;
290                 }
291
292                 for (i=0; i < scb.sub.num_packages; i++) {
293                         if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
294                                 scpk = &scb.sub.packages[i];
295                                 if (!scpk->data || !scpk->data[0]) {
296                                         scpk = NULL;
297                                         continue;
298                                 }
299                                 newer_keys = true;
300                                 break;
301                         } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
302                                 scpk = &scb.sub.packages[i];
303                                 if (!scpk->data || !scpk->data[0]) {
304                                         scpk = NULL;
305                                 }
306                                 /*
307                                  * we don't break here in hope to find
308                                  * a Kerberos-Newer-Keys package
309                                  */
310                         }
311                 }
312         }
313         /*
314          * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
315          * of supplementalCredentials
316          */
317         if (scpk) {
318                 DATA_BLOB blob;
319
320                 blob = strhex_to_data_blob(mem_ctx, scpk->data);
321                 if (!blob.data) {
322                         ret = ENOMEM;
323                         goto out;
324                 }
325
326                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
327                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
328                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
329                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
330                         ret = EINVAL;
331                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
332                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
333                         goto out;
334                 }
335
336                 if (newer_keys && _pkb.version != 4) {
337                         ret = EINVAL;
338                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
339                         krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
340                         goto out;
341                 }
342
343                 if (!newer_keys && _pkb.version != 3) {
344                         ret = EINVAL;
345                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
346                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
347                         goto out;
348                 }
349
350                 if (_pkb.version == 4) {
351                         pkb4 = &_pkb.ctr.ctr4;
352                         allocated_keys += pkb4->num_keys;
353                 } else if (_pkb.version == 3) {
354                         pkb3 = &_pkb.ctr.ctr3;
355                         allocated_keys += pkb3->num_keys;
356                 }
357         }
358
359         if (allocated_keys == 0) {
360                 if (kdc_db_ctx->rodc) {
361                         /* We are on an RODC, but don't have keys for this account.  Signal this to the caller */
362                         return HDB_ERR_NOT_FOUND_HERE;
363                 }
364
365                 /* oh, no password.  Apparently (comment in
366                  * hdb-ldap.c) this violates the ASN.1, but this
367                  * allows an entry with no keys (yet). */
368                 return 0;
369         }
370
371         /* allocate space to decode into */
372         entry_ex->entry.keys.len = 0;
373         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
374         if (entry_ex->entry.keys.val == NULL) {
375                 ret = ENOMEM;
376                 goto out;
377         }
378
379         if (hash && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
380                 Key key;
381
382                 key.mkvno = 0;
383                 key.salt = NULL; /* No salt for this enc type */
384
385                 ret = krb5_keyblock_init(context,
386                                          ENCTYPE_ARCFOUR_HMAC,
387                                          hash->hash, sizeof(hash->hash),
388                                          &key.key);
389                 if (ret) {
390                         goto out;
391                 }
392
393                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
394                 entry_ex->entry.keys.len++;
395         }
396
397         if (pkb4) {
398                 for (i=0; i < pkb4->num_keys; i++) {
399                         Key key;
400
401                         if (!pkb4->keys[i].value) continue;
402
403                         if (!(kerberos_enctype_to_bitmap(pkb4->keys[i].keytype) & supported_enctypes)) {
404                                 continue;
405                         }
406
407                         key.mkvno = 0;
408                         key.salt = NULL;
409
410                         if (pkb4->salt.string) {
411                                 DATA_BLOB salt;
412
413                                 salt = data_blob_string_const(pkb4->salt.string);
414
415                                 key.salt = calloc(1, sizeof(*key.salt));
416                                 if (key.salt == NULL) {
417                                         ret = ENOMEM;
418                                         goto out;
419                                 }
420
421                                 key.salt->type = hdb_pw_salt;
422
423                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
424                                 if (ret) {
425                                         free(key.salt);
426                                         key.salt = NULL;
427                                         goto out;
428                                 }
429                         }
430
431                         /* TODO: maybe pass the iteration_count somehow... */
432
433                         ret = krb5_keyblock_init(context,
434                                                  pkb4->keys[i].keytype,
435                                                  pkb4->keys[i].value->data,
436                                                  pkb4->keys[i].value->length,
437                                                  &key.key);
438                         if (ret == KRB5_PROG_ETYPE_NOSUPP) {
439                                 DEBUG(2,("Unsupported keytype ignored - type %u\n",
440                                          pkb4->keys[i].keytype));
441                                 ret = 0;
442                                 continue;
443                         }
444                         if (ret) {
445                                 if (key.salt) {
446                                         free_Salt(key.salt);
447                                         free(key.salt);
448                                         key.salt = NULL;
449                                 }
450                                 goto out;
451                         }
452
453                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
454                         entry_ex->entry.keys.len++;
455                 }
456         } else if (pkb3) {
457                 for (i=0; i < pkb3->num_keys; i++) {
458                         Key key;
459
460                         if (!pkb3->keys[i].value) continue;
461
462                         if (!(kerberos_enctype_to_bitmap(pkb3->keys[i].keytype) & supported_enctypes)) {
463                                 continue;
464                         }
465
466                         key.mkvno = 0;
467                         key.salt = NULL;
468
469                         if (pkb3->salt.string) {
470                                 DATA_BLOB salt;
471
472                                 salt = data_blob_string_const(pkb3->salt.string);
473
474                                 key.salt = calloc(1, sizeof(*key.salt));
475                                 if (key.salt == NULL) {
476                                         ret = ENOMEM;
477                                         goto out;
478                                 }
479
480                                 key.salt->type = hdb_pw_salt;
481
482                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
483                                 if (ret) {
484                                         free(key.salt);
485                                         key.salt = NULL;
486                                         goto out;
487                                 }
488                         }
489
490                         ret = krb5_keyblock_init(context,
491                                                  pkb3->keys[i].keytype,
492                                                  pkb3->keys[i].value->data,
493                                                  pkb3->keys[i].value->length,
494                                                  &key.key);
495                         if (ret) {
496                                 if (key.salt) {
497                                         free_Salt(key.salt);
498                                         free(key.salt);
499                                         key.salt = NULL;
500                                 }
501                                 goto out;
502                         }
503
504                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
505                         entry_ex->entry.keys.len++;
506                 }
507         }
508
509 out:
510         if (ret != 0) {
511                 entry_ex->entry.keys.len = 0;
512         }
513         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
514                 free(entry_ex->entry.keys.val);
515                 entry_ex->entry.keys.val = NULL;
516         }
517         return ret;
518 }
519
520 /*
521  * Construct an hdb_entry from a directory entry.
522  */
523 static krb5_error_code samba_kdc_message2entry(krb5_context context,
524                                                struct samba_kdc_db_context *kdc_db_ctx,
525                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
526                                                enum samba_kdc_ent_type ent_type,
527                                                unsigned flags,
528                                                struct ldb_dn *realm_dn,
529                                                struct ldb_message *msg,
530                                                hdb_entry_ex *entry_ex)
531 {
532         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
533         uint32_t userAccountControl;
534         unsigned int i;
535         krb5_error_code ret = 0;
536         krb5_boolean is_computer = FALSE;
537
538         struct samba_kdc_entry *p;
539         NTTIME acct_expiry;
540         NTSTATUS status;
541
542         uint32_t rid;
543         bool is_rodc = false;
544         struct ldb_message_element *objectclasses;
545         struct ldb_val computer_val;
546         const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
547         computer_val.data = discard_const_p(uint8_t,"computer");
548         computer_val.length = strlen((const char *)computer_val.data);
549
550         if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
551                 is_rodc = true;
552         }
553
554         if (!samAccountName) {
555                 ret = ENOENT;
556                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
557                 goto out;
558         }
559
560         objectclasses = ldb_msg_find_element(msg, "objectClass");
561
562         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
563                 is_computer = TRUE;
564         }
565
566         memset(entry_ex, 0, sizeof(*entry_ex));
567
568         p = talloc(mem_ctx, struct samba_kdc_entry);
569         if (!p) {
570                 ret = ENOMEM;
571                 goto out;
572         }
573
574         p->kdc_db_ctx = kdc_db_ctx;
575         p->entry_ex = entry_ex;
576         p->realm_dn = talloc_reference(p, realm_dn);
577         if (!p->realm_dn) {
578                 ret = ENOMEM;
579                 goto out;
580         }
581
582         talloc_set_destructor(p, samba_kdc_entry_destructor);
583
584         /* make sure we do not have bogus data in there */
585         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
586
587         entry_ex->ctx = p;
588         entry_ex->free_entry = samba_kdc_free_entry;
589
590         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
591
592
593         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
594         if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
595                 krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
596         } else {
597                 ret = copy_Principal(principal, entry_ex->entry.principal);
598                 if (ret) {
599                         krb5_clear_error_message(context);
600                         goto out;
601                 }
602
603                 /* While we have copied the client principal, tests
604                  * show that Win2k3 returns the 'corrected' realm, not
605                  * the client-specified realm.  This code attempts to
606                  * replace the client principal's realm with the one
607                  * we determine from our records */
608
609                 /* this has to be with malloc() */
610                 krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
611         }
612
613         /* First try and figure out the flags based on the userAccountControl */
614         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
615
616         /* Windows 2008 seems to enforce this (very sensible) rule by
617          * default - don't allow offline attacks on a user's password
618          * by asking for a ticket to them as a service (encrypted with
619          * their probably patheticly insecure password) */
620
621         if (entry_ex->entry.flags.server
622             && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
623                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
624                         entry_ex->entry.flags.server = 0;
625                 }
626         }
627
628         if (flags & HDB_F_ADMIN_DATA) {
629                 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
630                  * of the Heimdal KDC.  They are stored in a the traditional
631                  * DB for audit purposes, and still form part of the structure
632                  * we must return */
633
634                 /* use 'whenCreated' */
635                 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
636                 /* use 'kadmin' for now (needed by mit_samba) */
637                 krb5_make_principal(context,
638                                     &entry_ex->entry.created_by.principal,
639                                     lpcfg_realm(lp_ctx), "kadmin", NULL);
640
641                 entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
642                 if (entry_ex->entry.modified_by == NULL) {
643                         ret = ENOMEM;
644                         krb5_set_error_message(context, ret, "malloc: out of memory");
645                         goto out;
646                 }
647
648                 /* use 'whenChanged' */
649                 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
650                 /* use 'kadmin' for now (needed by mit_samba) */
651                 krb5_make_principal(context,
652                                     &entry_ex->entry.modified_by->principal,
653                                     lpcfg_realm(lp_ctx), "kadmin", NULL);
654         }
655
656
657         /* The lack of password controls etc applies to krbtgt by
658          * virtue of being that particular RID */
659         status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
660
661         if (!NT_STATUS_IS_OK(status)) {
662                 ret = EINVAL;
663                 goto out;
664         }
665
666         if (rid == DOMAIN_RID_KRBTGT) {
667                 entry_ex->entry.valid_end = NULL;
668                 entry_ex->entry.pw_end = NULL;
669
670                 entry_ex->entry.flags.invalid = 0;
671                 entry_ex->entry.flags.server = 1;
672
673                 /* Don't mark all requests for the krbtgt/realm as
674                  * 'change password', as otherwise we could get into
675                  * trouble, and not enforce the password expirty.
676                  * Instead, only do it when request is for the kpasswd service */
677                 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
678                     && principal->name.name_string.len == 2
679                     && (strcmp(principal->name.name_string.val[0], "kadmin") == 0)
680                     && (strcmp(principal->name.name_string.val[1], "changepw") == 0)
681                     && lpcfg_is_my_domain_or_realm(lp_ctx, principal->realm)) {
682                         entry_ex->entry.flags.change_pw = 1;
683                 }
684                 entry_ex->entry.flags.client = 0;
685                 entry_ex->entry.flags.forwardable = 1;
686                 entry_ex->entry.flags.ok_as_delegate = 1;
687         } else if (is_rodc) {
688                 /* The RODC krbtgt account is like the main krbtgt,
689                  * but it does not have a changepw or kadmin
690                  * service */
691
692                 entry_ex->entry.valid_end = NULL;
693                 entry_ex->entry.pw_end = NULL;
694
695                 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
696                 entry_ex->entry.flags.client = 0;
697                 entry_ex->entry.flags.invalid = 0;
698                 entry_ex->entry.flags.server = 1;
699
700                 entry_ex->entry.flags.client = 0;
701                 entry_ex->entry.flags.forwardable = 1;
702                 entry_ex->entry.flags.ok_as_delegate = 0;
703         } else if (entry_ex->entry.flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
704                 /* The account/password expiry only applies when the account is used as a
705                  * client (ie password login), not when used as a server */
706
707                 /* Make very well sure we don't use this for a client,
708                  * it could bypass the password restrictions */
709                 entry_ex->entry.flags.client = 0;
710
711                 entry_ex->entry.valid_end = NULL;
712                 entry_ex->entry.pw_end = NULL;
713
714         } else {
715                 NTTIME must_change_time
716                         = samdb_result_force_password_change(kdc_db_ctx->samdb, mem_ctx,
717                                                              realm_dn, msg);
718                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
719                         entry_ex->entry.pw_end = NULL;
720                 } else {
721                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
722                         if (entry_ex->entry.pw_end == NULL) {
723                                 ret = ENOMEM;
724                                 goto out;
725                         }
726                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
727                 }
728
729                 acct_expiry = samdb_result_account_expires(msg);
730                 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
731                         entry_ex->entry.valid_end = NULL;
732                 } else {
733                         entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
734                         if (entry_ex->entry.valid_end == NULL) {
735                                 ret = ENOMEM;
736                                 goto out;
737                         }
738                         *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
739                 }
740         }
741
742         entry_ex->entry.valid_start = NULL;
743
744         entry_ex->entry.max_life = malloc(sizeof(*entry_ex->entry.max_life));
745         if (entry_ex->entry.max_life == NULL) {
746                 ret = ENOMEM;
747                 goto out;
748         }
749
750         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
751                 *entry_ex->entry.max_life = nt_time_to_unix(kdc_db_ctx->policy.service_tkt_lifetime);
752         } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
753                 *entry_ex->entry.max_life = nt_time_to_unix(kdc_db_ctx->policy.user_tkt_lifetime);
754         } else {
755                 *entry_ex->entry.max_life = MIN(nt_time_to_unix(kdc_db_ctx->policy.service_tkt_lifetime),
756                                                nt_time_to_unix(kdc_db_ctx->policy.user_tkt_lifetime));
757         }
758
759         entry_ex->entry.max_renew = malloc(sizeof(*entry_ex->entry.max_life));
760         if (entry_ex->entry.max_renew == NULL) {
761                 ret = ENOMEM;
762                 goto out;
763         }
764
765         *entry_ex->entry.max_renew = nt_time_to_unix(kdc_db_ctx->policy.user_tkt_renewaltime);
766
767         entry_ex->entry.generation = NULL;
768
769         /* Get keys from the db */
770         ret = samba_kdc_message2entry_keys(context, kdc_db_ctx, p, msg,
771                                            rid, is_rodc, userAccountControl,
772                                            ent_type, entry_ex);
773         if (ret) {
774                 /* Could be bougus data in the entry, or out of memory */
775                 goto out;
776         }
777
778         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
779         if (entry_ex->entry.etypes == NULL) {
780                 krb5_clear_error_message(context);
781                 ret = ENOMEM;
782                 goto out;
783         }
784         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
785         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
786         if (entry_ex->entry.etypes->val == NULL) {
787                 krb5_clear_error_message(context);
788                 ret = ENOMEM;
789                 goto out;
790         }
791         for (i=0; i < entry_ex->entry.etypes->len; i++) {
792                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
793         }
794
795
796         p->msg = talloc_steal(p, msg);
797
798 out:
799         if (ret != 0) {
800                 /* This doesn't free ent itself, that is for the eventual caller to do */
801                 hdb_free_entry(context, entry_ex);
802         } else {
803                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
804         }
805
806         return ret;
807 }
808
809 /*
810  * Construct an hdb_entry from a directory entry.
811  */
812 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
813                                                struct samba_kdc_db_context *kdc_db_ctx,
814                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
815                                                enum trust_direction direction,
816                                                struct ldb_dn *realm_dn,
817                                                struct ldb_message *msg,
818                                                hdb_entry_ex *entry_ex)
819 {
820         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
821         const char *dnsdomain;
822         const char *realm = lpcfg_realm(lp_ctx);
823         DATA_BLOB password_utf16;
824         struct samr_Password password_hash;
825         const struct ldb_val *password_val;
826         struct trustAuthInOutBlob password_blob;
827         struct samba_kdc_entry *p;
828
829         enum ndr_err_code ndr_err;
830         int ret, trust_direction_flags;
831         unsigned int i;
832
833         p = talloc(mem_ctx, struct samba_kdc_entry);
834         if (!p) {
835                 ret = ENOMEM;
836                 goto out;
837         }
838
839         p->kdc_db_ctx = kdc_db_ctx;
840         p->entry_ex = entry_ex;
841         p->realm_dn = realm_dn;
842
843         talloc_set_destructor(p, samba_kdc_entry_destructor);
844
845         /* make sure we do not have bogus data in there */
846         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
847
848         entry_ex->ctx = p;
849         entry_ex->free_entry = samba_kdc_free_entry;
850
851         /* use 'whenCreated' */
852         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
853         /* use 'kadmin' for now (needed by mit_samba) */
854         krb5_make_principal(context,
855                             &entry_ex->entry.created_by.principal,
856                             realm, "kadmin", NULL);
857
858         entry_ex->entry.valid_start = NULL;
859
860         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
861
862         if (direction == INBOUND) {
863                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
864
865         } else { /* OUTBOUND */
866                 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
867                 /* replace realm */
868                 realm = strupper_talloc(mem_ctx, dnsdomain);
869                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
870         }
871
872         if (!password_val || !(trust_direction_flags & direction)) {
873                 ret = ENOENT;
874                 goto out;
875         }
876
877         ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
878                                            (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
879         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
880                 ret = EINVAL;
881                 goto out;
882         }
883
884         entry_ex->entry.kvno = -1;
885         for (i=0; i < password_blob.count; i++) {
886                 if (password_blob.current.array[i].AuthType == TRUST_AUTH_TYPE_VERSION) {
887                         entry_ex->entry.kvno = password_blob.current.array[i].AuthInfo.version.version;
888                 }
889         }
890
891         for (i=0; i < password_blob.count; i++) {
892                 if (password_blob.current.array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
893                         password_utf16 = data_blob_const(password_blob.current.array[i].AuthInfo.clear.password,
894                                                          password_blob.current.array[i].AuthInfo.clear.size);
895                         /* In the future, generate all sorts of
896                          * hashes, but for now we can't safely convert
897                          * the random strings windows uses into
898                          * utf8 */
899
900                         /* but as it is utf16 already, we can get the NT password/arcfour-hmac-md5 key */
901                         mdfour(password_hash.hash, password_utf16.data, password_utf16.length);
902                         break;
903                 } else if (password_blob.current.array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
904                         password_hash = password_blob.current.array[i].AuthInfo.nt4owf.password;
905                         break;
906                 }
907         }
908
909         if (i < password_blob.count) {
910                 Key key;
911                 /* Must have found a cleartext or MD4 password */
912                 entry_ex->entry.keys.val = calloc(1, sizeof(Key));
913
914                 key.mkvno = 0;
915                 key.salt = NULL; /* No salt for this enc type */
916
917                 if (entry_ex->entry.keys.val == NULL) {
918                         ret = ENOMEM;
919                         goto out;
920                 }
921
922                 ret = krb5_keyblock_init(context,
923                                          ENCTYPE_ARCFOUR_HMAC,
924                                          password_hash.hash, sizeof(password_hash.hash),
925                                          &key.key);
926
927                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
928                 entry_ex->entry.keys.len++;
929         }
930
931         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
932
933         ret = copy_Principal(principal, entry_ex->entry.principal);
934         if (ret) {
935                 krb5_clear_error_message(context);
936                 goto out;
937         }
938
939         /* While we have copied the client principal, tests
940          * show that Win2k3 returns the 'corrected' realm, not
941          * the client-specified realm.  This code attempts to
942          * replace the client principal's realm with the one
943          * we determine from our records */
944
945         krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
946         entry_ex->entry.flags = int2HDBFlags(0);
947         entry_ex->entry.flags.immutable = 1;
948         entry_ex->entry.flags.invalid = 0;
949         entry_ex->entry.flags.server = 1;
950         entry_ex->entry.flags.require_preauth = 1;
951
952         entry_ex->entry.pw_end = NULL;
953
954         entry_ex->entry.max_life = NULL;
955
956         entry_ex->entry.max_renew = NULL;
957
958         entry_ex->entry.generation = NULL;
959
960         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
961         if (entry_ex->entry.etypes == NULL) {
962                 krb5_clear_error_message(context);
963                 ret = ENOMEM;
964                 goto out;
965         }
966         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
967         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
968         if (entry_ex->entry.etypes->val == NULL) {
969                 krb5_clear_error_message(context);
970                 ret = ENOMEM;
971                 goto out;
972         }
973         for (i=0; i < entry_ex->entry.etypes->len; i++) {
974                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
975         }
976
977
978         p->msg = talloc_steal(p, msg);
979
980 out:
981         if (ret != 0) {
982                 /* This doesn't free ent itself, that is for the eventual caller to do */
983                 hdb_free_entry(context, entry_ex);
984         } else {
985                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
986         }
987
988         return ret;
989
990 }
991
992 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
993                                         TALLOC_CTX *mem_ctx,
994                                         const char *realm,
995                                         struct ldb_dn *realm_dn,
996                                         struct ldb_message **pmsg)
997 {
998         int lret;
999         krb5_error_code ret;
1000         char *filter = NULL;
1001         const char * const *attrs = trust_attrs;
1002
1003         struct ldb_result *res = NULL;
1004         filter = talloc_asprintf(mem_ctx, "(&(objectClass=trustedDomain)(|(flatname=%s)(trustPartner=%s)))", realm, realm);
1005
1006         if (!filter) {
1007                 ret = ENOMEM;
1008                 krb5_set_error_message(context, ret, "talloc_asprintf: out of memory");
1009                 return ret;
1010         }
1011
1012         lret = ldb_search(ldb_ctx, mem_ctx, &res,
1013                           ldb_get_default_basedn(ldb_ctx),
1014                           LDB_SCOPE_SUBTREE, attrs, "%s", filter);
1015         if (lret != LDB_SUCCESS) {
1016                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
1017                 return HDB_ERR_NOENTRY;
1018         } else if (res->count == 0 || res->count > 1) {
1019                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
1020                 talloc_free(res);
1021                 return HDB_ERR_NOENTRY;
1022         }
1023         talloc_steal(mem_ctx, res->msgs);
1024         *pmsg = res->msgs[0];
1025         talloc_free(res);
1026         return 0;
1027 }
1028
1029 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
1030                                                 struct samba_kdc_db_context *kdc_db_ctx,
1031                                                 TALLOC_CTX *mem_ctx,
1032                                                 krb5_const_principal principal,
1033                                                 const char **attrs,
1034                                                 struct ldb_dn **realm_dn,
1035                                                 struct ldb_message **msg) {
1036         NTSTATUS nt_status;
1037         char *principal_string;
1038         krb5_error_code ret;
1039
1040         ret = krb5_unparse_name(context, principal, &principal_string);
1041
1042         if (ret != 0) {
1043                 return ret;
1044         }
1045
1046         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1047                                               mem_ctx, principal_string, attrs,
1048                                               realm_dn, msg);
1049         free(principal_string);
1050         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1051                 return HDB_ERR_NOENTRY;
1052         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1053                 return ENOMEM;
1054         } else if (!NT_STATUS_IS_OK(nt_status)) {
1055                 return EINVAL;
1056         }
1057
1058         return ret;
1059 }
1060
1061 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1062                                                struct samba_kdc_db_context *kdc_db_ctx,
1063                                                TALLOC_CTX *mem_ctx,
1064                                                krb5_const_principal principal,
1065                                                unsigned flags,
1066                                                hdb_entry_ex *entry_ex) {
1067         struct ldb_dn *realm_dn;
1068         krb5_error_code ret;
1069         struct ldb_message *msg = NULL;
1070
1071         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1072                                        mem_ctx, principal, user_attrs,
1073                                        &realm_dn, &msg);
1074         if (ret != 0) {
1075                 return ret;
1076         }
1077
1078         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1079                                       principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1080                                       flags,
1081                                       realm_dn, msg, entry_ex);
1082         return ret;
1083 }
1084
1085 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1086                                               struct samba_kdc_db_context *kdc_db_ctx,
1087                                               TALLOC_CTX *mem_ctx,
1088                                               krb5_const_principal principal,
1089                                               unsigned flags,
1090                                               uint32_t krbtgt_number,
1091                                               hdb_entry_ex *entry_ex)
1092 {
1093         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1094         krb5_error_code ret;
1095         struct ldb_message *msg = NULL;
1096         struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1097
1098         krb5_principal alloc_principal = NULL;
1099         if (principal->name.name_string.len != 2
1100             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
1101                 /* Not a krbtgt */
1102                 return HDB_ERR_NOENTRY;
1103         }
1104
1105         /* krbtgt case.  Either us or a trusted realm */
1106
1107         if (lpcfg_is_my_domain_or_realm(lp_ctx, principal->realm)
1108             && lpcfg_is_my_domain_or_realm(lp_ctx, principal->name.name_string.val[1])) {
1109                 /* us, or someone quite like us */
1110                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1111                  * is in our db, then direct the caller at our primary
1112                  * krbtgt */
1113
1114                 int lret;
1115
1116                 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
1117                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1118                                                &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1119                                                krbtgt_attrs, 0,
1120                                                "(objectClass=user)");
1121                 } else {
1122                         /* We need to look up an RODC krbtgt (perhaps
1123                          * ours, if we are an RODC, perhaps another
1124                          * RODC if we are a read-write DC */
1125                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1126                                                &msg, realm_dn, LDB_SCOPE_SUBTREE,
1127                                                krbtgt_attrs,
1128                                                DSDB_SEARCH_SHOW_EXTENDED_DN,
1129                                                "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
1130                 }
1131
1132                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1133                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1134                                    (unsigned)(krbtgt_number));
1135                         krb5_set_error_message(context, HDB_ERR_NOENTRY,
1136                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1137                                                (unsigned)(krbtgt_number));
1138                         return HDB_ERR_NOENTRY;
1139                 } else if (lret != LDB_SUCCESS) {
1140                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1141                                    (unsigned)(krbtgt_number));
1142                         krb5_set_error_message(context, HDB_ERR_NOENTRY,
1143                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1144                                                (unsigned)(krbtgt_number));
1145                         return HDB_ERR_NOENTRY;
1146                 }
1147
1148                 if (flags & HDB_F_CANON) {
1149                         ret = krb5_copy_principal(context, principal, &alloc_principal);
1150                         if (ret) {
1151                                 return ret;
1152                         }
1153
1154                         /* When requested to do so, ensure that the
1155                          * both realm values in the principal are set
1156                          * to the upper case, canonical realm */
1157                         free(alloc_principal->name.name_string.val[1]);
1158                         alloc_principal->name.name_string.val[1] = strdup(lpcfg_realm(lp_ctx));
1159                         if (!alloc_principal->name.name_string.val[1]) {
1160                                 ret = ENOMEM;
1161                                 krb5_set_error_message(context, ret, "samba_kdc_fetch: strdup() failed!");
1162                                 return ret;
1163                         }
1164                         principal = alloc_principal;
1165                 }
1166
1167                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1168                                               principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
1169                                               flags, realm_dn, msg, entry_ex);
1170                 if (flags & HDB_F_CANON) {
1171                         /* This is again copied in the message2entry call */
1172                         krb5_free_principal(context, alloc_principal);
1173                 }
1174                 if (ret != 0) {
1175                         krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
1176                 }
1177                 return ret;
1178
1179         } else {
1180                 enum trust_direction direction = UNKNOWN;
1181                 const char *realm = NULL;
1182
1183                 /* Either an inbound or outbound trust */
1184
1185                 if (strcasecmp(lpcfg_realm(lp_ctx), principal->realm) == 0) {
1186                         /* look for inbound trust */
1187                         direction = INBOUND;
1188                         realm = principal->name.name_string.val[1];
1189                 } else if (strcasecmp(lpcfg_realm(lp_ctx), principal->name.name_string.val[1]) == 0) {
1190                         /* look for outbound trust */
1191                         direction = OUTBOUND;
1192                         realm = principal->realm;
1193                 } else {
1194                         krb5_warnx(context, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1195                                    principal->realm, principal->name.name_string.val[1]);
1196                         krb5_set_error_message(context, HDB_ERR_NOENTRY, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1197                                                principal->realm, principal->name.name_string.val[1]);
1198                         return HDB_ERR_NOENTRY;
1199                 }
1200
1201                 /* Trusted domains are under CN=system */
1202
1203                 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
1204                                        mem_ctx,
1205                                        realm, realm_dn, &msg);
1206
1207                 if (ret != 0) {
1208                         krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
1209                         krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
1210                         return ret;
1211                 }
1212
1213                 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
1214                                               principal, direction,
1215                                               realm_dn, msg, entry_ex);
1216                 if (ret != 0) {
1217                         krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed");
1218                 }
1219                 return ret;
1220         }
1221
1222 }
1223
1224 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
1225                                                 struct samba_kdc_db_context *kdc_db_ctx,
1226                                                 TALLOC_CTX *mem_ctx,
1227                                                 krb5_const_principal principal,
1228                                                 const char **attrs,
1229                                                 struct ldb_dn **realm_dn,
1230                                                 struct ldb_message **msg)
1231 {
1232         krb5_error_code ret;
1233         if (principal->name.name_string.len >= 2) {
1234                 /* 'normal server' case */
1235                 int ldb_ret;
1236                 NTSTATUS nt_status;
1237                 struct ldb_dn *user_dn;
1238                 char *principal_string;
1239
1240                 ret = krb5_unparse_name_flags(context, principal,
1241                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1242                                               &principal_string);
1243                 if (ret != 0) {
1244                         return ret;
1245                 }
1246
1247                 /* At this point we may find the host is known to be
1248                  * in a different realm, so we should generate a
1249                  * referral instead */
1250                 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
1251                                                          mem_ctx, principal_string,
1252                                                          &user_dn, realm_dn);
1253                 free(principal_string);
1254
1255                 if (!NT_STATUS_IS_OK(nt_status)) {
1256                         return HDB_ERR_NOENTRY;
1257                 }
1258
1259                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
1260                                           mem_ctx,
1261                                           msg, user_dn, LDB_SCOPE_BASE,
1262                                           attrs, DSDB_SEARCH_SHOW_EXTENDED_DN, "(objectClass=*)");
1263                 if (ldb_ret != LDB_SUCCESS) {
1264                         return HDB_ERR_NOENTRY;
1265                 }
1266
1267         } else {
1268                 int lret;
1269                 char *filter = NULL;
1270                 char *short_princ;
1271                 const char *realm;
1272                 /* server as client principal case, but we must not lookup userPrincipalNames */
1273                 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1274                 realm = krb5_principal_get_realm(context, principal);
1275
1276                 /* TODO: Check if it is our realm, otherwise give referall */
1277
1278                 ret = krb5_unparse_name_flags(context, principal,  KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
1279
1280                 if (ret != 0) {
1281                         krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
1282                         krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
1283                         return ret;
1284                 }
1285
1286                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
1287                                        *realm_dn, LDB_SCOPE_SUBTREE,
1288                                        attrs,
1289                                        DSDB_SEARCH_SHOW_EXTENDED_DN,
1290                                        "(&(objectClass=user)(samAccountName=%s))",
1291                                        ldb_binary_encode_string(mem_ctx, short_princ));
1292                 free(short_princ);
1293                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1294                         DEBUG(3, ("Failed find a entry for %s\n", filter));
1295                         return HDB_ERR_NOENTRY;
1296                 }
1297                 if (lret != LDB_SUCCESS) {
1298                         DEBUG(3, ("Failed single search for for %s - %s\n",
1299                                   filter, ldb_errstring(kdc_db_ctx->samdb)));
1300                         return HDB_ERR_NOENTRY;
1301                 }
1302         }
1303
1304         return 0;
1305 }
1306
1307 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
1308                                               struct samba_kdc_db_context *kdc_db_ctx,
1309                                               TALLOC_CTX *mem_ctx,
1310                                               krb5_const_principal principal,
1311                                               unsigned flags,
1312                                               hdb_entry_ex *entry_ex)
1313 {
1314         krb5_error_code ret;
1315         struct ldb_dn *realm_dn;
1316         struct ldb_message *msg;
1317
1318         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
1319                                        server_attrs, &realm_dn, &msg);
1320         if (ret != 0) {
1321                 return ret;
1322         }
1323
1324         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1325                                       principal, SAMBA_KDC_ENT_TYPE_SERVER,
1326                                       flags,
1327                                       realm_dn, msg, entry_ex);
1328         if (ret != 0) {
1329                 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
1330         }
1331
1332         return ret;
1333 }
1334
1335 krb5_error_code samba_kdc_fetch(krb5_context context,
1336                                 struct samba_kdc_db_context *kdc_db_ctx,
1337                                 krb5_const_principal principal,
1338                                 unsigned flags,
1339                                 krb5_kvno kvno,
1340                                 hdb_entry_ex *entry_ex)
1341 {
1342         krb5_error_code ret = HDB_ERR_NOENTRY;
1343         TALLOC_CTX *mem_ctx;
1344         unsigned int krbtgt_number;
1345         if (flags & HDB_F_KVNO_SPECIFIED) {
1346                 krbtgt_number = kvno >> 16;
1347                 if (kdc_db_ctx->rodc) {
1348                         if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
1349                                 return HDB_ERR_NOT_FOUND_HERE;
1350                         }
1351                 }
1352         } else {
1353                 krbtgt_number = kdc_db_ctx->my_krbtgt_number;
1354         }
1355
1356         mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
1357         if (!mem_ctx) {
1358                 ret = ENOMEM;
1359                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1360                 return ret;
1361         }
1362
1363         if (flags & HDB_F_GET_CLIENT) {
1364                 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
1365                 if (ret != HDB_ERR_NOENTRY) goto done;
1366         }
1367         if (flags & HDB_F_GET_SERVER) {
1368                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1369                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, krbtgt_number, entry_ex);
1370                 if (ret != HDB_ERR_NOENTRY) goto done;
1371
1372                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1373                 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
1374                 if (ret != HDB_ERR_NOENTRY) goto done;
1375         }
1376         if (flags & HDB_F_GET_KRBTGT) {
1377                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, krbtgt_number, entry_ex);
1378                 if (ret != HDB_ERR_NOENTRY) goto done;
1379         }
1380
1381 done:
1382         talloc_free(mem_ctx);
1383         return ret;
1384 }
1385
1386 struct samba_kdc_seq {
1387         unsigned int index;
1388         unsigned int count;
1389         struct ldb_message **msgs;
1390         struct ldb_dn *realm_dn;
1391 };
1392
1393 static krb5_error_code samba_kdc_seq(krb5_context context,
1394                                      struct samba_kdc_db_context *kdc_db_ctx,
1395                                      hdb_entry_ex *entry)
1396 {
1397         krb5_error_code ret;
1398         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1399         TALLOC_CTX *mem_ctx;
1400         hdb_entry_ex entry_ex;
1401         memset(&entry_ex, '\0', sizeof(entry_ex));
1402
1403         if (!priv) {
1404                 return HDB_ERR_NOENTRY;
1405         }
1406
1407         mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
1408
1409         if (!mem_ctx) {
1410                 ret = ENOMEM;
1411                 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
1412                 return ret;
1413         }
1414
1415         if (priv->index < priv->count) {
1416                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1417                                               NULL, SAMBA_KDC_ENT_TYPE_ANY,
1418                                               HDB_F_ADMIN_DATA|HDB_F_GET_ANY,
1419                                               priv->realm_dn, priv->msgs[priv->index++], entry);
1420         } else {
1421                 ret = HDB_ERR_NOENTRY;
1422         }
1423
1424         if (ret != 0) {
1425                 TALLOC_FREE(priv);
1426                 kdc_db_ctx->seq_ctx = NULL;
1427         } else {
1428                 talloc_free(mem_ctx);
1429         }
1430
1431         return ret;
1432 }
1433
1434 krb5_error_code samba_kdc_firstkey(krb5_context context,
1435                                    struct samba_kdc_db_context *kdc_db_ctx,
1436                                    hdb_entry_ex *entry)
1437 {
1438         struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
1439         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1440         char *realm;
1441         struct ldb_result *res = NULL;
1442         krb5_error_code ret;
1443         TALLOC_CTX *mem_ctx;
1444         int lret;
1445
1446         if (priv) {
1447                 TALLOC_FREE(priv);
1448                 kdc_db_ctx->seq_ctx = NULL;
1449         }
1450
1451         priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
1452         if (!priv) {
1453                 ret = ENOMEM;
1454                 krb5_set_error_message(context, ret, "talloc: out of memory");
1455                 return ret;
1456         }
1457
1458         priv->index = 0;
1459         priv->msgs = NULL;
1460         priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
1461         priv->count = 0;
1462
1463         mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
1464
1465         if (!mem_ctx) {
1466                 ret = ENOMEM;
1467                 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
1468                 return ret;
1469         }
1470
1471         ret = krb5_get_default_realm(context, &realm);
1472         if (ret != 0) {
1473                 TALLOC_FREE(priv);
1474                 return ret;
1475         }
1476
1477         lret = ldb_search(ldb_ctx, priv, &res,
1478                           priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
1479                           "(objectClass=user)");
1480
1481         if (lret != LDB_SUCCESS) {
1482                 TALLOC_FREE(priv);
1483                 return HDB_ERR_NOENTRY;
1484         }
1485
1486         priv->count = res->count;
1487         priv->msgs = talloc_steal(priv, res->msgs);
1488         talloc_free(res);
1489
1490         kdc_db_ctx->seq_ctx = priv;
1491
1492         ret = samba_kdc_seq(context, kdc_db_ctx, entry);
1493
1494         if (ret != 0) {
1495                 TALLOC_FREE(priv);
1496                 kdc_db_ctx->seq_ctx = NULL;
1497         } else {
1498                 talloc_free(mem_ctx);
1499         }
1500         return ret;
1501 }
1502
1503 krb5_error_code samba_kdc_nextkey(krb5_context context,
1504                                   struct samba_kdc_db_context *kdc_db_ctx,
1505                                   hdb_entry_ex *entry)
1506 {
1507         return samba_kdc_seq(context, kdc_db_ctx, entry);
1508 }
1509
1510 /* Check if a given entry may delegate or do s4u2self to this target principal
1511  *
1512  * This is currently a very nasty hack - allowing only delegation to itself.
1513  *
1514  * This is shared between the constrained delegation and S4U2Self code.
1515  */
1516 krb5_error_code
1517 samba_kdc_check_identical_client_and_server(krb5_context context,
1518                                             struct samba_kdc_db_context *kdc_db_ctx,
1519                                             hdb_entry_ex *entry,
1520                                             krb5_const_principal target_principal)
1521 {
1522         krb5_error_code ret;
1523         krb5_principal enterprise_prinicpal = NULL;
1524         struct ldb_dn *realm_dn;
1525         struct ldb_message *msg;
1526         struct dom_sid *orig_sid;
1527         struct dom_sid *target_sid;
1528         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1529         const char *delegation_check_attrs[] = {
1530                 "objectSid", NULL
1531         };
1532
1533         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_constrained_delegation");
1534
1535         if (!mem_ctx) {
1536                 ret = ENOMEM;
1537                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1538                 return ret;
1539         }
1540
1541         if (target_principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1542                 /* Need to reparse the enterprise principal to find the real target */
1543                 if (target_principal->name.name_string.len != 1) {
1544                         ret = KRB5_PARSE_MALFORMED;
1545                         krb5_set_error_message(context, ret, "samba_kdc_check_constrained_delegation: request for delegation to enterprise principal with wrong (%d) number of components",
1546                                                target_principal->name.name_string.len);
1547                         talloc_free(mem_ctx);
1548                         return ret;
1549                 }
1550                 ret = krb5_parse_name(context, target_principal->name.name_string.val[0],
1551                                       &enterprise_prinicpal);
1552                 if (ret) {
1553                         talloc_free(mem_ctx);
1554                         return ret;
1555                 }
1556                 target_principal = enterprise_prinicpal;
1557         }
1558
1559         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, target_principal,
1560                                        delegation_check_attrs, &realm_dn, &msg);
1561
1562         krb5_free_principal(context, enterprise_prinicpal);
1563
1564         if (ret != 0) {
1565                 talloc_free(mem_ctx);
1566                 return ret;
1567         }
1568
1569         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1570         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1571
1572         /* Allow delegation to the same principal, even if by a different
1573          * name.  The easy and safe way to prove this is by SID
1574          * comparison */
1575         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1576                 talloc_free(mem_ctx);
1577                 return KRB5KDC_ERR_BADOPTION;
1578         }
1579
1580         talloc_free(mem_ctx);
1581         return ret;
1582 }
1583
1584 /* Certificates printed by a the Certificate Authority might have a
1585  * slightly different form of the user principal name to that in the
1586  * database.  Allow a mismatch where they both refer to the same
1587  * SID */
1588
1589 krb5_error_code
1590 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
1591                                     struct samba_kdc_db_context *kdc_db_ctx,
1592                                      hdb_entry_ex *entry,
1593                                      krb5_const_principal certificate_principal)
1594 {
1595         krb5_error_code ret;
1596         struct ldb_dn *realm_dn;
1597         struct ldb_message *msg;
1598         struct dom_sid *orig_sid;
1599         struct dom_sid *target_sid;
1600         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1601         const char *ms_upn_check_attrs[] = {
1602                 "objectSid", NULL
1603         };
1604
1605         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
1606
1607         if (!mem_ctx) {
1608                 ret = ENOMEM;
1609                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1610                 return ret;
1611         }
1612
1613         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1614                                        mem_ctx, certificate_principal,
1615                                        ms_upn_check_attrs, &realm_dn, &msg);
1616
1617         if (ret != 0) {
1618                 talloc_free(mem_ctx);
1619                 return ret;
1620         }
1621
1622         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1623         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1624
1625         /* Consider these to be the same principal, even if by a different
1626          * name.  The easy and safe way to prove this is by SID
1627          * comparison */
1628         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1629                 talloc_free(mem_ctx);
1630                 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1631         }
1632
1633         talloc_free(mem_ctx);
1634         return ret;
1635 }
1636
1637 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
1638                                 struct samba_kdc_db_context **kdc_db_ctx_out)
1639 {
1640         int ldb_ret;
1641         struct ldb_message *msg;
1642         struct auth_session_info *session_info;
1643         struct samba_kdc_db_context *kdc_db_ctx;
1644         /* The idea here is very simple.  Using Kerberos to
1645          * authenticate the KDC to the LDAP server is higly likely to
1646          * be circular.
1647          *
1648          * In future we may set this up to use EXERNAL and SSL
1649          * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
1650         */
1651
1652         kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
1653         if (kdc_db_ctx == NULL) {
1654                 return NT_STATUS_NO_MEMORY;
1655         }
1656         kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
1657         kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
1658
1659         kdc_get_policy(base_ctx->lp_ctx, NULL, &kdc_db_ctx->policy);
1660
1661         session_info = system_session(kdc_db_ctx->lp_ctx);
1662         if (session_info == NULL) {
1663                 return NT_STATUS_INTERNAL_ERROR;
1664         }
1665
1666         /* Setup the link to LDB */
1667         kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx, base_ctx->ev_ctx,
1668                                           base_ctx->lp_ctx, session_info, 0);
1669         if (kdc_db_ctx->samdb == NULL) {
1670                 DEBUG(1, ("hdb_samba4_create: Cannot open samdb for KDC backend!"));
1671                 talloc_free(kdc_db_ctx);
1672                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1673         }
1674
1675         /* Find out our own krbtgt kvno */
1676         ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
1677         if (ldb_ret != LDB_SUCCESS) {
1678                 DEBUG(1, ("hdb_samba4_create: Cannot determine if we are an RODC in KDC backend: %s\n",
1679                           ldb_errstring(kdc_db_ctx->samdb)));
1680                 talloc_free(kdc_db_ctx);
1681                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1682         }
1683         if (kdc_db_ctx->rodc) {
1684                 int my_krbtgt_number;
1685                 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
1686                 struct ldb_dn *account_dn;
1687                 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
1688                 if (!server_dn) {
1689                         DEBUG(1, ("hdb_samba4_create: Cannot determine server DN in KDC backend: %s\n",
1690                                   ldb_errstring(kdc_db_ctx->samdb)));
1691                         talloc_free(kdc_db_ctx);
1692                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1693                 }
1694
1695                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
1696                                              "serverReference", &account_dn);
1697                 if (ldb_ret != LDB_SUCCESS) {
1698                         DEBUG(1, ("hdb_samba4_create: Cannot determine server account in KDC backend: %s\n",
1699                                   ldb_errstring(kdc_db_ctx->samdb)));
1700                         talloc_free(kdc_db_ctx);
1701                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1702                 }
1703
1704                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
1705                                              "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
1706                 talloc_free(account_dn);
1707                 if (ldb_ret != LDB_SUCCESS) {
1708                         DEBUG(1, ("hdb_samba4_create: Cannot determine RODC krbtgt account in KDC backend: %s\n",
1709                                   ldb_errstring(kdc_db_ctx->samdb)));
1710                         talloc_free(kdc_db_ctx);
1711                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1712                 }
1713
1714                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
1715                                           &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1716                                           secondary_keytab,
1717                                           0,
1718                                           "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
1719                 if (ldb_ret != LDB_SUCCESS) {
1720                         DEBUG(1, ("hdb_samba4_create: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
1721                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
1722                                   ldb_errstring(kdc_db_ctx->samdb),
1723                                   ldb_strerror(ldb_ret)));
1724                         talloc_free(kdc_db_ctx);
1725                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1726                 }
1727                 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
1728                 if (my_krbtgt_number == -1) {
1729                         DEBUG(1, ("hdb_samba4_create: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
1730                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
1731                                   my_krbtgt_number));
1732                         talloc_free(kdc_db_ctx);
1733                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1734                 }
1735                 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
1736
1737         } else {
1738                 kdc_db_ctx->my_krbtgt_number = 0;
1739                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
1740                                           &msg, NULL, LDB_SCOPE_SUBTREE,
1741                                           krbtgt_attrs,
1742                                           DSDB_SEARCH_SHOW_EXTENDED_DN,
1743                                           "(&(objectClass=user)(samAccountName=krbtgt))");
1744
1745                 if (ldb_ret != LDB_SUCCESS) {
1746                         DEBUG(1, ("samba_kdc_fetch: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
1747                         talloc_free(kdc_db_ctx);
1748                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1749                 }
1750                 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
1751                 kdc_db_ctx->my_krbtgt_number = 0;
1752                 talloc_free(msg);
1753         }
1754         *kdc_db_ctx_out = kdc_db_ctx;
1755         return NT_STATUS_OK;
1756 }