Skip to content

Node.js based forum software built for the modern web

feat: add an ip lockout to loginAttempts

Barış Soner Uşaklı780dd79e9aab
diff --git a/install/data/defaults.json b/install/data/defaults.json
index 29d0e3bbe6..bf1b018d39 100644
--- a/install/data/defaults.json
+++ b/install/data/defaults.json
@@ -7,6 +7,7 @@
"sessionDuration": 0,
"loginAttempts": 5,
"lockoutDuration": 60,
+ "ipLoginAttempts": 20,
"adminReloginDuration": 60,
"postDelay": 10,
"initialPostDelay": 10,
diff --git a/public/language/en-GB/admin/settings/user.json b/public/language/en-GB/admin/settings/user.json
index 08ceba910c..597127978b 100644
--- a/public/language/en-GB/admin/settings/user.json
+++ b/public/language/en-GB/admin/settings/user.json
@@ -22,6 +22,8 @@
"admin-relogin-duration-help": "After a set amount of time accessing the admin section will require re-login, set to 0 to disable",
"login-attempts": "Login attempts per hour",
"login-attempts-help": "If login attempts to a user's account exceeds this threshold, that account will be locked for a pre-configured amount of time",
+ "ip-login-attempts": "Login attempts per IP per hour",
+ "ip-login-attempts-help": "If login attempts from a single IP address exceed this threshold, that IP will be temporarily locked out",
"lockout-duration": "Account Lockout Duration (minutes)",
"login-days": "Days to remember user login sessions",
"password-expiry-days": "Force password reset after a set number of days",
diff --git a/src/user/auth.js b/src/user/auth.js
index f95057e28a..d3f0c59fcf 100644
--- a/src/user/auth.js
+++ b/src/user/auth.js
@@ -11,7 +11,27 @@ module.exports = function (User) {
User.auth = {};
User.auth.logAttempt = async function (uid, ip) {
- // Use a fixed dummy key for non-existent users to prevent username enumeration (CWE-203)
+ const onHourMs = 60 * 60 * 1000;
+ const ipLocked = await db.exists(`lockout:ip:${ip}`);
+ if (ipLocked) {
+ throw new Error('[[error:ip-locked]]');
+ }
+ const ipAttempts = await db.increment(`loginAttempts:ip:${ip}`);
+ if (ipAttempts <= meta.config.ipLoginAttempts) {
+ await db.pexpire(`loginAttempts:ip:${ip}`, onHourMs);
+ } else {
+ // Lock the IP
+ await db.set(`lockout:ip:${ip}`, '');
+ await db.pexpire(`lockout:ip:${ip}`, onHourMs);
+ await db.delete(`loginAttempts:ip:${ip}`);
+ await events.log({
+ type: 'ip-locked',
+ ip: ip,
+ });
+ throw new Error('[[error:ip-locked]]');
+ }
+
+ // Use a fixed dummy key for non‑existent users to prevent username enumeration (CWE-203)
const targetKey = parseInt(uid, 10) > 0 ? uid : 'dummy';
const exists = await db.exists(`lockout:${targetKey}`);
diff --git a/src/views/admin/settings/user.tpl b/src/views/admin/settings/user.tpl
index f32a0208eb..dc6939d2ed 100644
--- a/src/views/admin/settings/user.tpl
+++ b/src/views/admin/settings/user.tpl
@@ -70,6 +70,13 @@
{{tx("admin/settings/user:login-attempts-help")}}
</p>
</div>
+ <div class="mb-3">
+ <label class="form-label" for="ipLoginAttempts">{{tx("admin/settings/user:ip-login-attempts")}}</label>
+ <input id="ipLoginAttempts" type="text" class="form-control" data-field="ipLoginAttempts" placeholder="5" />
+ <p class="form-text">
+ {{tx("admin/settings/user:ip-login-attempts-help")}}
+ </p>
+ </div>
<div class="mb-3">
<label class="form-label" for="lockoutDuration">{{tx("admin/settings/user:lockout-duration")}}</label>
<input id="lockoutDuration" type="text" class="form-control" data-field="lockoutDuration" placeholder="60" />
diff --git a/test/authentication.js b/test/authentication.js
index 114c97a014..e73504597c 100644
--- a/test/authentication.js
+++ b/test/authentication.js
@@ -839,6 +839,50 @@ describe('authentication', () => {
assert(locked);
});
+ it('should lockout IP after 5 failed login attempts', async () => {
+ const ip = '1.2.3.4';
+ const jar = request.jar();
+ const oldIpLoginAttempts = meta.config.ipLoginAttempts;
+ meta.config.ipLoginAttempts = 5;
+ const oldLoginAttempts = meta.config.loginAttempts;
+ meta.config.loginAttempts = 1000;
+ const csrf_token = await helpers.getCsrfToken(jar);
+ const payload = { username: 'nonexistent', password: 'wrongpassword' };
+ const headers = {
+ 'x-forwarded-for': ip,
+ 'x-csrf-token': csrf_token,
+ };
+
+ // 5 attempts should not lock out yet
+ for (let i = 0; i < 5; i++) {
+ // eslint-disable-next-line no-await-in-loop
+ const { response, body } = await request.post(`${nconf.get('url')}/login`, {
+ jar,
+ body: payload,
+ headers,
+ });
+ assert.strictEqual(response.statusCode, 403);
+ assert.strictEqual(body, '[[error:invalid-login-credentials]]');
+ }
+
+ // 6th attempt should lock out
+ const { response: res21, body: body21 } = await request.post(`${nconf.get('url')}/login`, {
+ jar,
+ body: payload,
+ headers,
+ });
+ assert.strictEqual(res21.statusCode, 403);
+ assert.strictEqual(body21, '[[error:ip-locked]]');
+
+ // verify lockout key exists
+ const locked = await db.exists(`lockout:ip:${ip}`);
+ assert(locked);
+
+ meta.config.loginAttempts = oldLoginAttempts;
+ meta.config.ipLoginAttempts = oldIpLoginAttempts;
+ });
+
+
it('should clear all reset tokens upon successful login', async () => {
const code = await user.reset.generate(regularUid);
await helpers.loginUser('regular', 'regularpwd');
diff --git a/test/mocks/databasemock.js b/test/mocks/databasemock.js
index de979a6299..66fdaf82e7 100644
--- a/test/mocks/databasemock.js
+++ b/test/mocks/databasemock.js
@@ -205,6 +205,7 @@ async function setupMockDefaults() {
meta.config.autoDetectLang = 0;
meta.config.activitypubProbeTimeout = 30000;
meta.config.postQueue = 0;
+ meta.config.ipLoginAttempts = 1000000;
require('../../src/cache/tracker').resetAll();
require('../../src/middleware/uploads').clearCache(); // lazily created; explicit clear still req'd.