s4:kdc: Look up authentication policies for Kerberos clients and servers
[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 "librpc/gen_ndr/ndr_security.h"
27 #include "auth/auth.h"
28 #include "auth/auth_sam.h"
29 #include "dsdb/samdb/samdb.h"
30 #include "dsdb/common/util.h"
31 #include "librpc/gen_ndr/ndr_drsblobs.h"
32 #include "param/param.h"
33 #include "param/secrets.h"
34 #include "../lib/crypto/md4.h"
35 #include "system/kerberos.h"
36 #include "auth/kerberos/kerberos.h"
37 #include "kdc/authn_policy_util.h"
38 #include "kdc/sdb.h"
39 #include "kdc/samba_kdc.h"
40 #include "kdc/db-glue.h"
41 #include "kdc/pac-glue.h"
42 #include "librpc/gen_ndr/ndr_irpc_c.h"
43 #include "lib/messaging/irpc.h"
44
45 #undef DBGC_CLASS
46 #define DBGC_CLASS DBGC_KERBEROS
47
48 #undef strcasecmp
49 #undef strncasecmp
50
51 #define SAMBA_KVNO_GET_KRBTGT(kvno) \
52         ((uint16_t)(((uint32_t)kvno) >> 16))
53
54 #define SAMBA_KVNO_GET_VALUE(kvno) \
55         ((uint16_t)(((uint32_t)kvno) & 0xFFFF))
56
57 #define SAMBA_KVNO_AND_KRBTGT(kvno, krbtgt) \
58         ((krb5_kvno)((((uint32_t)kvno) & 0xFFFF) | \
59          ((((uint32_t)krbtgt) << 16) & 0xFFFF0000)))
60
61 enum trust_direction {
62         UNKNOWN = 0,
63         INBOUND = LSA_TRUST_DIRECTION_INBOUND,
64         OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
65 };
66
67 static const char *trust_attrs[] = {
68         "securityIdentifier",
69         "flatName",
70         "trustPartner",
71         "trustAttributes",
72         "trustDirection",
73         "trustType",
74         "msDS-TrustForestTrustInfo",
75         "trustAuthIncoming",
76         "trustAuthOutgoing",
77         "whenCreated",
78         "msDS-SupportedEncryptionTypes",
79         NULL
80 };
81
82 /*
83   send a message to the drepl server telling it to initiate a
84   REPL_SECRET getncchanges extended op to fetch the users secrets
85  */
86 static void auth_sam_trigger_repl_secret(TALLOC_CTX *mem_ctx,
87                                   struct imessaging_context *msg_ctx,
88                                   struct tevent_context *event_ctx,
89                                   struct ldb_dn *user_dn)
90 {
91         struct dcerpc_binding_handle *irpc_handle;
92         struct drepl_trigger_repl_secret r;
93         struct tevent_req *req;
94         TALLOC_CTX *tmp_ctx;
95
96         tmp_ctx = talloc_new(mem_ctx);
97         if (tmp_ctx == NULL) {
98                 return;
99         }
100
101         irpc_handle = irpc_binding_handle_by_name(tmp_ctx, msg_ctx,
102                                                   "dreplsrv",
103                                                   &ndr_table_irpc);
104         if (irpc_handle == NULL) {
105                 DEBUG(1,(__location__ ": Unable to get binding handle for dreplsrv\n"));
106                 TALLOC_FREE(tmp_ctx);
107                 return;
108         }
109
110         r.in.user_dn = ldb_dn_get_linearized(user_dn);
111
112         /*
113          * This seem to rely on the current IRPC implementation,
114          * which delivers the message in the _send function.
115          *
116          * TODO: we need a ONE_WAY IRPC handle and register
117          * a callback and wait for it to be triggered!
118          */
119         req = dcerpc_drepl_trigger_repl_secret_r_send(tmp_ctx,
120                                                       event_ctx,
121                                                       irpc_handle,
122                                                       &r);
123
124         /* we aren't interested in a reply */
125         talloc_free(req);
126         TALLOC_FREE(tmp_ctx);
127 }
128
129 static time_t ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, time_t default_val)
130 {
131     const char *tmp;
132     const char *gentime;
133     struct tm tm;
134
135     gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
136     if (!gentime)
137         return default_val;
138
139     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
140     if (tmp == NULL) {
141             return default_val;
142     }
143
144     return timegm(&tm);
145 }
146
147 static struct SDBFlags uf2SDBFlags(krb5_context context, uint32_t userAccountControl, enum samba_kdc_ent_type ent_type)
148 {
149         struct SDBFlags flags = int2SDBFlags(0);
150
151         /* we don't allow kadmin deletes */
152         flags.immutable = 1;
153
154         /* mark the principal as invalid to start with */
155         flags.invalid = 1;
156
157         flags.renewable = 1;
158
159         /* All accounts are servers, but this may be disabled again in the caller */
160         flags.server = 1;
161
162         /* Account types - clear the invalid bit if it turns out to be valid */
163         if (userAccountControl & UF_NORMAL_ACCOUNT) {
164                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
165                         flags.client = 1;
166                 }
167                 flags.invalid = 0;
168         }
169
170         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
171                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
172                         flags.client = 1;
173                 }
174                 flags.invalid = 0;
175         }
176         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
177                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
178                         flags.client = 1;
179                 }
180                 flags.invalid = 0;
181         }
182         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
183                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
184                         flags.client = 1;
185                 }
186                 flags.invalid = 0;
187         }
188
189         /* Not permitted to act as a client if disabled */
190         if (userAccountControl & UF_ACCOUNTDISABLE) {
191                 flags.client = 0;
192         }
193         if (userAccountControl & UF_LOCKOUT) {
194                 flags.locked_out = 1;
195         }
196 /*
197         if (userAccountControl & UF_PASSWD_NOTREQD) {
198                 flags.invalid = 1;
199         }
200 */
201 /*
202         UF_PASSWD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevant
203 */
204         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
205                 flags.invalid = 1;
206         }
207
208 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in samba_kdc_message2entry() */
209
210 /*
211         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
212                 flags.invalid = 1;
213         }
214 */
215         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
216                 flags.require_hwauth = 1;
217         }
218         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
219                 flags.ok_as_delegate = 1;
220         }
221         if (userAccountControl & UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION) {
222                 /*
223                  * this is confusing...
224                  *
225                  * UF_TRUSTED_FOR_DELEGATION
226                  * => ok_as_delegate
227                  *
228                  * and
229                  *
230                  * UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
231                  * => trusted_for_delegation
232                  */
233                 flags.trusted_for_delegation = 1;
234         }
235         if (!(userAccountControl & UF_NOT_DELEGATED)) {
236                 flags.forwardable = 1;
237                 flags.proxiable = 1;
238         }
239
240         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
241                 flags.require_preauth = 0;
242         } else {
243                 flags.require_preauth = 1;
244         }
245
246         if (userAccountControl & UF_NO_AUTH_DATA_REQUIRED) {
247                 flags.no_auth_data_reqd = 1;
248         }
249
250         return flags;
251 }
252
253 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
254 {
255         if (p->db_entry != NULL) {
256                 /*
257                  * A sdb_entry still has a reference
258                  */
259                 return -1;
260         }
261
262         if (p->kdc_entry != NULL) {
263                 /*
264                  * hdb_entry or krb5_db_entry still
265                  * have a reference...
266                  */
267                 return -1;
268         }
269
270         return 0;
271 }
272
273 /*
274  * Sort keys in descending order of strength.
275  *
276  * Explanaton from Greg Hudson:
277  *
278  * To encrypt tickets only the first returned key is used by the MIT KDC.  The
279  * other keys just communicate support for session key enctypes, and aren't
280  * really used.  The encryption key for the ticket enc part doesn't have
281  * to be of a type requested by the client. The session key enctype is chosen
282  * based on the client preference order, limited by the set of enctypes present
283  * in the server keys (unless the string attribute is set on the server
284  * principal overriding that set).
285  */
286
287 static int sdb_key_strength_priority(krb5_enctype etype)
288 {
289         static const krb5_enctype etype_list[] = {
290                 ENCTYPE_AES256_CTS_HMAC_SHA1_96,
291                 ENCTYPE_AES128_CTS_HMAC_SHA1_96,
292                 ENCTYPE_DES3_CBC_SHA1,
293                 ENCTYPE_ARCFOUR_HMAC,
294                 ENCTYPE_DES_CBC_MD5,
295                 ENCTYPE_DES_CBC_MD4,
296                 ENCTYPE_DES_CBC_CRC,
297                 ENCTYPE_NULL
298         };
299         int i;
300
301         for (i = 0; i < ARRAY_SIZE(etype_list); i++) {
302                 if (etype == etype_list[i]) {
303                         break;
304                 }
305         }
306
307         return ARRAY_SIZE(etype_list) - i;
308 }
309
310 static int sdb_key_strength_cmp(const struct sdb_key *k1, const struct sdb_key *k2)
311 {
312         int p1 = sdb_key_strength_priority(KRB5_KEY_TYPE(&k1->key));
313         int p2 = sdb_key_strength_priority(KRB5_KEY_TYPE(&k2->key));
314
315         if (p1 == p2) {
316                 return 0;
317         }
318
319         if (p1 > p2) {
320                 /*
321                  * Higher priority comes first
322                  */
323                 return -1;
324         } else {
325                 return 1;
326         }
327 }
328
329 static void samba_kdc_sort_keys(struct sdb_keys *keys)
330 {
331         if (keys == NULL) {
332                 return;
333         }
334
335         TYPESAFE_QSORT(keys->val, keys->len, sdb_key_strength_cmp);
336 }
337
338 int samba_kdc_set_fixed_keys(krb5_context context,
339                              const struct ldb_val *secretbuffer,
340                              uint32_t supported_enctypes,
341                              struct sdb_keys *keys)
342 {
343         uint16_t allocated_keys = 0;
344         int ret;
345
346         allocated_keys = 3;
347         keys->len = 0;
348         keys->val = calloc(allocated_keys, sizeof(struct sdb_key));
349         if (keys->val == NULL) {
350                 memset(secretbuffer->data, 0, secretbuffer->length);
351                 ret = ENOMEM;
352                 goto out;
353         }
354
355         if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
356                 struct sdb_key key = {};
357
358                 ret = smb_krb5_keyblock_init_contents(context,
359                                                       ENCTYPE_AES256_CTS_HMAC_SHA1_96,
360                                                       secretbuffer->data,
361                                                       MIN(secretbuffer->length, 32),
362                                                       &key.key);
363                 if (ret) {
364                         memset(secretbuffer->data, 0, secretbuffer->length);
365                         goto out;
366                 }
367
368                 keys->val[keys->len] = key;
369                 keys->len++;
370         }
371
372         if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
373                 struct sdb_key key = {};
374
375                 ret = smb_krb5_keyblock_init_contents(context,
376                                                       ENCTYPE_AES128_CTS_HMAC_SHA1_96,
377                                                       secretbuffer->data,
378                                                       MIN(secretbuffer->length, 16),
379                                                       &key.key);
380                 if (ret) {
381                         memset(secretbuffer->data, 0, secretbuffer->length);
382                         goto out;
383                 }
384
385                 keys->val[keys->len] = key;
386                 keys->len++;
387         }
388
389         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
390                 struct sdb_key key = {};
391
392                 ret = smb_krb5_keyblock_init_contents(context,
393                                                       ENCTYPE_ARCFOUR_HMAC,
394                                                       secretbuffer->data,
395                                                       MIN(secretbuffer->length, 16),
396                                                       &key.key);
397                 if (ret) {
398                         memset(secretbuffer->data, 0, secretbuffer->length);
399                         goto out;
400                 }
401
402                 keys->val[keys->len] = key;
403                 keys->len++;
404         }
405         ret = 0;
406 out:
407         return ret;
408 }
409
410
411 static int samba_kdc_set_random_keys(krb5_context context,
412                                      uint32_t supported_enctypes,
413                                      struct sdb_keys *keys)
414 {
415         struct ldb_val secret_val;
416         uint8_t secretbuffer[32];
417
418         /*
419          * Fake keys until we have a better way to reject
420          * non-pkinit requests.
421          *
422          * We just need to indicate which encryption types are
423          * supported.
424          */
425         generate_secret_buffer(secretbuffer, sizeof(secretbuffer));
426
427         secret_val = data_blob_const(secretbuffer,
428                                      sizeof(secretbuffer));
429         return samba_kdc_set_fixed_keys(context,
430                                         &secret_val,
431                                         supported_enctypes,
432                                         keys);
433 }
434
435 struct samba_kdc_user_keys {
436         struct sdb_keys *skeys;
437         uint32_t kvno;
438         uint32_t *returned_kvno;
439         uint32_t supported_enctypes;
440         uint32_t *available_enctypes;
441         const struct samr_Password *nthash;
442         const char *salt_string;
443         uint16_t num_pkeys;
444         const struct package_PrimaryKerberosKey4 *pkeys;
445 };
446
447 static krb5_error_code samba_kdc_fill_user_keys(krb5_context context,
448                                                 struct samba_kdc_user_keys *p)
449 {
450         /*
451          * Make sure we'll never reveal DES keys
452          */
453         uint32_t supported_enctypes = p->supported_enctypes &= ~(ENC_CRC32 | ENC_RSA_MD5);
454         uint32_t _available_enctypes = 0;
455         uint32_t *available_enctypes = p->available_enctypes;
456         uint32_t _returned_kvno = 0;
457         uint32_t *returned_kvno = p->returned_kvno;
458         uint32_t num_pkeys = p->num_pkeys;
459         uint32_t allocated_keys = num_pkeys;
460         uint32_t i;
461         int ret;
462
463         if (available_enctypes == NULL) {
464                 available_enctypes = &_available_enctypes;
465         }
466
467         *available_enctypes = 0;
468
469         if (returned_kvno == NULL) {
470                 returned_kvno = &_returned_kvno;
471         }
472
473         *returned_kvno = p->kvno;
474
475         if (p->nthash != NULL) {
476                 allocated_keys += 1;
477         }
478
479         allocated_keys = MAX(1, allocated_keys);
480
481         /* allocate space to decode into */
482         p->skeys->len = 0;
483         p->skeys->val = calloc(allocated_keys, sizeof(struct sdb_key));
484         if (p->skeys->val == NULL) {
485                 return ENOMEM;
486         }
487
488         for (i=0; i < num_pkeys; i++) {
489                 struct sdb_key key = {};
490                 uint32_t enctype_bit;
491
492                 if (p->pkeys[i].value == NULL) {
493                         continue;
494                 }
495
496                 enctype_bit = kerberos_enctype_to_bitmap(p->pkeys[i].keytype);
497                 if (!(enctype_bit & supported_enctypes)) {
498                         continue;
499                 }
500
501                 if (p->salt_string != NULL) {
502                         DATA_BLOB salt;
503
504                         salt = data_blob_string_const(p->salt_string);
505
506                         key.salt = calloc(1, sizeof(*key.salt));
507                         if (key.salt == NULL) {
508                                 ret = ENOMEM;
509                                 goto fail;
510                         }
511
512                         key.salt->type = KRB5_PW_SALT;
513
514                         ret = smb_krb5_copy_data_contents(&key.salt->salt,
515                                                           salt.data,
516                                                           salt.length);
517                         if (ret) {
518                                 ZERO_STRUCTP(key.salt);
519                                 sdb_key_free(&key);
520                                 goto fail;
521                         }
522                 }
523
524                 ret = smb_krb5_keyblock_init_contents(context,
525                                                       p->pkeys[i].keytype,
526                                                       p->pkeys[i].value->data,
527                                                       p->pkeys[i].value->length,
528                                                       &key.key);
529                 if (ret == 0) {
530                         p->skeys->val[p->skeys->len++] = key;
531                         *available_enctypes |= enctype_bit;
532                         continue;
533                 }
534                 ZERO_STRUCT(key.key);
535                 sdb_key_free(&key);
536                 if (ret == KRB5_PROG_ETYPE_NOSUPP) {
537                         DEBUG(2,("Unsupported keytype ignored - type %u\n",
538                                  p->pkeys[i].keytype));
539                         ret = 0;
540                         continue;
541                 }
542
543                 goto fail;
544         }
545
546         if (p->nthash != NULL && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
547                 struct sdb_key key = {};
548
549                 ret = smb_krb5_keyblock_init_contents(context,
550                                                       ENCTYPE_ARCFOUR_HMAC,
551                                                       p->nthash->hash,
552                                                       sizeof(p->nthash->hash),
553                                                       &key.key);
554                 if (ret == 0) {
555                         p->skeys->val[p->skeys->len++] = key;
556
557                         *available_enctypes |= ENC_RC4_HMAC_MD5;
558                 } else if (ret == KRB5_PROG_ETYPE_NOSUPP) {
559                         DEBUG(2,("Unsupported keytype ignored - type %u\n",
560                                  ENCTYPE_ARCFOUR_HMAC));
561                         ret = 0;
562                 }
563                 if (ret != 0) {
564                         goto fail;
565                 }
566         }
567
568         samba_kdc_sort_keys(p->skeys);
569
570         return 0;
571 fail:
572         sdb_keys_free(p->skeys);
573         return ret;
574 }
575
576 krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
577                                              TALLOC_CTX *mem_ctx,
578                                              const struct ldb_message *msg,
579                                              bool is_krbtgt,
580                                              bool is_rodc,
581                                              uint32_t userAccountControl,
582                                              enum samba_kdc_ent_type ent_type,
583                                              unsigned flags,
584                                              krb5_kvno requested_kvno,
585                                              struct sdb_entry *entry,
586                                              const uint32_t supported_enctypes_in,
587                                              uint32_t *supported_enctypes_out)
588 {
589         krb5_error_code ret = 0;
590         enum ndr_err_code ndr_err;
591         struct samr_Password *hash;
592         unsigned int num_ntPwdHistory = 0;
593         struct samr_Password *ntPwdHistory = NULL;
594         struct samr_Password *old_hash = NULL;
595         struct samr_Password *older_hash = NULL;
596         const struct ldb_val *sc_val;
597         struct supplementalCredentialsBlob scb;
598         struct supplementalCredentialsPackage *scpk = NULL;
599         struct package_PrimaryKerberosBlob _pkb;
600         struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
601         int krbtgt_number = 0;
602         uint32_t current_kvno;
603         uint32_t old_kvno = 0;
604         uint32_t older_kvno = 0;
605         uint32_t returned_kvno = 0;
606         uint16_t i;
607         struct samba_kdc_user_keys keys = { .num_pkeys = 0, };
608         struct samba_kdc_user_keys old_keys = { .num_pkeys = 0, };
609         struct samba_kdc_user_keys older_keys = { .num_pkeys = 0, };
610         uint32_t available_enctypes = 0;
611         uint32_t supported_enctypes = supported_enctypes_in;
612
613         *supported_enctypes_out = 0;
614
615         /* Is this the krbtgt or a RODC krbtgt */
616         if (is_rodc) {
617                 krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
618
619                 if (krbtgt_number == -1) {
620                         return EINVAL;
621                 }
622                 if (krbtgt_number == 0) {
623                         return EINVAL;
624                 }
625         }
626
627         if ((ent_type == SAMBA_KDC_ENT_TYPE_CLIENT)
628             && (userAccountControl & UF_SMARTCARD_REQUIRED)) {
629                 ret = samba_kdc_set_random_keys(context,
630                                                 supported_enctypes,
631                                                 &entry->keys);
632
633                 *supported_enctypes_out = supported_enctypes & ENC_ALL_TYPES;
634
635                 goto out;
636         }
637
638         current_kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
639         if (current_kvno > 1) {
640                 old_kvno = current_kvno - 1;
641         }
642         if (current_kvno > 2) {
643                 older_kvno = current_kvno - 2;
644         }
645         if (is_krbtgt) {
646                 /*
647                  * Even for the main krbtgt account
648                  * we have to strictly split the kvno into
649                  * two 16-bit parts and the upper 16-bit
650                  * need to be all zero, even if
651                  * the msDS-KeyVersionNumber has a value
652                  * larger than 65535.
653                  *
654                  * See https://bugzilla.samba.org/show_bug.cgi?id=14951
655                  */
656                 current_kvno = SAMBA_KVNO_GET_VALUE(current_kvno);
657                 old_kvno = SAMBA_KVNO_GET_VALUE(old_kvno);
658                 older_kvno = SAMBA_KVNO_GET_VALUE(older_kvno);
659                 requested_kvno = SAMBA_KVNO_GET_VALUE(requested_kvno);
660         }
661
662         /* Get keys from the db */
663
664         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
665         num_ntPwdHistory = samdb_result_hashes(mem_ctx, msg,
666                                                "ntPwdHistory",
667                                                &ntPwdHistory);
668         if (num_ntPwdHistory > 1) {
669                 old_hash = &ntPwdHistory[1];
670         }
671         if (num_ntPwdHistory > 2) {
672                 older_hash = &ntPwdHistory[1];
673         }
674         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
675
676         /* supplementalCredentials if present */
677         if (sc_val) {
678                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
679                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
680                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
681                         dump_data(0, sc_val->data, sc_val->length);
682                         ret = EINVAL;
683                         goto out;
684                 }
685
686                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
687                         if (scb.sub.num_packages != 0) {
688                                 NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
689                                 ret = EINVAL;
690                                 goto out;
691                         }
692                 }
693
694                 for (i=0; i < scb.sub.num_packages; i++) {
695                         if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
696                                 scpk = &scb.sub.packages[i];
697                                 if (!scpk->data || !scpk->data[0]) {
698                                         scpk = NULL;
699                                         continue;
700                                 }
701                                 break;
702                         }
703                 }
704         }
705         /*
706          * Primary:Kerberos-Newer-Keys element
707          * of supplementalCredentials
708          *
709          * The legacy Primary:Kerberos only contains
710          * single DES keys, which are completely ignored
711          * now.
712          */
713         if (scpk) {
714                 DATA_BLOB blob;
715
716                 blob = strhex_to_data_blob(mem_ctx, scpk->data);
717                 if (!blob.data) {
718                         ret = ENOMEM;
719                         goto out;
720                 }
721
722                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
723                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
724                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
725                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
726                         ret = EINVAL;
727                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
728                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
729                         goto out;
730                 }
731
732                 if (_pkb.version != 4) {
733                         ret = EINVAL;
734                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
735                         krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
736                         goto out;
737                 }
738
739                 pkb4 = &_pkb.ctr.ctr4;
740         }
741
742         keys = (struct samba_kdc_user_keys) {
743                 .kvno = current_kvno,
744                 .supported_enctypes = supported_enctypes,
745                 .nthash = hash,
746                 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
747                 .num_pkeys = pkb4 != NULL ? pkb4->num_keys : 0,
748                 .pkeys = pkb4 != NULL ? pkb4->keys : NULL,
749         };
750
751         old_keys = (struct samba_kdc_user_keys) {
752                 .kvno = old_kvno,
753                 .supported_enctypes = supported_enctypes,
754                 .nthash = old_hash,
755                 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
756                 .num_pkeys = pkb4 != NULL ? pkb4->num_old_keys : 0,
757                 .pkeys = pkb4 != NULL ? pkb4->old_keys : NULL,
758         };
759         older_keys = (struct samba_kdc_user_keys) {
760                 .kvno = older_kvno,
761                 .supported_enctypes = supported_enctypes,
762                 .nthash = older_hash,
763                 .salt_string = pkb4 != NULL ? pkb4->salt.string : NULL,
764                 .num_pkeys = pkb4 != NULL ? pkb4->num_older_keys : 0,
765                 .pkeys = pkb4 != NULL ? pkb4->older_keys : NULL,
766         };
767
768         if (flags & SDB_F_KVNO_SPECIFIED) {
769                 if (requested_kvno == keys.kvno) {
770                         /*
771                          * The current kvno was requested,
772                          * so we return it.
773                          */
774                         keys.skeys = &entry->keys;
775                         keys.available_enctypes = &available_enctypes;
776                         keys.returned_kvno = &returned_kvno;
777                 } else if (requested_kvno == 0) {
778                         /*
779                          * don't return any keys
780                          */
781                 } else if (requested_kvno == old_keys.kvno) {
782                         /*
783                          * return the old keys as default keys
784                          * with the requested kvno.
785                          */
786                         old_keys.skeys = &entry->keys;
787                         old_keys.available_enctypes = &available_enctypes;
788                         old_keys.returned_kvno = &returned_kvno;
789                 } else if (requested_kvno == older_keys.kvno) {
790                         /*
791                          * return the older keys as default keys
792                          * with the requested kvno.
793                          */
794                         older_keys.skeys = &entry->keys;
795                         older_keys.available_enctypes = &available_enctypes;
796                         older_keys.returned_kvno = &returned_kvno;
797                 } else {
798                         /*
799                          * don't return any keys
800                          */
801                 }
802         } else {
803                 bool include_history = false;
804
805                 if ((flags & SDB_F_GET_CLIENT) && (flags & SDB_F_FOR_AS_REQ)) {
806                         include_history = true;
807                 } else if (flags & SDB_F_ADMIN_DATA) {
808                         include_history = true;
809                 }
810
811                 keys.skeys = &entry->keys;
812                 keys.available_enctypes = &available_enctypes;
813                 keys.returned_kvno = &returned_kvno;
814
815                 if (include_history && old_keys.kvno != 0) {
816                         old_keys.skeys = &entry->old_keys;
817                 }
818                 if (include_history && older_keys.kvno != 0) {
819                         older_keys.skeys = &entry->older_keys;
820                 }
821         }
822
823         if (keys.skeys != NULL) {
824                 ret = samba_kdc_fill_user_keys(context, &keys);
825                 if (ret != 0) {
826                         goto out;
827                 }
828         }
829
830         if (old_keys.skeys != NULL) {
831                 ret = samba_kdc_fill_user_keys(context, &old_keys);
832                 if (ret != 0) {
833                         goto out;
834                 }
835         }
836
837         if (older_keys.skeys != NULL) {
838                 ret = samba_kdc_fill_user_keys(context, &older_keys);
839                 if (ret != 0) {
840                         goto out;
841                 }
842         }
843
844         *supported_enctypes_out |= available_enctypes;
845
846         if (is_krbtgt) {
847                 /*
848                  * Even for the main krbtgt account
849                  * we have to strictly split the kvno into
850                  * two 16-bit parts and the upper 16-bit
851                  * need to be all zero, even if
852                  * the msDS-KeyVersionNumber has a value
853                  * larger than 65535.
854                  *
855                  * See https://bugzilla.samba.org/show_bug.cgi?id=14951
856                  */
857                 returned_kvno = SAMBA_KVNO_AND_KRBTGT(returned_kvno, krbtgt_number);
858         }
859         entry->kvno = returned_kvno;
860
861 out:
862         return ret;
863 }
864
865 static int principal_comp_strcmp_int(krb5_context context,
866                                      krb5_const_principal principal,
867                                      unsigned int component,
868                                      const char *string,
869                                      bool do_strcasecmp)
870 {
871         const char *p;
872
873 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
874         p = krb5_principal_get_comp_string(context, principal, component);
875         if (p == NULL) {
876                 return -1;
877         }
878         if (do_strcasecmp) {
879                 return strcasecmp(p, string);
880         } else {
881                 return strcmp(p, string);
882         }
883 #else
884         size_t len;
885         krb5_data *d;
886         if (component >= krb5_princ_size(context, principal)) {
887                 return -1;
888         }
889
890         d = krb5_princ_component(context, principal, component);
891         if (d == NULL) {
892                 return -1;
893         }
894
895         p = d->data;
896
897         len = strlen(string);
898
899         /*
900          * We explicitly return -1 or 1. Subtracting of the two lengths might
901          * give the wrong result if the result overflows or loses data when
902          * narrowed to int.
903          */
904         if (d->length < len) {
905                 return -1;
906         } else if (d->length > len) {
907                 return 1;
908         }
909
910         if (do_strcasecmp) {
911                 return strncasecmp(p, string, len);
912         } else {
913                 return memcmp(p, string, len);
914         }
915 #endif
916 }
917
918 static int principal_comp_strcasecmp(krb5_context context,
919                                      krb5_const_principal principal,
920                                      unsigned int component,
921                                      const char *string)
922 {
923         return principal_comp_strcmp_int(context, principal,
924                                          component, string, true);
925 }
926
927 static int principal_comp_strcmp(krb5_context context,
928                                  krb5_const_principal principal,
929                                  unsigned int component,
930                                  const char *string)
931 {
932         return principal_comp_strcmp_int(context, principal,
933                                          component, string, false);
934 }
935
936 static bool is_kadmin_changepw(krb5_context context,
937                                krb5_const_principal principal)
938 {
939         return krb5_princ_size(context, principal) == 2 &&
940                 (principal_comp_strcmp(context, principal, 0, "kadmin") == 0) &&
941                 (principal_comp_strcmp(context, principal, 1, "changepw") == 0);
942 }
943
944 static krb5_error_code samba_kdc_get_entry_principal(
945                 krb5_context context,
946                 struct samba_kdc_db_context *kdc_db_ctx,
947                 const char *samAccountName,
948                 enum samba_kdc_ent_type ent_type,
949                 unsigned flags,
950                 bool is_kadmin_changepw,
951                 krb5_const_principal in_princ,
952                 krb5_principal *out_princ)
953 {
954         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
955         krb5_error_code code = 0;
956         bool canon = flags & (SDB_F_CANON|SDB_F_FORCE_CANON);
957
958         /*
959          * If we are set to canonicalize, we get back the fixed UPPER
960          * case realm, and the real username (ie matching LDAP
961          * samAccountName)
962          *
963          * Otherwise, if we are set to enterprise, we
964          * get back the whole principal as-sent
965          *
966          * Finally, if we are not set to canonicalize, we get back the
967          * fixed UPPER case realm, but the as-sent username
968          */
969
970         /*
971          * We need to ensure that the kadmin/changepw principal isn't able to
972          * issue krbtgt tickets, even if canonicalization is turned on.
973          */
974         if (!is_kadmin_changepw) {
975                 if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT && canon) {
976                         /*
977                          * When requested to do so, ensure that the
978                          * both realm values in the principal are set
979                          * to the upper case, canonical realm
980                          */
981                         code = smb_krb5_make_principal(context,
982                                                        out_princ,
983                                                        lpcfg_realm(lp_ctx),
984                                                        "krbtgt",
985                                                        lpcfg_realm(lp_ctx),
986                                                        NULL);
987                         if (code != 0) {
988                                 return code;
989                         }
990                         smb_krb5_principal_set_type(context,
991                                                     *out_princ,
992                                                     KRB5_NT_SRV_INST);
993
994                         return 0;
995                 }
996
997                 if ((canon && flags & (SDB_F_FORCE_CANON|SDB_F_FOR_AS_REQ)) ||
998                     (ent_type == SAMBA_KDC_ENT_TYPE_ANY && in_princ == NULL)) {
999                         /*
1000                          * SDB_F_CANON maps from the canonicalize flag in the
1001                          * packet, and has a different meaning between AS-REQ
1002                          * and TGS-REQ.  We only change the principal in the
1003                          * AS-REQ case.
1004                          *
1005                          * The SDB_F_FORCE_CANON if for new MIT KDC code that
1006                          * wants the canonical name in all lookups, and takes
1007                          * care to canonicalize only when appropriate.
1008                          */
1009                         code = smb_krb5_make_principal(context,
1010                                                       out_princ,
1011                                                       lpcfg_realm(lp_ctx),
1012                                                       samAccountName,
1013                                                       NULL);
1014                         return code;
1015                 }
1016         }
1017
1018         /*
1019          * For a krbtgt entry, this appears to be required regardless of the
1020          * canonicalize flag from the client.
1021          */
1022         code = krb5_copy_principal(context, in_princ, out_princ);
1023         if (code != 0) {
1024                 return code;
1025         }
1026
1027         /*
1028          * While we have copied the client principal, tests show that Win2k3
1029          * returns the 'corrected' realm, not the client-specified realm.  This
1030          * code attempts to replace the client principal's realm with the one
1031          * we determine from our records
1032          */
1033         code = smb_krb5_principal_set_realm(context,
1034                                             *out_princ,
1035                                             lpcfg_realm(lp_ctx));
1036
1037         return code;
1038 }
1039
1040 /*
1041  * Construct an hdb_entry from a directory entry.
1042  */
1043 static krb5_error_code samba_kdc_message2entry(krb5_context context,
1044                                                struct samba_kdc_db_context *kdc_db_ctx,
1045                                                TALLOC_CTX *mem_ctx,
1046                                                krb5_const_principal principal,
1047                                                enum samba_kdc_ent_type ent_type,
1048                                                unsigned flags,
1049                                                krb5_kvno kvno,
1050                                                struct ldb_dn *realm_dn,
1051                                                struct ldb_message *msg,
1052                                                struct sdb_entry *entry)
1053 {
1054         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1055         uint32_t userAccountControl;
1056         uint32_t msDS_User_Account_Control_Computed;
1057         krb5_error_code ret = 0;
1058         krb5_boolean is_computer = FALSE;
1059         struct samba_kdc_entry *p;
1060         NTTIME acct_expiry;
1061         NTSTATUS status;
1062         bool protected_user = false;
1063         uint32_t rid;
1064         bool is_krbtgt = false;
1065         bool is_rodc = false;
1066         bool force_rc4 = lpcfg_kdc_force_enable_rc4_weak_session_keys(lp_ctx);
1067         struct ldb_message_element *objectclasses;
1068         struct ldb_val computer_val = data_blob_string_const("computer");
1069         uint32_t config_default_supported_enctypes = lpcfg_kdc_default_domain_supported_enctypes(lp_ctx);
1070         uint32_t default_supported_enctypes =
1071                 config_default_supported_enctypes != 0 ?
1072                 config_default_supported_enctypes :
1073                 ENC_RC4_HMAC_MD5 | ENC_HMAC_SHA1_96_AES256_SK;
1074         uint32_t supported_enctypes
1075                 = ldb_msg_find_attr_as_uint(msg,
1076                                             "msDS-SupportedEncryptionTypes",
1077                                             default_supported_enctypes);
1078         uint32_t pa_supported_enctypes;
1079         uint32_t supported_session_etypes;
1080         uint32_t available_enctypes = 0;
1081         /*
1082          * also lagacy enctypes are announced,
1083          * but effectively restricted by kdc_enctypes
1084          */
1085         uint32_t domain_enctypes = ENC_RC4_HMAC_MD5 | ENC_RSA_MD5 | ENC_CRC32;
1086         uint32_t config_kdc_enctypes = lpcfg_kdc_supported_enctypes(lp_ctx);
1087         uint32_t kdc_enctypes =
1088                 config_kdc_enctypes != 0 ?
1089                 config_kdc_enctypes :
1090                 ENC_ALL_TYPES;
1091         const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
1092
1093         const struct authn_kerberos_client_policy *authn_client_policy = NULL;
1094         const struct authn_server_policy *authn_server_policy = NULL;
1095
1096         ZERO_STRUCTP(entry);
1097
1098         if (supported_enctypes == 0) {
1099                 supported_enctypes = default_supported_enctypes;
1100         }
1101
1102         if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1103                 domain_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
1104         }
1105
1106         if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
1107                 is_rodc = true;
1108         }
1109
1110         if (!samAccountName) {
1111                 ret = ENOENT;
1112                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
1113                 goto out;
1114         }
1115
1116         objectclasses = ldb_msg_find_element(msg, "objectClass");
1117
1118         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
1119                 is_computer = TRUE;
1120         }
1121
1122         p = talloc_zero(mem_ctx, struct samba_kdc_entry);
1123         if (!p) {
1124                 ret = ENOMEM;
1125                 goto out;
1126         }
1127
1128         p->is_rodc = is_rodc;
1129         p->kdc_db_ctx = kdc_db_ctx;
1130         p->realm_dn = talloc_reference(p, realm_dn);
1131         if (!p->realm_dn) {
1132                 ret = ENOMEM;
1133                 goto out;
1134         }
1135
1136         talloc_set_destructor(p, samba_kdc_entry_destructor);
1137
1138         entry->skdc_entry = p;
1139
1140         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
1141
1142         msDS_User_Account_Control_Computed
1143                 = ldb_msg_find_attr_as_uint(msg,
1144                                             "msDS-User-Account-Control-Computed",
1145                                             UF_ACCOUNTDISABLE);
1146
1147         /*
1148          * This brings in the lockout flag, block the account if not
1149          * found.  We need the weird UF_ACCOUNTDISABLE check because
1150          * we do not want to fail open if the value is not returned,
1151          * but 0 is a valid value (all OK)
1152          */
1153         if (msDS_User_Account_Control_Computed == UF_ACCOUNTDISABLE) {
1154                 ret = EINVAL;
1155                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: "
1156                                 "no msDS-User-Account-Control-Computed present");
1157                 goto out;
1158         } else {
1159                 userAccountControl |= msDS_User_Account_Control_Computed;
1160         }
1161
1162         if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) {
1163                 p->is_krbtgt = true;
1164         }
1165
1166         /* First try and figure out the flags based on the userAccountControl */
1167         entry->flags = uf2SDBFlags(context, userAccountControl, ent_type);
1168
1169         /*
1170          * Take control of the returned principal here, rather than
1171          * allowing the Heimdal code to do it as we have specific
1172          * behaviour around the forced realm to honour
1173          */
1174         entry->flags.force_canonicalize = true;
1175
1176         /* Windows 2008 seems to enforce this (very sensible) rule by
1177          * default - don't allow offline attacks on a user's password
1178          * by asking for a ticket to them as a service (encrypted with
1179          * their probably patheticly insecure password) */
1180
1181         if (entry->flags.server
1182             && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
1183                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
1184                         entry->flags.server = 0;
1185                 }
1186         }
1187
1188         /*
1189          * We restrict a 3-part SPN ending in my domain/realm to full
1190          * domain controllers.
1191          *
1192          * This avoids any cases where (eg) a demoted DC still has
1193          * these more restricted SPNs.
1194          */
1195         if (krb5_princ_size(context, principal) > 2) {
1196                 char *third_part
1197                         = smb_krb5_principal_get_comp_string(mem_ctx,
1198                                                              context,
1199                                                              principal,
1200                                                              2);
1201                 bool is_our_realm =
1202                          lpcfg_is_my_domain_or_realm(lp_ctx,
1203                                                      third_part);
1204                 bool is_dc = userAccountControl &
1205                         (UF_SERVER_TRUST_ACCOUNT | UF_PARTIAL_SECRETS_ACCOUNT);
1206                 if (is_our_realm && !is_dc) {
1207                         entry->flags.server = 0;
1208                 }
1209         }
1210         /*
1211          * To give the correct type of error to the client, we must
1212          * not just return the entry without .server set, we must
1213          * pretend the principal does not exist.  Otherwise we may
1214          * return ERR_POLICY instead of
1215          * KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN
1216          */
1217         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && entry->flags.server == 0) {
1218                 ret = SDB_ERR_NOENTRY;
1219                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no servicePrincipalName present for this server, refusing with no-such-entry");
1220                 goto out;
1221         }
1222         if (flags & SDB_F_ADMIN_DATA) {
1223                 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
1224                  * of the Heimdal KDC.  They are stored in a the traditional
1225                  * DB for audit purposes, and still form part of the structure
1226                  * we must return */
1227
1228                 /* use 'whenCreated' */
1229                 entry->created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1230                 /* use 'kadmin' for now (needed by mit_samba) */
1231
1232                 ret = smb_krb5_make_principal(context,
1233                                               &entry->created_by.principal,
1234                                               lpcfg_realm(lp_ctx), "kadmin", NULL);
1235                 if (ret) {
1236                         krb5_clear_error_message(context);
1237                         goto out;
1238                 }
1239
1240                 entry->modified_by = (struct sdb_event *) malloc(sizeof(struct sdb_event));
1241                 if (entry->modified_by == NULL) {
1242                         ret = ENOMEM;
1243                         krb5_set_error_message(context, ret, "malloc: out of memory");
1244                         goto out;
1245                 }
1246
1247                 /* use 'whenChanged' */
1248                 entry->modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
1249                 /* use 'kadmin' for now (needed by mit_samba) */
1250                 ret = smb_krb5_make_principal(context,
1251                                               &entry->modified_by->principal,
1252                                               lpcfg_realm(lp_ctx), "kadmin", NULL);
1253                 if (ret) {
1254                         krb5_clear_error_message(context);
1255                         goto out;
1256                 }
1257         }
1258
1259
1260         /* The lack of password controls etc applies to krbtgt by
1261          * virtue of being that particular RID */
1262         status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
1263
1264         if (!NT_STATUS_IS_OK(status)) {
1265                 ret = EINVAL;
1266                 goto out;
1267         }
1268
1269         if (rid == DOMAIN_RID_KRBTGT) {
1270                 char *realm = NULL;
1271
1272                 entry->valid_end = NULL;
1273                 entry->pw_end = NULL;
1274
1275                 entry->flags.invalid = 0;
1276                 entry->flags.server = 1;
1277
1278                 realm = smb_krb5_principal_get_realm(
1279                         mem_ctx, context, principal);
1280                 if (realm == NULL) {
1281                         ret = ENOMEM;
1282                         goto out;
1283                 }
1284
1285                 /* Don't mark all requests for the krbtgt/realm as
1286                  * 'change password', as otherwise we could get into
1287                  * trouble, and not enforce the password expirty.
1288                  * Instead, only do it when request is for the kpasswd service */
1289                 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER &&
1290                     is_kadmin_changepw(context, principal) &&
1291                     lpcfg_is_my_domain_or_realm(lp_ctx, realm)) {
1292                         entry->flags.change_pw = 1;
1293                 }
1294
1295                 TALLOC_FREE(realm);
1296
1297                 entry->flags.client = 0;
1298                 entry->flags.forwardable = 1;
1299                 entry->flags.ok_as_delegate = 1;
1300         } else if (is_rodc) {
1301                 /* The RODC krbtgt account is like the main krbtgt,
1302                  * but it does not have a changepw or kadmin
1303                  * service */
1304
1305                 entry->valid_end = NULL;
1306                 entry->pw_end = NULL;
1307
1308                 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
1309                 entry->flags.client = 0;
1310                 entry->flags.invalid = 0;
1311                 entry->flags.server = 1;
1312
1313                 entry->flags.client = 0;
1314                 entry->flags.forwardable = 1;
1315                 entry->flags.ok_as_delegate = 0;
1316         } else if (entry->flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1317                 /* The account/password expiry only applies when the account is used as a
1318                  * client (ie password login), not when used as a server */
1319
1320                 /* Make very well sure we don't use this for a client,
1321                  * it could bypass the password restrictions */
1322                 entry->flags.client = 0;
1323
1324                 entry->valid_end = NULL;
1325                 entry->pw_end = NULL;
1326
1327         } else {
1328                 NTTIME must_change_time
1329                         = samdb_result_nttime(msg,
1330                                         "msDS-UserPasswordExpiryTimeComputed",
1331                                         0);
1332                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
1333                         entry->pw_end = NULL;
1334                 } else {
1335                         entry->pw_end = malloc(sizeof(*entry->pw_end));
1336                         if (entry->pw_end == NULL) {
1337                                 ret = ENOMEM;
1338                                 goto out;
1339                         }
1340                         *entry->pw_end = nt_time_to_unix(must_change_time);
1341                 }
1342
1343                 acct_expiry = samdb_result_account_expires(msg);
1344                 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
1345                         entry->valid_end = NULL;
1346                 } else {
1347                         entry->valid_end = malloc(sizeof(*entry->valid_end));
1348                         if (entry->valid_end == NULL) {
1349                                 ret = ENOMEM;
1350                                 goto out;
1351                         }
1352                         *entry->valid_end = nt_time_to_unix(acct_expiry);
1353                 }
1354         }
1355
1356         ret = samba_kdc_get_entry_principal(context,
1357                                             kdc_db_ctx,
1358                                             samAccountName,
1359                                             ent_type,
1360                                             flags,
1361                                             entry->flags.change_pw,
1362                                             principal,
1363                                             &entry->principal);
1364         if (ret != 0) {
1365                 krb5_clear_error_message(context);
1366                 goto out;
1367         }
1368
1369         entry->valid_start = NULL;
1370
1371         entry->max_life = malloc(sizeof(*entry->max_life));
1372         if (entry->max_life == NULL) {
1373                 ret = ENOMEM;
1374                 goto out;
1375         }
1376
1377         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1378                 *entry->max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
1379         } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
1380                 *entry->max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
1381         } else {
1382                 *entry->max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
1383                                                 kdc_db_ctx->policy.usr_tkt_lifetime);
1384         }
1385
1386         if (entry->flags.change_pw) {
1387                 /* Limit lifetime of kpasswd tickets to two minutes or less. */
1388                 *entry->max_life = MIN(*entry->max_life, CHANGEPW_LIFETIME);
1389         }
1390
1391         entry->max_renew = malloc(sizeof(*entry->max_renew));
1392         if (entry->max_renew == NULL) {
1393                 ret = ENOMEM;
1394                 goto out;
1395         }
1396
1397         *entry->max_renew = kdc_db_ctx->policy.renewal_lifetime;
1398
1399         /*
1400          * A principal acting as a client that is not being looked up as the
1401          * principal of an armor ticket may have an authentication policy apply
1402          * to it.
1403          */
1404         if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT &&
1405             (flags & SDB_F_FOR_AS_REQ) &&
1406             !(flags & SDB_F_ARMOR_PRINCIPAL))
1407         {
1408                 ret = authn_policy_kerberos_client(kdc_db_ctx->samdb, mem_ctx, msg,
1409                                                    &authn_client_policy);
1410                 if (ret) {
1411                         goto out;
1412                 }
1413         }
1414
1415         /*
1416          * A principal acting as a server may have an authentication policy
1417          * apply to it.
1418          */
1419         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1420                 ret = authn_policy_server(kdc_db_ctx->samdb, mem_ctx, msg,
1421                                           &authn_server_policy);
1422                 if (ret) {
1423                         goto out;
1424                 }
1425         }
1426
1427         if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT && (flags & SDB_F_FOR_AS_REQ)) {
1428                 int result;
1429                 const struct auth_user_info_dc *user_info_dc = NULL;
1430                 /*
1431                  * These protections only apply to clients, so servers in the
1432                  * Protected Users group may still have service tickets to them
1433                  * encrypted with RC4. For accounts looked up as servers, note
1434                  * that 'msg' does not contain the 'memberOf' attribute for
1435                  * determining whether the account is a member of Protected
1436                  * Users.
1437                  *
1438                  * Additionally, Microsoft advises that accounts for services
1439                  * and computers should never be members of Protected Users, or
1440                  * they may fail to authenticate.
1441                  */
1442                 status = samba_kdc_get_user_info_from_db(p, msg, &user_info_dc);
1443                 if (!NT_STATUS_IS_OK(status)) {
1444                         ret = EINVAL;
1445                         goto out;
1446                 }
1447
1448                 result = dsdb_is_protected_user(kdc_db_ctx->samdb,
1449                                                 user_info_dc->sids,
1450                                                 user_info_dc->num_sids);
1451                 if (result == -1) {
1452                         ret = EINVAL;
1453                         goto out;
1454                 }
1455
1456                 protected_user = result;
1457
1458                 if (protected_user) {
1459                         *entry->max_life = MIN(*entry->max_life, 4 * 60 * 60);
1460                         *entry->max_renew = MIN(*entry->max_renew, 4 * 60 * 60);
1461
1462                         entry->flags.forwardable = 0;
1463                         entry->flags.proxiable = 0;
1464                 }
1465         }
1466
1467         if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
1468                 bool enable_fast;
1469
1470                 is_krbtgt = true;
1471
1472                 /*
1473                  * KDCs (and KDCs on RODCs)
1474                  * ignore msDS-SupportedEncryptionTypes completely
1475                  * but support all supported enctypes by the domain.
1476                  */
1477                 supported_enctypes = domain_enctypes;
1478
1479                 enable_fast = lpcfg_kdc_enable_fast(kdc_db_ctx->lp_ctx);
1480                 if (enable_fast) {
1481                         supported_enctypes |= ENC_FAST_SUPPORTED;
1482                 }
1483
1484                 supported_enctypes |= ENC_CLAIMS_SUPPORTED;
1485                 supported_enctypes |= ENC_COMPOUND_IDENTITY_SUPPORTED;
1486
1487                 /*
1488                  * Resource SID compression is enabled implicitly, unless
1489                  * disabled in msDS-SupportedEncryptionTypes.
1490                  */
1491
1492         } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
1493                 /*
1494                  * DCs and RODCs computer accounts take
1495                  * msDS-SupportedEncryptionTypes unmodified, but
1496                  * force all enctypes supported by the domain.
1497                  */
1498                 supported_enctypes |= domain_enctypes;
1499
1500         } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
1501                    (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
1502                 /*
1503                  * for AS-REQ the client chooses the enc types it
1504                  * supports, and this will vary between computers a
1505                  * user logs in from. Therefore, so that we accept any
1506                  * of the client's keys for decrypting padata,
1507                  * supported_enctypes should not restrict etype usage.
1508                  *
1509                  * likewise for 'any' return as much as is supported,
1510                  * to export into a keytab.
1511                  */
1512                 supported_enctypes |= ENC_ALL_TYPES;
1513         }
1514
1515         /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
1516         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
1517                 supported_enctypes &= ~ENC_ALL_TYPES;
1518         }
1519
1520         if (protected_user) {
1521                 supported_enctypes &= ~ENC_RC4_HMAC_MD5;
1522         }
1523
1524         pa_supported_enctypes = supported_enctypes;
1525         supported_session_etypes = supported_enctypes;
1526         if (supported_session_etypes & ENC_HMAC_SHA1_96_AES256_SK) {
1527                 supported_session_etypes |= ENC_HMAC_SHA1_96_AES256;
1528                 supported_session_etypes |= ENC_HMAC_SHA1_96_AES128;
1529         }
1530         if (force_rc4) {
1531                 supported_session_etypes |= ENC_RC4_HMAC_MD5;
1532         }
1533         /*
1534          * now that we remembered what to announce in pa_supported_enctypes
1535          * and normalized ENC_HMAC_SHA1_96_AES256_SK, we restrict the
1536          * rest to the enc types the local kdc supports.
1537          */
1538         supported_enctypes &= kdc_enctypes;
1539         supported_session_etypes &= kdc_enctypes;
1540
1541         /* Get keys from the db */
1542         ret = samba_kdc_message2entry_keys(context, p, msg,
1543                                            is_krbtgt, is_rodc,
1544                                            userAccountControl,
1545                                            ent_type, flags, kvno, entry,
1546                                            supported_enctypes,
1547                                            &available_enctypes);
1548         if (ret) {
1549                 /* Could be bogus data in the entry, or out of memory */
1550                 goto out;
1551         }
1552
1553         /*
1554          * If we only have a nthash stored,
1555          * but a better session key would be
1556          * available, we fallback to fetching the
1557          * RC4_HMAC_MD5, which implicitly also
1558          * would allow an RC4_HMAC_MD5 session key.
1559          * But only if the kdc actually supports
1560          * RC4_HMAC_MD5.
1561          */
1562         if (available_enctypes == 0 &&
1563             (supported_enctypes & ENC_RC4_HMAC_MD5) == 0 &&
1564             (supported_enctypes & ~ENC_RC4_HMAC_MD5) != 0 &&
1565             (kdc_enctypes & ENC_RC4_HMAC_MD5) != 0)
1566         {
1567                 supported_enctypes = ENC_RC4_HMAC_MD5;
1568                 ret = samba_kdc_message2entry_keys(context, p, msg,
1569                                                    is_krbtgt, is_rodc,
1570                                                    userAccountControl,
1571                                                    ent_type, flags, kvno, entry,
1572                                                    supported_enctypes,
1573                                                    &available_enctypes);
1574                 if (ret) {
1575                         /* Could be bogus data in the entry, or out of memory */
1576                         goto out;
1577                 }
1578         }
1579
1580         /*
1581          * We need to support all session keys enctypes for
1582          * all keys we provide
1583          */
1584         supported_session_etypes |= available_enctypes;
1585
1586         ret = sdb_entry_set_etypes(entry);
1587         if (ret) {
1588                 goto out;
1589         }
1590
1591         if (entry->flags.server) {
1592                 bool add_aes256 =
1593                         supported_session_etypes & KERB_ENCTYPE_AES256_CTS_HMAC_SHA1_96;
1594                 bool add_aes128 =
1595                         supported_session_etypes & KERB_ENCTYPE_AES128_CTS_HMAC_SHA1_96;
1596                 bool add_rc4 =
1597                         supported_session_etypes & ENC_RC4_HMAC_MD5;
1598                 ret = sdb_entry_set_session_etypes(entry,
1599                                                    add_aes256,
1600                                                    add_aes128,
1601                                                    add_rc4);
1602                 if (ret) {
1603                         goto out;
1604                 }
1605         }
1606
1607         if (entry->keys.len != 0) {
1608                 /*
1609                  * FIXME: Currently limited to Heimdal so as not to
1610                  * break MIT KDCs, for which no fix is available.
1611                  */
1612 #ifdef SAMBA4_USES_HEIMDAL
1613                 if (is_krbtgt) {
1614                         /*
1615                          * The krbtgt account, having no reason to
1616                          * issue tickets encrypted in weaker keys,
1617                          * shall only make available its strongest
1618                          * key. All weaker keys are stripped out. This
1619                          * makes it impossible for an RC4-encrypted
1620                          * TGT to be accepted when AES KDC keys exist.
1621                          *
1622                          * This controls the ticket key and so the PAC
1623                          * signature algorithms indirectly, preventing
1624                          * a weak KDC checksum from being accepted
1625                          * when we verify the signatures for an
1626                          * S4U2Proxy evidence ticket. As such, this is
1627                          * indispensable for addressing
1628                          * CVE-2022-37966.
1629                          *
1630                          * Being strict here also provides protection
1631                          * against possible future attacks on weak
1632                          * keys.
1633                          */
1634                         entry->keys.len = 1;
1635                         if (entry->etypes != NULL) {
1636                                 entry->etypes->len = 1;
1637                         }
1638                         entry->old_keys.len = MIN(entry->old_keys.len, 1);
1639                         entry->older_keys.len = MIN(entry->older_keys.len, 1);
1640                 }
1641 #endif
1642         } else if (kdc_db_ctx->rodc) {
1643                 /*
1644                  * We are on an RODC, but don't have keys for this
1645                  * account.  Signal this to the caller
1646                  */
1647                 auth_sam_trigger_repl_secret(kdc_db_ctx,
1648                                              kdc_db_ctx->msg_ctx,
1649                                              kdc_db_ctx->ev_ctx,
1650                                              msg->dn);
1651                 return SDB_ERR_NOT_FOUND_HERE;
1652         } else {
1653                 /*
1654                  * oh, no password.  Apparently (comment in
1655                  * hdb-ldap.c) this violates the ASN.1, but this
1656                  * allows an entry with no keys (yet).
1657                  */
1658         }
1659
1660         p->msg = talloc_steal(p, msg);
1661         p->supported_enctypes = pa_supported_enctypes;
1662
1663         p->client_policy = talloc_steal(p, authn_client_policy);
1664         p->server_policy = talloc_steal(p, authn_server_policy);
1665
1666 out:
1667         if (ret != 0) {
1668                 /* This doesn't free ent itself, that is for the eventual caller to do */
1669                 sdb_entry_free(entry);
1670         } else {
1671                 talloc_steal(kdc_db_ctx, p);
1672         }
1673
1674         return ret;
1675 }
1676
1677 /*
1678  * Construct an hdb_entry from a directory entry.
1679  * The kvno is what the remote client asked for
1680  */
1681 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
1682                                                struct samba_kdc_db_context *kdc_db_ctx,
1683                                                TALLOC_CTX *mem_ctx,
1684                                                enum trust_direction direction,
1685                                                struct ldb_dn *realm_dn,
1686                                                unsigned flags,
1687                                                uint32_t kvno,
1688                                                struct ldb_message *msg,
1689                                                struct sdb_entry *entry)
1690 {
1691         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1692         const char *our_realm = lpcfg_realm(lp_ctx);
1693         char *partner_realm = NULL;
1694         const char *realm = NULL;
1695         const char *krbtgt_realm = NULL;
1696         DATA_BLOB password_utf16 = data_blob_null;
1697         DATA_BLOB password_utf8 = data_blob_null;
1698         struct samr_Password _password_hash;
1699         const struct samr_Password *password_hash = NULL;
1700         const struct ldb_val *password_val;
1701         struct trustAuthInOutBlob password_blob;
1702         struct samba_kdc_entry *p;
1703         bool use_previous = false;
1704         uint32_t current_kvno;
1705         uint32_t previous_kvno;
1706         uint32_t num_keys = 0;
1707         enum ndr_err_code ndr_err;
1708         int ret;
1709         unsigned int i;
1710         struct AuthenticationInformationArray *auth_array;
1711         struct timeval tv;
1712         NTTIME an_hour_ago;
1713         uint32_t *auth_kvno;
1714         bool preferr_current = false;
1715         bool force_rc4 = lpcfg_kdc_force_enable_rc4_weak_session_keys(lp_ctx);
1716         uint32_t supported_enctypes = ENC_RC4_HMAC_MD5;
1717         uint32_t pa_supported_enctypes;
1718         uint32_t supported_session_etypes;
1719         uint32_t config_kdc_enctypes = lpcfg_kdc_supported_enctypes(lp_ctx);
1720         uint32_t kdc_enctypes =
1721                 config_kdc_enctypes != 0 ?
1722                 config_kdc_enctypes :
1723                 ENC_ALL_TYPES;
1724         struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
1725         NTSTATUS status;
1726
1727         ZERO_STRUCTP(entry);
1728
1729         if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1730                 /* If not told otherwise, Windows now assumes that trusts support AES. */
1731                 supported_enctypes = ldb_msg_find_attr_as_uint(msg,
1732                                         "msDS-SupportedEncryptionTypes",
1733                                         ENC_HMAC_SHA1_96_AES256);
1734         }
1735
1736         pa_supported_enctypes = supported_enctypes;
1737         supported_session_etypes = supported_enctypes;
1738         if (supported_session_etypes & ENC_HMAC_SHA1_96_AES256_SK) {
1739                 supported_session_etypes |= ENC_HMAC_SHA1_96_AES256;
1740                 supported_session_etypes |= ENC_HMAC_SHA1_96_AES128;
1741         }
1742         if (force_rc4) {
1743                 supported_session_etypes |= ENC_RC4_HMAC_MD5;
1744         }
1745         /*
1746          * now that we remembered what to announce in pa_supported_enctypes
1747          * and normalized ENC_HMAC_SHA1_96_AES256_SK, we restrict the
1748          * rest to the enc types the local kdc supports.
1749          */
1750         supported_enctypes &= kdc_enctypes;
1751         supported_session_etypes &= kdc_enctypes;
1752
1753         status = dsdb_trust_parse_tdo_info(mem_ctx, msg, &tdo);
1754         if (!NT_STATUS_IS_OK(status)) {
1755                 krb5_clear_error_message(context);
1756                 ret = ENOMEM;
1757                 goto out;
1758         }
1759
1760         if (!(tdo->trust_direction & direction)) {
1761                 krb5_clear_error_message(context);
1762                 ret = SDB_ERR_NOENTRY;
1763                 goto out;
1764         }
1765
1766         if (tdo->trust_type != LSA_TRUST_TYPE_UPLEVEL) {
1767                 /*
1768                  * Only UPLEVEL domains support kerberos here,
1769                  * as we don't support LSA_TRUST_TYPE_MIT.
1770                  */
1771                 krb5_clear_error_message(context);
1772                 ret = SDB_ERR_NOENTRY;
1773                 goto out;
1774         }
1775
1776         if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_CROSS_ORGANIZATION) {
1777                 /*
1778                  * We don't support selective authentication yet.
1779                  */
1780                 krb5_clear_error_message(context);
1781                 ret = SDB_ERR_NOENTRY;
1782                 goto out;
1783         }
1784
1785         if (tdo->domain_name.string == NULL) {
1786                 krb5_clear_error_message(context);
1787                 ret = SDB_ERR_NOENTRY;
1788                 goto out;
1789         }
1790         partner_realm = strupper_talloc(mem_ctx, tdo->domain_name.string);
1791         if (partner_realm == NULL) {
1792                 krb5_clear_error_message(context);
1793                 ret = ENOMEM;
1794                 goto out;
1795         }
1796
1797         if (direction == INBOUND) {
1798                 realm = our_realm;
1799                 krbtgt_realm = partner_realm;
1800
1801                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
1802         } else { /* OUTBOUND */
1803                 realm = partner_realm;
1804                 krbtgt_realm = our_realm;
1805
1806                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
1807         }
1808
1809         if (password_val == NULL) {
1810                 krb5_clear_error_message(context);
1811                 ret = SDB_ERR_NOENTRY;
1812                 goto out;
1813         }
1814
1815         ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
1816                                        (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
1817         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1818                 krb5_clear_error_message(context);
1819                 ret = EINVAL;
1820                 goto out;
1821         }
1822
1823         p = talloc_zero(mem_ctx, struct samba_kdc_entry);
1824         if (!p) {
1825                 ret = ENOMEM;
1826                 goto out;
1827         }
1828
1829         p->is_trust = true;
1830         p->kdc_db_ctx = kdc_db_ctx;
1831         p->realm_dn = realm_dn;
1832         p->supported_enctypes = pa_supported_enctypes;
1833
1834         talloc_set_destructor(p, samba_kdc_entry_destructor);
1835
1836         entry->skdc_entry = p;
1837
1838         /* use 'whenCreated' */
1839         entry->created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1840         /* use 'kadmin' for now (needed by mit_samba) */
1841         ret = smb_krb5_make_principal(context,
1842                                       &entry->created_by.principal,
1843                                       realm, "kadmin", NULL);
1844         if (ret) {
1845                 krb5_clear_error_message(context);
1846                 goto out;
1847         }
1848
1849         /*
1850          * We always need to generate the canonicalized principal
1851          * with the values of our database.
1852          */
1853         ret = smb_krb5_make_principal(context, &entry->principal, realm,
1854                                       "krbtgt", krbtgt_realm, NULL);
1855         if (ret) {
1856                 krb5_clear_error_message(context);
1857                 goto out;
1858         }
1859         smb_krb5_principal_set_type(context, entry->principal,
1860                                     KRB5_NT_SRV_INST);
1861
1862         entry->valid_start = NULL;
1863
1864         /* we need to work out if we are going to use the current or
1865          * the previous password hash.
1866          * We base this on the kvno the client passes in. If the kvno
1867          * passed in is equal to the current kvno in our database then
1868          * we use the current structure. If it is the current kvno-1,
1869          * then we use the previous substrucure.
1870          */
1871
1872         /*
1873          * Windows preferrs the previous key for one hour.
1874          */
1875         tv = timeval_current();
1876         if (tv.tv_sec > 3600) {
1877                 tv.tv_sec -= 3600;
1878         }
1879         an_hour_ago = timeval_to_nttime(&tv);
1880
1881         /* first work out the current kvno */
1882         current_kvno = 0;
1883         for (i=0; i < password_blob.count; i++) {
1884                 struct AuthenticationInformation *a =
1885                         &password_blob.current.array[i];
1886
1887                 if (a->LastUpdateTime <= an_hour_ago) {
1888                         preferr_current = true;
1889                 }
1890
1891                 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1892                         current_kvno = a->AuthInfo.version.version;
1893                 }
1894         }
1895         if (current_kvno == 0) {
1896                 previous_kvno = 255;
1897         } else {
1898                 previous_kvno = current_kvno - 1;
1899         }
1900         for (i=0; i < password_blob.count; i++) {
1901                 struct AuthenticationInformation *a =
1902                         &password_blob.previous.array[i];
1903
1904                 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1905                         previous_kvno = a->AuthInfo.version.version;
1906                 }
1907         }
1908
1909         /* work out whether we will use the previous or current
1910            password */
1911         if (password_blob.previous.count == 0) {
1912                 /* there is no previous password */
1913                 use_previous = false;
1914         } else if (!(flags & SDB_F_KVNO_SPECIFIED)) {
1915                 /*
1916                  * If not specified we use the lowest kvno
1917                  * for the first hour after an update.
1918                  */
1919                 if (preferr_current) {
1920                         use_previous = false;
1921                 } else if (previous_kvno < current_kvno) {
1922                         use_previous = true;
1923                 } else {
1924                         use_previous = false;
1925                 }
1926         } else if (kvno == current_kvno) {
1927                 /*
1928                  * Exact match ...
1929                  */
1930                 use_previous = false;
1931         } else if (kvno == previous_kvno) {
1932                 /*
1933                  * Exact match ...
1934                  */
1935                 use_previous = true;
1936         } else {
1937                 /*
1938                  * Fallback to the current one for anything else
1939                  */
1940                 use_previous = false;
1941         }
1942
1943         if (use_previous) {
1944                 auth_array = &password_blob.previous;
1945                 auth_kvno = &previous_kvno;
1946         } else {
1947                 auth_array = &password_blob.current;
1948                 auth_kvno = &current_kvno;
1949         }
1950
1951         /* use the kvno the client specified, if available */
1952         if (flags & SDB_F_KVNO_SPECIFIED) {
1953                 entry->kvno = kvno;
1954         } else {
1955                 entry->kvno = *auth_kvno;
1956         }
1957
1958         for (i=0; i < auth_array->count; i++) {
1959                 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
1960                         bool ok;
1961
1962                         password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
1963                                                          auth_array->array[i].AuthInfo.clear.size);
1964                         if (password_utf16.length == 0) {
1965                                 break;
1966                         }
1967
1968                         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1969                                 mdfour(_password_hash.hash, password_utf16.data, password_utf16.length);
1970                                 if (password_hash == NULL) {
1971                                         num_keys += 1;
1972                                 }
1973                                 password_hash = &_password_hash;
1974                         }
1975
1976                         if (!(supported_enctypes & (ENC_HMAC_SHA1_96_AES128|ENC_HMAC_SHA1_96_AES256))) {
1977                                 break;
1978                         }
1979
1980                         ok = convert_string_talloc(mem_ctx,
1981                                                    CH_UTF16MUNGED, CH_UTF8,
1982                                                    password_utf16.data,
1983                                                    password_utf16.length,
1984                                                    (void *)&password_utf8.data,
1985                                                    &password_utf8.length);
1986                         if (!ok) {
1987                                 krb5_clear_error_message(context);
1988                                 ret = ENOMEM;
1989                                 goto out;
1990                         }
1991
1992                         if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1993                                 num_keys += 1;
1994                         }
1995                         if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1996                                 num_keys += 1;
1997                         }
1998                         break;
1999                 } else if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
2000                         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
2001                                 password_hash = &auth_array->array[i].AuthInfo.nt4owf.password;
2002                                 num_keys += 1;
2003                         }
2004                 }
2005         }
2006
2007         /* Must have found a cleartext or MD4 password */
2008         if (num_keys == 0) {
2009                 DEBUG(1,(__location__ ": no usable key found\n"));
2010                 krb5_clear_error_message(context);
2011                 ret = SDB_ERR_NOENTRY;
2012                 goto out;
2013         }
2014
2015         entry->keys.val = calloc(num_keys, sizeof(struct sdb_key));
2016         if (entry->keys.val == NULL) {
2017                 krb5_clear_error_message(context);
2018                 ret = ENOMEM;
2019                 goto out;
2020         }
2021
2022         if (password_utf8.length != 0) {
2023                 struct sdb_key key = {};
2024                 krb5_const_principal salt_principal = entry->principal;
2025                 krb5_data salt;
2026                 krb5_data cleartext_data;
2027
2028                 cleartext_data.data = discard_const_p(char, password_utf8.data);
2029                 cleartext_data.length = password_utf8.length;
2030
2031                 ret = smb_krb5_get_pw_salt(context,
2032                                            salt_principal,
2033                                            &salt);
2034                 if (ret != 0) {
2035                         goto out;
2036                 }
2037
2038                 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
2039                         ret = smb_krb5_create_key_from_string(context,
2040                                                               salt_principal,
2041                                                               &salt,
2042                                                               &cleartext_data,
2043                                                               ENCTYPE_AES256_CTS_HMAC_SHA1_96,
2044                                                               &key.key);
2045                         if (ret != 0) {
2046                                 smb_krb5_free_data_contents(context, &salt);
2047                                 goto out;
2048                         }
2049
2050                         entry->keys.val[entry->keys.len] = key;
2051                         entry->keys.len++;
2052                 }
2053
2054                 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
2055                         ret = smb_krb5_create_key_from_string(context,
2056                                                               salt_principal,
2057                                                               &salt,
2058                                                               &cleartext_data,
2059                                                               ENCTYPE_AES128_CTS_HMAC_SHA1_96,
2060                                                               &key.key);
2061                         if (ret != 0) {
2062                                 smb_krb5_free_data_contents(context, &salt);
2063                                 goto out;
2064                         }
2065
2066                         entry->keys.val[entry->keys.len] = key;
2067                         entry->keys.len++;
2068                 }
2069
2070                 smb_krb5_free_data_contents(context, &salt);
2071         }
2072
2073         if (password_hash != NULL) {
2074                 struct sdb_key key = {};
2075
2076                 ret = smb_krb5_keyblock_init_contents(context,
2077                                                       ENCTYPE_ARCFOUR_HMAC,
2078                                                       password_hash->hash,
2079                                                       sizeof(password_hash->hash),
2080                                                       &key.key);
2081                 if (ret != 0) {
2082                         goto out;
2083                 }
2084
2085                 entry->keys.val[entry->keys.len] = key;
2086                 entry->keys.len++;
2087         }
2088
2089         entry->flags = int2SDBFlags(0);
2090         entry->flags.immutable = 1;
2091         entry->flags.invalid = 0;
2092         entry->flags.server = 1;
2093         entry->flags.require_preauth = 1;
2094
2095         entry->pw_end = NULL;
2096
2097         entry->max_life = NULL;
2098
2099         entry->max_renew = NULL;
2100
2101         /* Match Windows behavior and allow forwardable flag in cross-realm. */
2102         entry->flags.forwardable = 1;
2103
2104         samba_kdc_sort_keys(&entry->keys);
2105
2106         ret = sdb_entry_set_etypes(entry);
2107         if (ret) {
2108                 goto out;
2109         }
2110
2111         {
2112                 bool add_aes256 =
2113                         supported_session_etypes & KERB_ENCTYPE_AES256_CTS_HMAC_SHA1_96;
2114                 bool add_aes128 =
2115                         supported_session_etypes & KERB_ENCTYPE_AES128_CTS_HMAC_SHA1_96;
2116                 bool add_rc4 =
2117                         supported_session_etypes & ENC_RC4_HMAC_MD5;
2118                 ret = sdb_entry_set_session_etypes(entry,
2119                                                    add_aes256,
2120                                                    add_aes128,
2121                                                    add_rc4);
2122                 if (ret) {
2123                         goto out;
2124                 }
2125         }
2126
2127         p->msg = talloc_steal(p, msg);
2128
2129 out:
2130         TALLOC_FREE(partner_realm);
2131
2132         if (ret != 0) {
2133                 /* This doesn't free ent itself, that is for the eventual caller to do */
2134                 sdb_entry_free(entry);
2135         } else {
2136                 talloc_steal(kdc_db_ctx, p);
2137         }
2138
2139         return ret;
2140
2141 }
2142
2143 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
2144                                         TALLOC_CTX *mem_ctx,
2145                                         const char *realm,
2146                                         struct ldb_dn *realm_dn,
2147                                         struct ldb_message **pmsg)
2148 {
2149         NTSTATUS status;
2150         const char * const *attrs = trust_attrs;
2151
2152         status = dsdb_trust_search_tdo(ldb_ctx, realm, realm,
2153                                        attrs, mem_ctx, pmsg);
2154         if (NT_STATUS_IS_OK(status)) {
2155                 return 0;
2156         } else if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2157                 return SDB_ERR_NOENTRY;
2158         } else if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
2159                 int ret = ENOMEM;
2160                 krb5_set_error_message(context, ret, "samba_kdc_lookup_trust: out of memory");
2161                 return ret;
2162         } else {
2163                 int ret = EINVAL;
2164                 krb5_set_error_message(context, ret, "samba_kdc_lookup_trust: %s", nt_errstr(status));
2165                 return ret;
2166         }
2167 }
2168
2169 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
2170                                                 struct samba_kdc_db_context *kdc_db_ctx,
2171                                                 TALLOC_CTX *mem_ctx,
2172                                                 krb5_const_principal principal,
2173                                                 const char **attrs,
2174                                                 struct ldb_dn **realm_dn,
2175                                                 struct ldb_message **msg)
2176 {
2177         NTSTATUS nt_status;
2178         char *principal_string = NULL;
2179
2180         if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2181                 principal_string = smb_krb5_principal_get_comp_string(mem_ctx, context,
2182                                                                       principal, 0);
2183                 if (principal_string == NULL) {
2184                         return ENOMEM;
2185                 }
2186         } else {
2187                 char *principal_string_m = NULL;
2188                 krb5_error_code ret;
2189
2190                 ret = krb5_unparse_name(context, principal, &principal_string_m);
2191                 if (ret != 0) {
2192                         return ret;
2193                 }
2194
2195                 principal_string = talloc_strdup(mem_ctx, principal_string_m);
2196                 SAFE_FREE(principal_string_m);
2197                 if (principal_string == NULL) {
2198                         return ENOMEM;
2199                 }
2200         }
2201
2202         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
2203                                               mem_ctx, principal_string, attrs,
2204                                               realm_dn, msg);
2205         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
2206                 krb5_principal fallback_principal = NULL;
2207                 unsigned int num_comp;
2208                 char *fallback_realm = NULL;
2209                 char *fallback_account = NULL;
2210                 krb5_error_code ret;
2211
2212                 ret = krb5_parse_name(context, principal_string,
2213                                       &fallback_principal);
2214                 TALLOC_FREE(principal_string);
2215                 if (ret != 0) {
2216                         return ret;
2217                 }
2218
2219                 num_comp = krb5_princ_size(context, fallback_principal);
2220                 fallback_realm = smb_krb5_principal_get_realm(
2221                         mem_ctx, context, fallback_principal);
2222                 if (fallback_realm == NULL) {
2223                         krb5_free_principal(context, fallback_principal);
2224                         return ENOMEM;
2225                 }
2226
2227                 if (num_comp == 1) {
2228                         size_t len;
2229
2230                         fallback_account = smb_krb5_principal_get_comp_string(mem_ctx,
2231                                                 context, fallback_principal, 0);
2232                         if (fallback_account == NULL) {
2233                                 krb5_free_principal(context, fallback_principal);
2234                                 TALLOC_FREE(fallback_realm);
2235                                 return ENOMEM;
2236                         }
2237
2238                         len = strlen(fallback_account);
2239                         if (len >= 2 && fallback_account[len - 1] == '$') {
2240                                 TALLOC_FREE(fallback_account);
2241                         }
2242                 }
2243                 krb5_free_principal(context, fallback_principal);
2244                 fallback_principal = NULL;
2245
2246                 if (fallback_account != NULL) {
2247                         char *with_dollar;
2248
2249                         with_dollar = talloc_asprintf(mem_ctx, "%s$",
2250                                                      fallback_account);
2251                         if (with_dollar == NULL) {
2252                                 TALLOC_FREE(fallback_realm);
2253                                 return ENOMEM;
2254                         }
2255                         TALLOC_FREE(fallback_account);
2256
2257                         ret = smb_krb5_make_principal(context,
2258                                                       &fallback_principal,
2259                                                       fallback_realm,
2260                                                       with_dollar, NULL);
2261                         TALLOC_FREE(with_dollar);
2262                         if (ret != 0) {
2263                                 TALLOC_FREE(fallback_realm);
2264                                 return ret;
2265                         }
2266                 }
2267                 TALLOC_FREE(fallback_realm);
2268
2269                 if (fallback_principal != NULL) {
2270                         char *fallback_string = NULL;
2271
2272                         ret = krb5_unparse_name(context,
2273                                                 fallback_principal,
2274                                                 &fallback_string);
2275                         if (ret != 0) {
2276                                 krb5_free_principal(context, fallback_principal);
2277                                 return ret;
2278                         }
2279
2280                         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
2281                                                               mem_ctx,
2282                                                               fallback_string,
2283                                                               attrs,
2284                                                               realm_dn, msg);
2285                         SAFE_FREE(fallback_string);
2286                 }
2287                 krb5_free_principal(context, fallback_principal);
2288                 fallback_principal = NULL;
2289         }
2290         TALLOC_FREE(principal_string);
2291
2292         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
2293                 return SDB_ERR_NOENTRY;
2294         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
2295                 return ENOMEM;
2296         } else if (!NT_STATUS_IS_OK(nt_status)) {
2297                 return EINVAL;
2298         }
2299
2300         return 0;
2301 }
2302
2303 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
2304                                                struct samba_kdc_db_context *kdc_db_ctx,
2305                                                TALLOC_CTX *mem_ctx,
2306                                                krb5_const_principal principal,
2307                                                unsigned flags,
2308                                                krb5_kvno kvno,
2309                                                struct sdb_entry *entry)
2310 {
2311         struct ldb_dn *realm_dn;
2312         krb5_error_code ret;
2313         struct ldb_message *msg = NULL;
2314
2315         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
2316                                       mem_ctx, principal, user_attrs,
2317                                       &realm_dn, &msg);
2318         if (ret != 0) {
2319                 return ret;
2320         }
2321
2322         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2323                                       principal, SAMBA_KDC_ENT_TYPE_CLIENT,
2324                                       flags, kvno,
2325                                       realm_dn, msg, entry);
2326         return ret;
2327 }
2328
2329 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
2330                                               struct samba_kdc_db_context *kdc_db_ctx,
2331                                               TALLOC_CTX *mem_ctx,
2332                                               krb5_const_principal principal,
2333                                               unsigned flags,
2334                                               uint32_t kvno,
2335                                               struct sdb_entry *entry)
2336 {
2337         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
2338         krb5_error_code ret;
2339         struct ldb_message *msg = NULL;
2340         struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
2341         char *realm_from_princ;
2342         char *realm_princ_comp = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 1);
2343
2344         realm_from_princ = smb_krb5_principal_get_realm(
2345                 mem_ctx, context, principal);
2346         if (realm_from_princ == NULL) {
2347                 /* can't happen */
2348                 return SDB_ERR_NOENTRY;
2349         }
2350
2351         if (krb5_princ_size(context, principal) != 2
2352             || (principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME) != 0)) {
2353                 /* Not a krbtgt */
2354                 return SDB_ERR_NOENTRY;
2355         }
2356
2357         /* krbtgt case.  Either us or a trusted realm */
2358
2359         if (lpcfg_is_my_domain_or_realm(lp_ctx, realm_from_princ)
2360             && lpcfg_is_my_domain_or_realm(lp_ctx, realm_princ_comp)) {
2361                 /* us, or someone quite like us */
2362                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
2363                  * is in our db, then direct the caller at our primary
2364                  * krbtgt */
2365
2366                 int lret;
2367                 unsigned int krbtgt_number;
2368                 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
2369                    trust tickets. We don't yet know what this means, but we do
2370                    seem to need to treat it as unspecified */
2371                 if (flags & SDB_F_KVNO_SPECIFIED) {
2372                         krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
2373                         if (kdc_db_ctx->rodc) {
2374                                 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
2375                                         return SDB_ERR_NOT_FOUND_HERE;
2376                                 }
2377                         }
2378                 } else {
2379                         krbtgt_number = kdc_db_ctx->my_krbtgt_number;
2380                 }
2381
2382                 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
2383                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
2384                                                &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
2385                                                krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG,
2386                                                "(objectClass=user)");
2387                 } else {
2388                         /* We need to look up an RODC krbtgt (perhaps
2389                          * ours, if we are an RODC, perhaps another
2390                          * RODC if we are a read-write DC */
2391                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
2392                                                &msg, realm_dn, LDB_SCOPE_SUBTREE,
2393                                                krbtgt_attrs,
2394                                                DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2395                                                "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
2396                 }
2397
2398                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
2399                         krb5_warnx(context, "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
2400                                    (unsigned)(krbtgt_number));
2401                         krb5_set_error_message(context, SDB_ERR_NOENTRY,
2402                                                "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
2403                                                (unsigned)(krbtgt_number));
2404                         return SDB_ERR_NOENTRY;
2405                 } else if (lret != LDB_SUCCESS) {
2406                         krb5_warnx(context, "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
2407                                    (unsigned)(krbtgt_number));
2408                         krb5_set_error_message(context, SDB_ERR_NOENTRY,
2409                                                "samba_kdc_fetch_krbtgt: could not find KRBTGT number %u in DB!",
2410                                                (unsigned)(krbtgt_number));
2411                         return SDB_ERR_NOENTRY;
2412                 }
2413
2414                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2415                                               principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
2416                                               flags, kvno, realm_dn, msg, entry);
2417                 if (ret != 0) {
2418                         krb5_warnx(context, "samba_kdc_fetch_krbtgt: self krbtgt message2entry failed");
2419                 }
2420                 return ret;
2421
2422         } else {
2423                 enum trust_direction direction = UNKNOWN;
2424                 const char *realm = NULL;
2425
2426                 /* Either an inbound or outbound trust */
2427
2428                 if (strcasecmp(lpcfg_realm(lp_ctx), realm_from_princ) == 0) {
2429                         /* look for inbound trust */
2430                         direction = INBOUND;
2431                         realm = realm_princ_comp;
2432                 } else if (principal_comp_strcasecmp(context, principal, 1, lpcfg_realm(lp_ctx)) == 0) {
2433                         /* look for outbound trust */
2434                         direction = OUTBOUND;
2435                         realm = realm_from_princ;
2436                 } else {
2437                         krb5_warnx(context, "samba_kdc_fetch_krbtgt: not our realm for trusts ('%s', '%s')",
2438                                    realm_from_princ,
2439                                    realm_princ_comp);
2440                         krb5_set_error_message(context, SDB_ERR_NOENTRY, "samba_kdc_fetch_krbtgt: not our realm for trusts ('%s', '%s')",
2441                                                realm_from_princ,
2442                                                realm_princ_comp);
2443                         return SDB_ERR_NOENTRY;
2444                 }
2445
2446                 /* Trusted domains are under CN=system */
2447
2448                 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
2449                                        mem_ctx,
2450                                        realm, realm_dn, &msg);
2451
2452                 if (ret != 0) {
2453                         krb5_warnx(context, "samba_kdc_fetch_krbtgt: could not find principal in DB");
2454                         krb5_set_error_message(context, ret, "samba_kdc_fetch_krbtgt: could not find principal in DB");
2455                         return ret;
2456                 }
2457
2458                 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
2459                                                     direction,
2460                                                     realm_dn, flags, kvno, msg, entry);
2461                 if (ret != 0) {
2462                         krb5_warnx(context, "samba_kdc_fetch_krbtgt: trust_message2entry failed for %s",
2463                                    ldb_dn_get_linearized(msg->dn));
2464                         krb5_set_error_message(context, ret, "samba_kdc_fetch_krbtgt: "
2465                                                "trust_message2entry failed for %s",
2466                                                ldb_dn_get_linearized(msg->dn));
2467                 }
2468                 return ret;
2469         }
2470
2471 }
2472
2473 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
2474                                                struct samba_kdc_db_context *kdc_db_ctx,
2475                                                TALLOC_CTX *mem_ctx,
2476                                                krb5_const_principal principal,
2477                                                unsigned flags,
2478                                                const char **attrs,
2479                                                struct ldb_dn **realm_dn,
2480                                                struct ldb_message **msg)
2481 {
2482         krb5_error_code ret;
2483         if ((smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL)
2484             && krb5_princ_size(context, principal) >= 2) {
2485                 /* 'normal server' case */
2486                 int ldb_ret;
2487                 NTSTATUS nt_status;
2488                 struct ldb_dn *user_dn;
2489                 char *principal_string;
2490
2491                 ret = krb5_unparse_name_flags(context, principal,
2492                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM,
2493                                               &principal_string);
2494                 if (ret != 0) {
2495                         return ret;
2496                 }
2497
2498                 /* At this point we may find the host is known to be
2499                  * in a different realm, so we should generate a
2500                  * referral instead */
2501                 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
2502                                                          mem_ctx, principal_string,
2503                                                          &user_dn, realm_dn);
2504                 free(principal_string);
2505
2506                 if (!NT_STATUS_IS_OK(nt_status)) {
2507                         return SDB_ERR_NOENTRY;
2508                 }
2509
2510                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
2511                                           mem_ctx,
2512                                           msg, user_dn, LDB_SCOPE_BASE,
2513                                           attrs,
2514                                           DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2515                                           "(objectClass=*)");
2516                 if (ldb_ret != LDB_SUCCESS) {
2517                         return SDB_ERR_NOENTRY;
2518                 }
2519                 return 0;
2520         } else if (!(flags & SDB_F_FOR_AS_REQ)
2521                    && smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2522                 /*
2523                  * The behaviour of accepting an
2524                  * KRB5_NT_ENTERPRISE_PRINCIPAL server principal
2525                  * containing a UPN only applies to TGS-REQ packets,
2526                  * not AS-REQ packets.
2527                  */
2528                 return samba_kdc_lookup_client(context, kdc_db_ctx,
2529                                                mem_ctx, principal, attrs,
2530                                                realm_dn, msg);
2531         } else {
2532                 /*
2533                  * This case is for:
2534                  *  - the AS-REQ, where we only accept
2535                  *    samAccountName based lookups for the server, no
2536                  *    matter if the name is an
2537                  *    KRB5_NT_ENTERPRISE_PRINCIPAL or not
2538                  *  - for the TGS-REQ when we are not given an
2539                  *    KRB5_NT_ENTERPRISE_PRINCIPAL, which also must
2540                  *    only lookup samAccountName based names.
2541                  */
2542                 int lret;
2543                 char *short_princ;
2544                 krb5_principal enterprise_principal = NULL;
2545                 krb5_const_principal used_principal = NULL;
2546                 char *name1 = NULL;
2547                 size_t len1 = 0;
2548                 char *filter = NULL;
2549
2550                 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2551                         char *str = NULL;
2552                         /* Need to reparse the enterprise principal to find the real target */
2553                         if (krb5_princ_size(context, principal) != 1) {
2554                                 ret = KRB5_PARSE_MALFORMED;
2555                                 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: request for an "
2556                                                        "enterprise principal with wrong (%d) number of components",
2557                                                        krb5_princ_size(context, principal));
2558                                 return ret;
2559                         }
2560                         str = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 0);
2561                         if (str == NULL) {
2562                                 return KRB5_PARSE_MALFORMED;
2563                         }
2564                         ret = krb5_parse_name(context, str,
2565                                               &enterprise_principal);
2566                         talloc_free(str);
2567                         if (ret) {
2568                                 return ret;
2569                         }
2570                         used_principal = enterprise_principal;
2571                 } else {
2572                         used_principal = principal;
2573                 }
2574
2575                 /* server as client principal case, but we must not lookup userPrincipalNames */
2576                 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
2577
2578                 /* TODO: Check if it is our realm, otherwise give referral */
2579
2580                 ret = krb5_unparse_name_flags(context, used_principal,
2581                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM |
2582                                               KRB5_PRINCIPAL_UNPARSE_DISPLAY,
2583                                               &short_princ);
2584                 used_principal = NULL;
2585                 krb5_free_principal(context, enterprise_principal);
2586                 enterprise_principal = NULL;
2587
2588                 if (ret != 0) {
2589                         krb5_set_error_message(context, ret, "samba_kdc_lookup_server: could not parse principal");
2590                         krb5_warnx(context, "samba_kdc_lookup_server: could not parse principal");
2591                         return ret;
2592                 }
2593
2594                 name1 = ldb_binary_encode_string(mem_ctx, short_princ);
2595                 SAFE_FREE(short_princ);
2596                 if (name1 == NULL) {
2597                         return ENOMEM;
2598                 }
2599                 len1 = strlen(name1);
2600                 if (len1 >= 1 && name1[len1 - 1] != '$') {
2601                         filter = talloc_asprintf(mem_ctx,
2602                                         "(&(objectClass=user)(|(samAccountName=%s)(samAccountName=%s$)))",
2603                                         name1, name1);
2604                         if (filter == NULL) {
2605                                 return ENOMEM;
2606                         }
2607                 } else {
2608                         filter = talloc_asprintf(mem_ctx,
2609                                         "(&(objectClass=user)(samAccountName=%s))",
2610                                         name1);
2611                         if (filter == NULL) {
2612                                 return ENOMEM;
2613                         }
2614                 }
2615
2616                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
2617                                        *realm_dn, LDB_SCOPE_SUBTREE,
2618                                        attrs,
2619                                        DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2620                                        "%s", filter);
2621                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
2622                         DEBUG(10, ("Failed to find an entry for %s filter:%s\n",
2623                                   name1, filter));
2624                         return SDB_ERR_NOENTRY;
2625                 }
2626                 if (lret == LDB_ERR_CONSTRAINT_VIOLATION) {
2627                         DEBUG(10, ("Failed to find unique entry for %s filter:%s\n",
2628                                   name1, filter));
2629                         return SDB_ERR_NOENTRY;
2630                 }
2631                 if (lret != LDB_SUCCESS) {
2632                         DEBUG(0, ("Failed single search for %s - %s\n",
2633                                   name1, ldb_errstring(kdc_db_ctx->samdb)));
2634                         return SDB_ERR_NOENTRY;
2635                 }
2636                 return 0;
2637         }
2638         return SDB_ERR_NOENTRY;
2639 }
2640
2641
2642
2643 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
2644                                               struct samba_kdc_db_context *kdc_db_ctx,
2645                                               TALLOC_CTX *mem_ctx,
2646                                               krb5_const_principal principal,
2647                                               unsigned flags,
2648                                               krb5_kvno kvno,
2649                                               struct sdb_entry *entry)
2650 {
2651         krb5_error_code ret;
2652         struct ldb_dn *realm_dn;
2653         struct ldb_message *msg;
2654
2655         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
2656                                       flags, server_attrs, &realm_dn, &msg);
2657         if (ret != 0) {
2658                 return ret;
2659         }
2660
2661         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2662                                       principal, SAMBA_KDC_ENT_TYPE_SERVER,
2663                                       flags, kvno,
2664                                       realm_dn, msg, entry);
2665         if (ret != 0) {
2666                 char *client_name = NULL;
2667                 krb5_error_code code;
2668
2669                 code = krb5_unparse_name(context, principal, &client_name);
2670                 if (code == 0) {
2671                         krb5_warnx(context,
2672                                    "samba_kdc_fetch_server: message2entry failed for "
2673                                    "%s",
2674                                    client_name);
2675                 } else {
2676                         krb5_warnx(context,
2677                                    "samba_kdc_fetch_server: message2entry and "
2678                                    "krb5_unparse_name failed");
2679                 }
2680                 SAFE_FREE(client_name);
2681         }
2682
2683         return ret;
2684 }
2685
2686 static krb5_error_code samba_kdc_lookup_realm(krb5_context context,
2687                                               struct samba_kdc_db_context *kdc_db_ctx,
2688                                               TALLOC_CTX *mem_ctx,
2689                                               krb5_const_principal principal,
2690                                               unsigned flags,
2691                                               struct sdb_entry *entry)
2692 {
2693         TALLOC_CTX *frame = talloc_stackframe();
2694         NTSTATUS status;
2695         krb5_error_code ret;
2696         bool check_realm = false;
2697         const char *realm = NULL;
2698         struct dsdb_trust_routing_table *trt = NULL;
2699         const struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
2700         unsigned int num_comp;
2701         bool ok;
2702         char *upper = NULL;
2703
2704         num_comp = krb5_princ_size(context, principal);
2705
2706         if (flags & SDB_F_GET_CLIENT) {
2707                 if (flags & SDB_F_FOR_AS_REQ) {
2708                         check_realm = true;
2709                 }
2710         }
2711         if (flags & SDB_F_GET_SERVER) {
2712                 if (flags & SDB_F_FOR_TGS_REQ) {
2713                         check_realm = true;
2714                 }
2715         }
2716
2717         if (!check_realm) {
2718                 TALLOC_FREE(frame);
2719                 return 0;
2720         }
2721
2722         realm = smb_krb5_principal_get_realm(frame, context, principal);
2723         if (realm == NULL) {
2724                 TALLOC_FREE(frame);
2725                 return ENOMEM;
2726         }
2727
2728         /*
2729          * The requested realm needs to be our own
2730          */
2731         ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2732         if (!ok) {
2733                 /*
2734                  * The request is not for us...
2735                  */
2736                 TALLOC_FREE(frame);
2737                 return SDB_ERR_NOENTRY;
2738         }
2739
2740         if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2741                 char *principal_string = NULL;
2742                 krb5_principal enterprise_principal = NULL;
2743                 char *enterprise_realm = NULL;
2744
2745                 if (num_comp != 1) {
2746                         TALLOC_FREE(frame);
2747                         return SDB_ERR_NOENTRY;
2748                 }
2749
2750                 principal_string = smb_krb5_principal_get_comp_string(frame, context,
2751                                                                       principal, 0);
2752                 if (principal_string == NULL) {
2753                         TALLOC_FREE(frame);
2754                         return ENOMEM;
2755                 }
2756
2757                 ret = krb5_parse_name(context, principal_string,
2758                                       &enterprise_principal);
2759                 TALLOC_FREE(principal_string);
2760                 if (ret) {
2761                         TALLOC_FREE(frame);
2762                         return ret;
2763                 }
2764
2765                 enterprise_realm = smb_krb5_principal_get_realm(
2766                         frame, context, enterprise_principal);
2767                 krb5_free_principal(context, enterprise_principal);
2768                 if (enterprise_realm != NULL) {
2769                         realm = enterprise_realm;
2770                 }
2771         }
2772
2773         if (flags & SDB_F_GET_SERVER) {
2774                 char *service_realm = NULL;
2775
2776                 ret = principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME);
2777                 if (ret == 0) {
2778                         /*
2779                          * we need to search krbtgt/ locally
2780                          */
2781                         TALLOC_FREE(frame);
2782                         return 0;
2783                 }
2784
2785                 /*
2786                  * We need to check the last component against the routing table.
2787                  *
2788                  * Note this works only with 2 or 3 component principals, e.g:
2789                  *
2790                  * servicePrincipalName: ldap/W2K8R2-219.bla.base
2791                  * servicePrincipalName: ldap/W2K8R2-219.bla.base/bla.base
2792                  * servicePrincipalName: ldap/W2K8R2-219.bla.base/ForestDnsZones.bla.base
2793                  * servicePrincipalName: ldap/W2K8R2-219.bla.base/DomainDnsZones.bla.base
2794                  */
2795
2796                 if (num_comp == 2 || num_comp == 3) {
2797                         service_realm = smb_krb5_principal_get_comp_string(frame,
2798                                                                            context,
2799                                                                            principal,
2800                                                                            num_comp - 1);
2801                 }
2802
2803                 if (service_realm != NULL) {
2804                         realm = service_realm;
2805                 }
2806         }
2807
2808         ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2809         if (ok) {
2810                 /*
2811                  * skip the expensive routing lookup
2812                  */
2813                 TALLOC_FREE(frame);
2814                 return 0;
2815         }
2816
2817         status = dsdb_trust_routing_table_load(kdc_db_ctx->samdb,
2818                                                frame, &trt);
2819         if (!NT_STATUS_IS_OK(status)) {
2820                 TALLOC_FREE(frame);
2821                 return EINVAL;
2822         }
2823
2824         tdo = dsdb_trust_routing_by_name(trt, realm);
2825         if (tdo == NULL) {
2826                 /*
2827                  * This principal has to be local
2828                  */
2829                 TALLOC_FREE(frame);
2830                 return 0;
2831         }
2832
2833         if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
2834                 /*
2835                  * TODO: handle the routing within the forest
2836                  *
2837                  * This should likely be handled in
2838                  * samba_kdc_message2entry() in case we're
2839                  * a global catalog. We'd need to check
2840                  * if realm_dn is our own domain and derive
2841                  * the dns domain name from realm_dn and check that
2842                  * against the routing table or fallback to
2843                  * the tdo we found here.
2844                  *
2845                  * But for now we don't support multiple domains
2846                  * in our forest correctly anyway.
2847                  *
2848                  * Just search in our local database.
2849                  */
2850                 TALLOC_FREE(frame);
2851                 return 0;
2852         }
2853
2854         ZERO_STRUCTP(entry);
2855
2856         ret = krb5_copy_principal(context, principal,
2857                                   &entry->principal);
2858         if (ret) {
2859                 TALLOC_FREE(frame);
2860                 return ret;
2861         }
2862
2863         upper = strupper_talloc(frame, tdo->domain_name.string);
2864         if (upper == NULL) {
2865                 TALLOC_FREE(frame);
2866                 return ENOMEM;
2867         }
2868
2869         ret = smb_krb5_principal_set_realm(context,
2870                                            entry->principal,
2871                                            upper);
2872         if (ret) {
2873                 TALLOC_FREE(frame);
2874                 return ret;
2875         }
2876
2877         TALLOC_FREE(frame);
2878         return SDB_ERR_WRONG_REALM;
2879 }
2880
2881 krb5_error_code samba_kdc_fetch(krb5_context context,
2882                                 struct samba_kdc_db_context *kdc_db_ctx,
2883                                 krb5_const_principal principal,
2884                                 unsigned flags,
2885                                 krb5_kvno kvno,
2886                                 struct sdb_entry *entry)
2887 {
2888         krb5_error_code ret = SDB_ERR_NOENTRY;
2889         TALLOC_CTX *mem_ctx;
2890
2891         mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
2892         if (!mem_ctx) {
2893                 ret = ENOMEM;
2894                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2895                 return ret;
2896         }
2897
2898         ret = samba_kdc_lookup_realm(context, kdc_db_ctx, mem_ctx,
2899                                      principal, flags, entry);
2900         if (ret != 0) {
2901                 goto done;
2902         }
2903
2904         ret = SDB_ERR_NOENTRY;
2905
2906         if (flags & SDB_F_GET_CLIENT) {
2907                 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
2908                 if (ret != SDB_ERR_NOENTRY) goto done;
2909         }
2910         if (flags & SDB_F_GET_SERVER) {
2911                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
2912                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
2913                 if (ret != SDB_ERR_NOENTRY) goto done;
2914
2915                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
2916                 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
2917                 if (ret != SDB_ERR_NOENTRY) goto done;
2918         }
2919         if (flags & SDB_F_GET_KRBTGT) {
2920                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry);
2921                 if (ret != SDB_ERR_NOENTRY) goto done;
2922         }
2923
2924 done:
2925         talloc_free(mem_ctx);
2926         return ret;
2927 }
2928
2929 struct samba_kdc_seq {
2930         unsigned int index;
2931         unsigned int count;
2932         struct ldb_message **msgs;
2933         struct ldb_dn *realm_dn;
2934 };
2935
2936 static krb5_error_code samba_kdc_seq(krb5_context context,
2937                                      struct samba_kdc_db_context *kdc_db_ctx,
2938                                      struct sdb_entry *entry)
2939 {
2940         krb5_error_code ret;
2941         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2942         const char *realm = lpcfg_realm(kdc_db_ctx->lp_ctx);
2943         struct ldb_message *msg = NULL;
2944         const char *sAMAccountName = NULL;
2945         krb5_principal principal = NULL;
2946         TALLOC_CTX *mem_ctx;
2947
2948         if (!priv) {
2949                 return SDB_ERR_NOENTRY;
2950         }
2951
2952         mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
2953
2954         if (!mem_ctx) {
2955                 ret = ENOMEM;
2956                 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
2957                 return ret;
2958         }
2959
2960         while (priv->index < priv->count) {
2961                 msg = priv->msgs[priv->index++];
2962
2963                 sAMAccountName = ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL);
2964                 if (sAMAccountName != NULL) {
2965                         break;
2966                 }
2967         }
2968
2969         if (sAMAccountName == NULL) {
2970                 ret = SDB_ERR_NOENTRY;
2971                 goto out;
2972         }
2973
2974         ret = smb_krb5_make_principal(context, &principal,
2975                                       realm, sAMAccountName, NULL);
2976         if (ret != 0) {
2977                 goto out;
2978         }
2979
2980         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2981                                       principal, SAMBA_KDC_ENT_TYPE_ANY,
2982                                       SDB_F_ADMIN_DATA|SDB_F_GET_ANY,
2983                                       0 /* kvno */,
2984                                       priv->realm_dn, msg, entry);
2985
2986 out:
2987         if (principal != NULL) {
2988                 krb5_free_principal(context, principal);
2989         }
2990
2991         if (ret != 0) {
2992                 TALLOC_FREE(priv);
2993                 kdc_db_ctx->seq_ctx = NULL;
2994         } else {
2995                 talloc_free(mem_ctx);
2996         }
2997
2998         return ret;
2999 }
3000
3001 krb5_error_code samba_kdc_firstkey(krb5_context context,
3002                                    struct samba_kdc_db_context *kdc_db_ctx,
3003                                    struct sdb_entry *entry)
3004 {
3005         struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
3006         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
3007         char *realm;
3008         struct ldb_result *res = NULL;
3009         krb5_error_code ret;
3010         TALLOC_CTX *mem_ctx;
3011         int lret;
3012
3013         if (priv) {
3014                 TALLOC_FREE(priv);
3015                 kdc_db_ctx->seq_ctx = NULL;
3016         }
3017
3018         priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
3019         if (!priv) {
3020                 ret = ENOMEM;
3021                 krb5_set_error_message(context, ret, "talloc: out of memory");
3022                 return ret;
3023         }
3024
3025         priv->index = 0;
3026         priv->msgs = NULL;
3027         priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
3028         priv->count = 0;
3029
3030         mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
3031
3032         if (!mem_ctx) {
3033                 ret = ENOMEM;
3034                 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
3035                 TALLOC_FREE(priv);
3036                 return ret;
3037         }
3038
3039         ret = krb5_get_default_realm(context, &realm);
3040         if (ret != 0) {
3041                 TALLOC_FREE(priv);
3042                 return ret;
3043         }
3044         krb5_free_default_realm(context, realm);
3045
3046         lret = dsdb_search(ldb_ctx, priv, &res,
3047                            priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
3048                            DSDB_SEARCH_NO_GLOBAL_CATALOG,
3049                            "(objectClass=user)");
3050
3051         if (lret != LDB_SUCCESS) {
3052                 TALLOC_FREE(priv);
3053                 return SDB_ERR_NOENTRY;
3054         }
3055
3056         priv->count = res->count;
3057         priv->msgs = talloc_steal(priv, res->msgs);
3058         talloc_free(res);
3059
3060         kdc_db_ctx->seq_ctx = priv;
3061
3062         ret = samba_kdc_seq(context, kdc_db_ctx, entry);
3063
3064         if (ret != 0) {
3065                 TALLOC_FREE(priv);
3066                 kdc_db_ctx->seq_ctx = NULL;
3067         } else {
3068                 talloc_free(mem_ctx);
3069         }
3070         return ret;
3071 }
3072
3073 krb5_error_code samba_kdc_nextkey(krb5_context context,
3074                                   struct samba_kdc_db_context *kdc_db_ctx,
3075                                   struct sdb_entry *entry)
3076 {
3077         return samba_kdc_seq(context, kdc_db_ctx, entry);
3078 }
3079
3080 /* Check if a given entry may delegate or do s4u2self to this target principal
3081  *
3082  * The safest way to determine 'self' is to check the DB record made at
3083  * the time the principal was presented to the KDC.
3084  */
3085 krb5_error_code
3086 samba_kdc_check_client_matches_target_service(krb5_context context,
3087                                               struct samba_kdc_entry *skdc_entry_client,
3088                                               struct samba_kdc_entry *skdc_entry_server_target)
3089 {
3090         struct dom_sid *orig_sid;
3091         struct dom_sid *target_sid;
3092         TALLOC_CTX *frame = talloc_stackframe();
3093
3094         orig_sid = samdb_result_dom_sid(frame,
3095                                         skdc_entry_client->msg,
3096                                         "objectSid");
3097         target_sid = samdb_result_dom_sid(frame,
3098                                           skdc_entry_server_target->msg,
3099                                           "objectSid");
3100
3101         /*
3102          * Allow delegation to the same record (representing a
3103          * principal), even if by a different name.  The easy and safe
3104          * way to prove this is by SID comparison
3105          */
3106         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
3107                 talloc_free(frame);
3108                 return KRB5KRB_AP_ERR_BADMATCH;
3109         }
3110
3111         talloc_free(frame);
3112         return 0;
3113 }
3114
3115 /* Certificates printed by a the Certificate Authority might have a
3116  * slightly different form of the user principal name to that in the
3117  * database.  Allow a mismatch where they both refer to the same
3118  * SID */
3119
3120 krb5_error_code
3121 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
3122                                     struct samba_kdc_db_context *kdc_db_ctx,
3123                                     struct samba_kdc_entry *skdc_entry,
3124                                      krb5_const_principal certificate_principal)
3125 {
3126         krb5_error_code ret;
3127         struct ldb_dn *realm_dn;
3128         struct ldb_message *msg;
3129         struct dom_sid *orig_sid;
3130         struct dom_sid *target_sid;
3131         const char *ms_upn_check_attrs[] = {
3132                 "objectSid", NULL
3133         };
3134
3135         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
3136
3137         if (!mem_ctx) {
3138                 ret = ENOMEM;
3139                 krb5_set_error_message(context, ret, "samba_kdc_check_pkinit_ms_upn_match: talloc_named() failed!");
3140                 return ret;
3141         }
3142
3143         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
3144                                       mem_ctx, certificate_principal,
3145                                       ms_upn_check_attrs, &realm_dn, &msg);
3146
3147         if (ret != 0) {
3148                 talloc_free(mem_ctx);
3149                 return ret;
3150         }
3151
3152         orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
3153         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
3154
3155         /* Consider these to be the same principal, even if by a different
3156          * name.  The easy and safe way to prove this is by SID
3157          * comparison */
3158         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
3159                 talloc_free(mem_ctx);
3160 #if defined(KRB5KDC_ERR_CLIENT_NAME_MISMATCH) /* MIT */
3161                 return KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
3162 #else /* Heimdal (where this is an enum) */
3163                 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
3164 #endif
3165         }
3166
3167         talloc_free(mem_ctx);
3168         return ret;
3169 }
3170
3171 /*
3172  * Check if a given entry may delegate to this target principal
3173  * with S4U2Proxy.
3174  */
3175 krb5_error_code
3176 samba_kdc_check_s4u2proxy(krb5_context context,
3177                           struct samba_kdc_db_context *kdc_db_ctx,
3178                           struct samba_kdc_entry *skdc_entry,
3179                           krb5_const_principal target_principal)
3180 {
3181         krb5_error_code ret;
3182         char *tmp = NULL;
3183         const char *client_dn = NULL;
3184         const char *target_principal_name = NULL;
3185         struct ldb_message_element *el;
3186         struct ldb_val val;
3187         unsigned int i;
3188         bool found = false;
3189
3190         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
3191
3192         if (!mem_ctx) {
3193                 ret = ENOMEM;
3194                 krb5_set_error_message(context, ret,
3195                                        "samba_kdc_check_s4u2proxy:"
3196                                        " talloc_named() failed!");
3197                 return ret;
3198         }
3199
3200         client_dn = ldb_dn_get_linearized(skdc_entry->msg->dn);
3201         if (!client_dn) {
3202                 if (errno == 0) {
3203                         errno = ENOMEM;
3204                 }
3205                 ret = errno;
3206                 krb5_set_error_message(context, ret,
3207                                        "samba_kdc_check_s4u2proxy:"
3208                                        " ldb_dn_get_linearized() failed!");
3209                 talloc_free(mem_ctx);
3210                 return ret;
3211         }
3212
3213         el = ldb_msg_find_element(skdc_entry->msg, "msDS-AllowedToDelegateTo");
3214         if (el == NULL) {
3215                 ret = ENOENT;
3216                 goto bad_option;
3217         }
3218         SMB_ASSERT(el->num_values != 0);
3219
3220         /*
3221          * This is the Microsoft forwardable flag behavior.
3222          *
3223          * If the proxy (target) principal is NULL, and we have any authorized
3224          * delegation target, allow to forward.
3225          */
3226         if (target_principal == NULL) {
3227                 talloc_free(mem_ctx);
3228                 return 0;
3229         }
3230
3231
3232         /*
3233          * The main heimdal code already checked that the target_principal
3234          * belongs to the same realm as the client.
3235          *
3236          * So we just need the principal without the realm,
3237          * as that is what is configured in the "msDS-AllowedToDelegateTo"
3238          * attribute.
3239          */
3240         ret = krb5_unparse_name_flags(context, target_principal,
3241                                       KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
3242         if (ret) {
3243                 talloc_free(mem_ctx);
3244                 krb5_set_error_message(context, ret,
3245                                        "samba_kdc_check_s4u2proxy:"
3246                                        " krb5_unparse_name() failed!");
3247                 return ret;
3248         }
3249         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] for target[%s]\n",
3250                  client_dn, tmp));
3251
3252         target_principal_name = talloc_strdup(mem_ctx, tmp);
3253         SAFE_FREE(tmp);
3254         if (target_principal_name == NULL) {
3255                 ret = ENOMEM;
3256                 krb5_set_error_message(context, ret,
3257                                        "samba_kdc_check_s4u2proxy:"
3258                                        " talloc_strdup() failed!");
3259                 talloc_free(mem_ctx);
3260                 return ret;
3261         }
3262
3263         val = data_blob_string_const(target_principal_name);
3264
3265         for (i=0; i<el->num_values; i++) {
3266                 struct ldb_val *val1 = &val;
3267                 struct ldb_val *val2 = &el->values[i];
3268                 int cmp;
3269
3270                 if (val1->length != val2->length) {
3271                         continue;
3272                 }
3273
3274                 cmp = strncasecmp((const char *)val1->data,
3275                                   (const char *)val2->data,
3276                                   val1->length);
3277                 if (cmp != 0) {
3278                         continue;
3279                 }
3280
3281                 found = true;
3282                 break;
3283         }
3284
3285         if (!found) {
3286                 ret = ENOENT;
3287                 goto bad_option;
3288         }
3289
3290         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] allowed target[%s]\n",
3291                  client_dn, target_principal_name));
3292         talloc_free(mem_ctx);
3293         return 0;
3294
3295 bad_option:
3296         krb5_set_error_message(context, ret,
3297                                "samba_kdc_check_s4u2proxy: client[%s] "
3298                                "not allowed for delegation to target[%s]",
3299                                client_dn,
3300                                target_principal_name);
3301         talloc_free(mem_ctx);
3302         return KRB5KDC_ERR_BADOPTION;
3303 }
3304
3305 /*
3306  * This method is called for S4U2Proxy requests and implements the
3307  * resource-based constrained delegation variant, which can support
3308  * cross-realm delegation.
3309  */
3310 krb5_error_code samba_kdc_check_s4u2proxy_rbcd(
3311                 krb5_context context,
3312                 struct samba_kdc_db_context *kdc_db_ctx,
3313                 krb5_const_principal client_principal,
3314                 krb5_const_principal server_principal,
3315                 krb5_const_pac header_pac,
3316                 struct samba_kdc_entry *proxy_skdc_entry)
3317 {
3318         krb5_error_code code;
3319         enum ndr_err_code ndr_err;
3320         char *client_name = NULL;
3321         char *server_name = NULL;
3322         const char *proxy_dn = NULL;
3323         const DATA_BLOB *data = NULL;
3324         struct security_descriptor *rbcd_security_descriptor = NULL;
3325         struct auth_user_info_dc *user_info_dc = NULL;
3326         struct security_token *security_token = NULL;
3327         uint32_t session_info_flags = AUTH_SESSION_INFO_SIMPLE_PRIVILEGES;
3328         /*
3329          * Testing shows that although Windows grants SEC_ADS_GENERIC_ALL access
3330          * in security descriptors it creates for RBCD, its KDC only requires
3331          * SEC_ADS_CONTROL_ACCESS for the access check to succeed.
3332          */
3333         uint32_t access_desired = SEC_ADS_CONTROL_ACCESS;
3334         uint32_t access_granted = 0;
3335         NTSTATUS nt_status;
3336         TALLOC_CTX *mem_ctx = NULL;
3337
3338         mem_ctx = talloc_named(kdc_db_ctx,
3339                                0,
3340                                "samba_kdc_check_s4u2proxy_rbcd");
3341         if (mem_ctx == NULL) {
3342                 errno = ENOMEM;
3343                 code = errno;
3344
3345                 return code;
3346         }
3347
3348         proxy_dn = ldb_dn_get_linearized(proxy_skdc_entry->msg->dn);
3349         if (proxy_dn == NULL) {
3350                 DBG_ERR("ldb_dn_get_linearized failed for proxy_dn!\n");
3351                 if (errno == 0) {
3352                         errno = ENOMEM;
3353                 }
3354                 code = errno;
3355
3356                 goto out;
3357         }
3358
3359         rbcd_security_descriptor = talloc_zero(mem_ctx,
3360                                                struct security_descriptor);
3361         if (rbcd_security_descriptor == NULL) {
3362                 errno = ENOMEM;
3363                 code = errno;
3364
3365                 goto out;
3366         }
3367
3368         code = krb5_unparse_name_flags(context,
3369                                        client_principal,
3370                                        KRB5_PRINCIPAL_UNPARSE_DISPLAY,
3371                                        &client_name);
3372         if (code != 0) {
3373                 DBG_ERR("Unable to parse client_principal!\n");
3374                 goto out;
3375         }
3376
3377         code = krb5_unparse_name_flags(context,
3378                                        server_principal,
3379                                        KRB5_PRINCIPAL_UNPARSE_DISPLAY,
3380                                        &server_name);
3381         if (code != 0) {
3382                 DBG_ERR("Unable to parse server_principal!\n");
3383                 goto out;
3384         }
3385
3386         DBG_INFO("Check delegation from client[%s] to server[%s] via "
3387                  "proxy[%s]\n",
3388                  client_name,
3389                  server_name,
3390                  proxy_dn);
3391
3392         code = kerberos_pac_to_user_info_dc(mem_ctx,
3393                                             header_pac,
3394                                             context,
3395                                             &user_info_dc,
3396                                             AUTH_INCLUDE_RESOURCE_GROUPS,
3397                                             NULL,
3398                                             NULL,
3399                                             NULL);
3400         if (code != 0) {
3401                 goto out;
3402         }
3403
3404         if (!(user_info_dc->info->user_flags & NETLOGON_GUEST)) {
3405                 session_info_flags |= AUTH_SESSION_INFO_AUTHENTICATED;
3406         }
3407
3408         nt_status = auth_generate_security_token(mem_ctx,
3409                                                  kdc_db_ctx->lp_ctx,
3410                                                  kdc_db_ctx->samdb,
3411                                                  user_info_dc,
3412                                                  session_info_flags,
3413                                                  &security_token);
3414         if (!NT_STATUS_IS_OK(nt_status)) {
3415                 code = map_errno_from_nt_status(nt_status);
3416                 goto out;
3417         }
3418
3419         data = ldb_msg_find_ldb_val(proxy_skdc_entry->msg,
3420                                     "msDS-AllowedToActOnBehalfOfOtherIdentity");
3421         if (data == NULL) {
3422                 DBG_ERR("Could not find security descriptor "
3423                         "msDS-AllowedToActOnBehalfOfOtherIdentity in "
3424                         "proxy[%s]\n",
3425                         proxy_dn);
3426                 code = KRB5KDC_ERR_BADOPTION;
3427                 goto out;
3428         }
3429
3430         ndr_err = ndr_pull_struct_blob(
3431                         data,
3432                         mem_ctx,
3433                         rbcd_security_descriptor,
3434                         (ndr_pull_flags_fn_t)ndr_pull_security_descriptor);
3435         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3436                 errno = ndr_map_error2errno(ndr_err);
3437                 DBG_ERR("Failed to unmarshall "
3438                         "msDS-AllowedToActOnBehalfOfOtherIdentity "
3439                         "security descriptor of proxy[%s]\n",
3440                         proxy_dn);
3441                 code = KRB5KDC_ERR_BADOPTION;
3442                 goto out;
3443         }
3444
3445         if (DEBUGLEVEL >= 10) {
3446                 NDR_PRINT_DEBUG(security_token, security_token);
3447                 NDR_PRINT_DEBUG(security_descriptor, rbcd_security_descriptor);
3448         }
3449
3450         nt_status = sec_access_check_ds(rbcd_security_descriptor,
3451                                         security_token,
3452                                         access_desired,
3453                                         &access_granted,
3454                                         NULL,
3455                                         NULL);
3456
3457         if (!NT_STATUS_IS_OK(nt_status)) {
3458                 DBG_WARNING("RBCD: sec_access_check_ds(access_desired=%#08x, "
3459                             "access_granted:%#08x) failed with: %s\n",
3460                             access_desired,
3461                             access_granted,
3462                             nt_errstr(nt_status));
3463
3464                 code = KRB5KDC_ERR_BADOPTION;
3465                 goto out;
3466         }
3467
3468         DBG_NOTICE("RBCD: Access granted for client[%s]\n", client_name);
3469
3470         code = 0;
3471 out:
3472         SAFE_FREE(client_name);
3473         SAFE_FREE(server_name);
3474
3475         TALLOC_FREE(mem_ctx);
3476         return code;
3477 }
3478
3479 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
3480                                 struct samba_kdc_db_context **kdc_db_ctx_out)
3481 {
3482         int ldb_ret;
3483         struct ldb_message *msg;
3484         struct auth_session_info *session_info;
3485         struct samba_kdc_db_context *kdc_db_ctx;
3486         /* The idea here is very simple.  Using Kerberos to
3487          * authenticate the KDC to the LDAP server is highly likely to
3488          * be circular.
3489          *
3490          * In future we may set this up to use EXERNAL and SSL
3491          * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
3492         */
3493
3494         kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
3495         if (kdc_db_ctx == NULL) {
3496                 return NT_STATUS_NO_MEMORY;
3497         }
3498         kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
3499         kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
3500         kdc_db_ctx->msg_ctx = base_ctx->msg_ctx;
3501
3502         /* get default kdc policy */
3503         lpcfg_default_kdc_policy(mem_ctx,
3504                                  base_ctx->lp_ctx,
3505                                  &kdc_db_ctx->policy.svc_tkt_lifetime,
3506                                  &kdc_db_ctx->policy.usr_tkt_lifetime,
3507                                  &kdc_db_ctx->policy.renewal_lifetime);
3508
3509         session_info = system_session(kdc_db_ctx->lp_ctx);
3510         if (session_info == NULL) {
3511                 talloc_free(kdc_db_ctx);
3512                 return NT_STATUS_INTERNAL_ERROR;
3513         }
3514
3515         /* Setup the link to secrets.ldb */
3516
3517         kdc_db_ctx->secrets_db = secrets_db_connect(kdc_db_ctx,
3518                                                     base_ctx->lp_ctx);
3519         if (kdc_db_ctx->secrets_db == NULL) {
3520                 DEBUG(1, ("samba_kdc_setup_db_ctx: "
3521                           "Cannot open secrets.ldb for KDC backend!"));
3522                 talloc_free(kdc_db_ctx);
3523                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3524         }
3525
3526         kdc_db_ctx->fx_cookie_dn = ldb_dn_new(kdc_db_ctx,
3527                                               kdc_db_ctx->secrets_db,
3528                                               "CN=FX Cookie");
3529         if (kdc_db_ctx->fx_cookie_dn == NULL) {
3530                 talloc_free(kdc_db_ctx);
3531                 return NT_STATUS_NO_MEMORY;
3532         }
3533
3534         /* Setup the link to LDB */
3535         kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx,
3536                                           base_ctx->ev_ctx,
3537                                           base_ctx->lp_ctx,
3538                                           session_info,
3539                                           NULL,
3540                                           0);
3541         if (kdc_db_ctx->samdb == NULL) {
3542                 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot open samdb for KDC backend!"));
3543                 talloc_free(kdc_db_ctx);
3544                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3545         }
3546
3547         /* Find out our own krbtgt kvno */
3548         ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
3549         if (ldb_ret != LDB_SUCCESS) {
3550                 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine if we are an RODC in KDC backend: %s\n",
3551                           ldb_errstring(kdc_db_ctx->samdb)));
3552                 talloc_free(kdc_db_ctx);
3553                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3554         }
3555         if (kdc_db_ctx->rodc) {
3556                 int my_krbtgt_number;
3557                 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
3558                 struct ldb_dn *account_dn;
3559                 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
3560                 if (!server_dn) {
3561                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server DN in KDC backend: %s\n",
3562                                   ldb_errstring(kdc_db_ctx->samdb)));
3563                         talloc_free(kdc_db_ctx);
3564                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3565                 }
3566
3567                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
3568                                              "serverReference", &account_dn);
3569                 if (ldb_ret != LDB_SUCCESS) {
3570                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server account in KDC backend: %s\n",
3571                                   ldb_errstring(kdc_db_ctx->samdb)));
3572                         talloc_free(kdc_db_ctx);
3573                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3574                 }
3575
3576                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
3577                                              "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
3578                 talloc_free(account_dn);
3579                 if (ldb_ret != LDB_SUCCESS) {
3580                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine RODC krbtgt account in KDC backend: %s\n",
3581                                   ldb_errstring(kdc_db_ctx->samdb)));
3582                         talloc_free(kdc_db_ctx);
3583                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3584                 }
3585
3586                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
3587                                           &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
3588                                           secondary_keytab,
3589                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
3590                                           "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
3591                 if (ldb_ret != LDB_SUCCESS) {
3592                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
3593                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
3594                                   ldb_errstring(kdc_db_ctx->samdb),
3595                                   ldb_strerror(ldb_ret)));
3596                         talloc_free(kdc_db_ctx);
3597                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3598                 }
3599                 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
3600                 if (my_krbtgt_number == -1) {
3601                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
3602                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
3603                                   my_krbtgt_number));
3604                         talloc_free(kdc_db_ctx);
3605                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3606                 }
3607                 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
3608
3609         } else {
3610                 kdc_db_ctx->my_krbtgt_number = 0;
3611                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
3612                                           &msg,
3613                                           ldb_get_default_basedn(kdc_db_ctx->samdb),
3614                                           LDB_SCOPE_SUBTREE,
3615                                           krbtgt_attrs,
3616                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
3617                                           "(&(objectClass=user)(samAccountName=krbtgt))");
3618
3619                 if (ldb_ret != LDB_SUCCESS) {
3620                         DEBUG(1, ("samba_kdc_setup_db_ctx: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
3621                         talloc_free(kdc_db_ctx);
3622                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3623                 }
3624                 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
3625                 kdc_db_ctx->my_krbtgt_number = 0;
3626                 talloc_free(msg);
3627         }
3628         *kdc_db_ctx_out = kdc_db_ctx;
3629         return NT_STATUS_OK;
3630 }
3631
3632 krb5_error_code dsdb_extract_aes_256_key(krb5_context context,
3633                                          TALLOC_CTX *mem_ctx,
3634                                          const struct ldb_message *msg,
3635                                          uint32_t user_account_control,
3636                                          const uint32_t *kvno,
3637                                          uint32_t *kvno_out,
3638                                          DATA_BLOB *aes_256_key,
3639                                          DATA_BLOB *salt)
3640 {
3641         krb5_error_code krb5_ret;
3642         uint32_t supported_enctypes;
3643         unsigned flags = SDB_F_GET_CLIENT;
3644         struct sdb_entry sentry = {};
3645
3646         if (kvno != NULL) {
3647                 flags |= SDB_F_KVNO_SPECIFIED;
3648         }
3649
3650         krb5_ret = samba_kdc_message2entry_keys(context,
3651                                                 mem_ctx,
3652                                                 msg,
3653                                                 false, /* is_krbtgt */
3654                                                 false, /* is_rodc */
3655                                                 user_account_control,
3656                                                 SAMBA_KDC_ENT_TYPE_CLIENT,
3657                                                 flags,
3658                                                 (kvno != NULL) ? *kvno : 0,
3659                                                 &sentry,
3660                                                 ENC_HMAC_SHA1_96_AES256,
3661                                                 &supported_enctypes);
3662         if (krb5_ret != 0) {
3663                 DBG_ERR("Failed to parse supplementalCredentials "
3664                         "of %s with %s kvno using "
3665                         "ENCTYPE_HMAC_SHA1_96_AES256 "
3666                         "Kerberos Key: %s\n",
3667                         ldb_dn_get_linearized(msg->dn),
3668                         (kvno != NULL) ? "previous" : "current",
3669                         krb5_get_error_message(context,
3670                                                krb5_ret));
3671                 return krb5_ret;
3672         }
3673
3674         if ((supported_enctypes & ENC_HMAC_SHA1_96_AES256) == 0 ||
3675             sentry.keys.len != 1) {
3676                 DBG_INFO("Failed to find a ENCTYPE_HMAC_SHA1_96_AES256 "
3677                          "key in supplementalCredentials "
3678                          "of %s at KVNO %u (got %u keys, expected 1)\n",
3679                          ldb_dn_get_linearized(msg->dn),
3680                          sentry.kvno,
3681                          sentry.keys.len);
3682                 sdb_entry_free(&sentry);
3683                 return ENOENT;
3684         }
3685
3686         if (sentry.keys.val[0].salt == NULL) {
3687                 DBG_INFO("Failed to find a salt in "
3688                          "supplementalCredentials "
3689                          "of %s at KVNO %u\n",
3690                          ldb_dn_get_linearized(msg->dn),
3691                          sentry.kvno);
3692                 sdb_entry_free(&sentry);
3693                 return ENOENT;
3694         }
3695
3696         if (aes_256_key != NULL) {
3697                 *aes_256_key = data_blob_talloc(mem_ctx,
3698                                                 KRB5_KEY_DATA(&sentry.keys.val[0].key),
3699                                                 KRB5_KEY_LENGTH(&sentry.keys.val[0].key));
3700                 if (aes_256_key->data == NULL) {
3701                         sdb_entry_free(&sentry);
3702                         return ENOMEM;
3703                 }
3704                 talloc_keep_secret(aes_256_key->data);
3705         }
3706
3707         if (salt != NULL) {
3708                 *salt = data_blob_talloc(mem_ctx,
3709                                          sentry.keys.val[0].salt->salt.data,
3710                                          sentry.keys.val[0].salt->salt.length);
3711                 if (salt->data == NULL) {
3712                         sdb_entry_free(&sentry);
3713                         return ENOMEM;
3714                 }
3715         }
3716
3717         if (kvno_out != NULL) {
3718                 *kvno_out = sentry.kvno;
3719         }
3720
3721         sdb_entry_free(&sentry);
3722
3723         return 0;
3724 }