Initial commit

This commit is contained in:
2020-10-19 19:00:17 +02:00
parent 634ead79db
commit 48140f557b
61 changed files with 18269 additions and 0 deletions

1
backend/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.env

130
backend/app.ts Normal file
View File

@@ -0,0 +1,130 @@
import { bold } from 'chalk';
import * as figlet from 'figlet';
import * as mongoose from 'mongoose';
import { exit } from 'process';
import { hash } from 'argon2';
import { config as dconfig } from 'dotenv';
import * as winston from 'winston';
import * as express from 'express';
import { User } from './models/user/user.model';
import { UserType } from './models/user/user.interface';
import bodyParser = require('body-parser');
import { DeleteUser, GetUser, LoginUser, MW_User, PatchUser } from './endpoints/user';
import { hashPassword, randomPepper, randomString } from './lib/crypto';
import { config } from './config';
// Load .env
dconfig({ debug: true, encoding: 'UTF-8' });
export const MONGO_URI = process.env.MONGO_URI || "";
export const JWT_SECRET = process.env.JWT_SECRET;
export const IS_DEBUG = process.env.DEBUG == 'true'
export let logger: winston.Logger;
async function run() {
const { combine, timestamp, label, printf, prettyPrint } = winston.format;
const myFormat = printf(({ level, message, label, timestamp }) => {
return `${timestamp} ${level} ${message}`;
});
/**
* Printing starting screen
*/
console.log(figlet.textSync('Livebeat', {
font: 'Doom'
}));
console.log(`Starting up version ${bold("1.0.0")} of Livebeat ...
============================================`)
/**
* Setting up logger
*/
logger = winston.createLogger({
level: IS_DEBUG ? 'debug' : 'info',
levels: winston.config.syslog.levels,
format: combine(
timestamp(),
prettyPrint(),
myFormat
),
defaultMeta: { },
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// Adding seperate logger for files (with color)
logger.add(new winston.transports.Console({
format: combine(
winston.format.colorize({ level: true }),
timestamp(),
prettyPrint(),
myFormat
)
}));
logger.info("Logger started");
if (IS_DEBUG) {
logger.info("Debug mode is enabled. Do not use this in production!")
}
if (JWT_SECRET == undefined) {
logger.crit("No JWT secret was provided. Make sure you add JWT_SECRET=YOUR_SECRET to your .env file.");
exit(1);
}
/**
* Database connection
*/
const connection = await mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }).catch((err) => {
logger.crit("Database connection could not be made: ", err);
exit(1);
});
logger.info(`Database connection made to ${mongoose.connection.host}`);
// Check if admin account doesn't exists
if((await User.countDocuments({ type: UserType.ADMIN })) == 0) {
const randomPassword = "$1" + randomString(12);
const salt = randomString(config.authentification.salt_length);
await User.create({
name: 'admin',
password: await hashPassword(randomPassword + salt + randomPepper()),
salt,
createdAt: Date.now(),
lastLogin: 0,
type: UserType.ADMIN
});
logger.info("===================================================");
logger.info("ADMIN USER HAS BEEN CREATED! Username: admin\tPassword: " + randomPassword);
logger.info("===================================================");
} else {
logger.debug("At least one admin user already exists, skip.");
}
/**
* HTTP server
*/
const app = express();
app.use(express.json());
app.use(bodyParser.json({ limit: '5kb' }));
app.get('/user/', MW_User, (req, res) => GetUser(req, res));
app.get('/user/:id', MW_User, (req, res) => GetUser(req, res));
app.patch('/user/:id', MW_User, (req, res) => PatchUser(req, res));
app.delete('/user/:id', MW_User, (req, res) => DeleteUser(req, res));
app.post('/user/login', (req, res) => LoginUser(req, res));
app.listen(config.http.port, config.http.host, () => {
logger.info(`HTTP server is running at ${config.http.host}:${config.http.port}`);
});
}
run();

32
backend/config.ts Normal file
View File

@@ -0,0 +1,32 @@
/**
* Here you can change various settings like database credentials, http settings and more.
*
* Debug mode and MongoDB connections are set via enviroment variables for security reasons.
*/
export const config: IConfig = {
authentification: {
pepper: 'J3%_zö\\^',
salt_length: 8,
argonTimecost: 8,
minPasswordLength: 4,
maxPasswordLength: 150
},
http: {
port: 8040,
host: "0.0.0.0"
}
}
export interface IConfig {
authentification: {
pepper: string,
salt_length: number,
argonTimecost: number,
minPasswordLength: number,
maxPasswordLength: number
},
http: {
port: number,
host: string
}
}

86
backend/endpoints/user.ts Normal file
View File

@@ -0,0 +1,86 @@
import { Request, Response } from "express";
import { verifyPassword } from "../lib/crypto";
import { User } from "../models/user/user.model";
import { sign, decode, verify } from 'jsonwebtoken';
import { JWT_SECRET, logger } from "../app";
import { IUser } from "../models/user/user.interface";
export async function GetUser(req: Request, res: Response) {
}
export async function DeleteUser(req: Request, res: Response) {
}
export async function PatchUser(req: Request, res: Response) {
}
export async function LoginUser(req: Request, res: Response) {
const username = req.body.username;
const password = req.body.password;
const twoFA = req.body.twoFA;
const user = await User.findOne({ name: username });
// Check if user exists
if (user == undefined) {
setTimeout(() => {
res.status(404).send({ message: "Either the username or password is wrong." });
}, Math.random() * 1500 + 400);
return;
}
// Check if 2FA is turned on (the attack doesn't know yet if the password is wrong)
if (user.twoFASecret != undefined) {
if (twoFA == undefined) {
res.status(401).send({ message: "2FA code is required." });
return;
}
// TODO: Implement 2FA logic here
}
// Check if password is wrong
if (!await verifyPassword(password + user.salt, user.password)) {
res.status(404).send({ message: 'Either the username or password is wrong.' });
return;
}
// We're good. Create JWT token.
const token = sign({ user: user._id }, JWT_SECRET!, { notBefore: Date.now(), expiresIn: '30d' });
logger.info(`User ${user.name} logged in.`)
res.status(200).send({ token });
}
/**
* This middleware validates any tokens that are required to access most of the endpoints.
* Note: This validation doesn't contain any permission checking.
*/
export async function MW_User(req: Request, res: Response, next: () => void) {
if (req.headers.token === undefined) {
res.status(401).send();
return;
}
const token = req.headers.token.toString();
try {
// Verify token
if(await verify(token, JWT_SECRET!, { algorithms: ['HS256'] })) {
// Token is valid, now look if user is in db (in case he got deleted)
const id: number = Number(decode(token, { json: true })!.id);
const db = await User.findOne({ where: { id } });
if (db !== undefined) {
next();
return;
} else {
res.status(401).send();
}
} else {
res.status(401).send();
}
} catch (err) {
if (err) res.status(401).send();
}
}

105
backend/lib/crypto.ts Normal file
View File

@@ -0,0 +1,105 @@
import { hash, verify } from 'argon2';
import { config } from '../config';
import { IS_DEBUG, logger } from '../app';
export async function hashPassword(input: string): Promise<string> {
const start = Date.now();
return new Promise<string>(async (resolve, reject) => {
// Get real password (remove salt and pepper)
const realPassword = input.substring(0, input.length - config.authentification.salt_length - 1);
if (!check_password_requirements(realPassword)) {
if (!IS_DEBUG) reject("This password does not meet the minimum requirements!");
else {
reject(`This password does not meet the minimum requirements! (${input} => ${realPassword})`);
}
return;
}
try {
const hashed = await hash(input, {
hashLength: 42,
memoryCost: 1024*32,
parallelism: 2,
timeCost: config.authentification.argonTimecost
});
const finished = Date.now();
logger.debug("Hashing took " + (finished-start) + "ms to finish! " + input);
resolve(hashed);
} catch(err) {
reject(err);
}
});
}
/**
* Verfiy If given password matches with provided hash by brute forcing the pepper.
* @param password Password with salt appended
* @param hashInput Hash from database
*/
export async function verifyPassword(password: string, hashInput: string): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
const start = Date.now();
const peppers = config.authentification.pepper.split('');
const realPassword = password.substring(0, password.length - config.authentification.salt_length);
while (peppers.length !== 0) {
const pepper = peppers[Math.floor(Math.random()*peppers.length)];
if (IS_DEBUG) {
logger.debug(`Try ${password}}${pepper} (left: ${peppers})`);
} else {
// Show censored (with fixed length) password in non-debug mode to prevent password leaking.
logger.debug(`Try ********${password.replace(realPassword, '')}${pepper} (left: ${peppers})`);
}
if (await verify(hashInput, password + pepper)) {
const finished = Date.now();
logger.debug("Verifying took " + (finished-start) + "ms to complete!");
resolve(true);
return;
} else {
peppers.splice(peppers.indexOf(pepper), 1);
}
}
resolve(false);
});
}
export function randomString(length: number): string {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const charactersLength = characters.length;
for ( let i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
export function randomPepper(): string {
return config.authentification.pepper.charAt(Math.floor(Math.random() * config.authentification.pepper.length));
}
/**
* Requirements are:
* - at least 8 characters
* - min one upper-, lowercase- and special character
* - min one number
*/
export function check_password_requirements(password: string): boolean {
// Check for length
if (password.length < config.authentification.minPasswordLength ||
password.length > config.authentification.maxPasswordLength) return false;
// Check for one lowercase
if (!(/^(?=.*[a-z]).+$/.test(password))) return false;
// Check for one uppercase
if (!(/^(?=.*[A-Z]).+$/.test(password))) return false;
// Check for one uppercase
if (!(/^(?=.*[0-9]).+$/.test(password))) return false;
// Check for special characters
if (!(/[^A-Za-z0-9]/.test(password))) return false;
return true;
}

View File

@@ -0,0 +1,12 @@
import { Document } from 'mongoose';
import { IUser } from '../user/user.interface';
export interface IPhone extends Document {
displayName: String,
modelName: String,
operatingSystem: String,
architecture: String,
user: IUser,
updatedAt?: Date,
createdAt?: Date
}

View File

@@ -0,0 +1,6 @@
import { Model, model } from 'mongoose';
import { IPhone } from './phone.interface';
import { schemaPhone } from './phone.schema';
const modelPhone: Model<IPhone> = model<IPhone>('Phone', schemaPhone , 'Phone');
export { modelPhone as Phone };

View File

@@ -0,0 +1,17 @@
import { Schema } from 'mongoose';
import { User } from '../user/user.model';
const schemaPhone = new Schema({
displayName: { type: String, required: true },
modelName: { type: String, required: false },
operatingSystem: { type: String, required: false },
architecture: { type: String, required: false },
user: { type: User, required: true }
}, {
timestamps: {
createdAt: true,
updatedAt: true
}
});
export { schemaPhone };

View File

@@ -0,0 +1,11 @@
import { Document } from 'mongoose';
import { IPhone } from '../phone/phone.interface';
export interface ITrack extends Document {
coordinate?: number[],
velocity?: number,
battery?: number,
magneticField?: number,
phone: IPhone,
createdAt?: Date
}

View File

@@ -0,0 +1,6 @@
import { Model, model } from 'mongoose';
import { ITrack } from './track.interface';
import { schemaTrack } from './track.schema';
const modelTrack: Model<ITrack> = model<ITrack>('Track', schemaTrack, 'Track');
export { modelTrack as Phone };

View File

@@ -0,0 +1,16 @@
import { Schema } from 'mongoose';
import { Phone } from '../phone/phone.model';
const schemaTrack = new Schema({
coordinate: { type: [Number], required: false },
velocity: { type: Number, required: false },
battery: { type: Number, required: false },
magneticField: { type: Number, required: false },
phone: { type: Phone, required: true, default: 'user' }
}, {
timestamps: {
createdAt: true
}
});
export { schemaTrack };

View File

@@ -0,0 +1,17 @@
import { Document } from 'mongoose';
export enum UserType {
ADMIN = 'admin',
USER = 'user',
GUEST = 'guest'
}
export interface IUser extends Document {
name: string,
password: string,
salt: string,
type: UserType,
lastLogin: Date,
twoFASecret?: string,
createdAt?: Date
}

View File

@@ -0,0 +1,6 @@
import { Model, model } from 'mongoose';
import { IUser } from "./user.interface";
import { schemaUser } from './user.schema';
const modelUser: Model<IUser> = model<IUser>('User', schemaUser , 'User');
export { modelUser as User };

View File

@@ -0,0 +1,16 @@
import { Schema } from 'mongoose';
const schemaUser = new Schema({
name: { type: String, required: true },
password: { type: String, required: true },
salt: { type: String, required: true },
type: { type: String, required: true, default: 'user' }, // This could be user, admin, guest
twoFASecret: { type: String, required: false },
lastLogin: { type: Date, required: true, default: Date.now },
}, {
timestamps: {
createdAt: true
}
});
export { schemaUser }

2953
backend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

46
backend/package.json Normal file
View File

@@ -0,0 +1,46 @@
{
"name": "livebeat",
"version": "1.0.0",
"description": "Backend of Livebeat",
"main": "app.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "ts-node app.ts",
"start:dev": "nodemon dist/app.js",
"build:dev": "tsc --watch --preserveWatchOutput",
"dev": "concurrently \"npm:build:dev\" \"npm:start:dev\""
},
"repository": {
"type": "git",
"url": "https://nicolasklier.de:3000/Nicolas/Livebeat.git"
},
"author": "Mondei1",
"license": "GPL-3.0-or-later",
"dependencies": {
"argon2": "^0.27.0",
"body-parser": "^1.19.0",
"chalk": "^4.1.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"figlet": "^1.5.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.10.9",
"ts-node": "^9.0.0",
"typescript": "^4.0.3",
"winston": "^3.3.3"
},
"devDependencies": {
"@types/argon2": "0.15.0",
"@types/body-parser": "1.19.0",
"@types/chalk": "2.2.0",
"@types/dotenv": "8.2.0",
"@types/express": "4.17.8",
"@types/figlet": "1.2.0",
"@types/mongoose": "5.7.36",
"@types/typescript": "2.0.0",
"@types/winston": "2.4.4",
"concurrently": "^5.3.0",
"nodemon": "^2.0.5",
"@types/jsonwebtoken": "8.5.0"
}
}

10
backend/tsconfig.json Normal file
View File

@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./",
"strict": true,
"forceConsistentCasingInFileNames": true
}
}