We have protected the path and we have protected the endpoints. One door remains that, by definition, cannot be closed: the one Rutalia keeps open at mirutalia.example twenty-four hours a day so that 400 corporate customers can look up their shipments. No firewall can close port 443 on the portal, because that is the service. No EDR stops somebody typing ' OR 1=1-- into a form. No allow-list stops cliente412 from changing a number in the address bar and seeing the shipments of customer 087.

This is the lesson where we open the code. We are going to work through real web vulnerabilities — not as a list of names, but with MiRutalia's vulnerable code in front of us, its exploitation explained and its fix line by line —, finally take apart hypothesis H4 from the threat model, build the security headers on top of the nginx we already hardened in 03-02, and decide what an application handling the data of 400 companies must log — and what it must never log.

An ethical and legal warning, before we start. Every offensive technique in this lesson is explained so that you can find and fix them in your own code. Trying them against a system that is not yours, without the owner's written authorisation, is an offence under the Spanish Criminal Code, even if you cause no damage and your intentions are good. Practise only in your own test environment or on the deliberately vulnerable applications we will see in 04-05. The full legal framework is developed there.

  1. Why the application is the most exposed surface

MiRutalia is a Flask application served by gunicorn behind nginx, with PostgreSQL behind that, hosted on srv-web01 (10.10.30.10 in the DMZ) and published at 203.0.113.20. It has around 40 routes, 400 customers with an account, and it exposes: shipment tracking, invoice downloads, delivery address management, uploads of signed delivery notes and an API for the customers who integrate their systems with Rutalia's.

Four reasons make it the prime target:

Reason Explanation
It is exposed to the whole internet There is no firewall to protect it: the service consists of being reachable
It talks directly to the data Behind it sits the customer database (asset A005), with all 400 customers and their history
The logic was written by a person A well-patched server has the vulnerabilities Debian has not fixed; an application has the ones its team introduced
The traffic is legitimate and encrypted Suricata sees an HTTPS request to port 443, exactly like the 50,000 legitimate ones that day

That last row is the key and it explains why everything done so far is not enough: an attack on a web application travels over the same channel, looking the same and using the same port as normal use of the service. The defence has to be inside the application.

  1. The trust model: every input from the client is hostile

This is the idea to internalise before any other. A developer writes code thinking about the user who fills in the form the way it was designed. An attacker thinks about everything else.

Everything that arrives from the client is controllable by the client. Everything, with no exception:

Element Does the client control it? Common mistake
Form fields Yes Trusting the HTML maxlength
URL parameters Yes Trusting an ?admin=false
Hidden fields (<input type="hidden">) Yes Putting the price or the cliente_id in a hidden field
Cookies Yes Storing the role in an unsigned cookie
HTTP headers (User-Agent, Referer, X-Forwarded-For) Yes Authorising by Referer; trusting X-Forwarded-For
The HTTP method Yes Assuming only a POST will arrive
The name and type of the uploaded file Yes Trusting Content-Type or the extension
The order and number of parameters Yes Assuming the form sends exactly the expected fields
JavaScript validation in the browser Yes: it can be disabled Validating only on the client

The last row deserves a full sentence: client-side validation is usability, not security. It stops the user wasting time submitting a badly filled-in form. An attacker does not use the browser: they send the request directly.

POST /pedido/confirmar HTTP/1.1
Host: mirutalia.example
Content-Type: application/x-www-form-urlencoded
Cookie: session=eyJjbGllbnRlX2lkIjo0MTJ9...

envio_id=10412&cliente_id=87&importe=0.01&es_admin=true

That request is built with curl in ten seconds. It has been through no form, no JavaScript and no browser check. If the server trusts cliente_id, importe or es_admin because "the form does not send them like that", the application is broken.

The general rule, which sums up half the lesson:

Data is not code, identity comes from the session and authority comes from the server.

  1. Server-side validation: allow-listing and canonicalisation

Correct validation has four properties:

  1. It is done on the server, always, even if it is also done on the client.
  2. It is an allow-list, not a block-list. You define what is valid and reject everything else. Trying to enumerate what is dangerous (<script>, ', --, UNION) is a race you always lose: there are alternative encodings, mixed case, interleaved comments and equivalent Unicode characters.
  3. It is as strict as the business allows. A Rutalia customer code is C followed by four digits. That is an eleven-character regular expression, not a free-text field.
  4. It is done after canonicalisation. If you validate before decoding, the attacker sends %2e%2e%2f and the validation sees something different from what the system will use afterwards.

In Flask, with a schema library:

# esquemas.py - input validation for MiRutalia
from marshmallow import Schema, fields, validate, EXCLUDE

class ShipmentQuerySchema(Schema):
    class Meta:
        # Any undeclared field is DISCARDED: not accepted, and no error raised.
        # That way an "es_admin=true" added by the attacker never reaches the logic.
        unknown = EXCLUDE

    envio_id = fields.Integer(
        required=True,
        validate=validate.Range(min=1, max=99_999_999)   # a plausible range, not an infinite one
    )
    referencia = fields.String(
        required=False,
        validate=validate.Regexp(r"^[A-Z0-9\-]{4,20}$")  # an explicit allow-list
    )
    fecha_desde = fields.Date(required=False)            # a real type: not a string

And how it is used:

from marshmallow import ValidationError

@bp.route("/envios/buscar")
@require_permission("shipment:view_own")
def search_shipments():
    try:
        data = ShipmentQuerySchema().load(request.args)
    except ValidationError as err:
        # A generic 400: the internal detail is not returned to the client
        current_app.logger.info("validation_failed fields=%s ip=%s",
                                list(err.messages.keys()), request.remote_addr)
        abort(400)
    # From here on, 'data' contains ONLY declared fields, with the correct type
    ...

A line-by-line commentary on what matters:

  • unknown = EXCLUDE is the line that protects most: it silently discards the fields the attacker adds. The alternative, RAISE, is also valid and a little noisier; what is unacceptable is INCLUDE.
  • fields.Integer with Range converts the input to the correct type. An envio_id arriving as 10412 OR 1=1 fails here, before it reaches any query. Type validation is, on its own, a defence against injection in many cases.
  • Regexp anchored with ^ and $: without the anchors, C0114'; DROP TABLE... would pass validation because it contains a match. It is a classic mistake.
  • The error is logged but not returned: the client gets a bare 400; the detail goes to the log. A detailed error message is information for the attacker (section 19).

Validation does not replace the specific defences. Validating the input greatly reduces the surface, but the protection against SQL injection is the parameterised query, and the protection against XSS is output encoding. Validation is the first layer, not the only one.

  1. The OWASP Top 10 prioritised for MiRutalia

The OWASP Top 10 is a consensus list of the most critical risk categories in web applications. It is not a compliance standard and it is not exhaustive: it is an excellent starting point. Here it is, translated into MiRutalia's reality and prioritised by real risk in this specific portal:

Priority OWASP risk What it is How it shows up in MiRutalia Main mitigation Section
1 Broken access control (A01) The user reaches what is not theirs cliente412 sees the shipments of 087; hypothesis H4 require_ownership() on every instance 11-13
2 Injection (A03) Data interpreted as code Shipment search with concatenated SQL Parameterised queries + a non-superuser account 5-10
3 Cryptographic failures (A02) Sensitive data badly protected SECRET_KEY and AES_KEY in config.py, committed to Git A secrets manager + rotation 18
4 Security misconfiguration (A05) Defaults, verbose errors Inherited DEBUG=True, no security headers Hardening nginx and Flask 19, 25-26
5 Identification and authentication failures (A07) Weak sessions and login No attempt limits, user enumeration, no MFA Rate limiting + uniform messages + MFA 23-24, 27
6 Software and data integrity failures (A08) Deserialisation, unverified dependencies pickle in the route cache Safe formats; dependencies in 08-01 21
7 Insecure design (A04) The flaw is in the design, not the code Sequential identifiers, no download limits Threat modelling in 08-01 12
8 Logging and monitoring failures (A09) What is needed is not logged No application security logging Structured logging + the C9999 canary 29
9 Vulnerable and outdated components (A06) Libraries with known CVEs Flask and dependencies not updated since 2024 Dependency management, 06-04 19
10 SSRF (A10) The server makes requests wherever it is told Delivery note preview generator by URL An allow-list of destinations 20

To this list, for MiRutalia, two more have to be added that are not categories of their own in the Top 10 but are concrete vectors: XSS (part of injection) and CSRF (part of broken access control). We treat them separately because their mechanics and their fixes are different.

Notice the order: the first one is not SQL injection, which is the most famous vulnerability. It is broken access control, because it is the most frequent, the hardest to detect automatically — no tool knows which shipments cliente412 should see — and because in MiRutalia we already know it exists.

  1. SQL injection: what actually happens

Injection happens when data supplied by the user ends up being interpreted as instructions by an interpreter. In the case of SQL, the interpreter is the database engine.

The origin of the problem is string concatenation. When the program builds the query by gluing text together, it loses the boundary between "this is the instruction" and "this is the data":

Intended query:      SELECT * FROM envios WHERE referencia = 'RT-10412'
                                                             +- data -+

Attacker input:      RT-10412' OR '1'='1

Resulting query:     SELECT * FROM envios WHERE referencia = 'RT-10412' OR '1'='1'
                                                             +-- now it is logic --+

The attacker's quote closes the data string, and everything they write afterwards is read by the engine as part of the instruction. OR '1'='1' is always true, so the query returns every shipment in the table.

flowchart LR
    subgraph BAD["Concatenation"]
        A1["Text template"] --> C1["A single string"]
        B1["User data"] --> C1
        C1 --> D1["SQL engine<br/>interprets EVERYTHING"]
    end
    subgraph GOOD["Parameterisation"]
        A2["Query with<br/>? placeholders"] --> D2["SQL engine<br/>compiles the instruction"]
        B2["User data"] --> P["Sent SEPARATELY<br/>as a value"]
        P --> D2
        D2 --> R["The data can NEVER<br/>become an instruction"]
    end
    style D1 fill:#ffcccc
    style R fill:#ccffcc

The essential difference: with parameterisation, the instruction is compiled first and the data is delivered afterwards. There is no moment at which the data can become an instruction, whatever the user types. It is not "escaping quotes properly": it is that the data travels through a different channel.

  1. MiRutalia's vulnerable code and its exploitation

This is the real shipment search function, written in 2022 when the portal was put together in a hurry:

# rutas/envios.py - VULNERABLE. Do not copy.
import psycopg2
from flask import request, render_template, session
from db import get_connection

@bp.route("/envios/buscar")
def search_shipments():
    reference = request.args.get("ref", "")
    conn = get_connection()
    cur = conn.cursor()

    # [!] CONCATENATION: here is the vulnerability
    sql = "SELECT id, referencia, destino, estado, fecha " \
          "FROM envios WHERE cliente_id = " + str(session["cliente_id"]) + \
          " AND referencia LIKE '%" + reference + "%' ORDER BY fecha DESC"

    cur.execute(sql)
    results = cur.fetchall()
    return render_template("envios.html", envios=results)

An analysis of the flaw:

  • The sql line builds the query by gluing text together. reference comes straight from request.args, unvalidated and unescaped.
  • The LIKE '%...%' makes it worse: it forces single quotes into the template, handing the attacker an obvious breaking point.
  • The cliente_id = ... check comes from the session, which is right — not from the client — but it is useless if the attacker can rewrite the condition.

Exploitation. With the input x%' OR '1'='1, the resulting query is:

SELECT id, referencia, destino, estado, fecha
FROM envios
WHERE cliente_id = 412 AND referencia LIKE '%x%' OR '1'='1%'
ORDER BY fecha DESC

Because of operator precedence, AND is evaluated before OR, so the whole condition is equivalent to (cliente_id = 412 AND referencia LIKE '%x%') OR true: it returns every shipment of every customer. An ordinary customer has just seen Rutalia's entire operation.

And with a union input, the attacker is not limited to the envios table:

x%' UNION SELECT id, nombre, cif, email, NULL FROM clientes --
SELECT id, referencia, destino, estado, fecha FROM envios
WHERE cliente_id = 412 AND referencia LIKE '%x%'
UNION SELECT id, nombre, cif, email, NULL FROM clientes --%'
ORDER BY fecha DESC

The -- comments out the rest of the query, removing the leftover quote and the ORDER BY. The result mixes the shipments with the complete portfolio of 400 customers, displayed in the same HTML table. That is, literally, hypothesis H4 carried out, and it comes out through the browser with no tooling at all.

A reminder: this can only be tried against MiRutalia's own test environment. The same request against another company's portal is unlawful access to an information system.

  1. The fix: parameterised queries

The fixed version, with everything we learned in the previous sections:

# rutas/envios.py - FIXED
import psycopg2
from psycopg2.extras import RealDictCursor
from flask import request, render_template, session, abort, current_app
from marshmallow import ValidationError
from db import get_connection
from autorizacion import require_permission
from esquemas import ShipmentQuerySchema

SQL_SEARCH_SHIPMENTS = """
    SELECT id, referencia, destino, estado, fecha
    FROM envios
    WHERE cliente_id = %(cliente_id)s
      AND referencia ILIKE %(pattern)s
    ORDER BY fecha DESC
    LIMIT %(limit)s
"""

@bp.route("/envios/buscar")
@require_permission("shipment:view_own")
def search_shipments():
    # 1. Strict validation of the input
    try:
        data = ShipmentQuerySchema().load(request.args)
    except ValidationError:
        abort(400)

    reference = data.get("referencia", "")

    # 2. The identity ALWAYS from the session, never from the request
    customer_id = session["cliente_id"]

    # 3. Parameterised query: the data travels SEPARATELY from the instruction
    with get_connection() as conn:
        with conn.cursor(cursor_factory=RealDictCursor) as cur:
            cur.execute(SQL_SEARCH_SHIPMENTS, {
                "cliente_id": customer_id,
                "pattern": f"%{reference}%",   # the wildcards are added by the SERVER
                "limit": 200,
            })
            results = cur.fetchall()

    # 4. Security logging
    current_app.logger.info(
        "shipment_search customer=%s results=%d pattern_len=%d",
        customer_id, len(results), len(reference)
    )
    return render_template("envios.html", envios=results)

An explanation of each decision:

  1. SQL_SEARCH_SHIPMENTS as a constant with %(name)s placeholders. It is not a string that gets built: it is a fixed template. Being outside the function and in capitals, any reviewer can see at a glance that nothing is concatenated.
  2. cur.execute(SQL, dict): psycopg2 sends the query and the parameters separately to the PostgreSQL server. The data is never interpreted as SQL. It is essential to understand that this is not escaping quotes: even if reference contains '; DROP TABLE envios; --, PostgreSQL will search for it literally as text and find nothing.
  3. f"%{reference}%": the LIKE wildcards are added by the Python code to the value, not to the SQL template. This is the detail almost everybody gets wrong: if you write LIKE '%%(pattern)s%' in the SQL, you have reintroduced quotes into the template.
  4. ILIKE instead of LIKE gives case-insensitive search in PostgreSQL, which is what the user expects. It is not security, it is functional correctness.
  5. LIMIT %(limit)s: a hard limit. Without it, a query returning a million rows is a denial of service, and it makes mass extraction easier.
  6. customer_id comes from session, never from request. If it came from the request, we would have an IDOR even if the SQL were perfect. They are two independent problems.
  7. with get_connection() and with conn.cursor(): the context managers close the cursor and the transaction even if an exception is raised. One leaked connection per request exhausts the pool in minutes.
  8. The log does not include the search pattern, only its length. A search term can contain personal data; the length is enough to detect anomalies.

A very common mistake worth pointing out. This is still vulnerable:

# [!] BAD: it looks parameterised but it is not
cur.execute("SELECT * FROM envios WHERE referencia = '%s'" % reference)
cur.execute(f"SELECT * FROM envios WHERE referencia = '{reference}'")

Python's % operator and f-strings build the string before execute ever sees it. The driver receives an already concatenated string and can do nothing. The difference from the correct version is a comma instead of a %, and it is all the difference in the world. This is why static analysis tools flag any f-string inside an execute.

And what cannot be parameterised. Parameters substitute values, not identifiers. This does not work:

cur.execute("SELECT * FROM envios ORDER BY %(col)s", {"col": column})   # it does not do what you think

To sort by a column chosen by the user, the only correct solution is an allow-list:

SORTABLE_COLUMNS = {"fecha": "fecha", "estado": "estado", "destino": "destino"}

col = SORTABLE_COLUMNS.get(request.args.get("orden"), "fecha")   # a safe default
sql = f"SELECT id, referencia FROM envios WHERE cliente_id = %(c)s ORDER BY {col} DESC"

Here the f-string is safe because col can only take one of three values defined in the code. The dictionary does not translate whatever the user types: if it is not among the keys, it returns the default. You never pass user input straight into a column name, not even "after validating it".

  1. ORMs and their limits

An ORM (object-relational mapper) such as SQLAlchemy generates the SQL for you and parameterises by default:

from modelo import Envio, db

shipments = (db.session.query(Envio)
             .filter(Envio.cliente_id == session["cliente_id"])
             .filter(Envio.referencia.ilike(f"%{reference}%"))
             .order_by(Envio.fecha.desc())
             .limit(200)
             .all())

Real advantages: it is harder to get wrong, the code is more readable and parameterisation is automatic.

But an ORM is not immune, and it is worth knowing where it breaks:

Situation Does the ORM protect you?
Normal filters and comparisons Yes
db.session.execute(text("... " + input)) No: you have concatenated again
filter(text(f"estado = '{x}'")) No
Dynamic column or table names No: use an allow-list
ORDER BY clauses built from text No
Access control No, not in the slightest

The last row is the important one: an ORM prevents SQL injection and does absolutely nothing against IDOR. db.session.query(Envio).get(envio_id) will happily return any customer's shipment. Authorisation is the code's responsibility, always.

  1. Least privilege in the database

Even if the application were perfect, there is a second line of defence that MiRutalia does not have today: the account the application uses to connect to PostgreSQL is a superuser.

The consequences, if an injection slips through:

With a superuser With a least-privilege account
Read any table, including payroll or any other database in the instance Only the granted tables
DROP TABLE, TRUNCATE None of that
Read files from the server (pg_read_file) No
Write files and, in some configurations, run commands No
Create database users No
Read the password hashes in pg_shadow No

The fix, applied on srv-db01 (10.10.20.30):

-- 1. A specific account for the application, with no special attributes
CREATE ROLE mirutalia_app WITH LOGIN PASSWORD :'clave' NOSUPERUSER NOCREATEDB NOCREATEROLE;

-- 2. Everything PostgreSQL grants by default is taken away
REVOKE ALL ON DATABASE rutalia FROM PUBLIC;
REVOKE ALL ON SCHEMA public FROM PUBLIC;

-- 3. Only what is needed is granted, table by table
GRANT CONNECT ON DATABASE rutalia TO mirutalia_app;
GRANT USAGE  ON SCHEMA public     TO mirutalia_app;

GRANT SELECT, INSERT, UPDATE ON envios, direcciones, albaranes TO mirutalia_app;
GRANT SELECT                 ON clientes, facturas, tarifas     TO mirutalia_app;
GRANT USAGE  ON ALL SEQUENCES IN SCHEMA public TO mirutalia_app;

-- 4. Explicitly: NO deleting
REVOKE DELETE ON ALL TABLES IN SCHEMA public FROM mirutalia_app;

-- 5. The tables the application must never see
REVOKE ALL ON empleados, nominas, auditoria_interna FROM mirutalia_app;

Comments on the decisions:

  • Line 1: NOSUPERUSER NOCREATEDB NOCREATEROLE is explicit even though it is the default. The documentation lives in the code.
  • Line 2: PostgreSQL historically grants permissions to PUBLIC on the public schema. Revoking them is a step almost everybody forgets, and without it the later GRANTs limit nothing.
  • Line 3: SELECT on facturas but not UPDATE: the portal displays invoices, it does not modify them. INSERT on albaranes because customers upload documents.
  • Line 4: without DELETE, an injection of the form '; DELETE FROM envios; -- does nothing. Legitimate deletions — which at Rutalia are logical deletions flagged in a column — are done with UPDATE.
  • Line 5: even though the application never queries nominas, the engine does not know that. An injection with UNION could. Revoking it explicitly closes that route.

And the same principle applied per row, which in PostgreSQL can be reinforced with row-level security:

ALTER TABLE envios ENABLE ROW LEVEL SECURITY;

CREATE POLICY envios_propios ON envios
    FOR SELECT TO mirutalia_app
    USING (cliente_id = current_setting('app.cliente_id')::int);

With this policy, the database itself refuses to return another customer's rows even if the query asks for them, provided the application sets app.cliente_id at the start of every request. It is genuine defence in depth against IDOR and against injection, because it acts after both. Its downside is complexity: you have to make sure the variable is set correctly on every connection in the pool, and a mistake there breaks the application. For Rutalia it is proposed as phase 2, after the code is fixed.

  1. Injection variants: union, error-based and blind

It is worth knowing the variants, not in order to exploit them, but to understand why "no error is shown" does not mean there is no vulnerability.

Variant How it works What the attacker needs Speed
Union-based Adds a UNION SELECT and reads the data in the response itself The response to display the results Very fast
Error-based Triggers an error whose message contains the data Visible error messages Fast
Blind boolean The page changes depending on whether a condition is true or false Only that the response differs somehow Slow: one bit per request
Blind time-based Uses pg_sleep() so that the response is delayed if the condition holds Nothing visible: measuring the time is enough Very slow, but it always works
Out of band Makes the server perform a DNS or HTTP lookup to the attacker Permissions and network egress Variable

Two practical conclusions:

  1. Hiding error messages is good practice, but it is not a fix. With the blind time-based variant, the attacker extracts data by measuring whether the response takes five seconds or not. It is slow — an automated tool takes hours to pull out a table — but it works against an application that shows nothing.
  2. The out-of-band variant is the one that connects to module 3. If PostgreSQL or the application can make an arbitrary DNS lookup, the attacker exfiltrates data by encoding it in domain names. It is exactly what the egress rules on fw-zgz01 and the signatures on sec-sensor01 from 03-03 are there to detect. A DMZ with no internet egress beyond the essentials turns an exploitable injection into a far less profitable one.

  1. Broken access control: the cliente412 IDOR

We reach vulnerability number 1 on the list and half of hypothesis H4.

IDOR (Insecure Direct Object Reference) is the most common case of broken access control: the application uses an identifier coming from the client to locate a resource, and does not check whether that resource belongs to the person asking for it.

MiRutalia's current code:

# [!] VULNERABLE
@bp.route("/envio/<int:envio_id>")
@require_login
def view_shipment(envio_id):
    shipment = get_shipment(envio_id)      # looks it up by id, nothing more
    if shipment is None:
        abort(404)
    return render_template("envio.html", envio=shipment)

Notice that there is authentication: @require_login. The user has to have logged in. That is exactly what makes this flaw slip past superficial reviews: "the route is protected". It is protected against anonymous users, not against customers looking at other people's shipments.

Exploiting it requires no tooling. It is this:

GET /envio/10412 HTTP/1.1          <- their own shipment: it works, as it should
Cookie: session=...

GET /envio/10413 HTTP/1.1          <- customer 087's shipment: it ALSO works
Cookie: session=...

Changing a number in the address bar. That is all. And with a three-line loop, an attacker walks from 10412 to 99999 and downloads Rutalia's entire operation: destinations, dates, references and, in the detail view, the recipient's contact details.

In the logs of 02-02 we already saw the unmistakable signature of this behaviour: consecutive identifiers queried within seconds by the same session.

  1. Fixing the IDOR and predictable identifiers

The fix has two levels, and you have to do both.

Level 1: check ownership of the resource. We reuse the require_ownership() function we built in 02-02:

from autorizacion import require_permission, require_ownership

@bp.route("/envio/<int:envio_id>")
@require_permission("shipment:view_own")
def view_shipment(envio_id: int):
    shipment = get_shipment(envio_id)
    if shipment is None:
        abort(404)

    # THE LINE THAT CLOSES H4: is it yours, or do you have permission to see everyone's?
    require_ownership(shipment.cliente_id, "shipment:view_all")

    return render_template("envio.html", envio=shipment)

Why this function and not just any if:

  • It checks the instance, not the type. The @require_permission decorator answers "can this role see shipments?"; require_ownership answers "can it see this shipment?". The absence of the second check is the exact definition of IDOR.
  • It allows the legitimate exception: jlopez, with the customer_service role and the shipment:view_all permission, passes without trouble. The control does not break the business.
  • It logs the denial with the specific resource, which is what makes the detection rule possible: more than 5 DENIED_OWNERSHIP events from the same session in 60 seconds → alert.
  • It lives in one single place. Forty views each with their own if is a guarantee that one of them will end up without it.

An even better pattern: make it impossible for the query to return somebody else's data. Instead of looking it up and then checking, you look it up filtering by the owner from the start:

SQL_OWN_SHIPMENT = """
    SELECT * FROM envios
    WHERE id = %(envio_id)s AND cliente_id = %(cliente_id)s
"""

This variant is superior for three reasons: somebody else's shipment simply does not exist as far as that query is concerned, there is no window between the lookup and the check, and it returns a 404 naturally, without revealing whether the resource exists. Its limit is that the roles that genuinely can see everything have to be handled separately, which is solved with two queries or with a conditional parameter.

Level 2: unpredictable identifiers. This does not replace the access check — a random identifier without a check is still an IDOR, just harder to walk through — but it removes trivial enumeration and has an unexpected additional benefit:

Identifier type Example Enumerable Business leak
Sequential 10412 Yes, trivially Yes: it reveals the shipment volume
UUID v4 e7c4a1b2-3f8d-4c91-a0e5-17b3d9c2f4a8 No No
Short random identifier env_8Kd2mQxR No No

The "business leak" column deserves an explanation: if a customer places two shipments a month apart and their identifiers are 10412 and 12890, they know Rutalia has handled around 2,478 shipments that month. A competitor thus obtains the real scale of the business without doing anything illegal. It is what is known as a sequential identifier leak, and it is why public resource identifiers should be opaque.

For MiRutalia, the pragmatic decision is: keep the internal numeric identifier (primary keys, indexes, performance) and add an opaque public identifier that is the one appearing in URLs:

ALTER TABLE envios ADD COLUMN ref_publica TEXT UNIQUE
    DEFAULT 'env_' || encode(gen_random_bytes(9), 'base64');
CREATE INDEX idx_envios_ref_publica ON envios(ref_publica);

  1. Other forms of broken access control

IDOR is the most famous, but the category is wider. These are the ones to review in MiRutalia:

Form Example in MiRutalia Fix
IDOR /envio/10413 require_ownership()
Vertical escalation /admin/clientes reachable without a role check A permission check in every view, not just in the menu
A route left unprotected by oversight /api/v1/envios/exportar with no decorator Deny by default: a global check with a list of public routes
A check only in the interface The "Edit" button is not displayed, but the route POST /envio/10413/editar works Authorisation belongs on the server; hiding is cosmetic
Trusting a hidden field <input type="hidden" name="cliente_id" value="412"> Identity comes from the session
An unconsidered HTTP method GET /envio/borrar/10412 works with no CSRF token Actions with effects always by POST/DELETE and with a token
Directory traversal /descargar?fichero=../../etc/passwd An allow-list of files; never build paths from user input
API access with somebody else's token A token not bound to the customer Validate the token's binding on every call

The structural fix that covers nearly all of them is deny by default at application level:

# app.py - a global check: no route is left unauthorised by oversight
PUBLIC_ROUTES = {"login", "static", "health", "logout", "password_reset"}

@app.before_request
def require_global_authorisation():
    endpoint = request.endpoint
    if endpoint is None:
        abort(404)
    # Public routes are declared EXPLICITLY, by function name
    if endpoint.split(".")[-1] in PUBLIC_ROUTES:
        return
    if "user" not in session:
        abort(401)
    # If the view declares no permission, access is denied: it forces every view to be decorated
    if not getattr(app.view_functions[endpoint], "_permission_declared", False):
        current_app.logger.error("route_without_declared_permission endpoint=%s", endpoint)
        abort(403)
  • before_request runs before any view. It is the safety net.
  • The list of public routes is explicit and short. Adding a public route is a conscious decision that shows up in code review.
  • _permission_declared is an attribute the @require_permission decorator sets on the function. If a developer adds a new view and forgets the decorator, the application denies and logs an error. It is the difference between failing safely and failing silently.

  1. XSS: the three types and why they still exist

XSS (Cross-Site Scripting) is injection, but the interpreter is another user's browser, not the database. The attacker gets their JavaScript to run in the context of the site, with the victim's session.

What that JavaScript can do, which is what explains the severity:

  • Read the session cookie (if it does not have HttpOnly) and send it to the attacker.
  • Make requests as the user: change their delivery address, download their invoices, create a user.
  • Alter what the user sees: a fake payment form inside the genuine site, with the right padlock and the right domain.
  • Log everything they type.

The three types:

Type Where the payload lives Example in MiRutalia Reach
Reflected In the URL; it comes back in the response /buscar?ref=<script>...</script> sent by email One victim per link
Stored Saved in the database A delivery address name containing a script, seen by jlopez in the internal panel Everybody who sees it
DOM-based The server is not involved; it is client-side JavaScript location.hash inserted with innerHTML It depends

The stored one is the most serious and, at Rutalia, the most dangerous for a specific reason: a customer creates a delivery address called Almacén Central<script>...</script>. When jlopez, from customer service, opens the internal panel to handle that order, the script runs with jlopez's session, which holds the customer:view permission over all 400 customers. A customer has just stolen the entire portfolio by exploiting an employee's privileges. This is H4 and H3 at the same time.

An example of vulnerable code in MiRutalia, a template somebody "fixed" one day:

<!-- [!] plantillas/envio.html - VULNERABLE -->
<h2>Shipment {{ envio.referencia }}</h2>
<p>Delivery address: {{ envio.direccion | safe }}</p>
<div id="notes">{{ envio.notas | safe }}</div>

Jinja2's |safe filter literally means "do not escape this, I trust its contents". It usually gets added because a legitimate field contained an & or a <br> and "it looked wrong". And that thirty-second decision opens the door.

  1. Contextual output encoding and the danger of |safe

The defence against XSS is not filtering the input: it is encoding the output according to the context into which the data is inserted.

The same string is dangerous in a different way in each place:

Context Example Encoding needed Danger
HTML text <p>DATA</p> HTML entities: < → &lt; <script>
HTML attribute <input value="DATA"> Entities + mandatory quotes " onmouseover="alert(1)
Inside <script> var x = "DATA"; JavaScript encoding, or better: do not do it ";alert(1);//
URL / href <a href="DATA"> URL encoding + validate the scheme javascript:alert(1)
CSS style="color: DATA" CSS encoding, or better: do not do it Expressions and url()

The most useful practical rule: never insert user data inside <script>, inside an event attribute (onclick) or inside CSS. If JavaScript needs a value, pass it through a data- attribute and read it with dataset:

<!-- [OK] CORRECT -->
<div id="shipment" data-reference="{{ envio.referencia }}"></div>
<script>
  const ref = document.getElementById('shipment').dataset.reference;  // safe: it is text
</script>

MiRutalia's fixed template:

<!-- [OK] plantillas/envio.html - FIXED -->
<h2>Shipment {{ envio.referencia }}</h2>
<p>Delivery address: {{ envio.direccion }}</p>
<div id="notes">{{ envio.notas }}</div>

<a href="{{ url_for('shipments.invoice', ref=envio.ref_publica) }}">View invoice</a>

What changes and why it works:

  • The |safe filters are removed. Jinja2 escapes automatically in .html files thanks to autoescape, which Flask enables by default. Without |safe, a <script> in the address name renders as visible, harmless text: &lt;script&gt;.
  • url_for instead of building the URL by hand: it generates the path correctly encoded and avoids injection into the href.
  • If some HTML genuinely had to be allowed — bold text in the notes, for example — the solution is not |safe, but sanitising with a specialised library that applies an allow-list of tags and attributes:
import bleach

ALLOWED_TAGS = ["b", "i", "em", "strong", "br", "p"]

clean_notes = bleach.clean(
    user_notes,
    tags=ALLOWED_TAGS,
    attributes={},          # no attributes at all: goodbye onclick and style
    strip=True              # removes what is not allowed instead of escaping it
)

And a check that belongs in any MiRutalia review:

# Where has automatic escaping been switched off?
grep -rn "| *safe\|Markup(\|autoescape *= *False\|{% *autoescape *false" \
     /var/www/mirutalia/plantillas/ /var/www/mirutalia/*.py

Every result of that grep must have a written justification. In MiRutalia there are seven; after the review there are none.

  1. DOM-based XSS and the part the server never sees

There is a variant no server-side defence detects, because the data never reaches the server:

// [!] VULNERABLE - in MiRutalia's JavaScript
const filterText = decodeURIComponent(location.hash.substring(1));
document.getElementById('summary').innerHTML = 'Filtering by: ' + filterText;

With the URL https://mirutalia.example/envios#<img src=x onerror=alert(1)>, the browser runs the code. And what follows the # is not sent to the server: it does not appear in nginx's logs, a WAF does not see it and Suricata does not see it. It is invisible to the entire perimeter defence.

The fix is to use the correct API:

// [OK] FIXED
const filterText = decodeURIComponent(location.hash.substring(1));
document.getElementById('summary').textContent = 'Filtering by: ' + filterText;

textContent inserts text; innerHTML interprets HTML. That is the whole difference.

The dangerous functions to look for in any application's JavaScript:

Dangerous Safe alternative
innerHTML, outerHTML textContent
document.write() DOM manipulation
eval(), new Function() Never
setTimeout("code") (with a string) setTimeout(function)
element.setAttribute('onclick', ...) addEventListener
location = userValue Validate the scheme first
grep -rn "innerHTML\|document\.write\|eval(\|new Function(" /var/www/mirutalia/static/js/

  1. CSRF: the synchroniser token and SameSite

CSRF (Cross-Site Request Forgery) exploits the fact that the browser automatically sends the site's cookies on any request addressed to it, wherever it comes from.

The scenario at Rutalia:

sequenceDiagram
    participant V as Nuria (browser)
    participant M as mirutalia.example
    participant A as attacker-site
    V->>M: Logs in (valid session cookie)
    Note over V: In another tab, opens a link received by email
    V->>A: GET /oferta-transporte
    A-->>V: HTML with a hidden, self-submitting form
    V->>M: POST /direccion/cambiar (with Nuria's cookie!)
    M-->>V: 200 OK - delivery address changed
    Note over M: The server cannot tell this request<br/>from a legitimate one: the cookie is valid

The attacker's HTML:

<form action="https://mirutalia.example/direccion/cambiar" method="POST" id="f">
  <input type="hidden" name="street" value="123 Fake Street">
  <input type="hidden" name="city" value="Nowhere">
</form>
<script>document.getElementById('f').submit();</script>

Nuria sees nothing. The request leaves her browser with her session cookie, and MiRutalia processes it as legitimate.

Defence 1: the synchroniser token. The server generates a random value per session, includes it in every form and requires it on receipt. The attacker cannot read it because the same-origin policy prevents them.

# app.py
from flask_wtf.csrf import CSRFProtect

csrf = CSRFProtect()
csrf.init_app(app)                      # protects ALL POST/PUT/DELETE by default
app.config["WTF_CSRF_TIME_LIMIT"] = 3600
<form method="POST" action="{{ url_for('addresses.change') }}">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  ...
</form>
  • CSRFProtect protects every state-changing method by default. This is the right way round: you have to exclude explicitly, not include. A new route is protected from day one.
  • WTF_CSRF_TIME_LIMIT: the token expires after an hour. It stops a captured token being usable indefinitely, although it has to be balanced against long forms.
  • For AJAX calls, the token is sent in an X-CSRFToken header.

Defence 2: SameSite on the cookie. It is a browser-side defence, and complementary:

Value Behaviour Effect
Strict The cookie is never sent from another site Maximum protection; it breaks arrival from external links
Lax Sent on top-level navigation with GET, not on cross-site POST The right balance; it is the default in modern browsers
None Always sent (requires Secure) Only for cross-site integrations; it has to be justified

And the third leg, which is a design matter: actions with effects never by GET. If GET /envio/borrar/10412 works, all it takes is for the victim to load an <img src="..."> for it to run, and no form token is involved. HTTP verbs have semantics: GET reads, POST/PUT/DELETE modify.

Do I still need the token if I have SameSite=Lax? Yes. SameSite depends on the user's browser, not on your server; there are old browsers, and there are scenarios where it is not enough. Defence in depth requires both.

  1. Cryptographic failures: the secrets in config.py and the Git history

This is the file we have been carrying since 02-04 and which in 04-01 we left with 640 permissions, warning that the underlying problem was still there:

# config.py - what is in MiRutalia TODAY, and it is in Git
DB_PASSWORD = "Rutalia2022!"
SECRET_KEY  = "clave-secreta-mirutalia-2024"
AES_KEY     = b"0123456789abcdef0123456789abcdef"

Four problems, of differing severity:

  1. They are in the code. Anybody with access to the repository has them: the three developers, Marta's laptop, the copy of the repository on the integration server.
  2. They are in the Git history. And this is what many people do not understand: deleting them in a new commit does not remove them. They remain in every earlier commit, for ever, and are recovered with one command.
  3. SECRET_KEY signs Flask's session cookies. Whoever knows it can forge a valid session cookie for any user, an administrator included. No password needs to be stolen.
  4. AES_KEY encrypts the nightly export to S3 (cifrar_clientes.py). Whoever has it decrypts the entire customer portfolio from the cloud copy, without touching any Rutalia system. This is picked up again in 04-04.

Checking the scope, which is the first step:

# In which commits does the file appear, and since when?
git log --oneline --follow -- config.py | tail -5

# Which secrets are in the WHOLE history, not just in the current version?
git log -p --all -S "SECRET_KEY" -- config.py | grep -E "^\+.*SECRET_KEY"

# Who has cloned the repository? (if there is a Git server with logging)
  • --follow tracks the file even if it has been renamed.
  • -S "string" is the key option: it looks for the commits in which the number of occurrences of that string changed. It is the way to find when a secret was introduced and when it was removed.

The fix, in the right order (and the order matters):

# config.py - FIXED
import os

def _required(name: str) -> str:
    """Fail at start-up if a secret is missing. Never a default value."""
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"Missing mandatory environment variable: {name}")
    return value

DB_PASSWORD = _required("MIRUTALIA_DB_PASSWORD")
SECRET_KEY  = _required("MIRUTALIA_SECRET_KEY")
AES_KEY     = bytes.fromhex(_required("MIRUTALIA_AES_KEY"))

SESSION_COOKIE_SECURE   = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = "Lax"
PERMANENT_SESSION_LIFETIME = 3600
  • _required accepts no default values. An os.environ.get("SECRET_KEY", "dev") is the pattern that ends with a development key in production, and it is surprisingly common. It is better for the application not to start than for it to start with a known key.
  • AES_KEY is read as hexadecimal and converted to bytes: a binary key in an environment variable causes encoding problems.

The variables are delivered through the systemd unit, with an environment file with restrictive permissions:

# /etc/systemd/system/mirutalia.service
[Service]
User=mirutalia
Group=mirutalia
EnvironmentFile=/etc/mirutalia/secretos.env      # chmod 600, owned by root
ExecStart=/opt/mirutalia/venv/bin/gunicorn -c /etc/mirutalia/gunicorn.conf.py app:app
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/mirutalia/uploads

The last four directives are the hardening of 04-01 applied to the service: no privilege elevation, a private /tmp, a read-only filesystem except for the uploads path, and no access to home directories.

And the step that cannot be skipped: because the secrets have been exposed, they must be considered compromised and all rotated:

Secret Action Side effect
DB_PASSWORD Change it in PostgreSQL and in the environment A service restart
SECRET_KEY Generate a new one from 32 random bytes It closes every session: people have to be warned
AES_KEY A new key and re-encryption of the S3 exports A planned process; see 04-04

And, going forward, an automatic control that prevents a repeat:

# .pre-commit-config.yaml - stops secrets being pushed to the repository
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.18.0
    hooks:
      - id: gitleaks

This hook scans every commit before it is created and rejects it if it detects something that looks like a credential. The cost is ten minutes of configuration. The complete secure development process is the subject of 08-01.

  1. Security misconfiguration

A run-through of the configuration flaws MiRutalia has and that can be fixed in an afternoon:

Flaw Check Fix
DEBUG=True in production curl triggers an error and returns the traceback FLASK_DEBUG=0; Flask's debugger allows code execution
Verbose error messages A 500 error with a traceback and the SQL query Generic error handlers
Directory listing in nginx GET /static/ returns the index autoindex off;
Server header with the version curl -I shows nginx/1.22.1 server_tokens off;
/.git/ reachable curl https://mirutalia.example/.git/config Block it in nginx
Backup files reachable config.py.bak, .env.old Block the extensions and clean up
Unnecessary HTTP methods OPTIONS, TRACE, PUT Limit the allowed methods
Outdated dependencies pip list --outdated Update; see 06-04

The error handlers in Flask:

@app.errorhandler(500)
def internal_error(e):
    # The detail goes to the LOG, with an identifier so it can be correlated
    error_id = uuid.uuid4().hex[:12]
    current_app.logger.exception("internal_error id=%s path=%s", error_id, request.path)
    # To the user, the bare minimum
    return render_template("error.html", id_error=error_id), 500

The error identifier is a piece of good engineering: the user can ring support saying "error 3f8a1c2d9e04" and Diego finds the full traceback in the log without the user ever having seen a line of code or a table name.

And the blocking in nginx, which is added to the hardened configuration from 03-02:

server_tokens off;                      # hides the version in headers and errors
autoindex off;                          # no directory listings

location ~ /\.(git|env|svn|ht) {        # blocks .git, .env, .svn, .htaccess
    deny all;
    return 404;                         # 404, not 403: it does not confirm existence
}

location ~ \.(bak|old|orig|save|swp|sql|log)$ {
    deny all;
    return 404;
}

if ($request_method !~ ^(GET|HEAD|POST|PUT|DELETE)$) {
    return 405;
}

A note on style: returning 404 instead of 403 on blocked routes avoids confirming to the attacker that the resource exists. It is a small difference that saves you from appearing in the results of an automated scan.

  1. SSRF: when the server makes the request for you

SSRF (Server-Side Request Forgery) happens when the application makes an HTTP request to a URL the user controls. The attacker cannot reach those destinations, but the server can: it is inside the network.

MiRutalia has a function like this: it generates the preview of a delivery note hosted on the customer's own system.

# [!] VULNERABLE
@bp.route("/albaran/previsualizar")
def preview():
    url = request.args.get("url")
    response = requests.get(url, timeout=5)     # the server goes wherever it is told
    return Response(response.content, mimetype="application/pdf")

What an attacker can ask for from srv-web01, which sits in the DMZ:

URL What it gets them
http://10.10.20.30:5432/ Probing PostgreSQL in the server VLAN
http://10.10.20.40:8080/ The unsupported ERP
http://127.0.0.1:8000/admin The local gunicorn, bypassing nginx and its rules
http://169.254.169.254/latest/meta-data/ The cloud instance's credentials (see 04-04)
file:///etc/passwd Local files, if the HTTP client allows it
http://192.0.2.66/?datos=... Out-of-band exfiltration

The fix, with an allow-list and validation after resolving the name:

import ipaddress, socket
from urllib.parse import urlparse

ALLOWED_DOMAINS = {"albaranes.cliente-ejemplo.example", "docs.otro-cliente.example"}

def is_safe_url(url: str) -> bool:
    p = urlparse(url)
    # 1. HTTPS only: no file://, gopher://, ftp://
    if p.scheme != "https":
        return False
    # 2. Domain on the allow-list; no odd port
    if p.hostname not in ALLOWED_DOMAINS:
        return False
    if p.port not in (None, 443):
        return False
    # 3. Resolve and check that NO resolved IP is internal
    try:
        infos = socket.getaddrinfo(p.hostname, 443)
    except socket.gaierror:
        return False
    for info in infos:
        ip = ipaddress.ip_address(info[4][0])
        if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:
            return False
    return True


@bp.route("/albaran/previsualizar")
@require_permission("delivery_note:view")
def preview():
    url = request.args.get("url", "")
    if not is_safe_url(url):
        current_app.logger.warning("ssrf_blocked url=%s ip=%s", url[:200], request.remote_addr)
        abort(400)
    response = requests.get(url, timeout=5, allow_redirects=False, stream=True)
    ...

The critical points, and here the devil is in the detail:

  • Check the scheme first: file://, gopher:// and dict:// are known vectors.
  • ip.is_link_local covers 169.254.169.254, the address of the public clouds' metadata service. It is the number one target of an SSRF in cloud environments, because it returns temporary credentials.
  • allow_redirects=False is essential: without it, the allowed domain can return a 302 towards http://169.254.169.254/ and the validation becomes useless. This is the most common mistake when fixing an SSRF.
  • Even so, a known race condition remains (DNS can return a different IP between the validation and the request). The genuinely robust defence is to complement it with the network: rules on fw-zgz01 that stop srv-web01 initiating connections towards the internal VLANs and towards 169.254.0.0/16. It is the direct application of what we learned in 03-04: the application defence and the network defence cover each other.

  1. Insecure deserialisation

MiRutalia caches the calculated routes using pickle:

# [!] VERY DANGEROUS
import pickle
data = pickle.loads(cache.get(f"ruta:{envio_id}"))

pickle is not a data format: it is an execution format. Deserialising a pickle object can run arbitrary code by design, not by flaw. If an attacker can write to the cache — for example, because the memcached we found in 04-01 was exposed without authentication — they control the server.

The rule is short: never deserialise data that is not absolutely trusted, and pickle is never trusted if the data travels or is stored outside the process.

# [OK] CORRECT: a data format, not a code format
import json
data = json.loads(cache.get(f"ruta:{envio_id}") or "{}")
Format Does it run code? Use
pickle (Python) Yes, by design Only within the process, never with external data
json No Recommended
YAML with yaml.load() Yes Always use yaml.safe_load()
XML with external entities File disclosure (XXE) Disable external entities
Java/.NET serialisation Yes A classic remote execution vector

If the serialised data has to leave the process and come back, and cannot be JSON, the protection is to sign it with HMAC using the technique from 02-05 and verify the signature before deserialising.

  1. File upload: the delivery notes in PDF

Rutalia's customers upload signed delivery notes as PDFs. It is the feature with the most ways of going wrong in the entire application.

What can go wrong and how each route is closed:

Risk What happens Control
Uploading a .php/.py and running it Remote code execution Store outside the web root; serve through a view
A faked extension (albaran.pdf.exe) The user downloads and runs it Validate the real type; rename it
Path traversal in the name (../../etc/cron.d/x) Arbitrary write Never use the original name
A huge file Denial of service, full disk A size limit in nginx and in Flask
A decompression bomb Resource exhaustion Limits and scanning
A PDF with JavaScript or malware It infects whoever opens it Antivirus scanning (04-02)
XSS through SVG or HTML served inline A script on the portal's domain Content-Disposition: attachment and X-Content-Type-Options
Overwriting an existing file Corruption or impersonation A generated name, never the user's

A correct implementation:

import os, uuid, magic          # python-magic reads the REAL type from the content
from werkzeug.utils import secure_filename

UPLOAD_DIR = "/var/lib/mirutalia/uploads"     # OUTSIDE nginx's root
ALLOWED_TYPES = {"application/pdf": ".pdf",
                 "image/jpeg": ".jpg",
                 "image/png": ".png"}
MAX_SIZE = 10 * 1024 * 1024                    # 10 MB

@bp.route("/albaran/subir", methods=["POST"])
@require_permission("delivery_note:upload")
def upload_delivery_note():
    f = request.files.get("delivery_note")
    if f is None or f.filename == "":
        abort(400)

    # 1. Read a sample and determine the REAL type from its content
    header = f.stream.read(2048)
    f.stream.seek(0)
    file_type = magic.from_buffer(header, mime=True)
    if file_type not in ALLOWED_TYPES:
        current_app.logger.warning("upload_rejected type=%s customer=%s",
                                   file_type, session["cliente_id"])
        abort(400)

    # 2. A server-generated name: the user's is NOT used for the path
    stored_name = f"{uuid.uuid4().hex}{ALLOWED_TYPES[file_type]}"
    target = os.path.join(UPLOAD_DIR, stored_name)

    # 3. Save with restrictive permissions and no execute bit
    f.save(target)
    os.chmod(target, 0o640)

    # 4. Keep the original name ONLY as metadata, escaped when displayed
    save_delivery_note(cliente_id=session["cliente_id"],
                       stored_name=stored_name,
                       original_name=secure_filename(f.filename)[:120],
                       file_type=file_type, size=os.path.getsize(target))
    return redirect(url_for("delivery_notes.list"))

And the download, which is the other half of the problem:

@bp.route("/albaran/<uuid:albaran_id>/descargar")
@require_permission("delivery_note:view")
def download_delivery_note(albaran_id):
    note = get_delivery_note(albaran_id)
    if note is None:
        abort(404)
    require_ownership(note.cliente_id, "delivery_note:view_all")   # again: without this, IDOR

    return send_from_directory(
        UPLOAD_DIR, note.stored_name,
        as_attachment=True,                   # forces a download, not execution in the browser
        download_name=note.original_name,     # the user sees their original name
        mimetype=note.file_type,              # the stored type, not the one declared by the client
    )

The four key decisions, in one sentence each:

  1. The files live outside the web root, so nginx cannot serve them directly even if somebody guesses the path: they always go through the authorisation check.
  2. The storage name is generated by the server (a UUID), which eliminates path traversal and overwriting at the root.
  3. The type is determined from the content, not from the extension or from the Content-Type sent by the client, which is data the attacker controls.
  4. as_attachment=True stops an SVG or an HTML file being rendered on the portal's domain, which would be a textbook stored XSS.

And the size limit, in both layers:

app.config["MAX_CONTENT_LENGTH"] = 10 * 1024 * 1024
client_max_body_size 10m;      # nginx rejects it before it reaches the application

  1. Session management: cookies versus JWT

After authenticating, the user needs the application to remember them. There are two approaches, and the choice has consequences.

Server-side session (cookie with an identifier) JWT (self-contained token)
What the client stores An opaque identifier The user's data, signed
Where the state lives On the server (Redis, a database) In the token itself
Immediate revocation Trivial: delete the session Hard: the token is valid until it expires
Horizontal scaling Requires a shared store Requires no state
Size Small Larger, on every request
Typical risks Session fixation, cookie theft alg: none, a weak key, not validating the issuer, storing it in localStorage

The decision for MiRutalia: server-side sessions for the web portal, tokens for the API (section 30). The reasons:

  • Rutalia needs to be able to close sessions instantly: when a customer reports unauthorised access, when an employee leaves, when an incident is detected. With a one-hour JWT, an attacker with a stolen token is still inside for an hour even after the account is disabled.
  • The portal does not have the scaling problem that justifies JWT: a single server and one Redis.

Flask uses client-side signed session cookies by default: the data goes in the cookie, signed with SECRET_KEY. They are signed — they cannot be modified — but they are readable and cannot be revoked. For MiRutalia we switch to server-side sessions:

from flask_session import Session
import redis

app.config.update(
    SESSION_TYPE="redis",
    SESSION_REDIS=redis.Redis(host="127.0.0.1", port=6379, db=0),
    SESSION_PERMANENT=True,
    PERMANENT_SESSION_LIFETIME=timedelta(hours=1),
    SESSION_COOKIE_NAME="mirutalia_sid",
    SESSION_COOKIE_SECURE=True,      # over HTTPS only
    SESSION_COOKIE_HTTPONLY=True,    # JavaScript cannot read it
    SESSION_COOKIE_SAMESITE="Lax",   # CSRF mitigation
)
Session(app)

The three cookie attributes, explained, because they are the cheapest defence there is:

Attribute What it does If it is missing
Secure Sent over HTTPS only The cookie can travel in the clear and be captured
HttpOnly JavaScript cannot read it An XSS steals the session in one line
SameSite=Lax Not sent on POST requests from other sites CSRF is easier
__Host- as a name prefix The browser requires Secure, path / and no Domain Less protection against subdomains

HttpOnly is the reason an XSS is serious but not catastrophic: without it, document.cookie hands the session to the attacker instantly.

  1. Session fixation, expiry and logout

Session fixation: the attacker gets the victim to use a session identifier they know — for example, by sending them a link containing the identifier — and when the victim authenticates, that identifier becomes an authenticated one. The attacker already has it.

The defence is one line, and it is non-negotiable: regenerate the session identifier at the moment of login.

@bp.route("/login", methods=["POST"])
def login():
    user = authenticate(request.form["username"], request.form["password"])
    if user is None:
        # An identical message whether the user does not exist or the password is wrong
        time.sleep(random.uniform(0.15, 0.35))      # levels out the response time
        return render_template("login.html", error="Invalid credentials"), 401

    session.clear()                 # <- DISCARDS the previous session: closes fixation
    session["user"] = user.login
    session["cliente_id"] = user.cliente_id
    session["roles"] = user.roles
    session["created"] = time.time()
    session.permanent = True

    current_app.logger.info("login_ok user=%s ip=%s ua_hash=%s",
                            user.login, request.remote_addr,
                            hashlib.sha256(request.user_agent.string.encode()).hexdigest()[:16])
    return redirect(url_for("home"))
  • session.clear() with server-side sessions causes a new identifier to be generated. It is the fix for fixation.
  • The error message is identical for a non-existent user and a wrong password (section 27).
  • The random wait levels out the response time: without it, checking a password hash takes longer than not checking it, and that difference reveals whether the user exists.
  • A hash of the User-Agent is logged, not the full value: it serves to detect an abrupt browser change within the same session without storing data that helps profile the user.

Expiry: two different clocks, and you need both.

Clock Value in MiRutalia Why
Inactivity 30 minutes A session abandoned on a shared warehouse machine
Absolute 8 hours Limits the value of a stolen session, even if it is kept artificially alive
@app.before_request
def check_expiry():
    if "user" not in session:
        return
    now = time.time()
    if now - session.get("created", 0) > 8 * 3600:          # absolute
        session.clear(); abort(401)
    if now - session.get("last_seen", now) > 1800:          # inactivity
        session.clear(); abort(401)
    session["last_seen"] = now

Logout: it has to invalidate the session on the server, not just delete the cookie. A logout limited to response.delete_cookie() leaves the session alive: whoever has a copy of the cookie is still inside.

@bp.route("/logout", methods=["POST"])       # POST, not GET: protected by CSRF
def logout():
    user = session.get("user")
    session.clear()                          # removes the session from Redis
    current_app.logger.info("logout user=%s", user)
    resp = redirect(url_for("login"))
    resp.delete_cookie("mirutalia_sid")
    return resp

  1. Security headers in nginx

Security headers are instructions to the browser. They do not protect the server: they protect the user and limit the damage of a vulnerability that got past you. It is pure defence in depth.

They are added to the srv-web01 configuration we already hardened with TLS 1.3 and HSTS in 03-02:

server {
    listen 443 ssl;
    http2 on;
    server_name mirutalia.example;

    # --- Already configured in 03-02 ---
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

    # --- New application headers ---
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy "geolocation=(), camera=(), microphone=(), payment=(), usb=()" always;
    add_header Cross-Origin-Opener-Policy "same-origin" always;
    add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests" always;

    server_tokens off;
    ...
}

Header by header:

Header What it does Consequence of omitting it
Strict-Transport-Security Forces HTTPS for 2 years Possible downgrade to HTTP on the first visit
X-Content-Type-Options: nosniff Forbids the browser from guessing the content type A .txt containing HTML can be executed as HTML
Referrer-Policy Limits what is sent in Referer when leaving the site Leaking internal URLs with identifiers to third-party sites
Permissions-Policy Disables browser APIs the site does not use An XSS could ask for the location or the camera
Cross-Origin-Opener-Policy Isolates the browsing context Cross-window attacks
Content-Security-Policy Declares what can be loaded and executed Without the most powerful mitigation against XSS

Two nginx technicalities that cause real problems:

  • always at the end makes the header be sent on error responses too (4xx, 5xx). Without it, a 404 page carries no CSP, and error pages are a common place for reflected content to appear.
  • add_header is not inherited: if a location block has its own add_header, it loses all of the parent block's. It is the number one cause of "I have the headers but they do not appear on some routes". The solution is to repeat them or to include a common file.

And why X-Frame-Options is no longer on the list. That header was used to prevent clickjacking — your site being loaded in an invisible <iframe> over the attacker's site. It has been superseded by frame-ancestors 'none' inside CSP, which does the same thing and also:

X-Frame-Options frame-ancestors
Values DENY, SAMEORIGIN A list of origins with wildcards
Multiple allowed origins No (ALLOW-FROM was never implemented properly) Yes
Standardised De facto Yes, W3C
Precedence Ignored when frame-ancestors is present Takes precedence

You can keep X-Frame-Options: DENY for a few months for compatibility with very old browsers, but the header you have to get right is frame-ancestors.

A check:

curl -sI https://mirutalia.example/ | grep -iE "strict-transport|content-security|x-content-type|referrer|permissions|frame"

  1. Building a CSP for MiRutalia, step by step

The Content Security Policy is the most powerful mitigation against XSS there is, and the one most people configure badly or abandon. It works by declaring where each kind of resource can be loaded from; if an attacker injects a <script>, the browser refuses to run it because it is not in the policy.

A CSP is not written in one go: it is built in four phases.

Phase 1: observe without blocking. It is deployed in report mode, which breaks nothing:

add_header Content-Security-Policy-Report-Only
    "default-src 'self'; report-uri /csp-informe" always;
@app.route("/csp-informe", methods=["POST"])
@csrf.exempt                       # it is sent by the browser, not by a form
def csp_report():
    report = request.get_json(force=True, silent=True) or {}
    current_app.logger.info("csp_violation %s", json.dumps(report)[:2000])
    return "", 204

The violations are collected for two weeks. Typical output from MiRutalia on day one:

{"csp-report": {
  "document-uri": "https://mirutalia.example/envios",
  "violated-directive": "script-src",
  "blocked-uri": "inline",
  "line-number": 412,
  "source-file": "https://mirutalia.example/envios"}}
{"csp-report": {
  "violated-directive": "font-src",
  "blocked-uri": "https://fonts.gstatic.com/s/roboto/v30/..."}}

Phase 2: interpret and fix. MiRutalia's inventory comes out like this:

Violation Origin Decision
47 inline scripts (<script>...</script>) Old code in templates Move them to .js files
23 onclick attributes Templates Replace with addEventListener
Google fonts Design Self-host the fonts
A charting library from a CDN The shipments panel Self-host with a pinned version
data: images in the icons Generated Allow data: only in img-src

The important decision is to move the inline JavaScript into files. It is work — 47 places — but it is what makes a strong CSP possible. The alternative, 'unsafe-inline', completely cancels the protection against XSS: if any inline script is allowed, the attacker's script is allowed too. A CSP with 'unsafe-inline' in script-src is not a CSP; it is a decorative header.

Phase 3: tighten progressively.

# Iteration 1 - still in report mode, but already realistic
default-src 'self';
script-src 'self';
style-src 'self';
img-src 'self' data:;
font-src 'self';
connect-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
report-uri /csp-informe;

What each less obvious directive adds:

  • object-src 'none': blocks <object>, <embed> and <applet>, legacy execution vectors. It should be 'none' in any modern application.
  • base-uri 'self': stops an attacker injecting <base href="http://malo.example/">, which would redirect all the site's relative paths to their server. It is a forgotten and very important directive.
  • form-action 'self': stops an injected form sending the data elsewhere. It turns an XSS into a minor problem for credential theft.
  • frame-ancestors 'none': replaces X-Frame-Options.

Phase 4: move to enforcement and refine. You change Content-Security-Policy-Report-Only to Content-Security-Policy, keeping report-uri so that you carry on receiving reports of what is now genuinely being blocked.

And if in future some unavoidable inline script were needed, the correct way is not 'unsafe-inline', but a different nonce in every response:

set $csp_nonce $request_id;                  # a unique value per request
add_header Content-Security-Policy "script-src 'self' 'nonce-$csp_nonce'; ..." always;
<script nonce="{{ csp_nonce }}">/* only this script runs */</script>

The attacker cannot guess the nonce, which changes on every load, so their injected script is blocked even though inline scripts are allowed.

  1. Rate limiting and user enumeration

User enumeration: if the login form responds differently depending on whether the user exists, the attacker builds a list of valid accounts before starting to try passwords.

Leak route Revealing response Fix
The error message "User not found" vs "Incorrect password" A single message: "Invalid credentials"
The response time 250 ms if it exists (the hash is computed), 8 ms if not Always compute a hash, or level it out with a wait
Account registration "That email address is already registered" A neutral message and confirmation by email
Password recovery "That account does not exist" "If the account exists, an email has been sent"
The status code or length 401 vs 404, different sizes Identical responses

The fix for the timing leak, which is the subtlest:

from argon2 import PasswordHasher
ph = PasswordHasher()
# The hash of a password nobody uses, precomputed at start-up
DECOY_HASH = ph.hash("this-account-does-not-exist-" + os.urandom(8).hex())

def authenticate(login: str, password: str):
    user = find_user(login)
    if user is None:
        ph.verify(DECOY_HASH, password)   # spends the SAME time as a real verification
        return None                       # (it raises an exception; caught outside)
    ...

Rate limiting: without it, an attacker tries thousands of passwords a minute. It is applied in two layers.

In nginx, the first barrier:

# Limiting zones: 10 MB of state, key = the client's IP
limit_req_zone $binary_remote_addr zone=login:10m  rate=5r/m;
limit_req_zone $binary_remote_addr zone=general:10m rate=60r/m;
limit_req_zone $binary_remote_addr zone=api:10m    rate=600r/m;

server {
    location /login {
        limit_req zone=login burst=3 nodelay;
        limit_req_status 429;
        ...
    }
    location /api/ {
        limit_req zone=api burst=100;
        ...
    }
    location / {
        limit_req zone=general burst=30 nodelay;
        ...
    }
}
  • $binary_remote_addr uses the binary form of the IP: it takes less memory than the textual one.
  • rate=5r/m on /login: five attempts a minute. Enough for a user who mistypes, not enough for brute force.
  • burst=3 nodelay allows a small burst without delaying legitimate requests.
  • limit_req_status 429: the correct code for "too many requests".

And in the application, the second layer, which is the one that understands the business:

Control Configuration in MiRutalia
Lockout by account 10 failures in 15 min → a 15-minute lockout, with an email to the account holder
Lockout by IP 30 failures in 15 min across different accounts → a 1-hour lockout + an alert
Spraying detection More than 20 different accounts tried from one IP in 1 h → an immediate alert
Progressive delay 1 s, 2 s, 4 s, 8 s after each failure on the same account
CAPTCHA From the fifth failure onwards

The third row is the one that detects the genuinely dangerous attack: password spraying, which tries a single very common password against many accounts. It does not trigger the per-account lockout — each account only receives one attempt — and it is the attack that succeeds most often against organisations without MFA. Rutalia is in exactly that position until the MFA plan of 02-03 reaches its phase 4.

A note on X-Forwarded-For: because nginx sits in front, the application sees 127.0.0.1 as the source IP unless it is configured properly. You have to pass the real IP and trust only your own proxy; accepting any X-Forwarded-For lets the attacker spoof their IP and bypass the lockouts.

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)   # ONE single proxy

The x_for=1 matters: it states that there is only one trusted proxy and that the last value should be taken, not the one the client might have injected.

  1. WAF: what it adds, what it does not and why it does not replace correct code

A WAF (web application firewall) inspects HTTP requests and blocks the ones matching attack patterns. It sits in front of the application, in nginx or as a service.

What it genuinely adds:

Benefit Comment
Virtual patching When a CVE appears in Flask and you cannot deploy today, a rule blocks it until Sunday
It cuts out automated noise Most hostile traffic is mass-produced and unsophisticated
Visibility It logs attempts you would not otherwise see
Rate limiting and reputation It usually includes bot and known-IP control

What it cannot do, and this is what has to be clear:

Limitation Why
Stop an IDOR GET /envio/10413 is a perfectly normal request. The WAF does not know whose shipment that is
Stop the abuse of legitimate permissions (H3) jlopez looking up 300 customers is 300 valid requests
See DOM-based XSS What follows the # never reaches the server
Resist evasion Alternative encodings, fragmentation, interleaved SQL comments
Replace the fix A badly tuned WAF blocks real customers and does not block the attacker who knows how to evade it

The sentence that sums up the section: a WAF is an airbag, not a brake. It reduces the damage when something fails; it does not prevent the crash.

A starting configuration with ModSecurity and the OWASP Core Rule Set (CRS):

modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
# /etc/nginx/modsec/main.conf
Include /etc/nginx/modsec/modsecurity.conf
Include /etc/nginx/modsec/coreruleset/crs-setup.conf
Include /etc/nginx/modsec/coreruleset/rules/*.conf

# Phase 1: DETECT ONLY for 4 weeks
SecRuleEngine DetectionOnly

SecAuditLog /var/log/nginx/modsec_audit.log
SecAuditLogParts ABIJDEFHZ

# Paranoia level 1 (the default): few false positives
SecAction "id:900000,phase:1,pass,nolog,setvar:tx.paranoia_level=1"
# Anomaly score thresholds
SecAction "id:900110,phase:1,pass,nolog,\
  setvar:tx.inbound_anomaly_score_threshold=5,\
  setvar:tx.outbound_anomaly_score_threshold=4"

How it is deployed without causing an availability incident:

  1. SecRuleEngine DetectionOnly for four weeks. It only logs.
  2. Review the false positives. In MiRutalia there will be several: the PDF delivery notes trigger file upload rules, and the comment fields with special characters trigger injection rules.
  3. Write specific exclusions by rule and by route, never disable whole families:
# Exclude the "request body too large" rule ONLY on the delivery note upload
SecRule REQUEST_URI "@beginsWith /albaran/subir" \
    "id:1000010,phase:1,pass,nolog,ctl:ruleRemoveById=200002"
  1. Move to SecRuleEngine On in batches, starting with the least critical routes.
  2. Never raise the paranoia level above 1 or 2 without a dedicated tuning process.

And the golden rule: every finding blocked by the WAF must open a remediation ticket in the code. If the vulnerability is still there and one day the WAF fails, is updated or is evaded, you are exposed again. The WAF buys time; it does not give it away.

  1. Application security logging

Here the circle closes with 02-02 and 03-03: the application is the only place from which certain attacks are visible.

What MiRutalia must log:

Event Why
Successful and failed logins, with IP and time The basis of nearly every investigation
Logout and expiry It bounds the sessions
Authorisation denials, with the resource Detects an IDOR being probed
Granted access to sensitive data Detects H3: the insider generates no denials
Changes of password, email and account details Account takeover
Creations, deletions and permission changes Accountability
Input validation errors Probing of the application
File uploads and downloads Exfiltration
Access to the canary customer C9999 A mass query or export of the portfolio
API usage: token, route, volume Abuse of integrations

What it must never log:

Never Why
Passwords, not even failed ones A failure is often another account's password, or the right one mistyped
Full session or API tokens The log becomes a credential store
Full cookies The same
Account numbers, cards, identity documents Data minimisation (06-03)
Full request bodies with personal data Volume and risk with no value
Literal search terms They can contain personal data; the length is enough

A structured format, so that it can be queried:

import logging, json

class JSONFormatter(logging.Formatter):
    def format(self, record):
        base = {
            "ts": self.formatTime(record, "%Y-%m-%dT%H:%M:%S%z"),
            "level": record.levelname,
            "event": record.getMessage(),
            "request_id": getattr(record, "request_id", None),
            "user": getattr(record, "user", None),
            "ip": getattr(record, "ip", None),
        }
        return json.dumps(base, ensure_ascii=False)

An example of the output, with a sequence that matters:

{"ts":"2027-04-14T09:12:03+0200","level":"INFO","event":"login_ok","user":"cliente412","ip":"203.0.113.44","request_id":"a91f3c"}
{"ts":"2027-04-14T09:12:41+0200","level":"WARNING","event":"ownership_access_denied resource=envio:10433","user":"cliente412","ip":"203.0.113.44","request_id":"a91f40"}
{"ts":"2027-04-14T09:12:43+0200","level":"WARNING","event":"ownership_access_denied resource=envio:10434","user":"cliente412","ip":"203.0.113.44","request_id":"a91f41"}
{"ts":"2027-04-14T09:12:45+0200","level":"WARNING","event":"ownership_access_denied resource=envio:10435","user":"cliente412","ip":"203.0.113.44","request_id":"a91f42"}
{"ts":"2027-04-14T09:13:02+0200","level":"CRITICAL","event":"canary_queried resource=cliente:C9999","user":"cliente412","ip":"203.0.113.44","request_id":"a91f55"}

How to read it: three denials on consecutive identifiers within four seconds — the unmistakable signature of enumeration — and, twenty seconds later, a query on the canary customer C9999. The canary we planted in 03-03 does its job here: C9999 does not exist as a real customer, no legitimate operation touches it, and a query on it means somebody is walking through the whole portfolio. False positives: practically zero.

Implementing the canary in code is trivial and worth its weight in gold:

CANARY_CUSTOMERS = {"C9999"}

def get_customer(code: str):
    if code in CANARY_CUSTOMERS:
        current_app.logger.critical(
            "canary_queried resource=cliente:%s user=%s ip=%s",
            code, session.get("user"), request.remote_addr)
        alert_security(f"Canary {code} queried by {session.get('user')}")
        # The decoy record is returned as normal: the attacker is not warned
    return query_customer(code)

The logs are sent to a centralised store outside srv-web01 — because the logs of a compromised machine are not trustworthy — and exploiting them as a SIEM, with correlation and metrics, is the subject of 08-04.

  1. MiRutalia API security

Around 30 of the 400 customers integrate their systems with Rutalia through the API: they check the status of their shipments and create consignments automatically. The API has the same problems as the portal, plus a few of its own.

Aspect Decision for MiRutalia
Authentication A token per customer, with an identifiable prefix (rtl_live_...), stored hashed in the database
Transport HTTPS only. For the ERP supplier, mTLS as in 03-02
Authorisation Every call checks ownership of the resource: the same require_ownership() calls
Rate limiting 600 requests/minute per token, with X-RateLimit-* headers
Versioning /api/v1/; breaking changes create a /v2/
Expiry and rotation A token valid for 12 months, with a warning 30 days out; rotation without downtime
Logging Every call: the token (last 4 characters), route, status code, volume
Revocation Immediate, from the administration panel

The tokens are stored hashed, just like passwords:

import secrets, hashlib

def create_token(customer_id: int) -> str:
    # 32 bytes of entropy; the prefix makes a leak in a public repository identifiable
    raw = "rtl_live_" + secrets.token_urlsafe(32)
    # SHA-256 is stored: if the database is stolen, no usable tokens are obtained.
    # SHA-256 is enough here (unlike with passwords) because the token is already random
    # and high-entropy: there is no dictionary to try.
    store_token(customer_id, hashlib.sha256(raw.encode()).hexdigest())
    return raw          # it is shown ONCE only, when it is created

The most serious API mistake: excessive data exposure. It is so common that it deserves its own example.

# [!] BAD: the whole object is returned
@bp.route("/api/v1/envios/<uuid:ref>")
def api_shipment(ref):
    shipment = get_shipment_by_ref(ref)
    return jsonify(shipment.__dict__)      # what is in there?

The real response:

{
  "id": 10412, "ref_publica": "env_8Kd2mQxR", "cliente_id": 412,
  "destino": "Valencia", "estado": "en_transito",
  "coste_interno": 42.18,
  "margen": 0.31,
  "conductor_dni": "12345678Z",
  "conductor_telefono": "600123456",
  "notas_internas": "Customer in arrears, require payment in advance",
  "created_by": "jlopez"
}

What has leaked: Rutalia's commercial margin, the driver's identity document number and phone number (an employee's personal data) and an internal note that, as well as being sensitive commercial information, is exactly the kind of data whose disclosure to the data subject can end in a complaint to the AEPD.

And here is the nuance that defines the flaw: it does not matter that the web interface does not display those fields. The API returns them, and the API is what the customer consumes. Filtering on the client is not filtering.

The fix is to declare explicitly what goes out:

from marshmallow import Schema, fields

class PublicShipmentSchema(Schema):
    """The output contract: if a field is not here, it does not go out. Full stop."""
    referencia = fields.String(attribute="ref_publica")
    destino    = fields.String()
    estado     = fields.String()
    fecha      = fields.DateTime()
    entrega_estimada = fields.DateTime(attribute="eta")

@bp.route("/api/v1/envios/<string:ref>")
@require_api_token
def api_shipment(ref):
    shipment = get_shipment_by_ref(ref)
    if shipment is None:
        abort(404)
    require_ownership(shipment.cliente_id, "shipment:view_all")    # in the API too
    return jsonify(PublicShipmentSchema().dump(shipment))

The general principle: an allow-list of output fields, not a list of fields to hide. When somebody adds a comision_comercial column to the table tomorrow, with this schema nothing leaks; with __dict__, it does.

  1. MiRutalia's remediation plan

# Finding Criticality Fix Owner Deadline
1 IDOR in /envio/<id> and 6 other routes (H4) CRITICAL require_ownership() everywhere; a global check Marta Ruiz 7 days
2 Concatenated SQL in the search and 3 other queries CRITICAL Parameterised queries Marta Ruiz 7 days
3 Secrets in config.py and in the Git history CRITICAL Environment variables + rotation of all three Marta + Diego 14 days
4 The PostgreSQL account is a superuser HIGH mirutalia_app with minimum permissions Diego Salas 14 days
5 Seven |safe filters in templates HIGH Remove them; sanitise with bleach where needed Marta Ruiz 14 days
6 No CSRF protection HIGH CSRFProtect + SameSite=Lax Marta Ruiz 14 days
7 Cookies without Secure/HttpOnly; client-side session HIGH Redis sessions + the attributes Marta + Diego 21 days
8 No security headers and no CSP MEDIUM Headers now; CSP in 4 phases Diego Salas 30 / 60 days
9 SSRF in the delivery note preview HIGH An allow-list + egress rules on fw-zgz01 Marta + Diego 21 days
10 pickle in the cache MEDIUM Migrate to JSON Marta Ruiz 30 days
11 File upload with no real type validation HIGH Content-based validation, UUID, outside the web root Marta Ruiz 21 days
12 No attempt limits and no enumeration protection HIGH limit_req + account lockout + uniform messages Diego Salas 14 days
13 The API returns the whole object HIGH Explicit output schemas Marta Ruiz 21 days
14 No application security logging MEDIUM Structured logging + the C9999 canary Marta Ruiz 30 days
15 Dependencies not updated since 2024 MEDIUM Update + a continuous process (08-01) Marta Ruiz 45 days

With one condition Laura imposes that changes the long-term outcome: every fix carries an automated test that fails if the vulnerability comes back.

def test_cannot_view_another_customers_shipment(authenticated_customer_412):
    """Regression for finding 1 (H4). If this turns into a 200, we have reintroduced the IDOR."""
    r = authenticated_customer_412.get("/envio/10413")     # customer 087's shipment
    assert r.status_code in (403, 404)
    assert b"087" not in r.data

def test_sql_injection_does_not_return_other_customers(authenticated_customer_412):
    """Regression for finding 2."""
    r = authenticated_customer_412.get("/envios/buscar?ref=x%25'+OR+'1'%3D'1")
    assert r.status_code in (200, 400)
    assert b"C0087" not in r.data

Without these tests, the fix lasts until the next refactoring.


Common Mistakes and Tips

Mistake 1: believing that validating the input replaces parameterisation. Validation reduces the surface, but the protection against SQL injection is the parameterised query, and the protection against XSS is output encoding. Tip: do both, and do not confuse their roles.

Mistake 2: using f-strings or the % operator inside execute(). It looks like parameterisation and it is not: the string is already concatenated by the time the driver receives it. Tip: the comma is the difference. cur.execute(SQL, parameters), never cur.execute(SQL % parameters).

Mistake 3: thinking an ORM protects you completely. It protects you from injection; it does not protect you from IDOR, from concatenated text(), or from dynamic column names. Tip: authorisation is always the code's responsibility.

Mistake 4: adding |safe because "it looked wrong". It is the number one cause of stored XSS. Tip: if you need HTML from the user, sanitise it with an allow-list library; never switch off escaping.

Mistake 5: 'unsafe-inline' in script-src. It cancels the CSP completely. Tip: move the JavaScript into files; if you cannot, use per-request nonces.

Mistake 6: trusting that the interface hides the button. If the route responds, the functionality exists. Tip: authorisation belongs on the server, in every view; hiding is cosmetic.

Mistake 7: storing secrets in the repository and believing that deleting them removes them. The Git history keeps them for ever. Tip: always rotate exposed secrets and add a hook that stops it happening again.

Mistake 8: deploying a WAF and considering the vulnerabilities fixed. The WAF buys time. Tip: every WAF block opens a ticket in the code.

Mistake 9: logging too much. A log with passwords, tokens and complete personal data is a target in itself. Tip: log the event and the identifier, not the content.

Tip 10: prove the fixes with automated regression tests. It is the only way for a fixed vulnerability not to come back in six months.

Tip 11: prioritise by what you already know you have. The OWASP Top 10 is a general guide; your list of concrete findings is better. In MiRutalia, the IDOR goes first because it is already confirmed.

Tip 12: start every review by looking for the patterns. grep for |safe, for f-strings in execute, for innerHTML, for routes without a decorator. Half an hour of well-aimed grep finds more than a week of disorganised reading.


Exercises

Exercise 1: reviewing vulnerable code

Marta hands you this MiRutalia view for review before pushing it to production:

@bp.route("/factura/<int:factura_id>/descargar")
@require_login
def download_invoice(factura_id):
    conn = get_connection()
    cur = conn.cursor()
    cur.execute("SELECT fichero, cliente_id FROM facturas WHERE id = %d" % factura_id)
    row = cur.fetchone()
    if not row:
        return f"<h1>Invoice {factura_id} not found</h1>", 404
    path = os.path.join("/var/www/mirutalia/static/facturas", row[0])
    return send_file(path)

a) Identify all the vulnerabilities, giving the OWASP category of each one. b) Which is the most serious and why? c) Rewrite the corrected function, commenting on each change. d) Write an automated test that detects the most serious vulnerability if it reappears.

Exercise 2: building the CSP

After two weeks with the CSP in report mode, /csp-informe has collected these violations on the shipments panel:

script-src   inline                                              1,847 times
script-src   https://cdn.ejemplo-graficos.example/chart.min.js      312 times
style-src    inline                                                892 times
font-src     https://fonts.gstatic.com/s/roboto/v30/...             298 times
img-src      https://mapas-proveedor.example/tiles/...              145 times
connect-src  https://api.mapas-proveedor.example/v2/geocode          87 times
frame-src    https://www.youtube.com/embed/tutorial-portal            3 times

a) For each violation, decide: do you fix the code or add it to the policy? Justify it. b) Write the resulting CSP, directive by directive, with a comment on each one. c) Why is it not enough to add 'unsafe-inline' to script-src and be done with it sooner? d) The team says that moving 1,847 inline scripts is unfeasible. What technical alternative do you propose and what condition must it meet to be safe?

Exercise 3: analysing an application log

MiRutalia's log for 22 June 2027 contains this sequence:

{"ts":"2027-06-22T02:14:03+0200","event":"login_failed","user":"admin","ip":"192.0.2.66"}
{"ts":"2027-06-22T02:14:05+0200","event":"login_failed","user":"administrador","ip":"192.0.2.66"}
{"ts":"2027-06-22T02:14:07+0200","event":"login_failed","user":"mruiz","ip":"192.0.2.66"}
{"ts":"2027-06-22T02:14:09+0200","event":"login_failed","user":"dsalas","ip":"192.0.2.66"}
{"ts":"2027-06-22T02:14:11+0200","event":"login_failed","user":"jlopez","ip":"192.0.2.66"}
{"ts":"2027-06-22T02:31:44+0200","event":"login_ok","user":"cliente087","ip":"198.51.100.201"}
{"ts":"2027-06-22T02:31:58+0200","event":"validation_failed fields=['ref']","user":"cliente087","ip":"198.51.100.201"}
{"ts":"2027-06-22T02:32:01+0200","event":"validation_failed fields=['ref']","user":"cliente087","ip":"198.51.100.201"}
{"ts":"2027-06-22T02:32:04+0200","event":"validation_failed fields=['ref']","user":"cliente087","ip":"198.51.100.201"}
{"ts":"2027-06-22T02:33:12+0200","event":"ownership_access_denied resource=envio:10501","user":"cliente087","ip":"198.51.100.201"}
{"ts":"2027-06-22T02:33:14+0200","event":"ownership_access_denied resource=envio:10502","user":"cliente087","ip":"198.51.100.201"}
{"ts":"2027-06-22T02:33:16+0200","event":"ownership_access_denied resource=envio:10503","user":"cliente087","ip":"198.51.100.201"}
{"ts":"2027-06-22T02:41:30+0200","event":"delivery_note_uploaded type=application/pdf size=8402","user":"cliente087","ip":"198.51.100.201"}
{"ts":"2027-06-22T02:41:33+0200","event":"internal_error id=7c3a9f01 path=/albaran/previsualizar","user":"cliente087","ip":"198.51.100.201"}

a) Reconstruct what is happening, in order and by phases. b) Which two things tell you the defences are working? c) Which event would worry you most and what would you investigate immediately? d) Propose three automatic detection rules over this log, with their specific thresholds. e) What is missing from this log that you would like to have?


Solutions

Solution 1

a) Vulnerabilities found:

# Vulnerability OWASP category Where
1 IDOR: cliente_id is fetched but never checked A01 Broken access control require_ownership is missing
2 SQL injection through the % operator A03 Injection "... id = %d" % factura_id
3 Reflected XSS in the error message A03 Injection f"<h1>Invoice {factura_id} ..."
4 Potential path traversal A01 os.path.join with row[0] from the database
5 Files in the web root (/static/facturas) A05 Misconfiguration nginx can serve them without authorisation
6 No permission declaration and no Content-Disposition A01 / A05 @require_login is not @require_permission
7 Connection and cursor never closed Quality / availability No context managers

Number 2 deserves a caveat: because the route declares <int:factura_id>, Flask only accepts integers, so on this specific route the injection is not exploitable. But it is a time bomb: the day somebody changes the route to <string:...> or reuses that pattern in another view, it becomes exploitable. It is fixed anyway, because security cannot depend on a routing detail ten lines away.

On number 5: the subtlest point. If the invoices live in /var/www/mirutalia/static/facturas, nginx serves them directly at https://mirutalia.example/static/facturas/F2026-0871.pdf, without going through Flask and therefore without any authorisation check. The view can be perfectly protected and the files still be public to anybody who guesses the name. And the names follow an obvious pattern.

b) The most serious is the IDOR (1), combined with (5). The reasons:

  • It is exploitable right now, with no tooling: any authenticated customer changes the number and downloads everybody else's invoices.
  • The impact is maximal: an invoice contains the company name, tax number, registered address, amounts, discounts and a breakdown of services. It is commercial information and personal data about the contacts.
  • It affects all 400 customers.
  • And with (5), you do not even need to be authenticated if you guess the file name.

c) The corrected function:

SQL_INVOICE = """
    SELECT fichero, cliente_id, numero
    FROM facturas
    WHERE id = %(factura_id)s
"""

INVOICE_DIR = "/var/lib/mirutalia/facturas"             # (5) OUTSIDE the web root

@bp.route("/factura/<int:factura_id>/descargar")
@require_permission("invoice:view_own")                 # (6) a specific permission, not just login
def download_invoice(factura_id: int):
    with get_connection() as conn:                      # (7) guaranteed closing
        with conn.cursor(cursor_factory=RealDictCursor) as cur:
            cur.execute(SQL_INVOICE, {"factura_id": factura_id})   # (2) parameterised
            row = cur.fetchone()

    if row is None:
        abort(404)                                      # (3) without reflecting the input

    require_ownership(row["cliente_id"], "invoice:view_all")       # (1) CLOSES THE IDOR

    # (4) The stored name is never concatenated straight into the path
    filename = os.path.basename(row["fichero"])         # discards any "../"
    path = os.path.realpath(os.path.join(INVOICE_DIR, filename))
    if not path.startswith(INVOICE_DIR + os.sep):                  # an additional defence
        current_app.logger.error("path_outside_directory id=%s", factura_id)
        abort(404)
    if not os.path.isfile(path):
        abort(404)

    current_app.logger.info("invoice_downloaded number=%s customer=%s",
                            row["numero"], session["cliente_id"])

    return send_file(path, as_attachment=True,
                     download_name=f"{row['numero']}.pdf",
                     mimetype="application/pdf")

A summary of the changes: a parameterised query; a declared permission; an ownership check; files outside the web root; basename plus a prefix check with realpath against path traversal; a generic abort(404) that does not reflect the input; a forced download with a name and type controlled by the server; logging of the access; and resource closing with context managers.

d) Regression tests:

def test_cannot_download_another_customers_invoice(app, customer_412, invoice_of_087):
    """Regression: IDOR in /factura/<id>/descargar."""
    r = customer_412.get(f"/factura/{invoice_of_087.id}/descargar")
    assert r.status_code in (403, 404), "IDOR reintroduced: another customer's invoice is reachable"
    assert b"%PDF" not in r.data, "The contents of another customer's PDF were returned"


def test_invoices_not_accessible_via_static_path(anonymous_client):
    """Regression: the files must not be served from the web root."""
    r = anonymous_client.get("/static/facturas/F2026-0871.pdf")
    assert r.status_code == 404

The second test is as important as the first and almost nobody writes it: it checks the configuration side, not the code side.

Solution 2

a) The decision for each violation:

Violation Decision Justification
script-src inline (1,847) Fix the code Allowing it cancels the CSP. It is the main piece of work and it is non-negotiable
The charting CDN (312) Self-host A third-party CDN is a supply chain dependency: if they are compromised, they run code on your domain (06-04). Self-hosting with a pinned version removes the risk
style-src inline (892) Add it to the policy, with caveats 'unsafe-inline' in styles is far less serious than in scripts: the risk is exfiltration through CSS selectors and visual spoofing, not execution. It is accepted temporarily and its removal is planned
Google fonts (298) Self-host It removes the request to a third party (as well as the data transfer question from 06-03) and one directive from the policy
The supplier's maps (145) Add it to the policy It is necessary business functionality. The specific domain is allowed, never a generic https:
The geocoding API (87) Add it to the policy The same; it goes in connect-src
YouTube (3) Fix: remove the video Three loads in two weeks do not justify opening frame-src to a third-party domain. The video is linked to instead of embedded

b) The resulting CSP:

add_header Content-Security-Policy "
  default-src 'self';
  # No 'unsafe-inline': all the JavaScript in our own files after the fix
  script-src 'self';
  # Inline styles allowed TEMPORARILY. Ticket MIR-418, deadline 2027-12-31
  style-src 'self' 'unsafe-inline';
  # data: for the generated icons; the maps domain for the tiles
  img-src 'self' data: https://mapas-proveedor.example;
  # Self-hosted fonts: our own origin only
  font-src 'self';
  # Our own AJAX + the supplier's geocoding API
  connect-src 'self' https://api.mapas-proveedor.example;
  # No <object>, <embed> or applets
  object-src 'none';
  # No third-party iframes and none of our own
  frame-src 'none';
  # Stops <base> being injected and the relative paths hijacked
  base-uri 'self';
  # Forms can only be submitted to our own site
  form-action 'self';
  # Replaces X-Frame-Options: nobody can embed MiRutalia
  frame-ancestors 'none';
  # Forces HTTPS on any resource still left on http://
  upgrade-insecure-requests;
  # The report is kept so we can see what is now genuinely blocked
  report-uri /csp-informe;
" always;

c) Because 'unsafe-inline' in script-src disables the protection against XSS, which is 90% of a CSP's value. A CSP works because the browser only runs scripts from declared origins; if you declare that any inline script is allowed, the <script>alert(1)</script> an attacker injects is allowed too. The policy would still contribute frame-ancestors, form-action, base-uri and object-src, which is far from nothing, but you would have given up the main point. A CSP with 'unsafe-inline' in scripts gives a false sense of security that is worse than not having one, because it closes the item on the to-do list.

d) The technical alternative is the per-request nonce:

set $csp_nonce $request_id;
add_header Content-Security-Policy "script-src 'self' 'nonce-$csp_nonce'; ..." always;
<script nonce="{{ csp_nonce }}">/* the existing inline script, untouched */</script>

The four conditions it must meet to be safe:

  1. A unique, unpredictable value per response. A fixed or reused nonce is worthless: the attacker copies it from an earlier response. nginx's $request_id qualifies, or it is generated with secrets.token_urlsafe(16) in Flask.
  2. Enough entropy: at least 128 bits.
  3. Never cache the HTML response that contains the nonce, neither in the browser nor in an intermediate proxy. A cached page with its nonce hands every user a valid, known nonce.
  4. The nonce may only appear in <script> tags the server generates, never in content coming from the user. If user data can end up inside a tag with a nonce, everything is lost.

A recommended complement: add 'strict-dynamic', which lets a script with a nonce load other scripts, greatly simplifying applications with module loaders.

But it is worth telling the truth about the effort: 1,847 violations are not 1,847 distinct scripts. They are a few dozen templates loaded many times. The real work is usually two or three days, not the unmanageable project it appears to be. The honest recommendation is to measure first how many unique scripts there are and decide afterwards; the nonce is a legitimate alternative, not an excuse.

Solution 3

a) Reconstruction by phases:

Phase 1 - 02:14, password spraying from 192.0.2.66. Five attempts in eight seconds, each against a different user: admin, administrador, mruiz, dsalas, jlopez. It is not brute force against one account: it is one password tried against several accounts. The last three names are real internal Rutalia users, which indicates the attacker has done prior reconnaissance or obtained them from some leak. The IP is that of the attacker from the canonical scenario.

Phase 2 - 02:31, access with a legitimate customer account. cliente087 logs in successfully from a different IP, 198.51.100.201, seventeen minutes later. There are two possible readings: either it is a legitimate customer working in the middle of the night, or the account is compromised and the attacker has changed origin. The time — 02:31 — and what they do next tip the balance clearly towards the second.

Phase 3 - 02:31-02:32, injection probing. Three validation_failed events on the same ref field within six seconds. Somebody is trying inputs the schema rejects: quotes, UNION, SQL comments. And here is the good news: they never reach the query.

Phase 4 - 02:33, IDOR enumeration. Three ownership_access_denied events on envio:10501, 10502, 10503: consecutive identifiers, two seconds apart. It is the exact signature of probing an IDOR, the same one we saw in 02-02. And all three are denied.

Phase 5 - 02:41, a file upload and an SSRF. They upload an 8 KB PDF — small, more of a decoy than a delivery note — and three seconds later they trigger an internal error on /albaran/previsualizar. The closeness in time is no coincidence: they are probing the preview feature, which is precisely where MiRutalia had the SSRF of section 20.

b) Two things show that the defences are working:

  1. The three validation_failed events: the input schema is rejecting the injection attempts before they reach the database. The fix for finding 2 in the plan is operational.
  2. The three ownership_access_denied events: require_ownership() is preventing the IDOR. The fix for finding 1 — the one that closes H4 — works, and it also generates the log that lets you see the attack. Before the fix, those three requests would have returned 200 and left no trace at all.

It is a good moment to point out something that gets forgotten: a preventive control that also logs is worth twice one that only prevents.

c) The event that worries you most is internal_error id=7c3a9f01 path=/albaran/previsualizar, for three reasons:

  • It is the only event where the attacker got an unexpected response from the application. Everything else is a clean denial; this is an uncontrolled failure.
  • The route is exactly the SSRF one. An error there may mean that the is_safe_url() validation does not cover the case that was sent, or that the outbound request failed in a way that reveals information.
  • An internal error can leak details in the response if the handler is not properly in place.

Immediate investigation:

  1. Find the full traceback by the identifier 7c3a9f01 in the server log: which exception it was, with exactly which URL.
  2. Check on fw-zgz01 and on sec-sensor01 whether srv-web01 initiated any outbound connection at that moment, and to where. If it went towards an internal VLAN or towards 169.254.169.254, the SSRF is exploitable and this is a serious incident.
  3. Retrieve the PDF uploaded at 02:41 and analyse it in the isolated lab, with the precautions from 04-02: look up the hash, do not upload it to any public service.
  4. Review the cliente087 account: contact the real customer during working hours and ask whether anybody in their organisation logged in that night. In the meantime, revoke their sessions.

d) Three detection rules with specific thresholds:

RULE 1 - Password spraying
  Condition: >= 5 login_failed events from the SAME IP against >= 5 DIFFERENT users
             within a 5-minute window.
  Severity: HIGH
  Action: an immediate alert to [email protected] + a 1-hour block of the IP.
  Note: the per-account threshold does NOT fire here; you have to count distinct users per IP.

RULE 2 - IDOR probing
  Condition: >= 3 ownership_access_denied events from the SAME session within 60 s,
             with consecutive resource identifiers (difference <= 5).
  Severity: HIGH
  Action: an alert + closing the session + a temporary lockout of the account.

RULE 3 - Injection probing followed by an internal error
  Condition: >= 3 validation_failed events from the same user within 5 min,
             OR any internal_error on /albaran/previsualizar or /api/*.
  Severity: MEDIUM for the first, CRITICAL for both combined within 15 minutes.
  Action: an alert + preservation of the full request for analysis.

A fourth rule, cross-cutting and very cost-effective: any activity from a customer account between 00:00 and 06:00 generates an informational event. It is not malicious in itself — some customers work at night — but as a scoring factor combined with the other rules it raises the priority. And in this log, all five phases happen between 02:14 and 02:41.

e) What is missing from the log:

Missing Why I would want it
The session identifier (partial, not the cookie) To correlate events from the same session, not just from the same user
A hash of the User-Agent To detect a client change within a session: a sign of hijacking
The country or ASN of the IP cliente087 is a Spanish company; access from another continent is an immediate signal
The result of the request (the HTTP status code) To distinguish what was denied from what was served
The volume of data returned To detect mass extraction: a thousand small legitimate requests are not the same as one of 40 MB
request_id on every event It is on some and missing from others; without it you cannot link the application event to the nginx one
The exact URL that triggered the internal_error Without it you have to go and look for the traceback elsewhere
Logout events To know when the activity really ended
A correlated nginx log To see the requests that never even reached the application (blocked by limit_req or by the WAF)

And, above all, what is missing is for these logs to be in a centralised store outside srv-web01. If the attacker had achieved execution on the server, the first thing they would have done is delete exactly these fourteen lines. That centralisation and how to exploit it are the subject of 08-04.


Conclusion

You have gone into MiRutalia's code and come out with the application transformed. You have now internalised the trust model that orders everything else: every input from the client is hostile, identity comes from the session and authority comes from the server. You know that hidden fields, headers, cookies and JavaScript validation are data the attacker controls, and that a request built with curl goes through none of the browser's controls.

You know how to validate on the server with allow-lists, discarding what is not declared, and you know that validation is the first layer, never the only one. You have the OWASP Top 10 prioritised for this specific portal, with broken access control in first place — ahead of injection — because it is the most frequent, the one no tool detects on its own and the one we already knew existed.

You understand SQL injection from the inside: why concatenation erases the boundary between instruction and data, why parameterisation is not "escaping quotes" but sending the data through another channel, why an f-string inside execute() parameterises nothing, and what to do when the dynamic part is a column name and not a value. You know that an ORM protects against injection and does not protect at all against access control failures. And you have added the second line of defence that was missing: a PostgreSQL account with minimum permissions, with no DELETE and no access to the tables the application must never see, so that an injection that slips through finds a database that lets it do almost nothing.

You have taken apart and repaired the IDOR of hypothesis H4: require_ownership() on every instance, the superior pattern of filtering by owner in the query itself, the global check that denies any view that forgets to declare its permission, and the opaque identifiers that also stop giving away Rutalia's business volume to anybody who can subtract.

You have mastered XSS in its three forms, output encoding by context, why |safe is the number one cause of stored XSS and why the most serious case at Rutalia is the customer who injects a script that runs with jlopez's session. You know that DOM-based XSS never reaches the server and is therefore invisible to the WAF, the logs and Suricata. You understand CSRF, the synchroniser token, SameSite and the design rule that precedes it: actions with effects never by GET.

You have taken the secrets out of config.py, you know that the Git history keeps them for ever, and you know that the fix includes rotating all three because they have to be considered compromised. You know SSRF with the detail that decides whether the fix works — allow_redirects=False and 169.254.169.254 —, you know why pickle is an execution format and not a data format, and you have the delivery note uploads solved with the four decisions that matter: outside the web root, a server-generated name, a type determined from the content and a forced download.

You have session management decided on the merits — server-side sessions for the portal because Rutalia needs to revoke instantly, tokens for the API —, the three cookie attributes and their consequences, the identifier regeneration that closes fixation, the two expiry clocks and a logout that invalidates on the server and does not just delete the cookie.

You have built the security headers on top of the nginx from 03-02, with the two traps that wreck half of all deployments (always and the non-inheritance of add_header), you know why frame-ancestors supersedes X-Frame-Options, and you have built a CSP in four phases with its reporting endpoint, understanding that 'unsafe-inline' in script-src turns the policy into decoration and that the legitimate alternative is the per-request nonce with its four conditions.

You know how to rate-limit in both layers, close the four routes to user enumeration — including the timing one, with a decoy hash — and detect password spraying, which is the attack no other rule sees. You are clear about what a WAF is: an airbag, not a brake; what it can never do — an IDOR looks like a normal request to it —, and how to deploy it without causing an incident. You know what the application must log and what it must never log, and you have put the C9999 canary to work inside the code. And you have closed off the API with explicit output schemas, because returning the whole object leaks the commercial margin, the driver's identity document number and the internal notes even though the web interface does not show them.

Finally, you take away a remediation plan with fifteen findings, owners and deadlines, and the condition that makes all of this last: every fix carries an automated test that fails if the vulnerability comes back.

But MiRutalia does not live alone on srv-web01. Every night, at 02:00, a script called cifrar_clientes.py exports the customer database, encrypts it with the AES_KEY we have just rotated and uploads it to an S3 bucket in Amazon Web Services. Nobody has ever checked whether that bucket is public. The AWS access key the script uses has not been rotated for three years and there is a copy of it on Marta's laptop. The AWS root account has no MFA. And all of Rutalia's email is in Microsoft 365, where a simple automatic forwarding rule may be copying Nuria Campos's messages to an external mailbox without anybody knowing.

The next lesson, Cloud Security, goes there: what changes and what does not when you move systems out of the data centre, the shared responsibility model applied to Rutalia's three real cases, the misconfigurations that cause most cloud incidents, least-privilege IAM policies commented line by line, CloudTrail events read the way you read logs, the conditional access and the Microsoft 365 forwarding rules that give away hypothesis H2, encryption and key management against what they really protect, data sovereignty and a twelve-point checklist. The application is now closed; it is time to look at where its data sleeps.

© Copyright 2026. All rights reserved