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