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