xref: /netbsd-src/crypto/external/bsd/heimdal/dist/kdc/pkinit.c (revision afab4e300d3a9fb07dd8c80daf53d0feb3345706)
1 /*	$NetBSD: pkinit.c,v 1.6 2023/06/19 21:41:42 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 2003 - 2016 Kungliga Tekniska Högskolan
5  * (Royal Institute of Technology, Stockholm, Sweden).
6  * All rights reserved.
7  *
8  * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  *
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * 3. Neither the name of the Institute nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 
38 #include "kdc_locl.h"
39 
40 #ifdef PKINIT
41 
42 #include <krb5/heim_asn1.h>
43 #include <krb5/rfc2459_asn1.h>
44 #include <krb5/cms_asn1.h>
45 #include <krb5/pkinit_asn1.h>
46 
47 #include <krb5/hx509.h>
48 #include "crypto-headers.h"
49 
50 struct pk_client_params {
51     enum krb5_pk_type type;
52     enum keyex_enum keyex;
53     union {
54 	struct {
55 	    BIGNUM *public_key;
56 	    DH *key;
57 	} dh;
58 	struct {
59 	    void *public_key;
60 	    void *key;
61 	} ecdh;
62     } u;
63     hx509_cert cert;
64     unsigned nonce;
65     EncryptionKey reply_key;
66     char *dh_group_name;
67     hx509_peer_info peer;
68     hx509_certs client_anchors;
69     hx509_verify_ctx verify_ctx;
70 };
71 
72 struct pk_principal_mapping {
73     unsigned int len;
74     struct pk_allowed_princ {
75 	krb5_principal principal;
76 	char *subject;
77     } *val;
78 };
79 
80 static struct krb5_pk_identity *kdc_identity;
81 static struct pk_principal_mapping principal_mappings;
82 static struct krb5_dh_moduli **moduli;
83 
84 static struct {
85     krb5_data data;
86     time_t expire;
87     time_t next_update;
88 } ocsp;
89 
90 /*
91  *
92  */
93 
94 static krb5_error_code
pk_check_pkauthenticator_win2k(krb5_context context,PKAuthenticator_Win2k * a,const KDC_REQ * req)95 pk_check_pkauthenticator_win2k(krb5_context context,
96 			       PKAuthenticator_Win2k *a,
97 			       const KDC_REQ *req)
98 {
99     krb5_timestamp now;
100 
101     krb5_timeofday (context, &now);
102 
103     /* XXX cusec */
104     if (a->ctime == 0 || labs(a->ctime - now) > context->max_skew) {
105 	krb5_clear_error_message(context);
106 	return KRB5KRB_AP_ERR_SKEW;
107     }
108     return 0;
109 }
110 
111 static krb5_error_code
pk_check_pkauthenticator(krb5_context context,PKAuthenticator * a,const KDC_REQ * req)112 pk_check_pkauthenticator(krb5_context context,
113 			 PKAuthenticator *a,
114 			 const KDC_REQ *req)
115 {
116     u_char *buf = NULL;
117     size_t buf_size;
118     krb5_error_code ret;
119     size_t len = 0;
120     krb5_timestamp now;
121     Checksum checksum;
122 
123     krb5_timeofday (context, &now);
124 
125     /* XXX cusec */
126     if (a->ctime == 0 || labs(a->ctime - now) > context->max_skew) {
127 	krb5_clear_error_message(context);
128 	return KRB5KRB_AP_ERR_SKEW;
129     }
130 
131     ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, &req->req_body, &len, ret);
132     if (ret) {
133 	krb5_clear_error_message(context);
134 	return ret;
135     }
136     if (buf_size != len)
137 	krb5_abortx(context, "Internal error in ASN.1 encoder");
138 
139     ret = krb5_create_checksum(context,
140 			       NULL,
141 			       0,
142 			       CKSUMTYPE_SHA1,
143 			       buf,
144 			       len,
145 			       &checksum);
146     free(buf);
147     if (ret) {
148 	krb5_clear_error_message(context);
149 	return ret;
150     }
151 
152     if (a->paChecksum == NULL) {
153 	krb5_clear_error_message(context);
154 	ret = KRB5_KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED;
155 	goto out;
156     }
157 
158     if (der_heim_octet_string_cmp(a->paChecksum, &checksum.checksum) != 0) {
159 	krb5_clear_error_message(context);
160 	ret = KRB5KRB_ERR_GENERIC;
161     }
162 
163 out:
164     free_Checksum(&checksum);
165 
166     return ret;
167 }
168 
169 void
_kdc_pk_free_client_param(krb5_context context,pk_client_params * cp)170 _kdc_pk_free_client_param(krb5_context context, pk_client_params *cp)
171 {
172     if (cp == NULL)
173         return;
174     if (cp->cert)
175 	hx509_cert_free(cp->cert);
176     if (cp->verify_ctx)
177 	hx509_verify_destroy_ctx(cp->verify_ctx);
178     if (cp->keyex == USE_DH) {
179 	if (cp->u.dh.key)
180 	    DH_free(cp->u.dh.key);
181 	if (cp->u.dh.public_key)
182 	    BN_free(cp->u.dh.public_key);
183     }
184     if (cp->keyex == USE_ECDH)
185         _kdc_pk_free_client_ec_param(context, cp->u.ecdh.key,
186                                      cp->u.ecdh.public_key);
187     krb5_free_keyblock_contents(context, &cp->reply_key);
188     if (cp->dh_group_name)
189 	free(cp->dh_group_name);
190     if (cp->peer)
191 	hx509_peer_info_free(cp->peer);
192     if (cp->client_anchors)
193 	hx509_certs_free(&cp->client_anchors);
194     memset(cp, 0, sizeof(*cp));
195     free(cp);
196 }
197 
198 static krb5_error_code
generate_dh_keyblock(krb5_context context,pk_client_params * client_params,krb5_enctype enctype)199 generate_dh_keyblock(krb5_context context,
200 		     pk_client_params *client_params,
201                      krb5_enctype enctype)
202 {
203     unsigned char *dh_gen_key = NULL;
204     krb5_keyblock key;
205     krb5_error_code ret;
206     size_t dh_gen_keylen, size;
207 
208     memset(&key, 0, sizeof(key));
209 
210     if (client_params->keyex == USE_DH) {
211 
212 	if (client_params->u.dh.public_key == NULL) {
213 	    ret = KRB5KRB_ERR_GENERIC;
214 	    krb5_set_error_message(context, ret, "missing DH public_key");
215 	    goto out;
216 	}
217 
218 	if (!DH_generate_key(client_params->u.dh.key)) {
219 	    ret = KRB5KRB_ERR_GENERIC;
220 	    krb5_set_error_message(context, ret,
221 				   "Can't generate Diffie-Hellman keys");
222 	    goto out;
223 	}
224 
225 	size = DH_size(client_params->u.dh.key);
226 
227 	dh_gen_key = malloc(size);
228 	if (dh_gen_key == NULL) {
229 	    ret = ENOMEM;
230 	    krb5_set_error_message(context, ret, "malloc: out of memory");
231 	    goto out;
232 	}
233 
234 	dh_gen_keylen = DH_compute_key(dh_gen_key,client_params->u.dh.public_key, client_params->u.dh.key);
235 	if (dh_gen_keylen == (size_t)-1) {
236 	    ret = KRB5KRB_ERR_GENERIC;
237 	    krb5_set_error_message(context, ret,
238 				   "Can't compute Diffie-Hellman key");
239 	    goto out;
240 	}
241 	if (dh_gen_keylen < size) {
242 	    size -= dh_gen_keylen;
243 	    memmove(dh_gen_key + size, dh_gen_key, dh_gen_keylen);
244 	    memset(dh_gen_key, 0, size);
245 	}
246     } else if (client_params->keyex == USE_ECDH) {
247 	if (client_params->u.ecdh.public_key == NULL) {
248 	    ret = KRB5KRB_ERR_GENERIC;
249 	    krb5_set_error_message(context, ret, "missing ECDH public_key");
250 	    goto out;
251 	}
252         ret = _kdc_generate_ecdh_keyblock(context,
253                                           client_params->u.ecdh.public_key,
254                                           &client_params->u.ecdh.key,
255                                           &dh_gen_key, &dh_gen_keylen);
256         if (ret)
257             goto out;
258     } else {
259 	ret = KRB5KRB_ERR_GENERIC;
260 	krb5_set_error_message(context, ret,
261 			       "Diffie-Hellman not selected keys");
262 	goto out;
263     }
264 
265     ret = _krb5_pk_octetstring2key(context,
266 				   enctype,
267 				   dh_gen_key, dh_gen_keylen,
268 				   NULL, NULL,
269 				   &client_params->reply_key);
270 
271  out:
272     if (dh_gen_key)
273 	free(dh_gen_key);
274     if (key.keyvalue.data)
275 	krb5_free_keyblock_contents(context, &key);
276 
277     return ret;
278 }
279 
280 static BIGNUM *
integer_to_BN(krb5_context context,const char * field,heim_integer * f)281 integer_to_BN(krb5_context context, const char *field, heim_integer *f)
282 {
283     BIGNUM *bn;
284 
285     bn = BN_bin2bn((const unsigned char *)f->data, f->length, NULL);
286     if (bn == NULL) {
287 	krb5_set_error_message(context, KRB5_BADMSGTYPE,
288 			       "PKINIT: parsing BN failed %s", field);
289 	return NULL;
290     }
291     BN_set_negative(bn, f->negative);
292     return bn;
293 }
294 
295 static krb5_error_code
get_dh_param(krb5_context context,krb5_kdc_configuration * config,SubjectPublicKeyInfo * dh_key_info,pk_client_params * client_params)296 get_dh_param(krb5_context context,
297 	     krb5_kdc_configuration *config,
298 	     SubjectPublicKeyInfo *dh_key_info,
299 	     pk_client_params *client_params)
300 {
301     DomainParameters dhparam;
302     DH *dh = NULL;
303     krb5_error_code ret;
304 
305     memset(&dhparam, 0, sizeof(dhparam));
306 
307     if ((dh_key_info->subjectPublicKey.length % 8) != 0) {
308 	ret = KRB5_BADMSGTYPE;
309 	krb5_set_error_message(context, ret,
310 			       "PKINIT: subjectPublicKey not aligned "
311 			       "to 8 bit boundary");
312 	goto out;
313     }
314 
315     if (dh_key_info->algorithm.parameters == NULL) {
316 	krb5_set_error_message(context, KRB5_BADMSGTYPE,
317 			       "PKINIT missing algorithm parameter "
318 			      "in clientPublicValue");
319 	return KRB5_BADMSGTYPE;
320     }
321 
322     ret = decode_DomainParameters(dh_key_info->algorithm.parameters->data,
323 				  dh_key_info->algorithm.parameters->length,
324 				  &dhparam,
325 				  NULL);
326     if (ret) {
327 	krb5_set_error_message(context, ret, "Can't decode algorithm "
328 			       "parameters in clientPublicValue");
329 	goto out;
330     }
331 
332     ret = _krb5_dh_group_ok(context, config->pkinit_dh_min_bits,
333 			    &dhparam.p, &dhparam.g, dhparam.q, moduli,
334 			    &client_params->dh_group_name);
335     if (ret) {
336 	/* XXX send back proposal of better group */
337 	goto out;
338     }
339 
340     dh = DH_new();
341     if (dh == NULL) {
342 	ret = ENOMEM;
343 	krb5_set_error_message(context, ret, "Cannot create DH structure");
344 	goto out;
345     }
346     ret = KRB5_BADMSGTYPE;
347     BIGNUM *p, *q, *g;
348     p = integer_to_BN(context, "DH prime", &dhparam.p);
349     if (p == NULL)
350 	goto out;
351     g = integer_to_BN(context, "DH base", &dhparam.g);
352     if (g == NULL)
353 	goto out;
354 
355     if (dhparam.q) {
356 	q = integer_to_BN(context, "DH p-1 factor", dhparam.q);
357 	if (q == NULL)
358 	    goto out;
359     } else
360 	q = NULL;
361 
362 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
363     dh->p = p;
364     if (q)
365 	    dh->q = q;
366     dh->g = g;
367 #else
368     DH_set0_pqg(dh, p, q, g);
369 #endif
370     {
371 	heim_integer glue;
372 	size_t size;
373 
374 	ret = decode_DHPublicKey(dh_key_info->subjectPublicKey.data,
375 				 dh_key_info->subjectPublicKey.length / 8,
376 				 &glue,
377 				 &size);
378 	if (ret) {
379 	    krb5_clear_error_message(context);
380 	    return ret;
381 	}
382 
383 	client_params->u.dh.public_key = integer_to_BN(context,
384 						       "subjectPublicKey",
385 						       &glue);
386 	der_free_heim_integer(&glue);
387 	if (client_params->u.dh.public_key == NULL) {
388 	    ret = KRB5_BADMSGTYPE;
389 	    goto out;
390 	}
391     }
392 
393     client_params->u.dh.key = dh;
394     dh = NULL;
395     ret = 0;
396 
397  out:
398     if (dh)
399 	DH_free(dh);
400     free_DomainParameters(&dhparam);
401     return ret;
402 }
403 
404 krb5_error_code
_kdc_pk_rd_padata(krb5_context context,krb5_kdc_configuration * config,const KDC_REQ * req,const PA_DATA * pa,hdb_entry_ex * client,pk_client_params ** ret_params)405 _kdc_pk_rd_padata(krb5_context context,
406 		  krb5_kdc_configuration *config,
407 		  const KDC_REQ *req,
408 		  const PA_DATA *pa,
409 		  hdb_entry_ex *client,
410 		  pk_client_params **ret_params)
411 {
412     pk_client_params *cp;
413     krb5_error_code ret;
414     heim_oid eContentType = { 0, NULL }, contentInfoOid = { 0, NULL };
415     krb5_data eContent = { 0, NULL };
416     krb5_data signed_content = { 0, NULL };
417     const char *type = "unknown type";
418     hx509_certs trust_anchors;
419     int have_data = 0;
420     const HDB_Ext_PKINIT_cert *pc;
421 
422     *ret_params = NULL;
423 
424     if (!config->enable_pkinit) {
425 	kdc_log(context, config, 0, "PK-INIT request but PK-INIT not enabled");
426 	krb5_clear_error_message(context);
427 	return 0;
428     }
429 
430     cp = calloc(1, sizeof(*cp));
431     if (cp == NULL) {
432 	krb5_clear_error_message(context);
433 	ret = ENOMEM;
434 	goto out;
435     }
436 
437     ret = hx509_certs_init(context->hx509ctx,
438 			   "MEMORY:trust-anchors",
439 			   0, NULL, &trust_anchors);
440     if (ret) {
441 	krb5_set_error_message(context, ret, "failed to create trust anchors");
442 	goto out;
443     }
444 
445     ret = hx509_certs_merge(context->hx509ctx, trust_anchors,
446 			    kdc_identity->anchors);
447     if (ret) {
448 	hx509_certs_free(&trust_anchors);
449 	krb5_set_error_message(context, ret, "failed to create verify context");
450 	goto out;
451     }
452 
453     /* Add any registered certificates for this client as trust anchors */
454     ret = hdb_entry_get_pkinit_cert(&client->entry, &pc);
455     if (ret == 0 && pc != NULL) {
456 	hx509_cert cert;
457 	unsigned int i;
458 
459 	for (i = 0; i < pc->len; i++) {
460 	    cert = hx509_cert_init_data(context->hx509ctx,
461 					pc->val[i].cert.data,
462 					pc->val[i].cert.length,
463 					NULL);
464 	    if (cert == NULL)
465 		continue;
466 	    hx509_certs_add(context->hx509ctx, trust_anchors, cert);
467 	    hx509_cert_free(cert);
468 	}
469     }
470 
471     ret = hx509_verify_init_ctx(context->hx509ctx, &cp->verify_ctx);
472     if (ret) {
473 	hx509_certs_free(&trust_anchors);
474 	krb5_set_error_message(context, ret, "failed to create verify context");
475 	goto out;
476     }
477 
478     hx509_verify_set_time(cp->verify_ctx, kdc_time);
479     hx509_verify_attach_anchors(cp->verify_ctx, trust_anchors);
480     hx509_certs_free(&trust_anchors);
481 
482     if (config->pkinit_allow_proxy_certs)
483 	hx509_verify_set_proxy_certificate(cp->verify_ctx, 1);
484 
485     if (pa->padata_type == KRB5_PADATA_PK_AS_REQ_WIN) {
486 	PA_PK_AS_REQ_Win2k r;
487 
488 	type = "PK-INIT-Win2k";
489 
490 	if (_kdc_is_anonymous(context, client->entry.principal)) {
491 	    ret = KRB5_KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED;
492 	    krb5_set_error_message(context, ret,
493 				   "Anon not supported in RSA mode");
494 	    goto out;
495 	}
496 
497 	ret = decode_PA_PK_AS_REQ_Win2k(pa->padata_value.data,
498 					pa->padata_value.length,
499 					&r,
500 					NULL);
501 	if (ret) {
502 	    krb5_set_error_message(context, ret, "Can't decode "
503 				   "PK-AS-REQ-Win2k: %d", ret);
504 	    goto out;
505 	}
506 
507 	ret = hx509_cms_unwrap_ContentInfo(&r.signed_auth_pack,
508 					   &contentInfoOid,
509 					   &signed_content,
510 					   &have_data);
511 	free_PA_PK_AS_REQ_Win2k(&r);
512 	if (ret) {
513 	    krb5_set_error_message(context, ret,
514 				   "Can't unwrap ContentInfo(win): %d", ret);
515 	    goto out;
516 	}
517 
518     } else if (pa->padata_type == KRB5_PADATA_PK_AS_REQ) {
519 	PA_PK_AS_REQ r;
520 
521 	type = "PK-INIT-IETF";
522 
523 	ret = decode_PA_PK_AS_REQ(pa->padata_value.data,
524 				  pa->padata_value.length,
525 				  &r,
526 				  NULL);
527 	if (ret) {
528 	    krb5_set_error_message(context, ret,
529 				   "Can't decode PK-AS-REQ: %d", ret);
530 	    goto out;
531 	}
532 
533 	/* XXX look at r.kdcPkId */
534 	if (r.trustedCertifiers) {
535 	    ExternalPrincipalIdentifiers *edi = r.trustedCertifiers;
536 	    unsigned int i, maxedi;
537 
538 	    ret = hx509_certs_init(context->hx509ctx,
539 				   "MEMORY:client-anchors",
540 				   0, NULL,
541 				   &cp->client_anchors);
542 	    if (ret) {
543 		krb5_set_error_message(context, ret,
544 				       "Can't allocate client anchors: %d",
545 				       ret);
546 		goto out;
547 
548 	    }
549 	    /*
550 	     * If the client sent more then 10 EDI, don't bother
551 	     * looking more then 10 of performance reasons.
552 	     */
553 	    maxedi = edi->len;
554 	    if (maxedi > 10)
555 		maxedi = 10;
556 	    for (i = 0; i < maxedi; i++) {
557 		IssuerAndSerialNumber iasn;
558 		hx509_query *q;
559 		hx509_cert cert;
560 		size_t size;
561 
562 		if (edi->val[i].issuerAndSerialNumber == NULL)
563 		    continue;
564 
565 		ret = hx509_query_alloc(context->hx509ctx, &q);
566 		if (ret) {
567 		    krb5_set_error_message(context, ret,
568 					  "Failed to allocate hx509_query");
569 		    goto out;
570 		}
571 
572 		ret = decode_IssuerAndSerialNumber(edi->val[i].issuerAndSerialNumber->data,
573 						   edi->val[i].issuerAndSerialNumber->length,
574 						   &iasn,
575 						   &size);
576 		if (ret) {
577 		    hx509_query_free(context->hx509ctx, q);
578 		    continue;
579 		}
580 		ret = hx509_query_match_issuer_serial(q, &iasn.issuer, &iasn.serialNumber);
581 		free_IssuerAndSerialNumber(&iasn);
582 		if (ret) {
583 		    hx509_query_free(context->hx509ctx, q);
584 		    continue;
585 		}
586 
587 		ret = hx509_certs_find(context->hx509ctx,
588 				       kdc_identity->certs,
589 				       q,
590 				       &cert);
591 		hx509_query_free(context->hx509ctx, q);
592 		if (ret)
593 		    continue;
594 		hx509_certs_add(context->hx509ctx,
595 				cp->client_anchors, cert);
596 		hx509_cert_free(cert);
597 	    }
598 	}
599 
600 	ret = hx509_cms_unwrap_ContentInfo(&r.signedAuthPack,
601 					   &contentInfoOid,
602 					   &signed_content,
603 					   &have_data);
604 	free_PA_PK_AS_REQ(&r);
605 	if (ret) {
606 	    krb5_set_error_message(context, ret,
607 				   "Can't unwrap ContentInfo: %d", ret);
608 	    goto out;
609 	}
610 
611     } else {
612 	krb5_clear_error_message(context);
613 	ret = KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
614 	goto out;
615     }
616 
617     ret = der_heim_oid_cmp(&contentInfoOid, &asn1_oid_id_pkcs7_signedData);
618     if (ret != 0) {
619 	ret = KRB5KRB_ERR_GENERIC;
620 	krb5_set_error_message(context, ret,
621 			       "PK-AS-REQ-Win2k invalid content type oid");
622 	goto out;
623     }
624 
625     if (!have_data) {
626 	ret = KRB5KRB_ERR_GENERIC;
627 	krb5_set_error_message(context, ret,
628 			      "PK-AS-REQ-Win2k no signed auth pack");
629 	goto out;
630     }
631 
632     {
633 	hx509_certs signer_certs;
634 	int flags = HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH; /* BTMM */
635 
636 	if (_kdc_is_anonymous(context, client->entry.principal)
637 	    || (config->historical_anon_realm && _kdc_is_anon_request(req)))
638 	    flags |= HX509_CMS_VS_ALLOW_ZERO_SIGNER;
639 
640 	ret = hx509_cms_verify_signed(context->hx509ctx,
641 				      cp->verify_ctx,
642 				      flags,
643 				      signed_content.data,
644 				      signed_content.length,
645 				      NULL,
646 				      kdc_identity->certpool,
647 				      &eContentType,
648 				      &eContent,
649 				      &signer_certs);
650 	if (ret) {
651 	    char *s = hx509_get_error_string(context->hx509ctx, ret);
652 	    krb5_warnx(context, "PKINIT: failed to verify signature: %s: %d",
653 		       s, ret);
654 	    free(s);
655 	    goto out;
656 	}
657 
658 	if (signer_certs) {
659 	    ret = hx509_get_one_cert(context->hx509ctx, signer_certs,
660 				     &cp->cert);
661 	    hx509_certs_free(&signer_certs);
662 	}
663 	if (ret)
664 	    goto out;
665     }
666 
667     /* Signature is correct, now verify the signed message */
668     if (der_heim_oid_cmp(&eContentType, &asn1_oid_id_pkcs7_data) != 0 &&
669 	der_heim_oid_cmp(&eContentType, &asn1_oid_id_pkauthdata) != 0)
670     {
671 	ret = KRB5_BADMSGTYPE;
672 	krb5_set_error_message(context, ret, "got wrong oid for pkauthdata");
673 	goto out;
674     }
675 
676     if (pa->padata_type == KRB5_PADATA_PK_AS_REQ_WIN) {
677 	AuthPack_Win2k ap;
678 
679 	ret = decode_AuthPack_Win2k(eContent.data,
680 				    eContent.length,
681 				    &ap,
682 				    NULL);
683 	if (ret) {
684 	    krb5_set_error_message(context, ret,
685 				   "Can't decode AuthPack: %d", ret);
686 	    goto out;
687 	}
688 
689 	ret = pk_check_pkauthenticator_win2k(context,
690 					     &ap.pkAuthenticator,
691 					     req);
692 	if (ret) {
693 	    free_AuthPack_Win2k(&ap);
694 	    goto out;
695 	}
696 
697 	cp->type = PKINIT_WIN2K;
698 	cp->nonce = ap.pkAuthenticator.nonce;
699 
700 	if (ap.clientPublicValue) {
701 	    ret = KRB5KRB_ERR_GENERIC;
702 	    krb5_set_error_message(context, ret,
703 				   "DH not supported for windows");
704 	    goto out;
705 	}
706 	free_AuthPack_Win2k(&ap);
707 
708     } else if (pa->padata_type == KRB5_PADATA_PK_AS_REQ) {
709 	AuthPack ap;
710 
711 	ret = decode_AuthPack(eContent.data,
712 			      eContent.length,
713 			      &ap,
714 			      NULL);
715 	if (ret) {
716 	    krb5_set_error_message(context, ret,
717 				   "Can't decode AuthPack: %d", ret);
718 	    free_AuthPack(&ap);
719 	    goto out;
720 	}
721 
722 	if (_kdc_is_anonymous(context, client->entry.principal) &&
723 	    ap.clientPublicValue == NULL) {
724 	    free_AuthPack(&ap);
725 	    ret = KRB5_KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED;
726 	    krb5_set_error_message(context, ret,
727 				   "Anon not supported in RSA mode");
728 	    goto out;
729 	}
730 
731 	ret = pk_check_pkauthenticator(context,
732 				       &ap.pkAuthenticator,
733 				       req);
734 	if (ret) {
735 	    free_AuthPack(&ap);
736 	    goto out;
737 	}
738 
739 	cp->type = PKINIT_27;
740 	cp->nonce = ap.pkAuthenticator.nonce;
741 
742 	if (ap.clientPublicValue) {
743 	    if (der_heim_oid_cmp(&ap.clientPublicValue->algorithm.algorithm, &asn1_oid_id_dhpublicnumber) == 0) {
744 		cp->keyex = USE_DH;
745 		ret = get_dh_param(context, config,
746 				   ap.clientPublicValue, cp);
747 	    } else if (der_heim_oid_cmp(&ap.clientPublicValue->algorithm.algorithm, &asn1_oid_id_ecPublicKey) == 0) {
748 		cp->keyex = USE_ECDH;
749                 ret = _kdc_get_ecdh_param(context, config,
750                                           ap.clientPublicValue,
751                                           &cp->u.ecdh.public_key);
752 	    } else {
753 		ret = KRB5_BADMSGTYPE;
754 		krb5_set_error_message(context, ret, "PKINIT unknown DH mechanism");
755 	    }
756 	    if (ret) {
757 		free_AuthPack(&ap);
758 		goto out;
759 	    }
760 	} else
761 	    cp->keyex = USE_RSA;
762 
763 	ret = hx509_peer_info_alloc(context->hx509ctx,
764 					&cp->peer);
765 	if (ret) {
766 	    free_AuthPack(&ap);
767 	    goto out;
768 	}
769 
770 	if (ap.supportedCMSTypes) {
771 	    ret = hx509_peer_info_set_cms_algs(context->hx509ctx,
772 					       cp->peer,
773 					       ap.supportedCMSTypes->val,
774 					       ap.supportedCMSTypes->len);
775 	    if (ret) {
776 		free_AuthPack(&ap);
777 		goto out;
778 	    }
779 	} else {
780 	    /* assume old client */
781 	    hx509_peer_info_add_cms_alg(context->hx509ctx, cp->peer,
782 					hx509_crypto_des_rsdi_ede3_cbc());
783 	    hx509_peer_info_add_cms_alg(context->hx509ctx, cp->peer,
784 					hx509_signature_rsa_with_sha1());
785 	    hx509_peer_info_add_cms_alg(context->hx509ctx, cp->peer,
786 					hx509_signature_sha1());
787 	}
788 	free_AuthPack(&ap);
789     } else
790 	krb5_abortx(context, "internal pkinit error");
791 
792     kdc_log(context, config, 0, "PK-INIT request of type %s", type);
793 
794 out:
795     if (ret)
796 	krb5_warn(context, ret, "PKINIT");
797 
798     if (signed_content.data)
799 	free(signed_content.data);
800     krb5_data_free(&eContent);
801     der_free_oid(&eContentType);
802     der_free_oid(&contentInfoOid);
803     if (ret) {
804         _kdc_pk_free_client_param(context, cp);
805     } else
806 	*ret_params = cp;
807     return ret;
808 }
809 
810 /*
811  *
812  */
813 
814 static krb5_error_code
BN_to_integer(krb5_context context,const BIGNUM * bn,heim_integer * integer)815 BN_to_integer(krb5_context context, const BIGNUM *bn, heim_integer *integer)
816 {
817     integer->length = BN_num_bytes(bn);
818     integer->data = malloc(integer->length);
819     if (integer->data == NULL) {
820 	krb5_clear_error_message(context);
821 	return ENOMEM;
822     }
823     BN_bn2bin(bn, integer->data);
824     integer->negative = BN_is_negative(bn);
825     return 0;
826 }
827 
828 static krb5_error_code
pk_mk_pa_reply_enckey(krb5_context context,krb5_kdc_configuration * config,pk_client_params * cp,const KDC_REQ * req,const krb5_data * req_buffer,krb5_keyblock * reply_key,ContentInfo * content_info,hx509_cert * kdc_cert)829 pk_mk_pa_reply_enckey(krb5_context context,
830 		      krb5_kdc_configuration *config,
831 		      pk_client_params *cp,
832 		      const KDC_REQ *req,
833 		      const krb5_data *req_buffer,
834 		      krb5_keyblock *reply_key,
835 		      ContentInfo *content_info,
836 		      hx509_cert *kdc_cert)
837 {
838     const heim_oid *envelopedAlg = NULL, *sdAlg = NULL, *evAlg = NULL;
839     krb5_error_code ret;
840     krb5_data buf, signed_data;
841     size_t size = 0;
842     int do_win2k = 0;
843 
844     krb5_data_zero(&buf);
845     krb5_data_zero(&signed_data);
846 
847     *kdc_cert = NULL;
848 
849     /*
850      * If the message client is a win2k-type but it send pa data
851      * 09-binding it expects a IETF (checksum) reply so there can be
852      * no replay attacks.
853      */
854 
855     switch (cp->type) {
856     case PKINIT_WIN2K: {
857 	int i = 0;
858 	if (_kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_09_BINDING) == NULL
859 	    && config->pkinit_require_binding == 0)
860 	{
861 	    do_win2k = 1;
862 	}
863 	sdAlg = &asn1_oid_id_pkcs7_data;
864 	evAlg = &asn1_oid_id_pkcs7_data;
865 	envelopedAlg = &asn1_oid_id_rsadsi_des_ede3_cbc;
866 	break;
867     }
868     case PKINIT_27:
869 	sdAlg = &asn1_oid_id_pkrkeydata;
870 	evAlg = &asn1_oid_id_pkcs7_signedData;
871 	break;
872     default:
873 	krb5_abortx(context, "internal pkinit error");
874     }
875 
876     if (do_win2k) {
877 	ReplyKeyPack_Win2k kp;
878 	memset(&kp, 0, sizeof(kp));
879 
880 	ret = copy_EncryptionKey(reply_key, &kp.replyKey);
881 	if (ret) {
882 	    krb5_clear_error_message(context);
883 	    goto out;
884 	}
885 	kp.nonce = cp->nonce;
886 
887 	ASN1_MALLOC_ENCODE(ReplyKeyPack_Win2k,
888 			   buf.data, buf.length,
889 			   &kp, &size,ret);
890 	free_ReplyKeyPack_Win2k(&kp);
891     } else {
892 	krb5_crypto ascrypto;
893 	ReplyKeyPack kp;
894 	memset(&kp, 0, sizeof(kp));
895 
896 	ret = copy_EncryptionKey(reply_key, &kp.replyKey);
897 	if (ret) {
898 	    krb5_clear_error_message(context);
899 	    goto out;
900 	}
901 
902 	ret = krb5_crypto_init(context, reply_key, 0, &ascrypto);
903 	if (ret) {
904 	    krb5_clear_error_message(context);
905 	    goto out;
906 	}
907 
908 	ret = krb5_create_checksum(context, ascrypto, 6, 0,
909 				   req_buffer->data, req_buffer->length,
910 				   &kp.asChecksum);
911 	if (ret) {
912 	    krb5_clear_error_message(context);
913 	    goto out;
914 	}
915 
916 	ret = krb5_crypto_destroy(context, ascrypto);
917 	if (ret) {
918 	    krb5_clear_error_message(context);
919 	    goto out;
920 	}
921 	ASN1_MALLOC_ENCODE(ReplyKeyPack, buf.data, buf.length, &kp, &size,ret);
922 	free_ReplyKeyPack(&kp);
923     }
924     if (ret) {
925 	krb5_set_error_message(context, ret, "ASN.1 encoding of ReplyKeyPack "
926 			       "failed (%d)", ret);
927 	goto out;
928     }
929     if (buf.length != size)
930 	krb5_abortx(context, "Internal ASN.1 encoder error");
931 
932     {
933 	hx509_query *q;
934 	hx509_cert cert;
935 
936 	ret = hx509_query_alloc(context->hx509ctx, &q);
937 	if (ret)
938 	    goto out;
939 
940 	hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
941 	if (config->pkinit_kdc_friendly_name)
942 	    hx509_query_match_friendly_name(q, config->pkinit_kdc_friendly_name);
943 
944 	ret = hx509_certs_find(context->hx509ctx,
945 			       kdc_identity->certs,
946 			       q,
947 			       &cert);
948 	hx509_query_free(context->hx509ctx, q);
949 	if (ret)
950 	    goto out;
951 
952 	ret = hx509_cms_create_signed_1(context->hx509ctx,
953 					0,
954 					sdAlg,
955 					buf.data,
956 					buf.length,
957 					NULL,
958 					cert,
959 					cp->peer,
960 					cp->client_anchors,
961 					kdc_identity->certpool,
962 					&signed_data);
963 	*kdc_cert = cert;
964     }
965 
966     krb5_data_free(&buf);
967     if (ret)
968 	goto out;
969 
970     if (cp->type == PKINIT_WIN2K) {
971 	ret = hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_signedData,
972 					 &signed_data,
973 					 &buf);
974 	if (ret)
975 	    goto out;
976 	krb5_data_free(&signed_data);
977 	signed_data = buf;
978     }
979 
980     ret = hx509_cms_envelope_1(context->hx509ctx,
981 			       HX509_CMS_EV_NO_KU_CHECK,
982 			       cp->cert,
983 			       signed_data.data, signed_data.length,
984 			       envelopedAlg,
985 			       evAlg, &buf);
986     if (ret)
987 	goto out;
988 
989     ret = _krb5_pk_mk_ContentInfo(context,
990 				  &buf,
991 				  &asn1_oid_id_pkcs7_envelopedData,
992 				  content_info);
993 out:
994     if (ret && *kdc_cert) {
995         hx509_cert_free(*kdc_cert);
996 	*kdc_cert = NULL;
997     }
998 
999     krb5_data_free(&buf);
1000     krb5_data_free(&signed_data);
1001     return ret;
1002 }
1003 
1004 /*
1005  *
1006  */
1007 
1008 static krb5_error_code
pk_mk_pa_reply_dh(krb5_context context,krb5_kdc_configuration * config,pk_client_params * cp,ContentInfo * content_info,hx509_cert * kdc_cert)1009 pk_mk_pa_reply_dh(krb5_context context,
1010 		  krb5_kdc_configuration *config,
1011       		  pk_client_params *cp,
1012 		  ContentInfo *content_info,
1013 		  hx509_cert *kdc_cert)
1014 {
1015     KDCDHKeyInfo dh_info;
1016     krb5_data signed_data, buf;
1017     ContentInfo contentinfo;
1018     krb5_error_code ret;
1019     hx509_cert cert;
1020     hx509_query *q;
1021     size_t size = 0;
1022 
1023     memset(&contentinfo, 0, sizeof(contentinfo));
1024     memset(&dh_info, 0, sizeof(dh_info));
1025     krb5_data_zero(&signed_data);
1026     krb5_data_zero(&buf);
1027 
1028     *kdc_cert = NULL;
1029 
1030     if (cp->keyex == USE_DH) {
1031 	DH *kdc_dh = cp->u.dh.key;
1032 	heim_integer i;
1033 
1034 	const BIGNUM *pub_key;
1035 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
1036 	pub_key = kdc_dh->pub_key;
1037 #else
1038 	DH_get0_key(kdc_dh, &pub_key, NULL);
1039 #endif
1040 	ret = BN_to_integer(context, pub_key, &i);
1041 	if (ret)
1042 	    return ret;
1043 
1044 	ASN1_MALLOC_ENCODE(DHPublicKey, buf.data, buf.length, &i, &size, ret);
1045 	der_free_heim_integer(&i);
1046 	if (ret) {
1047 	    krb5_set_error_message(context, ret, "ASN.1 encoding of "
1048 				   "DHPublicKey failed (%d)", ret);
1049 	    return ret;
1050 	}
1051 	if (buf.length != size)
1052 	    krb5_abortx(context, "Internal ASN.1 encoder error");
1053 
1054 	dh_info.subjectPublicKey.length = buf.length * 8;
1055 	dh_info.subjectPublicKey.data = buf.data;
1056 	krb5_data_zero(&buf);
1057     } else if (cp->keyex == USE_ECDH) {
1058         unsigned char *p;
1059         ret = _kdc_serialize_ecdh_key(context, cp->u.ecdh.key, &p,
1060                                       &dh_info.subjectPublicKey.length);
1061         dh_info.subjectPublicKey.data = p;
1062         if (ret)
1063             goto out;
1064     } else
1065 	krb5_abortx(context, "no keyex selected ?");
1066 
1067 
1068     dh_info.nonce = cp->nonce;
1069 
1070     ASN1_MALLOC_ENCODE(KDCDHKeyInfo, buf.data, buf.length, &dh_info, &size,
1071 		       ret);
1072     if (ret) {
1073 	krb5_set_error_message(context, ret, "ASN.1 encoding of "
1074 			       "KdcDHKeyInfo failed (%d)", ret);
1075 	goto out;
1076     }
1077     if (buf.length != size)
1078 	krb5_abortx(context, "Internal ASN.1 encoder error");
1079 
1080     /*
1081      * Create the SignedData structure and sign the KdcDHKeyInfo
1082      * filled in above
1083      */
1084 
1085     ret = hx509_query_alloc(context->hx509ctx, &q);
1086     if (ret)
1087 	goto out;
1088 
1089     hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
1090     if (config->pkinit_kdc_friendly_name)
1091 	hx509_query_match_friendly_name(q, config->pkinit_kdc_friendly_name);
1092 
1093     ret = hx509_certs_find(context->hx509ctx,
1094 			   kdc_identity->certs,
1095 			   q,
1096 			   &cert);
1097     hx509_query_free(context->hx509ctx, q);
1098     if (ret)
1099 	goto out;
1100 
1101     ret = hx509_cms_create_signed_1(context->hx509ctx,
1102 				    0,
1103 				    &asn1_oid_id_pkdhkeydata,
1104 				    buf.data,
1105 				    buf.length,
1106 				    NULL,
1107 				    cert,
1108 				    cp->peer,
1109 				    cp->client_anchors,
1110 				    kdc_identity->certpool,
1111 				    &signed_data);
1112     if (ret) {
1113 	kdc_log(context, config, 0, "Failed signing the DH* reply: %d", ret);
1114 	goto out;
1115     }
1116     *kdc_cert = cert;
1117 
1118     ret = _krb5_pk_mk_ContentInfo(context,
1119 				  &signed_data,
1120 				  &asn1_oid_id_pkcs7_signedData,
1121 				  content_info);
1122     if (ret)
1123 	goto out;
1124 
1125  out:
1126     if (ret && *kdc_cert) {
1127 	hx509_cert_free(*kdc_cert);
1128 	*kdc_cert = NULL;
1129     }
1130 
1131     krb5_data_free(&buf);
1132     krb5_data_free(&signed_data);
1133     free_KDCDHKeyInfo(&dh_info);
1134 
1135     return ret;
1136 }
1137 
1138 /*
1139  *
1140  */
1141 
1142 krb5_error_code
_kdc_pk_mk_pa_reply(krb5_context context,krb5_kdc_configuration * config,pk_client_params * cp,const hdb_entry_ex * client,krb5_enctype sessionetype,const KDC_REQ * req,const krb5_data * req_buffer,krb5_keyblock * reply_key,krb5_keyblock * sessionkey,METHOD_DATA * md)1143 _kdc_pk_mk_pa_reply(krb5_context context,
1144 		    krb5_kdc_configuration *config,
1145 		    pk_client_params *cp,
1146 		    const hdb_entry_ex *client,
1147 		    krb5_enctype sessionetype,
1148 		    const KDC_REQ *req,
1149 		    const krb5_data *req_buffer,
1150 		    krb5_keyblock *reply_key,
1151 		    krb5_keyblock *sessionkey,
1152 		    METHOD_DATA *md)
1153 {
1154     krb5_error_code ret;
1155     void *buf = NULL;
1156     size_t len = 0, size = 0;
1157     krb5_enctype enctype;
1158     int pa_type;
1159     hx509_cert kdc_cert = NULL;
1160     size_t i;
1161 
1162     if (!config->enable_pkinit) {
1163 	krb5_clear_error_message(context);
1164 	return 0;
1165     }
1166 
1167     if (req->req_body.etype.len > 0) {
1168 	for (i = 0; i < req->req_body.etype.len; i++)
1169 	    if (krb5_enctype_valid(context, req->req_body.etype.val[i]) == 0)
1170 		break;
1171 	if (req->req_body.etype.len <= i) {
1172 	    ret = KRB5KRB_ERR_GENERIC;
1173 	    krb5_set_error_message(context, ret,
1174 				   "No valid enctype available from client");
1175 	    goto out;
1176 	}
1177 	enctype = req->req_body.etype.val[i];
1178     } else
1179 	enctype = ETYPE_DES3_CBC_SHA1;
1180 
1181     if (cp->type == PKINIT_27) {
1182 	PA_PK_AS_REP rep;
1183 	const char *type, *other = "";
1184 
1185 	memset(&rep, 0, sizeof(rep));
1186 
1187 	pa_type = KRB5_PADATA_PK_AS_REP;
1188 
1189 	if (cp->keyex == USE_RSA) {
1190 	    ContentInfo info;
1191 
1192 	    type = "enckey";
1193 
1194 	    rep.element = choice_PA_PK_AS_REP_encKeyPack;
1195 
1196 	    ret = krb5_generate_random_keyblock(context, enctype,
1197 						&cp->reply_key);
1198 	    if (ret) {
1199 		free_PA_PK_AS_REP(&rep);
1200 		goto out;
1201 	    }
1202 	    ret = pk_mk_pa_reply_enckey(context,
1203 					config,
1204 					cp,
1205 					req,
1206 					req_buffer,
1207 					&cp->reply_key,
1208 					&info,
1209 					&kdc_cert);
1210 	    if (ret) {
1211 		free_PA_PK_AS_REP(&rep);
1212 		goto out;
1213 	    }
1214 	    ASN1_MALLOC_ENCODE(ContentInfo, rep.u.encKeyPack.data,
1215 			       rep.u.encKeyPack.length, &info, &size,
1216 			       ret);
1217 	    free_ContentInfo(&info);
1218 	    if (ret) {
1219 		krb5_set_error_message(context, ret, "encoding of Key ContentInfo "
1220 				       "failed %d", ret);
1221 		free_PA_PK_AS_REP(&rep);
1222 		goto out;
1223 	    }
1224 	    if (rep.u.encKeyPack.length != size)
1225 		krb5_abortx(context, "Internal ASN.1 encoder error");
1226 
1227 	    ret = krb5_generate_random_keyblock(context, sessionetype,
1228 						sessionkey);
1229 	    if (ret) {
1230 		free_PA_PK_AS_REP(&rep);
1231 		goto out;
1232 	    }
1233 
1234 	} else {
1235 	    ContentInfo info;
1236 
1237 	    switch (cp->keyex) {
1238 	    case USE_DH: type = "dh"; break;
1239 	    case USE_ECDH: type = "ecdh"; break;
1240 	    default: krb5_abortx(context, "unknown keyex"); break;
1241 	    }
1242 
1243 	    if (cp->dh_group_name)
1244 		other = cp->dh_group_name;
1245 
1246 	    rep.element = choice_PA_PK_AS_REP_dhInfo;
1247 
1248 	    ret = generate_dh_keyblock(context, cp, enctype);
1249 	    if (ret)
1250 		return ret;
1251 
1252 	    ret = pk_mk_pa_reply_dh(context, config,
1253 				    cp,
1254 				    &info,
1255 				    &kdc_cert);
1256 	    if (ret) {
1257 		free_PA_PK_AS_REP(&rep);
1258 		krb5_set_error_message(context, ret,
1259 				       "create pa-reply-dh "
1260 				       "failed %d", ret);
1261 		goto out;
1262 	    }
1263 
1264 	    ASN1_MALLOC_ENCODE(ContentInfo, rep.u.dhInfo.dhSignedData.data,
1265 			       rep.u.dhInfo.dhSignedData.length, &info, &size,
1266 			       ret);
1267 	    free_ContentInfo(&info);
1268 	    if (ret) {
1269 		krb5_set_error_message(context, ret,
1270 				       "encoding of Key ContentInfo "
1271 				       "failed %d", ret);
1272 		free_PA_PK_AS_REP(&rep);
1273 		goto out;
1274 	    }
1275 	    if (rep.u.encKeyPack.length != size)
1276 		krb5_abortx(context, "Internal ASN.1 encoder error");
1277 
1278 	    /* generate the session key using the method from RFC6112 */
1279 	    {
1280 		krb5_keyblock kdc_contribution_key;
1281 		krb5_crypto reply_crypto;
1282 		krb5_crypto kdccont_crypto;
1283 		krb5_data p1 = { strlen("PKINIT"), "PKINIT"};
1284 		krb5_data p2 = { strlen("KEYEXCHANGE"), "KEYEXCHANGE"};
1285 		void *kckdata;
1286 		size_t kcklen;
1287 		EncryptedData kx;
1288 		void *kxdata;
1289 		size_t kxlen;
1290 
1291 		ret = krb5_generate_random_keyblock(context, sessionetype,
1292 						&kdc_contribution_key);
1293 		if (ret) {
1294 		    free_PA_PK_AS_REP(&rep);
1295 		    goto out;
1296 		}
1297 		ret = krb5_crypto_init(context, &cp->reply_key, enctype, &reply_crypto);
1298 		if (ret) {
1299 		    krb5_free_keyblock_contents(context, &kdc_contribution_key);
1300 		    free_PA_PK_AS_REP(&rep);
1301 		    goto out;
1302 		}
1303 		ret = krb5_crypto_init(context, &kdc_contribution_key, sessionetype, &kdccont_crypto);
1304 		if (ret) {
1305 		    krb5_crypto_destroy(context, reply_crypto);
1306 		    krb5_free_keyblock_contents(context, &kdc_contribution_key);
1307 		    free_PA_PK_AS_REP(&rep);
1308 		    goto out;
1309 		}
1310 		/* KRB-FX-CF2 */
1311 		ret = krb5_crypto_fx_cf2(context, kdccont_crypto, reply_crypto,
1312 					 &p1, &p2, sessionetype, sessionkey);
1313 		krb5_crypto_destroy(context, kdccont_crypto);
1314 		if (ret) {
1315 		    krb5_crypto_destroy(context, reply_crypto);
1316 		    krb5_free_keyblock_contents(context, &kdc_contribution_key);
1317 		    free_PA_PK_AS_REP(&rep);
1318 		    goto out;
1319 		}
1320 		ASN1_MALLOC_ENCODE(EncryptionKey, kckdata, kcklen,
1321 				   &kdc_contribution_key, &size, ret);
1322 		krb5_free_keyblock_contents(context, &kdc_contribution_key);
1323 		if (ret) {
1324 		    krb5_set_error_message(context, ret, "encoding of PKINIT-KX Key failed %d", ret);
1325 		    krb5_crypto_destroy(context, reply_crypto);
1326 		    free_PA_PK_AS_REP(&rep);
1327 		    goto out;
1328 		}
1329 		if (kcklen != size)
1330 		    krb5_abortx(context, "Internal ASN.1 encoder error");
1331 		ret = krb5_encrypt_EncryptedData(context, reply_crypto, KRB5_KU_PA_PKINIT_KX,
1332 					kckdata, kcklen, 0, &kx);
1333 		krb5_crypto_destroy(context, reply_crypto);
1334 		free(kckdata);
1335 		if (ret) {
1336 		    free_PA_PK_AS_REP(&rep);
1337 		    goto out;
1338 		}
1339 		ASN1_MALLOC_ENCODE(EncryptedData, kxdata, kxlen,
1340 				   &kx, &size, ret);
1341 		free_EncryptedData(&kx);
1342 		if (ret) {
1343 		    krb5_set_error_message(context, ret, "encoding of PKINIT-KX failed %d", ret);
1344 		    free_PA_PK_AS_REP(&rep);
1345 		    goto out;
1346 		}
1347 		if (kxlen != size)
1348 		    krb5_abortx(context, "Internal ASN.1 encoder error");
1349 		/* Add PA-PKINIT-KX */
1350 		ret = krb5_padata_add(context, md, KRB5_PADATA_PKINIT_KX, kxdata, kxlen);
1351 		if (ret) {
1352 		    krb5_set_error_message(context, ret,
1353 					   "Failed adding PKINIT-KX %d", ret);
1354 		    free(buf);
1355 		    goto out;
1356 		}
1357 	    }
1358 	}
1359 
1360 #define use_btmm_with_enckey 0
1361 	if (use_btmm_with_enckey && rep.element == choice_PA_PK_AS_REP_encKeyPack) {
1362 	    PA_PK_AS_REP_BTMM btmm;
1363 	    heim_any any;
1364 
1365 	    any.data = rep.u.encKeyPack.data;
1366 	    any.length = rep.u.encKeyPack.length;
1367 
1368 	    btmm.dhSignedData = NULL;
1369 	    btmm.encKeyPack = &any;
1370 
1371 	    ASN1_MALLOC_ENCODE(PA_PK_AS_REP_BTMM, buf, len, &btmm, &size, ret);
1372 	} else {
1373 	    ASN1_MALLOC_ENCODE(PA_PK_AS_REP, buf, len, &rep, &size, ret);
1374 	}
1375 
1376 	free_PA_PK_AS_REP(&rep);
1377 	if (ret) {
1378 	    krb5_set_error_message(context, ret,
1379 				   "encode PA-PK-AS-REP failed %d", ret);
1380 	    goto out;
1381 	}
1382 	if (len != size)
1383 	    krb5_abortx(context, "Internal ASN.1 encoder error");
1384 
1385 	kdc_log(context, config, 0, "PK-INIT using %s %s", type, other);
1386 
1387     } else if (cp->type == PKINIT_WIN2K) {
1388 	PA_PK_AS_REP_Win2k rep;
1389 	ContentInfo info;
1390 
1391 	if (cp->keyex != USE_RSA) {
1392 	    ret = KRB5KRB_ERR_GENERIC;
1393 	    krb5_set_error_message(context, ret,
1394 				   "Windows PK-INIT doesn't support DH");
1395 	    goto out;
1396 	}
1397 
1398 	memset(&rep, 0, sizeof(rep));
1399 
1400 	pa_type = KRB5_PADATA_PK_AS_REP_19;
1401 	rep.element = choice_PA_PK_AS_REP_Win2k_encKeyPack;
1402 
1403 	ret = krb5_generate_random_keyblock(context, enctype,
1404 					    &cp->reply_key);
1405 	if (ret) {
1406 	    free_PA_PK_AS_REP_Win2k(&rep);
1407 	    goto out;
1408 	}
1409 	ret = pk_mk_pa_reply_enckey(context,
1410 				    config,
1411 				    cp,
1412 				    req,
1413 				    req_buffer,
1414 				    &cp->reply_key,
1415 				    &info,
1416 				    &kdc_cert);
1417 	if (ret) {
1418 	    free_PA_PK_AS_REP_Win2k(&rep);
1419 	    goto out;
1420 	}
1421 	ASN1_MALLOC_ENCODE(ContentInfo, rep.u.encKeyPack.data,
1422 			   rep.u.encKeyPack.length, &info, &size,
1423 			   ret);
1424 	free_ContentInfo(&info);
1425 	if (ret) {
1426 	    krb5_set_error_message(context, ret, "encoding of Key ContentInfo "
1427 				  "failed %d", ret);
1428 	    free_PA_PK_AS_REP_Win2k(&rep);
1429 	    goto out;
1430 	}
1431 	if (rep.u.encKeyPack.length != size)
1432 	    krb5_abortx(context, "Internal ASN.1 encoder error");
1433 
1434 	ASN1_MALLOC_ENCODE(PA_PK_AS_REP_Win2k, buf, len, &rep, &size, ret);
1435 	free_PA_PK_AS_REP_Win2k(&rep);
1436 	if (ret) {
1437 	    krb5_set_error_message(context, ret,
1438 				  "encode PA-PK-AS-REP-Win2k failed %d", ret);
1439 	    goto out;
1440 	}
1441 	if (len != size)
1442 	    krb5_abortx(context, "Internal ASN.1 encoder error");
1443 
1444 	ret = krb5_generate_random_keyblock(context, sessionetype,
1445 					    sessionkey);
1446 	if (ret) {
1447 	    free(buf);
1448 	    goto out;
1449 	}
1450 
1451     } else
1452 	krb5_abortx(context, "PK-INIT internal error");
1453 
1454 
1455     ret = krb5_padata_add(context, md, pa_type, buf, len);
1456     if (ret) {
1457 	krb5_set_error_message(context, ret,
1458 			       "Failed adding PA-PK-AS-REP %d", ret);
1459 	free(buf);
1460 	goto out;
1461     }
1462 
1463     if (config->pkinit_kdc_ocsp_file) {
1464 
1465 	if (ocsp.expire == 0 && ocsp.next_update > kdc_time) {
1466 	    struct stat sb;
1467 	    int fd;
1468 
1469 	    krb5_data_free(&ocsp.data);
1470 
1471 	    ocsp.expire = 0;
1472 	    ocsp.next_update = kdc_time + 60 * 5;
1473 
1474 	    fd = open(config->pkinit_kdc_ocsp_file, O_RDONLY);
1475 	    if (fd < 0) {
1476 		kdc_log(context, config, 0,
1477 			"PK-INIT failed to open ocsp data file %d", errno);
1478 		goto out_ocsp;
1479 	    }
1480 	    ret = fstat(fd, &sb);
1481 	    if (ret) {
1482 		ret = errno;
1483 		close(fd);
1484 		kdc_log(context, config, 0,
1485 			"PK-INIT failed to stat ocsp data %d", ret);
1486 		goto out_ocsp;
1487 	    }
1488 
1489 	    ret = krb5_data_alloc(&ocsp.data, sb.st_size);
1490 	    if (ret) {
1491 		close(fd);
1492 		kdc_log(context, config, 0,
1493 			"PK-INIT failed to stat ocsp data %d", ret);
1494 		goto out_ocsp;
1495 	    }
1496 	    ocsp.data.length = sb.st_size;
1497 	    ret = read(fd, ocsp.data.data, sb.st_size);
1498 	    close(fd);
1499 	    if (ret != sb.st_size) {
1500 		kdc_log(context, config, 0,
1501 			"PK-INIT failed to read ocsp data %d", errno);
1502 		goto out_ocsp;
1503 	    }
1504 
1505 	    ret = hx509_ocsp_verify(context->hx509ctx,
1506 				    kdc_time,
1507 				    kdc_cert,
1508 				    0,
1509 				    ocsp.data.data, ocsp.data.length,
1510 				    &ocsp.expire);
1511 	    if (ret) {
1512 		kdc_log(context, config, 0,
1513 			"PK-INIT failed to verify ocsp data %d", ret);
1514 		krb5_data_free(&ocsp.data);
1515 		ocsp.expire = 0;
1516 	    } else if (ocsp.expire > 180) {
1517 		ocsp.expire -= 180; /* refetch the ocsp before it expire */
1518 		ocsp.next_update = ocsp.expire;
1519 	    } else {
1520 		ocsp.next_update = kdc_time;
1521 	    }
1522 	out_ocsp:
1523 	    ret = 0;
1524 	}
1525 
1526 	if (ocsp.expire != 0 && ocsp.expire > kdc_time) {
1527 
1528 	    ret = krb5_padata_add(context, md,
1529 				  KRB5_PADATA_PA_PK_OCSP_RESPONSE,
1530 				  ocsp.data.data, ocsp.data.length);
1531 	    if (ret) {
1532 		krb5_set_error_message(context, ret,
1533 				       "Failed adding OCSP response %d", ret);
1534 		goto out;
1535 	    }
1536 	}
1537     }
1538 
1539 out:
1540     if (kdc_cert)
1541 	hx509_cert_free(kdc_cert);
1542 
1543     if (ret == 0)
1544 	ret = krb5_copy_keyblock_contents(context, &cp->reply_key, reply_key);
1545     return ret;
1546 }
1547 
1548 static int
match_rfc_san(krb5_context context,krb5_kdc_configuration * config,hx509_context hx509ctx,hx509_cert client_cert,krb5_const_principal match)1549 match_rfc_san(krb5_context context,
1550 	      krb5_kdc_configuration *config,
1551 	      hx509_context hx509ctx,
1552 	      hx509_cert client_cert,
1553 	      krb5_const_principal match)
1554 {
1555     hx509_octet_string_list list;
1556     int ret, found = 0;
1557     size_t i;
1558 
1559     memset(&list, 0 , sizeof(list));
1560 
1561     ret = hx509_cert_find_subjectAltName_otherName(hx509ctx,
1562 						   client_cert,
1563 						   &asn1_oid_id_pkinit_san,
1564 						   &list);
1565     if (ret)
1566 	goto out;
1567 
1568     for (i = 0; !found && i < list.len; i++) {
1569 	krb5_principal_data principal;
1570 	KRB5PrincipalName kn;
1571 	size_t size;
1572 
1573 	ret = decode_KRB5PrincipalName(list.val[i].data,
1574 				       list.val[i].length,
1575 				       &kn, &size);
1576 	if (ret) {
1577 	    const char *msg = krb5_get_error_message(context, ret);
1578 	    kdc_log(context, config, 0,
1579 		    "Decoding kerberos name in certificate failed: %s", msg);
1580 	    krb5_free_error_message(context, msg);
1581 	    break;
1582 	}
1583 	if (size != list.val[i].length) {
1584 	    kdc_log(context, config, 0,
1585 		    "Decoding kerberos name have extra bits on the end");
1586 	    return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1587 	}
1588 
1589 	memset(&principal, 0, sizeof (principal));
1590 	principal.name = kn.principalName;
1591 	principal.realm = kn.realm;
1592 
1593 	if (krb5_principal_compare(context, &principal, match) == TRUE)
1594 	    found = 1;
1595 	free_KRB5PrincipalName(&kn);
1596     }
1597 
1598 out:
1599     hx509_free_octet_string_list(&list);
1600     if (ret)
1601 	return ret;
1602 
1603     if (!found)
1604 	return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1605 
1606     return 0;
1607 }
1608 
1609 static int
match_ms_upn_san(krb5_context context,krb5_kdc_configuration * config,hx509_context hx509ctx,hx509_cert client_cert,HDB * clientdb,hdb_entry_ex * client)1610 match_ms_upn_san(krb5_context context,
1611 		 krb5_kdc_configuration *config,
1612 		 hx509_context hx509ctx,
1613 		 hx509_cert client_cert,
1614 		 HDB *clientdb,
1615 		 hdb_entry_ex *client)
1616 {
1617     hx509_octet_string_list list;
1618     krb5_principal principal = NULL;
1619     int ret;
1620     MS_UPN_SAN upn;
1621     size_t size;
1622 
1623     memset(&list, 0 , sizeof(list));
1624 
1625     ret = hx509_cert_find_subjectAltName_otherName(hx509ctx,
1626 						   client_cert,
1627 						   &asn1_oid_id_pkinit_ms_san,
1628 						   &list);
1629     if (ret)
1630 	goto out;
1631 
1632     if (list.len != 1) {
1633 	kdc_log(context, config, 0,
1634 		"More then one PK-INIT MS UPN SAN");
1635 	ret = KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1636 	goto out;
1637     }
1638 
1639     ret = decode_MS_UPN_SAN(list.val[0].data, list.val[0].length, &upn, &size);
1640     if (ret) {
1641 	kdc_log(context, config, 0, "Decode of MS-UPN-SAN failed");
1642 	goto out;
1643     }
1644     if (size != list.val[0].length) {
1645 	free_MS_UPN_SAN(&upn);
1646 	kdc_log(context, config, 0, "Trailing data in ");
1647 	ret = KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1648 	goto out;
1649     }
1650 
1651     kdc_log(context, config, 0, "found MS UPN SAN: %s", upn);
1652 
1653     ret = krb5_parse_name(context, upn, &principal);
1654     free_MS_UPN_SAN(&upn);
1655     if (ret) {
1656 	kdc_log(context, config, 0, "Failed to parse principal in MS UPN SAN");
1657 	goto out;
1658     }
1659 
1660     if (clientdb->hdb_check_pkinit_ms_upn_match) {
1661 	ret = clientdb->hdb_check_pkinit_ms_upn_match(context, clientdb, client, principal);
1662     } else {
1663 
1664 	/*
1665 	 * This is very wrong, but will do for a fallback
1666 	 */
1667 	strupr(principal->realm);
1668 
1669 	if (krb5_principal_compare(context, principal, client->entry.principal) == FALSE)
1670 	    ret = KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1671     }
1672 
1673 out:
1674     if (principal)
1675 	krb5_free_principal(context, principal);
1676     hx509_free_octet_string_list(&list);
1677 
1678     return ret;
1679 }
1680 
1681 krb5_error_code
_kdc_pk_check_client(krb5_context context,krb5_kdc_configuration * config,HDB * clientdb,hdb_entry_ex * client,pk_client_params * cp,char ** subject_name)1682 _kdc_pk_check_client(krb5_context context,
1683 		     krb5_kdc_configuration *config,
1684 		     HDB *clientdb,
1685 		     hdb_entry_ex *client,
1686 		     pk_client_params *cp,
1687 		     char **subject_name)
1688 {
1689     const HDB_Ext_PKINIT_acl *acl;
1690     const HDB_Ext_PKINIT_cert *pc;
1691     krb5_error_code ret;
1692     hx509_name name;
1693     size_t i;
1694 
1695     if (cp->cert == NULL) {
1696 	if (!_kdc_is_anonymous(context, client->entry.principal)
1697 	    && !config->historical_anon_realm)
1698 	    return KRB5KDC_ERR_BADOPTION;
1699 
1700 	*subject_name = strdup("<unauthenticated anonymous client>");
1701 	if (*subject_name == NULL)
1702 	    return ENOMEM;
1703 	return 0;
1704     }
1705 
1706     ret = hx509_cert_get_base_subject(context->hx509ctx,
1707 				      cp->cert,
1708 				      &name);
1709     if (ret)
1710 	return ret;
1711 
1712     ret = hx509_name_to_string(name, subject_name);
1713     hx509_name_free(&name);
1714     if (ret)
1715 	return ret;
1716 
1717     kdc_log(context, config, 0,
1718 	    "Trying to authorize PK-INIT subject DN %s",
1719 	    *subject_name);
1720 
1721     ret = hdb_entry_get_pkinit_cert(&client->entry, &pc);
1722     if (ret == 0 && pc) {
1723 	hx509_cert cert;
1724 	size_t j;
1725 
1726 	for (j = 0; j < pc->len; j++) {
1727 	    cert = hx509_cert_init_data(context->hx509ctx,
1728 					pc->val[j].cert.data,
1729 					pc->val[j].cert.length,
1730 					NULL);
1731 	    if (cert == NULL)
1732 		continue;
1733 	    ret = hx509_cert_cmp(cert, cp->cert);
1734 	    hx509_cert_free(cert);
1735 	    if (ret == 0) {
1736 		kdc_log(context, config, 5,
1737 			"Found matching PK-INIT cert in hdb");
1738 		return 0;
1739 	    }
1740 	}
1741     }
1742 
1743 
1744     if (config->pkinit_princ_in_cert) {
1745 	ret = match_rfc_san(context, config,
1746 			    context->hx509ctx,
1747 			    cp->cert,
1748 			    client->entry.principal);
1749 	if (ret == 0) {
1750 	    kdc_log(context, config, 5,
1751 		    "Found matching PK-INIT SAN in certificate");
1752 	    return 0;
1753 	}
1754 	ret = match_ms_upn_san(context, config,
1755 			       context->hx509ctx,
1756 			       cp->cert,
1757 			       clientdb,
1758 			       client);
1759 	if (ret == 0) {
1760 	    kdc_log(context, config, 5,
1761 		    "Found matching MS UPN SAN in certificate");
1762 	    return 0;
1763 	}
1764     }
1765 
1766     ret = hdb_entry_get_pkinit_acl(&client->entry, &acl);
1767     if (ret == 0 && acl != NULL) {
1768 	/*
1769 	 * Cheat here and compare the generated name with the string
1770 	 * and not the reverse.
1771 	 */
1772 	for (i = 0; i < acl->len; i++) {
1773 	    if (strcmp(*subject_name, acl->val[0].subject) != 0)
1774 		continue;
1775 
1776 	    /* Don't support isser and anchor checking right now */
1777 	    if (acl->val[0].issuer)
1778 		continue;
1779 	    if (acl->val[0].anchor)
1780 		continue;
1781 
1782 	    kdc_log(context, config, 5,
1783 		    "Found matching PK-INIT database ACL");
1784 	    return 0;
1785 	}
1786     }
1787 
1788     for (i = 0; i < principal_mappings.len; i++) {
1789 	krb5_boolean b;
1790 
1791 	b = krb5_principal_compare(context,
1792 				   client->entry.principal,
1793 				   principal_mappings.val[i].principal);
1794 	if (b == FALSE)
1795 	    continue;
1796 	if (strcmp(principal_mappings.val[i].subject, *subject_name) != 0)
1797 	    continue;
1798 	kdc_log(context, config, 5,
1799 		"Found matching PK-INIT FILE ACL");
1800 	return 0;
1801     }
1802 
1803     ret = KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1804     krb5_set_error_message(context, ret,
1805 			  "PKINIT no matching principals for %s",
1806 			  *subject_name);
1807 
1808     kdc_log(context, config, 5,
1809 	    "PKINIT no matching principals for %s",
1810 	    *subject_name);
1811 
1812     free(*subject_name);
1813     *subject_name = NULL;
1814 
1815     return ret;
1816 }
1817 
1818 static krb5_error_code
add_principal_mapping(krb5_context context,const char * principal_name,const char * subject)1819 add_principal_mapping(krb5_context context,
1820 		      const char *principal_name,
1821 		      const char * subject)
1822 {
1823    struct pk_allowed_princ *tmp;
1824    krb5_principal principal;
1825    krb5_error_code ret;
1826 
1827    tmp = realloc(principal_mappings.val,
1828 	         (principal_mappings.len + 1) * sizeof(*tmp));
1829    if (tmp == NULL)
1830        return ENOMEM;
1831    principal_mappings.val = tmp;
1832 
1833    ret = krb5_parse_name(context, principal_name, &principal);
1834    if (ret)
1835        return ret;
1836 
1837    principal_mappings.val[principal_mappings.len].principal = principal;
1838 
1839    principal_mappings.val[principal_mappings.len].subject = strdup(subject);
1840    if (principal_mappings.val[principal_mappings.len].subject == NULL) {
1841        krb5_free_principal(context, principal);
1842        return ENOMEM;
1843    }
1844    principal_mappings.len++;
1845 
1846    return 0;
1847 }
1848 
1849 krb5_error_code
_kdc_add_inital_verified_cas(krb5_context context,krb5_kdc_configuration * config,pk_client_params * cp,EncTicketPart * tkt)1850 _kdc_add_inital_verified_cas(krb5_context context,
1851 			     krb5_kdc_configuration *config,
1852 			     pk_client_params *cp,
1853 			     EncTicketPart *tkt)
1854 {
1855     AD_INITIAL_VERIFIED_CAS cas;
1856     krb5_error_code ret;
1857     krb5_data data;
1858     size_t size = 0;
1859 
1860     memset(&cas, 0, sizeof(cas));
1861 
1862     /* XXX add CAs to cas here */
1863 
1864     ASN1_MALLOC_ENCODE(AD_INITIAL_VERIFIED_CAS, data.data, data.length,
1865 		       &cas, &size, ret);
1866     if (ret)
1867 	return ret;
1868     if (data.length != size)
1869 	krb5_abortx(context, "internal asn.1 encoder error");
1870 
1871     ret = _kdc_tkt_add_if_relevant_ad(context, tkt,
1872 				      KRB5_AUTHDATA_INITIAL_VERIFIED_CAS,
1873 				      &data);
1874     krb5_data_free(&data);
1875     return ret;
1876 }
1877 
1878 /*
1879  *
1880  */
1881 
1882 static void
load_mappings(krb5_context context,const char * fn)1883 load_mappings(krb5_context context, const char *fn)
1884 {
1885     krb5_error_code ret;
1886     char buf[1024];
1887     unsigned long lineno = 0;
1888     FILE *f;
1889 
1890     f = fopen(fn, "r");
1891     if (f == NULL)
1892 	return;
1893 
1894     while (fgets(buf, sizeof(buf), f) != NULL) {
1895 	char *subject_name, *p;
1896 
1897 	buf[strcspn(buf, "\n")] = '\0';
1898 	lineno++;
1899 
1900 	p = buf + strspn(buf, " \t");
1901 
1902 	if (*p == '#' || *p == '\0')
1903 	    continue;
1904 
1905 	subject_name = strchr(p, ':');
1906 	if (subject_name == NULL) {
1907 	    krb5_warnx(context, "pkinit mapping file line %lu "
1908 		       "missing \":\" :%s",
1909 		       lineno, buf);
1910 	    continue;
1911 	}
1912 	*subject_name++ = '\0';
1913 
1914 	ret = add_principal_mapping(context, p, subject_name);
1915 	if (ret) {
1916 	    krb5_warn(context, ret, "failed to add line %lu \":\" :%s\n",
1917 		      lineno, buf);
1918 	    continue;
1919 	}
1920     }
1921 
1922     fclose(f);
1923 }
1924 
1925 /*
1926  *
1927  */
1928 
1929 krb5_error_code
krb5_kdc_pk_initialize(krb5_context context,krb5_kdc_configuration * config,const char * user_id,const char * anchors,char ** pool,char ** revoke_list)1930 krb5_kdc_pk_initialize(krb5_context context,
1931 		       krb5_kdc_configuration *config,
1932 		       const char *user_id,
1933 		       const char *anchors,
1934 		       char **pool,
1935 		       char **revoke_list)
1936 {
1937     const char *file;
1938     char *fn = NULL;
1939     krb5_error_code ret;
1940 
1941     file = krb5_config_get_string(context, NULL,
1942 				  "libdefaults", "moduli", NULL);
1943 
1944     ret = _krb5_parse_moduli(context, file, &moduli);
1945     if (ret)
1946 	krb5_err(context, 1, ret, "PKINIT: failed to load modidi file");
1947 
1948     principal_mappings.len = 0;
1949     principal_mappings.val = NULL;
1950 
1951     ret = _krb5_pk_load_id(context,
1952 			   &kdc_identity,
1953 			   user_id,
1954 			   anchors,
1955 			   pool,
1956 			   revoke_list,
1957 			   NULL,
1958 			   NULL,
1959 			   NULL);
1960     if (ret) {
1961 	krb5_warn(context, ret, "PKINIT: ");
1962 	config->enable_pkinit = 0;
1963 	return ret;
1964     }
1965 
1966     {
1967 	hx509_query *q;
1968 	hx509_cert cert;
1969 
1970 	ret = hx509_query_alloc(context->hx509ctx, &q);
1971 	if (ret) {
1972 	    krb5_warnx(context, "PKINIT: out of memory");
1973 	    return ENOMEM;
1974 	}
1975 
1976 	hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
1977 	if (config->pkinit_kdc_friendly_name)
1978 	    hx509_query_match_friendly_name(q, config->pkinit_kdc_friendly_name);
1979 
1980 	ret = hx509_certs_find(context->hx509ctx,
1981 			       kdc_identity->certs,
1982 			       q,
1983 			       &cert);
1984 	hx509_query_free(context->hx509ctx, q);
1985 	if (ret == 0) {
1986 	    if (hx509_cert_check_eku(context->hx509ctx, cert,
1987 				     &asn1_oid_id_pkkdcekuoid, 0)) {
1988 		hx509_name name;
1989 		char *str;
1990 		ret = hx509_cert_get_subject(cert, &name);
1991 		if (ret == 0) {
1992 		    hx509_name_to_string(name, &str);
1993 		    krb5_warnx(context, "WARNING Found KDC certificate (%s)"
1994 			       "is missing the PK-INIT KDC EKU, this is bad for "
1995 			       "interoperability.", str);
1996 		    hx509_name_free(&name);
1997 		    free(str);
1998 		}
1999 	    }
2000 	    hx509_cert_free(cert);
2001 	} else
2002 	    krb5_warnx(context, "PKINIT: failed to find a signing "
2003 		       "certifiate with a public key");
2004     }
2005 
2006     if (krb5_config_get_bool_default(context,
2007 				     NULL,
2008 				     FALSE,
2009 				     "kdc",
2010 				     "pkinit_allow_proxy_certificate",
2011 				     NULL))
2012 	config->pkinit_allow_proxy_certs = 1;
2013 
2014     file = krb5_config_get_string(context,
2015 				  NULL,
2016 				  "kdc",
2017 				  "pkinit_mappings_file",
2018 				  NULL);
2019     if (file == NULL) {
2020 	int aret;
2021 
2022 	aret = asprintf(&fn, "%s/pki-mapping", hdb_db_dir(context));
2023 	if (aret == -1) {
2024 	    krb5_warnx(context, "PKINIT: out of memory");
2025 	    return ENOMEM;
2026 	}
2027 
2028 	file = fn;
2029     }
2030 
2031     load_mappings(context, file);
2032     if (fn)
2033 	free(fn);
2034 
2035     return 0;
2036 }
2037 
2038 #endif /* PKINIT */
2039