1 /*
2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10 #include <openssl/mem.h>
11
12 #include <assert.h>
13 #include <errno.h>
14 #include <limits.h>
15 #include <stdarg.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18
19 #include <openssl/err.h>
20
21 #if defined(OPENSSL_WINDOWS)
22 OPENSSL_MSVC_PRAGMA(warning(push, 3))
23 #include <windows.h>
24 OPENSSL_MSVC_PRAGMA(warning(pop))
25 #endif
26
27 #if defined(BORINGSSL_MALLOC_FAILURE_TESTING)
28 #include <errno.h>
29 #include <signal.h>
30 #include <unistd.h>
31 #endif
32
33 #include "internal.h"
34
35
36 #define OPENSSL_MALLOC_PREFIX 8
37 static_assert(OPENSSL_MALLOC_PREFIX >= sizeof(size_t), "size_t too large");
38
39 #if defined(OPENSSL_ASAN)
40 extern "C" {
41 void __asan_poison_memory_region(const volatile void *addr, size_t size);
42 void __asan_unpoison_memory_region(const volatile void *addr, size_t size);
43 }
44 #else
__asan_poison_memory_region(const void * addr,size_t size)45 static void __asan_poison_memory_region(const void *addr, size_t size) {}
__asan_unpoison_memory_region(const void * addr,size_t size)46 static void __asan_unpoison_memory_region(const void *addr, size_t size) {}
47 #endif
48
49 // Windows doesn't really support weak symbols as of May 2019, and Clang on
50 // Windows will emit strong symbols instead. See
51 // https://bugs.llvm.org/show_bug.cgi?id=37598
52 //
53 // EDK2 targets UEFI but builds as ELF and then translates the binary to
54 // COFF(!). Thus it builds with __ELF__ defined but cannot actually cope with
55 // weak symbols.
56 #if !defined(__EDK2_BORINGSSL__) && defined(__ELF__) && defined(__GNUC__)
57 #define WEAK_SYMBOL_FUNC(rettype, name, args) \
58 extern "C" { \
59 rettype name args __attribute__((weak)); \
60 }
61 #else
62 #define WEAK_SYMBOL_FUNC(rettype, name, args) \
63 static rettype(*const name) args = NULL;
64 #endif
65
66 #if defined(BORINGSSL_DETECT_SDALLOCX)
67 // sdallocx is a sized |free| function. By passing the size (which we happen to
68 // always know in BoringSSL), the malloc implementation can save work. We cannot
69 // depend on |sdallocx| being available, however, so it's a weak symbol.
70 //
71 // This mechanism is kept opt-in because it assumes that, when |sdallocx| is
72 // defined, it is part of the same allocator as |malloc|. This is usually true
73 // but may break if |malloc| does not implement |sdallocx|, but some other
74 // allocator with |sdallocx| is imported which does.
75 WEAK_SYMBOL_FUNC(void, sdallocx, (void *ptr, size_t size, int flags))
76 #else
77 static void (*const sdallocx)(void *ptr, size_t size, int flags) = NULL;
78 #endif
79
80 // The following three functions can be defined to override default heap
81 // allocation and freeing. If defined, it is the responsibility of
82 // |OPENSSL_memory_free| to zero out the memory before returning it to the
83 // system. |OPENSSL_memory_free| will not be passed NULL pointers.
84 //
85 // WARNING: These functions are called on every allocation and free in
86 // BoringSSL across the entire process. They may be called by any code in the
87 // process which calls BoringSSL, including in process initializers and thread
88 // destructors. When called, BoringSSL may hold pthreads locks. Any other code
89 // in the process which, directly or indirectly, calls BoringSSL may be on the
90 // call stack and may itself be using arbitrary synchronization primitives.
91 //
92 // As a result, these functions may not have the usual programming environment
93 // available to most C or C++ code. In particular, they may not call into
94 // BoringSSL, or any library which depends on BoringSSL. Any synchronization
95 // primitives used must tolerate every other synchronization primitive linked
96 // into the process, including pthreads locks. Failing to meet these constraints
97 // may result in deadlocks, crashes, or memory corruption.
98 WEAK_SYMBOL_FUNC(void *, OPENSSL_memory_alloc, (size_t size))
99 WEAK_SYMBOL_FUNC(void, OPENSSL_memory_free, (void *ptr))
100 WEAK_SYMBOL_FUNC(size_t, OPENSSL_memory_get_size, (void *ptr))
101
102 #if defined(BORINGSSL_MALLOC_FAILURE_TESTING)
103 static CRYPTO_MUTEX malloc_failure_lock = CRYPTO_MUTEX_INIT;
104 static uint64_t current_malloc_count = 0;
105 static uint64_t malloc_number_to_fail = 0;
106 static int malloc_failure_enabled = 0, break_on_malloc_fail = 0,
107 any_malloc_failed = 0, disable_malloc_failures = 0;
108
malloc_exit_handler(void)109 static void malloc_exit_handler(void) {
110 CRYPTO_MUTEX_lock_read(&malloc_failure_lock);
111 if (any_malloc_failed) {
112 // Signal to the test driver that some allocation failed, so it knows to
113 // increment the counter and continue.
114 _exit(88);
115 }
116 CRYPTO_MUTEX_unlock_read(&malloc_failure_lock);
117 }
118
init_malloc_failure(void)119 static void init_malloc_failure(void) {
120 const char *env = getenv("MALLOC_NUMBER_TO_FAIL");
121 if (env != NULL && env[0] != 0) {
122 char *endptr;
123 malloc_number_to_fail = strtoull(env, &endptr, 10);
124 if (*endptr == 0) {
125 malloc_failure_enabled = 1;
126 atexit(malloc_exit_handler);
127 }
128 }
129 break_on_malloc_fail = getenv("MALLOC_BREAK_ON_FAIL") != NULL;
130 }
131
132 // should_fail_allocation returns one if the current allocation should fail and
133 // zero otherwise.
should_fail_allocation()134 static int should_fail_allocation() {
135 static CRYPTO_once_t once = CRYPTO_ONCE_INIT;
136 CRYPTO_once(&once, init_malloc_failure);
137 if (!malloc_failure_enabled || disable_malloc_failures) {
138 return 0;
139 }
140
141 // We lock just so multi-threaded tests are still correct, but we won't test
142 // every malloc exhaustively.
143 CRYPTO_MUTEX_lock_write(&malloc_failure_lock);
144 int should_fail = current_malloc_count == malloc_number_to_fail;
145 current_malloc_count++;
146 any_malloc_failed = any_malloc_failed || should_fail;
147 CRYPTO_MUTEX_unlock_write(&malloc_failure_lock);
148
149 if (should_fail && break_on_malloc_fail) {
150 raise(SIGTRAP);
151 }
152 if (should_fail) {
153 errno = ENOMEM;
154 }
155 return should_fail;
156 }
157
OPENSSL_reset_malloc_counter_for_testing(void)158 void OPENSSL_reset_malloc_counter_for_testing(void) {
159 CRYPTO_MUTEX_lock_write(&malloc_failure_lock);
160 current_malloc_count = 0;
161 CRYPTO_MUTEX_unlock_write(&malloc_failure_lock);
162 }
163
OPENSSL_disable_malloc_failures_for_testing(void)164 void OPENSSL_disable_malloc_failures_for_testing(void) {
165 CRYPTO_MUTEX_lock_write(&malloc_failure_lock);
166 BSSL_CHECK(!disable_malloc_failures);
167 disable_malloc_failures = 1;
168 CRYPTO_MUTEX_unlock_write(&malloc_failure_lock);
169 }
170
OPENSSL_enable_malloc_failures_for_testing(void)171 void OPENSSL_enable_malloc_failures_for_testing(void) {
172 CRYPTO_MUTEX_lock_write(&malloc_failure_lock);
173 BSSL_CHECK(disable_malloc_failures);
174 disable_malloc_failures = 0;
175 CRYPTO_MUTEX_unlock_write(&malloc_failure_lock);
176 }
177
178 #else
179 static int should_fail_allocation(void) { return 0; }
180 #endif
181
OPENSSL_malloc(size_t size)182 void *OPENSSL_malloc(size_t size) {
183 void *ptr = nullptr;
184 if (should_fail_allocation()) {
185 goto err;
186 }
187
188 if (OPENSSL_memory_alloc != NULL) {
189 assert(OPENSSL_memory_free != NULL);
190 assert(OPENSSL_memory_get_size != NULL);
191 void *ptr2 = OPENSSL_memory_alloc(size);
192 if (ptr2 == NULL && size != 0) {
193 goto err;
194 }
195 return ptr2;
196 }
197
198 if (size + OPENSSL_MALLOC_PREFIX < size) {
199 goto err;
200 }
201
202 ptr = malloc(size + OPENSSL_MALLOC_PREFIX);
203 if (ptr == NULL) {
204 goto err;
205 }
206
207 *(size_t *)ptr = size;
208
209 __asan_poison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
210 return ((uint8_t *)ptr) + OPENSSL_MALLOC_PREFIX;
211
212 err:
213 // This only works because ERR does not call OPENSSL_malloc.
214 OPENSSL_PUT_ERROR(CRYPTO, ERR_R_MALLOC_FAILURE);
215 return NULL;
216 }
217
OPENSSL_zalloc(size_t size)218 void *OPENSSL_zalloc(size_t size) {
219 void *ret = OPENSSL_malloc(size);
220 if (ret != NULL) {
221 OPENSSL_memset(ret, 0, size);
222 }
223 return ret;
224 }
225
OPENSSL_calloc(size_t num,size_t size)226 void *OPENSSL_calloc(size_t num, size_t size) {
227 if (size != 0 && num > SIZE_MAX / size) {
228 OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW);
229 return NULL;
230 }
231
232 return OPENSSL_zalloc(num * size);
233 }
234
OPENSSL_free(void * orig_ptr)235 void OPENSSL_free(void *orig_ptr) {
236 if (orig_ptr == NULL) {
237 return;
238 }
239
240 if (OPENSSL_memory_free != NULL) {
241 OPENSSL_memory_free(orig_ptr);
242 return;
243 }
244
245 void *ptr = ((uint8_t *)orig_ptr) - OPENSSL_MALLOC_PREFIX;
246 __asan_unpoison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
247
248 size_t size = *(size_t *)ptr;
249 OPENSSL_cleanse(ptr, size + OPENSSL_MALLOC_PREFIX);
250
251 // ASan knows to intercept malloc and free, but not sdallocx.
252 #if defined(OPENSSL_ASAN)
253 (void)sdallocx;
254 free(ptr);
255 #else
256 if (sdallocx) {
257 sdallocx(ptr, size + OPENSSL_MALLOC_PREFIX, 0 /* flags */);
258 } else {
259 free(ptr);
260 }
261 #endif
262 }
263
OPENSSL_realloc(void * orig_ptr,size_t new_size)264 void *OPENSSL_realloc(void *orig_ptr, size_t new_size) {
265 if (orig_ptr == NULL) {
266 return OPENSSL_malloc(new_size);
267 }
268
269 size_t old_size;
270 if (OPENSSL_memory_get_size != NULL) {
271 old_size = OPENSSL_memory_get_size(orig_ptr);
272 } else {
273 void *ptr = ((uint8_t *)orig_ptr) - OPENSSL_MALLOC_PREFIX;
274 __asan_unpoison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
275 old_size = *(size_t *)ptr;
276 __asan_poison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
277 }
278
279 void *ret = OPENSSL_malloc(new_size);
280 if (ret == NULL) {
281 return NULL;
282 }
283
284 size_t to_copy = new_size;
285 if (old_size < to_copy) {
286 to_copy = old_size;
287 }
288
289 memcpy(ret, orig_ptr, to_copy);
290 OPENSSL_free(orig_ptr);
291
292 return ret;
293 }
294
OPENSSL_cleanse(void * ptr,size_t len)295 void OPENSSL_cleanse(void *ptr, size_t len) {
296 #if defined(OPENSSL_WINDOWS)
297 SecureZeroMemory(ptr, len);
298 #else
299 OPENSSL_memset(ptr, 0, len);
300
301 #if !defined(OPENSSL_NO_ASM)
302 /* As best as we can tell, this is sufficient to break any optimisations that
303 might try to eliminate "superfluous" memsets. If there's an easy way to
304 detect memset_s, it would be better to use that. */
305 __asm__ __volatile__("" : : "r"(ptr) : "memory");
306 #endif
307 #endif // !OPENSSL_NO_ASM
308 }
309
OPENSSL_clear_free(void * ptr,size_t unused)310 void OPENSSL_clear_free(void *ptr, size_t unused) { OPENSSL_free(ptr); }
311
CRYPTO_secure_malloc_init(size_t size,size_t min_size)312 int CRYPTO_secure_malloc_init(size_t size, size_t min_size) { return 0; }
313
CRYPTO_secure_malloc_initialized(void)314 int CRYPTO_secure_malloc_initialized(void) { return 0; }
315
CRYPTO_secure_used(void)316 size_t CRYPTO_secure_used(void) { return 0; }
317
OPENSSL_secure_malloc(size_t size)318 void *OPENSSL_secure_malloc(size_t size) { return OPENSSL_malloc(size); }
319
OPENSSL_secure_clear_free(void * ptr,size_t len)320 void OPENSSL_secure_clear_free(void *ptr, size_t len) {
321 OPENSSL_clear_free(ptr, len);
322 }
323
CRYPTO_memcmp(const void * in_a,const void * in_b,size_t len)324 int CRYPTO_memcmp(const void *in_a, const void *in_b, size_t len) {
325 const uint8_t *a = reinterpret_cast<const uint8_t *>(in_a);
326 const uint8_t *b = reinterpret_cast<const uint8_t *>(in_b);
327 uint8_t x = 0;
328
329 for (size_t i = 0; i < len; i++) {
330 x |= a[i] ^ b[i];
331 }
332
333 return x;
334 }
335
OPENSSL_hash32(const void * ptr,size_t len)336 uint32_t OPENSSL_hash32(const void *ptr, size_t len) {
337 // These are the FNV-1a parameters for 32 bits.
338 static const uint32_t kPrime = 16777619u;
339 static const uint32_t kOffsetBasis = 2166136261u;
340
341 const uint8_t *in = reinterpret_cast<const uint8_t *>(ptr);
342 uint32_t h = kOffsetBasis;
343
344 for (size_t i = 0; i < len; i++) {
345 h ^= in[i];
346 h *= kPrime;
347 }
348
349 return h;
350 }
351
OPENSSL_strhash(const char * s)352 uint32_t OPENSSL_strhash(const char *s) { return OPENSSL_hash32(s, strlen(s)); }
353
OPENSSL_strnlen(const char * s,size_t len)354 size_t OPENSSL_strnlen(const char *s, size_t len) {
355 for (size_t i = 0; i < len; i++) {
356 if (s[i] == 0) {
357 return i;
358 }
359 }
360
361 return len;
362 }
363
OPENSSL_strdup(const char * s)364 char *OPENSSL_strdup(const char *s) {
365 if (s == NULL) {
366 return NULL;
367 }
368 // Copy the NUL terminator.
369 return reinterpret_cast<char *>(OPENSSL_memdup(s, strlen(s) + 1));
370 }
371
OPENSSL_isalpha(int c)372 int OPENSSL_isalpha(int c) {
373 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
374 }
375
OPENSSL_isdigit(int c)376 int OPENSSL_isdigit(int c) { return c >= '0' && c <= '9'; }
377
OPENSSL_isxdigit(int c)378 int OPENSSL_isxdigit(int c) {
379 return OPENSSL_isdigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
380 }
381
OPENSSL_fromxdigit(uint8_t * out,int c)382 int OPENSSL_fromxdigit(uint8_t *out, int c) {
383 if (OPENSSL_isdigit(c)) {
384 *out = c - '0';
385 return 1;
386 }
387 if ('a' <= c && c <= 'f') {
388 *out = c - 'a' + 10;
389 return 1;
390 }
391 if ('A' <= c && c <= 'F') {
392 *out = c - 'A' + 10;
393 return 1;
394 }
395 return 0;
396 }
397
OPENSSL_isalnum(int c)398 int OPENSSL_isalnum(int c) { return OPENSSL_isalpha(c) || OPENSSL_isdigit(c); }
399
OPENSSL_tolower(int c)400 int OPENSSL_tolower(int c) {
401 if (c >= 'A' && c <= 'Z') {
402 return c + ('a' - 'A');
403 }
404 return c;
405 }
406
OPENSSL_isspace(int c)407 int OPENSSL_isspace(int c) {
408 return c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r' ||
409 c == ' ';
410 }
411
OPENSSL_strcasecmp(const char * a,const char * b)412 int OPENSSL_strcasecmp(const char *a, const char *b) {
413 for (size_t i = 0;; i++) {
414 const int aa = OPENSSL_tolower(a[i]);
415 const int bb = OPENSSL_tolower(b[i]);
416
417 if (aa < bb) {
418 return -1;
419 } else if (aa > bb) {
420 return 1;
421 } else if (aa == 0) {
422 return 0;
423 }
424 }
425 }
426
OPENSSL_strncasecmp(const char * a,const char * b,size_t n)427 int OPENSSL_strncasecmp(const char *a, const char *b, size_t n) {
428 for (size_t i = 0; i < n; i++) {
429 const int aa = OPENSSL_tolower(a[i]);
430 const int bb = OPENSSL_tolower(b[i]);
431
432 if (aa < bb) {
433 return -1;
434 } else if (aa > bb) {
435 return 1;
436 } else if (aa == 0) {
437 return 0;
438 }
439 }
440
441 return 0;
442 }
443
BIO_snprintf(char * buf,size_t n,const char * format,...)444 int BIO_snprintf(char *buf, size_t n, const char *format, ...) {
445 va_list args;
446 va_start(args, format);
447 int ret = BIO_vsnprintf(buf, n, format, args);
448 va_end(args);
449 return ret;
450 }
451
BIO_vsnprintf(char * buf,size_t n,const char * format,va_list args)452 int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args) {
453 return vsnprintf(buf, n, format, args);
454 }
455
OPENSSL_vasprintf_internal(char ** str,const char * format,va_list args,int system_malloc)456 int OPENSSL_vasprintf_internal(char **str, const char *format, va_list args,
457 int system_malloc) {
458 void *(*allocate)(size_t) = system_malloc ? malloc : OPENSSL_malloc;
459 void (*deallocate)(void *) = system_malloc ? free : OPENSSL_free;
460 void *(*reallocate)(void *, size_t) =
461 system_malloc ? realloc : OPENSSL_realloc;
462 char *candidate = NULL;
463 size_t candidate_len = 64; // TODO(bbe) what's the best initial size?
464 int ret;
465
466 if ((candidate = reinterpret_cast<char *>(allocate(candidate_len))) == NULL) {
467 goto err;
468 }
469 va_list args_copy;
470 va_copy(args_copy, args);
471 ret = vsnprintf(candidate, candidate_len, format, args_copy);
472 va_end(args_copy);
473 if (ret < 0) {
474 goto err;
475 }
476 if ((size_t)ret >= candidate_len) {
477 // Too big to fit in allocation.
478 char *tmp;
479
480 candidate_len = (size_t)ret + 1;
481 if ((tmp = reinterpret_cast<char *>(
482 reallocate(candidate, candidate_len))) == NULL) {
483 goto err;
484 }
485 candidate = tmp;
486 ret = vsnprintf(candidate, candidate_len, format, args);
487 }
488 // At this point this should not happen unless vsnprintf is insane.
489 if (ret < 0 || (size_t)ret >= candidate_len) {
490 goto err;
491 }
492 *str = candidate;
493 return ret;
494
495 err:
496 deallocate(candidate);
497 *str = NULL;
498 errno = ENOMEM;
499 return -1;
500 }
501
OPENSSL_vasprintf(char ** str,const char * format,va_list args)502 int OPENSSL_vasprintf(char **str, const char *format, va_list args) {
503 return OPENSSL_vasprintf_internal(str, format, args, /*system_malloc=*/0);
504 }
505
OPENSSL_asprintf(char ** str,const char * format,...)506 int OPENSSL_asprintf(char **str, const char *format, ...) {
507 va_list args;
508 va_start(args, format);
509 int ret = OPENSSL_vasprintf(str, format, args);
510 va_end(args);
511 return ret;
512 }
513
OPENSSL_strndup(const char * str,size_t size)514 char *OPENSSL_strndup(const char *str, size_t size) {
515 size = OPENSSL_strnlen(str, size);
516
517 size_t alloc_size = size + 1;
518 if (alloc_size < size) {
519 // overflow
520 OPENSSL_PUT_ERROR(CRYPTO, ERR_R_MALLOC_FAILURE);
521 return NULL;
522 }
523 char *ret = reinterpret_cast<char *>(OPENSSL_malloc(alloc_size));
524 if (ret == NULL) {
525 return NULL;
526 }
527
528 OPENSSL_memcpy(ret, str, size);
529 ret[size] = '\0';
530 return ret;
531 }
532
OPENSSL_strlcpy(char * dst,const char * src,size_t dst_size)533 size_t OPENSSL_strlcpy(char *dst, const char *src, size_t dst_size) {
534 size_t l = 0;
535
536 for (; dst_size > 1 && *src; dst_size--) {
537 *dst++ = *src++;
538 l++;
539 }
540
541 if (dst_size) {
542 *dst = 0;
543 }
544
545 return l + strlen(src);
546 }
547
OPENSSL_strlcat(char * dst,const char * src,size_t dst_size)548 size_t OPENSSL_strlcat(char *dst, const char *src, size_t dst_size) {
549 size_t l = 0;
550 for (; dst_size > 0 && *dst; dst_size--, dst++) {
551 l++;
552 }
553 return l + OPENSSL_strlcpy(dst, src, dst_size);
554 }
555
OPENSSL_memdup(const void * data,size_t size)556 void *OPENSSL_memdup(const void *data, size_t size) {
557 if (size == 0) {
558 return NULL;
559 }
560
561 void *ret = OPENSSL_malloc(size);
562 if (ret == NULL) {
563 return NULL;
564 }
565
566 OPENSSL_memcpy(ret, data, size);
567 return ret;
568 }
569
CRYPTO_malloc(size_t size,const char * file,int line)570 void *CRYPTO_malloc(size_t size, const char *file, int line) {
571 return OPENSSL_malloc(size);
572 }
573
CRYPTO_realloc(void * ptr,size_t new_size,const char * file,int line)574 void *CRYPTO_realloc(void *ptr, size_t new_size, const char *file, int line) {
575 return OPENSSL_realloc(ptr, new_size);
576 }
577
CRYPTO_free(void * ptr,const char * file,int line)578 void CRYPTO_free(void *ptr, const char *file, int line) { OPENSSL_free(ptr); }
579