Bug fix in ossl_cmp_certRep_new(): must allocate empty extraCerts stack
[openssl.git] / crypto / cmp / cmp_msg.c
1 /*
2  * Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright Nokia 2007-2019
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
12 /* CMP functions for PKIMessage construction */
13
14 #include "cmp_local.h"
15
16 /* explicit #includes not strictly needed since implied by the above: */
17 #include <openssl/asn1t.h>
18 #include <openssl/cmp.h>
19 #include <openssl/crmf.h>
20 #include <openssl/err.h>
21 #include <openssl/x509.h>
22
23 DEFINE_STACK_OF(OSSL_CMP_CERTSTATUS)
24 DEFINE_STACK_OF(OSSL_CMP_ITAV)
25 DEFINE_STACK_OF(GENERAL_NAME)
26 DEFINE_STACK_OF(X509)
27 DEFINE_STACK_OF(X509_EXTENSION)
28 DEFINE_STACK_OF(OSSL_CMP_PKISI)
29 DEFINE_STACK_OF(OSSL_CRMF_MSG)
30 DEFINE_STACK_OF(OSSL_CMP_CERTRESPONSE)
31 DEFINE_STACK_OF(OSSL_CRMF_CERTID)
32 DEFINE_STACK_OF(ASN1_UTF8STRING)
33
34 OSSL_CMP_PKIHEADER *OSSL_CMP_MSG_get0_header(const OSSL_CMP_MSG *msg)
35 {
36     if (msg == NULL) {
37         CMPerr(0, CMP_R_NULL_ARGUMENT);
38         return NULL;
39     }
40     return msg->header;
41 }
42
43 const char *ossl_cmp_bodytype_to_string(int type)
44 {
45     static const char *type_names[] = {
46         "IR", "IP", "CR", "CP", "P10CR",
47         "POPDECC", "POPDECR", "KUR", "KUP",
48         "KRR", "KRP", "RR", "RP", "CCR", "CCP",
49         "CKUANN", "CANN", "RANN", "CRLANN", "PKICONF", "NESTED",
50         "GENM", "GENP", "ERROR", "CERTCONF", "POLLREQ", "POLLREP",
51     };
52
53     if (type < 0 || type > OSSL_CMP_PKIBODY_TYPE_MAX)
54         return "illegal body type";
55     return type_names[type];
56 }
57
58 int ossl_cmp_msg_set_bodytype(OSSL_CMP_MSG *msg, int type)
59 {
60     if (!ossl_assert(msg != NULL && msg->body != NULL))
61         return 0;
62
63     msg->body->type = type;
64     return 1;
65 }
66
67 int ossl_cmp_msg_get_bodytype(const OSSL_CMP_MSG *msg)
68 {
69     if (!ossl_assert(msg != NULL && msg->body != NULL))
70         return -1;
71
72     return msg->body->type;
73 }
74
75 /* Add an extension to the referenced extension stack, which may be NULL */
76 static int add1_extension(X509_EXTENSIONS **pexts, int nid, int crit, void *ex)
77 {
78     X509_EXTENSION *ext;
79     int res;
80
81     if (!ossl_assert(pexts != NULL)) /* pointer to var must not be NULL */
82         return 0;
83
84     if ((ext = X509V3_EXT_i2d(nid, crit, ex)) == NULL)
85         return 0;
86
87     res = X509v3_add_ext(pexts, ext, 0) != NULL;
88     X509_EXTENSION_free(ext);
89     return res;
90 }
91
92 /* Add a CRL revocation reason code to extension stack, which may be NULL */
93 static int add_crl_reason_extension(X509_EXTENSIONS **pexts, int reason_code)
94 {
95     ASN1_ENUMERATED *val = ASN1_ENUMERATED_new();
96     int res = 0;
97
98     if (val != NULL && ASN1_ENUMERATED_set(val, reason_code))
99         res = add1_extension(pexts, NID_crl_reason, 0 /* non-critical */, val);
100     ASN1_ENUMERATED_free(val);
101     return res;
102 }
103
104 OSSL_CMP_MSG *ossl_cmp_msg_create(OSSL_CMP_CTX *ctx, int bodytype)
105 {
106     OSSL_CMP_MSG *msg = NULL;
107
108     if (!ossl_assert(ctx != NULL))
109         return NULL;
110
111     if ((msg = OSSL_CMP_MSG_new()) == NULL)
112         return NULL;
113     if (!ossl_cmp_hdr_init(ctx, msg->header)
114             || !ossl_cmp_msg_set_bodytype(msg, bodytype))
115         goto err;
116     if (ctx->geninfo_ITAVs != NULL
117             && !ossl_cmp_hdr_generalInfo_push1_items(msg->header,
118                                                      ctx->geninfo_ITAVs))
119         goto err;
120
121     switch (bodytype) {
122     case OSSL_CMP_PKIBODY_IR:
123     case OSSL_CMP_PKIBODY_CR:
124     case OSSL_CMP_PKIBODY_KUR:
125         if ((msg->body->value.ir = OSSL_CRMF_MSGS_new()) == NULL)
126             goto err;
127         return msg;
128
129     case OSSL_CMP_PKIBODY_P10CR:
130         if (ctx->p10CSR == NULL) {
131             CMPerr(0, CMP_R_ERROR_CREATING_P10CR);
132             goto err;
133         }
134         if ((msg->body->value.p10cr = X509_REQ_dup(ctx->p10CSR)) == NULL)
135             goto err;
136         return msg;
137
138     case OSSL_CMP_PKIBODY_IP:
139     case OSSL_CMP_PKIBODY_CP:
140     case OSSL_CMP_PKIBODY_KUP:
141         if ((msg->body->value.ip = OSSL_CMP_CERTREPMESSAGE_new()) == NULL)
142             goto err;
143         return msg;
144
145     case OSSL_CMP_PKIBODY_RR:
146         if ((msg->body->value.rr = sk_OSSL_CMP_REVDETAILS_new_null()) == NULL)
147             goto err;
148         return msg;
149     case OSSL_CMP_PKIBODY_RP:
150         if ((msg->body->value.rp = OSSL_CMP_REVREPCONTENT_new()) == NULL)
151             goto err;
152         return msg;
153
154     case OSSL_CMP_PKIBODY_CERTCONF:
155         if ((msg->body->value.certConf =
156              sk_OSSL_CMP_CERTSTATUS_new_null()) == NULL)
157             goto err;
158         return msg;
159     case OSSL_CMP_PKIBODY_PKICONF:
160         if ((msg->body->value.pkiconf = ASN1_TYPE_new()) == NULL)
161             goto err;
162         ASN1_TYPE_set(msg->body->value.pkiconf, V_ASN1_NULL, NULL);
163         return msg;
164
165     case OSSL_CMP_PKIBODY_POLLREQ:
166         if ((msg->body->value.pollReq = sk_OSSL_CMP_POLLREQ_new_null()) == NULL)
167             goto err;
168         return msg;
169     case OSSL_CMP_PKIBODY_POLLREP:
170         if ((msg->body->value.pollRep = sk_OSSL_CMP_POLLREP_new_null()) == NULL)
171             goto err;
172         return msg;
173
174     case OSSL_CMP_PKIBODY_GENM:
175     case OSSL_CMP_PKIBODY_GENP:
176         if ((msg->body->value.genm = sk_OSSL_CMP_ITAV_new_null()) == NULL)
177             goto err;
178         return msg;
179
180     case OSSL_CMP_PKIBODY_ERROR:
181         if ((msg->body->value.error = OSSL_CMP_ERRORMSGCONTENT_new()) == NULL)
182             goto err;
183         return msg;
184
185     default:
186         CMPerr(0, CMP_R_UNEXPECTED_PKIBODY);
187         goto err;
188     }
189
190  err:
191     OSSL_CMP_MSG_free(msg);
192     return NULL;
193 }
194
195 #define HAS_SAN(ctx) \
196     (sk_GENERAL_NAME_num((ctx)->subjectAltNames) > 0 \
197          || OSSL_CMP_CTX_reqExtensions_have_SAN(ctx) == 1)
198
199 static const X509_NAME *determine_subj(OSSL_CMP_CTX *ctx, X509 *refcert,
200                                        int bodytype)
201 {
202     if (ctx->subjectName != NULL)
203         return ctx->subjectName;
204
205     if (refcert != NULL
206             && (bodytype == OSSL_CMP_PKIBODY_KUR || !HAS_SAN(ctx)))
207         /*
208          * For KUR, copy subjectName from reference certificate.
209          * For IR or CR, do the same only if there is no subjectAltName.
210          */
211         return X509_get_subject_name(refcert);
212     return NULL;
213 }
214
215 /*
216  * Create CRMF certificate request message for IR/CR/KUR
217  * returns a pointer to the OSSL_CRMF_MSG on success, NULL on error
218  */
219 static OSSL_CRMF_MSG *crm_new(OSSL_CMP_CTX *ctx, int bodytype, int rid)
220 {
221     OSSL_CRMF_MSG *crm = NULL;
222     X509 *refcert = ctx->oldCert != NULL ? ctx->oldCert : ctx->cert;
223     /* refcert defaults to current client cert */
224     EVP_PKEY *rkey = OSSL_CMP_CTX_get0_newPkey(ctx, 0);
225     STACK_OF(GENERAL_NAME) *default_sans = NULL;
226     const X509_NAME *subject = determine_subj(ctx, refcert, bodytype);
227     int crit = ctx->setSubjectAltNameCritical || subject == NULL;
228     /* RFC5280: subjectAltName MUST be critical if subject is null */
229     X509_EXTENSIONS *exts = NULL;
230
231     if (rkey == NULL)
232         rkey = ctx->pkey; /* default is independent of ctx->oldCert */
233     if (rkey == NULL) {
234 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
235         CMPerr(0, CMP_R_NULL_ARGUMENT);
236         return NULL;
237 #endif
238     }
239     if (bodytype == OSSL_CMP_PKIBODY_KUR && refcert == NULL) {
240         CMPerr(0, CMP_R_MISSING_REFERENCE_CERT);
241         return NULL;
242     }
243     if ((crm = OSSL_CRMF_MSG_new()) == NULL)
244         return NULL;
245     if (!OSSL_CRMF_MSG_set_certReqId(crm, rid)
246             /*
247              * fill certTemplate, corresponding to CertificationRequestInfo
248              * of PKCS#10. The rkey param cannot be NULL so far -
249              * it could be NULL if centralized key creation was supported
250              */
251             || !OSSL_CRMF_CERTTEMPLATE_fill(OSSL_CRMF_MSG_get0_tmpl(crm), rkey,
252                                             subject, ctx->issuer,
253                                             NULL /* serial */))
254         goto err;
255     if (ctx->days != 0) {
256         time_t notBefore, notAfter;
257
258         notBefore = time(NULL);
259         notAfter = notBefore + 60 * 60 * 24 * ctx->days;
260         if (!OSSL_CRMF_MSG_set_validity(crm, notBefore, notAfter))
261             goto err;
262     }
263
264     /* extensions */
265     if (refcert != NULL && !ctx->SubjectAltName_nodefault)
266         default_sans = X509V3_get_d2i(X509_get0_extensions(refcert),
267                                       NID_subject_alt_name, NULL, NULL);
268     /* exts are copied from ctx to allow reuse */
269     if (ctx->reqExtensions != NULL) {
270         exts = sk_X509_EXTENSION_deep_copy(ctx->reqExtensions,
271                                            X509_EXTENSION_dup,
272                                            X509_EXTENSION_free);
273         if (exts == NULL)
274             goto err;
275     }
276     if (sk_GENERAL_NAME_num(ctx->subjectAltNames) > 0
277             && !add1_extension(&exts, NID_subject_alt_name,
278                                crit, ctx->subjectAltNames))
279         goto err;
280     if (!HAS_SAN(ctx) && default_sans != NULL
281             && !add1_extension(&exts, NID_subject_alt_name, crit, default_sans))
282         goto err;
283     if (ctx->policies != NULL
284             && !add1_extension(&exts, NID_certificate_policies,
285                                ctx->setPoliciesCritical, ctx->policies))
286         goto err;
287     if (!OSSL_CRMF_MSG_set0_extensions(crm, exts))
288         goto err;
289     exts = NULL;
290     /* end fill certTemplate, now set any controls */
291
292     /* for KUR, set OldCertId according to D.6 */
293     if (bodytype == OSSL_CMP_PKIBODY_KUR) {
294         OSSL_CRMF_CERTID *cid =
295             OSSL_CRMF_CERTID_gen(X509_get_issuer_name(refcert),
296                                  X509_get_serialNumber(refcert));
297         int ret;
298
299         if (cid == NULL)
300             goto err;
301         ret = OSSL_CRMF_MSG_set1_regCtrl_oldCertID(crm, cid);
302         OSSL_CRMF_CERTID_free(cid);
303         if (ret == 0)
304             goto err;
305     }
306
307     goto end;
308
309  err:
310     OSSL_CRMF_MSG_free(crm);
311     crm = NULL;
312
313  end:
314     sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
315     sk_GENERAL_NAME_pop_free(default_sans, GENERAL_NAME_free);
316     return crm;
317 }
318
319 OSSL_CMP_MSG *ossl_cmp_certReq_new(OSSL_CMP_CTX *ctx, int type, int err_code)
320 {
321     OSSL_CMP_MSG *msg;
322     OSSL_CRMF_MSG *crm = NULL;
323
324     if (!ossl_assert(ctx != NULL))
325         return NULL;
326
327     if (type != OSSL_CMP_PKIBODY_IR && type != OSSL_CMP_PKIBODY_CR
328             && type != OSSL_CMP_PKIBODY_KUR && type != OSSL_CMP_PKIBODY_P10CR) {
329         CMPerr(0, CMP_R_INVALID_ARGS);
330         return NULL;
331     }
332
333     if ((msg = ossl_cmp_msg_create(ctx, type)) == NULL)
334         goto err;
335
336     /* header */
337     if (ctx->implicitConfirm && !ossl_cmp_hdr_set_implicitConfirm(msg->header))
338         goto err;
339
340     /* body */
341     /* For P10CR the content has already been set in OSSL_CMP_MSG_create */
342     if (type != OSSL_CMP_PKIBODY_P10CR) {
343         EVP_PKEY *privkey = OSSL_CMP_CTX_get0_newPkey(ctx, 1);
344
345         if (privkey == NULL)
346             privkey = ctx->pkey; /* default is independent of ctx->oldCert */
347         if (ctx->popoMethod == OSSL_CRMF_POPO_SIGNATURE && privkey == NULL) {
348             CMPerr(0, CMP_R_MISSING_PRIVATE_KEY);
349             goto err;
350         }
351         if ((crm = crm_new(ctx, type, OSSL_CMP_CERTREQID)) == NULL
352             || !OSSL_CRMF_MSG_create_popo(crm, privkey, ctx->digest,
353                                           ctx->popoMethod)
354             /* value.ir is same for cr and kur */
355             || !sk_OSSL_CRMF_MSG_push(msg->body->value.ir, crm))
356             goto err;
357         crm = NULL;
358         /* TODO: here optional 2nd certreqmsg could be pushed to the stack */
359     }
360
361     if (!ossl_cmp_msg_protect(ctx, msg))
362         goto err;
363
364     return msg;
365
366  err:
367     if (err_code != 0)
368         CMPerr(0, err_code);
369     OSSL_CRMF_MSG_free(crm);
370     OSSL_CMP_MSG_free(msg);
371     return NULL;
372 }
373
374 OSSL_CMP_MSG *ossl_cmp_certRep_new(OSSL_CMP_CTX *ctx, int bodytype,
375                                    int certReqId, OSSL_CMP_PKISI *si,
376                                    X509 *cert, STACK_OF(X509) *chain,
377                                    STACK_OF(X509) *caPubs, int encrypted,
378                                    int unprotectedErrors)
379 {
380     OSSL_CMP_MSG *msg = NULL;
381     OSSL_CMP_CERTREPMESSAGE *repMsg = NULL;
382     OSSL_CMP_CERTRESPONSE *resp = NULL;
383     int status = -1;
384
385     if (!ossl_assert(ctx != NULL && si != NULL))
386         return NULL;
387
388     if ((msg = ossl_cmp_msg_create(ctx, bodytype)) == NULL)
389         goto err;
390     repMsg = msg->body->value.ip; /* value.ip is same for cp and kup */
391
392     /* header */
393     if (ctx->implicitConfirm && !ossl_cmp_hdr_set_implicitConfirm(msg->header))
394         goto err;
395
396     /* body */
397     if ((resp = OSSL_CMP_CERTRESPONSE_new()) == NULL)
398         goto err;
399     OSSL_CMP_PKISI_free(resp->status);
400     if ((resp->status = OSSL_CMP_PKISI_dup(si)) == NULL
401             || !ASN1_INTEGER_set(resp->certReqId, certReqId))
402         goto err;
403
404     status = ossl_cmp_pkisi_get_status(resp->status);
405     if (status != OSSL_CMP_PKISTATUS_rejection
406             && status != OSSL_CMP_PKISTATUS_waiting && cert != NULL) {
407         if (encrypted) {
408             CMPerr(0, CMP_R_INVALID_ARGS);
409             goto err;
410         }
411
412         if ((resp->certifiedKeyPair = OSSL_CMP_CERTIFIEDKEYPAIR_new())
413             == NULL)
414             goto err;
415         resp->certifiedKeyPair->certOrEncCert->type =
416             OSSL_CMP_CERTORENCCERT_CERTIFICATE;
417         if (!X509_up_ref(cert))
418             goto err;
419         resp->certifiedKeyPair->certOrEncCert->value.certificate = cert;
420     }
421
422     if (!sk_OSSL_CMP_CERTRESPONSE_push(repMsg->response, resp))
423         goto err;
424     resp = NULL;
425     /* TODO: here optional 2nd certrep could be pushed to the stack */
426
427     if (bodytype == OSSL_CMP_PKIBODY_IP && caPubs != NULL
428             && (repMsg->caPubs = X509_chain_up_ref(caPubs)) == NULL)
429         goto err;
430     if (sk_X509_num(chain) > 0) {
431         msg->extraCerts = sk_X509_new_reserve(NULL, sk_X509_num(chain));
432         if (msg->extraCerts == NULL
433             || !ossl_cmp_sk_X509_add1_certs(msg->extraCerts, chain, 0, 1, 0))
434         goto err;
435     }
436
437     if (!unprotectedErrors
438             || ossl_cmp_pkisi_get_status(si) != OSSL_CMP_PKISTATUS_rejection)
439         if (!ossl_cmp_msg_protect(ctx, msg))
440             goto err;
441
442     return msg;
443
444  err:
445     CMPerr(0, CMP_R_ERROR_CREATING_CERTREP);
446     OSSL_CMP_CERTRESPONSE_free(resp);
447     OSSL_CMP_MSG_free(msg);
448     return NULL;
449 }
450
451 OSSL_CMP_MSG *ossl_cmp_rr_new(OSSL_CMP_CTX *ctx)
452 {
453     OSSL_CMP_MSG *msg = NULL;
454     OSSL_CMP_REVDETAILS *rd;
455
456     if (!ossl_assert(ctx != NULL && ctx->oldCert != NULL))
457         return NULL;
458
459     if ((rd = OSSL_CMP_REVDETAILS_new()) == NULL)
460         goto err;
461
462     /* Fill the template from the contents of the certificate to be revoked */
463     if (!OSSL_CRMF_CERTTEMPLATE_fill(rd->certDetails,
464                                      NULL /* pubkey would be redundant */,
465                                      NULL /* subject would be redundant */,
466                                      X509_get_issuer_name(ctx->oldCert),
467                                      X509_get_serialNumber(ctx->oldCert)))
468         goto err;
469
470     /* revocation reason code is optional */
471     if (ctx->revocationReason != CRL_REASON_NONE
472             && !add_crl_reason_extension(&rd->crlEntryDetails,
473                                          ctx->revocationReason))
474         goto err;
475
476     if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_RR)) == NULL)
477         goto err;
478
479     if (!sk_OSSL_CMP_REVDETAILS_push(msg->body->value.rr, rd))
480         goto err;
481     rd = NULL;
482
483     /*
484      * TODO: the Revocation Passphrase according to section 5.3.19.9 could be
485      *       set here if set in ctx
486      */
487
488     if (!ossl_cmp_msg_protect(ctx, msg))
489         goto err;
490
491     return msg;
492
493  err:
494     CMPerr(0, CMP_R_ERROR_CREATING_RR);
495     OSSL_CMP_MSG_free(msg);
496     OSSL_CMP_REVDETAILS_free(rd);
497     return NULL;
498 }
499
500 OSSL_CMP_MSG *ossl_cmp_rp_new(OSSL_CMP_CTX *ctx, OSSL_CMP_PKISI *si,
501                               OSSL_CRMF_CERTID *cid, int unprot_err)
502 {
503     OSSL_CMP_REVREPCONTENT *rep = NULL;
504     OSSL_CMP_PKISI *si1 = NULL;
505     OSSL_CRMF_CERTID *cid_copy = NULL;
506     OSSL_CMP_MSG *msg = NULL;
507
508     if (!ossl_assert(ctx != NULL && si != NULL && cid != NULL))
509         return NULL;
510
511     if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_RP)) == NULL)
512         goto err;
513     rep = msg->body->value.rp;
514
515     if ((si1 = OSSL_CMP_PKISI_dup(si)) == NULL)
516         goto err;
517
518     if (!sk_OSSL_CMP_PKISI_push(rep->status, si1)) {
519         OSSL_CMP_PKISI_free(si1);
520         goto err;
521     }
522
523     if ((rep->revCerts = sk_OSSL_CRMF_CERTID_new_null()) == NULL)
524         goto err;
525     if ((cid_copy = OSSL_CRMF_CERTID_dup(cid)) == NULL)
526         goto err;
527     if (!sk_OSSL_CRMF_CERTID_push(rep->revCerts, cid_copy)) {
528         OSSL_CRMF_CERTID_free(cid_copy);
529         goto err;
530     }
531
532     if (!unprot_err
533             || ossl_cmp_pkisi_get_status(si) != OSSL_CMP_PKISTATUS_rejection)
534         if (!ossl_cmp_msg_protect(ctx, msg))
535             goto err;
536
537     return msg;
538
539  err:
540     CMPerr(0, CMP_R_ERROR_CREATING_RP);
541     OSSL_CMP_MSG_free(msg);
542     return NULL;
543 }
544
545 OSSL_CMP_MSG *ossl_cmp_pkiconf_new(OSSL_CMP_CTX *ctx)
546 {
547     OSSL_CMP_MSG *msg;
548
549     if (!ossl_assert(ctx != NULL))
550         return NULL;
551
552     if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_PKICONF)) == NULL)
553         goto err;
554     if (ossl_cmp_msg_protect(ctx, msg))
555         return msg;
556
557  err:
558     CMPerr(0, CMP_R_ERROR_CREATING_PKICONF);
559     OSSL_CMP_MSG_free(msg);
560     return NULL;
561 }
562
563 int ossl_cmp_msg_gen_push0_ITAV(OSSL_CMP_MSG *msg, OSSL_CMP_ITAV *itav)
564 {
565     int bodytype;
566
567     if (!ossl_assert(msg != NULL && itav != NULL))
568         return 0;
569
570     bodytype = ossl_cmp_msg_get_bodytype(msg);
571     if (bodytype != OSSL_CMP_PKIBODY_GENM
572             && bodytype != OSSL_CMP_PKIBODY_GENP) {
573         CMPerr(0, CMP_R_INVALID_ARGS);
574         return 0;
575     }
576
577     /* value.genp has the same structure, so this works for genp as well */
578     return OSSL_CMP_ITAV_push0_stack_item(&msg->body->value.genm, itav);
579 }
580
581 int ossl_cmp_msg_gen_push1_ITAVs(OSSL_CMP_MSG *msg,
582                                  const STACK_OF(OSSL_CMP_ITAV) *itavs)
583 {
584     int i;
585     OSSL_CMP_ITAV *itav = NULL;
586
587     if (!ossl_assert(msg != NULL))
588         return 0;
589
590     for (i = 0; i < sk_OSSL_CMP_ITAV_num(itavs); i++) {
591         itav = OSSL_CMP_ITAV_dup(sk_OSSL_CMP_ITAV_value(itavs, i));
592         if (itav == NULL
593                 || !ossl_cmp_msg_gen_push0_ITAV(msg, itav)) {
594             OSSL_CMP_ITAV_free(itav);
595             return 0;
596         }
597     }
598     return 1;
599 }
600
601 /*
602  * Creates a new General Message/Response with an empty itav stack
603  * returns a pointer to the PKIMessage on success, NULL on error
604  */
605 static OSSL_CMP_MSG *gen_new(OSSL_CMP_CTX *ctx,
606                              const STACK_OF(OSSL_CMP_ITAV) *itavs,
607                              int body_type, int err_code)
608 {
609     OSSL_CMP_MSG *msg = NULL;
610
611     if (!ossl_assert(ctx != NULL))
612         return NULL;
613
614     if ((msg = ossl_cmp_msg_create(ctx, body_type)) == NULL)
615         return NULL;
616
617     if (ctx->genm_ITAVs != NULL
618             && !ossl_cmp_msg_gen_push1_ITAVs(msg, itavs))
619         goto err;
620
621     if (!ossl_cmp_msg_protect(ctx, msg))
622         goto err;
623
624     return msg;
625
626  err:
627     CMPerr(0, err_code);
628     OSSL_CMP_MSG_free(msg);
629     return NULL;
630 }
631
632 OSSL_CMP_MSG *ossl_cmp_genm_new(OSSL_CMP_CTX *ctx)
633 {
634     return gen_new(ctx, ctx->genm_ITAVs,
635                    OSSL_CMP_PKIBODY_GENM, CMP_R_ERROR_CREATING_GENM);
636 }
637
638 OSSL_CMP_MSG *ossl_cmp_genp_new(OSSL_CMP_CTX *ctx,
639                                 const STACK_OF(OSSL_CMP_ITAV) *itavs)
640 {
641     return gen_new(ctx, itavs,
642                    OSSL_CMP_PKIBODY_GENP, CMP_R_ERROR_CREATING_GENP);
643 }
644
645 OSSL_CMP_MSG *ossl_cmp_error_new(OSSL_CMP_CTX *ctx, OSSL_CMP_PKISI *si,
646                                  int errorCode,
647                                  const char *details, int unprotected)
648 {
649     OSSL_CMP_MSG *msg = NULL;
650     OSSL_CMP_PKIFREETEXT *ft;
651
652     if (!ossl_assert(ctx != NULL && si != NULL))
653         return NULL;
654
655     if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_ERROR)) == NULL)
656         goto err;
657
658     OSSL_CMP_PKISI_free(msg->body->value.error->pKIStatusInfo);
659     if ((msg->body->value.error->pKIStatusInfo = OSSL_CMP_PKISI_dup(si))
660         == NULL)
661         goto err;
662     if (errorCode >= 0) {
663         if ((msg->body->value.error->errorCode = ASN1_INTEGER_new()) == NULL)
664             goto err;
665         if (!ASN1_INTEGER_set(msg->body->value.error->errorCode, errorCode))
666             goto err;
667     }
668     if (details != NULL) {
669         if ((ft = sk_ASN1_UTF8STRING_new_null()) == NULL)
670             goto err;
671         msg->body->value.error->errorDetails = ft;
672         if (!ossl_cmp_sk_ASN1_UTF8STRING_push_str(ft, details))
673             goto err;
674     }
675
676     if (!unprotected && !ossl_cmp_msg_protect(ctx, msg))
677         goto err;
678     return msg;
679
680  err:
681     CMPerr(0, CMP_R_ERROR_CREATING_ERROR);
682     OSSL_CMP_MSG_free(msg);
683     return NULL;
684 }
685
686 /*
687  * Set the certHash field of a OSSL_CMP_CERTSTATUS structure.
688  * This is used in the certConf message, for example,
689  * to confirm that the certificate was received successfully.
690  */
691 int ossl_cmp_certstatus_set0_certHash(OSSL_CMP_CERTSTATUS *certStatus,
692                                       ASN1_OCTET_STRING *hash)
693 {
694     if (!ossl_assert(certStatus != NULL))
695         return 0;
696     ASN1_OCTET_STRING_free(certStatus->certHash);
697     certStatus->certHash = hash;
698     return 1;
699 }
700
701 /*
702  * TODO: handle potential 2nd certificate when signing and encrypting
703  * certificates have been requested/received
704  */
705 OSSL_CMP_MSG *ossl_cmp_certConf_new(OSSL_CMP_CTX *ctx, int fail_info,
706                                     const char *text)
707 {
708     OSSL_CMP_MSG *msg = NULL;
709     OSSL_CMP_CERTSTATUS *certStatus = NULL;
710     ASN1_OCTET_STRING *certHash = NULL;
711     OSSL_CMP_PKISI *sinfo;
712
713     if (!ossl_assert(ctx != NULL && ctx->newCert != NULL))
714         return NULL;
715
716     if ((unsigned)fail_info > OSSL_CMP_PKIFAILUREINFO_MAX_BIT_PATTERN) {
717         CMPerr(0, CMP_R_FAIL_INFO_OUT_OF_RANGE);
718         return NULL;
719     }
720
721     if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_CERTCONF)) == NULL)
722         goto err;
723
724     if ((certStatus = OSSL_CMP_CERTSTATUS_new()) == NULL)
725         goto err;
726     /* consume certStatus into msg right away so it gets deallocated with msg */
727     if (!sk_OSSL_CMP_CERTSTATUS_push(msg->body->value.certConf, certStatus))
728         goto err;
729     /* set the ID of the certReq */
730     if (!ASN1_INTEGER_set(certStatus->certReqId, OSSL_CMP_CERTREQID))
731         goto err;
732     /*
733      * the hash of the certificate, using the same hash algorithm
734      * as is used to create and verify the certificate signature
735      */
736     if ((certHash = X509_digest_sig(ctx->newCert)) == NULL)
737         goto err;
738
739     if (!ossl_cmp_certstatus_set0_certHash(certStatus, certHash))
740         goto err;
741     certHash = NULL;
742     /*
743      * For any particular CertStatus, omission of the statusInfo field
744      * indicates ACCEPTANCE of the specified certificate.  Alternatively,
745      * explicit status details (with respect to acceptance or rejection) MAY
746      * be provided in the statusInfo field, perhaps for auditing purposes at
747      * the CA/RA.
748      */
749     sinfo = fail_info != 0 ?
750         OSSL_CMP_STATUSINFO_new(OSSL_CMP_PKISTATUS_rejection, fail_info, text) :
751         OSSL_CMP_STATUSINFO_new(OSSL_CMP_PKISTATUS_accepted, 0, text);
752     if (sinfo == NULL)
753         goto err;
754     certStatus->statusInfo = sinfo;
755
756     if (!ossl_cmp_msg_protect(ctx, msg))
757         goto err;
758
759     return msg;
760
761  err:
762     CMPerr(0, CMP_R_ERROR_CREATING_CERTCONF);
763     OSSL_CMP_MSG_free(msg);
764     ASN1_OCTET_STRING_free(certHash);
765     return NULL;
766 }
767
768 OSSL_CMP_MSG *ossl_cmp_pollReq_new(OSSL_CMP_CTX *ctx, int crid)
769 {
770     OSSL_CMP_MSG *msg = NULL;
771     OSSL_CMP_POLLREQ *preq = NULL;
772
773     if (!ossl_assert(ctx != NULL))
774         return NULL;
775
776     if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_POLLREQ)) == NULL)
777         goto err;
778
779     /* TODO: support multiple cert request IDs to poll */
780     if ((preq = OSSL_CMP_POLLREQ_new()) == NULL
781             || !ASN1_INTEGER_set(preq->certReqId, crid)
782             || !sk_OSSL_CMP_POLLREQ_push(msg->body->value.pollReq, preq))
783         goto err;
784
785     preq = NULL;
786     if (!ossl_cmp_msg_protect(ctx, msg))
787         goto err;
788
789     return msg;
790
791  err:
792     CMPerr(0, CMP_R_ERROR_CREATING_POLLREQ);
793     OSSL_CMP_POLLREQ_free(preq);
794     OSSL_CMP_MSG_free(msg);
795     return NULL;
796 }
797
798 OSSL_CMP_MSG *ossl_cmp_pollRep_new(OSSL_CMP_CTX *ctx, int crid,
799                                    int64_t poll_after)
800 {
801     OSSL_CMP_MSG *msg;
802     OSSL_CMP_POLLREP *prep;
803
804     if (!ossl_assert(ctx != NULL))
805         return NULL;
806
807     if ((msg = ossl_cmp_msg_create(ctx, OSSL_CMP_PKIBODY_POLLREP)) == NULL)
808         goto err;
809     if ((prep = OSSL_CMP_POLLREP_new()) == NULL)
810         goto err;
811     if (!sk_OSSL_CMP_POLLREP_push(msg->body->value.pollRep, prep))
812         goto err;
813     if (!ASN1_INTEGER_set(prep->certReqId, crid))
814         goto err;
815     if (!ASN1_INTEGER_set_int64(prep->checkAfter, poll_after))
816         goto err;
817
818     if (!ossl_cmp_msg_protect(ctx, msg))
819         goto err;
820     return msg;
821
822  err:
823     CMPerr(0, CMP_R_ERROR_CREATING_POLLREP);
824     OSSL_CMP_MSG_free(msg);
825     return NULL;
826 }
827
828 /*-
829  * returns the status field of the RevRepContent with the given
830  * request/sequence id inside a revocation response.
831  * RevRepContent has the revocation statuses in same order as they were sent in
832  * RevReqContent.
833  * returns NULL on error
834  */
835 OSSL_CMP_PKISI *
836 ossl_cmp_revrepcontent_get_pkisi(OSSL_CMP_REVREPCONTENT *rrep, int rsid)
837 {
838     OSSL_CMP_PKISI *status;
839
840     if (!ossl_assert(rrep != NULL))
841         return NULL;
842
843     if ((status = sk_OSSL_CMP_PKISI_value(rrep->status, rsid)) != NULL)
844         return status;
845
846     CMPerr(0, CMP_R_PKISTATUSINFO_NOT_FOUND);
847     return NULL;
848 }
849
850 /*
851  * returns the CertId field in the revCerts part of the RevRepContent
852  * with the given request/sequence id inside a revocation response.
853  * RevRepContent has the CertIds in same order as they were sent in
854  * RevReqContent.
855  * returns NULL on error
856  */
857 OSSL_CRMF_CERTID *
858 ossl_cmp_revrepcontent_get_CertId(OSSL_CMP_REVREPCONTENT *rrep, int rsid)
859 {
860     OSSL_CRMF_CERTID *cid = NULL;
861
862     if (!ossl_assert(rrep != NULL))
863         return NULL;
864
865     if ((cid = sk_OSSL_CRMF_CERTID_value(rrep->revCerts, rsid)) != NULL)
866         return cid;
867
868     CMPerr(0, CMP_R_CERTID_NOT_FOUND);
869     return NULL;
870 }
871
872 static int suitable_rid(const ASN1_INTEGER *certReqId, int rid)
873 {
874     int trid;
875
876     if (rid == -1)
877         return 1;
878
879     trid = ossl_cmp_asn1_get_int(certReqId);
880
881     if (trid == -1) {
882         CMPerr(0, CMP_R_BAD_REQUEST_ID);
883         return 0;
884     }
885     return rid == trid;
886 }
887
888 static void add_expected_rid(int rid)
889 {
890     char str[DECIMAL_SIZE(rid) + 1];
891
892     BIO_snprintf(str, sizeof(str), "%d", rid);
893     ERR_add_error_data(2, "expected certReqId = ", str);
894 }
895
896 /*
897  * returns a pointer to the PollResponse with the given CertReqId
898  * (or the first one in case -1) inside a PollRepContent
899  * returns NULL on error or if no suitable PollResponse available
900  */
901 OSSL_CMP_POLLREP *
902 ossl_cmp_pollrepcontent_get0_pollrep(const OSSL_CMP_POLLREPCONTENT *prc,
903                                      int rid)
904 {
905     OSSL_CMP_POLLREP *pollRep = NULL;
906     int i;
907
908     if (!ossl_assert(prc != NULL))
909         return NULL;
910
911     for (i = 0; i < sk_OSSL_CMP_POLLREP_num(prc); i++) {
912         pollRep = sk_OSSL_CMP_POLLREP_value(prc, i);
913         if (suitable_rid(pollRep->certReqId, rid))
914             return pollRep;
915     }
916
917     CMPerr(0, CMP_R_CERTRESPONSE_NOT_FOUND);
918     add_expected_rid(rid);
919     return NULL;
920 }
921
922 /*
923  * returns a pointer to the CertResponse with the given CertReqId
924  * (or the first one in case -1) inside a CertRepMessage
925  * returns NULL on error or if no suitable CertResponse available
926  */
927 OSSL_CMP_CERTRESPONSE *
928 ossl_cmp_certrepmessage_get0_certresponse(const OSSL_CMP_CERTREPMESSAGE *crm,
929                                           int rid)
930 {
931     OSSL_CMP_CERTRESPONSE *crep = NULL;
932     int i;
933
934     if (!ossl_assert(crm != NULL && crm->response != NULL))
935         return NULL;
936
937     for (i = 0; i < sk_OSSL_CMP_CERTRESPONSE_num(crm->response); i++) {
938         crep = sk_OSSL_CMP_CERTRESPONSE_value(crm->response, i);
939         if (suitable_rid(crep->certReqId, rid))
940             return crep;
941     }
942
943     CMPerr(0, CMP_R_CERTRESPONSE_NOT_FOUND);
944     add_expected_rid(rid);
945     return NULL;
946 }
947
948 /*
949  * CMP_CERTRESPONSE_get1_certificate() attempts to retrieve the returned
950  * certificate from the given certResponse B<crep>.
951  * Uses the privkey in case of indirect POP from B<ctx>.
952  * Returns a pointer to a copy of the found certificate, or NULL if not found.
953  */
954 X509 *ossl_cmp_certresponse_get1_certificate(EVP_PKEY *privkey,
955                                              const OSSL_CMP_CERTRESPONSE *crep)
956 {
957     OSSL_CMP_CERTORENCCERT *coec;
958     X509 *crt = NULL;
959
960     if (!ossl_assert(crep != NULL))
961         return NULL;
962
963     if (crep->certifiedKeyPair
964             && (coec = crep->certifiedKeyPair->certOrEncCert) != NULL) {
965         switch (coec->type) {
966         case OSSL_CMP_CERTORENCCERT_CERTIFICATE:
967             crt = X509_dup(coec->value.certificate);
968             break;
969         case OSSL_CMP_CERTORENCCERT_ENCRYPTEDCERT:
970             /* cert encrypted for indirect PoP; RFC 4210, 5.2.8.2 */
971             if (privkey == NULL) {
972                 CMPerr(0, CMP_R_MISSING_PRIVATE_KEY);
973                 return NULL;
974             }
975             crt =
976                 OSSL_CRMF_ENCRYPTEDVALUE_get1_encCert(coec->value.encryptedCert,
977                                                       privkey);
978             break;
979         default:
980             CMPerr(0, CMP_R_UNKNOWN_CERT_TYPE);
981             return NULL;
982         }
983     }
984     if (crt == NULL)
985         CMPerr(0, CMP_R_CERTIFICATE_NOT_FOUND);
986     return crt;
987 }
988
989 int OSSL_CMP_MSG_update_transactionID(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg)
990 {
991     if (ctx == NULL || msg == NULL) {
992         CMPerr(0, CMP_R_NULL_ARGUMENT);
993         return 0;
994     }
995     if (!ossl_cmp_hdr_set_transactionID(ctx, msg->header))
996         return 0;
997     return msg->header->protectionAlg == NULL
998             || ossl_cmp_msg_protect(ctx, msg);
999 }
1000
1001 OSSL_CMP_MSG *ossl_cmp_msg_load(const char *file)
1002 {
1003     OSSL_CMP_MSG *msg = NULL;
1004     BIO *bio = NULL;
1005
1006     if (!ossl_assert(file != NULL))
1007         return NULL;
1008
1009     if ((bio = BIO_new_file(file, "rb")) == NULL)
1010         return NULL;
1011     msg = d2i_OSSL_CMP_MSG_bio(bio, NULL);
1012     BIO_free(bio);
1013     return msg;
1014 }
1015
1016 OSSL_CMP_MSG *d2i_OSSL_CMP_MSG_bio(BIO *bio, OSSL_CMP_MSG **msg)
1017 {
1018     return ASN1_d2i_bio_of(OSSL_CMP_MSG, OSSL_CMP_MSG_new,
1019                            d2i_OSSL_CMP_MSG, bio, msg);
1020 }
1021
1022 int i2d_OSSL_CMP_MSG_bio(BIO *bio, const OSSL_CMP_MSG *msg)
1023 {
1024     return ASN1_i2d_bio_of(OSSL_CMP_MSG, i2d_OSSL_CMP_MSG, bio, msg);
1025 }