🔒 prevent passwort denial of server

This commit is contained in:
Flam3rboy 2021-02-03 17:42:49 +01:00
parent 18d4aa0c67
commit 54e5b61095
13 changed files with 62 additions and 36 deletions

View File

@ -13,6 +13,6 @@
"BASE_TYPE_CONSTANT": "Dieses Feld muss {{value}} sein",
"EMAIL_TYPE_INVALID_EMAIL": "Keine gültige E-Mail Adresse",
"DATE_TYPE_PARSE": "Ungültiges Datum {{date}}, muss dem ISO8601 Standard entsprechen",
"BASE_TYPE_BAD_LENGTH": "Muss {{length}} lang sein"
"BASE_TYPE_BAD_LENGTH": "Muss {{length}} Zeichen lang sein"
}
}

View File

@ -1,6 +1,6 @@
import { Request, Response, Router } from "express";
import db from "../../../../util/Database";
import { check, FieldErrors } from "../../../../util/instanceOf";
import { check, FieldErrors, Length } from "../../../../util/instanceOf";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import Config from "../../../../util/Config";
@ -11,8 +11,8 @@ const router: Router = Router();
router.post(
"/",
check({
login: String, // email or telephone
password: String,
login: new Length(String, 2, 100), // email or telephone
password: new Length(String, 8, 64),
$undelete: Boolean,
$captcha_key: String,
$login_source: String,

View File

@ -2,22 +2,24 @@ import { NextFunction, Request, Response, Router } from "express";
import Config from "../../../../util/Config";
import db from "../../../../util/Database";
import bcrypt from "bcrypt";
import { check, Email, EMAIL_REGEX, FieldErrors } from "../../../../util/instanceOf";
import { check, Email, EMAIL_REGEX, FieldErrors, Length } from "../../../../util/instanceOf";
import { Snowflake } from "../../../../util/Snowflake";
import "missing-native-js-functions";
import { User } from "../../../../models/User";
import { generateToken } from "./login";
import { checkLength, trimSpecial } from "../../../../util/String";
import { trimSpecial } from "../../../../util/String";
const router: Router = Router();
router.post(
"/",
check({
username: String,
password: String,
username: new Length(String, 2, 32),
// TODO: check min password length in config
// prevent Denial of Service with max length of 64 chars
password: new Length(String, 8, 64),
consent: Boolean,
$email: Email,
$email: new Length(Email, 5, 100),
$fingerprint: String,
$invite: String,
$date_of_birth: Date, // "2000-04-03"
@ -52,9 +54,6 @@ router.post(
// discriminator will be randomly generated
let discriminator = "";
checkLength(adjusted_username, 2, 32, "username", req);
checkLength(password, 8, 100, "password", req);
const { register } = Config.get();
// check if registration is allowed
@ -146,7 +145,10 @@ router.post(
adjusted_password = await bcrypt.hash(password, 12);
let exists;
// TODO: is there any better way to generate a random discriminator only once, without checking if it already exists in the database?
// randomly generates a discriminator between 1 and 9999 and checks max five times if it already exists
// if it all five times already exists, abort with USERNAME_TOO_MANY_USERS error
// else just continue
// TODO: is there any better way to generate a random discriminator only once, without checking if it already exists in the mongodb database?
for (let tries = 0; tries < 5; tries++) {
discriminator = Math.randomIntBetween(1, 9999).toString().padStart(4, "0");
exists = await db.data.users({ discriminator, username: adjusted_username }).get({ id: true });

View File

@ -1,7 +1,6 @@
// different version of lambert-server instanceOf with discord error format
import { NextFunction, Request, Response } from "express";
import { TFunction } from "i18next";
import { Tuple } from "lambert-server";
import "missing-native-js-functions";
@ -11,7 +10,7 @@ export const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*
export function check(schema: any) {
return (req: Request, res: Response, next: NextFunction) => {
try {
const result = instanceOf(schema, req.body, { path: "body", t: req.t, ref: { obj: null, key: "" } });
const result = instanceOf(schema, req.body, { path: "body", req, ref: { obj: null, key: "" } });
if (result === true) return next();
throw result;
} catch (error) {
@ -48,6 +47,14 @@ export class Email {
}
}
export class Length {
constructor(public type: any, public min: number, public max: number) {}
check(value: string) {
return value.length >= this.min && value.length <= this.max;
}
}
export function instanceOf(
type: any,
value: any,
@ -55,65 +62,82 @@ export function instanceOf(
path = "",
optional = false,
errors = {},
t,
req,
ref,
}: { path?: string; optional?: boolean; errors?: any; t: TFunction; ref: { key: string | number; obj: any } }
}: { path?: string; optional?: boolean; errors?: any; req: Request; ref: { key: string | number; obj: any } }
): Boolean {
try {
if (!type) return true; // no type was specified
if (value == null) {
if (optional) return true;
throw new FieldError("BASE_TYPE_REQUIRED", t("common:field.BASE_TYPE_REQUIRED"));
throw new FieldError("BASE_TYPE_REQUIRED", req.t("common:field.BASE_TYPE_REQUIRED"));
}
switch (type) {
case String:
if (typeof value === "string") return true;
throw new FieldError("BASE_TYPE_STRING", t("common:field.BASE_TYPE_STRING"));
throw new FieldError("BASE_TYPE_STRING", req.t("common:field.BASE_TYPE_STRING"));
case Number:
value = Number(value);
ref.obj[ref.key] = value;
if (typeof value === "number" && !isNaN(value)) return true;
throw new FieldError("BASE_TYPE_NUMBER", t("common:field.BASE_TYPE_NUMBER"));
throw new FieldError("BASE_TYPE_NUMBER", req.t("common:field.BASE_TYPE_NUMBER"));
case BigInt:
try {
value = BigInt(value);
ref.obj[ref.key] = value;
if (typeof value === "bigint") return true;
} catch (error) {}
throw new FieldError("BASE_TYPE_BIGINT", t("common:field.BASE_TYPE_BIGINT"));
throw new FieldError("BASE_TYPE_BIGINT", req.t("common:field.BASE_TYPE_BIGINT"));
case Boolean:
if (value == "true") value = true;
if (value == "false") value = false;
ref.obj[ref.key] = value;
if (typeof value === "boolean") return true;
throw new FieldError("BASE_TYPE_BOOLEAN", t("common:field.BASE_TYPE_BOOLEAN"));
throw new FieldError("BASE_TYPE_BOOLEAN", req.t("common:field.BASE_TYPE_BOOLEAN"));
case Tuple:
if ((<Tuple>type).types.some((x) => instanceOf(x, value, { path, optional, errors, t, ref })))
return true;
throw new FieldError("BASE_TYPE_CHOICES", t("common:field.BASE_TYPE_CHOICES", { types: type.types }));
case Email:
if (new Email(value).check()) return true;
throw new FieldError("EMAIL_TYPE_INVALID_EMAIL", t("common:field.EMAIL_TYPE_INVALID_EMAIL"));
throw new FieldError("EMAIL_TYPE_INVALID_EMAIL", req.t("common:field.EMAIL_TYPE_INVALID_EMAIL"));
case Date:
value = new Date(value);
ref.obj[ref.key] = value;
// value.getTime() can be < 0, if it is before 1970
if (!isNaN(value)) return true;
throw new FieldError("DATE_TYPE_PARSE", t("common:field.DATE_TYPE_PARSE"));
throw new FieldError("DATE_TYPE_PARSE", req.t("common:field.DATE_TYPE_PARSE"));
}
if (typeof type === "object") {
if (type?.constructor?.name != "Object") {
if (type instanceof Tuple) {
if ((<Tuple>type).types.some((x) => instanceOf(x, value, { path, optional, errors, req, ref })))
return true;
throw new FieldError(
"BASE_TYPE_CHOICES",
req.t("common:field.BASE_TYPE_CHOICES", { types: type.types })
);
} else if (type instanceof Length) {
let length = <Length>type;
if (instanceOf(length.type, value, { path, optional, req, ref, errors }) !== true) return errors;
let val = ref.obj[ref.key];
if ((<Length>type).check(val)) return true;
throw new FieldError(
"BASE_TYPE_BAD_LENGTH",
req.t("common:field.BASE_TYPE_BAD_LENGTH", {
length: `${type.min} - ${type.max}`,
})
);
}
if (value instanceof type) return true;
throw new FieldError("BASE_TYPE_CLASS", t("common:field.BASE_TYPE_CLASS", { type }));
throw new FieldError("BASE_TYPE_CLASS", req.t("common:field.BASE_TYPE_CLASS", { type }));
}
if (typeof value !== "object") throw new FieldError("BASE_TYPE_OBJECT", t("common:field.BASE_TYPE_OBJECT"));
if (typeof value !== "object")
throw new FieldError("BASE_TYPE_OBJECT", req.t("common:field.BASE_TYPE_OBJECT"));
if (Array.isArray(type)) {
if (!Array.isArray(value)) throw new FieldError("BASE_TYPE_ARRAY", t("common:field.BASE_TYPE_ARRAY"));
if (!Array.isArray(value))
throw new FieldError("BASE_TYPE_ARRAY", req.t("common:field.BASE_TYPE_ARRAY"));
if (!type.length) return true; // type array didn't specify any type
return (
@ -124,7 +148,7 @@ export function instanceOf(
path: `${path}[${i}]`,
optional,
errors: errors[i],
t,
req,
ref: { key: i, obj: value },
}) === true
);
@ -136,7 +160,7 @@ export function instanceOf(
Object.keys(type).map((x) => (x.startsWith(OPTIONAL_PREFIX) ? x.slice(OPTIONAL_PREFIX.length) : x))
);
if (diff.length) throw new FieldError("UNKOWN_FIELD", t("common:field.UNKOWN_FIELD", { key: diff }));
if (diff.length) throw new FieldError("UNKOWN_FIELD", req.t("common:field.UNKOWN_FIELD", { key: diff }));
return (
Object.keys(type).every((key) => {
@ -150,7 +174,7 @@ export function instanceOf(
path: `${path}.${newKey}`,
optional: OPTIONAL,
errors: errors[newKey],
t,
req,
ref: { key: newKey, obj: value },
}) === true
);
@ -158,10 +182,10 @@ export function instanceOf(
);
} else if (typeof type === "number" || typeof type === "string" || typeof type === "boolean") {
if (value === type) return true;
throw new FieldError("BASE_TYPE_CONSTANT", t("common:field.BASE_TYPE_CONSTANT", { value: type }));
throw new FieldError("BASE_TYPE_CONSTANT", req.t("common:field.BASE_TYPE_CONSTANT", { value: type }));
} else if (typeof type === "bigint") {
if (BigInt(value) === type) return true;
throw new FieldError("BASE_TYPE_CONSTANT", t("common:field.BASE_TYPE_CONSTANT", { value: type }));
throw new FieldError("BASE_TYPE_CONSTANT", req.t("common:field.BASE_TYPE_CONSTANT", { value: type }));
}
return type == value;