No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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