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