diff --git a/src/config/index.ts b/src/config/index.ts index 23c1189d..e38ab47b 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -43,6 +43,7 @@ export const COOKIES = 'cookies'; export const CONTACT_US = 'contact-us'; // Routing paths +export const ROOT = '/'; export const START_URL = '/start'; export const HOME_URL = '/home'; export const ADD_MEMBER_URL = '/add-member'; diff --git a/src/middleware/validation.middleware.ts b/src/middleware/validation.middleware.ts index 56a83418..ee3de4ec 100644 --- a/src/middleware/validation.middleware.ts +++ b/src/middleware/validation.middleware.ts @@ -3,17 +3,18 @@ import { validationResult, FieldValidationError } from 'express-validator'; import * as config from '../config'; import { log } from '../utils/logger'; +import { validateFilepath } from '../utils/validateFilepath'; import { FormattedValidationErrors } from '../model/validation.model'; export const checkValidations = (req: Request, res: Response, next: NextFunction) => { try { const errorList = validationResult(req); + const sanitisedPath = validateFilepath(req, res); - if (!errorList.isEmpty()) { - const path = req.path; + if (!errorList.isEmpty() && sanitisedPath) { const id = req.params[config.ID]; // Removing trailing slash and 36 characters from UUID length - const template_path = (id) ? path.substring(0, path.length - 37).substring(1) : path.substring(1); + const template_path = (id) ? sanitisedPath.substring(0, sanitisedPath.length - 37).substring(1) : sanitisedPath.substring(1); const errors = formatValidationError(errorList.array() as FieldValidationError[]); log.info(`Validation error on ${template_path} page`); diff --git a/src/utils/validateFilepath.ts b/src/utils/validateFilepath.ts new file mode 100644 index 00000000..78c96758 --- /dev/null +++ b/src/utils/validateFilepath.ts @@ -0,0 +1,17 @@ +import path from 'path'; +import * as config from '../config'; +import { Request, Response } from 'express'; + +// https://codeql.github.com/codeql-query-help/javascript/js-path-injection/ + +export const validateFilepath = (req: Request, res: Response): string | void => { + + const unsanitizedPath = req.path; + + // Check if the normalised path is within the root directory + if (path.resolve(unsanitizedPath).startsWith(config.ROOT)) { + return req.path; + } else { + return res.render(config.ERROR_PAGE); + } +};