internal.h.grpc_back 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.]
  56. */
  57. /* ====================================================================
  58. * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
  59. *
  60. * Redistribution and use in source and binary forms, with or without
  61. * modification, are permitted provided that the following conditions
  62. * are met:
  63. *
  64. * 1. Redistributions of source code must retain the above copyright
  65. * notice, this list of conditions and the following disclaimer.
  66. *
  67. * 2. Redistributions in binary form must reproduce the above copyright
  68. * notice, this list of conditions and the following disclaimer in
  69. * the documentation and/or other materials provided with the
  70. * distribution.
  71. *
  72. * 3. All advertising materials mentioning features or use of this
  73. * software must display the following acknowledgment:
  74. * "This product includes software developed by the OpenSSL Project
  75. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  76. *
  77. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  78. * endorse or promote products derived from this software without
  79. * prior written permission. For written permission, please contact
  80. * openssl-core@openssl.org.
  81. *
  82. * 5. Products derived from this software may not be called "OpenSSL"
  83. * nor may "OpenSSL" appear in their names without prior written
  84. * permission of the OpenSSL Project.
  85. *
  86. * 6. Redistributions of any form whatsoever must retain the following
  87. * acknowledgment:
  88. * "This product includes software developed by the OpenSSL Project
  89. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  90. *
  91. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  92. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  93. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  94. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  95. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  96. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  97. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  98. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  99. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  100. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  101. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  102. * OF THE POSSIBILITY OF SUCH DAMAGE.
  103. * ====================================================================
  104. *
  105. * This product includes cryptographic software written by Eric Young
  106. * (eay@cryptsoft.com). This product includes software written by Tim
  107. * Hudson (tjh@cryptsoft.com). */
  108. #ifndef OPENSSL_HEADER_CRYPTO_INTERNAL_H
  109. #define OPENSSL_HEADER_CRYPTO_INTERNAL_H
  110. #include <openssl_grpc/crypto.h>
  111. #include <openssl_grpc/ex_data.h>
  112. #include <openssl_grpc/stack.h>
  113. #include <openssl_grpc/thread.h>
  114. #include <assert.h>
  115. #include <string.h>
  116. #if defined(BORINGSSL_CONSTANT_TIME_VALIDATION)
  117. #include <valgrind/memcheck.h>
  118. #endif
  119. #if !defined(__cplusplus)
  120. #if defined(_MSC_VER)
  121. #define alignas(x) __declspec(align(x))
  122. #define alignof __alignof
  123. #else
  124. #include <stdalign.h>
  125. #endif
  126. #endif
  127. #if defined(OPENSSL_THREADS) && \
  128. (!defined(OPENSSL_WINDOWS) || defined(__MINGW32__))
  129. #include <pthread.h>
  130. #define OPENSSL_PTHREADS
  131. #endif
  132. #if defined(OPENSSL_THREADS) && !defined(OPENSSL_PTHREADS) && \
  133. defined(OPENSSL_WINDOWS)
  134. #define OPENSSL_WINDOWS_THREADS
  135. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  136. #include <windows.h>
  137. OPENSSL_MSVC_PRAGMA(warning(pop))
  138. #endif
  139. #if defined(__cplusplus)
  140. extern "C" {
  141. #endif
  142. #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || defined(OPENSSL_ARM) || \
  143. defined(OPENSSL_AARCH64) || defined(OPENSSL_PPC64LE)
  144. // OPENSSL_cpuid_setup initializes the platform-specific feature cache.
  145. void OPENSSL_cpuid_setup(void);
  146. #endif
  147. #if (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) && \
  148. !defined(OPENSSL_STATIC_ARMCAP)
  149. // OPENSSL_get_armcap_pointer_for_test returns a pointer to |OPENSSL_armcap_P|
  150. // for unit tests. Any modifications to the value must be made after
  151. // |CRYPTO_library_init| but before any other function call in BoringSSL.
  152. OPENSSL_EXPORT uint32_t *OPENSSL_get_armcap_pointer_for_test(void);
  153. #endif
  154. #if (!defined(_MSC_VER) || defined(__clang__)) && defined(OPENSSL_64_BIT)
  155. #define BORINGSSL_HAS_UINT128
  156. typedef __int128_t int128_t;
  157. typedef __uint128_t uint128_t;
  158. // clang-cl supports __uint128_t but modulus and division don't work.
  159. // https://crbug.com/787617.
  160. #if !defined(_MSC_VER) || !defined(__clang__)
  161. #define BORINGSSL_CAN_DIVIDE_UINT128
  162. #endif
  163. #endif
  164. #define OPENSSL_ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
  165. // Have a generic fall-through for different versions of C/C++.
  166. #if defined(__cplusplus) && __cplusplus >= 201703L
  167. #define OPENSSL_FALLTHROUGH [[fallthrough]]
  168. #elif defined(__cplusplus) && __cplusplus >= 201103L && defined(__clang__)
  169. #define OPENSSL_FALLTHROUGH [[clang::fallthrough]]
  170. #elif defined(__cplusplus) && __cplusplus >= 201103L && defined(__GNUC__) && \
  171. __GNUC__ >= 7
  172. #define OPENSSL_FALLTHROUGH [[gnu::fallthrough]]
  173. #elif defined(__GNUC__) && __GNUC__ >= 7 // gcc 7
  174. #define OPENSSL_FALLTHROUGH __attribute__ ((fallthrough))
  175. #elif defined(__clang__)
  176. #if __has_attribute(fallthrough) && __clang_major__ >= 5
  177. // Clang 3.5, at least, complains about "error: declaration does not declare
  178. // anything", possibily because we put a semicolon after this macro in
  179. // practice. Thus limit it to >= Clang 5, which does work.
  180. #define OPENSSL_FALLTHROUGH __attribute__ ((fallthrough))
  181. #else // clang versions that do not support fallthrough.
  182. #define OPENSSL_FALLTHROUGH
  183. #endif
  184. #else // C++11 on gcc 6, and all other cases
  185. #define OPENSSL_FALLTHROUGH
  186. #endif
  187. // For convenience in testing 64-bit generic code, we allow disabling SSE2
  188. // intrinsics via |OPENSSL_NO_SSE2_FOR_TESTING|. x86_64 always has SSE2
  189. // available, so we would otherwise need to test such code on a non-x86_64
  190. // platform.
  191. #if defined(__SSE2__) && !defined(OPENSSL_NO_SSE2_FOR_TESTING)
  192. #define OPENSSL_SSE2
  193. #endif
  194. // Pointer utility functions.
  195. // buffers_alias returns one if |a| and |b| alias and zero otherwise.
  196. static inline int buffers_alias(const uint8_t *a, size_t a_len,
  197. const uint8_t *b, size_t b_len) {
  198. // Cast |a| and |b| to integers. In C, pointer comparisons between unrelated
  199. // objects are undefined whereas pointer to integer conversions are merely
  200. // implementation-defined. We assume the implementation defined it in a sane
  201. // way.
  202. uintptr_t a_u = (uintptr_t)a;
  203. uintptr_t b_u = (uintptr_t)b;
  204. return a_u + a_len > b_u && b_u + b_len > a_u;
  205. }
  206. // align_pointer returns |ptr|, advanced to |alignment|. |alignment| must be a
  207. // power of two, and |ptr| must have at least |alignment - 1| bytes of scratch
  208. // space.
  209. static inline void *align_pointer(void *ptr, size_t alignment) {
  210. // |alignment| must be a power of two.
  211. assert(alignment != 0 && (alignment & (alignment - 1)) == 0);
  212. // Instead of aligning |ptr| as a |uintptr_t| and casting back, compute the
  213. // offset and advance in pointer space. C guarantees that casting from pointer
  214. // to |uintptr_t| and back gives the same pointer, but general
  215. // integer-to-pointer conversions are implementation-defined. GCC does define
  216. // it in the useful way, but this makes fewer assumptions.
  217. uintptr_t offset = (0u - (uintptr_t)ptr) & (alignment - 1);
  218. ptr = (char *)ptr + offset;
  219. assert(((uintptr_t)ptr & (alignment - 1)) == 0);
  220. return ptr;
  221. }
  222. // Constant-time utility functions.
  223. //
  224. // The following methods return a bitmask of all ones (0xff...f) for true and 0
  225. // for false. This is useful for choosing a value based on the result of a
  226. // conditional in constant time. For example,
  227. //
  228. // if (a < b) {
  229. // c = a;
  230. // } else {
  231. // c = b;
  232. // }
  233. //
  234. // can be written as
  235. //
  236. // crypto_word_t lt = constant_time_lt_w(a, b);
  237. // c = constant_time_select_w(lt, a, b);
  238. // crypto_word_t is the type that most constant-time functions use. Ideally we
  239. // would like it to be |size_t|, but NaCl builds in 64-bit mode with 32-bit
  240. // pointers, which means that |size_t| can be 32 bits when |BN_ULONG| is 64
  241. // bits. Since we want to be able to do constant-time operations on a
  242. // |BN_ULONG|, |crypto_word_t| is defined as an unsigned value with the native
  243. // word length.
  244. #if defined(OPENSSL_64_BIT)
  245. typedef uint64_t crypto_word_t;
  246. #elif defined(OPENSSL_32_BIT)
  247. typedef uint32_t crypto_word_t;
  248. #else
  249. #error "Must define either OPENSSL_32_BIT or OPENSSL_64_BIT"
  250. #endif
  251. #define CONSTTIME_TRUE_W ~((crypto_word_t)0)
  252. #define CONSTTIME_FALSE_W ((crypto_word_t)0)
  253. #define CONSTTIME_TRUE_8 ((uint8_t)0xff)
  254. #define CONSTTIME_FALSE_8 ((uint8_t)0)
  255. // value_barrier_w returns |a|, but prevents GCC and Clang from reasoning about
  256. // the returned value. This is used to mitigate compilers undoing constant-time
  257. // code, until we can express our requirements directly in the language.
  258. //
  259. // Note the compiler is aware that |value_barrier_w| has no side effects and
  260. // always has the same output for a given input. This allows it to eliminate
  261. // dead code, move computations across loops, and vectorize.
  262. static inline crypto_word_t value_barrier_w(crypto_word_t a) {
  263. #if !defined(OPENSSL_NO_ASM) && (defined(__GNUC__) || defined(__clang__))
  264. __asm__("" : "+r"(a) : /* no inputs */);
  265. #endif
  266. return a;
  267. }
  268. // value_barrier_u32 behaves like |value_barrier_w| but takes a |uint32_t|.
  269. static inline uint32_t value_barrier_u32(uint32_t a) {
  270. #if !defined(OPENSSL_NO_ASM) && (defined(__GNUC__) || defined(__clang__))
  271. __asm__("" : "+r"(a) : /* no inputs */);
  272. #endif
  273. return a;
  274. }
  275. // value_barrier_u64 behaves like |value_barrier_w| but takes a |uint64_t|.
  276. static inline uint64_t value_barrier_u64(uint64_t a) {
  277. #if !defined(OPENSSL_NO_ASM) && (defined(__GNUC__) || defined(__clang__))
  278. __asm__("" : "+r"(a) : /* no inputs */);
  279. #endif
  280. return a;
  281. }
  282. // constant_time_msb_w returns the given value with the MSB copied to all the
  283. // other bits.
  284. static inline crypto_word_t constant_time_msb_w(crypto_word_t a) {
  285. return 0u - (a >> (sizeof(a) * 8 - 1));
  286. }
  287. // constant_time_lt_w returns 0xff..f if a < b and 0 otherwise.
  288. static inline crypto_word_t constant_time_lt_w(crypto_word_t a,
  289. crypto_word_t b) {
  290. // Consider the two cases of the problem:
  291. // msb(a) == msb(b): a < b iff the MSB of a - b is set.
  292. // msb(a) != msb(b): a < b iff the MSB of b is set.
  293. //
  294. // If msb(a) == msb(b) then the following evaluates as:
  295. // msb(a^((a^b)|((a-b)^a))) ==
  296. // msb(a^((a-b) ^ a)) == (because msb(a^b) == 0)
  297. // msb(a^a^(a-b)) == (rearranging)
  298. // msb(a-b) (because ∀x. x^x == 0)
  299. //
  300. // Else, if msb(a) != msb(b) then the following evaluates as:
  301. // msb(a^((a^b)|((a-b)^a))) ==
  302. // msb(a^(𝟙 | ((a-b)^a))) == (because msb(a^b) == 1 and 𝟙
  303. // represents a value s.t. msb(𝟙) = 1)
  304. // msb(a^𝟙) == (because ORing with 1 results in 1)
  305. // msb(b)
  306. //
  307. //
  308. // Here is an SMT-LIB verification of this formula:
  309. //
  310. // (define-fun lt ((a (_ BitVec 32)) (b (_ BitVec 32))) (_ BitVec 32)
  311. // (bvxor a (bvor (bvxor a b) (bvxor (bvsub a b) a)))
  312. // )
  313. //
  314. // (declare-fun a () (_ BitVec 32))
  315. // (declare-fun b () (_ BitVec 32))
  316. //
  317. // (assert (not (= (= #x00000001 (bvlshr (lt a b) #x0000001f)) (bvult a b))))
  318. // (check-sat)
  319. // (get-model)
  320. return constant_time_msb_w(a^((a^b)|((a-b)^a)));
  321. }
  322. // constant_time_lt_8 acts like |constant_time_lt_w| but returns an 8-bit
  323. // mask.
  324. static inline uint8_t constant_time_lt_8(crypto_word_t a, crypto_word_t b) {
  325. return (uint8_t)(constant_time_lt_w(a, b));
  326. }
  327. // constant_time_ge_w returns 0xff..f if a >= b and 0 otherwise.
  328. static inline crypto_word_t constant_time_ge_w(crypto_word_t a,
  329. crypto_word_t b) {
  330. return ~constant_time_lt_w(a, b);
  331. }
  332. // constant_time_ge_8 acts like |constant_time_ge_w| but returns an 8-bit
  333. // mask.
  334. static inline uint8_t constant_time_ge_8(crypto_word_t a, crypto_word_t b) {
  335. return (uint8_t)(constant_time_ge_w(a, b));
  336. }
  337. // constant_time_is_zero returns 0xff..f if a == 0 and 0 otherwise.
  338. static inline crypto_word_t constant_time_is_zero_w(crypto_word_t a) {
  339. // Here is an SMT-LIB verification of this formula:
  340. //
  341. // (define-fun is_zero ((a (_ BitVec 32))) (_ BitVec 32)
  342. // (bvand (bvnot a) (bvsub a #x00000001))
  343. // )
  344. //
  345. // (declare-fun a () (_ BitVec 32))
  346. //
  347. // (assert (not (= (= #x00000001 (bvlshr (is_zero a) #x0000001f)) (= a #x00000000))))
  348. // (check-sat)
  349. // (get-model)
  350. return constant_time_msb_w(~a & (a - 1));
  351. }
  352. // constant_time_is_zero_8 acts like |constant_time_is_zero_w| but returns an
  353. // 8-bit mask.
  354. static inline uint8_t constant_time_is_zero_8(crypto_word_t a) {
  355. return (uint8_t)(constant_time_is_zero_w(a));
  356. }
  357. // constant_time_eq_w returns 0xff..f if a == b and 0 otherwise.
  358. static inline crypto_word_t constant_time_eq_w(crypto_word_t a,
  359. crypto_word_t b) {
  360. return constant_time_is_zero_w(a ^ b);
  361. }
  362. // constant_time_eq_8 acts like |constant_time_eq_w| but returns an 8-bit
  363. // mask.
  364. static inline uint8_t constant_time_eq_8(crypto_word_t a, crypto_word_t b) {
  365. return (uint8_t)(constant_time_eq_w(a, b));
  366. }
  367. // constant_time_eq_int acts like |constant_time_eq_w| but works on int
  368. // values.
  369. static inline crypto_word_t constant_time_eq_int(int a, int b) {
  370. return constant_time_eq_w((crypto_word_t)(a), (crypto_word_t)(b));
  371. }
  372. // constant_time_eq_int_8 acts like |constant_time_eq_int| but returns an 8-bit
  373. // mask.
  374. static inline uint8_t constant_time_eq_int_8(int a, int b) {
  375. return constant_time_eq_8((crypto_word_t)(a), (crypto_word_t)(b));
  376. }
  377. // constant_time_select_w returns (mask & a) | (~mask & b). When |mask| is all
  378. // 1s or all 0s (as returned by the methods above), the select methods return
  379. // either |a| (if |mask| is nonzero) or |b| (if |mask| is zero).
  380. static inline crypto_word_t constant_time_select_w(crypto_word_t mask,
  381. crypto_word_t a,
  382. crypto_word_t b) {
  383. // Clang recognizes this pattern as a select. While it usually transforms it
  384. // to a cmov, it sometimes further transforms it into a branch, which we do
  385. // not want.
  386. //
  387. // Adding barriers to both |mask| and |~mask| breaks the relationship between
  388. // the two, which makes the compiler stick with bitmasks.
  389. return (value_barrier_w(mask) & a) | (value_barrier_w(~mask) & b);
  390. }
  391. // constant_time_select_8 acts like |constant_time_select| but operates on
  392. // 8-bit values.
  393. static inline uint8_t constant_time_select_8(uint8_t mask, uint8_t a,
  394. uint8_t b) {
  395. return (uint8_t)(constant_time_select_w(mask, a, b));
  396. }
  397. // constant_time_select_int acts like |constant_time_select| but operates on
  398. // ints.
  399. static inline int constant_time_select_int(crypto_word_t mask, int a, int b) {
  400. return (int)(constant_time_select_w(mask, (crypto_word_t)(a),
  401. (crypto_word_t)(b)));
  402. }
  403. #if defined(BORINGSSL_CONSTANT_TIME_VALIDATION)
  404. // CONSTTIME_SECRET takes a pointer and a number of bytes and marks that region
  405. // of memory as secret. Secret data is tracked as it flows to registers and
  406. // other parts of a memory. If secret data is used as a condition for a branch,
  407. // or as a memory index, it will trigger warnings in valgrind.
  408. #define CONSTTIME_SECRET(x, y) VALGRIND_MAKE_MEM_UNDEFINED(x, y)
  409. // CONSTTIME_DECLASSIFY takes a pointer and a number of bytes and marks that
  410. // region of memory as public. Public data is not subject to constant-time
  411. // rules.
  412. #define CONSTTIME_DECLASSIFY(x, y) VALGRIND_MAKE_MEM_DEFINED(x, y)
  413. #else
  414. #define CONSTTIME_SECRET(x, y)
  415. #define CONSTTIME_DECLASSIFY(x, y)
  416. #endif // BORINGSSL_CONSTANT_TIME_VALIDATION
  417. // Thread-safe initialisation.
  418. #if !defined(OPENSSL_THREADS)
  419. typedef uint32_t CRYPTO_once_t;
  420. #define CRYPTO_ONCE_INIT 0
  421. #elif defined(OPENSSL_WINDOWS_THREADS)
  422. typedef INIT_ONCE CRYPTO_once_t;
  423. #define CRYPTO_ONCE_INIT INIT_ONCE_STATIC_INIT
  424. #elif defined(OPENSSL_PTHREADS)
  425. typedef pthread_once_t CRYPTO_once_t;
  426. #define CRYPTO_ONCE_INIT PTHREAD_ONCE_INIT
  427. #else
  428. #error "Unknown threading library"
  429. #endif
  430. // CRYPTO_once calls |init| exactly once per process. This is thread-safe: if
  431. // concurrent threads call |CRYPTO_once| with the same |CRYPTO_once_t| argument
  432. // then they will block until |init| completes, but |init| will have only been
  433. // called once.
  434. //
  435. // The |once| argument must be a |CRYPTO_once_t| that has been initialised with
  436. // the value |CRYPTO_ONCE_INIT|.
  437. OPENSSL_EXPORT void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void));
  438. // Reference counting.
  439. // Automatically enable C11 atomics if implemented.
  440. #if !defined(OPENSSL_C11_ATOMIC) && defined(OPENSSL_THREADS) && \
  441. !defined(__STDC_NO_ATOMICS__) && defined(__STDC_VERSION__) && \
  442. __STDC_VERSION__ >= 201112L
  443. #define OPENSSL_C11_ATOMIC
  444. #endif
  445. // CRYPTO_REFCOUNT_MAX is the value at which the reference count saturates.
  446. #define CRYPTO_REFCOUNT_MAX 0xffffffff
  447. // CRYPTO_refcount_inc atomically increments the value at |*count| unless the
  448. // value would overflow. It's safe for multiple threads to concurrently call
  449. // this or |CRYPTO_refcount_dec_and_test_zero| on the same
  450. // |CRYPTO_refcount_t|.
  451. OPENSSL_EXPORT void CRYPTO_refcount_inc(CRYPTO_refcount_t *count);
  452. // CRYPTO_refcount_dec_and_test_zero tests the value at |*count|:
  453. // if it's zero, it crashes the address space.
  454. // if it's the maximum value, it returns zero.
  455. // otherwise, it atomically decrements it and returns one iff the resulting
  456. // value is zero.
  457. //
  458. // It's safe for multiple threads to concurrently call this or
  459. // |CRYPTO_refcount_inc| on the same |CRYPTO_refcount_t|.
  460. OPENSSL_EXPORT int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count);
  461. // Locks.
  462. //
  463. // Two types of locks are defined: |CRYPTO_MUTEX|, which can be used in
  464. // structures as normal, and |struct CRYPTO_STATIC_MUTEX|, which can be used as
  465. // a global lock. A global lock must be initialised to the value
  466. // |CRYPTO_STATIC_MUTEX_INIT|.
  467. //
  468. // |CRYPTO_MUTEX| can appear in public structures and so is defined in
  469. // thread.h as a structure large enough to fit the real type. The global lock is
  470. // a different type so it may be initialized with platform initializer macros.
  471. #if !defined(OPENSSL_THREADS)
  472. struct CRYPTO_STATIC_MUTEX {
  473. char padding; // Empty structs have different sizes in C and C++.
  474. };
  475. #define CRYPTO_STATIC_MUTEX_INIT { 0 }
  476. #elif defined(OPENSSL_WINDOWS_THREADS)
  477. struct CRYPTO_STATIC_MUTEX {
  478. SRWLOCK lock;
  479. };
  480. #define CRYPTO_STATIC_MUTEX_INIT { SRWLOCK_INIT }
  481. #elif defined(OPENSSL_PTHREADS)
  482. struct CRYPTO_STATIC_MUTEX {
  483. pthread_rwlock_t lock;
  484. };
  485. #define CRYPTO_STATIC_MUTEX_INIT { PTHREAD_RWLOCK_INITIALIZER }
  486. #else
  487. #error "Unknown threading library"
  488. #endif
  489. // CRYPTO_MUTEX_init initialises |lock|. If |lock| is a static variable, use a
  490. // |CRYPTO_STATIC_MUTEX|.
  491. OPENSSL_EXPORT void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock);
  492. // CRYPTO_MUTEX_lock_read locks |lock| such that other threads may also have a
  493. // read lock, but none may have a write lock.
  494. OPENSSL_EXPORT void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock);
  495. // CRYPTO_MUTEX_lock_write locks |lock| such that no other thread has any type
  496. // of lock on it.
  497. OPENSSL_EXPORT void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock);
  498. // CRYPTO_MUTEX_unlock_read unlocks |lock| for reading.
  499. OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX *lock);
  500. // CRYPTO_MUTEX_unlock_write unlocks |lock| for writing.
  501. OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX *lock);
  502. // CRYPTO_MUTEX_cleanup releases all resources held by |lock|.
  503. OPENSSL_EXPORT void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock);
  504. // CRYPTO_STATIC_MUTEX_lock_read locks |lock| such that other threads may also
  505. // have a read lock, but none may have a write lock. The |lock| variable does
  506. // not need to be initialised by any function, but must have been statically
  507. // initialised with |CRYPTO_STATIC_MUTEX_INIT|.
  508. OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_lock_read(
  509. struct CRYPTO_STATIC_MUTEX *lock);
  510. // CRYPTO_STATIC_MUTEX_lock_write locks |lock| such that no other thread has
  511. // any type of lock on it. The |lock| variable does not need to be initialised
  512. // by any function, but must have been statically initialised with
  513. // |CRYPTO_STATIC_MUTEX_INIT|.
  514. OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_lock_write(
  515. struct CRYPTO_STATIC_MUTEX *lock);
  516. // CRYPTO_STATIC_MUTEX_unlock_read unlocks |lock| for reading.
  517. OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_unlock_read(
  518. struct CRYPTO_STATIC_MUTEX *lock);
  519. // CRYPTO_STATIC_MUTEX_unlock_write unlocks |lock| for writing.
  520. OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_unlock_write(
  521. struct CRYPTO_STATIC_MUTEX *lock);
  522. #if defined(__cplusplus)
  523. extern "C++" {
  524. BSSL_NAMESPACE_BEGIN
  525. namespace internal {
  526. // MutexLockBase is a RAII helper for CRYPTO_MUTEX locking.
  527. template <void (*LockFunc)(CRYPTO_MUTEX *), void (*ReleaseFunc)(CRYPTO_MUTEX *)>
  528. class MutexLockBase {
  529. public:
  530. explicit MutexLockBase(CRYPTO_MUTEX *mu) : mu_(mu) {
  531. assert(mu_ != nullptr);
  532. LockFunc(mu_);
  533. }
  534. ~MutexLockBase() { ReleaseFunc(mu_); }
  535. MutexLockBase(const MutexLockBase<LockFunc, ReleaseFunc> &) = delete;
  536. MutexLockBase &operator=(const MutexLockBase<LockFunc, ReleaseFunc> &) =
  537. delete;
  538. private:
  539. CRYPTO_MUTEX *const mu_;
  540. };
  541. } // namespace internal
  542. using MutexWriteLock =
  543. internal::MutexLockBase<CRYPTO_MUTEX_lock_write, CRYPTO_MUTEX_unlock_write>;
  544. using MutexReadLock =
  545. internal::MutexLockBase<CRYPTO_MUTEX_lock_read, CRYPTO_MUTEX_unlock_read>;
  546. BSSL_NAMESPACE_END
  547. } // extern "C++"
  548. #endif // defined(__cplusplus)
  549. // Thread local storage.
  550. // thread_local_data_t enumerates the types of thread-local data that can be
  551. // stored.
  552. typedef enum {
  553. OPENSSL_THREAD_LOCAL_ERR = 0,
  554. OPENSSL_THREAD_LOCAL_RAND,
  555. OPENSSL_THREAD_LOCAL_FIPS_COUNTERS,
  556. OPENSSL_THREAD_LOCAL_TEST,
  557. NUM_OPENSSL_THREAD_LOCALS,
  558. } thread_local_data_t;
  559. // thread_local_destructor_t is the type of a destructor function that will be
  560. // called when a thread exits and its thread-local storage needs to be freed.
  561. typedef void (*thread_local_destructor_t)(void *);
  562. // CRYPTO_get_thread_local gets the pointer value that is stored for the
  563. // current thread for the given index, or NULL if none has been set.
  564. OPENSSL_EXPORT void *CRYPTO_get_thread_local(thread_local_data_t value);
  565. // CRYPTO_set_thread_local sets a pointer value for the current thread at the
  566. // given index. This function should only be called once per thread for a given
  567. // |index|: rather than update the pointer value itself, update the data that
  568. // is pointed to.
  569. //
  570. // The destructor function will be called when a thread exits to free this
  571. // thread-local data. All calls to |CRYPTO_set_thread_local| with the same
  572. // |index| should have the same |destructor| argument. The destructor may be
  573. // called with a NULL argument if a thread that never set a thread-local
  574. // pointer for |index|, exits. The destructor may be called concurrently with
  575. // different arguments.
  576. //
  577. // This function returns one on success or zero on error. If it returns zero
  578. // then |destructor| has been called with |value| already.
  579. OPENSSL_EXPORT int CRYPTO_set_thread_local(
  580. thread_local_data_t index, void *value,
  581. thread_local_destructor_t destructor);
  582. // ex_data
  583. typedef struct crypto_ex_data_func_st CRYPTO_EX_DATA_FUNCS;
  584. DECLARE_STACK_OF(CRYPTO_EX_DATA_FUNCS)
  585. // CRYPTO_EX_DATA_CLASS tracks the ex_indices registered for a type which
  586. // supports ex_data. It should defined as a static global within the module
  587. // which defines that type.
  588. typedef struct {
  589. struct CRYPTO_STATIC_MUTEX lock;
  590. STACK_OF(CRYPTO_EX_DATA_FUNCS) *meth;
  591. // num_reserved is one if the ex_data index zero is reserved for legacy
  592. // |TYPE_get_app_data| functions.
  593. uint8_t num_reserved;
  594. } CRYPTO_EX_DATA_CLASS;
  595. #define CRYPTO_EX_DATA_CLASS_INIT {CRYPTO_STATIC_MUTEX_INIT, NULL, 0}
  596. #define CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA \
  597. {CRYPTO_STATIC_MUTEX_INIT, NULL, 1}
  598. // CRYPTO_get_ex_new_index allocates a new index for |ex_data_class| and writes
  599. // it to |*out_index|. Each class of object should provide a wrapper function
  600. // that uses the correct |CRYPTO_EX_DATA_CLASS|. It returns one on success and
  601. // zero otherwise.
  602. OPENSSL_EXPORT int CRYPTO_get_ex_new_index(CRYPTO_EX_DATA_CLASS *ex_data_class,
  603. int *out_index, long argl,
  604. void *argp,
  605. CRYPTO_EX_free *free_func);
  606. // CRYPTO_set_ex_data sets an extra data pointer on a given object. Each class
  607. // of object should provide a wrapper function.
  608. OPENSSL_EXPORT int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int index, void *val);
  609. // CRYPTO_get_ex_data returns an extra data pointer for a given object, or NULL
  610. // if no such index exists. Each class of object should provide a wrapper
  611. // function.
  612. OPENSSL_EXPORT void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int index);
  613. // CRYPTO_new_ex_data initialises a newly allocated |CRYPTO_EX_DATA|.
  614. OPENSSL_EXPORT void CRYPTO_new_ex_data(CRYPTO_EX_DATA *ad);
  615. // CRYPTO_free_ex_data frees |ad|, which is embedded inside |obj|, which is an
  616. // object of the given class.
  617. OPENSSL_EXPORT void CRYPTO_free_ex_data(CRYPTO_EX_DATA_CLASS *ex_data_class,
  618. void *obj, CRYPTO_EX_DATA *ad);
  619. // Endianness conversions.
  620. #if defined(__GNUC__) && __GNUC__ >= 2
  621. static inline uint16_t CRYPTO_bswap2(uint16_t x) {
  622. return __builtin_bswap16(x);
  623. }
  624. static inline uint32_t CRYPTO_bswap4(uint32_t x) {
  625. return __builtin_bswap32(x);
  626. }
  627. static inline uint64_t CRYPTO_bswap8(uint64_t x) {
  628. return __builtin_bswap64(x);
  629. }
  630. #elif defined(_MSC_VER)
  631. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  632. #include <stdlib.h>
  633. OPENSSL_MSVC_PRAGMA(warning(pop))
  634. #pragma intrinsic(_byteswap_uint64, _byteswap_ulong, _byteswap_ushort)
  635. static inline uint16_t CRYPTO_bswap2(uint16_t x) {
  636. return _byteswap_ushort(x);
  637. }
  638. static inline uint32_t CRYPTO_bswap4(uint32_t x) {
  639. return _byteswap_ulong(x);
  640. }
  641. static inline uint64_t CRYPTO_bswap8(uint64_t x) {
  642. return _byteswap_uint64(x);
  643. }
  644. #else
  645. static inline uint16_t CRYPTO_bswap2(uint16_t x) {
  646. return (x >> 8) | (x << 8);
  647. }
  648. static inline uint32_t CRYPTO_bswap4(uint32_t x) {
  649. x = (x >> 16) | (x << 16);
  650. x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
  651. return x;
  652. }
  653. static inline uint64_t CRYPTO_bswap8(uint64_t x) {
  654. return CRYPTO_bswap4(x >> 32) | (((uint64_t)CRYPTO_bswap4(x)) << 32);
  655. }
  656. #endif
  657. // Language bug workarounds.
  658. //
  659. // Most C standard library functions are undefined if passed NULL, even when the
  660. // corresponding length is zero. This gives them (and, in turn, all functions
  661. // which call them) surprising behavior on empty arrays. Some compilers will
  662. // miscompile code due to this rule. See also
  663. // https://www.imperialviolet.org/2016/06/26/nonnull.html
  664. //
  665. // These wrapper functions behave the same as the corresponding C standard
  666. // functions, but behave as expected when passed NULL if the length is zero.
  667. //
  668. // Note |OPENSSL_memcmp| is a different function from |CRYPTO_memcmp|.
  669. // C++ defines |memchr| as a const-correct overload.
  670. #if defined(__cplusplus)
  671. extern "C++" {
  672. static inline const void *OPENSSL_memchr(const void *s, int c, size_t n) {
  673. if (n == 0) {
  674. return NULL;
  675. }
  676. return memchr(s, c, n);
  677. }
  678. static inline void *OPENSSL_memchr(void *s, int c, size_t n) {
  679. if (n == 0) {
  680. return NULL;
  681. }
  682. return memchr(s, c, n);
  683. }
  684. } // extern "C++"
  685. #else // __cplusplus
  686. static inline void *OPENSSL_memchr(const void *s, int c, size_t n) {
  687. if (n == 0) {
  688. return NULL;
  689. }
  690. return memchr(s, c, n);
  691. }
  692. #endif // __cplusplus
  693. static inline int OPENSSL_memcmp(const void *s1, const void *s2, size_t n) {
  694. if (n == 0) {
  695. return 0;
  696. }
  697. return memcmp(s1, s2, n);
  698. }
  699. static inline void *OPENSSL_memcpy(void *dst, const void *src, size_t n) {
  700. if (n == 0) {
  701. return dst;
  702. }
  703. return memcpy(dst, src, n);
  704. }
  705. static inline void *OPENSSL_memmove(void *dst, const void *src, size_t n) {
  706. if (n == 0) {
  707. return dst;
  708. }
  709. return memmove(dst, src, n);
  710. }
  711. static inline void *OPENSSL_memset(void *dst, int c, size_t n) {
  712. if (n == 0) {
  713. return dst;
  714. }
  715. return memset(dst, c, n);
  716. }
  717. // Loads and stores.
  718. //
  719. // The following functions load and store sized integers with the specified
  720. // endianness. They use |memcpy|, and so avoid alignment or strict aliasing
  721. // requirements on the input and output pointers.
  722. static inline uint32_t CRYPTO_load_u32_le(const void *in) {
  723. uint32_t v;
  724. OPENSSL_memcpy(&v, in, sizeof(v));
  725. return v;
  726. }
  727. static inline void CRYPTO_store_u32_le(void *out, uint32_t v) {
  728. OPENSSL_memcpy(out, &v, sizeof(v));
  729. }
  730. static inline uint32_t CRYPTO_load_u32_be(const void *in) {
  731. uint32_t v;
  732. OPENSSL_memcpy(&v, in, sizeof(v));
  733. return CRYPTO_bswap4(v);
  734. }
  735. static inline void CRYPTO_store_u32_be(void *out, uint32_t v) {
  736. v = CRYPTO_bswap4(v);
  737. OPENSSL_memcpy(out, &v, sizeof(v));
  738. }
  739. static inline uint64_t CRYPTO_load_u64_be(const void *ptr) {
  740. uint64_t ret;
  741. OPENSSL_memcpy(&ret, ptr, sizeof(ret));
  742. return CRYPTO_bswap8(ret);
  743. }
  744. static inline void CRYPTO_store_u64_be(void *out, uint64_t v) {
  745. v = CRYPTO_bswap8(v);
  746. OPENSSL_memcpy(out, &v, sizeof(v));
  747. }
  748. static inline crypto_word_t CRYPTO_load_word_le(const void *in) {
  749. crypto_word_t v;
  750. OPENSSL_memcpy(&v, in, sizeof(v));
  751. return v;
  752. }
  753. static inline void CRYPTO_store_word_le(void *out, crypto_word_t v) {
  754. OPENSSL_memcpy(out, &v, sizeof(v));
  755. }
  756. // Bit rotation functions.
  757. //
  758. // Note these functions use |(-shift) & 31|, etc., because shifting by the bit
  759. // width is undefined. Both Clang and GCC recognize this pattern as a rotation,
  760. // but MSVC does not. Instead, we call MSVC's built-in functions.
  761. static inline uint32_t CRYPTO_rotl_u32(uint32_t value, int shift) {
  762. #if defined(_MSC_VER)
  763. return _rotl(value, shift);
  764. #else
  765. return (value << shift) | (value >> ((-shift) & 31));
  766. #endif
  767. }
  768. static inline uint32_t CRYPTO_rotr_u32(uint32_t value, int shift) {
  769. #if defined(_MSC_VER)
  770. return _rotr(value, shift);
  771. #else
  772. return (value >> shift) | (value << ((-shift) & 31));
  773. #endif
  774. }
  775. static inline uint64_t CRYPTO_rotl_u64(uint64_t value, int shift) {
  776. #if defined(_MSC_VER)
  777. return _rotl64(value, shift);
  778. #else
  779. return (value << shift) | (value >> ((-shift) & 63));
  780. #endif
  781. }
  782. static inline uint64_t CRYPTO_rotr_u64(uint64_t value, int shift) {
  783. #if defined(_MSC_VER)
  784. return _rotr64(value, shift);
  785. #else
  786. return (value >> shift) | (value << ((-shift) & 63));
  787. #endif
  788. }
  789. // FIPS functions.
  790. #if defined(BORINGSSL_FIPS)
  791. // BORINGSSL_FIPS_abort is called when a FIPS power-on or continuous test
  792. // fails. It prevents any further cryptographic operations by the current
  793. // process.
  794. void BORINGSSL_FIPS_abort(void) __attribute__((noreturn));
  795. #endif
  796. // boringssl_fips_self_test runs the FIPS KAT-based self tests. It returns one
  797. // on success and zero on error. The argument is the integrity hash of the FIPS
  798. // module and may be used to check and write flag files to suppress duplicate
  799. // self-tests. If |module_hash_len| is zero then no flag file will be checked
  800. // nor written and tests will always be run.
  801. int boringssl_fips_self_test(const uint8_t *module_hash,
  802. size_t module_hash_len);
  803. #if defined(BORINGSSL_FIPS_COUNTERS)
  804. void boringssl_fips_inc_counter(enum fips_counter_t counter);
  805. #else
  806. OPENSSL_INLINE void boringssl_fips_inc_counter(enum fips_counter_t counter) {}
  807. #endif
  808. #if defined(__cplusplus)
  809. } // extern C
  810. #endif
  811. #endif // OPENSSL_HEADER_CRYPTO_INTERNAL_H