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