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.
 
 
 
 
 
 

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