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