e3d77c06219f76e16668619c4947346d6b54a025
[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.72 2006/10/24 17:51:33 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             kdc_log(context, config, 0,
532                     "PK-INIT failed to verify signature %d", ret);
533             goto out;
534         }
535
536         ret = hx509_get_one_cert(kdc_identity->hx509ctx, signer_certs,
537                                  &client_params->cert);
538         hx509_certs_free(&signer_certs);
539         if (ret)
540             goto out;
541     }
542
543     /* Signature is correct, now verify the signed message */
544     if (der_heim_oid_cmp(&eContentType, pa_contentType)) {
545         krb5_set_error_string(context, "got wrong oid for pkauthdata");
546         ret = KRB5_BADMSGTYPE;
547         goto out;
548     }
549
550     if (pa->padata_type == KRB5_PADATA_PK_AS_REQ_WIN) {
551         AuthPack_Win2k ap;
552
553         ret = decode_AuthPack_Win2k(eContent.data,
554                                     eContent.length,
555                                     &ap,
556                                     NULL);
557         if (ret) {
558             krb5_set_error_string(context, "can't decode AuthPack: %d", ret);
559             goto out;
560         }
561   
562         ret = pk_check_pkauthenticator_win2k(context, 
563                                              &ap.pkAuthenticator,
564                                              req);
565         if (ret) {
566             free_AuthPack_Win2k(&ap);
567             goto out;
568         }
569
570         client_params->type = PKINIT_COMPAT_WIN2K;
571         client_params->nonce = ap.pkAuthenticator.nonce;
572
573         if (ap.clientPublicValue) {
574             krb5_set_error_string(context, "DH not supported for windows");
575             ret = KRB5KRB_ERR_GENERIC;
576             goto out;
577         }
578         free_AuthPack_Win2k(&ap);
579
580     } else if (pa->padata_type == KRB5_PADATA_PK_AS_REQ) {
581         AuthPack ap;
582
583         ret = decode_AuthPack(eContent.data,
584                               eContent.length,
585                               &ap,
586                               NULL);
587         if (ret) {
588             krb5_set_error_string(context, "can't decode AuthPack: %d", ret);
589             free_AuthPack(&ap);
590             goto out;
591         }
592   
593         ret = pk_check_pkauthenticator(context, 
594                                        &ap.pkAuthenticator,
595                                        req);
596         if (ret) {
597             free_AuthPack(&ap);
598             goto out;
599         }
600
601         client_params->type = PKINIT_COMPAT_27;
602         client_params->nonce = ap.pkAuthenticator.nonce;
603
604         if (ap.clientPublicValue) {
605             ret = get_dh_param(context, config, 
606                                ap.clientPublicValue, client_params);
607             if (ret) {
608                 free_AuthPack(&ap);
609                 goto out;
610             }
611         }
612         free_AuthPack(&ap);
613     } else
614         krb5_abortx(context, "internal pkinit error");
615
616     kdc_log(context, config, 0, "PK-INIT request of type %s", type);
617
618 out:
619
620     if (signed_content.data)
621         free(signed_content.data);
622     krb5_data_free(&eContent);
623     der_free_oid(&eContentType);
624     der_free_oid(&contentInfoOid);
625     if (ret)
626         _kdc_pk_free_client_param(context, client_params);
627     else
628         *ret_params = client_params;
629     return ret;
630 }
631
632 /*
633  *
634  */
635
636 static krb5_error_code
637 BN_to_integer(krb5_context context, BIGNUM *bn, heim_integer *integer)
638 {
639     integer->length = BN_num_bytes(bn);
640     integer->data = malloc(integer->length);
641     if (integer->data == NULL) {
642         krb5_clear_error_string(context);
643         return ENOMEM;
644     }
645     BN_bn2bin(bn, integer->data);
646     integer->negative = BN_is_negative(bn);
647     return 0;
648 }
649
650 static krb5_error_code
651 pk_mk_pa_reply_enckey(krb5_context context,
652                       pk_client_params *client_params,
653                       const KDC_REQ *req,
654                       const krb5_data *req_buffer,
655                       krb5_keyblock *reply_key,
656                       ContentInfo *content_info)
657 {
658     krb5_error_code ret;
659     krb5_data buf, signed_data;
660     size_t size;
661
662     krb5_data_zero(&buf);
663     krb5_data_zero(&signed_data);
664
665     switch (client_params->type) {
666     case PKINIT_COMPAT_WIN2K: {
667         ReplyKeyPack_Win2k kp;
668         memset(&kp, 0, sizeof(kp));
669
670         ret = copy_EncryptionKey(reply_key, &kp.replyKey);
671         if (ret) {
672             krb5_clear_error_string(context);
673             goto out;
674         }
675         kp.nonce = client_params->nonce;
676         
677         ASN1_MALLOC_ENCODE(ReplyKeyPack_Win2k, 
678                            buf.data, buf.length,
679                            &kp, &size,ret);
680         free_ReplyKeyPack_Win2k(&kp);
681         break;
682     }
683     case PKINIT_COMPAT_27: {
684         krb5_crypto ascrypto;
685         ReplyKeyPack kp;
686         memset(&kp, 0, sizeof(kp));
687
688         ret = copy_EncryptionKey(reply_key, &kp.replyKey);
689         if (ret) {
690             krb5_clear_error_string(context);
691             goto out;
692         }
693
694         ret = krb5_crypto_init(context, reply_key, 0, &ascrypto);
695         if (ret) {
696             krb5_clear_error_string(context);
697             goto out;
698         }
699
700         ret = krb5_create_checksum(context, ascrypto, 6, 0,
701                                    req_buffer->data, req_buffer->length,
702                                    &kp.asChecksum);
703         if (ret) {
704             krb5_clear_error_string(context);
705             goto out;
706         }
707                              
708         ret = krb5_crypto_destroy(context, ascrypto);
709         if (ret) {
710             krb5_clear_error_string(context);
711             goto out;
712         }
713         ASN1_MALLOC_ENCODE(ReplyKeyPack, buf.data, buf.length, &kp, &size,ret);
714         free_ReplyKeyPack(&kp);
715         break;
716     }
717     default:
718         krb5_abortx(context, "internal pkinit error");
719     }
720     if (ret) {
721         krb5_set_error_string(context, "ASN.1 encoding of ReplyKeyPack "
722                               "failed (%d)", ret);
723         goto out;
724     }
725     if (buf.length != size)
726         krb5_abortx(context, "Internal ASN.1 encoder error");
727
728     {
729         hx509_query *q;
730         hx509_cert cert;
731         
732         ret = hx509_query_alloc(kdc_identity->hx509ctx, &q);
733         if (ret)
734             goto out;
735         
736         hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
737         hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
738         
739         ret = hx509_certs_find(kdc_identity->hx509ctx, 
740                                kdc_identity->certs, 
741                                q, 
742                                &cert);
743         hx509_query_free(kdc_identity->hx509ctx, q);
744         if (ret)
745             goto out;
746         
747         ret = hx509_cms_create_signed_1(kdc_identity->hx509ctx,
748                                         oid_id_pkrkeydata(),
749                                         buf.data,
750                                         buf.length,
751                                         NULL,
752                                         cert,
753                                         kdc_identity->anchors,
754                                         kdc_identity->certpool,
755                                         &signed_data);
756         hx509_cert_free(cert);
757     }
758
759     krb5_data_free(&buf);
760     if (ret) 
761         goto out;
762
763     ret = hx509_cms_envelope_1(kdc_identity->hx509ctx,
764                                client_params->cert,
765                                signed_data.data, signed_data.length, NULL,
766                                oid_id_pkcs7_signedData(), &buf);
767     if (ret)
768         goto out;
769     
770     ret = _krb5_pk_mk_ContentInfo(context,
771                                   &buf,
772                                   oid_id_pkcs7_envelopedData(),
773                                   content_info);
774 out:
775     krb5_data_free(&buf);
776     krb5_data_free(&signed_data);
777     return ret;
778 }
779
780 /*
781  *
782  */
783
784 static krb5_error_code
785 pk_mk_pa_reply_dh(krb5_context context,
786                   DH *kdc_dh,
787                   pk_client_params *client_params,
788                   krb5_keyblock *reply_key,
789                   ContentInfo *content_info,
790                   hx509_cert *kdc_cert)
791 {
792     KDCDHKeyInfo dh_info;
793     krb5_data signed_data, buf;
794     ContentInfo contentinfo;
795     krb5_error_code ret;
796     size_t size;
797     heim_integer i;
798
799     memset(&contentinfo, 0, sizeof(contentinfo));
800     memset(&dh_info, 0, sizeof(dh_info));
801     krb5_data_zero(&buf);
802     krb5_data_zero(&signed_data);
803
804     *kdc_cert = NULL;
805
806     ret = BN_to_integer(context, kdc_dh->pub_key, &i);
807     if (ret)
808         return ret;
809
810     ASN1_MALLOC_ENCODE(DHPublicKey, buf.data, buf.length, &i, &size, ret);
811     if (ret) {
812         krb5_set_error_string(context, "ASN.1 encoding of "
813                               "DHPublicKey failed (%d)", ret);
814         krb5_clear_error_string(context);
815         return ret;
816     }
817     if (buf.length != size)
818         krb5_abortx(context, "Internal ASN.1 encoder error");
819
820     dh_info.subjectPublicKey.length = buf.length * 8;
821     dh_info.subjectPublicKey.data = buf.data;
822     
823     dh_info.nonce = client_params->nonce;
824
825     ASN1_MALLOC_ENCODE(KDCDHKeyInfo, buf.data, buf.length, &dh_info, &size, 
826                        ret);
827     if (ret) {
828         krb5_set_error_string(context, "ASN.1 encoding of "
829                               "KdcDHKeyInfo failed (%d)", ret);
830         goto out;
831     }
832     if (buf.length != size)
833         krb5_abortx(context, "Internal ASN.1 encoder error");
834
835     /* 
836      * Create the SignedData structure and sign the KdcDHKeyInfo
837      * filled in above
838      */
839
840     {
841         hx509_query *q;
842         hx509_cert cert;
843         
844         ret = hx509_query_alloc(kdc_identity->hx509ctx, &q);
845         if (ret)
846             goto out;
847         
848         hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
849         hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
850         
851         ret = hx509_certs_find(kdc_identity->hx509ctx, 
852                                kdc_identity->certs, 
853                                q, 
854                                &cert);
855         hx509_query_free(kdc_identity->hx509ctx, q);
856         if (ret)
857             goto out;
858         
859         ret = hx509_cms_create_signed_1(kdc_identity->hx509ctx,
860                                         oid_id_pkdhkeydata(),
861                                         buf.data,
862                                         buf.length,
863                                         NULL,
864                                         cert,
865                                         kdc_identity->anchors,
866                                         kdc_identity->certpool,
867                                         &signed_data);
868         *kdc_cert = cert;
869     }
870     if (ret)
871         goto out;
872
873     ret = _krb5_pk_mk_ContentInfo(context,
874                                   &signed_data,
875                                   oid_id_pkcs7_signedData(),
876                                   content_info);
877     if (ret)
878         goto out;
879
880  out:
881     if (ret && *kdc_cert) {
882         hx509_cert_free(*kdc_cert);
883         *kdc_cert = NULL;
884     }
885
886     krb5_data_free(&buf);
887     krb5_data_free(&signed_data);
888     free_KDCDHKeyInfo(&dh_info);
889
890     return ret;
891 }
892
893 /*
894  *
895  */
896
897 krb5_error_code
898 _kdc_pk_mk_pa_reply(krb5_context context,
899                     krb5_kdc_configuration *config,
900                     pk_client_params *client_params,
901                     const hdb_entry_ex *client,
902                     const KDC_REQ *req,
903                     const krb5_data *req_buffer,
904                     krb5_keyblock **reply_key,
905                     METHOD_DATA *md)
906 {
907     krb5_error_code ret;
908     void *buf;
909     size_t len, size;
910     krb5_enctype enctype;
911     int pa_type;
912     hx509_cert kdc_cert = NULL;
913     int i;
914
915     if (!config->enable_pkinit) {
916         krb5_clear_error_string(context);
917         return 0;
918     }
919
920     if (req->req_body.etype.len > 0) {
921         for (i = 0; i < req->req_body.etype.len; i++)
922             if (krb5_enctype_valid(context, req->req_body.etype.val[i]) == 0)
923                 break;
924         if (req->req_body.etype.len <= i) {
925             ret = KRB5KRB_ERR_GENERIC;
926             krb5_set_error_string(context,
927                                   "No valid enctype available from client");
928             goto out;
929         }       
930         enctype = req->req_body.etype.val[i];
931     } else
932         enctype = ETYPE_DES3_CBC_SHA1;
933
934     if (client_params->type == PKINIT_COMPAT_27) {
935         PA_PK_AS_REP rep;
936         const char *type, *other = "";
937
938         memset(&rep, 0, sizeof(rep));
939
940         pa_type = KRB5_PADATA_PK_AS_REP;
941
942         if (client_params->dh == NULL) {
943             ContentInfo info;
944
945             type = "enckey";
946
947             rep.element = choice_PA_PK_AS_REP_encKeyPack;
948
949             krb5_generate_random_keyblock(context, enctype, 
950                                           &client_params->reply_key);
951             ret = pk_mk_pa_reply_enckey(context,
952                                         client_params,
953                                         req,
954                                         req_buffer,
955                                         &client_params->reply_key,
956                                         &info);
957             if (ret) {
958                 free_PA_PK_AS_REP(&rep);
959                 goto out;
960             }
961             ASN1_MALLOC_ENCODE(ContentInfo, rep.u.encKeyPack.data, 
962                                rep.u.encKeyPack.length, &info, &size, 
963                                ret);
964             free_ContentInfo(&info);
965             if (ret) {
966                 krb5_set_error_string(context, "encoding of Key ContentInfo "
967                                       "failed %d", ret);
968                 free_PA_PK_AS_REP(&rep);
969                 goto out;
970             }
971             if (rep.u.encKeyPack.length != size)
972                 krb5_abortx(context, "Internal ASN.1 encoder error");
973
974         } else {
975             ContentInfo info;
976
977             type = "dh";
978             if (client_params->dh_group_name)
979                 other = client_params->dh_group_name;
980
981             rep.element = choice_PA_PK_AS_REP_dhInfo;
982
983             ret = generate_dh_keyblock(context, client_params, enctype,
984                                        &client_params->reply_key);
985             if (ret)
986                 return ret;
987
988             ret = pk_mk_pa_reply_dh(context, client_params->dh,
989                                     client_params, 
990                                     &client_params->reply_key,
991                                     &info,
992                                     &kdc_cert);
993
994             ASN1_MALLOC_ENCODE(ContentInfo, rep.u.dhInfo.dhSignedData.data,
995                                rep.u.dhInfo.dhSignedData.length, &info, &size,
996                                ret);
997             free_ContentInfo(&info);
998             if (ret) {
999                 krb5_set_error_string(context, "encoding of Key ContentInfo "
1000                                       "failed %d", ret);
1001                 free_PA_PK_AS_REP(&rep);
1002                 goto out;
1003             }
1004             if (rep.u.encKeyPack.length != size)
1005                 krb5_abortx(context, "Internal ASN.1 encoder error");
1006
1007         }
1008         if (ret) {
1009             free_PA_PK_AS_REP(&rep);
1010             goto out;
1011         }
1012
1013         ASN1_MALLOC_ENCODE(PA_PK_AS_REP, buf, len, &rep, &size, ret);
1014         free_PA_PK_AS_REP(&rep);
1015         if (ret) {
1016             krb5_set_error_string(context, "encode PA-PK-AS-REP failed %d",
1017                                   ret);
1018             goto out;
1019         }
1020         if (len != size)
1021             krb5_abortx(context, "Internal ASN.1 encoder error");
1022
1023         kdc_log(context, config, 0, "PK-INIT using %s %s", type, other);
1024
1025     } else if (client_params->type == PKINIT_COMPAT_WIN2K) {
1026         PA_PK_AS_REP_Win2k rep;
1027         ContentInfo info;
1028
1029         if (client_params->dh) {
1030             krb5_set_error_string(context, "Windows PK-INIT doesn't support DH");
1031             ret = KRB5KRB_ERR_GENERIC;
1032             goto out;
1033         }
1034
1035         memset(&rep, 0, sizeof(rep));
1036
1037         pa_type = KRB5_PADATA_PK_AS_REP_19;
1038         rep.element = choice_PA_PK_AS_REP_encKeyPack;
1039
1040         krb5_generate_random_keyblock(context, enctype, 
1041                                       &client_params->reply_key);
1042         ret = pk_mk_pa_reply_enckey(context,
1043                                     client_params,
1044                                     req,
1045                                     req_buffer,
1046                                     &client_params->reply_key,
1047                                     &info);
1048         if (ret) {
1049             free_PA_PK_AS_REP_Win2k(&rep);
1050             goto out;
1051         }
1052         ASN1_MALLOC_ENCODE(ContentInfo, rep.u.encKeyPack.data, 
1053                            rep.u.encKeyPack.length, &info, &size, 
1054                            ret);
1055         free_ContentInfo(&info);
1056         if (ret) {
1057             krb5_set_error_string(context, "encoding of Key ContentInfo "
1058                                   "failed %d", ret);
1059             free_PA_PK_AS_REP_Win2k(&rep);
1060             goto out;
1061         }
1062         if (rep.u.encKeyPack.length != size)
1063             krb5_abortx(context, "Internal ASN.1 encoder error");
1064
1065         ASN1_MALLOC_ENCODE(PA_PK_AS_REP_Win2k, buf, len, &rep, &size, ret);
1066         free_PA_PK_AS_REP_Win2k(&rep);
1067         if (ret) {
1068             krb5_set_error_string(context, 
1069                                   "encode PA-PK-AS-REP-Win2k failed %d", ret);
1070             goto out;
1071         }
1072         if (len != size)
1073             krb5_abortx(context, "Internal ASN.1 encoder error");
1074
1075     } else
1076         krb5_abortx(context, "PK-INIT internal error");
1077
1078
1079     ret = krb5_padata_add(context, md, pa_type, buf, len);
1080     if (ret) {
1081         krb5_set_error_string(context, "failed adding PA-PK-AS-REP %d", ret);
1082         free(buf);
1083         goto out;
1084     }
1085
1086     if (config->pkinit_kdc_ocsp_file) {
1087
1088         if (ocsp.expire == 0 && ocsp.next_update > kdc_time) {
1089             struct stat sb;
1090             int fd;
1091
1092             krb5_data_free(&ocsp.data);
1093
1094             ocsp.expire = 0;
1095
1096             fd = open(config->pkinit_kdc_ocsp_file, O_RDONLY);
1097             if (fd < 0) {
1098                 kdc_log(context, config, 0, 
1099                         "PK-INIT failed to open ocsp data file %d", errno);
1100                 goto out_ocsp;
1101             }
1102             ret = fstat(fd, &sb);
1103             if (ret) {
1104                 ret = errno;
1105                 close(fd);
1106                 kdc_log(context, config, 0, 
1107                         "PK-INIT failed to stat ocsp data %d", ret);
1108                 goto out_ocsp;
1109             }
1110             
1111             ret = krb5_data_alloc(&ocsp.data, sb.st_size);
1112             if (ret) {
1113                 close(fd);
1114                 kdc_log(context, config, 0, 
1115                         "PK-INIT failed to stat ocsp data %d", ret);
1116                 goto out_ocsp;
1117             }
1118             ocsp.data.length = sb.st_size;
1119             ret = read(fd, ocsp.data.data, sb.st_size);
1120             close(fd);
1121             if (ret != sb.st_size) {
1122                 kdc_log(context, config, 0, 
1123                         "PK-INIT failed to read ocsp data %d", errno);
1124                 goto out_ocsp;
1125             }
1126
1127             ret = hx509_ocsp_verify(kdc_identity->hx509ctx,
1128                                     kdc_time,
1129                                     kdc_cert,
1130                                     0,
1131                                     ocsp.data.data, ocsp.data.length,
1132                                     &ocsp.expire);
1133             if (ret) {
1134                 kdc_log(context, config, 0, 
1135                         "PK-INIT failed to verify ocsp data %d", ret);
1136                 krb5_data_free(&ocsp.data);
1137                 ocsp.expire = 0;
1138             } else if (ocsp.expire > 180)
1139                 ocsp.expire -= 180; /* refetch the ocsp before it expire */
1140             
1141         out_ocsp:
1142             ocsp.next_update = kdc_time + 3600;
1143             ret = 0;
1144         }
1145
1146         if (ocsp.expire != 0 && ocsp.expire > kdc_time) {
1147
1148             ret = krb5_padata_add(context, md, 
1149                                   KRB5_PADATA_PA_PK_OCSP_RESPONSE,
1150                                   ocsp.data.data, ocsp.data.length);
1151             if (ret) {
1152                 krb5_set_error_string(context, 
1153                                       "Failed adding OCSP response %d", ret);
1154                 goto out;
1155             }
1156         }
1157     }
1158
1159 out:
1160     if (kdc_cert)
1161         hx509_cert_free(kdc_cert);
1162
1163     if (ret == 0)
1164         *reply_key = &client_params->reply_key;
1165     return ret;
1166 }
1167
1168 static int
1169 pk_principal_from_X509(krb5_context context, 
1170                        krb5_kdc_configuration *config,
1171                        hx509_cert client_cert, 
1172                        krb5_const_principal match)
1173 {
1174     hx509_octet_string_list list;
1175     int ret, i, found = 0;
1176
1177     memset(&list, 0 , sizeof(list));
1178
1179     ret = hx509_cert_find_subjectAltName_otherName(client_cert,
1180                                                    oid_id_pkinit_san(),
1181                                                    &list);
1182     if (ret)
1183         goto out;
1184
1185     for (i = 0; !found && i < list.len; i++) {
1186         krb5_principal_data principal;
1187         KRB5PrincipalName kn;
1188         size_t size;
1189
1190         ret = decode_KRB5PrincipalName(list.val[i].data, 
1191                                        list.val[i].length,
1192                                        &kn, &size);
1193         if (ret) {
1194             kdc_log(context, config, 0,
1195                     "Decoding kerberos name in certificate failed: %s",
1196                     krb5_get_err_text(context, ret));
1197             break;
1198         }
1199         if (size != list.val[i].length) {
1200             kdc_log(context, config, 0,
1201                     "Decoding kerberos name have extra bits on the end");
1202             return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1203         }
1204
1205         principal.name = kn.principalName;
1206         principal.realm = kn.realm;
1207
1208         if (krb5_principal_compare(context, &principal, match) == TRUE)
1209             found = 1;
1210         free_KRB5PrincipalName(&kn);
1211     }
1212
1213 out:
1214     hx509_free_octet_string_list(&list);    
1215     if (ret)
1216         return ret;
1217
1218     if (!found)
1219         return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1220
1221     return 0;
1222 }
1223
1224
1225 krb5_error_code
1226 _kdc_pk_check_client(krb5_context context,
1227                      krb5_kdc_configuration *config,
1228                      krb5_principal client_princ,
1229                      const hdb_entry_ex *client,
1230                      pk_client_params *client_params,
1231                      char **subject_name)
1232 {
1233     const HDB_Ext_PKINIT_acl *acl;
1234     krb5_error_code ret;
1235     hx509_name name;
1236     int i;
1237
1238     ret = hx509_cert_get_base_subject(kdc_identity->hx509ctx, 
1239                                       client_params->cert,
1240                                       &name);
1241     if (ret)
1242         return ret;
1243
1244     ret = hx509_name_to_string(name, subject_name);
1245     hx509_name_free(&name);
1246     if (ret)
1247         return ret;
1248
1249     kdc_log(context, config, 0,
1250             "Trying to authorize PK-INIT subject DN %s", 
1251             *subject_name);
1252
1253     if (config->enable_pkinit_princ_in_cert) {
1254         ret = pk_principal_from_X509(context, config, 
1255                                      client_params->cert,
1256                                      client_princ);
1257         if (ret == 0) {
1258             kdc_log(context, config, 5,
1259                     "Found matching PK-INIT SAN in certificate");
1260             return 0;
1261         }
1262     }
1263
1264     ret = hdb_entry_get_pkinit_acl(&client->entry, &acl);
1265     if (ret == 0 && acl != NULL) {
1266         /*
1267          * Cheat here and compare the generated name with the string
1268          * and not the reverse.
1269          */
1270         for (i = 0; i < acl->len; i++) {
1271             if (strcmp(*subject_name, acl->val[0].subject) != 0)
1272                 continue;
1273
1274             /* Don't support isser and anchor checking right now */
1275             if (acl->val[0].issuer)
1276                 continue;
1277             if (acl->val[0].anchor)
1278                 continue;
1279
1280             kdc_log(context, config, 5,
1281                     "Found matching PK-INIT database ACL");
1282             return 0;
1283         }
1284     }
1285
1286     for (i = 0; i < principal_mappings.len; i++) {
1287         krb5_boolean b;
1288
1289         b = krb5_principal_compare(context,
1290                                    client_princ,
1291                                    principal_mappings.val[i].principal);
1292         if (b == FALSE)
1293             continue;
1294         if (strcmp(principal_mappings.val[i].subject, *subject_name) != 0)
1295             continue;
1296         kdc_log(context, config, 5,
1297                 "Found matching PK-INIT FILE ACL");
1298         return 0;
1299     }
1300
1301     free(*subject_name);
1302     *subject_name = NULL;
1303
1304     krb5_set_error_string(context, "PKINIT no matching principals");
1305     return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1306 }
1307
1308 static krb5_error_code
1309 add_principal_mapping(krb5_context context, 
1310                       const char *principal_name,
1311                       const char * subject)
1312 {
1313    struct pk_allowed_princ *tmp;
1314    krb5_principal principal;
1315    krb5_error_code ret;
1316
1317    tmp = realloc(principal_mappings.val,
1318                  (principal_mappings.len + 1) * sizeof(*tmp));
1319    if (tmp == NULL)
1320        return ENOMEM;
1321    principal_mappings.val = tmp;
1322
1323    ret = krb5_parse_name(context, principal_name, &principal);
1324    if (ret)
1325        return ret;
1326
1327    principal_mappings.val[principal_mappings.len].principal = principal;
1328
1329    principal_mappings.val[principal_mappings.len].subject = strdup(subject);
1330    if (principal_mappings.val[principal_mappings.len].subject == NULL) {
1331        krb5_free_principal(context, principal);
1332        return ENOMEM;
1333    }
1334    principal_mappings.len++;
1335
1336    return 0;
1337 }
1338
1339
1340 krb5_error_code
1341 _kdc_pk_initialize(krb5_context context,
1342                    krb5_kdc_configuration *config,
1343                    const char *user_id,
1344                    const char *anchors,
1345                    char **pool,
1346                    char **revoke_list)
1347 {
1348     const char *file; 
1349     krb5_error_code ret;
1350     char buf[1024];
1351     unsigned long lineno = 0;
1352     FILE *f;
1353
1354     file = krb5_config_get_string(context, NULL,
1355                                   "libdefaults", "moduli", NULL);
1356
1357     ret = _krb5_parse_moduli(context, file, &moduli);
1358     if (ret)
1359         krb5_err(context, 1, ret, "PKINIT: failed to load modidi file");
1360
1361     principal_mappings.len = 0;
1362     principal_mappings.val = NULL;
1363
1364     ret = _krb5_pk_load_id(context,
1365                            &kdc_identity,
1366                            user_id,
1367                            anchors,
1368                            pool,
1369                            revoke_list,
1370                            NULL,
1371                            NULL,
1372                            NULL);
1373     if (ret) {
1374         krb5_warn(context, ret, "PKINIT: failed to load");
1375         config->enable_pkinit = 0;
1376         return ret;
1377     }
1378
1379     ret = krb5_config_get_bool_default(context, 
1380                                        NULL,
1381                                        FALSE,
1382                                        "kdc",
1383                                        "pki-allow-proxy-certificate",
1384                                        NULL);
1385     _krb5_pk_allow_proxy_certificate(kdc_identity, ret);
1386
1387     file = krb5_config_get_string_default(context, 
1388                                           NULL,
1389                                           HDB_DB_DIR "/pki-mapping",
1390                                           "kdc",
1391                                           "pki-mappings-file",
1392                                           NULL);
1393     f = fopen(file, "r");
1394     if (f == NULL) {
1395         krb5_warnx(context, "PKINIT: failed to load mappings file %s", file);
1396         return 0;
1397     }
1398
1399     while (fgets(buf, sizeof(buf), f) != NULL) {
1400         char *subject_name, *p;
1401     
1402         buf[strcspn(buf, "\n")] = '\0';
1403         lineno++;
1404
1405         p = buf + strspn(buf, " \t");
1406
1407         if (*p == '#' || *p == '\0')
1408             continue;
1409
1410         subject_name = strchr(p, ':');
1411         if (subject_name == NULL) {
1412             krb5_warnx(context, "pkinit mapping file line %lu "
1413                        "missing \":\" :%s",
1414                        lineno, buf);
1415             continue;
1416         }
1417         *subject_name++ = '\0';
1418
1419         ret = add_principal_mapping(context, p, subject_name);
1420         if (ret) {
1421             krb5_warn(context, ret, "failed to add line %lu \":\" :%s\n",
1422                       lineno, buf);
1423             continue;
1424         }
1425     } 
1426
1427     fclose(f);
1428
1429     return 0;
1430 }
1431
1432 #endif /* PKINIT */