CVE-2023-48223: Fast jwt JWT Algorithm Confusion Vulnerability

MODERATE
Advisory Identifier: GHSA-c2ff-88x2-x9pg
CVSS 5.9
CWE-20
Published
Advisory Summary

CVE-2023-48223 is a MODERATE (CVSS 5.9) jwt algorithm confusion vulnerability (CWE-20: Improper Input Validation) affecting Fast jwt libraries in the npm ecosystem. The issue involves jwt algorithm confusion. Remediation is available by upgrading affected packages to version 3.3.2.

CVE-2023-48223 at a Glance

CVE Identifier CVE-2023-48223
GHSA Identifier GHSA-c2ff-88x2-x9pg
Severity MODERATE
CVSS v3.1 Base Score 5.9
CWE Classification CWE-20: Improper Input Validation
Affected Product Fast jwt
Package Ecosystem npm
Published Date
Last Updated

Security Impact

CVSS: 5.9

The security impact metrics below are parsed directly from the CVSS v3.1 vector string (CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N).

Attack Vector Network (AV:N)
Attack Complexity High (AC:H)
Privileges Required None (PR:N)
User Interaction None (UI:N)
Scope Unchanged (S:U)
Confidentiality None (C:N)
Integrity High (I:H)
Availability None (A:N)

How to Fix CVE-2023-48223

To remediate this vulnerability, upgrade all affected Fast jwt dependencies to a patched release. Both direct and transitive dependencies should be checked, as frameworks or security libraries may pull in vulnerable versions transitively.

fast-jwt fixed: 3.3.2
npm install fast-jwt@3.3.2
Verify Direct and Transitive Dependencies

Run the following command in your project directory to verify that all resolved dependencies use the patched release:

npm ls fast-jwt

How to Check if You Are Affected

To determine whether your Node.js application is affected by CVE-2023-48223, inspect your project dependencies using npm:

npm ls fast-jwt

Analyze the terminal output to locate any version of Fast jwt in your dependency tree. If any resolved version matches the vulnerable ranges listed in the table below (for example, versions earlier than 3.3.2), your application is affected.

Note: The npm ls fast-jwt command inspects dependencies declared in your package.json and lockfile; it does not perform automated runtime dynamic scanning.

Technical Details

Vulnerability Mechanism & Technical Analysis

This vulnerability is classified under CWE-20: Improper Input Validation, where the product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. In Fast jwt, software state validation or input boundaries are circumvented during processing. Review the official source advisory statement below for specific affected components, classes, and reproduction details.

Source Advisory Statement

### Summary The fast-jwt library does not properly prevent JWT algorithm confusion for all public key types. ### Details The 'publicKeyPemMatcher' in 'fast-jwt/src/crypto.js' does not properly match all common PEM formats for public keys. To exploit this vulnerability, an attacker needs to craft a malicious JWT token containing the HS256 algorithm, signed with the public RSA key of the victim application. This attack will only work if the victim application utilizes a public key containing the `BEGIN RSA PUBLIC KEY` header. ### PoC Take a server running the following code: ```javascript const express = require('express'); const { createSigner, createVerifier } = require('fast-jwt') const fs = require('fs'); const path = require('path'); const app = express(); const port = 3000; // Load the keys from the file const publicKeyPath = path.join(__dirname, 'public_key.pem'); const publicKey = fs.readFileSync(publicKeyPath, 'utf8'); const privateKeyPath = path.join(__dirname, 'key'); const privateKey = fs.readFileSync(privateKeyPath, 'utf8'); app.use(express.json()); // Endpoint to generate a JWT token with admin: False app.get('/generateToken', async (req, res) => { const payload = { admin: false, name: req.query.name }; const signSync = createSigner({ algorithm: 'RS256', key: privateKey }); const token = signSync(payload); res.json({ token }); }); // Middleware to verify the JWT token function verifyToken(req, res, next) { const token = req.query.token; const verifySync = createVerifier({ key: publicKey }); const payload = verifySync(token); req.decoded = payload; next(); } // Endpoint to check if you are the admin or not app.get('/checkAdmin', verifyToken, (req, res) => { res.json(req.decoded); }); app.listen(port, () => { console.log(`Server is running on port ${port}`); }); ``` Assume the server generated their keys like follows: ``` ssh-keygen -t rsa -b 2048 -m PEM ssh-keygen -f key.pub -e -m PEM > public_key.pem ``` **Public key recovery** First, an attacker needs to recover the public key from the server in any way possible. It is possible to extract this from just two JWT tokens as shown below. Grab two different JWT tokens and utilize the following tool: `https://github.com/silentsignal/rsa_sign2n/blob/release/standalone/jwt_forgery.py` ``` python3 jwt_forgery.py token1 token2 ``` The tool will generate 4 different public keys, all in different formats. Try the following for all 4 formats. **Algorithm confusion** Change the JWT to the HS256 algorithm and modify any of the contents to your liking at `https://jwt.io/`. Copy the resulting JWT token and use with the following tool: `https://github.com/ticarpi/jwt_tool` ``` python /opt/jwt_tool/jwt_tool.py --exploit k -pk public_key token ``` You will now get a resulting JWT token that is validly signed. ### Impact Applications using the RS256 algorithm, a public key with a `BEGIN RSA PUBLIC KEY` header, and calling the verify function without explicitly providing an algorithm, are vulnerable to this algorithm confusion attack which allows attackers to sign arbitrary payloads which will be accepted by the verifier. ### Solution Change https://github.com/nearform/fast-jwt/blob/master/src/crypto.js#L29 ```javascript const publicKeyPemMatcher = '-----BEGIN PUBLIC KEY-----' ``` to be regex: ```javascript const publicKeyPemMatcher = /^-----BEGIN( RSA)? PUBLIC KEY-----/ ```

CVE-2023-48223 Affected Fast jwt Versions

1 component(s)
Fixed Versions:
3.3.2
Product / Package Ecosystem Affected Versions Fixed Version
fast-jwt
npm
< 3.3.2
3.3.2

References

Frequently Asked Questions

What is CVE-2023-48223?
CVE-2023-48223 is a security vulnerability in Fast jwt involving JWT Algorithm Confusion under CWE-20: Improper Input Validation.
Which Fast jwt versions are affected?
Affected versions include releases prior to 3.3.2 across affected packages: fast-jwt.
What version fixes CVE-2023-48223?
Upgrading to 3.3.2 (or the latest patched release for your respective branch) resolves the vulnerability.
Is fast-jwt affected?
Yes, fast-jwt is affected in releases prior to 3.3.2. Upgrade your dependency to 3.3.2 or later.
What is the CVSS score of CVE-2023-48223?
CVE-2023-48223 has a CVSS v3.1 base score of 5.9 (MODERATE) with vector string CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N.
What CWE is associated with CVE-2023-48223?
CVE-2023-48223 is classified under CWE-20: Improper Input Validation (The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.).
How can I check npm dependencies for CVE-2023-48223?
Run the dependency tree command: 'npm ls fast-jwt'. This command lists direct and transitive dependencies in your build configuration so you can verify if a vulnerable version is resolved.
Machine-readable OSV JSON OSV v1.5 Schema
Normalized schema output
{
  "schema_version" : "1.4.0",
  "id" : "GHSA-c2ff-88x2-x9pg",
  "modified" : "2023-11-20T20:58:56Z",
  "published" : "2023-11-20T20:58:56Z",
  "aliases" : [ "CVE-2023-48223" ],
  "summary" : "JWT Algorithm Confusion",
  "details" : "### Summary\nThe fast-jwt library does not properly prevent JWT algorithm confusion for all public key types.\n\n### Details\nThe 'publicKeyPemMatcher' in 'fast-jwt/src/crypto.js' does not properly match all common PEM formats for public keys. To exploit this vulnerability, an attacker needs to craft a malicious JWT token containing the HS256 algorithm, signed with the public RSA key of the victim application. This attack will only work if the victim application utilizes a public key containing the `BEGIN RSA PUBLIC KEY` header.\n\n### PoC\nTake a server running the following code:\n```javascript\nconst express = require('express');\nconst { createSigner, createVerifier } = require('fast-jwt')\nconst fs = require('fs');\nconst path = require('path');\n\nconst app = express();\nconst port = 3000;\n\n// Load the keys from the file\nconst publicKeyPath = path.join(__dirname, 'public_key.pem');\nconst publicKey = fs.readFileSync(publicKeyPath, 'utf8');\nconst privateKeyPath = path.join(__dirname, 'key');\nconst privateKey = fs.readFileSync(privateKeyPath, 'utf8');\n\napp.use(express.json());\n\n// Endpoint to generate a JWT token with admin: False\napp.get('/generateToken', async (req, res) => {\n  const payload = { admin: false, name: req.query.name };\n\n  const signSync = createSigner({ algorithm: 'RS256', key: privateKey });\n  const token = signSync(payload);\n  \n  res.json({ token });\n});\n\n// Middleware to verify the JWT token\nfunction verifyToken(req, res, next) {\n  const token = req.query.token;\n\n  const verifySync = createVerifier({ key: publicKey });\n  const payload = verifySync(token);\n\n  req.decoded = payload;\n  next();\n}\n\n// Endpoint to check if you are the admin or not\napp.get('/checkAdmin', verifyToken, (req, res) => {\n  res.json(req.decoded);\n});\n\napp.listen(port, () => {\n  console.log(`Server is running on port ${port}`);\n});\n```\n\nAssume the server generated their keys like follows:\n```\nssh-keygen -t rsa -b 2048 -m PEM\nssh-keygen -f key.pub -e -m PEM > public_key.pem\n```\n\n**Public key recovery**\nFirst, an attacker needs to recover the public key from the server in any way possible. It is possible to extract this from just two JWT tokens as shown below.\nGrab two different JWT tokens and utilize the following tool: `https://github.com/silentsignal/rsa_sign2n/blob/release/standalone/jwt_forgery.py`\n```\npython3 jwt_forgery.py token1 token2\n```\nThe tool will generate 4 different public keys, all in different formats. Try the following for all 4 formats.\n\n**Algorithm confusion**\nChange the JWT to the HS256 algorithm and modify any of the contents to your liking at `https://jwt.io/`.\nCopy the resulting JWT token and use with the following tool: `https://github.com/ticarpi/jwt_tool`\n```\npython /opt/jwt_tool/jwt_tool.py --exploit k -pk public_key token\n```\nYou will now get a resulting JWT token that is validly signed.\n\n### Impact\nApplications using the RS256 algorithm, a public key with a `BEGIN RSA PUBLIC KEY` header, and calling the verify function without explicitly providing an algorithm, are vulnerable to this algorithm confusion attack which allows attackers to sign arbitrary payloads which will be accepted by the verifier.\n\n### Solution\n\nChange https://github.com/nearform/fast-jwt/blob/master/src/crypto.js#L29\n\n```javascript\nconst publicKeyPemMatcher = '-----BEGIN PUBLIC KEY-----'\n```\n\nto be regex: \n\n```javascript\nconst publicKeyPemMatcher = /^-----BEGIN( RSA)? PUBLIC KEY-----/\n```",
  "severity" : [ {
    "type" : "CVSS_V3",
    "score" : "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N"
  } ],
  "affected" : [ {
    "package" : {
      "ecosystem" : "npm",
      "name" : "fast-jwt"
    },
    "ranges" : [ {
      "type" : "ECOSYSTEM",
      "events" : [ {
        "introduced" : "0"
      }, {
        "fixed" : "3.3.2"
      } ]
    } ]
  } ],
  "references" : [ {
    "type" : "WEB",
    "url" : "https://github.com/nearform/fast-jwt/security/advisories/GHSA-c2ff-88x2-x9pg"
  }, {
    "type" : "ADVISORY",
    "url" : "https://nvd.nist.gov/vuln/detail/CVE-2023-48223"
  }, {
    "type" : "WEB",
    "url" : "https://github.com/nearform/fast-jwt/commit/15a6e92c9adb39acde41a9b11cec0cbde8ad763b"
  }, {
    "type" : "PACKAGE",
    "url" : "https://github.com/nearform/fast-jwt"
  }, {
    "type" : "WEB",
    "url" : "https://github.com/nearform/fast-jwt/blob/master/src/crypto.js#L29"
  }, {
    "type" : "WEB",
    "url" : "https://github.com/nearform/fast-jwt/releases/tag/v3.3.2"
  } ],
  "database_specific" : {
    "cwe_ids" : [ "CWE-20" ],
    "severity" : "MODERATE",
    "github_reviewed" : true,
    "github_reviewed_at" : "2023-11-20T20:58:56Z",
    "nvd_published_at" : "2023-11-20T18:15:07Z"
  }
}