Skip to content

Argon2id.deriveKey gives segmentation fault for large parameter values #177

Open

Description

@elliotwutingfeng

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.

Activity

  1. elliotwutingfeng commented on Oct 19, 2024

    @elliotwutingfeng
    Author

    An alternative solution would be to use the hashlib package, which is able to handle the aforementioned KDF settings (10 iterations, 16 parallelism, and 1024 MiB memory).

  2. terrier989 commented on Nov 21, 2025

    @terrier989
    Member

    Thank you for the issue report! 👍 I'll look at this later.

  3. diogogfre94-ai commented on Aug 22, 2026

    @diogogfre94-ai

    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:

    10.10  10.15  10.11  10.12  10.11  10.06  10.11  10.08  10.14   (seconds)
    

    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

    1. getByteBuffer() allocates the block buffer with malloc and hands worker isolates only the raw address, which they rebuild with Pointer.fromAddress. The GC cannot see that reference.
    2. If a segment exceeds the 10 s deadline, the controlling isolate throws StateError('Segment processing timeout'). The worker is never told, and keeps writing.
    3. The finally in iterate() only schedules the kills — isolateFuture.then(... isolate.kill(...)) is not awaited, and Isolate.kill is itself asynchronous.
    4. Unwinding continues: deriveKeyBytesFromPrehashingDigest's finally sets _isBufferUsed = false, which disarms the guard in tryReleaseMemory(); deriveKey's finally then calls it and frees the buffer.
    5. glibc munmaps an allocation that size, so the region becomes unmapped. The still-running worker touches it and the process aborts.

    Typical crash:

    si_signo=Segmentation fault(11), si_code=SEGV_MAPERR(1), si_addr=0x7f7968700010
    isolate=argon2-0(...)
      pc ... [Optimized]   DartArgon2State.processBlock+0x575
      pc ... [Optimized]   DartArgon2State.processSegment+0x379
      pc ... [Unoptimized] DartArgon2StateImplFfi._segmentProcessingEntryPoint.<anonymous closure>
    

    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 raise RangeError. 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: 4 on 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: 0 on DartArgon2id (from package:cryptography/dart.dart) avoids it entirely:

    import 'package:cryptography/dart.dart';
    
    final algorithm = DartArgon2id(
      parallelism: 4,
      memory: 262144,
      iterations: 3,
      hashLength: 32,
      maxIsolates: 0, // no isolates -> heap Uint32List, no raw pointer, no deadline, no free()
    );

    With isolateCount == 0, getByteBuffer() takes the other branch — a GC-managed Uint32List — so the raw pointer, the 10 s deadline and the free() 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 (Python argon2-cffi and Node argon2) 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

    1. Await the isolate kills in iterate()'s finally before returning, so tryReleaseMemory() cannot race a live worker.
    2. Or never free on the timeout path — treat a timed-out state as poisoned and leak it, rather than freeing memory of unknown liveness.
    3. Have the worker acknowledge cancellation before the controller proceeds.
    4. Independently: make the deadline configurable and scale its default with 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.

  4. chris-coria commented on Nov 3, 2026

    @chris-coria

    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: cryptography 2.9.0 (argon2_impl_default.dart on master is byte-identical), Dart 3.13.7 stable, linux_x64. Unless noted, parameters are memory: 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.yaml needs only cryptography: 2.9.0.

    bin/repro.dart:

    // Usage: repro [maxIsolates] [memoryKiB]
    // Loops Argon2id with fixed dummy inputs so a pause lands mid-derivation.
    import 'package:cryptography/cryptography.dart';
    import 'package:cryptography/dart.dart';
    
    Future<void> main(List<String> args) async {
      final maxIsolates = args.isNotEmpty ? int.parse(args[0]) : null;
      final memory = args.length > 1 ? int.parse(args[1]) : 65536;
      final loops = args.length > 2 ? int.parse(args[2]) : 40;
      for (var i = 0; i < loops; i++) {
        final watch = Stopwatch()..start();
        final key = await DartArgon2id(
          memory: memory,
          iterations: 3,
          parallelism: 4,
          hashLength: 32,
          maxIsolates: maxIsolates,
        ).deriveKey(
          secretKey: SecretKeyData(List<int>.filled(12, 7)),
          nonce: List<int>.filled(16, 1),
        );
        final bytes = await key.extractBytes();
        print('#$i ${watch.elapsedMilliseconds} ms ${bytes.take(4).toList()}');
      }
    }
    dart compile exe bin/repro.dart -o repro
    ./repro & pid=$!; sleep 1; kill -STOP $pid; sleep 11; kill -CONT $pid; wait $pid; echo "exit=$?"

    Results, all from AOT executables:

    Run Result
    ./repro (default maxIsolates, 64 MiB) 6/6 crashed: SEGV_MAPERR, exit 134. Where the dump named an isolate, it was an argon2-N worker
    ./repro 0 (maxIsolates: 0, 64 MiB) 0/3 crashed; all 40 derivations finished, exit 0
    ./repro 8 8192 3000 (maxIsolates: 8, the default value; 8 MiB) 0/4 crashed, but 4/4 died with an uncaught StateError: Segment processing timeout, exit 255

    So 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):

    • 18 of 20 took about 0.9–1.0 s.
    • 2 of 20 took 40–42 s.

    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–7 Too many deoptimizations lines for DartArgon2StateImplFfi'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: 0 avoided the crash in every run above. Measured cost per derivation at 64 MiB in AOT, over 3 rounds of 6 runs each:

    CPUs Default maxIsolates: 0
    16 about 270 ms about 495 ms
    2 about 590 ms about 500 ms

    On the proposed fixes, Isolate.kill returns void, so option 1 would need an addOnExitListener registered 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.

  5. tganzerli commented on Nov 12, 2026

    @tganzerli

    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):

    1. On the Dart VM, Argon2id uses DartArgon2StateImplFfi. With isolateCount > 0, the block memory is allocated with malloc (lib/src/dart/argon2_impl_default.dart:105-110) and the worker isolate only receives the raw address (:293-295).
    2. Each segment has a hard-coded 10-second timeout (argon2_impl_default.dart:266-269, receivePort.first.timeout(const Duration(seconds: 10), ...)).
    3. When it fires, the StateError propagates; the finally in iterate() asks the isolates to die without waiting for them (:206-214, isolate.kill(...) inside isolateFuture.then), and deriveKey's finally calls tryReleaseMemory() (lib/src/dart/argon2.dart:110-111), which frees the native buffer immediately (argon2_impl_default.dart:225-236).
    4. The worker isolate is still inside processSegment / processBlock, now reading and writing freed memory (a buffer this large is usually mmap-backed, so free unmaps it) → SIGSEGV (SEGV_MAPERR), and the whole process dies.

    That matches the stack trace we saw in production:

    ===== CRASH =====
    si_signo=Segmentation fault(11), si_code=SEGV_MAPERR(1)
    isolate=argon2-0
    [Optimized] DartArgon2State.processBlock
    [Optimized] DartArgon2State.processSegment
    [Optimized] DartArgon2StateImplFfi._segmentProcessingEntryPoint.<anonymous closure>
    [Optimized] _RootZone.runUnaryGuarded
    ...
    [Optimized] _RawReceivePort._handleMessage
    

    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 with docker run --cpus=0.02. The process aborts with the stack above. Under the same conditions, a native Argon2id (libsodium's crypto_pwhash_argon2id) completes all 12.

    Possible fixes (not tested in the package):

    • don't free the buffer until every worker isolate has actually exited (wait for the onExit port after kill, or have the worker acknowledge before the owner calls free);
    • or let the worker own the allocation for its lifetime;
    • and make the per-segment timeout configurable (or remove it), since a slow segment is not an error by itself.

    As a workaround, DartArgon2id(..., maxIsolates: 0) avoids the isolates, the malloc and the timeout (at the cost of running on the calling isolate).

    Thanks for the package!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions