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
10 changes: 10 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
4 changes: 3 additions & 1 deletion server/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import authRoutes from './routes/auth.js';
import reviewRoutes from './routes/reviews.js';
import userRoutes from './routes/users.js';
import instructorRoutes from './routes/instructors.js';
import mongoSanitize from 'express-mongo-sanitize';


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

app.use('/api/auth', authRoutes);
Expand Down
40 changes: 28 additions & 12 deletions server/src/controllers/instructorController.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Instructor } from '../models/Instructor.js';
import Joi from 'joi';


// =============================================================================
// INSTRUCTOR PORTAL CONTROLLER — ⚠️ INTENTIONALLY VULNERABLE (security lab)
Expand All @@ -14,6 +16,20 @@ import { Instructor } from '../models/Instructor.js';
// This is the bug students must find and fix. Do not "clean this up".
// =============================================================================



const loginSchema = Joi.object({
username: Joi.string().required().min(2).max(50),
password: Joi.string().required()
});


const searchSchema = Joi.object({
name: Joi.string().max(100).min(1),
department: Joi.string().max(100).min(1)
}).options({ stripUnknown: true });


function publicProfile(doc) {
// A successful login is a "trophy": we deliberately return the sensitive
// fields so a bypass clearly reveals what it compromised.
Expand All @@ -32,27 +48,25 @@ function publicProfile(doc) {
// 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);
if (error) return res.status(400).json({ message: error.message });


// ⚠️ 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) {
return res.status(401).json({ message: 'Invalid credentials' });
}
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);
}
}
}}


// GET /api/instructors
// Public directory. Deliberately limited fields so the contrast with the
Expand All @@ -79,7 +93,9 @@ export async function searchInstructors(req, res, next) {
// ?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 { value, error } = searchSchema.validate(req.query);
if (error) return res.status(400).json({ message: error.message });
const filter = value;
const instructors = await Instructor.find(filter).lean();
res.json({ count: instructors.length, instructors });
} catch (err) {
Expand Down
17 changes: 13 additions & 4 deletions server/src/models/Instructor.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';

// Instructor Portal account.
//
Expand All @@ -11,16 +12,24 @@ 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 }
apiKey: { type: String, select: false },
privateEmail: { type: String, select: false},
privatePhone: { type: String, select: false }
},
{ timestamps: true }
);

instructorSchema.methods.comparePassword = async function (password) {
return bcrypt.compare(password, this.password);
};
instructorSchema.pre('save', async function (next) {
if (!this.isModified('password')) return next();
this.password = await bcrypt.hash(this.password, 10);
next();
});
export const Instructor = mongoose.model('Instructor', instructorSchema);
8 changes: 6 additions & 2 deletions server/src/seed/instructors.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ dotenv.config();
import mongoose from 'mongoose';
import { connectDB } from '../config/db.js';
import { Instructor } from '../models/Instructor.js';
import bcrypt from 'bcryptjs';

// Seed data for the Instructor Portal NoSQL injection lab.
// Passwords are plaintext ON PURPOSE (see Instructor model / Flow.md).
Expand Down Expand Up @@ -49,8 +50,11 @@ const instructors = [

async function run() {
await connectDB();
await Instructor.deleteMany({});
const created = await Instructor.insertMany(instructors);
await Instructor.deleteMany({});
const hashed = await Promise.all(
instructors.map(async (i) => ({ ...i, password: await bcrypt.hash(i.password, 10) }))
);
const created = await Instructor.insertMany(hashed);
console.log(`Seeded ${created.length} instructor(s):`);
for (const i of created) {
console.log(` - ${i.username} (${i.role})`);
Expand Down
83 changes: 83 additions & 0 deletions server/tests/helpers/testEnv.js
Original file line number Diff line number Diff line change
@@ -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);
}
Loading