1 /*
2 * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (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 "internal/e_os.h"
11 #include "internal/cryptlib.h"
12 #include "crypto/cryptlib.h"
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <limits.h>
16 #include <openssl/crypto.h>
17
18 /*
19 * the following pointers may be changed as long as 'allow_customize' is set
20 */
21 static int allow_customize = 1;
22 static CRYPTO_malloc_fn malloc_impl = CRYPTO_malloc;
23 static CRYPTO_realloc_fn realloc_impl = CRYPTO_realloc;
24 static CRYPTO_free_fn free_impl = CRYPTO_free;
25
26 #if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE)
27 # include "internal/tsan_assist.h"
28
29 # ifdef TSAN_REQUIRES_LOCKING
30 # define INCREMENT(x) /* empty */
31 # define LOAD(x) 0
32 # else /* TSAN_REQUIRES_LOCKING */
33 static TSAN_QUALIFIER int malloc_count;
34 static TSAN_QUALIFIER int realloc_count;
35 static TSAN_QUALIFIER int free_count;
36
37 # define INCREMENT(x) tsan_counter(&(x))
38 # define LOAD(x) tsan_load(&x)
39 # endif /* TSAN_REQUIRES_LOCKING */
40
41 static char md_failbuf[CRYPTO_MEM_CHECK_MAX_FS + 1];
42 static char *md_failstring = NULL;
43 static long md_count;
44 static int md_fail_percent = 0;
45 static int md_tracefd = -1;
46
47 static void parseit(void);
48 static int shouldfail(void);
49
50 # define FAILTEST() if (shouldfail()) return NULL
51
52 #else
53
54 # define INCREMENT(x) /* empty */
55 # define FAILTEST() /* empty */
56 #endif
57
CRYPTO_set_mem_functions(CRYPTO_malloc_fn malloc_fn,CRYPTO_realloc_fn realloc_fn,CRYPTO_free_fn free_fn)58 int CRYPTO_set_mem_functions(CRYPTO_malloc_fn malloc_fn,
59 CRYPTO_realloc_fn realloc_fn,
60 CRYPTO_free_fn free_fn)
61 {
62 if (!allow_customize)
63 return 0;
64 if (malloc_fn != NULL)
65 malloc_impl = malloc_fn;
66 if (realloc_fn != NULL)
67 realloc_impl = realloc_fn;
68 if (free_fn != NULL)
69 free_impl = free_fn;
70 return 1;
71 }
72
CRYPTO_get_mem_functions(CRYPTO_malloc_fn * malloc_fn,CRYPTO_realloc_fn * realloc_fn,CRYPTO_free_fn * free_fn)73 void CRYPTO_get_mem_functions(CRYPTO_malloc_fn *malloc_fn,
74 CRYPTO_realloc_fn *realloc_fn,
75 CRYPTO_free_fn *free_fn)
76 {
77 if (malloc_fn != NULL)
78 *malloc_fn = malloc_impl;
79 if (realloc_fn != NULL)
80 *realloc_fn = realloc_impl;
81 if (free_fn != NULL)
82 *free_fn = free_impl;
83 }
84
85 #if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE)
CRYPTO_get_alloc_counts(int * mcount,int * rcount,int * fcount)86 void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount)
87 {
88 if (mcount != NULL)
89 *mcount = LOAD(malloc_count);
90 if (rcount != NULL)
91 *rcount = LOAD(realloc_count);
92 if (fcount != NULL)
93 *fcount = LOAD(free_count);
94 }
95
96 /*
97 * Parse a "malloc failure spec" string. This likes like a set of fields
98 * separated by semicolons. Each field has a count and an optional failure
99 * percentage. For example:
100 * 100@0;100@25;0@0
101 * or 100;100@25;0
102 * This means 100 mallocs succeed, then next 100 fail 25% of the time, and
103 * all remaining (count is zero) succeed.
104 * The failure percentge can have 2 digits after the comma. For example:
105 * 0@0.01
106 * This means 0.01% of all allocations will fail.
107 */
parseit(void)108 static void parseit(void)
109 {
110 char *semi = strchr(md_failstring, ';');
111 char *atsign;
112
113 if (semi != NULL)
114 *semi++ = '\0';
115
116 /* Get the count (atol will stop at the @ if there), and percentage */
117 md_count = atol(md_failstring);
118 atsign = strchr(md_failstring, '@');
119 md_fail_percent = atsign == NULL ? 0 : (int)(atof(atsign + 1) * 100 + 0.5);
120
121 if (semi != NULL)
122 md_failstring = semi;
123 }
124
125 /*
126 * Windows doesn't have random() and srandom(), but it has rand() and srand().
127 * Some rand() implementations aren't good, but we're not
128 * dealing with secure randomness here.
129 */
130 # ifdef _WIN32
131 # define random() rand()
132 # define srandom(seed) srand(seed)
133 # endif
134 /*
135 * See if the current malloc should fail.
136 */
shouldfail(void)137 static int shouldfail(void)
138 {
139 int roll = (int)(random() % 10000);
140 int shoulditfail = roll < md_fail_percent;
141 # ifndef _WIN32
142 /* suppressed on Windows as POSIX-like file descriptors are non-inheritable */
143 int len;
144 char buff[80];
145
146 if (md_tracefd > 0) {
147 BIO_snprintf(buff, sizeof(buff),
148 "%c C%ld %%%d R%d\n",
149 shoulditfail ? '-' : '+', md_count, md_fail_percent, roll);
150 len = strlen(buff);
151 if (write(md_tracefd, buff, len) != len)
152 perror("shouldfail write failed");
153 }
154 # endif
155
156 if (md_count) {
157 /* If we used up this one, go to the next. */
158 if (--md_count == 0)
159 parseit();
160 }
161
162 return shoulditfail;
163 }
164
ossl_malloc_setup_failures(void)165 void ossl_malloc_setup_failures(void)
166 {
167 const char *cp = getenv("OPENSSL_MALLOC_FAILURES");
168 size_t cplen = 0;
169
170 if (cp != NULL) {
171 /* if the value is too long we'll just ignore it */
172 cplen = strlen(cp);
173 if (cplen <= CRYPTO_MEM_CHECK_MAX_FS) {
174 strncpy(md_failbuf, cp, CRYPTO_MEM_CHECK_MAX_FS);
175 md_failstring = md_failbuf;
176 parseit();
177 }
178 }
179 if ((cp = getenv("OPENSSL_MALLOC_FD")) != NULL)
180 md_tracefd = atoi(cp);
181 if ((cp = getenv("OPENSSL_MALLOC_SEED")) != NULL)
182 srandom(atoi(cp));
183 }
184 #endif
185
CRYPTO_malloc(size_t num,const char * file,int line)186 void *CRYPTO_malloc(size_t num, const char *file, int line)
187 {
188 void *ptr;
189
190 INCREMENT(malloc_count);
191 if (malloc_impl != CRYPTO_malloc) {
192 ptr = malloc_impl(num, file, line);
193 if (ptr != NULL || num == 0)
194 return ptr;
195 goto err;
196 }
197
198 if (num == 0)
199 return NULL;
200
201 FAILTEST();
202 if (allow_customize) {
203 /*
204 * Disallow customization after the first allocation. We only set this
205 * if necessary to avoid a store to the same cache line on every
206 * allocation.
207 */
208 allow_customize = 0;
209 }
210
211 ptr = malloc(num);
212 if (ptr != NULL)
213 return ptr;
214 err:
215 /*
216 * ossl_err_get_state_int() in err.c uses CRYPTO_zalloc(num, NULL, 0) for
217 * ERR_STATE allocation. Prevent mem alloc error loop while reporting error.
218 */
219 if (file != NULL || line != 0) {
220 ERR_new();
221 ERR_set_debug(file, line, NULL);
222 ERR_set_error(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE, NULL);
223 }
224 return NULL;
225 }
226
CRYPTO_zalloc(size_t num,const char * file,int line)227 void *CRYPTO_zalloc(size_t num, const char *file, int line)
228 {
229 void *ret;
230
231 ret = CRYPTO_malloc(num, file, line);
232 if (ret != NULL)
233 memset(ret, 0, num);
234
235 return ret;
236 }
237
CRYPTO_aligned_alloc(size_t num,size_t alignment,void ** freeptr,const char * file,int line)238 void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr,
239 const char *file, int line)
240 {
241 void *ret;
242
243 *freeptr = NULL;
244
245 #if defined(OPENSSL_SMALL_FOOTPRINT)
246 ret = freeptr = NULL;
247 return ret;
248 #endif
249
250 /* Allow non-malloc() allocations as long as no malloc_impl is provided. */
251 if (malloc_impl == CRYPTO_malloc) {
252 #if defined(_BSD_SOURCE) || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
253 if (posix_memalign(&ret, alignment, num))
254 return NULL;
255 *freeptr = ret;
256 return ret;
257 #elif defined(_ISOC11_SOURCE)
258 ret = *freeptr = aligned_alloc(alignment, num);
259 return ret;
260 #endif
261 }
262
263 /* we have to do this the hard way */
264
265 /*
266 * Note: Windows supports an _aligned_malloc call, but we choose
267 * not to use it here, because allocations from that function
268 * require that they be freed via _aligned_free. Given that
269 * we can't differentiate plain malloc blocks from blocks obtained
270 * via _aligned_malloc, just avoid its use entirely
271 */
272
273 /*
274 * Step 1: Allocate an amount of memory that is <alignment>
275 * bytes bigger than requested
276 */
277 *freeptr = CRYPTO_malloc(num + alignment, file, line);
278 if (*freeptr == NULL)
279 return NULL;
280
281 /*
282 * Step 2: Add <alignment - 1> bytes to the pointer
283 * This will cross the alignment boundary that is
284 * requested
285 */
286 ret = (void *)((char *)*freeptr + (alignment - 1));
287
288 /*
289 * Step 3: Use the alignment as a mask to translate the
290 * least significant bits of the allocation at the alignment
291 * boundary to 0. ret now holds a pointer to the memory
292 * buffer at the requested alignment
293 * NOTE: It is a documented requirement that alignment be a
294 * power of 2, which is what allows this to work
295 */
296 ret = (void *)((uintptr_t)ret & (uintptr_t)(~(alignment - 1)));
297 return ret;
298 }
299
CRYPTO_realloc(void * str,size_t num,const char * file,int line)300 void *CRYPTO_realloc(void *str, size_t num, const char *file, int line)
301 {
302 INCREMENT(realloc_count);
303 if (realloc_impl != CRYPTO_realloc)
304 return realloc_impl(str, num, file, line);
305
306 if (str == NULL)
307 return CRYPTO_malloc(num, file, line);
308
309 if (num == 0) {
310 CRYPTO_free(str, file, line);
311 return NULL;
312 }
313
314 FAILTEST();
315 return realloc(str, num);
316 }
317
CRYPTO_clear_realloc(void * str,size_t old_len,size_t num,const char * file,int line)318 void *CRYPTO_clear_realloc(void *str, size_t old_len, size_t num,
319 const char *file, int line)
320 {
321 void *ret = NULL;
322
323 if (str == NULL)
324 return CRYPTO_malloc(num, file, line);
325
326 if (num == 0) {
327 CRYPTO_clear_free(str, old_len, file, line);
328 return NULL;
329 }
330
331 /* Can't shrink the buffer since memcpy below copies |old_len| bytes. */
332 if (num < old_len) {
333 OPENSSL_cleanse((char*)str + num, old_len - num);
334 return str;
335 }
336
337 ret = CRYPTO_malloc(num, file, line);
338 if (ret != NULL) {
339 memcpy(ret, str, old_len);
340 CRYPTO_clear_free(str, old_len, file, line);
341 }
342 return ret;
343 }
344
CRYPTO_free(void * str,const char * file,int line)345 void CRYPTO_free(void *str, const char *file, int line)
346 {
347 INCREMENT(free_count);
348 if (free_impl != CRYPTO_free) {
349 free_impl(str, file, line);
350 return;
351 }
352
353 free(str);
354 }
355
CRYPTO_clear_free(void * str,size_t num,const char * file,int line)356 void CRYPTO_clear_free(void *str, size_t num, const char *file, int line)
357 {
358 if (str == NULL)
359 return;
360 if (num)
361 OPENSSL_cleanse(str, num);
362 CRYPTO_free(str, file, line);
363 }
364
365 #if !defined(OPENSSL_NO_CRYPTO_MDEBUG)
366
367 # ifndef OPENSSL_NO_DEPRECATED_3_0
CRYPTO_mem_ctrl(int mode)368 int CRYPTO_mem_ctrl(int mode)
369 {
370 (void)mode;
371 return -1;
372 }
373
CRYPTO_set_mem_debug(int flag)374 int CRYPTO_set_mem_debug(int flag)
375 {
376 (void)flag;
377 return -1;
378 }
379
CRYPTO_mem_debug_push(const char * info,const char * file,int line)380 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
381 {
382 (void)info; (void)file; (void)line;
383 return 0;
384 }
385
CRYPTO_mem_debug_pop(void)386 int CRYPTO_mem_debug_pop(void)
387 {
388 return 0;
389 }
390
CRYPTO_mem_debug_malloc(void * addr,size_t num,int flag,const char * file,int line)391 void CRYPTO_mem_debug_malloc(void *addr, size_t num, int flag,
392 const char *file, int line)
393 {
394 (void)addr; (void)num; (void)flag; (void)file; (void)line;
395 }
396
CRYPTO_mem_debug_realloc(void * addr1,void * addr2,size_t num,int flag,const char * file,int line)397 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num, int flag,
398 const char *file, int line)
399 {
400 (void)addr1; (void)addr2; (void)num; (void)flag; (void)file; (void)line;
401 }
402
CRYPTO_mem_debug_free(void * addr,int flag,const char * file,int line)403 void CRYPTO_mem_debug_free(void *addr, int flag,
404 const char *file, int line)
405 {
406 (void)addr; (void)flag; (void)file; (void)line;
407 }
408
CRYPTO_mem_leaks(BIO * b)409 int CRYPTO_mem_leaks(BIO *b)
410 {
411 (void)b;
412 return -1;
413 }
414
415 # ifndef OPENSSL_NO_STDIO
CRYPTO_mem_leaks_fp(FILE * fp)416 int CRYPTO_mem_leaks_fp(FILE *fp)
417 {
418 (void)fp;
419 return -1;
420 }
421 # endif
422
CRYPTO_mem_leaks_cb(int (* cb)(const char * str,size_t len,void * u),void * u)423 int CRYPTO_mem_leaks_cb(int (*cb)(const char *str, size_t len, void *u),
424 void *u)
425 {
426 (void)cb; (void)u;
427 return -1;
428 }
429
430 # endif
431
432 #endif
433