VirtualBox

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

Last change on this file since 82957 was 82957, checked in by vboxsync, 5 years ago

SUPHard/darwin: Ignore patching failures in supR3HardenedPosixInit if the hardened runtime option is active (can't easily modify text pages then). bugref:9466

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

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