cmp_vfy.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. /*
  2. * Copyright 2007-2024 The OpenSSL Project Authors. All Rights Reserved.
  3. * Copyright Nokia 2007-2020
  4. * Copyright Siemens AG 2015-2020
  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. /* CMP functions for PKIMessage checking */
  12. #include "cmp_local.h"
  13. #include <openssl/cmp_util.h>
  14. /* explicit #includes not strictly needed since implied by the above: */
  15. #include <openssl/asn1t.h>
  16. #include <openssl/cmp.h>
  17. #include <openssl/crmf.h>
  18. #include <openssl/err.h>
  19. #include <openssl/x509.h>
  20. /* Verify a message protected by signature according to RFC section 5.1.3.3 */
  21. static int verify_signature(const OSSL_CMP_CTX *cmp_ctx,
  22. const OSSL_CMP_MSG *msg, X509 *cert)
  23. {
  24. OSSL_CMP_PROTECTEDPART prot_part;
  25. EVP_PKEY *pubkey = NULL;
  26. BIO *bio;
  27. int res = 0;
  28. if (!ossl_assert(cmp_ctx != NULL && msg != NULL && cert != NULL))
  29. return 0;
  30. bio = BIO_new(BIO_s_mem()); /* may be NULL */
  31. if (bio == NULL)
  32. return 0;
  33. /* verify that keyUsage, if present, contains digitalSignature */
  34. if (!cmp_ctx->ignore_keyusage
  35. && (X509_get_key_usage(cert) & X509v3_KU_DIGITAL_SIGNATURE) == 0) {
  36. ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_KEY_USAGE_DIGITALSIGNATURE);
  37. goto sig_err;
  38. }
  39. pubkey = X509_get_pubkey(cert);
  40. if (pubkey == NULL) {
  41. ERR_raise(ERR_LIB_CMP, CMP_R_FAILED_EXTRACTING_PUBKEY);
  42. goto sig_err;
  43. }
  44. prot_part.header = msg->header;
  45. prot_part.body = msg->body;
  46. if (ASN1_item_verify_ex(ASN1_ITEM_rptr(OSSL_CMP_PROTECTEDPART),
  47. msg->header->protectionAlg, msg->protection,
  48. &prot_part, NULL, pubkey, cmp_ctx->libctx,
  49. cmp_ctx->propq) > 0) {
  50. res = 1;
  51. goto end;
  52. }
  53. sig_err:
  54. res = ossl_x509_print_ex_brief(bio, cert, X509_FLAG_NO_EXTENSIONS);
  55. ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_SIGNATURE);
  56. if (res)
  57. ERR_add_error_mem_bio("\n", bio);
  58. res = 0;
  59. end:
  60. EVP_PKEY_free(pubkey);
  61. BIO_free(bio);
  62. return res;
  63. }
  64. /* Verify a message protected with PBMAC */
  65. static int verify_PBMAC(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
  66. {
  67. ASN1_BIT_STRING *protection = NULL;
  68. int valid = 0;
  69. /* generate expected protection for the message */
  70. if ((protection = ossl_cmp_calc_protection(ctx, msg)) == NULL)
  71. return 0; /* failed to generate protection string! */
  72. valid = msg->protection != NULL && msg->protection->length >= 0
  73. && msg->protection->type == protection->type
  74. && msg->protection->length == protection->length
  75. && CRYPTO_memcmp(msg->protection->data, protection->data,
  76. protection->length) == 0;
  77. ASN1_BIT_STRING_free(protection);
  78. if (!valid)
  79. ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_PBM_VALUE);
  80. return valid;
  81. }
  82. /*-
  83. * Attempt to validate certificate and path using any given store with trusted
  84. * certs (possibly including CRLs and a cert verification callback function)
  85. * and non-trusted intermediate certs from the given ctx.
  86. *
  87. * Returns 1 on successful validation and 0 otherwise.
  88. */
  89. int OSSL_CMP_validate_cert_path(const OSSL_CMP_CTX *ctx,
  90. X509_STORE *trusted_store, X509 *cert)
  91. {
  92. int valid = 0;
  93. X509_STORE_CTX *csc = NULL;
  94. int err;
  95. if (ctx == NULL || cert == NULL) {
  96. ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
  97. return 0;
  98. }
  99. if (trusted_store == NULL) {
  100. ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_STORE);
  101. return 0;
  102. }
  103. if ((csc = X509_STORE_CTX_new_ex(ctx->libctx, ctx->propq)) == NULL
  104. || !X509_STORE_CTX_init(csc, trusted_store,
  105. cert, ctx->untrusted))
  106. goto err;
  107. valid = X509_verify_cert(csc) > 0;
  108. /* make sure suitable error is queued even if callback did not do */
  109. err = ERR_peek_last_error();
  110. if (!valid && ERR_GET_REASON(err) != CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
  111. ERR_raise(ERR_LIB_CMP, CMP_R_POTENTIALLY_INVALID_CERTIFICATE);
  112. err:
  113. /* directly output any fresh errors, needed for check_msg_find_cert() */
  114. OSSL_CMP_CTX_print_errors(ctx);
  115. X509_STORE_CTX_free(csc);
  116. return valid;
  117. }
  118. static int verify_cb_cert(X509_STORE *ts, X509 *cert, int err)
  119. {
  120. X509_STORE_CTX_verify_cb verify_cb;
  121. X509_STORE_CTX *csc;
  122. int ok = 0;
  123. if (ts == NULL || (verify_cb = X509_STORE_get_verify_cb(ts)) == NULL)
  124. return ok;
  125. if ((csc = X509_STORE_CTX_new()) != NULL
  126. && X509_STORE_CTX_init(csc, ts, cert, NULL)) {
  127. X509_STORE_CTX_set_error(csc, err);
  128. X509_STORE_CTX_set_current_cert(csc, cert);
  129. ok = (*verify_cb)(0, csc);
  130. }
  131. X509_STORE_CTX_free(csc);
  132. return ok;
  133. }
  134. /* Return 0 if expect_name != NULL and there is no matching actual_name */
  135. static int check_name(const OSSL_CMP_CTX *ctx, int log_success,
  136. const char *actual_desc, const X509_NAME *actual_name,
  137. const char *expect_desc, const X509_NAME *expect_name)
  138. {
  139. char *str;
  140. if (expect_name == NULL)
  141. return 1; /* no expectation, thus trivially fulfilled */
  142. /* make sure that a matching name is there */
  143. if (actual_name == NULL) {
  144. ossl_cmp_log1(WARN, ctx, "missing %s", actual_desc);
  145. return 0;
  146. }
  147. str = X509_NAME_oneline(actual_name, NULL, 0);
  148. if (X509_NAME_cmp(actual_name, expect_name) == 0) {
  149. if (log_success && str != NULL)
  150. ossl_cmp_log3(INFO, ctx, " %s matches %s: %s",
  151. actual_desc, expect_desc, str);
  152. OPENSSL_free(str);
  153. return 1;
  154. }
  155. if (str != NULL)
  156. ossl_cmp_log2(INFO, ctx, " actual name in %s = %s", actual_desc, str);
  157. OPENSSL_free(str);
  158. if ((str = X509_NAME_oneline(expect_name, NULL, 0)) != NULL)
  159. ossl_cmp_log2(INFO, ctx, " does not match %s = %s", expect_desc, str);
  160. OPENSSL_free(str);
  161. return 0;
  162. }
  163. /* Return 0 if skid != NULL and there is no matching subject key ID in cert */
  164. static int check_kid(const OSSL_CMP_CTX *ctx,
  165. const ASN1_OCTET_STRING *ckid,
  166. const ASN1_OCTET_STRING *skid)
  167. {
  168. char *str;
  169. if (skid == NULL)
  170. return 1; /* no expectation, thus trivially fulfilled */
  171. /* make sure that the expected subject key identifier is there */
  172. if (ckid == NULL) {
  173. ossl_cmp_warn(ctx, "missing Subject Key Identifier in certificate");
  174. return 0;
  175. }
  176. str = i2s_ASN1_OCTET_STRING(NULL, ckid);
  177. if (ASN1_OCTET_STRING_cmp(ckid, skid) == 0) {
  178. if (str != NULL)
  179. ossl_cmp_log1(INFO, ctx, " subjectKID matches senderKID: %s", str);
  180. OPENSSL_free(str);
  181. return 1;
  182. }
  183. if (str != NULL)
  184. ossl_cmp_log1(INFO, ctx, " cert Subject Key Identifier = %s", str);
  185. OPENSSL_free(str);
  186. if ((str = i2s_ASN1_OCTET_STRING(NULL, skid)) != NULL)
  187. ossl_cmp_log1(INFO, ctx, " does not match senderKID = %s", str);
  188. OPENSSL_free(str);
  189. return 0;
  190. }
  191. static int already_checked(const X509 *cert,
  192. const STACK_OF(X509) *already_checked)
  193. {
  194. int i;
  195. for (i = sk_X509_num(already_checked /* may be NULL */); i > 0; i--)
  196. if (X509_cmp(sk_X509_value(already_checked, i - 1), cert) == 0)
  197. return 1;
  198. return 0;
  199. }
  200. /*-
  201. * Check if the given cert is acceptable as sender cert of the given message.
  202. * The subject DN must match, the subject key ID as well if present in the msg,
  203. * and the cert must be current (checked if ctx->trusted is not NULL).
  204. * Note that cert revocation etc. is checked by OSSL_CMP_validate_cert_path().
  205. *
  206. * Returns 0 on error or not acceptable, else 1.
  207. */
  208. static int cert_acceptable(const OSSL_CMP_CTX *ctx,
  209. const char *desc1, const char *desc2, X509 *cert,
  210. const STACK_OF(X509) *already_checked1,
  211. const STACK_OF(X509) *already_checked2,
  212. const OSSL_CMP_MSG *msg)
  213. {
  214. X509_STORE *ts = ctx->trusted;
  215. int self_issued = X509_check_issued(cert, cert) == X509_V_OK;
  216. char *str;
  217. X509_VERIFY_PARAM *vpm = ts != NULL ? X509_STORE_get0_param(ts) : NULL;
  218. int time_cmp;
  219. ossl_cmp_log3(INFO, ctx, " considering %s%s %s with..",
  220. self_issued ? "self-issued ": "", desc1, desc2);
  221. if ((str = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0)) != NULL)
  222. ossl_cmp_log1(INFO, ctx, " subject = %s", str);
  223. OPENSSL_free(str);
  224. if (!self_issued) {
  225. str = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
  226. if (str != NULL)
  227. ossl_cmp_log1(INFO, ctx, " issuer = %s", str);
  228. OPENSSL_free(str);
  229. }
  230. if (already_checked(cert, already_checked1)
  231. || already_checked(cert, already_checked2)) {
  232. ossl_cmp_info(ctx, " cert has already been checked");
  233. return 0;
  234. }
  235. time_cmp = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
  236. X509_get0_notAfter(cert));
  237. if (time_cmp != 0) {
  238. int err = time_cmp > 0 ? X509_V_ERR_CERT_HAS_EXPIRED
  239. : X509_V_ERR_CERT_NOT_YET_VALID;
  240. ossl_cmp_warn(ctx, time_cmp > 0 ? "cert has expired"
  241. : "cert is not yet valid");
  242. if (ctx->log_cb != NULL /* logging not temporarily disabled */
  243. && verify_cb_cert(ts, cert, err) <= 0)
  244. return 0;
  245. }
  246. if (!check_name(ctx, 1,
  247. "cert subject", X509_get_subject_name(cert),
  248. "sender field", msg->header->sender->d.directoryName))
  249. return 0;
  250. if (!check_kid(ctx, X509_get0_subject_key_id(cert), msg->header->senderKID))
  251. return 0;
  252. /* prevent misleading error later in case x509v3_cache_extensions() fails */
  253. if (!ossl_x509v3_cache_extensions(cert)) {
  254. ossl_cmp_warn(ctx, "cert appears to be invalid");
  255. return 0;
  256. }
  257. if (!verify_signature(ctx, msg, cert)) {
  258. ossl_cmp_warn(ctx, "msg signature verification failed");
  259. return 0;
  260. }
  261. /* acceptable also if there is no senderKID in msg header */
  262. ossl_cmp_info(ctx, " cert seems acceptable");
  263. return 1;
  264. }
  265. static int check_cert_path(const OSSL_CMP_CTX *ctx, X509_STORE *store,
  266. X509 *scrt)
  267. {
  268. if (OSSL_CMP_validate_cert_path(ctx, store, scrt))
  269. return 1;
  270. ossl_cmp_warn(ctx,
  271. "msg signature validates but cert path validation failed");
  272. return 0;
  273. }
  274. /*
  275. * Exceptional handling for 3GPP TS 33.310 [3G/LTE Network Domain Security
  276. * (NDS); Authentication Framework (AF)], only to use for IP messages
  277. * and if the ctx option is explicitly set: use self-issued certificates
  278. * from extraCerts as trust anchor to validate sender cert -
  279. * provided it also can validate the newly enrolled certificate
  280. */
  281. static int check_cert_path_3gpp(const OSSL_CMP_CTX *ctx,
  282. const OSSL_CMP_MSG *msg, X509 *scrt)
  283. {
  284. int valid = 0;
  285. X509_STORE *store;
  286. if (!ctx->permitTAInExtraCertsForIR)
  287. return 0;
  288. if ((store = X509_STORE_new()) == NULL
  289. || !ossl_cmp_X509_STORE_add1_certs(store, msg->extraCerts,
  290. 1 /* self-issued only */))
  291. goto err;
  292. /* store does not include CRLs */
  293. valid = OSSL_CMP_validate_cert_path(ctx, store, scrt);
  294. if (!valid) {
  295. ossl_cmp_warn(ctx,
  296. "also exceptional 3GPP mode cert path validation failed");
  297. } else {
  298. /*
  299. * verify that the newly enrolled certificate (which assumed rid ==
  300. * OSSL_CMP_CERTREQID) can also be validated with the same trusted store
  301. */
  302. OSSL_CMP_CERTRESPONSE *crep =
  303. ossl_cmp_certrepmessage_get0_certresponse(msg->body->value.ip,
  304. OSSL_CMP_CERTREQID);
  305. X509 *newcrt = ossl_cmp_certresponse_get1_cert(ctx, crep);
  306. /*
  307. * maybe better use get_cert_status() from cmp_client.c, which catches
  308. * errors
  309. */
  310. valid = OSSL_CMP_validate_cert_path(ctx, store, newcrt);
  311. X509_free(newcrt);
  312. }
  313. err:
  314. X509_STORE_free(store);
  315. return valid;
  316. }
  317. static int check_msg_given_cert(const OSSL_CMP_CTX *ctx, X509 *cert,
  318. const OSSL_CMP_MSG *msg)
  319. {
  320. return cert_acceptable(ctx, "previously validated", "sender cert",
  321. cert, NULL, NULL, msg)
  322. && (check_cert_path(ctx, ctx->trusted, cert)
  323. || check_cert_path_3gpp(ctx, msg, cert));
  324. }
  325. /*-
  326. * Try all certs in given list for verifying msg, normally or in 3GPP mode.
  327. * If already_checked1 == NULL then certs are assumed to be the msg->extraCerts.
  328. * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
  329. */
  330. static int check_msg_with_certs(OSSL_CMP_CTX *ctx, const STACK_OF(X509) *certs,
  331. const char *desc,
  332. const STACK_OF(X509) *already_checked1,
  333. const STACK_OF(X509) *already_checked2,
  334. const OSSL_CMP_MSG *msg, int mode_3gpp)
  335. {
  336. int in_extraCerts = already_checked1 == NULL;
  337. int n_acceptable_certs = 0;
  338. int i;
  339. if (sk_X509_num(certs) <= 0) {
  340. ossl_cmp_log1(WARN, ctx, "no %s", desc);
  341. return 0;
  342. }
  343. for (i = 0; i < sk_X509_num(certs); i++) { /* certs may be NULL */
  344. X509 *cert = sk_X509_value(certs, i);
  345. if (!ossl_assert(cert != NULL))
  346. return 0;
  347. if (!cert_acceptable(ctx, "cert from", desc, cert,
  348. already_checked1, already_checked2, msg))
  349. continue;
  350. n_acceptable_certs++;
  351. if (mode_3gpp ? check_cert_path_3gpp(ctx, msg, cert)
  352. : check_cert_path(ctx, ctx->trusted, cert)) {
  353. /* store successful sender cert for further msgs in transaction */
  354. return ossl_cmp_ctx_set1_validatedSrvCert(ctx, cert);
  355. }
  356. }
  357. if (in_extraCerts && n_acceptable_certs == 0)
  358. ossl_cmp_warn(ctx, "no acceptable cert in extraCerts");
  359. return 0;
  360. }
  361. /*-
  362. * Verify msg trying first ctx->untrusted, which should include extraCerts
  363. * at its front, then trying the trusted certs in truststore (if any) of ctx.
  364. * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
  365. */
  366. static int check_msg_all_certs(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
  367. int mode_3gpp)
  368. {
  369. int ret = 0;
  370. if (ctx->permitTAInExtraCertsForIR
  371. && OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_IP)
  372. ossl_cmp_info(ctx, mode_3gpp ?
  373. "normal mode failed; trying now 3GPP mode trusting extraCerts"
  374. : "trying first normal mode using trust store");
  375. else if (mode_3gpp)
  376. return 0;
  377. if (check_msg_with_certs(ctx, msg->extraCerts, "extraCerts",
  378. NULL, NULL, msg, mode_3gpp))
  379. return 1;
  380. if (check_msg_with_certs(ctx, ctx->untrusted, "untrusted certs",
  381. msg->extraCerts, NULL, msg, mode_3gpp))
  382. return 1;
  383. if (ctx->trusted == NULL) {
  384. ossl_cmp_warn(ctx, mode_3gpp ? "no self-issued extraCerts"
  385. : "no trusted store");
  386. } else {
  387. STACK_OF(X509) *trusted = X509_STORE_get1_all_certs(ctx->trusted);
  388. ret = check_msg_with_certs(ctx, trusted,
  389. mode_3gpp ? "self-issued extraCerts"
  390. : "certs in trusted store",
  391. msg->extraCerts, ctx->untrusted,
  392. msg, mode_3gpp);
  393. OSSL_STACK_OF_X509_free(trusted);
  394. }
  395. return ret;
  396. }
  397. /*-
  398. * Verify message signature with any acceptable and valid candidate cert.
  399. * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
  400. */
  401. static int check_msg_find_cert(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
  402. {
  403. X509 *scrt = ctx->validatedSrvCert; /* previous successful sender cert */
  404. GENERAL_NAME *sender = msg->header->sender;
  405. char *sname = NULL;
  406. char *skid_str = NULL;
  407. const ASN1_OCTET_STRING *skid = msg->header->senderKID;
  408. OSSL_CMP_log_cb_t backup_log_cb = ctx->log_cb;
  409. int res = 0;
  410. if (sender == NULL || msg->body == NULL)
  411. return 0; /* other NULL cases already have been checked */
  412. if (sender->type != GEN_DIRNAME) {
  413. /* So far, only X509_NAME is supported */
  414. ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
  415. return 0;
  416. }
  417. /* dump any hitherto errors to avoid confusion when printing further ones */
  418. OSSL_CMP_CTX_print_errors(ctx);
  419. /* enable clearing irrelevant errors in attempts to validate sender certs */
  420. (void)ERR_set_mark();
  421. ctx->log_cb = NULL; /* temporarily disable logging */
  422. /*
  423. * try first cached scrt, used successfully earlier in same transaction,
  424. * for validating this and any further msgs where extraCerts may be left out
  425. */
  426. if (scrt != NULL) {
  427. if (check_msg_given_cert(ctx, scrt, msg)) {
  428. ctx->log_cb = backup_log_cb;
  429. (void)ERR_pop_to_mark();
  430. return 1;
  431. }
  432. /* cached sender cert has shown to be no more successfully usable */
  433. (void)ossl_cmp_ctx_set1_validatedSrvCert(ctx, NULL);
  434. /* re-do the above check (just) for adding diagnostic information */
  435. ossl_cmp_info(ctx,
  436. "trying to verify msg signature with previously validated cert");
  437. (void)check_msg_given_cert(ctx, scrt, msg);
  438. }
  439. res = check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */)
  440. || check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
  441. ctx->log_cb = backup_log_cb;
  442. if (res) {
  443. /* discard any diagnostic information on trying to use certs */
  444. (void)ERR_pop_to_mark();
  445. goto end;
  446. }
  447. /* failed finding a sender cert that verifies the message signature */
  448. (void)ERR_clear_last_mark();
  449. sname = X509_NAME_oneline(sender->d.directoryName, NULL, 0);
  450. skid_str = skid == NULL ? NULL : i2s_ASN1_OCTET_STRING(NULL, skid);
  451. if (ctx->log_cb != NULL) {
  452. ossl_cmp_info(ctx, "trying to verify msg signature with a valid cert that..");
  453. if (sname != NULL)
  454. ossl_cmp_log1(INFO, ctx, "matches msg sender = %s", sname);
  455. if (skid_str != NULL)
  456. ossl_cmp_log1(INFO, ctx, "matches msg senderKID = %s", skid_str);
  457. else
  458. ossl_cmp_info(ctx, "while msg header does not contain senderKID");
  459. /* re-do the above checks (just) for adding diagnostic information */
  460. (void)check_msg_all_certs(ctx, msg, 0 /* using ctx->trusted */);
  461. (void)check_msg_all_certs(ctx, msg, 1 /* 3gpp */);
  462. }
  463. ERR_raise(ERR_LIB_CMP, CMP_R_NO_SUITABLE_SENDER_CERT);
  464. if (sname != NULL) {
  465. ERR_add_error_txt(NULL, "for msg sender name = ");
  466. ERR_add_error_txt(NULL, sname);
  467. }
  468. if (skid_str != NULL) {
  469. ERR_add_error_txt(" and ", "for msg senderKID = ");
  470. ERR_add_error_txt(NULL, skid_str);
  471. }
  472. end:
  473. OPENSSL_free(sname);
  474. OPENSSL_free(skid_str);
  475. return res;
  476. }
  477. /*-
  478. * Validate the protection of the given PKIMessage using either password-
  479. * based mac (PBM) or a signature algorithm. In the case of signature algorithm,
  480. * the sender certificate can have been pinned by providing it in ctx->srvCert,
  481. * else it is searched in msg->extraCerts, ctx->untrusted, in ctx->trusted
  482. * (in this order) and is path is validated against ctx->trusted.
  483. * On success cache the found cert using ossl_cmp_ctx_set1_validatedSrvCert().
  484. *
  485. * If ctx->permitTAInExtraCertsForIR is true and when validating a CMP IP msg,
  486. * the trust anchor for validating the IP msg may be taken from msg->extraCerts
  487. * if a self-issued certificate is found there that can be used to
  488. * validate the enrolled certificate returned in the IP.
  489. * This is according to the need given in 3GPP TS 33.310.
  490. *
  491. * Returns 1 on success, 0 on error or validation failed.
  492. */
  493. int OSSL_CMP_validate_msg(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg)
  494. {
  495. X509 *scrt;
  496. ossl_cmp_debug(ctx, "validating CMP message");
  497. if (ctx == NULL || msg == NULL
  498. || msg->header == NULL || msg->body == NULL) {
  499. ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT);
  500. return 0;
  501. }
  502. if (msg->header->protectionAlg == NULL /* unprotected message */
  503. || msg->protection == NULL || msg->protection->data == NULL) {
  504. ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
  505. return 0;
  506. }
  507. switch (ossl_cmp_hdr_get_protection_nid(msg->header)) {
  508. /* 5.1.3.1. Shared Secret Information */
  509. case NID_id_PasswordBasedMAC:
  510. if (ctx->secretValue == NULL) {
  511. ossl_cmp_info(ctx, "no secret available for verifying PBM-based CMP message protection");
  512. ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_SECRET);
  513. return 0;
  514. }
  515. if (verify_PBMAC(ctx, msg)) {
  516. /*
  517. * RFC 4210, 5.3.2: 'Note that if the PKI Message Protection is
  518. * "shared secret information", then any certificate transported in
  519. * the caPubs field may be directly trusted as a root CA
  520. * certificate by the initiator.'
  521. */
  522. switch (OSSL_CMP_MSG_get_bodytype(msg)) {
  523. case -1:
  524. return 0;
  525. case OSSL_CMP_PKIBODY_IP:
  526. case OSSL_CMP_PKIBODY_CP:
  527. case OSSL_CMP_PKIBODY_KUP:
  528. case OSSL_CMP_PKIBODY_CCP:
  529. if (ctx->trusted != NULL) {
  530. STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
  531. /* value.ip is same for cp, kup, and ccp */
  532. if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
  533. /* adds both self-issued and not self-issued certs */
  534. return 0;
  535. }
  536. break;
  537. default:
  538. break;
  539. }
  540. ossl_cmp_debug(ctx,
  541. "successfully validated PBM-based CMP message protection");
  542. return 1;
  543. }
  544. ossl_cmp_warn(ctx, "verifying PBM-based CMP message protection failed");
  545. break;
  546. /*
  547. * 5.1.3.2 DH Key Pairs
  548. * Not yet supported
  549. */
  550. case NID_id_DHBasedMac:
  551. ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC);
  552. break;
  553. /*
  554. * 5.1.3.3. Signature
  555. */
  556. default:
  557. scrt = ctx->srvCert;
  558. if (scrt == NULL) {
  559. if (ctx->trusted == NULL) {
  560. ossl_cmp_info(ctx, "no trust store nor pinned server cert available for verifying signature-based CMP message protection");
  561. ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_TRUST_ANCHOR);
  562. return 0;
  563. }
  564. if (check_msg_find_cert(ctx, msg)) {
  565. ossl_cmp_debug(ctx,
  566. "successfully validated signature-based CMP message protection using trust store");
  567. return 1;
  568. }
  569. } else { /* use pinned sender cert */
  570. /* use ctx->srvCert for signature check even if not acceptable */
  571. if (verify_signature(ctx, msg, scrt)) {
  572. ossl_cmp_debug(ctx,
  573. "successfully validated signature-based CMP message protection using pinned server cert");
  574. return ossl_cmp_ctx_set1_validatedSrvCert(ctx, scrt);
  575. }
  576. ossl_cmp_warn(ctx, "CMP message signature verification failed");
  577. ERR_raise(ERR_LIB_CMP, CMP_R_SRVCERT_DOES_NOT_VALIDATE_MSG);
  578. }
  579. break;
  580. }
  581. return 0;
  582. }
  583. static int check_transactionID_or_nonce(ASN1_OCTET_STRING *expected,
  584. ASN1_OCTET_STRING *actual, int reason)
  585. {
  586. if (expected != NULL
  587. && (actual == NULL || ASN1_OCTET_STRING_cmp(expected, actual) != 0)) {
  588. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  589. char *expected_str, *actual_str;
  590. expected_str = i2s_ASN1_OCTET_STRING(NULL, expected);
  591. actual_str = actual == NULL ? NULL: i2s_ASN1_OCTET_STRING(NULL, actual);
  592. ERR_raise_data(ERR_LIB_CMP, reason,
  593. "expected = %s, actual = %s",
  594. expected_str == NULL ? "?" : expected_str,
  595. actual == NULL ? "(none)" :
  596. actual_str == NULL ? "?" : actual_str);
  597. OPENSSL_free(expected_str);
  598. OPENSSL_free(actual_str);
  599. return 0;
  600. #endif
  601. }
  602. return 1;
  603. }
  604. /*-
  605. * Check received message (i.e., response by server or request from client)
  606. * Any msg->extraCerts are prepended to ctx->untrusted.
  607. *
  608. * Ensures that:
  609. * its sender is of appropriate type (currently only X509_NAME) and
  610. * matches any expected sender or srvCert subject given in the ctx
  611. * it has a valid body type
  612. * its protection is valid (or invalid/absent, but only if a callback function
  613. * is present and yields a positive result using also the supplied argument)
  614. * its transaction ID matches the previous transaction ID stored in ctx (if any)
  615. * its recipNonce matches the previous senderNonce stored in the ctx (if any)
  616. *
  617. * If everything is fine:
  618. * learns the senderNonce from the received message,
  619. * learns the transaction ID if it is not yet in ctx,
  620. * and makes any certs in caPubs directly trusted.
  621. *
  622. * Returns 1 on success, 0 on error.
  623. */
  624. int ossl_cmp_msg_check_update(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
  625. ossl_cmp_allow_unprotected_cb_t cb, int cb_arg)
  626. {
  627. OSSL_CMP_PKIHEADER *hdr;
  628. const X509_NAME *expected_sender;
  629. int num_untrusted, num_added, res;
  630. if (!ossl_assert(ctx != NULL && msg != NULL && msg->header != NULL))
  631. return 0;
  632. hdr = OSSL_CMP_MSG_get0_header(msg);
  633. /* If expected_sender is given, validate sender name of received msg */
  634. expected_sender = ctx->expected_sender;
  635. if (expected_sender == NULL && ctx->srvCert != NULL)
  636. expected_sender = X509_get_subject_name(ctx->srvCert);
  637. if (expected_sender != NULL) {
  638. const X509_NAME *actual_sender;
  639. char *str;
  640. if (hdr->sender->type != GEN_DIRNAME) {
  641. ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED);
  642. return 0;
  643. }
  644. actual_sender = hdr->sender->d.directoryName;
  645. /*
  646. * Compare actual sender name of response with expected sender name.
  647. * Mitigates risk of accepting misused PBM secret or
  648. * misused certificate of an unauthorized entity of a trusted hierarchy.
  649. */
  650. if (!check_name(ctx, 0, "sender DN field", actual_sender,
  651. "expected sender", expected_sender)) {
  652. str = X509_NAME_oneline(actual_sender, NULL, 0);
  653. ERR_raise_data(ERR_LIB_CMP, CMP_R_UNEXPECTED_SENDER,
  654. str != NULL ? str : "<unknown>");
  655. OPENSSL_free(str);
  656. return 0;
  657. }
  658. }
  659. /* Note: if recipient was NULL-DN it could be learned here if needed */
  660. num_added = sk_X509_num(msg->extraCerts);
  661. if (num_added > 10)
  662. ossl_cmp_log1(WARN, ctx, "received CMP message contains %d extraCerts",
  663. num_added);
  664. /*
  665. * Store any provided extraCerts in ctx for use in OSSL_CMP_validate_msg()
  666. * and for future use, such that they are available to ctx->certConf_cb and
  667. * the peer does not need to send them again in the same transaction.
  668. * Note that it does not help validating the message before storing the
  669. * extraCerts because they do not belong to the protected msg part anyway.
  670. * The extraCerts are prepended. Allows simple removal if they shall not be
  671. * cached. Also they get used first, which is likely good for efficiency.
  672. */
  673. num_untrusted = ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted);
  674. res = ossl_x509_add_certs_new(&ctx->untrusted, msg->extraCerts,
  675. /* this allows self-signed certs */
  676. X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP
  677. | X509_ADD_FLAG_PREPEND);
  678. num_added = (ctx->untrusted == NULL ? 0 : sk_X509_num(ctx->untrusted))
  679. - num_untrusted;
  680. if (!res) {
  681. while (num_added-- > 0)
  682. X509_free(sk_X509_shift(ctx->untrusted));
  683. return 0;
  684. }
  685. if (hdr->protectionAlg != NULL)
  686. res = OSSL_CMP_validate_msg(ctx, msg)
  687. /* explicitly permitted exceptions for invalid protection: */
  688. || (cb != NULL && (*cb)(ctx, msg, 1, cb_arg) > 0);
  689. else
  690. /* explicitly permitted exceptions for missing protection: */
  691. res = cb != NULL && (*cb)(ctx, msg, 0, cb_arg) > 0;
  692. #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  693. res = 1; /* support more aggressive fuzzing by letting invalid msg pass */
  694. #endif
  695. /* remove extraCerts again if not caching */
  696. if (ctx->noCacheExtraCerts)
  697. while (num_added-- > 0)
  698. X509_free(sk_X509_shift(ctx->untrusted));
  699. if (!res) {
  700. if (hdr->protectionAlg != NULL)
  701. ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_VALIDATING_PROTECTION);
  702. else
  703. ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PROTECTION);
  704. return 0;
  705. }
  706. /* check CMP version number in header */
  707. if (ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_2
  708. && ossl_cmp_hdr_get_pvno(hdr) != OSSL_CMP_PVNO_3) {
  709. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  710. ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PVNO);
  711. return 0;
  712. #endif
  713. }
  714. if (OSSL_CMP_MSG_get_bodytype(msg) < 0) {
  715. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  716. ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
  717. return 0;
  718. #endif
  719. }
  720. /* compare received transactionID with the expected one in previous msg */
  721. if (!check_transactionID_or_nonce(ctx->transactionID, hdr->transactionID,
  722. CMP_R_TRANSACTIONID_UNMATCHED))
  723. return 0;
  724. /*
  725. * enable clearing irrelevant errors
  726. * in attempts to validate recipient nonce in case of delayed delivery.
  727. */
  728. (void)ERR_set_mark();
  729. /* compare received nonce with the one we sent */
  730. if (!check_transactionID_or_nonce(ctx->senderNonce, hdr->recipNonce,
  731. CMP_R_RECIPNONCE_UNMATCHED)) {
  732. /* check if we are polling and received final response */
  733. if (ctx->first_senderNonce == NULL
  734. || OSSL_CMP_MSG_get_bodytype(msg) == OSSL_CMP_PKIBODY_POLLREP
  735. /* compare received nonce with our sender nonce at poll start */
  736. || !check_transactionID_or_nonce(ctx->first_senderNonce,
  737. hdr->recipNonce,
  738. CMP_R_RECIPNONCE_UNMATCHED)) {
  739. (void)ERR_clear_last_mark();
  740. return 0;
  741. }
  742. }
  743. (void)ERR_pop_to_mark();
  744. /* if not yet present, learn transactionID */
  745. if (ctx->transactionID == NULL
  746. && !OSSL_CMP_CTX_set1_transactionID(ctx, hdr->transactionID))
  747. return 0;
  748. /*
  749. * RFC 4210 section 5.1.1 states: the recipNonce is copied from
  750. * the senderNonce of the previous message in the transaction.
  751. * --> Store for setting in next message
  752. */
  753. if (!ossl_cmp_ctx_set1_recipNonce(ctx, hdr->senderNonce))
  754. return 0;
  755. if (ossl_cmp_hdr_get_protection_nid(hdr) == NID_id_PasswordBasedMAC) {
  756. /*
  757. * RFC 4210, 5.3.2: 'Note that if the PKI Message Protection is
  758. * "shared secret information", then any certificate transported in
  759. * the caPubs field may be directly trusted as a root CA
  760. * certificate by the initiator.'
  761. */
  762. switch (OSSL_CMP_MSG_get_bodytype(msg)) {
  763. case OSSL_CMP_PKIBODY_IP:
  764. case OSSL_CMP_PKIBODY_CP:
  765. case OSSL_CMP_PKIBODY_KUP:
  766. case OSSL_CMP_PKIBODY_CCP:
  767. if (ctx->trusted != NULL) {
  768. STACK_OF(X509) *certs = msg->body->value.ip->caPubs;
  769. /* value.ip is same for cp, kup, and ccp */
  770. if (!ossl_cmp_X509_STORE_add1_certs(ctx->trusted, certs, 0))
  771. /* adds both self-issued and not self-issued certs */
  772. return 0;
  773. }
  774. break;
  775. default:
  776. break;
  777. }
  778. }
  779. return 1;
  780. }
  781. int ossl_cmp_verify_popo(const OSSL_CMP_CTX *ctx,
  782. const OSSL_CMP_MSG *msg, int acceptRAVerified)
  783. {
  784. if (!ossl_assert(msg != NULL && msg->body != NULL))
  785. return 0;
  786. switch (msg->body->type) {
  787. case OSSL_CMP_PKIBODY_P10CR:
  788. {
  789. X509_REQ *req = msg->body->value.p10cr;
  790. if (X509_REQ_verify_ex(req, X509_REQ_get0_pubkey(req), ctx->libctx,
  791. ctx->propq) <= 0) {
  792. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  793. ERR_raise(ERR_LIB_CMP, CMP_R_REQUEST_NOT_ACCEPTED);
  794. return 0;
  795. #endif
  796. }
  797. }
  798. break;
  799. case OSSL_CMP_PKIBODY_IR:
  800. case OSSL_CMP_PKIBODY_CR:
  801. case OSSL_CMP_PKIBODY_KUR:
  802. if (!OSSL_CRMF_MSGS_verify_popo(msg->body->value.ir, OSSL_CMP_CERTREQID,
  803. acceptRAVerified,
  804. ctx->libctx, ctx->propq)) {
  805. #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
  806. return 0;
  807. #endif
  808. }
  809. break;
  810. default:
  811. ERR_raise(ERR_LIB_CMP, CMP_R_PKIBODY_ERROR);
  812. return 0;
  813. }
  814. return 1;
  815. }