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