Fix safestack issues in asn1.h
[openssl.git] / crypto / cmp / cmp_client.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 #include "cmp_local.h"
13 #include "internal/cryptlib.h"
14
15 /* explicit #includes not strictly needed since implied by the above: */
16 #include <openssl/bio.h>
17 #include <openssl/cmp.h>
18 #include <openssl/err.h>
19 #include <openssl/evp.h>
20 #include <openssl/x509v3.h>
21
22 #include "openssl/cmp_util.h"
23
24 DEFINE_STACK_OF(OSSL_CMP_CERTRESPONSE)
25 DEFINE_STACK_OF(OSSL_CMP_PKISI)
26 DEFINE_STACK_OF(OSSL_CRMF_CERTID)
27
28 #define IS_CREP(t) ((t) == OSSL_CMP_PKIBODY_IP || (t) == OSSL_CMP_PKIBODY_CP \
29                         || (t) == OSSL_CMP_PKIBODY_KUP)
30
31 /*-
32  * Evaluate whether there's an exception (violating the standard) configured for
33  * handling negative responses without protection or with invalid protection.
34  * Returns 1 on acceptance, 0 on rejection, or -1 on (internal) error.
35  */
36 static int unprotected_exception(const OSSL_CMP_CTX *ctx,
37                                  const OSSL_CMP_MSG *rep,
38                                  int invalid_protection,
39                                  int expected_type /* ignored here */)
40 {
41     int rcvd_type = ossl_cmp_msg_get_bodytype(rep /* may be NULL */);
42     const char *msg_type = NULL;
43
44     if (!ossl_assert(ctx != NULL && rep != NULL))
45         return -1;
46
47     if (!ctx->unprotectedErrors)
48         return 0;
49
50     switch (rcvd_type) {
51     case OSSL_CMP_PKIBODY_ERROR:
52         msg_type = "error response";
53         break;
54     case OSSL_CMP_PKIBODY_RP:
55         {
56             OSSL_CMP_PKISI *si =
57                 ossl_cmp_revrepcontent_get_pkisi(rep->body->value.rp,
58                                                  OSSL_CMP_REVREQSID);
59
60             if (si == NULL)
61                 return -1;
62             if (ossl_cmp_pkisi_get_status(si) == OSSL_CMP_PKISTATUS_rejection)
63                 msg_type = "revocation response message with rejection status";
64             break;
65         }
66     case OSSL_CMP_PKIBODY_PKICONF:
67         msg_type = "PKI Confirmation message";
68         break;
69     default:
70         if (IS_CREP(rcvd_type)) {
71             OSSL_CMP_CERTREPMESSAGE *crepmsg = rep->body->value.ip;
72             OSSL_CMP_CERTRESPONSE *crep =
73                 ossl_cmp_certrepmessage_get0_certresponse(crepmsg,
74                                                           -1 /* any rid */);
75
76             if (sk_OSSL_CMP_CERTRESPONSE_num(crepmsg->response) > 1)
77                 return -1;
78             /* TODO: handle potentially multiple CertResponses in CertRepMsg */
79             if (crep == NULL)
80                 return -1;
81             if (ossl_cmp_pkisi_get_status(crep->status)
82                 == OSSL_CMP_PKISTATUS_rejection)
83                 msg_type = "CertRepMessage with rejection status";
84         }
85     }
86     if (msg_type == NULL)
87         return 0;
88     ossl_cmp_log2(WARN, ctx, "ignoring %s protection of %s",
89                   invalid_protection ? "invalid" : "missing", msg_type);
90     return 1;
91 }
92
93
94 /* Save error info from PKIStatusInfo field of a certresponse into ctx */
95 static int save_statusInfo(OSSL_CMP_CTX *ctx, OSSL_CMP_PKISI *si)
96 {
97     int i;
98     OSSL_CMP_PKIFREETEXT *ss;
99
100     if (!ossl_assert(ctx != NULL && si != NULL))
101         return 0;
102
103     if ((ctx->status = ossl_cmp_pkisi_get_status(si)) < 0)
104         return 0;
105
106     ctx->failInfoCode = 0;
107     if (si->failInfo != NULL) {
108         for (i = 0; i <= OSSL_CMP_PKIFAILUREINFO_MAX; i++) {
109             if (ASN1_BIT_STRING_get_bit(si->failInfo, i))
110                 ctx->failInfoCode |= (1 << i);
111         }
112     }
113
114     if (!ossl_cmp_ctx_set0_statusString(ctx, sk_ASN1_UTF8STRING_new_null())
115             || (ctx->statusString == NULL))
116         return 0;
117
118     ss = si->statusString; /* may be NULL */
119     for (i = 0; i < sk_ASN1_UTF8STRING_num(ss); i++) {
120         ASN1_UTF8STRING *str = sk_ASN1_UTF8STRING_value(ss, i);
121
122         if (!sk_ASN1_UTF8STRING_push(ctx->statusString, ASN1_STRING_dup(str)))
123             return 0;
124     }
125     return 1;
126 }
127
128 /*-
129  * Perform the generic aspects of sending a request and receiving a response.
130  * Returns 1 on success and provides the received PKIMESSAGE in *rep.
131  * Returns 0 on error.
132  * Regardless of success, caller is responsible for freeing *rep (unless NULL).
133  */
134 static int send_receive_check(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *req,
135                               OSSL_CMP_MSG **rep, int expected_type)
136 {
137     const char *req_type_str =
138         ossl_cmp_bodytype_to_string(ossl_cmp_msg_get_bodytype(req));
139     const char *expected_type_str = ossl_cmp_bodytype_to_string(expected_type);
140     int msg_timeout;
141     int bt;
142     time_t now = time(NULL);
143     int time_left;
144     OSSL_CMP_transfer_cb_t transfer_cb = ctx->transfer_cb;
145
146     if (transfer_cb == NULL)
147         transfer_cb = OSSL_CMP_MSG_http_perform;
148
149     *rep = NULL;
150     msg_timeout = ctx->msg_timeout; /* backup original value */
151     if ((IS_CREP(expected_type) || expected_type == OSSL_CMP_PKIBODY_POLLREP)
152             && ctx->total_timeout > 0 /* timeout is not infinite */) {
153         if (now >= ctx->end_time) {
154             CMPerr(0, CMP_R_TOTAL_TIMEOUT);
155             return 0;
156         }
157         if (!ossl_assert(ctx->end_time - time(NULL) < INT_MAX)) {
158             /* cannot really happen due to the assignment in do_certreq_seq() */
159             CMPerr(0, CMP_R_INVALID_ARGS);
160             return 0;
161         }
162         time_left = (int)(ctx->end_time - now);
163         if (ctx->msg_timeout == 0 || time_left < ctx->msg_timeout)
164             ctx->msg_timeout = time_left;
165     }
166
167     /* should print error queue since transfer_cb may call ERR_clear_error() */
168     OSSL_CMP_CTX_print_errors(ctx);
169
170     ossl_cmp_log1(INFO, ctx, "sending %s", req_type_str);
171
172     *rep = (*transfer_cb)(ctx, req);
173     ctx->msg_timeout = msg_timeout; /* restore original value */
174
175     if (*rep == NULL) {
176         CMPerr(0, CMP_R_TRANSFER_ERROR); /* or receiving response */
177         ERR_add_error_data(2, "request sent: ", req_type_str);
178         ERR_add_error_data(2, ", expected response: ", expected_type_str);
179         return 0;
180     }
181
182     bt = ossl_cmp_msg_get_bodytype(*rep);
183     /*
184      * The body type in the 'bt' variable is not yet verified.
185      * Still we use this preliminary value already for a progress report because
186      * the following msg verification may also produce log entries and may fail.
187      */
188     ossl_cmp_log1(INFO, ctx, "received %s", ossl_cmp_bodytype_to_string(bt));
189
190     /* copy received extraCerts to ctx->extraCertsIn so they can be retrieved */
191     if (bt != OSSL_CMP_PKIBODY_POLLREP && bt != OSSL_CMP_PKIBODY_PKICONF
192             && !ossl_cmp_ctx_set1_extraCertsIn(ctx, (*rep)->extraCerts))
193         return 0;
194
195     if (!ossl_cmp_msg_check_update(ctx, *rep, unprotected_exception,
196                                    expected_type))
197         return 0;
198
199     if (bt == expected_type
200         /* as an answer to polling, there could be IP/CP/KUP: */
201             || (IS_CREP(bt) && expected_type == OSSL_CMP_PKIBODY_POLLREP))
202         return 1;
203
204     /* received message type is not one of the expected ones (e.g., error) */
205     CMPerr(0, bt == OSSL_CMP_PKIBODY_ERROR ? CMP_R_RECEIVED_ERROR :
206            CMP_R_UNEXPECTED_PKIBODY); /* in next line for mkerr.pl */
207
208     if (bt != OSSL_CMP_PKIBODY_ERROR) {
209         ERR_add_error_data(3, "message type is '",
210                            ossl_cmp_bodytype_to_string(bt), "'");
211     } else {
212         OSSL_CMP_ERRORMSGCONTENT *emc = (*rep)->body->value.error;
213         OSSL_CMP_PKISI *si = emc->pKIStatusInfo;
214         char buf[OSSL_CMP_PKISI_BUFLEN];
215
216         if (save_statusInfo(ctx, si)
217                 && OSSL_CMP_CTX_snprint_PKIStatus(ctx, buf,
218                                                   sizeof(buf)) != NULL)
219             ERR_add_error_data(1, buf);
220         if (emc->errorCode != NULL
221                 && BIO_snprintf(buf, sizeof(buf), "; errorCode: %ld",
222                                 ASN1_INTEGER_get(emc->errorCode)) > 0)
223             ERR_add_error_data(1, buf);
224         if (emc->errorDetails != NULL) {
225             char *text = sk_ASN1_UTF8STRING2text(emc->errorDetails, ", ",
226                                                  OSSL_CMP_PKISI_BUFLEN - 1);
227
228             if (text != NULL)
229                 ERR_add_error_data(2, "; errorDetails: ", text);
230             OPENSSL_free(text);
231         }
232         if (ctx->status != OSSL_CMP_PKISTATUS_rejection) {
233             CMPerr(0, CMP_R_UNEXPECTED_PKISTATUS);
234             if (ctx->status == OSSL_CMP_PKISTATUS_waiting)
235                 ctx->status = OSSL_CMP_PKISTATUS_rejection;
236         }
237     }
238     return 0;
239 }
240
241 /*-
242  * When a 'waiting' PKIStatus has been received, this function is used to
243  * poll, which should yield a pollRep or finally a CertRepMessage in ip/cp/kup.
244  * On receiving a pollRep, which includes a checkAfter value, it return this
245  * value if sleep == 0, else it sleeps as long as indicated and retries.
246  *
247  * A transaction timeout is enabled if ctx->total_timeout is > 0.
248  * In this case polling will continue until the timeout is reached and then
249  * polling is done a last time even if this is before the "checkAfter" time.
250  *
251  * Returns -1 on receiving pollRep if sleep == 0, setting the checkAfter value.
252  * Returns 1 on success and provides the received PKIMESSAGE in *rep.
253  *           In this case the caller is responsible for freeing *rep.
254  * Returns 0 on error (which includes the case that timeout has been reached).
255  */
256 static int poll_for_response(OSSL_CMP_CTX *ctx, int sleep, int rid,
257                              OSSL_CMP_MSG **rep, int *checkAfter)
258 {
259     OSSL_CMP_MSG *preq = NULL;
260     OSSL_CMP_MSG *prep = NULL;
261
262     ossl_cmp_info(ctx,
263                   "received 'waiting' PKIStatus, starting to poll for response");
264     *rep = NULL;
265     for (;;) {
266         /* TODO: handle potentially multiple poll requests per message */
267         if ((preq = ossl_cmp_pollReq_new(ctx, rid)) == NULL)
268             goto err;
269
270         if (!send_receive_check(ctx, preq, &prep, OSSL_CMP_PKIBODY_POLLREP))
271             goto err;
272
273         /* handle potential pollRep */
274         if (ossl_cmp_msg_get_bodytype(prep) == OSSL_CMP_PKIBODY_POLLREP) {
275             OSSL_CMP_POLLREPCONTENT *prc = prep->body->value.pollRep;
276             OSSL_CMP_POLLREP *pollRep = NULL;
277             int64_t check_after;
278             char str[OSSL_CMP_PKISI_BUFLEN];
279             int len;
280
281             /* TODO: handle potentially multiple elements in pollRep */
282             if (sk_OSSL_CMP_POLLREP_num(prc) > 1) {
283                 CMPerr(0, CMP_R_MULTIPLE_RESPONSES_NOT_SUPPORTED);
284                 goto err;
285             }
286             pollRep = ossl_cmp_pollrepcontent_get0_pollrep(prc, rid);
287             if (pollRep == NULL)
288                 goto err;
289
290             if (!ASN1_INTEGER_get_int64(&check_after, pollRep->checkAfter)) {
291                 CMPerr(0, CMP_R_BAD_CHECKAFTER_IN_POLLREP);
292                 goto err;
293             }
294             if (check_after < 0 || (uint64_t)check_after
295                 > (sleep ? ULONG_MAX / 1000 : INT_MAX)) {
296                 CMPerr(0, CMP_R_CHECKAFTER_OUT_OF_RANGE);
297                 if (BIO_snprintf(str, OSSL_CMP_PKISI_BUFLEN, "value = %jd",
298                                  check_after) >= 0)
299                     ERR_add_error_data(1, str);
300                 goto err;
301             }
302             if (ctx->total_timeout > 0) { /* timeout is not infinite */
303                 const int exp = 5; /* expected max time per msg round trip */
304                 int64_t time_left = (int64_t)(ctx->end_time - exp - time(NULL));
305
306                 if (time_left <= 0) {
307                     CMPerr(0, CMP_R_TOTAL_TIMEOUT);
308                     goto err;
309                 }
310                 if (time_left < check_after)
311                     check_after = time_left;
312                 /* poll one last time just when timeout was reached */
313             }
314
315             if (pollRep->reason == NULL
316                     || (len = BIO_snprintf(str, OSSL_CMP_PKISI_BUFLEN,
317                                            " with reason = '")) < 0) {
318                 *str = '\0';
319             } else {
320                 char *text = sk_ASN1_UTF8STRING2text(pollRep->reason, ", ",
321                                                      sizeof(str) - len - 2);
322
323                 if (text == NULL
324                         || BIO_snprintf(str + len, sizeof(str) - len,
325                                         "%s'", text) < 0)
326                     *str = '\0';
327                 OPENSSL_free(text);
328             }
329             ossl_cmp_log2(INFO, ctx,
330                           "received polling response%s; checkAfter = %ld seconds",
331                           str, check_after);
332
333             OSSL_CMP_MSG_free(preq);
334             preq = NULL;
335             OSSL_CMP_MSG_free(prep);
336             prep = NULL;
337             if (sleep) {
338                 ossl_sleep((unsigned long)(1000 * check_after));
339             } else {
340                 if (checkAfter != NULL)
341                     *checkAfter = (int)check_after;
342                 return -1; /* exits the loop */
343             }
344         } else {
345             ossl_cmp_info(ctx, "received ip/cp/kup after polling");
346             /* any other body type has been rejected by send_receive_check() */
347             break;
348         }
349     }
350     if (prep == NULL)
351         goto err;
352
353     OSSL_CMP_MSG_free(preq);
354     *rep = prep;
355
356     return 1;
357  err:
358     OSSL_CMP_MSG_free(preq);
359     OSSL_CMP_MSG_free(prep);
360     return 0;
361 }
362
363 /* Send certConf for IR, CR or KUR sequences and check response */
364 int ossl_cmp_exchange_certConf(OSSL_CMP_CTX *ctx, int fail_info,
365                                const char *txt)
366 {
367     OSSL_CMP_MSG *certConf;
368     OSSL_CMP_MSG *PKIconf = NULL;
369     int res = 0;
370
371     /* OSSL_CMP_certConf_new() also checks if all necessary options are set */
372     if ((certConf = ossl_cmp_certConf_new(ctx, fail_info, txt)) == NULL)
373         goto err;
374
375     res = send_receive_check(ctx, certConf, &PKIconf, OSSL_CMP_PKIBODY_PKICONF);
376
377  err:
378     OSSL_CMP_MSG_free(certConf);
379     OSSL_CMP_MSG_free(PKIconf);
380     return res;
381 }
382
383 /* Send given error and check response */
384 int ossl_cmp_exchange_error(OSSL_CMP_CTX *ctx, int status, int fail_info,
385                             const char *txt, int errorCode, const char *details)
386 {
387     OSSL_CMP_MSG *error = NULL;
388     OSSL_CMP_PKISI *si = NULL;
389     OSSL_CMP_MSG *PKIconf = NULL;
390     int res = 0;
391
392     if ((si = OSSL_CMP_STATUSINFO_new(status, fail_info, txt)) == NULL)
393         goto err;
394     /* ossl_cmp_error_new() also checks if all necessary options are set */
395     if ((error = ossl_cmp_error_new(ctx, si, errorCode, details, 0)) == NULL)
396         goto err;
397
398     res = send_receive_check(ctx, error, &PKIconf, OSSL_CMP_PKIBODY_PKICONF);
399
400  err:
401     OSSL_CMP_MSG_free(error);
402     OSSL_CMP_PKISI_free(si);
403     OSSL_CMP_MSG_free(PKIconf);
404     return res;
405 }
406
407 /*-
408  * Retrieve a copy of the certificate, if any, from the given CertResponse.
409  * Take into account PKIStatusInfo of CertResponse in ctx, report it on error.
410  * Returns NULL if not found or on error.
411  */
412 static X509 *get1_cert_status(OSSL_CMP_CTX *ctx, int bodytype,
413                               OSSL_CMP_CERTRESPONSE *crep)
414 {
415     char buf[OSSL_CMP_PKISI_BUFLEN];
416     X509 *crt = NULL;
417     EVP_PKEY *privkey;
418
419     if (!ossl_assert(ctx != NULL && crep != NULL))
420         return NULL;
421
422     privkey = OSSL_CMP_CTX_get0_newPkey(ctx, 1);
423     switch (ossl_cmp_pkisi_get_status(crep->status)) {
424     case OSSL_CMP_PKISTATUS_waiting:
425         ossl_cmp_err(ctx,
426                      "received \"waiting\" status for cert when actually aiming to extract cert");
427         CMPerr(0, CMP_R_ENCOUNTERED_WAITING);
428         goto err;
429     case OSSL_CMP_PKISTATUS_grantedWithMods:
430         ossl_cmp_warn(ctx, "received \"grantedWithMods\" for certificate");
431         break;
432     case OSSL_CMP_PKISTATUS_accepted:
433         break;
434         /* get all information in case of a rejection before going to error */
435     case OSSL_CMP_PKISTATUS_rejection:
436         ossl_cmp_err(ctx, "received \"rejection\" status rather than cert");
437         CMPerr(0, CMP_R_REQUEST_REJECTED_BY_SERVER);
438         goto err;
439     case OSSL_CMP_PKISTATUS_revocationWarning:
440         ossl_cmp_warn(ctx,
441                       "received \"revocationWarning\" - a revocation of the cert is imminent");
442         break;
443     case OSSL_CMP_PKISTATUS_revocationNotification:
444         ossl_cmp_warn(ctx,
445                       "received \"revocationNotification\" - a revocation of the cert has occurred");
446         break;
447     case OSSL_CMP_PKISTATUS_keyUpdateWarning:
448         if (bodytype != OSSL_CMP_PKIBODY_KUR) {
449             CMPerr(0, CMP_R_ENCOUNTERED_KEYUPDATEWARNING);
450             goto err;
451         }
452         break;
453     default:
454         ossl_cmp_log1(ERROR, ctx,
455                       "received unsupported PKIStatus %d for certificate",
456                       ctx->status);
457         CMPerr(0, CMP_R_UNKNOWN_PKISTATUS);
458         goto err;
459     }
460     crt = ossl_cmp_certresponse_get1_cert(crep, ctx, privkey);
461     if (crt == NULL) /* according to PKIStatus, we can expect a cert */
462         CMPerr(0, CMP_R_CERTIFICATE_NOT_FOUND);
463
464     return crt;
465
466  err:
467     if (OSSL_CMP_CTX_snprint_PKIStatus(ctx, buf, sizeof(buf)) != NULL)
468         ERR_add_error_data(1, buf);
469     return NULL;
470 }
471
472 /*-
473  * Callback fn validating that the new certificate can be verified, using
474  * ctx->certConf_cb_arg, which has been initialized using opt_out_trusted, and
475  * ctx->untrusted, which at this point already contains msg->extraCerts.
476  * Returns 0 on acceptance, else a bit field reflecting PKIFailureInfo.
477  * Quoting from RFC 4210 section 5.1. Overall PKI Message:
478  *     The extraCerts field can contain certificates that may be useful to
479  *     the recipient.  For example, this can be used by a CA or RA to
480  *     present an end entity with certificates that it needs to verify its
481  *     own new certificate (if, for example, the CA that issued the end
482  *     entity's certificate is not a root CA for the end entity).  Note that
483  *     this field does not necessarily contain a certification path; the
484  *     recipient may have to sort, select from, or otherwise process the
485  *     extra certificates in order to use them.
486  * Note: While often handy, there is no hard requirement by CMP that
487  * an EE must be able to validate the certificates it gets enrolled.
488  */
489 int OSSL_CMP_certConf_cb(OSSL_CMP_CTX *ctx, X509 *cert, int fail_info,
490                          const char **text)
491 {
492     X509_STORE *out_trusted = OSSL_CMP_CTX_get_certConf_cb_arg(ctx);
493     STACK_OF(X509) *chain = NULL;
494     (void)text; /* make (artificial) use of var to prevent compiler warning */
495
496     if (fail_info != 0) /* accept any error flagged by CMP core library */
497         return fail_info;
498
499     ossl_cmp_debug(ctx, "trying to build chain for newly enrolled cert");
500     chain = ossl_cmp_build_cert_chain(ctx->libctx, ctx->propq,
501                                       out_trusted /* may be NULL */,
502                                       ctx->untrusted, cert);
503     if (sk_X509_num(chain) > 0)
504         X509_free(sk_X509_shift(chain)); /* remove leaf (EE) cert */
505     if (out_trusted != NULL) {
506         if (chain == NULL) {
507             ossl_cmp_err(ctx, "failed building chain for newly enrolled cert");
508             fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_incorrectData;
509         } else {
510             ossl_cmp_debug(ctx,
511                            "succeeded building proper chain for newly enrolled cert");
512         }
513     } else if (chain == NULL) {
514         ossl_cmp_warn(ctx, "could not build approximate chain for newly enrolled cert, resorting to received extraCerts");
515         chain = OSSL_CMP_CTX_get1_extraCertsIn(ctx);
516     } else {
517         ossl_cmp_debug(ctx,
518                        "success building approximate chain for newly enrolled cert");
519     }
520     (void)ossl_cmp_ctx_set1_newChain(ctx, chain);
521     sk_X509_pop_free(chain, X509_free);
522
523     return fail_info;
524 }
525
526 /*-
527  * Perform the generic handling of certificate responses for IR/CR/KUR/P10CR.
528  * Returns -1 on receiving pollRep if sleep == 0, setting the checkAfter value.
529  * Returns 1 on success and provides the received PKIMESSAGE in *resp.
530  * Returns 0 on error (which includes the case that timeout has been reached).
531  * Regardless of success, caller is responsible for freeing *resp (unless NULL).
532  */
533 static int cert_response(OSSL_CMP_CTX *ctx, int sleep, int rid,
534                          OSSL_CMP_MSG **resp, int *checkAfter,
535                          int req_type, int expected_type)
536 {
537     EVP_PKEY *rkey = OSSL_CMP_CTX_get0_newPkey(ctx /* may be NULL */, 0);
538     int fail_info = 0; /* no failure */
539     const char *txt = NULL;
540     OSSL_CMP_CERTREPMESSAGE *crepmsg;
541     OSSL_CMP_CERTRESPONSE *crep;
542     OSSL_CMP_certConf_cb_t cb;
543     X509 *cert;
544     char *subj = NULL;
545     int ret = 1;
546
547     if (!ossl_assert(ctx != NULL))
548         return 0;
549
550  retry:
551     crepmsg = (*resp)->body->value.ip; /* same for cp and kup */
552     if (sk_OSSL_CMP_CERTRESPONSE_num(crepmsg->response) > 1) {
553         CMPerr(0, CMP_R_MULTIPLE_RESPONSES_NOT_SUPPORTED);
554         return 0;
555     }
556     /* TODO: handle potentially multiple CertResponses in CertRepMsg */
557     crep = ossl_cmp_certrepmessage_get0_certresponse(crepmsg, rid);
558     if (crep == NULL)
559         return 0;
560     if (!save_statusInfo(ctx, crep->status))
561         return 0;
562     if (rid == -1) {
563         /* for OSSL_CMP_PKIBODY_P10CR learn CertReqId from response */
564         rid = ossl_cmp_asn1_get_int(crep->certReqId);
565         if (rid == -1) {
566             CMPerr(0, CMP_R_BAD_REQUEST_ID);
567             return 0;
568         }
569     }
570
571     if (ossl_cmp_pkisi_get_status(crep->status) == OSSL_CMP_PKISTATUS_waiting) {
572         OSSL_CMP_MSG_free(*resp);
573         *resp = NULL;
574         if ((ret = poll_for_response(ctx, sleep, rid, resp, checkAfter)) != 0) {
575             if (ret == -1) /* at this point implies sleep == 0 */
576                 return ret; /* waiting */
577             goto retry; /* got ip/cp/kup, which may still indicate 'waiting' */
578         } else {
579             CMPerr(0, CMP_R_POLLING_FAILED);
580             return 0;
581         }
582     }
583
584     cert = get1_cert_status(ctx, (*resp)->body->type, crep);
585     if (cert == NULL) {
586         ERR_add_error_data(1, "; cannot extract certificate from response");
587         return 0;
588     }
589     if (!ossl_cmp_ctx_set0_newCert(ctx, cert))
590         return 0;
591
592     /*
593      * if the CMP server returned certificates in the caPubs field, copy them
594      * to the context so that they can be retrieved if necessary
595      */
596     if (crepmsg->caPubs != NULL
597             && !ossl_cmp_ctx_set1_caPubs(ctx, crepmsg->caPubs))
598         return 0;
599
600     subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
601     if (rkey != NULL
602         /* X509_check_private_key() also works if rkey is just public key */
603             && !(X509_check_private_key(ctx->newCert, rkey))) {
604         fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_incorrectData;
605         txt = "public key in new certificate does not match our enrollment key";
606         /*-
607          * not calling (void)ossl_cmp_exchange_error(ctx,
608          *                   OSSL_CMP_PKISTATUS_rejection, fail_info, txt)
609          * not throwing CMP_R_CERTIFICATE_NOT_ACCEPTED with txt
610          * not returning 0
611          * since we better leave this for the certConf_cb to decide
612          */
613     }
614
615     /*
616      * Execute the certification checking callback function,
617      * which can determine whether to accept a newly enrolled certificate.
618      * It may overrule the pre-decision reflected in 'fail_info' and '*txt'.
619      */
620     cb = ctx->certConf_cb != NULL ? ctx->certConf_cb : OSSL_CMP_certConf_cb;
621     if ((fail_info = cb(ctx, ctx->newCert, fail_info, &txt)) != 0
622             && txt == NULL)
623         txt = "CMP client did not accept it";
624     if (fail_info != 0) /* immediately log error before any certConf exchange */
625         ossl_cmp_log1(ERROR, ctx,
626                       "rejecting newly enrolled cert with subject: %s", subj);
627
628     /*
629      * TODO: better move certConf exchange to do_certreq_seq() such that
630      * also more low-level errors with CertReqMessages get reported to server
631      */
632     if (!ctx->disableConfirm
633             && !ossl_cmp_hdr_has_implicitConfirm((*resp)->header)) {
634         if (!ossl_cmp_exchange_certConf(ctx, fail_info, txt))
635             ret = 0;
636     }
637
638     /* not throwing failure earlier as transfer_cb may call ERR_clear_error() */
639     if (fail_info != 0) {
640         CMPerr(0, CMP_R_CERTIFICATE_NOT_ACCEPTED);
641         ERR_add_error_data(2, "rejecting newly enrolled cert with subject: ",
642                            subj);
643         if (txt != NULL)
644             ERR_add_error_txt("; ", txt);
645         ret = 0;
646     }
647     OPENSSL_free(subj);
648     return ret;
649 }
650
651 int OSSL_CMP_try_certreq(OSSL_CMP_CTX *ctx, int req_type,
652                          const OSSL_CRMF_MSG *crm, int *checkAfter)
653 {
654     OSSL_CMP_MSG *req = NULL;
655     OSSL_CMP_MSG *rep = NULL;
656     int is_p10 = req_type == OSSL_CMP_PKIBODY_P10CR;
657     int rid = is_p10 ? -1 : OSSL_CMP_CERTREQID;
658     int rep_type = is_p10 ? OSSL_CMP_PKIBODY_CP : req_type + 1;
659     int res = 0;
660
661     if (ctx == NULL) {
662         CMPerr(0, CMP_R_NULL_ARGUMENT);
663         return 0;
664     }
665
666     if (ctx->status != OSSL_CMP_PKISTATUS_waiting) { /* not polling already */
667         ctx->status = -1;
668         if (!ossl_cmp_ctx_set0_newCert(ctx, NULL))
669             return 0;
670
671         if (ctx->total_timeout > 0) /* else ctx->end_time is not used */
672             ctx->end_time = time(NULL) + ctx->total_timeout;
673
674         req = ossl_cmp_certreq_new(ctx, req_type, crm);
675         if (req == NULL) /* also checks if all necessary options are set */
676             return 0;
677
678         if (!send_receive_check(ctx, req, &rep, rep_type))
679             goto err;
680     } else {
681         if (req_type < 0)
682             return ossl_cmp_exchange_error(ctx, OSSL_CMP_PKISTATUS_rejection,
683                                            0 /* TODO better fail_info value? */,
684                                            "polling aborted", 0 /* errorCode */,
685                                            "by application");
686         res = poll_for_response(ctx, 0 /* no sleep */, rid, &rep, checkAfter);
687         if (res <= 0) /* waiting or error */
688             return res;
689     }
690     res = cert_response(ctx, 0 /* no sleep */, rid, &rep, checkAfter,
691                         req_type, rep_type);
692
693  err:
694     OSSL_CMP_MSG_free(req);
695     OSSL_CMP_MSG_free(rep);
696     return res;
697 }
698
699 /*-
700  * Do the full sequence CR/IR/KUR/P10CR, CP/IP/KUP/CP,
701  * certConf, PKIconf, and polling if required.
702  * Will sleep as long as indicated by the server (according to checkAfter).
703  * All enrollment options need to be present in the context.
704  * TODO: another function to request two certificates at once should be created.
705  * Returns pointer to received certificate, or NULL if none was received.
706  */
707 X509 *OSSL_CMP_exec_certreq(OSSL_CMP_CTX *ctx, int req_type,
708                             const OSSL_CRMF_MSG *crm)
709 {
710
711     OSSL_CMP_MSG *req = NULL;
712     OSSL_CMP_MSG *rep = NULL;
713     int is_p10 = req_type == OSSL_CMP_PKIBODY_P10CR;
714     int rid = is_p10 ? -1 : OSSL_CMP_CERTREQID;
715     int rep_type = is_p10 ? OSSL_CMP_PKIBODY_CP : req_type + 1;
716     X509 *result = NULL;
717
718     if (ctx == NULL) {
719         CMPerr(0, CMP_R_NULL_ARGUMENT);
720         return NULL;
721     }
722     if (is_p10 && crm != NULL) {
723         CMPerr(0, CMP_R_INVALID_ARGS);
724         return NULL;
725     }
726
727     ctx->status = -1;
728     if (!ossl_cmp_ctx_set0_newCert(ctx, NULL))
729         return NULL;
730
731     if (ctx->total_timeout > 0) /* else ctx->end_time is not used */
732         ctx->end_time = time(NULL) + ctx->total_timeout;
733
734     /* OSSL_CMP_certreq_new() also checks if all necessary options are set */
735     if ((req = ossl_cmp_certreq_new(ctx, req_type, crm)) == NULL)
736         goto err;
737
738     if (!send_receive_check(ctx, req, &rep, rep_type))
739         goto err;
740
741     if (cert_response(ctx, 1 /* sleep */, rid, &rep, NULL, req_type, rep_type)
742         <= 0)
743         goto err;
744
745     result = ctx->newCert;
746  err:
747     OSSL_CMP_MSG_free(req);
748     OSSL_CMP_MSG_free(rep);
749     return result;
750 }
751
752 X509 *OSSL_CMP_exec_RR_ses(OSSL_CMP_CTX *ctx)
753 {
754     OSSL_CMP_MSG *rr = NULL;
755     OSSL_CMP_MSG *rp = NULL;
756     const int num_RevDetails = 1;
757     const int rsid = OSSL_CMP_REVREQSID;
758     OSSL_CMP_REVREPCONTENT *rrep = NULL;
759     OSSL_CMP_PKISI *si = NULL;
760     char buf[OSSL_CMP_PKISI_BUFLEN];
761     X509 *result = NULL;
762
763     if (ctx == NULL) {
764         CMPerr(0, CMP_R_INVALID_ARGS);
765         return 0;
766     }
767     if (ctx->oldCert == NULL) {
768         CMPerr(0, CMP_R_MISSING_REFERENCE_CERT);
769         return 0;
770     }
771     ctx->status = -1;
772
773     /* OSSL_CMP_rr_new() also checks if all necessary options are set */
774     if ((rr = ossl_cmp_rr_new(ctx)) == NULL)
775         goto end;
776
777     if (!send_receive_check(ctx, rr, &rp, OSSL_CMP_PKIBODY_RP))
778         goto end;
779
780     rrep = rp->body->value.rp;
781 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
782     if (sk_OSSL_CMP_PKISI_num(rrep->status) != num_RevDetails) {
783         CMPerr(0, CMP_R_WRONG_RP_COMPONENT_COUNT);
784         goto end;
785     }
786 #else
787     if (sk_OSSL_CMP_PKISI_num(rrep->status) < 1) {
788         CMPerr(0, CMP_R_WRONG_RP_COMPONENT_COUNT);
789         goto end;
790     }
791 #endif
792
793     /* evaluate PKIStatus field */
794     si = ossl_cmp_revrepcontent_get_pkisi(rrep, rsid);
795     if (!save_statusInfo(ctx, si))
796         goto err;
797     switch (ossl_cmp_pkisi_get_status(si)) {
798     case OSSL_CMP_PKISTATUS_accepted:
799         ossl_cmp_info(ctx, "revocation accepted (PKIStatus=accepted)");
800         result = ctx->oldCert;
801         break;
802     case OSSL_CMP_PKISTATUS_grantedWithMods:
803         ossl_cmp_info(ctx, "revocation accepted (PKIStatus=grantedWithMods)");
804         result = ctx->oldCert;
805         break;
806     case OSSL_CMP_PKISTATUS_rejection:
807         CMPerr(0, CMP_R_REQUEST_REJECTED_BY_SERVER);
808         goto err;
809     case OSSL_CMP_PKISTATUS_revocationWarning:
810         ossl_cmp_info(ctx, "revocation accepted (PKIStatus=revocationWarning)");
811         result = ctx->oldCert;
812         break;
813     case OSSL_CMP_PKISTATUS_revocationNotification:
814         /* interpretation as warning or error depends on CA */
815         ossl_cmp_warn(ctx,
816                       "revocation accepted (PKIStatus=revocationNotification)");
817         result = ctx->oldCert;
818         break;
819     case OSSL_CMP_PKISTATUS_waiting:
820     case OSSL_CMP_PKISTATUS_keyUpdateWarning:
821         CMPerr(0, CMP_R_UNEXPECTED_PKISTATUS);
822         goto err;
823     default:
824         CMPerr(0, CMP_R_UNKNOWN_PKISTATUS);
825         goto err;
826     }
827
828     /* check any present CertId in optional revCerts field */
829     if (rrep->revCerts != NULL) {
830         OSSL_CRMF_CERTID *cid;
831         OSSL_CRMF_CERTTEMPLATE *tmpl =
832             sk_OSSL_CMP_REVDETAILS_value(rr->body->value.rr, rsid)->certDetails;
833         const X509_NAME *issuer = OSSL_CRMF_CERTTEMPLATE_get0_issuer(tmpl);
834         ASN1_INTEGER *serial = OSSL_CRMF_CERTTEMPLATE_get0_serialNumber(tmpl);
835
836         if (sk_OSSL_CRMF_CERTID_num(rrep->revCerts) != num_RevDetails) {
837             CMPerr(0, CMP_R_WRONG_RP_COMPONENT_COUNT);
838             result = NULL;
839             goto err;
840         }
841         if ((cid = ossl_cmp_revrepcontent_get_CertId(rrep, rsid)) == NULL) {
842             result = NULL;
843             goto err;
844         }
845         if (X509_NAME_cmp(issuer, OSSL_CRMF_CERTID_get0_issuer(cid)) != 0) {
846 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
847             CMPerr(0, CMP_R_WRONG_CERTID_IN_RP);
848             result = NULL;
849             goto err;
850 #endif
851         }
852         if (ASN1_INTEGER_cmp(serial,
853                              OSSL_CRMF_CERTID_get0_serialNumber(cid)) != 0) {
854 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
855             CMPerr(0, CMP_R_WRONG_SERIAL_IN_RP);
856             result = NULL;
857             goto err;
858 #endif
859         }
860     }
861
862     /* check number of any optionally present crls */
863     if (rrep->crls != NULL && sk_X509_CRL_num(rrep->crls) != num_RevDetails) {
864         CMPerr(0, CMP_R_WRONG_RP_COMPONENT_COUNT);
865         result = NULL;
866         goto err;
867     }
868
869  err:
870     if (result == NULL
871             && OSSL_CMP_CTX_snprint_PKIStatus(ctx, buf, sizeof(buf)) != NULL)
872         ERR_add_error_data(1, buf);
873
874  end:
875     OSSL_CMP_MSG_free(rr);
876     OSSL_CMP_MSG_free(rp);
877     return result;
878 }
879
880 STACK_OF(OSSL_CMP_ITAV) *OSSL_CMP_exec_GENM_ses(OSSL_CMP_CTX *ctx)
881 {
882     OSSL_CMP_MSG *genm;
883     OSSL_CMP_MSG *genp = NULL;
884     STACK_OF(OSSL_CMP_ITAV) *rcvd_itavs = NULL;
885
886     if (ctx == NULL) {
887         CMPerr(0, CMP_R_INVALID_ARGS);
888         return 0;
889     }
890
891     if ((genm = ossl_cmp_genm_new(ctx)) == NULL)
892         goto err;
893
894     if (!send_receive_check(ctx, genm, &genp, OSSL_CMP_PKIBODY_GENP))
895         goto err;
896
897     /* received stack of itavs not to be freed with the genp */
898     rcvd_itavs = genp->body->value.genp;
899     genp->body->value.genp = NULL;
900
901  err:
902     OSSL_CMP_MSG_free(genm);
903     OSSL_CMP_MSG_free(genp);
904
905     return rcvd_itavs; /* recv_itavs == NULL indicates an error */
906 }