s4:kdc: remove Primary:Kerberos usage from samba_kdc_message2entry_keys()
[samba.git] / source4 / kdc / db-glue.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Database Glue between Samba and the KDC
5
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2009
7    Copyright (C) Simo Sorce <idra@samba.org> 2010
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "libcli/security/security.h"
26 #include "librpc/gen_ndr/ndr_security.h"
27 #include "auth/auth.h"
28 #include "auth/auth_sam.h"
29 #include "dsdb/samdb/samdb.h"
30 #include "dsdb/common/util.h"
31 #include "librpc/gen_ndr/ndr_drsblobs.h"
32 #include "param/param.h"
33 #include "param/secrets.h"
34 #include "../lib/crypto/md4.h"
35 #include "system/kerberos.h"
36 #include "auth/kerberos/kerberos.h"
37 #include "kdc/sdb.h"
38 #include "kdc/samba_kdc.h"
39 #include "kdc/db-glue.h"
40 #include "kdc/pac-glue.h"
41 #include "librpc/gen_ndr/ndr_irpc_c.h"
42 #include "lib/messaging/irpc.h"
43
44 #undef strcasecmp
45 #undef strncasecmp
46
47 #define SAMBA_KVNO_GET_KRBTGT(kvno) \
48         ((uint16_t)(((uint32_t)kvno) >> 16))
49
50 #define SAMBA_KVNO_GET_VALUE(kvno) \
51         ((uint16_t)(((uint32_t)kvno) & 0xFFFF))
52
53 #define SAMBA_KVNO_AND_KRBTGT(kvno, krbtgt) \
54         ((krb5_kvno)((((uint32_t)kvno) & 0xFFFF) | \
55          ((((uint32_t)krbtgt) << 16) & 0xFFFF0000)))
56
57 enum samba_kdc_ent_type
58 { SAMBA_KDC_ENT_TYPE_CLIENT, SAMBA_KDC_ENT_TYPE_SERVER,
59   SAMBA_KDC_ENT_TYPE_KRBTGT, SAMBA_KDC_ENT_TYPE_TRUST, SAMBA_KDC_ENT_TYPE_ANY };
60
61 enum trust_direction {
62         UNKNOWN = 0,
63         INBOUND = LSA_TRUST_DIRECTION_INBOUND,
64         OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
65 };
66
67 static const char *trust_attrs[] = {
68         "securityIdentifier",
69         "flatName",
70         "trustPartner",
71         "trustAttributes",
72         "trustDirection",
73         "trustType",
74         "msDS-TrustForestTrustInfo",
75         "trustAuthIncoming",
76         "trustAuthOutgoing",
77         "whenCreated",
78         "msDS-SupportedEncryptionTypes",
79         NULL
80 };
81
82 /*
83   send a message to the drepl server telling it to initiate a
84   REPL_SECRET getncchanges extended op to fetch the users secrets
85  */
86 static void auth_sam_trigger_repl_secret(TALLOC_CTX *mem_ctx,
87                                   struct imessaging_context *msg_ctx,
88                                   struct tevent_context *event_ctx,
89                                   struct ldb_dn *user_dn)
90 {
91         struct dcerpc_binding_handle *irpc_handle;
92         struct drepl_trigger_repl_secret r;
93         struct tevent_req *req;
94         TALLOC_CTX *tmp_ctx;
95
96         tmp_ctx = talloc_new(mem_ctx);
97         if (tmp_ctx == NULL) {
98                 return;
99         }
100
101         irpc_handle = irpc_binding_handle_by_name(tmp_ctx, msg_ctx,
102                                                   "dreplsrv",
103                                                   &ndr_table_irpc);
104         if (irpc_handle == NULL) {
105                 DEBUG(1,(__location__ ": Unable to get binding handle for dreplsrv\n"));
106                 TALLOC_FREE(tmp_ctx);
107                 return;
108         }
109
110         r.in.user_dn = ldb_dn_get_linearized(user_dn);
111
112         /*
113          * This seem to rely on the current IRPC implementation,
114          * which delivers the message in the _send function.
115          *
116          * TODO: we need a ONE_WAY IRPC handle and register
117          * a callback and wait for it to be triggered!
118          */
119         req = dcerpc_drepl_trigger_repl_secret_r_send(tmp_ctx,
120                                                       event_ctx,
121                                                       irpc_handle,
122                                                       &r);
123
124         /* we aren't interested in a reply */
125         talloc_free(req);
126         TALLOC_FREE(tmp_ctx);
127 }
128
129 static time_t ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, time_t default_val)
130 {
131     const char *tmp;
132     const char *gentime;
133     struct tm tm;
134
135     gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
136     if (!gentime)
137         return default_val;
138
139     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
140     if (tmp == NULL) {
141             return default_val;
142     }
143
144     return timegm(&tm);
145 }
146
147 static struct SDBFlags uf2SDBFlags(krb5_context context, uint32_t userAccountControl, enum samba_kdc_ent_type ent_type)
148 {
149         struct SDBFlags flags = int2SDBFlags(0);
150
151         /* we don't allow kadmin deletes */
152         flags.immutable = 1;
153
154         /* mark the principal as invalid to start with */
155         flags.invalid = 1;
156
157         flags.renewable = 1;
158
159         /* All accounts are servers, but this may be disabled again in the caller */
160         flags.server = 1;
161
162         /* Account types - clear the invalid bit if it turns out to be valid */
163         if (userAccountControl & UF_NORMAL_ACCOUNT) {
164                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
165                         flags.client = 1;
166                 }
167                 flags.invalid = 0;
168         }
169
170         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
171                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
172                         flags.client = 1;
173                 }
174                 flags.invalid = 0;
175         }
176         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
177                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
178                         flags.client = 1;
179                 }
180                 flags.invalid = 0;
181         }
182         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
183                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
184                         flags.client = 1;
185                 }
186                 flags.invalid = 0;
187         }
188
189         /* Not permitted to act as a client if disabled */
190         if (userAccountControl & UF_ACCOUNTDISABLE) {
191                 flags.client = 0;
192         }
193         if (userAccountControl & UF_LOCKOUT) {
194                 flags.locked_out = 1;
195         }
196 /*
197         if (userAccountControl & UF_PASSWORD_NOTREQD) {
198                 flags.invalid = 1;
199         }
200 */
201 /*
202         UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
203 */
204         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
205                 flags.invalid = 1;
206         }
207
208 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in samba_kdc_message2entry() */
209
210 /*
211         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
212                 flags.invalid = 1;
213         }
214 */
215         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
216                 flags.require_hwauth = 1;
217         }
218         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
219                 flags.ok_as_delegate = 1;
220         }
221         if (userAccountControl & UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION) {
222                 /*
223                  * this is confusing...
224                  *
225                  * UF_TRUSTED_FOR_DELEGATION
226                  * => ok_as_delegate
227                  *
228                  * and
229                  *
230                  * UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
231                  * => trusted_for_delegation
232                  */
233                 flags.trusted_for_delegation = 1;
234         }
235         if (!(userAccountControl & UF_NOT_DELEGATED)) {
236                 flags.forwardable = 1;
237                 flags.proxiable = 1;
238         }
239
240         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
241                 flags.require_preauth = 0;
242         } else {
243                 flags.require_preauth = 1;
244         }
245
246         if (userAccountControl & UF_NO_AUTH_DATA_REQUIRED) {
247                 flags.no_auth_data_reqd = 1;
248         }
249
250         return flags;
251 }
252
253 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
254 {
255         if (p->db_entry != NULL) {
256                 /*
257                  * A sdb_entry still has a reference
258                  */
259                 return -1;
260         }
261
262         if (p->kdc_entry != NULL) {
263                 /*
264                  * hdb_entry or krb5_db_entry still
265                  * have a reference...
266                  */
267                 return -1;
268         }
269
270         return 0;
271 }
272
273 /*
274  * Sort keys in descending order of strength.
275  *
276  * Explanaton from Greg Hudson:
277  *
278  * To encrypt tickets only the first returned key is used by the MIT KDC.  The
279  * other keys just communicate support for session key enctypes, and aren't
280  * really used.  The encryption key for the ticket enc part doesn't have
281  * to be of a type requested by the client. The session key enctype is chosen
282  * based on the client preference order, limited by the set of enctypes present
283  * in the server keys (unless the string attribute is set on the server
284  * principal overriding that set).
285  */
286
287 static int sdb_key_strength_priority(krb5_enctype etype)
288 {
289         static const krb5_enctype etype_list[] = {
290                 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
291                 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
292                 ENCTYPE_DES3_CBC_SHA1,
293                 ENCTYPE_ARCFOUR_HMAC,
294                 ENCTYPE_DES_CBC_MD5,
295                 ENCTYPE_DES_CBC_MD4,
296                 ENCTYPE_DES_CBC_CRC,
297                 ENCTYPE_NULL
298         };
299         int i;
300
301         for (i = 0; i < ARRAY_SIZE(etype_list); i++) {
302                 if (etype == etype_list[i]) {
303                         break;
304                 }
305         }
306
307         return ARRAY_SIZE(etype_list) - i;
308 }
309
310 static int sdb_key_strength_cmp(const struct sdb_key *k1, const struct sdb_key *k2)
311 {
312         int p1 = sdb_key_strength_priority(KRB5_KEY_TYPE(&k1->key));
313         int p2 = sdb_key_strength_priority(KRB5_KEY_TYPE(&k2->key));
314
315         if (p1 == p2) {
316                 return 0;
317         }
318
319         if (p1 > p2) {
320                 /*
321                  * Higher priority comes first
322                  */
323                 return -1;
324         } else {
325                 return 1;
326         }
327 }
328
329 static void samba_kdc_sort_keys(struct sdb_keys *keys)
330 {
331         if (keys == NULL) {
332                 return;
333         }
334
335         TYPESAFE_QSORT(keys->val, keys->len, sdb_key_strength_cmp);
336 }
337
338 int samba_kdc_set_fixed_keys(krb5_context context,
339                              struct samba_kdc_db_context *kdc_db_ctx,
340                              const struct ldb_val *secretbuffer,
341                              bool is_protected,
342                              struct sdb_keys *keys)
343 {
344         uint32_t supported_enctypes = ENC_ALL_TYPES;
345         uint16_t allocated_keys = 0;
346         int ret;
347
348         allocated_keys = 3;
349         keys->len = 0;
350         keys->val = calloc(allocated_keys, sizeof(struct sdb_key));
351         if (keys->val == NULL) {
352                 memset(secretbuffer->data, 0, secretbuffer->length);
353                 ret = ENOMEM;
354                 goto out;
355         }
356
357         if (is_protected) {
358                 supported_enctypes &= ~ENC_RC4_HMAC_MD5;
359         }
360
361         if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
362                 struct sdb_key key = {};
363
364                 ret = smb_krb5_keyblock_init_contents(context,
365                                                       ENCTYPE_AES256_CTS_HMAC_SHA1_96,
366                                                       secretbuffer->data,
367                                                       MIN(secretbuffer->length, 32),
368                                                       &key.key);
369                 if (ret) {
370                         memset(secretbuffer->data, 0, secretbuffer->length);
371                         goto out;
372                 }
373
374                 keys->val[keys->len] = key;
375                 keys->len++;
376         }
377
378         if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
379                 struct sdb_key key = {};
380
381                 ret = smb_krb5_keyblock_init_contents(context,
382                                                       ENCTYPE_AES128_CTS_HMAC_SHA1_96,
383                                                       secretbuffer->data,
384                                                       MIN(secretbuffer->length, 16),
385                                                       &key.key);
386                 if (ret) {
387                         memset(secretbuffer->data, 0, secretbuffer->length);
388                         goto out;
389                 }
390
391                 keys->val[keys->len] = key;
392                 keys->len++;
393         }
394
395         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
396                 struct sdb_key key = {};
397
398                 ret = smb_krb5_keyblock_init_contents(context,
399                                                       ENCTYPE_ARCFOUR_HMAC,
400                                                       secretbuffer->data,
401                                                       MIN(secretbuffer->length, 16),
402                                                       &key.key);
403                 if (ret) {
404                         memset(secretbuffer->data, 0, secretbuffer->length);
405                         goto out;
406                 }
407
408                 keys->val[keys->len] = key;
409                 keys->len++;
410         }
411         ret = 0;
412 out:
413         return ret;
414 }
415
416
417 static int samba_kdc_set_random_keys(krb5_context context,
418                                      struct samba_kdc_db_context *kdc_db_ctx,
419                                      struct sdb_keys *keys,
420                                      bool is_protected)
421 {
422         struct ldb_val secret_val;
423         uint8_t secretbuffer[32];
424
425         /*
426          * Fake keys until we have a better way to reject
427          * non-pkinit requests.
428          *
429          * We just need to indicate which encryption types are
430          * supported.
431          */
432         generate_secret_buffer(secretbuffer, sizeof(secretbuffer));
433
434         secret_val = data_blob_const(secretbuffer,
435                                      sizeof(secretbuffer));
436         return samba_kdc_set_fixed_keys(context, kdc_db_ctx,
437                                         &secret_val,
438                                         is_protected,
439                                         keys);
440 }
441
442
443 static krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
444                                                     struct samba_kdc_db_context *kdc_db_ctx,
445                                                     TALLOC_CTX *mem_ctx,
446                                                     struct ldb_message *msg,
447                                                     uint32_t rid,
448                                                     bool is_rodc,
449                                                     uint32_t userAccountControl,
450                                                     enum samba_kdc_ent_type ent_type,
451                                                     struct sdb_entry_ex *entry_ex,
452                                                     bool is_protected,
453                                                     uint32_t *supported_enctypes_out)
454 {
455         struct sdb_entry *entry = &entry_ex->entry;
456         krb5_error_code ret = 0;
457         enum ndr_err_code ndr_err;
458         struct samr_Password *hash;
459         const struct ldb_val *sc_val;
460         struct supplementalCredentialsBlob scb;
461         struct supplementalCredentialsPackage *scpk = NULL;
462         struct package_PrimaryKerberosBlob _pkb;
463         struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
464         bool is_krbtgt = false;
465         int krbtgt_number = 0;
466         uint32_t current_kvno;
467         uint32_t returned_kvno = 0;
468         uint16_t i;
469         uint16_t allocated_keys = 0;
470         uint32_t supported_enctypes
471                 = ldb_msg_find_attr_as_uint(msg,
472                                             "msDS-SupportedEncryptionTypes",
473                                             0);
474         *supported_enctypes_out = 0;
475
476         if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
477                 bool enable_fast;
478
479                 /* KDCs (and KDCs on RODCs) use AES */
480                 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
481                 is_krbtgt = true;
482
483                 enable_fast = lpcfg_kdc_enable_fast(kdc_db_ctx->lp_ctx);
484                 if (enable_fast) {
485                         supported_enctypes |= ENC_FAST_SUPPORTED;
486                 }
487         } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
488                 /* DCs and RODCs comptuer accounts use AES */
489                 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
490         } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
491                    (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
492                 /* for AS-REQ the client chooses the enc types it
493                  * supports, and this will vary between computers a
494                  * user logs in from.
495                  *
496                  * likewise for 'any' return as much as is supported,
497                  * to export into a keytab */
498                 supported_enctypes = ENC_ALL_TYPES;
499         }
500
501         /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
502         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
503                 supported_enctypes = 0;
504         } else {
505                 /* Otherwise, add in the default enc types */
506                 supported_enctypes |= ENC_RC4_HMAC_MD5;
507         }
508
509         if (is_protected) {
510                 supported_enctypes &= ~ENC_RC4_HMAC_MD5;
511         }
512
513         /* Is this the krbtgt or a RODC krbtgt */
514         if (is_rodc) {
515                 krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
516
517                 if (krbtgt_number == -1) {
518                         return EINVAL;
519                 }
520                 if (krbtgt_number == 0) {
521                         return EINVAL;
522                 }
523         }
524
525         if ((ent_type == SAMBA_KDC_ENT_TYPE_CLIENT)
526             && (userAccountControl & UF_SMARTCARD_REQUIRED)) {
527                 ret = samba_kdc_set_random_keys(context,
528                                                 kdc_db_ctx,
529                                                 &entry->keys,
530                                                 is_protected);
531
532                 *supported_enctypes_out = supported_enctypes;
533
534                 goto out;
535         }
536
537         current_kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
538         if (is_krbtgt) {
539                 /*
540                  * Even for the main krbtgt account
541                  * we have to strictly split the kvno into
542                  * two 16-bit parts and the upper 16-bit
543                  * need to be all zero, even if
544                  * the msDS-KeyVersionNumber has a value
545                  * larger than 65535.
546                  *
547                  * See https://bugzilla.samba.org/show_bug.cgi?id=14951
548                  */
549                 current_kvno = SAMBA_KVNO_GET_VALUE(current_kvno);
550         }
551
552         /* Get keys from the db */
553
554         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
555         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
556
557         /* unicodePwd for enctype 0x17 (23) if present */
558         if (hash) {
559                 allocated_keys++;
560         }
561
562         /* supplementalCredentials if present */
563         if (sc_val) {
564                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
565                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
566                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
567                         dump_data(0, sc_val->data, sc_val->length);
568                         ret = EINVAL;
569                         goto out;
570                 }
571
572                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
573                         if (scb.sub.num_packages != 0) {
574                                 NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
575                                 ret = EINVAL;
576                                 goto out;
577                         }
578                 }
579
580                 for (i=0; i < scb.sub.num_packages; i++) {
581                         if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
582                                 scpk = &scb.sub.packages[i];
583                                 if (!scpk->data || !scpk->data[0]) {
584                                         scpk = NULL;
585                                         continue;
586                                 }
587                                 break;
588                         }
589                 }
590         }
591         /*
592          * Primary:Kerberos-Newer-Keys element
593          * of supplementalCredentials
594          *
595          * The legacy Primary:Kerberos only contains
596          * single DES keys, which are completely ignored
597          * now.
598          */
599         if (scpk) {
600                 DATA_BLOB blob;
601
602                 blob = strhex_to_data_blob(mem_ctx, scpk->data);
603                 if (!blob.data) {
604                         ret = ENOMEM;
605                         goto out;
606                 }
607
608                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
609                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
610                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
611                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
612                         ret = EINVAL;
613                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
614                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
615                         goto out;
616                 }
617
618                 if (_pkb.version != 4) {
619                         ret = EINVAL;
620                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
621                         krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
622                         goto out;
623                 }
624
625                 pkb4 = &_pkb.ctr.ctr4;
626                 allocated_keys += pkb4->num_keys;
627         }
628
629         if (allocated_keys == 0) {
630                 if (kdc_db_ctx->rodc) {
631                         /* We are on an RODC, but don't have keys for this account.  Signal this to the caller */
632                         auth_sam_trigger_repl_secret(kdc_db_ctx, kdc_db_ctx->msg_ctx,
633                                                      kdc_db_ctx->ev_ctx, msg->dn);
634                         return SDB_ERR_NOT_FOUND_HERE;
635                 }
636
637                 /* oh, no password.  Apparently (comment in
638                  * hdb-ldap.c) this violates the ASN.1, but this
639                  * allows an entry with no keys (yet). */
640                 return 0;
641         }
642
643         /* allocate space to decode into */
644         entry_ex->entry.keys.len = 0;
645         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(struct sdb_key));
646         if (entry_ex->entry.keys.val == NULL) {
647                 ret = ENOMEM;
648                 goto out;
649         }
650
651         if (hash && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
652                 struct sdb_key key = {};
653
654                 ret = smb_krb5_keyblock_init_contents(context,
655                                                       ENCTYPE_ARCFOUR_HMAC,
656                                                       hash->hash,
657                                                       sizeof(hash->hash),
658                                                       &key.key);
659                 if (ret) {
660                         goto out;
661                 }
662
663                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
664                 entry_ex->entry.keys.len++;
665
666                 *supported_enctypes_out |= ENC_RC4_HMAC_MD5;
667         }
668
669         if (pkb4) {
670                 for (i=0; i < pkb4->num_keys; i++) {
671                         struct sdb_key key = {};
672                         uint32_t enctype_bit;
673
674                         if (!pkb4->keys[i].value) continue;
675
676                         enctype_bit = kerberos_enctype_to_bitmap(pkb4->keys[i].keytype);
677                         if (!(enctype_bit & supported_enctypes)) {
678                                 continue;
679                         }
680
681                         if (pkb4->salt.string) {
682                                 DATA_BLOB salt;
683
684                                 salt = data_blob_string_const(pkb4->salt.string);
685
686                                 key.salt = calloc(1, sizeof(*key.salt));
687                                 if (key.salt == NULL) {
688                                         ret = ENOMEM;
689                                         goto out;
690                                 }
691
692                                 key.salt->type = KRB5_PW_SALT;
693
694                                 ret = smb_krb5_copy_data_contents(&key.salt->salt,
695                                                                   salt.data,
696                                                                   salt.length);
697                                 if (ret) {
698                                         free(key.salt);
699                                         key.salt = NULL;
700                                         goto out;
701                                 }
702                         }
703
704                         /* TODO: maybe pass the iteration_count somehow... */
705
706                         ret = smb_krb5_keyblock_init_contents(context,
707                                                               pkb4->keys[i].keytype,
708                                                               pkb4->keys[i].value->data,
709                                                               pkb4->keys[i].value->length,
710                                                               &key.key);
711                         if (ret) {
712                                 if (key.salt) {
713                                         smb_krb5_free_data_contents(context, &key.salt->salt);
714                                         free(key.salt);
715                                         key.salt = NULL;
716                                 }
717                                 if (ret == KRB5_PROG_ETYPE_NOSUPP) {
718                                         DEBUG(2,("Unsupported keytype ignored - type %u\n",
719                                                  pkb4->keys[i].keytype));
720                                         ret = 0;
721                                         continue;
722                                 }
723                                 goto out;
724                         }
725
726                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
727                         entry_ex->entry.keys.len++;
728
729                         *supported_enctypes_out |= enctype_bit;
730                 }
731         }
732
733         /* Set FAST support bits */
734         *supported_enctypes_out |= supported_enctypes & (ENC_FAST_SUPPORTED |
735                                                          ENC_COMPOUND_IDENTITY_SUPPORTED |
736                                                          ENC_CLAIMS_SUPPORTED);
737
738         returned_kvno = current_kvno;
739         if (is_krbtgt) {
740                 /*
741                  * Even for the main krbtgt account
742                  * we have to strictly split the kvno into
743                  * two 16-bit parts and the upper 16-bit
744                  * need to be all zero, even if
745                  * the msDS-KeyVersionNumber has a value
746                  * larger than 65535.
747                  *
748                  * See https://bugzilla.samba.org/show_bug.cgi?id=14951
749                  */
750                 returned_kvno = SAMBA_KVNO_AND_KRBTGT(returned_kvno, krbtgt_number);
751         }
752         entry->kvno = returned_kvno;
753
754 out:
755         if (ret != 0) {
756                 entry_ex->entry.keys.len = 0;
757         } else if (entry_ex->entry.keys.len > 0 &&
758                    entry_ex->entry.keys.val != NULL) {
759                 samba_kdc_sort_keys(&entry_ex->entry.keys);
760         }
761         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
762                 free(entry_ex->entry.keys.val);
763                 entry_ex->entry.keys.val = NULL;
764         }
765         return ret;
766 }
767
768 static int principal_comp_strcmp_int(krb5_context context,
769                                      krb5_const_principal principal,
770                                      unsigned int component,
771                                      const char *string,
772                                      bool do_strcasecmp)
773 {
774         const char *p;
775         size_t len;
776
777 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
778         p = krb5_principal_get_comp_string(context, principal, component);
779         if (p == NULL) {
780                 return -1;
781         }
782         len = strlen(p);
783 #else
784         krb5_data *d;
785         if (component >= krb5_princ_size(context, principal)) {
786                 return -1;
787         }
788
789         d = krb5_princ_component(context, principal, component);
790         if (d == NULL) {
791                 return -1;
792         }
793
794         p = d->data;
795         len = d->length;
796 #endif
797         if (do_strcasecmp) {
798                 return strncasecmp(p, string, len);
799         } else {
800                 return strncmp(p, string, len);
801         }
802 }
803
804 static int principal_comp_strcasecmp(krb5_context context,
805                                      krb5_const_principal principal,
806                                      unsigned int component,
807                                      const char *string)
808 {
809         return principal_comp_strcmp_int(context, principal,
810                                          component, string, true);
811 }
812
813 static int principal_comp_strcmp(krb5_context context,
814                                  krb5_const_principal principal,
815                                  unsigned int component,
816                                  const char *string)
817 {
818         return principal_comp_strcmp_int(context, principal,
819                                          component, string, false);
820 }
821
822 /*
823  * Construct an hdb_entry from a directory entry.
824  */
825 static krb5_error_code samba_kdc_message2entry(krb5_context context,
826                                                struct samba_kdc_db_context *kdc_db_ctx,
827                                                TALLOC_CTX *mem_ctx,
828                                                krb5_const_principal principal,
829                                                enum samba_kdc_ent_type ent_type,
830                                                unsigned flags,
831                                                struct ldb_dn *realm_dn,
832                                                struct ldb_message *msg,
833                                                struct sdb_entry_ex *entry_ex)
834 {
835         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
836         uint32_t userAccountControl;
837         uint32_t msDS_User_Account_Control_Computed;
838         krb5_error_code ret = 0;
839         krb5_boolean is_computer = FALSE;
840         struct samba_kdc_entry *p;
841         uint32_t supported_enctypes = 0;
842         NTTIME acct_expiry;
843         NTSTATUS status;
844         bool protected_user = false;
845         uint32_t rid;
846         bool is_rodc = false;
847         struct ldb_message_element *objectclasses;
848         struct ldb_val computer_val = data_blob_string_const("computer");
849         const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
850
851         ZERO_STRUCTP(entry_ex);
852
853         if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
854                 is_rodc = true;
855         }
856
857         if (!samAccountName) {
858                 ret = ENOENT;
859                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
860                 goto out;
861         }
862
863         objectclasses = ldb_msg_find_element(msg, "objectClass");
864
865         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
866                 is_computer = TRUE;
867         }
868
869         p = talloc_zero(mem_ctx, struct samba_kdc_entry);
870         if (!p) {
871                 ret = ENOMEM;
872                 goto out;
873         }
874
875         p->is_rodc = is_rodc;
876         p->kdc_db_ctx = kdc_db_ctx;
877         p->realm_dn = talloc_reference(p, realm_dn);
878         if (!p->realm_dn) {
879                 ret = ENOMEM;
880                 goto out;
881         }
882
883         talloc_set_destructor(p, samba_kdc_entry_destructor);
884
885         entry_ex->entry.skdc_entry = p;
886
887         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
888
889         msDS_User_Account_Control_Computed
890                 = ldb_msg_find_attr_as_uint(msg,
891                                             "msDS-User-Account-Control-Computed",
892                                             UF_ACCOUNTDISABLE);
893
894         /*
895          * This brings in the lockout flag, block the account if not
896          * found.  We need the weird UF_ACCOUNTDISABLE check because
897          * we do not want to fail open if the value is not returned,
898          * but 0 is a valid value (all OK)
899          */
900         if (msDS_User_Account_Control_Computed == UF_ACCOUNTDISABLE) {
901                 ret = EINVAL;
902                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: "
903                                 "no msDS-User-Account-Control-Computed present");
904                 goto out;
905         } else {
906                 userAccountControl |= msDS_User_Account_Control_Computed;
907         }
908
909         /*
910          * If we are set to canonicalize, we get back the fixed UPPER
911          * case realm, and the real username (ie matching LDAP
912          * samAccountName)
913          *
914          * Otherwise, if we are set to enterprise, we
915          * get back the whole principal as-sent
916          *
917          * Finally, if we are not set to canonicalize, we get back the
918          * fixed UPPER case realm, but the as-sent username
919          */
920
921         if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) {
922                 p->is_krbtgt = true;
923
924                 if (flags & (SDB_F_CANON|SDB_F_FORCE_CANON)) {
925                         /*
926                          * When requested to do so, ensure that the
927                          * both realm values in the principal are set
928                          * to the upper case, canonical realm
929                          */
930                         ret = smb_krb5_make_principal(context, &entry_ex->entry.principal,
931                                                       lpcfg_realm(lp_ctx), "krbtgt",
932                                                       lpcfg_realm(lp_ctx), NULL);
933                         if (ret) {
934                                 krb5_clear_error_message(context);
935                                 goto out;
936                         }
937                         smb_krb5_principal_set_type(context, entry_ex->entry.principal, KRB5_NT_SRV_INST);
938                 } else {
939                         ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
940                         if (ret) {
941                                 krb5_clear_error_message(context);
942                                 goto out;
943                         }
944                         /*
945                          * this appears to be required regardless of
946                          * the canonicalize flag from the client
947                          */
948                         ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
949                         if (ret) {
950                                 krb5_clear_error_message(context);
951                                 goto out;
952                         }
953                 }
954
955         } else if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
956                 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
957                 if (ret) {
958                         krb5_clear_error_message(context);
959                         goto out;
960                 }
961         } else if ((flags & SDB_F_FORCE_CANON) ||
962                    ((flags & SDB_F_CANON) && (flags & SDB_F_FOR_AS_REQ))) {
963                 /*
964                  * SDB_F_CANON maps from the canonicalize flag in the
965                  * packet, and has a different meaning between AS-REQ
966                  * and TGS-REQ.  We only change the principal in the AS-REQ case
967                  *
968                  * The SDB_F_FORCE_CANON if for new MIT KDC code that wants
969                  * the canonical name in all lookups, and takes care to
970                  * canonicalize only when appropriate.
971                  */
972                 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
973                 if (ret) {
974                         krb5_clear_error_message(context);
975                         goto out;
976                 }
977         } else {
978                 ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
979                 if (ret) {
980                         krb5_clear_error_message(context);
981                         goto out;
982                 }
983
984                 /* While we have copied the client principal, tests
985                  * show that Win2k3 returns the 'corrected' realm, not
986                  * the client-specified realm.  This code attempts to
987                  * replace the client principal's realm with the one
988                  * we determine from our records */
989
990                 /* this has to be with malloc() */
991                 ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
992                 if (ret) {
993                         krb5_clear_error_message(context);
994                         goto out;
995                 }
996         }
997
998         /* First try and figure out the flags based on the userAccountControl */
999         entry_ex->entry.flags = uf2SDBFlags(context, userAccountControl, ent_type);
1000
1001         /*
1002          * Take control of the returned principal here, rather than
1003          * allowing the Heimdal code to do it as we have specific
1004          * behaviour around the forced realm to honour
1005          */
1006         entry_ex->entry.flags.force_canonicalize = true;
1007
1008         /* Windows 2008 seems to enforce this (very sensible) rule by
1009          * default - don't allow offline attacks on a user's password
1010          * by asking for a ticket to them as a service (encrypted with
1011          * their probably patheticly insecure password) */
1012
1013         if (entry_ex->entry.flags.server
1014             && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
1015                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
1016                         entry_ex->entry.flags.server = 0;
1017                 }
1018         }
1019
1020         /*
1021          * We restrict a 3-part SPN ending in my domain/realm to full
1022          * domain controllers.
1023          *
1024          * This avoids any cases where (eg) a demoted DC still has
1025          * these more restricted SPNs.
1026          */
1027         if (krb5_princ_size(context, principal) > 2) {
1028                 char *third_part
1029                         = smb_krb5_principal_get_comp_string(mem_ctx,
1030                                                              context,
1031                                                              principal,
1032                                                              2);
1033                 bool is_our_realm =
1034                          lpcfg_is_my_domain_or_realm(lp_ctx,
1035                                                      third_part);
1036                 bool is_dc = userAccountControl &
1037                         (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT);
1038                 if (is_our_realm && !is_dc) {
1039                         entry_ex->entry.flags.server = 0;
1040                 }
1041         }
1042         /*
1043          * To give the correct type of error to the client, we must
1044          * not just return the entry without .server set, we must
1045          * pretend the principal does not exist.  Otherwise we may
1046          * return ERR_POLICY instead of
1047          * KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN
1048          */
1049         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && entry_ex->entry.flags.server == 0) {
1050                 ret = SDB_ERR_NOENTRY;
1051                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no servicePrincipalName present for this server, refusing with no-such-entry");
1052                 goto out;
1053         }
1054         if (flags & SDB_F_ADMIN_DATA) {
1055                 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
1056                  * of the Heimdal KDC.  They are stored in a the traditional
1057                  * DB for audit purposes, and still form part of the structure
1058                  * we must return */
1059
1060                 /* use 'whenCreated' */
1061                 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1062                 /* use 'kadmin' for now (needed by mit_samba) */
1063
1064                 ret = smb_krb5_make_principal(context,
1065                                               &entry_ex->entry.created_by.principal,
1066                                               lpcfg_realm(lp_ctx), "kadmin", NULL);
1067                 if (ret) {
1068                         krb5_clear_error_message(context);
1069                         goto out;
1070                 }
1071
1072                 entry_ex->entry.modified_by = (struct sdb_event *) malloc(sizeof(struct sdb_event));
1073                 if (entry_ex->entry.modified_by == NULL) {
1074                         ret = ENOMEM;
1075                         krb5_set_error_message(context, ret, "malloc: out of memory");
1076                         goto out;
1077                 }
1078
1079                 /* use 'whenChanged' */
1080                 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
1081                 /* use 'kadmin' for now (needed by mit_samba) */
1082                 ret = smb_krb5_make_principal(context,
1083                                               &entry_ex->entry.modified_by->principal,
1084                                               lpcfg_realm(lp_ctx), "kadmin", NULL);
1085                 if (ret) {
1086                         krb5_clear_error_message(context);
1087                         goto out;
1088                 }
1089         }
1090
1091
1092         /* The lack of password controls etc applies to krbtgt by
1093          * virtue of being that particular RID */
1094         status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
1095
1096         if (!NT_STATUS_IS_OK(status)) {
1097                 ret = EINVAL;
1098                 goto out;
1099         }
1100
1101         if (rid == DOMAIN_RID_KRBTGT) {
1102                 char *realm = NULL;
1103
1104                 entry_ex->entry.valid_end = NULL;
1105                 entry_ex->entry.pw_end = NULL;
1106
1107                 entry_ex->entry.flags.invalid = 0;
1108                 entry_ex->entry.flags.server = 1;
1109
1110                 realm = smb_krb5_principal_get_realm(
1111                         mem_ctx, context, principal);
1112                 if (realm == NULL) {
1113                         ret = ENOMEM;
1114                         goto out;
1115                 }
1116
1117                 /* Don't mark all requests for the krbtgt/realm as
1118                  * 'change password', as otherwise we could get into
1119                  * trouble, and not enforce the password expirty.
1120                  * Instead, only do it when request is for the kpasswd service */
1121                 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
1122                     && krb5_princ_size(context, principal) == 2
1123                     && (principal_comp_strcmp(context, principal, 0, "kadmin") == 0)
1124                     && (principal_comp_strcmp(context, principal, 1, "changepw") == 0)
1125                     && lpcfg_is_my_domain_or_realm(lp_ctx, realm)) {
1126                         entry_ex->entry.flags.change_pw = 1;
1127                 }
1128
1129                 TALLOC_FREE(realm);
1130
1131                 entry_ex->entry.flags.client = 0;
1132                 entry_ex->entry.flags.forwardable = 1;
1133                 entry_ex->entry.flags.ok_as_delegate = 1;
1134         } else if (is_rodc) {
1135                 /* The RODC krbtgt account is like the main krbtgt,
1136                  * but it does not have a changepw or kadmin
1137                  * service */
1138
1139                 entry_ex->entry.valid_end = NULL;
1140                 entry_ex->entry.pw_end = NULL;
1141
1142                 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
1143                 entry_ex->entry.flags.client = 0;
1144                 entry_ex->entry.flags.invalid = 0;
1145                 entry_ex->entry.flags.server = 1;
1146
1147                 entry_ex->entry.flags.client = 0;
1148                 entry_ex->entry.flags.forwardable = 1;
1149                 entry_ex->entry.flags.ok_as_delegate = 0;
1150         } else if (entry_ex->entry.flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1151                 /* The account/password expiry only applies when the account is used as a
1152                  * client (ie password login), not when used as a server */
1153
1154                 /* Make very well sure we don't use this for a client,
1155                  * it could bypass the password restrictions */
1156                 entry_ex->entry.flags.client = 0;
1157
1158                 entry_ex->entry.valid_end = NULL;
1159                 entry_ex->entry.pw_end = NULL;
1160
1161         } else {
1162                 NTTIME must_change_time
1163                         = samdb_result_nttime(msg,
1164                                         "msDS-UserPasswordExpiryTimeComputed",
1165                                         0);
1166                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
1167                         entry_ex->entry.pw_end = NULL;
1168                 } else {
1169                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
1170                         if (entry_ex->entry.pw_end == NULL) {
1171                                 ret = ENOMEM;
1172                                 goto out;
1173                         }
1174                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
1175                 }
1176
1177                 acct_expiry = samdb_result_account_expires(msg);
1178                 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
1179                         entry_ex->entry.valid_end = NULL;
1180                 } else {
1181                         entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
1182                         if (entry_ex->entry.valid_end == NULL) {
1183                                 ret = ENOMEM;
1184                                 goto out;
1185                         }
1186                         *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
1187                 }
1188         }
1189
1190         entry_ex->entry.valid_start = NULL;
1191
1192         entry_ex->entry.max_life = malloc(sizeof(*entry_ex->entry.max_life));
1193         if (entry_ex->entry.max_life == NULL) {
1194                 ret = ENOMEM;
1195                 goto out;
1196         }
1197
1198         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1199                 *entry_ex->entry.max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
1200         } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
1201                 *entry_ex->entry.max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
1202         } else {
1203                 *entry_ex->entry.max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
1204                                                 kdc_db_ctx->policy.usr_tkt_lifetime);
1205         }
1206
1207         entry_ex->entry.max_renew = malloc(sizeof(*entry_ex->entry.max_renew));
1208         if (entry_ex->entry.max_renew == NULL) {
1209                 ret = ENOMEM;
1210                 goto out;
1211         }
1212
1213         *entry_ex->entry.max_renew = kdc_db_ctx->policy.renewal_lifetime;
1214
1215         if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT && (flags & SDB_F_FOR_AS_REQ)) {
1216                 int result;
1217                 struct auth_user_info_dc *user_info_dc = NULL;
1218                 /*
1219                  * These protections only apply to clients, so servers in the
1220                  * Protected Users group may still have service tickets to them
1221                  * encrypted with RC4. For accounts looked up as servers, note
1222                  * that 'msg' does not contain the 'memberOf' attribute for
1223                  * determining whether the account is a member of Protected
1224                  * Users.
1225                  *
1226                  * Additionally, Microsoft advises that accounts for services
1227                  * and computers should never be members of Protected Users, or
1228                  * they may fail to authenticate.
1229                  */
1230                 status = samba_kdc_get_user_info_from_db(p, msg, &user_info_dc);
1231                 if (!NT_STATUS_IS_OK(status)) {
1232                         ret = EINVAL;
1233                         goto out;
1234                 }
1235
1236                 result = dsdb_is_protected_user(kdc_db_ctx->samdb,
1237                                                 user_info_dc->sids,
1238                                                 user_info_dc->num_sids);
1239                 if (result == -1) {
1240                         ret = EINVAL;
1241                         goto out;
1242                 }
1243
1244                 protected_user = result;
1245
1246                 if (protected_user) {
1247                         *entry_ex->entry.max_life = MIN(*entry_ex->entry.max_life, 4 * 60 * 60);
1248                         *entry_ex->entry.max_renew = MIN(*entry_ex->entry.max_renew, 4 * 60 * 60);
1249
1250                         entry_ex->entry.flags.forwardable = 0;
1251                         entry_ex->entry.flags.proxiable = 0;
1252                 }
1253         }
1254
1255         /* Get keys from the db */
1256         ret = samba_kdc_message2entry_keys(context, kdc_db_ctx, p, msg,
1257                                            rid, is_rodc, userAccountControl,
1258                                            ent_type, entry_ex, protected_user, &supported_enctypes);
1259         if (ret) {
1260                 /* Could be bogus data in the entry, or out of memory */
1261                 goto out;
1262         }
1263
1264         p->msg = talloc_steal(p, msg);
1265         p->supported_enctypes = supported_enctypes;
1266
1267 out:
1268         if (ret != 0) {
1269                 /* This doesn't free ent itself, that is for the eventual caller to do */
1270                 sdb_free_entry(entry_ex);
1271         } else {
1272                 talloc_steal(kdc_db_ctx, p);
1273         }
1274
1275         return ret;
1276 }
1277
1278 /*
1279  * Construct an hdb_entry from a directory entry.
1280  * The kvno is what the remote client asked for
1281  */
1282 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
1283                                                struct samba_kdc_db_context *kdc_db_ctx,
1284                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
1285                                                enum trust_direction direction,
1286                                                struct ldb_dn *realm_dn,
1287                                                unsigned flags,
1288                                                uint32_t kvno,
1289                                                struct ldb_message *msg,
1290                                                struct sdb_entry_ex *entry_ex)
1291 {
1292         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1293         const char *our_realm = lpcfg_realm(lp_ctx);
1294         char *partner_realm = NULL;
1295         const char *realm = NULL;
1296         const char *krbtgt_realm = NULL;
1297         DATA_BLOB password_utf16 = data_blob_null;
1298         DATA_BLOB password_utf8 = data_blob_null;
1299         struct samr_Password _password_hash;
1300         const struct samr_Password *password_hash = NULL;
1301         const struct ldb_val *password_val;
1302         struct trustAuthInOutBlob password_blob;
1303         struct samba_kdc_entry *p;
1304         bool use_previous = false;
1305         uint32_t current_kvno;
1306         uint32_t previous_kvno;
1307         uint32_t num_keys = 0;
1308         enum ndr_err_code ndr_err;
1309         int ret;
1310         unsigned int i;
1311         struct AuthenticationInformationArray *auth_array;
1312         struct timeval tv;
1313         NTTIME an_hour_ago;
1314         uint32_t *auth_kvno;
1315         bool preferr_current = false;
1316         uint32_t supported_enctypes = ENC_RC4_HMAC_MD5;
1317         struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
1318         NTSTATUS status;
1319
1320         ZERO_STRUCTP(entry_ex);
1321
1322         if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1323                 supported_enctypes = ldb_msg_find_attr_as_uint(msg,
1324                                         "msDS-SupportedEncryptionTypes",
1325                                         supported_enctypes);
1326         }
1327
1328         status = dsdb_trust_parse_tdo_info(mem_ctx, msg, &tdo);
1329         if (!NT_STATUS_IS_OK(status)) {
1330                 krb5_clear_error_message(context);
1331                 ret = ENOMEM;
1332                 goto out;
1333         }
1334
1335         if (!(tdo->trust_direction & direction)) {
1336                 krb5_clear_error_message(context);
1337                 ret = SDB_ERR_NOENTRY;
1338                 goto out;
1339         }
1340
1341         if (tdo->trust_type != LSA_TRUST_TYPE_UPLEVEL) {
1342                 /*
1343                  * Only UPLEVEL domains support kerberos here,
1344                  * as we don't support LSA_TRUST_TYPE_MIT.
1345                  */
1346                 krb5_clear_error_message(context);
1347                 ret = SDB_ERR_NOENTRY;
1348                 goto out;
1349         }
1350
1351         if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_CROSS_ORGANIZATION) {
1352                 /*
1353                  * We don't support selective authentication yet.
1354                  */
1355                 krb5_clear_error_message(context);
1356                 ret = SDB_ERR_NOENTRY;
1357                 goto out;
1358         }
1359
1360         if (tdo->domain_name.string == NULL) {
1361                 krb5_clear_error_message(context);
1362                 ret = SDB_ERR_NOENTRY;
1363                 goto out;
1364         }
1365         partner_realm = strupper_talloc(mem_ctx, tdo->domain_name.string);
1366         if (partner_realm == NULL) {
1367                 krb5_clear_error_message(context);
1368                 ret = ENOMEM;
1369                 goto out;
1370         }
1371
1372         if (direction == INBOUND) {
1373                 realm = our_realm;
1374                 krbtgt_realm = partner_realm;
1375
1376                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
1377         } else { /* OUTBOUND */
1378                 realm = partner_realm;
1379                 krbtgt_realm = our_realm;
1380
1381                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
1382         }
1383
1384         if (password_val == NULL) {
1385                 krb5_clear_error_message(context);
1386                 ret = SDB_ERR_NOENTRY;
1387                 goto out;
1388         }
1389
1390         ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
1391                                        (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
1392         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1393                 krb5_clear_error_message(context);
1394                 ret = EINVAL;
1395                 goto out;
1396         }
1397
1398         p = talloc_zero(mem_ctx, struct samba_kdc_entry);
1399         if (!p) {
1400                 ret = ENOMEM;
1401                 goto out;
1402         }
1403
1404         p->is_trust = true;
1405         p->kdc_db_ctx = kdc_db_ctx;
1406         p->realm_dn = realm_dn;
1407         p->supported_enctypes = supported_enctypes;
1408
1409         talloc_set_destructor(p, samba_kdc_entry_destructor);
1410
1411         entry_ex->entry.skdc_entry = p;
1412
1413         /* use 'whenCreated' */
1414         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1415         /* use 'kadmin' for now (needed by mit_samba) */
1416         ret = smb_krb5_make_principal(context,
1417                                       &entry_ex->entry.created_by.principal,
1418                                       realm, "kadmin", NULL);
1419         if (ret) {
1420                 krb5_clear_error_message(context);
1421                 goto out;
1422         }
1423
1424         /*
1425          * We always need to generate the canonicalized principal
1426          * with the values of our database.
1427          */
1428         ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, realm,
1429                                       "krbtgt", krbtgt_realm, NULL);
1430         if (ret) {
1431                 krb5_clear_error_message(context);
1432                 goto out;
1433         }
1434         smb_krb5_principal_set_type(context, entry_ex->entry.principal,
1435                                     KRB5_NT_SRV_INST);
1436
1437         entry_ex->entry.valid_start = NULL;
1438
1439         /* we need to work out if we are going to use the current or
1440          * the previous password hash.
1441          * We base this on the kvno the client passes in. If the kvno
1442          * passed in is equal to the current kvno in our database then
1443          * we use the current structure. If it is the current kvno-1,
1444          * then we use the previous substrucure.
1445          */
1446
1447         /*
1448          * Windows preferrs the previous key for one hour.
1449          */
1450         tv = timeval_current();
1451         if (tv.tv_sec > 3600) {
1452                 tv.tv_sec -= 3600;
1453         }
1454         an_hour_ago = timeval_to_nttime(&tv);
1455
1456         /* first work out the current kvno */
1457         current_kvno = 0;
1458         for (i=0; i < password_blob.count; i++) {
1459                 struct AuthenticationInformation *a =
1460                         &password_blob.current.array[i];
1461
1462                 if (a->LastUpdateTime <= an_hour_ago) {
1463                         preferr_current = true;
1464                 }
1465
1466                 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1467                         current_kvno = a->AuthInfo.version.version;
1468                 }
1469         }
1470         if (current_kvno == 0) {
1471                 previous_kvno = 255;
1472         } else {
1473                 previous_kvno = current_kvno - 1;
1474         }
1475         for (i=0; i < password_blob.count; i++) {
1476                 struct AuthenticationInformation *a =
1477                         &password_blob.previous.array[i];
1478
1479                 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1480                         previous_kvno = a->AuthInfo.version.version;
1481                 }
1482         }
1483
1484         /* work out whether we will use the previous or current
1485            password */
1486         if (password_blob.previous.count == 0) {
1487                 /* there is no previous password */
1488                 use_previous = false;
1489         } else if (!(flags & SDB_F_KVNO_SPECIFIED)) {
1490                 /*
1491                  * If not specified we use the lowest kvno
1492                  * for the first hour after an update.
1493                  */
1494                 if (preferr_current) {
1495                         use_previous = false;
1496                 } else if (previous_kvno < current_kvno) {
1497                         use_previous = true;
1498                 } else {
1499                         use_previous = false;
1500                 }
1501         } else if (kvno == current_kvno) {
1502                 /*
1503                  * Exact match ...
1504                  */
1505                 use_previous = false;
1506         } else if (kvno == previous_kvno) {
1507                 /*
1508                  * Exact match ...
1509                  */
1510                 use_previous = true;
1511         } else {
1512                 /*
1513                  * Fallback to the current one for anything else
1514                  */
1515                 use_previous = false;
1516         }
1517
1518         if (use_previous) {
1519                 auth_array = &password_blob.previous;
1520                 auth_kvno = &previous_kvno;
1521         } else {
1522                 auth_array = &password_blob.current;
1523                 auth_kvno = &current_kvno;
1524         }
1525
1526         /* use the kvno the client specified, if available */
1527         if (flags & SDB_F_KVNO_SPECIFIED) {
1528                 entry_ex->entry.kvno = kvno;
1529         } else {
1530                 entry_ex->entry.kvno = *auth_kvno;
1531         }
1532
1533         for (i=0; i < auth_array->count; i++) {
1534                 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
1535                         bool ok;
1536
1537                         password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
1538                                                          auth_array->array[i].AuthInfo.clear.size);
1539                         if (password_utf16.length == 0) {
1540                                 break;
1541                         }
1542
1543                         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1544                                 mdfour(_password_hash.hash, password_utf16.data, password_utf16.length);
1545                                 if (password_hash == NULL) {
1546                                         num_keys += 1;
1547                                 }
1548                                 password_hash = &_password_hash;
1549                         }
1550
1551                         if (!(supported_enctypes & (ENC_HMAC_SHA1_96_AES128|ENC_HMAC_SHA1_96_AES256))) {
1552                                 break;
1553                         }
1554
1555                         ok = convert_string_talloc(mem_ctx,
1556                                                    CH_UTF16MUNGED, CH_UTF8,
1557                                                    password_utf16.data,
1558                                                    password_utf16.length,
1559                                                    (void *)&password_utf8.data,
1560                                                    &password_utf8.length);
1561                         if (!ok) {
1562                                 krb5_clear_error_message(context);
1563                                 ret = ENOMEM;
1564                                 goto out;
1565                         }
1566
1567                         if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1568                                 num_keys += 1;
1569                         }
1570                         if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1571                                 num_keys += 1;
1572                         }
1573                         break;
1574                 } else if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
1575                         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1576                                 password_hash = &auth_array->array[i].AuthInfo.nt4owf.password;
1577                                 num_keys += 1;
1578                         }
1579                 }
1580         }
1581
1582         /* Must have found a cleartext or MD4 password */
1583         if (num_keys == 0) {
1584                 DEBUG(1,(__location__ ": no usable key found\n"));
1585                 krb5_clear_error_message(context);
1586                 ret = SDB_ERR_NOENTRY;
1587                 goto out;
1588         }
1589
1590         entry_ex->entry.keys.val = calloc(num_keys, sizeof(struct sdb_key));
1591         if (entry_ex->entry.keys.val == NULL) {
1592                 krb5_clear_error_message(context);
1593                 ret = ENOMEM;
1594                 goto out;
1595         }
1596
1597         if (password_utf8.length != 0) {
1598                 struct sdb_key key = {};
1599                 krb5_const_principal salt_principal = entry_ex->entry.principal;
1600                 krb5_data salt;
1601                 krb5_data cleartext_data;
1602
1603                 cleartext_data.data = discard_const_p(char, password_utf8.data);
1604                 cleartext_data.length = password_utf8.length;
1605
1606                 ret = smb_krb5_get_pw_salt(context,
1607                                            salt_principal,
1608                                            &salt);
1609                 if (ret != 0) {
1610                         goto out;
1611                 }
1612
1613                 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1614                         ret = smb_krb5_create_key_from_string(context,
1615                                                               salt_principal,
1616                                                               &salt,
1617                                                               &cleartext_data,
1618                                                               ENCTYPE_AES256_CTS_HMAC_SHA1_96,
1619                                                               &key.key);
1620                         if (ret != 0) {
1621                                 smb_krb5_free_data_contents(context, &salt);
1622                                 goto out;
1623                         }
1624
1625                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1626                         entry_ex->entry.keys.len++;
1627                 }
1628
1629                 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1630                         ret = smb_krb5_create_key_from_string(context,
1631                                                               salt_principal,
1632                                                               &salt,
1633                                                               &cleartext_data,
1634                                                               ENCTYPE_AES128_CTS_HMAC_SHA1_96,
1635                                                               &key.key);
1636                         if (ret != 0) {
1637                                 smb_krb5_free_data_contents(context, &salt);
1638                                 goto out;
1639                         }
1640
1641                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1642                         entry_ex->entry.keys.len++;
1643                 }
1644
1645                 smb_krb5_free_data_contents(context, &salt);
1646         }
1647
1648         if (password_hash != NULL) {
1649                 struct sdb_key key = {};
1650
1651                 ret = smb_krb5_keyblock_init_contents(context,
1652                                                       ENCTYPE_ARCFOUR_HMAC,
1653                                                       password_hash->hash,
1654                                                       sizeof(password_hash->hash),
1655                                                       &key.key);
1656                 if (ret != 0) {
1657                         goto out;
1658                 }
1659
1660                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1661                 entry_ex->entry.keys.len++;
1662         }
1663
1664         entry_ex->entry.flags = int2SDBFlags(0);
1665         entry_ex->entry.flags.immutable = 1;
1666         entry_ex->entry.flags.invalid = 0;
1667         entry_ex->entry.flags.server = 1;
1668         entry_ex->entry.flags.require_preauth = 1;
1669
1670         entry_ex->entry.pw_end = NULL;
1671
1672         entry_ex->entry.max_life = NULL;
1673
1674         entry_ex->entry.max_renew = NULL;
1675
1676         /* Match Windows behavior and allow forwardable flag in cross-realm. */
1677         entry_ex->entry.flags.forwardable = 1;
1678
1679         samba_kdc_sort_keys(&entry_ex->entry.keys);
1680
1681         p->msg = talloc_steal(p, msg);
1682
1683 out:
1684         TALLOC_FREE(partner_realm);
1685
1686         if (ret != 0) {
1687                 /* This doesn't free ent itself, that is for the eventual caller to do */
1688                 sdb_free_entry(entry_ex);
1689         } else {
1690                 talloc_steal(kdc_db_ctx, p);
1691         }
1692
1693         return ret;
1694
1695 }
1696
1697 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
1698                                         TALLOC_CTX *mem_ctx,
1699                                         const char *realm,
1700                                         struct ldb_dn *realm_dn,
1701                                         struct ldb_message **pmsg)
1702 {
1703         NTSTATUS status;
1704         const char * const *attrs = trust_attrs;
1705
1706         status = dsdb_trust_search_tdo(ldb_ctx, realm, realm,
1707                                        attrs, mem_ctx, pmsg);
1708         if (NT_STATUS_IS_OK(status)) {
1709                 return 0;
1710         } else if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1711                 return SDB_ERR_NOENTRY;
1712         } else if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1713                 int ret = ENOMEM;
1714                 krb5_set_error_message(context, ret, "get_sam_result_trust: out of memory");
1715                 return ret;
1716         } else {
1717                 int ret = EINVAL;
1718                 krb5_set_error_message(context, ret, "get_sam_result_trust: %s", nt_errstr(status));
1719                 return ret;
1720         }
1721 }
1722
1723 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
1724                                                 struct samba_kdc_db_context *kdc_db_ctx,
1725                                                 TALLOC_CTX *mem_ctx,
1726                                                 krb5_const_principal principal,
1727                                                 const char **attrs,
1728                                                 struct ldb_dn **realm_dn,
1729                                                 struct ldb_message **msg)
1730 {
1731         NTSTATUS nt_status;
1732         char *principal_string = NULL;
1733
1734         if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1735                 principal_string = smb_krb5_principal_get_comp_string(mem_ctx, context,
1736                                                                       principal, 0);
1737                 if (principal_string == NULL) {
1738                         return ENOMEM;
1739                 }
1740         } else {
1741                 char *principal_string_m = NULL;
1742                 krb5_error_code ret;
1743
1744                 ret = krb5_unparse_name(context, principal, &principal_string_m);
1745                 if (ret != 0) {
1746                         return ret;
1747                 }
1748
1749                 principal_string = talloc_strdup(mem_ctx, principal_string_m);
1750                 SAFE_FREE(principal_string_m);
1751                 if (principal_string == NULL) {
1752                         return ENOMEM;
1753                 }
1754         }
1755
1756         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1757                                               mem_ctx, principal_string, attrs,
1758                                               realm_dn, msg);
1759         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1760                 krb5_principal fallback_principal = NULL;
1761                 unsigned int num_comp;
1762                 char *fallback_realm = NULL;
1763                 char *fallback_account = NULL;
1764                 krb5_error_code ret;
1765
1766                 ret = krb5_parse_name(context, principal_string,
1767                                       &fallback_principal);
1768                 TALLOC_FREE(principal_string);
1769                 if (ret != 0) {
1770                         return ret;
1771                 }
1772
1773                 num_comp = krb5_princ_size(context, fallback_principal);
1774                 fallback_realm = smb_krb5_principal_get_realm(
1775                         mem_ctx, context, fallback_principal);
1776                 if (fallback_realm == NULL) {
1777                         krb5_free_principal(context, fallback_principal);
1778                         return ENOMEM;
1779                 }
1780
1781                 if (num_comp == 1) {
1782                         size_t len;
1783
1784                         fallback_account = smb_krb5_principal_get_comp_string(mem_ctx,
1785                                                 context, fallback_principal, 0);
1786                         if (fallback_account == NULL) {
1787                                 krb5_free_principal(context, fallback_principal);
1788                                 TALLOC_FREE(fallback_realm);
1789                                 return ENOMEM;
1790                         }
1791
1792                         len = strlen(fallback_account);
1793                         if (len >= 2 && fallback_account[len - 1] == '$') {
1794                                 TALLOC_FREE(fallback_account);
1795                         }
1796                 }
1797                 krb5_free_principal(context, fallback_principal);
1798                 fallback_principal = NULL;
1799
1800                 if (fallback_account != NULL) {
1801                         char *with_dollar;
1802
1803                         with_dollar = talloc_asprintf(mem_ctx, "%s$",
1804                                                      fallback_account);
1805                         if (with_dollar == NULL) {
1806                                 TALLOC_FREE(fallback_realm);
1807                                 return ENOMEM;
1808                         }
1809                         TALLOC_FREE(fallback_account);
1810
1811                         ret = smb_krb5_make_principal(context,
1812                                                       &fallback_principal,
1813                                                       fallback_realm,
1814                                                       with_dollar, NULL);
1815                         TALLOC_FREE(with_dollar);
1816                         if (ret != 0) {
1817                                 TALLOC_FREE(fallback_realm);
1818                                 return ret;
1819                         }
1820                 }
1821                 TALLOC_FREE(fallback_realm);
1822
1823                 if (fallback_principal != NULL) {
1824                         char *fallback_string = NULL;
1825
1826                         ret = krb5_unparse_name(context,
1827                                                 fallback_principal,
1828                                                 &fallback_string);
1829                         if (ret != 0) {
1830                                 krb5_free_principal(context, fallback_principal);
1831                                 return ret;
1832                         }
1833
1834                         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1835                                                               mem_ctx,
1836                                                               fallback_string,
1837                                                               attrs,
1838                                                               realm_dn, msg);
1839                         SAFE_FREE(fallback_string);
1840                 }
1841                 krb5_free_principal(context, fallback_principal);
1842                 fallback_principal = NULL;
1843         }
1844         TALLOC_FREE(principal_string);
1845
1846         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1847                 return SDB_ERR_NOENTRY;
1848         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1849                 return ENOMEM;
1850         } else if (!NT_STATUS_IS_OK(nt_status)) {
1851                 return EINVAL;
1852         }
1853
1854         return 0;
1855 }
1856
1857 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1858                                                struct samba_kdc_db_context *kdc_db_ctx,
1859                                                TALLOC_CTX *mem_ctx,
1860                                                krb5_const_principal principal,
1861                                                unsigned flags,
1862                                                struct sdb_entry_ex *entry_ex) {
1863         struct ldb_dn *realm_dn;
1864         krb5_error_code ret;
1865         struct ldb_message *msg = NULL;
1866
1867         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1868                                       mem_ctx, principal, user_attrs,
1869                                       &realm_dn, &msg);
1870         if (ret != 0) {
1871                 return ret;
1872         }
1873
1874         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1875                                       principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1876                                       flags,
1877                                       realm_dn, msg, entry_ex);
1878         return ret;
1879 }
1880
1881 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1882                                               struct samba_kdc_db_context *kdc_db_ctx,
1883                                               TALLOC_CTX *mem_ctx,
1884                                               krb5_const_principal principal,
1885                                               unsigned flags,
1886                                               uint32_t kvno,
1887                                               struct sdb_entry_ex *entry_ex)
1888 {
1889         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1890         krb5_error_code ret;
1891         struct ldb_message *msg = NULL;
1892         struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1893         char *realm_from_princ;
1894         char *realm_princ_comp = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 1);
1895
1896         realm_from_princ = smb_krb5_principal_get_realm(
1897                 mem_ctx, context, principal);
1898         if (realm_from_princ == NULL) {
1899                 /* can't happen */
1900                 return SDB_ERR_NOENTRY;
1901         }
1902
1903         if (krb5_princ_size(context, principal) != 2
1904             || (principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME) != 0)) {
1905                 /* Not a krbtgt */
1906                 return SDB_ERR_NOENTRY;
1907         }
1908
1909         /* krbtgt case.  Either us or a trusted realm */
1910
1911         if (lpcfg_is_my_domain_or_realm(lp_ctx, realm_from_princ)
1912             && lpcfg_is_my_domain_or_realm(lp_ctx, realm_princ_comp)) {
1913                 /* us, or someone quite like us */
1914                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1915                  * is in our db, then direct the caller at our primary
1916                  * krbtgt */
1917
1918                 int lret;
1919                 unsigned int krbtgt_number;
1920                 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
1921                    trust tickets. We don't yet know what this means, but we do
1922                    seem to need to treat it as unspecified */
1923                 if (flags & SDB_F_KVNO_SPECIFIED) {
1924                         krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
1925                         if (kdc_db_ctx->rodc) {
1926                                 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
1927                                         return SDB_ERR_NOT_FOUND_HERE;
1928                                 }
1929                         }
1930                 } else {
1931                         krbtgt_number = kdc_db_ctx->my_krbtgt_number;
1932                 }
1933
1934                 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
1935                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1936                                                &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1937                                                krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG,
1938                                                "(objectClass=user)");
1939                 } else {
1940                         /* We need to look up an RODC krbtgt (perhaps
1941                          * ours, if we are an RODC, perhaps another
1942                          * RODC if we are a read-write DC */
1943                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1944                                                &msg, realm_dn, LDB_SCOPE_SUBTREE,
1945                                                krbtgt_attrs,
1946                                                DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1947                                                "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
1948                 }
1949
1950                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1951                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1952                                    (unsigned)(krbtgt_number));
1953                         krb5_set_error_message(context, SDB_ERR_NOENTRY,
1954                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1955                                                (unsigned)(krbtgt_number));
1956                         return SDB_ERR_NOENTRY;
1957                 } else if (lret != LDB_SUCCESS) {
1958                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1959                                    (unsigned)(krbtgt_number));
1960                         krb5_set_error_message(context, SDB_ERR_NOENTRY,
1961                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1962                                                (unsigned)(krbtgt_number));
1963                         return SDB_ERR_NOENTRY;
1964                 }
1965
1966                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1967                                               principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
1968                                               flags, realm_dn, msg, entry_ex);
1969                 if (ret != 0) {
1970                         krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
1971                 }
1972                 return ret;
1973
1974         } else {
1975                 enum trust_direction direction = UNKNOWN;
1976                 const char *realm = NULL;
1977
1978                 /* Either an inbound or outbound trust */
1979
1980                 if (strcasecmp(lpcfg_realm(lp_ctx), realm_from_princ) == 0) {
1981                         /* look for inbound trust */
1982                         direction = INBOUND;
1983                         realm = realm_princ_comp;
1984                 } else if (principal_comp_strcasecmp(context, principal, 1, lpcfg_realm(lp_ctx)) == 0) {
1985                         /* look for outbound trust */
1986                         direction = OUTBOUND;
1987                         realm = realm_from_princ;
1988                 } else {
1989                         krb5_warnx(context, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1990                                    realm_from_princ,
1991                                    realm_princ_comp);
1992                         krb5_set_error_message(context, SDB_ERR_NOENTRY, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1993                                                realm_from_princ,
1994                                                realm_princ_comp);
1995                         return SDB_ERR_NOENTRY;
1996                 }
1997
1998                 /* Trusted domains are under CN=system */
1999
2000                 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
2001                                        mem_ctx,
2002                                        realm, realm_dn, &msg);
2003
2004                 if (ret != 0) {
2005                         krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
2006                         krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
2007                         return ret;
2008                 }
2009
2010                 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
2011                                                     principal, direction,
2012                                                     realm_dn, flags, kvno, msg, entry_ex);
2013                 if (ret != 0) {
2014                         krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed for %s",
2015                                    ldb_dn_get_linearized(msg->dn));
2016                         krb5_set_error_message(context, ret, "samba_kdc_fetch: "
2017                                                "trust_message2entry failed for %s",
2018                                                ldb_dn_get_linearized(msg->dn));
2019                 }
2020                 return ret;
2021         }
2022
2023 }
2024
2025 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
2026                                                struct samba_kdc_db_context *kdc_db_ctx,
2027                                                TALLOC_CTX *mem_ctx,
2028                                                krb5_const_principal principal,
2029                                                unsigned flags,
2030                                                const char **attrs,
2031                                                struct ldb_dn **realm_dn,
2032                                                struct ldb_message **msg)
2033 {
2034         krb5_error_code ret;
2035         if ((smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL)
2036             && krb5_princ_size(context, principal) >= 2) {
2037                 /* 'normal server' case */
2038                 int ldb_ret;
2039                 NTSTATUS nt_status;
2040                 struct ldb_dn *user_dn;
2041                 char *principal_string;
2042
2043                 ret = krb5_unparse_name_flags(context, principal,
2044                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM,
2045                                               &principal_string);
2046                 if (ret != 0) {
2047                         return ret;
2048                 }
2049
2050                 /* At this point we may find the host is known to be
2051                  * in a different realm, so we should generate a
2052                  * referral instead */
2053                 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
2054                                                          mem_ctx, principal_string,
2055                                                          &user_dn, realm_dn);
2056                 free(principal_string);
2057
2058                 if (!NT_STATUS_IS_OK(nt_status)) {
2059                         return SDB_ERR_NOENTRY;
2060                 }
2061
2062                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
2063                                           mem_ctx,
2064                                           msg, user_dn, LDB_SCOPE_BASE,
2065                                           attrs,
2066                                           DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2067                                           "(objectClass=*)");
2068                 if (ldb_ret != LDB_SUCCESS) {
2069                         return SDB_ERR_NOENTRY;
2070                 }
2071                 return 0;
2072         } else if (!(flags & SDB_F_FOR_AS_REQ)
2073                    && smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2074                 /*
2075                  * The behaviour of accepting an
2076                  * KRB5_NT_ENTERPRISE_PRINCIPAL server principal
2077                  * containing a UPN only applies to TGS-REQ packets,
2078                  * not AS-REQ packets.
2079                  */
2080                 return samba_kdc_lookup_client(context, kdc_db_ctx,
2081                                                mem_ctx, principal, attrs,
2082                                                realm_dn, msg);
2083         } else {
2084                 /*
2085                  * This case is for:
2086                  *  - the AS-REQ, where we only accept
2087                  *    samAccountName based lookups for the server, no
2088                  *    matter if the name is an
2089                  *    KRB5_NT_ENTERPRISE_PRINCIPAL or not
2090                  *  - for the TGS-REQ when we are not given an
2091                  *    KRB5_NT_ENTERPRISE_PRINCIPAL, which also must
2092                  *    only lookup samAccountName based names.
2093                  */
2094                 int lret;
2095                 char *short_princ;
2096                 krb5_principal enterprise_principal = NULL;
2097                 krb5_const_principal used_principal = NULL;
2098                 char *name1 = NULL;
2099                 size_t len1 = 0;
2100                 char *filter = NULL;
2101
2102                 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2103                         char *str = NULL;
2104                         /* Need to reparse the enterprise principal to find the real target */
2105                         if (krb5_princ_size(context, principal) != 1) {
2106                                 ret = KRB5_PARSE_MALFORMED;
2107                                 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: request for an "
2108                                                        "enterprise principal with wrong (%d) number of components",
2109                                                        krb5_princ_size(context, principal));
2110                                 return ret;
2111                         }
2112                         str = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 0);
2113                         if (str == NULL) {
2114                                 return KRB5_PARSE_MALFORMED;
2115                         }
2116                         ret = krb5_parse_name(context, str,
2117                                               &enterprise_principal);
2118                         talloc_free(str);
2119                         if (ret) {
2120                                 return ret;
2121                         }
2122                         used_principal = enterprise_principal;
2123                 } else {
2124                         used_principal = principal;
2125                 }
2126
2127                 /* server as client principal case, but we must not lookup userPrincipalNames */
2128                 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
2129
2130                 /* TODO: Check if it is our realm, otherwise give referral */
2131
2132                 ret = krb5_unparse_name_flags(context, used_principal,
2133                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM |
2134                                               KRB5_PRINCIPAL_UNPARSE_DISPLAY,
2135                                               &short_princ);
2136                 used_principal = NULL;
2137                 krb5_free_principal(context, enterprise_principal);
2138                 enterprise_principal = NULL;
2139
2140                 if (ret != 0) {
2141                         krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
2142                         krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
2143                         return ret;
2144                 }
2145
2146                 name1 = ldb_binary_encode_string(mem_ctx, short_princ);
2147                 SAFE_FREE(short_princ);
2148                 if (name1 == NULL) {
2149                         return ENOMEM;
2150                 }
2151                 len1 = strlen(name1);
2152                 if (len1 >= 1 && name1[len1 - 1] != '$') {
2153                         filter = talloc_asprintf(mem_ctx,
2154                                         "(&(objectClass=user)(|(samAccountName=%s)(samAccountName=%s$)))",
2155                                         name1, name1);
2156                         if (filter == NULL) {
2157                                 return ENOMEM;
2158                         }
2159                 } else {
2160                         filter = talloc_asprintf(mem_ctx,
2161                                         "(&(objectClass=user)(samAccountName=%s))",
2162                                         name1);
2163                         if (filter == NULL) {
2164                                 return ENOMEM;
2165                         }
2166                 }
2167
2168                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
2169                                        *realm_dn, LDB_SCOPE_SUBTREE,
2170                                        attrs,
2171                                        DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2172                                        "%s", filter);
2173                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
2174                         DEBUG(10, ("Failed to find an entry for %s filter:%s\n",
2175                                   name1, filter));
2176                         return SDB_ERR_NOENTRY;
2177                 }
2178                 if (lret == LDB_ERR_CONSTRAINT_VIOLATION) {
2179                         DEBUG(10, ("Failed to find unique entry for %s filter:%s\n",
2180                                   name1, filter));
2181                         return SDB_ERR_NOENTRY;
2182                 }
2183                 if (lret != LDB_SUCCESS) {
2184                         DEBUG(0, ("Failed single search for %s - %s\n",
2185                                   name1, ldb_errstring(kdc_db_ctx->samdb)));
2186                         return SDB_ERR_NOENTRY;
2187                 }
2188                 return 0;
2189         }
2190         return SDB_ERR_NOENTRY;
2191 }
2192
2193
2194
2195 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
2196                                               struct samba_kdc_db_context *kdc_db_ctx,
2197                                               TALLOC_CTX *mem_ctx,
2198                                               krb5_const_principal principal,
2199                                               unsigned flags,
2200                                               struct sdb_entry_ex *entry_ex)
2201 {
2202         krb5_error_code ret;
2203         struct ldb_dn *realm_dn;
2204         struct ldb_message *msg;
2205
2206         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
2207                                       flags, server_attrs, &realm_dn, &msg);
2208         if (ret != 0) {
2209                 return ret;
2210         }
2211
2212         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2213                                       principal, SAMBA_KDC_ENT_TYPE_SERVER,
2214                                       flags,
2215                                       realm_dn, msg, entry_ex);
2216         if (ret != 0) {
2217                 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
2218         }
2219
2220         return ret;
2221 }
2222
2223 static krb5_error_code samba_kdc_lookup_realm(krb5_context context,
2224                                               struct samba_kdc_db_context *kdc_db_ctx,
2225                                               TALLOC_CTX *mem_ctx,
2226                                               krb5_const_principal principal,
2227                                               unsigned flags,
2228                                               struct sdb_entry_ex *entry_ex)
2229 {
2230         TALLOC_CTX *frame = talloc_stackframe();
2231         NTSTATUS status;
2232         krb5_error_code ret;
2233         bool check_realm = false;
2234         const char *realm = NULL;
2235         struct dsdb_trust_routing_table *trt = NULL;
2236         const struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
2237         unsigned int num_comp;
2238         bool ok;
2239         char *upper = NULL;
2240
2241         num_comp = krb5_princ_size(context, principal);
2242
2243         if (flags & SDB_F_GET_CLIENT) {
2244                 if (flags & SDB_F_FOR_AS_REQ) {
2245                         check_realm = true;
2246                 }
2247         }
2248         if (flags & SDB_F_GET_SERVER) {
2249                 if (flags & SDB_F_FOR_TGS_REQ) {
2250                         check_realm = true;
2251                 }
2252         }
2253
2254         if (!check_realm) {
2255                 TALLOC_FREE(frame);
2256                 return 0;
2257         }
2258
2259         realm = smb_krb5_principal_get_realm(frame, context, principal);
2260         if (realm == NULL) {
2261                 TALLOC_FREE(frame);
2262                 return ENOMEM;
2263         }
2264
2265         /*
2266          * The requested realm needs to be our own
2267          */
2268         ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2269         if (!ok) {
2270                 /*
2271                  * The request is not for us...
2272                  */
2273                 TALLOC_FREE(frame);
2274                 return SDB_ERR_NOENTRY;
2275         }
2276
2277         if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2278                 char *principal_string = NULL;
2279                 krb5_principal enterprise_principal = NULL;
2280                 char *enterprise_realm = NULL;
2281
2282                 if (num_comp != 1) {
2283                         TALLOC_FREE(frame);
2284                         return SDB_ERR_NOENTRY;
2285                 }
2286
2287                 principal_string = smb_krb5_principal_get_comp_string(frame, context,
2288                                                                       principal, 0);
2289                 if (principal_string == NULL) {
2290                         TALLOC_FREE(frame);
2291                         return ENOMEM;
2292                 }
2293
2294                 ret = krb5_parse_name(context, principal_string,
2295                                       &enterprise_principal);
2296                 TALLOC_FREE(principal_string);
2297                 if (ret) {
2298                         TALLOC_FREE(frame);
2299                         return ret;
2300                 }
2301
2302                 enterprise_realm = smb_krb5_principal_get_realm(
2303                         frame, context, enterprise_principal);
2304                 krb5_free_principal(context, enterprise_principal);
2305                 if (enterprise_realm != NULL) {
2306                         realm = enterprise_realm;
2307                 }
2308         }
2309
2310         if (flags & SDB_F_GET_SERVER) {
2311                 char *service_realm = NULL;
2312
2313                 ret = principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME);
2314                 if (ret == 0) {
2315                         /*
2316                          * we need to search krbtgt/ locally
2317                          */
2318                         TALLOC_FREE(frame);
2319                         return 0;
2320                 }
2321
2322                 /*
2323                  * We need to check the last component against the routing table.
2324                  *
2325                  * Note this works only with 2 or 3 component principals, e.g:
2326                  *
2327                  * servicePrincipalName: ldap/W2K8R2-219.bla.base
2328                  * servicePrincipalName: ldap/W2K8R2-219.bla.base/bla.base
2329                  * servicePrincipalName: ldap/W2K8R2-219.bla.base/ForestDnsZones.bla.base
2330                  * servicePrincipalName: ldap/W2K8R2-219.bla.base/DomainDnsZones.bla.base
2331                  */
2332
2333                 if (num_comp == 2 || num_comp == 3) {
2334                         service_realm = smb_krb5_principal_get_comp_string(frame,
2335                                                                            context,
2336                                                                            principal,
2337                                                                            num_comp - 1);
2338                 }
2339
2340                 if (service_realm != NULL) {
2341                         realm = service_realm;
2342                 }
2343         }
2344
2345         ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2346         if (ok) {
2347                 /*
2348                  * skip the expensive routing lookup
2349                  */
2350                 TALLOC_FREE(frame);
2351                 return 0;
2352         }
2353
2354         status = dsdb_trust_routing_table_load(kdc_db_ctx->samdb,
2355                                                frame, &trt);
2356         if (!NT_STATUS_IS_OK(status)) {
2357                 TALLOC_FREE(frame);
2358                 return EINVAL;
2359         }
2360
2361         tdo = dsdb_trust_routing_by_name(trt, realm);
2362         if (tdo == NULL) {
2363                 /*
2364                  * This principal has to be local
2365                  */
2366                 TALLOC_FREE(frame);
2367                 return 0;
2368         }
2369
2370         if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
2371                 /*
2372                  * TODO: handle the routing within the forest
2373                  *
2374                  * This should likely be handled in
2375                  * samba_kdc_message2entry() in case we're
2376                  * a global catalog. We'd need to check
2377                  * if realm_dn is our own domain and derive
2378                  * the dns domain name from realm_dn and check that
2379                  * against the routing table or fallback to
2380                  * the tdo we found here.
2381                  *
2382                  * But for now we don't support multiple domains
2383                  * in our forest correctly anyway.
2384                  *
2385                  * Just search in our local database.
2386                  */
2387                 TALLOC_FREE(frame);
2388                 return 0;
2389         }
2390
2391         ZERO_STRUCT(entry_ex->entry);
2392
2393         ret = krb5_copy_principal(context, principal,
2394                                   &entry_ex->entry.principal);
2395         if (ret) {
2396                 TALLOC_FREE(frame);
2397                 return ret;
2398         }
2399
2400         upper = strupper_talloc(frame, tdo->domain_name.string);
2401         if (upper == NULL) {
2402                 TALLOC_FREE(frame);
2403                 return ENOMEM;
2404         }
2405
2406         ret = smb_krb5_principal_set_realm(context,
2407                                            entry_ex->entry.principal,
2408                                            upper);
2409         if (ret) {
2410                 TALLOC_FREE(frame);
2411                 return ret;
2412         }
2413
2414         TALLOC_FREE(frame);
2415         return SDB_ERR_WRONG_REALM;
2416 }
2417
2418 krb5_error_code samba_kdc_fetch(krb5_context context,
2419                                 struct samba_kdc_db_context *kdc_db_ctx,
2420                                 krb5_const_principal principal,
2421                                 unsigned flags,
2422                                 krb5_kvno kvno,
2423                                 struct sdb_entry_ex *entry_ex)
2424 {
2425         krb5_error_code ret = SDB_ERR_NOENTRY;
2426         TALLOC_CTX *mem_ctx;
2427
2428         mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
2429         if (!mem_ctx) {
2430                 ret = ENOMEM;
2431                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2432                 return ret;
2433         }
2434
2435         ret = samba_kdc_lookup_realm(context, kdc_db_ctx, mem_ctx,
2436                                      principal, flags, entry_ex);
2437         if (ret != 0) {
2438                 goto done;
2439         }
2440
2441         ret = SDB_ERR_NOENTRY;
2442
2443         if (flags & SDB_F_GET_CLIENT) {
2444                 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
2445                 if (ret != SDB_ERR_NOENTRY) goto done;
2446         }
2447         if (flags & SDB_F_GET_SERVER) {
2448                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
2449                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
2450                 if (ret != SDB_ERR_NOENTRY) goto done;
2451
2452                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
2453                 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
2454                 if (ret != SDB_ERR_NOENTRY) goto done;
2455         }
2456         if (flags & SDB_F_GET_KRBTGT) {
2457                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
2458                 if (ret != SDB_ERR_NOENTRY) goto done;
2459         }
2460
2461 done:
2462         talloc_free(mem_ctx);
2463         return ret;
2464 }
2465
2466 struct samba_kdc_seq {
2467         unsigned int index;
2468         unsigned int count;
2469         struct ldb_message **msgs;
2470         struct ldb_dn *realm_dn;
2471 };
2472
2473 static krb5_error_code samba_kdc_seq(krb5_context context,
2474                                      struct samba_kdc_db_context *kdc_db_ctx,
2475                                      struct sdb_entry_ex *entry)
2476 {
2477         krb5_error_code ret;
2478         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2479         const char *realm = lpcfg_realm(kdc_db_ctx->lp_ctx);
2480         struct ldb_message *msg = NULL;
2481         const char *sAMAccountName = NULL;
2482         krb5_principal principal = NULL;
2483         TALLOC_CTX *mem_ctx;
2484
2485         if (!priv) {
2486                 return SDB_ERR_NOENTRY;
2487         }
2488
2489         mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
2490
2491         if (!mem_ctx) {
2492                 ret = ENOMEM;
2493                 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
2494                 return ret;
2495         }
2496
2497         while (priv->index < priv->count) {
2498                 msg = priv->msgs[priv->index++];
2499
2500                 sAMAccountName = ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL);
2501                 if (sAMAccountName != NULL) {
2502                         break;
2503                 }
2504         }
2505
2506         if (sAMAccountName == NULL) {
2507                 ret = SDB_ERR_NOENTRY;
2508                 goto out;
2509         }
2510
2511         ret = smb_krb5_make_principal(context, &principal,
2512                                       realm, sAMAccountName, NULL);
2513         if (ret != 0) {
2514                 goto out;
2515         }
2516
2517         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2518                                       principal, SAMBA_KDC_ENT_TYPE_ANY,
2519                                       SDB_F_ADMIN_DATA|SDB_F_GET_ANY,
2520                                       priv->realm_dn, msg, entry);
2521
2522 out:
2523         if (principal != NULL) {
2524                 krb5_free_principal(context, principal);
2525         }
2526
2527         if (ret != 0) {
2528                 TALLOC_FREE(priv);
2529                 kdc_db_ctx->seq_ctx = NULL;
2530         } else {
2531                 talloc_free(mem_ctx);
2532         }
2533
2534         return ret;
2535 }
2536
2537 krb5_error_code samba_kdc_firstkey(krb5_context context,
2538                                    struct samba_kdc_db_context *kdc_db_ctx,
2539                                    struct sdb_entry_ex *entry)
2540 {
2541         struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
2542         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2543         char *realm;
2544         struct ldb_result *res = NULL;
2545         krb5_error_code ret;
2546         TALLOC_CTX *mem_ctx;
2547         int lret;
2548
2549         if (priv) {
2550                 TALLOC_FREE(priv);
2551                 kdc_db_ctx->seq_ctx = NULL;
2552         }
2553
2554         priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
2555         if (!priv) {
2556                 ret = ENOMEM;
2557                 krb5_set_error_message(context, ret, "talloc: out of memory");
2558                 return ret;
2559         }
2560
2561         priv->index = 0;
2562         priv->msgs = NULL;
2563         priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
2564         priv->count = 0;
2565
2566         mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
2567
2568         if (!mem_ctx) {
2569                 ret = ENOMEM;
2570                 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
2571                 return ret;
2572         }
2573
2574         ret = krb5_get_default_realm(context, &realm);
2575         if (ret != 0) {
2576                 TALLOC_FREE(priv);
2577                 return ret;
2578         }
2579         krb5_free_default_realm(context, realm);
2580
2581         lret = dsdb_search(ldb_ctx, priv, &res,
2582                            priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
2583                            DSDB_SEARCH_NO_GLOBAL_CATALOG,
2584                            "(objectClass=user)");
2585
2586         if (lret != LDB_SUCCESS) {
2587                 TALLOC_FREE(priv);
2588                 return SDB_ERR_NOENTRY;
2589         }
2590
2591         priv->count = res->count;
2592         priv->msgs = talloc_steal(priv, res->msgs);
2593         talloc_free(res);
2594
2595         kdc_db_ctx->seq_ctx = priv;
2596
2597         ret = samba_kdc_seq(context, kdc_db_ctx, entry);
2598
2599         if (ret != 0) {
2600                 TALLOC_FREE(priv);
2601                 kdc_db_ctx->seq_ctx = NULL;
2602         } else {
2603                 talloc_free(mem_ctx);
2604         }
2605         return ret;
2606 }
2607
2608 krb5_error_code samba_kdc_nextkey(krb5_context context,
2609                                   struct samba_kdc_db_context *kdc_db_ctx,
2610                                   struct sdb_entry_ex *entry)
2611 {
2612         return samba_kdc_seq(context, kdc_db_ctx, entry);
2613 }
2614
2615 /* Check if a given entry may delegate or do s4u2self to this target principal
2616  *
2617  * The safest way to determine 'self' is to check the DB record made at
2618  * the time the principal was presented to the KDC.
2619  */
2620 krb5_error_code
2621 samba_kdc_check_client_matches_target_service(krb5_context context,
2622                                               struct samba_kdc_entry *skdc_entry_client,
2623                                               struct samba_kdc_entry *skdc_entry_server_target)
2624 {
2625         struct dom_sid *orig_sid;
2626         struct dom_sid *target_sid;
2627         TALLOC_CTX *frame = talloc_stackframe();
2628
2629         orig_sid = samdb_result_dom_sid(frame,
2630                                         skdc_entry_client->msg,
2631                                         "objectSid");
2632         target_sid = samdb_result_dom_sid(frame,
2633                                           skdc_entry_server_target->msg,
2634                                           "objectSid");
2635
2636         /*
2637          * Allow delegation to the same record (representing a
2638          * principal), even if by a different name.  The easy and safe
2639          * way to prove this is by SID comparison
2640          */
2641         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
2642                 talloc_free(frame);
2643                 return KRB5KRB_AP_ERR_BADMATCH;
2644         }
2645
2646         talloc_free(frame);
2647         return 0;
2648 }
2649
2650 /* Certificates printed by a the Certificate Authority might have a
2651  * slightly different form of the user principal name to that in the
2652  * database.  Allow a mismatch where they both refer to the same
2653  * SID */
2654
2655 krb5_error_code
2656 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
2657                                     struct samba_kdc_db_context *kdc_db_ctx,
2658                                     struct samba_kdc_entry *skdc_entry,
2659                                      krb5_const_principal certificate_principal)
2660 {
2661         krb5_error_code ret;
2662         struct ldb_dn *realm_dn;
2663         struct ldb_message *msg;
2664         struct dom_sid *orig_sid;
2665         struct dom_sid *target_sid;
2666         const char *ms_upn_check_attrs[] = {
2667                 "objectSid", NULL
2668         };
2669
2670         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
2671
2672         if (!mem_ctx) {
2673                 ret = ENOMEM;
2674                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2675                 return ret;
2676         }
2677
2678         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
2679                                       mem_ctx, certificate_principal,
2680                                       ms_upn_check_attrs, &realm_dn, &msg);
2681
2682         if (ret != 0) {
2683                 talloc_free(mem_ctx);
2684                 return ret;
2685         }
2686
2687         orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
2688         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
2689
2690         /* Consider these to be the same principal, even if by a different
2691          * name.  The easy and safe way to prove this is by SID
2692          * comparison */
2693         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
2694                 talloc_free(mem_ctx);
2695 #if defined(KRB5KDC_ERR_CLIENT_NAME_MISMATCH) /* MIT */
2696                 return KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
2697 #else /* Heimdal (where this is an enum) */
2698                 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
2699 #endif
2700         }
2701
2702         talloc_free(mem_ctx);
2703         return ret;
2704 }
2705
2706 /*
2707  * Check if a given entry may delegate to this target principal
2708  * with S4U2Proxy.
2709  */
2710 krb5_error_code
2711 samba_kdc_check_s4u2proxy(krb5_context context,
2712                           struct samba_kdc_db_context *kdc_db_ctx,
2713                           struct samba_kdc_entry *skdc_entry,
2714                           krb5_const_principal target_principal)
2715 {
2716         krb5_error_code ret;
2717         char *tmp = NULL;
2718         const char *client_dn = NULL;
2719         const char *target_principal_name = NULL;
2720         struct ldb_message_element *el;
2721         struct ldb_val val;
2722         unsigned int i;
2723         bool found = false;
2724
2725         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
2726
2727         if (!mem_ctx) {
2728                 ret = ENOMEM;
2729                 krb5_set_error_message(context, ret,
2730                                        "samba_kdc_check_s4u2proxy:"
2731                                        " talloc_named() failed!");
2732                 return ret;
2733         }
2734
2735         client_dn = ldb_dn_get_linearized(skdc_entry->msg->dn);
2736         if (!client_dn) {
2737                 if (errno == 0) {
2738                         errno = ENOMEM;
2739                 }
2740                 ret = errno;
2741                 krb5_set_error_message(context, ret,
2742                                        "samba_kdc_check_s4u2proxy:"
2743                                        " ldb_dn_get_linearized() failed!");
2744                 return ret;
2745         }
2746
2747         el = ldb_msg_find_element(skdc_entry->msg, "msDS-AllowedToDelegateTo");
2748         if (el == NULL) {
2749                 ret = ENOENT;
2750                 goto bad_option;
2751         }
2752         SMB_ASSERT(el->num_values != 0);
2753
2754         /*
2755          * This is the Microsoft forwardable flag behavior.
2756          *
2757          * If the proxy (target) principal is NULL, and we have any authorized
2758          * delegation target, allow to forward.
2759          */
2760         if (target_principal == NULL) {
2761                 return 0;
2762         }
2763
2764
2765         /*
2766          * The main heimdal code already checked that the target_principal
2767          * belongs to the same realm as the client.
2768          *
2769          * So we just need the principal without the realm,
2770          * as that is what is configured in the "msDS-AllowedToDelegateTo"
2771          * attribute.
2772          */
2773         ret = krb5_unparse_name_flags(context, target_principal,
2774                                       KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
2775         if (ret) {
2776                 talloc_free(mem_ctx);
2777                 krb5_set_error_message(context, ret,
2778                                        "samba_kdc_check_s4u2proxy:"
2779                                        " krb5_unparse_name() failed!");
2780                 return ret;
2781         }
2782         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] for target[%s]\n",
2783                  client_dn, tmp));
2784
2785         target_principal_name = talloc_strdup(mem_ctx, tmp);
2786         SAFE_FREE(tmp);
2787         if (target_principal_name == NULL) {
2788                 ret = ENOMEM;
2789                 krb5_set_error_message(context, ret,
2790                                        "samba_kdc_check_s4u2proxy:"
2791                                        " talloc_strdup() failed!");
2792                 return ret;
2793         }
2794
2795         val = data_blob_string_const(target_principal_name);
2796
2797         for (i=0; i<el->num_values; i++) {
2798                 struct ldb_val *val1 = &val;
2799                 struct ldb_val *val2 = &el->values[i];
2800                 int cmp;
2801
2802                 if (val1->length != val2->length) {
2803                         continue;
2804                 }
2805
2806                 cmp = strncasecmp((const char *)val1->data,
2807                                   (const char *)val2->data,
2808                                   val1->length);
2809                 if (cmp != 0) {
2810                         continue;
2811                 }
2812
2813                 found = true;
2814                 break;
2815         }
2816
2817         if (!found) {
2818                 ret = ENOENT;
2819                 goto bad_option;
2820         }
2821
2822         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] allowed target[%s]\n",
2823                  client_dn, tmp));
2824         talloc_free(mem_ctx);
2825         return 0;
2826
2827 bad_option:
2828         krb5_set_error_message(context, ret,
2829                                "samba_kdc_check_s4u2proxy: client[%s] "
2830                                "not allowed for delegation to target[%s]",
2831                                client_dn,
2832                                target_principal_name);
2833         talloc_free(mem_ctx);
2834         return KRB5KDC_ERR_BADOPTION;
2835 }
2836
2837 /*
2838  * This method is called for S4U2Proxy requests and implements the
2839  * resource-based constrained delegation variant, which can support
2840  * cross-realm delegation.
2841  */
2842 krb5_error_code samba_kdc_check_s4u2proxy_rbcd(
2843                 krb5_context context,
2844                 struct samba_kdc_db_context *kdc_db_ctx,
2845                 krb5_const_principal client_principal,
2846                 krb5_const_principal server_principal,
2847                 krb5_pac header_pac,
2848                 struct samba_kdc_entry *proxy_skdc_entry)
2849 {
2850         krb5_error_code code;
2851         enum ndr_err_code ndr_err;
2852         char *client_name = NULL;
2853         char *server_name = NULL;
2854         const char *proxy_dn = NULL;
2855         const DATA_BLOB *data = NULL;
2856         struct security_descriptor *rbcd_security_descriptor = NULL;
2857         struct auth_user_info_dc *user_info_dc = NULL;
2858         struct auth_session_info *session_info = NULL;
2859         uint32_t session_info_flags = AUTH_SESSION_INFO_SIMPLE_PRIVILEGES;
2860         uint32_t access_desired = SEC_ADS_GENERIC_ALL; /* => 0x000f01ff */
2861         uint32_t access_granted = 0;
2862         NTSTATUS nt_status;
2863         TALLOC_CTX *mem_ctx = NULL;
2864
2865         mem_ctx = talloc_named(kdc_db_ctx,
2866                                0,
2867                                "samba_kdc_check_s4u2proxy_rbcd");
2868         if (mem_ctx == NULL) {
2869                 errno = ENOMEM;
2870                 code = errno;
2871
2872                 return code;
2873         }
2874
2875         proxy_dn = ldb_dn_get_linearized(proxy_skdc_entry->msg->dn);
2876         if (proxy_dn == NULL) {
2877                 DBG_ERR("ldb_dn_get_linearized failed for proxy_dn!\n");
2878                 TALLOC_FREE(mem_ctx);
2879                 if (errno == 0) {
2880                         errno = ENOMEM;
2881                 }
2882                 code = errno;
2883
2884                 goto out;
2885         }
2886
2887         rbcd_security_descriptor = talloc_zero(mem_ctx,
2888                                                struct security_descriptor);
2889         if (rbcd_security_descriptor == NULL) {
2890                 errno = ENOMEM;
2891                 code = errno;
2892
2893                 goto out;
2894         }
2895
2896         code = krb5_unparse_name_flags(context,
2897                                        client_principal,
2898                                        KRB5_PRINCIPAL_UNPARSE_DISPLAY,
2899                                        &client_name);
2900         if (code != 0) {
2901                 DBG_ERR("Unable to parse client_principal!\n");
2902                 goto out;
2903         }
2904
2905         code = krb5_unparse_name_flags(context,
2906                                        server_principal,
2907                                        KRB5_PRINCIPAL_UNPARSE_DISPLAY,
2908                                        &server_name);
2909         if (code != 0) {
2910                 DBG_ERR("Unable to parse server_principal!\n");
2911                 SAFE_FREE(client_name);
2912                 goto out;
2913         }
2914
2915         DBG_INFO("Check delegation from client[%s] to server[%s] via "
2916                  "proxy[%s]\n",
2917                  client_name,
2918                  server_name,
2919                  proxy_dn);
2920
2921         code = kerberos_pac_to_user_info_dc(mem_ctx,
2922                                             header_pac,
2923                                             context,
2924                                             &user_info_dc,
2925                                             NULL,
2926                                             NULL);
2927         if (code != 0) {
2928                 goto out;
2929         }
2930
2931         if (user_info_dc->info->authenticated) {
2932                 session_info_flags |= AUTH_SESSION_INFO_AUTHENTICATED;
2933         }
2934
2935         nt_status = auth_generate_session_info(mem_ctx,
2936                                                kdc_db_ctx->lp_ctx,
2937                                                kdc_db_ctx->samdb,
2938                                                user_info_dc,
2939                                                session_info_flags,
2940                                                &session_info);
2941         if (!NT_STATUS_IS_OK(nt_status)) {
2942                 code = map_errno_from_nt_status(nt_status);
2943                 goto out;
2944         }
2945
2946         data = ldb_msg_find_ldb_val(proxy_skdc_entry->msg,
2947                                     "msDS-AllowedToActOnBehalfOfOtherIdentity");
2948         if (data == NULL) {
2949                 DBG_ERR("Could not find security descriptor"
2950                         "msDS-AllowedToActOnBehalfOfOtherIdentity in "
2951                         "proxy[%s]\n",
2952                         proxy_dn);
2953                 code = KRB5KDC_ERR_BADOPTION;
2954                 goto out;
2955         }
2956
2957         ndr_err = ndr_pull_struct_blob(
2958                         data,
2959                         mem_ctx,
2960                         rbcd_security_descriptor,
2961                         (ndr_pull_flags_fn_t)ndr_pull_security_descriptor);
2962         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2963                 errno = ndr_map_error2errno(ndr_err);
2964                 DBG_ERR("Failed to unmarshall "
2965                         "msDS-AllowedToActOnBehalfOfOtherIdentity "
2966                         "security descriptor of proxy[%s]\n",
2967                         proxy_dn);
2968                 code = KRB5KDC_ERR_BADOPTION;
2969                 goto out;
2970         }
2971
2972         if (DEBUGLEVEL >= 10) {
2973                 NDR_PRINT_DEBUG(security_token, session_info->security_token);
2974                 NDR_PRINT_DEBUG(security_descriptor, rbcd_security_descriptor);
2975         }
2976
2977         nt_status = sec_access_check_ds(rbcd_security_descriptor,
2978                                         session_info->security_token,
2979                                         access_desired,
2980                                         &access_granted,
2981                                         NULL,
2982                                         NULL);
2983
2984         if (!NT_STATUS_IS_OK(nt_status)) {
2985                 DBG_WARNING("RBCD: sec_access_check_ds(access_desired=%#08x, "
2986                             "access_granted:%#08x) failed with: %s\n",
2987                             access_desired,
2988                             access_granted,
2989                             nt_errstr(nt_status));
2990
2991                 code = KRB5KDC_ERR_BADOPTION;
2992                 goto out;
2993         }
2994
2995         DBG_NOTICE("RBCD: Access granted for client[%s]\n", client_name);
2996
2997         code = 0;
2998 out:
2999         SAFE_FREE(client_name);
3000         SAFE_FREE(server_name);
3001
3002         TALLOC_FREE(mem_ctx);
3003         return code;
3004 }
3005
3006 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
3007                                 struct samba_kdc_db_context **kdc_db_ctx_out)
3008 {
3009         int ldb_ret;
3010         struct ldb_message *msg;
3011         struct auth_session_info *session_info;
3012         struct samba_kdc_db_context *kdc_db_ctx;
3013         /* The idea here is very simple.  Using Kerberos to
3014          * authenticate the KDC to the LDAP server is higly likely to
3015          * be circular.
3016          *
3017          * In future we may set this up to use EXERNAL and SSL
3018          * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
3019         */
3020
3021         kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
3022         if (kdc_db_ctx == NULL) {
3023                 return NT_STATUS_NO_MEMORY;
3024         }
3025         kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
3026         kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
3027         kdc_db_ctx->msg_ctx = base_ctx->msg_ctx;
3028
3029         /* get default kdc policy */
3030         lpcfg_default_kdc_policy(mem_ctx,
3031                                  base_ctx->lp_ctx,
3032                                  &kdc_db_ctx->policy.svc_tkt_lifetime,
3033                                  &kdc_db_ctx->policy.usr_tkt_lifetime,
3034                                  &kdc_db_ctx->policy.renewal_lifetime);
3035
3036         session_info = system_session(kdc_db_ctx->lp_ctx);
3037         if (session_info == NULL) {
3038                 return NT_STATUS_INTERNAL_ERROR;
3039         }
3040
3041         /* Setup the link to secrets.ldb */
3042
3043         kdc_db_ctx->secrets_db = secrets_db_connect(kdc_db_ctx,
3044                                                     base_ctx->lp_ctx);
3045         if (kdc_db_ctx->secrets_db == NULL) {
3046                 DEBUG(1, ("samba_kdc_setup_db_ctx: "
3047                           "Cannot open secrets.ldb for KDC backend!"));
3048                 talloc_free(kdc_db_ctx);
3049                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3050         }
3051
3052         kdc_db_ctx->fx_cookie_dn = ldb_dn_new(kdc_db_ctx,
3053                                               kdc_db_ctx->secrets_db,
3054                                               "CN=FX Cookie");
3055
3056         /* Setup the link to LDB */
3057         kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx,
3058                                           base_ctx->ev_ctx,
3059                                           base_ctx->lp_ctx,
3060                                           session_info,
3061                                           NULL,
3062                                           0);
3063         if (kdc_db_ctx->samdb == NULL) {
3064                 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot open samdb for KDC backend!"));
3065                 talloc_free(kdc_db_ctx);
3066                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3067         }
3068
3069         /* Find out our own krbtgt kvno */
3070         ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
3071         if (ldb_ret != LDB_SUCCESS) {
3072                 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine if we are an RODC in KDC backend: %s\n",
3073                           ldb_errstring(kdc_db_ctx->samdb)));
3074                 talloc_free(kdc_db_ctx);
3075                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3076         }
3077         if (kdc_db_ctx->rodc) {
3078                 int my_krbtgt_number;
3079                 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
3080                 struct ldb_dn *account_dn;
3081                 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
3082                 if (!server_dn) {
3083                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server DN in KDC backend: %s\n",
3084                                   ldb_errstring(kdc_db_ctx->samdb)));
3085                         talloc_free(kdc_db_ctx);
3086                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3087                 }
3088
3089                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
3090                                              "serverReference", &account_dn);
3091                 if (ldb_ret != LDB_SUCCESS) {
3092                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server account in KDC backend: %s\n",
3093                                   ldb_errstring(kdc_db_ctx->samdb)));
3094                         talloc_free(kdc_db_ctx);
3095                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3096                 }
3097
3098                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
3099                                              "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
3100                 talloc_free(account_dn);
3101                 if (ldb_ret != LDB_SUCCESS) {
3102                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine RODC krbtgt account in KDC backend: %s\n",
3103                                   ldb_errstring(kdc_db_ctx->samdb)));
3104                         talloc_free(kdc_db_ctx);
3105                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3106                 }
3107
3108                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
3109                                           &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
3110                                           secondary_keytab,
3111                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
3112                                           "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
3113                 if (ldb_ret != LDB_SUCCESS) {
3114                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
3115                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
3116                                   ldb_errstring(kdc_db_ctx->samdb),
3117                                   ldb_strerror(ldb_ret)));
3118                         talloc_free(kdc_db_ctx);
3119                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3120                 }
3121                 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
3122                 if (my_krbtgt_number == -1) {
3123                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
3124                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
3125                                   my_krbtgt_number));
3126                         talloc_free(kdc_db_ctx);
3127                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3128                 }
3129                 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
3130
3131         } else {
3132                 kdc_db_ctx->my_krbtgt_number = 0;
3133                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
3134                                           &msg,
3135                                           ldb_get_default_basedn(kdc_db_ctx->samdb),
3136                                           LDB_SCOPE_SUBTREE,
3137                                           krbtgt_attrs,
3138                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
3139                                           "(&(objectClass=user)(samAccountName=krbtgt))");
3140
3141                 if (ldb_ret != LDB_SUCCESS) {
3142                         DEBUG(1, ("samba_kdc_fetch: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
3143                         talloc_free(kdc_db_ctx);
3144                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3145                 }
3146                 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
3147                 kdc_db_ctx->my_krbtgt_number = 0;
3148                 talloc_free(msg);
3149         }
3150         *kdc_db_ctx_out = kdc_db_ctx;
3151         return NT_STATUS_OK;
3152 }