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