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