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