Skip to content

ActivityPub-federated video streaming platform using P2P directly in your web browser

Require multiple IPs to block an account

Chocobozzz538f58cdbb50
diff --git a/config/config-schema.json b/config/config-schema.json
index 760d87f475..b125178040 100644
--- a/config/config-schema.json
+++ b/config/config-schema.json
@@ -264,7 +264,7 @@
"additionalProperties": false
},
"login_lockout": {
- "description": "Lock an account (independently of the source IP) after too many password/OTP login failures. Since this is keyed per account rather than per IP, an attacker who knows a username can keep it locked by repeating failed logins once per window; raise max/lower window if this tradeoff is a concern for your instance",
+ "description": "Lock an account (independently of the source IP) after too many password/OTP login failures. Each source IP's failures only count towards the lock up to max_per_ip, so a single attacker IP cannot lock an account by itself; reaching max requires failures from several distinct IPs",
"type": "object",
"properties": {
"window": {
@@ -273,9 +273,14 @@
"default": "5 minutes"
},
"max": {
- "description": "Failed login/OTP attempts allowed before the account is locked",
+ "description": "Failed login/OTP attempts allowed (summed across contributing IPs, see max_per_ip) before the account is locked",
"type": "integer",
"default": 10
+ },
+ "max_per_ip": {
+ "description": "Cap on how many of a single source IP's failed attempts count towards max",
+ "type": "integer",
+ "default": 3
}
},
"additionalProperties": false
diff --git a/config/default.yaml b/config/default.yaml
index b5f4debd82..737b656f0c 100644
--- a/config/default.yaml
+++ b/config/default.yaml
@@ -74,11 +74,10 @@ rates_limit:
# 60 attempts in 5 minutes
window: 5 minutes
max: 60
- login_lockout: # Lock an account (independently of the source IP) after too many password/OTP login failures
- # Tradeoff: this is keyed per account, not per IP, so an attacker who knows a username can keep it locked
- # by repeating failed logins once per window. Raise max/lower window if this is a concern for your instance
+ login_lockout: # Lock an account after too many password/OTP login failures
window: 5 minutes
- max: 10
+ max: 20 # Requires at least 4 distinct IPs (`max / max_per_ip`) to lock an account
+ max_per_ip: 5 # A single IP's contribution to the account lock is capped at 5 failures
oauth2:
token_lifetime:
diff --git a/config/production.yaml.example b/config/production.yaml.example
index 777e3d6375..1b5cc87e6c 100644
--- a/config/production.yaml.example
+++ b/config/production.yaml.example
@@ -72,11 +72,10 @@ rates_limit:
# 60 attempts in 5 minutes
window: 5 minutes
max: 60
- login_lockout: # Lock an account (independently of the source IP) after too many password/OTP login failures
- # Tradeoff: this is keyed per account, not per IP, so an attacker who knows a username can keep it locked
- # by repeating failed logins once per window. Raise max/lower window if this is a concern for your instance
+ login_lockout: # Lock an account after too many password/OTP login failures
window: 5 minutes
- max: 10
+ max: 20 # Requires at least 4 distinct IPs (`max / max_per_ip`) to lock an account
+ max_per_ip: 5 # A single IP's contribution to the account lock is capped at 5 failures
oauth2:
token_lifetime:
diff --git a/config/test.yaml b/config/test.yaml
index 5334663f07..47eb29dd74 100644
--- a/config/test.yaml
+++ b/config/test.yaml
@@ -28,6 +28,7 @@ rates_limit:
login_lockout:
window: 5 seconds
max: 10
+ max_per_ip: 3
database:
hostname: '127.0.0.1'
diff --git a/packages/tests/src/api/users/login-lockout.ts b/packages/tests/src/api/users/login-lockout.ts
index 7c5e7f5a35..536937aab6 100644
--- a/packages/tests/src/api/users/login-lockout.ts
+++ b/packages/tests/src/api/users/login-lockout.ts
@@ -21,22 +21,36 @@ describe('Test login lockout', function () {
// Sync with rates_limit.login_lockout in config/test.yaml (window is 5 seconds on a test instance)
const maxFailures = 10
+ const maxFailuresPerIP = 3
const lifetimeMs = 5000
function expectLockout (body: PeerTubeProblemDocument) {
expect(body.code).to.equal(ServerErrorCode.TOO_MANY_LOGIN_FAILURES)
}
- async function failLogin (password: string, otpToken?: string) {
+ function xForwardedForAt (index: number) {
+ const ipIndex = Math.floor(index / maxFailuresPerIP) + 1
+
+ return `0.0.0.${ipIndex},127.0.0.1`
+ }
+
+ async function failLogin (password: string, otpToken?: string, xForwardedFor?: string) {
const { body } = await server.login.loginAndGetResponse({
user: { username: userUsername, password },
otpToken,
+ xForwardedFor,
expectedStatus: HttpStatusCode.BAD_REQUEST_400
})
return body as unknown as PeerTubeProblemDocument
}
+ async function failLoginsSpreadOverIPs (count: number, password: string, otpToken?: string) {
+ for (let i = 0; i < count; i++) {
+ await failLogin(password, otpToken, xForwardedForAt(i))
+ }
+ }
+
async function expectLockedLogin (password: string, otpToken?: string) {
const { body } = await server.login.loginAndGetResponse({
user: { username: userUsername, password },
@@ -71,9 +85,7 @@ describe('Test login lockout', function () {
it('Should not lock the account below the failure threshold', async function () {
this.timeout(30000)
- for (let i = 0; i < maxFailures - 1; i++) {
- await failLogin('invalid password')
- }
+ await failLoginsSpreadOverIPs(maxFailures - 1, 'invalid password')
await server.login.login({
user: { username: userUsername, password: userPassword },
@@ -84,9 +96,7 @@ describe('Test login lockout', function () {
it('Should have reset the counter on successful login', async function () {
this.timeout(30000)
- for (let i = 0; i < maxFailures - 1; i++) {
- await failLogin('invalid password')
- }
+ await failLoginsSpreadOverIPs(maxFailures - 1, 'invalid password')
await server.login.login({
user: { username: userUsername, password: userPassword },
@@ -94,13 +104,24 @@ describe('Test login lockout', function () {
})
})
- it('Should lock the account after too many password failures', async function () {
+ it('Should not lock the account from a single IP alone', async function () {
this.timeout(30000)
- for (let i = 0; i < maxFailures; i++) {
+ for (let i = 0; i < maxFailures * 2; i++) {
await failLogin('invalid password')
}
+ await server.login.login({
+ user: { username: userUsername, password: userPassword },
+ expectedStatus: HttpStatusCode.OK_200
+ })
+ })
+
+ it('Should lock the account after too many password failures spread over several IPs', async function () {
+ this.timeout(30000)
+
+ await failLoginsSpreadOverIPs(maxFailures, 'invalid password')
+
// Even with the correct password
await expectLockedLogin(userPassword)
@@ -132,7 +153,7 @@ describe('Test login lockout', function () {
})
for (let i = 0; i < maxFailures; i++) {
- const body = await failLogin(userPassword, '123456')
+ const body = await failLogin(userPassword, '123456', xForwardedForAt(i))
expect(body.code).to.equal(ServerErrorCode.INVALID_TWO_FACTOR)
}
diff --git a/server/core/initializers/config.ts b/server/core/initializers/config.ts
index 6c1ce1c1eb..270dca9cb5 100644
--- a/server/core/initializers/config.ts
+++ b/server/core/initializers/config.ts
@@ -393,7 +393,8 @@ const CONFIG = {
},
LOGIN_LOCKOUT: {
WINDOW_MS: parseDurationToMs(config.get<string>('rates_limit.login_lockout.window')),
- MAX: config.get<number>('rates_limit.login_lockout.max')
+ MAX: config.get<number>('rates_limit.login_lockout.max'),
+ MAX_PER_IP: config.get<number>('rates_limit.login_lockout.max_per_ip')
}
},
TRUST_PROXY: config.get<string[]>('trust_proxy'),
diff --git a/server/core/lib/auth/oauth-user.ts b/server/core/lib/auth/oauth-user.ts
index 42f85184ab..d5e329344c 100644
--- a/server/core/lib/auth/oauth-user.ts
+++ b/server/core/lib/auth/oauth-user.ts
@@ -90,7 +90,7 @@ export async function getUserOrThrow (options: {
const passwordMatch = await user.isPasswordMatch(password)
if (passwordMatch !== true) {
- await Redis.Instance.addLoginFailure(user.id)
+ await Redis.Instance.addLoginFailure(user.id, req.ip)
throwInvalidGrantError()
}
@@ -108,7 +108,7 @@ export async function getUserOrThrow (options: {
}
if (await isOTPValid({ encryptedSecret: user.otpSecret, token: oauthHeaders[OTP.HEADER_NAME] }) !== true) {
- await Redis.Instance.addLoginFailure(user.id)
+ await Redis.Instance.addLoginFailure(user.id, req.ip)
throw new InvalidTwoFactorError(req.t('Invalid two factor header'))
}
diff --git a/server/core/lib/redis.ts b/server/core/lib/redis.ts
index 6903ab0b0f..e6a8304135 100644
--- a/server/core/lib/redis.ts
+++ b/server/core/lib/redis.ts
@@ -192,21 +192,22 @@ class Redis {
/* ************ Login failures ************ */
- async addLoginFailure (userId: number) {
+ // Failures are tracked per source IP
+ // Each IP's contribution to the account lock is capped at MAX_PER_IP so a single IP cannot lock an account by themselves
+ async addLoginFailure (userId: number, ip: string) {
const key = this.generateLoginFailureKey(userId)
+ const field = this.generateLoginFailureIPField(ip)
- const failures = await this.increment(key)
+ await this.incrementHashField(key, field)
await this.setExpiration(key, CONFIG.RATES_LIMIT.LOGIN_LOCKOUT.WINDOW_MS)
-
- return failures
}
async getLoginFailures (userId: number) {
- const value = await this.getValue(this.generateLoginFailureKey(userId))
+ const failuresPerIP = await this.getHash(this.generateLoginFailureKey(userId))
- return value
- ? parseInt(value, 10)
- : 0
+ return Object.values(failuresPerIP).reduce((total, value) => {
+ return total + Math.min(parseInt(value, 10), CONFIG.RATES_LIMIT.LOGIN_LOCKOUT.MAX_PER_IP)
+ }, 0)
}
deleteLoginFailures (userId: number) {
@@ -514,6 +515,10 @@ class Redis {
return 'login-failure-' + userId
}
+ private generateLoginFailureIPField (ip: string) {
+ return sha256(CONFIG.SECRETS.PEERTUBE + '-' + ip)
+ }
+
private generateUserVerifyEmailKey (userId: number) {
return 'verify-email-user-' + userId
}
@@ -588,6 +593,14 @@ class Redis {
return this.client.incr(this.prefix + key)
}
+ private incrementHashField (key: string, field: string) {
+ return this.client.hincrby(this.prefix + key, field, 1)
+ }
+
+ private getHash (key: string) {
+ return this.client.hgetall(this.prefix + key)
+ }
+
private async exists (key: string) {
const result = await this.client.exists(this.prefix + key)