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 #include <openssl/mem.h>
58
59 #include <assert.h>
60 #include <stdarg.h>
61 #include <stdio.h>
62
63 #include <openssl/err.h>
64
65 #if defined(OPENSSL_WINDOWS)
66 OPENSSL_MSVC_PRAGMA(warning(push, 3))
67 #include <windows.h>
68 OPENSSL_MSVC_PRAGMA(warning(pop))
69 #endif
70
71 #include "internal.h"
72
73
74 #define OPENSSL_MALLOC_PREFIX 8
75 OPENSSL_STATIC_ASSERT(OPENSSL_MALLOC_PREFIX >= sizeof(size_t),
76 "size_t too large");
77
78 #if defined(OPENSSL_ASAN)
79 void __asan_poison_memory_region(const volatile void *addr, size_t size);
80 void __asan_unpoison_memory_region(const volatile void *addr, size_t size);
81 #else
__asan_poison_memory_region(const void * addr,size_t size)82 static void __asan_poison_memory_region(const void *addr, size_t size) {}
__asan_unpoison_memory_region(const void * addr,size_t size)83 static void __asan_unpoison_memory_region(const void *addr, size_t size) {}
84 #endif
85
86 // Windows doesn't really support weak symbols as of May 2019, and Clang on
87 // Windows will emit strong symbols instead. See
88 // https://bugs.llvm.org/show_bug.cgi?id=37598
89 #if defined(__ELF__) && defined(__GNUC__)
90 #define WEAK_SYMBOL_FUNC(rettype, name, args) \
91 rettype name args __attribute__((weak));
92 #else
93 #define WEAK_SYMBOL_FUNC(rettype, name, args) static rettype(*name) args = NULL;
94 #endif
95
96 #if defined(BORINGSSL_SDALLOCX)
97 // sdallocx is a sized |free| function. By passing the size (which we happen to
98 // always know in BoringSSL), the malloc implementation can save work.
99 //
100 // This is guarded by BORINGSSL_SDALLOCX, rather than being a weak symbol,
101 // because it can work poorly if there are two malloc implementations in the
102 // address space. (Which probably isn't valid, ODR etc, but
103 // https://github.com/grpc/grpc/issues/25450). In that situation, |malloc| can
104 // come from one allocator but |sdallocx| from another and crashes quickly
105 // result. We can't match |sdallocx| with |mallocx| because tcmalloc only
106 // provides the former, so a mismatch can still happen.
107 void sdallocx(void *ptr, size_t size, int flags);
108 #endif
109
110 // The following three functions can be defined to override default heap
111 // allocation and freeing. If defined, it is the responsibility of
112 // |OPENSSL_memory_free| to zero out the memory before returning it to the
113 // system. |OPENSSL_memory_free| will not be passed NULL pointers.
114 //
115 // WARNING: These functions are called on every allocation and free in
116 // BoringSSL across the entire process. They may be called by any code in the
117 // process which calls BoringSSL, including in process initializers and thread
118 // destructors. When called, BoringSSL may hold pthreads locks. Any other code
119 // in the process which, directly or indirectly, calls BoringSSL may be on the
120 // call stack and may itself be using arbitrary synchronization primitives.
121 //
122 // As a result, these functions may not have the usual programming environment
123 // available to most C or C++ code. In particular, they may not call into
124 // BoringSSL, or any library which depends on BoringSSL. Any synchronization
125 // primitives used must tolerate every other synchronization primitive linked
126 // into the process, including pthreads locks. Failing to meet these constraints
127 // may result in deadlocks, crashes, or memory corruption.
128 WEAK_SYMBOL_FUNC(void*, OPENSSL_memory_alloc, (size_t size));
129 WEAK_SYMBOL_FUNC(void, OPENSSL_memory_free, (void *ptr));
130 WEAK_SYMBOL_FUNC(size_t, OPENSSL_memory_get_size, (void *ptr));
131
OPENSSL_malloc(size_t size)132 void *OPENSSL_malloc(size_t size) {
133 if (OPENSSL_memory_alloc != NULL) {
134 assert(OPENSSL_memory_free != NULL);
135 assert(OPENSSL_memory_get_size != NULL);
136 return OPENSSL_memory_alloc(size);
137 }
138
139 if (size + OPENSSL_MALLOC_PREFIX < size) {
140 return NULL;
141 }
142
143 void *ptr = malloc(size + OPENSSL_MALLOC_PREFIX);
144 if (ptr == NULL) {
145 return NULL;
146 }
147
148 *(size_t *)ptr = size;
149
150 __asan_poison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
151 return ((uint8_t *)ptr) + OPENSSL_MALLOC_PREFIX;
152 }
153
OPENSSL_free(void * orig_ptr)154 void OPENSSL_free(void *orig_ptr) {
155 if (orig_ptr == NULL) {
156 return;
157 }
158
159 if (OPENSSL_memory_free != NULL) {
160 OPENSSL_memory_free(orig_ptr);
161 return;
162 }
163
164 void *ptr = ((uint8_t *)orig_ptr) - OPENSSL_MALLOC_PREFIX;
165 __asan_unpoison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
166
167 size_t size = *(size_t *)ptr;
168 OPENSSL_cleanse(ptr, size + OPENSSL_MALLOC_PREFIX);
169 #if defined(BORINGSSL_SDALLOCX)
170 sdallocx(ptr, size + OPENSSL_MALLOC_PREFIX, 0 /* flags */);
171 #else
172 free(ptr);
173 #endif
174 }
175
OPENSSL_realloc(void * orig_ptr,size_t new_size)176 void *OPENSSL_realloc(void *orig_ptr, size_t new_size) {
177 if (orig_ptr == NULL) {
178 return OPENSSL_malloc(new_size);
179 }
180
181 size_t old_size;
182 if (OPENSSL_memory_get_size != NULL) {
183 old_size = OPENSSL_memory_get_size(orig_ptr);
184 } else {
185 void *ptr = ((uint8_t *)orig_ptr) - OPENSSL_MALLOC_PREFIX;
186 __asan_unpoison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
187 old_size = *(size_t *)ptr;
188 __asan_poison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
189 }
190
191 void *ret = OPENSSL_malloc(new_size);
192 if (ret == NULL) {
193 return NULL;
194 }
195
196 size_t to_copy = new_size;
197 if (old_size < to_copy) {
198 to_copy = old_size;
199 }
200
201 memcpy(ret, orig_ptr, to_copy);
202 OPENSSL_free(orig_ptr);
203
204 return ret;
205 }
206
OPENSSL_cleanse(void * ptr,size_t len)207 void OPENSSL_cleanse(void *ptr, size_t len) {
208 #if defined(OPENSSL_WINDOWS)
209 SecureZeroMemory(ptr, len);
210 #else
211 OPENSSL_memset(ptr, 0, len);
212
213 #if !defined(OPENSSL_NO_ASM)
214 /* As best as we can tell, this is sufficient to break any optimisations that
215 might try to eliminate "superfluous" memsets. If there's an easy way to
216 detect memset_s, it would be better to use that. */
217 __asm__ __volatile__("" : : "r"(ptr) : "memory");
218 #endif
219 #endif // !OPENSSL_NO_ASM
220 }
221
OPENSSL_clear_free(void * ptr,size_t unused)222 void OPENSSL_clear_free(void *ptr, size_t unused) {
223 OPENSSL_free(ptr);
224 }
225
CRYPTO_memcmp(const void * in_a,const void * in_b,size_t len)226 int CRYPTO_memcmp(const void *in_a, const void *in_b, size_t len) {
227 const uint8_t *a = in_a;
228 const uint8_t *b = in_b;
229 uint8_t x = 0;
230
231 for (size_t i = 0; i < len; i++) {
232 x |= a[i] ^ b[i];
233 }
234
235 return x;
236 }
237
OPENSSL_hash32(const void * ptr,size_t len)238 uint32_t OPENSSL_hash32(const void *ptr, size_t len) {
239 // These are the FNV-1a parameters for 32 bits.
240 static const uint32_t kPrime = 16777619u;
241 static const uint32_t kOffsetBasis = 2166136261u;
242
243 const uint8_t *in = ptr;
244 uint32_t h = kOffsetBasis;
245
246 for (size_t i = 0; i < len; i++) {
247 h ^= in[i];
248 h *= kPrime;
249 }
250
251 return h;
252 }
253
OPENSSL_strhash(const char * s)254 uint32_t OPENSSL_strhash(const char *s) { return OPENSSL_hash32(s, strlen(s)); }
255
OPENSSL_strnlen(const char * s,size_t len)256 size_t OPENSSL_strnlen(const char *s, size_t len) {
257 for (size_t i = 0; i < len; i++) {
258 if (s[i] == 0) {
259 return i;
260 }
261 }
262
263 return len;
264 }
265
OPENSSL_strdup(const char * s)266 char *OPENSSL_strdup(const char *s) {
267 if (s == NULL) {
268 return NULL;
269 }
270 const size_t len = strlen(s) + 1;
271 char *ret = OPENSSL_malloc(len);
272 if (ret == NULL) {
273 return NULL;
274 }
275 OPENSSL_memcpy(ret, s, len);
276 return ret;
277 }
278
OPENSSL_tolower(int c)279 int OPENSSL_tolower(int c) {
280 if (c >= 'A' && c <= 'Z') {
281 return c + ('a' - 'A');
282 }
283 return c;
284 }
285
OPENSSL_strcasecmp(const char * a,const char * b)286 int OPENSSL_strcasecmp(const char *a, const char *b) {
287 for (size_t i = 0;; i++) {
288 const int aa = OPENSSL_tolower(a[i]);
289 const int bb = OPENSSL_tolower(b[i]);
290
291 if (aa < bb) {
292 return -1;
293 } else if (aa > bb) {
294 return 1;
295 } else if (aa == 0) {
296 return 0;
297 }
298 }
299 }
300
OPENSSL_strncasecmp(const char * a,const char * b,size_t n)301 int OPENSSL_strncasecmp(const char *a, const char *b, size_t n) {
302 for (size_t i = 0; i < n; i++) {
303 const int aa = OPENSSL_tolower(a[i]);
304 const int bb = OPENSSL_tolower(b[i]);
305
306 if (aa < bb) {
307 return -1;
308 } else if (aa > bb) {
309 return 1;
310 } else if (aa == 0) {
311 return 0;
312 }
313 }
314
315 return 0;
316 }
317
BIO_snprintf(char * buf,size_t n,const char * format,...)318 int BIO_snprintf(char *buf, size_t n, const char *format, ...) {
319 va_list args;
320 va_start(args, format);
321 int ret = BIO_vsnprintf(buf, n, format, args);
322 va_end(args);
323 return ret;
324 }
325
BIO_vsnprintf(char * buf,size_t n,const char * format,va_list args)326 int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args) {
327 return vsnprintf(buf, n, format, args);
328 }
329
OPENSSL_strndup(const char * str,size_t size)330 char *OPENSSL_strndup(const char *str, size_t size) {
331 size = OPENSSL_strnlen(str, size);
332
333 size_t alloc_size = size + 1;
334 if (alloc_size < size) {
335 // overflow
336 OPENSSL_PUT_ERROR(CRYPTO, ERR_R_MALLOC_FAILURE);
337 return NULL;
338 }
339 char *ret = OPENSSL_malloc(alloc_size);
340 if (ret == NULL) {
341 OPENSSL_PUT_ERROR(CRYPTO, ERR_R_MALLOC_FAILURE);
342 return NULL;
343 }
344
345 OPENSSL_memcpy(ret, str, size);
346 ret[size] = '\0';
347 return ret;
348 }
349
OPENSSL_strlcpy(char * dst,const char * src,size_t dst_size)350 size_t OPENSSL_strlcpy(char *dst, const char *src, size_t dst_size) {
351 size_t l = 0;
352
353 for (; dst_size > 1 && *src; dst_size--) {
354 *dst++ = *src++;
355 l++;
356 }
357
358 if (dst_size) {
359 *dst = 0;
360 }
361
362 return l + strlen(src);
363 }
364
OPENSSL_strlcat(char * dst,const char * src,size_t dst_size)365 size_t OPENSSL_strlcat(char *dst, const char *src, size_t dst_size) {
366 size_t l = 0;
367 for (; dst_size > 0 && *dst; dst_size--, dst++) {
368 l++;
369 }
370 return l + OPENSSL_strlcpy(dst, src, dst_size);
371 }
372
OPENSSL_memdup(const void * data,size_t size)373 void *OPENSSL_memdup(const void *data, size_t size) {
374 if (size == 0) {
375 return NULL;
376 }
377
378 void *ret = OPENSSL_malloc(size);
379 if (ret == NULL) {
380 OPENSSL_PUT_ERROR(CRYPTO, ERR_R_MALLOC_FAILURE);
381 return NULL;
382 }
383
384 OPENSSL_memcpy(ret, data, size);
385 return ret;
386 }
387