diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..fc6a005 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,19 @@ +name: Instructor Portal security tests +on: [push, pull_request] + +jobs: + test: + runs-on: ubuntu-22.04 # 22.04 has libssl1.1 for mongod 6.0.x + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm # uses the root package-lock.json + - name: Cache mongod binary + uses: actions/cache@v4 + with: + path: ~/.cache/mongodb-binaries + key: mongodb-memory-server-6.0.14-${{ runner.os }} + - run: npm ci # installs the server+client workspaces + - run: npm test --workspace server diff --git a/package-lock.json b/package-lock.json index 997c257..8fee876 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3488,6 +3488,15 @@ "url": "https://opencollective.com/express" } }, + "node_modules/express-mongo-sanitize": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/express-mongo-sanitize/-/express-mongo-sanitize-2.2.0.tgz", + "integrity": "sha512-PZBs5nwhD6ek9ZuP+W2xmpvcrHwXZxD5GdieX2dsjPbAbH4azOkrHbycBud2QRU+YQF1CT+pki/lZGedHgo/dQ==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/express/node_modules/debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", @@ -7871,6 +7880,7 @@ "cors": "^2.8.5", "dotenv": "^16.4.5", "express": "^4.19.2", + "express-mongo-sanitize": "^2.2.0", "joi": "^17.12.3", "jsonwebtoken": "^9.0.2", "mongoose": "^8.6.0", diff --git a/server/package.json b/server/package.json index 5bb00a3..595cdf9 100644 --- a/server/package.json +++ b/server/package.json @@ -19,6 +19,7 @@ "cors": "^2.8.5", "dotenv": "^16.4.5", "express": "^4.19.2", + "express-mongo-sanitize": "^2.2.0", "joi": "^17.12.3", "jsonwebtoken": "^9.0.2", "mongoose": "^8.6.0", diff --git a/server/src/app.js b/server/src/app.js index c975cd0..430e672 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -1,6 +1,7 @@ import express from 'express'; import morgan from 'morgan'; import cors from 'cors'; +import mongoSanitize from 'express-mongo-sanitize'; import authRoutes from './routes/auth.js'; import reviewRoutes from './routes/reviews.js'; import userRoutes from './routes/users.js'; @@ -12,6 +13,12 @@ app.use(morgan('dev')); app.use(cors({ origin: 'http://localhost:5175', credentials: false })); app.use(express.json()); +// Defense-in-depth: strip any keys containing `$` or `.` from req.body, +// req.query and req.params before they can reach Mongoose. This is a blunt +// second layer; per-endpoint Joi validation (in the controllers) remains the +// primary defense, since sanitize alone cannot type-check values. +app.use(mongoSanitize()); + app.get('/api/health', (req, res) => res.json({ ok: true })); app.use('/api/auth', authRoutes); diff --git a/server/src/controllers/instructorController.js b/server/src/controllers/instructorController.js index 2a3582d..d26fa46 100644 --- a/server/src/controllers/instructorController.js +++ b/server/src/controllers/instructorController.js @@ -1,53 +1,66 @@ +import Joi from 'joi'; import { Instructor } from '../models/Instructor.js'; // ============================================================================= -// INSTRUCTOR PORTAL CONTROLLER — ⚠️ INTENTIONALLY VULNERABLE (security lab) +// INSTRUCTOR PORTAL CONTROLLER — HARDENED against NoSQL injection // ============================================================================= // -// Unlike the review/auth controllers in this project, these handlers do NOT -// validate input with Joi and the app has NO express-mongo-sanitize. They pass -// `req.body` / `req.query` straight into Mongoose. Because Express parses JSON -// bodies and bracket-notation query strings into nested objects, an attacker -// can smuggle MongoDB query operators ($ne, $gt, $regex, $where, ...) into -// what the code treats as plain strings. -// -// This is the bug students must find and fix. Do not "clean this up". +// Defense layers (see README "Task" section): +// 1. Joi validates and *types* every input. `Joi.string()` rejects objects, so +// a smuggled operator like {"$ne": null} or {"$regex": "^S"} never reaches +// Mongoose; Joi also rejects unknown keys, so `?$where=...` or +// `?role[$ne]=...` are refused outright. +// 2. We build the Mongo filter ourselves from the validated values instead of +// handing `req.body` / `req.query` straight to Mongoose. +// 3. express-mongo-sanitize (wired in app.js) strips any `$`/`.` keys as a +// belt-and-braces second layer. +// 4. Passwords are bcrypt-hashed and compared with `comparePassword`; secret +// fields are `select: false` on the model and never returned to clients. // ============================================================================= +// Only ever expose non-sensitive profile fields. Even if a sensitive field were +// loaded, it is not copied into the response object. function publicProfile(doc) { - // A successful login is a "trophy": we deliberately return the sensitive - // fields so a bypass clearly reveals what it compromised. return { id: doc._id.toString(), name: doc.name, username: doc.username, department: doc.department, - role: doc.role, - apiKey: doc.apiKey, - privateEmail: doc.privateEmail, - privatePhone: doc.privatePhone + role: doc.role }; } +// Escape a user string so it is treated as a literal inside a RegExp — this lets +// `name=Smith` do a safe, case-insensitive partial match without letting the +// user inject regex/operator syntax. +function escapeRegExp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +const loginSchema = Joi.object({ + username: Joi.string().trim().max(120).required(), + password: Joi.string().max(200).required() +}); + // POST /api/instructors/login export async function loginInstructor(req, res, next) { try { - const { username, password } = req.body; - if (username === undefined || password === undefined) { - return res.status(400).json({ message: 'username and password are required' }); - } - - // ⚠️ VULNERABLE (NoSQL injection): `username` and `password` are placed - // directly into the query. Honest clients send strings, but a crafted body - // like {"username":{"$ne":null},"password":{"$ne":null}} turns this into a - // filter that matches any account (authentication bypass). With - // {"password":{"$regex":"^S"}} the success/failure response becomes an - // oracle for extracting the stored password one character at a time. - const instructor = await Instructor.findOne({ username, password }); + const { value, error } = loginSchema.validate(req.body); + if (error) return res.status(400).json({ message: error.message }); + // `username` is now guaranteed to be a plain string, so this is a literal + // equality match — no operator can be smuggled in. `password` is select:false + // on the model, so we opt it in explicitly just for the comparison. + const instructor = await Instructor.findOne({ username: value.username }).select('+password'); if (!instructor) { return res.status(401).json({ message: 'Invalid credentials' }); } + + const ok = await instructor.comparePassword(value.password); + if (!ok) { + return res.status(401).json({ message: 'Invalid credentials' }); + } + return res.json({ instructor: publicProfile(instructor) }); } catch (err) { next(err); @@ -55,8 +68,7 @@ export async function loginInstructor(req, res, next) { } // GET /api/instructors -// Public directory. Deliberately limited fields so the contrast with the -// leaky /search endpoint below is obvious. +// Public directory — limited fields only. export async function getDirectory(req, res, next) { try { const instructors = await Instructor.find() @@ -69,18 +81,39 @@ export async function getDirectory(req, res, next) { } } +// Whitelisted search fields and the only accepted role values. +const SEARCHABLE_STRING_FIELDS = ['name', 'department']; +const VALID_ROLES = ['instructor', 'superadmin']; + // GET /api/instructors/search export async function searchInstructors(req, res, next) { try { - // ⚠️ VULNERABLE (NoSQL injection): the entire query string is used as the - // MongoDB filter and full documents (incl. password / apiKey / private - // contact info) are returned. Examples of what this allows: - // ?name=Smith -> intended, honest use - // ?role[$ne]=instructor -> operator injection, leaks superadmin - // ?username[$regex]=^admin -> regex enumeration - // ?$where=this.password.length>10 -> server-side JavaScript execution - const filter = req.query; - const instructors = await Instructor.find(filter).lean(); + // Build the filter ONLY from whitelisted fields whose value is a plain + // string. Anything else — an injected operator object (`role[$ne]=...`, + // `name[$regex]=...`), an unknown key (`$where`, `username`), or a non-string + // value — is simply ignored rather than rejected. Combined with + // express-mongo-sanitize (which already strips `$`/`.` keys), no operator can + // reach the query, so a tampered request degrades to a normal public search + // and returns 200 instead of leaking data or erroring out. + const q = req.query || {}; + const filter = {}; + + for (const field of SEARCHABLE_STRING_FIELDS) { + const val = q[field]; + if (typeof val === 'string' && val.trim() !== '') { + // Escaped literal regex: case-insensitive "contains", no regex injection. + filter[field] = { $regex: escapeRegExp(val.trim()), $options: 'i' }; + } + } + if (typeof q.role === 'string' && VALID_ROLES.includes(q.role)) { + filter.role = q.role; + } + + // Return only public fields regardless of the filter, so search can never + // leak password / apiKey / private contact info. + const instructors = await Instructor.find(filter) + .select('name department role') + .lean(); res.json({ count: instructors.length, instructors }); } catch (err) { next(err); diff --git a/server/src/models/Instructor.js b/server/src/models/Instructor.js index c5ea0e0..47b9324 100644 --- a/server/src/models/Instructor.js +++ b/server/src/models/Instructor.js @@ -1,26 +1,43 @@ import mongoose from 'mongoose'; +import bcrypt from 'bcryptjs'; // Instructor Portal account. // -// NOTE (security lab): this model is intentionally insecure. Passwords are -// stored in PLAINTEXT (never do this in real code) so that the NoSQL injection -// lab can demonstrate blind $regex password extraction. The apiKey / private -// contact fields are "trophy" data that filter-injection attacks can leak. +// Hardened against the NoSQL injection lab: +// - Passwords are hashed with bcrypt (pre-save hook) and never stored in +// plaintext, so a blind $regex oracle can no longer rebuild them and a leak +// does not expose a usable secret. +// - The sensitive "trophy" fields (password, apiKey, private contact info) are +// `select: false`, so they are stripped from every query result by default +// and can only be pulled in deliberately (e.g. `.select('+password')` during +// login). No handler can accidentally return them to a client. const instructorSchema = new mongoose.Schema( { name: { type: String, required: true }, username: { type: String, required: true, unique: true, trim: true }, - // ⚠️ VULNERABLE (lab): plaintext password, no bcrypt hashing. - password: { type: String, required: true }, + // Stores the bcrypt hash, never the plain-text password. Hidden by default. + password: { type: String, required: true, select: false }, department: { type: String }, role: { type: String, default: 'instructor' }, // 'instructor' | 'superadmin' - // Sensitive "trophy" fields the directory hides but injection can leak. - apiKey: { type: String }, - privateEmail: { type: String }, - privatePhone: { type: String } + // Sensitive fields: hidden by default so they never leak through a query. + apiKey: { type: String, select: false }, + privateEmail: { type: String, select: false }, + privatePhone: { type: String, select: false } }, { timestamps: true } ); +// Hash the password whenever it is set or changed. Runs on `save()` and on +// `create()` (including `create([...])`), so the seed is hashed too. +instructorSchema.pre('save', async function hashPassword(next) { + if (!this.isModified('password')) return next(); + this.password = await bcrypt.hash(this.password, 10); + next(); +}); + +instructorSchema.methods.comparePassword = async function comparePassword(candidate) { + return bcrypt.compare(candidate, this.password); +}; + export const Instructor = mongoose.model('Instructor', instructorSchema); diff --git a/server/src/seed/instructors.js b/server/src/seed/instructors.js index 396a941..b8ea6da 100644 --- a/server/src/seed/instructors.js +++ b/server/src/seed/instructors.js @@ -4,8 +4,10 @@ import mongoose from 'mongoose'; import { connectDB } from '../config/db.js'; import { Instructor } from '../models/Instructor.js'; -// Seed data for the Instructor Portal NoSQL injection lab. -// Passwords are plaintext ON PURPOSE (see Instructor model / Flow.md). +// Seed data for the Instructor Portal. +// Passwords here are the *plain-text* values; they are hashed with bcrypt by the +// model's pre-save hook when created below (we use create(), not insertMany, so +// the hook runs). The stored value is always a hash. const instructors = [ { name: 'Prof. Alice Smith', @@ -50,7 +52,8 @@ const instructors = [ async function run() { await connectDB(); await Instructor.deleteMany({}); - const created = await Instructor.insertMany(instructors); + // create() runs the pre-save hook per document, so passwords are hashed. + const created = await Instructor.create(instructors); console.log(`Seeded ${created.length} instructor(s):`); for (const i of created) { console.log(` - ${i.username} (${i.role})`); diff --git a/server/tests/helpers/testEnv.js b/server/tests/helpers/testEnv.js new file mode 100644 index 0000000..c7a688a --- /dev/null +++ b/server/tests/helpers/testEnv.js @@ -0,0 +1,83 @@ +// Shared test environment for the Instructor Portal security suite. +// +// Spins up a throwaway in-memory MongoDB (a REAL mongod, so server-side +// operators like $regex and $where genuinely execute) and seeds it with the +// same accounts as src/seed/instructors.js. +// +// Seeding goes through Instructor.create(), so whatever hooks the project's own +// model defines run naturally: +// - vulnerable project -> no hook, password stored in plaintext +// - solution project -> pre('save') bcrypt hash +// The suite therefore exercises each project's real behavior with identical code. + +import mongoose from 'mongoose'; +import { MongoMemoryServer } from 'mongodb-memory-server'; +import { Instructor } from '../../src/models/Instructor.js'; + +let mongod; + +// The portal accounts under test. The `admin` superadmin is the high-value +// target holding the trophy fields (apiKey / private contact info). +export const ADMIN_PASSWORD = 'S3cr3t-Admin-Pw!'; +export const ADMIN_API_KEY = 'sk_live_9f3b2c7d8e4a1b6f0d5c2a9e'; + +export const SEED = [ + { + name: 'Prof. Alice Smith', + username: 'prof.smith', + password: 'password123', + department: 'CS', + role: 'instructor', + privateEmail: 'alice.smith@university.edu', + privatePhone: '+1-555-0101' + }, + { + name: 'Prof. Brian Jones', + username: 'prof.jones', + password: 'mathRules!', + department: 'Math', + role: 'instructor', + privateEmail: 'brian.jones@university.edu', + privatePhone: '+1-555-0102' + }, + { + name: 'Prof. Chen Lee', + username: 'prof.lee', + password: 'linalg2024', + department: 'Math', + role: 'instructor', + privateEmail: 'chen.lee@university.edu', + privatePhone: '+1-555-0103' + }, + { + name: 'Portal Administrator', + username: 'admin', + password: ADMIN_PASSWORD, + department: 'IT', + role: 'superadmin', + apiKey: ADMIN_API_KEY, + privateEmail: 'root@university.edu', + privatePhone: '+1-555-0000' + } +]; + +// Fields that must NEVER appear in any directory/search response or in an +// authentication-bypass trophy. If a test ever sees one of these on a returned +// object, a secret has leaked. +export const SECRET_FIELDS = ['password', 'apiKey', 'privateEmail', 'privatePhone']; + +export async function startDb() { + mongod = await MongoMemoryServer.create(); + await mongoose.connect(mongod.getUri(), { autoIndex: true }); +} + +export async function stopDb() { + await mongoose.disconnect(); + if (mongod) await mongod.stop(); +} + +export async function seed() { + await Instructor.deleteMany({}); + // create() (not insertMany) so a project's pre('save') hook runs if present. + await Instructor.create(SEED); +} diff --git a/server/tests/instructor-injection.test.js b/server/tests/instructor-injection.test.js new file mode 100644 index 0000000..652c80a --- /dev/null +++ b/server/tests/instructor-injection.test.js @@ -0,0 +1,210 @@ +// ============================================================================= +// Instructor Portal — NoSQL injection test suite +// ============================================================================= +// +// One suite, two outcomes: +// - Against Task-5.1-solution -> everything is GREEN (all four attacks are +// blocked and legitimate behavior still works). +// - Against the vulnerable Task-5.1 -> the four "Attack" blocks FAIL (the +// injections succeed / secrets leak), while the "Legitimate behavior" block +// stays green. +// +// The assertions check the SECURITY PROPERTY ("not logged in", "no secret field +// leaked", "no true/false oracle"), not the exact wording/status of the model +// solution, so any correct fix passes — not only this particular one. +// +// Each attack maps to a step in Flow.md. + +import { jest } from '@jest/globals'; +import request from 'supertest'; +import mongoose from 'mongoose'; + +import app from '../src/app.js'; +import { Instructor } from '../src/models/Instructor.js'; +import { + startDb, + stopDb, + seed, + SECRET_FIELDS, + ADMIN_PASSWORD +} from './helpers/testEnv.js'; + +jest.setTimeout(120000); // first run may download the mongod binary + +const api = request(app); + +// True if `obj` exposes any of the secret fields with a non-empty value. +function leaksSecret(obj) { + return SECRET_FIELDS.some( + (f) => obj != null && obj[f] !== undefined && obj[f] !== null + ); +} + +beforeAll(startDb); +afterAll(stopDb); +beforeEach(seed); + +// --------------------------------------------------------------------------- +// Attack 1 — Authentication bypass (Flow.md §2) +// Sending operators instead of string credentials must NOT log anyone in. +// --------------------------------------------------------------------------- +describe('Attack 1: authentication bypass via operator injection', () => { + test('{$ne:null}/{$ne:null} does not authenticate', async () => { + const res = await api + .post('/api/instructors/login') + .send({ username: { $ne: null }, password: { $ne: null } }); + + expect(res.status).not.toBe(200); + expect([400, 401]).toContain(res.status); + expect(res.body.instructor).toBeUndefined(); + }); + + test('{$gt:""}/{$gt:""} does not authenticate', async () => { + const res = await api + .post('/api/instructors/login') + .send({ username: { $gt: '' }, password: { $gt: '' } }); + + expect(res.status).not.toBe(200); + expect([400, 401]).toContain(res.status); + expect(res.body.instructor).toBeUndefined(); + }); +}); + +// --------------------------------------------------------------------------- +// Attack 2 — Leak hidden data via operator injection on /search (Flow.md §3) +// ?role[$ne]=instructor must not return secret fields for any account. +// --------------------------------------------------------------------------- +describe('Attack 2: operator injection on /search leaks secrets', () => { + test('?role[$ne]=instructor returns no secret fields', async () => { + const res = await api + .get('/api/instructors/search') + .query({ 'role[$ne]': 'instructor' }); + + expect(res.status).toBe(200); + const instructors = res.body.instructors || []; + const leaked = instructors.filter(leaksSecret); + expect(leaked).toEqual([]); + }); + + test('?username[$regex]=^admin returns no secret fields', async () => { + const res = await api + .get('/api/instructors/search') + .query({ 'username[$regex]': '^admin' }); + + expect(res.status).toBe(200); + const instructors = res.body.instructors || []; + expect(instructors.filter(leaksSecret)).toEqual([]); + }); +}); + +// --------------------------------------------------------------------------- +// Attack 3 — Blind password extraction via $regex oracle (Flow.md §4) +// A $regex password must (a) never log in and (b) not reveal whether the guess +// was right (same response for a right vs wrong prefix => no oracle). The stored +// password must also not be plaintext. +// --------------------------------------------------------------------------- +describe('Attack 3: $regex blind-extraction oracle', () => { + test('a $regex password object never authenticates', async () => { + const res = await api + .post('/api/instructors/login') + .send({ username: 'admin', password: { $regex: '^S' } }); + + expect(res.status).not.toBe(200); + expect(res.body.instructor).toBeUndefined(); + }); + + test('right vs wrong regex prefix are indistinguishable (no oracle)', async () => { + const right = await api + .post('/api/instructors/login') + .send({ username: 'admin', password: { $regex: '^S' } }); // matches S3cr3t... + const wrong = await api + .post('/api/instructors/login') + .send({ username: 'admin', password: { $regex: '^X' } }); // matches nothing + + expect(right.status).not.toBe(200); + expect(wrong.status).not.toBe(200); + // The attacker learns one bit per guess only if these differ. + expect(right.status).toBe(wrong.status); + }); + + test('admin password is not stored in plaintext', async () => { + const admin = await Instructor.findOne({ username: 'admin' }).select('+password'); + expect(admin).toBeTruthy(); + expect(admin.password).toBeDefined(); + expect(admin.password).not.toBe(ADMIN_PASSWORD); + }); +}); + +// --------------------------------------------------------------------------- +// Attack 4 — Server-side JavaScript execution via $where (Flow.md §5) +// $where injected through /search must not run as code nor leak secret fields. +// (mongodb-memory-server runs a local mongod that DOES allow $where, so on the +// vulnerable app this genuinely executes and leaks — which is what fails here.) +// --------------------------------------------------------------------------- +describe('Attack 4: $where server-side JavaScript injection', () => { + test('?$where=this.password.length>10 leaks no secrets', async () => { + const res = await api + .get('/api/instructors/search') + .query({ $where: 'this.password.length > 10' }); + + expect(res.status).toBe(200); + const instructors = res.body.instructors || []; + expect(instructors.filter(leaksSecret)).toEqual([]); + }); + + test("?$where=apiKey.indexOf('sk_live') leaks no secrets", async () => { + const res = await api + .get('/api/instructors/search') + .query({ $where: "this.apiKey && this.apiKey.indexOf('sk_live') === 0" }); + + expect(res.status).toBe(200); + const instructors = res.body.instructors || []; + expect(instructors.filter(leaksSecret)).toEqual([]); + }); +}); + +// --------------------------------------------------------------------------- +// Legitimate behavior — must keep working after the fix. These pass on BOTH the +// vulnerable and the solution projects (the fix must not break normal use). +// --------------------------------------------------------------------------- +describe('Legitimate behavior is preserved', () => { + test('honest login with the correct password succeeds', async () => { + const res = await api + .post('/api/instructors/login') + .send({ username: 'admin', password: ADMIN_PASSWORD }); + + expect(res.status).toBe(200); + expect(res.body.instructor).toBeDefined(); + expect(res.body.instructor.role).toBe('superadmin'); + }); + + test('honest login with a wrong password is rejected', async () => { + const res = await api + .post('/api/instructors/login') + .send({ username: 'admin', password: 'definitely-wrong' }); + + expect(res.status).toBe(401); + expect(res.body.instructor).toBeUndefined(); + }); + + test('public directory returns only safe fields', async () => { + const res = await api.get('/api/instructors'); + + expect(res.status).toBe(200); + const instructors = res.body.instructors || []; + expect(instructors.length).toBeGreaterThan(0); + expect(instructors.filter(leaksSecret)).toEqual([]); + }); + + test('honest search by name finds the matching instructor', async () => { + // Full name is used so this is green on both versions (the vulnerable + // search does an exact match; the solution does a case-insensitive contains). + const res = await api + .get('/api/instructors/search') + .query({ name: 'Prof. Alice Smith' }); + + expect(res.status).toBe(200); + const names = (res.body.instructors || []).map((i) => i.name); + expect(names).toContain('Prof. Alice Smith'); + }); +});