Skip to content
Open
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
19 changes: 19 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ Thumbs.db

# Server-side specific ignores (if server is in a subfolder)
server/node_modules/
server/build/
server/build/
server/.local-demo/
5 changes: 5 additions & 0 deletions Flow.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# NoSQL Injection Lab — Instructor Portal

> This walkthrough describes the original vulnerable implementation. After the
> security fix, operator requests should return **400**, not the success
> responses shown below. See `SECURITY.md` for implementation and verification
> details, including which checks have actually been run locally.

This walkthrough shows you how to attack the **Instructor Portal** of the Course
Review Board and, step by step, *why* each attack works. You will:

Expand Down
6 changes: 1 addition & 5 deletions client/src/pages/InstructorDashboard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import { api } from '../api'

// Instructor Portal dashboard. Reads the naive session from localStorage.
// Shows the signed-in profile, the public directory, and a name search.
// The search box sends a plain string; students intercept the request
// (Postman / proxy) to inject MongoDB operators — see Flow.md.
// Search returns public directory fields and treats the name as literal text.
export default function InstructorDashboard() {
const nav = useNavigate()
const [instructor, setInstructor] = useState(null)
Expand Down Expand Up @@ -58,9 +57,6 @@ export default function InstructorDashboard() {
<div className="text-sm text-zinc-600">
@{instructor.username} • {instructor.department} • role: <b>{instructor.role}</b>
</div>
{instructor.apiKey && (
<div className="text-sm mt-1">API key: <code>{instructor.apiKey}</code></div>
)}
</div>
<button onClick={logout} className="btn">Log out</button>
</div>
Expand Down
3 changes: 1 addition & 2 deletions client/src/pages/InstructorLogin.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import { api } from '../api'
// Instructor Portal login. This portal is separate from the student JWT auth
// (AuthContext) — it has its own simple session stored in localStorage.
//
// The form sends plain strings (honest use). The backing endpoint is
// intentionally vulnerable to NoSQL injection; see Flow.md for the lab.
// The backing endpoint validates string credentials and verifies a bcrypt hash.
export default function InstructorLogin() {
const nav = useNavigate()
const [username, setUsername] = useState('')
Expand Down
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
],
"scripts": {
"install:all": "npm --workspaces install",
"dev": "concurrently -n server,client -c blue,magenta \"npm:dev --workspace server\" \"npm:dev --workspace client\""
"dev": "concurrently -n server,client -c blue,magenta \"npm --prefix server run dev\" \"npm --prefix client run dev\""
},
"devDependencies": {
"concurrently": "^8.2.2"
}
}
}
6 changes: 5 additions & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
"scripts": {
"dev": "nodemon src/index.js",
"start": "node src/index.js",
"dev:db": "node src/seed/localDemoDb.js",
"seed:instructors": "node src/seed/instructors.js",
"test": "NODE_OPTIONS=--experimental-vm-modules jest --runInBand"
"migrate:instructor-passwords": "node src/seed/migrateInstructorPasswords.js",
"test:unit": "node --test tests/instructor-controller.check.js",
"test": "node --experimental-vm-modules ../node_modules/jest/bin/jest.js --runInBand"
},
"jest": {
"testEnvironment": "node",
Expand All @@ -19,6 +22,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",
Expand Down
98 changes: 37 additions & 61 deletions server/src/controllers/instructorController.js
Original file line number Diff line number Diff line change
@@ -1,86 +1,62 @@
import Joi from 'joi';
import bcrypt from 'bcryptjs';
import { Instructor } from '../models/Instructor.js';

// =============================================================================
// INSTRUCTOR PORTAL CONTROLLER — ⚠️ INTENTIONALLY VULNERABLE (security lab)
// =============================================================================
//
// 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".
// =============================================================================
const loginSchema = Joi.object({
username: Joi.string().max(100).required(),
// bcrypt uses at most 72 bytes. Never trim or otherwise alter passwords.
password: Joi.string().required().custom((value, helpers) =>
Buffer.byteLength(value, 'utf8') <= 72 ? value : helpers.error('any.invalid'))
}).required();
const searchSchema = Joi.object({
name: Joi.string().max(100).allow(''),
department: Joi.string().max(100),
role: Joi.string().valid('instructor', 'superadmin')
}).required();
const validationOptions = { convert: false, abortEarly: false, allowUnknown: false };
const directoryFields = '_id name department role';
const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

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
};
}

// 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 });

if (!instructor) {
const { error, value } = loginSchema.validate(req.body, validationOptions);
if (error) return res.status(400).json({ message: 'Invalid login input' });
// Only a validated username enters the query; bcrypt verifies the password.
const instructor = await Instructor.findOne({ username: value.username }).select('+password');
if (!instructor || !(await bcrypt.compare(value.password, instructor.password))) {
return res.status(401).json({ message: 'Invalid credentials' });
}
return res.json({ instructor: publicProfile(instructor) });
return res.json({ instructor: {
id: instructor._id.toString(),
name: instructor.name,
username: instructor.username,
department: instructor.department,
role: instructor.role
} });
} catch (err) {
next(err);
}
}

// GET /api/instructors
// Public directory. Deliberately limited fields so the contrast with the
// leaky /search endpoint below is obvious.
export async function getDirectory(req, res, next) {
try {
const instructors = await Instructor.find()
.select('name department role')
.sort({ name: 1 })
.lean();
const instructors = await Instructor.find().select(directoryFields).sort({ name: 1 }).lean();
res.json({ instructors });
} catch (err) {
next(err);
}
}

// 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();
const { error, value } = searchSchema.validate(req.query, validationOptions);
if (error) return res.status(400).json({ message: 'Invalid search input' });
// Build a filter from allowed strings. Search text is literal, not regex code.
const filter = {};
if (value.name) filter.name = { $regex: escapeRegex(value.name), $options: 'i' };
if (value.department) filter.department = value.department;
if (value.role) filter.role = value.role;
const instructors = await Instructor.find(filter).select(directoryFields).sort({ name: 1 }).lean();
res.json({ count: instructors.length, instructors });
} catch (err) {
next(err);
Expand Down
16 changes: 16 additions & 0 deletions server/src/middleware/instructorInput.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import mongoSanitize from 'express-mongo-sanitize';

const sanitize = mongoSanitize({
onSanitize: ({ req }) => { req.unsafeInstructorInput = true; }
});

export function sanitizeInstructorInput(req, res, next) {
sanitize(req, res, (err) => {
if (err) return next(err);
// Silently dropping operators could broaden a search to every account.
if (req.unsafeInstructorInput) {
return res.status(400).json({ message: 'Query operators and dotted keys are not allowed' });
}
next();
});
}
29 changes: 15 additions & 14 deletions server/src/models/Instructor.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
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.
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 },
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 }
role: { type: String, enum: ['instructor', 'superadmin'], default: 'instructor' },
apiKey: { type: String, select: false },
privateEmail: { type: String, select: false },
privatePhone: { type: String, select: false }
},
{ timestamps: true }
);

instructorSchema.pre('save', async function () {
if (this.isModified('password')) {
if (Buffer.byteLength(this.password, 'utf8') > 72) {
throw new Error('Password must not exceed 72 bytes');
}
this.password = await bcrypt.hash(this.password, 12);
}
});

export const Instructor = mongoose.model('Instructor', instructorSchema);
6 changes: 4 additions & 2 deletions server/src/routes/instructors.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Router } from 'express';
import { sanitizeInstructorInput } from '../middleware/instructorInput.js';
import {
loginInstructor,
getDirectory,
Expand All @@ -7,8 +8,9 @@ import {

const router = Router();

// The Instructor Portal has its own (naive, vulnerable) login — it does NOT use
// the JWT requireAuth middleware. That is intentional for the lab.
router.use(sanitizeInstructorInput);

// The instructor portal is separate from student JWT authentication.
router.post('/login', loginInstructor);
router.get('/', getDirectory);
router.get('/search', searchInstructors);
Expand Down
4 changes: 2 additions & 2 deletions server/src/seed/instructors.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ 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).
// create() runs the model's bcrypt save hook before storing these fixtures.
const instructors = [
{
name: 'Prof. Alice Smith',
Expand Down Expand Up @@ -50,7 +50,7 @@ const instructors = [
async function run() {
await connectDB();
await Instructor.deleteMany({});
const created = await Instructor.insertMany(instructors);
const created = await Instructor.create(instructors);
console.log(`Seeded ${created.length} instructor(s):`);
for (const i of created) {
console.log(` - ${i.username} (${i.role})`);
Expand Down
30 changes: 30 additions & 0 deletions server/src/seed/localDemoDb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Local-only MongoDB for the TA demonstration; no system installation required.
import { MongoMemoryServer } from 'mongodb-memory-server';
import { mkdir } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';

const dbPath = fileURLToPath(new URL('../../.local-demo/mongo-data/', import.meta.url));
const systemBinary = fileURLToPath(new URL('../../.local-demo/bin/mongod.exe', import.meta.url));
await mkdir(dbPath, { recursive: true });

const database = await MongoMemoryServer.create({
binary: { version: '7.0.14', ...(existsSync(systemBinary) ? { systemBinary } : {}) },
instance: {
ip: '127.0.0.1',
port: 27017,
dbPath,
storageEngine: 'wiredTiger'
}
});
console.log('Local demo MongoDB ready at mongodb://127.0.0.1:27017/task51_ta_demo');

let stopping = false;
async function stop() {
if (stopping) return;
stopping = true;
await database.stop({ doCleanup: false });
process.exit(0);
}
process.on('SIGINT', stop);
process.on('SIGTERM', stop);
23 changes: 23 additions & 0 deletions server/src/seed/migrateInstructorPasswords.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import 'dotenv/config';
import mongoose from 'mongoose';
import { connectDB } from '../config/db.js';
import { Instructor } from '../models/Instructor.js';

// One-time upgrade for accounts created by the original plaintext seed.
// Use save() so hashing follows the same rules as new accounts.
try {
await connectDB();
let migrated = 0;
for await (const instructor of Instructor.find().select('+password').cursor()) {
if (/^\$2[aby]\$\d{2}\$[./A-Za-z0-9]{53}$/.test(instructor.password)) continue;
instructor.markModified('password');
await instructor.save();
migrated++;
}
console.log(`Hashed passwords for ${migrated} existing instructor(s).`);
} catch (err) {
console.error('Password migration failed:', err.message);
process.exitCode = 1;
} finally {
await mongoose.disconnect();
}
Loading