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