A self-extracting archive (SFX) is convenient when you need to copy files to another computer which may not already have the archive software installed. For example, many Windows drivers are installed using SFX.

On Windows, we can create a SFX using a GUI archive software such as 7-Zip and WinRAR. Simply right click the selected files and choose Add to archive…, then tick Create SFX archive. If you want to encrypt the files, you can set a password. If you also want to encrypt the file names, tick Encrypt file names. In this way, a SFX with password protection on both data and header is created.

## Create SFX (as Linux binary) on Linux

But how can we create a SFX on Linux using command line?

This turns out to be possible with the 7z program (from package p7zip) using option -sfx. For example, to create a SFX data.exe for dir data:

7z a -sfx data.exe data


You can also encrypt both data and header in a SFX with option -mhe=on. For example, to create a SFX data.exe with password 123456 for dir data:

7z a -mhe=on -p123456 -sfx data.exe data


If you don’t want to write the password in plaintext, you can use -p alone and it will prompt you for the password:

7z a -mhe=on -p -sfx data.exe data


## Create SFX (as Windows binary) on Linux

But you may have noticed that, the created SFX is a Linux binary, not a Windows binary:

# file data.exe
data.exe: ELF 64-bit LSB executable, x86-64,...


So it won’t work on Windows systems. To understand this, note that a SFX is combined from a executable part (stub) and a non-executable part (archive). To visualize this, we give a simple example of creating SFX with the ZIP format using cat:

cat "\$(which unzipsfx)" foo.zip > foo.exe


Here the stub unzipsfx comes from package unzip, which you can find on most Linux distros. As you can see, creating SFX can be as simple as cat a stub and a archive.

Now it should be easier to understand why data.exe is a Linux binary: Because it’s generated with a Linux stub. If you are copying files to a Windows machine, you have to generate SFX using a Windows stub. This is still possible with the -sfx option. Actually, the -sfx option allows you to specify the SFX module in the generated archive using format -sfx[{SFX_Module}]. Now we need to find a proper Windows SFX module.

The Windows SFX module exists in the 7-Zip installation program:

Taking the 64-bit program for example. This program is actually a SFX itself. So we can extract files from it even if we are on Linux:

7z x 7z1805-x64.exe


There is a file named 7z.sfx in the extracted files. This is what we use as the SFX module in the command line option. Copy this file to the dir where the command will be run, and run the command:

7z a -mhe=on -p -sfx7z.sfx data.exe data


The generated SFX should work on a Windows system.