VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/posix/SUPR3HardenedMain-posix.cpp

Last change on this file was 109060, checked in by vboxsync, 4 weeks ago

SUPHardPosix: Comment about the dlerror problem from bugref:10892 / ticketref:22193.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 27.1 KB
Line 
1/* $Id: SUPR3HardenedMain-posix.cpp 109060 2025-04-23 11:46:53Z vboxsync $ */
2/** @file
3 * VirtualBox Support Library - Hardened main(), posix bits.
4 */
5
6/*
7 * Copyright (C) 2017-2024 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.215389.xyz.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
27 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
28 * in the VirtualBox distribution, in which case the provisions of the
29 * CDDL are applicable instead of those of the GPL.
30 *
31 * You may elect to license modified versions of this file under the
32 * terms and conditions of either the GPL or the CDDL or both.
33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#include <VBox/err.h>
42#include <VBox/dis.h>
43#include <VBox/sup.h>
44
45#include <iprt/path.h>
46#include <iprt/string.h>
47#include <iprt/x86.h>
48
49#include <dlfcn.h>
50#include <sys/mman.h>
51#if defined(RT_OS_SOLARIS)
52# include <link.h>
53#endif
54#include <stdio.h>
55#include <stdint.h>
56
57#include "SUPLibInternal.h"
58
59
60/*********************************************************************************************************************************
61* Defined Constants And Macros *
62*********************************************************************************************************************************/
63
64/**
65 * Memory for code patching.
66 */
67#define DLOPEN_PATCH_MEMORY_SIZE _4K
68
69
70/*********************************************************************************************************************************
71* Structures and Typedefs *
72*********************************************************************************************************************************/
73#ifndef SUP_HARDENED_WITHOUT_DLOPEN_PATCHING
74/**
75 * Callback (SUPHARDENEDPOSIXHOOK::pfnResolv) for triggering lazy GOT resolver.
76 *
77 * This generally just calls the API in a harmless manner and triggers the lazy
78 * resolving of the symbol, ensuring a proper address in the GOT/PLT entry.
79 *
80 * On Solaris dlsym() will return the value in the GOT/PLT entry. We don't wish
81 * to patch the lazy loader trampoline function, but rather the real function!
82 */
83typedef DECLCALLBACKTYPE(void, FNSUPHARDENEDSYMRESOLVE,(void));
84/** Pointer to FNSUPHARDENEDSYMRESOLVE. */
85typedef FNSUPHARDENEDSYMRESOLVE *PFNSUPHARDENEDSYMRESOLVE;
86
87/**
88 * A hook descriptor.
89 */
90typedef struct SUPHARDENEDPOSIXHOOK
91{
92 /** The symbol to hook. */
93 const char *pszSymbol;
94 /** The intercepting wrapper doing additional checks. */
95 PFNRT pfnHook;
96 /** Where to store the pointer to the code into patch memory
97 * which resumes the original call.
98 * @note uintptr_t instead of PFNRT is for Clang 11. */
99 uintptr_t *ppfnRealResume;
100 /** Pointer to the resolver method used on Solaris. */
101 PFNSUPHARDENEDSYMRESOLVE pfnResolve;
102} SUPHARDENEDPOSIXHOOK;
103/** Pointer to a hook descriptor. */
104typedef SUPHARDENEDPOSIXHOOK *PSUPHARDENEDPOSIXHOOK;
105/** Pointer to a const hook descriptor. */
106typedef const SUPHARDENEDPOSIXHOOK *PCSUPHARDENEDPOSIXHOOK;
107
108/** dlopen() declaration. */
109typedef void *FNDLOPEN(const char *pszFilename, int fFlags);
110/** Pointer to dlopen. */
111typedef FNDLOPEN *PFNDLOPEN;
112
113#ifdef SUP_HARDENED_WITH_DLMOPEN
114/** dlmopen() declaration */
115typedef void *FNDLMOPEN(Lmid_t idLm, const char *pszFilename, int fFlags);
116/** Pointer to dlmopen. */
117typedef FNDLMOPEN *PFNDLMOPEN;
118#endif
119
120#endif /* SUP_HARDENED_WITHOUT_DLOPEN_PATCHING */
121
122
123/*********************************************************************************************************************************
124* Internal Functions *
125*********************************************************************************************************************************/
126#ifndef SUP_HARDENED_WITHOUT_DLOPEN_PATCHING
127static FNSUPHARDENEDSYMRESOLVE supR3HardenedPosixMonitorDlopenResolve;
128#ifdef SUP_HARDENED_WITH_DLMOPEN
129static FNSUPHARDENEDSYMRESOLVE supR3HardenedPosixMonitorDlmopenResolve;
130#endif
131
132/* SUPR3HardenedMainA-posix.asm: */
133DECLASM(void) supR3HardenedPosixMonitor_Dlopen(const char *pszFilename, int fFlags);
134#ifdef SUP_HARDENED_WITH_DLMOPEN
135DECLASM(void) supR3HardenedPosixMonitor_Dlmopen(Lmid_t idLm, const char *pszFilename, int fFlags);
136#endif
137#endif /* SUP_HARDENED_WITHOUT_DLOPEN_PATCHING */
138
139
140/*********************************************************************************************************************************
141* Global Variables *
142*********************************************************************************************************************************/
143#ifndef SUP_HARDENED_WITHOUT_DLOPEN_PATCHING
144
145RT_C_DECLS_BEGIN
146/** Resume patch for dlopen(), jumped to form assembly stub. */
147DECL_HIDDEN_DATA(PFNDLOPEN) g_pfnDlopenReal = NULL;
148#ifdef SUP_HARDENED_WITH_DLMOPEN
149/** Resume patch for dlmopen(), jumped to form assembly stub. */
150DECL_HIDDEN_DATA(PFNDLMOPEN) g_pfnDlmopenReal = NULL;
151#endif
152RT_C_DECLS_END
153
154/** Memory allocated for the patches. */
155static uint8_t *g_pbExecMemory = NULL;
156/** Offset into the patch memory which is not used. */
157static uint32_t g_offExecMemory = 0;
158
159/**
160 * Array of hooks to install.
161 */
162static SUPHARDENEDPOSIXHOOK const g_aHooks[] =
163{
164 /* pszSymbol, pfnHook, ppfnRealResume, pfnResolve */
165 { "dlopen", (PFNRT)supR3HardenedPosixMonitor_Dlopen, (uintptr_t *)&g_pfnDlopenReal, supR3HardenedPosixMonitorDlopenResolve },
166#ifdef SUP_HARDENED_WITH_DLMOPEN
167 { "dlmopen", (PFNRT)supR3HardenedPosixMonitor_Dlmopen, (uintptr_t *)&g_pfnDlmopenReal, supR3HardenedPosixMonitorDlmopenResolve }
168#endif
169};
170
171
172
173/**
174 * Verifies the given library for proper access rights for further loading
175 * into the process.
176 *
177 * @returns Flag whether the access rights of the library look sane and loading
178 * it is not considered a security risk. Returns true if the library
179 * looks sane, false otherwise.
180 * @param pszFilename The library to load, this can be an absolute or relative path
181 * or just the filename of the library when the default paths should
182 * be searched. NULL is allowed too to indicate opening the main
183 * binary.
184 *
185 * @todo When this is used by dlopen and dlmopen intercepts, it doesn't set
186 * dlerror which can be confusing to the caller and lead to crashes.
187 * However, since we don't have access to the libdl internals, there is
188 * little we can do about it here without intercepting dlerror calls as
189 * well, allocating a TLS variable, and all that ... For now IPRT just
190 * has to be careful. See @bugref{10892}.
191 */
192DECLASM(bool) supR3HardenedPosixMonitor_VerifyLibrary(const char *pszFilename)
193{
194 /*
195 * Giving NULL as the filename indicates opening the main program which is fine
196 * We are already loaded and executing after all.
197 *
198 * Filenames without any path component (whether absolute or relative) are allowed
199 * unconditionally too as the loader will only search the default paths configured by root.
200 */
201 bool fAllow = true;
202
203 if ( pszFilename
204 && strchr(pszFilename, '/') != NULL)
205 {
206#if defined(RT_OS_LINUX)
207 int rc = supR3HardenedVerifyFileFollowSymlinks(pszFilename, RTHCUINTPTR_MAX, true /* fMaybe3rdParty */,
208 NULL /* pErrInfo */);
209#else
210 int rc = supR3HardenedVerifyFile(pszFilename, RTHCUINTPTR_MAX, true /* fMaybe3rdParty */,
211 NULL /* pErrInfo */);
212#endif
213
214 if (RT_FAILURE(rc))
215 fAllow = false;
216 }
217
218 return fAllow;
219}
220
221
222/**
223 * Returns the start address of the given symbol if found or NULL otherwise.
224 *
225 * @returns Start address of the symbol or NULL if not found.
226 * @param pszSymbol The symbol name.
227 * @param pfnResolve The resolver to call before trying to query the start address.
228 */
229static void *supR3HardenedMainPosixGetStartBySymbol(const char *pszSymbol, PFNSUPHARDENEDSYMRESOLVE pfnResolve)
230{
231#ifndef RT_OS_SOLARIS
232 RT_NOREF(pfnResolve);
233 return dlsym(RTLD_DEFAULT, pszSymbol);
234
235#else /* RT_OS_SOLARIS */
236 /*
237 * Solaris is tricky as dlsym doesn't return the actual start address of
238 * the symbol but the start of the trampoline in the PLT of the caller.
239 *
240 * Disassemble the first jmp instruction to get at the entry in the global
241 * offset table where the actual address is stored.
242 *
243 * To counter lazy symbol resolving, we first have to call the API before
244 * trying to resolve and disassemble it.
245 */
246 pfnResolve();
247
248 uint8_t *pbSym = (uint8_t *)dlsym(RTLD_DEFAULT, pszSymbol);
249
250# ifdef RT_ARCH_AMD64
251 DISSTATE Dis;
252 uint32_t cbInstr = 1;
253 int rc = DISInstr(pbSym, DISCPUMODE_64BIT, &Dis, &cbInstr);
254 if ( RT_FAILURE(rc)
255 || Dis.pCurInstr->uOpcode != OP_JMP
256 || !(Dis.x86.ModRM.Bits.Mod == 0 && Dis.x86.ModRM.Bits.Rm == 5 /* wrt RIP */))
257 return NULL;
258
259 /* Extract start address. */
260 pbSym = (pbSym + cbInstr + Dis.aParams[0].x86.uDisp.i32);
261 pbSym = (uint8_t *)*((uintptr_t *)pbSym);
262# else
263# error "Unsupported architecture"
264# endif
265
266 return pbSym;
267#endif /* RT_OS_SOLARIS */
268}
269
270
271/**
272 * Allocates executable patch memory with the given constraints.
273 *
274 * @returns VBox status code.
275 * @param cb Size of the patch memory in bytes.
276 * @param pvHint Where to try allocating nearby.
277 * @param fRipRelAddr Flag whether the executable memory must be within
278 * 2GB before or after the hint as it will contain
279 * instructions using RIP relative addressing
280 */
281static uint8_t *supR3HardenedMainPosixExecMemAlloc(size_t cb, void *pvHint, bool fRipRelAddr)
282{
283 AssertReturn(cb < _1K, NULL);
284
285 /* Lazy allocation of exectuable memory. */
286 if (!g_pbExecMemory)
287 {
288 g_pbExecMemory = (uint8_t *)mmap(pvHint, DLOPEN_PATCH_MEMORY_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC,
289 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
290 g_offExecMemory = 0;
291 if (g_pbExecMemory == MAP_FAILED)
292 return NULL;
293
294 memset(g_pbExecMemory, 0xcc, DLOPEN_PATCH_MEMORY_SIZE);
295 }
296
297 if (g_offExecMemory + cb >= DLOPEN_PATCH_MEMORY_SIZE)
298 return NULL;
299
300 uint8_t *pb = &g_pbExecMemory[g_offExecMemory];
301
302 if (fRipRelAddr)
303 {
304 /* Check that we allocated within 2GB of the hint. */
305 uintptr_t uPtrHint = (uintptr_t)pvHint;
306 uintptr_t uPtrPatchMem = (uintptr_t)pb;
307 uintptr_t cbDistance = uPtrHint < uPtrPatchMem
308 ? uPtrPatchMem - uPtrHint
309 : uPtrHint - uPtrPatchMem;
310
311 if (cbDistance >= _2G - _4K)
312 return NULL;
313 }
314
315 g_offExecMemory = RT_ALIGN_32(g_offExecMemory + cb, 16);
316 return pb;
317}
318
319
320/**
321 * Hooks the given method to execute the given one first.
322 *
323 * @returns VBox status code.
324 * @param pszSymbol The symbol to hook.
325 * @param pfnHook The hook to install.
326 * @param ppfnReal Where to store the pointer to entry point of the real method
327 * (somewhere in patch memory).
328 * @param pfnResolve The resolver to call before trying to query the start address.
329 */
330static int supR3HardenedMainPosixHookOne(const char *pszSymbol, PFNRT pfnHook, uintptr_t /*PFNRT*/ *ppfnReal,
331 PFNSUPHARDENEDSYMRESOLVE pfnResolve)
332{
333 void *pfnTarget = supR3HardenedMainPosixGetStartBySymbol(pszSymbol, pfnResolve);
334 if (!pfnTarget)
335 return VERR_NOT_FOUND;
336
337 /*
338 * Make the target memory writeable to be able to insert the patch.
339 * Unprotect two pages in case the code crosses a page boundary.
340 */
341 void *pvTargetBase = (void *)(((uintptr_t)pfnTarget) & ~(uintptr_t)(_4K - 1));
342 int rcPsx = mprotect(pvTargetBase, 2 * _4K, PROT_WRITE | PROT_READ | PROT_EXEC);
343 if (rcPsx == -1)
344 return VERR_SUPLIB_TEXT_NOT_WRITEABLE;
345
346 uint8_t * const pbTarget = (uint8_t *)(uintptr_t)pfnTarget;
347
348 DISSTATE Dis;
349 uint32_t cbInstr;
350 uint32_t offJmpBack = 0;
351 uint32_t cbPatchMem = 0;
352
353#ifdef RT_ARCH_AMD64
354 /*
355 * Patch 64-bit hosts.
356 */
357 uint32_t cRipRelMovs = 0;
358 uint32_t cRelCalls = 0;
359
360 /* Just use the disassembler to skip 12 bytes or more, we might need to
361 rewrite mov instructions using RIP relative addressing. */
362 while (offJmpBack < 12)
363 {
364 cbInstr = 1;
365 int rc = DISInstr(pbTarget + offJmpBack, DISCPUMODE_64BIT, &Dis, &cbInstr);
366 if ( RT_FAILURE(rc)
367 || ( Dis.pCurInstr->fOpType & DISOPTYPE_CONTROLFLOW
368 && Dis.pCurInstr->uOpcode != OP_CALL)
369 || ( Dis.x86.ModRM.Bits.Mod == 0
370 && Dis.x86.ModRM.Bits.Rm == 5 /* wrt RIP */
371 && Dis.pCurInstr->uOpcode != OP_MOV))
372 return VERR_SUPLIB_UNEXPECTED_INSTRUCTION;
373
374 if (Dis.x86.ModRM.Bits.Mod == 0 && Dis.x86.ModRM.Bits.Rm == 5 /* wrt RIP */)
375 cRipRelMovs++;
376 if ( Dis.pCurInstr->uOpcode == OP_CALL
377 && (Dis.pCurInstr->fOpType & DISOPTYPE_RELATIVE_CONTROLFLOW))
378 cRelCalls++;
379
380 offJmpBack += cbInstr;
381 cbPatchMem += cbInstr;
382 }
383
384 /*
385 * Each relative call requires extra bytes as it is converted to a pushq imm32
386 * + mov [RSP+4], imm32 + a jmp qword [$+8 wrt RIP] to avoid clobbering registers.
387 */
388 cbPatchMem += cRelCalls * RT_ALIGN_32(13 + 6 + 8, 8);
389 cbPatchMem += 14; /* jmp qword [$+8 wrt RIP] + 8 byte address to jump to. */
390 cbPatchMem = RT_ALIGN_32(cbPatchMem, 8);
391
392 /* Allocate suitable executable memory available. */
393 bool fConvRipRelMovs = false;
394 uint8_t *pbPatchMem = supR3HardenedMainPosixExecMemAlloc(cbPatchMem, pbTarget, cRipRelMovs > 0);
395 if (!pbPatchMem)
396 {
397 /*
398 * Try to allocate memory again without the RIP relative mov addressing constraint
399 * Makes it a bit more difficult for us later on but there is no way around it.
400 * We need to increase the patch memory because we create two instructions for one
401 * (7 bytes for the RIP relative mov vs. 13 bytes for the two instructions replacing it ->
402 * need to allocate 6 bytes more per RIP relative mov).
403 */
404 fConvRipRelMovs = true;
405 if (cRipRelMovs > 0)
406 pbPatchMem = supR3HardenedMainPosixExecMemAlloc(cbPatchMem + cRipRelMovs * 6,
407 pbTarget, false /*fRipRelAddr*/);
408
409 if (!pbPatchMem)
410 return VERR_NO_MEMORY;
411 }
412
413 /* Assemble the code for resuming the call.*/
414 *ppfnReal = (uintptr_t)pbPatchMem;
415
416 /* Go through the instructions to patch and fixup any rip relative mov instructions. */
417 uint32_t offInsn = 0;
418 while (offInsn < offJmpBack)
419 {
420 cbInstr = 1;
421 int rc = DISInstr(pbTarget + offInsn, DISCPUMODE_64BIT, &Dis, &cbInstr);
422 if ( RT_FAILURE(rc)
423 || ( Dis.pCurInstr->fOpType & DISOPTYPE_CONTROLFLOW
424 && Dis.pCurInstr->uOpcode != OP_CALL))
425 return VERR_SUPLIB_UNEXPECTED_INSTRUCTION;
426
427 if ( Dis.x86.ModRM.Bits.Mod == 0
428 && Dis.x86.ModRM.Bits.Rm == 5 /* wrt RIP */
429 && Dis.pCurInstr->uOpcode == OP_MOV)
430 {
431 /* Deduce destination register and write out new instruction. */
432 if (RT_UNLIKELY(!( (Dis.aParams[0].fUse & (DISUSE_BASE | DISUSE_REG_GEN64))
433 && (Dis.aParams[1].fUse & DISUSE_RIPDISPLACEMENT32))))
434 return VERR_SUPLIB_UNEXPECTED_INSTRUCTION;
435
436 uintptr_t uAddr = (uintptr_t)&pbTarget[offInsn + cbInstr] + (intptr_t)Dis.aParams[1].x86.uDisp.i32;
437
438 if (fConvRipRelMovs)
439 {
440 /*
441 * Create two instructions, first one moves the address as a constant to the destination register
442 * and the second one loads the data from the memory into the destination register.
443 */
444
445 *pbPatchMem++ = 0x48;
446 *pbPatchMem++ = 0xb8 + Dis.aParams[0].x86.Base.idxGenReg;
447 *(uintptr_t *)pbPatchMem = uAddr;
448 pbPatchMem += sizeof(uintptr_t);
449
450 *pbPatchMem++ = 0x48;
451 *pbPatchMem++ = 0x8b;
452 *pbPatchMem++ = (Dis.aParams[0].x86.Base.idxGenReg << X86_MODRM_REG_SHIFT) | Dis.aParams[0].x86.Base.idxGenReg;
453 }
454 else
455 {
456 intptr_t iDispNew = uAddr - (uintptr_t)&pbPatchMem[3 + sizeof(int32_t)];
457 Assert(iDispNew == (int32_t)iDispNew);
458
459 /* Assemble the mov to register instruction with the updated rip relative displacement. */
460 *pbPatchMem++ = 0x48;
461 *pbPatchMem++ = 0x8b;
462 *pbPatchMem++ = (Dis.aParams[0].x86.Base.idxGenReg << X86_MODRM_REG_SHIFT) | 5;
463 *(int32_t *)pbPatchMem = (int32_t)iDispNew;
464 pbPatchMem += sizeof(int32_t);
465 }
466 }
467 else if ( Dis.pCurInstr->uOpcode == OP_CALL
468 && (Dis.pCurInstr->fOpType & DISOPTYPE_RELATIVE_CONTROLFLOW))
469 {
470 /* Convert to absolute jump. */
471 uintptr_t uAddr = (uintptr_t)&pbTarget[offInsn + cbInstr] + (intptr_t)Dis.aParams[0].uValue;
472
473 /* Skip the push instructions till the return address is known. */
474 uint8_t *pbPatchMemPush = pbPatchMem;
475 pbPatchMem += 13;
476
477 *pbPatchMem++ = 0xff; /* jmp qword [$+8 wrt RIP] */
478 *pbPatchMem++ = 0x25;
479 *(uint32_t *)pbPatchMem = (uint32_t)(RT_ALIGN_PT(pbPatchMem + 4, 8, uint8_t *) - (pbPatchMem + 4));
480 pbPatchMem = RT_ALIGN_PT(pbPatchMem + 4, 8, uint8_t *);
481 *(uint64_t *)pbPatchMem = uAddr;
482 pbPatchMem += sizeof(uint64_t);
483
484 /* Push the return address onto stack. Difficult on amd64 without clobbering registers... */
485 uintptr_t uAddrReturn = (uintptr_t)pbPatchMem;
486 *pbPatchMemPush++ = 0x68; /* push imm32 sign-extended as 64-bit*/
487 *(uint32_t *)pbPatchMemPush = RT_LO_U32(uAddrReturn);
488 pbPatchMemPush += sizeof(uint32_t);
489 *pbPatchMemPush++ = 0xc7;
490 *pbPatchMemPush++ = 0x44;
491 *pbPatchMemPush++ = 0x24;
492 *pbPatchMemPush++ = 0x04; /* movl [RSP+4], imm32 */
493 *(uint32_t *)pbPatchMemPush = RT_HI_U32(uAddrReturn);
494 }
495 else
496 {
497 memcpy(pbPatchMem, pbTarget + offInsn, cbInstr);
498 pbPatchMem += cbInstr;
499 }
500
501 offInsn += cbInstr;
502 }
503
504 *pbPatchMem++ = 0xff; /* jmp qword [$+8 wrt RIP] */
505 *pbPatchMem++ = 0x25;
506 *(uint32_t *)pbPatchMem = (uint32_t)(RT_ALIGN_PT(pbPatchMem + 4, 8, uint8_t *) - (pbPatchMem + 4));
507 pbPatchMem = RT_ALIGN_PT(pbPatchMem + 4, 8, uint8_t *);
508 *(uint64_t *)pbPatchMem = (uintptr_t)&pbTarget[offJmpBack];
509
510 /* Assemble the patch. */
511 Assert(offJmpBack >= 12);
512 pbTarget[0] = 0x48; /* mov rax, qword */
513 pbTarget[1] = 0xb8;
514 *(uintptr_t *)&pbTarget[2] = (uintptr_t)pfnHook;
515 pbTarget[10] = 0xff; /* jmp rax */
516 pbTarget[11] = 0xe0;
517
518#else /* !RT_ARCH_AMD64 */
519 /*
520 * Patch 32-bit hosts.
521 */
522 /* Just use the disassembler to skip 5 bytes or more. */
523 while (offJmpBack < 5)
524 {
525 cbInstr = 1;
526 int rc = DISInstr(pbTarget + offJmpBack, DISCPUMODE_32BIT, &Dis, &cbInstr);
527 if ( RT_FAILURE(rc)
528 || ( (Dis.pCurInstr->fOpType & DISOPTYPE_CONTROLFLOW)
529 && Dis.pCurInstr->uOpcode != OP_CALL))
530 return VERR_SUPLIB_UNEXPECTED_INSTRUCTION;
531
532 if ( Dis.pCurInstr->uOpcode == OP_CALL
533 && (Dis.pCurInstr->fOpType & DISOPTYPE_RELATIVE_CONTROLFLOW))
534 cbPatchMem += 10; /* push imm32 + jmp rel32 */
535 else
536 cbPatchMem += cbInstr;
537
538 offJmpBack += cbInstr;
539 }
540
541 /* Allocate suitable exectuable memory available. */
542 uint8_t *pbPatchMem = supR3HardenedMainPosixExecMemAlloc(cbPatchMem, pbTarget, false /* fRipRelAddr */);
543 if (!pbPatchMem)
544 return VERR_NO_MEMORY;
545
546 /* Assemble the code for resuming the call.*/
547 *ppfnReal = (uintptr_t)pbPatchMem;
548
549 /* Go through the instructions to patch and fixup any relative call instructions. */
550 uint32_t offInsn = 0;
551 while (offInsn < offJmpBack)
552 {
553 cbInstr = 1;
554 int rc = DISInstr(pbTarget + offInsn, DISCPUMODE_32BIT, &Dis, &cbInstr);
555 if ( RT_FAILURE(rc)
556 || ( (Dis.pCurInstr->fOpType & DISOPTYPE_CONTROLFLOW)
557 && Dis.pCurInstr->uOpcode != OP_CALL))
558 return VERR_SUPLIB_UNEXPECTED_INSTRUCTION;
559
560 if ( Dis.pCurInstr->uOpcode == OP_CALL
561 && (Dis.pCurInstr->fOpType & DISOPTYPE_RELATIVE_CONTROLFLOW))
562 {
563 /*
564 * Don't use a call instruction directly but push the original return address
565 * onto the stack and use a relative jump to the call target.
566 * The reason here is that on Linux the called method saves the return
567 * address from the stack which will be different from the original because
568 * the code is executed from our patch memory.
569 *
570 * Luckily the call instruction is 5 bytes long which means it is always the
571 * last instruction to patch and we don't need to return from the call
572 * to patch memory anyway but can use this method to resume the original call.
573 */
574 AssertReturn(offInsn + cbInstr >= offJmpBack, VERR_SUPLIB_UNEXPECTED_INSTRUCTION); /* Must be last instruction! */
575
576 /* push return address */
577 uint32_t const uAddrReturn = (uintptr_t)&pbTarget[offInsn + cbInstr]; /* The return address to push to the stack. */
578
579 *pbPatchMem++ = 0x68; /* push dword */
580 *(uint32_t *)pbPatchMem = uAddrReturn;
581 pbPatchMem += sizeof(uint32_t);
582
583 /* jmp rel32 to the call target */
584 uintptr_t const uAddr = uAddrReturn + (int32_t)Dis.aParams[0].uValue;
585 int32_t const i32DispNew = uAddr - (uintptr_t)&pbPatchMem[5];
586
587 *pbPatchMem++ = 0xe9; /* jmp rel32 */
588 *(int32_t *)pbPatchMem = i32DispNew;
589 pbPatchMem += sizeof(int32_t);
590 }
591 else
592 {
593 memcpy(pbPatchMem, pbTarget + offInsn, cbInstr);
594 pbPatchMem += cbInstr;
595 }
596
597 offInsn += cbInstr;
598 }
599
600 *pbPatchMem++ = 0xe9; /* jmp rel32 */
601 *(uint32_t *)pbPatchMem = (uintptr_t)&pbTarget[offJmpBack] - ((uintptr_t)pbPatchMem + 4);
602
603 /* Assemble the patch. */
604 Assert(offJmpBack >= 5);
605 pbTarget[0] = 0xe9;
606 *(uint32_t *)&pbTarget[1] = (uintptr_t)pfnHook - (uintptr_t)&pbTarget[1+4];
607#endif /* !RT_ARCH_AMD64 */
608
609 /*
610 * Re-seal target (ASSUMING that the shared object either has page aligned
611 * section or that the patch target is far enough from the writable parts).
612 */
613 rcPsx = mprotect(pvTargetBase, 2 * _4K, PROT_READ | PROT_EXEC);
614 if (rcPsx == -1)
615 return VERR_SUPLIB_TEXT_NOT_SEALED;
616
617 return VINF_SUCCESS;
618}
619
620
621/**
622 * @callback_method_impl{FNSUPHARDENEDSYMRESOLVE, dlopen}
623 */
624static DECLCALLBACK(void) supR3HardenedPosixMonitorDlopenResolve(void)
625{
626 /* Make harmless dlopen call. */
627 void *pv = dlopen(NULL, RTLD_LAZY);
628 if (pv)
629 dlclose(pv);
630}
631
632
633#ifdef SUP_HARDENED_WITH_DLMOPEN
634/**
635 * @callback_method_impl{FNSUPHARDENEDSYMRESOLVE, dlmopen}
636 */
637static DECLCALLBACK(void) supR3HardenedPosixMonitorDlmopenResolve(void)
638{
639 /* Make harmless dlmopen call. */
640 void *pv = dlmopen(LM_ID_BASE, NULL, RTLD_LAZY);
641 if (pv)
642 dlclose(pv);
643}
644#endif
645
646#endif /* SUP_HARDENED_WITHOUT_DLOPEN_PATCHING */
647
648
649/**
650 * Hardening initialization for POSIX compatible hosts.
651 *
652 * @note Doesn't return on error.
653 */
654DECLHIDDEN(void) supR3HardenedPosixInit(void)
655{
656#ifndef SUP_HARDENED_WITHOUT_DLOPEN_PATCHING
657 for (unsigned i = 0; i < RT_ELEMENTS(g_aHooks); i++)
658 {
659 PCSUPHARDENEDPOSIXHOOK pHook = &g_aHooks[i];
660 int rc = supR3HardenedMainPosixHookOne(pHook->pszSymbol, pHook->pfnHook, pHook->ppfnRealResume, pHook->pfnResolve);
661 if (RT_FAILURE(rc))
662 supR3HardenedFatalMsg("supR3HardenedPosixInit", kSupInitOp_Integrity, rc,
663 "Failed to hook the %s interface", pHook->pszSymbol);
664 }
665#endif
666}
667
668
669
670/*
671 * assert.cpp
672 *
673 * ASSUMES working DECLHIDDEN or there will be symbol confusion!
674 */
675
676RTDATADECL(char) g_szRTAssertMsg1[1024];
677RTDATADECL(char) g_szRTAssertMsg2[4096];
678RTDATADECL(const char * volatile) g_pszRTAssertExpr;
679RTDATADECL(const char * volatile) g_pszRTAssertFile;
680RTDATADECL(uint32_t volatile) g_u32RTAssertLine;
681RTDATADECL(const char * volatile) g_pszRTAssertFunction;
682
683RTDECL(bool) RTAssertMayPanic(void)
684{
685 return true;
686}
687
688
689RTDECL(void) RTAssertMsg1(const char *pszExpr, unsigned uLine, const char *pszFile, const char *pszFunction)
690{
691 /*
692 * Fill in the globals.
693 */
694 g_pszRTAssertExpr = pszExpr;
695 g_pszRTAssertFile = pszFile;
696 g_pszRTAssertFunction = pszFunction;
697 g_u32RTAssertLine = uLine;
698 snprintf(g_szRTAssertMsg1, sizeof(g_szRTAssertMsg1),
699 "\n!!Assertion Failed!!\n"
700 "Expression: %s\n"
701 "Location : %s(%u) %s\n",
702 pszExpr, pszFile, uLine, pszFunction);
703}
704
705
706RTDECL(void) RTAssertMsg2V(const char *pszFormat, va_list va)
707{
708 vsnprintf(g_szRTAssertMsg2, sizeof(g_szRTAssertMsg2), pszFormat, va);
709 if (g_enmSupR3HardenedMainState < SUPR3HARDENEDMAINSTATE_CALLED_TRUSTED_MAIN)
710 supR3HardenedFatalMsg(g_pszRTAssertExpr, kSupInitOp_Misc, VERR_INTERNAL_ERROR,
711 "%s%s", g_szRTAssertMsg1, g_szRTAssertMsg2);
712 else
713 supR3HardenedError(VERR_INTERNAL_ERROR, false/*fFatal*/, "%s%s", g_szRTAssertMsg1, g_szRTAssertMsg2);
714}
715
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette