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