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.
 
 
 
 
 
 

468 line
15 KiB

  1. /*
  2. * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
  3. * project.
  4. */
  5. /* ====================================================================
  6. * Copyright (c) 2015 The OpenSSL Project. All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. *
  20. * 3. All advertising materials mentioning features or use of this
  21. * software must display the following acknowledgment:
  22. * "This product includes software developed by the OpenSSL Project
  23. * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
  24. *
  25. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  26. * endorse or promote products derived from this software without
  27. * prior written permission. For written permission, please contact
  28. * licensing@OpenSSL.org.
  29. *
  30. * 5. Products derived from this software may not be called "OpenSSL"
  31. * nor may "OpenSSL" appear in their names without prior written
  32. * permission of the OpenSSL Project.
  33. *
  34. * 6. Redistributions of any form whatsoever must retain the following
  35. * acknowledgment:
  36. * "This product includes software developed by the OpenSSL Project
  37. * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
  38. *
  39. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  40. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  41. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  42. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  43. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  44. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  45. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  46. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  48. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  49. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  50. * OF THE POSSIBILITY OF SUCH DAMAGE.
  51. * ====================================================================
  52. */
  53. #include <openssl/evp.h>
  54. #include <stdio.h>
  55. #include <stdint.h>
  56. #include <stdlib.h>
  57. #include <string.h>
  58. OPENSSL_MSVC_PRAGMA(warning(push))
  59. OPENSSL_MSVC_PRAGMA(warning(disable: 4702))
  60. #include <map>
  61. #include <string>
  62. #include <utility>
  63. #include <vector>
  64. OPENSSL_MSVC_PRAGMA(warning(pop))
  65. #include <gtest/gtest.h>
  66. #include <openssl/buf.h>
  67. #include <openssl/bytestring.h>
  68. #include <openssl/crypto.h>
  69. #include <openssl/digest.h>
  70. #include <openssl/err.h>
  71. #include <openssl/rsa.h>
  72. #include "../test/file_test.h"
  73. #include "../test/test_util.h"
  74. #include "../test/wycheproof_util.h"
  75. // evp_test dispatches between multiple test types. PrivateKey tests take a key
  76. // name parameter and single block, decode it as a PEM private key, and save it
  77. // under that key name. Decrypt, Sign, and Verify tests take a previously
  78. // imported key name as parameter and test their respective operations.
  79. static const EVP_MD *GetDigest(FileTest *t, const std::string &name) {
  80. if (name == "MD5") {
  81. return EVP_md5();
  82. } else if (name == "SHA1") {
  83. return EVP_sha1();
  84. } else if (name == "SHA224") {
  85. return EVP_sha224();
  86. } else if (name == "SHA256") {
  87. return EVP_sha256();
  88. } else if (name == "SHA384") {
  89. return EVP_sha384();
  90. } else if (name == "SHA512") {
  91. return EVP_sha512();
  92. }
  93. ADD_FAILURE() << "Unknown digest: " << name;
  94. return nullptr;
  95. }
  96. static int GetKeyType(FileTest *t, const std::string &name) {
  97. if (name == "RSA") {
  98. return EVP_PKEY_RSA;
  99. }
  100. if (name == "EC") {
  101. return EVP_PKEY_EC;
  102. }
  103. if (name == "DSA") {
  104. return EVP_PKEY_DSA;
  105. }
  106. if (name == "Ed25519") {
  107. return EVP_PKEY_ED25519;
  108. }
  109. ADD_FAILURE() << "Unknown key type: " << name;
  110. return EVP_PKEY_NONE;
  111. }
  112. static int GetRSAPadding(FileTest *t, int *out, const std::string &name) {
  113. if (name == "PKCS1") {
  114. *out = RSA_PKCS1_PADDING;
  115. return true;
  116. }
  117. if (name == "PSS") {
  118. *out = RSA_PKCS1_PSS_PADDING;
  119. return true;
  120. }
  121. if (name == "OAEP") {
  122. *out = RSA_PKCS1_OAEP_PADDING;
  123. return true;
  124. }
  125. ADD_FAILURE() << "Unknown RSA padding mode: " << name;
  126. return false;
  127. }
  128. using KeyMap = std::map<std::string, bssl::UniquePtr<EVP_PKEY>>;
  129. static bool ImportKey(FileTest *t, KeyMap *key_map,
  130. EVP_PKEY *(*parse_func)(CBS *cbs),
  131. int (*marshal_func)(CBB *cbb, const EVP_PKEY *key)) {
  132. std::vector<uint8_t> input;
  133. if (!t->GetBytes(&input, "Input")) {
  134. return false;
  135. }
  136. CBS cbs;
  137. CBS_init(&cbs, input.data(), input.size());
  138. bssl::UniquePtr<EVP_PKEY> pkey(parse_func(&cbs));
  139. if (!pkey) {
  140. return false;
  141. }
  142. std::string key_type;
  143. if (!t->GetAttribute(&key_type, "Type")) {
  144. return false;
  145. }
  146. EXPECT_EQ(GetKeyType(t, key_type), EVP_PKEY_id(pkey.get()));
  147. // The key must re-encode correctly.
  148. bssl::ScopedCBB cbb;
  149. uint8_t *der;
  150. size_t der_len;
  151. if (!CBB_init(cbb.get(), 0) ||
  152. !marshal_func(cbb.get(), pkey.get()) ||
  153. !CBB_finish(cbb.get(), &der, &der_len)) {
  154. return false;
  155. }
  156. bssl::UniquePtr<uint8_t> free_der(der);
  157. std::vector<uint8_t> output = input;
  158. if (t->HasAttribute("Output") &&
  159. !t->GetBytes(&output, "Output")) {
  160. return false;
  161. }
  162. EXPECT_EQ(Bytes(output), Bytes(der, der_len)) << "Re-encoding the key did not match.";
  163. // Save the key for future tests.
  164. const std::string &key_name = t->GetParameter();
  165. EXPECT_EQ(0u, key_map->count(key_name)) << "Duplicate key: " << key_name;
  166. (*key_map)[key_name] = std::move(pkey);
  167. return true;
  168. }
  169. // SetupContext configures |ctx| based on attributes in |t|, with the exception
  170. // of the signing digest which must be configured externally.
  171. static bool SetupContext(FileTest *t, EVP_PKEY_CTX *ctx) {
  172. if (t->HasAttribute("RSAPadding")) {
  173. int padding;
  174. if (!GetRSAPadding(t, &padding, t->GetAttributeOrDie("RSAPadding")) ||
  175. !EVP_PKEY_CTX_set_rsa_padding(ctx, padding)) {
  176. return false;
  177. }
  178. }
  179. if (t->HasAttribute("PSSSaltLength") &&
  180. !EVP_PKEY_CTX_set_rsa_pss_saltlen(
  181. ctx, atoi(t->GetAttributeOrDie("PSSSaltLength").c_str()))) {
  182. return false;
  183. }
  184. if (t->HasAttribute("MGF1Digest")) {
  185. const EVP_MD *digest = GetDigest(t, t->GetAttributeOrDie("MGF1Digest"));
  186. if (digest == nullptr || !EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, digest)) {
  187. return false;
  188. }
  189. }
  190. if (t->HasAttribute("OAEPDigest")) {
  191. const EVP_MD *digest = GetDigest(t, t->GetAttributeOrDie("OAEPDigest"));
  192. if (digest == nullptr || !EVP_PKEY_CTX_set_rsa_oaep_md(ctx, digest)) {
  193. return false;
  194. }
  195. }
  196. if (t->HasAttribute("OAEPLabel")) {
  197. std::vector<uint8_t> label;
  198. if (!t->GetBytes(&label, "OAEPLabel")) {
  199. return false;
  200. }
  201. // For historical reasons, |EVP_PKEY_CTX_set0_rsa_oaep_label| expects to be
  202. // take ownership of the input.
  203. bssl::UniquePtr<uint8_t> buf(
  204. reinterpret_cast<uint8_t *>(BUF_memdup(label.data(), label.size())));
  205. if (!buf ||
  206. !EVP_PKEY_CTX_set0_rsa_oaep_label(ctx, buf.get(), label.size())) {
  207. return false;
  208. }
  209. buf.release();
  210. }
  211. return true;
  212. }
  213. static bool TestEVP(FileTest *t, KeyMap *key_map) {
  214. if (t->GetType() == "PrivateKey") {
  215. return ImportKey(t, key_map, EVP_parse_private_key,
  216. EVP_marshal_private_key);
  217. }
  218. if (t->GetType() == "PublicKey") {
  219. return ImportKey(t, key_map, EVP_parse_public_key, EVP_marshal_public_key);
  220. }
  221. int (*key_op_init)(EVP_PKEY_CTX *ctx) = nullptr;
  222. int (*key_op)(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *out_len,
  223. const uint8_t *in, size_t in_len) = nullptr;
  224. int (*md_op_init)(EVP_MD_CTX * ctx, EVP_PKEY_CTX * *pctx, const EVP_MD *type,
  225. ENGINE *e, EVP_PKEY *pkey) = nullptr;
  226. bool is_verify = false;
  227. if (t->GetType() == "Decrypt") {
  228. key_op_init = EVP_PKEY_decrypt_init;
  229. key_op = EVP_PKEY_decrypt;
  230. } else if (t->GetType() == "Sign") {
  231. key_op_init = EVP_PKEY_sign_init;
  232. key_op = EVP_PKEY_sign;
  233. } else if (t->GetType() == "Verify") {
  234. key_op_init = EVP_PKEY_verify_init;
  235. is_verify = true;
  236. } else if (t->GetType() == "SignMessage") {
  237. md_op_init = EVP_DigestSignInit;
  238. } else if (t->GetType() == "VerifyMessage") {
  239. md_op_init = EVP_DigestVerifyInit;
  240. is_verify = true;
  241. } else if (t->GetType() == "Encrypt") {
  242. key_op_init = EVP_PKEY_encrypt_init;
  243. key_op = EVP_PKEY_encrypt;
  244. } else {
  245. ADD_FAILURE() << "Unknown test " << t->GetType();
  246. return false;
  247. }
  248. // Load the key.
  249. const std::string &key_name = t->GetParameter();
  250. if (key_map->count(key_name) == 0) {
  251. ADD_FAILURE() << "Could not find key " << key_name;
  252. return false;
  253. }
  254. EVP_PKEY *key = (*key_map)[key_name].get();
  255. const EVP_MD *digest = nullptr;
  256. if (t->HasAttribute("Digest")) {
  257. digest = GetDigest(t, t->GetAttributeOrDie("Digest"));
  258. if (digest == nullptr) {
  259. return false;
  260. }
  261. }
  262. // For verify tests, the "output" is the signature. Read it now so that, for
  263. // tests which expect a failure in SetupContext, the attribute is still
  264. // consumed.
  265. std::vector<uint8_t> input, actual, output;
  266. if (!t->GetBytes(&input, "Input") ||
  267. (is_verify && !t->GetBytes(&output, "Output"))) {
  268. return false;
  269. }
  270. if (md_op_init) {
  271. bssl::ScopedEVP_MD_CTX ctx;
  272. EVP_PKEY_CTX *pctx;
  273. if (!md_op_init(ctx.get(), &pctx, digest, nullptr, key) ||
  274. !SetupContext(t, pctx)) {
  275. return false;
  276. }
  277. if (is_verify) {
  278. return !!EVP_DigestVerify(ctx.get(), output.data(), output.size(),
  279. input.data(), input.size());
  280. }
  281. size_t len;
  282. if (!EVP_DigestSign(ctx.get(), nullptr, &len, input.data(), input.size())) {
  283. return false;
  284. }
  285. actual.resize(len);
  286. if (!EVP_DigestSign(ctx.get(), actual.data(), &len, input.data(),
  287. input.size()) ||
  288. !t->GetBytes(&output, "Output")) {
  289. return false;
  290. }
  291. actual.resize(len);
  292. EXPECT_EQ(Bytes(output), Bytes(actual));
  293. return true;
  294. }
  295. bssl::UniquePtr<EVP_PKEY_CTX> ctx(EVP_PKEY_CTX_new(key, nullptr));
  296. if (!ctx ||
  297. !key_op_init(ctx.get()) ||
  298. (digest != nullptr &&
  299. !EVP_PKEY_CTX_set_signature_md(ctx.get(), digest)) ||
  300. !SetupContext(t, ctx.get())) {
  301. return false;
  302. }
  303. if (is_verify) {
  304. return !!EVP_PKEY_verify(ctx.get(), output.data(), output.size(),
  305. input.data(), input.size());
  306. }
  307. size_t len;
  308. if (!key_op(ctx.get(), nullptr, &len, input.data(), input.size())) {
  309. return false;
  310. }
  311. actual.resize(len);
  312. if (!key_op(ctx.get(), actual.data(), &len, input.data(), input.size())) {
  313. return false;
  314. }
  315. // Encryption is non-deterministic, so we check by decrypting.
  316. if (t->HasAttribute("CheckDecrypt")) {
  317. size_t plaintext_len;
  318. ctx.reset(EVP_PKEY_CTX_new(key, nullptr));
  319. if (!ctx ||
  320. !EVP_PKEY_decrypt_init(ctx.get()) ||
  321. (digest != nullptr &&
  322. !EVP_PKEY_CTX_set_signature_md(ctx.get(), digest)) ||
  323. !SetupContext(t, ctx.get()) ||
  324. !EVP_PKEY_decrypt(ctx.get(), nullptr, &plaintext_len, actual.data(),
  325. actual.size())) {
  326. return false;
  327. }
  328. output.resize(plaintext_len);
  329. if (!EVP_PKEY_decrypt(ctx.get(), output.data(), &plaintext_len,
  330. actual.data(), actual.size())) {
  331. ADD_FAILURE() << "Could not decrypt result.";
  332. return false;
  333. }
  334. output.resize(plaintext_len);
  335. EXPECT_EQ(Bytes(input), Bytes(output)) << "Decrypted result mismatch.";
  336. return true;
  337. }
  338. // Some signature schemes are non-deterministic, so we check by verifying.
  339. if (t->HasAttribute("CheckVerify")) {
  340. ctx.reset(EVP_PKEY_CTX_new(key, nullptr));
  341. if (!ctx ||
  342. !EVP_PKEY_verify_init(ctx.get()) ||
  343. (digest != nullptr &&
  344. !EVP_PKEY_CTX_set_signature_md(ctx.get(), digest)) ||
  345. !SetupContext(t, ctx.get())) {
  346. return false;
  347. }
  348. if (t->HasAttribute("VerifyPSSSaltLength") &&
  349. !EVP_PKEY_CTX_set_rsa_pss_saltlen(
  350. ctx.get(),
  351. atoi(t->GetAttributeOrDie("VerifyPSSSaltLength").c_str()))) {
  352. return false;
  353. }
  354. EXPECT_TRUE(EVP_PKEY_verify(ctx.get(), actual.data(), actual.size(),
  355. input.data(), input.size()))
  356. << "Could not verify result.";
  357. return true;
  358. }
  359. // By default, check by comparing the result against Output.
  360. if (!t->GetBytes(&output, "Output")) {
  361. return false;
  362. }
  363. actual.resize(len);
  364. EXPECT_EQ(Bytes(output), Bytes(actual));
  365. return true;
  366. }
  367. TEST(EVPTest, TestVectors) {
  368. KeyMap key_map;
  369. FileTestGTest("crypto/evp/evp_tests.txt", [&](FileTest *t) {
  370. bool result = TestEVP(t, &key_map);
  371. if (t->HasAttribute("Error")) {
  372. ASSERT_FALSE(result) << "Operation unexpectedly succeeded.";
  373. uint32_t err = ERR_peek_error();
  374. EXPECT_EQ(t->GetAttributeOrDie("Error"), ERR_reason_error_string(err));
  375. } else if (!result) {
  376. ADD_FAILURE() << "Operation unexpectedly failed.";
  377. }
  378. });
  379. }
  380. static void RunWycheproofTest(const char *path) {
  381. SCOPED_TRACE(path);
  382. FileTestGTest(path, [](FileTest *t) {
  383. t->IgnoreInstruction("key.type");
  384. // Extra ECDSA fields.
  385. t->IgnoreInstruction("key.curve");
  386. t->IgnoreInstruction("key.keySize");
  387. t->IgnoreInstruction("key.wx");
  388. t->IgnoreInstruction("key.wy");
  389. // Extra RSA fields.
  390. t->IgnoreInstruction("e");
  391. t->IgnoreInstruction("keyAsn");
  392. t->IgnoreInstruction("keysize");
  393. t->IgnoreInstruction("n");
  394. t->IgnoreAttribute("padding");
  395. std::vector<uint8_t> der;
  396. ASSERT_TRUE(t->GetInstructionBytes(&der, "keyDer"));
  397. CBS cbs;
  398. CBS_init(&cbs, der.data(), der.size());
  399. bssl::UniquePtr<EVP_PKEY> key(EVP_parse_public_key(&cbs));
  400. ASSERT_TRUE(key);
  401. const EVP_MD *md = GetWycheproofDigest(t, "sha", true);
  402. ASSERT_TRUE(md);
  403. std::vector<uint8_t> msg;
  404. ASSERT_TRUE(t->GetBytes(&msg, "msg"));
  405. std::vector<uint8_t> sig;
  406. ASSERT_TRUE(t->GetBytes(&sig, "sig"));
  407. bssl::ScopedEVP_MD_CTX ctx;
  408. ASSERT_TRUE(
  409. EVP_DigestVerifyInit(ctx.get(), nullptr, md, nullptr, key.get()));
  410. WycheproofResult result;
  411. ASSERT_TRUE(GetWycheproofResult(t, &result));
  412. EXPECT_EQ(result == WycheproofResult::kValid ? 1 : 0,
  413. EVP_DigestVerify(ctx.get(), sig.data(), sig.size(), msg.data(),
  414. msg.size()));
  415. });
  416. }
  417. TEST(EVPTest, Wycheproof) {
  418. RunWycheproofTest("third_party/wycheproof/ecdsa_secp224r1_sha224_test.txt");
  419. RunWycheproofTest("third_party/wycheproof/ecdsa_secp224r1_sha256_test.txt");
  420. RunWycheproofTest("third_party/wycheproof/ecdsa_secp256r1_sha256_test.txt");
  421. RunWycheproofTest("third_party/wycheproof/ecdsa_secp384r1_sha384_test.txt");
  422. RunWycheproofTest("third_party/wycheproof/ecdsa_secp384r1_sha512_test.txt");
  423. RunWycheproofTest("third_party/wycheproof/ecdsa_secp521r1_sha512_test.txt");
  424. RunWycheproofTest("third_party/wycheproof/rsa_signature_test.txt");
  425. }