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