[RFC PATCH v3 0/5] Libffi Static Trampolines

madvenka@linux.microsoft.com madvenka@linux.microsoft.com
Fri Jan 15 18:46:48 GMT 2021


From: "Madhavan T. Venkataraman" <madvenka@linux.microsoft.com>

Libffi Static Trampolines

Closures
========

Libffi Closures enable a program to call a function whose arguments, argument
types and return value are known only at runtime. Also, the calling
conventions of the called function can be different from native calling
conventions.

Closures support a variety of architectures and Application Binary Interfaces
or ABIs.

Closure Trampoline
==================

When a program invokes a closure, a libffi supplied trampoline is executed.
The trampoline loads the closure pointer in a designated register or on the
stack (depending on the ABI of the target function) and jumps to an ABI
handler. The ABI handler extracts arguments from the closure, calls the
target function and returns the function's return value in the native ABI.
To the program, it appears as if the target function was called natively.

Security Issue
==============

Currently, the trampoline code used in libffi is not statically defined in
a source file (except for MACH). The trampoline is either pre-defined
machine code in a data buffer. Or, it is generated at runtime. In order to
execute a trampoline, it needs to be placed in a page with executable
permissions.

Executable data pages are attack surfaces for attackers who may try to
inject their own code into the page and contrive to have it executed. The
security settings in a system may prevent various tricks used in user land
to write code into a page and to have it executed somehow. On such systems,
libffi trampolines would not be able to run.

Static Trampoline
=================

To solve this problem, the trampoline code needs to be defined statically
in a source file, compiled and placed in the text segment so it can be
mapped and executed naturally without any tricks. However, the trampoline
needs to be able to access the closure pointer at runtime.

PC-relative data referencing
============================

The solution implemented in this patch set uses PC-relative data references.
The trampoline is mapped in a code page. Adjacent to the code page, a data
page is mapped that contains the parameters of the trampoline:

	- the closure pointer
	- pointer to the ABI handler to jump to

The trampoline code uses an offset relative to its current PC to access its
data.

Some architectures support PC-relative data references in the ISA itself.
E.g., X64 supports RIP-relative references. For others, the PC has to
somehow be loaded into a general purpose register to do PC-relative data
referencing. To do this, we need to define a get_pc() kind of function and
call it to load the PC in a desired register.

There are two cases:

1. The call instruction pushes the return address on the stack.

   In this case, get_pc() will extract the return address from the stack
   and load it in the desired register and return.

2. The call instruction stores the return address in a designated register.

   In this case, get_pc() will copy the return address to the desired
   register and return.

Either way, the PC next to the call instruction is obtained.

Scratch register
================

In order to do its job, the trampoline code would need to use a scratch
register. Depending on the ABI, there may not be a register available for
scratch. This problem needs to be solved so that all ABIs will work.

The trampoline will save two values on the stack:

	- the closure pointer
	- the original value of the scratch register

This is what the stack will look like:

	sp before trampoline ------>	--------------------
					| closure pointer  |
					--------------------
					| scratch register |
	sp after trampoline ------->	--------------------

The ABI handler can do the following as needed:

	- the closure pointer can be loaded in a desired register

	- the scratch register can be restored to its original value

	- the stack pointer can be restored to its original value
	  (the value when the trampoline was invoked)

To do this, I have defined prolog code for each ABI handler. The legacy
trampoline jumps to the ABI handler directly. But the static trampoline
defined in this patch jumps tp the prolog code which performs the above
actions before jumping to the ABI handler.

NOTE:
	The documentation for this feature will contain information on:

	- the name of the scratch register for each architecture

	- the stack offsets at which the closure and the scratch register
	  will be copied

Trampoline Table
================

In order to reduce the trampoline memory footprint, the trampoline code
would be defined as a code array in the text segment. This array would be
mapped into the address space of the caller. The mapping would, therefore,
contain a trampoline table.

Adjacent to the trampoline table mapping, there will be a data mapping that
contains a parameter table, one parameter block for each trampoline. The
parameter block will contain:

	- a pointer to the closure
	- a pointer to the ABI handler

The static trampoline code would finally look like this:

	- Make space on the stack for the closure and the scratch register
	  by moving the stack pointer down
	- Store the original value of the scratch register on the stack
	- Using PC-relative reference, get the closure pointer
	- Store the closure pointer on the stack
	- Using PC-relative reference, get the ABI handler pointer
	- Jump to the ABI handler

Trampoline API
==============

There is a lot of dynamic code out there. They all have the same security
issue. Dynamic code can be re-written into static code provided the data
required by the static code can be passed to it just like we pass the closure
pointer to an ABI handler.

So, the same trampoline functions used by libffi internally need to be
made available to the rest of the world in the form of an API. The
following API has been defined in this solution:

int ffi_tramp_is_supported(void);

	To support static trampolines, code needs to be added to each
	architecture. This function tells us whether or not the feature is
	supported in the current libffi for the current architecture.

void *ffi_tramp_alloc (int flags);

	Allocate a trampoline. Currently, flags are zero. An opaque
	trampoline structure pointer is returned.
	
	Internally, libffi manages trampoline tables and individual
	trampolines in each table.

int ffi_tramp_set_parms (void *tramp, void *target, void *data);

	Initialize the parameters of a trampoline. That is, the target code
	that the trampoline should jump to and the data that needs to be
	passed to the target code.

void *ffi_tramp_get_addr (void *tramp);

	Return the address of the trampoline to invoke the trampoline with.
	The trampoline can be invoked in one of two ways:

		- Simply branch to the trampoline address
		- Treat the trampoline address as a function pointer and call
		  it.

	Which method is used depends on the target code.

void ffi_tramp_free (void *tramp);

	Free a trampoline.

Testing
=======

The libffi selftests have been run successfully on X86 and ARM, 32-bit and
64-bit. I also have my own API test that does stress testing of the API.

TBD
===

Changelog:

v1
	Introduced the Static Trampoline feature.

v2
	- I have removed the configuration option --enable-static-tramp from
	  configure.ac. Now, this feature is enabled unconditionally for
	  Linux and BSD variants mentioned below.

	- In v1, I had defined a method to obtain the path to libffi and the
	  offset within the libffi binary of the trampoline code table. This
	  is used to mmap() the trampoline code table into an address space.

	  This is obtained by parsing /proc/<pid>/maps. However, the maps file
	  is not available on other OSes (except NetBSD). So, I have defined
	  an alternative way. Wherever mkstemp() is available, a temporary file
	  can be created and the trampoline code table can be written into that
	  file and the temporary file can be used to map the trampoline code
	  table.

	  The code tries the maps method first. If that fails, it falls back
	  to using the temporary file method.

	- In v1, only Linux was supported. In v2, I have added support for
	  static trampolines for FreeBSD, NetBSD and OpenBSD. With the NetBSD
	  support, we can remove the following chunk of code from
	  src/closures.c:

	  #if __NetBSD_Version__ - 0 >= 799007200
	  /* NetBSD with PROT_MPROTECT */
	  ...
	  #else /* !NetBSD with PROT_MPROTECT */

	  The new code supports more versions of NetBSD than before.

	- In configure.ac, I set FFI_MMAP_EXEC_WRIT to 1 for NetBSD as well
	  so that NetBSD versions can use static trampolines instead of using
	  malloc() for obtaining executable data space.

	- The code in src/tramp.c has been organized into OS-specific and
	  generic parts to make it easier to add support for more OSes. For
	  instance, if we add support for MACH (which is just a few lines of
	  changes), we can get rid of the FFI_EXEC_TRAMPOLINE_TABLE code.

	- There was a bug in version 1. If, for any reason, the static
	  trampoline initialization fails, then libffi should fall back to
	  using the legacy trampolines. But this was not implemented correctly.
	  I have now corrected the problem.

	- Fixed a build problem encountered when CI testing was done on my pull
	  request.

v3:
	- Added some comments.

	- Fixed a compilation warning on 32-bit systems from the sscanf()
	  statement in ffi_tramp_get_libffi() in src/tramp.c.

	- Addressed build failures that happen when old compilers that have not
	  been updated for Intel Control Flow Enforcement Technology (CET) are
	  used.

	- Removed the support for BSD variants. I plan to submit these as a
	  separate patchset once the initial static trampoline patch supporting
	  Linux is accepted. All of the code works properly on the BSD variants
	  and will be worked on next. This is mainly to keep the current
	  review smaller and more focused.

	- Added code to handle the case where the OS page size can differ from
	  the hardware page size.
I need to study how to include my trampoline API test in the libffi selftests.
---

Madhavan T. Venkataraman (5):
  Libffi Static Trampolines
  x86: Support for Static Trampolines
  i386: Support for Static Trampolines
  arm64: Support for Static Trampolines
  arm: Support for Static Trampolines

 Makefile.am                                 |   3 +-
 configure.ac                                |   9 +-
 include/ffi.h.in                            |  13 +-
 include/ffi_common.h                        |   4 +
 libffi.map.in                               |   9 +
 src/aarch64/ffi.c                           |  36 +-
 src/aarch64/internal.h                      |  10 +
 src/aarch64/sysv.S                          |  68 ++
 src/arm/ffi.c                               |  29 +-
 src/arm/internal.h                          |  10 +
 src/arm/sysv.S                              |  45 ++
 src/closures.c                              |  47 +-
 src/tramp.c                                 | 718 ++++++++++++++++++++
 src/x86/ffi.c                               |  35 +
 src/x86/ffi64.c                             |  40 +-
 src/x86/ffiw64.c                            |  10 +
 src/x86/internal.h                          |  11 +
 src/x86/internal64.h                        |  11 +
 src/x86/sysv.S                              | 116 ++++
 src/x86/unix64.S                            | 104 +++
 src/x86/win64.S                             |  12 +
 testsuite/libffi.closures/closure_loc_fn0.c |   3 +
 22 files changed, 1332 insertions(+), 11 deletions(-)
 create mode 100644 src/tramp.c


base-commit: e70bf987daa7b7b5df2de7579d5c51a888e8bf7d
-- 
2.25.1



More information about the Libffi-discuss mailing list