Guide contents

Lesson 94 of 129

Encryption, TLS, and Attack Mitigation

Security controls for a system protect three properties: confidentiality (only authorized parties can read data), integrity (data is not altered undetected), and availability (the system stays usable). Encryption addresses confidentiality and, combined with authentication codes, integrity. The attack mitigations later in this article address all three.

Cryptographic building blocks

Primitive Purpose Examples
Symmetric encryption Encrypt and decrypt with one shared key. Fast. AES-GCM, ChaCha20-Poly1305
Asymmetric encryption A key pair: the public key encrypts or verifies, the private key decrypts or signs. Slower. RSA, elliptic-curve cryptography (ECDH, ECDSA, Ed25519)
Hash function Maps data to a fixed-size digest. One-way and collision resistant. SHA-256
MAC A keyed digest that proves integrity and authenticity. HMAC-SHA-256
Digital signature Proves that the holder of a private key produced the data. ECDSA, RSA-PSS

Practical systems combine them. Asymmetric cryptography or a key-agreement protocol establishes a shared secret, and symmetric encryption protects the bulk data because it is much faster.

Authenticated encryption (AEAD modes such as AES-GCM) encrypts and also authenticates the data, so tampering is detected on decryption. Unauthenticated modes should not be used. AES-GCM requires a nonce (a per-message value) that is never reused with the same key. Reuse breaks both confidentiality and authentication.

TLS

Transport Layer Security (TLS) protects a connection between two parties. HTTPS is HTTP over TLS. TLS provides:

  • Confidentiality: data is encrypted.
  • Integrity: tampering is detected.
  • Authentication: the client verifies the server's identity via its certificate. Optionally the server also verifies the client (mutual TLS, mTLS).

Certificates

A server presents a certificate binding its domain name to its public key. A certificate authority (CA) signs it. The client trusts a set of root CAs and verifies the chain from the server certificate to a trusted root, the domain name, and the validity period. If verification fails, the connection is refused.

TLS 1.3 handshake

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: ClientHello (supported ciphers, key share)
    S-->>C: ServerHello (chosen cipher, key share)
    S-->>C: Certificate and signature (encrypted)
    S-->>C: Finished
    C->>S: Finished
    Note over C,S: Application data encrypted with session keys
  1. The client sends the cipher suites it supports and a key share for an ephemeral Diffie-Hellman key exchange (typically elliptic-curve).
  2. The server picks a cipher, sends its key share, and both sides derive the same session keys without ever transmitting them.
  3. The server proves its identity by sending its certificate and a signature over the handshake.
  4. Both sides confirm with Finished messages and switch to encrypted application data.

TLS 1.3 needs one round trip before application data can be sent (TLS 1.2 needs two). Resumption of a previous session can reduce this further.

Forward secrecy. Because the key exchange uses ephemeral keys, compromise of the server's long-term private key later does not reveal past recorded sessions. TLS 1.3 requires this.

Versions older than TLS 1.2 (SSL, TLS 1.0, TLS 1.1) are deprecated and should be disabled.

Where TLS terminates

TLS can end at the load balancer or API gateway (TLS termination), which centralizes certificates but leaves traffic inside the network unencrypted unless re-encrypted. Inside a zero-trust network, internal traffic also uses TLS, often mTLS provided by a service mesh. Certificates need automated issuance and renewal to avoid outages from expired certificates. See HTTP/1, HTTP/2, and HTTP/3 for how TLS relates to those protocols.

Encryption at rest and in transit

  • In transit: data moving between systems is protected by TLS (client to server, service to service, replication links, database connections).
  • At rest: data on disk is encrypted so that stolen disks, snapshots, or backups do not expose it. Levels:
    • Disk or volume encryption: protects against physical loss. Data is readable by anyone with access to the running system.
    • Database or object-store encryption: the storage service encrypts data with keys it manages.
    • Application-level (field-level) encryption: the application encrypts sensitive fields before storing them. The database never sees plaintext, but the fields cannot be searched or indexed directly.

Key management

Encryption is only as strong as the protection of keys. Envelope encryption is the standard pattern: a unique data encryption key (DEK) encrypts each object or volume, and a key encryption key (KEK) held in a key management service (KMS) or hardware security module (HSM) encrypts the DEKs. Encrypted DEKs are stored next to the data. To decrypt, the service asks the KMS to unwrap the DEK, which produces an audit trail. Rotating the KEK requires rewrapping DEKs, not re-encrypting all data. See configuration and secrets management.

Password storage

Passwords must never be stored in plaintext or encrypted reversibly. Store the output of a password hashing function that is deliberately slow. Argon2id and scrypt are also memory-hard, meaning each hash needs a large amount of RAM, which limits parallel guessing on GPUs and custom hardware.

  • A plain fast hash such as SHA-256 lets an attacker test billions of guesses per second on GPUs.
  • Salt: a unique random value per password, stored with the hash. It ensures identical passwords produce different hashes and defeats precomputed (rainbow) tables.
  • Use Argon2id, scrypt, or bcrypt, with cost parameters tuned so that one hash takes a noticeable fraction of a second on the server. Raise the cost over time as hardware improves.
  • Login compares the hash of the submitted password (with the stored salt) to the stored hash, using a constant-time comparison.
  • A pepper (a secret key applied to all passwords and kept outside the database) can add protection if the database alone leaks.

Common attacks and mitigations

SQL injection

What: user input is concatenated into a SQL query, so the input changes the query structure. Input such as ' OR '1'='1 can bypass a login check or read other tables.

For example, with the query text SELECT * FROM users WHERE name = ' + input + ', the input x' OR '1'='1 makes the condition always true. With a parameterized query the text is SELECT * FROM users WHERE name = ? and the whole input is bound as one string value.

Mitigation:

  • Parameterized queries (prepared statements): the query text and the values are sent separately, so a value can never be parsed as SQL.
  • Use least-privilege database accounts, so a flaw exposes less.
  • Validate input types and lengths as defense in depth. Escaping alone is fragile.

Cross-site scripting (XSS)

What: an attacker gets a page to run their JavaScript in another user's browser, for example through a stored comment that is rendered unescaped. The script can read data on the page, act as the user, or steal tokens that scripts can access.

Mitigation:

  • Output encoding: escape user data for the context where it is inserted (HTML body, attribute, JavaScript, URL). Modern frameworks escape by default. Avoid raw HTML insertion APIs.
  • Content Security Policy (CSP): a response header restricting the sources from which scripts can load and disallowing inline scripts.
  • HttpOnly cookies keep session cookies out of reach of scripts.
  • Sanitize any HTML that must be accepted, with a maintained sanitizer library.

Cross-site request forgery (CSRF)

What: a malicious site causes the victim's browser to send a request to a site where the victim is logged in. The browser attaches the session cookie automatically, so the server sees an authenticated request, for example a money transfer.

Mitigation:

  • SameSite cookie attribute (Lax or Strict) stops the browser sending the cookie on cross-site requests in most cases.
  • CSRF tokens: a per-session random value required in a request header or form field on state-changing requests. A malicious site cannot read it.
  • Do not change state with GET requests.
  • APIs that authenticate with an Authorization header rather than cookies are not affected by CSRF, because the browser does not attach that header automatically.

Distributed denial of service (DDoS)

What: many sources flood a target so legitimate users cannot be served. Types:

  • Volumetric: saturate bandwidth (for example reflection and amplification via UDP services).
  • Protocol: exhaust connection state, such as SYN floods that fill the half-open connection table.
  • Application layer: many valid-looking requests to expensive endpoints.

Mitigation:

  • Absorb and filter at the network edge with a CDN or a DDoS protection provider that has far more capacity than the origin. Use anycast to spread traffic over many locations. See content delivery networks.
  • SYN cookies and connection limits against protocol attacks.
  • Rate limiting, request caching, and web application firewall rules against application-layer floods.
  • Hide origin addresses so attackers cannot bypass the edge.
  • Design for overload with load shedding and autoscaling, noting that autoscaling can turn an attack into a large bill.

Other common issues

  • Broken access control: missing authorization checks let users access others' objects by changing an ID. Enforce authorization on the server for every request.
  • Server-side request forgery (SSRF): the server is tricked into requesting internal URLs, such as cloud metadata endpoints. Validate and restrict outbound destinations.
  • Secrets in code or logs: use a secret store and scrub logs.
  • Vulnerable dependencies: track and update dependencies and scan them.

Defense in depth

No single control is sufficient. Layers include the network edge (DDoS protection, WAF), the gateway (authentication, rate limits), services (authorization, input validation), data stores (least privilege, encryption at rest), and monitoring (audit logs, alerts on anomalies). Apply the principle of least privilege to people, services, and credentials.

Interview questions

  • Why does TLS use both asymmetric and symmetric cryptography? Asymmetric key exchange and signatures establish trust and a shared secret over an untrusted network. Symmetric encryption then protects the data because it is far faster.
  • What is forward secrecy? Session keys are derived from ephemeral key exchanges, so compromising the server's long-term private key later does not allow decrypting previously captured traffic.
  • Why hash passwords with bcrypt or Argon2 instead of SHA-256? SHA-256 is designed to be fast, so attackers can test guesses at high speed. Password hashing functions are deliberately slow and, for Argon2 and scrypt, memory-hard, and they include a per-password salt.
  • How do prepared statements prevent SQL injection? The SQL text is parsed separately from the values, so input is always treated as data and never as part of the query structure.
  • How does SameSite help against CSRF? With SameSite=Lax or Strict, the browser does not send the cookie on most cross-site requests, so a forged request from another site arrives unauthenticated.