Back to the catalogue Courses

Application security: analysing and protecting a web portal

Analyse risks and secure a web portal: authentication, authorisations, injections, browser protections, secrets, backups and incident response.

MDJAD Intermediate 35 min read

Objectives and prerequisites

By the end of this course, you will be able to analyse the risks of a small web portal, choose complementary protections, verify their effectiveness and explain their limits. The common thread is a fictional association portal running in a local lab: member accounts, an authenticated area, documents, a search and an administration area. We will observe it, reproduce a few weaknesses in a controlled environment, then fix them. Never perform these manipulations on a system you do not own or for which you do not have written authorisation.

Prerequisites: you can read HTML, PHP and a simple SQL query; you can use a terminal; you understand what an HTTP request is. The examples assume a local lab, such as a virtual machine or a container, with a test database and no real data. Security is learned by doing, but always within an authorised, documented and reversible framework.

Path: chapters 1 and 2 establish vocabulary and the analysis method; chapters 3 to 5 cover transport, identity and authorisations; chapters 6 to 9 cover input, injection, the browser, secrets and dependencies; chapters 10 to 12 cover detection, response, verification and the improvement plan. Expect about thirty-five minutes of reading and three to five hours of practice.

Convention: commands run in the local lab. Addresses use localhost or a reserved test domain. The payloads shown are benign and only illustrate a mechanism. Never copy a demonstration configuration to production without adapting and testing it.

1. Scoping what must be protected

Security starts with a simple question: what are we trying to protect, from whom and from what? An asset is something of value: personal data, documents, accounts, reputation, service availability. An actor is a person or system interacting with the portal: member, administrator, visitor, provider, attacker. A trust boundary is a place where the level of trust changes: between the browser and the server, between the web server and the database, between the application and an external service.

For the association portal, the main assets are member accounts, internal documents, activity logs and the ability to serve members. Legitimate actors are members, administrators and maintainers. Malicious actors may be an anonymous visitor, a curious member trying to see another member's documents, a compromised account or an automated bot. Trust boundaries are the browser, the reverse proxy, the application, the database and file storage.

A useful inventory states, for each asset, who may read, modify and delete it, and for how long. It is not limited to database tables: a backup, a log, a CSV export or a copy on an administrator's laptop is also an asset. Data left in a temporary file or an error message can become the easiest leak to exploit. A system's security is often determined by its weakest link, not its most visible component.

Insiders deserve explicit attention. An employee, volunteer or provider with legitimate access can cause a leak through carelessness, a stolen laptop, a misdirected email or a temporary export. The response is not to distrust everyone, but to limit access to what is necessary, log sensitive actions, separate duties and make reporting a mistake easy. A culture where a lost USB key is reported within the hour is safer than a culture where it is hidden. Access reviews, at least annually and after every role change, keep the inventory aligned with reality.

Asset: member documents
Owner: association
Legitimate readers: the member concerned, administrator
Legitimate modifiers: the member concerned, administrator
Retention: 24 months after departure
Copies: database, encrypted backups, temporary exports
Boundaries: browser → proxy → application → database → storage

Classifying data helps choose protections. Public, internal, personal or sensitive data do not require the same controls. For each category, state the legal basis, retention period, authorised people and deletion obligations. Personal data copied to a test environment without anonymisation remains personal data. Exports, screenshots and attachments must be in the inventory, because they often travel outside protected databases.

Assumptions must be written down. "The server is up to date" is an assumption, not a guarantee. "The administrator is trusted" may be true for intent and false for the account if it is compromised. "The internal network is safe" is a dangerous assumption when a workstation may be infected. Writing assumptions lets you verify them and know what happens if they fail.

Finally, distinguish product security from operational security. The code may be correct and the server misconfigured; the server may be correct and backups untested; backups may be correct and logs missing. A serious analysis covers the lifecycle: design, development, deployment, operations, correction and retirement. We will return to this idea in every chapter.

2. Threats, vulnerabilities and risks

A threat is what can cause harm; a vulnerability is a weakness that lets the threat materialise; a risk combines likelihood and impact. A threat without a vulnerability does not produce an incident, and a vulnerability without an actor able to exploit it may remain theoretical. Risk therefore depends on context: the same flaw does not weigh the same on a public brochure site and on a portal holding health data.

The Confidentiality, Integrity and Availability model helps structure the analysis. Confidentiality limits access to authorised people. Integrity ensures data is not modified without authorisation. Availability ensures the service responds when needed. We often add traceability, which tells who did what, and non-repudiation, which prevents denying an action. These properties can conflict: a very detailed log improves traceability but may contain personal data.

A qualitative matrix crosses likelihood and impact. An easy-to-exploit flaw with strong impact is a priority; a hard-to-exploit flaw with low impact can wait. The matrix is not a mathematical truth: it supports discussion and prioritisation. Two people may classify the same risk differently; what matters is documenting the reasoning and reassessing after a change.

Likelihood: low / medium / high
Impact: low / medium / high
Risk = likelihood × impact, then adjusted for context
Example: SQL injection reachable without authentication, high impact → high priority
Example: overly detailed error message on an internal page, low impact → low priority

Residual risk is what remains after protections. It is never zero. A protection may reduce likelihood, impact or both; it may also move risk elsewhere. For example, a filter that blocks special characters may break legitimate names and push users to work around the system. A good security decision explains what it protects, what it does not protect and what it costs.

Risk treatment offers four options: avoid the activity, reduce the risk with a protection, transfer it through insurance or a contract, or accept it with a documented decision. These options are not equivalent. Reducing SQL injection with parameterised queries is generally preferable to accepting the risk; transferring availability risk through a contract does not remove the impact on users. Acceptance must have an owner, a review date and an understandable justification. An accepted risk without a record becomes an oversight that nobody can explain or reassess later.

A risk register makes the approach durable. For each risk, record an identifier, a description, the assets concerned, the likelihood, the impact, the chosen treatment, the owner, the target date and the residual risk. Review the register at each significant change: new feature, new provider, new regulation, incident. A register that is never reread becomes an administrative document disconnected from the system. Keep it short enough to be maintained and precise enough to be actionable.

Abuse cases make the analysis concrete. Instead of saying "protect documents", describe: "an authenticated member changes the identifier in the URL and downloads another member's document". This scenario can be tested, fixed and verified. Scenarios must cover legitimate actors misusing a function, compromised accounts, configuration errors and service failures. Security is not only defence against an outside attacker; it is also limiting the consequences of an internal error.

3. Network, HTTPS and certificates

HTTPS protects the confidentiality and integrity of data in transit between the browser and the server. It does not protect stored data, a compromised server or a user whose workstation is infected. It does not make an application secure: it prevents eavesdropping and tampering on the network. Understanding this limit prevents the belief that a padlock is enough to secure a portal.

TLS negotiates an encrypted session and verifies the server's identity through a certificate signed by a certificate authority. The browser checks that the certificate matches the domain name, is valid at the current date and is signed by a recognised authority. A self-signed certificate is suitable for a local lab but triggers a browser warning; it must not be used for a public service without an explicit decision and adapted configuration.

# Local lab: inspect the certificate presented by a test service
openssl s_client -connect localhost:8443 -servername localhost < /dev/null 2>/dev/null | openssl x509 -noout -subject -issuer -dates
# Check the security headers of a local response
curl -I http://localhost:8080/

HSTS tells the browser to always use HTTPS for that domain for a given period. Enable it only after verifying that HTTPS works on all relevant subdomains, otherwise you may make a service unreachable. Redirecting HTTP to HTTPS is useful, but it does not replace HSTS: the first request can still be intercepted. The certificate must be renewed before expiry and renewal must be monitored.

The certificate lifecycle includes request, validation, installation, renewal and revocation. An expired certificate causes downtime and pushes users to accept warnings, which weakens trust. Automate renewal and monitor the expiry date. Disable obsolete TLS versions and weak cipher suites according to current recommendations. Test the configuration after every server or proxy update, because a version change can alter accepted protocols.

The reverse proxy, web server and application form a chain. If the proxy terminates TLS and forwards the request over internal HTTP, the application must trust protocol and address headers in a controlled way, without accepting any value sent by a client. A configuration that trusts all proxies lets an attacker forge their address or protocol. The list of trusted proxies must be explicit and limited.

When TLS terminates at a proxy, the application often receives plain HTTP internally. Cookies marked Secure may then be dropped by the framework if it does not know the original request was secure. Configure the trusted proxy list and the forwarded headers carefully, and verify the resulting behaviour in a test environment. A misconfiguration can either break login or make the application believe an insecure request was secure. Both outcomes are security problems, and both are invisible in a simple functional test.

In the lab, test three things: the certificate presented, the HTTP-to-HTTPS redirect and the security headers. In production, add expiry monitoring, TLS error logging and a renewal test. Do not disable certificate verification in a client to "make an integration work": you remove precisely the protection against interception.

4. Identity, authentication and sessions

Authentication answers "who are you?". It relies on one or more factors: something you know, such as a password; something you have, such as a phone or a key; something you are, such as a fingerprint. A password alone is a weak factor, but it remains widespread. A second factor adds important protection against password theft without making the account invulnerable.

Passwords must be hashed with an algorithm designed for it, such as Argon2id or bcrypt, with a unique salt and an appropriate cost. A hash is irreversible; encryption is reversible and must not be used to store a password. Verification uses the environment's dedicated function, which compares the hash without revealing information through response time. Never store a plain-text password, in logs or in a debugging field.

// Local lab: create and verify a password
$hash = password_hash($password, PASSWORD_ARGON2ID);
$ok = password_verify($password, $hash);

if (!$ok) {
    // Generic message: do not reveal whether the account exists.
    throw new \RuntimeException('Invalid credentials');
}

A session is state kept across requests. The session identifier must be random and long enough, sent in an HttpOnly, Secure and, as needed, SameSite cookie. After a successful login, regenerate the identifier to prevent session fixation. Set an inactivity timeout and an absolute lifetime. On logout, invalidate the session on the server, not only the browser cookie.

The account lifecycle matters as much as the login form: creation, verification, password change, loss of access, suspension, deletion and purge. Plan revocation of active sessions after a password change or compromise. Inactive accounts must be disabled according to an explicit policy. Credential stuffing, which reuses pairs stolen from other sites, is countered by rate limiting, detection and a second factor. Do not store weak secret questions as the only recovery mechanism.

A second factor can be an authenticator application, a hardware key or a code sent through another channel. They do not all offer the same resistance: SMS codes are vulnerable to number hijacking, while a hardware key resists phishing better. Provide single-use recovery codes stored safely and a verified recovery procedure. Do not let the user disable the second factor without strong re-authentication. A second factor protects the account, but not an already stolen session: session management remains necessary.

Password reset is sensitive. The link must be random, single-use, time-limited and invalidated after use. Do not reveal whether an address exists: the response must remain generic. The link must not contain the password or a predictable identifier. If email delivery fails, the user must not receive a hint about the account's existence.

Second-factor fatigue is a real attack: the attacker repeatedly triggers a prompt until the user approves one by mistake. Counter it by showing the context of each request, limiting the number of prompts, alerting on repeated failures and allowing the user to report an unexpected prompt. A password manager also improves security, because it generates unique passwords and reduces reuse. Recommend it, but do not make it a condition of access. Password policies should favour length and check against known compromised passwords rather than impose complex composition rules that encourage predictable substitutions.

Also protect the login form against repeated attempts. Limiting by account and by address, with a progressive delay, reduces brute force without permanently blocking a legitimate user. Log failures and successes, but never the password. An administrator account must have a second factor and a stricter session policy than a member account.

Mental exercise: for each actor in the portal, list the authentication factor, session lifetime, reset conditions and logs produced. If an answer is "we will see later", it is a risk to document, not a protection.

5. Authorisation and least privilege

Authorisation answers "what may you do?". It must be checked on the server, for every action, on every resource. Hiding a button in the interface improves the experience but protects nothing: a user can send the request directly. The principle of least privilege gives each actor the minimum rights needed, for the minimum time.

An authorisation matrix clarifies decisions. Rows are actors, columns are actions, cells are rules. For the portal: a visitor may read the public page; a member may read and modify their own documents; an administrator may manage accounts and all members' documents. An empty cell means "denied by default". Deny by default prevents omissions: a new action without an explicit rule is not accessible.

Action                      | Visitor | Member | Administrator
Read public page            | yes     | yes    | yes
Read own documents          | no      | yes    | yes
Read other members' documents | no    | no     | yes
Create a document           | no      | yes    | yes
Delete a document           | no      | own documents | all
Manage accounts             | no      | no     | yes

Insecure direct object references, often called IDOR, are a common mistake: the application checks that the user is logged in, but not that they may access the requested object. If the URL contains /documents/42, a member can try /documents/43. The fix is to load the object and then check ownership or role before responding, returning 403 or 404 according to policy.

Roles should remain simple and stable. A role is a set of permissions; a permission is a precise action. Avoid scattered checks such as "if the role is admin or the identifier is the same or the date is...". Group the decision in a function or authorisation service, test it with several actors and document exceptions. An authorisation rule that is not tested eventually diverges from the requirement.

Roles and attributes answer different needs. A role-based model assigns permissions to a role, then a role to a user; it is easy to understand and audit. An attribute-based model decides from context, such as department, owner or time. The second model is finer, but harder to test. In either approach, separate duties: the person who creates an administrator account should not be the only one able to delete logs. Separation of duties reduces the risk of fraud and internal error.

Least privilege also applies to technical components. The application's database account must not be an administrator; it should read and write the necessary tables, not drop the schema. The web process must not modify code. An external service should receive a token limited to one action and one duration. These restrictions reduce the impact of a compromise.

In a multi-tenant application, authorisation must also isolate tenants. A user who belongs to one organisation must not reach another organisation's data, even with a valid identifier. Every query must be scoped by tenant, and the scope must come from the authenticated session, not from a client-supplied parameter. Tests must include a user from tenant A requesting a resource from tenant B. This scenario is easy to forget during a feature addition and expensive to discover in production.

6. Untrusted input and SQL injection

Every input from outside is untrusted: URL parameters, form bodies, headers, cookies, files, API responses, imported data. Validation checks that input matches an expected format; it does not replace escaping or a parameterised query. Input can be valid and dangerous if concatenated into a query. The rule is simple: never build a SQL query by concatenating input.

// Vulnerable — lab only, do not reproduce in production
$sql = "SELECT * FROM documents WHERE owner = '" . $_GET['owner'] . "'";
$rows = $pdo->query($sql)->fetchAll();

// Fixed: parameterised query
$stmt = $pdo->prepare('SELECT * FROM documents WHERE owner = :owner');
$stmt->execute(['owner' => $_GET['owner']]);
$rows = $stmt->fetchAll();

A parameterised query separates SQL code from data. The driver sends the query and values separately; a value containing quotes or operators remains a value, not code. Prepared statements do not protect table or column identifiers: if a column name comes from the user, use a whitelist of allowed values, not concatenation.

ORMs reduce risk but do not eliminate it. A method accepting DQL or raw SQL with a concatenated string remains vulnerable. Sort filters, column names and dynamically built clauses require strict validation. Database errors must be logged server-side and displayed generically to the client: a detailed message can reveal the schema, tables or engine version.

Input validation must be defined by a policy, not a list of forbidden characters. State the expected type, length, format and allowed values for each field. Reject by default what does not match. For URLs the server will call, check the scheme, domain and resolved address to prevent a user from making the server access an internal service; this family is called SSRF. A domain whitelist is safer than a blacklist, because attackers find variants.

Server-side validation is the reference. Validate type, length, format and allowed values; reject what is unexpected. Browser validation improves the experience, but it is under the user's control. For files, check the real MIME type, size, dimensions and content; do not trust the extension. Store uploaded files outside the public path or serve them through a controller that checks permissions.

Uploaded files are a particularly risky input. Check size before reading content, the real MIME type rather than only the extension, image dimensions and the presence of active content. Rename the file, store it outside the public path or serve it through a controller that checks rights, and never execute it as a script. For images, re-encode with a proven library and remove unnecessary metadata. An apparently harmless file may contain HTML, SVG with script or a malicious archive.

The database account must apply least privilege. If the application does not need to drop tables, it must not have that right. If it only reads a view, grant access to the view, not the underlying tables. An injection that cannot execute DDL or read another database has a more limited impact. Defence in depth combines validation, parameterised queries, minimal privileges and logging.

SQL is not the only injection family. Command injection occurs when input reaches a shell command; avoid passing user data to a shell, and when unavoidable, use argument arrays rather than string concatenation. Path traversal occurs when a file name such as ../../etc/passwd escapes the intended directory; resolve the path and verify it remains inside an allowed root. Deserialisation of untrusted data can execute code in some languages and libraries; prefer structured formats such as JSON with explicit validation. Template injection can turn a user-supplied template into code. The common principle is the same: never mix untrusted data with an interpreter's syntax.

7. XSS and context-aware escaping

A script injection, or XSS, occurs when untrusted data is interpreted as code by the browser. It can be reflected, stored or come from the DOM. XSS can steal a session, modify the interface, perform actions as the user or redirect to a malicious site. The main protection is output escaping adapted to the context, complemented by a Content Security Policy.

<!-- Vulnerable — lab only -->
<p>Hello <?= $_GET['name'] ?></p>

<!-- Fixed: HTML escaping -->
<p>Hello <?= htmlspecialchars($_GET['name'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?></p>

Context matters. A value inserted into HTML text, an attribute, a URL, CSS or JavaScript does not follow the same rules. htmlspecialchars is suitable for HTML, not a JavaScript string. Template engines such as Twig escape HTML by default; do not disable escaping without a reason and a context analysis. If you must allow rich HTML, use a sanitiser with an allowlist of elements and attributes, then test edge cases.

Validation does not replace escaping. A value can be valid according to the form and contain characters that become dangerous in another context. Conversely, escaping a value does not remove the need to validate its length and format. Defence in depth combines validation, output escaping, rich-HTML sanitisation and CSP. None of these layers is sufficient alone.

An XSS can also come from the DOM, without passing through the server. If a script reads a value from the URL and inserts it with innerHTML, the data is interpreted as HTML. Prefer textContent for text, avoid innerHTML with untrusted data and use node creation APIs. Modern frameworks often escape by default, but explicit escape hatches, javascript: URLs and event attributes remain dangerous. Code review must look for these patterns as much as server-side concatenation.

Content Security Policy limits sources of scripts, styles, images and connections. It reduces the impact of XSS, but it does not fix the flaw. A strict CSP can break an application using inline scripts or old libraries; deploy it in report-only mode, analyse violations, then apply it progressively. Avoid unsafe-inline and unsafe-eval when possible.

Rich text requires a sanitiser, not a simple filter. An allowlist defines which elements and attributes are accepted, and everything else is removed or encoded. The sanitiser must be applied on output, because stored content may have been created before a rule change. Test it with malformed HTML, nested tags, encoded payloads and SVG. Do not rely on a regular expression to parse HTML; HTML is not a regular language, and browsers are more tolerant than a naive filter.

Deploy a CSP in stages: collect violations in report-only mode, fix inline scripts and uncontrolled sources, then enable the policy. A CSP that is too strict on day one breaks the interface and pushes people to disable it. Keep a violation report accessible to the team and check that it contains no sensitive data. CSP reduces the impact of XSS, but it replaces neither escaping nor validation.

Session cookies must be HttpOnly so JavaScript cannot read them, Secure so they are not sent over HTTP and SameSite to limit cross-site requests. These attributes reduce the impact of XSS or CSRF, but do not replace escaping. An HttpOnly cookie protects against direct cookie theft, not against actions performed in the user's session.

8. CSRF, cookies and browser protections

A CSRF attack forces an authenticated user's browser to send a request the user did not intend. It exploits the fact that the browser automatically attaches cookies to the relevant site. The classic protection is an anti-CSRF token, random, linked to the session and verified server-side for every state-changing action. The token must be unpredictable and must not be accepted in a GET request.

// Local form: anti-CSRF token and server-side verification
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$token = $_SESSION['csrf'];

// On submission
if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    http_response_code(403);
    exit('Request rejected');
}

SameSite cookies limit cookie sending on cross-site requests. SameSite=Lax suits many journeys, but not all; SameSite=Strict can break inbound links. The choice depends on the journey and must be tested. SameSite does not replace a CSRF token for sensitive actions, because browsers and edge cases vary.

Session fixation consists of imposing a session identifier known to the attacker before login. Regenerating the identifier after authentication and refusing a client-supplied identifier fix this problem. Login CSRF, less known, forces a user to log in with the attacker's account so the attacker can later observe their actions; a token on the login form and origin verification reduce this risk. These attacks show that session security is not limited to the cookie.

Security headers complement protection. X-Content-Type-Options: nosniff prevents the browser from guessing a MIME type. Referrer-Policy limits information sent to other sites. X-Frame-Options or frame-ancestors in the CSP protect against clickjacking. Permissions-Policy disables unnecessary browser features. These headers are configured at the server or application level and checked with browser tools.

CORS is not an authentication mechanism. It tells the browser which origins may read a response. An overly permissive CORS configuration with cookies can expose data. Do not confuse CORS with server-side access control: a client that is not a browser can ignore CORS. APIs must check authentication and authorisation on the server, independently of CORS.

Clickjacking tricks a user into clicking an invisible or disguised element on a page that embeds the real application in a frame. X-Frame-Options: DENY or frame-ancestors 'none' in the CSP prevents this embedding. Tabnabbing exploits links opened with target="_blank" without rel="noopener": the opened page can modify the original tab. Modern browsers often apply noopener by default, but explicit attributes keep the protection visible and auditable.

A CORS configuration consists of allowed origins, methods, headers and sometimes credentials. Avoid the * wildcard with cookies, and do not accept a dynamically supplied origin without validation. A CORS error can reveal data to a third-party site or break a legitimate integration. Document expected origins and test preflight requests. CORS protects the browser, not the server: business authorisation remains mandatory.

Test traversal journeys: a form submitted from another site, a GET link that changes state, a request with a missing or expired token. Verify that the response is rejected without side effects. Log the rejection without logging the token. A form that "works" without a token is not proof of security; it may be a missing protection.

9. Secrets, dependencies and configuration

A secret is a value whose disclosure compromises security: database password, API key, signing key, private certificate. A secret must not be in code, in a Git repository, in a container image or in a log. Use environment variables or a secret manager, with limited access rights and a planned rotation. If a secret has been exposed, removing it from code is not enough: revoke and replace it.

Dependencies are part of the attack surface. An old library may contain a known vulnerability. Use a lock file, monitor security advisories, update in batches and test after each update. A software bill of materials, or SBOM, helps know what is installed and react quickly. Do not remove a dependency without checking that it is not used indirectly.

# Local checks, without exposing secrets
composer audit
composer outdated --direct
php -r 'echo PHP_VERSION, PHP_EOL;'
# Find sensitive files accidentally versioned (local example)
git ls-files | grep -Ei '\.(env|pem|key|p12)$'

The supply chain includes libraries, container images, build scripts and CI workflows. A compromised package or an overly permissive CI action can introduce malicious code without modifying your application. Pin versions, verify sources, limit workflow permissions and do not give pull requests from external repositories access to secrets. An SBOM helps quickly identify components affected by an advisory. Dependency security is not limited to running an audit once a year.

Production configuration must disable detailed errors, development tools and demonstration accounts. File permissions must be minimal: the web server reads code but does not write it. Data directories must not be directly accessible. Unnecessary services must be stopped. A container image should run as a non-privileged user and, where possible, with a read-only filesystem.

Errors must be useful to the operator and generic to the user. A message "internal error" with a correlation identifier lets you find the detail in logs without exposing the stack, path or SQL query. Logs must not contain passwords, tokens, card numbers or unnecessary personal data. Logging is a protection, but it can become a leak if misconfigured.

A configuration inventory helps verify environments: PHP version, extensions, database, web server, TLS, headers, backups, accounts. Compare production with a documented baseline and test deviations. A configuration that works is not necessarily secure; it may simply not have been attacked.

The build and deployment chain must be protected too. A CI workflow triggered by a pull request from a fork must not receive production secrets. Actions and images must be pinned to immutable versions when possible. Build artefacts must be traceable to a commit. A container image should be scanned for known vulnerabilities and rebuilt regularly, because a base image that was safe last month may not be today. Restrict who can modify the pipeline itself: an attacker who controls the build can produce a seemingly correct application that contains malicious code.

10. Logs, backups and incident detection

Detection relies on logs and metrics. Log successful and failed logins, password changes, denied access, application errors and administrative actions. Add a correlation identifier to link a request, an error and a business action. Protect log integrity: an attacker who can modify logs can erase their traces. Limit access and define a retention period.

Backups must cover the database, files and the configuration needed for restoration. The 3-2-1 rule is a guide: three copies, two different media, one off-site copy. Encrypt backups containing personal data and test restoration in a separate environment. An untested backup is an assumption, not a protection. Document who can restore, with which command and how to verify integrity.

Logs often contain personal data without the team realising it: IP address, email, identifier, URL parameters. Minimise what is written, mask sensitive values and define retention. Protect log access and integrity; an attacker who can modify them can erase traces. For backups, encrypt media and test restoration with the available keys. An encrypted backup whose key is lost is not a backup.

An incident follows a cycle: preparation, detection, containment, eradication, recovery and lessons learned. Preparation includes contacts, roles, procedures and backups. Containment prevents spread without destroying evidence. Eradication removes the cause. Recovery restores service and verifies it is not compromised. Lessons learned update procedures and controls.

Minimal incident record
Date and time of detection:
Detected by:
Systems and data affected:
Containment actions:
Evidence preserved:
Root cause:
Corrective and preventive actions:
Possible notification (authority, individuals):
Owner and closure date:

In a GDPR context, a data breach may need to be notified to the competent authority within a short period, often 72 hours, and to affected individuals if the risk is high. The decision depends on the nature of the data, the risk and applicable obligations. Prepare templates and contacts before an incident; in an emergency, you do not write a procedure. Security includes compliance, but it is not limited to it.

Monitoring must alert on useful signals: spikes in failed logins, 5xx errors, unusual access, saturation, certificates nearing expiry, failed backups. Too many non-actionable alerts tire teams; too few let an incident through. Define a threshold, an owner and an action for each alert. Test the escalation procedure.

Define recovery objectives before an incident: the recovery time objective, or RTO, is the acceptable duration of unavailability; the recovery point objective, or RPO, is the acceptable amount of data loss. These objectives drive backup frequency and restoration testing. A daily backup with an RTO of one hour is inconsistent unless restoration is fast and tested. Write the restoration procedure, run it on a schedule and record the duration and result. A backup that has never been restored is a hypothesis.

11. Analysis and verification method

Threat modelling describes the system, its flows, boundaries and plausible threats. A simple diagram is enough: browser, proxy, application, database, storage, external service. For each flow, ask what can be read, modified, replayed or interrupted. The STRIDE method proposes six families: spoofing, tampering, repudiation, information disclosure, denial of service and elevation of privilege. It helps cover overlooked angles.

Abuse cases complement use cases. A use case says "a member downloads their document"; an abuse case says "a member changes the identifier and downloads another member's document". Both must be tested. Security requirements must be explicit: authentication required, authorisation on the object, validation, logging, encryption, rate limiting. An untested requirement is an intention.

A threat-modelling workshop brings together people who know the business, the code and operations. Draw the flows, name the boundaries, then ask for each flow: who can read, modify, replay, interrupt or bypass? The resulting security requirements must be testable: "a member cannot read another member's document", "a missing CSRF token is rejected", "a backup restores in under two hours". A vague requirement such as "be secure" cannot be verified.

Frameworks help structure verification. The OWASP Top 10 presents widespread risk families; ASVS offers more detailed verifiable requirements. Use them as checklists, not as automatic certification. Verify the framework version and date, because lists evolve. A control present in a list is not necessarily applicable to your context; a missing control may be crucial.

Different verification exercises answer different questions. A code review looks for dangerous patterns in the source. A configuration audit compares a system with a baseline. A penetration test simulates an attacker within an agreed scope and time. A vulnerability scan detects known signatures but does not understand business logic. None of these replaces the others, and none replaces a tested authorisation rule. Define the scope, the rules of engagement and the expected deliverable before commissioning a test. A report without reproducible evidence and a prioritised remediation plan is difficult to act on.

For each control: threat addressed, expected evidence, test method, result, residual risk
Example: authorisation on documents
Threat: reading another person's document
Evidence: two test accounts, cross-access denied
Test: manual request and automated test
Result: expected / observed / date
Residual risk: documents shared by mistake, to handle through a sharing review

Verification combines automated tests, code review and manual testing. Automated tests cover regressions: a user cannot access a resource, a missing CSRF token is rejected, invalid input does not pass. Code review looks for dangerous patterns: SQL concatenation, innerHTML, |raw, missing authorisation checks, versioned secrets. Manual testing explores journeys and edge cases. No single method is enough.

Prioritise by impact and likelihood, then verify that the fix does not create a new problem. A fix that blocks legitimate users will be bypassed. A fix that treats only the surface leaves the cause. Document residual risk and the reassessment date. Security is a continuous process, not a checkbox to tick once.

12. Synthesis and improvement plan

For the association portal, defence in depth combines several layers: HTTPS and security headers; robust authentication and protected sessions; server-side authorisation on every object; validation and parameterised queries; output escaping and CSP; CSRF tokens and appropriate cookies; secret and dependency management; logs, backups and an incident procedure. No layer is sufficient, and each layer must be tested.

An improvement plan is built in stages. Start with high, easy-to-fix risks: remove secrets from the repository, apply critical updates, verify object authorisation, enable HTTPS and secure cookies. Then address medium risks: CSP, rate limiting, logging, tested backups. Finally, install durable practices: code review, security tests, dependency inventory, incident exercises, team training.

Typical plan
1. Asset and flow inventory
2. Risk analysis and abuse scenarios
3. Quick high-impact fixes
4. Preventive controls and detection
5. Verification tests and evidence
6. Periodic review and update

Security must be proportionate. A small association portal does not need the same organisation as a bank, but it must protect the personal data it holds and be able to restore its service. Measures must be understandable to the people who operate them. A protection nobody can maintain eventually gets disabled.

Documentation is itself a security control. An up-to-date diagram, a list of accounts and their owners, a backup procedure and an incident contact list let someone else take over when the usual maintainer is unavailable. Documentation must be stored where it can be reached during an incident, not only on the server that may be down. Keep it concise, date it and review it after each significant change. A procedure that exists only in one person's memory is a single point of failure, exactly like an untested backup or a shared administrator password.

An improvement plan is measured with a few useful indicators: open high risks, time to fix critical dependencies, authorisation test coverage, successful restorations, incident detection time, second-factor coverage for accounts. These indicators should drive action, not become artificial targets. Culture matters as much as tools: teams must be able to report a mistake without fear, and security decisions must be explained. An organisation that learns from incidents improves faster than one that hides its mistakes.

Training should be practical and role-specific. Developers need to recognise injection, broken authorisation and unsafe dependencies; administrators need patching, backups and incident procedures; everyone needs phishing and data-handling basics. Short regular exercises, such as a simulated phishing message or a restoration drill, teach more than an annual slide deck. Designate a referent who can answer questions and keep the plan alive. Security improves when it is part of daily work, not an annual campaign.

Finally, distinguish compliance from security. A signed document does not protect a misconfigured database; a technical control does not replace a legal basis and information to individuals. Technical security, compliance and organisation complement each other. The right indicator is not "have we ticked the box?" but "can we explain what is protected, how we verify it and what happens if a protection fails?". This ability to explain and verify is more durable than a fashionable tool.

Exercise 1 — Inventory and trust boundaries

Take the fictional portal and list five assets, five actors and three trust boundaries. For each asset, state who may read, modify and delete it. Add copies: backups, exports, logs and temporary files. Identify the asset whose loss would have the greatest impact and the one whose leak would be hardest to detect.

Solution

A correct inventory distinguishes data from copies and states rights per actor. Boundaries must be named: browser, proxy, application, database, storage. The most critical asset depends on context; for an association, personal data and member documents are often priorities. Detection difficulty depends on logs and monitoring. If a copy is not inventoried, it escapes protection measures.

Exercise 2 — Risk matrix

Build a risk matrix with five scenarios: access to another member's document, session theft, SQL injection, stored XSS and an unrestorable backup. Classify each scenario by likelihood and impact, then propose a priority and a first measure. Justify your choices in one sentence per scenario.

Solution

There is no single ranking, but the reasoning must be explicit. Access to another member's document is often easy and frequent; SQL injection depends on queries; stored XSS can affect several users; an unrestorable backup has high impact but likelihood linked to testing. Priority combines both axes and the cost of the fix. A measure must reduce risk, not merely move it.

Exercise 3 — HTTPS and headers

In a local lab, inspect the certificate of a test service, verify the HTTP-to-HTTPS redirect and record the security headers. Explain what HTTPS protects and does not protect. Propose a certificate renewal check.

Solution

The certificate must match the name, be valid and be signed by a recognised authority in production. HTTPS protects transport, not storage or a compromised server. Expected headers include HSTS, nosniff, a referrer policy and framing protection. Renewal checking can be an expiry alert and an automated renewal test. A self-signed certificate is acceptable in a lab, not for a public service without an explicit decision.

Exercise 4 — Authentication and sessions

Write an authentication and session checklist for the portal. Test session identifier regeneration after login, expiry, server-side logout and password reset. Verify that the error message does not reveal whether the account exists.

Solution

The checklist must cover hashing, password policy, second factor for administrators, regeneration, HttpOnly/Secure/SameSite cookies, expiry, logout and reset. The test must verify behaviour, not only the presence of a field. A generic message prevents account enumeration. Logout must invalidate the session on the server, not only delete the cookie.

Exercise 5 — Authorisation and IDOR

Create two test accounts and one document for each. Verify that a member cannot read, modify or delete the other member's document by changing the identifier in the URL. Test the administrator case. Note the response codes and side effects.

Solution

The check must be server-side, after loading the object. A member must receive 403 or 404 for another member's document; the administrator may access it according to the matrix. The test must also verify that no modification occurred. Insecure direct object references are one of the most frequent causes of data leaks. An unpredictable URL does not replace an authorisation check.

Exercise 6 — Injection, XSS and CSRF

In a local lab, reproduce a SQL injection with a benign input, an XSS with an alert script and a CSRF request from another origin. Fix each case: parameterised query, output escaping and CSRF token. Verify that the fixes do not break legitimate journeys.

Solution

Injection is fixed with a parameterised query and a whitelist for column identifiers. XSS is fixed with context-appropriate escaping, complemented by CSP. CSRF is fixed with an unpredictable token linked to the session and verified server-side, complemented by SameSite cookies. Tests must verify rejection and the absence of side effects. Test only your lab and do not keep offensive payloads in production code.

Capstone — securing the portal

Take the fictional portal and produce a complete security plan: inventory, abuse scenarios, risk matrix, priority fixes, detection controls, backups and incident procedure. Implement at least four fixes: document authorisation, parameterised queries, escaping and CSRF. Add automated tests for each fix. Write a verification record with expected evidence and observed results.

Assessment grid: assets and boundaries are identified; risks are prioritised; fixes are verified by tests; logs contain no secrets; backups are restorable; the incident procedure is understandable; residual risk is documented. To go further, add a CSP, rate limiting, a second factor for administrators and a restoration exercise. Record the evidence and date of each verification. Present the result to someone who did not write the plan and ask them to reproduce one check from the documentation alone. Review the plan after each fix.

Common errors and diagnostic method

Believing HTTPS is enough, that hiding a button protects an action, or that a character filter replaces a parameterised query are classic mistakes. Browser-side validation is not server-side validation. A test that only checks status 200 does not prove access is authorised. A detailed error message can reveal useful information to an attacker. A secret removed from code but still present in Git history remains compromised.

Method: reproduce the scenario in a lab, observe the request and response, check state before and after, then fix the cause. Test the denied case and the allowed case. Verify that the fix does not create a functional regression. Review logs to confirm no sensitive data is exposed. Document the evidence and residual risk.

Review and self-assessment

You should now be able to explain the difference between threat, vulnerability and risk; describe what HTTPS protects and does not protect; design reasonably secure authentication and sessions; verify authorisation on an object; fix SQL injection, XSS and CSRF; manage secrets and dependencies; prepare a backup, a log and an incident procedure.

Self-assessment: I can build a risk matrix; I can test cross-account access; I can explain why escaping depends on context; I can verify that a CSRF token is mandatory; I can prepare a restoration; I can describe the limits of a protection. To progress, study OWASP ASVS, automated security testing, threat modelling and incident response.

Reference documentation