Skip to main content
coreydaley.dev

Patching libarchive to read and write encrypted 7z

Point libarchive at a password-protected 7z and it stops before asking for a password:

The file content is encrypted, but currently not supported

If the archive also hides its filenames, the message says archive header instead of file content. Either way, the password you supplied is never used. libarchive 3.8.7, the version Purrchiver is built on, can read and write encrypted ZIP but not encrypted 7z, and encrypted 7z is one of the most common password-protected formats around. This is how I added it.

Why patch instead of adding another library

The obvious alternative was the LZMA SDK, the library 7-Zip is built on. A quick spike killed that: its plain-C 7z decoder doesn’t do decryption. The SDK ships an AES implementation, but the C extractor never calls it. The code that does handle encrypted 7z is 7-Zip’s C++ codebase, which is far too large to vendor for one feature.

libarchive already parses the 7z container, including the list of “coders” (the processing steps) that each block of data passes through. An encrypted 7z is an ordinary 7z with one extra coder, AES-256 with a SHA-256-based key, sitting in front of the usual LZMA2. So the smallest change was to teach libarchive’s existing 7z reader about that one coder. Purrchiver is Mac-only, so the crypto comes from CommonCrypto.

The key derivation

7z doesn’t use PBKDF2. Its key is a single SHA-256 hash, fed the same input over and over:

// key = SHA-256 over 2^cycles repetitions of (salt || password || counter)
CC_SHA256_Init(&sha);
for (uint64_t r = 0; r < (1ULL << cycles); r++) {
    CC_SHA256_Update(&sha, salt, salt_len);
    CC_SHA256_Update(&sha, pw_utf16le, pw_len);   // password as UTF-16LE
    CC_SHA256_Update(&sha, le64(r), 8);           // 8-byte little-endian counter
}
CC_SHA256_Final(key, &sha);

The salt, the IV, and cycles (7-Zip calls it NumCyclesPower) are packed into the coder’s property bytes: the low six bits of the first byte are the cycle count, the two high bits and a second byte encode the salt and IV lengths, and then come the salt and IV themselves. 7-Zip writes 19 by default, which is 524,288 rounds. The special value 0x3F means no hashing at all: the key is just the salt and password bytes, zero-padded.

With the key in hand, the data is AES-256-CBC with no padding, because 7z always encrypts whole 16-byte blocks. The patch decrypts each chunk into a 64 KiB buffer and hands the plaintext to libarchive’s normal decompression path, which never knows encryption was involved.

The passphrase that was never there

One detail is easy to miss. libarchive keeps a small iterator over the passphrases you’ve registered, and its candidate counter starts at zero. Zero, to that iterator, means every candidate has already been tried, so the first request comes back empty and the reader reports that a passphrase is required, even when one was supplied. Reset the iterator before asking:

__archive_read_reset_passphrase(a);              // candidate = -1: start fresh
const char *pw = __archive_read_next_passphrase(a);

Writing them too

With reading working, the writer got the matching patch: random salt and IV from SecRandomCopyBytes, 19 cycles to match 7-Zip, and an option that selects either content-only encryption or header encryption, where the list of filenames is encrypted as well. I tested the output by having 7-Zip’s own 7zz extract it, not just Purrchiver’s reader.

That option caused a bug of its own: the app asked the engine for the content-only variant while the Create sheet promised hidden filenames. A pre-release audit caught it, and the fix was one line. I wrote that one up with the other settings that did nothing.

2^63 rounds

The cycle count in the archive is six bits, so it can be as high as 63. Nothing in the format stops an archive from asking for 2^63 SHA-256 rounds, which would take far longer than anyone would wait for a file to open. Since the value comes from the file, an attacker controls it.

The patched reader refuses anything above 24 (about 16.8 million rounds) with a clean error before any hashing starts. The derivation function checks again as a second line of defense, and still allows 0x3F, because the spec gives that value its own meaning.

Even 2^24 rounds takes seconds, and at first canceling the open of such an archive couldn’t stop a derivation that had already started. The hash loop now checks a cancel flag every 131,072 rounds. On the Swift side, the reader installs that flag around each synchronous libarchive call and sets it from a task-cancellation handler, so canceling the Swift task stops the C loop. In the test, a derivation at the 24-cycle cap is canceled 50 ms in and returns at about 53 ms, instead of running for seconds.

The limitation: ASCII passwords only

7z hashes the password as UTF-16LE. The patch converts it the simple way, by widening each byte to two bytes, and that’s only correct for ASCII. For anything else it would produce a key that 7-Zip doesn’t, so archives Purrchiver encrypted wouldn’t open elsewhere, and vice versa.

Rather than produce archives that silently don’t interoperate, Purrchiver rejects non-ASCII passwords before any crypto runs, with an error that says so. Proper Unicode support needs correct UTF-16 conversion, normalization, and surrogate pairs, and it isn’t there yet.

What I’d pass on

  • Check the format’s knobs for cost. Any count or size that comes from the file and controls how much work you do needs a ceiling.
  • Test against the reference tool. A reader and writer from the same code can agree with each other and both be wrong. 7-Zip’s 7zz was the check.
  • Make the UI’s promise a test. “Filenames are hidden” was on screen before any test checked it.

libarchive is BSD-licensed, and the patch is small. It touches the 7z reader and writer and adds one helper file of CommonCrypto calls.

Related posts