Binary formats and compatibility
Single-page view · as markdown
Kernel Support for miscellaneous Binary Formats (binfmt_misc)
Peios Kernel / Administration / System administration / Binary formats and compatibility
Peios: Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0,
setcapand Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See Peios kernel behaviour for the mapping and exceptions.
This Kernel feature allows you to invoke almost (for restrictions see below) every program by simply typing its name in the shell. This includes for example compiled Java(TM), Python or Emacs programs.
To achieve this you must tell binfmt_misc which interpreter has to be invoked with which binary. Binfmt_misc recognises the binary-type by matching some bytes at the beginning of the file with a magic byte sequence (masking out specified bits) you have supplied. Binfmt_misc can also recognise a filename extension aka .com or .exe.
First you must mount binfmt_misc:
mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc
To actually register a new binary type, you have to set up a string looking like :name:type:offset:magic:mask:interpreter:flags (where you can choose the : upon your needs) and echo it to /proc/sys/fs/binfmt_misc/register.
Here is what the fields mean:
-
-
nameis an identifier string. A new /proc file will be created with this name below
/proc/sys/fs/binfmt_misc; cannot contain slashes/for obvious reasons.
-
-
-
typeis the type of recognition. Give
Mfor magic andEfor extension.
-
-
-
offsetis the offset of the magic/mask in the file, counted in bytes. This defaults to 0 if you omit it (i.e. you write
:name:type::magic...). Ignored when using filename extension matching.
-
-
-
magicis the byte sequence binfmt_misc is matching for. The magic string may contain hex-encoded characters like
\x0aor\xA4. Note that you must escape any NUL bytes; parsing halts at the first one. In a shell environment you might have to write\\x0ato prevent the shell from eating your\. If you chose filename extension matching, this is the extension to be recognised (without the., the\x0aspecials are not allowed). Extension matching is case sensitive, and slashes/are not allowed!
-
-
-
maskis an (optional, defaults to all 0xff) mask. You can mask out some bits from matching by supplying a string like magic and as long as magic. The mask is anded with the byte sequence of the file. Note that you must escape any NUL bytes; parsing halts at the first one. Ignored when using filename extension matching.
-
-
-
interpreteris the program that should be invoked with the binary as first argument (specify the full path)
-
-
-
flagsis an optional field that controls several aspects of the invocation of the interpreter. It is a string of capital letters, each controls a certain aspect. The following flags are supported:
-
P- preserve-argv[0]Legacy behavior of binfmt_misc is to overwrite the original argv[0] with the full path to the binary. When this flag is included, binfmt_misc will add an argument to the argument vector for this purpose, thus preserving the original
argv[0]. e.g. If your interp is set to/bin/fooand you runblah(which is in/usr/local/bin), then the kernel will execute/bin/foowithargv[]set to["/bin/foo", "/usr/local/bin/blah", "blah"]. The interp has to be aware of this so it can execute/usr/local/bin/blahwithargv[]set to["blah"]. -
O- open-binaryLegacy behavior of binfmt_misc is to pass the full path of the binary to the interpreter as an argument. When this flag is included, binfmt_misc will open the file for reading and pass its descriptor as an argument, instead of the full path, thus allowing the interpreter to execute non-readable binaries. This feature should be used with care - the interpreter has to be trusted not to emit the contents of the non-readable binary.
-
C- credentialsCurrently, the behavior of binfmt_misc is to calculate the credentials and security token of the new process according to the interpreter. When this flag is included, these attributes are calculated according to the binary. It also implies the
Oflag. In upstream Linux this can cause a root-owned set-user-ID binary to run its interpreter with elevated Unix credentials. In Peios, it does not mint native token authority; exec access, signing/PIP and PSB rules still apply. -
F- fix binaryThe usual behaviour of binfmt_misc is to spawn the binary lazily when the misc format file is invoked. However, this doesn't work very well in the face of mount namespaces and changeroots, so the
Fmode opens the binary as soon as the emulation is installed and uses the opened image to spawn the emulator, meaning it is always available once installed, regardless of how the environment changes.
-
-
There are some restrictions:
the whole register string may not exceed 1920 characters
the magic must reside in the first 128 bytes of the file, i.e. offset+size(magic) has to be less than 128
the interpreter string may not exceed 127 characters
To use binfmt_misc you have to mount it first. You can mount it with mount -t binfmt_misc none /proc/sys/fs/binfmt_misc command, or you can add a line none /proc/sys/fs/binfmt_misc binfmt_misc defaults 0 0 to your /etc/fstab so it auto mounts on boot.
You may want to add the binary formats in one of your /etc/rc scripts during boot-up. Read the manual of your init program to figure out how to do this right.
Think about the order of adding entries! Later added entries are matched first!
A few examples (assumed you are in /proc/sys/fs/binfmt_misc):
-
enable support for em86 (like binfmt_em86, for Alpha AXP only):
echo ':i386:M::\x7fELF\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x03:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff:/bin/em86:' > register echo ':i486:M::\x7fELF\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x06:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff:/bin/em86:' > register -
enable support for packed DOS applications (pre-configured dosemu hdimages):
echo ':DEXE:M::\x0eDEX::/usr/bin/dosexec:' > register -
enable support for Windows executables using wine:
echo ':DOSWin:M::MZ::/usr/local/bin/wine:' > register
For java support see Documentation/admin-guide/java.rst
You can enable/disable binfmt_misc or one binary type by echoing 0 (to disable) or 1 (to enable) to /proc/sys/fs/binfmt_misc/status or /proc/.../the_name. Catting the file tells you the current status of binfmt_misc/the_entry.
You can remove one entry or all entries by echoing -1 to /proc/.../the_name or /proc/sys/fs/binfmt_misc/status.
Hints #
If you want to pass special arguments to your interpreter, you can write a wrapper script for it. See Documentation/admin-guide/java.rst for an example.
Your interpreter should NOT look in the PATH for the filename; the kernel passes it the full filename (or the file descriptor) to use. Using $PATH can cause unexpected behaviour and can be a security hazard.
Richard Günther <rguenth@tat.physik.uni-tuebingen.de>
Java(tm) Binary Kernel Support for Linux v1.03
Peios Kernel / Administration / System administration / Binary formats and compatibility
Peios: Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access;
chmod,chownand POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See Peios kernel behaviour for mount-policy defaults and the tmpfs rootfs rule.
Linux beats them ALL! While all other OS's are TALKING about direct support of Java Binaries in the OS, Linux is doing it!
You can execute Java applications and Java Applets just like any other program after you have done the following:
-
You MUST FIRST install the Java Developers Kit for Linux. The Java on Linux HOWTO gives the details on getting and installing this. This HOWTO can be found at:
You should also set up a reasonable CLASSPATH environment variable to use Java applications that make use of any nonstandard classes (not included in the same directory as the application itself).
-
You have to compile BINFMT_MISC either as a module or into the kernel (
CONFIG_BINFMT_MISC) and set it up properly. If you choose to compile it as a module, you will have to insert it manually with modprobe/insmod, as kmod cannot easily be supported with binfmt_misc. Read the file 'binfmt_misc.txt' in this directory to know more about the configuration process. -
Add the following configuration items to binfmt_misc (you should really have read
binfmt_misc.txtnow): support for Java applications:':Java:M::\xca\xfe\xba\xbe::/usr/local/bin/javawrapper:'support for executable Jar files:
':ExecutableJAR:E::jar::/usr/local/bin/jarwrapper:'support for Java Applets:
':Applet:E::html::/usr/bin/appletviewer:'or the following, if you want to be more selective:
':Applet:M::<!--applet::/usr/bin/appletviewer:'Of course you have to fix the path names. The path/file names given in this document match the Debian 2.1 system. (i.e. jdk installed in
/usr, custom wrappers from this document in/usr/local)Note, that for the more selective applet support you have to modify existing html-files to contain
<!--applet-->in the first line (<has to be the first character!) to let this work!For the compiled Java programs you need a wrapper script like the following (this is because Java is broken in case of the filename handling), again fix the path names, both in the script and in the above given configuration string.
You, too, need the little program after the script. Compile like:
gcc -O2 -o javaclassname javaclassname.cand stick it to
/usr/local/bin.Both the javawrapper shellscript and the javaclassname program were supplied by Colin J. Watson <cjw44@cam.ac.uk>.
Javawrapper shell script:
#!/bin/bash
# /usr/local/bin/javawrapper - the wrapper for binfmt_misc/java
if [; then
fi
CLASS=
FQCLASS=
FQCLASSN=
FQCLASSP=
# for example:
# CLASS=Test.class
# FQCLASS=foo.bar.Test
# FQCLASSN=Test
# FQCLASSP=foo/bar
while ; do
if [; then
# See if this directory works straight off
CLASSDIR=
if | ; then
CLASSBASE=
break;
fi
# Try dereferencing the directory name
CLASSDIR=
if | ; then
CLASSBASE=
break;
fi
# If no other possible filename exists
if [; then
fi
fi
if [; then break; fi
# Go down one more level of symbolic links
if [; then
fi
CLASS=
done
if [; then
if [; then
GOODNAME=.class
else
GOODNAME=/.class
fi
fi
if ! | ; then
# class is not in CLASSPATH, so prepend dir of class to CLASSPATH
if [ ; then
else
fi
fi
javaclassname.c:
/* javaclassname.c
*
* Extracts the class name from a Java class file; intended for use in a Java
* wrapper of the type supported by the binfmt_misc option in the Linux kernel.
*
* Copyright (C) 1999 Colin J. Watson <cjw44@cam.ac.uk>.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* From Sun's Java VM Specification, as tag entries in the constant pool. */
/* Define some commonly used error messages */
char *program;
long *pool;
u_int8_t ;
u_int16_t ;
void ;
void ;
int ;
/* Reads in an unsigned 8-bit integer. */
u_int8_t
/* Reads in an unsigned 16-bit integer. */
u_int16_t
/* Reads in a value from the constant pool. */
void
void
int
jarwrapper:
#!/bin/bash
# /usr/local/java/bin/jarwrapper - the wrapper for binfmt_misc/jar
java -jar $1
Now simply chmod +x the .class, .jar and/or .html files you want to execute.
To add a Java program to your path best put a symbolic link to the main .class file into /usr/bin (or another place you like) omitting the .class extension. The directory containing the original .class file will be added to your CLASSPATH during execution.
To test your new setup, enter in the following simple Java app, and name it "HelloWorld.java":
Now compile the application with:
javac HelloWorld.java
Set the executable permissions of the binary file, with:
chmod 755 HelloWorld.class
And then execute it:
./HelloWorld.class
To execute Java Jar files, simple chmod the *.jar files to include the execution bit, then just do:
./Application.jar
To execute Java Applets, simple chmod the *.html files to include the execution bit, then just do:
./Applet.html
originally by Brian A. Lantz, brian@lantz.com heavily edited for binfmt_misc by Richard Günther new scripts by Colin J. Watson <cjw44@cam.ac.uk> added executable Jar file support by Kurt Huwig <kurt@iku-netz.de>
Mono(tm) Binary Kernel Support for Linux
Peios Kernel / Administration / System administration / Binary formats and compatibility
To configure Linux to automatically execute Mono-based .NET binaries (in the form of .exe files) without the need to use the mono CLR wrapper, you can use the BINFMT_MISC kernel support.
This will allow you to execute Mono-based .NET binaries just like any other program after you have done the following:
-
You MUST FIRST install the Mono CLR support, either by downloading a binary package, a source tarball or by installing from Git. Binary packages for several distributions can be found at:
Instructions for compiling Mono can be found at:
Once the Mono CLR support has been installed, just check that
/usr/bin/mono(which could be located elsewhere, for example/usr/local/bin/mono) is working. -
You have to compile BINFMT_MISC either as a module or into the kernel (
CONFIG_BINFMT_MISC) and set it up properly. If you choose to compile it as a module, you will have to insert it manually with modprobe/insmod, as kmod cannot be easily supported with binfmt_misc. Read the filebinfmt_misc.txtin this directory to know more about the configuration process. -
Add the following entries to
/etc/rc.localor similar script to be run at system startup:# Insert BINFMT_MISC module into the kernel if [; then # Some distributions, like Fedora Core, perform # the following command automatically when the # binfmt_misc module is loaded into the kernel # or during normal boot up (systemd-based systems). # Thus, it is possible that the following line # is not needed at all. fi # Register support for .NET CLR binaries if [; then # Replace /usr/bin/mono with the correct pathname to # the Mono CLR runtime (usually /usr/local/bin/mono # when compiling from sources or CVS). else fi -
Check that
.exebinaries can be ran without the need of a wrapper script, simply by launching the.exefile directly from a command prompt, for example:/usr/bin/xsd.exe
Syscall User Dispatch
Peios Kernel / Administration / System administration / Binary formats and compatibility
Background #
Compatibility layers like Wine need a way to efficiently emulate system calls of only a part of their process - the part that has the incompatible code - while being able to execute native syscalls without a high performance penalty on the native part of the process. Seccomp falls short on this task, since it has limited support to efficiently filter syscalls based on memory regions, and it doesn't support removing filters. Therefore a new mechanism is necessary.
Syscall User Dispatch brings the filtering of the syscall dispatcher address back to userspace. The application is in control of a flip switch, indicating the current personality of the process. A multiple-personality application can then flip the switch without invoking the kernel, when crossing the compatibility layer API boundaries, to enable/disable the syscall redirection and execute syscalls directly (disabled) or send them to be emulated in userspace through a SIGSYS.
The goal of this design is to provide very quick compatibility layer boundary crosses, which is achieved by not executing a syscall to change personality every time the compatibility layer executes. Instead, a userspace memory region exposed to the kernel indicates the current personality, and the application simply modifies that variable to configure the mechanism.
There is a relatively high cost associated with handling signals on most architectures, like x86, but at least for Wine, syscalls issued by native Windows code are currently not known to be a performance problem, since they are quite rare, at least for modern gaming applications.
Since this mechanism is designed to capture syscalls issued by non-native applications, it must function on syscalls whose invocation ABI is completely unexpected to Linux. Syscall User Dispatch, therefore doesn't rely on any of the syscall ABI to make the filtering. It uses only the syscall dispatcher address and the userspace key.
As the ABI of these intercepted syscalls is unknown to Linux, these syscalls are not instrumentable via ptrace or the syscall tracepoints.
Interface #
A thread can setup this mechanism on supported kernels by executing the following prctl:
prctl(PR_SET_SYSCALL_USER_DISPATCH, <op>, <offset>, <length>, [selector])
<op> is either PR_SYS_DISPATCH_EXCLUSIVE_ON/PR_SYS_DISPATCH_INCLUSIVE_ON or PR_SYS_DISPATCH_OFF, to enable and disable the mechanism globally for that thread. When PR_SYS_DISPATCH_OFF is used, the other fields must be zero.
For PR_SYS_DISPATCH_EXCLUSIVE_ON [<offset>, <offset>+<length>) delimit a memory region interval from which syscalls are always executed directly, regardless of the userspace selector. This provides a fast path for the C library, which includes the most common syscall dispatchers in the native code applications, and also provides a way for the signal handler to return without triggering a nested SIGSYS on (rt_)sigreturn. Users of this interface should make sure that at least the signal trampoline code is included in this region. In addition, for syscalls that implement the trampoline code on the vDSO, that trampoline is never intercepted.
For PR_SYS_DISPATCH_INCLUSIVE_ON [<offset>, <offset>+<length>) delimit a memory region interval from which syscalls are dispatched based on the userspace selector. Syscalls from outside of the range are always executed directly.
[selector] is a pointer to a char-sized region in the process memory region, that provides a quick way to enable disable syscall redirection thread-wide, without the need to invoke the kernel directly. selector can be set to SYSCALL_DISPATCH_FILTER_ALLOW or SYSCALL_DISPATCH_FILTER_BLOCK. Any other value should terminate the program with a SIGSYS.
Additionally, a tasks syscall user dispatch configuration can be peeked and poked via the PTRACE_(GET|SET)_SYSCALL_USER_DISPATCH_CONFIG ptrace requests. This is useful for checkpoint/restart software.
Security Notes #
Syscall User Dispatch provides functionality for compatibility layers to quickly capture system calls issued by a non-native part of the application, while not impacting the Linux native regions of the process. It is not a mechanism for sandboxing system calls, and it should not be seen as a security mechanism, since it is trivial for a malicious application to subvert the mechanism by jumping to an allowed dispatcher region prior to executing the syscall, or to discover the address and modify the selector value. If the use case requires any kind of security sandboxing, Seccomp should be used instead.
Any fork or exec of the existing process resets the mechanism to PR_SYS_DISPATCH_OFF.