VirtualBox

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

Last change on this file since 86719 was 86224, checked in by vboxsync, 4 years ago

SUPHard/posix: Function pointer exception hancks for Clang. bugref:9790 bugref:9794

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