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