Web Security 101

A comprehensive guide to understanding web security concepts, terminology, and best practices. Click any section below to expand.

Search and browse security terms. Click on highlighted terms within definitions to jump to related concepts.

Basics & Fundamentals
URL (Uniform Resource Locator) #

The complete address used to access a resource on the internet. Example: https://www.example.com:443/path/page.html?query=value. A URL includes the protocol, domain, optional port, path, and query parameters.

Domain Name #

A human-readable address that identifies a website, like example.com. Domains are translated to IP addresses by the DNS system. Domains consist of a TLD (.com), second-level domain (example), and optional subdomains (www).

Subdomain #

A prefix added to a domain name to organize or separate sections of a website. In blog.example.com, "blog" is the subdomain. Common subdomains include www, mail, api, and app.

TLD (Top-Level Domain) #

The last segment of a domain name, appearing after the final dot. Examples: .com, .org, .net (gTLDs - generic), .uk, .de, .jp (ccTLDs - country code). Some TLDs like .bank or .gov have strict registration requirements.

IP Address #

A numerical label assigned to each device on a network. IPv4 addresses look like 192.168.1.1, while IPv6 addresses are longer: 2001:0db8:85a3::8a2e:0370:7334. IP addresses identify where to send network traffic.

IPv4 #

Internet Protocol version 4, the fourth version of the Internet Protocol. Uses 32-bit addresses (e.g., 192.168.1.1), allowing approximately 4.3 billion unique addresses. Due to address exhaustion, IPv6 was developed.

IPv6 #

Internet Protocol version 6, designed to replace IPv4. Uses 128-bit addresses (e.g., 2001:0db8:85a3::8a2e:0370:7334), providing a vastly larger address space. Recorded in AAAA records in DNS.

Port #

A numerical identifier (0-65535) that specifies a particular process or service on a server. Common ports: 80 (HTTP), 443 (HTTPS), 22 (SSH), 25 (SMTP). Ports allow multiple services to run on the same IP address.

Protocol #

A set of rules governing how data is transmitted over a network. Examples include HTTP/HTTPS for web traffic, SMTP for email, DNS for name resolution, and TLS for encryption.

HTTP (Hypertext Transfer Protocol) #

The foundation protocol for data communication on the web. HTTP is unencrypted, meaning data can be intercepted and read. Modern websites should use HTTPS instead for security.

HTTPS (HTTP Secure) #

The secure version of HTTP, encrypted using TLS. HTTPS protects data in transit from eavesdropping and tampering. Indicated by a padlock icon in browsers and required for handling sensitive data.

Web Server #

Software that serves web pages to users' browsers. Common web servers include Apache, Nginx, and Microsoft IIS. Web servers handle HTTP/HTTPS requests and return HTML, CSS, JavaScript, and other files.

Web Browser #

Software that retrieves and displays web pages. Browsers (Chrome, Firefox, Safari, Edge) interpret HTML, CSS, and JavaScript to render websites. They also enforce security features like CSP and CORS.

DNS (Domain Name System)
DNS (Domain Name System) #

The internet's "phone book" that translates human-readable domain names into IP addresses. When you type a URL, DNS servers look up the corresponding IP address so your browser knows where to connect.

A Record #

A DNS record that maps a domain name to an IPv4 address. Example: example.com → 93.184.216.34. Multiple A records can point to different IPs for load balancing.

AAAA Record (Quad-A) #

A DNS record that maps a domain name to an IPv6 address. Similar to A records but for the newer IPv6 protocol.

MX Record (Mail Exchange) #

A DNS record specifying which mail servers accept email for a domain. MX records have a priority value; lower numbers indicate higher priority. Essential for email delivery.

NS Record (Name Server) #

A DNS record that specifies which name servers are authoritative for a domain. NS records delegate DNS resolution to specific servers.

TXT Record #

A DNS record that holds arbitrary text data. Commonly used for SPF, DKIM, DMARC email authentication, and domain ownership verification (Google, Microsoft, etc.).

CNAME Record (Canonical Name) #

A DNS record that creates an alias from one domain name to another. Example: www.example.com → example.com. Cannot coexist with other record types for the same name.

SOA Record (Start of Authority) #

A DNS record containing administrative information about a DNS zone, including the primary name server, admin email, serial number, and refresh intervals.

PTR Record (Pointer) #

A DNS record used for reverse DNS lookups—mapping an IP address back to a domain name. Important for email server verification and network diagnostics.

CAA Record (Certificate Authority Authorization) #

A DNS record specifying which Certificate Authorities are allowed to issue SSL certificates for a domain. Helps prevent unauthorized certificate issuance.

TTL (Time to Live) #

The duration (in seconds) that a DNS record can be cached before it must be refreshed. Lower TTLs mean faster propagation of changes but more DNS queries; higher TTLs reduce load but slow updates.

Name Server #

A server that handles DNS queries. Authoritative name servers hold the official records for a domain; recursive resolvers query other servers to find answers. Common providers: Cloudflare, AWS Route 53, Google DNS.

DNSSEC (DNS Security Extensions) #

A set of extensions to DNS that add cryptographic signatures to DNS records, preventing DNS spoofing and cache poisoning attacks. Verifies that DNS responses haven't been tampered with.

Email Security
SPF (Sender Policy Framework) #

An email authentication method using TXT records to specify which mail servers are authorized to send email for a domain. Helps prevent email spoofing. Works with DKIM and DMARC.

DKIM (DomainKeys Identified Mail) #

An email authentication method that adds a digital signature to outgoing emails. Recipients verify the signature using a public key published in DNS. Proves emails haven't been modified in transit.

DMARC (Domain-based Message Authentication, Reporting & Conformance) #

An email authentication protocol that builds on SPF and DKIM. DMARC tells receiving servers what to do when authentication fails (none, quarantine, or reject) and provides reporting.

SMTP (Simple Mail Transfer Protocol) #

The standard protocol for sending emails across the internet. SMTP servers (port 25, 587, or 465) relay messages between mail servers. Works with MX records to route email.

IMAP (Internet Message Access Protocol) #

A protocol for retrieving email that keeps messages on the server. Unlike POP3, IMAP syncs across multiple devices. Standard port: 993 (encrypted).

POP3 (Post Office Protocol) #

A protocol for retrieving email that typically downloads messages and removes them from the server. Simpler than IMAP but doesn't sync across devices. Standard port: 995 (encrypted).

Email Spoofing #

The practice of sending emails with a forged sender address to make them appear to come from someone else. Used in phishing attacks. Prevented by SPF, DKIM, and DMARC.

SSL/TLS & Encryption
SSL (Secure Sockets Layer) #

The predecessor to TLS, now deprecated due to security vulnerabilities. The term "SSL" is still commonly used to refer to TLS encryption and SSL certificates.

TLS (Transport Layer Security) #

A cryptographic protocol that provides secure communication over networks. TLS encrypts data between clients and servers, preventing eavesdropping. Used by HTTPS. Current version: TLS 1.3.

SSL/TLS Certificate #

A digital certificate that authenticates a website's identity and enables encrypted connections. Issued by Certificate Authorities. Contains the public key, domain name, issuer, and validity period.

Certificate Authority (CA) #

A trusted organization that issues SSL/TLS certificates. CAs verify domain ownership before issuing certificates. Examples: Let's Encrypt (free), DigiCert, Comodo, GlobalSign. Controlled by CAA records.

Self-Signed Certificate #

An SSL certificate signed by its own creator rather than a trusted CA. Browsers show warnings for self-signed certificates. Acceptable for internal/development use, not for public websites.

Certificate Chain #

The hierarchy of certificates from your site's certificate up to a trusted root CA. Includes intermediate certificates. A broken chain causes browser warnings.

Certificate Transparency (CT) #

A system of public logs that record all issued SSL certificates. Allows domain owners to detect unauthorized certificates. Browsers require CT compliance for trusted certificates.

Encryption #

The process of converting readable data (plaintext) into an unreadable format (ciphertext) using an algorithm and key. Only those with the correct key can decrypt the data. Used by HTTPS, email, file storage, etc.

Hashing #

A one-way function that converts data into a fixed-size string (hash/digest). Unlike encryption, hashing cannot be reversed. Used for password storage, data integrity verification. Common algorithms: SHA-256, bcrypt.

Security Headers
HSTS (HTTP Strict Transport Security) #

A security header that forces browsers to only connect via HTTPS. Prevents protocol downgrade attacks and cookie hijacking. Example: Strict-Transport-Security: max-age=31536000; includeSubDomains

CSP (Content Security Policy) #

A security header that controls which resources (scripts, styles, images, etc.) a browser can load. Prevents XSS and data injection attacks by whitelisting trusted sources.

X-Frame-Options #

A security header that controls whether a page can be embedded in an iframe. Prevents clickjacking attacks. Values: DENY, SAMEORIGIN. Being replaced by CSP's frame-ancestors directive.

X-Content-Type-Options #

A security header that prevents browsers from MIME-sniffing (guessing content types). Set to nosniff to ensure browsers respect declared content types, preventing certain attacks.

Referrer-Policy #

A security header controlling how much referrer information is sent with requests. Options range from no-referrer (none) to unsafe-url (full URL). Recommended: strict-origin-when-cross-origin.

Permissions-Policy #

A security header (formerly Feature-Policy) that controls which browser features and APIs can be used. Example: disable geolocation, camera, microphone access to reduce attack surface.

CORS (Cross-Origin Resource Sharing) #

A mechanism using HTTP headers to allow or restrict web pages from making requests to a different domain than the one serving the page. Controls cross-origin API access.

COOP (Cross-Origin-Opener-Policy) #

A security header that isolates a document's browsing context from cross-origin windows. Prevents cross-origin attacks that exploit window references. Values: same-origin, same-origin-allow-popups, unsafe-none.

COEP (Cross-Origin-Embedder-Policy) #

A security header that controls loading of cross-origin resources. Setting require-corp only allows resources that explicitly grant permission. Required (with COOP) to use SharedArrayBuffer.

CORP (Cross-Origin-Resource-Policy) #

A security header that tells browsers who can load a resource. Values: same-site, same-origin, cross-origin. Protects resources from being embedded by unauthorized sites.

Threats & Attacks
Phishing #

A social engineering attack where attackers impersonate legitimate entities to trick victims into revealing sensitive information like passwords or credit card numbers. Often uses email spoofing and fake websites.

Spear Phishing #

A targeted form of phishing aimed at specific individuals or organizations. Attackers research their targets to craft convincing, personalized messages. More dangerous than generic phishing.

XSS (Cross-Site Scripting) #

A vulnerability allowing attackers to inject malicious scripts into web pages viewed by other users. Can steal cookies, session tokens, or perform actions as the victim. Prevented by CSP and input sanitization.

CSRF (Cross-Site Request Forgery) #

An attack that tricks users into performing unintended actions on a site where they're authenticated. Example: clicking a link that transfers money. Prevented by CSRF tokens and SameSite cookie attributes.

SQL Injection #

An attack where malicious SQL code is inserted into application queries, allowing attackers to access, modify, or delete database data. Prevented by parameterized queries and input validation. One of OWASP Top 10.

MITM (Man-in-the-Middle Attack) #

An attack where the attacker secretly intercepts and potentially alters communications between two parties. Prevented by HTTPS/TLS encryption and certificate validation.

DDoS (Distributed Denial of Service) #

An attack that overwhelms a server with traffic from multiple sources, making it unavailable to legitimate users. Mitigated by CDNs, rate limiting, and DDoS protection services like Cloudflare.

Clickjacking #

An attack where a malicious site embeds your site in a hidden iframe, tricking users into clicking on it unknowingly. Prevented by X-Frame-Options or CSP frame-ancestors.

Typosquatting #

Registering domain names similar to legitimate ones (e.g., "gooogle.com" or "arnazon.com") to catch users who mistype URLs. Used for phishing or malware distribution. Also called URL hijacking.

Homograph Attack #

Using characters that look similar (e.g., Cyrillic "а" vs Latin "a") to create deceptive domain names. Example: "аpple.com" (using Cyrillic а) looks identical to "apple.com". Browsers show punycode to combat this.

Social Engineering #

Manipulating people into divulging confidential information or performing actions. Exploits human psychology rather than technical vulnerabilities. Includes phishing, pretexting, baiting, and tailgating.

Brute Force Attack #

An attack that systematically tries all possible passwords or keys until finding the correct one. Mitigated by rate limiting, account lockouts, CAPTCHA, and strong password requirements.

Subdomain Takeover #

When a subdomain points to an external service that's been decommissioned, attackers can claim that service and control the subdomain. Common with cloud services, GitHub Pages, Heroku.

Security Concepts
OSINT (Open Source Intelligence) #

Information collected from publicly available sources for intelligence purposes. In cybersecurity, this includes DNS records, WHOIS data, certificate transparency logs, and public threat feeds.

Threat Intelligence #

Evidence-based knowledge about existing or emerging threats. Includes indicators of compromise (IoCs), tactics, techniques, and procedures (TTPs). Sources: AlienVault OTX, VirusTotal, abuse.ch.

Vulnerability #

A weakness in software, hardware, or processes that can be exploited by attackers. Vulnerabilities are tracked using CVE identifiers and rated by severity (CVSS scores).

Exploit #

Code or technique that takes advantage of a vulnerability to compromise a system. Exploits can be used for unauthorized access, privilege escalation, or denial of service.

CVE (Common Vulnerabilities and Exposures) #

A standardized identifier for known security vulnerabilities. Format: CVE-YEAR-NUMBER (e.g., CVE-2021-44228 for Log4Shell). Maintained by MITRE Corporation.

Zero-Day #

A vulnerability that is unknown to the software vendor or has no available patch. "Zero days" refers to the number of days the vendor has known about it. Highly valuable to attackers.

Firewall #

A network security system that monitors and filters incoming and outgoing traffic based on security rules. Can be hardware or software-based. Controls access between trusted and untrusted networks.

WAF (Web Application Firewall) #

A firewall specifically designed to protect web applications by filtering HTTP traffic. Blocks SQL injection, XSS, and other web attacks. Examples: Cloudflare WAF, AWS WAF, ModSecurity.

VPN (Virtual Private Network) #

A service that creates an encrypted tunnel between your device and a server, protecting your traffic from eavesdroppers. Commonly used for privacy, bypassing geo-restrictions, and secure remote access.

MFA/2FA (Multi-Factor Authentication) #

An authentication method requiring two or more verification factors: something you know (password), something you have (phone/token), or something you are (biometrics). Significantly improves account security.

Authentication #

The process of verifying a user's identity—confirming they are who they claim to be. Typically done through passwords, MFA, certificates, or biometrics. Different from authorization.

Authorization #

The process of determining what an authenticated user is allowed to do—their permissions and access rights. Happens after authentication. Example: admin vs. regular user privileges.

Tools & Protocols
WHOIS #

A protocol and database for querying domain registration information: registrant, registrar, creation/expiration dates, and name servers. Being replaced by RDAP. Privacy services can mask registrant data.

RDAP (Registration Data Access Protocol) #

The modern replacement for WHOIS. Provides domain registration data in a standardized, machine-readable format (JSON). Supports authenticated access and better internationalization.

nslookup #

A command-line tool for querying DNS servers. Used to look up A records, MX records, and other DNS information. Available on Windows, macOS, and Linux.

dig (Domain Information Groper) #

A flexible command-line tool for DNS queries, providing more detailed output than nslookup. Can query specific record types, trace resolution path, and check DNSSEC.

traceroute / tracert #

A network diagnostic tool that shows the path packets take to reach a destination, listing each hop (router) along the way. Useful for identifying network issues and understanding routing.

ping #

A network utility that tests connectivity by sending ICMP echo requests to a host and measuring response time. Basic network troubleshooting tool. Example: ping example.com

curl #

A command-line tool for transferring data using various protocols including HTTP/HTTPS. Useful for testing APIs, checking headers, and downloading files. Highly versatile for web debugging.

CDN (Content Delivery Network) #

A distributed network of servers that delivers content to users from geographically closer locations, improving speed and reducing latency. Also provides DDoS protection. Examples: Cloudflare, AWS CloudFront, Akamai.

Email authentication prevents attackers from sending emails that appear to come from your domain. These protocols work together in layers to protect your domain's reputation, verify message integrity, and ensure secure transmission.

Why Email Authentication Matters

Email was designed in the 1970s without authentication—anyone could claim to send from any address. This fundamental flaw enables:

CEO Fraud

Attackers impersonate executives to request wire transfers or sensitive data

Brand Abuse

Phishers send fake invoices or login pages using your domain

Deliverability Issues

Without authentication, legitimate emails may be marked as spam

The Email Authentication Stack:
SPF "Is this IP allowed to send for this domain?"

DKIM "Is this message unaltered and signed by the domain?"

DMARC "What should I do if SPF/DKIM fail? Send reports."

MTA-STS "Force TLS encryption for incoming mail."

BIMI "Display our verified brand logo in email clients."

SPF (Sender Policy Framework)

SPF tells receiving mail servers which IP addresses are authorized to send email on behalf of your domain. It's the first line of defense against email spoofing.

How SPF Works (Step by Step)

When an email is received:

Sender Receiving Server

1. Receiving server extracts the domain from the "MAIL FROM" (envelope sender)

Receiving Server DNS Query TXT record for sender's domain

2. DNS returns the SPF record listing authorized senders

3. Server compares sending IP against the authorized list

4. Result: pass, fail, softfail, neutral, or none

SPF Record Syntax Explained:

v=spf1 ip4:192.0.2.0/24 include:_spf.google.com include:sendgrid.net -all
│      │                 │                        │                   │
│      │                 │                        │                   └─ Policy for non-matches
│      │                 │                        └─ Include SendGrid's SPF
│      │                 └─ Include Google's SPF record
│      └─ Allow this IP range
└─ SPF version (always v=spf1)

SPF Mechanisms:

Mechanism Purpose Example
ip4:Match IPv4 address or rangeip4:192.168.1.1 or ip4:192.168.0.0/16
ip6:Match IPv6 address or rangeip6:2001:db8::/32
aMatch domain's A record IPa or a:mail.example.com
mxMatch domain's MX record IPsmx or mx:example.com
include:Include another domain's SPFinclude:_spf.google.com
redirect=Use another domain's SPF entirelyredirect=_spf.example.com

SPF Qualifiers (the prefix before mechanisms):

Qualifier Meaning Recommendation
+ (Pass)IP is authorized (default if omitted)Standard for authorized senders
- (Fail)IP is NOT authorized, rejectUse in -all after thorough testing
~ (SoftFail)IP is probably not authorizedGood for initial deployment: ~all
? (Neutral)No statement about the IPRarely used

Common SPF Records for Popular Providers:

# Google Workspace
v=spf1 include:_spf.google.com ~all

# Microsoft 365
v=spf1 include:spf.protection.outlook.com ~all

# Amazon SES
v=spf1 include:amazonses.com ~all

# Multiple providers (common real-world example)
v=spf1 include:_spf.google.com include:servers.mcsv.net include:sendgrid.net ~all
SPF Limitations:
  • 10 DNS lookup limit: Each include:, a, mx, redirect= counts as a lookup. Exceeding 10 causes a permanent error (permerror).
  • Forwarding breaks SPF: When emails are forwarded, the forwarding server's IP isn't in the original domain's SPF.
  • Only checks envelope sender: SPF validates the "MAIL FROM" address, not the visible "From:" header users see.

DKIM (DomainKeys Identified Mail)

DKIM adds a cryptographic signature to emails, proving the message hasn't been altered in transit and was authorized by the domain owner.

How DKIM Works (Step by Step)

Signing (Outbound):

  1. Mail server hashes specific headers and body content
  2. Hash is encrypted with the domain's private key
  3. Signature is added as DKIM-Signature: header

Verification (Inbound):

  1. Receiving server extracts the selector and domain from signature
  2. Queries DNS for public key: selector._domainkey.domain.com
  3. Decrypts the signature using the public key
  4. Computes its own hash of the message
  5. Compares: if hashes match, signature is valid

The signature proves:

  • The email was authorized by the domain owner (who has the private key)
  • The signed portions haven't been modified

DKIM Signature Header Example:

DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
    d=example.com; s=selector1;
    h=from:to:subject:date:message-id;
    bh=base64hashOfBody==;
    b=base64SignatureValue...

DKIM Parameters Explained:

TagMeaningExample
v=Version (always 1)v=1
a=Signing algorithma=rsa-sha256
d=Signing domaind=example.com
s=Selector (identifies key pair)s=google or s=selector1
h=Headers included in signatureh=from:to:subject
bh=Body hashBase64 encoded hash
b=Signature valueBase64 encoded signature
c=Canonicalization (how to normalize)c=relaxed/relaxed

DKIM DNS Record:

# DNS Record Name:
selector1._domainkey.example.com

# DNS Record Value (TXT):
v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
Selectors: A domain can have multiple DKIM keys with different selectors. This allows key rotation without downtime and lets different services (marketing, transactional) use separate keys.

DMARC (Domain-based Message Authentication, Reporting & Conformance)

DMARC ties SPF and DKIM together, tells receivers what to do when checks fail, and provides visibility through reporting.

How DMARC Works (Step by Step)

DMARC Alignment Check:

DMARC requires that the domain in the visible "From:" header aligns with:

  • The domain that passed SPF (envelope sender), OR
  • The domain that passed DKIM (d= tag in signature)

This prevents attacks where SPF/DKIM pass for one domain but the "From:" shows a different domain.

DMARC passes if:

(SPF passes AND SPF aligns) OR (DKIM passes AND DKIM aligns)

Alignment Modes:

  • Strict (aspf=s, adkim=s): Exact domain match required
  • Relaxed (aspf=r, adkim=r): Subdomains allowed (default)

DMARC Record Syntax:

v=DMARC1; p=reject; sp=quarantine; pct=100; rua=mailto:dmarc@example.com; ruf=mailto:forensics@example.com; adkim=r; aspf=r
│        │         │              │        │                              │                                      │        │
│        │         │              │        │                              │                                      │        └─ SPF alignment mode
│        │         │              │        │                              │                                      └─ DKIM alignment mode
│        │         │              │        │                              └─ Forensic report address
│        │         │              │        └─ Aggregate report address
│        │         │              └─ Percentage of mail to apply policy to
│        │         └─ Subdomain policy
│        └─ Policy (none/quarantine/reject)
└─ Version

DMARC Policies:

PolicyActionWhen to Use
p=none Monitor only, deliver normally Start here Collect data, identify legitimate senders
p=quarantine Mark as suspicious (spam folder) Phase 2 After reviewing reports
p=reject Reject the message entirely Final goal Maximum protection

DMARC Implementation Path:

Week 1-2: Deploy Monitoring

v=DMARC1; p=none; rua=mailto:dmarc@yourdomain.com

Week 3-4: Analyze Reports

Review aggregate reports, identify all legitimate email sources, fix SPF/DKIM issues

Week 5-6: Gradual Enforcement

v=DMARC1; p=quarantine; pct=25; rua=... then increase pct to 50, 100

Week 7+: Full Rejection

v=DMARC1; p=reject; rua=...

DMARC Reports: Aggregate reports (RUA) are XML files sent daily showing authentication results. Use free services like DMARCIAN, Valimail, or Postmark DMARC to parse and visualize them.

MTA-STS (Mail Transfer Agent Strict Transport Security)

MTA-STS forces other mail servers to use encrypted TLS connections when delivering email to your domain, preventing man-in-the-middle attacks and downgrade attacks on email transmission.

Why MTA-STS is Important

The Problem: Email transmission between servers (SMTP) traditionally used "opportunistic TLS"—servers try encryption but fall back to unencrypted if it fails. An attacker can:

  • Strip the STARTTLS response, forcing unencrypted transmission
  • Present a fake certificate (no verification by default)
  • Intercept and read all email content

The Solution: MTA-STS tells senders "you MUST use TLS with a valid certificate, or don't deliver at all."

Setting Up MTA-STS (2 components):

1. DNS Record:

# TXT record for _mta-sts.yourdomain.com
v=STSv1; id=20240115120000

The id must change whenever you update the policy (use timestamp or version number).

2. Policy File (served via HTTPS):

Host this file at: https://mta-sts.yourdomain.com/.well-known/mta-sts.txt

version: STSv1
mode: enforce
mx: mail.yourdomain.com
mx: backup-mail.yourdomain.com
max_age: 604800

MTA-STS Modes:

ModeBehaviorUse Case
testingReport failures but still deliverInitial deployment, validation
enforceReject delivery if TLS failsProduction after testing
nonePolicy disabledTemporarily disable without removing DNS
Requirements:
  • Your MX servers must have valid, publicly-trusted TLS certificates
  • The policy file must be served over HTTPS with a valid certificate
  • The mta-sts subdomain needs HTTPS configured

TLS-RPT (TLS Reporting)

TLS-RPT provides reporting for MTA-STS (and DANE). It tells you when other servers have trouble establishing secure connections to your mail servers.

# TXT record for _smtp._tls.yourdomain.com
v=TLSRPTv1; rua=mailto:tls-reports@yourdomain.com

What TLS-RPT reports tell you:

  • Certificate validation failures
  • MTA-STS policy fetch failures
  • STARTTLS negotiation failures
  • Which sending domains had issues reaching you
Tip: Reports are JSON formatted. Services like URIports or your DMARC analysis tool can often parse TLS-RPT reports too.

BIMI (Brand Indicators for Message Identification)

BIMI displays your verified brand logo next to emails in supported mail clients (Gmail, Apple Mail, Yahoo). It requires DMARC enforcement and optionally a Verified Mark Certificate (VMC).

Why BIMI Matters
  • Brand Recognition: Your logo appears prominently, increasing trust and engagement
  • Anti-Phishing: Verified logos help users distinguish legitimate emails from spoofs
  • Incentive for DMARC: BIMI requires p=quarantine or p=reject, encouraging stronger email authentication

BIMI Prerequisites:

  1. DMARC policy of p=quarantine or p=reject
  2. Logo in SVG Tiny PS format (specific requirements)
  3. Optional: Verified Mark Certificate (VMC) from DigiCert or Entrust (~$1,500/year) — required by Gmail

BIMI DNS Record:

# TXT record for default._bimi.yourdomain.com

# Without VMC (works in Yahoo, some clients)
v=BIMI1; l=https://example.com/brand/logo.svg

# With VMC (required for Gmail)
v=BIMI1; l=https://example.com/brand/logo.svg; a=https://example.com/brand/certificate.pem
Logo Requirements:
  • SVG Tiny Portable/Secure (SVG Tiny PS) format
  • Square aspect ratio (centered subject)
  • Solid background color (no transparency)
  • Hosted on HTTPS
  • Use BIMI Generator to validate your logo

Complete Email Security Checklist

Protocol DNS Record Purpose Priority
SPF TXT @ v=spf1... Authorize sending IPs Essential
DKIM TXT selector._domainkey Sign messages cryptographically Essential
DMARC TXT _dmarc Policy + reporting Essential
MTA-STS TXT _mta-sts + HTTPS file Enforce TLS for inbound mail Recommended
TLS-RPT TXT _smtp._tls TLS failure reporting Recommended
BIMI TXT default._bimi Brand logo display Optional
Knowledge Check

An attacker sends an email that passes SPF (sent from an authorized IP), but the "From:" header shows your CEO's email address while the envelope sender is a different domain. Will DMARC protect against this?

Yes - DMARC requires alignment between the "From:" header and the authenticated domain
No - SPF passed, so DMARC will pass too
It depends on the DMARC policy (none/quarantine/reject)

SSL/TLS certificates encrypt data between your users and your server, verify your server's identity, and are essential for any website handling sensitive information. Understanding how TLS works helps you configure it securely.

What TLS Provides

Encryption

Data is encrypted in transit—attackers can't read intercepted traffic

Authentication

Certificates prove server identity—users know they're talking to the real site

Integrity

Messages can't be modified in transit without detection

How the TLS Handshake Works

Before encrypted communication begins, client and server perform a "handshake" to agree on encryption parameters and verify identities.

TLS 1.3 Handshake (Step by Step)

TLS 1.3 requires only 1 round trip (1-RTT):

Client Server

ClientHello: Supported TLS versions, cipher suites, key share (for key exchange)

Server Client

ServerHello: Chosen cipher suite, key share, certificate, finished message

Client Server

Finished: Client confirms, encrypted application data begins

Key Exchange: TLS 1.3 uses Ephemeral Diffie-Hellman (ECDHE), providing forward secrecy—even if the server's private key is compromised later, past sessions can't be decrypted.

Certificate Chain of Trust

Browsers trust certificates because they're signed by trusted Certificate Authorities (CAs). This creates a chain:

Root CA signs→ Intermediate CA signs→ Your Certificate
Why Intermediate Certificates Matter
  • Root CAs are kept offline: For security, root CA private keys are stored in hardware security modules (HSMs) disconnected from the internet
  • Intermediates handle daily signing: If compromised, only the intermediate is revoked, not the root
  • Your server must send the chain: Configure your server to send your certificate + intermediate(s). Browsers have roots built-in.

Common mistake: Missing intermediate certificates cause "untrusted" errors on some devices but not others (depending on cached certificates).

Certificate Types

Type Validation Trust Indicator Cost Use Case
DV (Domain Validated) Proves domain control only Padlock icon Free - $50/yr Personal sites, blogs, most websites
OV (Organization Validated) Verifies organization exists Padlock (org in cert details) $50 - $200/yr Business websites
EV (Extended Validation) Rigorous org verification Padlock (org in cert details) $150 - $500/yr Banks, e-commerce (diminishing value)
Modern Reality: Browsers no longer show the organization name in the address bar for EV certificates. The visual difference between DV and EV is minimal. For most websites, free DV certificates from Let's Encrypt provide the same encryption and user trust.

Wildcard vs. SAN Certificates

Type Covers Example Pros/Cons
Single Domain One specific domain www.example.com Simplest, most specific
Wildcard All subdomains at one level *.example.com Flexible, but if compromised all subdomains affected. Doesn't cover *.sub.example.com
SAN/UCC Multiple specific domains example.com, example.org, app.example.com Multiple unrelated domains on one cert. Must list each explicitly.

TLS Protocol Versions

SSL 2.0 (1995) — INSECURE

Fundamentally broken. Never use.

SSL 3.0 (1996) — INSECURE

Vulnerable to POODLE attack. Disabled by all modern browsers.

TLS 1.0 (1999) — DEPRECATED

Vulnerable to BEAST. PCI-DSS non-compliant since 2018.

TLS 1.1 (2006) — DEPRECATED

No known critical vulnerabilities, but deprecated by browsers in 2020.

TLS 1.2 (2008) — SUPPORTED

Secure when configured properly. Still widely used for compatibility.

TLS 1.3 (2018) — RECOMMENDED

Faster (1-RTT), removes weak ciphers, mandatory forward secrecy. The modern standard.

Best Practice: Enable TLS 1.2 and TLS 1.3 only. Disable TLS 1.0, TLS 1.1, and all SSL versions.

Understanding Cipher Suites

A cipher suite is a combination of algorithms used for key exchange, authentication, encryption, and message integrity.

TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
│   │     │        │   │   │    │
│   │     │        │   │   │    └─ MAC algorithm (integrity)
│   │     │        │   │   └─ Key size
│   │     │        │   └─ Mode (GCM = authenticated encryption)
│   │     │        └─ Bulk encryption algorithm
│   │     └─ Authentication (certificate type)
│   └─ Key exchange algorithm
└─ Protocol

Recommended Cipher Suites (Nginx):

ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;
ssl_prefer_server_ciphers off;  # Let client choose (TLS 1.3 doesn't use this)
Cipher Suites to Avoid
ContainsProblemExample
RC4Broken stream cipherTLS_RSA_WITH_RC4_128_SHA
DES / 3DESWeak block cipher (64-bit blocks)TLS_RSA_WITH_3DES_EDE_CBC_SHA
MD5Broken hash functionAnything with MD5
EXPORTIntentionally weakened for old regulationsTLS_RSA_EXPORT_WITH_*
NULLNo encryption at allTLS_RSA_WITH_NULL_SHA
RSA key exchangeNo forward secrecyTLS_RSA_WITH_AES_128_CBC_SHA
CBC modeVulnerable to padding oracle attacks (can be okay with TLS 1.2 mitigations)*_CBC_*

Certificate Transparency (CT)

Certificate Transparency is a system where CAs must log all issued certificates publicly. This helps detect misissued or malicious certificates.

How it helps you:
  • Monitor your domain: Use crt.sh to see all certificates issued for your domain
  • Detect unauthorized certs: If someone obtains a cert for your domain fraudulently, CT logs will show it
  • Browser enforcement: Chrome requires CT for all certificates (since 2018)

Certificate Revocation

When a private key is compromised or a certificate is misissued, it must be revoked. Browsers check revocation status via:

MethodHow it WorksPros/Cons
CRL (Certificate Revocation List) Download list of all revoked certs from CA Large downloads, infrequent updates, mostly abandoned
OCSP (Online Certificate Status Protocol) Real-time query to CA for specific cert Privacy concerns (CA knows what sites you visit), adds latency
OCSP Stapling Server fetches OCSP response, includes in TLS handshake Recommended Fast, private, but requires server configuration

Enable OCSP Stapling (Nginx):

ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /path/to/chain.pem;  # CA chain for verification
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;

Getting a Free SSL Certificate (Let's Encrypt)

Let's Encrypt provides free, automated SSL certificates. Certbot is the recommended client.

Nginx
Apache
Standalone

Install and run Certbot for Nginx:

# Ubuntu/Debian
sudo apt update
sudo apt install certbot python3-certbot-nginx

# Get certificate (auto-configures Nginx)
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

# Test auto-renewal
sudo certbot renew --dry-run

Install and run Certbot for Apache:

# Ubuntu/Debian
sudo apt update
sudo apt install certbot python3-certbot-apache

# Get certificate (auto-configures Apache)
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com

# Test auto-renewal
sudo certbot renew --dry-run

Standalone mode (no web server integration):

# Stop web server temporarily
sudo systemctl stop nginx

# Get certificate (Certbot runs its own server on port 80)
sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com

# Certificates saved to /etc/letsencrypt/live/yourdomain.com/
# - fullchain.pem (cert + intermediate)
# - privkey.pem (private key)

# Restart web server
sudo systemctl start nginx

Force HTTPS Redirect

Always redirect HTTP to HTTPS. This ensures users who type your domain without https:// still get encrypted connections.

Nginx
Apache
# Redirect all HTTP to HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$host$request_uri;
}

# HTTPS server block
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name yourdomain.com www.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;

    # ... rest of config
}
# In .htaccess or VirtualHost config
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Or in Apache 2.4+ VirtualHost:
<VirtualHost *:80>
    ServerName yourdomain.com
    Redirect permanent / https://yourdomain.com/
</VirtualHost>

Complete Secure Nginx SSL Configuration

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name yourdomain.com;

    # Certificate files
    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;

    # SSL/TLS settings
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/letsencrypt/live/yourdomain.com/chain.pem;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;

    # Session settings
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;  # Disable for forward secrecy

    # DH parameters (generate with: openssl dhparam -out /etc/nginx/dhparam.pem 2048)
    ssl_dhparam /etc/nginx/dhparam.pem;

    # HSTS (uncomment after testing)
    # add_header Strict-Transport-Security "max-age=63072000" always;

    # ... rest of server config
}
Knowledge Check

Why is "forward secrecy" important in TLS?

It makes connections faster by caching encryption keys
If the server's private key is compromised, past recorded sessions can't be decrypted
It allows the server to authenticate the client's identity

Security headers are HTTP response headers that instruct browsers how to behave when handling your content. They're your first line of defense against XSS, clickjacking, and many other client-side attacks—and they cost nothing to implement.

Why Security Headers Matter

Even with secure server-side code, browsers need instructions on how to protect users. Without security headers:

XSS Attacks Succeed

Injected scripts execute freely without CSP restrictions

Clickjacking Works

Your site can be invisibly embedded in malicious pages

HTTPS Downgrades

Attackers can strip encryption without HSTS

MIME Confusion

Uploaded files can be misinterpreted as executable scripts

Security Headers Quick Reference

Header Protects Against Priority
Content-Security-Policy XSS, data injection, unauthorized scripts Critical
Strict-Transport-Security Protocol downgrade, SSL stripping, MITM Critical
X-Frame-Options Clickjacking High
X-Content-Type-Options MIME sniffing attacks High
Referrer-Policy Information leakage via referrer Medium
Permissions-Policy Unauthorized feature access (camera, mic, etc.) Medium
Cross-Origin-Opener-Policy Cross-origin window attacks (Spectre) Medium
Cross-Origin-Resource-Policy Unauthorized resource embedding Low

Strict-Transport-Security (HSTS)

HSTS tells browsers to always use HTTPS for your domain, even if the user types http:// or clicks an HTTP link.

The Attack HSTS Prevents

SSL Stripping Attack (without HSTS):

User HTTP→ Attacker (MITM) HTTPS→ Server

The attacker intercepts HTTP requests and proxies them to HTTPS, stripping encryption from the user's side. User sees no padlock but might not notice.

With HSTS:

Browser remembers "always use HTTPS for this site" and refuses to connect via HTTP, blocking the attack entirely.

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
│                          │               │                   │
│                          │               │                   └─ Eligible for browser preload list
│                          │               └─ Apply to all subdomains
│                          └─ Remember for 1 year (in seconds)
└─ Header name

HSTS Directives:

DirectivePurposeRecommendation
max-age How long browser remembers (seconds) Start with 300 (5 min), increase to 31536000 (1 year)
includeSubDomains Apply to all subdomains Use if ALL subdomains support HTTPS
preload Request inclusion in browser preload lists Submit to hstspreload.org after testing
Warning: HSTS preloading is essentially permanent. If you preload and later need HTTP (e.g., for a subdomain), it's very difficult to undo. Only preload when you're certain all subdomains will always support HTTPS.

Content-Security-Policy (CSP)

CSP is the most powerful security header. It tells browsers exactly which resources are allowed to load, effectively blocking most XSS attacks even if your code has vulnerabilities.

How CSP Stops XSS

XSS Attack Scenario:

Attacker injects <script>stealCookies()</script> into a comment field.

Without CSP: Browser executes the script—cookies stolen.

With CSP script-src 'self': Browser checks if the inline script is allowed. It's not ('self' only allows scripts from your domain as files). Script is blocked, attack fails.

This is defense in depth: CSP protects users even when server-side validation fails.

CSP Directive Reference:

DirectiveControlsExample Values
default-srcFallback for all resource types'self'
script-srcJavaScript sources'self' https://cdn.example.com
style-srcCSS sources'self' 'unsafe-inline'
img-srcImage sources'self' data: https:
font-srcFont sources'self' https://fonts.gstatic.com
connect-srcAJAX, WebSocket, fetch'self' https://api.example.com
media-srcAudio/video sources'self'
object-srcPlugins (Flash, Java)'none'
frame-srcIframe sources'self' https://youtube.com
frame-ancestorsWho can embed YOUR page'self' or 'none'
form-actionForm submission targets'self'
base-uriBase URL for relative URLs'self'
upgrade-insecure-requestsAuto-upgrade HTTP to HTTPS(no value needed)

CSP Source Values:

ValueMeaningSecurity
'self'Same origin only Secure
'none'Block all Most secure
https://example.comSpecific origin Secure
https:Any HTTPS origin Too permissive
'unsafe-inline'Allow inline scripts/styles Defeats XSS protection
'unsafe-eval'Allow eval(), setTimeout(string) Dangerous
'nonce-xxx'Allow specific inline with nonce Secure alternative to unsafe-inline
'sha256-xxx'Allow specific inline by hash Secure alternative to unsafe-inline
'strict-dynamic'Trust scripts loaded by trusted scripts Modern approach
Using Nonces Instead of 'unsafe-inline'

A nonce (number used once) allows specific inline scripts while blocking injected ones:

1. Generate a random nonce per request (server-side):

$nonce = base64_encode(random_bytes(16));  // PHP example

2. Add nonce to CSP header:

Content-Security-Policy: script-src 'nonce-abc123RandomValue=='

3. Add same nonce to your inline scripts:

<script nonce="abc123RandomValue==">
    // This script will execute
    console.log("Allowed by nonce");
</script>

<script>
    // This script (no nonce) will be BLOCKED
    maliciousCode();
</script>

Example CSP Policies:

Strict
Moderate
Starter

Strict Policy (best security, requires no inline scripts):

Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; font-src 'self'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'self'; upgrade-insecure-requests

Moderate Policy (allows common CDNs):

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; connect-src 'self'; frame-ancestors 'self'; form-action 'self'; base-uri 'self'; object-src 'none'; upgrade-insecure-requests

Starter Policy (report-only, find what breaks):

Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; report-uri /csp-report-endpoint

Use Content-Security-Policy-Report-Only first to see violations without breaking your site.

Tip: Use Google's CSP Evaluator to check your policy for weaknesses and bypasses.

X-Frame-Options

Controls whether your page can be embedded in <iframe>, <frame>, or <object> elements. Prevents clickjacking attacks.

What is Clickjacking?

Attacker creates a page with an invisible iframe of your site positioned over a decoy button:

<!-- Attacker's page -->
<button>Click to win a prize!</button>
<iframe src="https://yourbank.com/transfer?to=attacker&amount=1000"
        style="opacity: 0; position: absolute; top: 0;">
</iframe>

User thinks they're clicking "win a prize" but actually clicks the hidden bank transfer button.

# Block all framing
X-Frame-Options: DENY

# Allow same-origin framing only
X-Frame-Options: SAMEORIGIN
Note: CSP's frame-ancestors directive is the modern replacement with more flexibility, but X-Frame-Options is still needed for older browsers.

X-Content-Type-Options

Prevents browsers from "sniffing" the MIME type, forcing them to respect the declared Content-Type.

The MIME Sniffing Attack

Scenario: Your site allows file uploads. An attacker uploads a file named innocent.jpg but containing:

<script>alert('XSS')</script>

Without nosniff: Browser might ignore the Content-Type: image/jpeg header, detect HTML content, and execute the script.

With nosniff: Browser strictly follows the Content-Type header. File treated as image (won't render as HTML).

X-Content-Type-Options: nosniff

Referrer-Policy

Controls how much URL information is sent in the Referer header when users navigate away from your site.

PolicySame OriginCross-Origin (HTTPS→HTTPS)Downgrade (HTTPS→HTTP)
no-referrerNoneNoneNone
no-referrer-when-downgradeFull URLFull URLNone
originOrigin onlyOrigin onlyOrigin only
origin-when-cross-originFull URLOrigin onlyOrigin only
same-originFull URLNoneNone
strict-originOrigin onlyOrigin onlyNone
strict-origin-when-cross-originFull URLOrigin onlyNone
# Recommended: full URL internally, origin only externally, nothing on downgrade
Referrer-Policy: strict-origin-when-cross-origin
Why it matters: URLs may contain sensitive information (session tokens, search queries, user IDs). Leaking https://app.com/users/12345/settings to third-party analytics reveals user IDs.

Permissions-Policy (Feature-Policy)

Controls which browser features and APIs your page can use. Prevents embedded content from accessing sensitive capabilities.

# Disable sensitive features
Permissions-Policy: geolocation=(), microphone=(), camera=(), payment=(), usb=()

# Allow only same-origin to use geolocation
Permissions-Policy: geolocation=(self)

# Allow specific iframe to use camera
Permissions-Policy: camera=(self "https://trusted-video-app.com")

Common Features to Restrict:

FeatureRisk if UnrestrictedRecommended
geolocationTrack user location() unless needed
cameraAccess webcam() unless needed
microphoneRecord audio() unless needed
paymentAccess Payment Request API() unless e-commerce
usbAccess USB devices() unless needed
accelerometerMotion tracking() unless needed
autoplayAuto-play media (annoyance)(self)

Cross-Origin Isolation Headers

These headers provide protection against side-channel attacks (like Spectre) and control how your resources interact with other origins.

Cross-Origin-Opener-Policy (COOP)

Controls whether your page shares a browsing context group with cross-origin windows (opened via window.open or links).

# Isolate from cross-origin openers (security) but allow popups
Cross-Origin-Opener-Policy: same-origin-allow-popups

# Full isolation (breaks window.opener references)
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy (COEP)

Requires all resources to explicitly opt-in via CORS or CORP headers. Enables powerful features like SharedArrayBuffer.

# Require CORS/CORP for all subresources
Cross-Origin-Embedder-Policy: require-corp

# Credentialless mode (newer, more compatible)
Cross-Origin-Embedder-Policy: credentialless
Warning: COEP require-corp will break loading from CDNs (fonts, scripts) that don't set CORP headers. Only use if you self-host all resources or need SharedArrayBuffer.
Cross-Origin-Resource-Policy (CORP)

Controls who can load YOUR resources (images, scripts, etc.).

# Only same-site can embed our resources
Cross-Origin-Resource-Policy: same-site

# Only same-origin (stricter)
Cross-Origin-Resource-Policy: same-origin

# Anyone can embed (for CDNs/public APIs)
Cross-Origin-Resource-Policy: cross-origin

Complete Server Configurations

Nginx
Apache
Cloudflare
# /etc/nginx/conf.d/security-headers.conf (include in server blocks)

# HTTPS enforcement
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

# XSS and injection protection
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self'; frame-ancestors 'self'; form-action 'self'; base-uri 'self'; object-src 'none'; upgrade-insecure-requests" always;

# Clickjacking protection
add_header X-Frame-Options "SAMEORIGIN" always;

# MIME sniffing protection
add_header X-Content-Type-Options "nosniff" always;

# Referrer control
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

# Feature restrictions
add_header Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=()" always;

# Cross-origin isolation
add_header Cross-Origin-Opener-Policy "same-origin-allow-popups" always;
add_header Cross-Origin-Resource-Policy "same-site" always;

# Remove server identification
server_tokens off;
more_clear_headers Server;
# .htaccess or Apache config

<IfModule mod_headers.c>
    # HTTPS enforcement
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"

    # XSS and injection protection
    Header always set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self'; frame-ancestors 'self'; form-action 'self'; base-uri 'self'; object-src 'none'; upgrade-insecure-requests"

    # Clickjacking protection
    Header always set X-Frame-Options "SAMEORIGIN"

    # MIME sniffing protection
    Header always set X-Content-Type-Options "nosniff"

    # Referrer control
    Header always set Referrer-Policy "strict-origin-when-cross-origin"

    # Feature restrictions
    Header always set Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=()"

    # Cross-origin isolation
    Header always set Cross-Origin-Opener-Policy "same-origin-allow-popups"
    Header always set Cross-Origin-Resource-Policy "same-site"

    # Remove server identification
    Header unset Server
    Header always unset X-Powered-By
</IfModule>

# Hide Apache version
ServerTokens Prod
ServerSignature Off

In Cloudflare, use Transform Rules (Rules > Transform Rules > Modify Response Header):

# Add these as "Set static" rules:

Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: geolocation=(), microphone=(), camera=()
Cross-Origin-Opener-Policy: same-origin-allow-popups

# For CSP, use Page Rules or Workers for complex policies
Knowledge Check

Which CSP directive would you use to prevent your site from being embedded in an iframe on another domain?

script-src 'self'
default-src 'none'
frame-ancestors 'self'
frame-src 'none'

DNS (Domain Name System) is the internet's phone book, translating domain names to IP addresses. Because almost everything starts with a DNS lookup, DNS security is foundational—if attackers control your DNS, they control your traffic.

How DNS Works

Understanding DNS resolution helps you understand where attacks can occur.

DNS Resolution Process (Step by Step)

When you type www.example.com in your browser:

1. Browser Cache Check

Browser "Do I already know this IP?" (cached?)

2. OS Resolver

Browser OS Resolver Checks /etc/hosts, local cache

3. Recursive Resolver (ISP or 8.8.8.8)

OS Recursive Resolver Does the heavy lifting

4. Root Servers → TLD Servers → Authoritative Servers

Recursive Root (.) TLD (.com) Authoritative (example.com)

5. Answer Returned

The authoritative server returns the IP, which flows back through the chain and is cached at each level.

DNS Record Types Explained

Record Purpose Example Security Relevance
A Maps name to IPv4 address @ A 93.184.216.34 Primary target for hijacking
AAAA Maps name to IPv6 address @ AAAA 2606:2800:220:1::1 Don't forget IPv6 security
CNAME Alias to another name www CNAME example.com Subdomain takeover risk
MX Mail server for domain @ MX 10 mail.example.com Email security foundation
TXT Text data (SPF, DKIM, verification) @ TXT "v=spf1 ..." Email auth, domain verification
NS Authoritative nameservers @ NS ns1.provider.com Highest value target
CAA Authorized Certificate Authorities @ CAA 0 issue "letsencrypt.org" Prevents unauthorized certs
SOA Start of Authority (zone metadata) @ SOA ns1... admin... serial... Zone transfer info
PTR Reverse lookup (IP → name) 34.216.184.93.in-addr.arpa PTR ... Email deliverability, logging

Common DNS Attacks

DNS Cache Poisoning

Attacker injects false DNS responses into a resolver's cache, redirecting users to malicious sites.

Defense: DNSSEC, use trusted resolvers

Subdomain Takeover

Dangling CNAME to decommissioned service (S3, Heroku) allows attacker to claim the subdomain.

Defense: Audit and remove unused DNS records

DNS Rebinding

Attacker's domain initially resolves to their server, then "rebinds" to victim's internal IP (127.0.0.1), bypassing same-origin policy.

Defense: Validate Host headers, block private IPs in responses

DNS Hijacking

Attacker gains access to your DNS provider account or compromises your registrar, changing your NS records.

Defense: Strong auth, registrar lock, monitoring

Zone Transfer Attack

Unauthorized AXFR request reveals all DNS records, exposing internal infrastructure.

Defense: Restrict zone transfers to known IPs

DNS Amplification (DDoS)

Attacker spoofs victim's IP, sends small queries that generate large responses, overwhelming victim.

Defense: Rate limiting, response rate limiting (RRL)

Subdomain Takeover: A Common and Dangerous Vulnerability

The Scenario:

  1. Your company created app.example.com hosted on Heroku
  2. DNS: app CNAME example-app.herokuapp.com
  3. Project is cancelled, Heroku app is deleted
  4. DNS record is forgotten and left in place
  5. Attacker creates new Heroku app at example-app.herokuapp.com
  6. Attacker now controls app.example.com!

What attackers can do:

  • Host phishing pages on your subdomain
  • Steal cookies scoped to *.example.com
  • Send emails that pass SPF (if your SPF includes that subdomain)
  • Damage your brand reputation

Vulnerable Services:

  • Heroku, AWS S3, Azure, GitHub Pages, Netlify, Shopify, Zendesk, and many more
Detection: Tools like Nuclei, SubJack, or SubOver can scan for takeover vulnerabilities. Regularly audit your DNS records!

CAA Records (Certificate Authority Authorization)

CAA records specify which Certificate Authorities (CAs) are permitted to issue certificates for your domain. Without CAA, any CA can issue a certificate for your domain.

Why CAA Matters

Without CAA:

  • Any of 100+ public CAs could issue a certificate for your domain
  • If any CA is compromised or tricked, attackers get a valid cert
  • You have no visibility into unauthorized issuance attempts

With CAA:

  • CAs are required to check CAA before issuing (mandatory since 2017)
  • Unauthorized CAs refuse to issue
  • You can receive alerts about failed issuance attempts
# Allow only Let's Encrypt to issue certificates
example.com.    CAA    0 issue "letsencrypt.org"

# Allow wildcard certificates only from Let's Encrypt
example.com.    CAA    0 issuewild "letsencrypt.org"

# Report violations to your email
example.com.    CAA    0 iodef "mailto:security@example.com"

# Block all CAs (use carefully!)
example.com.    CAA    0 issue ";"

CAA Tag Reference:

TagPurposeExample Value
issue Authorize CA for regular certificates "letsencrypt.org" or "digicert.com"
issuewild Authorize CA for wildcard certificates "letsencrypt.org"
iodef Report policy violations "mailto:security@example.com"
Common CA Identifiers: letsencrypt.org, digicert.com, comodoca.com, sectigo.com, globalsign.com, amazonaws.com (ACM), pki.goog (Google Trust Services)

DNSSEC (DNS Security Extensions)

DNSSEC adds cryptographic signatures to DNS records, allowing resolvers to verify that responses haven't been tampered with.

How DNSSEC Works

DNSSEC adds these record types:

RecordPurpose
RRSIGSignature for a record set (e.g., signs your A records)
DNSKEYPublic keys used to verify signatures
DSDelegation Signer - links child zone to parent (chain of trust)
NSEC/NSEC3Proves a record doesn't exist (authenticated denial)

Chain of Trust:

Root Zone DS→ .com Zone DS→ example.com Zone

Each level vouches for the next via DS records. Resolvers start from the trusted root and verify each step.

Enabling DNSSEC:

  1. DNS Provider: Enable DNSSEC signing in your DNS provider's control panel (Cloudflare, Route53, etc.)
  2. Registrar: Add the DS record to your domain registrar (links your zone to the parent)
  3. Verify: Use DNSViz or dig +dnssec to confirm
# Check DNSSEC status
dig +dnssec example.com

# Look for 'ad' flag (Authenticated Data) in response
# ;; flags: qr rd ra ad;

# Query for DNSKEY records
dig DNSKEY example.com +short
DNSSEC Considerations:
  • Key rotation: Keys must be rotated periodically. Automated management (like Cloudflare) is recommended.
  • Larger responses: DNSSEC adds data to responses, which can cause issues with some firewalls.
  • Zone enumeration: NSEC records can allow enumeration of all records. Use NSEC3 to prevent this.

Encrypted DNS (DoH & DoT)

Traditional DNS is unencrypted—anyone on the network path can see your queries. Encrypted DNS protocols protect privacy.

ProtocolPortEncryptionDetection
Traditional DNS 53 (UDP/TCP) None Easily monitored/filtered
DNS over TLS (DoT) 853 (TCP) TLS Dedicated port, can be blocked
DNS over HTTPS (DoH) 443 (TCP) HTTPS Blends with web traffic, harder to block
DoH: Privacy vs. Security Trade-offs

Benefits:

  • ISPs can't see/log your DNS queries
  • Prevents DNS-based censorship
  • Protects against local network attackers

Concerns:

  • Bypasses enterprise security controls (DNS filtering)
  • Centralizes trust in DoH providers (Cloudflare, Google)
  • Makes network troubleshooting harder

For enterprises: Consider deploying your own DoH resolver or explicitly configuring endpoints to use your DNS infrastructure.

Popular Public DoH/DoT Resolvers:

ProviderDoH URLDoT Hostname
Cloudflare https://cloudflare-dns.com/dns-query 1dot1dot1dot1.cloudflare-dns.com
Google https://dns.google/dns-query dns.google
Quad9 https://dns.quad9.net/dns-query dns.quad9.net

DNS Security Best Practices

Do
  • Enable DNSSEC for your domains
  • Add CAA records specifying authorized CAs
  • Use registrar lock to prevent unauthorized transfers
  • Enable 2FA on your registrar and DNS provider accounts
  • Audit DNS records regularly, remove unused entries
  • Monitor for changes using DNS monitoring tools
  • Use short TTLs during migrations for fast rollback
  • Document your DNS so you know what every record does
Don't
  • Leave dangling CNAMEs pointing to decommissioned services
  • Allow zone transfers to unauthorized IPs
  • Use weak passwords on registrar accounts
  • Ignore expiration dates - domains can be hijacked when they expire
  • Put sensitive info in TXT records (they're public)
  • Use extremely long TTLs (hard to recover from misconfig)
  • Forget about subdomains when auditing security

Understanding TTL (Time to Live)

TTL determines how long DNS resolvers cache your records. It's a balance between performance and flexibility.

TTLValueUse CaseTrade-off
Very Short 60-300 sec During migrations, failover scenarios More DNS queries, slightly slower
Short 300-3600 sec Dynamic environments, CDNs Good balance for most sites
Long 3600-86400 sec Stable records (MX, NS) Slow to update, but fewer queries
Migration Strategy: Before making DNS changes, lower TTL to 300 seconds (5 minutes) and wait for the old TTL to expire. Make your change. If something goes wrong, you can roll back within minutes instead of hours.

DNS Monitoring and Alerting

You should know immediately if your DNS records change unexpectedly. Set up monitoring for:

  • A/AAAA record changes: Detect if your site's IP changes
  • NS record changes: Critical - indicates potential hijacking
  • MX record changes: Could indicate email interception attempt
  • New certificates: Monitor Certificate Transparency logs
  • WHOIS changes: Registrar or owner changes
Monitoring Tools: DNS Spy, Uptrends, ThousandEyes, or simple scripts with dig and alerting

DNS Security Checklist

ItemPriorityStatus Check
DNSSEC enabled High dig +dnssec yourdomain.com - look for ad flag
CAA records configured High dig CAA yourdomain.com
No dangling CNAMEs High Audit all CNAME records, verify targets exist
Registrar lock enabled High Check registrar control panel
2FA on registrar/DNS accounts Critical Verify in account settings
Zone transfers restricted Medium dig AXFR yourdomain.com @ns1.provider.com should fail
SPF, DKIM, DMARC configured Critical See Email Security section
Knowledge Check

Your company used to host shop.example.com on Shopify but cancelled the store. The CNAME record still points to shops.myshopify.com. What's the risk?

No risk - Shopify will show a "not found" error
Subdomain takeover - an attacker could claim that Shopify store name and control your subdomain
The subdomain will automatically be removed after 30 days

Understanding common threats helps you better protect your websites and recognize potential attacks.

Email Spoofing

Attackers send emails that appear to come from your domain to conduct phishing attacks.

Prevention: Implement SPF, DKIM, and DMARC.

Subdomain Takeover

When a subdomain points to a decommissioned external service, attackers can claim it.

Prevention: Audit DNS records and remove unused CNAME records.

Cross-Site Scripting (XSS)

Attackers inject malicious scripts into web pages that execute in users' browsers.

Prevention: Implement CSP headers, sanitize input, encode output.

Clickjacking

Your site is embedded in a hidden iframe, tricking users into clicking on it.

Prevention: Set X-Frame-Options: DENY or use CSP frame-ancestors.

Protocol Downgrade

Attackers force a connection to use unencrypted HTTP instead of HTTPS.

Prevention: Implement HSTS and consider HSTS preloading.

Typosquatting

Attackers register domains similar to yours for phishing (e.g., "examp1e.com").

Prevention: Register common misspellings, monitor for lookalikes.

These tools can help you assess and improve your website's security posture. Most are free, open-source, or offer free tiers for basic use.

Domain & URL Analysis

SiteSpecter

Comprehensive domain security analysis including DNS, SSL, headers, and threat intelligence.

Use SiteSpecter
VirusTotal

Analyze URLs and files against 70+ antivirus engines and blocklisting services.

Visit VirusTotal
URLScan.io

Analyze websites in a safe, sandboxed environment with detailed reports and screenshots.

Visit URLScan.io
Google Safe Browsing

Check if a URL is flagged as dangerous by Google's Safe Browsing service.

Safe Browsing Check
PhishTank

Community-driven clearinghouse for phishing data. Check and report phishing URLs.

Visit PhishTank
URLhaus

Database of malicious URLs used for malware distribution. Free API available.

Visit URLhaus
CheckPhish

AI-powered phishing URL scanner with real-time analysis and screenshots.

Visit CheckPhish
ANY.RUN

Interactive malware sandbox. Analyze URLs and files in a live environment.

Visit ANY.RUN

SSL/TLS & Headers Analysis

SSL Labs

Deep analysis of SSL/TLS configuration with detailed recommendations and grading.

Visit SSL Labs
SecurityHeaders.com

Analyze your HTTP response headers and get a security grade.

Visit SecurityHeaders
Mozilla Observatory

Comprehensive website security scanner from Mozilla covering headers, TLS, and more.

Visit Observatory
crt.sh

Certificate Transparency log search. Find all SSL certificates issued for a domain.

Visit crt.sh
CSP Evaluator

Google's tool to evaluate Content Security Policy for weaknesses and bypasses.

CSP Evaluator
Hardenize

Comprehensive security configuration assessment for websites and email.

Visit Hardenize

DNS & Email Security

MXToolbox

Check email configuration including SPF, DKIM, DMARC, and blacklist status.

Visit MXToolbox
DNSDumpster

DNS reconnaissance tool. Discover subdomains, MX, TXT, and other records.

Visit DNSDumpster
ViewDNS.info

Collection of DNS tools including reverse IP, WHOIS, port scanner, and more.

Visit ViewDNS
DMARC Analyzer

Check DMARC, SPF, and DKIM records. Understand email authentication setup.

DMARC Check
SecurityTrails

Historical DNS data, WHOIS, and subdomain enumeration. Free tier available.

Visit SecurityTrails
ICANN WHOIS

Official ICANN WHOIS lookup for domain registration information.

ICANN Lookup

Threat Intelligence & OSINT

AlienVault OTX

Community-driven threat intelligence with free access to indicators of compromise.

Visit OTX
Shodan

Search engine for internet-connected devices. Find exposed services and vulnerabilities.

Visit Shodan
Censys

Internet-wide scanning platform. Discover hosts, certificates, and services.

Visit Censys
GreyNoise

Analyze internet-wide scan and attack traffic. Identify benign vs malicious IPs.

Visit GreyNoise
AbuseIPDB

IP address reputation database. Check and report malicious IPs.

Visit AbuseIPDB
ThreatFox

IOC sharing platform from abuse.ch. Search malware indicators and C2 servers.

Visit ThreatFox
MalwareBazaar

Malware sample sharing. Search hashes and download samples for analysis.

Visit MalwareBazaar
Pulsedive

Free threat intelligence platform with IOC enrichment and risk scoring.

Visit Pulsedive

Vulnerability & Web App Scanning

OWASP ZAP

Open-source web application security scanner. Industry standard for pen testing.

Visit ZAP
Nikto

Open-source web server scanner. Checks for dangerous files and outdated software.

Visit Nikto
Nuclei

Fast vulnerability scanner with community templates. Great for automation.

Visit Nuclei
WPScan

WordPress vulnerability scanner. Detects plugins, themes, and security issues.

Visit WPScan
Nmap

Network scanner and security auditing tool. The gold standard for port scanning.

Visit Nmap
testssl.sh

Command-line tool for checking TLS/SSL ciphers, protocols, and vulnerabilities.

Visit testssl.sh

Reconnaissance & OSINT

Wayback Machine

View historical snapshots of websites to investigate changes over time.

Visit Wayback Machine
BuiltWith

Technology lookup tool. See what frameworks, CMS, and services a site uses.

Visit BuiltWith
Wappalyzer

Browser extension to identify technologies on websites. Free and open-source.

Visit Wappalyzer
Hunter.io

Find email addresses associated with a domain. Useful for social engineering awareness.

Visit Hunter.io
theHarvester

OSINT tool for gathering emails, subdomains, hosts, and more from public sources.

View on GitHub
Recon-ng

Full-featured reconnaissance framework. Modular with many data sources.

View on GitHub
Amass

OWASP project for subdomain enumeration and network mapping. Very thorough.

View on GitHub
Subfinder

Fast passive subdomain discovery tool. Uses many data sources.

View on GitHub

Data Breach & Credential Checking

Have I Been Pwned

Check if your email or password has been compromised in a data breach.

Visit HIBP
DeHashed

Search engine for leaked credentials and personal data. Useful for exposure checks.

Visit DeHashed
Firefox Monitor

Mozilla's breach notification service powered by Have I Been Pwned.

Visit Firefox Monitor
IntelligenceX

Search engine for leaked data, darknet, and OSINT sources. Free tier available.

Visit IntelligenceX

Browser & Network Tools

Browser DevTools

Built into every browser. Inspect network traffic, cookies, storage, and more.

Press F12
Burp Suite Community

Web security testing toolkit. Intercept and modify HTTP traffic.

Download Burp
Wireshark

Network protocol analyzer. Capture and inspect network traffic at the packet level.

Visit Wireshark
mitmproxy

Open-source interactive HTTPS proxy. Great for debugging and testing.

Visit mitmproxy
Tip: Many of these tools have free tiers or are fully open-source. Start with web-based tools like VirusTotal and URLScan for quick checks, then explore command-line tools like Nmap and Nuclei for deeper analysis.

Deepen your knowledge of web security with these trusted external resources from industry leaders and security organizations.

Security Organizations & Standards

OWASP

The Open Web Application Security Project - leading nonprofit for web security. Home of the OWASP Top 10.

OWASP.org Top 10
NIST Cybersecurity

National Institute of Standards and Technology - authoritative cybersecurity frameworks.

NIST Framework
CISA

Cybersecurity and Infrastructure Security Agency - US government cybersecurity resources.

CISA KEV
SANS Institute

World's largest source for information security training and research.

SANS Reading Room

Web Security Documentation

MDN Web Security

Mozilla's comprehensive web security documentation covering CSP, CORS, HTTPS.

MDN Security
Cloudflare Learning

Educational content about DNS, DDoS protection, SSL/TLS, and web security.

Cloudflare Learning
PortSwigger Web Academy

Free, hands-on web security training with interactive labs.

Web Security Academy
Let's Encrypt

Free SSL/TLS certificates with comprehensive documentation.

Let's Encrypt Certbot

Threat Intelligence & News

Krebs on Security

In-depth security news and investigation by journalist Brian Krebs.

Krebs on Security
CVE Database

Standard for identifying and cataloging security vulnerabilities.

CVE NVD
AlienVault OTX

Community-driven threat intelligence with free access to indicators.

AlienVault OTX
The Hacker News

Daily cybersecurity news covering vulnerabilities, breaches, and research.

The Hacker News
Tip: Bookmark these resources and check them regularly. The security landscape changes constantly, and staying informed is one of the best defenses.