選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

330 行
9.9 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 <time.h>
  21. #include <openssl/aead.h>
  22. #include <openssl/bio.h>
  23. #include <openssl/digest.h>
  24. #include <openssl/obj.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. TimeResults results;
  121. std::unique_ptr<uint8_t[]> sig(new uint8_t[RSA_size(key)]);
  122. const uint8_t fake_sha256_hash[32] = {0};
  123. unsigned sig_len;
  124. if (!TimeFunction(&results,
  125. [key, &sig, &fake_sha256_hash, &sig_len]() -> bool {
  126. return RSA_sign(NID_sha256, fake_sha256_hash, sizeof(fake_sha256_hash),
  127. sig.get(), &sig_len, key);
  128. })) {
  129. fprintf(stderr, "RSA_sign failed.\n");
  130. BIO_print_errors_fp(stderr);
  131. return false;
  132. }
  133. results.Print(key_name + " signing");
  134. if (!TimeFunction(&results,
  135. [key, &fake_sha256_hash, &sig, sig_len]() -> bool {
  136. return RSA_verify(NID_sha256, fake_sha256_hash,
  137. sizeof(fake_sha256_hash), sig.get(), sig_len, key);
  138. })) {
  139. fprintf(stderr, "RSA_verify failed.\n");
  140. BIO_print_errors_fp(stderr);
  141. return false;
  142. }
  143. results.Print(key_name + " verify");
  144. return true;
  145. }
  146. template<typename T>
  147. struct free_functor {
  148. void operator()(T* ptr) {
  149. free(ptr);
  150. }
  151. };
  152. static uint8_t *align(uint8_t *in, unsigned alignment) {
  153. return reinterpret_cast<uint8_t *>(
  154. (reinterpret_cast<uintptr_t>(in) + alignment) & ~(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, free_functor<uint8_t>> in_storage(
  168. new uint8_t[chunk_len + kAlignment]);
  169. std::unique_ptr<uint8_t, free_functor<uint8_t>> out_storage(
  170. new uint8_t[chunk_len + overhead_len + kAlignment]);
  171. std::unique_ptr<uint8_t[]> ad(new uint8_t[ad_len]);
  172. memset(ad.get(), 0, ad_len);
  173. uint8_t *const in = align(in_storage.get(), kAlignment);
  174. memset(in, 0, chunk_len);
  175. uint8_t *const out = align(out_storage.get(), kAlignment);
  176. memset(out, 0, chunk_len + overhead_len);
  177. if (!EVP_AEAD_CTX_init(&ctx, aead, key.get(), key_len,
  178. EVP_AEAD_DEFAULT_TAG_LENGTH, NULL)) {
  179. fprintf(stderr, "Failed to create EVP_AEAD_CTX.\n");
  180. BIO_print_errors_fp(stderr);
  181. return false;
  182. }
  183. TimeResults results;
  184. if (!TimeFunction(&results, [chunk_len, overhead_len, nonce_len, ad_len, in,
  185. out, &ctx, &nonce, &ad]() -> bool {
  186. size_t out_len;
  187. return EVP_AEAD_CTX_seal(
  188. &ctx, out, &out_len, chunk_len + overhead_len, nonce.get(),
  189. nonce_len, in, chunk_len, ad.get(), ad_len);
  190. })) {
  191. fprintf(stderr, "EVP_AEAD_CTX_seal failed.\n");
  192. BIO_print_errors_fp(stderr);
  193. return false;
  194. }
  195. results.PrintWithBytes(name + " seal", chunk_len);
  196. EVP_AEAD_CTX_cleanup(&ctx);
  197. return true;
  198. }
  199. static bool SpeedAEAD(const EVP_AEAD *aead, const std::string &name,
  200. size_t ad_len) {
  201. return SpeedAEADChunk(aead, name + " (16 bytes)", 16, ad_len) &&
  202. SpeedAEADChunk(aead, name + " (1350 bytes)", 1350, ad_len) &&
  203. SpeedAEADChunk(aead, name + " (8192 bytes)", 8192, ad_len);
  204. }
  205. static bool SpeedHashChunk(const EVP_MD *md, const std::string &name,
  206. size_t chunk_len) {
  207. EVP_MD_CTX *ctx = EVP_MD_CTX_create();
  208. uint8_t scratch[8192];
  209. if (chunk_len > sizeof(scratch)) {
  210. return false;
  211. }
  212. TimeResults results;
  213. if (!TimeFunction(&results, [ctx, md, chunk_len, &scratch]() -> bool {
  214. uint8_t digest[EVP_MAX_MD_SIZE];
  215. unsigned int md_len;
  216. return EVP_DigestInit_ex(ctx, md, NULL /* ENGINE */) &&
  217. EVP_DigestUpdate(ctx, scratch, chunk_len) &&
  218. EVP_DigestFinal_ex(ctx, digest, &md_len);
  219. })) {
  220. fprintf(stderr, "EVP_DigestInit_ex failed.\n");
  221. BIO_print_errors_fp(stderr);
  222. return false;
  223. }
  224. results.PrintWithBytes(name, chunk_len);
  225. EVP_MD_CTX_destroy(ctx);
  226. return true;
  227. }
  228. static bool SpeedHash(const EVP_MD *md, const std::string &name) {
  229. return SpeedHashChunk(md, name + " (16 bytes)", 16) &&
  230. SpeedHashChunk(md, name + " (256 bytes)", 256) &&
  231. SpeedHashChunk(md, name + " (8192 bytes)", 8192);
  232. }
  233. bool Speed(const std::vector<std::string> &args) {
  234. const uint8_t *inp;
  235. RSA *key = NULL;
  236. inp = kDERRSAPrivate2048;
  237. if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate2048Len)) {
  238. fprintf(stderr, "Failed to parse RSA key.\n");
  239. BIO_print_errors_fp(stderr);
  240. return false;
  241. }
  242. if (!SpeedRSA("RSA 2048", key)) {
  243. return false;
  244. }
  245. RSA_free(key);
  246. key = NULL;
  247. inp = kDERRSAPrivate4096;
  248. if (NULL == d2i_RSAPrivateKey(&key, &inp, kDERRSAPrivate4096Len)) {
  249. fprintf(stderr, "Failed to parse 4096-bit RSA key.\n");
  250. BIO_print_errors_fp(stderr);
  251. return 1;
  252. }
  253. if (!SpeedRSA("RSA 4096", key)) {
  254. return false;
  255. }
  256. RSA_free(key);
  257. // kTLSADLen is the number of bytes of additional data that TLS passes to
  258. // AEADs.
  259. static const size_t kTLSADLen = 13;
  260. // kLegacyADLen is the number of bytes that TLS passes to the "legacy" AEADs.
  261. // These are AEADs that weren't originally defined as AEADs, but which we use
  262. // via the AEAD interface. In order for that to work, they have some TLS
  263. // knowledge in them and construct a couple of the AD bytes internally.
  264. static const size_t kLegacyADLen = kTLSADLen - 2;
  265. if (!SpeedAEAD(EVP_aead_aes_128_gcm(), "AES-128-GCM", kTLSADLen) ||
  266. !SpeedAEAD(EVP_aead_aes_256_gcm(), "AES-256-GCM", kTLSADLen) ||
  267. !SpeedAEAD(EVP_aead_chacha20_poly1305(), "ChaCha20-Poly1305", kTLSADLen) ||
  268. !SpeedAEAD(EVP_aead_rc4_md5_tls(), "RC4-MD5", kLegacyADLen) ||
  269. !SpeedAEAD(EVP_aead_aes_128_cbc_sha1_tls(), "AES-128-CBC-SHA1", kLegacyADLen) ||
  270. !SpeedAEAD(EVP_aead_aes_256_cbc_sha1_tls(), "AES-256-CBC-SHA1", kLegacyADLen) ||
  271. !SpeedHash(EVP_sha1(), "SHA-1") ||
  272. !SpeedHash(EVP_sha256(), "SHA-256") ||
  273. !SpeedHash(EVP_sha512(), "SHA-512")) {
  274. return false;
  275. }
  276. return 0;
  277. }