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