1 /*
2  * Common and shared functions used by multiple modules in the Mbed TLS
3  * library.
4  *
5  *  Copyright The Mbed TLS Contributors
6  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
7  */
8 
9 /*
10  * Ensure gmtime_r is available even with -std=c99; must be defined before
11  * mbedtls_config.h, which pulls in glibc's features.h. Harmless on other platforms
12  * except OpenBSD, where it stops us accessing explicit_bzero.
13  */
14 #if !defined(_POSIX_C_SOURCE) && !defined(__OpenBSD__)
15 #define _POSIX_C_SOURCE 200112L
16 #endif
17 
18 #if !defined(_GNU_SOURCE)
19 /* Clang requires this to get support for explicit_bzero */
20 #define _GNU_SOURCE
21 #endif
22 
23 #include "common.h"
24 
25 #include "mbedtls/platform_util.h"
26 #include "mbedtls/platform.h"
27 #include "mbedtls/threading.h"
28 
29 #include <stddef.h>
30 #include "securec.h"
31 
32 #ifndef __STDC_WANT_LIB_EXT1__
33 #define __STDC_WANT_LIB_EXT1__ 1 /* Ask for the C11 gmtime_s() and memset_s() if available */
34 #endif
35 #include <string.h>
36 
37 #if defined(_WIN32)
38 #include <windows.h>
39 #endif
40 
41 // Detect platforms known to support explicit_bzero()
42 #if defined(__GLIBC__) && (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 25)
43 #define MBEDTLS_PLATFORM_HAS_EXPLICIT_BZERO 1
44 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 1100037)) || defined(__OpenBSD__)
45 #define MBEDTLS_PLATFORM_HAS_EXPLICIT_BZERO 1
46 #endif
47 
48 #if !defined(MBEDTLS_PLATFORM_ZEROIZE_ALT)
49 
50 #undef HAVE_MEMORY_SANITIZER
51 #if defined(__has_feature)
52 #if __has_feature(memory_sanitizer)
53 #include <sanitizer/msan_interface.h>
54 #define HAVE_MEMORY_SANITIZER
55 #endif
56 #endif
57 
58 /*
59  * Where possible, we try to detect the presence of a platform-provided
60  * secure memset, such as explicit_bzero(), that is safe against being optimized
61  * out, and use that.
62  *
63  * For other platforms, we provide an implementation that aims not to be
64  * optimized out by the compiler.
65  *
66  * This implementation for mbedtls_platform_zeroize() was inspired from Colin
67  * Percival's blog article at:
68  *
69  * http://www.daemonology.net/blog/2014-09-04-how-to-zero-a-buffer.html
70  *
71  * It uses a volatile function pointer to the standard memset(). Because the
72  * pointer is volatile the compiler expects it to change at
73  * any time and will not optimize out the call that could potentially perform
74  * other operations on the input buffer instead of just setting it to 0.
75  * Nevertheless, as pointed out by davidtgoldblatt on Hacker News
76  * (refer to http://www.daemonology.net/blog/2014-09-05-erratum.html for
77  * details), optimizations of the following form are still possible:
78  *
79  * if (memset_func != memset)
80  *     memset_func(buf, 0, len);
81  *
82  * Note that it is extremely difficult to guarantee that
83  * the memset() call will not be optimized out by aggressive compilers
84  * in a portable way. For this reason, Mbed TLS also provides the configuration
85  * option MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure
86  * mbedtls_platform_zeroize() to use a suitable implementation for their
87  * platform and needs.
88  */
89 #if !defined(MBEDTLS_PLATFORM_HAS_EXPLICIT_BZERO) && !(defined(__STDC_LIB_EXT1__) && \
90     !defined(__IAR_SYSTEMS_ICC__)) \
91     && !defined(_WIN32)
92 static void *(*const volatile memset_func)(void *, int, size_t) = memset;
93 #endif
94 
mbedtls_platform_zeroize(void *buf, size_t len)95 void mbedtls_platform_zeroize(void *buf, size_t len)
96 {
97     if (len > 0) {
98 #if defined(MBEDTLS_PLATFORM_HAS_EXPLICIT_BZERO)
99         explicit_bzero(buf, len);
100 #if defined(HAVE_MEMORY_SANITIZER)
101         /* You'd think that Msan would recognize explicit_bzero() as
102          * equivalent to bzero(), but it actually doesn't on several
103          * platforms, including Linux (Ubuntu 20.04).
104          * https://github.com/google/sanitizers/issues/1507
105          * https://github.com/openssh/openssh-portable/commit/74433a19bb6f4cef607680fa4d1d7d81ca3826aa
106          */
107         __msan_unpoison(buf, len);
108 #endif
109 #elif defined(__STDC_LIB_EXT1__) && !defined(__IAR_SYSTEMS_ICC__)
110         memset_s(buf, len, 0, len);
111 #elif defined(_WIN32)
112         SecureZeroMemory(buf, len);
113 #else
114         memset_func(buf, 0, len);
115 #endif
116 
117 #if defined(__GNUC__)
118         /* For clang and recent gcc, pretend that we have some assembly that reads the
119          * zero'd memory as an additional protection against being optimised away. */
120 #if defined(__clang__) || (__GNUC__ >= 10)
121 #if defined(__clang__)
122 #pragma clang diagnostic push
123 #pragma clang diagnostic ignored "-Wvla"
124 #elif defined(MBEDTLS_COMPILER_IS_GCC)
125 #pragma GCC diagnostic push
126 #pragma GCC diagnostic ignored "-Wvla"
127 #endif
128         asm volatile ("" : : "m" (*(char (*)[len]) buf) :);
129 #if defined(__clang__)
130 #pragma clang diagnostic pop
131 #elif defined(MBEDTLS_COMPILER_IS_GCC)
132 #pragma GCC diagnostic pop
133 #endif
134 #endif
135 #endif
136     }
137 }
138 #endif /* MBEDTLS_PLATFORM_ZEROIZE_ALT */
139 
mbedtls_zeroize_and_free(void *buf, size_t len)140 void mbedtls_zeroize_and_free(void *buf, size_t len)
141 {
142     if (buf != NULL) {
143         mbedtls_platform_zeroize(buf, len);
144     }
145 
146     mbedtls_free(buf);
147 }
148 
149 #if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_PLATFORM_GMTIME_R_ALT)
150 #include <time.h>
151 #if !defined(_WIN32) && (defined(unix) || \
152     defined(__unix) || defined(__unix__) || (defined(__APPLE__) && \
153     defined(__MACH__)) || defined__midipix__)
154 #include <unistd.h>
155 #endif /* !_WIN32 && (unix || __unix || __unix__ ||
156         * (__APPLE__ && __MACH__) || __midipix__) */
157 
158 #if !((defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L) ||     \
159     (defined(_POSIX_THREAD_SAFE_FUNCTIONS) &&                     \
160     _POSIX_THREAD_SAFE_FUNCTIONS >= 200112L))
161 /*
162  * This is a convenience shorthand macro to avoid checking the long
163  * preprocessor conditions above. Ideally, we could expose this macro in
164  * platform_util.h and simply use it in platform_util.c, threading.c and
165  * threading.h. However, this macro is not part of the Mbed TLS public API, so
166  * we keep it private by only defining it in this file
167  */
168 #if !(defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)) || \
169     (defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR))
170 #define PLATFORM_UTIL_USE_GMTIME
171 #endif
172 
173 #endif /* !( ( defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L ) || \
174              ( defined(_POSIX_THREAD_SAFE_FUNCTIONS ) && \
175                 _POSIX_THREAD_SAFE_FUNCTIONS >= 200112L ) ) */
176 
mbedtls_platform_gmtime_r(const mbedtls_time_t *tt, struct tm *tm_buf)177 struct tm *mbedtls_platform_gmtime_r(const mbedtls_time_t *tt,
178                                      struct tm *tm_buf)
179 {
180 #if defined(_WIN32) && !defined(PLATFORM_UTIL_USE_GMTIME)
181 #if defined(__STDC_LIB_EXT1__)
182     return (gmtime_s(tt, tm_buf) == 0) ? NULL : tm_buf;
183 #else
184     /* MSVC and mingw64 argument order and return value are inconsistent with the C11 standard */
185     return (gmtime_s(tm_buf, tt) == 0) ? tm_buf : NULL;
186 #endif
187 #elif !defined(PLATFORM_UTIL_USE_GMTIME)
188     return gmtime_r(tt, tm_buf);
189 #else
190     struct tm *lt;
191 
192 #if defined(MBEDTLS_THREADING_C)
193     if (mbedtls_mutex_lock(&mbedtls_threading_gmtime_mutex) != 0) {
194         return NULL;
195     }
196 #endif /* MBEDTLS_THREADING_C */
197 
198     lt = gmtime(tt);
199 
200     if (lt != NULL) {
201         memcpy(tm_buf, lt, sizeof(struct tm));
202     }
203 
204 #if defined(MBEDTLS_THREADING_C)
205     if (mbedtls_mutex_unlock(&mbedtls_threading_gmtime_mutex) != 0) {
206         return NULL;
207     }
208 #endif /* MBEDTLS_THREADING_C */
209 
210     return (lt == NULL) ? NULL : tm_buf;
211 #endif /* _WIN32 && !EFIX64 && !EFI32 */
212 }
213 #endif /* MBEDTLS_HAVE_TIME_DATE && MBEDTLS_PLATFORM_GMTIME_R_ALT */
214 
215 #if defined(MBEDTLS_TEST_HOOKS)
216 void (*mbedtls_test_hook_test_fail)(const char *, int, const char *);
217 #endif /* MBEDTLS_TEST_HOOKS */
218 
219 #if defined(MBEDTLS_HAVE_TIME) && !defined(MBEDTLS_PLATFORM_MS_TIME_ALT)
220 
221 #include <time.h>
222 #if !defined(_WIN32) && \
223     (defined(unix) || defined(__unix) || defined(__unix__) || \
224     (defined(__APPLE__) && defined(__MACH__)) || defined(__HAIKU__) || defined(__midipix__))
225 #include <unistd.h>
226 #endif \
227     /* !_WIN32 && (unix || __unix || __unix__ || (__APPLE__ && __MACH__) || __HAIKU__ || __midipix__) */
228 #if (defined(_POSIX_VERSION) && _POSIX_VERSION >= 199309L) || defined(__HAIKU__) || defined(__unix__)
mbedtls_ms_time(void)229 mbedtls_ms_time_t mbedtls_ms_time(void)
230 {
231     int ret;
232     struct timespec tv;
233     mbedtls_ms_time_t current_ms;
234 
235 #if defined(__linux__) && defined(CLOCK_BOOTTIME) || defined(__midipix__)
236     ret = clock_gettime(CLOCK_BOOTTIME, &tv);
237 #else
238     ret = clock_gettime(CLOCK_MONOTONIC, &tv);
239 #endif
240     if (ret) {
241         return time(NULL) * 1000;
242     }
243 
244     current_ms = tv.tv_sec;
245 
246     return current_ms*1000 + tv.tv_nsec / 1000000;
247 }
248 #elif defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
249     defined(__MINGW32__) || defined(_WIN64)
250 #include <windows.h>
mbedtls_ms_time(void)251 mbedtls_ms_time_t mbedtls_ms_time(void)
252 {
253     FILETIME ct;
254     mbedtls_ms_time_t current_ms;
255 
256     GetSystemTimeAsFileTime(&ct);
257     current_ms = ((mbedtls_ms_time_t) ct.dwLowDateTime +
258                   ((mbedtls_ms_time_t) (ct.dwHighDateTime) << 32LL))/10000;
259     return current_ms;
260 }
261 #else
262 #error "No mbedtls_ms_time available"
263 #endif
264 #endif /* MBEDTLS_HAVE_TIME && !MBEDTLS_PLATFORM_MS_TIME_ALT */
265