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
109 #ifndef OPENSSL_HEADER_CRYPTO_INTERNAL_H
110 #define OPENSSL_HEADER_CRYPTO_INTERNAL_H
111
112 #include <openssl/crypto.h>
113 #include <openssl/ex_data.h>
114 #include <openssl/stack.h>
115 #include <openssl/thread.h>
116
117 #include <assert.h>
118 #include <string.h>
119
120 #if defined(BORINGSSL_CONSTANT_TIME_VALIDATION)
121 #include <valgrind/memcheck.h>
122 #endif
123
124 #if !defined(__cplusplus)
125 #if defined(_MSC_VER)
126 #define alignas(x) __declspec(align(x))
127 #define alignof __alignof
128 #else
129 #include <stdalign.h>
130 #endif
131 #endif
132
133 #if defined(OPENSSL_THREADS) && \
134 (!defined(OPENSSL_WINDOWS) || defined(__MINGW32__))
135 #include <pthread.h>
136 #define OPENSSL_PTHREADS
137 #endif
138
139 #if defined(OPENSSL_THREADS) && !defined(OPENSSL_PTHREADS) && \
140 defined(OPENSSL_WINDOWS)
141 #define OPENSSL_WINDOWS_THREADS
142 OPENSSL_MSVC_PRAGMA(warning(push, 3))
143 #include <windows.h>
OPENSSL_MSVC_PRAGMA(warning (pop))144 OPENSSL_MSVC_PRAGMA(warning(pop))
145 #endif
146
147 #if defined(__cplusplus)
148 extern "C" {
149 #endif
150
151
152 #if defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || defined(OPENSSL_ARM) || \
153 defined(OPENSSL_AARCH64) || defined(OPENSSL_PPC64LE)
154 // OPENSSL_cpuid_setup initializes the platform-specific feature cache.
155 void OPENSSL_cpuid_setup(void);
156 #endif
157
158 #if (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) && \
159 !defined(OPENSSL_STATIC_ARMCAP)
160 // OPENSSL_get_armcap_pointer_for_test returns a pointer to |OPENSSL_armcap_P|
161 // for unit tests. Any modifications to the value must be made after
162 // |CRYPTO_library_init| but before any other function call in BoringSSL.
163 OPENSSL_EXPORT uint32_t *OPENSSL_get_armcap_pointer_for_test(void);
164 #endif
165
166
167 #if (!defined(_MSC_VER) || defined(__clang__)) && defined(OPENSSL_64_BIT)
168 #define BORINGSSL_HAS_UINT128
169 typedef __int128_t int128_t;
170 typedef __uint128_t uint128_t;
171
172 // clang-cl supports __uint128_t but modulus and division don't work.
173 // https://crbug.com/787617.
174 #if !defined(_MSC_VER) || !defined(__clang__)
175 #define BORINGSSL_CAN_DIVIDE_UINT128
176 #endif
177 #endif
178
179 #define OPENSSL_ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
180
181 // Have a generic fall-through for different versions of C/C++.
182 #if defined(__cplusplus) && __cplusplus >= 201703L
183 #define OPENSSL_FALLTHROUGH [[fallthrough]]
184 #elif defined(__cplusplus) && __cplusplus >= 201103L && defined(__clang__)
185 #define OPENSSL_FALLTHROUGH [[clang::fallthrough]]
186 #elif defined(__cplusplus) && __cplusplus >= 201103L && defined(__GNUC__) && \
187 __GNUC__ >= 7
188 #define OPENSSL_FALLTHROUGH [[gnu::fallthrough]]
189 #elif defined(__GNUC__) && __GNUC__ >= 7 // gcc 7
190 #define OPENSSL_FALLTHROUGH __attribute__ ((fallthrough))
191 #elif defined(__clang__)
192 #if __has_attribute(fallthrough) && __clang_major__ >= 5
193 // Clang 3.5, at least, complains about "error: declaration does not declare
194 // anything", possibily because we put a semicolon after this macro in
195 // practice. Thus limit it to >= Clang 5, which does work.
196 #define OPENSSL_FALLTHROUGH __attribute__ ((fallthrough))
197 #else // clang versions that do not support fallthrough.
198 #define OPENSSL_FALLTHROUGH
199 #endif
200 #else // C++11 on gcc 6, and all other cases
201 #define OPENSSL_FALLTHROUGH
202 #endif
203
204 // For convenience in testing 64-bit generic code, we allow disabling SSE2
205 // intrinsics via |OPENSSL_NO_SSE2_FOR_TESTING|. x86_64 always has SSE2
206 // available, so we would otherwise need to test such code on a non-x86_64
207 // platform.
208 #if defined(__SSE2__) && !defined(OPENSSL_NO_SSE2_FOR_TESTING)
209 #define OPENSSL_SSE2
210 #endif
211
212
213 // Pointer utility functions.
214
215 // buffers_alias returns one if |a| and |b| alias and zero otherwise.
216 static inline int buffers_alias(const uint8_t *a, size_t a_len,
217 const uint8_t *b, size_t b_len) {
218 // Cast |a| and |b| to integers. In C, pointer comparisons between unrelated
219 // objects are undefined whereas pointer to integer conversions are merely
220 // implementation-defined. We assume the implementation defined it in a sane
221 // way.
222 uintptr_t a_u = (uintptr_t)a;
223 uintptr_t b_u = (uintptr_t)b;
224 return a_u + a_len > b_u && b_u + b_len > a_u;
225 }
226
227 // align_pointer returns |ptr|, advanced to |alignment|. |alignment| must be a
228 // power of two, and |ptr| must have at least |alignment - 1| bytes of scratch
229 // space.
230 static inline void *align_pointer(void *ptr, size_t alignment) {
231 // |alignment| must be a power of two.
232 assert(alignment != 0 && (alignment & (alignment - 1)) == 0);
233 // Instead of aligning |ptr| as a |uintptr_t| and casting back, compute the
234 // offset and advance in pointer space. C guarantees that casting from pointer
235 // to |uintptr_t| and back gives the same pointer, but general
236 // integer-to-pointer conversions are implementation-defined. GCC does define
237 // it in the useful way, but this makes fewer assumptions.
238 uintptr_t offset = (0u - (uintptr_t)ptr) & (alignment - 1);
239 ptr = (char *)ptr + offset;
240 assert(((uintptr_t)ptr & (alignment - 1)) == 0);
241 return ptr;
242 }
243
244
245 // Constant-time utility functions.
246 //
247 // The following methods return a bitmask of all ones (0xff...f) for true and 0
248 // for false. This is useful for choosing a value based on the result of a
249 // conditional in constant time. For example,
250 //
251 // if (a < b) {
252 // c = a;
253 // } else {
254 // c = b;
255 // }
256 //
257 // can be written as
258 //
259 // crypto_word_t lt = constant_time_lt_w(a, b);
260 // c = constant_time_select_w(lt, a, b);
261
262 // crypto_word_t is the type that most constant-time functions use. Ideally we
263 // would like it to be |size_t|, but NaCl builds in 64-bit mode with 32-bit
264 // pointers, which means that |size_t| can be 32 bits when |BN_ULONG| is 64
265 // bits. Since we want to be able to do constant-time operations on a
266 // |BN_ULONG|, |crypto_word_t| is defined as an unsigned value with the native
267 // word length.
268 #if defined(OPENSSL_64_BIT)
269 typedef uint64_t crypto_word_t;
270 #elif defined(OPENSSL_32_BIT)
271 typedef uint32_t crypto_word_t;
272 #else
273 #error "Must define either OPENSSL_32_BIT or OPENSSL_64_BIT"
274 #endif
275
276 #define CONSTTIME_TRUE_W ~((crypto_word_t)0)
277 #define CONSTTIME_FALSE_W ((crypto_word_t)0)
278 #define CONSTTIME_TRUE_8 ((uint8_t)0xff)
279 #define CONSTTIME_FALSE_8 ((uint8_t)0)
280
281 // value_barrier_w returns |a|, but prevents GCC and Clang from reasoning about
282 // the returned value. This is used to mitigate compilers undoing constant-time
283 // code, until we can express our requirements directly in the language.
284 //
285 // Note the compiler is aware that |value_barrier_w| has no side effects and
286 // always has the same output for a given input. This allows it to eliminate
287 // dead code, move computations across loops, and vectorize.
288 static inline crypto_word_t value_barrier_w(crypto_word_t a) {
289 #if !defined(OPENSSL_NO_ASM) && (defined(__GNUC__) || defined(__clang__))
290 __asm__("" : "+r"(a) : /* no inputs */);
291 #endif
292 return a;
293 }
294
295 // value_barrier_u32 behaves like |value_barrier_w| but takes a |uint32_t|.
296 static inline uint32_t value_barrier_u32(uint32_t a) {
297 #if !defined(OPENSSL_NO_ASM) && (defined(__GNUC__) || defined(__clang__))
298 __asm__("" : "+r"(a) : /* no inputs */);
299 #endif
300 return a;
301 }
302
303 // value_barrier_u64 behaves like |value_barrier_w| but takes a |uint64_t|.
304 static inline uint64_t value_barrier_u64(uint64_t a) {
305 #if !defined(OPENSSL_NO_ASM) && (defined(__GNUC__) || defined(__clang__))
306 __asm__("" : "+r"(a) : /* no inputs */);
307 #endif
308 return a;
309 }
310
311 // constant_time_msb_w returns the given value with the MSB copied to all the
312 // other bits.
313 static inline crypto_word_t constant_time_msb_w(crypto_word_t a) {
314 return 0u - (a >> (sizeof(a) * 8 - 1));
315 }
316
317 // constant_time_lt_w returns 0xff..f if a < b and 0 otherwise.
318 static inline crypto_word_t constant_time_lt_w(crypto_word_t a,
319 crypto_word_t b) {
320 // Consider the two cases of the problem:
321 // msb(a) == msb(b): a < b iff the MSB of a - b is set.
322 // msb(a) != msb(b): a < b iff the MSB of b is set.
323 //
324 // If msb(a) == msb(b) then the following evaluates as:
325 // msb(a^((a^b)|((a-b)^a))) ==
326 // msb(a^((a-b) ^ a)) == (because msb(a^b) == 0)
327 // msb(a^a^(a-b)) == (rearranging)
328 // msb(a-b) (because ∀x. x^x == 0)
329 //
330 // Else, if msb(a) != msb(b) then the following evaluates as:
331 // msb(a^((a^b)|((a-b)^a))) ==
332 // msb(a^( | ((a-b)^a))) == (because msb(a^b) == 1 and
333 // represents a value s.t. msb() = 1)
334 // msb(a^) == (because ORing with 1 results in 1)
335 // msb(b)
336 //
337 //
338 // Here is an SMT-LIB verification of this formula:
339 //
340 // (define-fun lt ((a (_ BitVec 32)) (b (_ BitVec 32))) (_ BitVec 32)
341 // (bvxor a (bvor (bvxor a b) (bvxor (bvsub a b) a)))
342 // )
343 //
344 // (declare-fun a () (_ BitVec 32))
345 // (declare-fun b () (_ BitVec 32))
346 //
347 // (assert (not (= (= #x00000001 (bvlshr (lt a b) #x0000001f)) (bvult a b))))
348 // (check-sat)
349 // (get-model)
350 return constant_time_msb_w(a^((a^b)|((a-b)^a)));
351 }
352
353 // constant_time_lt_8 acts like |constant_time_lt_w| but returns an 8-bit
354 // mask.
355 static inline uint8_t constant_time_lt_8(crypto_word_t a, crypto_word_t b) {
356 return (uint8_t)(constant_time_lt_w(a, b));
357 }
358
359 // constant_time_ge_w returns 0xff..f if a >= b and 0 otherwise.
360 static inline crypto_word_t constant_time_ge_w(crypto_word_t a,
361 crypto_word_t b) {
362 return ~constant_time_lt_w(a, b);
363 }
364
365 // constant_time_ge_8 acts like |constant_time_ge_w| but returns an 8-bit
366 // mask.
367 static inline uint8_t constant_time_ge_8(crypto_word_t a, crypto_word_t b) {
368 return (uint8_t)(constant_time_ge_w(a, b));
369 }
370
371 // constant_time_is_zero returns 0xff..f if a == 0 and 0 otherwise.
372 static inline crypto_word_t constant_time_is_zero_w(crypto_word_t a) {
373 // Here is an SMT-LIB verification of this formula:
374 //
375 // (define-fun is_zero ((a (_ BitVec 32))) (_ BitVec 32)
376 // (bvand (bvnot a) (bvsub a #x00000001))
377 // )
378 //
379 // (declare-fun a () (_ BitVec 32))
380 //
381 // (assert (not (= (= #x00000001 (bvlshr (is_zero a) #x0000001f)) (= a #x00000000))))
382 // (check-sat)
383 // (get-model)
384 return constant_time_msb_w(~a & (a - 1));
385 }
386
387 // constant_time_is_zero_8 acts like |constant_time_is_zero_w| but returns an
388 // 8-bit mask.
389 static inline uint8_t constant_time_is_zero_8(crypto_word_t a) {
390 return (uint8_t)(constant_time_is_zero_w(a));
391 }
392
393 // constant_time_eq_w returns 0xff..f if a == b and 0 otherwise.
394 static inline crypto_word_t constant_time_eq_w(crypto_word_t a,
395 crypto_word_t b) {
396 return constant_time_is_zero_w(a ^ b);
397 }
398
399 // constant_time_eq_8 acts like |constant_time_eq_w| but returns an 8-bit
400 // mask.
401 static inline uint8_t constant_time_eq_8(crypto_word_t a, crypto_word_t b) {
402 return (uint8_t)(constant_time_eq_w(a, b));
403 }
404
405 // constant_time_eq_int acts like |constant_time_eq_w| but works on int
406 // values.
407 static inline crypto_word_t constant_time_eq_int(int a, int b) {
408 return constant_time_eq_w((crypto_word_t)(a), (crypto_word_t)(b));
409 }
410
411 // constant_time_eq_int_8 acts like |constant_time_eq_int| but returns an 8-bit
412 // mask.
413 static inline uint8_t constant_time_eq_int_8(int a, int b) {
414 return constant_time_eq_8((crypto_word_t)(a), (crypto_word_t)(b));
415 }
416
417 // constant_time_select_w returns (mask & a) | (~mask & b). When |mask| is all
418 // 1s or all 0s (as returned by the methods above), the select methods return
419 // either |a| (if |mask| is nonzero) or |b| (if |mask| is zero).
420 static inline crypto_word_t constant_time_select_w(crypto_word_t mask,
421 crypto_word_t a,
422 crypto_word_t b) {
423 // Clang recognizes this pattern as a select. While it usually transforms it
424 // to a cmov, it sometimes further transforms it into a branch, which we do
425 // not want.
426 //
427 // Adding barriers to both |mask| and |~mask| breaks the relationship between
428 // the two, which makes the compiler stick with bitmasks.
429 return (value_barrier_w(mask) & a) | (value_barrier_w(~mask) & b);
430 }
431
432 // constant_time_select_8 acts like |constant_time_select| but operates on
433 // 8-bit values.
434 static inline uint8_t constant_time_select_8(uint8_t mask, uint8_t a,
435 uint8_t b) {
436 return (uint8_t)(constant_time_select_w(mask, a, b));
437 }
438
439 // constant_time_select_int acts like |constant_time_select| but operates on
440 // ints.
441 static inline int constant_time_select_int(crypto_word_t mask, int a, int b) {
442 return (int)(constant_time_select_w(mask, (crypto_word_t)(a),
443 (crypto_word_t)(b)));
444 }
445
446 #if defined(BORINGSSL_CONSTANT_TIME_VALIDATION)
447
448 // CONSTTIME_SECRET takes a pointer and a number of bytes and marks that region
449 // of memory as secret. Secret data is tracked as it flows to registers and
450 // other parts of a memory. If secret data is used as a condition for a branch,
451 // or as a memory index, it will trigger warnings in valgrind.
452 #define CONSTTIME_SECRET(x, y) VALGRIND_MAKE_MEM_UNDEFINED(x, y)
453
454 // CONSTTIME_DECLASSIFY takes a pointer and a number of bytes and marks that
455 // region of memory as public. Public data is not subject to constant-time
456 // rules.
457 #define CONSTTIME_DECLASSIFY(x, y) VALGRIND_MAKE_MEM_DEFINED(x, y)
458
459 #else
460
461 #define CONSTTIME_SECRET(x, y)
462 #define CONSTTIME_DECLASSIFY(x, y)
463
464 #endif // BORINGSSL_CONSTANT_TIME_VALIDATION
465
466
467 // Thread-safe initialisation.
468
469 #if !defined(OPENSSL_THREADS)
470 typedef uint32_t CRYPTO_once_t;
471 #define CRYPTO_ONCE_INIT 0
472 #elif defined(OPENSSL_WINDOWS_THREADS)
473 typedef INIT_ONCE CRYPTO_once_t;
474 #define CRYPTO_ONCE_INIT INIT_ONCE_STATIC_INIT
475 #elif defined(OPENSSL_PTHREADS)
476 typedef pthread_once_t CRYPTO_once_t;
477 #define CRYPTO_ONCE_INIT PTHREAD_ONCE_INIT
478 #else
479 #error "Unknown threading library"
480 #endif
481
482 // CRYPTO_once calls |init| exactly once per process. This is thread-safe: if
483 // concurrent threads call |CRYPTO_once| with the same |CRYPTO_once_t| argument
484 // then they will block until |init| completes, but |init| will have only been
485 // called once.
486 //
487 // The |once| argument must be a |CRYPTO_once_t| that has been initialised with
488 // the value |CRYPTO_ONCE_INIT|.
489 OPENSSL_EXPORT void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void));
490
491
492 // Reference counting.
493
494 // Automatically enable C11 atomics if implemented.
495 #if !defined(OPENSSL_C11_ATOMIC) && defined(OPENSSL_THREADS) && \
496 !defined(__STDC_NO_ATOMICS__) && defined(__STDC_VERSION__) && \
497 __STDC_VERSION__ >= 201112L
498 #define OPENSSL_C11_ATOMIC
499 #endif
500
501 // CRYPTO_REFCOUNT_MAX is the value at which the reference count saturates.
502 #define CRYPTO_REFCOUNT_MAX 0xffffffff
503
504 // CRYPTO_refcount_inc atomically increments the value at |*count| unless the
505 // value would overflow. It's safe for multiple threads to concurrently call
506 // this or |CRYPTO_refcount_dec_and_test_zero| on the same
507 // |CRYPTO_refcount_t|.
508 OPENSSL_EXPORT void CRYPTO_refcount_inc(CRYPTO_refcount_t *count);
509
510 // CRYPTO_refcount_dec_and_test_zero tests the value at |*count|:
511 // if it's zero, it crashes the address space.
512 // if it's the maximum value, it returns zero.
513 // otherwise, it atomically decrements it and returns one iff the resulting
514 // value is zero.
515 //
516 // It's safe for multiple threads to concurrently call this or
517 // |CRYPTO_refcount_inc| on the same |CRYPTO_refcount_t|.
518 OPENSSL_EXPORT int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count);
519
520
521 // Locks.
522 //
523 // Two types of locks are defined: |CRYPTO_MUTEX|, which can be used in
524 // structures as normal, and |struct CRYPTO_STATIC_MUTEX|, which can be used as
525 // a global lock. A global lock must be initialised to the value
526 // |CRYPTO_STATIC_MUTEX_INIT|.
527 //
528 // |CRYPTO_MUTEX| can appear in public structures and so is defined in
529 // thread.h as a structure large enough to fit the real type. The global lock is
530 // a different type so it may be initialized with platform initializer macros.
531
532 #if !defined(OPENSSL_THREADS)
533 struct CRYPTO_STATIC_MUTEX {
534 char padding; // Empty structs have different sizes in C and C++.
535 };
536 #define CRYPTO_STATIC_MUTEX_INIT { 0 }
537 #elif defined(OPENSSL_WINDOWS_THREADS)
538 struct CRYPTO_STATIC_MUTEX {
539 SRWLOCK lock;
540 };
541 #define CRYPTO_STATIC_MUTEX_INIT { SRWLOCK_INIT }
542 #elif defined(OPENSSL_PTHREADS)
543 struct CRYPTO_STATIC_MUTEX {
544 pthread_rwlock_t lock;
545 };
546 #define CRYPTO_STATIC_MUTEX_INIT { PTHREAD_RWLOCK_INITIALIZER }
547 #else
548 #error "Unknown threading library"
549 #endif
550
551 // CRYPTO_MUTEX_init initialises |lock|. If |lock| is a static variable, use a
552 // |CRYPTO_STATIC_MUTEX|.
553 OPENSSL_EXPORT void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock);
554
555 // CRYPTO_MUTEX_lock_read locks |lock| such that other threads may also have a
556 // read lock, but none may have a write lock.
557 OPENSSL_EXPORT void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock);
558
559 // CRYPTO_MUTEX_lock_write locks |lock| such that no other thread has any type
560 // of lock on it.
561 OPENSSL_EXPORT void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock);
562
563 // CRYPTO_MUTEX_unlock_read unlocks |lock| for reading.
564 OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_read(CRYPTO_MUTEX *lock);
565
566 // CRYPTO_MUTEX_unlock_write unlocks |lock| for writing.
567 OPENSSL_EXPORT void CRYPTO_MUTEX_unlock_write(CRYPTO_MUTEX *lock);
568
569 // CRYPTO_MUTEX_cleanup releases all resources held by |lock|.
570 OPENSSL_EXPORT void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock);
571
572 // CRYPTO_STATIC_MUTEX_lock_read locks |lock| such that other threads may also
573 // have a read lock, but none may have a write lock. The |lock| variable does
574 // not need to be initialised by any function, but must have been statically
575 // initialised with |CRYPTO_STATIC_MUTEX_INIT|.
576 OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_lock_read(
577 struct CRYPTO_STATIC_MUTEX *lock);
578
579 // CRYPTO_STATIC_MUTEX_lock_write locks |lock| such that no other thread has
580 // any type of lock on it. The |lock| variable does not need to be initialised
581 // by any function, but must have been statically initialised with
582 // |CRYPTO_STATIC_MUTEX_INIT|.
583 OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_lock_write(
584 struct CRYPTO_STATIC_MUTEX *lock);
585
586 // CRYPTO_STATIC_MUTEX_unlock_read unlocks |lock| for reading.
587 OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_unlock_read(
588 struct CRYPTO_STATIC_MUTEX *lock);
589
590 // CRYPTO_STATIC_MUTEX_unlock_write unlocks |lock| for writing.
591 OPENSSL_EXPORT void CRYPTO_STATIC_MUTEX_unlock_write(
592 struct CRYPTO_STATIC_MUTEX *lock);
593
594 #if defined(__cplusplus)
595 extern "C++" {
596
597 BSSL_NAMESPACE_BEGIN
598
599 namespace internal {
600
601 // MutexLockBase is a RAII helper for CRYPTO_MUTEX locking.
602 template <void (*LockFunc)(CRYPTO_MUTEX *), void (*ReleaseFunc)(CRYPTO_MUTEX *)>
603 class MutexLockBase {
604 public:
605 explicit MutexLockBase(CRYPTO_MUTEX *mu) : mu_(mu) {
606 assert(mu_ != nullptr);
607 LockFunc(mu_);
608 }
609 ~MutexLockBase() { ReleaseFunc(mu_); }
610 MutexLockBase(const MutexLockBase<LockFunc, ReleaseFunc> &) = delete;
611 MutexLockBase &operator=(const MutexLockBase<LockFunc, ReleaseFunc> &) =
612 delete;
613
614 private:
615 CRYPTO_MUTEX *const mu_;
616 };
617
618 } // namespace internal
619
620 using MutexWriteLock =
621 internal::MutexLockBase<CRYPTO_MUTEX_lock_write, CRYPTO_MUTEX_unlock_write>;
622 using MutexReadLock =
623 internal::MutexLockBase<CRYPTO_MUTEX_lock_read, CRYPTO_MUTEX_unlock_read>;
624
625 BSSL_NAMESPACE_END
626
627 } // extern "C++"
628 #endif // defined(__cplusplus)
629
630
631 // Thread local storage.
632
633 // thread_local_data_t enumerates the types of thread-local data that can be
634 // stored.
635 typedef enum {
636 OPENSSL_THREAD_LOCAL_ERR = 0,
637 OPENSSL_THREAD_LOCAL_RAND,
638 OPENSSL_THREAD_LOCAL_FIPS_COUNTERS,
639 OPENSSL_THREAD_LOCAL_TEST,
640 NUM_OPENSSL_THREAD_LOCALS,
641 } thread_local_data_t;
642
643 // thread_local_destructor_t is the type of a destructor function that will be
644 // called when a thread exits and its thread-local storage needs to be freed.
645 typedef void (*thread_local_destructor_t)(void *);
646
647 // CRYPTO_get_thread_local gets the pointer value that is stored for the
648 // current thread for the given index, or NULL if none has been set.
649 OPENSSL_EXPORT void *CRYPTO_get_thread_local(thread_local_data_t value);
650
651 // CRYPTO_set_thread_local sets a pointer value for the current thread at the
652 // given index. This function should only be called once per thread for a given
653 // |index|: rather than update the pointer value itself, update the data that
654 // is pointed to.
655 //
656 // The destructor function will be called when a thread exits to free this
657 // thread-local data. All calls to |CRYPTO_set_thread_local| with the same
658 // |index| should have the same |destructor| argument. The destructor may be
659 // called with a NULL argument if a thread that never set a thread-local
660 // pointer for |index|, exits. The destructor may be called concurrently with
661 // different arguments.
662 //
663 // This function returns one on success or zero on error. If it returns zero
664 // then |destructor| has been called with |value| already.
665 OPENSSL_EXPORT int CRYPTO_set_thread_local(
666 thread_local_data_t index, void *value,
667 thread_local_destructor_t destructor);
668
669
670 // ex_data
671
672 typedef struct crypto_ex_data_func_st CRYPTO_EX_DATA_FUNCS;
673
674 DECLARE_STACK_OF(CRYPTO_EX_DATA_FUNCS)
675
676 // CRYPTO_EX_DATA_CLASS tracks the ex_indices registered for a type which
677 // supports ex_data. It should defined as a static global within the module
678 // which defines that type.
679 typedef struct {
680 struct CRYPTO_STATIC_MUTEX lock;
681 STACK_OF(CRYPTO_EX_DATA_FUNCS) *meth;
682 // num_reserved is one if the ex_data index zero is reserved for legacy
683 // |TYPE_get_app_data| functions.
684 uint8_t num_reserved;
685 } CRYPTO_EX_DATA_CLASS;
686
687 #define CRYPTO_EX_DATA_CLASS_INIT {CRYPTO_STATIC_MUTEX_INIT, NULL, 0}
688 #define CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA \
689 {CRYPTO_STATIC_MUTEX_INIT, NULL, 1}
690
691 // CRYPTO_get_ex_new_index allocates a new index for |ex_data_class| and writes
692 // it to |*out_index|. Each class of object should provide a wrapper function
693 // that uses the correct |CRYPTO_EX_DATA_CLASS|. It returns one on success and
694 // zero otherwise.
695 OPENSSL_EXPORT int CRYPTO_get_ex_new_index(CRYPTO_EX_DATA_CLASS *ex_data_class,
696 int *out_index, long argl,
697 void *argp,
698 CRYPTO_EX_free *free_func);
699
700 // CRYPTO_set_ex_data sets an extra data pointer on a given object. Each class
701 // of object should provide a wrapper function.
702 OPENSSL_EXPORT int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int index, void *val);
703
704 // CRYPTO_get_ex_data returns an extra data pointer for a given object, or NULL
705 // if no such index exists. Each class of object should provide a wrapper
706 // function.
707 OPENSSL_EXPORT void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int index);
708
709 // CRYPTO_new_ex_data initialises a newly allocated |CRYPTO_EX_DATA|.
710 OPENSSL_EXPORT void CRYPTO_new_ex_data(CRYPTO_EX_DATA *ad);
711
712 // CRYPTO_free_ex_data frees |ad|, which is embedded inside |obj|, which is an
713 // object of the given class.
714 OPENSSL_EXPORT void CRYPTO_free_ex_data(CRYPTO_EX_DATA_CLASS *ex_data_class,
715 void *obj, CRYPTO_EX_DATA *ad);
716
717
718 // Endianness conversions.
719
720 #if defined(__GNUC__) && __GNUC__ >= 2
721 static inline uint16_t CRYPTO_bswap2(uint16_t x) {
722 return __builtin_bswap16(x);
723 }
724
725 static inline uint32_t CRYPTO_bswap4(uint32_t x) {
726 return __builtin_bswap32(x);
727 }
728
729 static inline uint64_t CRYPTO_bswap8(uint64_t x) {
730 return __builtin_bswap64(x);
731 }
732 #elif defined(_MSC_VER)
733 OPENSSL_MSVC_PRAGMA(warning(push, 3))
734 #include <stdlib.h>
735 OPENSSL_MSVC_PRAGMA(warning(pop))
736 #pragma intrinsic(_byteswap_uint64, _byteswap_ulong, _byteswap_ushort)
737 static inline uint16_t CRYPTO_bswap2(uint16_t x) {
738 return _byteswap_ushort(x);
739 }
740
741 static inline uint32_t CRYPTO_bswap4(uint32_t x) {
742 return _byteswap_ulong(x);
743 }
744
745 static inline uint64_t CRYPTO_bswap8(uint64_t x) {
746 return _byteswap_uint64(x);
747 }
748 #else
749 static inline uint16_t CRYPTO_bswap2(uint16_t x) {
750 return (x >> 8) | (x << 8);
751 }
752
753 static inline uint32_t CRYPTO_bswap4(uint32_t x) {
754 x = (x >> 16) | (x << 16);
755 x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
756 return x;
757 }
758
759 static inline uint64_t CRYPTO_bswap8(uint64_t x) {
760 return CRYPTO_bswap4(x >> 32) | (((uint64_t)CRYPTO_bswap4(x)) << 32);
761 }
762 #endif
763
764
765 // Language bug workarounds.
766 //
767 // Most C standard library functions are undefined if passed NULL, even when the
768 // corresponding length is zero. This gives them (and, in turn, all functions
769 // which call them) surprising behavior on empty arrays. Some compilers will
770 // miscompile code due to this rule. See also
771 // https://www.imperialviolet.org/2016/06/26/nonnull.html
772 //
773 // These wrapper functions behave the same as the corresponding C standard
774 // functions, but behave as expected when passed NULL if the length is zero.
775 //
776 // Note |OPENSSL_memcmp| is a different function from |CRYPTO_memcmp|.
777
778 // C++ defines |memchr| as a const-correct overload.
779 #if defined(__cplusplus)
780 extern "C++" {
781
782 static inline const void *OPENSSL_memchr(const void *s, int c, size_t n) {
783 if (n == 0) {
784 return NULL;
785 }
786
787 return memchr(s, c, n);
788 }
789
790 static inline void *OPENSSL_memchr(void *s, int c, size_t n) {
791 if (n == 0) {
792 return NULL;
793 }
794
795 return memchr(s, c, n);
796 }
797
798 } // extern "C++"
799 #else // __cplusplus
800
801 static inline void *OPENSSL_memchr(const void *s, int c, size_t n) {
802 if (n == 0) {
803 return NULL;
804 }
805
806 return memchr(s, c, n);
807 }
808
809 #endif // __cplusplus
810
811 static inline int OPENSSL_memcmp(const void *s1, const void *s2, size_t n) {
812 if (n == 0) {
813 return 0;
814 }
815
816 return memcmp(s1, s2, n);
817 }
818
819 static inline void *OPENSSL_memcpy(void *dst, const void *src, size_t n) {
820 if (n == 0) {
821 return dst;
822 }
823
824 return memcpy(dst, src, n);
825 }
826
827 static inline void *OPENSSL_memmove(void *dst, const void *src, size_t n) {
828 if (n == 0) {
829 return dst;
830 }
831
832 return memmove(dst, src, n);
833 }
834
835 static inline void *OPENSSL_memset(void *dst, int c, size_t n) {
836 if (n == 0) {
837 return dst;
838 }
839
840 return memset(dst, c, n);
841 }
842
843
844 // Loads and stores.
845 //
846 // The following functions load and store sized integers with the specified
847 // endianness. They use |memcpy|, and so avoid alignment or strict aliasing
848 // requirements on the input and output pointers.
849
850 static inline uint32_t CRYPTO_load_u32_le(const void *in) {
851 uint32_t v;
852 OPENSSL_memcpy(&v, in, sizeof(v));
853 return v;
854 }
855
856 static inline void CRYPTO_store_u32_le(void *out, uint32_t v) {
857 OPENSSL_memcpy(out, &v, sizeof(v));
858 }
859
860 static inline uint32_t CRYPTO_load_u32_be(const void *in) {
861 uint32_t v;
862 OPENSSL_memcpy(&v, in, sizeof(v));
863 return CRYPTO_bswap4(v);
864 }
865
866 static inline void CRYPTO_store_u32_be(void *out, uint32_t v) {
867 v = CRYPTO_bswap4(v);
868 OPENSSL_memcpy(out, &v, sizeof(v));
869 }
870
871 static inline uint64_t CRYPTO_load_u64_be(const void *ptr) {
872 uint64_t ret;
873 OPENSSL_memcpy(&ret, ptr, sizeof(ret));
874 return CRYPTO_bswap8(ret);
875 }
876
877 static inline void CRYPTO_store_u64_be(void *out, uint64_t v) {
878 v = CRYPTO_bswap8(v);
879 OPENSSL_memcpy(out, &v, sizeof(v));
880 }
881
882 static inline crypto_word_t CRYPTO_load_word_le(const void *in) {
883 crypto_word_t v;
884 OPENSSL_memcpy(&v, in, sizeof(v));
885 return v;
886 }
887
888 static inline void CRYPTO_store_word_le(void *out, crypto_word_t v) {
889 OPENSSL_memcpy(out, &v, sizeof(v));
890 }
891
892
893 // FIPS functions.
894
895 #if defined(BORINGSSL_FIPS)
896 // BORINGSSL_FIPS_abort is called when a FIPS power-on or continuous test
897 // fails. It prevents any further cryptographic operations by the current
898 // process.
899 void BORINGSSL_FIPS_abort(void) __attribute__((noreturn));
900 #endif
901
902 // boringssl_fips_self_test runs the FIPS KAT-based self tests. It returns one
903 // on success and zero on error. The argument is the integrity hash of the FIPS
904 // module and may be used to check and write flag files to suppress duplicate
905 // self-tests. If |module_hash_len| is zero then no flag file will be checked
906 // nor written and tests will always be run.
907 int boringssl_fips_self_test(const uint8_t *module_hash,
908 size_t module_hash_len);
909
910 #if defined(BORINGSSL_FIPS_COUNTERS)
911 void boringssl_fips_inc_counter(enum fips_counter_t counter);
912 #else
913 OPENSSL_INLINE void boringssl_fips_inc_counter(enum fips_counter_t counter) {}
914 #endif
915
916 #if defined(__cplusplus)
917 } // extern C
918 #endif
919
920 #endif // OPENSSL_HEADER_CRYPTO_INTERNAL_H
921