add throttling to login and register forms

This commit is contained in:
Evert Prants 2022-12-03 11:25:49 +02:00
parent 60623c79b5
commit f1ee066321
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
5 changed files with 118 additions and 1 deletions

View File

@ -0,0 +1,56 @@
import {
Injectable,
CanActivate,
ExecutionContext,
HttpException,
} from '@nestjs/common';
import { Request } from 'express';
import { AuditAction } from 'src/modules/objects/audit/audit.enum';
import { AuditService } from 'src/modules/objects/audit/audit.service';
import { IPLimitService } from 'src/modules/utility/services/iplimit.service';
@Injectable()
export class LoginAntispamGuard implements CanActivate {
constructor(private iplimit: IPLimitService, private audit: AuditService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
if (['GET', 'OPTIONS'].includes(request.method)) return true;
const known = this.iplimit.getAddressLimit(request.ip);
if (known && known.attempts >= 3) {
if (known.attempts >= 5) {
let reported = false;
if (!known.reported) {
reported = true;
await this.audit.insertAudit(
AuditAction.THROTTLE,
`antispam-guard ${known.attempts} attempts`,
undefined,
request.ip,
request.header('user-agent'),
);
}
const limitMinutes = known.attempts > 10 ? 30 : 10; // Half-Hour
this.iplimit.limitUntil(request.ip, limitMinutes * 60 * 1000, reported);
await new Promise((resolve) =>
setTimeout(resolve, known.attempts * 1000),
);
throw new HttpException(
`Too Many Requests. Try again in ${limitMinutes} minutes.`,
429,
);
}
await new Promise((resolve) => setTimeout(resolve, 1000));
}
this.iplimit.limitUntil(request.ip, 30 * 1000); // 30 seconds
return true;
}
}

View File

@ -8,10 +8,12 @@ import {
Req,
Res,
Session,
UseGuards,
} from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { Request, Response } from 'express';
import { SessionData } from 'express-session';
import { LoginAntispamGuard } from 'src/guards/login-antispam.guard';
import { AuditAction } from 'src/modules/objects/audit/audit.enum';
import { AuditService } from 'src/modules/objects/audit/audit.service';
import {
@ -33,6 +35,7 @@ interface VerifyChallenge {
}
@Controller('/login')
@UseGuards(LoginAntispamGuard)
export class LoginController {
constructor(
private readonly userService: UserService,

View File

@ -8,9 +8,11 @@ import {
Req,
Res,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';
import { Request, Response } from 'express';
import { LoginAntispamGuard } from 'src/guards/login-antispam.guard';
import { ConfigurationService } from 'src/modules/config/config.service';
import { AuditAction } from 'src/modules/objects/audit/audit.enum';
import { AuditService } from 'src/modules/objects/audit/audit.service';
@ -19,6 +21,7 @@ import { FormUtilityService } from 'src/modules/utility/services/form-utility.se
import { RegisterDto } from './register.interfaces';
@Controller('/register')
@UseGuards(LoginAntispamGuard)
export class RegisterController {
constructor(
private readonly userService: UserService,

View File

@ -0,0 +1,47 @@
import { Injectable } from '@nestjs/common';
export interface IPLimit {
ip: string;
attempts: number;
expires: number;
reported: boolean;
}
@Injectable()
export class IPLimitService {
public limitedAddresses: IPLimit[] = [];
public getAddressLimit(ip: string) {
this.flush();
const entry = this.limitedAddresses.find((item) => item.ip === ip);
if (!entry) return null;
return entry;
}
public limitUntil(ip: string, expires: number, reported = false) {
const existing = this.limitedAddresses.find((item) => item.ip === ip);
if (existing) {
existing.attempts++;
existing.expires = expires + Date.now();
if (reported) existing.reported = true;
return existing;
}
const newObj = {
ip,
expires: expires + Date.now(),
attempts: 0,
reported,
};
this.limitedAddresses.push(newObj);
return newObj;
}
public flush() {
this.limitedAddresses = this.limitedAddresses.filter(
(entry) => entry.expires > Date.now(),
);
}
}

View File

@ -1,5 +1,6 @@
import { Global, Module } from '@nestjs/common';
import { FormUtilityService } from './services/form-utility.service';
import { IPLimitService } from './services/iplimit.service';
import { PaginationService } from './services/paginate.service';
import { QRCodeService } from './services/qr-code.service';
import { TokenService } from './services/token.service';
@ -11,7 +12,14 @@ import { TokenService } from './services/token.service';
FormUtilityService,
QRCodeService,
PaginationService,
IPLimitService,
],
exports: [
TokenService,
FormUtilityService,
QRCodeService,
PaginationService,
IPLimitService,
],
exports: [TokenService, FormUtilityService, QRCodeService, PaginationService],
})
export class UtilityModule {}