SPF: Protecting Your Domain from Email Spoofing

What is it?

Sender Policy Framework (SPF) is an email authentication protocol designed to prevent email spoofing by verifying that incoming mail from a domain comes from an IP address authorized by that domain's administrators. SPF allows domain owners to specify which mail servers are permitted to send email on behalf of their domain.

At its core, SPF works through DNS TXT records. When you publish an SPF record in your domain's DNS zone, you're creating a public list of IP addresses and hostnames that are allowed to send email using your domain name. Email receiving servers can then query this DNS record to verify whether an incoming message claiming to be from your domain actually originated from an authorized source.

The SPF record is a specially formatted string that begins with v=spf1, followed by mechanisms that define authorized senders, and typically ends with a policy directive (-all, ~all, or ?all) that specifies what to do with messages from unauthorized sources.

Here's a basic example of an SPF record:

v=spf1 ip4:192.0.2.0/24 include:_spf.google.com -all

This record states: "Mail from this domain is authorized to come from IP addresses in the 192.0.2.0/24 range and from servers listed in Google's SPF record. All other sources should be rejected."

SPF verification happens during the SMTP transaction, before the message body is transmitted. The receiving mail server extracts the "MAIL FROM" address (also called envelope sender or Return-Path), queries DNS for the SPF record of the sender's domain, evaluates whether the sending IP address matches any of the authorized mechanisms, and generates an SPF result (Pass, Fail, SoftFail, Neutral, None, TempError, or PermError).

Why does it matter?

Without SPF, email systems operate on trust. SMTP, the protocol underlying email transmission, was designed in a more innocent era and includes no built-in sender authentication. Anyone can configure a mail server to claim messages are from any domain. This fundamental weakness makes email inherently vulnerable to spoofing attacks.

Email Spoofing and Phishing

The absence of SPF allows attackers to send emails that appear to come from your domain with trivial ease. They can send phishing emails to your customers claiming to be from your support team, your executives, or your billing department. These emails appear completely legitimate in the recipient's inbox with your domain in the "From" field.

Consider this scenario: An attacker sends emails claiming to be from [email protected], requesting customers update their payment information by clicking a link. Without SPF, nothing prevents these emails from appearing legitimate. Recipients see your domain, trust it, and become victims. Your organization suffers reputational damage, potential legal liability, and loss of customer trust.

Brand Reputation Damage

Email spoofing doesn't just enable phishing attacks against others. Attackers can use your domain to send spam, distribute malware, or conduct other malicious activities. When recipients receive these messages, they associate the abuse with your brand. Email providers may start blocking all email from your domain, preventing your legitimate messages from reaching customers. You may end up on DNS-based blacklists (DNSBLs), which can take weeks or months to remediate even after implementing SPF.

Business Email Compromise (BEC)

Without SPF, attackers can impersonate your executives or employees in targeted Business Email Compromise attacks. They send emails appearing to come from your CEO to your finance department, requesting urgent wire transfers. They impersonate employees to HR departments, changing direct deposit information. BEC attacks have resulted in billions of dollars in losses globally, and the lack of email authentication makes these attacks remarkably effective.

Compliance and Legal Requirements

Many regulatory frameworks and compliance standards now require or strongly recommend email authentication. GDPR in Europe emphasizes organizational security measures for protecting personal data, which includes preventing unauthorized use of your domain. Industry-specific regulations like HIPAA (healthcare) and PCI DSS (payment card industry) include email security requirements that SPF helps satisfy.

Email Deliverability

Major email providers like Gmail, Outlook, Yahoo, and others increasingly require SPF as a signal of legitimate email. Domains without SPF records face deliverability challenges:

  • Higher likelihood of legitimate emails being marked as spam
  • Rejection by strict mail servers
  • Lower sender reputation scores
  • Reduced effectiveness of marketing and transactional emails

Google and Yahoo announced in 2024 that they would require SPF (along with DKIM) for bulk senders. Without proper email authentication, your messages simply won't reach recipients using these providers.

Protection Against Backscatter

When spammers forge your domain in the "MAIL FROM" address and send to invalid recipients, mail servers generate bounce messages (Non-Delivery Reports) back to the forged address. This "backscatter" floods your legitimate mailboxes with bounce messages for emails you never sent. SPF helps prevent this by allowing receiving servers to reject forged messages during the SMTP transaction rather than accepting them and generating bounces.

How attacks work

Understanding how attackers exploit the absence of SPF helps illustrate why this authentication mechanism is critical.

Phase 1: Target Selection

Attackers identify domains without SPF records or with weak SPF configurations. They use automated tools to:

  • Query DNS for SPF records of target domains
  • Identify domains with no SPF record (SPF result: None)
  • Find weak SPF records using ?all (Neutral) or +all (Pass, which authorizes everyone)
  • Discover misconfigured SPF records that fail validation (PermError)

Phase 2: Infrastructure Setup

Once attackers identify a spoofable domain, they set up their attack infrastructure:

  • Configure a mail server under their control (often a compromised server or cheap VPS)
  • Set up email templates that mimic the target organization's communication style
  • Create phishing landing pages or malware distribution sites
  • Prepare address lists of potential victims (customers, employees, partners)

Phase 3: Spoofed Email Transmission

The actual spoofing attack is technically simple:

  1. The attacker's mail server connects to a recipient's mail server
  2. During the SMTP transaction, they specify any email address as the "MAIL FROM" value:
220 mail.victim.com ESMTP
HELO attacker.com
250 Hello attacker.com
MAIL FROM:<[email protected]>
250 OK
RCPT TO:<[email protected]>
250 OK
DATA
354 End data with <CR><LF>.<CR><LF>
From: CEO <[email protected]>
To: [email protected]
Subject: Urgent: Wire Transfer Required

Please process the attached wire transfer immediately...
.
250 OK

Notice that the attacker's server claims the email is from [email protected]. Without SPF, nothing prevents this claim.

Phase 4: SPF Bypass Attempts

Even when SPF is implemented, sophisticated attackers may attempt bypass techniques:

SPF Misalignment Exploit

SPF only validates the MAIL FROM address (envelope sender), not the From header (what users see). Attackers can use:

MAIL FROM:<[email protected]>   # Passes SPF
From: CEO <[email protected]>      # What victim sees

The SPF check passes (attacker's domain is correctly authenticated), but the user sees the spoofed domain. This is why DMARC is necessary in addition to SPF - it requires alignment between these addresses.

Subdomain Exploitation

If the main domain has SPF but subdomains don't, attackers can spoof subdomain addresses:

From: [email protected]

If mail.targetcompany.com lacks an SPF record and the parent domain's SPF doesn't cover subdomains, this spoofing succeeds.

SPF Macro Injection

Poorly implemented SPF parsers might be vulnerable to macro injection. SPF supports macros like %{i} (sending IP) and %{d} (domain). Complex macro expressions can sometimes confuse parsers or create unexpected authorization.

DNS Lookup Limit Exploitation

SPF has a limit of 10 DNS lookups. Attackers might send legitimate emails that consume multiple lookups, then later send malicious emails that cause the victim's SPF record to exceed the limit, resulting in PermError. Some mail servers treat PermError leniently, potentially allowing spoofed emails.

Phase 5: Social Engineering

With spoofed emails successfully delivered, attackers leverage social engineering:

  • Urgency ("Wire transfer needed immediately")
  • Authority ("Message from CEO/Executive")
  • Trust ("Coming from official domain")
  • Mimicry (Matching communication style and formatting)
  • Context (Timing emails with known events like payroll, tax season)

The combination of technical spoofing capability and social engineering tactics makes these attacks highly effective against organizations lacking proper email authentication.

Real-world incidents

SPF-related vulnerabilities and attacks have led to numerous high-profile incidents demonstrating the real-world impact of missing or misconfigured email authentication.

Business Email Compromise Epidemic

The FBI's Internet Crime Complaint Center (IC3) reports that BEC attacks resulted in losses exceeding $43 billion between 2016 and 2021. While not all these attacks exploited missing SPF, a significant portion succeeded because organizations lacked proper email authentication. In many documented cases, attackers spoofed executive email addresses to instruct finance departments to make fraudulent wire transfers. Companies with proper SPF, DKIM, and DMARC implementation could have prevented these spoofed emails from reaching employees.

Toyota Boshoku Corporation (2019)

This Toyota affiliate lost 4 billion yen (approximately $37 million) in a BEC attack. Attackers spoofed legitimate business partners and executives to authorize fraudulent fund transfers. The incident highlighted how even sophisticated organizations with mature security programs can fall victim when email authentication is absent or improperly configured.

Ubiquiti Networks (2015)

The networking equipment manufacturer lost $46.7 million to BEC fraud. Attackers impersonated executives and requested wire transfers to overseas accounts. While details of their email security configuration weren't publicly disclosed, the attack methodology matched typical BEC patterns that SPF and DMARC are designed to prevent.

COVID-19 Phishing Campaigns (2020-2021)

During the pandemic, researchers observed massive increases in phishing campaigns spoofing health organizations, government agencies, and logistics companies. Many of these campaigns succeeded because legitimate organizations lacked SPF records. Attackers spoofed domains of organizations like the WHO, CDC, and delivery services to distribute malware and steal credentials. Analysis of these campaigns showed that a significant percentage of spoofed domains had no SPF records or weak ?all policies.

Scattered Spider Group (2023)

This sophisticated threat actor group compromised major companies including MGM Resorts and Caesars Entertainment partially through social engineering attacks that included spoofed emails. While they used multiple techniques, their success was facilitated by the ability to send emails appearing to come from legitimate corporate domains. Strong email authentication could have blocked these spoofed messages and disrupted their attack chain.

Tax Season W-2 Phishing (Ongoing)

Every tax season, attackers send spoofed emails impersonating executives to HR and payroll departments requesting employee W-2 forms. These attacks have successfully compromised employee personal information at thousands of organizations, including healthcare providers, schools, and businesses. The consistent success of these attacks year after year demonstrates that many organizations still lack proper SPF implementation.

What Nyambush detects

Nyambush provides comprehensive SPF analysis as part of your email security posture assessment. Here's what our scanner examines:

SPF Record Discovery

Nyambush queries your domain's DNS to identify SPF records:

  • Checks for TXT records containing SPF data
  • Identifies domains with no SPF record
  • Detects multiple conflicting SPF records (which causes validation failure)
  • Examines subdomains for SPF coverage

SPF Syntax Validation

We parse and validate your SPF record syntax:

  • Verifies the record starts with v=spf1
  • Checks for syntax errors that would cause PermError
  • Validates mechanism formats (ip4, ip6, a, mx, include, etc.)
  • Ensures proper modifier placement
  • Identifies deprecated or non-standard mechanisms

DNS Lookup Count Analysis

SPF has a critical limit of 10 DNS lookups. Nyambush counts all lookups in your SPF record:

  • Recursively resolves all include: mechanisms
  • Counts lookups from a, mx, exists, and ptr mechanisms
  • Warns when approaching the 10-lookup limit
  • Identifies chains that exceed the limit (causing PermError)

Here's an example of lookup counting:

v=spf1 include:_spf.google.com include:spf.protection.outlook.com include:_spf.salesforce.com -all

This simple-looking record might actually require:

  • 3 direct lookups for the three includes
  • Each of those SPF records may have additional includes
  • The total could easily exceed 10 lookups

Policy Strength Assessment

Nyambush evaluates your SPF policy directive:

  • -all (Hard fail): Strongest policy, recommended for most domains
  • ~all (Soft fail): Acceptable during testing, less strict
  • ?all (Neutral): Weak, offers little protection
  • +all (Pass): Dangerous, authorizes all senders

We provide clear guidance on policy strength and recommendations for improvement.

Authorization Scope Analysis

Nyambush examines what your SPF record authorizes:

  • Identifies overly broad authorizations (ip4:0.0.0.0/0)
  • Flags inclusion of untrusted or compromised third-party SPF records
  • Checks for authorization of unnecessary mail servers
  • Validates that known sending sources are included

Subdomain Coverage Check

We test whether subdomains are protected:

  • Scans common subdomains for SPF records
  • Identifies subdomains lacking SPF protection
  • Verifies parent domain SPF doesn't unintentionally cover subdomains
  • Recommends explicit subdomain SPF records or null SPF (v=spf1 -all) for non-sending domains

Include Chain Analysis

For complex SPF records with multiple include: statements, Nyambush maps the entire authorization chain:

  • Visualizes nested include relationships
  • Identifies single points of failure (if an included domain goes offline)
  • Flags includes pointing to non-existent domains
  • Detects circular include references

Integration with DMARC Analysis

SPF is most effective when combined with DMARC. Nyambush analyzes SPF in the context of your complete email authentication posture:

  • Checks for DMARC policy presence
  • Verifies SPF alignment requirements
  • Identifies gaps where SPF passes but DMARC alignment fails
  • Provides holistic email authentication recommendations

How to fix it

Implementing SPF properly requires careful planning and testing to avoid disrupting legitimate email flow while providing strong protection against spoofing.

Step 1: Inventory Your Email Sources

Before creating an SPF record, identify all legitimate sources that send email from your domain:

  • Your email server (on-premises or hosted)
  • Email service providers (Google Workspace, Microsoft 365)
  • Marketing platforms (Mailchimp, SendGrid, HubSpot)
  • Transactional email services (AWS SES, Postmark, Mandrill)
  • Third-party systems (CRM, ERP, helpdesk software)
  • Custom applications sending notifications
  • Automated systems (monitoring alerts, backup reports)

Document each source's IP addresses or DNS names. Contact vendors if you need SPF information - most provide specific include statements for their services.

Step 2: Build Your SPF Record

Construct your SPF record using appropriate mechanisms:

Basic Structure:

v=spf1 [mechanisms] [qualifier]

Common Mechanisms:

# Authorize specific IP addresses
ip4:192.0.2.10
ip4:192.0.2.0/24
ip6:2001:db8::1

# Authorize mail servers from your domain's A record
a:mail.example.com

# Authorize mail servers from your domain's MX records
mx

# Include another domain's SPF record
include:_spf.google.com
include:spf.protection.outlook.com

# Authorize a specific hostname
a:mail.example.com

Example for a company using Google Workspace and SendGrid:

v=spf1 include:_spf.google.com include:sendgrid.net -all

Example for a company with on-premises mail server and Microsoft 365:

v=spf1 ip4:192.0.2.10 include:spf.protection.outlook.com -all

Step 3: Manage DNS Lookup Limits

SPF restricts you to 10 DNS lookups. Use these strategies to stay within the limit:

Flatten Include Chains:

Instead of including an SPF record that itself includes others, manually add IP addresses:

# Before (may exceed lookup limit)
v=spf1 include:vendor1.com include:vendor2.com include:vendor3.com -all

# After (if vendor1 includes multiple records)
v=spf1 ip4:203.0.113.0/24 ip4:198.51.100.0/24 include:vendor2.com include:vendor3.com -all

Consolidate Email Sources:

Consider routing all outbound email through fewer providers to reduce includes.

Use Dedicated Subdomains:

Split email sources across subdomains:

# Main domain
example.com: v=spf1 include:_spf.google.com -all

# Marketing subdomain
marketing.example.com: v=spf1 include:sendgrid.net -all

Step 4: Publish Your SPF Record

Add the SPF record to your DNS zone as a TXT record:

Cloudflare:

  1. Log in to Cloudflare dashboard
  2. Select your domain
  3. Navigate to DNS → Records
  4. Click "Add record"
  5. Type: TXT
  6. Name: @ (or your domain)
  7. Content: v=spf1 include:_spf.google.com -all
  8. TTL: Auto (or 3600 for 1 hour)
  9. Click "Save"

AWS Route 53 (CLI):

aws route53 change-resource-record-sets \
  --hosted-zone-id Z1234567890ABC \
  --change-batch '{
    "Changes": [{
      "Action": "UPSERT",
      "ResourceRecordSet": {
        "Name": "example.com",
        "Type": "TXT",
        "TTL": 3600,
        "ResourceRecords": [{
          "Value": "\"v=spf1 include:_spf.google.com -all\""
        }]
      }
    }]
  }'

Note: TXT record values must be enclosed in quotes, and quotes within the value must be escaped in some DNS interfaces.

Step 5: Start with Soft Fail

When first implementing SPF, use ~all (soft fail) instead of -all (hard fail) to avoid blocking legitimate email if you missed a sending source:

v=spf1 include:_spf.google.com ~all

This tells receiving servers: "These are authorized senders, but don't strictly reject messages from other sources."

Step 6: Monitor and Test

After publishing your SPF record:

Verify DNS propagation:

dig example.com TXT
nslookup -type=TXT example.com

Test with SPF validation tools:

  • Google Admin Toolbox: https://toolbox.googleapps.com/apps/checkmx/
  • MXToolbox: https://mxtoolbox.com/spf.aspx
  • Nyambush scan results

Send test emails:

Send test messages from each authorized source and check SPF results in email headers:

Received-SPF: pass (google.com: domain of [email protected] designates 192.0.2.10 as permitted sender)
Authentication-Results: spf=pass smtp.mailfrom=example.com

Monitor DMARC reports:

If you have DMARC configured, analyze aggregate reports (rua) to identify any legitimate sources failing SPF.

Step 7: Transition to Hard Fail

After monitoring for several weeks without issues, upgrade to -all:

v=spf1 include:_spf.google.com -all

This provides maximum protection by instructing receiving servers to reject messages from unauthorized sources.

Step 8: Protect Subdomains

Create SPF records for subdomains:

For subdomains that send email:

mail.example.com: v=spf1 ip4:192.0.2.10 -all

For subdomains that never send email (prevents spoofing):

cdn.example.com: v=spf1 -all
api.example.com: v=spf1 -all

The -all with no authorized mechanisms explicitly states that the subdomain should never send email, preventing spoofing.

Step 9: Regular Maintenance

SPF requires ongoing maintenance:

  • Review SPF records quarterly
  • Update records when email sources change
  • Monitor DNS lookup counts as you add services
  • Test after any changes
  • Document email sources and SPF configuration
  • Use Nyambush continuous monitoring for automated validation

Common Mistakes to Avoid:

  1. Multiple SPF records: Only one SPF record per domain (multiple records cause PermError)
  2. Exceeding 10 lookups: Monitor include chain depth
  3. Using deprecated ptr mechanism: Avoid ptr, it's inefficient and deprecated
  4. Forgetting the policy: Records must end with all qualifier
  5. Not protecting subdomains: Attackers exploit unprotected subdomains
  6. Never updating: Email sources change, SPF must be maintained

Summary

Sender Policy Framework (SPF) is a fundamental email authentication mechanism that protects your domain from spoofing by specifying which mail servers are authorized to send email on your behalf. Through DNS TXT records, SPF allows receiving mail servers to verify that incoming messages claiming to be from your domain actually originate from legitimate sources.

The stakes are high. Without SPF, attackers can trivially forge emails appearing to come from your domain, enabling phishing attacks against your customers, Business Email Compromise targeting your employees, spam campaigns damaging your reputation, and malware distribution using your brand's trust. Real-world incidents have resulted in billions of dollars in losses and severe reputational damage to organizations lacking proper email authentication.

SPF works by defining authorized senders through mechanisms like IP addresses, hostnames, and includes of other domains' SPF records. Receiving servers query your SPF record during the SMTP transaction and generate a result (Pass, Fail, SoftFail, etc.) that influences delivery decisions. When combined with DKIM and DMARC, SPF forms part of a comprehensive email authentication strategy.

Implementation requires careful planning: inventorying all email sources, constructing an SPF record within the 10 DNS lookup limit, publishing the record in DNS, testing with soft fail initially, monitoring for issues, and transitioning to hard fail for maximum protection. Don't forget to protect subdomains with explicit SPF records.

Nyambush automates SPF validation by discovering your SPF records, validating syntax, counting DNS lookups, assessing policy strength, checking subdomain coverage, and providing actionable recommendations. We continuously monitor your email authentication posture and alert you to configuration issues before they impact deliverability or security.

Email authentication is no longer optional. Major providers like Google and Yahoo now require SPF for bulk senders, and its absence directly impacts your ability to reach recipients. More importantly, SPF is essential for protecting your brand, your users, and your organization from the epidemic of email-based attacks. Implement SPF today - it's one of the highest-impact, lowest-cost security controls available.

Share this article:Post on X

Is your domain secure?

Run a free scan with Nyambush to check your security risks right now.