VirtualBox

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

Last change on this file since 66845 was 66845, checked in by vboxsync, 8 years ago

Support/posix: harder than expected

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