Prefer fetch over legacy get_digestby/get_cipherby
[openssl.git] / crypto / crmf / crmf_lib.c
1 /*-
2  * Copyright 2007-2021 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 #include "internal/sizes.h"
34
35 /* explicit #includes not strictly needed since implied by the above: */
36 #include <openssl/crmf.h>
37 #include <openssl/err.h>
38 #include <openssl/evp.h>
39
40 /*-
41  * atyp = Attribute Type
42  * valt = Value Type
43  * ctrlinf = "regCtrl" or "regInfo"
44  */
45 #define IMPLEMENT_CRMF_CTRL_FUNC(atyp, valt, ctrlinf)                     \
46 int OSSL_CRMF_MSG_set1_##ctrlinf##_##atyp(OSSL_CRMF_MSG *msg,             \
47                                           const valt *in)                 \
48 {                                                                         \
49     OSSL_CRMF_ATTRIBUTETYPEANDVALUE *atav = NULL;                         \
50                                                                           \
51     if (msg == NULL || in == NULL)                                       \
52         goto err;                                                         \
53     if ((atav = OSSL_CRMF_ATTRIBUTETYPEANDVALUE_new()) == NULL)           \
54         goto err;                                                         \
55     if ((atav->type = OBJ_nid2obj(NID_id_##ctrlinf##_##atyp)) == NULL)    \
56         goto err;                                                         \
57     if ((atav->value.atyp = valt##_dup(in)) == NULL)                      \
58         goto err;                                                         \
59     if (!OSSL_CRMF_MSG_push0_##ctrlinf(msg, atav))                        \
60         goto err;                                                         \
61     return 1;                                                             \
62  err:                                                                     \
63     OSSL_CRMF_ATTRIBUTETYPEANDVALUE_free(atav);                           \
64     return 0;                                                             \
65 }
66
67
68 /*-
69  * Pushes the given control attribute into the controls stack of a CertRequest
70  * (section 6)
71  * returns 1 on success, 0 on error
72  */
73 static int OSSL_CRMF_MSG_push0_regCtrl(OSSL_CRMF_MSG *crm,
74                                        OSSL_CRMF_ATTRIBUTETYPEANDVALUE *ctrl)
75 {
76     int new = 0;
77
78     if (crm == NULL || crm->certReq == NULL || ctrl == NULL) {
79         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
80         return 0;
81     }
82
83     if (crm->certReq->controls == NULL) {
84         crm->certReq->controls = sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_new_null();
85         if (crm->certReq->controls == NULL)
86             goto err;
87         new = 1;
88     }
89     if (!sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_push(crm->certReq->controls, ctrl))
90         goto err;
91
92     return 1;
93  err:
94     if (new != 0) {
95         sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_free(crm->certReq->controls);
96         crm->certReq->controls = NULL;
97     }
98     return 0;
99 }
100
101 /* id-regCtrl-regToken Control (section 6.1) */
102 IMPLEMENT_CRMF_CTRL_FUNC(regToken, ASN1_STRING, regCtrl)
103
104 /* id-regCtrl-authenticator Control (section 6.2) */
105 #define ASN1_UTF8STRING_dup ASN1_STRING_dup
106 IMPLEMENT_CRMF_CTRL_FUNC(authenticator, ASN1_UTF8STRING, regCtrl)
107
108 int OSSL_CRMF_MSG_set0_SinglePubInfo(OSSL_CRMF_SINGLEPUBINFO *spi,
109                                      int method, GENERAL_NAME *nm)
110 {
111     if (spi == NULL
112             || method < OSSL_CRMF_PUB_METHOD_DONTCARE
113             || method > OSSL_CRMF_PUB_METHOD_LDAP) {
114         ERR_raise(ERR_LIB_CRMF, 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
126 OSSL_CRMF_MSG_PKIPublicationInfo_push0_SinglePubInfo(OSSL_CRMF_PKIPUBLICATIONINFO *pi,
127                                                      OSSL_CRMF_SINGLEPUBINFO *spi)
128 {
129     if (pi == NULL || spi == NULL) {
130         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
131         return 0;
132     }
133     if (pi->pubInfos == NULL)
134         pi->pubInfos = sk_OSSL_CRMF_SINGLEPUBINFO_new_null();
135     if (pi->pubInfos == NULL)
136         return 0;
137
138     return sk_OSSL_CRMF_SINGLEPUBINFO_push(pi->pubInfos, spi);
139 }
140
141 int OSSL_CRMF_MSG_set_PKIPublicationInfo_action(OSSL_CRMF_PKIPUBLICATIONINFO *pi,
142                                                 int action)
143 {
144     if (pi == NULL
145             || action < OSSL_CRMF_PUB_ACTION_DONTPUBLISH
146             || action > OSSL_CRMF_PUB_ACTION_PLEASEPUBLISH) {
147         ERR_raise(ERR_LIB_CRMF, ERR_R_PASSED_INVALID_ARGUMENT);
148         return 0;
149     }
150
151     return ASN1_INTEGER_set(pi->action, action);
152 }
153
154 /* id-regCtrl-pkiPublicationInfo Control (section 6.3) */
155 IMPLEMENT_CRMF_CTRL_FUNC(pkiPublicationInfo, OSSL_CRMF_PKIPUBLICATIONINFO,
156                          regCtrl)
157
158 /* id-regCtrl-oldCertID Control (section 6.5) from the given */
159 IMPLEMENT_CRMF_CTRL_FUNC(oldCertID, OSSL_CRMF_CERTID, regCtrl)
160
161 OSSL_CRMF_CERTID *OSSL_CRMF_CERTID_gen(const X509_NAME *issuer,
162                                        const ASN1_INTEGER *serial)
163 {
164     OSSL_CRMF_CERTID *cid = NULL;
165
166     if (issuer == NULL || serial == NULL) {
167         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
168         return NULL;
169     }
170
171     if ((cid = OSSL_CRMF_CERTID_new()) == NULL)
172         goto err;
173
174     if (!X509_NAME_set(&cid->issuer->d.directoryName, issuer))
175         goto err;
176     cid->issuer->type = GEN_DIRNAME;
177
178     ASN1_INTEGER_free(cid->serialNumber);
179     if ((cid->serialNumber = ASN1_INTEGER_dup(serial)) == NULL)
180         goto err;
181
182     return cid;
183
184  err:
185     OSSL_CRMF_CERTID_free(cid);
186     return NULL;
187 }
188
189 /*
190  * id-regCtrl-protocolEncrKey Control (section 6.6)
191  */
192 IMPLEMENT_CRMF_CTRL_FUNC(protocolEncrKey, X509_PUBKEY, regCtrl)
193
194 /*-
195  * Pushes the attribute given in regInfo in to the CertReqMsg->regInfo stack.
196  * (section 7)
197  * returns 1 on success, 0 on error
198  */
199 static int OSSL_CRMF_MSG_push0_regInfo(OSSL_CRMF_MSG *crm,
200                                        OSSL_CRMF_ATTRIBUTETYPEANDVALUE *ri)
201 {
202     STACK_OF(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) *info = NULL;
203
204     if (crm == NULL || ri == NULL) {
205         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
206         return 0;
207     }
208
209     if (crm->regInfo == NULL)
210         crm->regInfo = info = sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_new_null();
211     if (crm->regInfo == NULL)
212         goto err;
213     if (!sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_push(crm->regInfo, ri))
214         goto err;
215     return 1;
216
217  err:
218     if (info != NULL)
219         crm->regInfo = NULL;
220     sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_free(info);
221     return 0;
222 }
223
224 /* id-regInfo-utf8Pairs to regInfo (section 7.1) */
225 IMPLEMENT_CRMF_CTRL_FUNC(utf8Pairs, ASN1_UTF8STRING, regInfo)
226
227 /* id-regInfo-certReq to regInfo (section 7.2) */
228 IMPLEMENT_CRMF_CTRL_FUNC(certReq, OSSL_CRMF_CERTREQUEST, regInfo)
229
230
231 /* retrieves the certificate template of crm */
232 OSSL_CRMF_CERTTEMPLATE *OSSL_CRMF_MSG_get0_tmpl(const OSSL_CRMF_MSG *crm)
233 {
234     if (crm == NULL || crm->certReq == NULL) {
235         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
236         return NULL;
237     }
238     return crm->certReq->certTemplate;
239 }
240
241
242 int OSSL_CRMF_MSG_set0_validity(OSSL_CRMF_MSG *crm,
243                                 ASN1_TIME *notBefore, ASN1_TIME *notAfter)
244 {
245     OSSL_CRMF_OPTIONALVALIDITY *vld;
246     OSSL_CRMF_CERTTEMPLATE *tmpl = OSSL_CRMF_MSG_get0_tmpl(crm);
247
248     if (tmpl == NULL) { /* also crm == NULL implies this */
249         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
250         return 0;
251     }
252
253     if ((vld = OSSL_CRMF_OPTIONALVALIDITY_new()) == NULL)
254         return 0;
255     vld->notBefore = notBefore;
256     vld->notAfter = notAfter;
257     tmpl->validity = vld;
258     return 1;
259 }
260
261
262 int OSSL_CRMF_MSG_set_certReqId(OSSL_CRMF_MSG *crm, int rid)
263 {
264     if (crm == NULL || crm->certReq == NULL || crm->certReq->certReqId == NULL) {
265         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
266         return 0;
267     }
268
269     return ASN1_INTEGER_set(crm->certReq->certReqId, rid);
270 }
271
272 /* get ASN.1 encoded integer, return -1 on error */
273 static int crmf_asn1_get_int(const ASN1_INTEGER *a)
274 {
275     int64_t res;
276
277     if (!ASN1_INTEGER_get_int64(&res, a)) {
278         ERR_raise(ERR_LIB_CRMF, ASN1_R_INVALID_NUMBER);
279         return -1;
280     }
281     if (res < INT_MIN) {
282         ERR_raise(ERR_LIB_CRMF, ASN1_R_TOO_SMALL);
283         return -1;
284     }
285     if (res > INT_MAX) {
286         ERR_raise(ERR_LIB_CRMF, ASN1_R_TOO_LARGE);
287         return -1;
288     }
289     return (int)res;
290 }
291
292 int OSSL_CRMF_MSG_get_certReqId(const OSSL_CRMF_MSG *crm)
293 {
294     if (crm == NULL || /* not really needed: */ crm->certReq == NULL) {
295         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
296         return -1;
297     }
298     return crmf_asn1_get_int(crm->certReq->certReqId);
299 }
300
301
302 int OSSL_CRMF_MSG_set0_extensions(OSSL_CRMF_MSG *crm,
303                                   X509_EXTENSIONS *exts)
304 {
305     OSSL_CRMF_CERTTEMPLATE *tmpl = OSSL_CRMF_MSG_get0_tmpl(crm);
306
307     if (tmpl == NULL) { /* also crm == NULL implies this */
308         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
309         return 0;
310     }
311
312     if (sk_X509_EXTENSION_num(exts) == 0) {
313         sk_X509_EXTENSION_free(exts);
314         exts = NULL; /* do not include empty extensions list */
315     }
316
317     sk_X509_EXTENSION_pop_free(tmpl->extensions, X509_EXTENSION_free);
318     tmpl->extensions = exts;
319     return 1;
320 }
321
322
323 int OSSL_CRMF_MSG_push0_extension(OSSL_CRMF_MSG *crm,
324                                   X509_EXTENSION *ext)
325 {
326     int new = 0;
327     OSSL_CRMF_CERTTEMPLATE *tmpl = OSSL_CRMF_MSG_get0_tmpl(crm);
328
329     if (tmpl == NULL || ext == NULL) { /* also crm == NULL implies this */
330         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
331         return 0;
332     }
333
334     if (tmpl->extensions == NULL) {
335         if ((tmpl->extensions = sk_X509_EXTENSION_new_null()) == NULL)
336             goto err;
337         new = 1;
338     }
339
340     if (!sk_X509_EXTENSION_push(tmpl->extensions, ext))
341         goto err;
342     return 1;
343  err:
344     if (new != 0) {
345         sk_X509_EXTENSION_free(tmpl->extensions);
346         tmpl->extensions = NULL;
347     }
348     return 0;
349 }
350
351 static int create_popo_signature(OSSL_CRMF_POPOSIGNINGKEY *ps,
352                                  const OSSL_CRMF_CERTREQUEST *cr,
353                                  EVP_PKEY *pkey, const EVP_MD *digest,
354                                  OSSL_LIB_CTX *libctx, const char *propq)
355 {
356     if (ps == NULL || cr == NULL || pkey == NULL) {
357         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
358         return 0;
359     }
360     if (ps->poposkInput != NULL) {
361         /* TODO: support cases 1+2 defined in RFC 4211, section 4.1 */
362         ERR_raise(ERR_LIB_CRMF, CRMF_R_POPOSKINPUT_NOT_SUPPORTED);
363         return 0;
364     }
365
366     return ASN1_item_sign_ex(ASN1_ITEM_rptr(OSSL_CRMF_CERTREQUEST),
367                              ps->algorithmIdentifier, NULL, ps->signature, cr,
368                              NULL, pkey, digest, libctx, propq);
369 }
370
371
372 int OSSL_CRMF_MSG_create_popo(int meth, OSSL_CRMF_MSG *crm,
373                               EVP_PKEY *pkey, const EVP_MD *digest,
374                               OSSL_LIB_CTX *libctx, const char *propq)
375 {
376     OSSL_CRMF_POPO *pp = NULL;
377     ASN1_INTEGER *tag = NULL;
378
379     if (crm == NULL || (meth == OSSL_CRMF_POPO_SIGNATURE && pkey == NULL)) {
380         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
381         return 0;
382     }
383
384     if (meth == OSSL_CRMF_POPO_NONE)
385         goto end;
386     if ((pp = OSSL_CRMF_POPO_new()) == NULL)
387         goto err;
388     pp->type = meth;
389
390     switch (meth) {
391     case OSSL_CRMF_POPO_RAVERIFIED:
392         if ((pp->value.raVerified = ASN1_NULL_new()) == NULL)
393             goto err;
394         break;
395
396     case OSSL_CRMF_POPO_SIGNATURE:
397         {
398             OSSL_CRMF_POPOSIGNINGKEY *ps = OSSL_CRMF_POPOSIGNINGKEY_new();
399
400             if (ps == NULL)
401                 goto err;
402             if (!create_popo_signature(ps, crm->certReq, pkey, digest,
403                                        libctx, propq)) {
404                 OSSL_CRMF_POPOSIGNINGKEY_free(ps);
405                 goto err;
406             }
407             pp->value.signature = ps;
408         }
409         break;
410
411     case OSSL_CRMF_POPO_KEYENC:
412         if ((pp->value.keyEncipherment = OSSL_CRMF_POPOPRIVKEY_new()) == NULL)
413             goto err;
414         tag = ASN1_INTEGER_new();
415         pp->value.keyEncipherment->type =
416             OSSL_CRMF_POPOPRIVKEY_SUBSEQUENTMESSAGE;
417         pp->value.keyEncipherment->value.subsequentMessage = tag;
418         if (tag == NULL
419                 || !ASN1_INTEGER_set(tag, OSSL_CRMF_SUBSEQUENTMESSAGE_ENCRCERT))
420             goto err;
421         break;
422
423     default:
424         ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_METHOD_FOR_CREATING_POPO);
425         goto err;
426     }
427
428  end:
429     OSSL_CRMF_POPO_free(crm->popo);
430     crm->popo = pp;
431
432     return 1;
433  err:
434     OSSL_CRMF_POPO_free(pp);
435     return 0;
436 }
437
438 /* verifies the Proof-of-Possession of the request with the given rid in reqs */
439 int OSSL_CRMF_MSGS_verify_popo(const OSSL_CRMF_MSGS *reqs,
440                                int rid, int acceptRAVerified,
441                                OSSL_LIB_CTX *libctx, const char *propq)
442 {
443     OSSL_CRMF_MSG *req = NULL;
444     X509_PUBKEY *pubkey = NULL;
445     OSSL_CRMF_POPOSIGNINGKEY *sig = NULL;
446     const ASN1_ITEM *it;
447     void *asn;
448
449     if (reqs == NULL || (req = sk_OSSL_CRMF_MSG_value(reqs, rid)) == NULL) {
450         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
451         return 0;
452     }
453
454     if (req->popo == NULL) {
455         ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_MISSING);
456         return 0;
457     }
458
459     switch (req->popo->type) {
460     case OSSL_CRMF_POPO_RAVERIFIED:
461         if (!acceptRAVerified) {
462             ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_RAVERIFIED_NOT_ACCEPTED);
463             return 0;
464         }
465         break;
466     case OSSL_CRMF_POPO_SIGNATURE:
467         pubkey = req->certReq->certTemplate->publicKey;
468         if (pubkey == NULL) {
469             ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_MISSING_PUBLIC_KEY);
470             return 0;
471         }
472         sig = req->popo->value.signature;
473         if (sig->poposkInput != NULL) {
474             /*
475              * According to RFC 4211: publicKey contains a copy of
476              * the public key from the certificate template. This MUST be
477              * exactly the same value as contained in the certificate template.
478              */
479             if (sig->poposkInput->publicKey == NULL) {
480                 ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_MISSING_PUBLIC_KEY);
481                 return 0;
482             }
483             if (X509_PUBKEY_eq(pubkey, sig->poposkInput->publicKey) != 1) {
484                 ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_INCONSISTENT_PUBLIC_KEY);
485                 return 0;
486             }
487             /*
488              * TODO check the contents of the authInfo sub-field,
489              * see RFC 4211 https://tools.ietf.org/html/rfc4211#section-4.1
490              */
491             it = ASN1_ITEM_rptr(OSSL_CRMF_POPOSIGNINGKEYINPUT);
492             asn = sig->poposkInput;
493         } else {
494             if (req->certReq->certTemplate->subject == NULL) {
495                 ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_MISSING_SUBJECT);
496                 return 0;
497             }
498             it = ASN1_ITEM_rptr(OSSL_CRMF_CERTREQUEST);
499             asn = req->certReq;
500         }
501         if (ASN1_item_verify_ex(it, sig->algorithmIdentifier, sig->signature,
502                                 asn, NULL, X509_PUBKEY_get0(pubkey), libctx,
503                                 propq) < 1)
504             return 0;
505         break;
506     case OSSL_CRMF_POPO_KEYENC:
507         /*
508          * TODO: when OSSL_CMP_certrep_new() supports encrypted certs,
509          * return 1 if the type of req->popo->value.keyEncipherment
510          * is OSSL_CRMF_POPOPRIVKEY_SUBSEQUENTMESSAGE and
511          * its value.subsequentMessage == OSSL_CRMF_SUBSEQUENTMESSAGE_ENCRCERT
512          */
513     case OSSL_CRMF_POPO_KEYAGREE:
514     default:
515         ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_POPO_METHOD);
516         return 0;
517     }
518     return 1;
519 }
520
521 /* retrieves the serialNumber of the given cert template or NULL on error */
522 ASN1_INTEGER
523 *OSSL_CRMF_CERTTEMPLATE_get0_serialNumber(const OSSL_CRMF_CERTTEMPLATE *tmpl)
524 {
525     return tmpl != NULL ? tmpl->serialNumber : NULL;
526 }
527
528 /* retrieves the issuer name of the given cert template or NULL on error */
529 const X509_NAME
530     *OSSL_CRMF_CERTTEMPLATE_get0_issuer(const OSSL_CRMF_CERTTEMPLATE *tmpl)
531 {
532     return tmpl != NULL ? tmpl->issuer : NULL;
533 }
534
535 /* retrieves the issuer name of the given CertId or NULL on error */
536 const X509_NAME *OSSL_CRMF_CERTID_get0_issuer(const OSSL_CRMF_CERTID *cid)
537 {
538     return cid != NULL && cid->issuer->type == GEN_DIRNAME ?
539         cid->issuer->d.directoryName : NULL;
540 }
541
542 /* retrieves the serialNumber of the given CertId or NULL on error */
543 ASN1_INTEGER *OSSL_CRMF_CERTID_get0_serialNumber(const OSSL_CRMF_CERTID *cid)
544 {
545     return cid != NULL ? cid->serialNumber : NULL;
546 }
547
548 /*-
549  * fill in certificate template.
550  * Any value argument that is NULL will leave the respective field unchanged.
551  */
552 int OSSL_CRMF_CERTTEMPLATE_fill(OSSL_CRMF_CERTTEMPLATE *tmpl,
553                                 EVP_PKEY *pubkey,
554                                 const X509_NAME *subject,
555                                 const X509_NAME *issuer,
556                                 const ASN1_INTEGER *serial)
557 {
558     if (tmpl == NULL) {
559         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
560         return 0;
561     }
562     if (subject != NULL && !X509_NAME_set((X509_NAME **)&tmpl->subject, subject))
563         return 0;
564     if (issuer != NULL && !X509_NAME_set((X509_NAME **)&tmpl->issuer, issuer))
565         return 0;
566     if (serial != NULL) {
567         ASN1_INTEGER_free(tmpl->serialNumber);
568         if ((tmpl->serialNumber = ASN1_INTEGER_dup(serial)) == NULL)
569             return 0;
570     }
571     if (pubkey != NULL && !X509_PUBKEY_set(&tmpl->publicKey, pubkey))
572         return 0;
573     return 1;
574 }
575
576
577 /*-
578  * Decrypts the certificate in the given encryptedValue using private key pkey.
579  * This is needed for the indirect PoP method as in RFC 4210 section 5.2.8.2.
580  *
581  * returns a pointer to the decrypted certificate
582  * returns NULL on error or if no certificate available
583  */
584 X509
585 *OSSL_CRMF_ENCRYPTEDVALUE_get1_encCert(const OSSL_CRMF_ENCRYPTEDVALUE *ecert,
586                                        OSSL_LIB_CTX *libctx, const char *propq,
587                                        EVP_PKEY *pkey)
588 {
589     X509 *cert = NULL; /* decrypted certificate */
590     EVP_CIPHER_CTX *evp_ctx = NULL; /* context for symmetric encryption */
591     unsigned char *ek = NULL; /* decrypted symmetric encryption key */
592     size_t eksize = 0; /* size of decrypted symmetric encryption key */
593     EVP_CIPHER *cipher = NULL; /* used cipher */
594     int cikeysize = 0; /* key size from cipher */
595     unsigned char *iv = NULL; /* initial vector for symmetric encryption */
596     unsigned char *outbuf = NULL; /* decryption output buffer */
597     const unsigned char *p = NULL; /* needed for decoding ASN1 */
598     int n, outlen = 0;
599     EVP_PKEY_CTX *pkctx = NULL; /* private key context */
600     char name[OSSL_MAX_NAME_SIZE];
601
602     if (ecert == NULL || ecert->symmAlg == NULL || ecert->encSymmKey == NULL
603             || ecert->encValue == NULL || pkey == NULL) {
604         ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT);
605         return NULL;
606     }
607
608     /* select symmetric cipher based on algorithm given in message */
609     OBJ_obj2txt(name, sizeof(name), ecert->symmAlg->algorithm, 0);
610
611     (void)ERR_set_mark();
612     cipher = EVP_CIPHER_fetch(NULL, name, NULL);
613
614     if (cipher == NULL)
615         cipher = (EVP_CIPHER *)EVP_get_cipherbyname(name);
616
617     if (cipher == NULL) {
618         (void)ERR_clear_last_mark();
619         ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_CIPHER);
620         goto end;
621     }
622     (void)ERR_pop_to_mark();
623
624     cikeysize = EVP_CIPHER_key_length(cipher);
625     /* first the symmetric key needs to be decrypted */
626     pkctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq);
627     if (pkctx != NULL && EVP_PKEY_decrypt_init(pkctx)) {
628         ASN1_BIT_STRING *encKey = ecert->encSymmKey;
629         size_t failure;
630         int retval;
631
632         if (EVP_PKEY_decrypt(pkctx, NULL, &eksize,
633                              encKey->data, encKey->length) <= 0
634                 || (ek = OPENSSL_malloc(eksize)) == NULL)
635             goto end;
636         retval = EVP_PKEY_decrypt(pkctx, ek, &eksize,
637                                   encKey->data, encKey->length);
638         ERR_clear_error(); /* error state may have sensitive information */
639         failure = ~constant_time_is_zero_s(constant_time_msb(retval)
640                                            | constant_time_is_zero(retval));
641         failure |= ~constant_time_eq_s(eksize, (size_t)cikeysize);
642         if (failure) {
643             ERR_raise(ERR_LIB_CRMF, CRMF_R_ERROR_DECRYPTING_SYMMETRIC_KEY);
644             goto end;
645         }
646     } else {
647         goto end;
648     }
649     if ((iv = OPENSSL_malloc(EVP_CIPHER_iv_length(cipher))) == NULL)
650         goto end;
651     if (ASN1_TYPE_get_octetstring(ecert->symmAlg->parameter, iv,
652                                   EVP_CIPHER_iv_length(cipher))
653         != EVP_CIPHER_iv_length(cipher)) {
654         ERR_raise(ERR_LIB_CRMF, CRMF_R_MALFORMED_IV);
655         goto end;
656     }
657
658     /*
659      * d2i_X509 changes the given pointer, so use p for decoding the message and
660      * keep the original pointer in outbuf so the memory can be freed later
661      */
662     if ((p = outbuf = OPENSSL_malloc(ecert->encValue->length +
663                                      EVP_CIPHER_block_size(cipher))) == NULL
664             || (evp_ctx = EVP_CIPHER_CTX_new()) == NULL)
665         goto end;
666     EVP_CIPHER_CTX_set_padding(evp_ctx, 0);
667
668     if (!EVP_DecryptInit(evp_ctx, cipher, ek, iv)
669             || !EVP_DecryptUpdate(evp_ctx, outbuf, &outlen,
670                                   ecert->encValue->data,
671                                   ecert->encValue->length)
672             || !EVP_DecryptFinal(evp_ctx, outbuf + outlen, &n)) {
673         ERR_raise(ERR_LIB_CRMF, CRMF_R_ERROR_DECRYPTING_CERTIFICATE);
674         goto end;
675     }
676     outlen += n;
677
678     /* convert decrypted certificate from DER to internal ASN.1 structure */
679     if ((cert = X509_new_ex(libctx, propq)) == NULL)
680         goto end;
681     if (d2i_X509(&cert, &p, outlen) == NULL)
682         ERR_raise(ERR_LIB_CRMF, CRMF_R_ERROR_DECODING_CERTIFICATE);
683  end:
684     EVP_PKEY_CTX_free(pkctx);
685     OPENSSL_free(outbuf);
686     EVP_CIPHER_CTX_free(evp_ctx);
687     EVP_CIPHER_free(cipher);
688     OPENSSL_clear_free(ek, eksize);
689     OPENSSL_free(iv);
690     return cert;
691 }