CVE-2022-36083: Excessive Iteration (CWE-834)
value: JOSE is "JSON Web Almost Everything" - JWA, JWS, JWE, JWT, JWK, JWKS with no dependencies using runtime's native crypto in Node.js, Browser, Cloudflare Workers, Electron, and Deno. The PBKDF2-based JWE key management algorithms expect a JOSE Header Parameter named `p2c` PBES2 Count, which determines how many PBKDF2 iterations must be executed in order to derive a CEK wrapping key. The purpose of this parameter is to intentionally slow down the key derivation function in order to make password brute-force and dictionary attacks more expensive. This makes the PBES2 algorithms unsuitable for situations where the JWE is coming from an untrusted source: an adversary can intentionally pick an extremely high PBES2 Count value, that will initiate a CPU-bound computation that may take an unreasonable amount of time to finish. Under certain conditions, it is possible to have the user's environment consume unreasonable amount of CPU time. The impact is limited only to users utilizing the JWE decryption APIs with symmetric secrets to decrypt JWEs from untrusted parties who do not limit the accepted JWE Key Management Algorithms (`alg` Header Parameter) using the `keyManagementAlgorithms` (or `algorithms` in v1.x) decryption option or through other means. The `v1.28.2`, `v2.0.6`, `v3.20.4`, and `v4.9.2` releases limit the maximum PBKDF2 iteration count to `10000` by default. It is possible to adjust this limit with a newly introduced `maxPBES2Count` decryption option. If users are unable to upgrade their required library version, they have two options depending on whether they expect to receive JWEs using any of the three PBKDF2-based JWE key management algorithms. They can use the `keyManagementAlgorithms` decryption option to disable accepting PBKDF2 altogether, or they can inspect the JOSE Header prior to using the decryption API and limit the PBKDF2 iteration count (`p2c` Header Parameter).
CWE description: The product performs an iteration or loop without sufficiently limiting the number of times that the loop is executed.
CVSS v3 base score: 5.3
Published: 2022-09-07T22:15Z
Repository: https://github.com/panva/jose
Language: TypeScript
Files changed: src/jwe/flattened/decrypt.ts, src/lib/decrypt_key_management.ts, src/types.d.ts, test/jwe/flattened.decrypt.test.mjs
Commit date: 2022-09-01 09:47:26 +0200
Commit message: fix: limit default PBES2 alg's computational expense

Also adds an option to opt-in to higher computation expense.

Diff: diff --git a/src/jwe/flattened/decrypt.ts b/src/jwe/flattened/decrypt.ts
index 777e9e57..afb621a1 100644
--- a/src/jwe/flattened/decrypt.ts
+++ b/src/jwe/flattened/decrypt.ts
@@ -186,13 +186,13 @@ export async function flattenedDecrypt(
     resolvedKey = true
   }
 
   let cek: KeyLike | Uint8Array
   try {
-    cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader)
+    cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options)
   } catch (err) {
-    if (err instanceof TypeError) {
+    if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
       throw err
     }
     // https://www.rfc-editor.org/rfc/rfc7516#section-11.5
     // To mitigate the attacks described in RFC 3218, the
     // recipient MUST NOT distinguish between format, padding, and length
diff --git a/src/lib/decrypt_key_management.ts b/src/lib/decrypt_key_management.ts
index 3e4f9068..72793065 100644
--- a/src/lib/decrypt_key_management.ts
+++ b/src/lib/decrypt_key_management.ts
@@ -2,11 +2,11 @@ import { unwrap as aesKw } from '../runtime/aeskw.js'
 import * as ECDH from '../runtime/ecdhes.js'
 import { decrypt as pbes2Kw } from '../runtime/pbes2kw.js'
 import { decrypt as rsaEs } from '../runtime/rsaes.js'
 import { decode as base64url } from '../runtime/base64url.js'
 
-import type { JWEHeaderParameters, KeyLike, JWK } from '../types.d'
+import type { DecryptOptions, JWEHeaderParameters, KeyLike, JWK } from '../types.d'
 import { JOSENotSupported, JWEInvalid } from '../util/errors.js'
 import { bitLength as cekLength } from '../lib/cek.js'
 import { importJWK } from '../key/import.js'
 import checkKeyType from './check_key_type.js'
 import isObject from './is_object.js'
@@ -15,10 +15,11 @@ import { unwrap as aesGcmKw } from './aesgcmkw.js'
 async function decryptKeyManagement(
   alg: string,
   key: KeyLike | Uint8Array,
   encryptedKey: Uint8Array | undefined,
   joseHeader: JWEHeaderParameters,
+  options?: DecryptOptions,
 ): Promise<KeyLike | Uint8Array> {
   checkKeyType(alg, key, 'decrypt')
 
   switch (alg) {
     case 'dir': {
@@ -94,10 +95,15 @@ async function decryptKeyManagement(
       if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing')
 
       if (typeof joseHeader.p2c !== 'number')
         throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`)
 
+      const p2cLimit = options?.maxPBES2Count || 10_000
+
+      if (joseHeader.p2c > p2cLimit)
+        throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`)
+
       if (typeof joseHeader.p2s !== 'string')
         throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`)
 
       return pbes2Kw(alg, key, encryptedKey, joseHeader.p2c, base64url(joseHeader.p2s))
     }
diff --git a/src/types.d.ts b/src/types.d.ts
index cc7f2c2d..2cc937eb 100644
--- a/src/types.d.ts
+++ b/src/types.d.ts
@@ -399,10 +399,17 @@ export interface DecryptOptions extends CritOption {
   /**
    * In a browser runtime you have to provide an implementation for Inflate Raw when you expect JWEs
    * with compressed plaintext.
    */
   inflateRaw?: InflateFunction
+
+  /**
+   * (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter
+   * value. The PBKDF2 iteration count defines the algorithm's computational expense. By default
+   * this value is set to 10000.
+   */
+  maxPBES2Count?: number
 }
 
 /** JWE Deflate option. */
 export interface DeflateOption {
   /**
diff --git a/test/jwe/flattened.decrypt.test.mjs b/test/jwe/flattened.decrypt.test.mjs
index a00350d5..e3f09604 100644
--- a/test/jwe/flattened.decrypt.test.mjs
+++ b/test/jwe/flattened.decrypt.test.mjs
@@ -1,8 +1,8 @@
 import test from 'ava'
 import * as crypto from 'crypto'
-import { root } from '../dist.mjs'
+import { root, conditional } from '../dist.mjs'
 
 const { FlattenedEncrypt, flattenedDecrypt, base64url } = await import(root)
 
 test.before(async (t) => {
   const encode = TextEncoder.prototype.encode.bind(new TextEncoder())
@@ -175,12 +175,12 @@ test('JWE format validation', async (t) => {
   {
     const jwe = { ...fullJwe }
     jwe.encrypted_key = 'foo'
 
     await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), {
-      message: 'decryption operation failed',
-      code: 'ERR_JWE_DECRYPTION_FAILED',
+      message: 'Encountered unexpected JWE Encrypted Key',
+      code: 'ERR_JWE_INVALID',
     })
   }
 })
 
 test('AES CBC + HMAC', async (t) => {
@@ -237,5 +237,17 @@ test('decrypt empty data (CBC)', async (t) => {
   t.is(base64url.decode(jwe.ciphertext).byteLength, 16)
 
   const { plaintext } = await flattenedDecrypt(jwe, new Uint8Array(32))
   t.is(plaintext.byteLength, 0)
 })
+
+conditional({ electron: 0 })('decrypt PBES2 p2c limit', async (t) => {
+  const jwe = await new FlattenedEncrypt(new Uint8Array(0))
+    .setProtectedHeader({ alg: 'PBES2-HS256+A128KW', enc: 'A128CBC-HS256' })
+    .setKeyManagementParameters({ p2c: 2049 })
+    .encrypt(new Uint8Array(32))
+
+  await t.throwsAsync(flattenedDecrypt(jwe, new Uint8Array(32), { maxPBES2Count: 2048 }), {
+    message: 'JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds',
+    code: 'ERR_JWE_INVALID',
+  })
+})

Vulnerable code:     cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader)
    if (err instanceof TypeError) {
import type { JWEHeaderParameters, KeyLike, JWK } from '../types.d'
import { root } from '../dist.mjs'
      message: 'decryption operation failed',
      code: 'ERR_JWE_DECRYPTION_FAILED',
Fixed code:     cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options)
    if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
import type { DecryptOptions, JWEHeaderParameters, KeyLike, JWK } from '../types.d'
  options?: DecryptOptions,
      const p2cLimit = options?.maxPBES2Count || 10_000

      if (joseHeader.p2c > p2cLimit)
        throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`)


  /**
   * (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter
   * value. The PBKDF2 iteration count defines the algorithm's computational expense. By default
   * this value is set to 10000.
   */
  maxPBES2Count?: number
import { root, conditional } from '../dist.mjs'
      message: 'Encountered unexpected JWE Encrypted Key',
      code: 'ERR_JWE_INVALID',

conditional({ electron: 0 })('decrypt PBES2 p2c limit', async (t) => {
  const jwe = await new FlattenedEncrypt(new Uint8Array(0))
    .setProtectedHeader({ alg: 'PBES2-HS256+A128KW', enc: 'A128CBC-HS256' })
    .setKeyManagementParameters({ p2c: 2049 })
    .encrypt(new Uint8Array(32))

  await t.throwsAsync(flattenedDecrypt(jwe, new Uint8Array(32), { maxPBES2Count: 2048 }), {
    message: 'JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds',
    code: 'ERR_JWE_INVALID',
  })
})