From 3ada567f5d0a0c4f9054867a55582273acd82e20 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 31 Oct 2026 05:47:55 +0000 Subject: [PATCH 1/4] Initial plan From 8c9a5ae5fb65df0b293d115b9221c030b45b0b30 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:39:53 +0000 Subject: [PATCH 2/4] JavaScript: extend js/session-fixation, add js/rate-limit-spoofable-key and missing-rate-limiting regression tests Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .../RateLimitSpoofableKey.qhelp | 55 ++++++++ .../RateLimitSpoofableKey.ql | 129 ++++++++++++++++++ .../examples/RateLimitSpoofableKeyBad.js | 11 ++ .../examples/RateLimitSpoofableKeyGood.js | 12 ++ .../src/SessionFixation/SessionFixation.qhelp | 44 ++++++ .../src/SessionFixation/SessionFixation.ql | 61 +++++++++ .../examples/SessionFixationBad.js | 21 +++ .../examples/SessionFixationGood.js | 23 ++++ ...6-10-31-session-fixation-rate-limit-key.md | 6 + .../MissingRateLimiting.expected | 3 + .../MissingRateLimiting.qlref | 2 + .../test/MissingRateLimiting/goatlin/app.js | 8 ++ .../goatlin/middleware/auth.js | 17 +++ .../goatlin/models/account.js | 8 ++ .../goatlin/routes/accounts.js | 16 +++ .../test/MissingRateLimiting/goof/app.js | 13 ++ .../MissingRateLimiting/goof/mongoose-db.js | 9 ++ .../test/MissingRateLimiting/goof/routes.js | 18 +++ .../nodegoat/routes/index.js | 12 ++ .../nodegoat/routes/session.js | 24 ++++ .../MissingRateLimiting/nodegoat/server.js | 11 ++ .../MissingRateLimiting/nodegoat/user-dao.js | 12 ++ .../test/MissingRateLimiting/package.json | 4 + .../RateLimitSpoofableKey.expected | 35 +++++ .../RateLimitSpoofableKey.qlref | 2 + .../test/RateLimitSpoofableKey/limiters.js | 43 ++++++ .../test/RateLimitSpoofableKey/package.json | 4 + .../test/RateLimitSpoofableKey/server.ts | 20 +++ .../RateLimitSpoofableKey.expected | 8 ++ .../RateLimitSpoofableKey.qlref | 2 + .../RateLimitSpoofableKeyTrustedProxy/app.js | 19 +++ .../package.json | 4 + .../SessionFixation/SessionFixation.expected | 2 + .../SessionFixation/SessionFixation.qlref | 2 + .../custom/test/SessionFixation/goof/app.js | 9 ++ .../test/SessionFixation/goof/routes.js | 43 ++++++ .../SessionFixation/nodegoat/routes/index.js | 13 ++ .../nodegoat/routes/session.js | 34 +++++ .../test/SessionFixation/nodegoat/server.js | 13 ++ .../test/SessionFixation/nodegoat/user-dao.js | 12 ++ .../custom/test/SessionFixation/package.json | 4 + languages/javascript/custom/test/qlpack.yml | 1 + 42 files changed, 789 insertions(+) create mode 100644 languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.qhelp create mode 100644 languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.ql create mode 100644 languages/javascript/custom/src/RateLimitSpoofableKey/examples/RateLimitSpoofableKeyBad.js create mode 100644 languages/javascript/custom/src/RateLimitSpoofableKey/examples/RateLimitSpoofableKeyGood.js create mode 100644 languages/javascript/custom/src/SessionFixation/SessionFixation.qhelp create mode 100644 languages/javascript/custom/src/SessionFixation/SessionFixation.ql create mode 100644 languages/javascript/custom/src/SessionFixation/examples/SessionFixationBad.js create mode 100644 languages/javascript/custom/src/SessionFixation/examples/SessionFixationGood.js create mode 100644 languages/javascript/custom/src/change-notes/2026-10-31-session-fixation-rate-limit-key.md create mode 100644 languages/javascript/custom/test/MissingRateLimiting/MissingRateLimiting.expected create mode 100644 languages/javascript/custom/test/MissingRateLimiting/MissingRateLimiting.qlref create mode 100644 languages/javascript/custom/test/MissingRateLimiting/goatlin/app.js create mode 100644 languages/javascript/custom/test/MissingRateLimiting/goatlin/middleware/auth.js create mode 100644 languages/javascript/custom/test/MissingRateLimiting/goatlin/models/account.js create mode 100644 languages/javascript/custom/test/MissingRateLimiting/goatlin/routes/accounts.js create mode 100644 languages/javascript/custom/test/MissingRateLimiting/goof/app.js create mode 100644 languages/javascript/custom/test/MissingRateLimiting/goof/mongoose-db.js create mode 100644 languages/javascript/custom/test/MissingRateLimiting/goof/routes.js create mode 100644 languages/javascript/custom/test/MissingRateLimiting/nodegoat/routes/index.js create mode 100644 languages/javascript/custom/test/MissingRateLimiting/nodegoat/routes/session.js create mode 100644 languages/javascript/custom/test/MissingRateLimiting/nodegoat/server.js create mode 100644 languages/javascript/custom/test/MissingRateLimiting/nodegoat/user-dao.js create mode 100644 languages/javascript/custom/test/MissingRateLimiting/package.json create mode 100644 languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.expected create mode 100644 languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.qlref create mode 100644 languages/javascript/custom/test/RateLimitSpoofableKey/limiters.js create mode 100644 languages/javascript/custom/test/RateLimitSpoofableKey/package.json create mode 100644 languages/javascript/custom/test/RateLimitSpoofableKey/server.ts create mode 100644 languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/RateLimitSpoofableKey.expected create mode 100644 languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/RateLimitSpoofableKey.qlref create mode 100644 languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/app.js create mode 100644 languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/package.json create mode 100644 languages/javascript/custom/test/SessionFixation/SessionFixation.expected create mode 100644 languages/javascript/custom/test/SessionFixation/SessionFixation.qlref create mode 100644 languages/javascript/custom/test/SessionFixation/goof/app.js create mode 100644 languages/javascript/custom/test/SessionFixation/goof/routes.js create mode 100644 languages/javascript/custom/test/SessionFixation/nodegoat/routes/index.js create mode 100644 languages/javascript/custom/test/SessionFixation/nodegoat/routes/session.js create mode 100644 languages/javascript/custom/test/SessionFixation/nodegoat/server.js create mode 100644 languages/javascript/custom/test/SessionFixation/nodegoat/user-dao.js create mode 100644 languages/javascript/custom/test/SessionFixation/package.json diff --git a/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.qhelp b/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.qhelp new file mode 100644 index 00000000..799bb250 --- /dev/null +++ b/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.qhelp @@ -0,0 +1,55 @@ + + + + +

+Rate limiters such as express-rate-limit and express-slow-down count +requests per client, using a key computed by the keyGenerator option. If the key is +taken from a value that the client controls, such as the X-Forwarded-For or +X-Real-IP request header, a client can send a different value with each request and +is never limited. This allows, for example, brute-force attacks on passwords, one-time codes or +password-reset answers. +

+

+The same applies to req.ip and req.ips when the Express application +trusts all proxies (app.enable('trust proxy') or +app.set('trust proxy', true)), because Express then takes the client address from the +left-most, client-supplied, entry of the X-Forwarded-For header. +

+
+ + +

+Do not derive rate-limiting keys from request headers. Use req.ip and configure the +Express trust proxy setting to trust only the proxies that are actually in front of +the application (for example a fixed number of hops, or specific addresses). If a reverse proxy +overwrites a client address header, make sure the application can't be reached without that +proxy before relying on the header. +

+
+ + +

+In the following example, all proxies are trusted and the limiter is keyed on the raw +X-Forwarded-For header, falling back to req.ip. Both values are chosen +by the client, so the limit can be evaded by changing the header on every request. +

+ + +

+In the following example, only the single reverse proxy in front of the application is trusted, +so req.ip is the address of the client as seen by that proxy. +

+ +
+ + +
  • Express: Express behind proxies.
  • +
  • express-rate-limit: Troubleshooting proxy issues.
  • +
  • OWASP: Blocking Brute Force Attacks.
  • +
  • Common Weakness Enumeration: CWE-307.
  • +
  • Common Weakness Enumeration: CWE-348.
  • +
    +
    diff --git a/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.ql b/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.ql new file mode 100644 index 00000000..4ca931b7 --- /dev/null +++ b/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.ql @@ -0,0 +1,129 @@ +/** + * @name Rate limiter keyed on a spoofable client address + * @description A rate limiter that identifies clients by a value the client controls, such as + * the `X-Forwarded-For` header, can be bypassed by sending a different value with + * each request. + * @kind path-problem + * @problem.severity warning + * @security-severity 5.3 + * @precision medium + * @id js/rate-limit-spoofable-key + * @tags security + * external/cwe/cwe-307 + * external/cwe/cwe-348 + */ + +import javascript + +/** Gets the name of a rate-limiting package whose options take a `keyGenerator` function. */ +private string rateLimiterPackage() { result = ["express-rate-limit", "express-slow-down"] } + +/** A call that creates an `express-rate-limit` (or `express-slow-down`) middleware. */ +class RateLimiterCreation extends DataFlow::InvokeNode { + RateLimiterCreation() { + exists(API::Node mod | mod = API::moduleImport(rateLimiterPackage()) | + this = [mod, mod.getMember(["rateLimit", "slowDown", "default"])].getAnInvocation() + ) + } + + /** Gets the function used by this rate limiter to compute the key that identifies a client. */ + DataFlow::FunctionNode getKeyGenerator() { + result = this.getOptionArgument(0, "keyGenerator").getALocalSource() + } +} + +/** Gets a reference to the request object passed to the key generator `keyGen`. */ +private DataFlow::SourceNode keyGeneratorRequest( + DataFlow::FunctionNode keyGen, DataFlow::TypeTracker t +) { + t.start() and + keyGen = any(RateLimiterCreation c).getKeyGenerator() and + result = keyGen.getParameter(0) + or + exists(DataFlow::TypeTracker t2 | result = keyGeneratorRequest(keyGen, t2).track(t2, t)) +} + +/** Gets a reference to the request object passed to the key generator `keyGen`. */ +private DataFlow::SourceNode keyGeneratorRequest(DataFlow::FunctionNode keyGen) { + result = keyGeneratorRequest(keyGen, DataFlow::TypeTracker::end()) +} + +/** Gets the lower-case name of a request header that conventionally carries a client IP address. */ +private string clientIpHeader() { + result = + [ + "x-forwarded-for", "x-real-ip", "forwarded", "forwarded-for", "x-forwarded", "x-client-ip", + "true-client-ip", "cf-connecting-ip", "fastly-client-ip", "x-cluster-client-ip" + ] +} + +/** + * Holds if the application trusts any number of proxies (`app.enable('trust proxy')` or + * `app.set('trust proxy', true)`), so that `req.ip` and `req.ips` are taken from the + * client-supplied `X-Forwarded-For` header. + */ +private predicate trustsAllProxies() { + exists(DataFlow::MethodCallNode call | + call.getArgument(0).getStringValue() = "trust proxy" and + ( + call.getMethodName() = "enable" and call.getNumArgument() = 1 + or + call.getMethodName() = "set" and + call.getArgument(1).asExpr().(BooleanLiteral).getBoolValue() = true + ) + ) +} + +/** A client-controlled value read from the request passed to a rate-limiter key generator. */ +class SpoofableClientAddress extends DataFlow::Node { + string description; + + SpoofableClientAddress() { + exists(DataFlow::SourceNode req | req = keyGeneratorRequest(_) | + exists(string header | header = clientIpHeader() | + ( + this = + req.getAPropertyRead("headers") + .getAPropertyRead(any(string h | h.toLowerCase() = header)) + or + this = req.getAMethodCall(["get", "header"]) and + this.(DataFlow::MethodCallNode).getArgument(0).getStringValue().toLowerCase() = header + ) and + description = "the client-supplied '" + header + "' header" + ) + or + trustsAllProxies() and + this = req.getAPropertyRead(["ip", "ips"]) and + description = + "the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted" + ) + } + + /** Gets a description of this value for use in an alert message. */ + string getDescription() { result = description } +} + +module RateLimitSpoofableKeyConfig implements DataFlow::ConfigSig { + predicate isSource(DataFlow::Node source) { source instanceof SpoofableClientAddress } + + predicate isSink(DataFlow::Node sink) { + sink = any(RateLimiterCreation c).getKeyGenerator().getAReturn() + } + + predicate observeDiffInformedIncrementalMode() { any() } +} + +module RateLimitSpoofableKeyFlow = TaintTracking::Global; + +import RateLimitSpoofableKeyFlow::PathGraph + +from + RateLimitSpoofableKeyFlow::PathNode source, RateLimitSpoofableKeyFlow::PathNode sink, + RateLimiterCreation limiter +where + RateLimitSpoofableKeyFlow::flowPath(source, sink) and + sink.getNode() = limiter.getKeyGenerator().getAReturn() +select sink.getNode(), source, sink, + "This rate-limiting key depends on $@, so a client can evade the $@ by changing it.", + source.getNode(), source.getNode().(SpoofableClientAddress).getDescription(), limiter, + "rate limiter" diff --git a/languages/javascript/custom/src/RateLimitSpoofableKey/examples/RateLimitSpoofableKeyBad.js b/languages/javascript/custom/src/RateLimitSpoofableKey/examples/RateLimitSpoofableKeyBad.js new file mode 100644 index 00000000..b4903635 --- /dev/null +++ b/languages/javascript/custom/src/RateLimitSpoofableKey/examples/RateLimitSpoofableKeyBad.js @@ -0,0 +1,11 @@ +const express = require('express'); +const { rateLimit } = require('express-rate-limit'); + +const app = express(); +app.enable('trust proxy'); + +app.use('/reset-password', rateLimit({ + windowMs: 5 * 60 * 1000, + max: 100, + keyGenerator: (req) => req.headers['x-forwarded-for'] || req.ip +})); diff --git a/languages/javascript/custom/src/RateLimitSpoofableKey/examples/RateLimitSpoofableKeyGood.js b/languages/javascript/custom/src/RateLimitSpoofableKey/examples/RateLimitSpoofableKeyGood.js new file mode 100644 index 00000000..dce307e7 --- /dev/null +++ b/languages/javascript/custom/src/RateLimitSpoofableKey/examples/RateLimitSpoofableKeyGood.js @@ -0,0 +1,12 @@ +const express = require('express'); +const { rateLimit } = require('express-rate-limit'); + +const app = express(); +// Exactly one reverse proxy sits in front of the application. +app.set('trust proxy', 1); + +app.use('/reset-password', rateLimit({ + windowMs: 5 * 60 * 1000, + max: 100, + keyGenerator: (req) => req.ip +})); diff --git a/languages/javascript/custom/src/SessionFixation/SessionFixation.qhelp b/languages/javascript/custom/src/SessionFixation/SessionFixation.qhelp new file mode 100644 index 00000000..da46c594 --- /dev/null +++ b/languages/javascript/custom/src/SessionFixation/SessionFixation.qhelp @@ -0,0 +1,44 @@ + + + + +

    +Reusing a session could allow an attacker to gain unauthorized access to another account. +Always ensure that, when a user logs in or out, the current session is abandoned so that a new +session may be started. +

    +

    +This query also recognizes login handlers that pass the session object to a helper function, +which then marks the session as authenticated without regenerating it. +

    +
    + + +

    +Always use req.session.regenerate(...); to start a new session when a user logs in or out. +

    +
    + + +

    +The following example passes the existing session to a helper that stores the authenticated user +in it. An attacker who planted or learned the session ID before the user logged in can use it to +access the user's account afterwards. +

    + + +

    +The following example solves the problem by calling req.session.regenerate() before +storing the authenticated user, so that the previous session is not reused. +

    + +
    + + +
  • OWASP: Session fixation.
  • +
  • Stack Overflow: Creating a new session after authentication with Passport.
  • +
  • Common Weakness Enumeration: CWE-384.
  • +
    +
    diff --git a/languages/javascript/custom/src/SessionFixation/SessionFixation.ql b/languages/javascript/custom/src/SessionFixation/SessionFixation.ql new file mode 100644 index 00000000..98922413 --- /dev/null +++ b/languages/javascript/custom/src/SessionFixation/SessionFixation.ql @@ -0,0 +1,61 @@ +/** + * @name Failure to abandon session + * @description Reusing an existing session as a different user could allow + * an attacker to access someone else's account by using + * their session. + * @kind problem + * @problem.severity warning + * @security-severity 5 + * @precision medium + * @id js/session-fixation + * @tags security + * external/cwe/cwe-384 + */ + +// This query is a superset of the standard `js/session-fixation` query +// (codeql/javascript-queries, Security/CWE-384/SessionFixation.ql). In addition it +// tracks the `req.session` object across function calls, so that a login handler which +// passes the session to a helper that marks it as authenticated (or regenerates it) is +// handled like a handler that writes to (or regenerates) `req.session` directly. +import javascript + +/** + * Gets a reference to the session object (`req.session`) of a request handled by `handler`, + * including references obtained by passing the session object to another function. + */ +private DataFlow::SourceNode sessionRef(Express::RouteHandler handler, DataFlow::TypeTracker t) { + t.start() and + result = handler.getARequestSource().ref().getAPropertyRead("session") + or + exists(DataFlow::TypeTracker t2 | result = sessionRef(handler, t2).track(t2, t)) +} + +/** Gets a reference to the session object of a request handled by `handler`. */ +private DataFlow::SourceNode sessionRef(Express::RouteHandler handler) { + result = sessionRef(handler, DataFlow::TypeTracker::end()) +} + +/** + * Holds if `setup` uses express-session (or similar) to log in a user. + */ +pragma[inline] +predicate isLoginSetup(Express::RouteSetup setup) { + // some path that contains "login" with a write to `req.session` + setup.getPath().matches("%login%") and + exists(sessionRef(setup.getARouteHandler()).getAPropertyWrite()) + // passport used to be recognized, but they have since added built-in protection against session fixation +} + +/** + * Holds if `setup` regenerates its session using `req.session.regenerate`. + */ +pragma[inline] +predicate regeneratesSession(Express::RouteSetup setup) { + exists(sessionRef(setup.getARouteHandler()).getAPropertyRead("regenerate")) +} + +from Express::RouteSetup setup +where + isLoginSetup(setup) and + not regeneratesSession(setup) +select setup, "Route handler does not invalidate session following login." diff --git a/languages/javascript/custom/src/SessionFixation/examples/SessionFixationBad.js b/languages/javascript/custom/src/SessionFixation/examples/SessionFixationBad.js new file mode 100644 index 00000000..4024dd08 --- /dev/null +++ b/languages/javascript/custom/src/SessionFixation/examples/SessionFixationBad.js @@ -0,0 +1,21 @@ +const express = require('express'); +const session = require('express-session'); +const bodyParser = require('body-parser'); +const app = express(); +app.use(bodyParser.urlencoded({ extended: false })); +app.use(session({ secret: 'keyboard cat' })); + +function markLoggedIn(session, username) { + session.username = username; + session.authenticated = true; +} + +app.post('/login', function (req, res) { + // Check that username password matches + if (req.body.username === 'admin' && req.body.password === 'admin') { + markLoggedIn(req.session, req.body.username); + res.redirect('/'); + } else { + res.redirect('/login'); + } +}); diff --git a/languages/javascript/custom/src/SessionFixation/examples/SessionFixationGood.js b/languages/javascript/custom/src/SessionFixation/examples/SessionFixationGood.js new file mode 100644 index 00000000..57868302 --- /dev/null +++ b/languages/javascript/custom/src/SessionFixation/examples/SessionFixationGood.js @@ -0,0 +1,23 @@ +const express = require('express'); +const session = require('express-session'); +const bodyParser = require('body-parser'); +const app = express(); +app.use(bodyParser.urlencoded({ extended: false })); +app.use(session({ secret: 'keyboard cat' })); + +app.post('/login', function (req, res) { + // Check that username password matches + if (req.body.username === 'admin' && req.body.password === 'admin') { + req.session.regenerate(function (err) { + if (err) { + res.send('Error'); + } else { + req.session.username = req.body.username; + req.session.authenticated = true; + res.redirect('/'); + } + }); + } else { + res.redirect('/login'); + } +}); diff --git a/languages/javascript/custom/src/change-notes/2026-10-31-session-fixation-rate-limit-key.md b/languages/javascript/custom/src/change-notes/2026-10-31-session-fixation-rate-limit-key.md new file mode 100644 index 00000000..5d16f109 --- /dev/null +++ b/languages/javascript/custom/src/change-notes/2026-10-31-session-fixation-rate-limit-key.md @@ -0,0 +1,6 @@ +--- +category: minorAnalysis +--- + +- Added a custom variant of the `js/session-fixation` query (`SessionFixation/SessionFixation.ql`). In addition to the standard query, it tracks the `req.session` object across function calls, so a login route that passes the session to a helper which marks it as authenticated (without calling `regenerate`) is now reported. +- Added a new query, `js/rate-limit-spoofable-key` (`RateLimitSpoofableKey/RateLimitSpoofableKey.ql`), which finds `express-rate-limit` and `express-slow-down` limiters whose `keyGenerator` derives the client key from a client address header such as `X-Forwarded-For`, or from `req.ip`/`req.ips` while the application trusts all proxies. diff --git a/languages/javascript/custom/test/MissingRateLimiting/MissingRateLimiting.expected b/languages/javascript/custom/test/MissingRateLimiting/MissingRateLimiting.expected new file mode 100644 index 00000000..f5997d36 --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/MissingRateLimiting.expected @@ -0,0 +1,3 @@ +| goatlin/routes/accounts.js:7:43:7:46 | auth | This route handler performs $@, but is not rate-limited. | goatlin/middleware/auth.js:12:25:12:67 | Account ... .exec() | a database access | +| goof/app.js:9:20:9:38 | routes.loginHandler | This route handler performs $@, but is not rate-limited. | goof/routes.js:7:3:13:4 | User.fi ... );\\n }) | a database access | +| nodegoat/routes/index.js:9:22:9:54 | session ... Request | This route handler performs $@, but is not rate-limited. | nodegoat/routes/session.js:12:5:16:6 | userDAO ... \\n }) | authorization | diff --git a/languages/javascript/custom/test/MissingRateLimiting/MissingRateLimiting.qlref b/languages/javascript/custom/test/MissingRateLimiting/MissingRateLimiting.qlref new file mode 100644 index 00000000..2fa46c1f --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/MissingRateLimiting.qlref @@ -0,0 +1,2 @@ +query: Security/CWE-770/MissingRateLimiting.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/languages/javascript/custom/test/MissingRateLimiting/goatlin/app.js b/languages/javascript/custom/test/MissingRateLimiting/goatlin/app.js new file mode 100644 index 00000000..0028cafe --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/goatlin/app.js @@ -0,0 +1,8 @@ +const express = require('express'); +const accountsRouter = require('./routes/accounts'); + +const app = express(); +app.use(express.json()); +app.use('/', accountsRouter); + +module.exports = app; diff --git a/languages/javascript/custom/test/MissingRateLimiting/goatlin/middleware/auth.js b/languages/javascript/custom/test/MissingRateLimiting/goatlin/middleware/auth.js new file mode 100644 index 00000000..81a9e7ed --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/goatlin/middleware/auth.js @@ -0,0 +1,17 @@ +// HTTP Basic authentication middleware that checks the decoded credentials against the +// database on every request (reduced from a Goatlin-style API service). +const Account = require('../models/account'); + +module.exports = async function (req, res, next) { + const header = req.get('Authorization') || ''; + if (header === '') { + return res.status(401).end(); + } + const [scheme, data] = header.split(' '); + const [email, password] = Buffer.from(data, 'base64').toString().split(':'); + const account = await Account.findOne({ email, password }).exec(); + if (account === null) { + return res.status(401).end(); + } + return next(); +}; diff --git a/languages/javascript/custom/test/MissingRateLimiting/goatlin/models/account.js b/languages/javascript/custom/test/MissingRateLimiting/goatlin/models/account.js new file mode 100644 index 00000000..70f3055e --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/goatlin/models/account.js @@ -0,0 +1,8 @@ +const mongoose = require('mongoose'); + +const accountSchema = new mongoose.Schema({ + email: { type: String, required: true, unique: true }, + password: { type: String, required: true } +}); + +module.exports = new mongoose.model('Account', accountSchema); diff --git a/languages/javascript/custom/test/MissingRateLimiting/goatlin/routes/accounts.js b/languages/javascript/custom/test/MissingRateLimiting/goatlin/routes/accounts.js new file mode 100644 index 00000000..c620eb36 --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/goatlin/routes/accounts.js @@ -0,0 +1,16 @@ +const express = require('express'); +const rateLimit = require('express-rate-limit'); +const auth = require('../middleware/auth'); + +const router = express.Router(); + +router.get('/accounts/:username/profile', auth, (req, res) => { // $ Alert + res.json({ username: req.params.username }); +}); + +// GOOD: the authentication middleware is rate-limited. +router.get('/accounts/:username/settings', rateLimit({ windowMs: 60 * 1000, max: 10 }), auth, (req, res) => { + res.json({ username: req.params.username }); +}); + +module.exports = router; diff --git a/languages/javascript/custom/test/MissingRateLimiting/goof/app.js b/languages/javascript/custom/test/MissingRateLimiting/goof/app.js new file mode 100644 index 00000000..21601c8b --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/goof/app.js @@ -0,0 +1,13 @@ +require('./mongoose-db'); + +var express = require('express'); +var rateLimit = require('express-rate-limit'); +var routes = require('./routes'); + +var app = express(); +app.get('/login', routes.login); +app.post('/login', routes.loginHandler); // $ Alert + +// GOOD: the login handler is rate-limited. +var loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 5 }); +app.post('/limited-login', loginLimiter, routes.loginHandler); diff --git a/languages/javascript/custom/test/MissingRateLimiting/goof/mongoose-db.js b/languages/javascript/custom/test/MissingRateLimiting/goof/mongoose-db.js new file mode 100644 index 00000000..a64f0832 --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/goof/mongoose-db.js @@ -0,0 +1,9 @@ +var mongoose = require('mongoose'); + +var User = new mongoose.Schema({ + username: String, + password: String +}); + +mongoose.model('User', User); +mongoose.connect('mongodb://localhost/goof'); diff --git a/languages/javascript/custom/test/MissingRateLimiting/goof/routes.js b/languages/javascript/custom/test/MissingRateLimiting/goof/routes.js new file mode 100644 index 00000000..9fd01712 --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/goof/routes.js @@ -0,0 +1,18 @@ +// Admin login handler that looks up the submitted credentials in the database +// (reduced from a nodejs-goof-style application). +var mongoose = require('mongoose'); +var User = mongoose.model('User'); + +exports.loginHandler = function (req, res, next) { + User.find({ username: req.body.username, password: req.body.password }, function (err, users) { + if (users.length > 0) { + req.session.loggedIn = 1; + return res.redirect('/admin'); + } + return res.status(401).send(); + }); +}; + +exports.login = function (req, res) { + return res.render('admin', { granted: false }); +}; diff --git a/languages/javascript/custom/test/MissingRateLimiting/nodegoat/routes/index.js b/languages/javascript/custom/test/MissingRateLimiting/nodegoat/routes/index.js new file mode 100644 index 00000000..4fa2ba66 --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/nodegoat/routes/index.js @@ -0,0 +1,12 @@ +const SessionHandler = require("./session"); + +const index = (app, db) => { + "use strict"; + + const sessionHandler = new SessionHandler(db); + + app.get("/login", sessionHandler.displayLoginPage); + app.post("/login", sessionHandler.handleLoginRequest); // $ Alert +}; + +module.exports = index; diff --git a/languages/javascript/custom/test/MissingRateLimiting/nodegoat/routes/session.js b/languages/javascript/custom/test/MissingRateLimiting/nodegoat/routes/session.js new file mode 100644 index 00000000..549384e5 --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/nodegoat/routes/session.js @@ -0,0 +1,24 @@ +// Login handler defined as a `this.x = ...` property of a constructor function; the +// credentials are verified by a DAO method (reduced from a NodeGoat-style application). +const UserDAO = require("../user-dao").UserDAO; + +function SessionHandler(db) { + "use strict"; + + const userDAO = new UserDAO(db); + + this.handleLoginRequest = (req, res, next) => { + const { userName, password } = req.body; + userDAO.validateLogin(userName, password, (err, user) => { + if (err) return next(err); + req.session.userId = user._id; + return res.redirect("/dashboard"); + }); + }; + + this.displayLoginPage = (req, res) => { + return res.render("login"); + }; +} + +module.exports = SessionHandler; diff --git a/languages/javascript/custom/test/MissingRateLimiting/nodegoat/server.js b/languages/javascript/custom/test/MissingRateLimiting/nodegoat/server.js new file mode 100644 index 00000000..f3490f80 --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/nodegoat/server.js @@ -0,0 +1,11 @@ +"use strict"; + +const express = require("express"); +const MongoClient = require("mongodb").MongoClient; +const app = express(); +const routes = require("./routes"); + +MongoClient.connect("mongodb://localhost/db", (err, db) => { + routes(app, db); + app.listen(4000); +}); diff --git a/languages/javascript/custom/test/MissingRateLimiting/nodegoat/user-dao.js b/languages/javascript/custom/test/MissingRateLimiting/nodegoat/user-dao.js new file mode 100644 index 00000000..6a4bab0e --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/nodegoat/user-dao.js @@ -0,0 +1,12 @@ +function UserDAO(db) { + const usersCol = db.collection("users"); + this.validateLogin = (userName, password, callback) => { + usersCol.findOne({ userName: userName }, (err, user) => { + if (err) return callback(err, null); + if (user && user.password === password) return callback(null, user); + return callback({ invalidPassword: true }, null); + }); + }; +} + +module.exports = { UserDAO }; diff --git a/languages/javascript/custom/test/MissingRateLimiting/package.json b/languages/javascript/custom/test/MissingRateLimiting/package.json new file mode 100644 index 00000000..5e0e2425 --- /dev/null +++ b/languages/javascript/custom/test/MissingRateLimiting/package.json @@ -0,0 +1,4 @@ +{ + "name": "missing-rate-limiting-test", + "type": "commonjs" +} diff --git a/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.expected b/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.expected new file mode 100644 index 00000000..fa64315e --- /dev/null +++ b/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.expected @@ -0,0 +1,35 @@ +#select +| limiters.js:10:26:10:45 | req.get('X-Real-IP') | limiters.js:10:26:10:45 | req.get('X-Real-IP') | limiters.js:10:26:10:45 | req.get('X-Real-IP') | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | limiters.js:10:26:10:45 | req.get('X-Real-IP') | the client-supplied 'x-real-ip' header | limiters.js:7:23:11:2 | RateLim ... lert\\n}) | rate limiter | +| limiters.js:22:12:22:27 | getClientIp(req) | limiters.js:14:21:14:50 | req.hea ... d-for'] | limiters.js:22:12:22:27 | getClientIp(req) | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | limiters.js:14:21:14:50 | req.hea ... d-for'] | the client-supplied 'x-forwarded-for' header | limiters.js:25:33:25:54 | new Rat ... ptions) | rate limiter | +| limiters.js:30:26:30:55 | req.hea ... ng-ip') | limiters.js:30:26:30:55 | req.hea ... ng-ip') | limiters.js:30:26:30:55 | req.hea ... ng-ip') | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | limiters.js:30:26:30:55 | req.hea ... ng-ip') | the client-supplied 'cf-connecting-ip' header | limiters.js:27:21:31:2 | slowDow ... lert\\n}) | rate limiter | +| server.ts:12:70:12:101 | headers ... ] ?? ip | server.ts:12:28:12:29 | ip | server.ts:12:70:12:101 | headers ... ] ?? ip | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | server.ts:12:28:12:29 | ip | the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted | server.ts:9:38:13:2 | rateLim ... lert\\n}) | rate limiter | +| server.ts:12:70:12:101 | headers ... ] ?? ip | server.ts:12:70:12:95 | headers ... d-For'] | server.ts:12:70:12:101 | headers ... ] ?? ip | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | server.ts:12:70:12:95 | headers ... d-For'] | the client-supplied 'x-forwarded-for' header | server.ts:9:38:13:2 | rateLim ... lert\\n}) | rate limiter | +edges +| limiters.js:14:9:14:17 | forwarded | limiters.js:15:22:15:30 | forwarded | provenance | | +| limiters.js:14:21:14:50 | req.hea ... d-for'] | limiters.js:14:9:14:17 | forwarded | provenance | | +| limiters.js:15:10:15:78 | forward ... Address | limiters.js:22:12:22:27 | getClientIp(req) | provenance | | +| limiters.js:15:22:15:30 | forwarded | limiters.js:15:22:15:41 | forwarded.split(',') [ArrayElement] | provenance | | +| limiters.js:15:22:15:41 | forwarded.split(',') [ArrayElement] | limiters.js:15:22:15:44 | forward ... ',')[0] | provenance | | +| limiters.js:15:22:15:44 | forward ... ',')[0] | limiters.js:15:22:15:51 | forward ... .trim() | provenance | | +| limiters.js:15:22:15:51 | forward ... .trim() | limiters.js:15:10:15:78 | forward ... Address | provenance | | +| server.ts:12:28:12:29 | ip | server.ts:12:28:12:29 | ip | provenance | | +| server.ts:12:28:12:29 | ip | server.ts:12:100:12:101 | ip | provenance | | +| server.ts:12:70:12:95 | headers ... d-For'] | server.ts:12:70:12:101 | headers ... ] ?? ip | provenance | | +| server.ts:12:100:12:101 | ip | server.ts:12:70:12:101 | headers ... ] ?? ip | provenance | | +nodes +| limiters.js:10:26:10:45 | req.get('X-Real-IP') | semmle.label | req.get('X-Real-IP') | +| limiters.js:14:9:14:17 | forwarded | semmle.label | forwarded | +| limiters.js:14:21:14:50 | req.hea ... d-for'] | semmle.label | req.hea ... d-for'] | +| limiters.js:15:10:15:78 | forward ... Address | semmle.label | forward ... Address | +| limiters.js:15:22:15:30 | forwarded | semmle.label | forwarded | +| limiters.js:15:22:15:41 | forwarded.split(',') [ArrayElement] | semmle.label | forwarded.split(',') [ArrayElement] | +| limiters.js:15:22:15:44 | forward ... ',')[0] | semmle.label | forward ... ',')[0] | +| limiters.js:15:22:15:51 | forward ... .trim() | semmle.label | forward ... .trim() | +| limiters.js:22:12:22:27 | getClientIp(req) | semmle.label | getClientIp(req) | +| limiters.js:30:26:30:55 | req.hea ... ng-ip') | semmle.label | req.hea ... ng-ip') | +| server.ts:12:28:12:29 | ip | semmle.label | ip | +| server.ts:12:28:12:29 | ip | semmle.label | ip | +| server.ts:12:70:12:95 | headers ... d-For'] | semmle.label | headers ... d-For'] | +| server.ts:12:70:12:101 | headers ... ] ?? ip | semmle.label | headers ... ] ?? ip | +| server.ts:12:100:12:101 | ip | semmle.label | ip | +subpaths diff --git a/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.qlref b/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.qlref new file mode 100644 index 00000000..bf1df9c7 --- /dev/null +++ b/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.qlref @@ -0,0 +1,2 @@ +query: RateLimitSpoofableKey/RateLimitSpoofableKey.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/languages/javascript/custom/test/RateLimitSpoofableKey/limiters.js b/languages/javascript/custom/test/RateLimitSpoofableKey/limiters.js new file mode 100644 index 00000000..57394aa7 --- /dev/null +++ b/languages/javascript/custom/test/RateLimitSpoofableKey/limiters.js @@ -0,0 +1,43 @@ +const express = require('express'); +const RateLimit = require('express-rate-limit'); +const slowDown = require('express-slow-down'); + +const router = express.Router(); + +router.post('/login', RateLimit({ + windowMs: 60 * 1000, + max: 5, + keyGenerator: (req) => req.get('X-Real-IP') // $ Alert +}), (req, res) => res.end()); + +function getClientIp(req) { + const forwarded = req.headers['x-forwarded-for']; // $ Source + return forwarded ? forwarded.split(',')[0].trim() : req.socket.remoteAddress; +} + +const options = { + windowMs: 60 * 1000, + max: 5, + keyGenerator: function (req, res) { + return getClientIp(req); // $ Alert + } +}; +router.post('/forgot-password', new RateLimit(options), (req, res) => res.end()); + +router.post('/otp', slowDown({ + windowMs: 60 * 1000, + delayAfter: 3, + keyGenerator: (req) => req.header('cf-connecting-ip') // $ Alert +}), (req, res) => res.end()); + +// GOOD: an API key header is not a client address header. +router.post('/api', RateLimit({ + keyGenerator: (req) => req.headers['x-api-key'] +}), (req, res) => res.end()); + +// GOOD: the socket address cannot be spoofed by the client. +router.post('/register', RateLimit({ + keyGenerator: (req) => req.socket.remoteAddress +}), (req, res) => res.end()); + +module.exports = router; diff --git a/languages/javascript/custom/test/RateLimitSpoofableKey/package.json b/languages/javascript/custom/test/RateLimitSpoofableKey/package.json new file mode 100644 index 00000000..6722a6d0 --- /dev/null +++ b/languages/javascript/custom/test/RateLimitSpoofableKey/package.json @@ -0,0 +1,4 @@ +{ + "name": "rate-limit-spoofable-key-test", + "type": "commonjs" +} diff --git a/languages/javascript/custom/test/RateLimitSpoofableKey/server.ts b/languages/javascript/custom/test/RateLimitSpoofableKey/server.ts new file mode 100644 index 00000000..3a16f7f3 --- /dev/null +++ b/languages/javascript/custom/test/RateLimitSpoofableKey/server.ts @@ -0,0 +1,20 @@ +// Reduced from a juice-shop-style application: all proxies are trusted and the +// reset-password limiter is keyed on the raw `X-Forwarded-For` header, falling back to `req.ip`. +import express from 'express' +import { rateLimit } from 'express-rate-limit' + +const app = express() + +app.enable('trust proxy') +app.use('/rest/user/reset-password', rateLimit({ + windowMs: 5 * 60 * 1000, + max: 100, + keyGenerator ({ headers, ip }: { headers: any, ip: any }) { return headers['X-Forwarded-For'] ?? ip } // $ Alert +})) + +// GOOD: the limiter is keyed on the authenticated user rather than on the client address. +app.use('/rest/user/change-password', rateLimit({ + windowMs: 5 * 60 * 1000, + max: 100, + keyGenerator: (req: any) => req.user.id +})) diff --git a/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/RateLimitSpoofableKey.expected b/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/RateLimitSpoofableKey.expected new file mode 100644 index 00000000..3f492941 --- /dev/null +++ b/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/RateLimitSpoofableKey.expected @@ -0,0 +1,8 @@ +#select +| app.js:18:26:18:65 | req.hea ... req.ip | app.js:18:26:18:55 | req.hea ... d-for'] | app.js:18:26:18:65 | req.hea ... req.ip | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | app.js:18:26:18:55 | req.hea ... d-for'] | the client-supplied 'x-forwarded-for' header | app.js:17:19:19:2 | rateLim ... lert\\n}) | rate limiter | +edges +| app.js:18:26:18:55 | req.hea ... d-for'] | app.js:18:26:18:65 | req.hea ... req.ip | provenance | | +nodes +| app.js:18:26:18:55 | req.hea ... d-for'] | semmle.label | req.hea ... d-for'] | +| app.js:18:26:18:65 | req.hea ... req.ip | semmle.label | req.hea ... req.ip | +subpaths diff --git a/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/RateLimitSpoofableKey.qlref b/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/RateLimitSpoofableKey.qlref new file mode 100644 index 00000000..bf1df9c7 --- /dev/null +++ b/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/RateLimitSpoofableKey.qlref @@ -0,0 +1,2 @@ +query: RateLimitSpoofableKey/RateLimitSpoofableKey.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/app.js b/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/app.js new file mode 100644 index 00000000..78d1f9cc --- /dev/null +++ b/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/app.js @@ -0,0 +1,19 @@ +// The application only trusts the first proxy hop, so `req.ip` is the address seen by that +// proxy and cannot be chosen by the client. +const express = require('express'); +const { rateLimit } = require('express-rate-limit'); + +const app = express(); +app.set('trust proxy', 1); + +// GOOD: `req.ip` is not spoofable when only a fixed number of proxy hops is trusted. +app.use('/login', rateLimit({ + windowMs: 60 * 1000, + max: 5, + keyGenerator: (req) => req.ip +})); + +// BAD: the raw header is still client-controlled. +app.use('/reset', rateLimit({ + keyGenerator: (req) => req.headers['x-forwarded-for'] || req.ip // $ Alert +})); diff --git a/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/package.json b/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/package.json new file mode 100644 index 00000000..855d80fd --- /dev/null +++ b/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/package.json @@ -0,0 +1,4 @@ +{ + "name": "rate-limit-spoofable-key-trusted-proxy-test", + "type": "commonjs" +} diff --git a/languages/javascript/custom/test/SessionFixation/SessionFixation.expected b/languages/javascript/custom/test/SessionFixation/SessionFixation.expected new file mode 100644 index 00000000..b37ed819 --- /dev/null +++ b/languages/javascript/custom/test/SessionFixation/SessionFixation.expected @@ -0,0 +1,2 @@ +| goof/app.js:7:1:7:39 | app.pos ... andler) | Route handler does not invalidate session following login. | +| nodegoat/routes/index.js:9:3:9:55 | app.pos ... equest) | Route handler does not invalidate session following login. | diff --git a/languages/javascript/custom/test/SessionFixation/SessionFixation.qlref b/languages/javascript/custom/test/SessionFixation/SessionFixation.qlref new file mode 100644 index 00000000..7eb939d2 --- /dev/null +++ b/languages/javascript/custom/test/SessionFixation/SessionFixation.qlref @@ -0,0 +1,2 @@ +query: SessionFixation/SessionFixation.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/languages/javascript/custom/test/SessionFixation/goof/app.js b/languages/javascript/custom/test/SessionFixation/goof/app.js new file mode 100644 index 00000000..42609965 --- /dev/null +++ b/languages/javascript/custom/test/SessionFixation/goof/app.js @@ -0,0 +1,9 @@ +var express = require('express'); +var session = require('express-session'); +var routes = require('./routes'); + +var app = express(); +app.use(session({ secret: 'keyboard cat' })); +app.post('/login', routes.loginHandler); // $ Alert +app.post('/safe-login', routes.safeLoginHandler); +app.get('/logout', routes.logout); diff --git a/languages/javascript/custom/test/SessionFixation/goof/routes.js b/languages/javascript/custom/test/SessionFixation/goof/routes.js new file mode 100644 index 00000000..cd74390b --- /dev/null +++ b/languages/javascript/custom/test/SessionFixation/goof/routes.js @@ -0,0 +1,43 @@ +// The session object is passed to a helper that marks it as logged in +// (reduced from a nodejs-goof-style application). +var mongoose = require('mongoose'); +var User = mongoose.model('User'); + +exports.loginHandler = function (req, res, next) { + User.find({ username: req.body.username, password: req.body.password }, function (err, users) { + if (users.length > 0) { + const session = req.session; + return adminLoginSuccess(req.body.redirectPage, session, res); + } + return res.status(401).send(); + }); +}; + +function adminLoginSuccess(redirectPage, session, res) { + session.loggedIn = 1; + return res.redirect(redirectPage || '/admin'); +} + +// GOOD: the session is regenerated in the helper. +exports.safeLoginHandler = function (req, res, next) { + User.find({ username: req.body.username, password: req.body.password }, function (err, users) { + if (users.length > 0) { + return safeLoginSuccess(req.session, res); + } + return res.status(401).send(); + }); +}; + +function safeLoginSuccess(session, res) { + session.regenerate(function () { + session.loggedIn = 1; + return res.redirect('/admin'); + }); +} + +exports.logout = function (req, res) { + req.session.loggedIn = 0; + req.session.destroy(function () { + return res.redirect('/'); + }); +}; diff --git a/languages/javascript/custom/test/SessionFixation/nodegoat/routes/index.js b/languages/javascript/custom/test/SessionFixation/nodegoat/routes/index.js new file mode 100644 index 00000000..66911024 --- /dev/null +++ b/languages/javascript/custom/test/SessionFixation/nodegoat/routes/index.js @@ -0,0 +1,13 @@ +const SessionHandler = require("./session"); + +const index = (app, db) => { + "use strict"; + + const sessionHandler = new SessionHandler(db); + + app.get("/login", sessionHandler.displayLoginPage); + app.post("/login", sessionHandler.handleLoginRequest); // $ Alert + app.post("/safe-login", sessionHandler.handleSafeLoginRequest); +}; + +module.exports = index; diff --git a/languages/javascript/custom/test/SessionFixation/nodegoat/routes/session.js b/languages/javascript/custom/test/SessionFixation/nodegoat/routes/session.js new file mode 100644 index 00000000..f4a1ee71 --- /dev/null +++ b/languages/javascript/custom/test/SessionFixation/nodegoat/routes/session.js @@ -0,0 +1,34 @@ +const UserDAO = require("../user-dao").UserDAO; +// Handlers defined as `this.x = ...` properties of a constructor function, with the +// session write inside a callback (reduced from a NodeGoat-style application). +function SessionHandler(db) { + const userDAO = new UserDAO(db); + "use strict"; + + this.handleLoginRequest = (req, res, next) => { + const { userName, password } = req.body; + userDAO.validateLogin(userName, password, (err, user) => { + if (err) return next(err); + req.session.userId = user._id; + return res.redirect("/dashboard"); + }); + }; + + // GOOD: the session is regenerated before the user ID is stored. + this.handleSafeLoginRequest = (req, res, next) => { + const { userName, password } = req.body; + userDAO.validateLogin(userName, password, (err, user) => { + if (err) return next(err); + req.session.regenerate(() => { + req.session.userId = user._id; + return res.redirect("/dashboard"); + }); + }); + }; + + this.displayLoginPage = (req, res) => { + return res.render("login"); + }; +} + +module.exports = SessionHandler; diff --git a/languages/javascript/custom/test/SessionFixation/nodegoat/server.js b/languages/javascript/custom/test/SessionFixation/nodegoat/server.js new file mode 100644 index 00000000..448cea4e --- /dev/null +++ b/languages/javascript/custom/test/SessionFixation/nodegoat/server.js @@ -0,0 +1,13 @@ +"use strict"; + +const express = require("express"); +const session = require("express-session"); +const MongoClient = require("mongodb").MongoClient; +const app = express(); +const routes = require("./routes"); + +MongoClient.connect("mongodb://localhost/db", (err, db) => { + app.use(session({ secret: "secret", saveUninitialized: true, resave: true })); + routes(app, db); + app.listen(4000); +}); diff --git a/languages/javascript/custom/test/SessionFixation/nodegoat/user-dao.js b/languages/javascript/custom/test/SessionFixation/nodegoat/user-dao.js new file mode 100644 index 00000000..6a4bab0e --- /dev/null +++ b/languages/javascript/custom/test/SessionFixation/nodegoat/user-dao.js @@ -0,0 +1,12 @@ +function UserDAO(db) { + const usersCol = db.collection("users"); + this.validateLogin = (userName, password, callback) => { + usersCol.findOne({ userName: userName }, (err, user) => { + if (err) return callback(err, null); + if (user && user.password === password) return callback(null, user); + return callback({ invalidPassword: true }, null); + }); + }; +} + +module.exports = { UserDAO }; diff --git a/languages/javascript/custom/test/SessionFixation/package.json b/languages/javascript/custom/test/SessionFixation/package.json new file mode 100644 index 00000000..614fd65a --- /dev/null +++ b/languages/javascript/custom/test/SessionFixation/package.json @@ -0,0 +1,4 @@ +{ + "name": "session-fixation-test", + "type": "commonjs" +} diff --git a/languages/javascript/custom/test/qlpack.yml b/languages/javascript/custom/test/qlpack.yml index d2cb9a4f..458afcd7 100644 --- a/languages/javascript/custom/test/qlpack.yml +++ b/languages/javascript/custom/test/qlpack.yml @@ -2,4 +2,5 @@ name: languages-javascript-custom-test version: 0.0.2 dependencies: languages-javascript-custom-src: ${workspace} + codeql/javascript-queries: "*" extractor: javascript From 3291985b34405f06670f4735103b1b9420c68832 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:44:05 +0000 Subject: [PATCH 3/4] js/rate-limit-spoofable-key: scope trust proxy to the limiter's app and match lower-case header names Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .../RateLimitSpoofableKey.qhelp | 5 +- .../RateLimitSpoofableKey.ql | 49 +++++++++++++++---- ...6-10-31-session-fixation-rate-limit-key.md | 2 +- .../RateLimitSpoofableKey.expected | 23 ++++----- .../test/RateLimitSpoofableKey/other-app.js | 12 +++++ .../test/RateLimitSpoofableKey/server.ts | 39 ++++++++++----- .../RateLimitSpoofableKeyTrustedProxy/app.js | 6 +++ 7 files changed, 101 insertions(+), 35 deletions(-) create mode 100644 languages/javascript/custom/test/RateLimitSpoofableKey/other-app.js diff --git a/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.qhelp b/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.qhelp index 799bb250..4c16842e 100644 --- a/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.qhelp +++ b/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.qhelp @@ -16,7 +16,10 @@ password-reset answers. The same applies to req.ip and req.ips when the Express application trusts all proxies (app.enable('trust proxy') or app.set('trust proxy', true)), because Express then takes the client address from the -left-most, client-supplied, entry of the X-Forwarded-For header. +left-most, client-supplied, entry of the X-Forwarded-For header. Note that Node.js +lower-cases the names of request headers, so a lookup such as +req.headers['X-Forwarded-For'] is always undefined; a key such as +req.headers['X-Forwarded-For'] ?? req.ip therefore depends only on req.ip.

    diff --git a/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.ql b/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.ql index 4ca931b7..51a24710 100644 --- a/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.ql +++ b/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.ql @@ -58,12 +58,13 @@ private string clientIpHeader() { } /** - * Holds if the application trusts any number of proxies (`app.enable('trust proxy')` or - * `app.set('trust proxy', true)`), so that `req.ip` and `req.ips` are taken from the - * client-supplied `X-Forwarded-For` header. + * Holds if the Express application `app` trusts any number of proxies + * (`app.enable('trust proxy')` or `app.set('trust proxy', true)`), so that `req.ip` and + * `req.ips` are taken from the client-supplied `X-Forwarded-For` header. */ -private predicate trustsAllProxies() { +private predicate trustsAllProxies(Express::RouterDefinition app) { exists(DataFlow::MethodCallNode call | + app.ref().flowsTo(call.getReceiver()) and call.getArgument(0).getStringValue() = "trust proxy" and ( call.getMethodName() = "enable" and call.getNumArgument() = 1 @@ -74,17 +75,47 @@ private predicate trustsAllProxies() { ) } +/** Gets a reference to the rate-limiting middleware created by `limiter`. */ +private DataFlow::SourceNode limiterRef(RateLimiterCreation limiter, DataFlow::TypeTracker t) { + t.start() and + result = limiter + or + exists(DataFlow::TypeTracker t2 | result = limiterRef(limiter, t2).track(t2, t)) +} + +/** Holds if `limiter` is installed on `router`, which is `app` or one of its sub-routers. */ +private predicate installedIn(RateLimiterCreation limiter, Express::RouterDefinition app) { + exists(Express::RouteSetup setup | + limiterRef(limiter, DataFlow::TypeTracker::end()).flowsTo(setup.getAnArgument()) and + setup.getRouter() = app.getASubRouter*() + ) +} + +/** + * Holds if `req.ip` and `req.ips` may be chosen by the client for requests that pass through + * `limiter`, that is, `limiter` is installed in an application that trusts all proxies or, if + * it cannot be linked to an application, some application trusts all proxies. + */ +private predicate usesSpoofableIp(RateLimiterCreation limiter) { + exists(Express::RouterDefinition app | trustsAllProxies(app) | + installedIn(limiter, app) + or + not installedIn(limiter, _) + ) +} + /** A client-controlled value read from the request passed to a rate-limiter key generator. */ class SpoofableClientAddress extends DataFlow::Node { string description; SpoofableClientAddress() { - exists(DataFlow::SourceNode req | req = keyGeneratorRequest(_) | + exists(RateLimiterCreation limiter, DataFlow::SourceNode req | + req = keyGeneratorRequest(limiter.getKeyGenerator()) + | exists(string header | header = clientIpHeader() | ( - this = - req.getAPropertyRead("headers") - .getAPropertyRead(any(string h | h.toLowerCase() = header)) + // Node.js lower-cases the keys of `req.headers`, so only lower-case names can be set by the client. + this = req.getAPropertyRead("headers").getAPropertyRead(header) or this = req.getAMethodCall(["get", "header"]) and this.(DataFlow::MethodCallNode).getArgument(0).getStringValue().toLowerCase() = header @@ -92,7 +123,7 @@ class SpoofableClientAddress extends DataFlow::Node { description = "the client-supplied '" + header + "' header" ) or - trustsAllProxies() and + usesSpoofableIp(limiter) and this = req.getAPropertyRead(["ip", "ips"]) and description = "the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted" diff --git a/languages/javascript/custom/src/change-notes/2026-10-31-session-fixation-rate-limit-key.md b/languages/javascript/custom/src/change-notes/2026-10-31-session-fixation-rate-limit-key.md index 5d16f109..df2b66d5 100644 --- a/languages/javascript/custom/src/change-notes/2026-10-31-session-fixation-rate-limit-key.md +++ b/languages/javascript/custom/src/change-notes/2026-10-31-session-fixation-rate-limit-key.md @@ -3,4 +3,4 @@ category: minorAnalysis --- - Added a custom variant of the `js/session-fixation` query (`SessionFixation/SessionFixation.ql`). In addition to the standard query, it tracks the `req.session` object across function calls, so a login route that passes the session to a helper which marks it as authenticated (without calling `regenerate`) is now reported. -- Added a new query, `js/rate-limit-spoofable-key` (`RateLimitSpoofableKey/RateLimitSpoofableKey.ql`), which finds `express-rate-limit` and `express-slow-down` limiters whose `keyGenerator` derives the client key from a client address header such as `X-Forwarded-For`, or from `req.ip`/`req.ips` while the application trusts all proxies. +- Added a new query, `js/rate-limit-spoofable-key` (`RateLimitSpoofableKey/RateLimitSpoofableKey.ql`), which finds `express-rate-limit` and `express-slow-down` limiters whose `keyGenerator` derives the client key from a client address header such as `X-Forwarded-For`, or from `req.ip`/`req.ips` while the Express application that installs the limiter trusts all proxies (`app.enable('trust proxy')`). diff --git a/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.expected b/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.expected index fa64315e..da3b2323 100644 --- a/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.expected +++ b/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.expected @@ -2,8 +2,8 @@ | limiters.js:10:26:10:45 | req.get('X-Real-IP') | limiters.js:10:26:10:45 | req.get('X-Real-IP') | limiters.js:10:26:10:45 | req.get('X-Real-IP') | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | limiters.js:10:26:10:45 | req.get('X-Real-IP') | the client-supplied 'x-real-ip' header | limiters.js:7:23:11:2 | RateLim ... lert\\n}) | rate limiter | | limiters.js:22:12:22:27 | getClientIp(req) | limiters.js:14:21:14:50 | req.hea ... d-for'] | limiters.js:22:12:22:27 | getClientIp(req) | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | limiters.js:14:21:14:50 | req.hea ... d-for'] | the client-supplied 'x-forwarded-for' header | limiters.js:25:33:25:54 | new Rat ... ptions) | rate limiter | | limiters.js:30:26:30:55 | req.hea ... ng-ip') | limiters.js:30:26:30:55 | req.hea ... ng-ip') | limiters.js:30:26:30:55 | req.hea ... ng-ip') | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | limiters.js:30:26:30:55 | req.hea ... ng-ip') | the client-supplied 'cf-connecting-ip' header | limiters.js:27:21:31:2 | slowDow ... lert\\n}) | rate limiter | -| server.ts:12:70:12:101 | headers ... ] ?? ip | server.ts:12:28:12:29 | ip | server.ts:12:70:12:101 | headers ... ] ?? ip | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | server.ts:12:28:12:29 | ip | the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted | server.ts:9:38:13:2 | rateLim ... lert\\n}) | rate limiter | -| server.ts:12:70:12:101 | headers ... ] ?? ip | server.ts:12:70:12:95 | headers ... d-For'] | server.ts:12:70:12:101 | headers ... ] ?? ip | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | server.ts:12:70:12:95 | headers ... d-For'] | the client-supplied 'x-forwarded-for' header | server.ts:9:38:13:2 | rateLim ... lert\\n}) | rate limiter | +| server.ts:15:72:15:103 | headers ... ] ?? ip | server.ts:15:30:15:31 | ip | server.ts:15:72:15:103 | headers ... ] ?? ip | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | server.ts:15:30:15:31 | ip | the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted | server.ts:12:40:16:4 | rateLim ... rt\\n }) | rate limiter | +| server.ts:30:33:30:42 | req.ips[0] | server.ts:30:33:30:39 | req.ips | server.ts:30:33:30:42 | req.ips[0] | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | server.ts:30:33:30:39 | req.ips | the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted | server.ts:27:27:31:4 | rateLim ... rt\\n }) | rate limiter | edges | limiters.js:14:9:14:17 | forwarded | limiters.js:15:22:15:30 | forwarded | provenance | | | limiters.js:14:21:14:50 | req.hea ... d-for'] | limiters.js:14:9:14:17 | forwarded | provenance | | @@ -12,10 +12,10 @@ edges | limiters.js:15:22:15:41 | forwarded.split(',') [ArrayElement] | limiters.js:15:22:15:44 | forward ... ',')[0] | provenance | | | limiters.js:15:22:15:44 | forward ... ',')[0] | limiters.js:15:22:15:51 | forward ... .trim() | provenance | | | limiters.js:15:22:15:51 | forward ... .trim() | limiters.js:15:10:15:78 | forward ... Address | provenance | | -| server.ts:12:28:12:29 | ip | server.ts:12:28:12:29 | ip | provenance | | -| server.ts:12:28:12:29 | ip | server.ts:12:100:12:101 | ip | provenance | | -| server.ts:12:70:12:95 | headers ... d-For'] | server.ts:12:70:12:101 | headers ... ] ?? ip | provenance | | -| server.ts:12:100:12:101 | ip | server.ts:12:70:12:101 | headers ... ] ?? ip | provenance | | +| server.ts:15:30:15:31 | ip | server.ts:15:30:15:31 | ip | provenance | | +| server.ts:15:30:15:31 | ip | server.ts:15:102:15:103 | ip | provenance | | +| server.ts:15:102:15:103 | ip | server.ts:15:72:15:103 | headers ... ] ?? ip | provenance | | +| server.ts:30:33:30:39 | req.ips | server.ts:30:33:30:42 | req.ips[0] | provenance | | nodes | limiters.js:10:26:10:45 | req.get('X-Real-IP') | semmle.label | req.get('X-Real-IP') | | limiters.js:14:9:14:17 | forwarded | semmle.label | forwarded | @@ -27,9 +27,10 @@ nodes | limiters.js:15:22:15:51 | forward ... .trim() | semmle.label | forward ... .trim() | | limiters.js:22:12:22:27 | getClientIp(req) | semmle.label | getClientIp(req) | | limiters.js:30:26:30:55 | req.hea ... ng-ip') | semmle.label | req.hea ... ng-ip') | -| server.ts:12:28:12:29 | ip | semmle.label | ip | -| server.ts:12:28:12:29 | ip | semmle.label | ip | -| server.ts:12:70:12:95 | headers ... d-For'] | semmle.label | headers ... d-For'] | -| server.ts:12:70:12:101 | headers ... ] ?? ip | semmle.label | headers ... ] ?? ip | -| server.ts:12:100:12:101 | ip | semmle.label | ip | +| server.ts:15:30:15:31 | ip | semmle.label | ip | +| server.ts:15:30:15:31 | ip | semmle.label | ip | +| server.ts:15:72:15:103 | headers ... ] ?? ip | semmle.label | headers ... ] ?? ip | +| server.ts:15:102:15:103 | ip | semmle.label | ip | +| server.ts:30:33:30:39 | req.ips | semmle.label | req.ips | +| server.ts:30:33:30:42 | req.ips[0] | semmle.label | req.ips[0] | subpaths diff --git a/languages/javascript/custom/test/RateLimitSpoofableKey/other-app.js b/languages/javascript/custom/test/RateLimitSpoofableKey/other-app.js new file mode 100644 index 00000000..620300eb --- /dev/null +++ b/languages/javascript/custom/test/RateLimitSpoofableKey/other-app.js @@ -0,0 +1,12 @@ +// A separate application that does not trust any proxy. +const express = require('express'); +const rateLimit = require('express-rate-limit'); + +const app = express(); + +// GOOD: `req.ip` is the socket address because this application does not trust proxies. +app.post('/login', rateLimit({ + windowMs: 60 * 1000, + max: 5, + keyGenerator: (req) => req.ip +}), (req, res) => res.end()); diff --git a/languages/javascript/custom/test/RateLimitSpoofableKey/server.ts b/languages/javascript/custom/test/RateLimitSpoofableKey/server.ts index 3a16f7f3..0acbb08b 100644 --- a/languages/javascript/custom/test/RateLimitSpoofableKey/server.ts +++ b/languages/javascript/custom/test/RateLimitSpoofableKey/server.ts @@ -1,20 +1,33 @@ // Reduced from a juice-shop-style application: all proxies are trusted and the -// reset-password limiter is keyed on the raw `X-Forwarded-For` header, falling back to `req.ip`. +// reset-password limiter is keyed on `headers['X-Forwarded-For'] ?? ip`. Node.js lower-cases +// header names, so the header read is always undefined and the key is `req.ip`, which is +// taken from the client-supplied `X-Forwarded-For` header because all proxies are trusted. import express from 'express' import { rateLimit } from 'express-rate-limit' const app = express() -app.enable('trust proxy') -app.use('/rest/user/reset-password', rateLimit({ - windowMs: 5 * 60 * 1000, - max: 100, - keyGenerator ({ headers, ip }: { headers: any, ip: any }) { return headers['X-Forwarded-For'] ?? ip } // $ Alert -})) +export async function start () { + app.enable('trust proxy') + app.use('/rest/user/reset-password', rateLimit({ + windowMs: 5 * 60 * 1000, + max: 100, + keyGenerator ({ headers, ip }: { headers: any, ip: any }) { return headers['X-Forwarded-For'] ?? ip } // $ Alert + })) -// GOOD: the limiter is keyed on the authenticated user rather than on the client address. -app.use('/rest/user/change-password', rateLimit({ - windowMs: 5 * 60 * 1000, - max: 100, - keyGenerator: (req: any) => req.user.id -})) + // GOOD: the limiter is keyed on the authenticated user rather than on the client address. + app.use('/rest/user/change-password', rateLimit({ + windowMs: 5 * 60 * 1000, + max: 100, + keyGenerator: (req: any) => req.user.id + })) + + // A sub-router of the application inherits its `trust proxy` setting. + const api = express.Router() + api.post('/2fa/verify', rateLimit({ + windowMs: 5 * 60 * 1000, + max: 10, + keyGenerator: (req: any) => req.ips[0] // $ Alert + }), (req: any, res: any) => res.end()) + app.use('/api', api) +} diff --git a/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/app.js b/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/app.js index 78d1f9cc..5d297e47 100644 --- a/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/app.js +++ b/languages/javascript/custom/test/RateLimitSpoofableKeyTrustedProxy/app.js @@ -17,3 +17,9 @@ app.use('/login', rateLimit({ app.use('/reset', rateLimit({ keyGenerator: (req) => req.headers['x-forwarded-for'] || req.ip // $ Alert })); + +// GOOD: Node.js lower-cases header names, so `req.headers['X-Real-IP']` is always undefined +// and the key is `req.ip`. +app.use('/verify', rateLimit({ + keyGenerator: (req) => req.headers['X-Real-IP'] || req.ip +})); From 4f0e9ac1e586ec56f5eef828186dcba9ed2daee1 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:21:45 +0000 Subject: [PATCH 4/4] Fix rate limiter proxy trust attribution Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .../RateLimitSpoofableKey.ql | 51 ++++++++++++-- .../RateLimitSpoofableKey.expected | 14 ++++ .../test/RateLimitSpoofableKey/regressions.js | 68 +++++++++++++++++++ 3 files changed, 127 insertions(+), 6 deletions(-) create mode 100644 languages/javascript/custom/test/RateLimitSpoofableKey/regressions.js diff --git a/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.ql b/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.ql index 51a24710..eb710f9d 100644 --- a/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.ql +++ b/languages/javascript/custom/src/RateLimitSpoofableKey/RateLimitSpoofableKey.ql @@ -75,6 +75,24 @@ private predicate trustsAllProxies(Express::RouterDefinition app) { ) } +/** Holds if the Express application `app` explicitly configures `trust proxy`. */ +private predicate configuresTrustProxy(Express::RouterDefinition app) { + exists(DataFlow::MethodCallNode call | + app.ref().flowsTo(call.getReceiver()) and + call.getArgument(0).getStringValue() = "trust proxy" and + ( + call.getMethodName() = "set" and call.getNumArgument() = 2 + or + call.getMethodName() in ["enable", "disable"] and call.getNumArgument() = 1 + ) + ) +} + +/** Holds if `app` is created by `express()` rather than `express.Router()`. */ +private predicate isExpressApp(Express::RouterDefinition app) { + app = Express::appCreation() +} + /** Gets a reference to the rate-limiting middleware created by `limiter`. */ private DataFlow::SourceNode limiterRef(RateLimiterCreation limiter, DataFlow::TypeTracker t) { t.start() and @@ -97,16 +115,27 @@ private predicate installedIn(RateLimiterCreation limiter, Express::RouterDefini * it cannot be linked to an application, some application trusts all proxies. */ private predicate usesSpoofableIp(RateLimiterCreation limiter) { - exists(Express::RouterDefinition app | trustsAllProxies(app) | - installedIn(limiter, app) + exists(Express::RouterDefinition app | + isExpressApp(app) and trustsAllProxies(app) + | + installedIn(limiter, app) and + not exists(Express::RouterDefinition subApp | + isExpressApp(subApp) and + configuresTrustProxy(subApp) and + installedIn(limiter, subApp) and + app.getASubRouter+() = subApp + ) or - not installedIn(limiter, _) + not exists(Express::RouterDefinition hostingApp | + isExpressApp(hostingApp) and installedIn(limiter, hostingApp) + ) ) } /** A client-controlled value read from the request passed to a rate-limiter key generator. */ class SpoofableClientAddress extends DataFlow::Node { string description; + boolean isIpAddress; SpoofableClientAddress() { exists(RateLimiterCreation limiter, DataFlow::SourceNode req | @@ -120,18 +149,23 @@ class SpoofableClientAddress extends DataFlow::Node { this = req.getAMethodCall(["get", "header"]) and this.(DataFlow::MethodCallNode).getArgument(0).getStringValue().toLowerCase() = header ) and - description = "the client-supplied '" + header + "' header" + description = "the client-supplied '" + header + "' header" and + isIpAddress = false ) or usesSpoofableIp(limiter) and this = req.getAPropertyRead(["ip", "ips"]) and description = - "the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted" + "the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted" and + isIpAddress = true ) } /** Gets a description of this value for use in an alert message. */ string getDescription() { result = description } + + /** Holds if this source is a request IP property rather than a header. */ + boolean getIsIpAddress() { result = isIpAddress } } module RateLimitSpoofableKeyConfig implements DataFlow::ConfigSig { @@ -153,7 +187,12 @@ from RateLimiterCreation limiter where RateLimitSpoofableKeyFlow::flowPath(source, sink) and - sink.getNode() = limiter.getKeyGenerator().getAReturn() + sink.getNode() = limiter.getKeyGenerator().getAReturn() and + ( + source.getNode().(SpoofableClientAddress).getIsIpAddress() = false + or + usesSpoofableIp(limiter) + ) select sink.getNode(), source, sink, "This rate-limiting key depends on $@, so a client can evade the $@ by changing it.", source.getNode(), source.getNode().(SpoofableClientAddress).getDescription(), limiter, diff --git a/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.expected b/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.expected index da3b2323..86c8fe0f 100644 --- a/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.expected +++ b/languages/javascript/custom/test/RateLimitSpoofableKey/RateLimitSpoofableKey.expected @@ -2,6 +2,11 @@ | limiters.js:10:26:10:45 | req.get('X-Real-IP') | limiters.js:10:26:10:45 | req.get('X-Real-IP') | limiters.js:10:26:10:45 | req.get('X-Real-IP') | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | limiters.js:10:26:10:45 | req.get('X-Real-IP') | the client-supplied 'x-real-ip' header | limiters.js:7:23:11:2 | RateLim ... lert\\n}) | rate limiter | | limiters.js:22:12:22:27 | getClientIp(req) | limiters.js:14:21:14:50 | req.hea ... d-for'] | limiters.js:22:12:22:27 | getClientIp(req) | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | limiters.js:14:21:14:50 | req.hea ... d-for'] | the client-supplied 'x-forwarded-for' header | limiters.js:25:33:25:54 | new Rat ... ptions) | rate limiter | | limiters.js:30:26:30:55 | req.hea ... ng-ip') | limiters.js:30:26:30:55 | req.hea ... ng-ip') | limiters.js:30:26:30:55 | req.hea ... ng-ip') | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | limiters.js:30:26:30:55 | req.hea ... ng-ip') | the client-supplied 'cf-connecting-ip' header | limiters.js:27:21:31:2 | slowDow ... lert\\n}) | rate limiter | +| regressions.js:6:26:6:31 | req.ip | regressions.js:6:26:6:31 | req.ip | regressions.js:6:26:6:31 | req.ip | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | regressions.js:6:26:6:31 | req.ip | the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted | regressions.js:5:33:7:2 | rateLim ... lert\\n}) | rate limiter | +| regressions.js:34:26:34:31 | req.ip | regressions.js:34:26:34:31 | req.ip | regressions.js:34:26:34:31 | req.ip | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | regressions.js:34:26:34:31 | req.ip | the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted | regressions.js:33:32:35:2 | rateLim ... lert\\n}) | rate limiter | +| regressions.js:41:26:41:31 | req.ip | regressions.js:41:26:41:31 | req.ip | regressions.js:41:26:41:31 | req.ip | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | regressions.js:41:26:41:31 | req.ip | the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted | regressions.js:40:41:42:2 | rateLim ... lert\\n}) | rate limiter | +| regressions.js:45:37:45:42 | req.ip | regressions.js:45:37:45:42 | req.ip | regressions.js:45:37:45:42 | req.ip | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | regressions.js:45:37:45:42 | req.ip | the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted | regressions.js:48:38:50:2 | rateLim ... ator\\n}) | rate limiter | +| regressions.js:63:26:63:42 | readClientIp(req) | regressions.js:57:10:57:15 | req.ip | regressions.js:63:26:63:42 | readClientIp(req) | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | regressions.js:57:10:57:15 | req.ip | the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted | regressions.js:62:47:64:2 | rateLim ... lert\\n}) | rate limiter | | server.ts:15:72:15:103 | headers ... ] ?? ip | server.ts:15:30:15:31 | ip | server.ts:15:72:15:103 | headers ... ] ?? ip | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | server.ts:15:30:15:31 | ip | the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted | server.ts:12:40:16:4 | rateLim ... rt\\n }) | rate limiter | | server.ts:30:33:30:42 | req.ips[0] | server.ts:30:33:30:39 | req.ips | server.ts:30:33:30:42 | req.ips[0] | This rate-limiting key depends on $@, so a client can evade the $@ by changing it. | server.ts:30:33:30:39 | req.ips | the client address, which is taken from the client-supplied 'X-Forwarded-For' header because all proxies are trusted | server.ts:27:27:31:4 | rateLim ... rt\\n }) | rate limiter | edges @@ -12,6 +17,8 @@ edges | limiters.js:15:22:15:41 | forwarded.split(',') [ArrayElement] | limiters.js:15:22:15:44 | forward ... ',')[0] | provenance | | | limiters.js:15:22:15:44 | forward ... ',')[0] | limiters.js:15:22:15:51 | forward ... .trim() | provenance | | | limiters.js:15:22:15:51 | forward ... .trim() | limiters.js:15:10:15:78 | forward ... Address | provenance | | +| regressions.js:57:10:57:15 | req.ip | regressions.js:63:26:63:42 | readClientIp(req) | provenance | | +| regressions.js:57:10:57:15 | req.ip | regressions.js:67:26:67:42 | readClientIp(req) | provenance | | | server.ts:15:30:15:31 | ip | server.ts:15:30:15:31 | ip | provenance | | | server.ts:15:30:15:31 | ip | server.ts:15:102:15:103 | ip | provenance | | | server.ts:15:102:15:103 | ip | server.ts:15:72:15:103 | headers ... ] ?? ip | provenance | | @@ -27,6 +34,13 @@ nodes | limiters.js:15:22:15:51 | forward ... .trim() | semmle.label | forward ... .trim() | | limiters.js:22:12:22:27 | getClientIp(req) | semmle.label | getClientIp(req) | | limiters.js:30:26:30:55 | req.hea ... ng-ip') | semmle.label | req.hea ... ng-ip') | +| regressions.js:6:26:6:31 | req.ip | semmle.label | req.ip | +| regressions.js:34:26:34:31 | req.ip | semmle.label | req.ip | +| regressions.js:41:26:41:31 | req.ip | semmle.label | req.ip | +| regressions.js:45:37:45:42 | req.ip | semmle.label | req.ip | +| regressions.js:57:10:57:15 | req.ip | semmle.label | req.ip | +| regressions.js:63:26:63:42 | readClientIp(req) | semmle.label | readClientIp(req) | +| regressions.js:67:26:67:42 | readClientIp(req) | semmle.label | readClientIp(req) | | server.ts:15:30:15:31 | ip | semmle.label | ip | | server.ts:15:30:15:31 | ip | semmle.label | ip | | server.ts:15:72:15:103 | headers ... ] ?? ip | semmle.label | headers ... ] ?? ip | diff --git a/languages/javascript/custom/test/RateLimitSpoofableKey/regressions.js b/languages/javascript/custom/test/RateLimitSpoofableKey/regressions.js new file mode 100644 index 00000000..8f23579b --- /dev/null +++ b/languages/javascript/custom/test/RateLimitSpoofableKey/regressions.js @@ -0,0 +1,68 @@ +const express = require('express'); +const rateLimit = require('express-rate-limit'); + +const unmountedRouter = express.Router(); +unmountedRouter.post('/orphan', rateLimit({ + keyGenerator: (req) => req.ip // $ Alert +}), (req, res) => res.end()); +module.exports = unmountedRouter; + +const unrelatedTrustedApp = express(); +unrelatedTrustedApp.enable('trust proxy'); + +const trustingParent = express(); +trustingParent.enable('trust proxy'); + +const fixedHopSubApp = express(); +fixedHopSubApp.set('trust proxy', 1); +fixedHopSubApp.post('/fixed-hop', rateLimit({ + keyGenerator: (req) => req.ip +}), (req, res) => res.end()); +trustingParent.use('/fixed-hop', fixedHopSubApp); + +const disabledSubApp = express(); +disabledSubApp.disable('trust proxy'); +disabledSubApp.post('/disabled', rateLimit({ + keyGenerator: (req) => req.ip +}), (req, res) => res.end()); +trustingParent.use('/disabled', disabledSubApp); + +const nonTrustingParent = express(); +const enabledSubApp = express(); +enabledSubApp.enable('trust proxy'); +enabledSubApp.post('/enabled', rateLimit({ + keyGenerator: (req) => req.ip // $ Alert +}), (req, res) => res.end()); +nonTrustingParent.use('/enabled', enabledSubApp); + +const setTrustingSubApp = express(); +setTrustingSubApp.set('trust proxy', true); +setTrustingSubApp.post('/set-trusting', rateLimit({ + keyGenerator: (req) => req.ip // $ Alert +}), (req, res) => res.end()); +nonTrustingParent.use('/set-trusting', setTrustingSubApp); + +const sharedKeyGenerator = (req) => req.ip; // $ Alert +const sharedTrustedApp = express(); +sharedTrustedApp.enable('trust proxy'); +sharedTrustedApp.post('/shared-key', rateLimit({ + keyGenerator: sharedKeyGenerator +}), (req, res) => res.end()); +const sharedSafeApp = express(); +sharedSafeApp.post('/shared-key', rateLimit({ + keyGenerator: sharedKeyGenerator +}), (req, res) => res.end()); + +function readClientIp(req) { + return req.ip; // $ Source +} + +const sharedHelperTrustedApp = express(); +sharedHelperTrustedApp.enable('trust proxy'); +sharedHelperTrustedApp.post('/shared-helper', rateLimit({ + keyGenerator: (req) => readClientIp(req) // $ Alert +}), (req, res) => res.end()); +const sharedHelperSafeApp = express(); +sharedHelperSafeApp.post('/shared-helper', rateLimit({ + keyGenerator: (req) => readClientIp(req) +}), (req, res) => res.end());