ntex_tls/openssl/alloc.rs
1//! Optional process-wide bridge from OpenSSL's allocation hooks to Rust's allocator.
2
3/// Routes OpenSSL memory allocations to the Rust global allocator.
4///
5/// OpenSSL allocates with the C runtime `malloc` by default. After this call
6/// it allocates through [`std::alloc`], so an application that registers
7/// a `#[global_allocator]` (for example mimalloc) uses it for TLS buffers
8/// and handshake state as well.
9///
10/// The setting is process wide and OpenSSL accepts it only before its first
11/// allocation, call this at the start of `main` before any other OpenSSL use.
12/// Returns `false` if OpenSSL has already allocated memory, another component
13/// has installed OpenSSL memory hooks, or the linked library does not support
14/// custom allocators (OpenSSL older than 1.1.0, `LibreSSL`, `BoringSSL`,
15/// `aws-lc`). A failed call leaves the existing allocator unchanged.
16///
17/// Returns `true` when the hooks were installed, or were already installed by
18/// an earlier call. This affects all OpenSSL users in the process, not just
19/// connections created by this crate.
20///
21/// # Safety
22///
23/// OpenSSL keeps its allocator hooks in unsynchronized globals. No other
24/// thread may use OpenSSL or replace its memory hooks while this function
25/// runs, and no other component may replace the hooks afterwards, otherwise
26/// a block may be released by an allocator that did not allocate it.
27///
28/// OpenSSL 3.5 and later on Unix allocate aligned blocks without closing the
29/// window for replacing the hooks. Such a block must not be live unless
30/// OpenSSL has also made a regular allocation, otherwise it would be released
31/// through these hooks. Library initialization makes regular allocations,
32/// calling this before any other OpenSSL use excludes the case.
33pub unsafe fn use_global_allocator() -> bool {
34 #[cfg(ntex_openssl_mem)]
35 {
36 // SAFETY: the caller upholds the same contract.
37 unsafe { shim::install() }
38 }
39 #[cfg(not(ntex_openssl_mem))]
40 {
41 false
42 }
43}
44
45#[cfg(ntex_openssl_mem)]
46mod shim {
47 //! C allocation callbacks with an aligned size header for Rust deallocation.
48 use std::alloc::{self, Layout};
49 use std::ffi::{c_char, c_int, c_void};
50 use std::ptr;
51
52 // Every block starts with a header that keeps the requested size, `free`
53 // has no size argument but `dealloc` needs the layout. 16 bytes keep the
54 // returned pointer aligned like `malloc` does (`max_align_t`).
55 /// Alignment of both the allocation base and the returned user pointer.
56 const ALIGN: usize = 16;
57 /// Prefix storing the requested size while preserving user-pointer alignment.
58 const HEADER: usize = 16;
59
60 /// OpenSSL allocation callback, including ignored source-location arguments.
61 type MallocFn = unsafe extern "C" fn(usize, *const c_char, c_int) -> *mut c_void;
62 /// OpenSSL reallocation callback.
63 type ReallocFn = unsafe extern "C" fn(*mut c_void, usize, *const c_char, c_int) -> *mut c_void;
64 /// OpenSSL deallocation callback.
65 type FreeFn = unsafe extern "C" fn(*mut c_void, *const c_char, c_int);
66
67 unsafe extern "C" {
68 /// Installs callbacks only while OpenSSL still permits allocator replacement.
69 fn CRYPTO_set_mem_functions(m: MallocFn, r: ReallocFn, f: FreeFn) -> c_int;
70 /// Reads the currently installed callbacks.
71 fn CRYPTO_get_mem_functions(
72 m: *mut Option<MallocFn>,
73 r: *mut Option<ReallocFn>,
74 f: *mut Option<FreeFn>,
75 );
76 /// OpenSSL's default allocation hook.
77 fn CRYPTO_malloc(size: usize, file: *const c_char, line: c_int) -> *mut c_void;
78 /// OpenSSL's default reallocation hook.
79 fn CRYPTO_realloc(
80 p: *mut c_void,
81 size: usize,
82 file: *const c_char,
83 line: c_int,
84 ) -> *mut c_void;
85 /// OpenSSL's default deallocation hook.
86 fn CRYPTO_free(p: *mut c_void, file: *const c_char, line: c_int);
87 }
88
89 /// Attempts to install this shim; failure leaves the existing hooks intact.
90 ///
91 /// OpenSSL stops accepting hooks after its default allocator first runs,
92 /// but a foreign custom allocator never closes that window. Installing
93 /// over one would make this shim free blocks that lack its size header,
94 /// so only OpenSSL's default hooks are replaced.
95 ///
96 /// # Safety
97 ///
98 /// See [`super::use_global_allocator`].
99 pub(super) unsafe fn install() -> bool {
100 let (mut m, mut r, mut f) = (None, None, None);
101 // SAFETY: the out pointers are locals, the caller excludes concurrent changes.
102 unsafe { CRYPTO_get_mem_functions(&raw mut m, &raw mut r, &raw mut f) };
103 let current = (
104 m.map(|m| m as usize),
105 r.map(|r| r as usize),
106 f.map(|f| f as usize),
107 );
108 let hooks = |m: MallocFn, r: ReallocFn, f: FreeFn| {
109 (Some(m as usize), Some(r as usize), Some(f as usize))
110 };
111 if current == hooks(malloc, realloc, free) {
112 true
113 } else if current == hooks(CRYPTO_malloc, CRYPTO_realloc, CRYPTO_free)
114 || current.0.and_then(dll_defaults) == Some(current)
115 {
116 // SAFETY: OpenSSL's default hooks are installed, so no live block was
117 // allocated by a foreign allocator that these hooks would free, and
118 // the caller excludes live aligned blocks from OpenSSL's allocator.
119 unsafe { CRYPTO_set_mem_functions(malloc, realloc, free) == 1 }
120 } else {
121 false
122 }
123 }
124
125 /// Default hooks exported by the DLL containing the `malloc` hook address.
126 ///
127 /// With a DLL OpenSSL our `CRYPTO_*` items are import thunks, while OpenSSL
128 /// reports its own addresses. Returns `None` if the address is not in a module.
129 #[cfg(windows)]
130 fn dll_defaults(malloc: usize) -> Option<(Option<usize>, Option<usize>, Option<usize>)> {
131 use windows_sys::Win32::System::LibraryLoader::{
132 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
133 GetModuleHandleExW, GetProcAddress,
134 };
135 let flags =
136 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;
137 let mut module = ptr::null_mut();
138 // SAFETY: with FROM_ADDRESS the name is an address, the reference count is unchanged.
139 if unsafe { GetModuleHandleExW(flags, malloc as *const u16, &raw mut module) } == 0 {
140 return None;
141 }
142 let export = |name: &std::ffi::CStr| {
143 // SAFETY: the module stays loaded, it provides the installed hooks.
144 unsafe { GetProcAddress(module, name.as_ptr().cast()) }.map(|f| f as usize)
145 };
146 Some((
147 export(c"CRYPTO_malloc"),
148 export(c"CRYPTO_realloc"),
149 export(c"CRYPTO_free"),
150 ))
151 }
152
153 /// Import thunks only exist on Windows.
154 #[cfg(not(windows))]
155 #[allow(clippy::unnecessary_wraps)]
156 fn dll_defaults(_: usize) -> Option<(Option<usize>, Option<usize>, Option<usize>)> {
157 None
158 }
159
160 /// Includes the aligned header, rejecting arithmetic overflow and invalid layouts.
161 fn layout(size: usize) -> Option<Layout> {
162 Layout::from_size_align(size.checked_add(HEADER)?, ALIGN).ok()
163 }
164
165 /// Recovers the allocation base and layout from a returned user pointer.
166 ///
167 /// # Safety
168 ///
169 /// `p` must be a non-null, live pointer returned by this shim's `malloc` or
170 /// `realloc`. Its preceding size header must remain intact.
171 #[allow(clippy::cast_ptr_alignment)] // blocks are ALIGN aligned
172 unsafe fn block(p: *mut c_void) -> (*mut u8, Layout) {
173 // SAFETY: `p` follows an aligned header written by `finish`, and
174 // `size + HEADER` was a valid layout when the block was allocated.
175 unsafe {
176 let base = p.cast::<u8>().sub(HEADER);
177 let size = base.cast::<usize>().read();
178 (
179 base,
180 Layout::from_size_align_unchecked(size + HEADER, ALIGN),
181 )
182 }
183 }
184
185 /// Stores the requested size and returns the user pointer, preserving null on failure.
186 ///
187 /// # Safety
188 ///
189 /// A non-null `base` must own an allocation with the layout returned by
190 /// `layout(size)`, and its header must be exclusively writable.
191 #[allow(clippy::cast_ptr_alignment)] // blocks are ALIGN aligned
192 unsafe fn finish(base: *mut u8, size: usize) -> *mut c_void {
193 if base.is_null() {
194 return ptr::null_mut();
195 }
196 // SAFETY: the allocation is `ALIGN` aligned and at least `HEADER` bytes long.
197 unsafe {
198 base.cast::<usize>().write(size);
199 base.add(HEADER).cast()
200 }
201 }
202
203 /// Allocates a block, returning null for zero size, overflow, or allocation failure.
204 ///
205 /// # Safety
206 ///
207 /// Returned storage must be released or resized only through this shim.
208 /// Source-location arguments are ignored and are not dereferenced.
209 pub(super) unsafe extern "C" fn malloc(size: usize, _: *const c_char, _: c_int) -> *mut c_void {
210 // OpenSSL's own malloc returns null for empty allocations
211 if size == 0 {
212 return ptr::null_mut();
213 }
214 match layout(size) {
215 // SAFETY: `layout` has a non-zero size, `finish` gets the block it describes.
216 Some(layout) => unsafe { finish(alloc::alloc(layout), size) },
217 None => ptr::null_mut(),
218 }
219 }
220
221 /// Resizes a block with C semantics, preserving the original allocation on failure.
222 ///
223 /// A null pointer acts as allocation; zero size frees a non-null pointer.
224 ///
225 /// # Safety
226 ///
227 /// A non-null `p` must be an exclusively owned live pointer from this shim
228 /// with an intact header. After success, only the returned pointer is valid.
229 pub(super) unsafe extern "C" fn realloc(
230 p: *mut c_void,
231 size: usize,
232 file: *const c_char,
233 line: c_int,
234 ) -> *mut c_void {
235 // OpenSSL forwards these cases to a custom realloc unchanged
236 if p.is_null() {
237 // SAFETY: forwarded from the caller.
238 return unsafe { malloc(size, file, line) };
239 }
240 if size == 0 {
241 // SAFETY: the caller passes an owned block from this shim.
242 unsafe { free(p, file, line) };
243 return ptr::null_mut();
244 }
245 let Some(new) = layout(size) else {
246 return ptr::null_mut();
247 };
248 // SAFETY: the caller passes an owned block from this shim, `new.size()` is
249 // non-zero and valid for `ALIGN`.
250 unsafe {
251 let (base, old) = block(p);
252 // on failure the original block stays valid, as with C realloc
253 finish(alloc::realloc(base, old, new.size()), size)
254 }
255 }
256
257 /// Releases an allocation; a null pointer is a no-op.
258 ///
259 /// # Safety
260 ///
261 /// A non-null `p` must be an exclusively owned live pointer from this shim
262 /// with an intact header, and must not be used after this call.
263 pub(super) unsafe extern "C" fn free(p: *mut c_void, _: *const c_char, _: c_int) {
264 if !p.is_null() {
265 // SAFETY: the caller passes an owned block from this shim.
266 unsafe {
267 let (base, layout) = block(p);
268 alloc::dealloc(base, layout);
269 }
270 }
271 }
272
273 #[cfg(test)]
274 mod tests {
275 use super::*;
276
277 /// STATEMENT: The allocator shim preserves alignment, data, and C allocation semantics.
278 ///
279 /// HOW:
280 /// - Allocate, grow, and shrink a block, checking alignment and retained bytes.
281 /// - Check zero-size and overflowing requests, null-pointer operations, and that
282 /// a failed reallocation leaves the original bytes intact.
283 #[test]
284 fn malloc_realloc_free() {
285 let (file, line) = (ptr::null(), 0);
286 // SAFETY: each pointer comes from the shim and is used within its size.
287 unsafe {
288 assert!(malloc(0, file, line).is_null());
289 assert!(malloc(usize::MAX - 8, file, line).is_null());
290 free(ptr::null_mut(), file, line);
291
292 let p = malloc(3, file, line).cast::<u8>();
293 assert!(!p.is_null());
294 assert_eq!(p as usize % ALIGN, 0);
295 p.copy_from(b"abc".as_ptr(), 3);
296
297 // grow keeps the data
298 let p = realloc(p.cast(), 64 * 1024, file, line).cast::<u8>();
299 assert_eq!(p as usize % ALIGN, 0);
300 assert_eq!(std::slice::from_raw_parts(p, 3), b"abc");
301 p.add(64 * 1024 - 1).write(1);
302
303 // shrink keeps the prefix
304 let p = realloc(p.cast(), 2, file, line).cast::<u8>();
305 assert_eq!(std::slice::from_raw_parts(p, 2), b"ab");
306
307 // too large fails and keeps the block
308 assert!(realloc(p.cast(), usize::MAX - 8, file, line).is_null());
309 assert_eq!(std::slice::from_raw_parts(p, 2), b"ab");
310
311 // zero size frees
312 assert!(realloc(p.cast(), 0, file, line).is_null());
313
314 // null acts as malloc
315 let p = realloc(ptr::null_mut(), 5, file, line);
316 assert!(!p.is_null());
317 free(p, file, line);
318 }
319 }
320 }
321}
322
323#[cfg(test)]
324mod tests {
325 use tls_openssl::ssl::{SslConnector, SslMethod};
326
327 /// STATEMENT: Allocator replacement is rejected after OpenSSL has allocated memory.
328 ///
329 /// HOW:
330 /// - Construct and drop an `SslConnector` builder.
331 /// - Confirm `use_global_allocator` returns `false`.
332 #[test]
333 fn rejected_after_openssl_allocated() {
334 drop(SslConnector::builder(SslMethod::tls()).unwrap());
335 // SAFETY: no other thread replaces the OpenSSL hooks during the test.
336 assert!(!unsafe { super::use_global_allocator() });
337 }
338}