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