Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

481 řádky
14 KiB

  1. /* Copyright (c) 2014, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #include <string>
  15. #include <functional>
  16. #include <memory>
  17. #include <vector>
  18. #include <stdint.h>
  19. #include <string.h>
  20. #include <openssl/aead.h>
  21. #include <openssl/digest.h>
  22. #include <openssl/err.h>
  23. #include <openssl/obj.h>
  24. #include <openssl/rand.h>
  25. #include <openssl/rsa.h>
  26. #if defined(OPENSSL_WINDOWS)
  27. #pragma warning(push, 3)
  28. #include <windows.h>
  29. #pragma warning(pop)
  30. #elif defined(OPENSSL_APPLE)
  31. #include <sys/time.h>
  32. #endif
  33. #include "../crypto/test/scoped_types.h"
  34. #include "internal.h"
  35. // TimeResults represents the results of benchmarking a function.
  36. struct TimeResults {
  37. // num_calls is the number of function calls done in the time period.
  38. unsigned num_calls;
  39. // us is the number of microseconds that elapsed in the time period.
  40. unsigned us;
  41. void Print(const std::string &description) {
  42. printf("Did %u %s operations in %uus (%.1f ops/sec)\n", num_calls,
  43. description.c_str(), us,
  44. (static_cast<double>(num_calls) / us) * 1000000);
  45. }
  46. void PrintWithBytes(const std::string &description, size_t bytes_per_call) {
  47. printf("Did %u %s operations in %uus (%.1f ops/sec): %.1f MB/s\n",
  48. num_calls, description.c_str(), us,
  49. (static_cast<double>(num_calls) / us) * 1000000,
  50. static_cast<double>(bytes_per_call * num_calls) / us);
  51. }
  52. };
  53. #if defined(OPENSSL_WINDOWS)
  54. static uint64_t time_now() { return GetTickCount64() * 1000; }
  55. #elif defined(OPENSSL_APPLE)
  56. static uint64_t time_now() {
  57. struct timeval tv;
  58. uint64_t ret;
  59. gettimeofday(&tv, NULL);
  60. ret = tv.tv_sec;
  61. ret *= 1000000;
  62. ret += tv.tv_usec;
  63. return ret;
  64. }
  65. #else
  66. static uint64_t time_now() {
  67. struct timespec ts;
  68. clock_gettime(CLOCK_MONOTONIC, &ts);
  69. uint64_t ret = ts.tv_sec;
  70. ret *= 1000000;
  71. ret += ts.tv_nsec / 1000;
  72. return ret;
  73. }
  74. #endif
  75. static bool TimeFunction(TimeResults *results, std::function<bool()> func) {
  76. // kTotalMS is the total amount of time that we'll aim to measure a function
  77. // for.
  78. static const uint64_t kTotalUS = 1000000;
  79. uint64_t start = time_now(), now, delta;
  80. unsigned done = 0, iterations_between_time_checks;
  81. if (!func()) {
  82. return false;
  83. }
  84. now = time_now();
  85. delta = now - start;
  86. if (delta == 0) {
  87. iterations_between_time_checks = 250;
  88. } else {
  89. // Aim for about 100ms between time checks.
  90. iterations_between_time_checks =
  91. static_cast<double>(100000) / static_cast<double>(delta);
  92. if (iterations_between_time_checks > 1000) {
  93. iterations_between_time_checks = 1000;
  94. } else if (iterations_between_time_checks < 1) {
  95. iterations_between_time_checks = 1;
  96. }
  97. }
  98. for (;;) {
  99. for (unsigned i = 0; i < iterations_between_time_checks; i++) {
  100. if (!func()) {
  101. return false;
  102. }
  103. done++;
  104. }
  105. now = time_now();
  106. if (now - start > kTotalUS) {
  107. break;
  108. }
  109. }
  110. results->us = now - start;
  111. results->num_calls = done;
  112. return true;
  113. }
  114. static bool SpeedRSA(const std::string &key_name, RSA *key,
  115. const std::string &selected) {
  116. if (!selected.empty() && key_name.find(selected) == std::string::npos) {
  117. return true;
  118. }
  119. std::unique_ptr<uint8_t[]> sig(new uint8_t[RSA_size(key)]);
  120. const uint8_t fake_sha256_hash[32] = {0};
  121. unsigned sig_len;
  122. TimeResults results;
  123. if (!TimeFunction(&results,
  124. [key, &sig, &fake_sha256_hash, &sig_len]() -> bool {
  125. return RSA_sign(NID_sha256, fake_sha256_hash, sizeof(fake_sha256_hash),
  126. sig.get(), &sig_len, key);
  127. })) {
  128. fprintf(stderr, "RSA_sign failed.\n");
  129. ERR_print_errors_fp(stderr);
  130. return false;
  131. }
  132. results.Print(key_name + " signing");
  133. if (!TimeFunction(&results,
  134. [key, &fake_sha256_hash, &sig, sig_len]() -> bool {
  135. return RSA_verify(NID_sha256, fake_sha256_hash,
  136. sizeof(fake_sha256_hash), sig.get(), sig_len, key);
  137. })) {
  138. fprintf(stderr, "RSA_verify failed.\n");
  139. ERR_print_errors_fp(stderr);
  140. return false;
  141. }
  142. results.Print(key_name + " verify");
  143. return true;
  144. }
  145. static uint8_t *align(uint8_t *in, unsigned alignment) {
  146. return reinterpret_cast<uint8_t *>(
  147. (reinterpret_cast<uintptr_t>(in) + alignment) &
  148. ~static_cast<size_t>(alignment - 1));
  149. }
  150. static bool SpeedAEADChunk(const EVP_AEAD *aead, const std::string &name,
  151. size_t chunk_len, size_t ad_len) {
  152. static const unsigned kAlignment = 16;
  153. EVP_AEAD_CTX ctx;
  154. const size_t key_len = EVP_AEAD_key_length(aead);
  155. const size_t nonce_len = EVP_AEAD_nonce_length(aead);
  156. const size_t overhead_len = EVP_AEAD_max_overhead(aead);
  157. std::unique_ptr<uint8_t[]> key(new uint8_t[key_len]);
  158. memset(key.get(), 0, key_len);
  159. std::unique_ptr<uint8_t[]> nonce(new uint8_t[nonce_len]);
  160. memset(nonce.get(), 0, nonce_len);
  161. std::unique_ptr<uint8_t[]> in_storage(new uint8_t[chunk_len + kAlignment]);
  162. std::unique_ptr<uint8_t[]> out_storage(new uint8_t[chunk_len + overhead_len + kAlignment]);
  163. std::unique_ptr<uint8_t[]> ad(new uint8_t[ad_len]);
  164. memset(ad.get(), 0, ad_len);
  165. uint8_t *const in = align(in_storage.get(), kAlignment);
  166. memset(in, 0, chunk_len);
  167. uint8_t *const out = align(out_storage.get(), kAlignment);
  168. memset(out, 0, chunk_len + overhead_len);
  169. if (!EVP_AEAD_CTX_init_with_direction(&ctx, aead, key.get(), key_len,
  170. EVP_AEAD_DEFAULT_TAG_LENGTH,
  171. evp_aead_seal)) {
  172. fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
  173. ERR_print_errors_fp(stderr);
  174. return false;
  175. }
  176. TimeResults results;
  177. if (!TimeFunction(&results, [chunk_len, overhead_len, nonce_len, ad_len, in,
  178. out, &ctx, &nonce, &ad]() -> bool {
  179. size_t out_len;
  180. return EVP_AEAD_CTX_seal(
  181. &ctx, out, &out_len, chunk_len + overhead_len, nonce.get(),
  182. nonce_len, in, chunk_len, ad.get(), ad_len);
  183. })) {
  184. fprintf(stderr, "EVP_AEAD_CTX_seal failed.\n");
  185. ERR_print_errors_fp(stderr);
  186. return false;
  187. }
  188. results.PrintWithBytes(name + " seal", chunk_len);
  189. EVP_AEAD_CTX_cleanup(&ctx);
  190. return true;
  191. }
  192. static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name,
  193. size_t ad_len, const std::string &selected) {
  194. if (!selected.empty() && name.find(selected) == std::string::npos) {
  195. return true;
  196. }
  197. return SpeedAEADChunk(aead, name + " (16 bytes)", 16, ad_len) &&
  198. SpeedAEADChunk(aead, name + " (1350 bytes)", 1350, ad_len) &&
  199. SpeedAEADChunk(aead, name + " (8192 bytes)", 8192, ad_len);
  200. }
  201. static bool SpeedHashChunk(const EVP_MD *md, const std::string &name,
  202. size_t chunk_len) {
  203. EVP_MD_CTX *ctx = EVP_MD_CTX_create();
  204. uint8_t scratch[8192];
  205. if (chunk_len > sizeof(scratch)) {
  206. return false;
  207. }
  208. TimeResults results;
  209. if (!TimeFunction(&results, [ctx, md, chunk_len, &scratch]() -> bool {
  210. uint8_t digest[EVP_MAX_MD_SIZE];
  211. unsigned int md_len;
  212. return EVP_DigestInit_ex(ctx, md, NULL /* ENGINE */) &&
  213. EVP_DigestUpdate(ctx, scratch, chunk_len) &&
  214. EVP_DigestFinal_ex(ctx, digest, &md_len);
  215. })) {
  216. fprintf(stderr, "EVP_DigestInit_ex failed.\n");
  217. ERR_print_errors_fp(stderr);
  218. return false;
  219. }
  220. results.PrintWithBytes(name, chunk_len);
  221. EVP_MD_CTX_destroy(ctx);
  222. return true;
  223. }
  224. static bool SpeedHash(const EVP_MD *md, const std::string &name,
  225. const std::string &selected) {
  226. if (!selected.empty() && name.find(selected) == std::string::npos) {
  227. return true;
  228. }
  229. return SpeedHashChunk(md, name + " (16 bytes)", 16) &&
  230. SpeedHashChunk(md, name + " (256 bytes)", 256) &&
  231. SpeedHashChunk(md, name + " (8192 bytes)", 8192);
  232. }
  233. static bool SpeedRandomChunk(const std::string name, size_t chunk_len) {
  234. uint8_t scratch[8192];
  235. if (chunk_len > sizeof(scratch)) {
  236. return false;
  237. }
  238. TimeResults results;
  239. if (!TimeFunction(&results, [chunk_len, &scratch]() -> bool {
  240. RAND_bytes(scratch, chunk_len);
  241. return true;
  242. })) {
  243. return false;
  244. }
  245. results.PrintWithBytes(name, chunk_len);
  246. return true;
  247. }
  248. static bool SpeedRandom(const std::string &selected) {
  249. if (!selected.empty() && selected != "RNG") {
  250. return true;
  251. }
  252. return SpeedRandomChunk("RNG (16 bytes)", 16) &&
  253. SpeedRandomChunk("RNG (256 bytes)", 256) &&
  254. SpeedRandomChunk("RNG (8192 bytes)", 8192);
  255. }
  256. static bool SpeedECDHCurve(const std::string &name, int nid,
  257. const std::string &selected) {
  258. if (!selected.empty() && name.find(selected) == std::string::npos) {
  259. return true;
  260. }
  261. TimeResults results;
  262. if (!TimeFunction(&results, [nid]() -> bool {
  263. ScopedEC_KEY key(EC_KEY_new_by_curve_name(nid));
  264. if (!key ||
  265. !EC_KEY_generate_key(key.get())) {
  266. return false;
  267. }
  268. const EC_GROUP *const group = EC_KEY_get0_group(key.get());
  269. ScopedEC_POINT point(EC_POINT_new(group));
  270. ScopedBN_CTX ctx(BN_CTX_new());
  271. ScopedBIGNUM x(BN_new());
  272. ScopedBIGNUM y(BN_new());
  273. if (!point || !ctx || !x || !y ||
  274. !EC_POINT_mul(group, point.get(), NULL,
  275. EC_KEY_get0_public_key(key.get()),
  276. EC_KEY_get0_private_key(key.get()), ctx.get()) ||
  277. !EC_POINT_get_affine_coordinates_GFp(group, point.get(), x.get(),
  278. y.get(), ctx.get())) {
  279. return false;
  280. }
  281. return true;
  282. })) {
  283. return false;
  284. }
  285. results.Print(name);
  286. return true;
  287. }
  288. static bool SpeedECDSACurve(const std::string &name, int nid,
  289. const std::string &selected) {
  290. if (!selected.empty() && name.find(selected) == std::string::npos) {
  291. return true;
  292. }
  293. ScopedEC_KEY key(EC_KEY_new_by_curve_name(nid));
  294. if (!key ||
  295. !EC_KEY_generate_key(key.get())) {
  296. return false;
  297. }
  298. uint8_t signature[256];
  299. if (ECDSA_size(key.get()) > sizeof(signature)) {
  300. return false;
  301. }
  302. uint8_t digest[20];
  303. memset(digest, 42, sizeof(digest));
  304. unsigned sig_len;
  305. TimeResults results;
  306. if (!TimeFunction(&results, [&key, &signature, &digest, &sig_len]() -> bool {
  307. return ECDSA_sign(0, digest, sizeof(digest), signature, &sig_len,
  308. key.get()) == 1;
  309. })) {
  310. return false;
  311. }
  312. results.Print(name + " signing");
  313. if (!TimeFunction(&results, [&key, &signature, &digest, sig_len]() -> bool {
  314. return ECDSA_verify(0, digest, sizeof(digest), signature, sig_len,
  315. key.get()) == 1;
  316. })) {
  317. return false;
  318. }
  319. results.Print(name + " verify");
  320. return true;
  321. }
  322. static bool SpeedECDH(const std::string &selected) {
  323. return SpeedECDHCurve("ECDH P-224", NID_secp224r1, selected) &&
  324. SpeedECDHCurve("ECDH P-256", NID_X9_62_prime256v1, selected) &&
  325. SpeedECDHCurve("ECDH P-384", NID_secp384r1, selected) &&
  326. SpeedECDHCurve("ECDH P-521", NID_secp521r1, selected);
  327. }
  328. static bool SpeedECDSA(const std::string &selected) {
  329. return SpeedECDSACurve("ECDSA P-224", NID_secp224r1, selected) &&
  330. SpeedECDSACurve("ECDSA P-256", NID_X9_62_prime256v1, selected) &&
  331. SpeedECDSACurve("ECDSA P-384", NID_secp384r1, selected) &&
  332. SpeedECDSACurve("ECDSA P-521", NID_secp521r1, selected);
  333. }
  334. bool Speed(const std::vector<std::string> &args) {
  335. std::string selected;
  336. if (args.size() > 1) {
  337. fprintf(stderr, "Usage: bssl speed [speed test selector, i.e. 'RNG']\n");
  338. return false;
  339. }
  340. if (args.size() > 0) {
  341. selected = args[0];
  342. }
  343. RSA *key = NULL;
  344. const uint8_t *inp = kDERRSAPrivate2048;
  345. if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate2048Len)) {
  346. fprintf(stderr, "Failed to parse RSA key.\n");
  347. ERR_print_errors_fp(stderr);
  348. return false;
  349. }
  350. if (!SpeedRSA("RSA 2048", key, selected)) {
  351. return false;
  352. }
  353. RSA_free(key);
  354. key = NULL;
  355. inp = kDERRSAPrivate3Prime2048;
  356. if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate3Prime2048Len)) {
  357. fprintf(stderr, "Failed to parse RSA key.\n");
  358. ERR_print_errors_fp(stderr);
  359. return false;
  360. }
  361. if (!SpeedRSA("RSA 2048 (3 prime, e=3)", key, selected)) {
  362. return false;
  363. }
  364. RSA_free(key);
  365. key = NULL;
  366. inp = kDERRSAPrivate4096;
  367. if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate4096Len)) {
  368. fprintf(stderr, "Failed to parse 4096-bit RSA key.\n");
  369. ERR_print_errors_fp(stderr);
  370. return 1;
  371. }
  372. if (!SpeedRSA("RSA 4096", key, selected)) {
  373. return false;
  374. }
  375. RSA_free(key);
  376. // kTLSADLen is the number of bytes of additional data that TLS passes to
  377. // AEADs.
  378. static const size_t kTLSADLen = 13;
  379. // kLegacyADLen is the number of bytes that TLS passes to the "legacy" AEADs.
  380. // These are AEADs that weren't originally defined as AEADs, but which we use
  381. // via the AEAD interface. In order for that to work, they have some TLS
  382. // knowledge in them and construct a couple of the AD bytes internally.
  383. static const size_t kLegacyADLen = kTLSADLen - 2;
  384. if (!SpeedAEAD(EVP_aead_aes_128_gcm(), "AES-128-GCM", kTLSADLen, selected) ||
  385. !SpeedAEAD(EVP_aead_aes_256_gcm(), "AES-256-GCM", kTLSADLen, selected) ||
  386. !SpeedAEAD(EVP_aead_chacha20_poly1305(), "ChaCha20-Poly1305", kTLSADLen,
  387. selected) ||
  388. !SpeedAEAD(EVP_aead_rc4_md5_tls(), "RC4-MD5", kLegacyADLen, selected) ||
  389. !SpeedAEAD(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1",
  390. kLegacyADLen, selected) ||
  391. !SpeedAEAD(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1",
  392. kLegacyADLen, selected) ||
  393. !SpeedHash(EVP_sha1(), "SHA-1", selected) ||
  394. !SpeedHash(EVP_sha256(), "SHA-256", selected) ||
  395. !SpeedHash(EVP_sha512(), "SHA-512", selected) ||
  396. !SpeedRandom(selected) ||
  397. !SpeedECDH(selected) ||
  398. !SpeedECDSA(selected)) {
  399. return false;
  400. }
  401. return true;
  402. }