GHSA-C2FF-88X2-X9PG

Vulnerability from github – Published: 2023-11-20 20:58 – Updated: 2023-11-20 20:58
VLAI
Summary
JWT Algorithm Confusion
Details

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:

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

const publicKeyPemMatcher = '-----BEGIN PUBLIC KEY-----'

to be regex:

const publicKeyPemMatcher = /^-----BEGIN( RSA)? PUBLIC KEY-----/
Show details on source website

{
  "affected": [
    {
      "package": {
        "ecosystem": "npm",
        "name": "fast-jwt"
      },
      "ranges": [
        {
          "events": [
            {
              "introduced": "0"
            },
            {
              "fixed": "3.3.2"
            }
          ],
          "type": "ECOSYSTEM"
        }
      ]
    }
  ],
  "aliases": [
    "CVE-2023-48223"
  ],
  "database_specific": {
    "cwe_ids": [
      "CWE-20"
    ],
    "github_reviewed": true,
    "github_reviewed_at": "2023-11-20T20:58:56Z",
    "nvd_published_at": "2023-11-20T18:15:07Z",
    "severity": "MODERATE"
  },
  "details": "### Summary\nThe fast-jwt library does not properly prevent JWT algorithm confusion for all public key types.\n\n### Details\nThe \u0027publicKeyPemMatcher\u0027 in \u0027fast-jwt/src/crypto.js\u0027 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(\u0027express\u0027);\nconst { createSigner, createVerifier } = require(\u0027fast-jwt\u0027)\nconst fs = require(\u0027fs\u0027);\nconst path = require(\u0027path\u0027);\n\nconst app = express();\nconst port = 3000;\n\n// Load the keys from the file\nconst publicKeyPath = path.join(__dirname, \u0027public_key.pem\u0027);\nconst publicKey = fs.readFileSync(publicKeyPath, \u0027utf8\u0027);\nconst privateKeyPath = path.join(__dirname, \u0027key\u0027);\nconst privateKey = fs.readFileSync(privateKeyPath, \u0027utf8\u0027);\n\napp.use(express.json());\n\n// Endpoint to generate a JWT token with admin: False\napp.get(\u0027/generateToken\u0027, async (req, res) =\u003e {\n  const payload = { admin: false, name: req.query.name };\n\n  const signSync = createSigner({ algorithm: \u0027RS256\u0027, 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(\u0027/checkAdmin\u0027, verifyToken, (req, res) =\u003e {\n  res.json(req.decoded);\n});\n\napp.listen(port, () =\u003e {\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 \u003e 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 = \u0027-----BEGIN PUBLIC KEY-----\u0027\n```\n\nto be regex: \n\n```javascript\nconst publicKeyPemMatcher = /^-----BEGIN( RSA)? PUBLIC KEY-----/\n```",
  "id": "GHSA-c2ff-88x2-x9pg",
  "modified": "2023-11-20T20:58:56Z",
  "published": "2023-11-20T20:58:56Z",
  "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"
    }
  ],
  "schema_version": "1.4.0",
  "severity": [
    {
      "score": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N",
      "type": "CVSS_V3"
    }
  ],
  "summary": "JWT Algorithm Confusion"
}



Log in or create an account to share your comment.




Tags
Taxonomy of the tags.


Loading…

Loading…

Loading…

Drag nodes to arrange them. Double-click a related vulnerability to open it, or a source to visit its link. The Physics button on the left tunes the layout and the simulation; the legend at the bottom left hides or shows nodes by kind and by sighting type.

Forecast uses a logistic model when the trend is rising, or an exponential decay model when the trend is falling. Fitted via linearized least squares.

Sightings

Author Source Type Date Other

Nomenclature

  • Seen: The vulnerability was mentioned, discussed, or observed by the user.
  • Confirmed: The vulnerability has been validated from an analyst's perspective.
  • Published Proof of Concept: A public proof of concept is available for this vulnerability.
  • Exploited: The vulnerability was observed as exploited by the user who reported the sighting.
  • Patched: The vulnerability was observed as successfully patched by the user who reported the sighting.
  • Not exploited: The vulnerability was not observed as exploited by the user who reported the sighting.
  • Not confirmed: The user expressed doubt about the validity of the vulnerability.
  • Not patched: The vulnerability was not observed as successfully patched by the user who reported the sighting.
Vulnerability timeline

Sightings and recorded dates, grouped by day · UTC

JSON
How durations are calculated

Following the VTEM framework (Black Hat USA 2015), time to patch starts when the vendor or a coordinator was informed, total time to patch at discovery, and disclosure to patch at public disclosure; vendor response time runs from the report to its acknowledgement. Time to exploit and time unpatched start at the earliest discovery or report, falling back to public disclosure. Unpatched time ends at the first recorded patch, or the calculation time when no patch is recorded. Exploitation to patch shows the interval between those two events; a published proof of concept is a public exploit, not exploitation. The method is described in a publication.

Each result shows its source dates. A negative interval means the end event came first; when date-only inputs leave the order open, the result says so. Date-only inputs are approximate. The earliest evidence wins: KEV report dates and sightings are labelled as such. Records describing another vulnerability are listed but never calculated from, and a PoC alone does not establish exploitation. Missing patch evidence does not prove that no patch exists. Filters below change the event list only.

Events included in the timeline

Loading timeline…


    Loading…

    Loading…

    Loading…

    Related by attack behaviour

    Vulnerabilities whose description is nearest to this one in the vector space of the CIRCL/vulnerability-attack-technique-biencoder model. This is a similarity search over the bi-encoder space (plain cosine), not a classification, and it has no measured accuracy.