r19633: Merge to lorikeet-heimdal, removing krb5_rd_req_return_keyblock in favour...
[amitay/samba.git] / source4 / heimdal / kdc / pkinit.c
1 /*
2  * Copyright (c) 2003 - 2005 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden). 
4  * All rights reserved. 
5  *
6  * Redistribution and use in source and binary forms, with or without 
7  * modification, are permitted provided that the following conditions 
8  * are met: 
9  *
10  * 1. Redistributions of source code must retain the above copyright 
11  *    notice, this list of conditions and the following disclaimer. 
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright 
14  *    notice, this list of conditions and the following disclaimer in the 
15  *    documentation and/or other materials provided with the distribution. 
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors 
18  *    may be used to endorse or promote products derived from this software 
19  *    without specific prior written permission. 
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND 
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE 
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
31  * SUCH DAMAGE. 
32  */
33
34 #include "kdc_locl.h"
35
36 RCSID("$Id: pkinit.c,v 1.73 2006/11/07 17:24:57 lha Exp $");
37
38 #ifdef PKINIT
39
40 #include <heim_asn1.h>
41 #include <rfc2459_asn1.h>
42 #include <cms_asn1.h>
43 #include <pkinit_asn1.h>
44
45 #include <hx509.h>
46 #include "crypto-headers.h"
47
48 /* XXX copied from lib/krb5/pkinit.c */
49 struct krb5_pk_identity {
50     hx509_context hx509ctx;
51     hx509_verify_ctx verify_ctx;
52     hx509_certs certs;
53     hx509_certs anchors;
54     hx509_certs certpool;
55     hx509_revoke_ctx revoke;
56 };
57
58 enum pkinit_type {
59     PKINIT_COMPAT_WIN2K = 1,
60     PKINIT_COMPAT_27 = 3
61 };
62
63 struct pk_client_params {
64     enum pkinit_type type;
65     BIGNUM *dh_public_key;
66     hx509_cert cert;
67     unsigned nonce;
68     DH *dh;
69     EncryptionKey reply_key;
70     char *dh_group_name;
71 };
72
73 struct pk_principal_mapping {
74     unsigned int len;
75     struct pk_allowed_princ {
76         krb5_principal principal;
77         char *subject;
78     } *val;
79 };
80
81 static struct krb5_pk_identity *kdc_identity;
82 static struct pk_principal_mapping principal_mappings;
83 static struct krb5_dh_moduli **moduli;
84
85 static struct {
86     krb5_data data;
87     time_t expire;
88     time_t next_update;
89 } ocsp;
90
91 /*
92  *
93  */
94
95 static krb5_error_code
96 pk_check_pkauthenticator_win2k(krb5_context context,
97                                PKAuthenticator_Win2k *a,
98                                KDC_REQ *req)
99 {
100     krb5_timestamp now;
101
102     krb5_timeofday (context, &now);
103
104     /* XXX cusec */
105     if (a->ctime == 0 || abs(a->ctime - now) > context->max_skew) {
106         krb5_clear_error_string(context);
107         return KRB5KRB_AP_ERR_SKEW;
108     }
109     return 0;
110 }
111
112 static krb5_error_code
113 pk_check_pkauthenticator(krb5_context context,
114                          PKAuthenticator *a,
115                          KDC_REQ *req)
116 {
117     u_char *buf = NULL;
118     size_t buf_size;
119     krb5_error_code ret;
120     size_t len;
121     krb5_timestamp now;
122     Checksum checksum;
123
124     krb5_timeofday (context, &now);
125
126     /* XXX cusec */
127     if (a->ctime == 0 || abs(a->ctime - now) > context->max_skew) {
128         krb5_clear_error_string(context);
129         return KRB5KRB_AP_ERR_SKEW;
130     }
131
132     ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, &req->req_body, &len, ret);
133     if (ret) {
134         krb5_clear_error_string(context);
135         return ret;
136     }
137     if (buf_size != len)
138         krb5_abortx(context, "Internal error in ASN.1 encoder");
139
140     ret = krb5_create_checksum(context,
141                                NULL,
142                                0,
143                                CKSUMTYPE_SHA1,
144                                buf,
145                                len,
146                                &checksum);
147     free(buf);
148     if (ret) {
149         krb5_clear_error_string(context);
150         return ret;
151     }
152         
153     if (a->paChecksum == NULL) {
154         krb5_clear_error_string(context);
155         ret = KRB5_KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED;
156         goto out;
157     }
158
159     if (der_heim_octet_string_cmp(a->paChecksum, &checksum.checksum) != 0) {
160         krb5_clear_error_string(context);
161         ret = KRB5KRB_ERR_GENERIC;
162     }
163
164 out:
165     free_Checksum(&checksum);
166
167     return ret;
168 }
169
170 void
171 _kdc_pk_free_client_param(krb5_context context, 
172                           pk_client_params *client_params)
173 {
174     if (client_params->cert)
175         hx509_cert_free(client_params->cert);
176     if (client_params->dh)
177         DH_free(client_params->dh);
178     if (client_params->dh_public_key)
179         BN_free(client_params->dh_public_key);
180     krb5_free_keyblock_contents(context, &client_params->reply_key);
181     if (client_params->dh_group_name)
182         free(client_params->dh_group_name);
183     memset(client_params, 0, sizeof(*client_params));
184     free(client_params);
185 }
186
187 static krb5_error_code
188 generate_dh_keyblock(krb5_context context, pk_client_params *client_params,
189                      krb5_enctype enctype, krb5_keyblock *reply_key)
190 {
191     unsigned char *dh_gen_key = NULL;
192     krb5_keyblock key;
193     krb5_error_code ret;
194     size_t dh_gen_keylen, size;
195
196     memset(&key, 0, sizeof(key));
197
198     if (!DH_generate_key(client_params->dh)) {
199         krb5_set_error_string(context, "Can't generate Diffie-Hellman keys");
200         ret = KRB5KRB_ERR_GENERIC;
201         goto out;
202     }
203     if (client_params->dh_public_key == NULL) {
204         krb5_set_error_string(context, "dh_public_key");
205         ret = KRB5KRB_ERR_GENERIC;
206         goto out;
207     }
208
209     dh_gen_keylen = DH_size(client_params->dh);
210     size = BN_num_bytes(client_params->dh->p);
211     if (size < dh_gen_keylen)
212         size = dh_gen_keylen;
213
214     dh_gen_key = malloc(size);
215     if (dh_gen_key == NULL) {
216         krb5_set_error_string(context, "malloc: out of memory");
217         ret = ENOMEM;
218         goto out;
219     }
220     memset(dh_gen_key, 0, size - dh_gen_keylen);
221
222     dh_gen_keylen = DH_compute_key(dh_gen_key + (size - dh_gen_keylen),
223                                    client_params->dh_public_key,
224                                    client_params->dh);
225     if (dh_gen_keylen == -1) {
226         krb5_set_error_string(context, "Can't compute Diffie-Hellman key");
227         ret = KRB5KRB_ERR_GENERIC;
228         goto out;
229     }
230
231     ret = _krb5_pk_octetstring2key(context,
232                                    enctype,
233                                    dh_gen_key, dh_gen_keylen,
234                                    NULL, NULL,
235                                    reply_key);
236
237  out:
238     if (dh_gen_key)
239         free(dh_gen_key);
240     if (key.keyvalue.data)
241         krb5_free_keyblock_contents(context, &key);
242
243     return ret;
244 }
245
246 static BIGNUM *
247 integer_to_BN(krb5_context context, const char *field, heim_integer *f)
248 {
249     BIGNUM *bn;
250
251     bn = BN_bin2bn((const unsigned char *)f->data, f->length, NULL);
252     if (bn == NULL) {
253         krb5_set_error_string(context, "PKINIT: parsing BN failed %s", field);
254         return NULL;
255     }
256     BN_set_negative(bn, f->negative);
257     return bn;
258 }
259
260 static krb5_error_code
261 get_dh_param(krb5_context context,
262              krb5_kdc_configuration *config,
263              SubjectPublicKeyInfo *dh_key_info,
264              pk_client_params *client_params)
265 {
266     DomainParameters dhparam;
267     DH *dh = NULL;
268     krb5_error_code ret;
269
270     memset(&dhparam, 0, sizeof(dhparam));
271
272     if (der_heim_oid_cmp(&dh_key_info->algorithm.algorithm, oid_id_dhpublicnumber())) {
273         krb5_set_error_string(context,
274                               "PKINIT invalid oid in clientPublicValue");
275         return KRB5_BADMSGTYPE;
276     }
277
278     if (dh_key_info->algorithm.parameters == NULL) {
279         krb5_set_error_string(context, "PKINIT missing algorithm parameter "
280                               "in clientPublicValue");
281         return KRB5_BADMSGTYPE;
282     }
283
284     ret = decode_DomainParameters(dh_key_info->algorithm.parameters->data,
285                                   dh_key_info->algorithm.parameters->length,
286                                   &dhparam,
287                                   NULL);
288     if (ret) {
289         krb5_set_error_string(context, "Can't decode algorithm "
290                               "parameters in clientPublicValue");
291         goto out;
292     }
293
294     if ((dh_key_info->subjectPublicKey.length % 8) != 0) {
295         ret = KRB5_BADMSGTYPE;
296         krb5_set_error_string(context, "PKINIT: subjectPublicKey not aligned "
297                               "to 8 bit boundary");
298         goto out;
299     }
300
301
302     ret = _krb5_dh_group_ok(context, config->pkinit_dh_min_bits, 
303                             &dhparam.p, &dhparam.g, &dhparam.q, moduli,
304                             &client_params->dh_group_name);
305     if (ret)
306         goto out;
307
308     dh = DH_new();
309     if (dh == NULL) {
310         krb5_set_error_string(context, "Cannot create DH structure");
311         ret = ENOMEM;
312         goto out;
313     }
314     ret = KRB5_BADMSGTYPE;
315     dh->p = integer_to_BN(context, "DH prime", &dhparam.p);
316     if (dh->p == NULL)
317         goto out;
318     dh->g = integer_to_BN(context, "DH base", &dhparam.g);
319     if (dh->g == NULL)
320         goto out;
321     dh->q = integer_to_BN(context, "DH p-1 factor", &dhparam.q);
322     if (dh->g == NULL)
323         goto out;
324
325     {
326         heim_integer glue;
327         size_t size;
328
329         ret = decode_DHPublicKey(dh_key_info->subjectPublicKey.data,
330                                  dh_key_info->subjectPublicKey.length / 8,
331                                  &glue,
332                                  &size);
333         if (ret) {
334             krb5_clear_error_string(context);
335             return ret;
336         }
337
338         client_params->dh_public_key = integer_to_BN(context,
339                                                      "subjectPublicKey",
340                                                      &glue);
341         der_free_heim_integer(&glue);
342         if (client_params->dh_public_key == NULL)
343             goto out;
344     }
345
346     client_params->dh = dh;
347     dh = NULL;
348     ret = 0;
349     
350  out:
351     if (dh)
352         DH_free(dh);
353     free_DomainParameters(&dhparam);
354     return ret;
355 }
356
357 #if 0
358 /* 
359  * XXX We only need this function if there are several certs for the
360  * KDC to choose from, and right now, we can't handle that so punt for
361  * now.
362  *
363  * If client has sent a list of CA's trusted by him, make sure our
364  * CA is in the list.
365  *
366  */
367
368 static void
369 verify_trusted_ca(PA_PK_AS_REQ_19 *r)
370 {
371
372     if (r.trustedCertifiers != NULL) {
373         X509_NAME *kdc_issuer;
374         X509 *kdc_cert;
375
376         kdc_cert = sk_X509_value(kdc_identity->cert, 0);
377         kdc_issuer = X509_get_issuer_name(kdc_cert);
378      
379         /* XXX will work for heirarchical CA's ? */
380         /* XXX also serial_number should be compared */
381
382         ret = KRB5_KDC_ERR_KDC_NOT_TRUSTED;
383         for (i = 0; i < r.trustedCertifiers->len; i++) {
384             TrustedCA_19 *ca = &r.trustedCertifiers->val[i];
385
386             switch (ca->element) {
387             case choice_TrustedCA_19_caName: {
388                 X509_NAME *name;
389                 unsigned char *p;
390
391                 p = ca->u.caName.data;
392                 name = d2i_X509_NAME(NULL, &p, ca->u.caName.length);
393                 if (name == NULL) /* XXX should this be a failure instead ? */
394                     break;
395                 if (X509_NAME_cmp(name, kdc_issuer) == 0)
396                     ret = 0;
397                 X509_NAME_free(name);
398                 break;
399             }
400             case choice_TrustedCA_19_issuerAndSerial:
401                 /* IssuerAndSerialNumber issuerAndSerial */
402                 break;
403             default:
404                 break;
405             }
406             if (ret == 0)
407                 break;
408         }
409         if (ret)
410             goto out;
411     }
412 }
413 #endif /* 0 */
414
415 krb5_error_code
416 _kdc_pk_rd_padata(krb5_context context,
417                   krb5_kdc_configuration *config,
418                   KDC_REQ *req,
419                   PA_DATA *pa,
420                   pk_client_params **ret_params)
421 {
422     pk_client_params *client_params;
423     krb5_error_code ret;
424     heim_oid eContentType = { 0, NULL }, contentInfoOid = { 0, NULL };
425     krb5_data eContent = { 0, NULL };
426     krb5_data signed_content = { 0, NULL };
427     const char *type = "unknown type";
428     const heim_oid *pa_contentType;
429     int have_data = 0;
430
431     *ret_params = NULL;
432     
433     if (!config->enable_pkinit) {
434         krb5_clear_error_string(context);
435         return 0;
436     }
437
438     client_params = calloc(1, sizeof(*client_params));
439     if (client_params == NULL) {
440         krb5_clear_error_string(context);
441         ret = ENOMEM;
442         goto out;
443     }
444
445     if (pa->padata_type == KRB5_PADATA_PK_AS_REQ_WIN) {
446         PA_PK_AS_REQ_Win2k r;
447
448         type = "PK-INIT-Win2k";
449         pa_contentType = oid_id_pkcs7_data();
450
451         ret = decode_PA_PK_AS_REQ_Win2k(pa->padata_value.data,
452                                         pa->padata_value.length,
453                                         &r,
454                                         NULL);
455         if (ret) {
456             krb5_set_error_string(context, "Can't decode "
457                                   "PK-AS-REQ-Win2k: %d", ret);
458             goto out;
459         }
460         
461         ret = hx509_cms_unwrap_ContentInfo(&r.signed_auth_pack,
462                                            &contentInfoOid,
463                                            &signed_content,
464                                            &have_data);
465         free_PA_PK_AS_REQ_Win2k(&r);
466         if (ret) {
467             krb5_set_error_string(context, "Can't decode PK-AS-REQ: %d", ret);
468             goto out;
469         }
470
471     } else if (pa->padata_type == KRB5_PADATA_PK_AS_REQ) {
472         PA_PK_AS_REQ r;
473
474         type = "PK-INIT-IETF";
475         pa_contentType = oid_id_pkauthdata();
476
477         ret = decode_PA_PK_AS_REQ(pa->padata_value.data,
478                                   pa->padata_value.length,
479                                   &r,
480                                   NULL);
481         if (ret) {
482             krb5_set_error_string(context, "Can't decode PK-AS-REQ: %d", ret);
483             goto out;
484         }
485         
486         /* XXX look at r.trustedCertifiers and r.kdcPkId */
487
488         ret = hx509_cms_unwrap_ContentInfo(&r.signedAuthPack,
489                                            &contentInfoOid,
490                                            &signed_content,
491                                            &have_data);
492         free_PA_PK_AS_REQ(&r);
493         if (ret) {
494             krb5_set_error_string(context, "Can't unwrap ContentInfo: %d", ret);
495             goto out;
496         }
497
498     } else { 
499         krb5_clear_error_string(context);
500         ret = KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
501         goto out;
502     }
503
504     ret = der_heim_oid_cmp(&contentInfoOid, oid_id_pkcs7_signedData());
505     if (ret != 0) {
506         krb5_set_error_string(context, "PK-AS-REQ-Win2k invalid content "
507                               "type oid");
508         ret = KRB5KRB_ERR_GENERIC;
509         goto out;
510     }
511         
512     if (!have_data) {
513         krb5_set_error_string(context,
514                               "PK-AS-REQ-Win2k no signed auth pack");
515         ret = KRB5KRB_ERR_GENERIC;
516         goto out;
517     }
518
519     {
520         hx509_certs signer_certs;
521
522         ret = hx509_cms_verify_signed(kdc_identity->hx509ctx,
523                                       kdc_identity->verify_ctx,
524                                       signed_content.data,
525                                       signed_content.length,
526                                       kdc_identity->certpool,
527                                       &eContentType,
528                                       &eContent,
529                                       &signer_certs);
530         if (ret) {
531             char *s = hx509_get_error_string(kdc_identity->hx509ctx, ret);
532             krb5_warnx(context, "PKINIT: failed to verify signature: %s: %d",
533                        s, ret);
534             free(s);
535             goto out;
536         }
537
538         ret = hx509_get_one_cert(kdc_identity->hx509ctx, signer_certs,
539                                  &client_params->cert);
540         hx509_certs_free(&signer_certs);
541         if (ret)
542             goto out;
543     }
544
545     /* Signature is correct, now verify the signed message */
546     if (der_heim_oid_cmp(&eContentType, pa_contentType)) {
547         krb5_set_error_string(context, "got wrong oid for pkauthdata");
548         ret = KRB5_BADMSGTYPE;
549         goto out;
550     }
551
552     if (pa->padata_type == KRB5_PADATA_PK_AS_REQ_WIN) {
553         AuthPack_Win2k ap;
554
555         ret = decode_AuthPack_Win2k(eContent.data,
556                                     eContent.length,
557                                     &ap,
558                                     NULL);
559         if (ret) {
560             krb5_set_error_string(context, "can't decode AuthPack: %d", ret);
561             goto out;
562         }
563   
564         ret = pk_check_pkauthenticator_win2k(context, 
565                                              &ap.pkAuthenticator,
566                                              req);
567         if (ret) {
568             free_AuthPack_Win2k(&ap);
569             goto out;
570         }
571
572         client_params->type = PKINIT_COMPAT_WIN2K;
573         client_params->nonce = ap.pkAuthenticator.nonce;
574
575         if (ap.clientPublicValue) {
576             krb5_set_error_string(context, "DH not supported for windows");
577             ret = KRB5KRB_ERR_GENERIC;
578             goto out;
579         }
580         free_AuthPack_Win2k(&ap);
581
582     } else if (pa->padata_type == KRB5_PADATA_PK_AS_REQ) {
583         AuthPack ap;
584
585         ret = decode_AuthPack(eContent.data,
586                               eContent.length,
587                               &ap,
588                               NULL);
589         if (ret) {
590             krb5_set_error_string(context, "can't decode AuthPack: %d", ret);
591             free_AuthPack(&ap);
592             goto out;
593         }
594   
595         ret = pk_check_pkauthenticator(context, 
596                                        &ap.pkAuthenticator,
597                                        req);
598         if (ret) {
599             free_AuthPack(&ap);
600             goto out;
601         }
602
603         client_params->type = PKINIT_COMPAT_27;
604         client_params->nonce = ap.pkAuthenticator.nonce;
605
606         if (ap.clientPublicValue) {
607             ret = get_dh_param(context, config, 
608                                ap.clientPublicValue, client_params);
609             if (ret) {
610                 free_AuthPack(&ap);
611                 goto out;
612             }
613         }
614         free_AuthPack(&ap);
615     } else
616         krb5_abortx(context, "internal pkinit error");
617
618     kdc_log(context, config, 0, "PK-INIT request of type %s", type);
619
620 out:
621
622     if (signed_content.data)
623         free(signed_content.data);
624     krb5_data_free(&eContent);
625     der_free_oid(&eContentType);
626     der_free_oid(&contentInfoOid);
627     if (ret)
628         _kdc_pk_free_client_param(context, client_params);
629     else
630         *ret_params = client_params;
631     return ret;
632 }
633
634 /*
635  *
636  */
637
638 static krb5_error_code
639 BN_to_integer(krb5_context context, BIGNUM *bn, heim_integer *integer)
640 {
641     integer->length = BN_num_bytes(bn);
642     integer->data = malloc(integer->length);
643     if (integer->data == NULL) {
644         krb5_clear_error_string(context);
645         return ENOMEM;
646     }
647     BN_bn2bin(bn, integer->data);
648     integer->negative = BN_is_negative(bn);
649     return 0;
650 }
651
652 static krb5_error_code
653 pk_mk_pa_reply_enckey(krb5_context context,
654                       pk_client_params *client_params,
655                       const KDC_REQ *req,
656                       const krb5_data *req_buffer,
657                       krb5_keyblock *reply_key,
658                       ContentInfo *content_info)
659 {
660     krb5_error_code ret;
661     krb5_data buf, signed_data;
662     size_t size;
663
664     krb5_data_zero(&buf);
665     krb5_data_zero(&signed_data);
666
667     switch (client_params->type) {
668     case PKINIT_COMPAT_WIN2K: {
669         ReplyKeyPack_Win2k kp;
670         memset(&kp, 0, sizeof(kp));
671
672         ret = copy_EncryptionKey(reply_key, &kp.replyKey);
673         if (ret) {
674             krb5_clear_error_string(context);
675             goto out;
676         }
677         kp.nonce = client_params->nonce;
678         
679         ASN1_MALLOC_ENCODE(ReplyKeyPack_Win2k, 
680                            buf.data, buf.length,
681                            &kp, &size,ret);
682         free_ReplyKeyPack_Win2k(&kp);
683         break;
684     }
685     case PKINIT_COMPAT_27: {
686         krb5_crypto ascrypto;
687         ReplyKeyPack kp;
688         memset(&kp, 0, sizeof(kp));
689
690         ret = copy_EncryptionKey(reply_key, &kp.replyKey);
691         if (ret) {
692             krb5_clear_error_string(context);
693             goto out;
694         }
695
696         ret = krb5_crypto_init(context, reply_key, 0, &ascrypto);
697         if (ret) {
698             krb5_clear_error_string(context);
699             goto out;
700         }
701
702         ret = krb5_create_checksum(context, ascrypto, 6, 0,
703                                    req_buffer->data, req_buffer->length,
704                                    &kp.asChecksum);
705         if (ret) {
706             krb5_clear_error_string(context);
707             goto out;
708         }
709                              
710         ret = krb5_crypto_destroy(context, ascrypto);
711         if (ret) {
712             krb5_clear_error_string(context);
713             goto out;
714         }
715         ASN1_MALLOC_ENCODE(ReplyKeyPack, buf.data, buf.length, &kp, &size,ret);
716         free_ReplyKeyPack(&kp);
717         break;
718     }
719     default:
720         krb5_abortx(context, "internal pkinit error");
721     }
722     if (ret) {
723         krb5_set_error_string(context, "ASN.1 encoding of ReplyKeyPack "
724                               "failed (%d)", ret);
725         goto out;
726     }
727     if (buf.length != size)
728         krb5_abortx(context, "Internal ASN.1 encoder error");
729
730     {
731         hx509_query *q;
732         hx509_cert cert;
733         
734         ret = hx509_query_alloc(kdc_identity->hx509ctx, &q);
735         if (ret)
736             goto out;
737         
738         hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
739         hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
740         
741         ret = hx509_certs_find(kdc_identity->hx509ctx, 
742                                kdc_identity->certs, 
743                                q, 
744                                &cert);
745         hx509_query_free(kdc_identity->hx509ctx, q);
746         if (ret)
747             goto out;
748         
749         ret = hx509_cms_create_signed_1(kdc_identity->hx509ctx,
750                                         oid_id_pkrkeydata(),
751                                         buf.data,
752                                         buf.length,
753                                         NULL,
754                                         cert,
755                                         kdc_identity->anchors,
756                                         kdc_identity->certpool,
757                                         &signed_data);
758         hx509_cert_free(cert);
759     }
760
761     krb5_data_free(&buf);
762     if (ret) 
763         goto out;
764
765     ret = hx509_cms_envelope_1(kdc_identity->hx509ctx,
766                                client_params->cert,
767                                signed_data.data, signed_data.length, NULL,
768                                oid_id_pkcs7_signedData(), &buf);
769     if (ret)
770         goto out;
771     
772     ret = _krb5_pk_mk_ContentInfo(context,
773                                   &buf,
774                                   oid_id_pkcs7_envelopedData(),
775                                   content_info);
776 out:
777     krb5_data_free(&buf);
778     krb5_data_free(&signed_data);
779     return ret;
780 }
781
782 /*
783  *
784  */
785
786 static krb5_error_code
787 pk_mk_pa_reply_dh(krb5_context context,
788                   DH *kdc_dh,
789                   pk_client_params *client_params,
790                   krb5_keyblock *reply_key,
791                   ContentInfo *content_info,
792                   hx509_cert *kdc_cert)
793 {
794     KDCDHKeyInfo dh_info;
795     krb5_data signed_data, buf;
796     ContentInfo contentinfo;
797     krb5_error_code ret;
798     size_t size;
799     heim_integer i;
800
801     memset(&contentinfo, 0, sizeof(contentinfo));
802     memset(&dh_info, 0, sizeof(dh_info));
803     krb5_data_zero(&buf);
804     krb5_data_zero(&signed_data);
805
806     *kdc_cert = NULL;
807
808     ret = BN_to_integer(context, kdc_dh->pub_key, &i);
809     if (ret)
810         return ret;
811
812     ASN1_MALLOC_ENCODE(DHPublicKey, buf.data, buf.length, &i, &size, ret);
813     if (ret) {
814         krb5_set_error_string(context, "ASN.1 encoding of "
815                               "DHPublicKey failed (%d)", ret);
816         krb5_clear_error_string(context);
817         return ret;
818     }
819     if (buf.length != size)
820         krb5_abortx(context, "Internal ASN.1 encoder error");
821
822     dh_info.subjectPublicKey.length = buf.length * 8;
823     dh_info.subjectPublicKey.data = buf.data;
824     
825     dh_info.nonce = client_params->nonce;
826
827     ASN1_MALLOC_ENCODE(KDCDHKeyInfo, buf.data, buf.length, &dh_info, &size, 
828                        ret);
829     if (ret) {
830         krb5_set_error_string(context, "ASN.1 encoding of "
831                               "KdcDHKeyInfo failed (%d)", ret);
832         goto out;
833     }
834     if (buf.length != size)
835         krb5_abortx(context, "Internal ASN.1 encoder error");
836
837     /* 
838      * Create the SignedData structure and sign the KdcDHKeyInfo
839      * filled in above
840      */
841
842     {
843         hx509_query *q;
844         hx509_cert cert;
845         
846         ret = hx509_query_alloc(kdc_identity->hx509ctx, &q);
847         if (ret)
848             goto out;
849         
850         hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
851         hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
852         
853         ret = hx509_certs_find(kdc_identity->hx509ctx, 
854                                kdc_identity->certs, 
855                                q, 
856                                &cert);
857         hx509_query_free(kdc_identity->hx509ctx, q);
858         if (ret)
859             goto out;
860         
861         ret = hx509_cms_create_signed_1(kdc_identity->hx509ctx,
862                                         oid_id_pkdhkeydata(),
863                                         buf.data,
864                                         buf.length,
865                                         NULL,
866                                         cert,
867                                         kdc_identity->anchors,
868                                         kdc_identity->certpool,
869                                         &signed_data);
870         *kdc_cert = cert;
871     }
872     if (ret)
873         goto out;
874
875     ret = _krb5_pk_mk_ContentInfo(context,
876                                   &signed_data,
877                                   oid_id_pkcs7_signedData(),
878                                   content_info);
879     if (ret)
880         goto out;
881
882  out:
883     if (ret && *kdc_cert) {
884         hx509_cert_free(*kdc_cert);
885         *kdc_cert = NULL;
886     }
887
888     krb5_data_free(&buf);
889     krb5_data_free(&signed_data);
890     free_KDCDHKeyInfo(&dh_info);
891
892     return ret;
893 }
894
895 /*
896  *
897  */
898
899 krb5_error_code
900 _kdc_pk_mk_pa_reply(krb5_context context,
901                     krb5_kdc_configuration *config,
902                     pk_client_params *client_params,
903                     const hdb_entry_ex *client,
904                     const KDC_REQ *req,
905                     const krb5_data *req_buffer,
906                     krb5_keyblock **reply_key,
907                     METHOD_DATA *md)
908 {
909     krb5_error_code ret;
910     void *buf;
911     size_t len, size;
912     krb5_enctype enctype;
913     int pa_type;
914     hx509_cert kdc_cert = NULL;
915     int i;
916
917     if (!config->enable_pkinit) {
918         krb5_clear_error_string(context);
919         return 0;
920     }
921
922     if (req->req_body.etype.len > 0) {
923         for (i = 0; i < req->req_body.etype.len; i++)
924             if (krb5_enctype_valid(context, req->req_body.etype.val[i]) == 0)
925                 break;
926         if (req->req_body.etype.len <= i) {
927             ret = KRB5KRB_ERR_GENERIC;
928             krb5_set_error_string(context,
929                                   "No valid enctype available from client");
930             goto out;
931         }       
932         enctype = req->req_body.etype.val[i];
933     } else
934         enctype = ETYPE_DES3_CBC_SHA1;
935
936     if (client_params->type == PKINIT_COMPAT_27) {
937         PA_PK_AS_REP rep;
938         const char *type, *other = "";
939
940         memset(&rep, 0, sizeof(rep));
941
942         pa_type = KRB5_PADATA_PK_AS_REP;
943
944         if (client_params->dh == NULL) {
945             ContentInfo info;
946
947             type = "enckey";
948
949             rep.element = choice_PA_PK_AS_REP_encKeyPack;
950
951             krb5_generate_random_keyblock(context, enctype, 
952                                           &client_params->reply_key);
953             ret = pk_mk_pa_reply_enckey(context,
954                                         client_params,
955                                         req,
956                                         req_buffer,
957                                         &client_params->reply_key,
958                                         &info);
959             if (ret) {
960                 free_PA_PK_AS_REP(&rep);
961                 goto out;
962             }
963             ASN1_MALLOC_ENCODE(ContentInfo, rep.u.encKeyPack.data, 
964                                rep.u.encKeyPack.length, &info, &size, 
965                                ret);
966             free_ContentInfo(&info);
967             if (ret) {
968                 krb5_set_error_string(context, "encoding of Key ContentInfo "
969                                       "failed %d", ret);
970                 free_PA_PK_AS_REP(&rep);
971                 goto out;
972             }
973             if (rep.u.encKeyPack.length != size)
974                 krb5_abortx(context, "Internal ASN.1 encoder error");
975
976         } else {
977             ContentInfo info;
978
979             type = "dh";
980             if (client_params->dh_group_name)
981                 other = client_params->dh_group_name;
982
983             rep.element = choice_PA_PK_AS_REP_dhInfo;
984
985             ret = generate_dh_keyblock(context, client_params, enctype,
986                                        &client_params->reply_key);
987             if (ret)
988                 return ret;
989
990             ret = pk_mk_pa_reply_dh(context, client_params->dh,
991                                     client_params, 
992                                     &client_params->reply_key,
993                                     &info,
994                                     &kdc_cert);
995
996             ASN1_MALLOC_ENCODE(ContentInfo, rep.u.dhInfo.dhSignedData.data,
997                                rep.u.dhInfo.dhSignedData.length, &info, &size,
998                                ret);
999             free_ContentInfo(&info);
1000             if (ret) {
1001                 krb5_set_error_string(context, "encoding of Key ContentInfo "
1002                                       "failed %d", ret);
1003                 free_PA_PK_AS_REP(&rep);
1004                 goto out;
1005             }
1006             if (rep.u.encKeyPack.length != size)
1007                 krb5_abortx(context, "Internal ASN.1 encoder error");
1008
1009         }
1010         if (ret) {
1011             free_PA_PK_AS_REP(&rep);
1012             goto out;
1013         }
1014
1015         ASN1_MALLOC_ENCODE(PA_PK_AS_REP, buf, len, &rep, &size, ret);
1016         free_PA_PK_AS_REP(&rep);
1017         if (ret) {
1018             krb5_set_error_string(context, "encode PA-PK-AS-REP failed %d",
1019                                   ret);
1020             goto out;
1021         }
1022         if (len != size)
1023             krb5_abortx(context, "Internal ASN.1 encoder error");
1024
1025         kdc_log(context, config, 0, "PK-INIT using %s %s", type, other);
1026
1027     } else if (client_params->type == PKINIT_COMPAT_WIN2K) {
1028         PA_PK_AS_REP_Win2k rep;
1029         ContentInfo info;
1030
1031         if (client_params->dh) {
1032             krb5_set_error_string(context, "Windows PK-INIT doesn't support DH");
1033             ret = KRB5KRB_ERR_GENERIC;
1034             goto out;
1035         }
1036
1037         memset(&rep, 0, sizeof(rep));
1038
1039         pa_type = KRB5_PADATA_PK_AS_REP_19;
1040         rep.element = choice_PA_PK_AS_REP_encKeyPack;
1041
1042         krb5_generate_random_keyblock(context, enctype, 
1043                                       &client_params->reply_key);
1044         ret = pk_mk_pa_reply_enckey(context,
1045                                     client_params,
1046                                     req,
1047                                     req_buffer,
1048                                     &client_params->reply_key,
1049                                     &info);
1050         if (ret) {
1051             free_PA_PK_AS_REP_Win2k(&rep);
1052             goto out;
1053         }
1054         ASN1_MALLOC_ENCODE(ContentInfo, rep.u.encKeyPack.data, 
1055                            rep.u.encKeyPack.length, &info, &size, 
1056                            ret);
1057         free_ContentInfo(&info);
1058         if (ret) {
1059             krb5_set_error_string(context, "encoding of Key ContentInfo "
1060                                   "failed %d", ret);
1061             free_PA_PK_AS_REP_Win2k(&rep);
1062             goto out;
1063         }
1064         if (rep.u.encKeyPack.length != size)
1065             krb5_abortx(context, "Internal ASN.1 encoder error");
1066
1067         ASN1_MALLOC_ENCODE(PA_PK_AS_REP_Win2k, buf, len, &rep, &size, ret);
1068         free_PA_PK_AS_REP_Win2k(&rep);
1069         if (ret) {
1070             krb5_set_error_string(context, 
1071                                   "encode PA-PK-AS-REP-Win2k failed %d", ret);
1072             goto out;
1073         }
1074         if (len != size)
1075             krb5_abortx(context, "Internal ASN.1 encoder error");
1076
1077     } else
1078         krb5_abortx(context, "PK-INIT internal error");
1079
1080
1081     ret = krb5_padata_add(context, md, pa_type, buf, len);
1082     if (ret) {
1083         krb5_set_error_string(context, "failed adding PA-PK-AS-REP %d", ret);
1084         free(buf);
1085         goto out;
1086     }
1087
1088     if (config->pkinit_kdc_ocsp_file) {
1089
1090         if (ocsp.expire == 0 && ocsp.next_update > kdc_time) {
1091             struct stat sb;
1092             int fd;
1093
1094             krb5_data_free(&ocsp.data);
1095
1096             ocsp.expire = 0;
1097
1098             fd = open(config->pkinit_kdc_ocsp_file, O_RDONLY);
1099             if (fd < 0) {
1100                 kdc_log(context, config, 0, 
1101                         "PK-INIT failed to open ocsp data file %d", errno);
1102                 goto out_ocsp;
1103             }
1104             ret = fstat(fd, &sb);
1105             if (ret) {
1106                 ret = errno;
1107                 close(fd);
1108                 kdc_log(context, config, 0, 
1109                         "PK-INIT failed to stat ocsp data %d", ret);
1110                 goto out_ocsp;
1111             }
1112             
1113             ret = krb5_data_alloc(&ocsp.data, sb.st_size);
1114             if (ret) {
1115                 close(fd);
1116                 kdc_log(context, config, 0, 
1117                         "PK-INIT failed to stat ocsp data %d", ret);
1118                 goto out_ocsp;
1119             }
1120             ocsp.data.length = sb.st_size;
1121             ret = read(fd, ocsp.data.data, sb.st_size);
1122             close(fd);
1123             if (ret != sb.st_size) {
1124                 kdc_log(context, config, 0, 
1125                         "PK-INIT failed to read ocsp data %d", errno);
1126                 goto out_ocsp;
1127             }
1128
1129             ret = hx509_ocsp_verify(kdc_identity->hx509ctx,
1130                                     kdc_time,
1131                                     kdc_cert,
1132                                     0,
1133                                     ocsp.data.data, ocsp.data.length,
1134                                     &ocsp.expire);
1135             if (ret) {
1136                 kdc_log(context, config, 0, 
1137                         "PK-INIT failed to verify ocsp data %d", ret);
1138                 krb5_data_free(&ocsp.data);
1139                 ocsp.expire = 0;
1140             } else if (ocsp.expire > 180)
1141                 ocsp.expire -= 180; /* refetch the ocsp before it expire */
1142             
1143         out_ocsp:
1144             ocsp.next_update = kdc_time + 3600;
1145             ret = 0;
1146         }
1147
1148         if (ocsp.expire != 0 && ocsp.expire > kdc_time) {
1149
1150             ret = krb5_padata_add(context, md, 
1151                                   KRB5_PADATA_PA_PK_OCSP_RESPONSE,
1152                                   ocsp.data.data, ocsp.data.length);
1153             if (ret) {
1154                 krb5_set_error_string(context, 
1155                                       "Failed adding OCSP response %d", ret);
1156                 goto out;
1157             }
1158         }
1159     }
1160
1161 out:
1162     if (kdc_cert)
1163         hx509_cert_free(kdc_cert);
1164
1165     if (ret == 0)
1166         *reply_key = &client_params->reply_key;
1167     return ret;
1168 }
1169
1170 static int
1171 pk_principal_from_X509(krb5_context context, 
1172                        krb5_kdc_configuration *config,
1173                        hx509_cert client_cert, 
1174                        krb5_const_principal match)
1175 {
1176     hx509_octet_string_list list;
1177     int ret, i, found = 0;
1178
1179     memset(&list, 0 , sizeof(list));
1180
1181     ret = hx509_cert_find_subjectAltName_otherName(client_cert,
1182                                                    oid_id_pkinit_san(),
1183                                                    &list);
1184     if (ret)
1185         goto out;
1186
1187     for (i = 0; !found && i < list.len; i++) {
1188         krb5_principal_data principal;
1189         KRB5PrincipalName kn;
1190         size_t size;
1191
1192         ret = decode_KRB5PrincipalName(list.val[i].data, 
1193                                        list.val[i].length,
1194                                        &kn, &size);
1195         if (ret) {
1196             kdc_log(context, config, 0,
1197                     "Decoding kerberos name in certificate failed: %s",
1198                     krb5_get_err_text(context, ret));
1199             break;
1200         }
1201         if (size != list.val[i].length) {
1202             kdc_log(context, config, 0,
1203                     "Decoding kerberos name have extra bits on the end");
1204             return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1205         }
1206
1207         principal.name = kn.principalName;
1208         principal.realm = kn.realm;
1209
1210         if (krb5_principal_compare(context, &principal, match) == TRUE)
1211             found = 1;
1212         free_KRB5PrincipalName(&kn);
1213     }
1214
1215 out:
1216     hx509_free_octet_string_list(&list);    
1217     if (ret)
1218         return ret;
1219
1220     if (!found)
1221         return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1222
1223     return 0;
1224 }
1225
1226
1227 krb5_error_code
1228 _kdc_pk_check_client(krb5_context context,
1229                      krb5_kdc_configuration *config,
1230                      krb5_principal client_princ,
1231                      const hdb_entry_ex *client,
1232                      pk_client_params *client_params,
1233                      char **subject_name)
1234 {
1235     const HDB_Ext_PKINIT_acl *acl;
1236     krb5_error_code ret;
1237     hx509_name name;
1238     int i;
1239
1240     ret = hx509_cert_get_base_subject(kdc_identity->hx509ctx, 
1241                                       client_params->cert,
1242                                       &name);
1243     if (ret)
1244         return ret;
1245
1246     ret = hx509_name_to_string(name, subject_name);
1247     hx509_name_free(&name);
1248     if (ret)
1249         return ret;
1250
1251     kdc_log(context, config, 0,
1252             "Trying to authorize PK-INIT subject DN %s", 
1253             *subject_name);
1254
1255     if (config->enable_pkinit_princ_in_cert) {
1256         ret = pk_principal_from_X509(context, config, 
1257                                      client_params->cert,
1258                                      client_princ);
1259         if (ret == 0) {
1260             kdc_log(context, config, 5,
1261                     "Found matching PK-INIT SAN in certificate");
1262             return 0;
1263         }
1264     }
1265
1266     ret = hdb_entry_get_pkinit_acl(&client->entry, &acl);
1267     if (ret == 0 && acl != NULL) {
1268         /*
1269          * Cheat here and compare the generated name with the string
1270          * and not the reverse.
1271          */
1272         for (i = 0; i < acl->len; i++) {
1273             if (strcmp(*subject_name, acl->val[0].subject) != 0)
1274                 continue;
1275
1276             /* Don't support isser and anchor checking right now */
1277             if (acl->val[0].issuer)
1278                 continue;
1279             if (acl->val[0].anchor)
1280                 continue;
1281
1282             kdc_log(context, config, 5,
1283                     "Found matching PK-INIT database ACL");
1284             return 0;
1285         }
1286     }
1287
1288     for (i = 0; i < principal_mappings.len; i++) {
1289         krb5_boolean b;
1290
1291         b = krb5_principal_compare(context,
1292                                    client_princ,
1293                                    principal_mappings.val[i].principal);
1294         if (b == FALSE)
1295             continue;
1296         if (strcmp(principal_mappings.val[i].subject, *subject_name) != 0)
1297             continue;
1298         kdc_log(context, config, 5,
1299                 "Found matching PK-INIT FILE ACL");
1300         return 0;
1301     }
1302
1303     free(*subject_name);
1304     *subject_name = NULL;
1305
1306     krb5_set_error_string(context, "PKINIT no matching principals");
1307     return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1308 }
1309
1310 static krb5_error_code
1311 add_principal_mapping(krb5_context context, 
1312                       const char *principal_name,
1313                       const char * subject)
1314 {
1315    struct pk_allowed_princ *tmp;
1316    krb5_principal principal;
1317    krb5_error_code ret;
1318
1319    tmp = realloc(principal_mappings.val,
1320                  (principal_mappings.len + 1) * sizeof(*tmp));
1321    if (tmp == NULL)
1322        return ENOMEM;
1323    principal_mappings.val = tmp;
1324
1325    ret = krb5_parse_name(context, principal_name, &principal);
1326    if (ret)
1327        return ret;
1328
1329    principal_mappings.val[principal_mappings.len].principal = principal;
1330
1331    principal_mappings.val[principal_mappings.len].subject = strdup(subject);
1332    if (principal_mappings.val[principal_mappings.len].subject == NULL) {
1333        krb5_free_principal(context, principal);
1334        return ENOMEM;
1335    }
1336    principal_mappings.len++;
1337
1338    return 0;
1339 }
1340
1341
1342 krb5_error_code
1343 _kdc_pk_initialize(krb5_context context,
1344                    krb5_kdc_configuration *config,
1345                    const char *user_id,
1346                    const char *anchors,
1347                    char **pool,
1348                    char **revoke_list)
1349 {
1350     const char *file; 
1351     krb5_error_code ret;
1352     char buf[1024];
1353     unsigned long lineno = 0;
1354     FILE *f;
1355
1356     file = krb5_config_get_string(context, NULL,
1357                                   "libdefaults", "moduli", NULL);
1358
1359     ret = _krb5_parse_moduli(context, file, &moduli);
1360     if (ret)
1361         krb5_err(context, 1, ret, "PKINIT: failed to load modidi file");
1362
1363     principal_mappings.len = 0;
1364     principal_mappings.val = NULL;
1365
1366     ret = _krb5_pk_load_id(context,
1367                            &kdc_identity,
1368                            user_id,
1369                            anchors,
1370                            pool,
1371                            revoke_list,
1372                            NULL,
1373                            NULL,
1374                            NULL);
1375     if (ret) {
1376         krb5_warn(context, ret, "PKINIT: failed to load");
1377         config->enable_pkinit = 0;
1378         return ret;
1379     }
1380
1381     {
1382         hx509_query *q;
1383         hx509_cert cert;
1384         
1385         ret = hx509_query_alloc(kdc_identity->hx509ctx, &q);
1386         if (ret) {
1387             krb5_warnx(context, "PKINIT: out of memory");
1388             return ENOMEM;
1389         }
1390         
1391         hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
1392         hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
1393         
1394         ret = hx509_certs_find(kdc_identity->hx509ctx,
1395                                kdc_identity->certs,
1396                                q,
1397                                &cert);
1398         hx509_query_free(kdc_identity->hx509ctx, q);
1399         if (ret == 0) {
1400             if (hx509_cert_check_eku(kdc_identity->hx509ctx, cert,
1401                                      oid_id_pkkdcekuoid(), 0))
1402                 krb5_warnx(context, "WARNING Found KDC certificate "
1403                            "is missing the PK-INIT KDC EKU, this is bad for "
1404                            "interoperability.");
1405             hx509_cert_free(cert);
1406         } else
1407             krb5_warnx(context, "PKINIT: failed to find a signing "
1408                        "certifiate with a public key");
1409     }
1410
1411     ret = krb5_config_get_bool_default(context, 
1412                                        NULL,
1413                                        FALSE,
1414                                        "kdc",
1415                                        "pki-allow-proxy-certificate",
1416                                        NULL);
1417     _krb5_pk_allow_proxy_certificate(kdc_identity, ret);
1418
1419     file = krb5_config_get_string_default(context, 
1420                                           NULL,
1421                                           HDB_DB_DIR "/pki-mapping",
1422                                           "kdc",
1423                                           "pki-mappings-file",
1424                                           NULL);
1425     f = fopen(file, "r");
1426     if (f == NULL) {
1427         krb5_warnx(context, "PKINIT: failed to load mappings file %s", file);
1428         return 0;
1429     }
1430
1431     while (fgets(buf, sizeof(buf), f) != NULL) {
1432         char *subject_name, *p;
1433     
1434         buf[strcspn(buf, "\n")] = '\0';
1435         lineno++;
1436
1437         p = buf + strspn(buf, " \t");
1438
1439         if (*p == '#' || *p == '\0')
1440             continue;
1441
1442         subject_name = strchr(p, ':');
1443         if (subject_name == NULL) {
1444             krb5_warnx(context, "pkinit mapping file line %lu "
1445                        "missing \":\" :%s",
1446                        lineno, buf);
1447             continue;
1448         }
1449         *subject_name++ = '\0';
1450
1451         ret = add_principal_mapping(context, p, subject_name);
1452         if (ret) {
1453             krb5_warn(context, ret, "failed to add line %lu \":\" :%s\n",
1454                       lineno, buf);
1455             continue;
1456         }
1457     } 
1458
1459     fclose(f);
1460
1461     return 0;
1462 }
1463
1464 #endif /* PKINIT */