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