r23456: Update Samba4 to current lorikeet-heimdal.
[ab/samba.git/.git] / source4 / heimdal / kdc / pkinit.c
1 /*
2  * Copyright (c) 2003 - 2006 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 21039 2007-06-10 06:20:31Z lha $");
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     hx509_peer_info peer;
72     hx509_certs client_anchors;
73 };
74
75 struct pk_principal_mapping {
76     unsigned int len;
77     struct pk_allowed_princ {
78         krb5_principal principal;
79         char *subject;
80     } *val;
81 };
82
83 static struct krb5_pk_identity *kdc_identity;
84 static struct pk_principal_mapping principal_mappings;
85 static struct krb5_dh_moduli **moduli;
86
87 static struct {
88     krb5_data data;
89     time_t expire;
90     time_t next_update;
91 } ocsp;
92
93 /*
94  *
95  */
96
97 static krb5_error_code
98 pk_check_pkauthenticator_win2k(krb5_context context,
99                                PKAuthenticator_Win2k *a,
100                                const KDC_REQ *req)
101 {
102     krb5_timestamp now;
103
104     krb5_timeofday (context, &now);
105
106     /* XXX cusec */
107     if (a->ctime == 0 || abs(a->ctime - now) > context->max_skew) {
108         krb5_clear_error_string(context);
109         return KRB5KRB_AP_ERR_SKEW;
110     }
111     return 0;
112 }
113
114 static krb5_error_code
115 pk_check_pkauthenticator(krb5_context context,
116                          PKAuthenticator *a,
117                          const KDC_REQ *req)
118 {
119     u_char *buf = NULL;
120     size_t buf_size;
121     krb5_error_code ret;
122     size_t len;
123     krb5_timestamp now;
124     Checksum checksum;
125
126     krb5_timeofday (context, &now);
127
128     /* XXX cusec */
129     if (a->ctime == 0 || abs(a->ctime - now) > context->max_skew) {
130         krb5_clear_error_string(context);
131         return KRB5KRB_AP_ERR_SKEW;
132     }
133
134     ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, &req->req_body, &len, ret);
135     if (ret) {
136         krb5_clear_error_string(context);
137         return ret;
138     }
139     if (buf_size != len)
140         krb5_abortx(context, "Internal error in ASN.1 encoder");
141
142     ret = krb5_create_checksum(context,
143                                NULL,
144                                0,
145                                CKSUMTYPE_SHA1,
146                                buf,
147                                len,
148                                &checksum);
149     free(buf);
150     if (ret) {
151         krb5_clear_error_string(context);
152         return ret;
153     }
154         
155     if (a->paChecksum == NULL) {
156         krb5_clear_error_string(context);
157         ret = KRB5_KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED;
158         goto out;
159     }
160
161     if (der_heim_octet_string_cmp(a->paChecksum, &checksum.checksum) != 0) {
162         krb5_clear_error_string(context);
163         ret = KRB5KRB_ERR_GENERIC;
164     }
165
166 out:
167     free_Checksum(&checksum);
168
169     return ret;
170 }
171
172 void
173 _kdc_pk_free_client_param(krb5_context context, 
174                           pk_client_params *client_params)
175 {
176     if (client_params->cert)
177         hx509_cert_free(client_params->cert);
178     if (client_params->dh)
179         DH_free(client_params->dh);
180     if (client_params->dh_public_key)
181         BN_free(client_params->dh_public_key);
182     krb5_free_keyblock_contents(context, &client_params->reply_key);
183     if (client_params->dh_group_name)
184         free(client_params->dh_group_name);
185     if (client_params->peer)
186         hx509_peer_info_free(client_params->peer);
187     if (client_params->client_anchors)
188         hx509_certs_free(&client_params->client_anchors);
189     memset(client_params, 0, sizeof(*client_params));
190     free(client_params);
191 }
192
193 static krb5_error_code
194 generate_dh_keyblock(krb5_context context, pk_client_params *client_params,
195                      krb5_enctype enctype, krb5_keyblock *reply_key)
196 {
197     unsigned char *dh_gen_key = NULL;
198     krb5_keyblock key;
199     krb5_error_code ret;
200     size_t dh_gen_keylen, size;
201
202     memset(&key, 0, sizeof(key));
203
204     if (!DH_generate_key(client_params->dh)) {
205         krb5_set_error_string(context, "Can't generate Diffie-Hellman keys");
206         ret = KRB5KRB_ERR_GENERIC;
207         goto out;
208     }
209     if (client_params->dh_public_key == NULL) {
210         krb5_set_error_string(context, "dh_public_key");
211         ret = KRB5KRB_ERR_GENERIC;
212         goto out;
213     }
214
215     dh_gen_keylen = DH_size(client_params->dh);
216     size = BN_num_bytes(client_params->dh->p);
217     if (size < dh_gen_keylen)
218         size = dh_gen_keylen;
219
220     dh_gen_key = malloc(size);
221     if (dh_gen_key == NULL) {
222         krb5_set_error_string(context, "malloc: out of memory");
223         ret = ENOMEM;
224         goto out;
225     }
226     memset(dh_gen_key, 0, size - dh_gen_keylen);
227
228     dh_gen_keylen = DH_compute_key(dh_gen_key + (size - dh_gen_keylen),
229                                    client_params->dh_public_key,
230                                    client_params->dh);
231     if (dh_gen_keylen == -1) {
232         krb5_set_error_string(context, "Can't compute Diffie-Hellman key");
233         ret = KRB5KRB_ERR_GENERIC;
234         goto out;
235     }
236
237     ret = _krb5_pk_octetstring2key(context,
238                                    enctype,
239                                    dh_gen_key, dh_gen_keylen,
240                                    NULL, NULL,
241                                    reply_key);
242
243  out:
244     if (dh_gen_key)
245         free(dh_gen_key);
246     if (key.keyvalue.data)
247         krb5_free_keyblock_contents(context, &key);
248
249     return ret;
250 }
251
252 static BIGNUM *
253 integer_to_BN(krb5_context context, const char *field, heim_integer *f)
254 {
255     BIGNUM *bn;
256
257     bn = BN_bin2bn((const unsigned char *)f->data, f->length, NULL);
258     if (bn == NULL) {
259         krb5_set_error_string(context, "PKINIT: parsing BN failed %s", field);
260         return NULL;
261     }
262     BN_set_negative(bn, f->negative);
263     return bn;
264 }
265
266 static krb5_error_code
267 get_dh_param(krb5_context context,
268              krb5_kdc_configuration *config,
269              SubjectPublicKeyInfo *dh_key_info,
270              pk_client_params *client_params)
271 {
272     DomainParameters dhparam;
273     DH *dh = NULL;
274     krb5_error_code ret;
275
276     memset(&dhparam, 0, sizeof(dhparam));
277
278     if (der_heim_oid_cmp(&dh_key_info->algorithm.algorithm, oid_id_dhpublicnumber())) {
279         krb5_set_error_string(context,
280                               "PKINIT invalid oid in clientPublicValue");
281         return KRB5_BADMSGTYPE;
282     }
283
284     if (dh_key_info->algorithm.parameters == NULL) {
285         krb5_set_error_string(context, "PKINIT missing algorithm parameter "
286                               "in clientPublicValue");
287         return KRB5_BADMSGTYPE;
288     }
289
290     ret = decode_DomainParameters(dh_key_info->algorithm.parameters->data,
291                                   dh_key_info->algorithm.parameters->length,
292                                   &dhparam,
293                                   NULL);
294     if (ret) {
295         krb5_set_error_string(context, "Can't decode algorithm "
296                               "parameters in clientPublicValue");
297         goto out;
298     }
299
300     if ((dh_key_info->subjectPublicKey.length % 8) != 0) {
301         ret = KRB5_BADMSGTYPE;
302         krb5_set_error_string(context, "PKINIT: subjectPublicKey not aligned "
303                               "to 8 bit boundary");
304         goto out;
305     }
306
307
308     ret = _krb5_dh_group_ok(context, config->pkinit_dh_min_bits, 
309                             &dhparam.p, &dhparam.g, &dhparam.q, moduli,
310                             &client_params->dh_group_name);
311     if (ret) {
312         /* XXX send back proposal of better group */
313         goto out;
314     }
315
316     dh = DH_new();
317     if (dh == NULL) {
318         krb5_set_error_string(context, "Cannot create DH structure");
319         ret = ENOMEM;
320         goto out;
321     }
322     ret = KRB5_BADMSGTYPE;
323     dh->p = integer_to_BN(context, "DH prime", &dhparam.p);
324     if (dh->p == NULL)
325         goto out;
326     dh->g = integer_to_BN(context, "DH base", &dhparam.g);
327     if (dh->g == NULL)
328         goto out;
329     dh->q = integer_to_BN(context, "DH p-1 factor", &dhparam.q);
330     if (dh->g == NULL)
331         goto out;
332
333     {
334         heim_integer glue;
335         size_t size;
336
337         ret = decode_DHPublicKey(dh_key_info->subjectPublicKey.data,
338                                  dh_key_info->subjectPublicKey.length / 8,
339                                  &glue,
340                                  &size);
341         if (ret) {
342             krb5_clear_error_string(context);
343             return ret;
344         }
345
346         client_params->dh_public_key = integer_to_BN(context,
347                                                      "subjectPublicKey",
348                                                      &glue);
349         der_free_heim_integer(&glue);
350         if (client_params->dh_public_key == NULL)
351             goto out;
352     }
353
354     client_params->dh = dh;
355     dh = NULL;
356     ret = 0;
357     
358  out:
359     if (dh)
360         DH_free(dh);
361     free_DomainParameters(&dhparam);
362     return ret;
363 }
364
365 krb5_error_code
366 _kdc_pk_rd_padata(krb5_context context,
367                   krb5_kdc_configuration *config,
368                   const KDC_REQ *req,
369                   const PA_DATA *pa,
370                   pk_client_params **ret_params)
371 {
372     pk_client_params *client_params;
373     krb5_error_code ret;
374     heim_oid eContentType = { 0, NULL }, contentInfoOid = { 0, NULL };
375     krb5_data eContent = { 0, NULL };
376     krb5_data signed_content = { 0, NULL };
377     const char *type = "unknown type";
378     int have_data = 0;
379
380     *ret_params = NULL;
381     
382     if (!config->enable_pkinit) {
383         krb5_clear_error_string(context);
384         return 0;
385     }
386
387     hx509_verify_set_time(kdc_identity->verify_ctx, _kdc_now.tv_sec);
388
389     client_params = calloc(1, sizeof(*client_params));
390     if (client_params == NULL) {
391         krb5_clear_error_string(context);
392         ret = ENOMEM;
393         goto out;
394     }
395
396     if (pa->padata_type == KRB5_PADATA_PK_AS_REQ_WIN) {
397         PA_PK_AS_REQ_Win2k r;
398
399         type = "PK-INIT-Win2k";
400
401         ret = decode_PA_PK_AS_REQ_Win2k(pa->padata_value.data,
402                                         pa->padata_value.length,
403                                         &r,
404                                         NULL);
405         if (ret) {
406             krb5_set_error_string(context, "Can't decode "
407                                   "PK-AS-REQ-Win2k: %d", ret);
408             goto out;
409         }
410         
411         ret = hx509_cms_unwrap_ContentInfo(&r.signed_auth_pack,
412                                            &contentInfoOid,
413                                            &signed_content,
414                                            &have_data);
415         free_PA_PK_AS_REQ_Win2k(&r);
416         if (ret) {
417             krb5_set_error_string(context, "Can't decode PK-AS-REQ: %d", ret);
418             goto out;
419         }
420
421     } else if (pa->padata_type == KRB5_PADATA_PK_AS_REQ) {
422         PA_PK_AS_REQ r;
423
424         type = "PK-INIT-IETF";
425
426         ret = decode_PA_PK_AS_REQ(pa->padata_value.data,
427                                   pa->padata_value.length,
428                                   &r,
429                                   NULL);
430         if (ret) {
431             krb5_set_error_string(context, "Can't decode PK-AS-REQ: %d", ret);
432             goto out;
433         }
434         
435         /* XXX look at r.kdcPkId */
436         if (r.trustedCertifiers) {
437             ExternalPrincipalIdentifiers *edi = r.trustedCertifiers;
438             unsigned int i;
439
440             ret = hx509_certs_init(kdc_identity->hx509ctx,
441                                    "MEMORY:client-anchors",
442                                    0, NULL,
443                                    &client_params->client_anchors);
444             if (ret) {
445                 krb5_set_error_string(context, "Can't allocate client anchors: %d", ret);
446                 goto out;
447
448             }
449             for (i = 0; i < edi->len; i++) {
450                 IssuerAndSerialNumber iasn;
451                 hx509_query *q;
452                 hx509_cert cert;
453                 size_t size;
454
455                 if (edi->val[i].issuerAndSerialNumber == NULL)
456                     continue;
457
458                 ret = hx509_query_alloc(kdc_identity->hx509ctx, &q);
459                 if (ret) {
460                     krb5_set_error_string(context, 
461                                           "Failed to allocate hx509_query");
462                     goto out;
463                 }
464                 
465                 ret = decode_IssuerAndSerialNumber(edi->val[i].issuerAndSerialNumber->data,
466                                                    edi->val[i].issuerAndSerialNumber->length,
467                                                    &iasn,
468                                                    &size);
469                 if (ret) {
470                     hx509_query_free(kdc_identity->hx509ctx, q);
471                     continue;
472                 }
473                 ret = hx509_query_match_issuer_serial(q, &iasn.issuer, &iasn.serialNumber);
474                 free_IssuerAndSerialNumber(&iasn);
475                 if (ret)
476                     continue;
477
478                 ret = hx509_certs_find(kdc_identity->hx509ctx,
479                                        kdc_identity->certs,
480                                        q,
481                                        &cert);
482                 hx509_query_free(kdc_identity->hx509ctx, q);
483                 if (ret)
484                     continue;
485                 hx509_certs_add(kdc_identity->hx509ctx, 
486                                 client_params->client_anchors, cert);
487                 hx509_cert_free(cert);
488             }
489         }
490
491         ret = hx509_cms_unwrap_ContentInfo(&r.signedAuthPack,
492                                            &contentInfoOid,
493                                            &signed_content,
494                                            &have_data);
495         free_PA_PK_AS_REQ(&r);
496         if (ret) {
497             krb5_set_error_string(context, "Can't unwrap ContentInfo: %d", ret);
498             goto out;
499         }
500
501     } else { 
502         krb5_clear_error_string(context);
503         ret = KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
504         goto out;
505     }
506
507     ret = der_heim_oid_cmp(&contentInfoOid, oid_id_pkcs7_signedData());
508     if (ret != 0) {
509         krb5_set_error_string(context, "PK-AS-REQ-Win2k invalid content "
510                               "type oid");
511         ret = KRB5KRB_ERR_GENERIC;
512         goto out;
513     }
514         
515     if (!have_data) {
516         krb5_set_error_string(context,
517                               "PK-AS-REQ-Win2k no signed auth pack");
518         ret = KRB5KRB_ERR_GENERIC;
519         goto out;
520     }
521
522     {
523         hx509_certs signer_certs;
524
525         ret = hx509_cms_verify_signed(kdc_identity->hx509ctx,
526                                       kdc_identity->verify_ctx,
527                                       signed_content.data,
528                                       signed_content.length,
529                                       NULL,
530                                       kdc_identity->certpool,
531                                       &eContentType,
532                                       &eContent,
533                                       &signer_certs);
534         if (ret) {
535             char *s = hx509_get_error_string(kdc_identity->hx509ctx, ret);
536             krb5_warnx(context, "PKINIT: failed to verify signature: %s: %d",
537                        s, ret);
538             free(s);
539             goto out;
540         }
541
542         ret = hx509_get_one_cert(kdc_identity->hx509ctx, signer_certs,
543                                  &client_params->cert);
544         hx509_certs_free(&signer_certs);
545         if (ret)
546             goto out;
547     }
548
549     /* Signature is correct, now verify the signed message */
550     if (der_heim_oid_cmp(&eContentType, oid_id_pkcs7_data()) != 0 &&
551         der_heim_oid_cmp(&eContentType, oid_id_pkauthdata()) != 0)
552     {
553         krb5_set_error_string(context, "got wrong oid for pkauthdata");
554         ret = KRB5_BADMSGTYPE;
555         goto out;
556     }
557
558     if (pa->padata_type == KRB5_PADATA_PK_AS_REQ_WIN) {
559         AuthPack_Win2k ap;
560
561         ret = decode_AuthPack_Win2k(eContent.data,
562                                     eContent.length,
563                                     &ap,
564                                     NULL);
565         if (ret) {
566             krb5_set_error_string(context, "can't decode AuthPack: %d", ret);
567             goto out;
568         }
569   
570         ret = pk_check_pkauthenticator_win2k(context, 
571                                              &ap.pkAuthenticator,
572                                              req);
573         if (ret) {
574             free_AuthPack_Win2k(&ap);
575             goto out;
576         }
577
578         client_params->type = PKINIT_COMPAT_WIN2K;
579         client_params->nonce = ap.pkAuthenticator.nonce;
580
581         if (ap.clientPublicValue) {
582             krb5_set_error_string(context, "DH not supported for windows");
583             ret = KRB5KRB_ERR_GENERIC;
584             goto out;
585         }
586         free_AuthPack_Win2k(&ap);
587
588     } else if (pa->padata_type == KRB5_PADATA_PK_AS_REQ) {
589         AuthPack ap;
590
591         ret = decode_AuthPack(eContent.data,
592                               eContent.length,
593                               &ap,
594                               NULL);
595         if (ret) {
596             krb5_set_error_string(context, "can't decode AuthPack: %d", ret);
597             free_AuthPack(&ap);
598             goto out;
599         }
600   
601         ret = pk_check_pkauthenticator(context, 
602                                        &ap.pkAuthenticator,
603                                        req);
604         if (ret) {
605             free_AuthPack(&ap);
606             goto out;
607         }
608
609         client_params->type = PKINIT_COMPAT_27;
610         client_params->nonce = ap.pkAuthenticator.nonce;
611
612         if (ap.clientPublicValue) {
613             ret = get_dh_param(context, config, 
614                                ap.clientPublicValue, client_params);
615             if (ret) {
616                 free_AuthPack(&ap);
617                 goto out;
618             }
619         }
620
621         if (ap.supportedCMSTypes) {
622             ret = hx509_peer_info_alloc(kdc_identity->hx509ctx,
623                                         &client_params->peer);
624             if (ret) {
625                 free_AuthPack(&ap);
626                 goto out;
627             }
628             ret = hx509_peer_info_set_cms_algs(kdc_identity->hx509ctx,
629                                                client_params->peer,
630                                                ap.supportedCMSTypes->val,
631                                                ap.supportedCMSTypes->len);
632             if (ret) {
633                 free_AuthPack(&ap);
634                 goto out;
635             }
636         }
637         free_AuthPack(&ap);
638     } else
639         krb5_abortx(context, "internal pkinit error");
640
641     kdc_log(context, config, 0, "PK-INIT request of type %s", type);
642
643 out:
644     if (ret)
645         krb5_warn(context, ret, "PKINIT");
646
647     if (signed_content.data)
648         free(signed_content.data);
649     krb5_data_free(&eContent);
650     der_free_oid(&eContentType);
651     der_free_oid(&contentInfoOid);
652     if (ret)
653         _kdc_pk_free_client_param(context, client_params);
654     else
655         *ret_params = client_params;
656     return ret;
657 }
658
659 /*
660  *
661  */
662
663 static krb5_error_code
664 BN_to_integer(krb5_context context, BIGNUM *bn, heim_integer *integer)
665 {
666     integer->length = BN_num_bytes(bn);
667     integer->data = malloc(integer->length);
668     if (integer->data == NULL) {
669         krb5_clear_error_string(context);
670         return ENOMEM;
671     }
672     BN_bn2bin(bn, integer->data);
673     integer->negative = BN_is_negative(bn);
674     return 0;
675 }
676
677 static krb5_error_code
678 pk_mk_pa_reply_enckey(krb5_context context,
679                       pk_client_params *client_params,
680                       const KDC_REQ *req,
681                       const krb5_data *req_buffer,
682                       krb5_keyblock *reply_key,
683                       ContentInfo *content_info)
684 {
685     const heim_oid *envelopedAlg = NULL, *sdAlg = NULL;
686     krb5_error_code ret;
687     krb5_data buf, signed_data;
688     size_t size;
689     int do_win2k = 0;
690
691     krb5_data_zero(&buf);
692     krb5_data_zero(&signed_data);
693
694     /*
695      * If the message client is a win2k-type but it send pa data
696      * 09-binding it expects a IETF (checksum) reply so there can be
697      * no replay attacks.
698      */
699
700     switch (client_params->type) {
701     case PKINIT_COMPAT_WIN2K: {
702         int i = 0;
703         if (_kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_09_BINDING) == NULL)
704             do_win2k = 1;
705         break;
706     }
707     case PKINIT_COMPAT_27:
708         break;
709     default:
710         krb5_abortx(context, "internal pkinit error");
711     }       
712
713     if (do_win2k) {
714         ReplyKeyPack_Win2k kp;
715         memset(&kp, 0, sizeof(kp));
716
717         envelopedAlg = oid_id_rsadsi_des_ede3_cbc();
718         sdAlg = oid_id_pkcs7_data();
719
720         ret = copy_EncryptionKey(reply_key, &kp.replyKey);
721         if (ret) {
722             krb5_clear_error_string(context);
723             goto out;
724         }
725         kp.nonce = client_params->nonce;
726         
727         ASN1_MALLOC_ENCODE(ReplyKeyPack_Win2k, 
728                            buf.data, buf.length,
729                            &kp, &size,ret);
730         free_ReplyKeyPack_Win2k(&kp);
731     } else {
732         krb5_crypto ascrypto;
733         ReplyKeyPack kp;
734         memset(&kp, 0, sizeof(kp));
735
736         sdAlg = oid_id_pkrkeydata();
737
738         ret = copy_EncryptionKey(reply_key, &kp.replyKey);
739         if (ret) {
740             krb5_clear_error_string(context);
741             goto out;
742         }
743
744         ret = krb5_crypto_init(context, reply_key, 0, &ascrypto);
745         if (ret) {
746             krb5_clear_error_string(context);
747             goto out;
748         }
749
750         ret = krb5_create_checksum(context, ascrypto, 6, 0,
751                                    req_buffer->data, req_buffer->length,
752                                    &kp.asChecksum);
753         if (ret) {
754             krb5_clear_error_string(context);
755             goto out;
756         }
757                              
758         ret = krb5_crypto_destroy(context, ascrypto);
759         if (ret) {
760             krb5_clear_error_string(context);
761             goto out;
762         }
763         ASN1_MALLOC_ENCODE(ReplyKeyPack, buf.data, buf.length, &kp, &size,ret);
764         free_ReplyKeyPack(&kp);
765     }
766     if (ret) {
767         krb5_set_error_string(context, "ASN.1 encoding of ReplyKeyPack "
768                               "failed (%d)", ret);
769         goto out;
770     }
771     if (buf.length != size)
772         krb5_abortx(context, "Internal ASN.1 encoder error");
773
774     {
775         hx509_query *q;
776         hx509_cert cert;
777         
778         ret = hx509_query_alloc(kdc_identity->hx509ctx, &q);
779         if (ret)
780             goto out;
781         
782         hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
783         hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
784         
785         ret = hx509_certs_find(kdc_identity->hx509ctx, 
786                                kdc_identity->certs, 
787                                q, 
788                                &cert);
789         hx509_query_free(kdc_identity->hx509ctx, q);
790         if (ret)
791             goto out;
792         
793         ret = hx509_cms_create_signed_1(kdc_identity->hx509ctx,
794                                         0,
795                                         sdAlg,
796                                         buf.data,
797                                         buf.length,
798                                         NULL,
799                                         cert,
800                                         client_params->peer,
801                                         client_params->client_anchors,
802                                         kdc_identity->certpool,
803                                         &signed_data);
804         hx509_cert_free(cert);
805     }
806
807     krb5_data_free(&buf);
808     if (ret) 
809         goto out;
810
811     if (client_params->type == PKINIT_COMPAT_WIN2K) {
812         ret = hx509_cms_wrap_ContentInfo(oid_id_pkcs7_signedData(),
813                                          &signed_data,
814                                          &buf);
815         if (ret)
816             goto out;
817         krb5_data_free(&signed_data);
818         signed_data = buf;
819     }
820
821     ret = hx509_cms_envelope_1(kdc_identity->hx509ctx,
822                                0,
823                                client_params->cert,
824                                signed_data.data, signed_data.length, 
825                                envelopedAlg,
826                                oid_id_pkcs7_signedData(), &buf);
827     if (ret)
828         goto out;
829     
830     ret = _krb5_pk_mk_ContentInfo(context,
831                                   &buf,
832                                   oid_id_pkcs7_envelopedData(),
833                                   content_info);
834 out:
835     krb5_data_free(&buf);
836     krb5_data_free(&signed_data);
837     return ret;
838 }
839
840 /*
841  *
842  */
843
844 static krb5_error_code
845 pk_mk_pa_reply_dh(krb5_context context,
846                   DH *kdc_dh,
847                   pk_client_params *client_params,
848                   krb5_keyblock *reply_key,
849                   ContentInfo *content_info,
850                   hx509_cert *kdc_cert)
851 {
852     KDCDHKeyInfo dh_info;
853     krb5_data signed_data, buf;
854     ContentInfo contentinfo;
855     krb5_error_code ret;
856     size_t size;
857     heim_integer i;
858
859     memset(&contentinfo, 0, sizeof(contentinfo));
860     memset(&dh_info, 0, sizeof(dh_info));
861     krb5_data_zero(&buf);
862     krb5_data_zero(&signed_data);
863
864     *kdc_cert = NULL;
865
866     ret = BN_to_integer(context, kdc_dh->pub_key, &i);
867     if (ret)
868         return ret;
869
870     ASN1_MALLOC_ENCODE(DHPublicKey, buf.data, buf.length, &i, &size, ret);
871     if (ret) {
872         krb5_set_error_string(context, "ASN.1 encoding of "
873                               "DHPublicKey failed (%d)", ret);
874         krb5_clear_error_string(context);
875         return ret;
876     }
877     if (buf.length != size)
878         krb5_abortx(context, "Internal ASN.1 encoder error");
879
880     dh_info.subjectPublicKey.length = buf.length * 8;
881     dh_info.subjectPublicKey.data = buf.data;
882     
883     dh_info.nonce = client_params->nonce;
884
885     ASN1_MALLOC_ENCODE(KDCDHKeyInfo, buf.data, buf.length, &dh_info, &size, 
886                        ret);
887     if (ret) {
888         krb5_set_error_string(context, "ASN.1 encoding of "
889                               "KdcDHKeyInfo failed (%d)", ret);
890         goto out;
891     }
892     if (buf.length != size)
893         krb5_abortx(context, "Internal ASN.1 encoder error");
894
895     /* 
896      * Create the SignedData structure and sign the KdcDHKeyInfo
897      * filled in above
898      */
899
900     {
901         hx509_query *q;
902         hx509_cert cert;
903         
904         ret = hx509_query_alloc(kdc_identity->hx509ctx, &q);
905         if (ret)
906             goto out;
907         
908         hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
909         hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
910         
911         ret = hx509_certs_find(kdc_identity->hx509ctx, 
912                                kdc_identity->certs, 
913                                q, 
914                                &cert);
915         hx509_query_free(kdc_identity->hx509ctx, q);
916         if (ret)
917             goto out;
918         
919         ret = hx509_cms_create_signed_1(kdc_identity->hx509ctx,
920                                         0,
921                                         oid_id_pkdhkeydata(),
922                                         buf.data,
923                                         buf.length,
924                                         NULL,
925                                         cert,
926                                         client_params->peer,
927                                         client_params->client_anchors,
928                                         kdc_identity->certpool,
929                                         &signed_data);
930         *kdc_cert = cert;
931     }
932     if (ret)
933         goto out;
934
935     ret = _krb5_pk_mk_ContentInfo(context,
936                                   &signed_data,
937                                   oid_id_pkcs7_signedData(),
938                                   content_info);
939     if (ret)
940         goto out;
941
942  out:
943     if (ret && *kdc_cert) {
944         hx509_cert_free(*kdc_cert);
945         *kdc_cert = NULL;
946     }
947
948     krb5_data_free(&buf);
949     krb5_data_free(&signed_data);
950     free_KDCDHKeyInfo(&dh_info);
951
952     return ret;
953 }
954
955 /*
956  *
957  */
958
959 krb5_error_code
960 _kdc_pk_mk_pa_reply(krb5_context context,
961                     krb5_kdc_configuration *config,
962                     pk_client_params *client_params,
963                     const hdb_entry_ex *client,
964                     const KDC_REQ *req,
965                     const krb5_data *req_buffer,
966                     krb5_keyblock **reply_key,
967                     METHOD_DATA *md)
968 {
969     krb5_error_code ret;
970     void *buf;
971     size_t len, size;
972     krb5_enctype enctype;
973     int pa_type;
974     hx509_cert kdc_cert = NULL;
975     int i;
976
977     if (!config->enable_pkinit) {
978         krb5_clear_error_string(context);
979         return 0;
980     }
981
982     if (req->req_body.etype.len > 0) {
983         for (i = 0; i < req->req_body.etype.len; i++)
984             if (krb5_enctype_valid(context, req->req_body.etype.val[i]) == 0)
985                 break;
986         if (req->req_body.etype.len <= i) {
987             ret = KRB5KRB_ERR_GENERIC;
988             krb5_set_error_string(context,
989                                   "No valid enctype available from client");
990             goto out;
991         }       
992         enctype = req->req_body.etype.val[i];
993     } else
994         enctype = ETYPE_DES3_CBC_SHA1;
995
996     if (client_params->type == PKINIT_COMPAT_27) {
997         PA_PK_AS_REP rep;
998         const char *type, *other = "";
999
1000         memset(&rep, 0, sizeof(rep));
1001
1002         pa_type = KRB5_PADATA_PK_AS_REP;
1003
1004         if (client_params->dh == NULL) {
1005             ContentInfo info;
1006
1007             type = "enckey";
1008
1009             rep.element = choice_PA_PK_AS_REP_encKeyPack;
1010
1011             ret = krb5_generate_random_keyblock(context, enctype, 
1012                                                 &client_params->reply_key);
1013             if (ret) {
1014                 free_PA_PK_AS_REP(&rep);
1015                 goto out;
1016             }
1017             ret = pk_mk_pa_reply_enckey(context,
1018                                         client_params,
1019                                         req,
1020                                         req_buffer,
1021                                         &client_params->reply_key,
1022                                         &info);
1023             if (ret) {
1024                 free_PA_PK_AS_REP(&rep);
1025                 goto out;
1026             }
1027             ASN1_MALLOC_ENCODE(ContentInfo, rep.u.encKeyPack.data, 
1028                                rep.u.encKeyPack.length, &info, &size, 
1029                                ret);
1030             free_ContentInfo(&info);
1031             if (ret) {
1032                 krb5_set_error_string(context, "encoding of Key ContentInfo "
1033                                       "failed %d", ret);
1034                 free_PA_PK_AS_REP(&rep);
1035                 goto out;
1036             }
1037             if (rep.u.encKeyPack.length != size)
1038                 krb5_abortx(context, "Internal ASN.1 encoder error");
1039
1040         } else {
1041             ContentInfo info;
1042
1043             type = "dh";
1044             if (client_params->dh_group_name)
1045                 other = client_params->dh_group_name;
1046
1047             rep.element = choice_PA_PK_AS_REP_dhInfo;
1048
1049             ret = generate_dh_keyblock(context, client_params, enctype,
1050                                        &client_params->reply_key);
1051             if (ret)
1052                 return ret;
1053
1054             ret = pk_mk_pa_reply_dh(context, client_params->dh,
1055                                     client_params, 
1056                                     &client_params->reply_key,
1057                                     &info,
1058                                     &kdc_cert);
1059
1060             ASN1_MALLOC_ENCODE(ContentInfo, rep.u.dhInfo.dhSignedData.data,
1061                                rep.u.dhInfo.dhSignedData.length, &info, &size,
1062                                ret);
1063             free_ContentInfo(&info);
1064             if (ret) {
1065                 krb5_set_error_string(context, "encoding of Key ContentInfo "
1066                                       "failed %d", ret);
1067                 free_PA_PK_AS_REP(&rep);
1068                 goto out;
1069             }
1070             if (rep.u.encKeyPack.length != size)
1071                 krb5_abortx(context, "Internal ASN.1 encoder error");
1072
1073         }
1074         if (ret) {
1075             free_PA_PK_AS_REP(&rep);
1076             goto out;
1077         }
1078
1079         ASN1_MALLOC_ENCODE(PA_PK_AS_REP, buf, len, &rep, &size, ret);
1080         free_PA_PK_AS_REP(&rep);
1081         if (ret) {
1082             krb5_set_error_string(context, "encode PA-PK-AS-REP failed %d",
1083                                   ret);
1084             goto out;
1085         }
1086         if (len != size)
1087             krb5_abortx(context, "Internal ASN.1 encoder error");
1088
1089         kdc_log(context, config, 0, "PK-INIT using %s %s", type, other);
1090
1091     } else if (client_params->type == PKINIT_COMPAT_WIN2K) {
1092         PA_PK_AS_REP_Win2k rep;
1093         ContentInfo info;
1094
1095         if (client_params->dh) {
1096             krb5_set_error_string(context, "Windows PK-INIT doesn't support DH");
1097             ret = KRB5KRB_ERR_GENERIC;
1098             goto out;
1099         }
1100
1101         memset(&rep, 0, sizeof(rep));
1102
1103         pa_type = KRB5_PADATA_PK_AS_REP_19;
1104         rep.element = choice_PA_PK_AS_REP_encKeyPack;
1105
1106         ret = krb5_generate_random_keyblock(context, enctype, 
1107                                             &client_params->reply_key);
1108         if (ret) {
1109             free_PA_PK_AS_REP_Win2k(&rep);
1110             goto out;
1111         }
1112         ret = pk_mk_pa_reply_enckey(context,
1113                                     client_params,
1114                                     req,
1115                                     req_buffer,
1116                                     &client_params->reply_key,
1117                                     &info);
1118         if (ret) {
1119             free_PA_PK_AS_REP_Win2k(&rep);
1120             goto out;
1121         }
1122         ASN1_MALLOC_ENCODE(ContentInfo, rep.u.encKeyPack.data, 
1123                            rep.u.encKeyPack.length, &info, &size, 
1124                            ret);
1125         free_ContentInfo(&info);
1126         if (ret) {
1127             krb5_set_error_string(context, "encoding of Key ContentInfo "
1128                                   "failed %d", ret);
1129             free_PA_PK_AS_REP_Win2k(&rep);
1130             goto out;
1131         }
1132         if (rep.u.encKeyPack.length != size)
1133             krb5_abortx(context, "Internal ASN.1 encoder error");
1134
1135         ASN1_MALLOC_ENCODE(PA_PK_AS_REP_Win2k, buf, len, &rep, &size, ret);
1136         free_PA_PK_AS_REP_Win2k(&rep);
1137         if (ret) {
1138             krb5_set_error_string(context, 
1139                                   "encode PA-PK-AS-REP-Win2k failed %d", ret);
1140             goto out;
1141         }
1142         if (len != size)
1143             krb5_abortx(context, "Internal ASN.1 encoder error");
1144
1145     } else
1146         krb5_abortx(context, "PK-INIT internal error");
1147
1148
1149     ret = krb5_padata_add(context, md, pa_type, buf, len);
1150     if (ret) {
1151         krb5_set_error_string(context, "failed adding PA-PK-AS-REP %d", ret);
1152         free(buf);
1153         goto out;
1154     }
1155
1156     if (config->pkinit_kdc_ocsp_file) {
1157
1158         if (ocsp.expire == 0 && ocsp.next_update > kdc_time) {
1159             struct stat sb;
1160             int fd;
1161
1162             krb5_data_free(&ocsp.data);
1163
1164             ocsp.expire = 0;
1165             ocsp.next_update = kdc_time + 60 * 5;
1166
1167             fd = open(config->pkinit_kdc_ocsp_file, O_RDONLY);
1168             if (fd < 0) {
1169                 kdc_log(context, config, 0, 
1170                         "PK-INIT failed to open ocsp data file %d", errno);
1171                 goto out_ocsp;
1172             }
1173             ret = fstat(fd, &sb);
1174             if (ret) {
1175                 ret = errno;
1176                 close(fd);
1177                 kdc_log(context, config, 0, 
1178                         "PK-INIT failed to stat ocsp data %d", ret);
1179                 goto out_ocsp;
1180             }
1181             
1182             ret = krb5_data_alloc(&ocsp.data, sb.st_size);
1183             if (ret) {
1184                 close(fd);
1185                 kdc_log(context, config, 0, 
1186                         "PK-INIT failed to stat ocsp data %d", ret);
1187                 goto out_ocsp;
1188             }
1189             ocsp.data.length = sb.st_size;
1190             ret = read(fd, ocsp.data.data, sb.st_size);
1191             close(fd);
1192             if (ret != sb.st_size) {
1193                 kdc_log(context, config, 0, 
1194                         "PK-INIT failed to read ocsp data %d", errno);
1195                 goto out_ocsp;
1196             }
1197
1198             ret = hx509_ocsp_verify(kdc_identity->hx509ctx,
1199                                     kdc_time,
1200                                     kdc_cert,
1201                                     0,
1202                                     ocsp.data.data, ocsp.data.length,
1203                                     &ocsp.expire);
1204             if (ret) {
1205                 kdc_log(context, config, 0, 
1206                         "PK-INIT failed to verify ocsp data %d", ret);
1207                 krb5_data_free(&ocsp.data);
1208                 ocsp.expire = 0;
1209             } else if (ocsp.expire > 180) {
1210                 ocsp.expire -= 180; /* refetch the ocsp before it expire */
1211                 ocsp.next_update = ocsp.expire;
1212             } else {
1213                 ocsp.next_update = kdc_time;
1214             }
1215         out_ocsp:
1216             ret = 0;
1217         }
1218
1219         if (ocsp.expire != 0 && ocsp.expire > kdc_time) {
1220
1221             ret = krb5_padata_add(context, md, 
1222                                   KRB5_PADATA_PA_PK_OCSP_RESPONSE,
1223                                   ocsp.data.data, ocsp.data.length);
1224             if (ret) {
1225                 krb5_set_error_string(context, 
1226                                       "Failed adding OCSP response %d", ret);
1227                 goto out;
1228             }
1229         }
1230     }
1231
1232 out:
1233     if (kdc_cert)
1234         hx509_cert_free(kdc_cert);
1235
1236     if (ret == 0)
1237         *reply_key = &client_params->reply_key;
1238     return ret;
1239 }
1240
1241 static int
1242 match_rfc_san(krb5_context context, 
1243               krb5_kdc_configuration *config,
1244               hx509_cert client_cert, 
1245               krb5_const_principal match)
1246 {
1247     hx509_octet_string_list list;
1248     int ret, i, found = 0;
1249
1250     memset(&list, 0 , sizeof(list));
1251
1252     ret = hx509_cert_find_subjectAltName_otherName(client_cert,
1253                                                    oid_id_pkinit_san(),
1254                                                    &list);
1255     if (ret)
1256         goto out;
1257
1258     for (i = 0; !found && i < list.len; i++) {
1259         krb5_principal_data principal;
1260         KRB5PrincipalName kn;
1261         size_t size;
1262
1263         ret = decode_KRB5PrincipalName(list.val[i].data, 
1264                                        list.val[i].length,
1265                                        &kn, &size);
1266         if (ret) {
1267             kdc_log(context, config, 0,
1268                     "Decoding kerberos name in certificate failed: %s",
1269                     krb5_get_err_text(context, ret));
1270             break;
1271         }
1272         if (size != list.val[i].length) {
1273             kdc_log(context, config, 0,
1274                     "Decoding kerberos name have extra bits on the end");
1275             return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1276         }
1277
1278         principal.name = kn.principalName;
1279         principal.realm = kn.realm;
1280
1281         if (krb5_principal_compare(context, &principal, match) == TRUE)
1282             found = 1;
1283         free_KRB5PrincipalName(&kn);
1284     }
1285
1286 out:
1287     hx509_free_octet_string_list(&list);    
1288     if (ret)
1289         return ret;
1290
1291     if (!found)
1292         return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1293
1294     return 0;
1295 }
1296
1297 static int
1298 match_ms_upn_san(krb5_context context, 
1299                  krb5_kdc_configuration *config,
1300                  hx509_cert client_cert, 
1301                  krb5_const_principal match)
1302 {
1303     hx509_octet_string_list list;
1304     krb5_principal principal = NULL;
1305     int ret, found = 0;
1306     MS_UPN_SAN upn;
1307     size_t size;
1308
1309     memset(&list, 0 , sizeof(list));
1310
1311     ret = hx509_cert_find_subjectAltName_otherName(client_cert,
1312                                                    oid_id_pkinit_ms_san(),
1313                                                    &list);
1314     if (ret)
1315         goto out;
1316
1317     if (list.len != 1) {
1318         kdc_log(context, config, 0,
1319                 "More then one PK-INIT MS UPN SAN");
1320         goto out;
1321     }
1322
1323     ret = decode_MS_UPN_SAN(list.val[0].data, list.val[0].length, &upn, &size);
1324     if (ret) {
1325         kdc_log(context, config, 0, "Decode of MS-UPN-SAN failed");
1326         goto out;
1327     }
1328
1329     kdc_log(context, config, 0, "found MS UPN SAN: %s", upn);
1330
1331     ret = krb5_parse_name(context, upn, &principal);
1332     free_MS_UPN_SAN(&upn);
1333     if (ret) {
1334         kdc_log(context, config, 0, "Failed to parse principal in MS UPN SAN");
1335         goto out;
1336     }
1337
1338     /* 
1339      * This is very wrong, but will do for now, should really and a
1340      * plugin to the windc layer to very this ACL.
1341     */
1342     strupr(principal->realm);
1343
1344     if (krb5_principal_compare(context, principal, match) == TRUE)
1345         found = 1;
1346
1347 out:
1348     if (principal)
1349         krb5_free_principal(context, principal);
1350     hx509_free_octet_string_list(&list);    
1351     if (ret)
1352         return ret;
1353
1354     if (!found)
1355         return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1356
1357     return 0;
1358 }
1359
1360 krb5_error_code
1361 _kdc_pk_check_client(krb5_context context,
1362                      krb5_kdc_configuration *config,
1363                      const hdb_entry_ex *client,
1364                      pk_client_params *client_params,
1365                      char **subject_name)
1366 {
1367     const HDB_Ext_PKINIT_acl *acl;
1368     krb5_error_code ret;
1369     hx509_name name;
1370     int i;
1371
1372     ret = hx509_cert_get_base_subject(kdc_identity->hx509ctx, 
1373                                       client_params->cert,
1374                                       &name);
1375     if (ret)
1376         return ret;
1377
1378     ret = hx509_name_to_string(name, subject_name);
1379     hx509_name_free(&name);
1380     if (ret)
1381         return ret;
1382
1383     kdc_log(context, config, 0,
1384             "Trying to authorize PK-INIT subject DN %s", 
1385             *subject_name);
1386
1387     if (config->enable_pkinit_princ_in_cert) {
1388         ret = match_rfc_san(context, config,
1389                             client_params->cert,
1390                             client->entry.principal);
1391         if (ret == 0) {
1392             kdc_log(context, config, 5,
1393                     "Found matching PK-INIT SAN in certificate");
1394             return 0;
1395         }
1396         ret = match_ms_upn_san(context, config,
1397                                client_params->cert,
1398                                client->entry.principal);
1399         if (ret == 0) {
1400             kdc_log(context, config, 5,
1401                     "Found matching MS UPN SAN in certificate");
1402             return 0;
1403         }
1404     }
1405
1406     ret = hdb_entry_get_pkinit_acl(&client->entry, &acl);
1407     if (ret == 0 && acl != NULL) {
1408         /*
1409          * Cheat here and compare the generated name with the string
1410          * and not the reverse.
1411          */
1412         for (i = 0; i < acl->len; i++) {
1413             if (strcmp(*subject_name, acl->val[0].subject) != 0)
1414                 continue;
1415
1416             /* Don't support isser and anchor checking right now */
1417             if (acl->val[0].issuer)
1418                 continue;
1419             if (acl->val[0].anchor)
1420                 continue;
1421
1422             kdc_log(context, config, 5,
1423                     "Found matching PK-INIT database ACL");
1424             return 0;
1425         }
1426     }
1427
1428     for (i = 0; i < principal_mappings.len; i++) {
1429         krb5_boolean b;
1430
1431         b = krb5_principal_compare(context,
1432                                    client->entry.principal,
1433                                    principal_mappings.val[i].principal);
1434         if (b == FALSE)
1435             continue;
1436         if (strcmp(principal_mappings.val[i].subject, *subject_name) != 0)
1437             continue;
1438         kdc_log(context, config, 5,
1439                 "Found matching PK-INIT FILE ACL");
1440         return 0;
1441     }
1442
1443     krb5_set_error_string(context,
1444                           "PKINIT no matching principals for %s",
1445                           *subject_name);
1446
1447     kdc_log(context, config, 5,
1448             "PKINIT no matching principals for %s",
1449             *subject_name);
1450
1451     free(*subject_name);
1452     *subject_name = NULL;
1453
1454     return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1455 }
1456
1457 static krb5_error_code
1458 add_principal_mapping(krb5_context context, 
1459                       const char *principal_name,
1460                       const char * subject)
1461 {
1462    struct pk_allowed_princ *tmp;
1463    krb5_principal principal;
1464    krb5_error_code ret;
1465
1466    tmp = realloc(principal_mappings.val,
1467                  (principal_mappings.len + 1) * sizeof(*tmp));
1468    if (tmp == NULL)
1469        return ENOMEM;
1470    principal_mappings.val = tmp;
1471
1472    ret = krb5_parse_name(context, principal_name, &principal);
1473    if (ret)
1474        return ret;
1475
1476    principal_mappings.val[principal_mappings.len].principal = principal;
1477
1478    principal_mappings.val[principal_mappings.len].subject = strdup(subject);
1479    if (principal_mappings.val[principal_mappings.len].subject == NULL) {
1480        krb5_free_principal(context, principal);
1481        return ENOMEM;
1482    }
1483    principal_mappings.len++;
1484
1485    return 0;
1486 }
1487
1488 krb5_error_code
1489 _kdc_add_inital_verified_cas(krb5_context context,
1490                              krb5_kdc_configuration *config,
1491                              pk_client_params *params,
1492                              EncTicketPart *tkt)
1493 {
1494     AD_INITIAL_VERIFIED_CAS cas;
1495     krb5_error_code ret;
1496     krb5_data data;
1497     size_t size;
1498
1499     memset(&cas, 0, sizeof(cas));
1500     
1501     /* XXX add CAs to cas here */
1502
1503     ASN1_MALLOC_ENCODE(AD_INITIAL_VERIFIED_CAS, data.data, data.length,
1504                        &cas, &size, ret);
1505     if (ret)
1506         return ret;
1507     if (data.length != size)
1508         krb5_abortx(context, "internal asn.1 encoder error");
1509
1510     ret = _kdc_tkt_add_if_relevant_ad(context, tkt, 
1511                                       ad_initial_verified_cas, &data);
1512     krb5_data_free(&data);
1513     return ret;
1514 }
1515
1516 /*
1517  *
1518  */
1519
1520 static void
1521 load_mappings(krb5_context context, const char *fn)
1522 {
1523     krb5_error_code ret;
1524     char buf[1024];
1525     unsigned long lineno = 0;
1526     FILE *f;
1527
1528     f = fopen(fn, "r");
1529     if (f == NULL)
1530         return;
1531
1532     while (fgets(buf, sizeof(buf), f) != NULL) {
1533         char *subject_name, *p;
1534     
1535         buf[strcspn(buf, "\n")] = '\0';
1536         lineno++;
1537
1538         p = buf + strspn(buf, " \t");
1539
1540         if (*p == '#' || *p == '\0')
1541             continue;
1542
1543         subject_name = strchr(p, ':');
1544         if (subject_name == NULL) {
1545             krb5_warnx(context, "pkinit mapping file line %lu "
1546                        "missing \":\" :%s",
1547                        lineno, buf);
1548             continue;
1549         }
1550         *subject_name++ = '\0';
1551
1552         ret = add_principal_mapping(context, p, subject_name);
1553         if (ret) {
1554             krb5_warn(context, ret, "failed to add line %lu \":\" :%s\n",
1555                       lineno, buf);
1556             continue;
1557         }
1558     } 
1559
1560     fclose(f);
1561 }
1562                    
1563 /*
1564  *
1565  */
1566
1567 krb5_error_code
1568 _kdc_pk_initialize(krb5_context context,
1569                    krb5_kdc_configuration *config,
1570                    const char *user_id,
1571                    const char *anchors,
1572                    char **pool,
1573                    char **revoke_list)
1574 {
1575     const char *file; 
1576     krb5_error_code ret;
1577
1578     file = krb5_config_get_string(context, NULL,
1579                                   "libdefaults", "moduli", NULL);
1580
1581     ret = _krb5_parse_moduli(context, file, &moduli);
1582     if (ret)
1583         krb5_err(context, 1, ret, "PKINIT: failed to load modidi file");
1584
1585     principal_mappings.len = 0;
1586     principal_mappings.val = NULL;
1587
1588     ret = _krb5_pk_load_id(context,
1589                            &kdc_identity,
1590                            user_id,
1591                            anchors,
1592                            pool,
1593                            revoke_list,
1594                            NULL,
1595                            NULL,
1596                            NULL);
1597     if (ret) {
1598         krb5_warn(context, ret, "PKINIT: ");
1599         config->enable_pkinit = 0;
1600         return ret;
1601     }
1602
1603     {
1604         hx509_query *q;
1605         hx509_cert cert;
1606         
1607         ret = hx509_query_alloc(kdc_identity->hx509ctx, &q);
1608         if (ret) {
1609             krb5_warnx(context, "PKINIT: out of memory");
1610             return ENOMEM;
1611         }
1612         
1613         hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
1614         hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
1615         
1616         ret = hx509_certs_find(kdc_identity->hx509ctx,
1617                                kdc_identity->certs,
1618                                q,
1619                                &cert);
1620         hx509_query_free(kdc_identity->hx509ctx, q);
1621         if (ret == 0) {
1622             if (hx509_cert_check_eku(kdc_identity->hx509ctx, cert,
1623                                      oid_id_pkkdcekuoid(), 0))
1624                 krb5_warnx(context, "WARNING Found KDC certificate "
1625                            "is missing the PK-INIT KDC EKU, this is bad for "
1626                            "interoperability.");
1627             hx509_cert_free(cert);
1628         } else
1629             krb5_warnx(context, "PKINIT: failed to find a signing "
1630                        "certifiate with a public key");
1631     }
1632
1633     ret = krb5_config_get_bool_default(context, 
1634                                        NULL,
1635                                        FALSE,
1636                                        "kdc",
1637                                        "pkinit_allow_proxy_certificate",
1638                                        NULL);
1639     _krb5_pk_allow_proxy_certificate(kdc_identity, ret);
1640
1641     file = krb5_config_get_string_default(context, 
1642                                           NULL,
1643                                           HDB_DB_DIR "/pki-mapping",
1644                                           "kdc",
1645                                           "pkinit_mappings_file",
1646                                           NULL);
1647
1648     load_mappings(context, file);
1649
1650     return 0;
1651 }
1652
1653 #endif /* PKINIT */