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