The previous lesson ended with a warning: Rutalia's entire access matrix rests on a single assumption — that whoever says they are Laura, is Laura — and if that assumption fails, the most carefully crafted authorisation in the world becomes a detailed map you hand to the attacker. This lesson is devoted entirely to that assumption.

And there is a reason to give it a whole lesson: the stolen credential is today the dominant entry vector. Not the exotic vulnerability, not the zero-day exploit, but a username and a password that work. We saw it in 01-02 with the catalogue of credential attacks — brute force, dictionary, password spraying, credential stuffing — and we saw it in 01-04 when the initial access broker was selling VPN access to companies like Rutalia for a few hundred euros. The attacker does not break in: they sign in.

Here you will learn how passwords are stored correctly, why almost everything you were taught about password policies is out of date, which second factors resist phishing and which merely inconvenience it, and how MFA is rolled out in a real company with 60 drivers who wear gloves and use a tablet in the cab of a truck.

The password has one virtue that explains its survival: it is free, universal and needs no hardware. And it has a structural defect that no policy can fully correct: it is a secret the user has to remember and transmit, and anyone who obtains it is indistinguishable from its owner.

The failure modes, ordered by real frequency rather than by drama:

Failure mode How it happens What neutralises it
Reuse The same password at work and on a forum that suffers a breach Password manager + MFA
Phishing The user types it into a fake page convinced it is the real one Phishing-resistant MFA (FIDO2); everything else only makes it harder
Infostealer A malicious program extracts the passwords saved in the browser MFA + endpoint protection + not saving corporate credentials in the browser
Password spraying Rutalia2026! is tried against the company's 180 accounts Checking against breached lists + MFA + pattern detection
Credential stuffing Username/password pairs from third-party breaches are tried en masse The same, plus rate limiting
Store leak The password database is leaked and cracked Storage with a slow derivation function (section 3)
Sharing It is dictated over the phone, written on a sticky note, sent over WhatsApp Named accounts + a corporate password manager

Look at the right-hand column: MFA appears in six of the seven rows. That is, summarised in one table, why the second factor is the best cost-benefit investment in the whole of an SME's security.

One nuance about complexity that is worth understanding from the outset. There is a widespread intuition that a "hard" password protects you. It is true only against an attacker who guesses it, which is the least frequent scenario. Against phishing, infostealers and reuse, password complexity is entirely irrelevant: X7#pQ!9zK@2w is stolen exactly as easily as summer2026. Hence the modern approach has shifted the effort from "making passwords stranger" towards "making the password no longer sufficient on its own".

Rutalia's starting position:

  • No MFA on the VPN or on Microsoft 365.
  • An old policy of "8 characters with an uppercase letter, a number and a symbol, changed every 60 days", which produces Rutalia01!, Rutalia02!, Rutalia03!…
  • No checking against breached password lists.
  • No password manager: the credentials for the shared systems live in a spreadsheet called claves.xlsx in \\fs01\comun.
  • Active former-employee accounts, with passwords those people still remember.

  1. How passwords are stored badly

Before looking at what is right, we need to understand why the intuitive alternatives fail. This section matters even if you do not develop software: it is what lets you ask a supplier "how do you store passwords?" and know whether the answer is acceptable.

Level 0: in the clear

user    | password
--------+-----------------
mruiz   | Zaragoza2024
dsalas  | Camiones!23

Any leak of the database hands over every password of every user, and — through reuse — their personal accounts too. Surprisingly it still turns up in small applications and in in-house developments like Rutalia's legacy ERP. An unmistakable signal: if a system can email you your current password when you forget it, it is storing it in the clear or reversibly. A correct system cannot know what your password is; it can only let you set a new one.

Level 1: a plain hash (MD5, SHA-1, bare SHA-256)

The right idea is not to store the password but its hash: a digest from which you cannot work backwards. The problem is not the idea, it is the choice of function.

user    | sha256(password)
--------+-------------------------------------------------------------------
mruiz   | 8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918

Two failings, both serious:

  • These are deliberately fast functions. SHA-256 is designed to process gigabytes per second. That, a virtue when verifying files (we used it in 02-01), is a disaster here: a consumer graphics card computes on the order of thousands of millions of SHA-256 hashes per second. Trying a dictionary of a million passwords is a matter of milliseconds.
  • The same password always produces the same hash. This enables two attacks: precomputed tables (the hashes of millions of common passwords are computed once and then looked up) and the direct observation that two users with the same hash have the same password.

Level 2: salted hash, but fast

The salt is a random value, different for each user, that is concatenated with the password before the hash is computed and stored alongside it.

user    | salt                 | sha256(salt + password)
--------+----------------------+-----------------------------------
mruiz   | 4f2a9c1e7b3d6a08     | a91c...
dsalas  | e70b3f5c2a9d18e4     | 7d42...

The salt is not secret: it is stored in the clear next to the hash. Its purpose is not to hide anything but to guarantee that each password has to be attacked separately. With a salt:

  • Precomputed tables stop being useful: you would need a table per salt.
  • Two users with the same password have different hashes.

But it is still far too fast. With a list of 180 users, an attacker with a GPU can attack each one individually and still recover every weak password within hours. The salt solves half the problem; the other half is missing.


  1. How they are stored well: salt and slow derivation functions

The solution is to use a function that is deliberately expensive to compute. These are called key derivation functions (KDFs) or password hashing functions, and the main ones are bcrypt, scrypt and Argon2.

The idea of a work factor

A KDF has a parameter that controls how long it takes to compute. The logic is asymmetric and very elegant:

Who How many times they compute it Cost of it taking 250 ms
The legitimate server, validating a sign-in Once per sign-in Imperceptible to the user
The attacker, trying a dictionary Millions or thousands of millions of times Turns "hours" into "centuries"

If a KDF takes 250 milliseconds, an attacker can try around 4 passwords per second per core, as against the thousands of millions per second of SHA-256. It is a difference of about nine orders of magnitude, and it is the whole defence.

That parameter is called the cost factor or work factor, and it has a very useful property: it can be raised over time. As hardware improves, every few years the cost factor is increased to maintain the same computation time. The bcrypt and Argon2 formats store the cost used inside the hash itself, so that old passwords still validate and can be re-hashed with the new cost the next time the user signs in.

Comparing the three functions

Function Year Adjustable cost GPU-resistant ASIC/FPGA-resistant When to choose it
bcrypt 1999 Yes (cost factor) Fairly Not much Very widely deployed, mature and available in every language; a safe, simple option. Limits the password to 72 bytes
scrypt 2009 Yes (CPU + memory) Yes Fairly When a memory cost is wanted and Argon2 is not available
Argon2 (the Argon2id variant) 2015 Yes (time, memory, parallelism) Yes Yes The current default recommendation for new systems

The innovation in scrypt and Argon2 is to demand memory, not just time. A GPU has thousands of cores but little memory per core; forcing each computation to use, say, 64 MB of RAM cancels out much of the specialised attacker's advantage. Argon2id combines defence against dedicated-hardware attacks with defence against side-channel attacks, and that is why it is the recommended option today for a new development such as a future evolution of MiRutalia.

Rule of thumb. Never implement this yourself. Use your language's standard library or a widely audited library, with the default parameters its documentation recommends. Section 11 shows how to do it with bcrypt in Python.

One final concept, optional but useful: the pepper is a secret value common to the whole application, stored not in the database but in the server configuration or in a hardware module. If the database leaks but the configuration does not, the attacker cannot even begin to try. It is an extra layer, not a substitute for the salt.

(Exactly what a hash function is, which mathematical properties make it trustworthy and why MD5 and SHA-1 are broken is studied in Hashes, Digital Signatures and Certificates (PKI). Here it is enough to know that it digests without allowing you to work backwards.)


  1. Password policy: the old rule versus current guidance

For twenty years, password policies were based on a recommendation from the late 1990s that its own author later acknowledged as mistaken. Current guidance — NIST SP 800-63B internationally, and in Spain the recommendations of INCIBE (Spain's National Cybersecurity Institute) and the CCN-STIC guidelines of the National Cryptologic Centre — has shifted substantially, based on how people actually behave.

Old rule Current recommendation Why the change
8 characters minimum 12 characters minimum for users; 15 or more for privileged accounts Computing power has grown; 8 characters no longer protect against an attack on a leaked hash
Require uppercase + lowercase + digit + symbol Do not impose composition; allow any character, including spaces and emoji Composition rules produce predictable patterns (Name123!) that attack dictionaries already cover. They add little real entropy and a great deal of frustration
Expiry every 30-90 days Do not force periodic change without an indication of compromise A forced change produces Rutalia01! → Rutalia02!. It degrades quality instead of improving it. It must be changed immediately on suspicion of compromise
Prevent reuse of the last 5 Keep the history and do not force expiry If there is no forced expiry, the history stops being the battleground
Security questions ("your first pet's name") Remove them The answers are public or guessable; they are a weaker recovery vector than the password itself
Always mask what is typed Allow the password to be revealed temporarily It reduces typing errors and makes long passwords usable on phones and tablets
Forbid pasting from the clipboard Allow pasting Forbidding it prevents the use of password managers, which is the best control available
No external checking Compare against breached password lists and against context words It attacks the real cause: passwords already known to attackers
A short maximum length (16) Allow at least 64 characters A low maximum length suggests incorrect storage and rules out passphrases

Passphrases

The practical consequence of this shift is that the best password a person can memorise is a passphrase: several unrelated words, easy to remember and long.

Memorable example:   horse-coldstore-Ebro-42-monday
"Complex" example:   X7#pQ!9z

The first has 30 characters and is remembered by picturing the scene. The second has 8 and will end up written on a sticky note. From the point of view of resistance to an attack on the hash, the first is orders of magnitude stronger.

An important warning: the strength of a passphrase lies in the words being chosen at random, not picked by the person. i-love-real-zaragoza is a long and predictable phrase. The robust way to generate them is to let the password manager do it.

The policy Rutalia adopts

# politica_contrasenas.ini — Rutalia Logística S.L.
# Approved by senior management. Reviewed annually.

[general]
minimum_length             = 12
minimum_length_privileged  = 15
maximum_length             = 128
mandatory_composition      = none
expiry_days                = 0        ; no forced expiry
change_if_compromised      = immediate
password_history           = 5
security_questions         = disabled
allow_paste                = yes
reveal_while_typing        = optional

[checks]
breached_list              = yes      ; reject passwords known from breaches
banned_words               = rutalia, logistica, zaragoza, valencia, sevilla, camion, 2025, 2026
similarity_to_username     = reject   ; must not contain the username or the person's own name

[lockout]
attempts_before_delay      = 5
progressive_delay          = 1m, 5m, 15m, 30m   ; never a permanent lockout
alert_threshold_by_source  = 20 failures from one IP in 10 minutes

[mfa]
mandatory_on               = vpn, m365, administrative_accounts, mirutalia_admin

Comments on the decisions that generate most debate:

  • expiry_days = 0 is the one that meets most resistance in an audit, because it contradicts custom. The argument behind it is twofold: forced expiry worsens password quality, and the right response to a compromise is not to wait 90 days, it is to change it today. If a customer or an auditor contractually demands expiry, a long period (12 months) is applied and documented.
  • progressive_delay instead of a permanent lockout is the decision we took in 02-01 when analysing the tension between confidentiality and availability: a permanent lockout turns a security control into a denial-of-service tool against your own workforce.
  • alert_threshold_by_source detects password spraying, which does not trip the per-account counters because it tries one password against many accounts. Watching only per-user failures leaves this attack invisible: you have to watch by source IP as well.

  1. Checking against breached password lists

This is by some distance the password control with the best effort-to-result ratio, and hardly any SME applies it.

The idea: there are public compilations of hundreds of millions of passwords that have appeared in known breaches. If the password the user wants to set is on that list, it is already in every attacker's dictionary, and its length or complexity are irrelevant. It is rejected at the moment it is set.

An important privacy detail: never send the password, nor its full hash, to an external service to check it. The correct method is called k-anonymity: the hash is computed locally, only the first five characters of the hash are sent, the service returns every hash starting with that prefix (a few hundred), and the final comparison is done locally. That way the service never knows which password was being checked.

# comprobar_filtrada.py — checking with k-anonymity
import hashlib
import requests

def is_breached(password: str) -> int:
    """Return how many times the password appears in known breaches (0 = it does not)."""
    # 1. SHA-1 hash of the password, in uppercase (the service's format)
    digest = hashlib.sha1(password.encode("utf-8")).hexdigest().upper()

    # 2. Split into prefix (5) and suffix (the rest)
    prefix, suffix = digest[:5], digest[5:]

    # 3. Only the PREFIX travels over the network
    response = requests.get(
        f"https://api.pwnedpasswords.com/range/{prefix}",
        headers={"Add-Padding": "true"},
        timeout=5,
    )
    response.raise_for_status()

    # 4. The comparison is done LOCALLY, against the returned list
    for line in response.text.splitlines():
        returned_suffix, count = line.split(":")
        if returned_suffix == suffix:
            return int(count)
    return 0

An explanation of the points that matter:

  • SHA-1 is used not for security but because it is the format that particular service requires. The security here does not come from the algorithm but from the fact that only 5 characters of the hash are transmitted.
  • digest[:5] leaves several hundred possible candidates for each prefix, which makes it unworkable to deduce which password was being queried.
  • Add-Padding: true asks the service to pad the response with fake entries, so that the size of the response does not leak information. It is a defence against traffic analysis, and a good example of privacy escaping through unexpected places.
  • timeout=5 is mandatory: if the external service does not answer, user registration cannot hang. And you have to decide consciously what happens on failure: allow and log (availability) or reject (security). For Rutalia, allow and log, because preventing somebody from changing their password because of an external outage is worse.
  • The function returns the number of occurrences, which allows graduated policies: reject if it appears more than 10 times, warn if it appears once or twice.

In Rutalia's environment there is also an equally valuable local check: banning context words (rutalia, zaragoza, camion, the current year). An attacker preparing a targeted attack will build their dictionary from exactly those words.


  1. Password managers

If the problem is that people cannot remember 40 long, distinct passwords, the solution is not to ask them to: it is for them not to have to.

How it works under the bonnet

graph LR
    MC["Master password<br/>(only the user knows it)"] --> KDF["Slow derivation<br/>function (Argon2/PBKDF2)"]
    KDF --> K["Encryption key<br/>(never leaves the device)"]
    K --> B["Encrypted vault<br/>(AES-256)"]
    B -->|synced while encrypted| S["Provider's<br/>server"]
    S -.->|cannot decrypt| X["The provider does NOT have<br/>the key or the master password"]
    style X fill:#e6f4ea,stroke:#137333

The key pieces:

  1. The user remembers one single master password, long and unique.
  2. From it an encryption key is derived using a slow function (the same ones from section 3).
  3. That key encrypts the vault, where all the other credentials live.
  4. Encryption and decryption happen on the user's device. The provider's server stores and syncs an encrypted block it cannot read. This is what is called a zero-knowledge architecture.

From which follows the most important consequence: if the master password is forgotten, the vault is lost. No recovery is possible, because the provider does not have the key. That is why every serious manager issues an emergency recovery code that has to be printed and kept physically.

The real risks, stated honestly

Risk Reality Mitigation
"You put all your eggs in one basket" True, but the real alternative is not "many secure baskets": it is the same password everywhere A strong master password + MFA on the manager itself
The provider suffers a breach It has happened in the sector. Vaults come out encrypted, but metadata (which sites you use) can be exposed, and a weak master password could be attacked at leisure A long, unique master password; high derivation parameters; change the master password if there is a notice
Malware on the machine If the machine is compromised while the vault is unlocked, contents can be extracted Automatic locking on inactivity; endpoint protection → 04-02
The user also stores MFA codes there It reduces the second factor to "something you know" if it shares a container with the password Keep the second factor on a different device or app for critical accounts

Rolling it out in an SME like Rutalia

A concrete recommendation, in order:

  1. Choose a manager with a team edition, with shared folders and access logging. The key is not the product, it is that it allows sharing without revealing: that somebody can use a credential without having it dictated to them over the phone.
  2. Start with IT and administration, who handle the most sensitive credentials.
  3. Migrate claves.xlsx immediately. That spreadsheet in \\fs01\comun is, today, Rutalia's most dangerous asset: a single file readable by the entire workforce holding the keys to the systems. When migrating, every password it contained must be changed: they have to be assumed compromised, because they have been accessible to 180 people for years.
  4. Shared folders per team, aligned with the roles in the 02-02 matrix.
  5. Mandatory MFA on the manager itself.
  6. A documented emergency procedure: who holds break-glass access if Laura is unavailable, where the recovery code is (a sealed envelope in the safe, with a record of any opening).
  7. Twenty minutes of training, and allow personal use of the tool: if the employee uses it at home too, they genuinely adopt it.

  1. MFA: the factors in practice

Multi-factor authentication combines proofs from different categories (lesson 02-02, section 3). What matters here is not the concept but that not all second factors protect equally. The difference between them is not one of degree: it is qualitative.

Method Factor Security Cost Usability Phishing-resistant?
SMS / phone call Possession (weak) Low Low (per-message cost) High: everyone has a phone No
Email Knowledge in disguise Very low None High No
TOTP (6-digit code in an app) Possession Medium-high None Medium: you have to open the app and type No
Push notification (approve/deny) Possession Medium Low Very high No
Push with number matching Possession Medium-high Low High Partially
FIDO2 / WebAuthn key (USB or NFC) Possession (strong) Very high €25-60 per key (order of magnitude) High once set up Yes
Passkey (on phone or laptop) Possession + inherence Very high None Very high Yes
Certificate on a card or device Possession High Medium Medium Yes
Local biometrics (fingerprint, face) Inherence High as an unlock None Very high Yes, when it protects a passkey

Why the right-hand column decides everything

A second factor that is not phishing-resistant can be intercepted by a fake page: the user enters their password and the 6-digit code as well, and the attacker relays both to the real site in real time. The code is valid for 30 seconds; the attacker has time to spare.

A phishing-resistant second factor (FIDO2/WebAuthn and passkeys) cannot be intercepted, for a reason rooted in its design: the credential is cryptographically bound to the real domain. If the user is on mirutalia-clientes.example.net instead of the genuine domain, the key simply does not respond. There is nothing the user can mistype, because they type nothing. It is the only method where security does not depend on the person spotting the deception.

This leads to a practical hierarchy worth being clear about:

Any MFA is vastly better than none. SMS stops credential stuffing, spraying and the use of leaked credentials, which are the majority of automated attacks. But only FIDO2/passkeys stop targeted phishing. The sensible strategy in an SME is: MFA for everybody, and physical keys for the administrators and senior management, which is where the attack will be targeted and where the impact is total.

A note on email as a second factor: it is not one. If the attacker has the user's password and that user reuses credentials, they probably have their email too. Sending the code to the very place that is already compromised adds nothing.


  1. Attacks against MFA and how they are mitigated

Switching MFA on does not close the matter. Attackers adapted, and it is worth knowing the three main techniques.

SIM swapping

The attacker convinces the mobile operator to port the victim's number to a SIM in their possession, supplying personal details obtained beforehand. From that moment on they receive every SMS, including verification codes and recovery links.

  • Typical target: executives and people with access to payments. At Rutalia, Andrés Vidal and Nuria Campos.
  • Mitigation: do not use SMS as a second factor on critical accounts; enable a port-out block or an account PIN with the operator; do not use the phone number as a recovery method for corporate accounts.

MFA fatigue (or push bombing)

The attacker, who already has the password, fires off dozens of push approval requests at 3 a.m. The victim, exhausted or confused, ends up pressing "Approve" to make them stop. It is a purely psychological attack and it has worked against large, well-prepared organisations.

  • Mitigation 1: number matching. The sign-in screen shows a two-digit number that the user has to type into the app. Pressing a button is no longer enough: you have to be looking at the legitimate screen. It eliminates accidental approval.
  • Mitigation 2: limit the number of requests per user per minute, and alert when the limit is exceeded.
  • Mitigation 3: show context in the notification (application, approximate location, IP). "Sign-in from Amsterdam" is a signal the user does understand.
  • Mitigation 4, and the definitive one: move to phishing-resistant factors, where this attack does not exist.
  • Cultural mitigation: teach everybody that an unexpected notification is not simply denied and forgotten: it is denied and reported to [email protected], because it means somebody has the password.

Reverse-proxy phishing (adversary in the middle)

This is the attack that makes code-based MFA irrelevant. How it works:

sequenceDiagram
    participant V as Victim<br/>(Marta Ruiz)
    participant P as Attacker's proxy<br/>login-rutalia.example.net
    participant R as Real site<br/>login.microsoftonline.com

    V->>P: Follows a link from the email
    P->>R: Forwards the request
    R-->>P: Genuine sign-in page
    P-->>V: Shows the page (it is the real one, relayed)
    V->>P: Username + password
    P->>R: Username + password
    R-->>P: Asks for the MFA code
    P-->>V: Asks for the MFA code
    V->>P: TOTP code (valid 30 s)
    P->>R: TOTP code
    R-->>P: Signed in + SESSION COOKIE
    P->>P: The attacker steals the cookie
    Note over P,R: The attacker is already inside.<br/>They need neither the password nor MFA again.

The victim sees the real page — because it is the real page, relayed — and everything works. The attacker does not keep the password: they keep the already-authenticated session cookie, which lets them get in without going through any factor again.

  • The real and only mitigation: FIDO2/WebAuthn. The credential is bound to the domain, and the browser refuses to use it on login-rutalia.example.net. The attack fails without the user having to suspect a thing.
  • Partial mitigations: conditional access requiring a managed device (the stolen cookie is useless from another machine), short session lifetimes for privileged accounts, detection of simultaneous sessions from impossible locations, and monitoring for domains that look like your own — which connects to certificate transparency in 02-05.

And the attack that is not technical

The password reset by telephone. The attacker rings the help desk posing as an employee who has lost their phone and needs MFA "temporarily disabled". In a company of 180 people where everybody knows each other by sight, it works more often than you would think. The defence is in section 13.


  1. Going passwordless: passkeys

The logical conclusion of all the above is to do away with the password. Not as a marketing slogan, but because the memorised secret is the component that gets stolen.

How a passkey works

A passkey is a pair of cryptographic keys — public and private — generated for a specific site:

  1. On registration, the device generates the pair. The private key never leaves the device; it is protected by its secure hardware and unlocked with a fingerprint, a face or a local PIN.
  2. The public key is sent to the server and stored there.
  3. On sign-in, the server sends a random challenge; the device signs it with the private key; the server verifies the signature with the public key.

The consequences are remarkable:

Property Practical consequence
The server only stores public keys A database breach exposes no usable credentials. The problem in section 2 disappears
The private key never travels There is nothing to intercept in transit
The credential is bound to the domain Phishing and reverse proxying do not work
There is nothing to remember No reuse, no sticky notes, no fatigue
Unlocking is by local biometrics The biometric data never leaves the device: the server never sees your fingerprint

(The public-key cryptography underneath — key pairs, signing and verification — is exactly the content of Basic Cryptography and 02-05. If it sounds like magic now, in two lessons it will not.)

Honest limitations

  • It requires the service to support it. Rutalia's legacy ERP never will.
  • Recovery: if the user loses the only device holding the passkey, a way back has to be planned for (section 13). Passkeys synced between devices in the same ecosystem ease this, at the cost of trusting the syncing provider.
  • Shared environments: on a warehouse terminal used by three shifts, a device-bound passkey does not fit well. Physical keys that each person carries work better there.

For Rutalia, the realistic recommendation in 2026 is: passkeys and FIDO2 keys where the system allows it (Microsoft 365, MiRutalia if Marta implements it), TOTP where it does not, and no SMS except as a last resort.


  1. Privileged accounts (PAM) and service accounts

In 02-02 we separated Diego's day-to-day account (dsalas) from his administrative one (adm-dsalas). Privileged Access Management (PAM) is the set of practices surrounding those administrative accounts.

The five elements, from lowest to highest implementation cost:

Element What it is Affordable version for an SME
Inventory of privileged accounts Knowing which they are and who uses them A maintained spreadsheet, reviewed quarterly. Without this, none of the rest is possible
Credential vault Nobody knows the administrative passwords: they are requested from the vault The corporate password manager with a restricted folder and access logging
Temporary elevation (just-in-time) The privilege is granted on request and expires by itself An administrative account disabled by default, enabled against a ticket and disabled on closure
Session recording There is a record of what was done with the privilege Reinforced logging of the adm-* accounts, centralised away from the administered server
Break-glass The emergency account for when everything fails A long, random password in a sealed envelope in the safe, with an automatic alert if it is used

The break-glass account deserves an explanation, because it is counterintuitive: it is an account with maximum privilege, without MFA — precisely so that it works when the MFA system is down — and whose security rests on three things: an extremely long, random password, physical custody with a record of any opening, and an immediate alert as soon as it is used. Without it, a failure of the identity provider leaves the company unable to administer anything; with it badly managed, it is the finest back door imaginable. It is documented, tested once a year and its password is changed after every use.

Service accounts

Picking up what we saw in 02-02, from the credential's point of view:

  • Very long, random passwords (30+ characters): nobody types them, so there is no reason for them to be short.
  • Stored in a secrets manager or in environment variables, never in the code nor in version control. MiRutalia's case, with the connection string in config.py, is exactly what needs correcting.
  • No MFA (a program cannot supply a second factor), which is compensated for with source restriction: that account can only connect from the application server's IP address.
  • Planned and tested rotation, with a documented named owner.
  • An alert if they are used from an unexpected origin, which is the clearest sign of compromise this kind of account will give.

  1. Hands-on 1: bcrypt in Python, step by step

Let us see how a password is stored and verified correctly. Marta Ruiz needs it for MiRutalia; you need it in order to understand what any system handling credentials must do.

pip install bcrypt
# contrasenas.py — Password storage and verification for MiRutalia
import bcrypt
import time

# ---------------------------------------------------------------
# 1. CREATE the hash when the user sets their password
# ---------------------------------------------------------------
password = "horse-coldstore-Ebro-42".encode("utf-8")

# The "cost factor" is the exponent of the iteration count: 2^12 = 4096 rounds
salt = bcrypt.gensalt(rounds=12)
stored_hash = bcrypt.hashpw(password, salt)

print(stored_hash.decode())
# $2b$12$KIXQ0s1mGz7uY9pQ3vN2SuJ5hV8wL0aR6tB4cD1eF3gH2iJ7kL9mO

# ---------------------------------------------------------------
# 2. VERIFY on every sign-in
# ---------------------------------------------------------------
attempt = "horse-coldstore-Ebro-42".encode("utf-8")
if bcrypt.checkpw(attempt, stored_hash):
    print("Password correct")
else:
    print("Password incorrect")

# ---------------------------------------------------------------
# 3. MEASURE the cost, in order to calibrate the parameter
# ---------------------------------------------------------------
for cost in (10, 12, 14):
    start = time.perf_counter()
    bcrypt.hashpw(b"performance-test", bcrypt.gensalt(rounds=cost))
    print(f"rounds={cost}: {time.perf_counter() - start:.3f} s")

Anatomy of the resulting hash

The stored value is not just the hash: it is a self-describing string.

$2b$12$KIXQ0s1mGz7uY9pQ3vN2Su  J5hV8wL0aR6tB4cD1eF3gH2iJ7kL9mO
└┬┘ └┬┘ └──────────┬─────────┘  └──────────────┬──────────────┘
 │   │             │                           │
 │   │             │                           └─ Hash (31 characters)
 │   │             └─ Salt (22 characters, randomly generated)
 │   └─ Cost factor: 12 → 2^12 = 4096 iterations
 └─ Algorithm identifier (bcrypt variant)

This explains several things at once:

  • The salt travels inside the hash, so it does not need storing in another column. checkpw extracts it from there in order to recompute.
  • The cost factor travels inside too, which allows it to be raised in future without invalidating old hashes: each is verified with the cost it was created with.
  • Two users with the same password will have completely different hashes, because the salt is different.

The four details you have to understand

  1. gensalt(rounds=12): the cost is exponential. Going from 12 to 13 doubles the time. The standard calibration criterion is to tune it so that the computation takes between 200 and 500 ms on the production hardware. Less is handing the attacker free speed; more leaves the server out of CPU when 50 people sign in at once at 08:00.

  2. checkpw and not ==: never compare hashes with the ordinary equality operator. checkpw performs a constant-time comparison, which takes the same time whether it matches or not. A normal comparison stops at the first differing byte, and that difference of microseconds, measured thousands of times, can leak information. It is called a timing attack, and it is why hmac.compare_digest exists in the standard library.

  3. bcrypt's 72-byte limit: bcrypt silently ignores anything beyond 72 bytes. With a long passphrase or with non-ASCII characters (which take several bytes) this can come as a surprise. If you need to accept arbitrarily long passwords, use Argon2id, or apply a SHA-256 first and encode the result — but carefully, because done casually it introduces other problems. It is a good example of why you do not improvise in cryptography.

  4. The same response time when the user does not exist: if your code answers immediately when the user does not exist and takes 300 ms when they do, you have just built a user enumerator. The solution is always to verify against a dummy hash:

DUMMY_HASH = bcrypt.hashpw(b"nonexistent-user", bcrypt.gensalt(rounds=12))

def verify(username: str, password: str) -> bool:
    record = find_user(username)
    if record is None:
        # The same time is spent even though the user does not exist
        bcrypt.checkpw(password.encode(), DUMMY_HASH)
        return False
    return bcrypt.checkpw(password.encode(), record.hash)

Transparent re-hashing when the cost is raised

When the decision is taken to raise the cost from 12 to 13, nobody has to be asked to change their password:

CURRENT_COST = 13

def verify_and_upgrade(username, password: str) -> bool:
    record = find_user(username)
    if not bcrypt.checkpw(password.encode(), record.hash):
        return False

    # The cost is in characters 4 and 5 of the hash: "$2b$12$..."
    stored_cost = int(record.hash.decode()[4:6])
    if stored_cost < CURRENT_COST:
        new_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt(CURRENT_COST))
        save_hash(username, new_hash)   # updated without disturbing the user
    return True

Only at the instant of a successful sign-in is the password available in the clear, and that is the only moment at which the hash can be regenerated. Taking advantage of it is the elegant way to migrate an entire system without anybody noticing.


  1. Hands-on 2: TOTP, how it works under the bonnet

TOTP (Time-based One-Time Password) is the algorithm behind the 6-digit codes that change every 30 seconds. Understanding its mechanics explains its virtues and its limits all at once.

The idea

graph LR
    S["Shared secret<br/>(generated on activation)"] --> A["Phone app"]
    S --> B["Server"]
    T["Current time<br/>divided by 30 s"] --> A
    T --> B
    A --> C1["HMAC-SHA1 to 6 digits"]
    B --> C2["HMAC-SHA1 to 6 digits"]
    C1 -->|the user types them| D{"Do they match?"}
    C2 --> D
    style S fill:#fef7e0,stroke:#b06000

Three ingredients: a shared secret (the QR code you scan when activating it), time divided into 30-second intervals, and an HMAC function. Both sides compute the same thing, separately, without communicating. The code travels nowhere except when the user types it.

The implementation, commented

# totp.py — Teaching implementation of TOTP (RFC 6238)
# In production use a proven library (pyotp). This is for UNDERSTANDING it.
import base64
import hashlib
import hmac
import secrets
import struct
import time


def generate_secret() -> str:
    """Generate the shared secret (20 bytes) in Base32, as the app expects."""
    return base64.b32encode(secrets.token_bytes(20)).decode("utf-8")


def totp(secret_b32: str, moment: float | None = None,
         period: int = 30, digits: int = 6) -> str:
    # 1. The secret is stored in Base32; it has to go back to bytes
    key = base64.b32decode(secret_b32, casefold=True)

    # 2. Counter: how many 30 s periods have passed since 1970
    counter = int((moment or time.time()) // period)

    # 3. The counter is packed as an 8-byte big-endian integer
    message = struct.pack(">Q", counter)

    # 4. HMAC-SHA1 of the counter using the secret as the key -> 20 bytes
    digest = hmac.new(key, message, hashlib.sha1).digest()

    # 5. "Dynamic truncation": the low 4 bits of the last byte
    #    say from which position to read 4 bytes
    offset = digest[-1] & 0x0F
    chunk = digest[offset:offset + 4]

    # 6. Convert to an integer and discard the sign bit
    value = struct.unpack(">I", chunk)[0] & 0x7FFFFFFF

    # 7. Keep the last 6 digits, padding with zeros
    return str(value % (10 ** digits)).zfill(digits)


def verify_totp(secret_b32: str, code: str, window: int = 1) -> bool:
    """Accept the current code and 'window' periods before and after."""
    now = time.time()
    for drift in range(-window, window + 1):
        candidate = totp(secret_b32, now + drift * 30)
        if hmac.compare_digest(candidate, code):
            return True
    return False


if __name__ == "__main__":
    s = generate_secret()
    print("Secret (scan as a QR code):", s)
    c = totp(s)
    print("Current code:", c, "| valid?", verify_totp(s, c))

The seven steps, explained

  1. Base32 and not hexadecimal because it is what authenticator apps expect in the QR code, and because it uses only uppercase letters and digits, with no ambiguous characters, which makes it possible to type it by hand if the camera fails.
  2. int(time // 30) is the whole "time ingredient": the number of 30-second intervals elapsed since 1 January 1970. As both sides use the same universal reference, they do not need to communicate. This is where the requirement for synchronised clocks comes from.
  3. struct.pack(">Q", counter) converts the number to 8 bytes in big-endian order. The exact format is fixed by the standard: change the byte order and your code will not match that of any app on the market.
  4. HMAC-SHA1: the secret acts as the key. Using HMAC and not a bare hash is essential, and why is explained in 02-05. SHA-1 here is not a security problem: HMAC-SHA1 remains sound and the standard fixed it that way.
  5. Dynamic truncation: the last byte is taken, its low 4 bits are read (a value from 0 to 15) and used as the position from which to read 4 bytes. It is a trick to make the part of the digest used vary, rather than always using the same one, without depending on anything secret.
  6. & 0x7FFFFFFF zeroes the most significant bit. It is pure pragmatism on the standard's part: it avoids problems with signed integers in languages that have no unsigned ones.
  7. % 10**6 and zfill(6): the remainder of dividing by a million gives the 6 digits, and zfill pads with leading zeros. Without zfill, the code 042318 would be shown as 42318 and verification would fail: it is the number one mistake when implementing TOTP by hand.

The tolerance window and the trade-off it contains

verify_totp accepts the current code and one before and one after. This exists for two real reasons:

  • Clock drift: the driver's phone may be 20 seconds fast.
  • Human latency: the user takes time to type and the code changes while they do.

And it contains a classic trade-off between security and usability:

Window Effective validity Consequence
0 30 s Many legitimate failures; frustrated users
1 90 s Recommended: the standard balance
3 210 s Too much margin for a code stolen by phishing

And two rules that always accompany TOTP in production:

  • A used code cannot be used again. The consumed counter has to be recorded per user and repetition rejected; otherwise an attacker who captures the code by phishing has up to 90 seconds to reuse it.
  • Attempt limiting. Six digits are a million combinations: with no limit on attempts, an automated attacker gets a hit. With 5 attempts per period, the probability is negligible.

What TOTP does not solve

Go back to the diagram in section 8: if the user types the code into a fake page that relays it in real time, the code is perfectly valid and the attacker gets in. TOTP protects against password theft, spraying and credential stuffing — that is, against the vast majority of automated attacks — but not against targeted phishing. That explains everything about why FIDO2 keys exist.


  1. Access recovery: the back door to the whole system

This is the section almost every course leaves out and the one many real attacks come through. It does not matter how robust your MFA is: if it can be switched off with a phone call, your MFA is worth whatever that phone call is worth.

The golden rule:

The recovery process cannot be weaker than the authentication process it replaces. If getting in requires two factors, recovering access must require an identity guarantee that is at least equivalent.

Rutalia's procedure

Case 1: forgotten password (user with MFA still active)

  1. Self-service: the user requests a reset.
  2. The second factor is required, which they still have.
  3. A single-use link, expiring in 15 minutes, is sent to their corporate address.
  4. They set a new password, which goes through the breached-list check.
  5. All active sessions are closed and the user is notified over an alternative channel.

Case 2: second factor lost (phone broken, stolen or key mislaid)

This is the critical case. The procedure:

  1. The user uses one of the recovery codes issued when MFA was activated (10 single-use codes, handed over printed, to be kept away from the phone). If they have one, they are done.
  2. If they do not, identity verification in person or by video call with their line manager, who confirms they are who they say. At Rutalia, with three warehouses, the video call is the realistic option.
  3. IT records the case with who requested it, who verified it and who carried it out. It is never carried out by the same person who verified it in the case of a privileged account.
  4. MFA is reset, not disabled: a new factor is registered there and then. An MFA "temporarily disabled until I buy another phone" stays disabled for three months.
  5. The user is notified over a different channel from the one used in the request: if they asked by email, they are called by phone. That way, if the requester was an impostor, the legitimate user finds out.

Case 3: privileged or senior management account

Mandatory in-person verification, approval by a second manager and automatic notification to [email protected]. The cost of a fraud here is total.

Rules that always apply

  • Never reset credentials on an incoming phone call without independent verification. If somebody rings Diego saying they are a driver who has lost their phone, Diego rings back on the number held in the HR file. Never the one he is given.
  • Recovery codes are issued once, kept away from the device they protect (on paper or in the password manager, which has its own MFA) and regenerated when used.
  • Every recovery generates a log entry and a notification. It is the event an attacker would most like to go unnoticed.
  • Administrators themselves need a recovery route: the break-glass account from section 10.

  1. An MFA rollout plan for Rutalia

Laura has 180 employees, two people in IT and no approved budget yet. This is the realistic, phased plan she can take to the board.

Principles of the plan

  1. Start where the risk is greatest, not where it is easiest.
  2. Never roll out without a pilot. A badly executed mass rollout swamps Diego and burns Laura's credibility for two years.
  3. Communicate before, during and after. Resistance to MFA is nearly always a communication problem, not a technology one.
  4. Have the recovery procedure ready before switching anything on.

Phase 0 — Preparation (weeks 1-2)

  • An inventory of accounts: active, inactive, service, former employee, supplier.
  • Disable the former employees' accounts. Zero cost, a risk eliminated immediately, and it is the measure that best shows senior management the project is worth something.
  • Draft the recovery procedure (section 13) and get it approved.
  • Prepare the communication: what MFA is, why, what is going to change and who to call.

Phase 1 — Administrative accounts (weeks 3-4)

Scope 2 sysadmins, the adm-* accounts, the M365 and AWS administration accounts
Method FIDO2 keys, two per person (a main one and a spare kept in the safe)
Cost 4-6 keys, of the order of a few hundred euros
Why first It is where a compromise means the end of the company. And it is two people: the perfect pilot

This is also where the separation of Diego's accounts that we designed in 02-02 is carried out: dsalas for day-to-day work, adm-dsalas with a physical key.

Phase 2 — VPN and remote access (weeks 5-7)

Scope All users of the VPN hastily set up in 2020
Method TOTP in a mobile app; a FIDO2 key for anyone who already has one
Why now It is the door the initial access broker would sell. It is the vector for H1
Risk of the change High in usability terms: it affects remote working. It needs a pilot with 5 volunteers over a week

Phase 3 — Microsoft 365 (weeks 8-12)

Scope The ~110 users with a mailbox
Method Push with number matching, or TOTP; passkeys for anyone who wants them
Internal priority Senior management and administration first: they are the target of H2 (BEC)
Essential extra Review the existing auto-forwarding rules: a rule forwarding email to an external mailbox is the signature of an account that is already compromised, and it survives MFA
Complement Conditional access: alert on sign-ins from countries where Rutalia does not operate

Phase 4 — The 60 drivers (weeks 10-16)

This is the difficult group, and it deserves a design of its own rather than forcing the general solution on it:

Real constraints: gloves, a moving cab, a small screen, patchy coverage on the road, limited familiarity with technology, and a tablet they sometimes share between shifts.

Proposed design:

  • The tablet is the possession factor. The device is enrolled through MDM as a trusted device bound to a single driver. With that, "something you have" is already solved without asking anything extra of them.
  • A local second factor: a 6-digit PIN or a fingerprint on the tablet, unlocking the device certificate. The driver types no codes: they unlock the tablet and work.
  • Minimum permissions: from the tablet only the route sheet and delivery confirmation are reachable (the driver role from the 02-02 matrix). No tablet can reach the ERP or the file server.
  • No access to corporate email from the tablet, which drastically reduces the phishing surface in the largest group.
  • Mandatory remote wipe and device encryption, because the likely scenario is not hacking: it is the tablet left behind at a service station.
  • If the tablet is shared between shifts, each driver signs in with an individual PIN and the session closes automatically at the end of the shift. No shared accounts: remember that they destroy accountability.

The design lesson is general: the answer for the difficult group is not to lower security, it is to change the factor. The combination "managed device + local PIN + minimum permissions" is more secure than "a complex password the driver will write on the dashboard".

Phase 5 — MiRutalia and the 400 customers (weeks 16-24)

  • MFA optional but recommended to begin with, mandatory for the customer's users who can see billing.
  • TOTP and passkeys, never SMS (the cost for 400 business customers would be absurd and the security worse).
  • Communication with customers as a commercial argument: Rutalia protects their data better than its competitors. It is the way to get senior management to see the project as value rather than cost.

Summary and tracking metrics

Phase Scope Method Weeks Hypothesis mitigated
0 Account clean-up — 1-2 H3, H1
1 Administrators FIDO2 3-4 H1, H5
2 VPN TOTP / FIDO2 5-7 H1
3 Microsoft 365 Push with number / passkey 8-12 H2
4 Drivers Device + PIN 10-16 H3
5 MiRutalia customers TOTP / passkey 16-24 H4

The metrics Laura takes to the committee each month: the percentage of accounts with MFA active, the number of privileged accounts without a phishing-resistant factor, active accounts unused for 90 days, the number of access recoveries requested and passwords rejected for appearing in breached lists. That is five numbers, they fit on one slide and they tell a story of improvement.


Common Mistakes and Tips

Mistake 1: demanding complexity and short expiry. It produces Rutalia03! and passwords on sticky notes. Tip: swap composition for length, expiry for checking against breached lists, and spend the political capital you save on deploying MFA.

Mistake 2: believing that "we already have MFA" is the end of it. SMS-based MFA stops automated attacks and does not stop targeted phishing. Tip: classify your accounts and put phishing-resistant factors at least on administrators and senior management.

Mistake 3: rolling out MFA with no recovery procedure. On day 3 somebody will lose their phone, Diego will improvise, and the improvisation will become the official procedure. Tip: write the procedure before switching on the first user.

Mistake 4: using the same device for the password and the second factor without thinking it through. If the password is in the phone's manager and the TOTP is on the same phone with no extra protection, the compromised phone is both factors. Tip: accept the trade-off for normal accounts, separate them for critical ones.

Mistake 5: keeping credentials in code or in a shared spreadsheet. The claves.xlsx in \\fs01\comun and the connection string in config.py are the same mistake. Tip: a secrets manager or environment variables; and when migrating, change every password, because they have to be assumed compromised.

Mistake 6: implementing password storage or TOTP yourself. The code in section 12 is for teaching, not for production. Tip: use proven libraries; your value is in configuring them well, not in rewriting them.

Mistake 7: forgetting the accounts that do not belong to people. Service, supplier, test and legacy application accounts. They have no MFA, they never expire and nobody looks at them. Tip: a quarterly inventory and source restriction.

A final tip: the order of the first three things Laura should do is this. First, disable the former employees' accounts (it costs nothing and removes a risk that is real today). Second, MFA on the VPN and for the administrators (it is the control that breaks the H1 chain at the first link). Third, a password manager and the elimination of claves.xlsx. With those three actions, and spending practically nothing, Rutalia's risk profile changes more than with any product it could buy.


Exercises

Exercise 1: auditing a password policy

The ERP vendor sends Laura their application's password policy for validation:

[erp_policy]
minimum_length          = 8
maximum_length          = 16
requires_uppercase      = yes
requires_digit          = yes
requires_symbol         = yes
expiry_days             = 45
history                 = 3
lockout_after_attempts  = 3
lockout_duration        = permanent_until_admin
recovery                = security_question
storage                 = SHA-256
new_credential_delivery = plain_text_email
mfa                     = not_available
  1. Identify all the problems, ordered by severity.
  2. For each one, explain which specific attack it makes easier.
  3. Rewrite the policy in line with current guidance.
  4. Since the ERP is legacy and the vendor is not going to change everything, propose three compensating controls Rutalia can apply on its own.

Exercise 2: choosing the second factor by profile

Assign each Rutalia profile the most suitable MFA method, justifying the choice in terms of risk, cost and operational constraints. Also state which method you rule out and why.

Profile No. Context
Diego Salas (sysadmin) 2 Full administrative access; works from the office and from home
Andrés Vidal (senior management) 5 Travels a lot; a BEC target; little patience with technology
Nuria Campos (administration/payments) 12 Fixed office post; handles banking details
Drivers 60 Tablet in the cab, gloves, patchy coverage
Warehouse staff 45 Terminal shared between shifts, cold and damp environment
Marta Ruiz (development) 3 Access to code and to pre-production
The ERP vendor 2-3 External, temporary access to the ERP
MiRutalia customers ~400 External users, no control over their devices

Exercise 3: responding to an MFA incident

On a Tuesday at 03:17, Marta Ruiz receives seven push notifications in a row on her phone asking her to approve a Microsoft 365 sign-in. Half asleep, she rejects the first three, and on the seventh she presses "Approve" to make them stop. At 09:00 she tells Laura about it.

  1. What exactly has happened and what do we know for certain about the state of the account?
  2. What does the attacker know that they did not know before 03:17?
  3. List, in order, the immediate actions Laura must carry out in the first hour.
  4. What should be looked for in the logs, and why?
  5. Propose three measures to ensure this cannot happen again, stating which of them eliminates it completely.

Solutions

Solution to Exercise 1

1 and 2. Problems, by severity

# Problem Attack it makes easier
1 storage = SHA-256 (no salt, no KDF) If the ERP database leaks, an attacker with a GPU recovers most of the passwords within hours. And with no salt, precomputed tables work and you can see who shares a password
2 mfa = not_available Any credential stolen by phishing, an infostealer or reuse gives direct access. It is the vector for H1 and H5
3 new_credential_delivery = plain text email The credential remains permanently in mailboxes and intermediate servers. It also suggests the system knows the password, that is, that it stores it reversibly
4 recovery = security_question Direct social engineering: the answers can be deduced from social media. Recovery is weaker than authentication
5 lockout_duration = permanent_until_admin with 3 attempts Trivial denial of service: an attacker locks out the whole workforce with 3 attempts per account. And it swamps Diego
6 maximum_length = 16 It rules out passphrases. Such a short maximum length usually betrays storage in a fixed-size field, or something worse
7 minimum_length = 8 + mandatory composition It generates Rutalia1!, exactly what a targeted attack dictionary contains
8 expiry_days = 45 + history = 3 It produces predictable incremental passwords: Rutalia1!, Rutalia2!…
9 No checking against breached lists It allows passwords to be set that are already in every attacker's dictionary

3. The rewritten policy

[erp_policy_revised]
minimum_length          = 12
maximum_length          = 128
composition             = none_mandatory
expiry_days             = 0            ; only on suspicion of compromise
history                 = 5
check_breached          = yes
banned_words            = rutalia, logistica, zaragoza, camion, 2026
lockout                 = progressive_delay  ; 1m, 5m, 15m, 30m
alert_by_source         = 20 failures from one IP in 10 min
recovery                = single_use_link_15min + identity_verification
storage                 = Argon2id (or bcrypt cost>=12)
new_credential_delivery = set_password_link (never the password itself)
mfa                     = mandatory

4. Compensating controls Rutalia can apply without touching the ERP

  1. Put the ERP behind MFA-authenticated access: publish it only on the internal network or behind a portal/VPN that does have a second factor. The legacy application stays exactly as it is, but to reach it you have to get past MFA. It is the control with the greatest impact and it does not require the vendor.
  2. Segment the network and restrict the origin: make the ERP reachable only from the segments and machines that need it, and make the vendor's access temporary and ticket-based. It reduces the reach of H5 → 03-04.
  3. Compensating monitoring: centralised logging of ERP sign-ins, with alerts on mass lockouts (denial of service through the permanent lockout), on out-of-hours access and on vendor access with no associated ticket. If you cannot prevent, detect.

As a fourth element, although it is not technical: build the security requirements into the contract at the next renewal, the subject of 06-04. The vendor will not change because of a polite request; it will change because of a clause.

Solution to Exercise 2

Profile Method chosen Justification Ruled out and why
Diego Salas (2) FIDO2 key, two per person Maximum privilege: his compromise is everybody's compromise. Phishing-resistant, mandatory. The cost is irrelevant for 2 people SMS and push: a single reverse-proxy phishing attack hands over the entire domain
Andrés Vidal (5) A passkey on his phone + a FIDO2 key as backup A priority BEC target (H2) and constantly travelling. The passkey is convenient (fingerprint) and resists phishing; the key covers the phone lost at an airport SMS, categorically: he is the classic SIM swapping profile
Nuria Campos (12) Push with number matching or TOTP; FIDO2 for whoever approves payments She handles banking details: she is the real target of H2. A fixed post, so a key is viable for the payments subgroup SMS: the same SIM swapping risk, and the financial impact is direct
Drivers (60) MDM-managed tablet as the possession factor + a local PIN or fingerprint They cannot type codes with gloves on in a cab and coverage drops out. The enrolled device is already "something you have"; the PIN is "something you know" TOTP: it requires opening an app and typing 6 digits on the move. SMS: coverage on the road makes it unworkable
Warehouse (45) A personal proximity card or NFC key + PIN, with short sessions A terminal shared between shifts: a personal and portable factor is needed. NFC works with gloves and in the cold; fingerprints fail with gloves and damp Fingerprint biometrics (gloves, cold, damp) and shared accounts (they destroy accountability)
Marta Ruiz (3) FIDO2 key Access to the source code and to pre-production: compromising it allows malicious code to be introduced into MiRutalia (an internal supply chain). She is technical staff, so adoption is straightforward SMS and push: hers is a profile exposed to targeted phishing, as we saw in 01-02
The ERP vendor (2-3) TOTP + temporary ticket-based access + source IP restriction We do not control their devices, so we cannot impose hardware. The real defence here is not the factor but bounding the access in time and scope Permanent access with no expiry, which is what they have today: it is hypothesis H5
MiRutalia customers (~400) TOTP and passkeys, optional at first and mandatory for profiles with access to billing You cannot impose hardware on external customers. A passkey is the best option available to them and it improves the experience SMS: a disproportionate cost for 400 companies and the worst security on the list

The cross-cutting criterion: the method is chosen by crossing the impact of a compromise with real operational constraints. Diego and Marta get physical keys because their compromise is catastrophic and there are few of them. The drivers do not get a worse factor: they get a different factor, adapted to their environment, combined with minimum permissions that limit the damage from a compromise.

Solution to Exercise 3

1. What has happened. It is an MFA fatigue attack. There is one fact that admits no argument: the attacker already had Marta's correct password. Push notifications are only generated after the first factor has been validated successfully. And with the seventh approval, the attacker completed the sign-in: the account has to be treated as compromised from 03:17, not as a suspicion but as a fact.

Where the password came from: reuse on an external service that suffered a breach, an infostealer on some machine, or earlier phishing. Finding out is part of the investigation, but it does not condition the immediate response.

2. What the attacker now knows.

  • That the password was correct (they knew that before 03:17).
  • That the account has push MFA and that Marta can be pressured: reusable information.
  • Everything in Marta's mailbox and M365 resources since 03:17: emails, shared files, internal contacts, and very possibly credentials or tokens that were circulating by email.
  • The internal knowledge needed to prepare a second targeted attack (names, suppliers, document formats). Marta is a developer: the additional risk is access to the code or to the development systems.

3. Immediate actions, in order (first hour).

  1. Revoke every session and token on Marta's account. This comes first: changing the password does not eject an already-established session.
  2. Change the password and check the new one against breached lists.
  3. Review and remove auto-forwarding rules, mailbox delegations and authorised applications on the account. This is the number one form of persistence after an email compromise, and it survives both a password change and MFA.
  4. Reset MFA completely: remove the registered method, register a new one and, given Marta's profile, take the opportunity to move her to a FIDO2 key.
  5. Review the account's activity since 03:17: sign-ins, IP addresses, downloads, emails sent, files accessed or shared.
  6. Check the reach: could the repository, pre-production or AWS be reached from that account? If Marta had saved credentials or open sessions to other systems, those have to be rotated too.
  7. Look for the same pattern on other accounts: if the attacker has Marta's password, they probably have more. Check whether there were night-time push attempts against other users.
  8. Tell Marta what has happened, without blaming her. This point is not a courtesy: if the message the rest of the workforce receives is that speaking up brings trouble, the next person will not speak up, and that silence costs far more than the incident.

4. What to look for in the logs, and why.

What to look for Why
Successful sign-ins and source IPs from 03:00 Confirm the compromise, the location and whether there were more sessions
Earlier MFA attempts on previous days Know whether this is the first attempt or they have been probing for a while
Mailbox rules created or modified Persistence: the classic "forward anything containing 'invoice'"
Authorised OAuth applications Persistence that survives a password change and MFA
Download volume from cloud storage An indication of exfiltration
Emails sent from the account Possible internal fraud under way (H2) or phishing of contacts
Other users with night-time push requests The real reach of the campaign
Access to code repositories and pre-production The risk of MiRutalia's code being tampered with

5. Three preventive measures.

  1. Number matching on push notifications (and showing the location and application in the request). It eliminates accidental approval: there is no longer a button to press, there is a number that only exists on the legitimate screen. Immediate implementation and no cost.
  2. Limit the frequency of MFA requests and alert automatically: more than 3 denied requests in 10 minutes → a notification to [email protected] and a temporary block on the account. It turns the attack into an alert instead of a breach.
  3. Migrate the at-risk profiles to FIDO2 or passkeys. This is the one that eliminates the attack completely: with a physical key there is no notification to approve and no code to type, so MFA fatigue ceases to exist as a vector. Marta, because of her access to the code, belongs in that group.

And a fourth, not technical but decisive: specific training with the right operational message — "a notification you did not ask for means somebody has your password: reject it and report it immediately". Marta did almost everything right: she rejected three times. What was missing was not willingness, it was knowing that this was not a system glitch but an attack in progress. That can be taught, and it is dealt with in Security Awareness and Training.


Conclusion

You have understood why the password is still the weak link and, above all, why that is not because it is short or simple: it is lost through reuse, phishing, infostealers and third-party leaks, scenarios in which the complexity of the secret is entirely irrelevant. You have seen how passwords are stored badly — in the clear, with a fast hash, with a salt but no cost — and how they are stored well, with a salt and slow derivation functions whose cost factor creates a brutal asymmetry: a computation imperceptible to the server and nine orders of magnitude of extra work for the attacker. You have brought the password policy into line with current guidance, swapping composition for length, forced expiry for checking against breached lists, and permanent lockout for a progressive delay so as not to turn a security control into a denial-of-service tool against your own workforce.

You have understood the zero-knowledge model of password managers, with its inevitable consequence — whoever forgets the master password loses the vault — and you have identified the claves.xlsx in \\fs01\comun for what it is: Rutalia's most dangerous asset today. You have compared the second factors and discovered that the difference that matters is not one of degree but qualitative: only FIDO2 and passkeys resist phishing, because the credential is bound to the domain and simply does not respond on a fake site. You have seen the three attacks that work against the rest — SIM swapping, MFA fatigue and reverse-proxy phishing — and why the reverse proxy makes any six-digit code irrelevant. You have written bcrypt in Python understanding what each part of the hash holds, why the comparison must be constant-time and how to raise the cost without disturbing anybody; and you have implemented TOTP from scratch, with its shared secret, its time counter, its dynamic truncation and its tolerance window, which is exactly the trade-off between security and usability we have been seeing since 02-01. You have closed the back door almost everyone forgets — access recovery can never be weaker than the authentication it replaces — and you have built a phased rollout plan for Rutalia that starts where it hurts most, resolves the difficult case of the 60 drivers by changing the factor rather than lowering security, and fits into five metrics that fit on one slide.

There is, however, an outstanding debt that has been building throughout the whole lesson. We have talked about hashes without saying what they are. We have used HMAC without explaining it. We have said that a passkey has a private key that never leaves the device and a public one stored on the server, and we have accepted it as magic. We have recommended encrypting data at rest without specifying what that means. All that scaffolding — the scaffolding that holds up well-stored passwords, one-time codes, FIDO2 keys and the encryption we discussed in 02-01 — rests on a single discipline. In Basic Cryptography we will go down to that foundation: what problem cryptography solves and which it does not, how symmetric and asymmetric encryption differ, why a badly chosen mode of operation leaves your data in plain sight even if you use AES-256, how two people who have never met can agree on a secret key across a channel somebody is listening to, and which cryptographic mistakes come up again and again — starting with the key Marta left written in MiRutalia's config.py.

© Copyright 2026. All rights reserved