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.
 
 
 
 
 
 

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