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