devHọc Dev

Week 1 - Day 3: SQL Injection, SSRF, IDOR and Password Hashing

Week 1 – Day 3

This lesson combines 2 topics: SQL Injection, SSRF, IDOR, Password Hashing & Storage.

Learning Objectives

  • Understand the 4 types of SQL Injection: Union-based, Error-based, Boolean-based blind, Time-based blind
  • Write secure code with prepared statements / parameterized queries in Node, Python, Go
  • Understand SSRF and the role of the AWS Instance Metadata Service (IMDSv1 vs IMDSv2)
  • Understand IDOR (Insecure Direct Object Reference) and how to fix it with authorization checks
  • Learn the bypass techniques attackers commonly use to get past naive filters
  • Understand why you must never store passwords as plaintext or with a plain hash (MD5/SHA-256)
  • Master the three standard password hashing algorithms: bcrypt, argon2id, scrypt
  • Distinguish salt (per-user) from pepper (server secret) and understand the role of each
  • Read and write hashing/verification code in Node.js and Python
  • Avoid common mistakes: short salts, low work factors, custom crypto, timing attacks

Part 1: SQL Injection, SSRF, IDOR

1. SQL Injection: When User Input Becomes SQL Code

SQL Injection happens when user input is concatenated into a SQL statement without escaping/parameterization → the attacker injects their own SQL syntax.

The classic example

// VULNERABLE
app.get('/login', (req, res) => {
  const { user, pass } = req.query;
  const sql = `SELECT * FROM users WHERE username='${user}' AND password='${pass}'`;
  db.query(sql, (err, rows) => {
    if (rows.length > 0) res.send('Login OK');
    else res.send('Fail');
  });
});

The attacker sends:

?user=admin'--&pass=anything

The actual SQL:

SELECT * FROM users WHERE username='admin'--' AND password='anything'
                                          ↑
                                  -- comment, AND password is ignored

→ Logged in as admin, no password needed.

Real-world impact

TalkTalk (2015)            156K customers, £77M loss
Sony Pictures (2011)       ~1M accounts (LulzSec, SQLi)
Heartland Payment (2008)   134M credit cards

All of them had SQL Injection as the entry point or escalation path.
(Capital One 2019 was NOT SQLi; it was SSRF, see §5.)

2. Types of SQL Injection

Union-based: pulling data from other tables

When the response shows query results, the attacker uses UNION SELECT to merge data from another table.

GET /products?id=1
SQL: SELECT name, price FROM products WHERE id=1

Attacker: ?id=1 UNION SELECT username, password FROM users--
SQL: SELECT name, price FROM products WHERE id=1
     UNION SELECT username, password FROM users--

Response: [name="iPhone", price=999], [name="admin", price="$2y$10$..."]
                                          ↑
                                  The admin's password hash

Error-based: database errors leak data

The attacker tricks the DB into throwing an error that contains data in its message:

-- MySQL
?id=1 AND (SELECT 1 FROM (SELECT COUNT(*),CONCAT(version(),FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)y)

-- Error message:
-- "Duplicate entry '8.0.30-MySQL1' for key '<group_key>'"
--                    ↑ data leaked via the error

Secondary mitigation: the app must NOT return stack traces / DB error messages to the client (return a generic 500).

Boolean-based Blind: asking yes/no questions

When the response does not display data, the attacker uses true/false questions to infer it:

?id=1 AND (SELECT SUBSTRING(password,1,1) FROM users WHERE username='admin')='a'
→ Page loads normally → true, the first character is 'a'

?id=1 AND (SELECT SUBSTRING(password,1,1) FROM users WHERE username='admin')='b'
→ Different page → false

Repeat for each character and each position → recover the password one character at a time

Slow but still usable. Tools like sqlmap automate thousands of requests.

Time-based Blind: using delay as the signal

When responses are completely identical, the attacker uses SLEEP to tell them apart:

?id=1 AND IF((SELECT SUBSTRING(password,1,1) FROM users WHERE id=1)='a', SLEEP(5), 0)
-- If the response is delayed by 5s → the first character is 'a'

Extremely slow (1 character = 1 five-second request), but an attacker with patience can still dump the full DB.

3. Prepared Statement / Parameterized Query: The Standard Solution

Separate the SQL statement and the data into two parts. The DB engine knows which part is code and which is a literal; input is never parsed as SQL.

Node.js — mysql2

// VULNERABLE
const sql = `SELECT * FROM users WHERE username='${user}'`;

// SECURE — parameterized
const [rows] = await db.execute(
  'SELECT * FROM users WHERE username = ? AND password = ?',
  [user, pass]
);

Node.js — pg (PostgreSQL)

const { rows } = await pool.query(
  'SELECT * FROM users WHERE username = $1 AND password = $2',
  [user, pass]
);

Python — psycopg2 / psycopg3

# VULNERABLE
cursor.execute(f"SELECT * FROM users WHERE username='{user}'")

# SECURE
cursor.execute(
    "SELECT * FROM users WHERE username = %s AND password = %s",
    (user, pass)
)

Note: %s here is not Python string formatting; it is psycopg's placeholder.

Python — SQLAlchemy ORM

# SECURE — the ORM parameterizes automatically
user = session.query(User).filter(User.username == username).first()

# Or raw with :param
result = session.execute(
    text("SELECT * FROM users WHERE username = :u"),
    {"u": username}
)

Go — database/sql

// VULNERABLE
query := fmt.Sprintf("SELECT * FROM users WHERE username='%s'", user)
db.Query(query)

// SECURE
rows, err := db.Query(
    "SELECT * FROM users WHERE username = $1 AND password = $2",
    user, pass,
)

ORMs are safe by default, but be careful with raw queries

// Prisma — SECURE
const user = await prisma.user.findFirst({
  where: { username: userInput }
});

// Prisma — VULNERABLE if you use $queryRawUnsafe
await prisma.$queryRawUnsafe(`SELECT * FROM users WHERE name='${userInput}'`);

// Prisma — SECURE with the template tag
await prisma.$queryRaw`SELECT * FROM users WHERE name=${userInput}`;
//                  ↑ the tagged template parameterizes automatically

4. Things You CANNOT Parameterize

Prepared statements only parameterize literal values. These cannot be bound as parameters:

  • Column names, table names
  • ORDER BY <column>
  • LIMIT <n> (in some DBs)
  • The size of an entire IN (...) list

If these parts must be dynamic, whitelist them against the allowed values:

const ALLOWED_SORT = ['name', 'price', 'created_at'];
const sortCol = ALLOWED_SORT.includes(req.query.sort) ? req.query.sort : 'created_at';
const order = req.query.order === 'desc' ? 'DESC' : 'ASC';

const sql = `SELECT * FROM products ORDER BY ${sortCol} ${order} LIMIT ?`;
db.query(sql, [pageSize]);

5. Server-Side Request Forgery (SSRF)

SSRF happens when the server fetches a user-supplied URL/resource without validating the destination. The attacker forces the server to call internal endpoints that are not reachable from the internet.

Patterns prone to SSRF

  • "Import URL" features (avatar, document, RSS)
  • Webhook callers
  • "Link preview" that generates OG meta
  • PDF/screenshot generators that render a user-entered URL
  • File proxy / image resizer

Classic exploit: the AWS metadata service

An EC2 instance has an internal service that returns IAM credentials:

http://169.254.169.254/latest/meta-data/iam/security-credentials/<role>

Response:
{
  "AccessKeyId": "AKIA...",
  "SecretAccessKey": "...",
  "Token": "...",
  "Expiration": "..."
}

The attacker exploits SSRF:

POST /api/screenshot
{ "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/web-role" }

→ The server fetches it → returns the credentials in the response → the attacker uses the AWS CLI with those credentials → full AWS account compromise.

This is the Capital One 2019 breach: SSRF + IMDSv1 + an over-permissioned IAM role.

IMDSv1 vs IMDSv2

IMDSv1(legacy)─────────────────────────────────────────────Request:GEThttp://169.254.169.254/latest/meta-data/...Response:credentialJSON→AnyHTTPclientontheEC2instancecancallit,includingviaSSRF
IMDSv2(recommended)─────────────────────────────────────────────Step1—Gettoken(PUT):PUThttp://169.254.169.254/latest/api/tokenHeader:X-aws-ec2-metadata-token-ttl-seconds:21600→returns:<token>Step2—Usetoken:GEThttp://169.254.169.254/latest/meta-data/...Header:X-aws-ec2-metadata-token:<token>WhyitstopsSSRF:-RequiresaPUTrequest→mostSSRFonlyallowsGET-Requiresacustomheader→SSRFviaaURLcannotsetheaders-ThetokenhasaTTL→itisnotstoredforever

Require IMDSv2 on every new EC2 instance/ASG. AWS now lets you disable IMDSv1 at the account level.

Internal network access

SSRF is also used to scan/access internal services:

  • http://localhost:6379/: Redis (often without auth)
  • http://10.0.0.5:9200/: Elasticsearch admin
  • http://internal-jenkins:8080/: Jenkins
  • file:///etc/passwd: local file read (if the library supports file://)

SSRF mitigation

1. Whitelist URL/scheme/host

const ALLOWED_HOSTS = ['cdn.example.com', 'api.partner.com'];
const ALLOWED_SCHEMES = ['https:'];

function isUrlSafe(rawUrl) {
  try {
    const u = new URL(rawUrl);
    if (!ALLOWED_SCHEMES.includes(u.protocol)) return false;
    if (!ALLOWED_HOSTS.includes(u.hostname)) return false;
    return true;
  } catch {
    return false;
  }
}

2. Block private IP ranges + the metadata IP

import ipaddress
import socket
from urllib.parse import urlparse

BLOCKED = [
    ipaddress.ip_network('10.0.0.0/8'),
    ipaddress.ip_network('172.16.0.0/12'),
    ipaddress.ip_network('192.168.0.0/16'),
    ipaddress.ip_network('127.0.0.0/8'),
    ipaddress.ip_network('169.254.0.0/16'),   # AWS/Azure/GCP metadata + link-local
    ipaddress.ip_network('::1/128'),
    ipaddress.ip_network('fc00::/7'),         # IPv6 ULA
]

def is_safe_url(url: str) -> bool:
    parsed = urlparse(url)
    if parsed.scheme not in ('http', 'https'):
        return False
    try:
        ip = socket.gethostbyname(parsed.hostname)
    except socket.gaierror:
        return False
    ip_obj = ipaddress.ip_address(ip)
    return not any(ip_obj in net for net in BLOCKED)

3. DNS rebinding protection

Resolve the hostname once and connect using the verified IP, so the attacker cannot use DNS to return a different IP between the check and the connection:

import requests
ip = socket.gethostbyname(hostname)
if not is_safe(ip):
    raise SSRFError()

# Connect via the IP, set the Host header manually
resp = requests.get(f"https://{ip}/path", headers={"Host": hostname}, verify=False)

4. Network-level defenses

  • Disable IMDSv1, enforce IMDSv2
  • EC2 metadata hop limit = 1 (prevents containers from accessing metadata)
  • VPC egress: only allow outbound traffic to a whitelist
  • IAM roles follow least privilege

6. Insecure Direct Object Reference (IDOR)

IDOR happens when the app references an object via an identifier (ID, filename) without verifying that the user is allowed to access that object.

Classic example

// VULNERABLE
app.get('/api/users/:id/profile', authMiddleware, async (req, res) => {
  const user = await User.findById(req.params.id);
  res.json(user);   // ← doesn't check user.id === req.user.id
});

User A logs in (/api/users/100/profile returns their own data). Changing the URL to /api/users/101/profile → returns user B's data. No auth bypass needed, just change the number.

Real-world examples

  • Snapchat 2014: phone number lookup by brute forcing numeric IDs
  • Facebook page admin role via page ID + IDOR
  • Optus 2022 (Australia): 10M customers leaked through an API endpoint with no authorization check and guessable IDs

Patterns prone to IDOR

  • /api/orders/123 (numeric, guessable)
  • /files/download?path=user_456_invoice.pdf
  • /api/messages/abc-123/read (UUID but no ownership check)
  • GraphQL query { user(id: "X") { email } }

Fix #1: Authorization check

app.get('/api/users/:id/profile', authMiddleware, async (req, res) => {
  const targetId = req.params.id;

  // Authorization: only the owner or an admin
  if (targetId !== req.user.id && req.user.role !== 'admin') {
    return res.status(403).json({ error: 'Forbidden' });
  }

  const user = await User.findById(targetId);
  res.json(user);
});

Fix #2: Queries scoped to the user

Instead of fetching by ID and checking afterward, scope the query up front:

// Better — cannot leak because the query filters
const order = await Order.findOne({
  where: { id: orderId, userId: req.user.id }
});
if (!order) return res.status(404).json({ error: 'Not found' });
res.json(order);

Return 404 instead of 403 so you don't leak "whether the object exists", which prevents enumeration.

Fix #3: Use opaque identifiers

/api/orders/123
        ↓ replace with a UUID or random token
/api/orders/d4f8e2b1-...

UUIDs are hard to guess → less risk of brute force enumeration. But they do not replace the authorization check: if a UUID leaks, IDOR still happens. Defense in depth: use UUIDs + check ownership.

Fix #4: Capability-based URL

The URL carries a capability token instead of a raw ID:

/api/download?token=eyJhbGciOiJIUzI1NiJ9...
                         ↑ signed JWT containing fileId + userId + expiry

The token is signed, so the user cannot modify it. It expires quickly (5 minutes) and is one-time use.

7. Common Bypass Tricks

Attackers try these techniques to get past naive filters:

Encoding tricks

Original:  '<script>alert(1)</script>'
URL enc:   %3Cscript%3Ealert(1)%3C/script%3E
Double:    %253Cscript%253E              (decode once → %3C... → server decodes a 2nd time)
Unicode:   <script>
HTML enc:  &lt;script&gt;                 (server decodes HTML entities)

Mitigation: decode only once, and validate after decoding is complete.

Case variation

SELECT  →  SeLeCt, sELECT, /*!50000SELECT*/  (MySQL inline comment)
script  →  ScRiPt

Mitigation: filter case-insensitively + use output encoding, not a blacklist.

Filter regex bypass

// VULNERABLE — strip "<script>"
input.replace(/<script>/gi, '');
// Bypass: <scr<script>ipt>  → after the replace, "<script>" remains

Mitigation: don't try to "sanitize" with a regex blacklist; use a proper library (DOMPurify).

Path traversal

?file=../../etc/passwd
?file=..%2F..%2Fetc%2Fpasswd
?file=....//....//etc/passwd     (strip "../" once → "../../")

Mitigation: path.normalize and then verify the path lies inside the allowed directory:

const safePath = path.resolve(BASE_DIR, req.query.file);
if (!safePath.startsWith(BASE_DIR + path.sep)) {
  return res.status(400).send('Bad path');
}

Null byte injection

?file=secret.txt%00.jpg

Some languages (C, old PHP) truncate strings at the null byte. Mitigation: reject input containing \x00.

IDOR via numeric vs string ID

/api/users/123        → forbid
/api/users/123/       → bypass? (trailing slash hits a different middleware route)
/api/users/0123       → leading zero?
/api/users/123e2      → "12300" parsed as float (JS!)

Mitigation: normalize input, use strict framework routes, parse IDs strictly.

HTTP method override

Forms only allow GET/POST. To bypass:
POST /api/users/123
X-HTTP-Method-Override: DELETE

The backend honors this header → executes DELETE

Mitigation: don't enable method override unless needed; if you need it, apply the authz check to the effective method.

Part 2: Password Hashing & Storage

1. Why Plaintext Passwords Are a Disaster

Breach scenario

Theattackergetsholdoftheusersdatabase:┌──────────────────────────────────────┐│idemailpassword││1alice@x.comsunshine123│←plaintext│2bob@y.comqwerty││3carol@z.comMyDog2024!│└──────────────────────────────────────┘

Consequences:

  • Credential stuffing: 60-80% of users reuse passwords → the attacker tries the same password on Gmail, Facebook, banks
  • Phishing target list: the attacker knows the email + password pattern
  • Legal liability: GDPR/CCPA fines are very heavy if plaintext is exposed
  • Reputation: the company loses all trust (Adobe 2013, Yahoo 2013, LinkedIn 2012)

Why SHA-256/MD5 is not enough either

General-purpose hashes are designed for speed, which is exactly what you DON'T want for passwords.

SHA-256 on a modern GPU (RTX 4090):
~10 billion hashes/second

Real attacks:

  • Rainbow table: precomputed hashes of the top 10 million common passwords; lookup in microseconds
  • Brute force of an 8-char password: ~a few hours on one GPU
  • Dictionary attack: try a dictionary + variants (P@ssw0rd, sunshine123); a few minutes

General-purpose hashes (MD5, SHA-1, SHA-256, SHA-512) lack:

  • Automatic salt → same password = same hash → rainbow tables thrive
  • Work factor → cannot be slowed down as GPUs get faster
  • Memory hardness → GPUs/ASICs break them easily

2. Standard Password Hashing Algorithms

bcrypt (1999)

bcrypthashformat:$2b$12$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy│││││││└──53chars:salt(22)+hash(31)││└──12:workfactor(2^12=4096iterations)│└──2b:algorithmversion└──$:separator

Characteristics:

  • Based on the Blowfish cipher, with an adjustable work factor (4-31, default 10-12)
  • The salt is generated automatically and embedded in the output → no need to store it separately
  • Input is limited to 72 bytes (pre-hash with SHA-256 if the password is longer)
  • Has held up for 25+ years: battle-tested

argon2id (2015, winner of the Password Hashing Competition)

argon2idhashformat:$argon2id$v=19$m=65536,t=3,p=4$randomsalt$hashresult│││││││└──p:parallelism(threads)││└──t:timecost(iterations)│└──m:memorycost(KB)└──v:version

Characteristics:

  • Memory-hard: needs lots of RAM → GPU/ASIC attacks are expensive
  • 3 variants: argon2d (GPU-resistant), argon2i (side-channel resistant), argon2id (hybrid, RECOMMENDED)
  • OWASP recommended for new applications (2024)
  • Tunable parameters: m (memory), t (iterations), p (parallelism)

scrypt (2009)

scryptparameters:N=2^15,r=8,p=1│││││└──parallelism│└──blocksize└──CPU/memorycost(mustbepowerof2)

Characteristics:

  • Memory-hard like argon2, but older
  • Used in Litecoin and some Linux systems
  • Still secure, but argon2id is preferred for new projects

Comparison

AlgorithmYearMemory-hardWork factorWhen to use
argon2id2015Yesm, t, pNew projects (OWASP top pick)
bcrypt1999Nocost (4-31)Well-supported legacy, default in many frameworks
scrypt2009YesN, r, pAlready in use, no need to replace
PBKDF22000NoiterationsWhen you need FIPS-140 compliance (gov/finance)
SHA-256/MD5———NEVER for passwords
bcrypt:    cost = 12 (or 13 on a powerful server)
argon2id:  m=19456 (19 MiB), t=2, p=1   ← minimum
           m=65536 (64 MiB), t=3, p=4   ← stronger
scrypt:    N=2^17, r=8, p=1
PBKDF2-SHA256: iterations = 600,000

Rule of thumb: choose parameters so that hashing takes ~250-500ms on the production server.

3. Salt and Pepper

Salt: random per-user

Without salt:
  alice: password="123456" → hash = abc123...
  bob:   password="123456" → hash = abc123...  ← same hash!

With salt:
  alice: salt="a1b2c3d4", password="123456" → hash(salt+pw) = xyz789...
  bob:   salt="z9y8x7w6", password="123456" → hash(salt+pw) = qwe456...

Salt requirements:

  • Random (use a CSPRNG: crypto.randomBytes / os.urandom)
  • Unique per user (DO NOT use the username/email)
  • Long enough: at least 16 bytes (128 bits)
  • Stored with the hash (it doesn't need to be secret); bcrypt/argon2 embed it automatically

The salt is not secret: even if the attacker reads it, they still have to brute force each user individually → rainbow tables are dead.

Pepper: a server-side secret

hash=bcrypt(password+pepper,salt)│└──storedseparately(envvar,KMS,HSM)NOTindatabase

A pepper adds an extra layer of protection: if the DB leaks but the secret store does not, the attacker cannot brute force.

SaltPepper
Unique per userYesNo (server-wide)
Where it is storedWith the hash in the DBEnv var / KMS / HSM
Secret?NoYes
RequiredYesOptional (defense in depth)

Note: peppers are controversial. Many experts (Thomas Ptacek) argue that if the DB is compromised, the server usually is too → the pepper adds little value. But for high-value targets (banking) you should still have one.

4. Code Examples

Node.js with bcrypt

// npm install bcrypt
import bcrypt from "bcrypt";

const SALT_ROUNDS = 12;   // 2^12 = 4096 iterations

// User sign-up
async function hashPassword(plaintext) {
  // bcrypt generates the salt itself and embeds it in the output
  const hash = await bcrypt.hash(plaintext, SALT_ROUNDS);
  // Store the hash in the DB (NEVER the plaintext)
  return hash;
}

// Login
async function verifyPassword(plaintext, storedHash) {
  // bcrypt.compare is constant-time → safe against timing attacks
  return await bcrypt.compare(plaintext, storedHash);
}

// Usage
const hash = await hashPassword("MySecret123!");
// → "$2b$12$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy"

const ok = await verifyPassword("MySecret123!", hash);  // true

Node.js with argon2

// npm install argon2
import argon2 from "argon2";

async function hashPassword(plaintext) {
  return await argon2.hash(plaintext, {
    type: argon2.argon2id,
    memoryCost: 65536,   // 64 MiB
    timeCost: 3,
    parallelism: 4,
  });
}

async function verifyPassword(plaintext, storedHash) {
  try {
    return await argon2.verify(storedHash, plaintext);
  } catch {
    return false;   // invalid hash format
  }
}

Python with argon2-cffi

# pip install argon2-cffi
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher(
    memory_cost=65536,   # 64 MiB
    time_cost=3,
    parallelism=4,
)

# Sign-up
hash = ph.hash("MySecret123!")
# → "$argon2id$v=19$m=65536,t=3,p=4$..."

# Login
def verify(plaintext, stored_hash):
    try:
        ph.verify(stored_hash, plaintext)
        # If the params are older than the current ones, rehash with the new params
        if ph.check_needs_rehash(stored_hash):
            new_hash = ph.hash(plaintext)
            # → update the DB with new_hash
        return True
    except VerifyMismatchError:
        return False

Pepper with Node.js

import bcrypt from "bcrypt";
import crypto from "crypto";

const PEPPER = process.env.PASSWORD_PEPPER;   // 32-byte random value from KMS

function applyPepper(password) {
  // HMAC-SHA256 instead of simple concatenation → safer
  return crypto.createHmac("sha256", PEPPER).update(password).digest("hex");
}

async function hashPassword(plaintext) {
  const peppered = applyPepper(plaintext);
  return await bcrypt.hash(peppered, 12);
}

async function verifyPassword(plaintext, hash) {
  const peppered = applyPepper(plaintext);
  return await bcrypt.compare(peppered, hash);
}

5. Common Mistakes

Mistake 1: Salt too short or not random

// ❌ WRONG
const salt = user.id.toString();   // not random
const salt = "myapp_salt";          // hardcoded
const salt = Date.now().toString(); // predictable

// ✅ RIGHT
import crypto from "crypto";
const salt = crypto.randomBytes(16);   // 128-bit CSPRNG
// Or use bcrypt/argon2 — they handle it for you

Mistake 2: Low work factor / not raised over time

// ❌ WRONG: cost = 4 (only 16 iterations, a few ms → brute forced in no time)
bcrypt.hash(pw, 4);

// ✅ RIGHT: cost = 12 (~250ms), raise it gradually as hardware improves
bcrypt.hash(pw, 12);

Periodically (every 1-2 years) raise the work factor. When a user logs in with an old hash, rehash with the new cost.

Mistake 3: Custom crypto

// ❌ WRONG: designing your own hashing
function myHash(pw) {
  return crypto.createHash("sha256")
    .update(pw + "secret" + pw.length)
    .digest("hex");
}

// ✅ RIGHT: use an audited library
import bcrypt from "bcrypt";

Golden rule: Don't roll your own crypto. Even experts use standard libraries.

Mistake 4: Timing attack in comparison

// ❌ WRONG: == exits early when bytes differ → leaks length info
if (hash === storedHash) { ... }

// ✅ RIGHT: constant-time compare
// bcrypt.compare, argon2.verify are constant-time built-in
// If you compare yourself: use crypto.timingSafeEqual
crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));

Mistake 5: Logging passwords

// ❌ WRONG
logger.info(`Login attempt: ${email} / ${password}`);
logger.error({ user, requestBody });   // the body contains the password!

// ✅ RIGHT
logger.info(`Login attempt: ${email}`);
// Redact the password in the logger middleware

Mistake 6: Returning different error messages

// ❌ WRONG: leaks whether the user exists
if (!user) return "User not found";
if (!valid) return "Wrong password";

// ✅ RIGHT: the same error
return "Invalid email or password";

6. Migration: From Legacy MD5/SHA to bcrypt/argon2

When you inherit an old system with MD5 passwords, the safe approach:

// Step 1: Wrap the legacy hash in bcrypt
// migration_hash = bcrypt(md5(plaintext))
const legacyMD5 = user.password_md5;
const newHash = await bcrypt.hash(legacyMD5, 12);

// Step 2: Store the flag "is_legacy_wrapped = true"
// Step 3: On the user's next login:
//   - verify: bcrypt.compare(md5(input), stored)
//   - If correct → rehash with plain bcrypt(input), set is_legacy_wrapped = false

Don't force users to reset their passwords (poor UX). Migrate silently when they log in.


Review Questions

  1. Why is a prepared statement safer than string concatenation, even if you escape input carefully?

    Show answer

    A prepared statement sends the SQL statement and the parameters to the DB engine over two separate channels. The DB compiles the SQL first, then binds the parameters; parameters are never parsed as SQL syntax. Manual escaping always carries risk: miss one edge case (Unicode normalization, charset encoding, engine-specific special syntax) and a single small bypass is enough. Prepared statements turn the problem into a structural one instead of a textual one: there is no way for input to escape the literal context.

  2. How does an SSRF exploit against IMDSv1 work? Why does IMDSv2 stop it?

    Show answer

    IMDSv1: any HTTP GET to 169.254.169.254 returns IAM credentials. SSRF only needs to force the server to send 1 GET request → read the response → exfiltrate the credentials.

    IMDSv2 requires 2 steps: (1) a PUT request to get a session token, (2) a GET with the X-aws-ec2-metadata-token header. SSRF usually only allows a simple GET: it cannot send a PUT or set a custom header (because the attacker only controls the URL). In addition, IMDSv2 has a hop limit (default 1) that blocks container/proxy access.

    The Capital One breach in 2019 = SSRF + IMDSv1 + overly broad role permissions. AWS now offers ways to enforce IMDSv2 at the organization level.

  3. Your app lets users download invoices via /api/invoices/:id/pdf. You already have middleware that verifies the JWT. Is that enough?

    Show answer

    Not enough: that is only authentication (knowing who the user is), not authorization (whether the user may access this invoice). This is textbook IDOR: User A logs in and changes :id to User B's invoice ID → downloads it.

    Fix: a scoped query Invoice.findOne({ id, userId: req.user.id }). If nothing is found → 404. Or check ownership explicitly before serving the file.

    This is OWASP A01, #1 in the Top 10 2021.

  4. Is a URL whitelist 100% safe against SSRF?

    Show answer

    Not 100%, but it is the best measure. Some bypasses:

    • DNS rebinding: the attacker controls the domain evil.com; DNS returns 1.2.3.4 at check time, then 169.254.169.254 at connect time.
    • Open redirect chain: allowed.com/redirect?to=evil.com → the server fetches allowed.com → gets redirected → fetches evil.com.
    • Subdomain takeover within a whitelisted domain.

    Additional mitigation: resolve DNS once, connect using the verified IP, don't follow redirects (or verify every hop), hard-block private IP ranges after resolution. Defense in depth: combine the whitelist + IP blocking + IMDSv2 + network egress control.

  5. You build an admin endpoint /admin/users that only admins can access. The frontend already hides this link from regular users. Is that enough?

    Show answer

    Not enough: the frontend is just UI; a regular user can still send HTTP requests directly (Postman, curl, DevTools). This is OWASP A01, "missing function level access control".

    Fix: the server must check the role. Every admin route needs middleware:

    function requireAdmin(req, res, next) {
      if (req.user.role !== 'admin') return res.status(403).end();
      next();
    }
    app.use('/admin', authMiddleware, requireAdmin);
    

    Rule: the client is untrusted. Every authorization decision must be made on the server. Hiding UI is just UX, not security.

  6. Why is SHA-256 unsuitable for storing passwords, even with a salt?

    Show answer

    SHA-256 is designed for speed (hashing files, blockchain). A modern GPU does ~10 billion hashes/second → an 8-character password is brute forced in a few hours. Password hashing needs an intentionally slow algorithm (work factor) and ideally a memory-hard one (argon2id, scrypt) to resist GPUs/ASICs. A salt helps against rainbow tables but does not slow down per-user brute force.

  7. How do salt and pepper differ, and where should the pepper be stored?

    Show answer

    A salt is random per-user, stored with the hash in the DB, and does not need to be secret; it defeats rainbow tables and same-password-same-hash. A pepper is a server-wide secret, NOT stored in the DB but in an env var / AWS KMS / HSM. If the DB leaks but the secret store stays safe, the pepper prevents the attacker from brute forcing. A pepper is defense in depth: optional, but recommended for high-value apps.

  8. Which algorithm does OWASP 2024 recommend for new projects, and why?

    Show answer

    argon2id: winner of the 2015 Password Hashing Competition, a hybrid of argon2d (GPU-resistant) and argon2i (side-channel resistant). It is memory-hard, so ASIC/GPU attacks are expensive. Recommended parameters: m=19456 KiB, t=2, p=1 (minimum) or m=65536, t=3, p=4 (stronger). If the environment doesn't support argon2 (old Node.js, restricted hosting), bcrypt cost=12 is a good fallback.

  9. Why is bcrypt.compare() safer than hash1 === hash2?

    Show answer

    === compares byte-by-byte and exits early at the first differing byte → the comparison time depends on the position of the wrong byte. An attacker measuring timing many times can guess character by character (timing attack). bcrypt.compare() (and crypto.timingSafeEqual) always compares the full length → constant time → no information leaks through timing.

  10. When you want to raise the work factor (e.g. bcrypt cost from 10 to 12), how do you migrate without forcing users to reset their passwords?

Show answer

When a user logs in successfully with the old hash, right after verification succeeds, call bcrypt.hash(plaintext, 12) (the new cost) and update the DB. The user notices nothing different. After a few months, most active users have the new hash. Inactive users keep the old hash (still safer than no hash), or you force a reset if they have been inactive too long. Argon2 has check_needs_rehash() built in for this pattern.

Hands-on Exercises

Part 1: SQL Injection, SSRF, IDOR

# 1. SQLi with DVWA or Juice Shop
docker run --rm -p 3000:3000 bkimminich/juice-shop
# Go to "Score Board" and find the "Login Admin" challenge
# Try ' OR 1=1-- in the email field

# 2. Try sqlmap
docker run --rm -it parrotsec/sqlmap \
  -u "http://target.com/products?id=1" --batch --dbs

# 3. Check the IMDS version on EC2
# IMDSv1 (only works if the instance still allows v1):
curl http://169.254.169.254/latest/meta-data/

# IMDSv2 (recommended):
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/

# Disable IMDSv1 on the instance:
aws ec2 modify-instance-metadata-options \
  --instance-id i-xxx \
  --http-tokens required

# 4. Audit IDOR in your app
# - List every route with :id, :uuid in the URL
# - For each route, read the handler: does it check ownership?
# - Write a test: user A logs in, calls user B's resource → expect 403/404

# 5. SSRF defense — write an is_safe_url function for Python/Node
# (see the example code in section 5)
# Test with input:
#   http://169.254.169.254/   → reject
#   http://10.0.0.5/          → reject
#   http://example.com/       → allow
#   file:///etc/passwd        → reject

Part 2: Password Hashing & Storage

# 1. Set up a Node.js project
mkdir password-lab && cd password-lab
npm init -y
npm install bcrypt argon2

# 2. Create the file hash-demo.js
cat > hash-demo.js << 'EOF'
import bcrypt from "bcrypt";
import argon2 from "argon2";

const password = "MySecret123!";

console.time("bcrypt cost=12");
const bcryptHash = await bcrypt.hash(password, 12);
console.timeEnd("bcrypt cost=12");
console.log(bcryptHash);

console.time("argon2id");
const argonHash = await argon2.hash(password, { type: argon2.argon2id });
console.timeEnd("argon2id");
console.log(argonHash);

// Verify
console.log("bcrypt verify:", await bcrypt.compare(password, bcryptHash));
console.log("argon2 verify:", await argon2.verify(argonHash, password));

// Verify with a wrong password
console.log("wrong:", await bcrypt.compare("wrong", bcryptHash));
EOF

# package.json needs "type": "module"
node hash-demo.js

# 3. Measure the time with different costs
# Try cost = 4, 8, 10, 12, 14 — observe the time grow exponentially

# 4. Inspect the hash format:
# - Which characters are the algorithm version?
# - Which characters are the cost?
# - How many characters are the salt? the hash?

# 5. Try a legacy MD5 → bcrypt migration
# Create an MD5 hash of a password, wrap it in bcrypt, verify

References


Next lesson →