Summary - Advanced security
Build a hardened app skeleton with rate limiting, CSP and secure upload.
Summary - Advanced security tools
In this group you learned six advanced security tools. With password_needs_rehash you silently upgrade old hashes. With rate limiting you slow brute force. With CSP, HSTS and X-Content-Type-Options you harden the browser side.
With session_regenerate_id you close fixation. With filter_var you validate input, with hash_hmac you sign it. With random_bytes you produce random filenames. Now let us combine these tools into a hardened app skeleton.
Exercise Write a hardened app skeleton
Define sendHeaders(): it calls header("Content-Security-Policy: default-src 'self'") and header("X-Content-Type-Options: nosniff"). Define isRateLimited(int $attempts, int $limit = 3): bool: it returns true when $attempts > $limit. Define needsRehash(string $hash): bool: it returns password_needs_rehash($hash, PASSWORD_DEFAULT). Define $hash = password_hash("test", PASSWORD_BCRYPT, ["cost" => 4]). Call sendHeaders(). Print the results of isRateLimited(5) and needsRehash($hash) as 1/0.
Show example solution
sendHeaders sends CSP and nosniff; isRateLimited compares the attempt count against the limit; needsRehash returns password_needs_rehash($hash, PASSWORD_DEFAULT). Define $hash = password_hash("test", PASSWORD_BCRYPT, ["cost" => 4]);. Call sendHeaders(). isRateLimited(5) → 5 > 3 → true → 1. needsRehash($hash) → cost 4 < 10 → true → 1.
Example solution:
<?php
function sendHeaders(): void {
header("Content-Security-Policy: default-src 'self'");
header("X-Content-Type-Options: nosniff");
}
function isRateLimited(int $attempts, int $limit = 3): bool {
return $attempts > $limit;
}
function needsRehash(string $hash): bool {
return password_needs_rehash($hash, PASSWORD_DEFAULT);
}
$hash = password_hash("test", PASSWORD_BCRYPT, ["cost" => 4]);
sendHeaders();
echo (isRateLimited(5) ? "1" : "0") . "\n";
echo (needsRehash($hash) ? "1" : "0") . "\n";
Test yourself
-
Which function upgrades old password hashes?
- password_needs_rehash
- password_verify
- hash_equals
- filter_var
Show answer
password_needs_rehash — Correct. password_needs_rehash returns whether an upgrade is needed.
-
Complete the hash_hmac call
$mac = ____("sha256", $data, $key);Show answer
$mac = hash_hmac("sha256", $data, $key); -
Match each defense to its attack
- password_needs_rehash
- Old hash upgrade
- rate_limiting
- Brute force
- CSP
- XSS
- session_regenerate_id
- Fixation