Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {

import { performanceMonitor } from "./middleware/performance.js";
import logger, { stream } from "./utils/logger.js";
import { sanitizeRequest } from "./middleware/validation.js";
import { sanitizeRequest, detectSqlInjection } from "./middleware/validation.js";

import {
globalLimiter,
Expand Down Expand Up @@ -104,6 +104,9 @@ app.use(compression({
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true, limit: "10mb" }));

// Detect SQL Injection attempts
app.use(detectSqlInjection);

// Sanitize all request inputs
app.use(sanitizeRequest);

Expand Down Expand Up @@ -196,7 +199,7 @@ app.use(
// ===== ERROR HANDLING =====

app.all("*", (req, res, next) => {
res.status(404).json({
res.status(404).json({
message: `Route ${req.originalUrl} not found`,
path: req.originalUrl,
method: req.method,
Expand Down
31 changes: 31 additions & 0 deletions backend/middleware/validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,34 @@ export const sanitizeRequest = (req, res, next) => {
req.params = sanitizeValue(req.params);
next();
};

/**
* Detect and block common SQL injection patterns in requests
*/
export const detectSqlInjection = (req, res, next) => {
const sqlInjectionPattern = /(union\s+select|select\s+.*\s+from|from\s+information_schema|or\s+1\s*=\s*1|drop\s+table|update\s+.*\s+set|delete\s+from|insert\s+into|exec\s*\(|;\s*--|--\s*$)/i;

const detectInObject = (obj) => {
if (typeof obj === "string") {
return sqlInjectionPattern.test(obj);
}
if (typeof obj === "object" && obj !== null) {
return Object.values(obj).some(detectInObject);
}
return false;
};

const hasSqlInjection =
detectInObject(req.body) ||
detectInObject(req.query) ||
detectInObject(req.params);

if (hasSqlInjection) {
return res.status(403).json({
status: "error",
message: "Forbidden: Suspicious input detected",
});
}

next();
};
Loading