Attempted adding of 'Salting' for the password, a method which adds random numbers or letters to make rainbowtable password cracking impossible, not tested yet

This commit is contained in:
Esad Mustafoski
2025-02-02 12:33:47 +01:00
parent 3c6fdd0b59
commit 4c80caa52a
4 changed files with 399 additions and 311 deletions

View File

@@ -1,10 +1,8 @@
/// <reference lib="deno.ns" /> /// <reference lib="deno.ns" />
/** /**
* @author Esad Mustafoski * @author Esad Mustafoski
* @file api/helpers.ts * @file api/helpers.ts
* @description Helper functions for the API * @description Helper functions for the API
*
*/ */
import { Context } from "https://deno.land/x/oak/mod.ts"; import { Context } from "https://deno.land/x/oak/mod.ts";
import { encodeHex } from "jsr:@std/encoding/hex"; import { encodeHex } from "jsr:@std/encoding/hex";
@@ -22,7 +20,7 @@ export type ApiResponse = {
* Status is the HTTP Status code * Status is the HTTP Status code
* Body is the response body/message/data. * Body is the response body/message/data.
*/ */
const sendResponse = (ctx: Context, {status, body}: ApiResponse): void => { const sendResponse = (ctx: Context, { status, body }: ApiResponse): void => {
ctx.response.status = status; ctx.response.status = status;
ctx.response.body = body as any; ctx.response.body = body as any;
}; };
@@ -35,21 +33,38 @@ const errorResponse = (ctx: Context, status: number, message: string): void => {
sendResponse(ctx, { status, body: { error: message } }); sendResponse(ctx, { status, body: { error: message } });
}; };
/**
* @description password "Salter", used to salt the passwords before the hash, this salt will be
* returned seperately to save the salt in the DB
* @param password The password to salt
* @returns {saltedPassword: string, salt: string} Password with the salt + Salt seperately, both strings
*/
const saltPassword = async (
password: string,
): Promise<{ saltedPassword: string; salt: string }> => {
const saltBytes = new Uint8Array(16); // 16 bytes = 128 bits for randomness
await crypto.getRandomValues(saltBytes);
const salt = encodeHex(saltBytes);
const saltedPassword = `${password}${salt}`;
return {
saltedPassword,
salt,
};
};
/** /**
* @description Hashing Function for Passwords/etc * @description Hashing Function for Passwords/etc
* @param password The password to hash * @param password The password to hash
* @returns {hash: string} The hashed password as a string
*/ */
const hashPassword = async(password: string): Promise<string> => { const hashPassword = async (password: string): Promise<string> => {
const to_hash = password; const to_hash = password;
const buffer = new TextEncoder().encode(to_hash); const buffer = new TextEncoder().encode(to_hash);
const hash_buffer = await crypto.subtle.digest("SHA-256", buffer); const hash_buffer = await crypto.subtle.digest("SHA-256", buffer);
const hash = await encodeHex(hash_buffer); const hash = await encodeHex(hash_buffer);
return hash; return hash;
}
export {
sendResponse,
errorResponse,
hashPassword
}; };
export { errorResponse, hashPassword, saltPassword, sendResponse };

View File

@@ -1,11 +1,16 @@
/// <reference lib="deno.ns" /> /// <reference lib="deno.ns" />
/** /**
* @author Esad Mustafoski * @author Esad Mustafoski
* Main API file, Handles all the routing/api stuff * @ðescription Main API file, Handles all the routing/api stuff
*/ */
// +++ IMPORTS ------------------------------------------------------ // // +++ IMPORTS ------------------------------------------------------ //
import { Application, Router, Context, Next } from "https://deno.land/x/oak/mod.ts"; import {
Application,
Context,
Next,
Router,
} from "https://deno.land/x/oak/mod.ts";
import { oakCors } from "https://deno.land/x/cors/mod.ts"; import { oakCors } from "https://deno.land/x/cors/mod.ts";
import * as db_utils from "../database/utils.ts"; import * as db_utils from "../database/utils.ts";
import * as helper_utils from "./helpers.ts"; import * as helper_utils from "./helpers.ts";
@@ -14,11 +19,11 @@ import * as helper_utils from "./helpers.ts";
const router = new Router(); const router = new Router();
const app = new Application(); const app = new Application();
// For the future // unused for now
type ApiResponse = { type ApiResponse = {
status: number; status: number;
body: unknown; body: unknown;
} };
// +++ ROUTER ------------------------------------------------------- // // +++ ROUTER ------------------------------------------------------- //
// Creates the routes for the API server. // Creates the routes for the API server.
@@ -27,13 +32,17 @@ type ApiResponse = {
// Docs Routes // Docs Routes
router router
.get("/", (ctx) => { ctx.response.body = "For endpoints, use /api/{name}"; }) .get("/", (ctx) => {
.get("/api", (ctx) => { ctx.response.body = "For API Documentation, visit /docs"; }) ctx.response.body = "For endpoints, use /api/{name}";
})
.get("/api", (ctx) => {
ctx.response.body = "For API Documentation, visit /docs";
});
// Account routes // -- Account routes --
router router
.post("/api/account/login", api_login) // TODO .post("/api/account/login", api_login)
.post("/api/account/register", api_register) // TODO .post("/api/account/register", api_register)
.post("/api/account/logout", () => {}) // TODO .post("/api/account/logout", () => {}) // TODO
.post("/api/account/password/forgot", () => {}) // TODO .post("/api/account/password/forgot", () => {}) // TODO
.post("/api/account/password/reset", () => {}) // TODO .post("/api/account/password/reset", () => {}) // TODO
@@ -41,37 +50,27 @@ router
.post("/api/account/email/change-email", () => {}) // TODO .post("/api/account/email/change-email", () => {}) // TODO
.post("/api/account/email/verify-email", () => {}) // TODO .post("/api/account/email/verify-email", () => {}) // TODO
.post("/api/account/delete-account", () => {}) // TODO .post("/api/account/delete-account", () => {}) // TODO
.post("/api/account/block", () => {}) // TODO .post("/api/account/block", () => {}); // TODO
// Auth Routes // -- Auth Routes --
router router
.get("/api/auth", () => {}) // TODO .get("/api/auth", () => {}) // TODO
.get("/api/auth/verify", () => {}) // TODO .get("/api/auth/verify", () => {}) // TODO
.get("/api/auth/refresh", () => {}) // TODO .get("/api/auth/refresh", () => {}); // TODO
// User routes // -- User routes --
router router
.get("/api/users", api_getAllUsers) .get("/api/users", api_getAllUsers)
.get("/api/user/:id/info", api_user_getInfo); // @error GEHT NICHT .get("/api/user/:id/info", api_user_getInfo);
// Post routes // -- Post routes --
router router
.get("/api/posts", api_posts_getAll); .get("/api/posts", api_posts_getAll);
// +++ FUNCTIONS ----------------------------------------------------- // // +++ FUNCTIONS ----------------------------------------------------- //
/**
* @description Stands between the client and the API
* It checks if the client is authorized to access the API with a token/Multiple tokens
* Currently not implemented
* Middleware
*/
async function authenticator(ctx: Context, next: Next): Promise<void> { async function authenticator(ctx: Context, next: Next): Promise<void> {
const authHeader = ctx.request.headers.get('Authorization'); const authHeader = ctx.request.headers.get("Authorization");
if (!authHeader) { if (!authHeader) {
ctx.response.status = 401; ctx.response.status = 401;
@@ -103,12 +102,8 @@ async function tokenChecker(ctx: Context, next: Next): Promise<void> {
* 1. check if the token is valid * 1. check if the token is valid
* 2. if valid, set the user in the context * 2. if valid, set the user in the context
* 3. if not valid, return 401 * 3. if not valid, return 401
* 4. if token is missing, return 401 * 4. if: token missing, expired, blacklisted, !DB, !user or !correct user, return 401 with associated error
* 5. if token is expired, return 401 * eg: wrong user: 401 -> "Token not associated with this user"
* 6. if token is blacklisted, return 401
* 7. if token is not in the database, return 401
* 8. if token is not associated with a user, return 401
* 9. if token is not associated with the correct user, return 401
*/ */
} }
@@ -122,7 +117,7 @@ async function api_user_getInfo(ctx: any): Promise<void> {
const id = ctx.params.id; const id = ctx.params.id;
if (!id) { if (!id) {
ctx.response.status = 400; // Bad Request status ctx.response.status = 400;
ctx.response.body = { error: "User ID required" }; ctx.response.body = { error: "User ID required" };
return; return;
} }
@@ -136,7 +131,7 @@ async function api_user_getInfo(ctx: any): Promise<void> {
ctx.response.body = user; ctx.response.body = user;
} catch (error) { } catch (error) {
helper_utils.errorResponse(ctx, 500, "Internal Server Error"); helper_utils.errorResponse(ctx, 500, error as string);
} }
} }
@@ -146,25 +141,55 @@ async function api_posts_getAll(ctx: Context): Promise<void> {
ctx.response.body = posts; ctx.response.body = posts;
} }
// Comments // Comments (missing)
// login/register // login/register
async function api_register(ctx: Context): Promise<void> { async function api_register(ctx: Context): Promise<void> {
try { try {
const body = ctx.request.body; const body = ctx.request.body;
const result = await body.json(); const result = await body.json();
const { username, password, userGroup, displayname, user_email, firstname, surname} = result; const {
const account_created = `${Math.floor(Date.now() / 1000)}-${new Date().toLocaleDateString('en-GB').split('/').join('-')}`; username,
password,
userGroup,
displayname,
user_email,
firstname,
surname,
} = result;
const account_created = `${Math.floor(Date.now() / 1000)}-${
new Date().toLocaleDateString("en-GB").split("/").join("-")
}`;
if (
if ( !username || !password || !userGroup || !displayname || !user_email || !firstname || !surname) { !username || !password || !userGroup || !displayname || !user_email ||
!firstname || !surname
) {
helper_utils.errorResponse(ctx, 400, "Missing required fields"); helper_utils.errorResponse(ctx, 400, "Missing required fields");
return; return;
} }
const hash = await helper_utils.hashPassword(password); // First salt the password
const userId = await db_utils.registerUser(username, hash, userGroup, displayname, user_email, firstname, surname, account_created); const { saltedPassword, salt } = await helper_utils.saltPassword(password);
helper_utils.sendResponse(ctx, { status: 200, body: `Registered under name: ${userId}` }); // Then hash the salted password
const hash = await helper_utils.hashPassword(saltedPassword);
const userId = await db_utils.registerUser(
username,
hash,
salt,
userGroup,
displayname,
user_email,
firstname,
surname,
account_created,
);
helper_utils.sendResponse(ctx, {
status: 200,
body: `Registered under name: ${userId}`,
});
} catch (error) { } catch (error) {
console.log(error); console.log(error);
helper_utils.errorResponse(ctx, 500, "Invalid request"); helper_utils.errorResponse(ctx, 500, "Invalid request");
@@ -189,28 +214,31 @@ async function api_login(ctx: Context): Promise<string> {
return "Error"; return "Error";
} }
const hash = await helper_utils.hashPassword(password); // Get the stored salt for this user
const storedSalt = user.password_salt;
// Salt the provided password with the stored salt
const saltedPassword = `${password}${storedSalt}`;
// Hash the salted password
const hash = await helper_utils.hashPassword(saltedPassword);
// Compare with stored hash
if (user.password !== hash) { if (user.password !== hash) {
helper_utils.errorResponse(ctx, 401, "Invalid password"); helper_utils.errorResponse(ctx, 401, "Invalid password");
return "Error"; return "Error";
} }
helper_utils.sendResponse(ctx, { status: 200, body: "Success" });
return "Success";
} catch (error) { } catch (error) {
console.log(error); console.log(error);
helper_utils.errorResponse(ctx, 500, "Invalid request"); helper_utils.errorResponse(ctx, 500, "Invalid request");
return "Error"; return "Error";
} }
helper_utils.sendResponse(ctx, { status: 200, body: "Success" });
return "Success";
} }
// Filtering
// +++ APP ---------------------------------------------------------- // // +++ APP ---------------------------------------------------------- //
app.use(oakCors({ app.use(oakCors({
origin: '*', origin: "*",
credentials: true, credentials: true,
})); }));
app.use(router.routes()); app.use(router.routes());

View File

@@ -24,6 +24,7 @@ export function createDatabase(): void {
user_username TEXT, user_username TEXT,
user_e-mail TEXT, user_e-mail TEXT,
password TEXT, password TEXT,
password_salt TEXT,
firstname TEXT, firstname TEXT,
surname TEXT, surname TEXT,
account_created TEXT, account_created TEXT,
@@ -50,28 +51,34 @@ export function createDatabase(): void {
likes INTEGER likes INTEGER
) )
`); `);
}; }
// Sample data generated using AI, does not work yet and will be adjusted // Sample data generated using AI, does not work yet and will be adjusted
export function insertSampleData(): void { export function insertSampleData(): void {
db.query(`INSERT INTO accounts (user_group, user_bio, user_displayname, user_username, user_email, password, firstname, surname, account_created, followers, following, contacts) VALUES db.query(
('admin', 'Admin bio', 'Admin User', 'admin', 'admin@example.com', 'hashedpass1', 'Admin', 'User', '2024-01-01', '[]', '[]', '[]', '[]'), `INSERT INTO accounts (user_group, user_bio, user_displayname, user_username, user_email, password, password_salt, firstname, surname, account_created, followers, following, contacts) VALUES
('user', 'I love coding!', 'John Dev', 'johndev', 'john@example.com', 'hashedpass2', 'John', 'Smith', '2024-01-02', '[]', '[3,4]', '[1,2]', '[]'), ('admin', 'Admin bio', 'Admin User', 'admin', 'admin@example.com', 'hashedpass1', 'salt1', 'Admin', 'User', '2024-01-01', '[]', '[]', '[]', '[]'),
('user', 'Photography enthusiast', 'Alice', 'alice_photo', 'alice@example.com', 'hashedpass3', 'Alice', 'Johnson', '2024-01-03', '[5]', '[1]', '[2]', '[]') ('user', 'I love coding!', 'John Dev', 'johndev', 'john@example.com', 'hashedpass2', 'salt2', 'John', 'Smith', '2024-01-02', '[]', '[3,4]', '[1,2]', '[]'),
`); ('user', 'Photography enthusiast', 'Alice', 'alice_photo', 'alice@example.com', 'hashedpass3', 'salt3', 'Alice', 'Johnson', '2024-01-03', '[5]', '[1]', '[2]', '[]')
`,
);
db.query(`INSERT INTO posts (user_id, created_at, post_text, likes, comments) VALUES db.query(
`INSERT INTO posts (user_id, created_at, post_text, likes, comments) VALUES
(1, '2024-01-15 10:00:00', 'First post about programming!', 5, 2), (1, '2024-01-15 10:00:00', 'First post about programming!', 5, 2),
(1, '2024-01-15 11:30:00', 'Check out this new feature', 10, 3), (1, '2024-01-15 11:30:00', 'Check out this new feature', 10, 3),
(2, '2024-01-16 09:15:00', 'Just learned about TypeScript', 8, 1), (2, '2024-01-16 09:15:00', 'Just learned about TypeScript', 8, 1),
(3, '2024-01-16 14:20:00', 'Posted my new photo collection', 15, 4) (3, '2024-01-16 14:20:00', 'Posted my new photo collection', 15, 4)
`); `,
);
db.query(`INSERT INTO comments (post_id, author_user_id, date_created_at, text, likes) VALUES db.query(
`INSERT INTO comments (post_id, author_user_id, date_created_at, text, likes) VALUES
(1, 2, '2024-01-15 10:05:00', 'Great post!', 3), (1, 2, '2024-01-15 10:05:00', 'Great post!', 3),
(1, 3, '2024-01-15 10:10:00', 'Very informative', 2), (1, 3, '2024-01-15 10:10:00', 'Very informative', 2),
(2, 3, '2024-01-15 11:35:00', 'Nice feature', 4), (2, 3, '2024-01-15 11:35:00', 'Nice feature', 4),
(3, 1, '2024-01-16 09:20:00', 'TypeScript is awesome', 5), (3, 1, '2024-01-16 09:20:00', 'TypeScript is awesome', 5),
(4, 2, '2024-01-16 14:25:00', 'Beautiful photos!', 6) (4, 2, '2024-01-16 14:25:00', 'Beautiful photos!', 6)
`); `,
}; );
}

View File

@@ -11,10 +11,9 @@ import { dirname, fromFileUrl, join } from "https://deno.land/std/path/mod.ts";
import * as db_create from "./create_db.ts"; import * as db_create from "./create_db.ts";
// +++ VARIABLES ---------------------------------------------------- // // +++ VARIABLES ---------------------------------------------------- //
// __dirname Is never getting used again, It's only needed because the DB Import // _dirname Is never getting used again, It's only needed because the DB Import
// from SQLite doesn't like relative paths, so I use this as // from SQLite doesn't like relative paths, so I use this as
// A Workaround // A Workaround
const _dirname: string = dirname(fromFileUrl(import.meta.url)); const _dirname: string = dirname(fromFileUrl(import.meta.url));
const dbPath: string = join(_dirname, "../database/esp-projekt.sqlite"); const dbPath: string = join(_dirname, "../database/esp-projekt.sqlite");
const db = new DB(dbPath); const db = new DB(dbPath);
@@ -38,6 +37,7 @@ interface Accounts {
username: string; username: string;
user_email: string; user_email: string;
password: string; password: string;
password_salt: string;
firstname: string; firstname: string;
surname: string; surname: string;
account_created: string; account_created: string;
@@ -78,6 +78,7 @@ function mapAccountRow(row: Row): Accounts {
username, username,
user_email, user_email,
password, password,
password_salt,
firstname, firstname,
surname, surname,
account_created, account_created,
@@ -94,6 +95,7 @@ function mapAccountRow(row: Row): Accounts {
username: String(username), username: String(username),
user_email: String(user_email), user_email: String(user_email),
password: String(password), password: String(password),
password_salt: String(password_salt),
firstname: String(firstname), firstname: String(firstname),
surname: String(surname), surname: String(surname),
account_created: String(account_created), account_created: String(account_created),
@@ -124,7 +126,11 @@ function mapCommentRow(row: Row): Comments {
} }
// "T" is a generic type, it can be anything and makes the function "flexible"(?) // "T" is a generic type, it can be anything and makes the function "flexible"(?)
async function queryDatabase<T>(query: string, params: any[], mapRow: (row: Row) => T,): Promise<T[]> { async function queryDatabase<T>(
query: string,
params: any[],
mapRow: (row: Row) => T,
): Promise<T[]> {
const results: T[] = []; const results: T[] = [];
try { try {
const rows = await db.query(query, params); const rows = await db.query(query, params);
@@ -163,7 +169,7 @@ async function getPostsFromDB(user_uuid?: string): Promise<Post[]> {
: `SELECT * FROM posts`; : `SELECT * FROM posts`;
const params = user_uuid ? [user_uuid] : []; const params = user_uuid ? [user_uuid] : [];
return await queryDatabase<Post>(query, params, mapPostRow); return await queryDatabase<Post>(query, params, mapPostRow);
} }
/** /**
* @returns Array of all Users in the Database * @returns Array of all Users in the Database
@@ -179,7 +185,7 @@ async function getAllUsersFromDB(): Promise<Accounts[]> {
*/ */
async function getUserByUsername(username: string): Promise<Accounts> { async function getUserByUsername(username: string): Promise<Accounts> {
const query = `SELECT * FROM accounts WHERE user_username = '${username}'`; const query = `SELECT * FROM accounts WHERE user_username = '${username}'`;
const params:string[] = []; const params: string[] = [];
const result = await queryDatabase<Accounts>(query, params, mapAccountRow); const result = await queryDatabase<Accounts>(query, params, mapAccountRow);
return result[0]; return result[0];
} }
@@ -233,36 +239,68 @@ function filterForTextPosts(posts_to_filter: Array<any>) {
return []; return [];
} }
// Register/Login/User // Register/Login/User
/** /**
* @param user The name of the User to add * @param user The username of the User to add
* @param password The password of the User to add * @param password The hashed password of the User to add
* @returns Array of Posts from the User, or an empty Array if the User doesn't exist or has no Posts * @param salt The salt used for the password
* @returns "noUser" if user exists, "newUser" if registration successful
*/ */
function registerUser (user: string, password: string, userGroup: string, displayname: string, user_email: string, firstname: string, surname: string, account_created: string): string { function registerUser(
const query_user_exists = `SELECT * FROM accounts WHERE user_username = '${user}'`; user: string,
password: string,
salt: string,
userGroup: string,
displayname: string,
user_email: string,
firstname: string,
surname: string,
account_created: string,
): string {
const query_user_exists =
`SELECT * FROM accounts WHERE user_username = '${user}'`;
if (!query_user_exists) { if (!query_user_exists) {
return "noUser"; return "noUser";
} }
const query_add_user = `INSERT INTO accounts (user_username, password, user_group, user_displayname, user_email, firstname, surname, account_created) VALUES ('${user}', '${password}', '${userGroup}', '${displayname}', '${user_email}', '${firstname}', '${surname}', '${account_created}')`; const query_add_user = `
INSERT INTO accounts (
user_username,
password,
password_salt,
user_group,
user_displayname,
user_email,
firstname,
surname,
account_created
) VALUES (
'${user}',
'${password}',
'${salt}',
'${userGroup}',
'${displayname}',
'${user_email}',
'${firstname}',
'${surname}',
'${account_created}'
)`;
db.query(query_add_user); db.query(query_add_user);
console.log(`New user: ${user}`) console.log(`New user: ${user}`);
return "newUser"; return "newUser";
} }
// Exporting all functions as this is a module // Exporting all functions as this is a module
export { export {
registerUser,
createDatabaseIfNotExist, createDatabaseIfNotExist,
getAllUserInfoByID, getAllUserInfoByID,
getAllUsersFromDB, getAllUsersFromDB,
getUserByUsername,
getCommentsForComments, getCommentsForComments,
getCommentsFromDB, getCommentsFromDB,
getPostsFromDB, getPostsFromDB,
getUserByUsername,
insertSamples, insertSamples,
registerUser,
}; };