Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

416 строки
13 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. // evp_test dispatches between multiple test types. PrivateKey tests take a key
  75. // name parameter and single block, decode it as a PEM private key, and save it
  76. // under that key name. Decrypt, Sign, and Verify tests take a previously
  77. // imported key name as parameter and test their respective operations.
  78. static const EVP_MD *GetDigest(FileTest *t, const std::string &name) {
  79. if (name == "MD5") {
  80. return EVP_md5();
  81. } else if (name == "SHA1") {
  82. return EVP_sha1();
  83. } else if (name == "SHA224") {
  84. return EVP_sha224();
  85. } else if (name == "SHA256") {
  86. return EVP_sha256();
  87. } else if (name == "SHA384") {
  88. return EVP_sha384();
  89. } else if (name == "SHA512") {
  90. return EVP_sha512();
  91. }
  92. ADD_FAILURE() << "Unknown digest: " << name;
  93. return nullptr;
  94. }
  95. static int GetKeyType(FileTest *t, const std::string &name) {
  96. if (name == "RSA") {
  97. return EVP_PKEY_RSA;
  98. }
  99. if (name == "EC") {
  100. return EVP_PKEY_EC;
  101. }
  102. if (name == "DSA") {
  103. return EVP_PKEY_DSA;
  104. }
  105. if (name == "Ed25519") {
  106. return EVP_PKEY_ED25519;
  107. }
  108. ADD_FAILURE() << "Unknown key type: " << name;
  109. return EVP_PKEY_NONE;
  110. }
  111. static int GetRSAPadding(FileTest *t, int *out, const std::string &name) {
  112. if (name == "PKCS1") {
  113. *out = RSA_PKCS1_PADDING;
  114. return true;
  115. }
  116. if (name == "PSS") {
  117. *out = RSA_PKCS1_PSS_PADDING;
  118. return true;
  119. }
  120. if (name == "OAEP") {
  121. *out = RSA_PKCS1_OAEP_PADDING;
  122. return true;
  123. }
  124. ADD_FAILURE() << "Unknown RSA padding mode: " << name;
  125. return false;
  126. }
  127. using KeyMap = std::map<std::string, bssl::UniquePtr<EVP_PKEY>>;
  128. static bool ImportKey(FileTest *t, KeyMap *key_map,
  129. EVP_PKEY *(*parse_func)(CBS *cbs),
  130. int (*marshal_func)(CBB *cbb, const EVP_PKEY *key)) {
  131. std::vector<uint8_t> input;
  132. if (!t->GetBytes(&input, "Input")) {
  133. return false;
  134. }
  135. CBS cbs;
  136. CBS_init(&cbs, input.data(), input.size());
  137. bssl::UniquePtr<EVP_PKEY> pkey(parse_func(&cbs));
  138. if (!pkey) {
  139. return false;
  140. }
  141. std::string key_type;
  142. if (!t->GetAttribute(&key_type, "Type")) {
  143. return false;
  144. }
  145. EXPECT_EQ(GetKeyType(t, key_type), EVP_PKEY_id(pkey.get()));
  146. // The key must re-encode correctly.
  147. bssl::ScopedCBB cbb;
  148. uint8_t *der;
  149. size_t der_len;
  150. if (!CBB_init(cbb.get(), 0) ||
  151. !marshal_func(cbb.get(), pkey.get()) ||
  152. !CBB_finish(cbb.get(), &der, &der_len)) {
  153. return false;
  154. }
  155. bssl::UniquePtr<uint8_t> free_der(der);
  156. std::vector<uint8_t> output = input;
  157. if (t->HasAttribute("Output") &&
  158. !t->GetBytes(&output, "Output")) {
  159. return false;
  160. }
  161. EXPECT_EQ(Bytes(output), Bytes(der, der_len)) << "Re-encoding the key did not match.";
  162. // Save the key for future tests.
  163. const std::string &key_name = t->GetParameter();
  164. EXPECT_EQ(0u, key_map->count(key_name)) << "Duplicate key: " << key_name;
  165. (*key_map)[key_name] = std::move(pkey);
  166. return true;
  167. }
  168. // SetupContext configures |ctx| based on attributes in |t|, with the exception
  169. // of the signing digest which must be configured externally.
  170. static bool SetupContext(FileTest *t, EVP_PKEY_CTX *ctx) {
  171. if (t->HasAttribute("RSAPadding")) {
  172. int padding;
  173. if (!GetRSAPadding(t, &padding, t->GetAttributeOrDie("RSAPadding")) ||
  174. !EVP_PKEY_CTX_set_rsa_padding(ctx, padding)) {
  175. return false;
  176. }
  177. }
  178. if (t->HasAttribute("PSSSaltLength") &&
  179. !EVP_PKEY_CTX_set_rsa_pss_saltlen(
  180. ctx, atoi(t->GetAttributeOrDie("PSSSaltLength").c_str()))) {
  181. return false;
  182. }
  183. if (t->HasAttribute("MGF1Digest")) {
  184. const EVP_MD *digest = GetDigest(t, t->GetAttributeOrDie("MGF1Digest"));
  185. if (digest == nullptr || !EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, digest)) {
  186. return false;
  187. }
  188. }
  189. if (t->HasAttribute("OAEPDigest")) {
  190. const EVP_MD *digest = GetDigest(t, t->GetAttributeOrDie("OAEPDigest"));
  191. if (digest == nullptr || !EVP_PKEY_CTX_set_rsa_oaep_md(ctx, digest)) {
  192. return false;
  193. }
  194. }
  195. if (t->HasAttribute("OAEPLabel")) {
  196. std::vector<uint8_t> label;
  197. if (!t->GetBytes(&label, "OAEPLabel")) {
  198. return false;
  199. }
  200. // For historical reasons, |EVP_PKEY_CTX_set0_rsa_oaep_label| expects to be
  201. // take ownership of the input.
  202. bssl::UniquePtr<uint8_t> buf(
  203. reinterpret_cast<uint8_t *>(BUF_memdup(label.data(), label.size())));
  204. if (!buf ||
  205. !EVP_PKEY_CTX_set0_rsa_oaep_label(ctx, buf.get(), label.size())) {
  206. return false;
  207. }
  208. buf.release();
  209. }
  210. return true;
  211. }
  212. static bool TestEVP(FileTest *t, KeyMap *key_map) {
  213. if (t->GetType() == "PrivateKey") {
  214. return ImportKey(t, key_map, EVP_parse_private_key,
  215. EVP_marshal_private_key);
  216. }
  217. if (t->GetType() == "PublicKey") {
  218. return ImportKey(t, key_map, EVP_parse_public_key, EVP_marshal_public_key);
  219. }
  220. int (*key_op_init)(EVP_PKEY_CTX *ctx) = nullptr;
  221. int (*key_op)(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *out_len,
  222. const uint8_t *in, size_t in_len) = nullptr;
  223. int (*md_op_init)(EVP_MD_CTX * ctx, EVP_PKEY_CTX * *pctx, const EVP_MD *type,
  224. ENGINE *e, EVP_PKEY *pkey) = nullptr;
  225. bool is_verify = false;
  226. if (t->GetType() == "Decrypt") {
  227. key_op_init = EVP_PKEY_decrypt_init;
  228. key_op = EVP_PKEY_decrypt;
  229. } else if (t->GetType() == "Sign") {
  230. key_op_init = EVP_PKEY_sign_init;
  231. key_op = EVP_PKEY_sign;
  232. } else if (t->GetType() == "Verify") {
  233. key_op_init = EVP_PKEY_verify_init;
  234. is_verify = true;
  235. } else if (t->GetType() == "SignMessage") {
  236. md_op_init = EVP_DigestSignInit;
  237. } else if (t->GetType() == "VerifyMessage") {
  238. md_op_init = EVP_DigestVerifyInit;
  239. is_verify = true;
  240. } else if (t->GetType() == "Encrypt") {
  241. key_op_init = EVP_PKEY_encrypt_init;
  242. key_op = EVP_PKEY_encrypt;
  243. } else {
  244. ADD_FAILURE() << "Unknown test " << t->GetType();
  245. return false;
  246. }
  247. // Load the key.
  248. const std::string &key_name = t->GetParameter();
  249. if (key_map->count(key_name) == 0) {
  250. ADD_FAILURE() << "Could not find key " << key_name;
  251. return false;
  252. }
  253. EVP_PKEY *key = (*key_map)[key_name].get();
  254. const EVP_MD *digest = nullptr;
  255. if (t->HasAttribute("Digest")) {
  256. digest = GetDigest(t, t->GetAttributeOrDie("Digest"));
  257. if (digest == nullptr) {
  258. return false;
  259. }
  260. }
  261. // For verify tests, the "output" is the signature. Read it now so that, for
  262. // tests which expect a failure in SetupContext, the attribute is still
  263. // consumed.
  264. std::vector<uint8_t> input, actual, output;
  265. if (!t->GetBytes(&input, "Input") ||
  266. (is_verify && !t->GetBytes(&output, "Output"))) {
  267. return false;
  268. }
  269. if (md_op_init) {
  270. bssl::ScopedEVP_MD_CTX ctx;
  271. EVP_PKEY_CTX *pctx;
  272. if (!md_op_init(ctx.get(), &pctx, digest, nullptr, key) ||
  273. !SetupContext(t, pctx)) {
  274. return false;
  275. }
  276. if (is_verify) {
  277. return !!EVP_DigestVerify(ctx.get(), output.data(), output.size(),
  278. input.data(), input.size());
  279. }
  280. size_t len;
  281. if (!EVP_DigestSign(ctx.get(), nullptr, &len, input.data(), input.size())) {
  282. return false;
  283. }
  284. actual.resize(len);
  285. if (!EVP_DigestSign(ctx.get(), actual.data(), &len, input.data(),
  286. input.size()) ||
  287. !t->GetBytes(&output, "Output")) {
  288. return false;
  289. }
  290. actual.resize(len);
  291. EXPECT_EQ(Bytes(output), Bytes(actual));
  292. return true;
  293. }
  294. bssl::UniquePtr<EVP_PKEY_CTX> ctx(EVP_PKEY_CTX_new(key, nullptr));
  295. if (!ctx ||
  296. !key_op_init(ctx.get()) ||
  297. (digest != nullptr &&
  298. !EVP_PKEY_CTX_set_signature_md(ctx.get(), digest)) ||
  299. !SetupContext(t, ctx.get())) {
  300. return false;
  301. }
  302. if (is_verify) {
  303. return !!EVP_PKEY_verify(ctx.get(), output.data(), output.size(),
  304. input.data(), input.size());
  305. }
  306. size_t len;
  307. if (!key_op(ctx.get(), nullptr, &len, input.data(), input.size())) {
  308. return false;
  309. }
  310. actual.resize(len);
  311. if (!key_op(ctx.get(), actual.data(), &len, input.data(), input.size())) {
  312. return false;
  313. }
  314. // Encryption is non-deterministic, so we check by decrypting.
  315. if (t->HasAttribute("CheckDecrypt")) {
  316. size_t plaintext_len;
  317. ctx.reset(EVP_PKEY_CTX_new(key, nullptr));
  318. if (!ctx ||
  319. !EVP_PKEY_decrypt_init(ctx.get()) ||
  320. (digest != nullptr &&
  321. !EVP_PKEY_CTX_set_signature_md(ctx.get(), digest)) ||
  322. !SetupContext(t, ctx.get()) ||
  323. !EVP_PKEY_decrypt(ctx.get(), nullptr, &plaintext_len, actual.data(),
  324. actual.size())) {
  325. return false;
  326. }
  327. output.resize(plaintext_len);
  328. if (!EVP_PKEY_decrypt(ctx.get(), output.data(), &plaintext_len,
  329. actual.data(), actual.size())) {
  330. ADD_FAILURE() << "Could not decrypt result.";
  331. return false;
  332. }
  333. output.resize(plaintext_len);
  334. EXPECT_EQ(Bytes(input), Bytes(output)) << "Decrypted result mismatch.";
  335. return true;
  336. }
  337. // Some signature schemes are non-deterministic, so we check by verifying.
  338. if (t->HasAttribute("CheckVerify")) {
  339. ctx.reset(EVP_PKEY_CTX_new(key, nullptr));
  340. if (!ctx ||
  341. !EVP_PKEY_verify_init(ctx.get()) ||
  342. (digest != nullptr &&
  343. !EVP_PKEY_CTX_set_signature_md(ctx.get(), digest)) ||
  344. !SetupContext(t, ctx.get())) {
  345. return false;
  346. }
  347. if (t->HasAttribute("VerifyPSSSaltLength") &&
  348. !EVP_PKEY_CTX_set_rsa_pss_saltlen(
  349. ctx.get(),
  350. atoi(t->GetAttributeOrDie("VerifyPSSSaltLength").c_str()))) {
  351. return false;
  352. }
  353. EXPECT_TRUE(EVP_PKEY_verify(ctx.get(), actual.data(), actual.size(),
  354. input.data(), input.size()))
  355. << "Could not verify result.";
  356. return true;
  357. }
  358. // By default, check by comparing the result against Output.
  359. if (!t->GetBytes(&output, "Output")) {
  360. return false;
  361. }
  362. actual.resize(len);
  363. EXPECT_EQ(Bytes(output), Bytes(actual));
  364. return true;
  365. }
  366. TEST(EVPTest, TestVectors) {
  367. KeyMap key_map;
  368. FileTestGTest("crypto/evp/evp_tests.txt", [&](FileTest *t) {
  369. bool result = TestEVP(t, &key_map);
  370. if (t->HasAttribute("Error")) {
  371. ASSERT_FALSE(result) << "Operation unexpectedly succeeded.";
  372. uint32_t err = ERR_peek_error();
  373. EXPECT_EQ(t->GetAttributeOrDie("Error"), ERR_reason_error_string(err));
  374. } else if (!result) {
  375. ADD_FAILURE() << "Operation unexpectedly failed.";
  376. }
  377. });
  378. }