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