Security Hardening for LAMP
By the end of this lesson ShikshaPortal will slow down password guessing, hide its software versions, send security headers from Apache, block injected scripts with a Content Security Policy, and run with the smallest rights it needs in MySQL and on disk. You will also review the session settings from earlier lessons and map every defence to the OWASP Top 10.
What you should know first: PHP Security Essentials and the OWASP Top 10 give the background. This lesson builds on the session code from Sessions, Login & Password Hashing, the CSRF check from Forms, Validation & CSRF and the Apache virtual host from Apache: Virtual Hosts & .htaccess.
Layers, not one wall
A school in Lucknow does not rely on one lock. There is a guard at the gate, a visitors' register, and locked almirahs in the record room. If the guard is fooled, the almirah is still locked. Hardening means adding such layers, so one mistake does not become a disaster. ShikshaPortal already has prepared statements, e(), CSRF tokens, bcrypt and safe session cookies; this lesson adds the rest.
Step 1: limit login attempts
A login form with no limit lets a program try thousands of passwords. Storing the count in the session does not help, because an attacker simply drops the cookie. The count must live on the server, keyed by things the attacker cannot change freely. Add a table (run by the database administrator):
CREATE TABLE login_failures (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
email VARCHAR(255) NOT NULL,
ip VARCHAR(45) NOT NULL,
failed_at DATETIME NOT NULL,
PRIMARY KEY (id),
KEY idx_login_failures_ip_time (ip, failed_at)
) ENGINE=InnoDB;The new model, src/Models/LoginThrottle.php, uses two limits in a 15-minute window: 5 failures for one email from one IP address, and 20 failures from one IP address for any email.
public function retryAfter(string $email, string $ip): int
{
$since = date('Y-m-d H:i:s', time() - self::WINDOW);
$wait = 0;
foreach ([
['WHERE ip = :ip AND email = :email AND failed_at > :since', ['ip' => $ip, 'email' => $email], self::MAX_PER_ACCOUNT],
['WHERE ip = :ip AND failed_at > :since', ['ip' => $ip], self::MAX_PER_IP],
] as [$where, $params, $max]) {
$stmt = $this->pdo->prepare("SELECT COUNT(*) AS n, MIN(failed_at) AS oldest FROM login_failures {$where}");
$stmt->execute($params + ['since' => $since]);
$row = $stmt->fetch();
if ((int) $row['n'] >= $max) {
$wait = max($wait, strtotime($row['oldest']) + self::WINDOW - time());
}
}
return max(0, $wait);
}recordFailure() inserts one row, and clear() deletes that email and address's rows after a successful login. PHP computes the times, so the SQL works on MySQL, MariaDB and SQLite, and the {$where} pieces are fixed text; values still travel as parameters. In AuthController::login(), the check comes before the password check:
$wait = $this->throttle->retryAfter($email, $ip);
if ($wait > 0) {
header('Retry-After: ' . $wait);
$this->showError(429, $email, $next,
'Too many attempts. Please wait ' . (int) ceil($wait / 60) . ' minute(s) and try again.');
return;
}
$user = attempt_login($email, $password);
if ($user === null) {
$this->throttle->recordFailure($email, $ip);
error_log("ShikshaPortal failed login for {$email} from {$ip}");
$this->showError(422, $email, $next, 'Email or password is wrong.');
return;
}
$this->throttle->clear($email, $ip);We tried six wrong passwords for Vikram, then his correct one:
try 1 (wrong1): 422 in 1.600444s Email or password is wrong. try 2 (wrong2): 422 in 2.011171s Email or password is wrong. try 3 (wrong3): 422 in 1.695307s Email or password is wrong. try 4 (wrong4): 422 in 1.579934s Email or password is wrong. try 5 (wrong5): 422 in 1.078922s Email or password is wrong. try 6 (wrong6): 429 in 0.232861s Retry-After: 884 Too many attempts. Please wait 15 minute(s) and try again. try 7 (Shiksha@Dev2026): 429 in 0.143553s Retry-After: 883 Too many attempts. Please wait 15 minute(s) and try again.
Even the right password waits, or the limit would tell a guesser when they succeeded. The 429 answers are fast because they skip bcrypt, so a flood of guesses cannot burn CPU. Each failure also wrote a line such as ShikshaPortal failed login for vikram@shiksha.test from 127.0.0.1 to the error log, which the backups and logs lesson watches.
Two cautions. A limit per email alone would let anyone lock a teacher out on purpose, so the account limit also uses the IP address. And behind a load balancer or CDN, REMOTE_ADDR is the proxy's address: use Apache's mod_remoteip with RemoteIPTrustedProxy, and never trust an X-Forwarded-For header from just anyone.
Step 2: say less about the server
The first lesson showed Server: Apache/2.4.58 (Win64) PHP/8.4.27 and X-Powered-By: PHP/8.4.27 in every response. Exact versions help attackers pick old bugs to try. In the main Apache config (on Ubuntu, /etc/apache2/conf-available/security.conf, which ships with ServerTokens OS and ServerSignature On):
ServerTokens Prod
ServerSignature Off
TraceEnable OffServerTokens Prod shortens the header to Server: Apache, ServerSignature Off removes the version line from Apache's own error pages, and TraceEnable Off refuses the old TRACE method (our test copy then answered TRACE / with 405). In php.ini, set expose_php = Off to remove X-Powered-By. Hiding versions is no substitute for updates; it just stops advertising.
Step 3: security headers from Apache
Browsers have safety features that a site must switch on with response headers. Put them in the virtual host, so every response gets them, including static files and Apache's own error pages. mod_headers must be enabled (sudo a2enmod headers):
<VirtualHost *:80>
ServerName shiksha.test
...
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "DENY"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "camera=(), microphone=(), geolocation=()"
Header always set Content-Security-Policy "default-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"
</VirtualHost>| Header | What it tells the browser |
|---|---|
X-Content-Type-Options: nosniff | Trust our Content-Type; never guess that an upload is a script |
X-Frame-Options: DENY | Never show this site inside another site's frame (stops clickjacking, where a hidden frame tricks clicks) |
Referrer-Policy | Send only our domain, not full URLs with ids, when following links to other sites |
Permissions-Policy | This site never uses the camera, microphone or location |
Content-Security-Policy | Which sources of scripts, images and forms are allowed (Step 4) |
always covers error responses too. After the change and a restart, curl -D - -o /dev/null http://shiksha.test/classes showed (the Date and Content-Length lines are left out):
HTTP/1.1 200 OK Server: Apache X-Content-Type-Options: nosniff X-Frame-Options: DENY Referrer-Policy: strict-origin-when-cross-origin Permissions-Policy: camera=(), microphone=(), geolocation=() Content-Security-Policy: default-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none' Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate Pragma: no-cache Content-Type: text/html; charset=UTF-8
X-Powered-By is gone. HSTS (Strict-Transport-Security), which tells browsers to use only HTTPS, must wait until HTTPS works, in Deploying to a Linux Server.
Step 4: Content Security Policy
A Content Security Policy (CSP) is a list of places the page may load code from. Even if an attacker slips <script> into a page through a bug we missed, the browser refuses to run it. It is the second lock on the almirah after e().
Read our policy one part at a time. default-src 'self' allows scripts, styles, fonts and requests only from our own origin, and no inline code. img-src 'self' data: adds small data: images. object-src 'none' blocks plugins, base-uri 'self' stops an injected <base> tag from redirecting relative links, form-action 'self' stops forms posting elsewhere, and frame-ancestors 'none' is the modern form of X-Frame-Options.
ShikshaPortal passes this strict policy because of choices made earlier: every script is an external file in public/assets/js/, page data travels in <script type="application/json"> blocks (data, not code), and templates use no style="..." attributes or onclick handlers. We loaded the student page in headless Chrome with the policy on, then injected an inline script from the console. The photo loaded, and Chrome reported:
Executing inline script violates the following Content Security Policy directive 'default-src 'self''. Either the 'unsafe-inline' keyword, a hash ('sha256-RChmYE/r1/njzlEvN+audvByiKwEQnLXe/BGNlJEkNM='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback. The action has been blocked.On an older app full of inline scripts, start with Content-Security-Policy-Report-Only, which reports problems but blocks nothing. When inline code cannot be avoided, a nonce (a random value, new on every response) marks the scripts you trust. This page uses a nonce in a <meta> tag, so you can see the browser block two "injected" scripts:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="script-src 'nonce-lucknow2026'; object-src 'none'; base-uri 'self'">
<title>CSP blocks injected script</title>
<style>body { font-family: system-ui, sans-serif; margin: 16px; } pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }</style>
<script nonce="lucknow2026">
const blocked = [];
document.addEventListener("securitypolicyviolation", (event) => {
blocked.push(event.violatedDirective + " blocked: " + event.blockedURI);
});
</script>
</head>
<body>
<h1>Guardian: Rakesh Mishra</h1>
<p>Below are two "injected" scripts, as if a name had been printed without e().</p>
<img src="no-such-photo.jpg" alt="" onerror="document.title = 'hacked by onerror'">
<script>document.body.dataset.hacked = "inline script ran";</script>
<pre id="out"></pre>
<script nonce="lucknow2026">
setTimeout(() => {
document.querySelector("#out").textContent = [
"Page title: " + document.title,
"Injected inline script: " + (document.body.dataset.hacked || "did not run"),
"",
"Violations reported:",
...blocked
].join("\n");
}, 500);
</script>
</body>
</html>Only the two scripts carrying the nonce ran. A real server must create a fresh nonce for every response; a fixed one, as in this demo, protects nothing.
Step 5: review the session settings
Here are PHP's built-in session defaults, printed with php -n -i (no php.ini loaded) on PHP 8.4.27:
session.cookie_httponly => Off => Off session.cookie_samesite => no value => no value session.cookie_secure => Off => Off session.gc_maxlifetime => 1440 => 1440 session.name => PHPSESSID => PHPSESSID session.sid_length => 32 => 32 session.use_only_cookies => On => On session.use_strict_mode => Off => Off session.use_trans_sid => Off => Off
| Setting | PHP default | ShikshaPortal |
|---|---|---|
| Cookie name | PHPSESSID | shiksha_sid |
| HttpOnly, SameSite | off, none | on, Lax |
| Secure | off | on when APP_URL is https |
| Strict mode | off | on |
| Only cookies, no ids in URLs | on | kept on |
| New id at login | not automatic | session_regenerate_id(true) |
| Idle limit | none | 30 minutes |
| Absolute limit | none | 8 hours, added now |
gc_maxlifetime | 1440 s (24 minutes) | set to 3600 in php.ini |
The review found two gaps. First, nothing ended a session that stayed busy all day, so start_session() now also stores started_at and clears any session older than 8 hours, one school day; login_user() resets it. Second, gc_maxlifetime was shorter than our 30-minute idle limit, so PHP's clean-up could delete a session after 24 minutes. Set session.gc_maxlifetime = 3600 in php.ini. Ubuntu cleans session files with a scheduled job that reads this value. Do not change the id length: PHP 8.4 deprecated session.sid_length, and our test printed "Deprecated: PHP Startup: session.sid_length INI setting is deprecated".
Step 6: least privilege everywhere
Least privilege means each account can do only its own job. In MySQL, shiksha_app already has only SELECT, INSERT, UPDATE and DELETE on shiksha_portal.* (PHP & MySQL with PDO). If someone ever runs SQL through the app, MySQL refuses DROP TABLE with a "command denied" error. Table changes, like this lesson's login_failures, are made by a separate administrator account that the web app never uses. Check the grants with SHOW GRANTS FOR 'shiksha_app'@'127.0.0.1';. MySQL Setup, Users & Security covers more.
On disk, Apache runs as www-data. It must read the code but write only where uploads go:
sudo chown -R deploy:www-data /var/www/shiksha-portal
sudo find /var/www/shiksha-portal -type d -exec chmod 750 {} +
sudo find /var/www/shiksha-portal -type f -exec chmod 640 {} +
sudo chown -R www-data:www-data /var/www/shiksha-portal/storageHere deploy is the Linux user who uploads new versions. An attacker who took over PHP could not change index.php or plant code. Permissions & Ownership explains the numbers.
ShikshaPortal against the OWASP Top 10:2025
| Risk | What ShikshaPortal does | Lesson |
|---|---|---|
| A01 Broken Access Control | require_login() roles on every route; photos through a controller | Sessions, Uploads |
| A02 Security Misconfiguration | Only public/ served, no folder listing, headers, display_errors off | Apache, this lesson |
| A03 Software Supply Chain Failures | composer.lock committed, composer audit before release | Composer |
| A04 Cryptographic Failures | bcrypt hashes; HTTPS and Secure cookies | Sessions, Deployment |
| A05 Injection | Prepared statements, e(), json_for_html(), CSP | CRUD, Templates |
| A06 Insecure Design | Students marked as left, never deleted; login limits | Database design |
| A07 Authentication Failures | Rate limits, strict sessions, fresh ids, one error message | this lesson |
| A08 Software or Data Integrity Failures | CSRF tokens; uploads re-encoded, never trusted | Forms |
| A09 Security Logging and Alerting Failures | Failed logins and database errors logged | Backups & logs |
| A10 Mishandling of Exceptional Conditions | Clean 500 pages; oversize uploads give 413, not a false "expired" | Uploads |
Common mistakes
- Counting failed logins in the session. The attacker drops the cookie. Count on the server.
- Letting the correct password through during a lockout. That tells the guesser they won.
- Adding
'unsafe-inline'to make CSP errors go away. It switches off most of the protection. Move code into files. - Making the whole project writable by
www-data. Onlystorage/needs it.
Interview questions
1. How would you rate-limit a PHP login form?
Store failed attempts on the server, for example in a table keyed by account and IP address, and check the count in a time window before verifying the password. Return 429 with Retry-After when over the limit, refuse even correct passwords during that time, and clear the counter after success. Combine per-account and per-IP limits so attackers cannot lock users out easily.
2. What does a Content Security Policy protect against?
It limits where the browser may load scripts and other resources from, so injected inline scripts and scripts from unknown hosts are blocked even if an XSS bug exists. It is a second layer after output escaping, not a replacement for it.
3. Why send security headers from Apache rather than from PHP?
Apache adds them to every response, including static files, PHP pages and Apache's own error pages, and a new PHP route cannot forget them. PHP can still set page-specific headers, such as a per-response nonce.
Key points
- Count failed logins in a table; answer 429 with
Retry-Afterbefore running bcrypt. ServerTokens Prod,ServerSignature Off,TraceEnable Offandexpose_php = Offstop version leaks.- Send
nosniff,X-Frame-Options,Referrer-Policy,Permissions-Policyand a CSP from the virtual host withHeader always set. - External scripts and JSON data blocks let ShikshaPortal use a strict CSP with no
'unsafe-inline'. - Sessions now have an 8-hour absolute limit, and
gc_maxlifetimeis longer than the idle limit. - The app's MySQL user and Linux user can do only their own jobs.
Exercise
The live search API could be used to copy the whole student list quickly. Add a limit of 60 requests per minute per logged-in user to GET /api/students. Over the limit, answer 429 in JSON with a Retry-After header. Store the counts on the server, and explain why the user id is a better key here than the IP address.
Show solution
// src/Models/ApiLimiter.php
final class ApiLimiter
{
public function __construct(private readonly PDO $pdo)
{
}
/** Count this call; return seconds to wait, or 0 if allowed. */
public function hit(int $userId, int $max = 60): int
{
$minute = date('Y-m-d H:i');
$stmt = $this->pdo->prepare('SELECT hits FROM api_hits WHERE user_id = :u AND minute = :m');
$stmt->execute(['u' => $userId, 'm' => $minute]);
$hits = (int) $stmt->fetchColumn();
if ($hits >= $max) {
return 60 - (int) date('s');
}
$sql = $hits === 0
? 'INSERT INTO api_hits (user_id, minute, hits) VALUES (:u, :m, 1)'
: 'UPDATE api_hits SET hits = hits + 1 WHERE user_id = :u AND minute = :m';
$this->pdo->prepare($sql)->execute(['u' => $userId, 'm' => $minute]);
return 0;
}
}
// in StudentController::search(), after require_api_login()
$wait = $this->limiter->hit($user['id']);
if ($wait > 0) {
header('Retry-After: ' . $wait);
json_response(['error' => 'Too many searches. Please wait a moment.'], 429);
}The table api_hits has a primary key on (user_id, minute). The route already requires a login, so the user id names the person exactly; many teachers in one school share a single public IP address, and an IP limit would block them all together. Old rows can be deleted by a nightly job.
Quick Quiz
1. Why does ShikshaPortal check the login limit before calling password_verify()?
Skipping bcrypt saves CPU, and refusing every attempt hides whether a guess was right.
2. Which directive turns Server: Apache/2.4.58 (Win64) into Server: Apache?
ServerTokens controls the Server header; expose_php controls X-Powered-By.
3. With default-src 'self' and no script-src, what happens to an injected inline <script>?
script-src falls back to default-src, which allows no inline code.
4. PHP's default session.gc_maxlifetime is 1440 seconds. Why is that a problem for ShikshaPortal?
Set gc_maxlifetime longer than the idle timeout, for example 3600.
Learn LAMP Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
