DEV Community

Adel ZEMZEMI
Adel ZEMZEMI

Posted on Originally published at adelzemzemi.github.io

Your encrypted localStorage values can be swapped

I maintain a small library that encrypts what a web app keeps in localStorage. It uses AES-256-GCM, so a stored value that has been modified is rejected rather than returned. For a year I read that sentence as "the stored data cannot be tampered with".

It can. Not by changing a value: by moving one.

The attack

Two values, same password, two keys:

import { SecureStorage, MemoryStorage, AesGcmEncryptor } from '@azemzemi/cryptobox';

const backend = new MemoryStorage();
const storage = new SecureStorage(backend, new AesGcmEncryptor(), { bindToKey: false });

await storage.setSecure('role:guest', { admin: false }, password);
await storage.setSecure('role:admin', { admin: true }, password);
Enter fullscreen mode Exit fullscreen mode

Now play the attacker. You do not know the password. You cannot read either value, and you cannot forge a new one. You can only write to the store, so you copy one ciphertext over the other:

await backend.setItem('role:guest', await backend.getItem('role:admin'));

await storage.getSecure('role:guest', password); // { admin: true }
Enter fullscreen mode Exit fullscreen mode

No error. The ciphertext is authentic: it was produced with the right key and no bit of it changed. GCM did its job. The library returned a value that is perfectly valid and sits in the wrong place.

{ bindToKey: false } above reproduces what version 1 did everywhere. Nothing in the ciphertext knew which storage key it belonged to.

Who can write to your storage without your password

This is the right question to ask before caring. An attacker who runs script in your page (XSS, a compromised dependency) does not need this trick: they see the password when it is typed and the plaintext when it is decrypted. No storage encryption helps there.

The swap matters for the cases storage encryption is actually for, where someone reaches the bytes but not the running application:

  • a copied or restored browser profile,
  • a synced storage area or a backup,
  • a shared device,
  • a server-side key-value store or a database dump, if you use the same format there.

In all of them the promise "they cannot read it and they cannot change it" was only half true. They could rearrange it.

The fix: tell the cipher where the value lives

AES-GCM takes a second input next to the plaintext, the additional authenticated data. It is not encrypted and not stored. It is mixed into the authentication tag, and decryption fails unless the reader supplies exactly the same bytes.

So the storage key goes in there:

// write
crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: header + 'role:admin' }, key, data);

// read, under the key the value was found at
crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData: header + 'role:guest' }, key, data);
// throws: the tag does not match
Enter fullscreen mode Exit fullscreen mode

The ciphertext is the same length as before. The binding costs nothing to store, because the reader already knows the key it is reading from.

With the default settings in version 2, the same swap ends differently:

const storage = new SecureStorage(backend, new AesGcmEncryptor());

// same writes, same copy
await storage.getSecure('role:guest', password); // CryptoBoxError: DECRYPTION_FAILED
Enter fullscreen mode Exit fullscreen mode

The same mechanism authenticates the envelope header, which records the format version and the PBKDF2 iteration count. Lowering the count in a stored value, to make the password cheaper to guess later, now breaks the tag too.

What it still does not do

Binding to the key stops a value from being moved. It does not stop these:

  • Rollback. Yesterday's value for the same key, put back in place, still decrypts. The format has no notion of freshness. If that matters, keep a counter or a timestamp inside the payload.
  • Deletion. Whoever can write can also erase. Tampering is detected, not prevented.
  • Old data. Values written by version 1 carry no binding. They stay movable until you rewrite them, and the library keeps accepting them until you tell it to stop. Migration is one call per key, then one option to close the door.

And the library has not been audited by a third party. What it has instead is a second implementation: the test suite writes and reads the same format with OpenSSL through node:crypto, in both directions, and a set of frozen ciphertexts that must keep decrypting forever.

Try it

There is a page where you can do this to your own browser: store a value, look at what localStorage holds, then read it back with the wrong password, after flipping one bit, and after moving it to another key.

If you encrypt anything keyed by a name, an id or a path, check what your ciphertext knows about where it lives. Mine knew nothing.

Top comments (5)

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

The header is authenticated, but the iteration count in it gets used before the tag is checked. I bumped it to 5,000,000 on a stored value with 2.0.0: the read still fails with DECRYPTION_FAILED, but takes 2.3s instead of 270ms. A read-side cap at the write count would stop that.

Collapse
 
adelzemzemi profile image
Adel ZEMZEMI •

You're right, and thanks for measuring it. The count has to be read before the tag can vouch for it, and the only bound in 2.0.0 is the 5,000,000 ceiling. I reproduced it: a failing read goes from 73 ms to about 580 ms here.

The fix is in github.com/adelzemzemi/CryptoBox/p... and will ship as 2.1.0: a maxIterations option on the reader. An envelope declaring more is refused before any key derivation.

I kept it opt-in rather than defaulting to the write count: a store can hold values written with a higher count than the one configured today, and those would stop decrypting in a minor release.

Collapse
 
adelzemzemi profile image
Adel ZEMZEMI •

2.1.0 is out with the cap: github.com/adelzemzemi/CryptoBox/r...

new AesGcmEncryptor({ maxIterations: 600_000 }) refuses an inflated count with INVALID_ITERATIONS before deriving anything. Thanks again for the report.

Thread Thread
 
sunnatulla_dev profile image
Sunnatulla •

Tried 2.1.0 with maxIterations 600k: the inflated header gets INVALID_ITERATIONS, nice. With allowLegacy left on, the refusal still costs about 50 ms here, because the same bytes get retried as a headerless legacy value at 100k. allowLegacy: false refuses in 1 ms. Bounded, but maybe worth a line in the docs.

Thread Thread
 
adelzemzemi profile image
Adel ZEMZEMI •

Confirmed, and my "before deriving anything" above was too strong. The cap only applies to the count a version 2 header declares. With allowLegacy on, the same bytes are still a candidate headerless 1.x value, and that one is tried at its fixed 100,000 iterations before the refusal. So one cheap derivation remains, about a sixth of a normal read, and none with allowLegacy: false.

I kept that attempt on purpose: skipping it would make a genuine 1.x value unreadable whenever its first bytes happen to look like an oversized header.

The README, SECURITY.md and the option's doc comment now say exactly this, in github.com/adelzemzemi/CryptoBox/p..., which ships as 2.1.1. Thanks for checking the fix as carefully as the bug.