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
8 changes: 2 additions & 6 deletions client/src/pages/InstructorDashboard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { api } from '../api'

// Instructor Portal dashboard. Reads the naive session from localStorage.
// Instructor Portal dashboard. Reads the signed-in profile 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.
// The search box sends a plain string to the restricted public directory search.
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 form sends plain string credentials to the instructor login endpoint.
export default function InstructorLogin() {
const nav = useNavigate()
const [username, setUsername] = useState('')
Expand Down
20 changes: 20 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions server/src/app.js
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -11,6 +12,7 @@ const app = express();
app.use(morgan('dev'));
app.use(cors({ origin: 'http://localhost:5175', credentials: false }));
app.use(express.json());
app.use(mongoSanitize());

app.get('/api/health', (req, res) => res.json({ ok: true }));

Expand Down
72 changes: 26 additions & 46 deletions server/src/controllers/instructorController.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,34 @@
import bcrypt from 'bcryptjs';
import Joi from 'joi';
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().trim().min(1).max(80).required(),
password: Joi.string().min(1).max(200).required()
}).unknown(false);

const searchSchema = Joi.object({
name: Joi.string().trim().max(100),
department: Joi.string().trim().max(80)
}).unknown(true);

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

// 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' });
}
const { value, error } = loginSchema.validate(req.body, { convert: true });
if (error) return res.status(400).json({ message: 'username and password must be strings' });

// ⚠️ 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 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) });
Expand All @@ -54,9 +37,6 @@ 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.
export async function getDirectory(req, res, next) {
try {
const instructors = await Instructor.find()
Expand All @@ -69,18 +49,18 @@ export async function getDirectory(req, res, next) {
}
}

// 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 { value, error } = searchSchema.validate(req.query, { convert: true });
if (error) return res.status(400).json({ message: 'name and department must be strings' });

const filter = {};
if (value.name) filter.name = { $regex: value.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), $options: 'i' };
if (value.department) filter.department = value.department;
const instructors = await Instructor.find(filter)
.select('name department role')
.sort({ name: 1 })
.lean();
res.json({ count: instructors.length, instructors });
} catch (err) {
next(err);
Expand Down
14 changes: 6 additions & 8 deletions server/src/models/Instructor.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
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'

Expand All @@ -23,4 +17,8 @@ const instructorSchema = new mongoose.Schema(
{ timestamps: true }
);

instructorSchema.pre('save', async function hashPassword() {
if (this.isModified('password')) this.password = await bcrypt.hash(this.password, 10);
});

export const Instructor = mongoose.model('Instructor', instructorSchema);
5 changes: 2 additions & 3 deletions server/src/seed/instructors.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ 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.
const instructors = [
{
name: 'Prof. Alice Smith',
Expand Down Expand Up @@ -50,7 +49,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
Loading