Move kdc_get_policy helper in the lsa server where it belongs.
[idra/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 "auth/auth.h"
27 #include "auth/auth_sam.h"
28 #include "dsdb/samdb/samdb.h"
29 #include "dsdb/common/util.h"
30 #include "librpc/gen_ndr/ndr_drsblobs.h"
31 #include "param/param.h"
32 #include "../lib/crypto/md4.h"
33 #include "system/kerberos.h"
34 #include "auth/kerberos/kerberos.h"
35 #include <hdb.h>
36 #include "kdc/samba_kdc.h"
37 #include "kdc/kdc-glue.h"
38 #include "kdc/db-glue.h"
39
40 #define SAMBA_KVNO_GET_KRBTGT(kvno) \
41         ((uint16_t)(((uint32_t)kvno) >> 16))
42
43 #define SAMBA_KVNO_AND_KRBTGT(kvno, krbtgt) \
44         ((krb5_kvno)((((uint32_t)kvno) & 0xFFFF) | \
45          ((((uint32_t)krbtgt) << 16) & 0xFFFF0000)))
46
47 enum samba_kdc_ent_type
48 { SAMBA_KDC_ENT_TYPE_CLIENT, SAMBA_KDC_ENT_TYPE_SERVER,
49   SAMBA_KDC_ENT_TYPE_KRBTGT, SAMBA_KDC_ENT_TYPE_TRUST, SAMBA_KDC_ENT_TYPE_ANY };
50
51 enum trust_direction {
52         UNKNOWN = 0,
53         INBOUND = LSA_TRUST_DIRECTION_INBOUND,
54         OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
55 };
56
57 static const char *trust_attrs[] = {
58         "trustPartner",
59         "trustAuthIncoming",
60         "trustAuthOutgoing",
61         "whenCreated",
62         "msDS-SupportedEncryptionTypes",
63         "trustAttributes",
64         "trustDirection",
65         "trustType",
66         NULL
67 };
68
69
70 /* Translate between the IETF encryption type values and the Microsoft
71  * msDS-SupportedEncryptionTypes values */
72 static uint32_t kerberos_enctype_to_bitmap(krb5_enctype enc_type_enum)
73 {
74         switch (enc_type_enum) {
75         case ENCTYPE_DES_CBC_CRC:
76                 return ENC_CRC32;
77         case ENCTYPE_DES_CBC_MD5:
78                 return ENC_RSA_MD5;
79         case ENCTYPE_ARCFOUR_HMAC_MD5:
80                 return ENC_RC4_HMAC_MD5;
81         case ENCTYPE_AES128_CTS_HMAC_SHA1_96:
82                 return ENC_HMAC_SHA1_96_AES128;
83         case ENCTYPE_AES256_CTS_HMAC_SHA1_96:
84                 return ENC_HMAC_SHA1_96_AES256;
85         default:
86                 return 0;
87         }
88 }
89
90 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
91 {
92     const char *tmp;
93     const char *gentime;
94     struct tm tm;
95
96     gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
97     if (!gentime)
98         return default_val;
99
100     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
101     if (tmp == NULL) {
102             return default_val;
103     }
104
105     return timegm(&tm);
106 }
107
108 static HDBFlags uf2HDBFlags(krb5_context context, uint32_t userAccountControl, enum samba_kdc_ent_type ent_type)
109 {
110         HDBFlags flags = int2HDBFlags(0);
111
112         /* we don't allow kadmin deletes */
113         flags.immutable = 1;
114
115         /* mark the principal as invalid to start with */
116         flags.invalid = 1;
117
118         flags.renewable = 1;
119
120         /* All accounts are servers, but this may be disabled again in the caller */
121         flags.server = 1;
122
123         /* Account types - clear the invalid bit if it turns out to be valid */
124         if (userAccountControl & UF_NORMAL_ACCOUNT) {
125                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
126                         flags.client = 1;
127                 }
128                 flags.invalid = 0;
129         }
130
131         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
132                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
133                         flags.client = 1;
134                 }
135                 flags.invalid = 0;
136         }
137         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
138                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
139                         flags.client = 1;
140                 }
141                 flags.invalid = 0;
142         }
143         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
144                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
145                         flags.client = 1;
146                 }
147                 flags.invalid = 0;
148         }
149
150         /* Not permitted to act as a client if disabled */
151         if (userAccountControl & UF_ACCOUNTDISABLE) {
152                 flags.client = 0;
153         }
154         if (userAccountControl & UF_LOCKOUT) {
155                 flags.invalid = 1;
156         }
157 /*
158         if (userAccountControl & UF_PASSWORD_NOTREQD) {
159                 flags.invalid = 1;
160         }
161 */
162 /*
163         UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
164 */
165         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
166                 flags.invalid = 1;
167         }
168
169 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in samba_kdc_message2entry() */
170
171 /*
172         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
173                 flags.invalid = 1;
174         }
175 */
176         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
177                 flags.require_hwauth = 1;
178         }
179         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
180                 flags.ok_as_delegate = 1;
181         }
182         if (userAccountControl & UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION) {
183                 /*
184                  * this is confusing...
185                  *
186                  * UF_TRUSTED_FOR_DELEGATION
187                  * => ok_as_delegate
188                  *
189                  * and
190                  *
191                  * UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
192                  * => trusted_for_delegation
193                  */
194                 flags.trusted_for_delegation = 1;
195         }
196         if (!(userAccountControl & UF_NOT_DELEGATED)) {
197                 flags.forwardable = 1;
198                 flags.proxiable = 1;
199         }
200
201         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
202                 flags.require_preauth = 0;
203         } else {
204                 flags.require_preauth = 1;
205
206         }
207         return flags;
208 }
209
210 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
211 {
212     hdb_entry_ex *entry_ex = p->entry_ex;
213     free_hdb_entry(&entry_ex->entry);
214     return 0;
215 }
216
217 static void samba_kdc_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
218 {
219         /* this function is called only from hdb_free_entry().
220          * Make sure we neutralize the destructor or we will
221          * get a double free later when hdb_free_entry() will
222          * try to call free_hdb_entry() */
223         talloc_set_destructor(entry_ex->ctx, NULL);
224
225         /* now proceed to free the talloc part */
226         talloc_free(entry_ex->ctx);
227 }
228
229 static krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
230                                                     struct samba_kdc_db_context *kdc_db_ctx,
231                                                     TALLOC_CTX *mem_ctx,
232                                                     struct ldb_message *msg,
233                                                     uint32_t rid,
234                                                     bool is_rodc,
235                                                     uint32_t userAccountControl,
236                                                     enum samba_kdc_ent_type ent_type,
237                                                     hdb_entry_ex *entry_ex)
238 {
239         krb5_error_code ret = 0;
240         enum ndr_err_code ndr_err;
241         struct samr_Password *hash;
242         const struct ldb_val *sc_val;
243         struct supplementalCredentialsBlob scb;
244         struct supplementalCredentialsPackage *scpk = NULL;
245         bool newer_keys = false;
246         struct package_PrimaryKerberosBlob _pkb;
247         struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
248         struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
249         uint16_t i;
250         uint16_t allocated_keys = 0;
251         int rodc_krbtgt_number = 0;
252         int kvno = 0;
253         uint32_t supported_enctypes
254                 = ldb_msg_find_attr_as_uint(msg,
255                                             "msDS-SupportedEncryptionTypes",
256                                             0);
257
258         if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
259                 /* KDCs (and KDCs on RODCs) use AES */
260                 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
261         } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
262                 /* DCs and RODCs comptuer accounts use AES */
263                 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
264         } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
265                    (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
266                 /* for AS-REQ the client chooses the enc types it
267                  * supports, and this will vary between computers a
268                  * user logs in from.
269                  *
270                  * likewise for 'any' return as much as is supported,
271                  * to export into a keytab */
272                 supported_enctypes = ENC_ALL_TYPES;
273         }
274
275         /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
276         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
277                 supported_enctypes = ENC_CRC32|ENC_RSA_MD5;
278         } else {
279                 /* Otherwise, add in the default enc types */
280                 supported_enctypes |= ENC_CRC32 | ENC_RSA_MD5 | ENC_RC4_HMAC_MD5;
281         }
282
283         /* Is this the krbtgt or a RODC krbtgt */
284         if (is_rodc) {
285                 rodc_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
286
287                 if (rodc_krbtgt_number == -1) {
288                         return EINVAL;
289                 }
290         }
291
292         entry_ex->entry.keys.val = NULL;
293         entry_ex->entry.keys.len = 0;
294
295         kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
296         if (is_rodc) {
297                 kvno = SAMBA_KVNO_AND_KRBTGT(kvno, rodc_krbtgt_number);
298         }
299         entry_ex->entry.kvno = kvno;
300
301         /* Get keys from the db */
302
303         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
304         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
305
306         /* unicodePwd for enctype 0x17 (23) if present */
307         if (hash) {
308                 allocated_keys++;
309         }
310
311         /* supplementalCredentials if present */
312         if (sc_val) {
313                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
314                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
315                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
316                         dump_data(0, sc_val->data, sc_val->length);
317                         ret = EINVAL;
318                         goto out;
319                 }
320
321                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
322                         NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
323                         ret = EINVAL;
324                         goto out;
325                 }
326
327                 for (i=0; i < scb.sub.num_packages; i++) {
328                         if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
329                                 scpk = &scb.sub.packages[i];
330                                 if (!scpk->data || !scpk->data[0]) {
331                                         scpk = NULL;
332                                         continue;
333                                 }
334                                 newer_keys = true;
335                                 break;
336                         } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
337                                 scpk = &scb.sub.packages[i];
338                                 if (!scpk->data || !scpk->data[0]) {
339                                         scpk = NULL;
340                                 }
341                                 /*
342                                  * we don't break here in hope to find
343                                  * a Kerberos-Newer-Keys package
344                                  */
345                         }
346                 }
347         }
348         /*
349          * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
350          * of supplementalCredentials
351          */
352         if (scpk) {
353                 DATA_BLOB blob;
354
355                 blob = strhex_to_data_blob(mem_ctx, scpk->data);
356                 if (!blob.data) {
357                         ret = ENOMEM;
358                         goto out;
359                 }
360
361                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
362                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
363                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
364                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
365                         ret = EINVAL;
366                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
367                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
368                         goto out;
369                 }
370
371                 if (newer_keys && _pkb.version != 4) {
372                         ret = EINVAL;
373                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
374                         krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
375                         goto out;
376                 }
377
378                 if (!newer_keys && _pkb.version != 3) {
379                         ret = EINVAL;
380                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
381                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
382                         goto out;
383                 }
384
385                 if (_pkb.version == 4) {
386                         pkb4 = &_pkb.ctr.ctr4;
387                         allocated_keys += pkb4->num_keys;
388                 } else if (_pkb.version == 3) {
389                         pkb3 = &_pkb.ctr.ctr3;
390                         allocated_keys += pkb3->num_keys;
391                 }
392         }
393
394         if (allocated_keys == 0) {
395                 if (kdc_db_ctx->rodc) {
396                         /* We are on an RODC, but don't have keys for this account.  Signal this to the caller */
397                         return HDB_ERR_NOT_FOUND_HERE;
398                 }
399
400                 /* oh, no password.  Apparently (comment in
401                  * hdb-ldap.c) this violates the ASN.1, but this
402                  * allows an entry with no keys (yet). */
403                 return 0;
404         }
405
406         /* allocate space to decode into */
407         entry_ex->entry.keys.len = 0;
408         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
409         if (entry_ex->entry.keys.val == NULL) {
410                 ret = ENOMEM;
411                 goto out;
412         }
413
414         if (hash && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
415                 Key key;
416
417                 key.mkvno = 0;
418                 key.salt = NULL; /* No salt for this enc type */
419
420                 ret = krb5_keyblock_init(context,
421                                          ENCTYPE_ARCFOUR_HMAC,
422                                          hash->hash, sizeof(hash->hash),
423                                          &key.key);
424                 if (ret) {
425                         goto out;
426                 }
427
428                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
429                 entry_ex->entry.keys.len++;
430         }
431
432         if (pkb4) {
433                 for (i=0; i < pkb4->num_keys; i++) {
434                         Key key;
435
436                         if (!pkb4->keys[i].value) continue;
437
438                         if (!(kerberos_enctype_to_bitmap(pkb4->keys[i].keytype) & supported_enctypes)) {
439                                 continue;
440                         }
441
442                         key.mkvno = 0;
443                         key.salt = NULL;
444
445                         if (pkb4->salt.string) {
446                                 DATA_BLOB salt;
447
448                                 salt = data_blob_string_const(pkb4->salt.string);
449
450                                 key.salt = calloc(1, sizeof(*key.salt));
451                                 if (key.salt == NULL) {
452                                         ret = ENOMEM;
453                                         goto out;
454                                 }
455
456                                 key.salt->type = hdb_pw_salt;
457
458                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
459                                 if (ret) {
460                                         free(key.salt);
461                                         key.salt = NULL;
462                                         goto out;
463                                 }
464                         }
465
466                         /* TODO: maybe pass the iteration_count somehow... */
467
468                         ret = krb5_keyblock_init(context,
469                                                  pkb4->keys[i].keytype,
470                                                  pkb4->keys[i].value->data,
471                                                  pkb4->keys[i].value->length,
472                                                  &key.key);
473                         if (ret == KRB5_PROG_ETYPE_NOSUPP) {
474                                 DEBUG(2,("Unsupported keytype ignored - type %u\n",
475                                          pkb4->keys[i].keytype));
476                                 ret = 0;
477                                 continue;
478                         }
479                         if (ret) {
480                                 if (key.salt) {
481                                         free_Salt(key.salt);
482                                         free(key.salt);
483                                         key.salt = NULL;
484                                 }
485                                 goto out;
486                         }
487
488                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
489                         entry_ex->entry.keys.len++;
490                 }
491         } else if (pkb3) {
492                 for (i=0; i < pkb3->num_keys; i++) {
493                         Key key;
494
495                         if (!pkb3->keys[i].value) continue;
496
497                         if (!(kerberos_enctype_to_bitmap(pkb3->keys[i].keytype) & supported_enctypes)) {
498                                 continue;
499                         }
500
501                         key.mkvno = 0;
502                         key.salt = NULL;
503
504                         if (pkb3->salt.string) {
505                                 DATA_BLOB salt;
506
507                                 salt = data_blob_string_const(pkb3->salt.string);
508
509                                 key.salt = calloc(1, sizeof(*key.salt));
510                                 if (key.salt == NULL) {
511                                         ret = ENOMEM;
512                                         goto out;
513                                 }
514
515                                 key.salt->type = hdb_pw_salt;
516
517                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
518                                 if (ret) {
519                                         free(key.salt);
520                                         key.salt = NULL;
521                                         goto out;
522                                 }
523                         }
524
525                         ret = krb5_keyblock_init(context,
526                                                  pkb3->keys[i].keytype,
527                                                  pkb3->keys[i].value->data,
528                                                  pkb3->keys[i].value->length,
529                                                  &key.key);
530                         if (ret) {
531                                 if (key.salt) {
532                                         free_Salt(key.salt);
533                                         free(key.salt);
534                                         key.salt = NULL;
535                                 }
536                                 goto out;
537                         }
538
539                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
540                         entry_ex->entry.keys.len++;
541                 }
542         }
543
544 out:
545         if (ret != 0) {
546                 entry_ex->entry.keys.len = 0;
547         }
548         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
549                 free(entry_ex->entry.keys.val);
550                 entry_ex->entry.keys.val = NULL;
551         }
552         return ret;
553 }
554
555 /*
556  * Construct an hdb_entry from a directory entry.
557  */
558 static krb5_error_code samba_kdc_message2entry(krb5_context context,
559                                                struct samba_kdc_db_context *kdc_db_ctx,
560                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
561                                                enum samba_kdc_ent_type ent_type,
562                                                unsigned flags,
563                                                struct ldb_dn *realm_dn,
564                                                struct ldb_message *msg,
565                                                hdb_entry_ex *entry_ex)
566 {
567         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
568         uint32_t userAccountControl;
569         unsigned int i;
570         krb5_error_code ret = 0;
571         krb5_boolean is_computer = FALSE;
572
573         struct samba_kdc_entry *p;
574         NTTIME acct_expiry;
575         NTSTATUS status;
576
577         uint32_t rid;
578         bool is_rodc = false;
579         struct ldb_message_element *objectclasses;
580         struct ldb_val computer_val;
581         const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
582         computer_val.data = discard_const_p(uint8_t,"computer");
583         computer_val.length = strlen((const char *)computer_val.data);
584
585         if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
586                 is_rodc = true;
587         }
588
589         if (!samAccountName) {
590                 ret = ENOENT;
591                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
592                 goto out;
593         }
594
595         objectclasses = ldb_msg_find_element(msg, "objectClass");
596
597         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
598                 is_computer = TRUE;
599         }
600
601         memset(entry_ex, 0, sizeof(*entry_ex));
602
603         p = talloc(mem_ctx, struct samba_kdc_entry);
604         if (!p) {
605                 ret = ENOMEM;
606                 goto out;
607         }
608
609         p->kdc_db_ctx = kdc_db_ctx;
610         p->entry_ex = entry_ex;
611         p->realm_dn = talloc_reference(p, realm_dn);
612         if (!p->realm_dn) {
613                 ret = ENOMEM;
614                 goto out;
615         }
616
617         talloc_set_destructor(p, samba_kdc_entry_destructor);
618
619         /* make sure we do not have bogus data in there */
620         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
621
622         entry_ex->ctx = p;
623         entry_ex->free_entry = samba_kdc_free_entry;
624
625         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
626
627
628         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
629         if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
630                 krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
631         } else {
632                 ret = copy_Principal(principal, entry_ex->entry.principal);
633                 if (ret) {
634                         krb5_clear_error_message(context);
635                         goto out;
636                 }
637
638                 /* While we have copied the client principal, tests
639                  * show that Win2k3 returns the 'corrected' realm, not
640                  * the client-specified realm.  This code attempts to
641                  * replace the client principal's realm with the one
642                  * we determine from our records */
643
644                 /* this has to be with malloc() */
645                 krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
646         }
647
648         /* First try and figure out the flags based on the userAccountControl */
649         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
650
651         /* Windows 2008 seems to enforce this (very sensible) rule by
652          * default - don't allow offline attacks on a user's password
653          * by asking for a ticket to them as a service (encrypted with
654          * their probably patheticly insecure password) */
655
656         if (entry_ex->entry.flags.server
657             && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
658                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
659                         entry_ex->entry.flags.server = 0;
660                 }
661         }
662
663         if (flags & HDB_F_ADMIN_DATA) {
664                 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
665                  * of the Heimdal KDC.  They are stored in a the traditional
666                  * DB for audit purposes, and still form part of the structure
667                  * we must return */
668
669                 /* use 'whenCreated' */
670                 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
671                 /* use 'kadmin' for now (needed by mit_samba) */
672                 krb5_make_principal(context,
673                                     &entry_ex->entry.created_by.principal,
674                                     lpcfg_realm(lp_ctx), "kadmin", NULL);
675
676                 entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
677                 if (entry_ex->entry.modified_by == NULL) {
678                         ret = ENOMEM;
679                         krb5_set_error_message(context, ret, "malloc: out of memory");
680                         goto out;
681                 }
682
683                 /* use 'whenChanged' */
684                 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
685                 /* use 'kadmin' for now (needed by mit_samba) */
686                 krb5_make_principal(context,
687                                     &entry_ex->entry.modified_by->principal,
688                                     lpcfg_realm(lp_ctx), "kadmin", NULL);
689         }
690
691
692         /* The lack of password controls etc applies to krbtgt by
693          * virtue of being that particular RID */
694         status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
695
696         if (!NT_STATUS_IS_OK(status)) {
697                 ret = EINVAL;
698                 goto out;
699         }
700
701         if (rid == DOMAIN_RID_KRBTGT) {
702                 entry_ex->entry.valid_end = NULL;
703                 entry_ex->entry.pw_end = NULL;
704
705                 entry_ex->entry.flags.invalid = 0;
706                 entry_ex->entry.flags.server = 1;
707
708                 /* Don't mark all requests for the krbtgt/realm as
709                  * 'change password', as otherwise we could get into
710                  * trouble, and not enforce the password expirty.
711                  * Instead, only do it when request is for the kpasswd service */
712                 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
713                     && principal->name.name_string.len == 2
714                     && (strcmp(principal->name.name_string.val[0], "kadmin") == 0)
715                     && (strcmp(principal->name.name_string.val[1], "changepw") == 0)
716                     && lpcfg_is_my_domain_or_realm(lp_ctx, principal->realm)) {
717                         entry_ex->entry.flags.change_pw = 1;
718                 }
719                 entry_ex->entry.flags.client = 0;
720                 entry_ex->entry.flags.forwardable = 1;
721                 entry_ex->entry.flags.ok_as_delegate = 1;
722         } else if (is_rodc) {
723                 /* The RODC krbtgt account is like the main krbtgt,
724                  * but it does not have a changepw or kadmin
725                  * service */
726
727                 entry_ex->entry.valid_end = NULL;
728                 entry_ex->entry.pw_end = NULL;
729
730                 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
731                 entry_ex->entry.flags.client = 0;
732                 entry_ex->entry.flags.invalid = 0;
733                 entry_ex->entry.flags.server = 1;
734
735                 entry_ex->entry.flags.client = 0;
736                 entry_ex->entry.flags.forwardable = 1;
737                 entry_ex->entry.flags.ok_as_delegate = 0;
738         } else if (entry_ex->entry.flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
739                 /* The account/password expiry only applies when the account is used as a
740                  * client (ie password login), not when used as a server */
741
742                 /* Make very well sure we don't use this for a client,
743                  * it could bypass the password restrictions */
744                 entry_ex->entry.flags.client = 0;
745
746                 entry_ex->entry.valid_end = NULL;
747                 entry_ex->entry.pw_end = NULL;
748
749         } else {
750                 NTTIME must_change_time
751                         = samdb_result_force_password_change(kdc_db_ctx->samdb, mem_ctx,
752                                                              realm_dn, msg);
753                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
754                         entry_ex->entry.pw_end = NULL;
755                 } else {
756                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
757                         if (entry_ex->entry.pw_end == NULL) {
758                                 ret = ENOMEM;
759                                 goto out;
760                         }
761                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
762                 }
763
764                 acct_expiry = samdb_result_account_expires(msg);
765                 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
766                         entry_ex->entry.valid_end = NULL;
767                 } else {
768                         entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
769                         if (entry_ex->entry.valid_end == NULL) {
770                                 ret = ENOMEM;
771                                 goto out;
772                         }
773                         *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
774                 }
775         }
776
777         entry_ex->entry.valid_start = NULL;
778
779         entry_ex->entry.max_life = malloc(sizeof(*entry_ex->entry.max_life));
780         if (entry_ex->entry.max_life == NULL) {
781                 ret = ENOMEM;
782                 goto out;
783         }
784
785         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
786                 *entry_ex->entry.max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
787         } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
788                 *entry_ex->entry.max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
789         } else {
790                 *entry_ex->entry.max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
791                                                 kdc_db_ctx->policy.usr_tkt_lifetime);
792         }
793
794         entry_ex->entry.max_renew = malloc(sizeof(*entry_ex->entry.max_life));
795         if (entry_ex->entry.max_renew == NULL) {
796                 ret = ENOMEM;
797                 goto out;
798         }
799
800         *entry_ex->entry.max_renew = kdc_db_ctx->policy.renewal_lifetime;
801
802         entry_ex->entry.generation = NULL;
803
804         /* Get keys from the db */
805         ret = samba_kdc_message2entry_keys(context, kdc_db_ctx, p, msg,
806                                            rid, is_rodc, userAccountControl,
807                                            ent_type, entry_ex);
808         if (ret) {
809                 /* Could be bougus data in the entry, or out of memory */
810                 goto out;
811         }
812
813         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
814         if (entry_ex->entry.etypes == NULL) {
815                 krb5_clear_error_message(context);
816                 ret = ENOMEM;
817                 goto out;
818         }
819         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
820         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
821         if (entry_ex->entry.etypes->val == NULL) {
822                 krb5_clear_error_message(context);
823                 ret = ENOMEM;
824                 goto out;
825         }
826         for (i=0; i < entry_ex->entry.etypes->len; i++) {
827                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
828         }
829
830
831         p->msg = talloc_steal(p, msg);
832
833 out:
834         if (ret != 0) {
835                 /* This doesn't free ent itself, that is for the eventual caller to do */
836                 hdb_free_entry(context, entry_ex);
837         } else {
838                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
839         }
840
841         return ret;
842 }
843
844 /*
845  * Construct an hdb_entry from a directory entry.
846  * The kvno is what the remote client asked for
847  */
848 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
849                                                struct samba_kdc_db_context *kdc_db_ctx,
850                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
851                                                enum trust_direction direction,
852                                                struct ldb_dn *realm_dn,
853                                                unsigned flags,
854                                                uint32_t kvno,
855                                                struct ldb_message *msg,
856                                                hdb_entry_ex *entry_ex)
857 {
858         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
859         const char *dnsdomain;
860         const char *realm = lpcfg_realm(lp_ctx);
861         DATA_BLOB password_utf16;
862         struct samr_Password password_hash;
863         const struct ldb_val *password_val;
864         struct trustAuthInOutBlob password_blob;
865         struct samba_kdc_entry *p;
866         bool use_previous;
867         uint32_t current_kvno;
868         enum ndr_err_code ndr_err;
869         int ret, trust_direction_flags;
870         unsigned int i;
871         struct AuthenticationInformationArray *auth_array;
872
873         p = talloc(mem_ctx, struct samba_kdc_entry);
874         if (!p) {
875                 ret = ENOMEM;
876                 goto out;
877         }
878
879         p->kdc_db_ctx = kdc_db_ctx;
880         p->entry_ex = entry_ex;
881         p->realm_dn = realm_dn;
882
883         talloc_set_destructor(p, samba_kdc_entry_destructor);
884
885         /* make sure we do not have bogus data in there */
886         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
887
888         entry_ex->ctx = p;
889         entry_ex->free_entry = samba_kdc_free_entry;
890
891         /* use 'whenCreated' */
892         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
893         /* use 'kadmin' for now (needed by mit_samba) */
894         krb5_make_principal(context,
895                             &entry_ex->entry.created_by.principal,
896                             realm, "kadmin", NULL);
897
898         entry_ex->entry.valid_start = NULL;
899
900         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
901
902         if (direction == INBOUND) {
903                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
904
905         } else { /* OUTBOUND */
906                 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
907                 /* replace realm */
908                 realm = strupper_talloc(mem_ctx, dnsdomain);
909                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
910         }
911
912         if (!password_val || !(trust_direction_flags & direction)) {
913                 ret = ENOENT;
914                 goto out;
915         }
916
917         ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
918                                            (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
919         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
920                 ret = EINVAL;
921                 goto out;
922         }
923
924
925         /* we need to work out if we are going to use the current or
926          * the previous password hash.
927          * We base this on the kvno the client passes in. If the kvno
928          * passed in is equal to the current kvno in our database then
929          * we use the current structure. If it is the current kvno-1,
930          * then we use the previous substrucure.
931          */
932
933         /* first work out the current kvno */
934         current_kvno = 0;
935         for (i=0; i < password_blob.count; i++) {
936                 if (password_blob.current.array[i].AuthType == TRUST_AUTH_TYPE_VERSION) {
937                         current_kvno = password_blob.current.array[i].AuthInfo.version.version;
938                 }
939         }
940
941         /* work out whether we will use the previous or current
942            password */
943         if (password_blob.previous.count == 0) {
944                 /* there is no previous password */
945                 use_previous = false;
946         } else if (!(flags & HDB_F_KVNO_SPECIFIED) ||
947             kvno == current_kvno) {
948                 use_previous = false;
949         } else if ((kvno+1 == current_kvno) ||
950                    (kvno == 255 && current_kvno == 0)) {
951                 use_previous = true;
952         } else {
953                 DEBUG(1,(__location__ ": Request for unknown kvno %u - current kvno is %u\n",
954                          kvno, current_kvno));
955                 ret = ENOENT;
956                 goto out;
957         }
958
959         if (use_previous) {
960                 auth_array = &password_blob.previous;
961         } else {
962                 auth_array = &password_blob.current;
963         }
964
965         /* use the kvno the client specified, if available */
966         if (flags & HDB_F_KVNO_SPECIFIED) {
967                 entry_ex->entry.kvno = kvno;
968         } else {
969                 entry_ex->entry.kvno = current_kvno;
970         }
971
972         for (i=0; i < auth_array->count; i++) {
973                 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
974                         password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
975                                                          auth_array->array[i].AuthInfo.clear.size);
976                         /* In the future, generate all sorts of
977                          * hashes, but for now we can't safely convert
978                          * the random strings windows uses into
979                          * utf8 */
980
981                         /* but as it is utf16 already, we can get the NT password/arcfour-hmac-md5 key */
982                         mdfour(password_hash.hash, password_utf16.data, password_utf16.length);
983                         break;
984                 } else if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
985                         password_hash = auth_array->array[i].AuthInfo.nt4owf.password;
986                         break;
987                 }
988         }
989
990         if (i < auth_array->count) {
991                 Key key;
992                 /* Must have found a cleartext or MD4 password */
993                 entry_ex->entry.keys.val = calloc(1, sizeof(Key));
994
995                 key.mkvno = 0;
996                 key.salt = NULL; /* No salt for this enc type */
997
998                 if (entry_ex->entry.keys.val == NULL) {
999                         ret = ENOMEM;
1000                         goto out;
1001                 }
1002
1003                 ret = krb5_keyblock_init(context,
1004                                          ENCTYPE_ARCFOUR_HMAC,
1005                                          password_hash.hash, sizeof(password_hash.hash),
1006                                          &key.key);
1007                 if (ret != 0) {
1008                         goto out;
1009                 }
1010
1011                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1012                 entry_ex->entry.keys.len++;
1013         }
1014
1015         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
1016
1017         ret = copy_Principal(principal, entry_ex->entry.principal);
1018         if (ret) {
1019                 krb5_clear_error_message(context);
1020                 goto out;
1021         }
1022
1023         /* While we have copied the client principal, tests
1024          * show that Win2k3 returns the 'corrected' realm, not
1025          * the client-specified realm.  This code attempts to
1026          * replace the client principal's realm with the one
1027          * we determine from our records */
1028
1029         krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
1030         entry_ex->entry.flags = int2HDBFlags(0);
1031         entry_ex->entry.flags.immutable = 1;
1032         entry_ex->entry.flags.invalid = 0;
1033         entry_ex->entry.flags.server = 1;
1034         entry_ex->entry.flags.require_preauth = 1;
1035
1036         entry_ex->entry.pw_end = NULL;
1037
1038         entry_ex->entry.max_life = NULL;
1039
1040         entry_ex->entry.max_renew = NULL;
1041
1042         entry_ex->entry.generation = NULL;
1043
1044         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
1045         if (entry_ex->entry.etypes == NULL) {
1046                 krb5_clear_error_message(context);
1047                 ret = ENOMEM;
1048                 goto out;
1049         }
1050         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
1051         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
1052         if (entry_ex->entry.etypes->val == NULL) {
1053                 krb5_clear_error_message(context);
1054                 ret = ENOMEM;
1055                 goto out;
1056         }
1057         for (i=0; i < entry_ex->entry.etypes->len; i++) {
1058                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
1059         }
1060
1061
1062         p->msg = talloc_steal(p, msg);
1063
1064 out:
1065         if (ret != 0) {
1066                 /* This doesn't free ent itself, that is for the eventual caller to do */
1067                 hdb_free_entry(context, entry_ex);
1068         } else {
1069                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
1070         }
1071
1072         return ret;
1073
1074 }
1075
1076 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
1077                                         TALLOC_CTX *mem_ctx,
1078                                         const char *realm,
1079                                         struct ldb_dn *realm_dn,
1080                                         struct ldb_message **pmsg)
1081 {
1082         int lret;
1083         krb5_error_code ret;
1084         char *filter = NULL;
1085         const char * const *attrs = trust_attrs;
1086
1087         struct ldb_result *res = NULL;
1088         char *realm_encoded = ldb_binary_encode_string(mem_ctx, realm);
1089         if (!realm_encoded) {
1090                 if (!filter) {
1091                         ret = ENOMEM;
1092                         krb5_set_error_message(context, ret, "talloc_asprintf: out of memory");
1093                         return ret;
1094                 }
1095         }
1096         filter = talloc_asprintf(mem_ctx, "(&(objectClass=trustedDomain)(|(flatname=%s)(trustPartner=%s)))", 
1097                                  realm_encoded, realm_encoded);
1098
1099         if (!filter) {
1100                 talloc_free(realm_encoded);
1101                 ret = ENOMEM;
1102                 krb5_set_error_message(context, ret, "talloc_asprintf: out of memory");
1103                 return ret;
1104         }
1105
1106         lret = dsdb_search(ldb_ctx, mem_ctx, &res,
1107                            ldb_get_default_basedn(ldb_ctx),
1108                            LDB_SCOPE_SUBTREE, attrs,
1109                            DSDB_SEARCH_NO_GLOBAL_CATALOG,
1110                            "%s", filter);
1111         if (lret != LDB_SUCCESS) {
1112                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
1113                 return HDB_ERR_NOENTRY;
1114         } else if (res->count == 0 || res->count > 1) {
1115                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
1116                 talloc_free(res);
1117                 return HDB_ERR_NOENTRY;
1118         }
1119         talloc_steal(mem_ctx, res->msgs);
1120         *pmsg = res->msgs[0];
1121         talloc_free(res);
1122         return 0;
1123 }
1124
1125 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
1126                                                 struct samba_kdc_db_context *kdc_db_ctx,
1127                                                 TALLOC_CTX *mem_ctx,
1128                                                 krb5_const_principal principal,
1129                                                 const char **attrs,
1130                                                 struct ldb_dn **realm_dn,
1131                                                 struct ldb_message **msg) {
1132         NTSTATUS nt_status;
1133         char *principal_string;
1134         krb5_error_code ret;
1135
1136         ret = krb5_unparse_name(context, principal, &principal_string);
1137
1138         if (ret != 0) {
1139                 return ret;
1140         }
1141
1142         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1143                                               mem_ctx, principal_string, attrs,
1144                                               realm_dn, msg);
1145         free(principal_string);
1146         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1147                 return HDB_ERR_NOENTRY;
1148         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1149                 return ENOMEM;
1150         } else if (!NT_STATUS_IS_OK(nt_status)) {
1151                 return EINVAL;
1152         }
1153
1154         return ret;
1155 }
1156
1157 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1158                                                struct samba_kdc_db_context *kdc_db_ctx,
1159                                                TALLOC_CTX *mem_ctx,
1160                                                krb5_const_principal principal,
1161                                                unsigned flags,
1162                                                hdb_entry_ex *entry_ex) {
1163         struct ldb_dn *realm_dn;
1164         krb5_error_code ret;
1165         struct ldb_message *msg = NULL;
1166
1167         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1168                                        mem_ctx, principal, user_attrs,
1169                                        &realm_dn, &msg);
1170         if (ret != 0) {
1171                 return ret;
1172         }
1173
1174         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1175                                       principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1176                                       flags,
1177                                       realm_dn, msg, entry_ex);
1178         return ret;
1179 }
1180
1181 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1182                                               struct samba_kdc_db_context *kdc_db_ctx,
1183                                               TALLOC_CTX *mem_ctx,
1184                                               krb5_const_principal principal,
1185                                               unsigned flags,
1186                                               uint32_t kvno,
1187                                               hdb_entry_ex *entry_ex)
1188 {
1189         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1190         krb5_error_code ret;
1191         struct ldb_message *msg = NULL;
1192         struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1193
1194         krb5_principal alloc_principal = NULL;
1195         if (principal->name.name_string.len != 2
1196             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
1197                 /* Not a krbtgt */
1198                 return HDB_ERR_NOENTRY;
1199         }
1200
1201         /* krbtgt case.  Either us or a trusted realm */
1202
1203         if (lpcfg_is_my_domain_or_realm(lp_ctx, principal->realm)
1204             && lpcfg_is_my_domain_or_realm(lp_ctx, principal->name.name_string.val[1])) {
1205                 /* us, or someone quite like us */
1206                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1207                  * is in our db, then direct the caller at our primary
1208                  * krbtgt */
1209
1210                 int lret;
1211                 unsigned int krbtgt_number;
1212                 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
1213                    trust tickets. We don't yet know what this means, but we do
1214                    seem to need to treat it as unspecified */
1215                 if (flags & HDB_F_KVNO_SPECIFIED) {
1216                         krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
1217                         if (kdc_db_ctx->rodc) {
1218                                 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
1219                                         return HDB_ERR_NOT_FOUND_HERE;
1220                                 }
1221                         }
1222                 } else {
1223                         krbtgt_number = kdc_db_ctx->my_krbtgt_number;
1224                 }
1225
1226                 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
1227                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1228                                                &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1229                                                krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG,
1230                                                "(objectClass=user)");
1231                 } else {
1232                         /* We need to look up an RODC krbtgt (perhaps
1233                          * ours, if we are an RODC, perhaps another
1234                          * RODC if we are a read-write DC */
1235                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1236                                                &msg, realm_dn, LDB_SCOPE_SUBTREE,
1237                                                krbtgt_attrs,
1238                                                DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1239                                                "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
1240                 }
1241
1242                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1243                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1244                                    (unsigned)(krbtgt_number));
1245                         krb5_set_error_message(context, HDB_ERR_NOENTRY,
1246                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1247                                                (unsigned)(krbtgt_number));
1248                         return HDB_ERR_NOENTRY;
1249                 } else if (lret != LDB_SUCCESS) {
1250                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1251                                    (unsigned)(krbtgt_number));
1252                         krb5_set_error_message(context, HDB_ERR_NOENTRY,
1253                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1254                                                (unsigned)(krbtgt_number));
1255                         return HDB_ERR_NOENTRY;
1256                 }
1257
1258                 /*
1259                  * Windows seems to canonicalize the principal
1260                  * in a TGS REP even if the client did not specify
1261                  * the canonicalize flag.
1262                  */
1263                 if (flags & (HDB_F_CANON|HDB_F_FOR_TGS_REQ)) {
1264                         ret = krb5_copy_principal(context, principal, &alloc_principal);
1265                         if (ret) {
1266                                 return ret;
1267                         }
1268
1269                         /* When requested to do so, ensure that the
1270                          * both realm values in the principal are set
1271                          * to the upper case, canonical realm */
1272                         free(alloc_principal->name.name_string.val[1]);
1273                         alloc_principal->name.name_string.val[1] = strdup(lpcfg_realm(lp_ctx));
1274                         if (!alloc_principal->name.name_string.val[1]) {
1275                                 ret = ENOMEM;
1276                                 krb5_set_error_message(context, ret, "samba_kdc_fetch: strdup() failed!");
1277                                 return ret;
1278                         }
1279                         principal = alloc_principal;
1280                 }
1281
1282                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1283                                               principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
1284                                               flags, realm_dn, msg, entry_ex);
1285                 if (alloc_principal) {
1286                         /* This is again copied in the message2entry call */
1287                         krb5_free_principal(context, alloc_principal);
1288                 }
1289                 if (ret != 0) {
1290                         krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
1291                 }
1292                 return ret;
1293
1294         } else {
1295                 enum trust_direction direction = UNKNOWN;
1296                 const char *realm = NULL;
1297
1298                 /* Either an inbound or outbound trust */
1299
1300                 if (strcasecmp(lpcfg_realm(lp_ctx), principal->realm) == 0) {
1301                         /* look for inbound trust */
1302                         direction = INBOUND;
1303                         realm = principal->name.name_string.val[1];
1304                 } else if (strcasecmp(lpcfg_realm(lp_ctx), principal->name.name_string.val[1]) == 0) {
1305                         /* look for outbound trust */
1306                         direction = OUTBOUND;
1307                         realm = principal->realm;
1308                 } else {
1309                         krb5_warnx(context, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1310                                    principal->realm, principal->name.name_string.val[1]);
1311                         krb5_set_error_message(context, HDB_ERR_NOENTRY, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1312                                                principal->realm, principal->name.name_string.val[1]);
1313                         return HDB_ERR_NOENTRY;
1314                 }
1315
1316                 /* Trusted domains are under CN=system */
1317
1318                 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
1319                                        mem_ctx,
1320                                        realm, realm_dn, &msg);
1321
1322                 if (ret != 0) {
1323                         krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
1324                         krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
1325                         return ret;
1326                 }
1327
1328                 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
1329                                                     principal, direction,
1330                                                     realm_dn, flags, kvno, msg, entry_ex);
1331                 if (ret != 0) {
1332                         krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed");
1333                 }
1334                 return ret;
1335         }
1336
1337 }
1338
1339 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
1340                                                 struct samba_kdc_db_context *kdc_db_ctx,
1341                                                 TALLOC_CTX *mem_ctx,
1342                                                 krb5_const_principal principal,
1343                                                 const char **attrs,
1344                                                 struct ldb_dn **realm_dn,
1345                                                 struct ldb_message **msg)
1346 {
1347         krb5_error_code ret;
1348         if (principal->name.name_string.len >= 2) {
1349                 /* 'normal server' case */
1350                 int ldb_ret;
1351                 NTSTATUS nt_status;
1352                 struct ldb_dn *user_dn;
1353                 char *principal_string;
1354
1355                 ret = krb5_unparse_name_flags(context, principal,
1356                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1357                                               &principal_string);
1358                 if (ret != 0) {
1359                         return ret;
1360                 }
1361
1362                 /* At this point we may find the host is known to be
1363                  * in a different realm, so we should generate a
1364                  * referral instead */
1365                 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
1366                                                          mem_ctx, principal_string,
1367                                                          &user_dn, realm_dn);
1368                 free(principal_string);
1369
1370                 if (!NT_STATUS_IS_OK(nt_status)) {
1371                         return HDB_ERR_NOENTRY;
1372                 }
1373
1374                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
1375                                           mem_ctx,
1376                                           msg, user_dn, LDB_SCOPE_BASE,
1377                                           attrs,
1378                                           DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1379                                           "(objectClass=*)");
1380                 if (ldb_ret != LDB_SUCCESS) {
1381                         return HDB_ERR_NOENTRY;
1382                 }
1383
1384         } else {
1385                 int lret;
1386                 char *short_princ;
1387                 const char *realm;
1388                 /* server as client principal case, but we must not lookup userPrincipalNames */
1389                 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1390                 realm = krb5_principal_get_realm(context, principal);
1391
1392                 /* TODO: Check if it is our realm, otherwise give referral */
1393
1394                 ret = krb5_unparse_name_flags(context, principal,  KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
1395
1396                 if (ret != 0) {
1397                         krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
1398                         krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
1399                         return ret;
1400                 }
1401
1402                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
1403                                        *realm_dn, LDB_SCOPE_SUBTREE,
1404                                        attrs,
1405                                        DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1406                                        "(&(objectClass=user)(samAccountName=%s))",
1407                                        ldb_binary_encode_string(mem_ctx, short_princ));
1408                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1409                         DEBUG(3, ("Failed to find an entry for %s\n", short_princ));
1410                         free(short_princ);
1411                         return HDB_ERR_NOENTRY;
1412                 }
1413                 if (lret != LDB_SUCCESS) {
1414                         DEBUG(3, ("Failed single search for %s - %s\n",
1415                                   short_princ, ldb_errstring(kdc_db_ctx->samdb)));
1416                         free(short_princ);
1417                         return HDB_ERR_NOENTRY;
1418                 }
1419                 free(short_princ);
1420         }
1421
1422         return 0;
1423 }
1424
1425 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
1426                                               struct samba_kdc_db_context *kdc_db_ctx,
1427                                               TALLOC_CTX *mem_ctx,
1428                                               krb5_const_principal principal,
1429                                               unsigned flags,
1430                                               hdb_entry_ex *entry_ex)
1431 {
1432         krb5_error_code ret;
1433         struct ldb_dn *realm_dn;
1434         struct ldb_message *msg;
1435
1436         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
1437                                        server_attrs, &realm_dn, &msg);
1438         if (ret != 0) {
1439                 return ret;
1440         }
1441
1442         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1443                                       principal, SAMBA_KDC_ENT_TYPE_SERVER,
1444                                       flags,
1445                                       realm_dn, msg, entry_ex);
1446         if (ret != 0) {
1447                 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
1448         }
1449
1450         return ret;
1451 }
1452
1453 krb5_error_code samba_kdc_fetch(krb5_context context,
1454                                 struct samba_kdc_db_context *kdc_db_ctx,
1455                                 krb5_const_principal principal,
1456                                 unsigned flags,
1457                                 krb5_kvno kvno,
1458                                 hdb_entry_ex *entry_ex)
1459 {
1460         krb5_error_code ret = HDB_ERR_NOENTRY;
1461         TALLOC_CTX *mem_ctx;
1462
1463         mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
1464         if (!mem_ctx) {
1465                 ret = ENOMEM;
1466                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1467                 return ret;
1468         }
1469
1470         if (flags & HDB_F_GET_CLIENT) {
1471                 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
1472                 if (ret != HDB_ERR_NOENTRY) goto done;
1473         }
1474         if (flags & HDB_F_GET_SERVER) {
1475                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1476                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
1477                 if (ret != HDB_ERR_NOENTRY) goto done;
1478
1479                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1480                 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
1481                 if (ret != HDB_ERR_NOENTRY) goto done;
1482         }
1483         if (flags & HDB_F_GET_KRBTGT) {
1484                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
1485                 if (ret != HDB_ERR_NOENTRY) goto done;
1486         }
1487
1488 done:
1489         talloc_free(mem_ctx);
1490         return ret;
1491 }
1492
1493 struct samba_kdc_seq {
1494         unsigned int index;
1495         unsigned int count;
1496         struct ldb_message **msgs;
1497         struct ldb_dn *realm_dn;
1498 };
1499
1500 static krb5_error_code samba_kdc_seq(krb5_context context,
1501                                      struct samba_kdc_db_context *kdc_db_ctx,
1502                                      hdb_entry_ex *entry)
1503 {
1504         krb5_error_code ret;
1505         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1506         TALLOC_CTX *mem_ctx;
1507         hdb_entry_ex entry_ex;
1508         memset(&entry_ex, '\0', sizeof(entry_ex));
1509
1510         if (!priv) {
1511                 return HDB_ERR_NOENTRY;
1512         }
1513
1514         mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
1515
1516         if (!mem_ctx) {
1517                 ret = ENOMEM;
1518                 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
1519                 return ret;
1520         }
1521
1522         if (priv->index < priv->count) {
1523                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1524                                               NULL, SAMBA_KDC_ENT_TYPE_ANY,
1525                                               HDB_F_ADMIN_DATA|HDB_F_GET_ANY,
1526                                               priv->realm_dn, priv->msgs[priv->index++], entry);
1527         } else {
1528                 ret = HDB_ERR_NOENTRY;
1529         }
1530
1531         if (ret != 0) {
1532                 TALLOC_FREE(priv);
1533                 kdc_db_ctx->seq_ctx = NULL;
1534         } else {
1535                 talloc_free(mem_ctx);
1536         }
1537
1538         return ret;
1539 }
1540
1541 krb5_error_code samba_kdc_firstkey(krb5_context context,
1542                                    struct samba_kdc_db_context *kdc_db_ctx,
1543                                    hdb_entry_ex *entry)
1544 {
1545         struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
1546         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1547         char *realm;
1548         struct ldb_result *res = NULL;
1549         krb5_error_code ret;
1550         TALLOC_CTX *mem_ctx;
1551         int lret;
1552
1553         if (priv) {
1554                 TALLOC_FREE(priv);
1555                 kdc_db_ctx->seq_ctx = NULL;
1556         }
1557
1558         priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
1559         if (!priv) {
1560                 ret = ENOMEM;
1561                 krb5_set_error_message(context, ret, "talloc: out of memory");
1562                 return ret;
1563         }
1564
1565         priv->index = 0;
1566         priv->msgs = NULL;
1567         priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
1568         priv->count = 0;
1569
1570         mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
1571
1572         if (!mem_ctx) {
1573                 ret = ENOMEM;
1574                 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
1575                 return ret;
1576         }
1577
1578         ret = krb5_get_default_realm(context, &realm);
1579         if (ret != 0) {
1580                 TALLOC_FREE(priv);
1581                 return ret;
1582         }
1583
1584         lret = dsdb_search(ldb_ctx, priv, &res,
1585                            priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
1586                            DSDB_SEARCH_NO_GLOBAL_CATALOG,
1587                            "(objectClass=user)");
1588
1589         if (lret != LDB_SUCCESS) {
1590                 TALLOC_FREE(priv);
1591                 return HDB_ERR_NOENTRY;
1592         }
1593
1594         priv->count = res->count;
1595         priv->msgs = talloc_steal(priv, res->msgs);
1596         talloc_free(res);
1597
1598         kdc_db_ctx->seq_ctx = priv;
1599
1600         ret = samba_kdc_seq(context, kdc_db_ctx, entry);
1601
1602         if (ret != 0) {
1603                 TALLOC_FREE(priv);
1604                 kdc_db_ctx->seq_ctx = NULL;
1605         } else {
1606                 talloc_free(mem_ctx);
1607         }
1608         return ret;
1609 }
1610
1611 krb5_error_code samba_kdc_nextkey(krb5_context context,
1612                                   struct samba_kdc_db_context *kdc_db_ctx,
1613                                   hdb_entry_ex *entry)
1614 {
1615         return samba_kdc_seq(context, kdc_db_ctx, entry);
1616 }
1617
1618 /* Check if a given entry may delegate or do s4u2self to this target principal
1619  *
1620  * This is currently a very nasty hack - allowing only delegation to itself.
1621  */
1622 krb5_error_code
1623 samba_kdc_check_s4u2self(krb5_context context,
1624                          struct samba_kdc_db_context *kdc_db_ctx,
1625                          hdb_entry_ex *entry,
1626                          krb5_const_principal target_principal)
1627 {
1628         krb5_error_code ret;
1629         krb5_principal enterprise_prinicpal = NULL;
1630         struct ldb_dn *realm_dn;
1631         struct ldb_message *msg;
1632         struct dom_sid *orig_sid;
1633         struct dom_sid *target_sid;
1634         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1635         const char *delegation_check_attrs[] = {
1636                 "objectSid", NULL
1637         };
1638
1639         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2self");
1640
1641         if (!mem_ctx) {
1642                 ret = ENOMEM;
1643                 krb5_set_error_message(context, ret, "samba_kdc_check_s4u2self: talloc_named() failed!");
1644                 return ret;
1645         }
1646
1647         if (target_principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1648                 /* Need to reparse the enterprise principal to find the real target */
1649                 if (target_principal->name.name_string.len != 1) {
1650                         ret = KRB5_PARSE_MALFORMED;
1651                         krb5_set_error_message(context, ret, "samba_kdc_check_s4u2self: request for delegation to enterprise principal with wrong (%d) number of components",
1652                                                target_principal->name.name_string.len);
1653                         talloc_free(mem_ctx);
1654                         return ret;
1655                 }
1656                 ret = krb5_parse_name(context, target_principal->name.name_string.val[0],
1657                                       &enterprise_prinicpal);
1658                 if (ret) {
1659                         talloc_free(mem_ctx);
1660                         return ret;
1661                 }
1662                 target_principal = enterprise_prinicpal;
1663         }
1664
1665         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, target_principal,
1666                                        delegation_check_attrs, &realm_dn, &msg);
1667
1668         krb5_free_principal(context, enterprise_prinicpal);
1669
1670         if (ret != 0) {
1671                 talloc_free(mem_ctx);
1672                 return ret;
1673         }
1674
1675         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1676         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1677
1678         /* Allow delegation to the same principal, even if by a different
1679          * name.  The easy and safe way to prove this is by SID
1680          * comparison */
1681         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1682                 talloc_free(mem_ctx);
1683                 return KRB5KDC_ERR_BADOPTION;
1684         }
1685
1686         talloc_free(mem_ctx);
1687         return ret;
1688 }
1689
1690 /* Certificates printed by a the Certificate Authority might have a
1691  * slightly different form of the user principal name to that in the
1692  * database.  Allow a mismatch where they both refer to the same
1693  * SID */
1694
1695 krb5_error_code
1696 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
1697                                     struct samba_kdc_db_context *kdc_db_ctx,
1698                                      hdb_entry_ex *entry,
1699                                      krb5_const_principal certificate_principal)
1700 {
1701         krb5_error_code ret;
1702         struct ldb_dn *realm_dn;
1703         struct ldb_message *msg;
1704         struct dom_sid *orig_sid;
1705         struct dom_sid *target_sid;
1706         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1707         const char *ms_upn_check_attrs[] = {
1708                 "objectSid", NULL
1709         };
1710
1711         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
1712
1713         if (!mem_ctx) {
1714                 ret = ENOMEM;
1715                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1716                 return ret;
1717         }
1718
1719         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1720                                        mem_ctx, certificate_principal,
1721                                        ms_upn_check_attrs, &realm_dn, &msg);
1722
1723         if (ret != 0) {
1724                 talloc_free(mem_ctx);
1725                 return ret;
1726         }
1727
1728         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1729         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1730
1731         /* Consider these to be the same principal, even if by a different
1732          * name.  The easy and safe way to prove this is by SID
1733          * comparison */
1734         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1735                 talloc_free(mem_ctx);
1736                 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1737         }
1738
1739         talloc_free(mem_ctx);
1740         return ret;
1741 }
1742
1743 /*
1744  * Check if a given entry may delegate to this target principal
1745  * with S4U2Proxy.
1746  */
1747 krb5_error_code
1748 samba_kdc_check_s4u2proxy(krb5_context context,
1749                           struct samba_kdc_db_context *kdc_db_ctx,
1750                           hdb_entry_ex *entry,
1751                           krb5_const_principal target_principal)
1752 {
1753         krb5_error_code ret;
1754         char *tmp = NULL;
1755         const char *client_dn = NULL;
1756         const char *target_principal_name = NULL;
1757         struct ldb_message_element *el;
1758         struct ldb_val val;
1759         unsigned int i;
1760         bool found = false;
1761         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1762
1763         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
1764
1765         if (!mem_ctx) {
1766                 ret = ENOMEM;
1767                 krb5_set_error_message(context, ret,
1768                                        "samba_kdc_check_s4u2proxy:"
1769                                        " talloc_named() failed!");
1770                 return ret;
1771         }
1772
1773         client_dn = ldb_dn_get_linearized(p->msg->dn);
1774         if (!client_dn) {
1775                 if (errno == 0) {
1776                         errno = ENOMEM;
1777                 }
1778                 ret = errno;
1779                 krb5_set_error_message(context, ret,
1780                                        "samba_kdc_check_s4u2proxy:"
1781                                        " ldb_dn_get_linearized() failed!");
1782                 return ret;
1783         }
1784
1785         /*
1786          * The main heimdal code already checked that the target_principal
1787          * belongs to the same realm as the client.
1788          *
1789          * So we just need the principal without the realm,
1790          * as that is what is configured in the "msDS-AllowedToDelegateTo"
1791          * attribute.
1792          */
1793         ret = krb5_unparse_name_flags(context, target_principal,
1794                                       KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
1795         if (ret) {
1796                 talloc_free(mem_ctx);
1797                 krb5_set_error_message(context, ret,
1798                                        "samba_kdc_check_s4u2proxy:"
1799                                        " krb5_unparse_name() failed!");
1800                 return ret;
1801         }
1802         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] for target[%s]\n",
1803                  client_dn, tmp));
1804
1805         target_principal_name = talloc_strdup(mem_ctx, tmp);
1806         SAFE_FREE(tmp);
1807         if (target_principal_name == NULL) {
1808                 ret = ENOMEM;
1809                 krb5_set_error_message(context, ret,
1810                                        "samba_kdc_check_s4u2proxy:"
1811                                        " talloc_strdup() failed!");
1812                 return ret;
1813         }
1814
1815         el = ldb_msg_find_element(p->msg, "msDS-AllowedToDelegateTo");
1816         if (el == NULL) {
1817                 goto bad_option;
1818         }
1819
1820         val = data_blob_string_const(target_principal_name);
1821
1822         for (i=0; i<el->num_values; i++) {
1823                 struct ldb_val *val1 = &val;
1824                 struct ldb_val *val2 = &el->values[i];
1825                 int cmp;
1826
1827                 if (val1->length != val2->length) {
1828                         continue;
1829                 }
1830
1831                 cmp = strncasecmp((const char *)val1->data,
1832                                   (const char *)val2->data,
1833                                   val1->length);
1834                 if (cmp != 0) {
1835                         continue;
1836                 }
1837
1838                 found = true;
1839                 break;
1840         }
1841
1842         if (!found) {
1843                 goto bad_option;
1844         }
1845
1846         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] allowed target[%s]\n",
1847                  client_dn, tmp));
1848         talloc_free(mem_ctx);
1849         return 0;
1850
1851 bad_option:
1852         krb5_set_error_message(context, ret,
1853                                "samba_kdc_check_s4u2proxy: client[%s] "
1854                                "not allowed for delegation to target[%s]",
1855                                client_dn,
1856                                target_principal_name);
1857         talloc_free(mem_ctx);
1858         return KRB5KDC_ERR_BADOPTION;
1859 }
1860
1861 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
1862                                 struct samba_kdc_db_context **kdc_db_ctx_out)
1863 {
1864         int ldb_ret;
1865         struct ldb_message *msg;
1866         struct auth_session_info *session_info;
1867         struct samba_kdc_db_context *kdc_db_ctx;
1868         /* The idea here is very simple.  Using Kerberos to
1869          * authenticate the KDC to the LDAP server is higly likely to
1870          * be circular.
1871          *
1872          * In future we may set this up to use EXERNAL and SSL
1873          * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
1874         */
1875
1876         kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
1877         if (kdc_db_ctx == NULL) {
1878                 return NT_STATUS_NO_MEMORY;
1879         }
1880         kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
1881         kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
1882
1883         /* get default kdc policy */
1884         lpcfg_default_kdc_policy(base_ctx->lp_ctx,
1885                                  &kdc_db_ctx->policy.svc_tkt_lifetime,
1886                                  &kdc_db_ctx->policy.usr_tkt_lifetime,
1887                                  &kdc_db_ctx->policy.renewal_lifetime);
1888
1889         session_info = system_session(kdc_db_ctx->lp_ctx);
1890         if (session_info == NULL) {
1891                 return NT_STATUS_INTERNAL_ERROR;
1892         }
1893
1894         /* Setup the link to LDB */
1895         kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx, base_ctx->ev_ctx,
1896                                           base_ctx->lp_ctx, session_info, 0);
1897         if (kdc_db_ctx->samdb == NULL) {
1898                 DEBUG(1, ("hdb_samba4_create: Cannot open samdb for KDC backend!"));
1899                 talloc_free(kdc_db_ctx);
1900                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1901         }
1902
1903         /* Find out our own krbtgt kvno */
1904         ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
1905         if (ldb_ret != LDB_SUCCESS) {
1906                 DEBUG(1, ("hdb_samba4_create: Cannot determine if we are an RODC in KDC backend: %s\n",
1907                           ldb_errstring(kdc_db_ctx->samdb)));
1908                 talloc_free(kdc_db_ctx);
1909                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1910         }
1911         if (kdc_db_ctx->rodc) {
1912                 int my_krbtgt_number;
1913                 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
1914                 struct ldb_dn *account_dn;
1915                 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
1916                 if (!server_dn) {
1917                         DEBUG(1, ("hdb_samba4_create: Cannot determine server DN in KDC backend: %s\n",
1918                                   ldb_errstring(kdc_db_ctx->samdb)));
1919                         talloc_free(kdc_db_ctx);
1920                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1921                 }
1922
1923                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
1924                                              "serverReference", &account_dn);
1925                 if (ldb_ret != LDB_SUCCESS) {
1926                         DEBUG(1, ("hdb_samba4_create: Cannot determine server account in KDC backend: %s\n",
1927                                   ldb_errstring(kdc_db_ctx->samdb)));
1928                         talloc_free(kdc_db_ctx);
1929                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1930                 }
1931
1932                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
1933                                              "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
1934                 talloc_free(account_dn);
1935                 if (ldb_ret != LDB_SUCCESS) {
1936                         DEBUG(1, ("hdb_samba4_create: Cannot determine RODC krbtgt account in KDC backend: %s\n",
1937                                   ldb_errstring(kdc_db_ctx->samdb)));
1938                         talloc_free(kdc_db_ctx);
1939                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1940                 }
1941
1942                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
1943                                           &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1944                                           secondary_keytab,
1945                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
1946                                           "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
1947                 if (ldb_ret != LDB_SUCCESS) {
1948                         DEBUG(1, ("hdb_samba4_create: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
1949                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
1950                                   ldb_errstring(kdc_db_ctx->samdb),
1951                                   ldb_strerror(ldb_ret)));
1952                         talloc_free(kdc_db_ctx);
1953                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1954                 }
1955                 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
1956                 if (my_krbtgt_number == -1) {
1957                         DEBUG(1, ("hdb_samba4_create: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
1958                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
1959                                   my_krbtgt_number));
1960                         talloc_free(kdc_db_ctx);
1961                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1962                 }
1963                 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
1964
1965         } else {
1966                 kdc_db_ctx->my_krbtgt_number = 0;
1967                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
1968                                           &msg,
1969                                           ldb_get_default_basedn(kdc_db_ctx->samdb),
1970                                           LDB_SCOPE_SUBTREE,
1971                                           krbtgt_attrs,
1972                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
1973                                           "(&(objectClass=user)(samAccountName=krbtgt))");
1974
1975                 if (ldb_ret != LDB_SUCCESS) {
1976                         DEBUG(1, ("samba_kdc_fetch: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
1977                         talloc_free(kdc_db_ctx);
1978                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1979                 }
1980                 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
1981                 kdc_db_ctx->my_krbtgt_number = 0;
1982                 talloc_free(msg);
1983         }
1984         *kdc_db_ctx_out = kdc_db_ctx;
1985         return NT_STATUS_OK;
1986 }