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