Ferrite is a self-hosted file storage app in Laravel and Livewire. It stores files as blobs under random keys on Flysystem disks (local, S3 or SFTP) that the admin adds in the UI and the app builds at runtime with Storage::build(). A disk can be set to encrypt, so a stolen drive, a leaked bucket or a leaked backup exposes no file contents.
Crypt::encrypt() on a whole file does not work for a file store. It loads the file into memory, and a ranged read has to decrypt everything before the offset: playing a video from minute 40 means decrypting the first 40 minutes. This post describes the format used instead.
Threat model
The threat model was written in the docs before any code. The encryption protects against this:
- Someone gets the storage but not the server: a stolen disk, a public S3 bucket, a compromised Storage Box account, a backup of the blobs in the wrong place.
It does not protect against these:
- Someone who has the server and its
.env. The app has to read the files, so the key sits next to it. - Metadata. File and folder names, sizes and owners are in the database, unencrypted.
Per-user keys and browser-side (end-to-end) encryption were rejected. Both break share links, thumbnails, search and password resets (a reset would lose the files). One key per disk protects less, but all of those keep working.
Why not secretstream
libsodium has crypto_secretstream_xchacha20poly1305 for streams of encrypted chunks. It is simpler than the format used here, but it cannot start in the middle: each chunk depends on the state left by the previous one, so seeking means decrypting from the start.
The format uses independent chunks instead, sealed with the plain AEAD function from PHP's sodium extension.
The format
header (98 bytes) "FRT1" | master key id (2) | chunk size (4) | nonce prefix (16) | wrap nonce (24) | wrapped data key (48) chunk i XChaCha20-Poly1305(up to 65536 bytes of plaintext) + 16 byte tag - Every blob gets its own random data key. The header carries it, wrapped with the master key (
FERRITE_FILE_KEY). Rotating the master key only rewrites 98-byte headers; the chunks are copied as they are. - Chunk
iis sealed with the nonceprefix . i, where the prefix is 16 random bytes per blob andiis a 64-bit counter. XChaCha20 has a 24-byte nonce, which fits both. - The additional data is one byte saying whether this is the last chunk. This detects truncation: in a blob cut after any chunk, the new final chunk was sealed as a non-last chunk, so it fails.
- Reordered, duplicated or altered chunks fail, because the nonce includes the index.
- The header is the additional data of the key wrap, so a modified header fails.
$sealed = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt( $plain, $last ? "\x01" : "\x00", // additional data: is this the last chunk $prefix . pack('J', $index), // 16 + 8 = 24 byte nonce $dataKey, ); Seeking
Every chunk is 65536 bytes of plaintext plus 16 bytes of tag, except the last one. The file size is in the database, so the position of any chunk is computed:
public static function cipherSize(int $plainSize): int { return self::HEADER + $plainSize + self::chunkCount($plainSize) * self::TAG; } A request for Range: bytes=500000000- becomes:
$startChunk = intdiv($offset, self::CHUNK); $raw = $openRaw(self::HEADER + $startChunk * (self::CHUNK + self::TAG)); // decrypt from there, and drop $offset % CHUNK bytes of the first chunk $openRaw opens the underlying blob at a byte offset: an fseek on the local disk, a read at that offset on SFTP, a ranged GET on S3. The decrypting layer does not care which one it is.
Decryption is a custom PHP stream wrapper (stream_wrapper_register). It reads one chunk, authenticates it and returns the plaintext, so memory stays at a few MiB whatever the file size, and no byte of a chunk is returned before it is verified. The same stream feeds downloads, ranges, previews, ZIP entries, share links, thumbnails and the API.
A client of the API that depends on this is Magnetite, a music player that can use a Ferrite folder as its library. It forwards the browser's Range header to Ferrite, so a track starts at once and seeking in it fetches only the bytes it needs.
Flysystem, responses and keys
Flysystem is not modified. The cipher wraps the stream before writeStream() on the way in, and after readStream() on the way out:
public function writeBlob(StorageDisk $disk, string $key, $stream, int $size): ?int { $filesystem = $this->filesystem($disk); // Storage::build($config) if (! $disk->encrypt) { $filesystem->writeStream($key, $stream); return null; } $encrypted = app(BlobCipher::class)->encrypt($stream, $size); $filesystem->writeStream($key, $encrypted); return app(KeyRing::class)->currentId(); // stored on the node } A disk set to encrypt never writes plaintext. If the key is missing, the upload fails and leaves nothing on the disk.
Reads end in a Symfony StreamedResponse. The responder parses the Range header and sets the 206 status and Content-Range. The response closure then reads from the decrypted stream, starting at the requested offset. It does not know whether the blob is encrypted.
Ferrite reads files in many places: downloads, previews, ZIP, share links and more. One that skipped decryption would serve ciphertext, so they all go through one method, StorageManager::openNodeStream(). Which blobs are encrypted is recorded in the database (nodes.encryption_key_id, null for plaintext), not guessed from the content, so a plaintext file that starts with FRT1 is still plaintext.
The master keys come from config/ferrite.php, which reads FERRITE_FILE_KEY from the environment. They are deliberately separate from APP_KEY: rotating one must never break the other. A small KeyRing class, resolved from the container, holds the current key and any retired ones during a rotation.
Encrypting a disk that already has files
The files:encrypt {disk} artisan command converts the existing blobs in place. For each blob:
- write an encrypted copy under a new random key,
- read the copy back and compare its sha256 with the one stored for the file,
- only then point the files at the new blob and delete the old one.
A crash at any point leaves every file readable, and running the command again continues. The disk keeps serving while it runs, because reads handle encrypted and plaintext blobs side by side. It needs space for the largest blob, not for the whole disk.
Performance and size
Measured on a development laptop, with a 512 MiB file on a local SSD:
- encrypting while writing: about 230 MB/s
- decrypting while hashing: about 125 MB/s (sha256 alone is about 180)
- memory: constant, one chunk at a time
- disk: 16 bytes per 64 KiB plus 98 bytes, about 0.03%
On a remote disk, the network is the limit.
Limits
- Extracted text for search is not stored for files on an encrypted disk by default, because the contents indexed in the database would be readable by anyone with a copy of it. An option turns it on, and the docs describe the trade-off.
- Unfinished uploads wait as plaintext in
FERRITE_TMP_PATHuntil they are complete, so that folder has to be on an encrypted volume. - The encrypted path has not been tested against a real S3 bucket. It is a plain PHP stream and should behave like any other blob, but that is unverified.
The code is in app/Support/Encryption, and the threat model and format are in docs/encryption.md.

