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