Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>

<overview>
<p>
Rate limiters such as <code>express-rate-limit</code> and <code>express-slow-down</code> count
requests per client, using a key computed by the <code>keyGenerator</code> option. If the key is
taken from a value that the client controls, such as the <code>X-Forwarded-For</code> or
<code>X-Real-IP</code> 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.
</p>
<p>
The same applies to <code>req.ip</code> and <code>req.ips</code> when the Express application
trusts all proxies (<code>app.enable('trust proxy')</code> or
<code>app.set('trust proxy', true)</code>), because Express then takes the client address from the
left-most, client-supplied, entry of the <code>X-Forwarded-For</code> header. Note that Node.js
lower-cases the names of request headers, so a lookup such as
<code>req.headers['X-Forwarded-For']</code> is always <code>undefined</code>; a key such as
<code>req.headers['X-Forwarded-For'] ?? req.ip</code> therefore depends only on <code>req.ip</code>.
</p>
</overview>

<recommendation>
<p>
Do not derive rate-limiting keys from request headers. Use <code>req.ip</code> and configure the
Express <code>trust proxy</code> 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.
</p>
</recommendation>

<example>
<p>
In the following example, all proxies are trusted and the limiter is keyed on the raw
<code>X-Forwarded-For</code> header, falling back to <code>req.ip</code>. Both values are chosen
by the client, so the limit can be evaded by changing the header on every request.
</p>
<sample src="examples/RateLimitSpoofableKeyBad.js" />

<p>
In the following example, only the single reverse proxy in front of the application is trusted,
so <code>req.ip</code> is the address of the client as seen by that proxy.
</p>
<sample src="examples/RateLimitSpoofableKeyGood.js" />
</example>

<references>
<li>Express: <a href="https://expressjs.com/en/guide/behind-proxies.html">Express behind proxies</a>.</li>
<li>express-rate-limit: <a href="https://express-rate-limit.mintlify.app/guides/troubleshooting-proxy-issues">Troubleshooting proxy issues</a>.</li>
<li>OWASP: <a href="https://owasp.org/www-community/controls/Blocking_Brute_Force_Attacks">Blocking Brute Force Attacks</a>.</li>
<li>Common Weakness Enumeration: <a href="https://cwe.mitre.org/data/definitions/307.html">CWE-307</a>.</li>
<li>Common Weakness Enumeration: <a href="https://cwe.mitre.org/data/definitions/348.html">CWE-348</a>.</li>
</references>
</qhelp>
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
/**
* @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 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(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
or
call.getMethodName() = "set" and
call.getArgument(1).asExpr().(BooleanLiteral).getBoolValue() = true
)
)
}

/** 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
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*()
Comment thread
felickz marked this conversation as resolved.
Resolved
)
}

/**
* 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 |
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 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 |
req = keyGeneratorRequest(limiter.getKeyGenerator())
|
exists(string header | header = clientIpHeader() |
(
// 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
) and
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" 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 {
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<RateLimitSpoofableKeyConfig>;

import RateLimitSpoofableKeyFlow::PathGraph

from
RateLimitSpoofableKeyFlow::PathNode source, RateLimitSpoofableKeyFlow::PathNode sink,
RateLimiterCreation limiter
where
RateLimitSpoofableKeyFlow::flowPath(source, sink) and
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,
"rate limiter"
Original file line number Diff line number Diff line change
@@ -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
}));
Original file line number Diff line number Diff line change
@@ -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
}));
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>

<overview>
<p>
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.
</p>
<p>
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.
</p>
</overview>

<recommendation>
<p>
Always use <code>req.session.regenerate(...);</code> to start a new session when a user logs in or out.
</p>
</recommendation>

<example>
<p>
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.
</p>
<sample src="examples/SessionFixationBad.js" />

<p>
The following example solves the problem by calling <code>req.session.regenerate()</code> before
storing the authenticated user, so that the previous session is not reused.
</p>
<sample src="examples/SessionFixationGood.js" />
</example>

<references>
<li>OWASP: <a href="https://owasp.org/www-community/attacks/Session_fixation">Session fixation</a>.</li>
<li>Stack Overflow: <a href="https://stackoverflow.com/questions/22209354/creating-a-new-session-after-authentication-with-passport/30468384#30468384">Creating a new session after authentication with Passport</a>.</li>
<li>Common Weakness Enumeration: <a href="https://cwe.mitre.org/data/definitions/384.html">CWE-384</a>.</li>
</references>
</qhelp>
61 changes: 61 additions & 0 deletions languages/javascript/custom/src/SessionFixation/SessionFixation.ql
Original file line number Diff line number Diff line change
@@ -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."
Loading
Loading