A local copy of OpenSSL from GitHub
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

897 lines
32 KiB

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