The previous lesson ended with a specific debt and an open problem. The debt: we have been using hashes since 02-01 without defining them, we have mentioned HMAC three times promising to explain it, and we have taken the digital signature on trust without seeing how it works. The open problem is deeper: when we encrypt "with Marta's public key", how do we know that key really is Marta's and not that of somebody who has slipped in between? Diffie-Hellman without authentication is vulnerable to whoever positions themselves between the two parties, and all of asymmetric cryptography collapses if you cannot trust the public key you have been given.

Solving that problem on a planetary scale — how trust is distributed between parties who have never met — is what public key infrastructure, PKI, does. It is the invisible machinery behind the padlock in the browser, behind signing a contract before the Spanish tax authority, behind the software update your machine installs without asking you, and behind the MiRutalia portal certificate that nearly expired on a Saturday night.

This lesson closes the fundamentals module. When you finish it you will have the complete conceptual toolkit — confidentiality, access control, identity, encryption and trust — that module 3 will apply to networks.

  1. Cryptographic hash functions: what they are and what properties they have

A cryptographic hash function takes an input of any size and produces a fixed-size output, called a digest, hash or fingerprint.

$ echo -n "Rutalia" | sha256sum
2a84f3...  (64 hexadecimal characters = 256 bits)

$ sha256sum pelicula_4k.mkv
9c1b7e...  (the same 64 characters, for 8 GB of input)

What is interesting is not the compression but the five properties that make it useful in security:

Property What it means Why it matters
Determinism The same input always produces the same output Without this nothing could be compared
Speed It computes quickly, even over enormous files It makes integrity verification practical
Avalanche effect Changing a single bit of the input changes roughly half the bits of the output A tiny change is immediately visible
Preimage resistance Given a digest, it is infeasible to find an input that produces it A hash cannot be "undone"
Collision resistance It is infeasible to find two different inputs with the same digest Nobody can manufacture an alternative document with the same fingerprint

The avalanche effect, demonstrated

$ echo -n "Transfer 1000 EUR to ES12 3456" | sha256sum
7f4a91c3e80d25b6f1a8c473e29b05d84f6a1c93e57b28d04a9f3c61b8e27d50

$ echo -n "Transfer 1000 EUR to ES12 3457" | sha256sum
c2e85b19f40a7d36c9182e5b70a4f8d61c93b27e58a04f1d36b9e2c750a8f413

A single character of difference (the last digit of the IBAN) and the digests bear no resemblance to each other. There is no way of deducing, by looking at the two digests, that the inputs were almost identical. That is exactly the property that makes a hash manifest — like the one we built in 02-01 — detect any tampering, however small.

Two nuances that get confused

  • Preimage and collision are not the same thing. A preimage is "give me an input that produces this specific digest"; a collision is "give me any two inputs that produce the same digest". The collision is far easier to find, because of a statistical phenomenon known as the birthday paradox: in a group of 23 people, the probability of two sharing a birthday exceeds 50%. The practical consequence is that an n-bit hash offers roughly n/2 bits of collision resistance: SHA-256 gives 128 bits against collisions, not 256.
  • A hash is not encryption. There is no key and there is no way back. "We encrypt the passwords with SHA-256" is a wrong sentence in both respects: it is not encryption, and SHA-256 is not the right thing for passwords (section 3).

  1. The hash families: which to use and which not

Family Output Status Recommended use
MD5 128 bits Broken (practical collisions since 2004) None in security. Only as a checksum against accidental transmission errors
SHA-1 160 bits Broken (first practical collision demonstrated in 2017) None in security. It remains in specific legacy uses where the design does not depend on collision resistance, such as HMAC-SHA1 in TOTP
SHA-2 (SHA-256, SHA-384, SHA-512) 256-512 bits Sound The default option. SHA-256 is the de facto standard
SHA-3 (Keccak) 224-512 bits Sound An alternative with an internal design different from SHA-2's; useful as diversification
BLAKE2 / BLAKE3 Variable Sound Very fast; excellent for integrity over large volumes
bcrypt / scrypt / Argon2 — Sound For passwords only. They are not general-purpose hashes

Why exactly MD5 and SHA-1 are broken

It is not that they can be "decrypted": the preimage resistance of both remains high in practice. What has been broken is collision resistance: two different files with the same digest can be constructed at an affordable computational cost.

Why that is devastating, with an example that explains itself:

  1. An attacker prepares two documents: a harmless contract and another with abusive terms, constructed to have the same MD5 fingerprint.
  2. They send the harmless one to Andrés Vidal, who reviews it and signs it digitally.
  3. Since the digital signature signs the document's fingerprint and not the whole document (section 5), that signature is equally valid for the second document.
  4. The attacker produces the abusive contract with Andrés's genuine signature. Cryptographically, it verifies.

That is why a collision breaks signing, certification and any scheme that depends on "this fingerprint uniquely identifies this content". And it is why certificates signed with SHA-1 stopped being accepted by browsers.

Rule of thumb: SHA-256 by default. If you find MD5 or SHA-1 in a security context, that is an audit finding; if they appear as a download checksum on an old website, it is an irritating oversight but not necessarily exploitable.


  1. Legitimate and incorrect uses of hashes

Correct uses

Use Description At Rutalia
Integrity verification Comparing a file's digest with the expected one The FIM manifest for the MiRutalia portal (02-01)
File fingerprints Identifying content compactly Deduplication in the backups
Indicators of compromise (IoCs) The hash of a known malicious file Searching the machines for the hash of Tarifas_Combustible_2026_Rev3.xlsm from the 01-04 incident
A component of other constructions The basis of HMAC, signatures, KDFs, TOTP Everything we have used in this module
Duplicate detection and version control Git identifies every object by its hash The MiRutalia repository

A clarification about indicators of compromise, which connects with the pyramid of pain from 01-04: a file hash is the most fragile indicator there is. Changing a single byte of the malware produces a completely different hash, and attackers automate that variation. It is still useful — it is cheap to check and it catches lazy reuse — but it cannot be your only detection.

Incorrect uses

1. Hashing passwords without a KDF. The central mistake we saw in 02-03. A general-purpose hash is deliberately fast, and that speed is precisely what you do not want when an attacker has your database. For passwords: bcrypt, scrypt or Argon2id.

2. Using a hash as though it authenticated. If you publish a file and its SHA-256 on the same website, an attacker who compromises the site changes both. The hash proves integrity against errors, not authenticity against an adversary. For that you need a key: HMAC or a signature.

3. Hashing low-entropy data expecting it to stay hidden. The hash of a national ID number, a phone number or a number plate is not anonymous: the space of possible values is small, and an attacker tries them all in seconds, building a complete table. It is a frequent mistake when "anonymising" data to comply with the GDPR, and it is dealt with in Personal Data Protection in Practice (GDPR).

4. Comparing digests with == in sensitive code. Just as in 02-03: the comparison must be in constant time (hmac.compare_digest in Python) so as not to leak information through timing.


  1. HMAC: what it adds over a hash

The problem

A hash with no key can be computed by anybody. If Rutalia sends a customer a message accompanied by its SHA-256, an attacker who intercepts the message can modify it and recompute the hash. The recipient will verify it and be entirely convinced.

The naive intuition is "well, I will prepend a secret and hash that": SHA256(key + message). It looks reasonable and it is broken: the internal structure of SHA-2 allows a length extension attack, by which an attacker who knows the hash and the length of the key can compute the valid hash of message + appended_data without knowing the key. It is the perfect example of why you do not improvise in cryptography: the construction looks correct and it is not.

The solution

HMAC (Hash-based Message Authentication Code) is the standard construction that solves this. It combines the message and the key by applying the hash twice, nested, with two different transformations of the key:

HMAC(K, m) = H( (K ⊕ opad) ‖ H( (K ⊕ ipad) ‖ m ) )

You do not need to memorise the formula. What you do need to retain is that this double nesting neutralises the length extension attack and that HMAC is proven secure even with somewhat weakened hash functions — which is why HMAC-SHA1 remains acceptable, as we saw with TOTP in 02-03, even though bare SHA-1 is not.

Bare hash HMAC Digital signature
Does it need a key? No Yes, a shared one (symmetric) Yes, an asymmetric pair
Who can generate it? Anybody Whoever has the key Only the owner of the private key
Who can verify it? Anybody Whoever has the same key Anybody, with the public key
Does it give integrity? Yes (against accidents) Yes Yes
Does it give authenticity? No Yes, between the parties sharing the key Yes
Does it give non-repudiation? No No: either party could generate it Yes
Speed Very fast Very fast Slow

The non-repudiation row is the one that decides which to use: HMAC authenticates between two parties who trust each other; the digital signature is for when you have to prove it to a third party.

An applied case: the MiRutalia webhook

MiRutalia notifies its customers when a shipment changes status, by sending an HTTP request to a URL the customer configures. The obvious problem: anybody who knows that URL can send fake notifications. A competitor could mark shipments as "delivered" or "exception".

The standard solution is to sign each request with HMAC using a secret shared between Rutalia and that customer.

Sender side (MiRutalia):

import hashlib
import hmac
import json
import time

import requests


def send_webhook(url: str, secret: bytes, event: dict) -> None:
    """Send a notification signed with HMAC-SHA256."""
    body = json.dumps(event, separators=(",", ":"), sort_keys=True).encode()
    timestamp = str(int(time.time()))

    # The timestamp AND the body are signed, not just the body
    message = timestamp.encode() + b"." + body
    signature = hmac.new(secret, message, hashlib.sha256).hexdigest()

    requests.post(
        url,
        data=body,
        headers={
            "Content-Type": "application/json",
            "X-Rutalia-Timestamp": timestamp,
            "X-Rutalia-Signature": f"sha256={signature}",
        },
        timeout=10,
    )

Receiver side (the customer's system):

import hashlib
import hmac
import time

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = b"..."            # the shared secret, from the secrets manager
TOLERANCE_SECONDS = 300    # 5 minutes


@app.route("/webhooks/rutalia", methods=["POST"])
def receive():
    body = request.get_data()                         # the EXACT bytes received
    timestamp = request.headers.get("X-Rutalia-Timestamp", "")
    received = request.headers.get("X-Rutalia-Signature", "")

    # 1. Reject old requests: a defence against REPLAY
    try:
        if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
            abort(400, "Timestamp out of range")
    except ValueError:
        abort(400, "Invalid timestamp")

    # 2. Recompute the HMAC over exactly what the sender signed
    expected = "sha256=" + hmac.new(
        SECRET, timestamp.encode() + b"." + body, hashlib.sha256
    ).hexdigest()

    # 3. CONSTANT-TIME comparison
    if not hmac.compare_digest(expected, received):
        abort(401, "Invalid signature")

    process(request.get_json())
    return "", 204

The four details that make this work:

  1. The raw body (get_data()) is signed, not the already-parsed JSON. If you rebuilt the JSON with json.dumps before verifying, the key order or the whitespace could differ and the signature would never match. You have to sign and verify exactly the same bytes. It is the number one mistake when implementing webhooks.
  2. The timestamp is part of what is signed. Without it, an attacker who captures a legitimate notification can resend it as often as they like: the signature remains valid. That is a replay attack, and the timestamp with a tolerance window closes it.
  3. hmac.compare_digest and not ==, for the same timing reason we saw in 02-03.
  4. The secret is different for each customer and it can be rotated. If one customer leaks theirs, only they are affected.

And the design consequence worth underlining: since HMAC is symmetric, Rutalia could also manufacture any notification. For this case that is perfectly adequate — all the customer needs to know is that it comes from Rutalia — but if the customer needed to be able to prove to a third party that Rutalia sent something, HMAC would not be enough. A digital signature would be required.


  1. The digital signature: what it guarantees and what it does not

A digital signature uses the asymmetric key pair from 02-04 in its second mode: you sign with the private key and verify with the public one.

How it actually works

The whole document is not signed — that would be extremely slow, and RSA only takes small messages. Its digest is signed:

sequenceDiagram
    participant A as Andrés Vidal<br/>(signer)
    participant D as Document
    participant C as Customer<br/>(verifier)

    Note over A,D: SIGNING
    D->>A: Contract.pdf
    A->>A: 1. Compute the SHA-256 of the document
    A->>A: 2. Encrypt that digest with his<br/>PRIVATE KEY -> signature
    A->>C: Sends document + signature + certificate

    Note over C: VERIFICATION
    C->>C: 3. Compute the SHA-256 of the received document
    C->>C: 4. Decrypt the signature with Andrés's<br/>PUBLIC KEY
    C->>C: 5. Do the two digests match?
    Note over C: Yes -> valid signature<br/>No -> altered document<br/>or a different signer

Note the elegance of the mechanism: if the two digests match, two things are proved at once. That the document has not changed (had it changed, the digest in step 3 would be different) and that whoever signed possessed Andrés's private key (nobody else could have produced a signature that decrypts correctly with his public key).

And now it is clear why a hash collision breaks the whole scheme: the signature is applied to the digest, so two documents with the same digest share a valid signature.

What it guarantees

Property Does it give it? Explanation
Integrity ✔ Any change to the document invalidates the signature
Authenticity ✔ Only the holder of the private key could have generated it
Non-repudiation ✔ The signer cannot credibly deny it before a third party
Confidentiality ✘ The signed document travels in the clear. Signing is not encrypting

The last row is the most common misunderstanding. A digitally signed email can be read by anybody; what nobody can do is modify it or impersonate its author. If secrecy is also needed, you have to sign and encrypt.

The two conditions the signature does not guarantee on its own

  1. That the private key still belongs to the signer. If the key was stolen, the signatures are cryptographically valid and legally arguable. Hence the importance of revocation (section 10).
  2. That the public key belongs to who you think. If I give you a public key saying it is Andrés Vidal's and you believe me, you will verify my signatures as though they were his. This is exactly the problem PKI solves, and it is why digital signatures and certificates always go together.

The usual signature algorithms: RSA with PSS (the recommended padding scheme for signing, the equivalent of what OAEP is for encryption), ECDSA with the P-256 curve, and Ed25519, which is modern, fast and less prone to implementation errors.


  1. Digital signature, electronic signature and timestamp

Three terms used as synonyms that are different things: one is technical and another legal.

Concept Nature What it is
Digital signature Technical The cryptographic mechanism from section 5
Electronic signature Legal Any data in electronic form that serves for the signatory to express their will. It may be a digital signature, a scanned image, a click on "I accept" or a confirmation SMS
Timestamp Technical Proof that a piece of data existed at a given instant

In the European Union, the eIDAS regulation establishes three levels of electronic signature:

Level Requirements Evidential value Example
Simple Any electronic data expressing intent Admissible as evidence, but rebuttable A click on "I accept the terms", an email of agreement
Advanced Uniquely linked to the signatory, allows them to be identified, created with means under their sole control and detects subsequent changes High A digital signature with a certificate
Qualified An advanced signature + a qualified certificate issued by a qualified provider + a qualified signature creation device Equivalent to a handwritten signature throughout the EU A certificate on a smart card from a qualified provider

The practical distinction that matters: only the qualified signature has, by law, the same effect as a handwritten one. The others are valid as evidence, but whoever relies on them must demonstrate their reliability.

In Spain, and at Rutalia

Rutalia uses an element of this infrastructure every day, even though nobody calls it that: the Spanish qualified company representative certificate, issued by a trust service provider, with which the company:

  • Files taxes and returns with the Spanish tax authority.
  • Deals with the social security administration.
  • Receives mandatory electronic notifications from public administrations.
  • Signs documentation in tenders and contracts.

And here there is a very real security problem that usually goes unnoticed, and which Laura should resolve:

Where is Rutalia's company certificate and who can use it? If it is installed in the browser on the administration machine, with no protecting password, exportable and on a machine with local administrator privileges, then anybody who compromises that machine can act legally on Rutalia's behalf: file returns, sign contracts, read notifications from the tax authority.

The proportionate measures: the certificate on a smart card or token (the private key is not exportable), marked as non-exportable if it is in software, a strong password, an inventory of who holds it, and control of the electronic notifications — which carry legal deadlines and whose non-receipt is no excuse.

Timestamp

A qualified timestamp is issued by a trusted third party and proves that a document existed at a given moment. It solves a specific problem with signatures: if the signer's certificate expires or is revoked in 2028, how do you demonstrate in 2030 that the 2026 signature was valid when it was made?

Without a timestamp, future verification becomes ambiguous. With one, it is proved that the signature was created while the certificate was in force. It is indispensable for documentation with long-term value: contracts, minutes, employment records.


  1. PKI: how trust is distributed

Let us go back to the underlying problem. You have a public key that claims to belong to mirutalia.example. How do you know that it does?

You cannot check it yourself for each of the millions of sites on the internet. The solution is to delegate trust to a third party you already trust: a certificate authority.

The pieces

Piece What it does
CA (Certificate Authority) Verifies an applicant's identity and signs a certificate binding an identity to a public key
RA (Registration Authority) Carries out the identity verification; it is often part of the CA
Certificate The signed document that says: "public key X belongs to identity Y, and I, the CA, guarantee it"
CRL / OCSP The mechanisms for announcing that a certificate has ceased to be valid before it expires
Trust store The list of root CAs your system or browser trusts from the outset

The central idea

A certificate is simply a public key digitally signed by somebody you already trust. The whole of PKI is the digital signature from section 5 applied recursively.

graph TD
    R["ROOT CA<br/>Private key offline,<br/>in an HSM, in a safe<br/>Validity: 20-25 years"]
    R -->|signs| I1["INTERMEDIATE CA<br/>The one that issues day to day<br/>Validity: 5-10 years"]
    R -->|signs| I2["INTERMEDIATE CA 2"]
    I1 -->|signs| C1["Certificate for<br/>mirutalia.example<br/>Validity: 90 days"]
    I1 -->|signs| C2["Certificate for<br/>www.rutalia.example"]
    I2 -->|signs| C3["Other certificates"]
    T["Trust store of the<br/>system or browser"] -.->|trusts| R
    style R fill:#e8f0fe,stroke:#1a73e8
    style T fill:#e6f4ea,stroke:#137333

Why intermediate CAs exist

It is a design decision worth understanding, because it is an excellent example of risk management:

  • The root CA's private key is the most critical asset in the system. If it is compromised, certificates can be forged for any domain in the world, and there is no practical way to revoke a root: it is burned into millions of devices.
  • That is why the root is kept offline, in a physically guarded HSM, and is used only in formal ceremonies with witnesses, perhaps once a year.
  • The day-to-day work is done by the intermediates, whose keys are online and exposed.
  • If an intermediate is compromised, the root revokes it and another is issued. The damage is bounded and recoverable.

It is exactly the principle of compartmentalisation we applied in 02-02 to administrative accounts and in 02-04 to keys: separating what is used day to day from what has absolute power.


  1. Anatomy of an X.509 certificate

X.509 is the standard certificate format. Let us look at a real one, field by field.

openssl x509 -in mirutalia.crt -noout -text

Abbreviated and annotated output:

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 04:8a:3f:21:9c:7e:52:b0:11:d4
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, O=Let's Encrypt, CN=R11
        Validity
            Not Before: Aug 15 09:22:41 2026 GMT
            Not After : Nov 13 09:22:40 2026 GMT
        Subject: CN=mirutalia.example
        Subject Public Key Info:
            Public Key Algorithm: id-ecPublicKey
                Public-Key: (256 bit)
                ASN1 OID: prime256v1
                NIST CURVE: P-256
        X509v3 extensions:
            X509v3 Key Usage: critical
                Digital Signature
            X509v3 Extended Key Usage:
                TLS Web Server Authentication, TLS Web Client Authentication
            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Subject Alternative Name:
                DNS:mirutalia.example, DNS:www.mirutalia.example, DNS:api.mirutalia.example
            X509v3 CRL Distribution Points: ...
            Authority Information Access:
                OCSP - URI:http://r11.o.lencr.org
                CA Issuers - URI:http://r11.i.lencr.org/
            CT Precertificate SCTs: ...
    Signature Algorithm: sha256WithRSAEncryption
    Signature Value: 8f:3a:91:c0:4b:...

Field by field

Field What it means Why it matters
Version: 3 The format version v3 is the one supporting extensions; any current certificate is v3
Serial Number A unique identifier within that CA It is what appears in revocation lists. It must be unpredictable: a sequential number would facilitate certain attacks
Signature Algorithm Which algorithm the CA signed with sha1With... here is grounds for rejection. It must be SHA-256 or better
Issuer Who issued it It must match the Subject of the certificate immediately above it in the chain
Not Before / Not After The validity window Outside it, the certificate is worthless. The origin of the incident in section 10
Subject Who it identifies In modern web certificates the CN is informational: what counts is the SAN
Subject Public Key Info The certified public key It is the essential content: what the CA is vouching for
Key Usage What the key may be used for Marked critical: a client that does not understand this extension must reject the certificate
Extended Key Usage The specific use: TLS server, client, code signing, email It prevents a web server certificate being used to sign software
Basic Constraints: CA:FALSE This certificate cannot sign others Without this restriction, anybody with a valid certificate could issue certificates for other domains. It was a real flaw in the early years of the web
Subject Alternative Name (SAN) The list of valid names It is the field browsers actually check. A certificate with no SAN is rejected, even if the CN is correct
CRL Distribution Points / AIA Where to check revocation and where to download the issuer Needed to complete the chain and check the status
CT Precertificate SCTs Proofs of publication in transparency logs Section 12
Signature Value The CA's signature over everything above It is what turns a data file into a certificate

The three fields you should always look at

If you only have time to look at three things in a certificate:

  1. SAN: does it include the exact name I am connecting to?
  2. Validity: are we inside the interval?
  3. Issuer and chain: was it signed by a CA I trust?

A mistake that gets made constantly: the wildcard *.rutalia.example covers portal.rutalia.example but not a.b.rutalia.example nor the bare domain rutalia.example. Wildcards cover only one level, and the base domain must be included explicitly.


  1. The certificate chain and trust stores

How a chain is validated

When your browser visits mirutalia.example, the server sends it its certificate and the intermediates. The browser then:

  1. Checks that the SAN includes the requested name.
  2. Checks that the current date is within the validity period.
  3. Verifies the certificate's signature using the issuer's public key (which is in the intermediate).
  4. Repeats the process upwards: it verifies the intermediate with the root's key.
  5. Checks that the root is in its trust store.
  6. Checks the constraints (Basic Constraints, Key Usage) at every link.
  7. Checks the revocation status (section 10).

If any step fails, the security warning appears.

Trust stores

A trust store is the list of root CAs a system trusts. There are several, and they are not identical:

Store Maintained by Notes
Operating system The system vendor On Linux it is usually in /etc/ssl/certs/
Browser Some browsers use the system's; others maintain their own That is why a certificate can work in one browser and not another
Language or library Python, Java and other environments ship their own A common source of certificate errors in scripts

Viewing the stores on Linux:

ls /etc/ssl/certs/ | head
awk -v cmd='openssl x509 -noout -subject' '/BEGIN/{close(cmd)};{print | cmd}' \
    /etc/ssl/certs/ca-certificates.crt | head -20

The security implication you have to understand

Any CA in your trust store can issue a valid certificate for any domain in the world. There is no restriction preventing a CA from issuing for mirutalia.example.

That has two practical consequences:

  1. Never install a root CA that is not indispensable. Software that asks to install its own root certificate in order to "inspect traffic" is asking for the ability to impersonate any website to that machine.
  2. It is the reason certificate transparency exists (section 12): if anybody can issue for your domain, at least let there be a public record when it happens.

  1. Revocation: CRLs, OCSP and short expiry

A certificate has an expiry date, but sometimes it has to be invalidated earlier: the private key has leaked, the server has been decommissioned, the details have changed. That is the revocation problem, and it is the weakest point in the whole of PKI.

Mechanism How it works Advantages Problems
CRL (revocation list) The CA publishes a signed list of revoked serial numbers; the client downloads it Simple, works offline once downloaded The lists grow very large; they are updated every few hours or days, so there is a window of validity after revocation
OCSP The client asks the CA about one specific certificate and receives a signed response Up-to-the-minute information; little traffic It leaks privacy (the CA knows which sites you visit); it adds latency; if the OCSP server goes down, the client usually carries on regardless
OCSP stapling The server periodically obtains the signed OCSP response and attaches it to the connection No privacy leak, no latency, no dependence on the CA being available It has to be configured on the server
Short expiry Certificates of 90 days or less, renewed automatically It limits the exposure window by design It makes automation compulsory

The "soft fail" problem

Here is the underlying discomfort: if the revocation check fails — the OCSP server does not answer, the CRL will not download — most clients carry on as though the certificate were valid. It is called soft-fail, and it exists for a practical reason: applying hard-fail would make half the internet stop working every time a CA had an incident.

The consequence is uncomfortable to admit: an attacker who can interfere with the network can also block the revocation check, and the client will accept the revoked certificate. That is why the industry's direction of travel has shifted towards short expiry: if a certificate only lives for 90 days — and the industry is heading towards even shorter periods — the damage window from a compromised key is small even if revocation does not work. It is a change of philosophy: instead of fixing revocation, the time during which it would be needed is reduced.

The case: MiRutalia's certificate expires on a Saturday

This is what happened at Rutalia in March, before Laura arrived.

Saturday, 09:14. The certificate for mirutalia.example expires. It had been issued for a year and renewed manually; whoever renewed it the previous year no longer works at the company and the date was in nobody's calendar.

09:15. The 400 business customers who use the portal see a full-screen "connection is not private" warning. Those working on a Saturday — mostly food warehouses — cannot check the status of their shipments.

09:40. The automated integrations of three large customers, which query Rutalia's API through scripts, fail silently. Those scripts show no warnings: they simply stop receiving data. Nobody finds out until Monday.

10:20. The first customer rings the support line. The rest start emailing. Some ask whether Rutalia has suffered an attack.

11:05. Diego Salas, tracked down on his day off, tries to renew. He cannot find the credentials for the certificate provider's account: they were in the former employee's name, with that former employee's email address as the recovery contact. Which is, of course, disabled.

14:30. After creating a new account and validating domain ownership, a new certificate is issued. The portal comes back.

The real cost: five hours of downtime during partial business hours, three broken integrations for two days, dozens of phone calls, and — the most expensive of all — the erosion of trust: several customers asked whether there had been a security breach.

The five lessons, which are the lessons of the whole subject:

Lesson Control
An expired certificate is downtime with a date known well in advance Automatic expiry monitoring (section 13)
Supplier accounts in an individual's name are a time bomb Corporate accounts with a shared mailbox ([email protected]), never personal ones
Manual annual processes always fail Automatic renewal (ACME)
What fails silently is more expensive than what fails noisily External monitoring of the API, not just of the website
Nobody had a certificate inventory An inventory with an owner, a date and a procedure

It is also the practical confirmation of something we stated in 02-01: availability is a security property, and its most frequent enemy is not an attacker but an expiry date nobody is watching.


  1. Certificates in practice

Self-signed versus a public CA

A self-signed certificate is one in which the issuer and the subject are the same: nobody vouches for it.

Self-signed Public CA Internal private CA
Cost Zero Zero (Let's Encrypt) or paid The cost of building and running it
Automatic trust No: a warning in every browser Yes Only on machines where the root is installed
Appropriate use Local testing, development Anything public Internal services, client certificates, IoT
Risk It trains users to ignore security warnings — If the private root is compromised, any internal service can be impersonated

The risk of self-signed certificates is not technical, it is behavioural: if Rutalia's employees get used to clicking "continue anyway" on the internal ERP, they will do the same the day the warning is real. A security warning that people ignore out of habit is worse than no warning at all.

Let's Encrypt and ACME

ACME is the protocol that automates certificate issuance. The flow:

  1. The ACME client (for example certbot) requests a certificate for mirutalia.example.
  2. The CA sets a challenge: "prove that you control that domain by publishing this value".
  3. The client publishes it, as a file on the website (HTTP-01) or as a DNS record (DNS-01).
  4. The CA checks it and issues the certificate.
  5. The client repeats the process automatically before every expiry.
# Initial issuance with HTTP validation
sudo certbot --nginx -d mirutalia.example -d www.mirutalia.example

# Check that automatic renewal works, WITHOUT issuing anything
sudo certbot renew --dry-run

# List the managed certificates and their dates
sudo certbot certificates

The command that really matters is the second. --dry-run simulates the complete renewal without consuming quota or touching anything, and it is the only way to know that the automatic process will work in two months' time. Running it after every change to the web server configuration avoids repeating the March incident.

A practical note: DNS validation (DNS-01) is the only one that allows wildcard certificates to be issued and it works for services not exposed to the internet — which makes it the right option for Rutalia's internal services.

An internal private CA

For services that do not face the internet (the ERP, the administration panels, the IoT probes), a private CA allows valid certificates without exposing anything. It requires: protecting the root key, distributing the root to every machine through domain policy, and automating issuance. It is not a trivial project, and for an SME it is usually better to use ACME with DNS validation for internal names that do sit under a domain of your own.

Inventory and renewal

The minimum deliverable Laura puts in place:

Domain / service Type Issuer Expires Renewal Owner
mirutalia.example Public Let's Encrypt 90 days Automatic (ACME) IT
www.rutalia.example Public Let's Encrypt 90 days Automatic (ACME) IT
erp.rutalia.local Internal Internal CA 1 year Manual + alert at 45 days Diego
VPN Public Paid CA 1 year Manual + alert at 60 days Diego
Company certificate Qualified Qualified provider 2 years Manual + alert at 60 days Administration
Email signing for senior management Qualified Qualified provider 2 years Manual + alert at 60 days Administration

Two rules that close the March hole: every supplier account in the company's name, with [email protected] as the contact; and every manual renewal has an automatic alert, not a note in one person's calendar.


  1. Certificate transparency (CT logs)

Section 9 left an unsettling consequence hanging: any trusted CA can issue a certificate for any domain, yours included, without you finding out. It has happened: by mistake, through the compromise of a CA and through improper issuance.

Certificate transparency answers that problem with an elegant solution: improper issuance cannot be prevented, but it can be made impossible to hide.

How it works:

  1. There are public, append-only, cryptographically verifiable logs (they use hash tree structures, built with the functions from section 1).
  2. CAs must publish in them every certificate they issue, and in return they receive a proof (an SCT) that is embedded in the certificate.
  3. Browsers reject certificates that do not carry those proofs. That makes publication compulsory in practice.
  4. Anybody can query the logs and see every certificate issued for a domain.

Its defensive value, which is twofold

Use 1: detecting improper issuance for your domain. If tomorrow a certificate appears for mirutalia.example issued by a CA Rutalia does not use, Laura finds out automatically. It is a sign of serious compromise, detectable at no cost at all.

Use 2, less well known and very useful: detecting phishing domains being prepared against you. An attacker preparing a campaign against Rutalia will register a lookalike domain — mirutalia-clientes.example, rutalia-portal.example — and request a certificate for it, because without a padlock the deception does not work. That certificate appears in the public logs within minutes, normally days before the campaign is launched.

It is one of the few controls that warn you before the attack begins. And it connects directly with the reverse-proxy phishing we saw in 02-03: that attack needs a domain with a valid certificate, and that certificate leaves a public trail.

In practice it is implemented by subscribing to a CT monitoring service that sends an alert when a certificate appears containing a watched string (rutalia, mirutalia). Cost: zero or near zero. It is one of the first things Laura should switch on.


  1. Hands-on: inspecting and monitoring Rutalia's certificates

Step 1: viewing a server's certificate with openssl s_client

openssl s_client -connect mirutalia.example:443 \
                 -servername mirutalia.example \
                 -showcerts </dev/null
  • -connect host:port: establishes the TLS connection.
  • -servername: sends the SNI extension, which tells the server which site you want. It is indispensable when one server hosts several domains: without it you will receive the default certificate, which may be a different one, and you will believe there is a configuration error where there is none.
  • -showcerts: shows the whole chain sent, not just the end certificate. It serves to detect the most common TLS configuration error: forgetting to send the intermediates.
  • </dev/null: closes standard input so that the command finishes on its own instead of sitting there waiting.

Abbreviated output:

Certificate chain
 0 s:CN=mirutalia.example
   i:C=US, O=Let's Encrypt, CN=R11
 1 s:C=US, O=Let's Encrypt, CN=R11
   i:C=US, O=Internet Security Research Group, CN=ISRG Root X1
---
SSL handshake has read 4231 bytes and written 401 bytes
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
Verify return code: 0 (ok)

How to read it:

  • The chain runs from the bottom up: the s: (subject) of each level is the i: (issuer) of the one before it. If that correspondence breaks, the chain is incomplete.
  • Verify return code: 0 (ok) is the line confirming that full validation succeeded. Any other value indicates a problem: 10 is an expired certificate, 19 means the root could not be verified (typically an incomplete chain), 21 means the first certificate could not be verified.
  • Note TLS_AES_256_GCM_SHA384: there are all the module's concepts together — AES-256 in GCM mode for authenticated encryption, SHA-384 for integrity, inside TLS 1.3. (The full negotiation is studied in Network Security Protocols.)

Step 2: reading the fields that matter

# Just the validity dates
openssl s_client -connect mirutalia.example:443 -servername mirutalia.example </dev/null 2>/dev/null \
  | openssl x509 -noout -dates

# notBefore=Aug 15 09:22:41 2026 GMT
# notAfter=Nov 13 09:22:40 2026 GMT

# Just the names covered (SAN)
openssl s_client -connect mirutalia.example:443 -servername mirutalia.example </dev/null 2>/dev/null \
  | openssl x509 -noout -ext subjectAltName

# X509v3 Subject Alternative Name:
#     DNS:mirutalia.example, DNS:www.mirutalia.example, DNS:api.mirutalia.example

# The certificate's fingerprint, to compare with the expected one
openssl s_client -connect mirutalia.example:443 -servername mirutalia.example </dev/null 2>/dev/null \
  | openssl x509 -noout -fingerprint -sha256

The pattern is the same in all three cases: s_client obtains the certificate, and openssl x509 extracts a specific field. The pipe between the two commands is the usual way of working with certificates from the console.

Step 3: generating a CSR

A CSR (Certificate Signing Request) is the request sent to the CA. It contains the public key and the requested identity, signed with the private key to prove that the requester holds that key.

# 1. An elliptic-curve P-256 private key
openssl ecparam -genkey -name prime256v1 -out mirutalia.key
chmod 600 mirutalia.key

# 2. A CSR with several names in the SAN
openssl req -new -key mirutalia.key -out mirutalia.csr \
  -subj "/C=ES/ST=Zaragoza/L=Zaragoza/O=Rutalia Logistica S.L./CN=mirutalia.example" \
  -addext "subjectAltName=DNS:mirutalia.example,DNS:www.mirutalia.example,DNS:api.mirutalia.example"

# 3. VERIFY the CSR before sending it
openssl req -in mirutalia.csr -noout -text | grep -A2 "Subject Alternative Name"
  • ecparam -genkey -name prime256v1 generates a P-256 elliptic-curve key which, as we saw in 02-04, is equivalent to RSA-3072 at a fraction of the size and the computation.
  • chmod 600 again: the private key is never shared. The CSR is sent; the .key never leaves the server. If a CA asks you for the private key, something is very wrong.
  • -addext "subjectAltName=..." is the step most often forgotten. Without a SAN, browsers reject the certificate even if the CN is correct.
  • Step 3 is not optional: verifying the CSR before sending it avoids discovering that a name is missing once the certificate has already been issued.

Step 4: signing and verifying a file

A complete demonstration of section 5, with the keys generated in 02-04:

# Sign the rates file with the PRIVATE key
openssl dgst -sha256 -sign rutalia_privada.pem \
             -out tarifas_2026.csv.sig tarifas_2026.csv

# Verify with the PUBLIC key (anybody can do this)
openssl dgst -sha256 -verify rutalia_publica.pem \
             -signature tarifas_2026.csv.sig tarifas_2026.csv
# Verified OK

# Alter a single byte and verify again
printf 'X' | dd of=tarifas_2026.csv bs=1 seek=50 conv=notrunc 2>/dev/null
openssl dgst -sha256 -verify rutalia_publica.pem \
             -signature tarifas_2026.csv.sig tarifas_2026.csv
# Verification failure

This experiment sums up the entire lesson: dgst -sha256 -sign computes the digest and signs it with the private key; -verify recomputes the digest and checks the signature with the public one. One byte changed and verification fails. It is exactly the mechanism that protects software updates, and the control Rutalia ought to demand from the ERP vendor against hypothesis H5.

Step 5: the expiry watchdog

This is the detective control Rutalia did not have and which would have saved it that Saturday in March.

#!/usr/bin/env python3
"""
vigilar_certificados.py — TLS certificate expiry monitoring.
Rutalia Logística S.L.

Usage: python3 vigilar_certificados.py dominios.txt
Exit codes: 0 = all correct | 1 = warnings | 2 = critical situation
"""

import datetime as dt
import socket
import ssl
import sys

CRITICAL_THRESHOLD = 7    # days
WARNING_THRESHOLD = 30    # days
TIMEOUT = 10              # seconds


def days_to_expiry(host: str, port: int = 443) -> tuple[int, str, str]:
    """Return (days remaining, issuer, ISO expiry date)."""
    context = ssl.create_default_context()

    with socket.create_connection((host, port), timeout=TIMEOUT) as sock:
        # server_hostname sends SNI: indispensable with several sites per server
        with context.wrap_socket(sock, server_hostname=host) as tls:
            cert = tls.getpeercert()

    # 'notAfter' arrives as 'Nov 13 09:22:40 2026 GMT'
    expires = dt.datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")
    expires = expires.replace(tzinfo=dt.timezone.utc)

    remaining = (expires - dt.datetime.now(dt.timezone.utc)).days

    issuer = dict(x[0] for x in cert["issuer"]).get("organizationName", "?")
    return remaining, issuer, expires.date().isoformat()


def main() -> int:
    if len(sys.argv) != 2:
        print("Usage: vigilar_certificados.py <domains_file>", file=sys.stderr)
        return 2

    with open(sys.argv[1], encoding="utf-8") as f:
        domains = [l.strip() for l in f
                   if l.strip() and not l.startswith("#")]

    worst = 0
    print(f"{'DOMAIN':<32} {'DAYS':>6}  {'EXPIRES':<12} {'ISSUER':<22} STATUS")
    print("-" * 92)

    for entry in domains:
        host, _, p = entry.partition(":")
        port = int(p) if p else 443
        try:
            days, issuer, date_str = days_to_expiry(host, port)
        except ssl.SSLCertVerificationError as e:
            print(f"{entry:<32} {'--':>6}  {'--':<12} {'--':<22} "
                  f"VALIDATION ERROR: {e.verify_message}")
            worst = 2
            continue
        except (socket.timeout, socket.gaierror, ConnectionError, OSError) as e:
            print(f"{entry:<32} {'--':>6}  {'--':<12} {'--':<22} "
                  f"UNREACHABLE: {type(e).__name__}")
            worst = max(worst, 1)
            continue

        if days < 0:
            status, level = "*** EXPIRED ***", 2
        elif days <= CRITICAL_THRESHOLD:
            status, level = "CRITICAL", 2
        elif days <= WARNING_THRESHOLD:
            status, level = "WARNING", 1
        else:
            status, level = "OK", 0

        worst = max(worst, level)
        print(f"{entry:<32} {days:>6}  {date_str:<12} {issuer[:22]:<22} {status}")

    return worst


if __name__ == "__main__":
    sys.exit(main())

An explanation of what matters:

  • ssl.create_default_context() creates a context that verifies the chain and the name by default. That is the correct behaviour: if you ever see ssl._create_unverified_context() or verify=False in production code, you have found a vulnerability, because it disables all the validation we have studied.
  • server_hostname=host sends SNI. Without it, a server hosting several sites would return the wrong certificate and the script would report another domain's dates.
  • cert["notAfter"] comes in a legacy text format. strptime with "%b %d %H:%M:%S %Y %Z" parses it, and replace(tzinfo=utc) makes it timezone-aware so that it can be subtracted from now(timezone.utc). Comparing an aware date with a naive one raises an exception in Python: it is the most common failing when writing scripts of this kind.
  • Two types of error are distinguished, and the distinction is important: SSLCertVerificationError means there is a certificate with a problem (expired, broken chain, wrong name) and it is critical; a network error means we could not check it, which is a warning but not the same class of problem. Confusing them generates false alarms every time the connection drops.
  • Three thresholds (30 days to warn, 7 for critical, negative for expired) because 30 days give margin to handle a manual renewal that requires identity validation.
  • The exit code allows it to be plugged into cron or a monitoring system, just as we did with the integrity verifier in 02-01.

The input file:

# dominios.txt — Rutalia Logística's monitored certificates
mirutalia.example
www.mirutalia.example
api.mirutalia.example
www.rutalia.example
vpn.rutalia.example:443
correo.rutalia.example:993

Note the last two lines: certificates are not only on web servers. The VPN, the mail server, the load balancers and any TLS service have their own, and those are precisely the ones nobody watches.

A run:

$ python3 vigilar_certificados.py dominios.txt
DOMAIN                             DAYS  EXPIRES      ISSUER                 STATUS
--------------------------------------------------------------------------------------------
mirutalia.example                    52  2026-11-13   Let's Encrypt          OK
www.mirutalia.example                52  2026-11-13   Let's Encrypt          OK
api.mirutalia.example                52  2026-11-13   Let's Encrypt          OK
www.rutalia.example                  18  2026-10-10   Let's Encrypt          WARNING
vpn.rutalia.example:443               5  2026-09-27   DigiCert               CRITICAL
correo.rutalia.example:993           -3  2026-09-19   DigiCert               *** EXPIRED ***
$ echo $?
2

That output tells a complete story in six lines: the VPN expires next Sunday, and the mail server's certificate expired three days ago without anybody noticing — probably because the configured mail clients already accepted the warning and carry on working, which is exactly the kind of silent failure that takes longest to discover.

Automation:

# /etc/cron.d/vigilar-certificados
# Daily check at 07:30; only sends email if there is something to review.
30 7 * * * root /usr/bin/python3 /opt/seguridad/vigilar_certificados.py \
    /opt/seguridad/dominios.txt | grep -E "WARNING|CRITICAL|EXPIRED|ERROR|UNREACHABLE" \
    | /usr/bin/mail -E -s "[CERT] Rutalia certificate review" [email protected]

The grep filters the problem lines and mail -E sends nothing if the result is empty. Email only arrives when there is something to do, which is the only way a detective control is still being read six months later.


Common Mistakes and Tips

Mistake 1: using a hash to store passwords. SHA-256 is fast by design, and that is exactly what you do not want. Tip: bcrypt, scrypt or Argon2id for passwords; SHA-256 for integrity.

Mistake 2: publishing a file and its hash in the same place. Whoever compromises the site changes both. Tip: authenticity needs a key — HMAC or a signature — not a hash.

Mistake 3: believing that signing is encrypting. A signed document reads perfectly well. Tip: if you also need secrecy, sign and encrypt.

Mistake 4: SHA256(key + message) as an authentication code. Vulnerable to length extension. Tip: use HMAC, which exists precisely for this.

Mistake 5: verifying a webhook against the rebuilt JSON. The key order and the whitespace change the bytes and the signature never matches. Tip: sign and verify against the raw body, and add a timestamp against replay.

Mistake 6: disabling certificate verification "to make it work". verify=False, -k in curl, InsecureSkipVerify. It annuls all the protection and usually stays in production forever. Tip: if it is an internal certificate, install your CA in the trust store; never disable verification.

Mistake 7: using self-signed certificates on internal services that people use. It trains them to ignore security warnings. Tip: an internal CA distributed by policy, or ACME with DNS validation.

Mistake 8: manual annual renewal. It always fails, and it fails at the worst moment. Tip: automation with ACME, and for whatever cannot be automated, alerts at 60 and 30 days with a named owner.

Mistake 9: supplier accounts in an individual's name. When that person leaves, control of the asset is lost. Tip: corporate accounts with a shared mailbox, always.

Mistake 10: not monitoring the transparency logs. It is free and it warns you about phishing campaigns before they are launched. Tip: subscribe today.

A final tip: in any certificate audit there are four questions that uncover most of the problems: is there a complete inventory, including the VPN, email and internal services? Is renewal automated, and has it been tested with --dry-run? Are there expiry alerts that reach a corporate mailbox? Are the supplier accounts in the company's name? At Rutalia, in March, all four answers were "no", and that cost five hours of portal downtime on a Saturday.


Exercises

Exercise 1: choosing the right integrity mechanism

For each Rutalia situation, state which of these mechanisms you would use — a plain hash, HMAC or a digital signature — and justify the choice in terms of who generates it, who verifies it and whether non-repudiation is needed:

  1. Checking that the .iso file downloaded from the manufacturer's site was not corrupted in transit.
  2. Notifying a customer, by webhook, that their shipment has changed status.
  3. Distributing the new rates catalogue to the 400 customers, so that anybody can check Rutalia issued it.
  4. Detecting whether anybody has modified the MiRutalia portal files on srv-web01.
  5. An €80,000 order that a customer must not be able to deny having placed.
  6. The session tokens MiRutalia issues and validates internally.
  7. Verifying that the ERP update package really comes from the vendor.

Exercise 2: diagnosing certificate problems

Interpret each of these outputs and say: what exactly the problem is, what causes it and how it is fixed.

Case A

$ openssl s_client -connect erp.rutalia.example:443 </dev/null
...
Verify return code: 19 (self-signed certificate in certificate chain)

Case B

$ curl https://api.mirutalia.example/envios
curl: (60) SSL: no alternative certificate subject name matches
      target host name 'api.mirutalia.example'

Case C

$ openssl x509 -in servicio.crt -noout -dates -issuer
notBefore=Sep 20 00:00:00 2025 GMT
notAfter=Sep 20 00:00:00 2026 GMT
issuer=C=ES, O=Rutalia Logistica, CN=Rutalia CA Interna

(Today's date is 22 September 2026, and the service is used by the drivers from their tablets.)

Case D

$ openssl s_client -connect www.rutalia.example:443 -showcerts </dev/null
Certificate chain
 0 s:CN=www.rutalia.example
   i:C=US, O=Let's Encrypt, CN=R11
---
Verify return code: 20 (unable to get local issuer certificate)

(The same site displays correctly in Laura's browser.)

Exercise 3: designing Rutalia's certificate management

Laura has to present senior management with a certificate management plan that prevents a repeat of the March incident. You are asked for:

  1. An inventory of all the certificates Rutalia should reasonably have, based on what you know of its infrastructure. State the appropriate certificate type for each.
  2. For each item in the inventory, the renewal strategy (automatic or manual) and why.
  3. The detective controls that have to be put in place, with their frequency.
  4. The organisational measures that would prevent the failure of the credentials in the former employee's name.
  5. A one-page emergency procedure for the case "certificate expired in production out of hours".

Solutions

Solution to Exercise 1

# Situation Mechanism Justification
1 Verifying a downloaded .iso A plain hash (SHA-256) All that is needed is to detect accidental transmission corruption. An important nuance: if the hash is published on the same website as the file, it does not protect against an attacker who compromises the site; for that the manufacturer should sign the file. If the manufacturer offers a signature, use it
2 A webhook to a customer HMAC It is communication between two parties sharing a secret. All the customer needs is to know it comes from Rutalia; there is no need to prove it to a third party. It is fast and simple to rotate per customer
3 The rates catalogue for 400 customers A digital signature Here HMAC does not work: it would require sharing a secret with all 400, and then any of them could manufacture a fake catalogue. With a signature, only Rutalia produces and everybody verifies
4 Integrity of the portal's files A plain hash (a manifest) An internal control over a system of your own, like the one in 02-01. A refinement: if the attacker has root they can rewrite the manifest, so it is wise to sign it or keep it on another system
5 An €80,000 order A digital signature (with a certificate and a timestamp) This is the non-repudiation case: it must be provable to a third party, possibly a judge. HMAC will not do because either party could have generated it
6 Internal session tokens HMAC Rutalia issues them and Rutalia validates them: a single party, a symmetric key. It is fast, and it is exactly what a JWT signed with HS256 does
7 The ERP update The vendor's digital signature Rutalia must be able to verify without being able to forge. It holds only the vendor's public key. It is the direct technical control against hypothesis H5

The criterion in one sentence: if both parties can share a secret and neither needs to prove anything to third parties, HMAC (faster and simpler). If there are many verifiers or non-repudiation is needed, a digital signature. If all you need is to detect accidents, a hash.

Solution to Exercise 2

Case A — Code 19: self-signed certificate in the chain

  • Problem: the ERP uses a certificate issued by an internal CA (or self-signed) that is not in the trust store of the system connecting to it.
  • Cause: the internal root has not been distributed to the machines and servers, or the connection is from a server that does not have it even though the laptops do.
  • Fix: distribute the internal root CA to every machine through domain policy, and also to the trust stores of the libraries and languages that connect (Python, Java) — a common reason for "it works in the browser but not in the script". What must not be done is to disable verification: it is the convenient answer that stays in production forever.

Case B — The name does not match the SAN

  • Problem: the certificate served does not include api.mirutalia.example among its alternative names.
  • Possible causes: (a) the certificate was issued only for mirutalia.example and www., forgetting api.; (b) the server does not receive SNI or has no virtual host configured for that name and returns the default certificate; (c) a wildcard *.mirutalia.example was used that does not cover the requested level or the bare domain.
  • Diagnosis: openssl s_client -connect api.mirutalia.example:443 -servername api.mirutalia.example </dev/null 2>/dev/null | openssl x509 -noout -ext subjectAltName shows exactly which names it covers.
  • Fix: reissue including api.mirutalia.example in the SAN, or correct the virtual host configuration. Never curl -k: that command disables verification and turns a configuration problem into a permanent vulnerability.

Case C — A certificate that expired two days ago

  • Problem: notAfter is 20 September 2026 and today is the 22nd: the certificate expired two days ago, and nobody has noticed.
  • Why it went unnoticed: it is an internal CA certificate used by applications on tablets. It is very likely that the mobile application does not validate the certificate properly, or that the drivers accepted a warning without understanding it. Both explanations are worrying: the first means the channel can be impersonated, the second that there is a culture of ignoring warnings.
  • Immediate fix: reissue the certificate and deploy it.
  • The underlying fix, which is the important one: include all internal certificates in the watchdog from section 13 — not just the public ones — and audit whether the tablet application really does validate the certificate. A validation failure in the client annuls the whole of PKI, because an attacker on the network could impersonate the service to 60 tablets. It connects with Wireless Network Security, since the tablets connect over networks Rutalia does not control.

Case D — Code 20: incomplete chain

  • Problem: the server sends only its own certificate (level 0) and not the intermediate. You can see it because only one entry appears under Certificate chain, whereas in the correct example in section 13 there were two.
  • Why it works in Laura's browser and not here: many browsers cache intermediates from earlier visits or download them automatically using the certificate's AIA field. openssl, API clients, phones and scripts do not. This is the exact mechanism by which a TLS configuration problem can go unnoticed for months: humans do not see it and automated integrations do.
  • Fix: configure the web server to send the complete chain (certbot's fullchain.pem file, not cert.pem). It is a classic configuration error when renewing by hand.
  • Subsequent verification: repeat openssl s_client -showcerts and check that levels 0 and 1 appear and that Verify return code is 0.

Solution to Exercise 3

1. Inventory of Rutalia's certificates

# Service Certificate type Recommended issuer
1 mirutalia.example, www., api. TLS server, public Let's Encrypt (ACME)
2 www.rutalia.example TLS server, public Let's Encrypt (ACME)
3 VPN concentrator TLS server, public A public CA (for client compatibility)
4 Mail server (SMTP/IMAP) TLS server, public Let's Encrypt (ACME)
5 Internal ERP TLS server, internal Internal CA or ACME with DNS validation
6 Internal administration panels TLS server, internal Internal CA
7 IoT probes and their concentrator TLS client and server Internal CA, one per device
8 Fleet tablets Client certificate (device identity) Internal CA, via MDM
9 Company representative certificate Qualified (eIDAS) Qualified provider
10 Email signing for senior management and administration Qualified or advanced Qualified provider
11 The ERP vendor's public key Custody of the public key only Supplied by the vendor

2. Renewal strategy

Item Strategy Why
1, 2, 4 Automatic (ACME/certbot), 90 days It is the only reliable method. Validated with certbot renew --dry-run after every server change
3 (VPN) Manual with alerts at 60 and 30 days Some concentrators do not support ACME. If the equipment allows it, automate
5, 6 ACME with DNS validation if the names sit under a domain of your own; otherwise an internal CA with a renewal script DNS validation works for services not exposed to the internet and allows wildcards
7, 8 Automatic via MDM and the provisioning system; long validity (2-3 years) with planned rotation These are thousands of renewals, unworkable by hand; and some devices are physically hard to reach
9, 10 Manual with an alert at 60 days and a named owner in administration It requires in-person identification before the provider; it cannot be automated

3. Detective controls

Control Frequency What it detects
The vigilar_certificados.py script over the whole inventory Daily, 07:30 Expiries, broken chains, already-expired certificates
certbot renew --dry-run Weekly and after every web server change That the automation will keep working
External monitoring of the website and the API Every 5 minutes Outages; it catches the silent integration failure from the March incident
Subscription to certificate transparency logs Continuous Improper issuance for Rutalia domains and lookalike phishing domains
Review of the inventory Quarterly New services nobody added to the inventory
Checking validation in clients (tablets, integrations) Annual Clients that do not validate the certificate, which annuls the whole of PKI

4. Organisational measures

  • Every supplier account in the company's name, with [email protected] — a shared mailbox with several owners — as the contact and as the recovery method. No corporate account may depend on one person's email.
  • A record of access to those accounts in the corporate password manager, with at least two people holding access.
  • A named owner and a deputy for each certificate in the inventory.
  • Include certificate revocation and account handover in the leaver procedure we designed in 02-02. The March incident was, fundamentally, an identity life cycle failure, not a cryptographic one.
  • Custody of the company certificate: on a smart card or marked as non-exportable, with an inventory of who can use it and a record of its use.

5. Emergency procedure (one page)

PROCEDURE EM-03: Certificate expired in production

Detection. An alert from the monitoring script, from external monitoring or a call from a customer.

Step 1 (5 min). Confirm the scope: openssl s_client -connect <host>:443 -servername <host> </dev/null | openssl x509 -noout -dates. Identify which services are affected, including the APIs, which fail silently.

Step 2 (5 min). Communicate. Post a notice on the incident channel and prepare a message for customer service: "we are resolving a technical issue with the portal's security certificate; there has been no unauthorised access to any data". Say explicitly that it is not a breach, because that is what customers are going to fear.

Step 3 (15 min). Attempt automatic renewal: sudo certbot renew --force-renewal -d <domain> and reload the web server. In most cases the incident ends here.

Step 4 (if it fails). Retrieve the provider's credentials from the corporate password manager (folder Infrastructure, access for Laura and Diego). Issue manually. If domain validation requires DNS, access to the DNS provider is in the same folder.

Step 5. Verify: openssl s_client -connect <host>:443 -servername <host> -showcerts </dev/null must return Verify return code: 0 and show the complete chain. Check from outside the corporate network too.

Step 6. Close: communicate the resolution, add the certificate to the inventory and to the monitoring script if it was not there, and log the incident for the subsequent review → Post-Incident Activity and Lessons Learned.

Contacts: IT on call · certificate provider (corporate account) · DNS provider · [email protected].

The essential thing about the procedure is that it should be executable by somebody who did not write it, on a Saturday, with no help. That is why it includes the literal commands and the exact location of the credentials.


Conclusion

You have closed the missing foundation. You now know what a cryptographic hash function is and which five properties make it useful — determinism, speed, the avalanche effect, preimage resistance and collision resistance — and why MD5 and SHA-1 are broken: not because they can be undone, but because two different documents can be manufactured with the same fingerprint, which turns a legitimate signature into a valid one for a contract nobody signed. You can tell the correct uses of hashes — integrity, fingerprints, indicators of compromise, components of other constructions — from the incorrect ones: storing passwords without a KDF, trusting a hash published next to the file it verifies, or believing that hashing an ID number anonymises it. You have understood what HMAC adds over a bare hash, why the intuitive construction SHA256(key + message) is broken, and you have applied it to a real MiRutalia webhook with a timestamp against replay and a constant-time comparison.

You have seen the digital signature from the inside: the digest is signed, not the document, and that is why a hash collision breaks it; it guarantees integrity, authenticity and non-repudiation, but not confidentiality, because signing is not encrypting. You have separated the technical concept of a digital signature from the legal concept of an electronic signature, with the three eIDAS levels and the realisation that only the qualified one is equivalent to a handwritten signature; and you have identified a very real and very poorly watched risk at Rutalia: an exportable company representative certificate on a machine with local administrator rights allows whoever compromises it to act legally on the company's behalf. You have understood PKI as the recursive application of the digital signature, with its hierarchy of an offline root and online intermediates — the same compartmentalisation principle you applied to administrative accounts in 02-02 — you have read an X.509 certificate field by field knowing that what counts is the SAN and not the CN, and you have followed the validation of a chain all the way to the trust store, understanding the uncomfortable consequence that any CA in that store can issue for any domain. You have studied revocation with its acknowledged weak point — soft failure — and why the industry has moved towards short expiry; you have walked through that Saturday in March, which cost five hours of portal downtime and whose root cause was not cryptographic but a non-existent leaver procedure; and you have discovered in certificate transparency one of the few controls that warn you before the phishing campaign begins. And you have built the expiry watchdog Rutalia did not have: a hundred-line script that would have prevented that Saturday entirely.

That closes Module 2. You have travelled the whole road from objectives to mechanisms: in 02-01 you turned three words into measurable objectives asset by asset; in 02-02 you decided who can do what and built the access matrix Rutalia never had; in 02-03 you reinforced the identity that holds up that matrix; in 02-04 you went down to the cryptographic foundations; and here you have learned how trust is distributed. These are the fundamentals, and you will not be coming back to them: from now on they are assumed.

Because it is time to apply them. In Module 3 we leave the concepts and enter the infrastructure, beginning with Network Fundamentals, where you will see how a packet really travels and why Rutalia's flat 10.10.0.0/16 network — without a single boundary between a driver's tablet, a cold store probe and the server holding the customer database — is the multiplier that turns any incident into a disaster. Then, in Network Security Protocols, you will meet everything from this module working at once and in real time: TLS is, literally, Diffie-Hellman to agree the key, X.509 certificates to authenticate the server, AES-GCM to encrypt the data and HMAC to protect it. When you see the full negotiation, you will not be learning anything new: you will be recognising pieces you already know, slotting into place.

© Copyright 2026. All rights reserved