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
42 changes: 37 additions & 5 deletions server/src/app.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@

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 @@ -9,25 +12,54 @@ import instructorRoutes from './routes/instructors.js';
const app = express();

app.use(morgan('dev'));
app.use(cors({ origin: 'http://localhost:5175', credentials: false }));

app.use(cors({
origin: 'http://localhost:5175',
credentials: false
}));

app.use(express.json());

app.get('/api/health', (req, res) => res.json({ ok: true }));
// Protect request bodies against MongoDB operator injection
app.use((req, res, next) => {
if (mongoSanitize.has(req.body)) {
return res.status(400).json({
message: 'Invalid request input'
});
}

if (req.body && typeof req.body === 'object') {
mongoSanitize.sanitize(req.body);
}

next();
});

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

// API routes
app.use('/api/auth', authRoutes);
app.use('/api/reviews', reviewRoutes);
app.use('/api/users', userRoutes);
app.use('/api/instructors', instructorRoutes);

// Not found
// 404 handler
app.use((req, res) => {
res.status(404).json({ message: 'Not Found' });
res.status(404).json({
message: 'Not Found'
});
});

// Error handler
app.use((err, req, res, next) => {
console.error(err);
res.status(err.status || 500).json({ message: err.message || 'Server Error' });

res.status(err.status || 500).json({
message: err.message || 'Server Error'
});
});

export default app;
134 changes: 90 additions & 44 deletions server/src/controllers/instructorController.js
Original file line number Diff line number Diff line change
@@ -1,69 +1,95 @@

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".
// =============================================================================
// Login validation
const loginSchema = Joi.object({
username: Joi.string().trim().min(1).max(100).required(),
password: Joi.string().min(1).max(256).required()
}).unknown(false);

// Search validation
const searchSchema = Joi.object({
name: Joi.string().trim().min(1).max(100).required()
}).unknown(false);

// Only expose approved instructor information
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 special characters in user search text
function escapeRegex(text) {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

// 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 { error, value } = loginSchema.validate(
req.body,
{ convert: false }
);

if (error) {
return res.status(400).json({
message: 'Invalid login input'
});
}

// ⚠️ 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 { username, password } = value;

// Only search using the validated username
const instructor = await Instructor.findOne({
username: username
}).select('+password');

if (!instructor) {
return res.status(401).json({ message: 'Invalid credentials' });
return res.status(401).json({
message: 'Invalid credentials'
});
}
return res.json({ instructor: publicProfile(instructor) });

// Compare plaintext input against stored bcrypt hash
const passwordMatches = await bcrypt.compare(
password,
instructor.password
);

if (!passwordMatches) {
return res.status(401).json({
message: 'Invalid credentials'
});
}

return res.status(200).json({
instructor: publicProfile(instructor)
});

} 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();
res.json({ instructors });

return res.status(200).json({
instructors
});

} catch (err) {
next(err);
}
Expand All @@ -72,16 +98,36 @@ 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();
res.json({ count: instructors.length, instructors });
const { error, value } = searchSchema.validate(
req.query,
{ convert: false }
);

// Unsupported or injected search parameters
// must never reach the MongoDB query.
if (error) {
return res.status(200).json({
count: 0,
instructors: []
});
}

const safeName = escapeRegex(value.name);

const instructors = await Instructor.find({
name: {
$regex: safeName,
$options: 'i'
}
})
.select('name username department role')
.lean();

return res.status(200).json({
count: instructors.length,
instructors
});

} catch (err) {
next(err);
}
Expand Down
Loading