Repository navigation
Open
Description
I am testing out some Dart cryptography libraries for deriving Argon2id keys with large parameter values, such as the maximum allowed settings in the Bitwarden password manager, which as of today are 10 iterations, 16 parallelism, and 1024 MiB memory.
The following leads to a segmentation fault. Running the script with --old_gen_heap_size=2g sometimes gives a segmentation fault, but sometimes it works.
import 'dart:convert';
import 'dart:typed_data';
import 'package:cryptography/cryptography.dart';
Future<void> main() async {
final Uint8List password = utf8.encode("passphrase");
final List<int> salt =
(await Sha256().hash(base64.decode("rNYWSe/wFO1k+Qxia0A96A=="))).bytes;
// Bitwarden maximum settings
final int kdfIterations = 10;
final int kdfParallelism = 16;
final int kdfMemory = 1024; // 1024 MiB
final Argon2id algorithm = Argon2id(
parallelism: kdfParallelism,
memory: kdfMemory * 1024,
iterations: kdfIterations,
hashLength: 32,
);
final SecretKey newSecretKey =
await algorithm.deriveKey(secretKey: SecretKey(password), nonce: salt);
final List<int> newSecretKeyBytes = await newSecretKey.extractBytes();
print('hashed password: $newSecretKeyBytes');
}Equivalent working program using pointycastle.
import 'dart:convert';
import 'dart:typed_data';
import 'package:pointycastle/digests/sha256.dart';
import 'package:pointycastle/key_derivators/argon2_native_int_impl.dart';
import 'package:pointycastle/pointycastle.dart';
Future<void> main() async {
final Uint8List password = utf8.encode("passphrase");
final Uint8List salt =
SHA256Digest().process(base64.decode("rNYWSe/wFO1k+Qxia0A96A=="));
// Bitwarden maximum settings
final int kdfIterations = 10;
final int kdfParallelism = 16;
final int kdfMemory = 1024; // 1024 MiB
final List<int> newSecretKeyBytes = (Argon2BytesGenerator()
..init(Argon2Parameters(Argon2Parameters.ARGON2_id, salt,
desiredKeyLength: 32,
iterations: kdfIterations,
memory: kdfMemory * 1024,
lanes: kdfParallelism)))
.process(Uint8List.fromList(password));
print('hashed password: $newSecretKeyBytes');
}Expected output for both programs:
hashed password: [207, 41, 183, 164, 139, 92, 97, 166, 115, 223, 111, 83, 7, 239, 193, 74, 180, 246, 103, 53, 177, 250, 203, 81, 148, 124, 62, 225, 215, 116, 170, 240]
I am aware that it is not advisable to set Argon2id KDF settings to such extreme values in either case, however, this may be worth some investigation.
Metadata
Metadata
Assignees
Labels
No labels
Activity
elliotwutingfeng commentedon Oct 19, 2024
An alternative solution would be to use the hashlib package, which is able to handle the aforementioned KDF settings (
10iterations,16parallelism, and1024 MiBmemory).terrier989 commentedon Nov 21, 2025
Thank you for the issue report! 👍 I'll look at this later.
diogogfre94-ai commentedon Aug 22, 2026
I hit this too, and I think I have the root cause. It is not memory exhaustion — it is a use-after-free, and it reproduces well below "large parameter values".
Evidence that pointed at the mechanism
Nine independent CI failures, same parameters (
parallelism: 4,memory: 262144(256 MiB),iterations: 3,hashLength: 32), on a 2-vCPU Linux runner. The interval between the start of the derivation and the crash was:Nine out of nine within 90 ms of each other. That is not resource pressure — it is the hardcoded
Duration(seconds: 10)in_sendSegmentsToIsolate(lib/src/dart/argon2_impl_default.dart).The mechanism
getByteBuffer()allocates the block buffer withmallocand hands worker isolates only the raw address, which they rebuild withPointer.fromAddress. The GC cannot see that reference.StateError('Segment processing timeout'). The worker is never told, and keeps writing.finallyiniterate()only schedules the kills —isolateFuture.then(... isolate.kill(...))is not awaited, andIsolate.killis itself asynchronous.deriveKeyBytesFromPrehashingDigest'sfinallysets_isBufferUsed = false, which disarms the guard intryReleaseMemory();deriveKey'sfinallythen calls it and frees the buffer.munmaps an allocation that size, so the region becomes unmapped. The still-running worker touches it and the process aborts.Typical crash:
Exit code 134 (SIGABRT). Sometimes two isolates die at once and the dump is truncated with
Aborting reentrant request for stack trace.Why it is not out-of-bounds indexing
Workers access the buffer through a typed-data view (
asTypedList), which the VM bounds-checks — an out-of-range index would raiseRangeError. A segfault through a bounds-checked view means the memory is no longer mapped.Why "large parameter values" is a red herring
Large parameters make it likelier by making segments slower, but nothing has to be large: the deadline only has to be missed once. At 256 MiB with
parallelism: 4on a 2-vCPU machine it happened in 9 of 72 runs (12.5%). On a fast, idle machine the same code never crashed, which is why it reads as random.Workaround that does not require leaving the package
Setting
maxIsolates: 0onDartArgon2id(frompackage:cryptography/dart.dart) avoids it entirely:With
isolateCount == 0,getByteBuffer()takes the other branch — a GC-managedUint32List— so the raw pointer, the 10 s deadline and thefree()all disappear.The digest is unchanged; I verified byte-for-byte against the isolate path at 8 MiB and 64 MiB (
parallelism: 4), and against independently generated Argon2id reference vectors (Pythonargon2-cffiand Nodeargon2) at 256 MiB / 3 iterations /parallelism: 4.Cost is a slowdown, and not a uniform one: at 8 MiB it was actually faster (163 ms → 70 ms, isolate startup dominates), while at 64 MiB it was ~1.9× slower (289 ms → 542 ms).
Possible fixes
iterate()'sfinallybefore returning, sotryReleaseMemory()cannot race a live worker.memory × iterations. On its own this only makes the race rarer, but a fixed 10 s is easy to miss on a loaded machine.Happy to open a PR for (1) if that is the direction you would prefer.
chris-coria commentedon Nov 3, 2026
I can confirm the root cause described in the comment above. Three things may add to it: a deterministic reproducer, confirmation that it also happens in AOT, and a JIT behavior that can cause the missed deadline at modest parameters.
Environment:
cryptography2.9.0 (argon2_impl_default.dartonmasteris byte-identical), Dart 3.13.7 stable,linux_x64. Unless noted, parameters arememory: 65536, iterations: 3, parallelism: 4, one of the RFC 9106 recommended options.Deterministic reproducer
The segment deadline keeps counting while the process is stopped, so a pause longer than 10 s triggers the bug even on a fast, idle machine.
pubspec.yamlneeds onlycryptography: 2.9.0.bin/repro.dart:Results, all from AOT executables:
./repro(defaultmaxIsolates, 64 MiB)SEGV_MAPERR, exit 134. Where the dump named an isolate, it was anargon2-Nworker./repro 0(maxIsolates: 0, 64 MiB)./repro 8 8192 3000(maxIsolates: 8, the default value; 8 MiB)StateError: Segment processing timeout, exit 255So this is not JIT-specific, and it needs no slow hardware. Any pause over 10 s during a derivation should be enough; I only tested
SIGSTOP. The same steps could serve as a regression test for a fix.Why the deadline can be missed in JIT at 64 MiB
On 2 CPUs (
taskset -c 0,1), I timed one derivation in each of 20 fresh JIT processes (dart run bin/repro.dart 8 65536 1):AOT took about 0.56 s in 5 of 5 runs on the same CPUs.
In a separate run of 14 JIT processes with
--trace_deoptimization --trace_failed_optimization_attempts, the 4 slow processes each logged 4–7Too many deoptimizationslines forDartArgon2StateImplFfi's_gb. The 10 fast processes logged none. In an earlier measurement, a slow process stayed slow for its later derivations.I saw the crash on a hosted CI runner under
dart test: tests in one suite were each taking over 2 minutes, one hit its test timeout, and the next test's derivation crashed about 10 s after it started. That timing fits the deadline, though the abandoned derivation from the timed-out test may also have been competing for CPU. My inference is that the deoptimization makes this reachable in ordinary JIT test runs, without unusually large parameters. I have not proven that link beyond this timing.Workaround and fix
maxIsolates: 0avoided the crash in every run above. Measured cost per derivation at 64 MiB in AOT, over 3 rounds of 6 runs each:maxIsolates: 0On the proposed fixes,
Isolate.killreturnsvoid, so option 1 would need anaddOnExitListenerregistered for each worker, with the free waiting until they have all exited. Since a process pause alone trips the deadline, a longer timeout would make this rarer but not remove it, so option 4 would need one of the others alongside it.tganzerli commentedon Nov 12, 2026
I believe I found the root cause of this crash, and it is not limited to large parameters: it also happens with the OWASP defaults (
memory: 19456,iterations: 2,parallelism: 1) whenever the CPU is slow enough.What happens (cryptography 2.9.0, Dart VM / AOT, Linux x64 and arm64):
Argon2idusesDartArgon2StateImplFfi. WithisolateCount > 0, the block memory is allocated withmalloc(lib/src/dart/argon2_impl_default.dart:105-110) and the worker isolate only receives the raw address (:293-295).argon2_impl_default.dart:266-269,receivePort.first.timeout(const Duration(seconds: 10), ...)).StateErrorpropagates; thefinallyiniterate()asks the isolates to die without waiting for them (:206-214,isolate.kill(...)insideisolateFuture.then), andderiveKey'sfinallycallstryReleaseMemory()(lib/src/dart/argon2.dart:110-111), which frees the native buffer immediately (argon2_impl_default.dart:225-236).processSegment/processBlock, now reading and writing freed memory (a buffer this large is usuallymmap-backed, sofreeunmaps it) →SIGSEGV (SEGV_MAPERR), and the whole process dies.That matches the stack trace we saw in production:
With large parameters (as in this issue), a single segment easily takes more than 10 s on a normal machine, which would explain why it "sometimes works". With small parameters, it takes a starved CPU: we hit it on a small cloud VM (1/8 vCPU, heavy CPU steal), where a login took ~30 s and the server crashed.
Reproduction with default parameters: run 12 concurrent
Argon2id(parallelism: 1, memory: 19456, iterations: 2, hashLength: 32).deriveKey(...)calls in an AOT binary inside a container limited withdocker run --cpus=0.02. The process aborts with the stack above. Under the same conditions, a native Argon2id (libsodium'scrypto_pwhash_argon2id) completes all 12.Possible fixes (not tested in the package):
onExitport afterkill, or have the worker acknowledge before the owner callsfree);As a workaround,
DartArgon2id(..., maxIsolates: 0)avoids the isolates, themallocand the timeout (at the cost of running on the calling isolate).Thanks for the package!