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