6ba3f7ab3ffa0d92505444889c51d329348323fe
[openssl.git] / crypto / crmf / crmf_lib.c
1 /*-
2  * Copyright 2007-2019 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright Nokia 2007-2018
4  * Copyright Siemens AG 2015-2019
5  *
6  * Licensed under the Apache License 2.0 (the "License").  You may not use
7  * this file except in compliance with the License.  You can obtain a copy
8  * in the file LICENSE in the source distribution or at
9  * https://www.openssl.org/source/license.html
10  *
11  * CRMF implementation by Martin Peylo, Miikka Viljanen, and David von Oheimb.
12  */
13
14 /*
15  * This file contains the functions that handle the individual items inside
16  * the CRMF structures
17  */
18
19 /*
20  * NAMING
21  *
22  * The 0 functions use the supplied structure pointer directly in the parent and
23  * it will be freed up when the parent is freed.
24  *
25  * The 1 functions use a copy of the supplied structure pointer (or in some
26  * cases increases its link count) in the parent and so both should be freed up.
27  */
28
29 #include <openssl/asn1t.h>
30
31 #include "crmf_local.h"
32 #include "internal/constant_time.h"
33
34 /* explicit #includes not strictly needed since implied by the above: */
35 #include <openssl/crmf.h>
36 #include <openssl/err.h>
37 #include <openssl/evp.h>
38
39 /*-
40  * atyp = Attribute Type
41  * valt = Value Type
42  * ctrlinf = "regCtrl" or "regInfo"
43  */
44 #define IMPLEMENT_CRMF_CTRL_FUNC(atyp, valt, ctrlinf)                     \
45 int OSSL_CRMF_MSG_set1_##ctrlinf##_##atyp(OSSL_CRMF_MSG *msg,             \
46                                           const valt *in)                 \
47 {                                                                         \
48     OSSL_CRMF_ATTRIBUTETYPEANDVALUE *atav = NULL;                         \
49                                                                           \
50     if (msg == NULL || in  == NULL)                                       \
51         goto err;                                                         \
52     if ((atav = OSSL_CRMF_ATTRIBUTETYPEANDVALUE_new()) == NULL)           \
53         goto err;                                                         \
54     if ((atav->type = OBJ_nid2obj(NID_id_##ctrlinf##_##atyp)) == NULL)    \
55         goto err;                                                         \
56     if ((atav->value.atyp = valt##_dup(in)) == NULL)                      \
57         goto err;                                                         \
58     if (!OSSL_CRMF_MSG_push0_##ctrlinf(msg, atav))                        \
59         goto err;                                                         \
60     return 1;                                                             \
61  err:                                                                     \
62     OSSL_CRMF_ATTRIBUTETYPEANDVALUE_free(atav);                           \
63     return 0;                                                             \
64 }
65
66
67 /*-
68  * Pushes the given control attribute into the controls stack of a CertRequest
69  * (section 6)
70  * returns 1 on success, 0 on error
71  */
72 static int OSSL_CRMF_MSG_push0_regCtrl(OSSL_CRMF_MSG *crm,
73                                        OSSL_CRMF_ATTRIBUTETYPEANDVALUE *ctrl)
74 {
75     int new = 0;
76
77     if (crm == NULL || crm->certReq == NULL || ctrl == NULL) {
78         CRMFerr(CRMF_F_OSSL_CRMF_MSG_PUSH0_REGCTRL, CRMF_R_NULL_ARGUMENT);
79         return 0;
80     }
81
82     if (crm->certReq->controls == NULL) {
83         crm->certReq->controls = sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_new_null();
84         if (crm->certReq->controls == NULL)
85             goto err;
86         new = 1;
87     }
88     if (!sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_push(crm->certReq->controls, ctrl))
89         goto err;
90
91     return 1;
92  err:
93     if (new != 0) {
94         sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_free(crm->certReq->controls);
95         crm->certReq->controls = NULL;
96     }
97     return 0;
98 }
99
100  /* id-regCtrl-regToken Control (section 6.1) */
101 IMPLEMENT_CRMF_CTRL_FUNC(regToken, ASN1_STRING, regCtrl)
102
103  /* id-regCtrl-authenticator Control (section 6.2) */
104 #define ASN1_UTF8STRING_dup ASN1_STRING_dup
105 IMPLEMENT_CRMF_CTRL_FUNC(authenticator, ASN1_UTF8STRING, regCtrl)
106
107 int OSSL_CRMF_MSG_set0_SinglePubInfo(OSSL_CRMF_SINGLEPUBINFO *spi,
108                                      int method, GENERAL_NAME *nm)
109 {
110     if (spi == NULL
111             || method < OSSL_CRMF_PUB_METHOD_DONTCARE
112             || method > OSSL_CRMF_PUB_METHOD_LDAP) {
113         CRMFerr(CRMF_F_OSSL_CRMF_MSG_SET0_SINGLEPUBINFO,
114                 ERR_R_PASSED_INVALID_ARGUMENT);
115         return 0;
116     }
117
118     if (!ASN1_INTEGER_set(spi->pubMethod, method))
119         return 0;
120     GENERAL_NAME_free(spi->pubLocation);
121     spi->pubLocation = nm;
122     return 1;
123 }
124
125 int OSSL_CRMF_MSG_PKIPublicationInfo_push0_SinglePubInfo(
126                                  OSSL_CRMF_PKIPUBLICATIONINFO *pi,
127                                  OSSL_CRMF_SINGLEPUBINFO *spi)
128 {
129     if (pi == NULL || spi == NULL) {
130         CRMFerr(CRMF_F_OSSL_CRMF_MSG_PKIPUBLICATIONINFO_PUSH0_SINGLEPUBINFO,
131                 CRMF_R_NULL_ARGUMENT);
132         return 0;
133     }
134     if (pi->pubInfos == NULL)
135         pi->pubInfos = sk_OSSL_CRMF_SINGLEPUBINFO_new_null();
136     if (pi->pubInfos == NULL)
137         return 0;
138
139     return sk_OSSL_CRMF_SINGLEPUBINFO_push(pi->pubInfos, spi);
140 }
141
142 int OSSL_CRMF_MSG_set_PKIPublicationInfo_action(
143                                  OSSL_CRMF_PKIPUBLICATIONINFO *pi, int action)
144 {
145     if (pi == NULL
146             || action < OSSL_CRMF_PUB_ACTION_DONTPUBLISH
147             || action > OSSL_CRMF_PUB_ACTION_PLEASEPUBLISH) {
148         CRMFerr(CRMF_F_OSSL_CRMF_MSG_SET_PKIPUBLICATIONINFO_ACTION,
149                 ERR_R_PASSED_INVALID_ARGUMENT);
150         return 0;
151     }
152
153     return ASN1_INTEGER_set(pi->action, action);
154 }
155
156  /* id-regCtrl-pkiPublicationInfo Control (section 6.3) */
157 IMPLEMENT_CRMF_CTRL_FUNC(pkiPublicationInfo, OSSL_CRMF_PKIPUBLICATIONINFO,
158                          regCtrl)
159
160  /* id-regCtrl-oldCertID Control (section 6.5) from the given */
161 IMPLEMENT_CRMF_CTRL_FUNC(oldCertID, OSSL_CRMF_CERTID, regCtrl)
162
163 OSSL_CRMF_CERTID *OSSL_CRMF_CERTID_gen(const X509_NAME *issuer,
164                                        const ASN1_INTEGER *serial)
165 {
166     OSSL_CRMF_CERTID *cid = NULL;
167
168     if (issuer == NULL || serial == NULL) {
169         CRMFerr(CRMF_F_OSSL_CRMF_CERTID_GEN, CRMF_R_NULL_ARGUMENT);
170         return NULL;
171     }
172
173     if ((cid = OSSL_CRMF_CERTID_new()) == NULL)
174         goto err;
175
176     if (!X509_NAME_set(&cid->issuer->d.directoryName, issuer))
177         goto err;
178     cid->issuer->type = GEN_DIRNAME;
179
180     ASN1_INTEGER_free(cid->serialNumber);
181     if ((cid->serialNumber = ASN1_INTEGER_dup(serial)) == NULL)
182         goto err;
183
184     return cid;
185
186  err:
187     OSSL_CRMF_CERTID_free(cid);
188     return NULL;
189 }
190
191  /*
192   * id-regCtrl-protocolEncrKey Control (section 6.6)
193   *
194   */
195 IMPLEMENT_CRMF_CTRL_FUNC(protocolEncrKey, X509_PUBKEY, regCtrl)
196
197 /*-
198  * Pushes the attribute given in regInfo in to the CertReqMsg->regInfo stack.
199  * (section 7)
200  * returns 1 on success, 0 on error
201  */
202 static int OSSL_CRMF_MSG_push0_regInfo(OSSL_CRMF_MSG *crm,
203                                        OSSL_CRMF_ATTRIBUTETYPEANDVALUE *ri)
204 {
205     STACK_OF(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) *info = NULL;
206
207     if (crm == NULL || ri == NULL) {
208         CRMFerr(CRMF_F_OSSL_CRMF_MSG_PUSH0_REGINFO, CRMF_R_NULL_ARGUMENT);
209         return 0;
210     }
211
212     if (crm->regInfo == NULL)
213         crm->regInfo = info = sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_new_null();
214     if (crm->regInfo == NULL)
215         goto err;
216     if (!sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_push(crm->regInfo, ri))
217         goto err;
218     return 1;
219
220  err:
221     if (info != NULL)
222         crm->regInfo = NULL;
223     sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_free(info);
224     return 0;
225 }
226
227 /* id-regInfo-utf8Pairs to regInfo (section 7.1) */
228 IMPLEMENT_CRMF_CTRL_FUNC(utf8Pairs, ASN1_UTF8STRING, regInfo)
229
230 /* id-regInfo-certReq to regInfo (section 7.2) */
231 IMPLEMENT_CRMF_CTRL_FUNC(certReq, OSSL_CRMF_CERTREQUEST, regInfo)
232
233
234 /* retrieves the certificate template of crm */
235 OSSL_CRMF_CERTTEMPLATE *OSSL_CRMF_MSG_get0_tmpl(const OSSL_CRMF_MSG *crm)
236 {
237     if (crm == NULL || crm->certReq == NULL) {
238         CRMFerr(CRMF_F_OSSL_CRMF_MSG_GET0_TMPL, CRMF_R_NULL_ARGUMENT);
239         return NULL;
240     }
241     return crm->certReq->certTemplate;
242 }
243
244
245 int OSSL_CRMF_MSG_set_validity(OSSL_CRMF_MSG *crm, time_t from, time_t to)
246 {
247     OSSL_CRMF_OPTIONALVALIDITY *vld = NULL;
248     ASN1_TIME *from_asn = NULL;
249     ASN1_TIME *to_asn = NULL;
250     OSSL_CRMF_CERTTEMPLATE *tmpl = OSSL_CRMF_MSG_get0_tmpl(crm);
251
252     if (tmpl == NULL) { /* also crm == NULL implies this */
253         CRMFerr(CRMF_F_OSSL_CRMF_MSG_SET_VALIDITY, CRMF_R_NULL_ARGUMENT);
254         return 0;
255     }
256
257     if (from != 0 && ((from_asn = ASN1_TIME_set(NULL, from)) == NULL))
258         goto err;
259     if (to != 0 && ((to_asn = ASN1_TIME_set(NULL, to)) == NULL))
260         goto err;
261     if ((vld = OSSL_CRMF_OPTIONALVALIDITY_new()) == NULL)
262         goto err;
263
264     vld->notBefore = from_asn;
265     vld->notAfter = to_asn;
266
267     tmpl->validity = vld;
268
269     return 1;
270  err:
271     ASN1_TIME_free(from_asn);
272     ASN1_TIME_free(to_asn);
273     return 0;
274 }
275
276
277 int OSSL_CRMF_MSG_set_certReqId(OSSL_CRMF_MSG *crm, int rid)
278 {
279     if (crm == NULL || crm->certReq == NULL || crm->certReq->certReqId == NULL) {
280         CRMFerr(CRMF_F_OSSL_CRMF_MSG_SET_CERTREQID, CRMF_R_NULL_ARGUMENT);
281         return 0;
282     }
283
284     return ASN1_INTEGER_set(crm->certReq->certReqId, rid);
285 }
286
287 /* get ASN.1 encoded integer, return -1 on error */
288 static int crmf_asn1_get_int(const ASN1_INTEGER *a)
289 {
290     int64_t res;
291
292     if (!ASN1_INTEGER_get_int64(&res, a)) {
293         CRMFerr(0, ASN1_R_INVALID_NUMBER);
294         return -1;
295     }
296     if (res < INT_MIN) {
297         CRMFerr(0, ASN1_R_TOO_SMALL);
298         return -1;
299     }
300     if (res > INT_MAX) {
301         CRMFerr(0, ASN1_R_TOO_LARGE);
302         return -1;
303     }
304     return (int)res;
305 }
306
307 int OSSL_CRMF_MSG_get_certReqId(OSSL_CRMF_MSG *crm)
308 {
309     if (crm == NULL || /* not really needed: */ crm->certReq == NULL) {
310         CRMFerr(CRMF_F_OSSL_CRMF_MSG_GET_CERTREQID, CRMF_R_NULL_ARGUMENT);
311         return -1;
312     }
313     return crmf_asn1_get_int(crm->certReq->certReqId);
314 }
315
316
317 int OSSL_CRMF_MSG_set0_extensions(OSSL_CRMF_MSG *crm,
318                                   X509_EXTENSIONS *exts)
319 {
320     OSSL_CRMF_CERTTEMPLATE *tmpl = OSSL_CRMF_MSG_get0_tmpl(crm);
321
322     if (tmpl == NULL) { /* also crm == NULL implies this */
323         CRMFerr(CRMF_F_OSSL_CRMF_MSG_SET0_EXTENSIONS, CRMF_R_NULL_ARGUMENT);
324         return 0;
325     }
326
327     if (sk_X509_EXTENSION_num(exts) == 0) {
328         sk_X509_EXTENSION_free(exts);
329         exts = NULL; /* do not include empty extensions list */
330     }
331
332     sk_X509_EXTENSION_pop_free(tmpl->extensions, X509_EXTENSION_free);
333     tmpl->extensions = exts;
334     return 1;
335 }
336
337
338 int OSSL_CRMF_MSG_push0_extension(OSSL_CRMF_MSG *crm,
339                                   X509_EXTENSION *ext)
340 {
341     int new = 0;
342     OSSL_CRMF_CERTTEMPLATE *tmpl = OSSL_CRMF_MSG_get0_tmpl(crm);
343
344     if (tmpl == NULL || ext == NULL) { /* also crm == NULL implies this */
345         CRMFerr(CRMF_F_OSSL_CRMF_MSG_PUSH0_EXTENSION, CRMF_R_NULL_ARGUMENT);
346         return 0;
347     }
348
349     if (tmpl->extensions == NULL) {
350         if ((tmpl->extensions = sk_X509_EXTENSION_new_null()) == NULL)
351             goto err;
352         new = 1;
353     }
354
355     if (!sk_X509_EXTENSION_push(tmpl->extensions, ext))
356         goto err;
357     return 1;
358  err:
359     if (new != 0) {
360         sk_X509_EXTENSION_free(tmpl->extensions);
361         tmpl->extensions = NULL;
362     }
363     return 0;
364 }
365
366 /* TODO: support cases 1+2 (besides case 3) defined in RFC 4211, section 4.1. */
367 static int CRMF_poposigningkey_init(OSSL_CRMF_POPOSIGNINGKEY *ps,
368                                     OSSL_CRMF_CERTREQUEST *cr,
369                                     EVP_PKEY *pkey, int dgst)
370 {
371     int len;
372     size_t crlen;
373     size_t siglen;
374     unsigned char *crder = NULL, *sig = NULL;
375     int alg_nid = 0;
376     int md_nid = 0;
377     const EVP_MD *alg = NULL;
378     EVP_MD_CTX *ctx = NULL;
379     int ret = 0;
380
381     if (ps == NULL || cr == NULL || pkey == NULL) {
382         CRMFerr(CRMF_F_CRMF_POPOSIGNINGKEY_INIT, CRMF_R_NULL_ARGUMENT);
383         return 0;
384     }
385
386     /* OpenSSL defaults all bit strings to be encoded as ASN.1 NamedBitList */
387     ps->signature->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
388     ps->signature->flags |= ASN1_STRING_FLAG_BITS_LEFT;
389
390     len = i2d_OSSL_CRMF_CERTREQUEST(cr, &crder);
391     if (len < 0 || crder == NULL) {
392         CRMFerr(CRMF_F_CRMF_POPOSIGNINGKEY_INIT, CRMF_R_ERROR);
393         goto err;
394     }
395     crlen = (size_t)len;
396
397     if (!OBJ_find_sigid_by_algs(&alg_nid, dgst, EVP_PKEY_id(pkey))) {
398         CRMFerr(CRMF_F_CRMF_POPOSIGNINGKEY_INIT,
399                 CRMF_R_UNSUPPORTED_ALG_FOR_POPSIGNINGKEY);
400         goto err;
401     }
402     if (!OBJ_find_sigid_algs(alg_nid, &md_nid, NULL)
403             || (alg = EVP_get_digestbynid(md_nid)) == NULL) {
404         CRMFerr(CRMF_F_CRMF_POPOSIGNINGKEY_INIT,
405                 CRMF_R_UNSUPPORTED_ALG_FOR_POPSIGNINGKEY);
406         goto err;
407     }
408     if (!X509_ALGOR_set0(ps->algorithmIdentifier, OBJ_nid2obj(alg_nid),
409                          V_ASN1_NULL, NULL)
410             || (ctx = EVP_MD_CTX_new()) == NULL
411             || EVP_DigestSignInit(ctx, NULL, alg, NULL, pkey) <= 0
412             || EVP_DigestSignUpdate(ctx, crder, crlen) <= 0
413             || EVP_DigestSignFinal(ctx, NULL, &siglen) <= 0) {
414         CRMFerr(CRMF_F_CRMF_POPOSIGNINGKEY_INIT, CRMF_R_ERROR);
415         goto err;
416     }
417     if ((sig = OPENSSL_malloc(siglen)) == NULL)
418         goto err;
419     if (EVP_DigestSignFinal(ctx, sig, &siglen) <= 0
420             || !ASN1_BIT_STRING_set(ps->signature, sig, siglen)) {
421         CRMFerr(CRMF_F_CRMF_POPOSIGNINGKEY_INIT, CRMF_R_ERROR);
422         goto err;
423     }
424     ret = 1;
425
426  err:
427     OPENSSL_free(crder);
428     EVP_MD_CTX_free(ctx);
429     OPENSSL_free(sig);
430     return ret;
431 }
432
433
434 int OSSL_CRMF_MSG_create_popo(OSSL_CRMF_MSG *crm, EVP_PKEY *pkey,
435                               int dgst, int ppmtd)
436 {
437     OSSL_CRMF_POPO *pp = NULL;
438     ASN1_INTEGER *tag = NULL;
439
440     if (crm == NULL || (ppmtd == OSSL_CRMF_POPO_SIGNATURE && pkey == NULL)) {
441         CRMFerr(CRMF_F_OSSL_CRMF_MSG_CREATE_POPO, CRMF_R_NULL_ARGUMENT);
442         return 0;
443     }
444
445     if (ppmtd == OSSL_CRMF_POPO_NONE)
446         goto end;
447     if ((pp = OSSL_CRMF_POPO_new()) == NULL)
448         goto err;
449     pp->type = ppmtd;
450
451     switch (ppmtd) {
452     case OSSL_CRMF_POPO_RAVERIFIED:
453         if ((pp->value.raVerified = ASN1_NULL_new()) == NULL)
454             goto err;
455         break;
456
457     case OSSL_CRMF_POPO_SIGNATURE:
458         {
459             OSSL_CRMF_POPOSIGNINGKEY *ps = OSSL_CRMF_POPOSIGNINGKEY_new();
460             if (ps == NULL
461                     || !CRMF_poposigningkey_init(ps, crm->certReq, pkey, dgst)){
462                 OSSL_CRMF_POPOSIGNINGKEY_free(ps);
463                 goto err;
464             }
465             pp->value.signature = ps;
466         }
467         break;
468
469     case OSSL_CRMF_POPO_KEYENC:
470         if ((pp->value.keyEncipherment = OSSL_CRMF_POPOPRIVKEY_new()) == NULL)
471             goto err;
472         tag = ASN1_INTEGER_new();
473         pp->value.keyEncipherment->type =
474             OSSL_CRMF_POPOPRIVKEY_SUBSEQUENTMESSAGE;
475         pp->value.keyEncipherment->value.subsequentMessage = tag;
476         if (tag == NULL
477                 || !ASN1_INTEGER_set(tag, OSSL_CRMF_SUBSEQUENTMESSAGE_ENCRCERT))
478             goto err;
479         break;
480
481     default:
482         CRMFerr(CRMF_F_OSSL_CRMF_MSG_CREATE_POPO,
483                 CRMF_R_UNSUPPORTED_METHOD_FOR_CREATING_POPO);
484         goto err;
485     }
486
487  end:
488     OSSL_CRMF_POPO_free(crm->popo);
489     crm->popo = pp;
490
491     return 1;
492  err:
493     OSSL_CRMF_POPO_free(pp);
494     return 0;
495 }
496
497 /* returns 0 for equal, -1 for a < b or error on a, 1 for a > b or error on b */
498 static int X509_PUBKEY_cmp(X509_PUBKEY *a, X509_PUBKEY *b)
499 {
500     X509_ALGOR *algA = NULL, *algB = NULL;
501     int res = 0;
502
503     if (a == b)
504         return 0;
505     if (a == NULL || !X509_PUBKEY_get0_param(NULL, NULL, NULL, &algA, a)
506             || algA == NULL)
507         return -1;
508     if (b == NULL || !X509_PUBKEY_get0_param(NULL, NULL, NULL, &algB, b)
509             || algB == NULL)
510         return 1;
511     if ((res = X509_ALGOR_cmp(algA, algB)) != 0)
512         return res;
513     return EVP_PKEY_cmp(X509_PUBKEY_get0(a), X509_PUBKEY_get0(b));
514 }
515
516 /* verifies the Proof-of-Possession of the request with the given rid in reqs */
517 int OSSL_CRMF_MSGS_verify_popo(const OSSL_CRMF_MSGS *reqs,
518                                int rid, int acceptRAVerified)
519 {
520     OSSL_CRMF_MSG *req = NULL;
521     X509_PUBKEY *pubkey = NULL;
522     OSSL_CRMF_POPOSIGNINGKEY *sig = NULL;
523
524     if (reqs == NULL
525             || (req = sk_OSSL_CRMF_MSG_value(reqs, rid)) == NULL
526             || req->popo == NULL) {
527         CRMFerr(CRMF_F_OSSL_CRMF_MSGS_VERIFY_POPO,
528                 CRMF_R_NULL_ARGUMENT);
529         return 0;
530     }
531
532     switch (req->popo->type) {
533     case OSSL_CRMF_POPO_RAVERIFIED:
534         if (acceptRAVerified)
535             return 1;
536         break;
537     case OSSL_CRMF_POPO_SIGNATURE:
538         pubkey = req->certReq->certTemplate->publicKey;
539         sig = req->popo->value.signature;
540         if (sig->poposkInput != NULL) {
541             /*
542              * According to RFC 4211: publicKey contains a copy of
543              * the public key from the certificate template. This MUST be
544              * exactly the same value as contained in the certificate template.
545              */
546             if (pubkey == NULL
547                     || sig->poposkInput->publicKey == NULL
548                     || X509_PUBKEY_cmp(pubkey, sig->poposkInput->publicKey)
549                     || ASN1_item_verify(
550                            ASN1_ITEM_rptr(OSSL_CRMF_POPOSIGNINGKEYINPUT),
551                            sig->algorithmIdentifier, sig->signature,
552                            sig->poposkInput, X509_PUBKEY_get0(pubkey)) < 1)
553                 break;
554         } else {
555             if (pubkey == NULL
556                     || req->certReq->certTemplate->subject == NULL
557                     || ASN1_item_verify(ASN1_ITEM_rptr(OSSL_CRMF_CERTREQUEST),
558                                     sig->algorithmIdentifier, sig->signature,
559                                     req->certReq,
560                                     X509_PUBKEY_get0(pubkey)) < 1)
561                 break;
562         }
563         return 1;
564     case OSSL_CRMF_POPO_KEYENC:
565         /*
566          * TODO: when OSSL_CMP_certrep_new() supports encrypted certs,
567          * return 1 if the type of req->popo->value.keyEncipherment
568          * is OSSL_CRMF_POPOPRIVKEY_SUBSEQUENTMESSAGE and
569          * its value.subsequentMessage == OSSL_CRMF_SUBSEQUENTMESSAGE_ENCRCERT
570         */
571     case OSSL_CRMF_POPO_KEYAGREE:
572     default:
573         CRMFerr(CRMF_F_OSSL_CRMF_MSGS_VERIFY_POPO,
574                 CRMF_R_UNSUPPORTED_POPO_METHOD);
575         return 0;
576     }
577     CRMFerr(CRMF_F_OSSL_CRMF_MSGS_VERIFY_POPO,
578             CRMF_R_UNSUPPORTED_POPO_NOT_ACCEPTED);
579     return 0;
580 }
581
582 /* retrieves the serialNumber of the given cert template or NULL on error */
583 ASN1_INTEGER *OSSL_CRMF_CERTTEMPLATE_get0_serialNumber(OSSL_CRMF_CERTTEMPLATE *tmpl)
584 {
585     return tmpl != NULL ? tmpl->serialNumber : NULL;
586 }
587
588 /* retrieves the issuer name of the given cert template or NULL on error */
589 X509_NAME *OSSL_CRMF_CERTTEMPLATE_get0_issuer(OSSL_CRMF_CERTTEMPLATE *tmpl)
590 {
591     return tmpl != NULL ? tmpl->issuer : NULL;
592 }
593
594 /* retrieves the issuer name of the given CertId or NULL on error */
595 X509_NAME *OSSL_CRMF_CERTID_get0_issuer(const OSSL_CRMF_CERTID *cid)
596 {
597     return cid != NULL && cid->issuer->type == GEN_DIRNAME ?
598         cid->issuer->d.directoryName : NULL;
599 }
600
601 /* retrieves the serialNumber of the given CertId or NULL on error */
602 ASN1_INTEGER *OSSL_CRMF_CERTID_get0_serialNumber(const OSSL_CRMF_CERTID *cid)
603 {
604     return cid != NULL ? cid->serialNumber : NULL;
605 }
606
607 /*-
608  * fill in certificate template.
609  * Any value argument that is NULL will leave the respective field unchanged.
610  */
611 int OSSL_CRMF_CERTTEMPLATE_fill(OSSL_CRMF_CERTTEMPLATE *tmpl,
612                                 EVP_PKEY *pubkey,
613                                 const X509_NAME *subject,
614                                 const X509_NAME *issuer,
615                                 const ASN1_INTEGER *serial)
616 {
617     if (tmpl == NULL) {
618         CRMFerr(CRMF_F_OSSL_CRMF_CERTTEMPLATE_FILL, CRMF_R_NULL_ARGUMENT);
619         return 0;
620     }
621     if (subject != NULL && !X509_NAME_set(&tmpl->subject, subject))
622         return 0;
623     if (issuer != NULL && !X509_NAME_set(&tmpl->issuer, issuer))
624         return 0;
625     if (serial != NULL) {
626         ASN1_INTEGER_free(tmpl->serialNumber);
627         if ((tmpl->serialNumber = ASN1_INTEGER_dup(serial)) == NULL)
628             return 0;
629     }
630     if (pubkey != NULL && !X509_PUBKEY_set(&tmpl->publicKey, pubkey))
631         return 0;
632     return 1;
633 }
634
635
636 /*-
637  * Decrypts the certificate in the given encryptedValue using private key pkey.
638  * This is needed for the indirect PoP method as in RFC 4210 section 5.2.8.2.
639  *
640  * returns a pointer to the decrypted certificate
641  * returns NULL on error or if no certificate available
642  */
643 X509 *OSSL_CRMF_ENCRYPTEDVALUE_get1_encCert(OSSL_CRMF_ENCRYPTEDVALUE *ecert,
644                                             EVP_PKEY *pkey)
645 {
646     X509 *cert = NULL; /* decrypted certificate */
647     EVP_CIPHER_CTX *evp_ctx = NULL; /* context for symmetric encryption */
648     unsigned char *ek = NULL; /* decrypted symmetric encryption key */
649     size_t eksize = 0; /* size of decrypted symmetric encryption key */
650     const EVP_CIPHER *cipher = NULL; /* used cipher */
651     int cikeysize = 0; /* key size from cipher */
652     unsigned char *iv = NULL; /* initial vector for symmetric encryption */
653     unsigned char *outbuf = NULL; /* decryption output buffer */
654     const unsigned char *p = NULL; /* needed for decoding ASN1 */
655     int symmAlg = 0; /* NIDs for symmetric algorithm */
656     int n, outlen = 0;
657     EVP_PKEY_CTX *pkctx = NULL; /* private key context */
658
659     if (ecert == NULL || ecert->symmAlg == NULL || ecert->encSymmKey == NULL
660             || ecert->encValue == NULL || pkey == NULL) {
661         CRMFerr(CRMF_F_OSSL_CRMF_ENCRYPTEDVALUE_GET1_ENCCERT,
662                 CRMF_R_NULL_ARGUMENT);
663         return NULL;
664     }
665     if ((symmAlg = OBJ_obj2nid(ecert->symmAlg->algorithm)) == 0) {
666         CRMFerr(CRMF_F_OSSL_CRMF_ENCRYPTEDVALUE_GET1_ENCCERT,
667                 CRMF_R_UNSUPPORTED_CIPHER);
668         return NULL;
669     }
670     /* select symmetric cipher based on algorithm given in message */
671     if ((cipher = EVP_get_cipherbynid(symmAlg)) == NULL) {
672         CRMFerr(CRMF_F_OSSL_CRMF_ENCRYPTEDVALUE_GET1_ENCCERT,
673                 CRMF_R_UNSUPPORTED_CIPHER);
674         goto end;
675     }
676     cikeysize = EVP_CIPHER_key_length(cipher);
677     /* first the symmetric key needs to be decrypted */
678     pkctx = EVP_PKEY_CTX_new(pkey, NULL);
679     if (pkctx != NULL && EVP_PKEY_decrypt_init(pkctx)) {
680         ASN1_BIT_STRING *encKey = ecert->encSymmKey;
681         size_t failure;
682         int retval;
683
684         if (EVP_PKEY_decrypt(pkctx, NULL, &eksize,
685                              encKey->data, encKey->length) <= 0
686                 || (ek = OPENSSL_malloc(eksize)) == NULL)
687             goto end;
688         retval = EVP_PKEY_decrypt(pkctx, ek, &eksize,
689                                   encKey->data, encKey->length);
690         ERR_clear_error(); /* error state may have sensitive information */
691         failure = ~constant_time_is_zero_s(constant_time_msb(retval)
692                                            | constant_time_is_zero(retval));
693         failure |= ~constant_time_eq_s(eksize, (size_t)cikeysize);
694         if (failure) {
695             CRMFerr(CRMF_F_OSSL_CRMF_ENCRYPTEDVALUE_GET1_ENCCERT,
696                     CRMF_R_ERROR_DECRYPTING_SYMMETRIC_KEY);
697             goto end;
698         }
699     } else {
700         goto end;
701     }
702     if ((iv = OPENSSL_malloc(EVP_CIPHER_iv_length(cipher))) == NULL)
703         goto end;
704     if (ASN1_TYPE_get_octetstring(ecert->symmAlg->parameter, iv,
705                                    EVP_CIPHER_iv_length(cipher))
706         != EVP_CIPHER_iv_length(cipher)) {
707         CRMFerr(CRMF_F_OSSL_CRMF_ENCRYPTEDVALUE_GET1_ENCCERT,
708                 CRMF_R_MALFORMED_IV);
709         goto end;
710     }
711
712     /*
713      * d2i_X509 changes the given pointer, so use p for decoding the message and
714      * keep the original pointer in outbuf so the memory can be freed later
715      */
716     if ((p = outbuf = OPENSSL_malloc(ecert->encValue->length +
717                                      EVP_CIPHER_block_size(cipher))) == NULL
718             || (evp_ctx = EVP_CIPHER_CTX_new()) == NULL)
719         goto end;
720     EVP_CIPHER_CTX_set_padding(evp_ctx, 0);
721
722     if (!EVP_DecryptInit(evp_ctx, cipher, ek, iv)
723             || !EVP_DecryptUpdate(evp_ctx, outbuf, &outlen,
724                                   ecert->encValue->data,
725                                   ecert->encValue->length)
726             || !EVP_DecryptFinal(evp_ctx, outbuf + outlen, &n)) {
727         CRMFerr(CRMF_F_OSSL_CRMF_ENCRYPTEDVALUE_GET1_ENCCERT,
728                 CRMF_R_ERROR_DECRYPTING_CERTIFICATE);
729         goto end;
730     }
731     outlen += n;
732
733     /* convert decrypted certificate from DER to internal ASN.1 structure */
734     if ((cert = d2i_X509(NULL, &p, outlen)) == NULL) {
735         CRMFerr(CRMF_F_OSSL_CRMF_ENCRYPTEDVALUE_GET1_ENCCERT,
736                 CRMF_R_ERROR_DECODING_CERTIFICATE);
737     }
738  end:
739     EVP_PKEY_CTX_free(pkctx);
740     OPENSSL_free(outbuf);
741     EVP_CIPHER_CTX_free(evp_ctx);
742     OPENSSL_clear_free(ek, eksize);
743     OPENSSL_free(iv);
744     return cert;
745 }