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