public inbox for libffi-discuss@sourceware.org
 help / color / mirror / Atom feed
From: madvenka@linux.microsoft.com
To: libffi-discuss@sourceware.org
Cc: green@moxielogic.com, fw@deneb.enyo.de, dj@redhat.com,
	madvenka@linux.microsoft.com
Subject: [RFC PATCH v2 0/5] Libffi Static Trampolines
Date: Wed, 16 Dec 2020 13:40:04 -0600	[thread overview]
Message-ID: <20201216194009.8268-1-madvenka@linux.microsoft.com> (raw)
In-Reply-To: <e42170d43f92c69f2b16264cddbccb91107d023e>

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 by the ABI:

	- 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 static
trampoline defined in this patch jumps to the prolog code which performs
the above actions before jumping to the ABI handler.

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

In order to reduce the trampoline memory footprint, the trampoline code
will 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 will 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 from the
	  parameter block

	- Store the closure pointer on the stack

	- Using PC-relative reference, get the ABI handler pointer from
	  the parameter block

	- Jump to the ABI handler

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

There is a lot of dynamic code out there. They all have the same security
issue. To solve this, dynamic code can be re-written into static code
provided the data required by the 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.
I have also run the tests on Linux, FreeBSD, OpenBSD and NetBSD.

TBD
===

I need to study how to include my trampoline API test in the libffi selftests.
---

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 above.

	- 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. Once NetBSD
	  static trampolines are in place, 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
	  altogether.

	- There was a bug in v1. 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
	  v1 pull request.

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                                |  11 +-
 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                          |  64 ++
 src/arm/ffi.c                               |  29 +-
 src/arm/internal.h                          |  10 +
 src/arm/sysv.S                              |  41 ++
 src/closures.c                              |  47 +-
 src/tramp.c                                 | 710 ++++++++++++++++++++
 src/x86/ffi.c                               |  29 +
 src/x86/ffi64.c                             |  34 +-
 src/x86/ffiw64.c                            |  10 +
 src/x86/internal.h                          |  10 +
 src/x86/internal64.h                        |  10 +
 src/x86/sysv.S                              |  70 ++
 src/x86/unix64.S                            |  62 ++
 src/x86/win64.S                             |  12 +
 testsuite/libffi.closures/closure_loc_fn0.c |   3 +
 22 files changed, 1215 insertions(+), 12 deletions(-)
 create mode 100644 src/tramp.c

-- 
2.27.0


       reply	other threads:[~2020-12-16 19:40 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
     [not found] <e42170d43f92c69f2b16264cddbccb91107d023e>
2020-12-16 19:40 ` madvenka [this message]
2020-12-16 19:40   ` [RFC PATCH v2 1/5] " madvenka
2020-12-16 19:40   ` [RFC PATCH v2 2/5] x86: Support for " madvenka
2020-12-16 19:40   ` [RFC PATCH v2 3/5] i386: " madvenka
2020-12-16 19:40   ` [RFC PATCH v2 4/5] arm64: " madvenka
2020-12-16 19:40   ` [RFC PATCH v2 5/5] arm: " madvenka

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20201216194009.8268-1-madvenka@linux.microsoft.com \
    --to=madvenka@linux.microsoft.com \
    --cc=dj@redhat.com \
    --cc=fw@deneb.enyo.de \
    --cc=green@moxielogic.com \
    --cc=libffi-discuss@sourceware.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).