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