s4-kdc use 'flags' to only create the 'admin data' elements when requested
[kai/samba.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                                                unsigned flags,
548                                                struct ldb_dn *realm_dn,
549                                                struct ldb_message *msg,
550                                                hdb_entry_ex *entry_ex)
551 {
552         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
553         uint32_t userAccountControl;
554         unsigned int i;
555         krb5_error_code ret = 0;
556         krb5_boolean is_computer = FALSE;
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         p = talloc(mem_ctx, struct samba_kdc_entry);
589         if (!p) {
590                 ret = ENOMEM;
591                 goto out;
592         }
593
594         p->kdc_db_ctx = kdc_db_ctx;
595         p->entry_ex = entry_ex;
596         p->realm_dn = talloc_reference(p, realm_dn);
597         if (!p->realm_dn) {
598                 ret = ENOMEM;
599                 goto out;
600         }
601
602         talloc_set_destructor(p, samba_kdc_entry_destructor);
603
604         /* make sure we do not have bogus data in there */
605         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
606
607         entry_ex->ctx = p;
608         entry_ex->free_entry = samba_kdc_free_entry;
609
610         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
611
612
613         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
614         if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
615                 krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
616         } else {
617                 ret = copy_Principal(principal, entry_ex->entry.principal);
618                 if (ret) {
619                         krb5_clear_error_message(context);
620                         goto out;
621                 }
622
623                 /* While we have copied the client principal, tests
624                  * show that Win2k3 returns the 'corrected' realm, not
625                  * the client-specified realm.  This code attempts to
626                  * replace the client principal's realm with the one
627                  * we determine from our records */
628
629                 /* this has to be with malloc() */
630                 krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
631         }
632
633         /* First try and figure out the flags based on the userAccountControl */
634         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
635
636         /* Windows 2008 seems to enforce this (very sensible) rule by
637          * default - don't allow offline attacks on a user's password
638          * by asking for a ticket to them as a service (encrypted with
639          * their probably patheticly insecure password) */
640
641         if (entry_ex->entry.flags.server
642             && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
643                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
644                         entry_ex->entry.flags.server = 0;
645                 }
646         }
647
648         if (flags & HDB_F_ADMIN_DATA) {
649                 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
650                  * of the Heimdal KDC.  They are stored in a the traditional
651                  * DB for audit purposes, and still form part of the structure
652                  * we must return */
653
654                 /* use 'whenCreated' */
655                 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
656                 /* use 'kadmin' for now (needed by mit_samba) */
657                 krb5_make_principal(context,
658                                     &entry_ex->entry.created_by.principal,
659                                     lpcfg_realm(lp_ctx), "kadmin", NULL);
660
661                 entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
662                 if (entry_ex->entry.modified_by == NULL) {
663                         ret = ENOMEM;
664                         krb5_set_error_message(context, ret, "malloc: out of memory");
665                         goto out;
666                 }
667
668                 /* use 'whenChanged' */
669                 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
670                 /* use 'kadmin' for now (needed by mit_samba) */
671                 krb5_make_principal(context,
672                                     &entry_ex->entry.modified_by->principal,
673                                     lpcfg_realm(lp_ctx), "kadmin", NULL);
674         }
675
676
677         /* The lack of password controls etc applies to krbtgt by
678          * virtue of being that particular RID */
679         status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
680
681         if (!NT_STATUS_IS_OK(status)) {
682                 ret = EINVAL;
683                 goto out;
684         }
685
686         if (rid == DOMAIN_RID_KRBTGT) {
687                 entry_ex->entry.valid_end = NULL;
688                 entry_ex->entry.pw_end = NULL;
689
690                 entry_ex->entry.flags.invalid = 0;
691                 entry_ex->entry.flags.server = 1;
692
693                 /* Don't mark all requests for the krbtgt/realm as
694                  * 'change password', as otherwise we could get into
695                  * trouble, and not enforce the password expirty.
696                  * Instead, only do it when request is for the kpasswd service */
697                 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
698                     && principal->name.name_string.len == 2
699                     && (strcmp(principal->name.name_string.val[0], "kadmin") == 0)
700                     && (strcmp(principal->name.name_string.val[1], "changepw") == 0)
701                     && lpcfg_is_my_domain_or_realm(lp_ctx, principal->realm)) {
702                         entry_ex->entry.flags.change_pw = 1;
703                 }
704                 entry_ex->entry.flags.client = 0;
705                 entry_ex->entry.flags.forwardable = 1;
706                 entry_ex->entry.flags.ok_as_delegate = 1;
707         } else if (is_rodc) {
708                 /* The RODC krbtgt account is like the main krbtgt,
709                  * but it does not have a changepw or kadmin
710                  * service */
711
712                 entry_ex->entry.valid_end = NULL;
713                 entry_ex->entry.pw_end = NULL;
714
715                 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
716                 entry_ex->entry.flags.client = 0;
717                 entry_ex->entry.flags.invalid = 0;
718                 entry_ex->entry.flags.server = 1;
719
720                 entry_ex->entry.flags.client = 0;
721                 entry_ex->entry.flags.forwardable = 1;
722                 entry_ex->entry.flags.ok_as_delegate = 0;
723         } else if (entry_ex->entry.flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
724                 /* The account/password expiry only applies when the account is used as a
725                  * client (ie password login), not when used as a server */
726
727                 /* Make very well sure we don't use this for a client,
728                  * it could bypass the password restrictions */
729                 entry_ex->entry.flags.client = 0;
730
731                 entry_ex->entry.valid_end = NULL;
732                 entry_ex->entry.pw_end = NULL;
733
734         } else {
735                 NTTIME must_change_time
736                         = samdb_result_force_password_change(kdc_db_ctx->samdb, mem_ctx,
737                                                              realm_dn, msg);
738                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
739                         entry_ex->entry.pw_end = NULL;
740                 } else {
741                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
742                         if (entry_ex->entry.pw_end == NULL) {
743                                 ret = ENOMEM;
744                                 goto out;
745                         }
746                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
747                 }
748
749                 acct_expiry = samdb_result_account_expires(msg);
750                 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
751                         entry_ex->entry.valid_end = NULL;
752                 } else {
753                         entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
754                         if (entry_ex->entry.valid_end == NULL) {
755                                 ret = ENOMEM;
756                                 goto out;
757                         }
758                         *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
759                 }
760         }
761
762         entry_ex->entry.valid_start = NULL;
763
764         entry_ex->entry.max_life = NULL;
765
766         entry_ex->entry.max_renew = NULL;
767
768         entry_ex->entry.generation = NULL;
769
770         /* Get keys from the db */
771         ret = samba_kdc_message2entry_keys(context, kdc_db_ctx, p, msg,
772                                            rid, is_rodc, userAccountControl,
773                                            ent_type, entry_ex);
774         if (ret) {
775                 /* Could be bougus data in the entry, or out of memory */
776                 goto out;
777         }
778
779         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
780         if (entry_ex->entry.etypes == NULL) {
781                 krb5_clear_error_message(context);
782                 ret = ENOMEM;
783                 goto out;
784         }
785         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
786         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
787         if (entry_ex->entry.etypes->val == NULL) {
788                 krb5_clear_error_message(context);
789                 ret = ENOMEM;
790                 goto out;
791         }
792         for (i=0; i < entry_ex->entry.etypes->len; i++) {
793                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
794         }
795
796
797         p->msg = talloc_steal(p, msg);
798
799 out:
800         if (ret != 0) {
801                 /* This doesn't free ent itself, that is for the eventual caller to do */
802                 hdb_free_entry(context, entry_ex);
803         } else {
804                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
805         }
806
807         return ret;
808 }
809
810 /*
811  * Construct an hdb_entry from a directory entry.
812  */
813 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
814                                                struct samba_kdc_db_context *kdc_db_ctx,
815                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
816                                                enum trust_direction direction,
817                                                struct ldb_dn *realm_dn,
818                                                struct ldb_message *msg,
819                                                hdb_entry_ex *entry_ex)
820 {
821         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
822         const char *dnsdomain;
823         const char *realm = lpcfg_realm(lp_ctx);
824         DATA_BLOB password_utf16;
825         struct samr_Password password_hash;
826         const struct ldb_val *password_val;
827         struct trustAuthInOutBlob password_blob;
828         struct samba_kdc_entry *p;
829
830         enum ndr_err_code ndr_err;
831         int ret, trust_direction_flags;
832         unsigned int i;
833
834         p = talloc(mem_ctx, struct samba_kdc_entry);
835         if (!p) {
836                 ret = ENOMEM;
837                 goto out;
838         }
839
840         p->kdc_db_ctx = kdc_db_ctx;
841         p->entry_ex = entry_ex;
842         p->realm_dn = realm_dn;
843
844         talloc_set_destructor(p, samba_kdc_entry_destructor);
845
846         /* make sure we do not have bogus data in there */
847         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
848
849         entry_ex->ctx = p;
850         entry_ex->free_entry = samba_kdc_free_entry;
851
852         /* use 'whenCreated' */
853         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
854         /* use 'kadmin' for now (needed by mit_samba) */
855         krb5_make_principal(context,
856                             &entry_ex->entry.created_by.principal,
857                             realm, "kadmin", NULL);
858
859         entry_ex->entry.valid_start = NULL;
860
861         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
862
863         if (direction == INBOUND) {
864                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
865
866         } else { /* OUTBOUND */
867                 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
868                 /* replace realm */
869                 realm = strupper_talloc(mem_ctx, dnsdomain);
870                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
871         }
872
873         if (!password_val || !(trust_direction_flags & direction)) {
874                 ret = ENOENT;
875                 goto out;
876         }
877
878         ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
879                                            (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
880         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
881                 ret = EINVAL;
882                 goto out;
883         }
884
885         entry_ex->entry.kvno = -1;
886         for (i=0; i < password_blob.count; i++) {
887                 if (password_blob.current.array[i].AuthType == TRUST_AUTH_TYPE_VERSION) {
888                         entry_ex->entry.kvno = password_blob.current.array[i].AuthInfo.version.version;
889                 }
890         }
891
892         for (i=0; i < password_blob.count; i++) {
893                 if (password_blob.current.array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
894                         password_utf16 = data_blob_const(password_blob.current.array[i].AuthInfo.clear.password,
895                                                          password_blob.current.array[i].AuthInfo.clear.size);
896                         /* In the future, generate all sorts of
897                          * hashes, but for now we can't safely convert
898                          * the random strings windows uses into
899                          * utf8 */
900
901                         /* but as it is utf16 already, we can get the NT password/arcfour-hmac-md5 key */
902                         mdfour(password_hash.hash, password_utf16.data, password_utf16.length);
903                         break;
904                 } else if (password_blob.current.array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
905                         password_hash = password_blob.current.array[i].AuthInfo.nt4owf.password;
906                         break;
907                 }
908         }
909
910         if (i < password_blob.count) {
911                 Key key;
912                 /* Must have found a cleartext or MD4 password */
913                 entry_ex->entry.keys.val = calloc(1, sizeof(Key));
914
915                 key.mkvno = 0;
916                 key.salt = NULL; /* No salt for this enc type */
917
918                 if (entry_ex->entry.keys.val == NULL) {
919                         ret = ENOMEM;
920                         goto out;
921                 }
922
923                 ret = krb5_keyblock_init(context,
924                                          ENCTYPE_ARCFOUR_HMAC,
925                                          password_hash.hash, sizeof(password_hash.hash),
926                                          &key.key);
927
928                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
929                 entry_ex->entry.keys.len++;
930         }
931
932         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
933
934         ret = copy_Principal(principal, entry_ex->entry.principal);
935         if (ret) {
936                 krb5_clear_error_message(context);
937                 goto out;
938         }
939
940         /* While we have copied the client principal, tests
941          * show that Win2k3 returns the 'corrected' realm, not
942          * the client-specified realm.  This code attempts to
943          * replace the client principal's realm with the one
944          * we determine from our records */
945
946         krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
947         entry_ex->entry.flags = int2HDBFlags(0);
948         entry_ex->entry.flags.immutable = 1;
949         entry_ex->entry.flags.invalid = 0;
950         entry_ex->entry.flags.server = 1;
951         entry_ex->entry.flags.require_preauth = 1;
952
953         entry_ex->entry.pw_end = NULL;
954
955         entry_ex->entry.max_life = NULL;
956
957         entry_ex->entry.max_renew = NULL;
958
959         entry_ex->entry.generation = NULL;
960
961         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
962         if (entry_ex->entry.etypes == NULL) {
963                 krb5_clear_error_message(context);
964                 ret = ENOMEM;
965                 goto out;
966         }
967         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
968         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
969         if (entry_ex->entry.etypes->val == NULL) {
970                 krb5_clear_error_message(context);
971                 ret = ENOMEM;
972                 goto out;
973         }
974         for (i=0; i < entry_ex->entry.etypes->len; i++) {
975                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
976         }
977
978
979         p->msg = talloc_steal(p, msg);
980
981 out:
982         if (ret != 0) {
983                 /* This doesn't free ent itself, that is for the eventual caller to do */
984                 hdb_free_entry(context, entry_ex);
985         } else {
986                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
987         }
988
989         return ret;
990
991 }
992
993 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
994                                         TALLOC_CTX *mem_ctx,
995                                         const char *realm,
996                                         struct ldb_dn *realm_dn,
997                                         struct ldb_message **pmsg)
998 {
999         int lret;
1000         krb5_error_code ret;
1001         char *filter = NULL;
1002         const char * const *attrs = trust_attrs;
1003
1004         struct ldb_result *res = NULL;
1005         filter = talloc_asprintf(mem_ctx, "(&(objectClass=trustedDomain)(|(flatname=%s)(trustPartner=%s)))", realm, realm);
1006
1007         if (!filter) {
1008                 ret = ENOMEM;
1009                 krb5_set_error_message(context, ret, "talloc_asprintf: out of memory");
1010                 return ret;
1011         }
1012
1013         lret = ldb_search(ldb_ctx, mem_ctx, &res,
1014                           ldb_get_default_basedn(ldb_ctx),
1015                           LDB_SCOPE_SUBTREE, attrs, "%s", filter);
1016         if (lret != LDB_SUCCESS) {
1017                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
1018                 return HDB_ERR_NOENTRY;
1019         } else if (res->count == 0 || res->count > 1) {
1020                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
1021                 talloc_free(res);
1022                 return HDB_ERR_NOENTRY;
1023         }
1024         talloc_steal(mem_ctx, res->msgs);
1025         *pmsg = res->msgs[0];
1026         talloc_free(res);
1027         return 0;
1028 }
1029
1030 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
1031                                                 struct samba_kdc_db_context *kdc_db_ctx,
1032                                                 TALLOC_CTX *mem_ctx,
1033                                                 krb5_const_principal principal,
1034                                                 const char **attrs,
1035                                                 struct ldb_dn **realm_dn,
1036                                                 struct ldb_message **msg) {
1037         NTSTATUS nt_status;
1038         char *principal_string;
1039         krb5_error_code ret;
1040
1041         ret = krb5_unparse_name(context, principal, &principal_string);
1042
1043         if (ret != 0) {
1044                 return ret;
1045         }
1046
1047         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1048                                               mem_ctx, principal_string, attrs,
1049                                               realm_dn, msg);
1050         free(principal_string);
1051         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1052                 return HDB_ERR_NOENTRY;
1053         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1054                 return ENOMEM;
1055         } else if (!NT_STATUS_IS_OK(nt_status)) {
1056                 return EINVAL;
1057         }
1058
1059         return ret;
1060 }
1061
1062 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1063                                                struct samba_kdc_db_context *kdc_db_ctx,
1064                                                TALLOC_CTX *mem_ctx,
1065                                                krb5_const_principal principal,
1066                                                unsigned flags,
1067                                                hdb_entry_ex *entry_ex) {
1068         struct ldb_dn *realm_dn;
1069         krb5_error_code ret;
1070         struct ldb_message *msg = NULL;
1071
1072         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1073                                        mem_ctx, principal, user_attrs,
1074                                        &realm_dn, &msg);
1075         if (ret != 0) {
1076                 return ret;
1077         }
1078
1079         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1080                                       principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1081                                       flags,
1082                                       realm_dn, msg, entry_ex);
1083         return ret;
1084 }
1085
1086 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1087                                               struct samba_kdc_db_context *kdc_db_ctx,
1088                                               TALLOC_CTX *mem_ctx,
1089                                               krb5_const_principal principal,
1090                                               unsigned flags,
1091                                               uint32_t krbtgt_number,
1092                                               hdb_entry_ex *entry_ex)
1093 {
1094         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1095         krb5_error_code ret;
1096         struct ldb_message *msg = NULL;
1097         struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1098
1099         krb5_principal alloc_principal = NULL;
1100         if (principal->name.name_string.len != 2
1101             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
1102                 /* Not a krbtgt */
1103                 return HDB_ERR_NOENTRY;
1104         }
1105
1106         /* krbtgt case.  Either us or a trusted realm */
1107
1108         if (lpcfg_is_my_domain_or_realm(lp_ctx, principal->realm)
1109             && lpcfg_is_my_domain_or_realm(lp_ctx, principal->name.name_string.val[1])) {
1110                 /* us, or someone quite like us */
1111                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1112                  * is in our db, then direct the caller at our primary
1113                  * krbtgt */
1114
1115                 int lret;
1116                 char *realm_fixed;
1117
1118                 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
1119                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1120                                                &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1121                                                krbtgt_attrs, 0,
1122                                                "(objectClass=user)");
1123                 } else {
1124                         /* We need to look up an RODC krbtgt (perhaps
1125                          * ours, if we are an RODC, perhaps another
1126                          * RODC if we are a read-write DC */
1127                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1128                                                &msg, realm_dn, LDB_SCOPE_SUBTREE,
1129                                                krbtgt_attrs,
1130                                                DSDB_SEARCH_SHOW_EXTENDED_DN,
1131                                                "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
1132                 }
1133
1134                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1135                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1136                                    (unsigned)(krbtgt_number));
1137                         krb5_set_error_message(context, HDB_ERR_NOENTRY,
1138                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1139                                                (unsigned)(krbtgt_number));
1140                         return HDB_ERR_NOENTRY;
1141                 } else if (lret != LDB_SUCCESS) {
1142                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1143                                    (unsigned)(krbtgt_number));
1144                         krb5_set_error_message(context, HDB_ERR_NOENTRY,
1145                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1146                                                (unsigned)(krbtgt_number));
1147                         return HDB_ERR_NOENTRY;
1148                 }
1149
1150                 realm_fixed = strupper_talloc(mem_ctx, lpcfg_realm(lp_ctx));
1151                 if (!realm_fixed) {
1152                         ret = ENOMEM;
1153                         krb5_set_error_message(context, ret, "strupper_talloc: out of memory");
1154                         return ret;
1155                 }
1156
1157                 ret = krb5_copy_principal(context, principal, &alloc_principal);
1158                 if (ret) {
1159                         return ret;
1160                 }
1161
1162                 free(alloc_principal->name.name_string.val[1]);
1163                 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
1164                 talloc_free(realm_fixed);
1165                 if (!alloc_principal->name.name_string.val[1]) {
1166                         ret = ENOMEM;
1167                         krb5_set_error_message(context, ret, "samba_kdc_fetch: strdup() failed!");
1168                         return ret;
1169                 }
1170                 principal = alloc_principal;
1171
1172                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1173                                               principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
1174                                               flags, realm_dn, msg, entry_ex);
1175                 if (ret != 0) {
1176                         krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
1177                 }
1178                 return ret;
1179
1180         } else {
1181                 enum trust_direction direction = UNKNOWN;
1182                 const char *realm = NULL;
1183
1184                 /* Either an inbound or outbound trust */
1185
1186                 if (strcasecmp(lpcfg_realm(lp_ctx), principal->realm) == 0) {
1187                         /* look for inbound trust */
1188                         direction = INBOUND;
1189                         realm = principal->name.name_string.val[1];
1190                 } else if (strcasecmp(lpcfg_realm(lp_ctx), principal->name.name_string.val[1]) == 0) {
1191                         /* look for outbound trust */
1192                         direction = OUTBOUND;
1193                         realm = principal->realm;
1194                 } else {
1195                         krb5_warnx(context, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1196                                    principal->realm, principal->name.name_string.val[1]);
1197                         krb5_set_error_message(context, HDB_ERR_NOENTRY, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1198                                                principal->realm, principal->name.name_string.val[1]);
1199                         return HDB_ERR_NOENTRY;
1200                 }
1201
1202                 /* Trusted domains are under CN=system */
1203
1204                 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
1205                                        mem_ctx,
1206                                        realm, realm_dn, &msg);
1207
1208                 if (ret != 0) {
1209                         krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
1210                         krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
1211                         return ret;
1212                 }
1213
1214                 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
1215                                               principal, direction,
1216                                               realm_dn, msg, entry_ex);
1217                 if (ret != 0) {
1218                         krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed");
1219                 }
1220                 return ret;
1221         }
1222
1223 }
1224
1225 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
1226                                                 struct samba_kdc_db_context *kdc_db_ctx,
1227                                                 TALLOC_CTX *mem_ctx,
1228                                                 krb5_const_principal principal,
1229                                                 const char **attrs,
1230                                                 struct ldb_dn **realm_dn,
1231                                                 struct ldb_message **msg)
1232 {
1233         krb5_error_code ret;
1234         if (principal->name.name_string.len >= 2) {
1235                 /* 'normal server' case */
1236                 int ldb_ret;
1237                 NTSTATUS nt_status;
1238                 struct ldb_dn *user_dn;
1239                 char *principal_string;
1240
1241                 ret = krb5_unparse_name_flags(context, principal,
1242                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1243                                               &principal_string);
1244                 if (ret != 0) {
1245                         return ret;
1246                 }
1247
1248                 /* At this point we may find the host is known to be
1249                  * in a different realm, so we should generate a
1250                  * referral instead */
1251                 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
1252                                                          mem_ctx, principal_string,
1253                                                          &user_dn, realm_dn);
1254                 free(principal_string);
1255
1256                 if (!NT_STATUS_IS_OK(nt_status)) {
1257                         return HDB_ERR_NOENTRY;
1258                 }
1259
1260                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
1261                                           mem_ctx,
1262                                           msg, user_dn, LDB_SCOPE_BASE,
1263                                           attrs, DSDB_SEARCH_SHOW_EXTENDED_DN, "(objectClass=*)");
1264                 if (ldb_ret != LDB_SUCCESS) {
1265                         return HDB_ERR_NOENTRY;
1266                 }
1267
1268         } else {
1269                 int lret;
1270                 char *filter = NULL;
1271                 char *short_princ;
1272                 const char *realm;
1273                 /* server as client principal case, but we must not lookup userPrincipalNames */
1274                 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1275                 realm = krb5_principal_get_realm(context, principal);
1276
1277                 /* TODO: Check if it is our realm, otherwise give referall */
1278
1279                 ret = krb5_unparse_name_flags(context, principal,  KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
1280
1281                 if (ret != 0) {
1282                         krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
1283                         krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
1284                         return ret;
1285                 }
1286
1287                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
1288                                        *realm_dn, LDB_SCOPE_SUBTREE,
1289                                        attrs,
1290                                        DSDB_SEARCH_SHOW_EXTENDED_DN,
1291                                        "(&(objectClass=user)(samAccountName=%s))",
1292                                        ldb_binary_encode_string(mem_ctx, short_princ));
1293                 free(short_princ);
1294                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1295                         DEBUG(3, ("Failed find a entry for %s\n", filter));
1296                         return HDB_ERR_NOENTRY;
1297                 }
1298                 if (lret != LDB_SUCCESS) {
1299                         DEBUG(3, ("Failed single search for for %s - %s\n",
1300                                   filter, ldb_errstring(kdc_db_ctx->samdb)));
1301                         return HDB_ERR_NOENTRY;
1302                 }
1303         }
1304
1305         return 0;
1306 }
1307
1308 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
1309                                               struct samba_kdc_db_context *kdc_db_ctx,
1310                                               TALLOC_CTX *mem_ctx,
1311                                               krb5_const_principal principal,
1312                                               unsigned flags,
1313                                               hdb_entry_ex *entry_ex)
1314 {
1315         krb5_error_code ret;
1316         struct ldb_dn *realm_dn;
1317         struct ldb_message *msg;
1318
1319         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
1320                                        server_attrs, &realm_dn, &msg);
1321         if (ret != 0) {
1322                 return ret;
1323         }
1324
1325         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1326                                       principal, SAMBA_KDC_ENT_TYPE_SERVER,
1327                                       flags,
1328                                       realm_dn, msg, entry_ex);
1329         if (ret != 0) {
1330                 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
1331         }
1332
1333         return ret;
1334 }
1335
1336 krb5_error_code samba_kdc_fetch(krb5_context context,
1337                                 struct samba_kdc_db_context *kdc_db_ctx,
1338                                 krb5_const_principal principal,
1339                                 unsigned flags,
1340                                 unsigned kvno,
1341                                 hdb_entry_ex *entry_ex)
1342 {
1343         krb5_error_code ret = HDB_ERR_NOENTRY;
1344         TALLOC_CTX *mem_ctx;
1345         unsigned int krbtgt_number;
1346         if (flags & HDB_F_KVNO_SPECIFIED) {
1347                 krbtgt_number = kvno >> 16;
1348                 if (kdc_db_ctx->rodc) {
1349                         if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
1350                                 return HDB_ERR_NOT_FOUND_HERE;
1351                         }
1352                 }
1353         } else {
1354                 krbtgt_number = kdc_db_ctx->my_krbtgt_number;
1355         }
1356
1357         mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
1358         if (!mem_ctx) {
1359                 ret = ENOMEM;
1360                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1361                 return ret;
1362         }
1363
1364         if (flags & HDB_F_GET_CLIENT) {
1365                 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
1366                 if (ret != HDB_ERR_NOENTRY) goto done;
1367         }
1368         if (flags & HDB_F_GET_SERVER) {
1369                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1370                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, krbtgt_number, entry_ex);
1371                 if (ret != HDB_ERR_NOENTRY) goto done;
1372
1373                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1374                 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
1375                 if (ret != HDB_ERR_NOENTRY) goto done;
1376         }
1377         if (flags & HDB_F_GET_KRBTGT) {
1378                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, krbtgt_number, entry_ex);
1379                 if (ret != HDB_ERR_NOENTRY) goto done;
1380         }
1381
1382 done:
1383         talloc_free(mem_ctx);
1384         return ret;
1385 }
1386
1387 struct samba_kdc_seq {
1388         unsigned int index;
1389         unsigned int count;
1390         struct ldb_message **msgs;
1391         struct ldb_dn *realm_dn;
1392 };
1393
1394 static krb5_error_code samba_kdc_seq(krb5_context context,
1395                                      struct samba_kdc_db_context *kdc_db_ctx,
1396                                      hdb_entry_ex *entry)
1397 {
1398         krb5_error_code ret;
1399         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1400         TALLOC_CTX *mem_ctx;
1401         hdb_entry_ex entry_ex;
1402         memset(&entry_ex, '\0', sizeof(entry_ex));
1403
1404         if (!priv) {
1405                 return HDB_ERR_NOENTRY;
1406         }
1407
1408         mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
1409
1410         if (!mem_ctx) {
1411                 ret = ENOMEM;
1412                 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
1413                 return ret;
1414         }
1415
1416         if (priv->index < priv->count) {
1417                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1418                                               NULL, SAMBA_KDC_ENT_TYPE_ANY,
1419                                               HDB_F_ADMIN_DATA|HDB_F_GET_ANY,
1420                                               priv->realm_dn, priv->msgs[priv->index++], entry);
1421         } else {
1422                 ret = HDB_ERR_NOENTRY;
1423         }
1424
1425         if (ret != 0) {
1426                 TALLOC_FREE(priv);
1427                 kdc_db_ctx->seq_ctx = NULL;
1428         } else {
1429                 talloc_free(mem_ctx);
1430         }
1431
1432         return ret;
1433 }
1434
1435 krb5_error_code samba_kdc_firstkey(krb5_context context,
1436                                    struct samba_kdc_db_context *kdc_db_ctx,
1437                                    hdb_entry_ex *entry)
1438 {
1439         struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
1440         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1441         char *realm;
1442         struct ldb_result *res = NULL;
1443         krb5_error_code ret;
1444         TALLOC_CTX *mem_ctx;
1445         int lret;
1446
1447         if (priv) {
1448                 TALLOC_FREE(priv);
1449                 kdc_db_ctx->seq_ctx = NULL;
1450         }
1451
1452         priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
1453         if (!priv) {
1454                 ret = ENOMEM;
1455                 krb5_set_error_message(context, ret, "talloc: out of memory");
1456                 return ret;
1457         }
1458
1459         priv->index = 0;
1460         priv->msgs = NULL;
1461         priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
1462         priv->count = 0;
1463
1464         mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
1465
1466         if (!mem_ctx) {
1467                 ret = ENOMEM;
1468                 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
1469                 return ret;
1470         }
1471
1472         ret = krb5_get_default_realm(context, &realm);
1473         if (ret != 0) {
1474                 TALLOC_FREE(priv);
1475                 return ret;
1476         }
1477
1478         lret = ldb_search(ldb_ctx, priv, &res,
1479                           priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
1480                           "(objectClass=user)");
1481
1482         if (lret != LDB_SUCCESS) {
1483                 TALLOC_FREE(priv);
1484                 return HDB_ERR_NOENTRY;
1485         }
1486
1487         priv->count = res->count;
1488         priv->msgs = talloc_steal(priv, res->msgs);
1489         talloc_free(res);
1490
1491         kdc_db_ctx->seq_ctx = priv;
1492
1493         ret = samba_kdc_seq(context, kdc_db_ctx, entry);
1494
1495         if (ret != 0) {
1496                 TALLOC_FREE(priv);
1497                 kdc_db_ctx->seq_ctx = NULL;
1498         } else {
1499                 talloc_free(mem_ctx);
1500         }
1501         return ret;
1502 }
1503
1504 krb5_error_code samba_kdc_nextkey(krb5_context context,
1505                                   struct samba_kdc_db_context *kdc_db_ctx,
1506                                   hdb_entry_ex *entry)
1507 {
1508         return samba_kdc_seq(context, kdc_db_ctx, entry);
1509 }
1510
1511 /* Check if a given entry may delegate or do s4u2self to this target principal
1512  *
1513  * This is currently a very nasty hack - allowing only delegation to itself.
1514  *
1515  * This is shared between the constrained delegation and S4U2Self code.
1516  */
1517 krb5_error_code
1518 samba_kdc_check_identical_client_and_server(krb5_context context,
1519                                             struct samba_kdc_db_context *kdc_db_ctx,
1520                                             hdb_entry_ex *entry,
1521                                             krb5_const_principal target_principal)
1522 {
1523         krb5_error_code ret;
1524         krb5_principal enterprise_prinicpal = NULL;
1525         struct ldb_dn *realm_dn;
1526         struct ldb_message *msg;
1527         struct dom_sid *orig_sid;
1528         struct dom_sid *target_sid;
1529         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1530         const char *delegation_check_attrs[] = {
1531                 "objectSid", NULL
1532         };
1533
1534         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_constrained_delegation");
1535
1536         if (!mem_ctx) {
1537                 ret = ENOMEM;
1538                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1539                 return ret;
1540         }
1541
1542         if (target_principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1543                 /* Need to reparse the enterprise principal to find the real target */
1544                 if (target_principal->name.name_string.len != 1) {
1545                         ret = KRB5_PARSE_MALFORMED;
1546                         krb5_set_error_message(context, ret, "samba_kdc_check_constrained_delegation: request for delegation to enterprise principal with wrong (%d) number of components",
1547                                                target_principal->name.name_string.len);
1548                         talloc_free(mem_ctx);
1549                         return ret;
1550                 }
1551                 ret = krb5_parse_name(context, target_principal->name.name_string.val[0],
1552                                       &enterprise_prinicpal);
1553                 if (ret) {
1554                         talloc_free(mem_ctx);
1555                         return ret;
1556                 }
1557                 target_principal = enterprise_prinicpal;
1558         }
1559
1560         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, target_principal,
1561                                        delegation_check_attrs, &realm_dn, &msg);
1562
1563         krb5_free_principal(context, enterprise_prinicpal);
1564
1565         if (ret != 0) {
1566                 talloc_free(mem_ctx);
1567                 return ret;
1568         }
1569
1570         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1571         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1572
1573         /* Allow delegation to the same principal, even if by a different
1574          * name.  The easy and safe way to prove this is by SID
1575          * comparison */
1576         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1577                 talloc_free(mem_ctx);
1578                 return KRB5KDC_ERR_BADOPTION;
1579         }
1580
1581         talloc_free(mem_ctx);
1582         return ret;
1583 }
1584
1585 /* Certificates printed by a the Certificate Authority might have a
1586  * slightly different form of the user principal name to that in the
1587  * database.  Allow a mismatch where they both refer to the same
1588  * SID */
1589
1590 krb5_error_code
1591 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
1592                                     struct samba_kdc_db_context *kdc_db_ctx,
1593                                      hdb_entry_ex *entry,
1594                                      krb5_const_principal certificate_principal)
1595 {
1596         krb5_error_code ret;
1597         struct ldb_dn *realm_dn;
1598         struct ldb_message *msg;
1599         struct dom_sid *orig_sid;
1600         struct dom_sid *target_sid;
1601         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1602         const char *ms_upn_check_attrs[] = {
1603                 "objectSid", NULL
1604         };
1605
1606         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
1607
1608         if (!mem_ctx) {
1609                 ret = ENOMEM;
1610                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1611                 return ret;
1612         }
1613
1614         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1615                                        mem_ctx, certificate_principal,
1616                                        ms_upn_check_attrs, &realm_dn, &msg);
1617
1618         if (ret != 0) {
1619                 talloc_free(mem_ctx);
1620                 return ret;
1621         }
1622
1623         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1624         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1625
1626         /* Consider these to be the same principal, even if by a different
1627          * name.  The easy and safe way to prove this is by SID
1628          * comparison */
1629         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1630                 talloc_free(mem_ctx);
1631                 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1632         }
1633
1634         talloc_free(mem_ctx);
1635         return ret;
1636 }
1637
1638 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
1639                                 struct samba_kdc_db_context **kdc_db_ctx_out)
1640 {
1641         int ldb_ret;
1642         struct ldb_message *msg;
1643         struct auth_session_info *session_info;
1644         struct samba_kdc_db_context *kdc_db_ctx;
1645         /* The idea here is very simple.  Using Kerberos to
1646          * authenticate the KDC to the LDAP server is higly likely to
1647          * be circular.
1648          *
1649          * In future we may set this up to use EXERNAL and SSL
1650          * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
1651         */
1652
1653         kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
1654         if (kdc_db_ctx == NULL) {
1655                 return NT_STATUS_NO_MEMORY;
1656         }
1657         kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
1658         kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
1659
1660         session_info = system_session(kdc_db_ctx->lp_ctx);
1661         if (session_info == NULL) {
1662                 return NT_STATUS_INTERNAL_ERROR;
1663         }
1664
1665         /* Setup the link to LDB */
1666         kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx, base_ctx->ev_ctx,
1667                                           base_ctx->lp_ctx, session_info, 0);
1668         if (kdc_db_ctx->samdb == NULL) {
1669                 DEBUG(1, ("hdb_samba4_create: Cannot open samdb for KDC backend!"));
1670                 talloc_free(kdc_db_ctx);
1671                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1672         }
1673
1674         /* Find out our own krbtgt kvno */
1675         ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
1676         if (ldb_ret != LDB_SUCCESS) {
1677                 DEBUG(1, ("hdb_samba4_create: Cannot determine if we are an RODC in KDC backend: %s\n",
1678                           ldb_errstring(kdc_db_ctx->samdb)));
1679                 talloc_free(kdc_db_ctx);
1680                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1681         }
1682         if (kdc_db_ctx->rodc) {
1683                 int my_krbtgt_number;
1684                 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
1685                 struct ldb_dn *account_dn;
1686                 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
1687                 if (!server_dn) {
1688                         DEBUG(1, ("hdb_samba4_create: Cannot determine server DN in KDC backend: %s\n",
1689                                   ldb_errstring(kdc_db_ctx->samdb)));
1690                         talloc_free(kdc_db_ctx);
1691                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1692                 }
1693
1694                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
1695                                              "serverReference", &account_dn);
1696                 if (ldb_ret != LDB_SUCCESS) {
1697                         DEBUG(1, ("hdb_samba4_create: Cannot determine server account in KDC backend: %s\n",
1698                                   ldb_errstring(kdc_db_ctx->samdb)));
1699                         talloc_free(kdc_db_ctx);
1700                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1701                 }
1702
1703                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
1704                                              "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
1705                 talloc_free(account_dn);
1706                 if (ldb_ret != LDB_SUCCESS) {
1707                         DEBUG(1, ("hdb_samba4_create: Cannot determine RODC krbtgt account in KDC backend: %s\n",
1708                                   ldb_errstring(kdc_db_ctx->samdb)));
1709                         talloc_free(kdc_db_ctx);
1710                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1711                 }
1712
1713                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
1714                                           &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1715                                           secondary_keytab,
1716                                           0,
1717                                           "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
1718                 if (ldb_ret != LDB_SUCCESS) {
1719                         DEBUG(1, ("hdb_samba4_create: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
1720                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
1721                                   ldb_errstring(kdc_db_ctx->samdb),
1722                                   ldb_strerror(ldb_ret)));
1723                         talloc_free(kdc_db_ctx);
1724                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1725                 }
1726                 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
1727                 if (my_krbtgt_number == -1) {
1728                         DEBUG(1, ("hdb_samba4_create: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
1729                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
1730                                   my_krbtgt_number));
1731                         talloc_free(kdc_db_ctx);
1732                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1733                 }
1734                 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
1735
1736         } else {
1737                 kdc_db_ctx->my_krbtgt_number = 0;
1738                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
1739                                           &msg, NULL, LDB_SCOPE_SUBTREE,
1740                                           krbtgt_attrs,
1741                                           DSDB_SEARCH_SHOW_EXTENDED_DN,
1742                                           "(&(objectClass=user)(samAccountName=krbtgt))");
1743
1744                 if (ldb_ret != LDB_SUCCESS) {
1745                         DEBUG(1, ("samba_kdc_fetch: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
1746                         talloc_free(kdc_db_ctx);
1747                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1748                 }
1749                 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
1750                 kdc_db_ctx->my_krbtgt_number = 0;
1751                 talloc_free(msg);
1752         }
1753         *kdc_db_ctx_out = kdc_db_ctx;
1754         return NT_STATUS_OK;
1755 }