Preventing Email Spoofing: How to Secure Your Domain Against Unauthorized SMTP Relays


3 views

When your mailserver starts receiving NDRs (Non-Delivery Reports) for emails you never sent, it's a clear sign of domain spoofing. Your case with itaccess.org demonstrates classic symptoms:

Return-Path: <whao@www20.aname.net>
Received: from smtp-gw.fsdata.se (smtp-gw.fsdata.se. [195.35.82.145])
        by mx.google.com with ESMTP id b9si24888989lbg.77.2012.08.08.07.12.44

Implement these DNS records to establish sender verification:

# SPF Record (TXT)
itaccess.org. IN TXT "v=spf1 include:_spf.google.com -all"

# DKIM Record (Google Apps specific)
google._domainkey.itaccess.org. IN TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC..."

# DMARC Record
_dmarc.itaccess.org. IN TXT "v=DMARC1; p=reject; rua=mailto:postmaster@itaccess.org"

Use this Python script to analyze suspicious messages:

import email
from email.header import decode_header

def analyze_bounce(msg_file):
    with open(msg_file, 'r') as f:
        msg = email.message_from_file(f)
    
    print(f"From: {msg['From']}")
    print(f"Return-Path: {msg['Return-Path']}")
    
    received_headers = msg.get_all('Received', [])
    for idx, header in enumerate(received_headers):
        print(f"\nHop #{idx+1}:")
        print(header.strip())

Enable these G Suite settings:

  1. Admin Console → Apps → G Suite → Gmail → Advanced settings
  2. Enable "Prevent spoofing of your domain"
  3. Set "Unauthenticated email" to reject

Set up a Bash script to monitor Postfix logs (adapt for your MTA):

#!/bin/bash
tail -f /var/log/mail.log | grep --line-buffered -i \
    -e 'relay=' \
    -e 'sender=' \
    -e 'client=' \
    -e 'itaccess.org' | \
    while read line; do
        echo "$(date '+%T') $line" >> /var/log/mail_audit.log
    done

Create a fail2ban filter for SMTP abuse:

[Definition]
failregex = ^.*client=.*sender=.*@itaccess.org.* 550
            ^.*SPF:.*fail.*client=

Combine with AWS Lambda for cloud-based domains:

// Node.js Lambda function for SES monitoring
exports.handler = async (event) => {
    const sesNotification = event.Records[0].ses;
    if(sesNotification.receipt.spfVerdict.status === 'FAIL') {
        // Add offender to blacklist
    }
};

The email headers reveal a classic case of domain spoofing where attackers are forging @itaccess.org addresses without proper authentication. The key indicators in the headers:

Return-Path: <whao@www20.aname.net>
Received: from www20.aname.net
X-FS-SpamAssassinScore: 1.8

This shows the emails are originating from a Swedish server (aname.net) while pretending to be from your domain.

Implement these DNS records immediately:

; SPF Record
itaccess.org. IN TXT "v=spf1 include:_spf.google.com ~all"

; DKIM Record (Google Apps example)
google._domainkey.itaccess.org. IN TXT "v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA..."

; DMARC Record
_dmarc.itaccess.org. IN TXT "v=DMARC1; p=reject; rua=mailto:postmaster@itaccess.org"

For domains using Google Apps:

  1. Enable SMTP TLS Reporting in Admin Console
  2. Configure Email Allowlist to restrict outgoing servers
  3. Set up Advanced phishing protection with these settings:
gmail api settings:
{
  "phishingProtection": {
    "enableStricterValidation": true,
    "enableEnhancedPredefinedRules": true
  }
}

If running your own mail server, implement these Postfix configurations:

# /etc/postfix/main.cf
smtpd_sender_restrictions = 
    reject_unknown_sender_domain,
    reject_unverified_sender,
    reject_unauth_pipelining,
    check_sender_access regexp:/etc/postfix/sender_access

smtpd_recipient_restrictions =
    permit_mynetworks,
    reject_unauth_destination

Create a Python script to monitor bouncebacks:

import imaplib
import email
from email.header import decode_header

def check_bounces(imap_server, username, password):
    mail = imaplib.IMAP4_SSL(imap_server)
    mail.login(username, password)
    mail.select('INBOX')
    
    typ, data = mail.search(None, '(SUBJECT "Mailer-Daemon")')
    for num in data[0].split():
        typ, msg_data = mail.fetch(num, '(RFC822)')
        raw_email = msg_data[0][1]
        msg = email.message_from_bytes(raw_email)
        
        print(f"Bounce detected from: {msg['From']}")
        print(f"Original recipient: {msg['To']}")
        
        # Analyze email content for spoofing patterns
        if 'itaccess.org' in str(msg) and 'Received: from' not in str(msg):
            print("[ALERT] Potential domain spoofing detected")
            
    mail.close()
    mail.logout()

Set up a Lambda function to automatically update firewall rules when abuse is detected:

// AWS Lambda function to block offending IPs
const AWS = require('aws-sdk');
const ec2 = new AWS.EC2();

exports.handler = async (event) => {
    const offendingIP = event.detail.sourceIPAddress;
    
    const params = {
        GroupId: 'sg-12345678',
        IpPermissions: [{
            IpProtocol: 'tcp',
            FromPort: 25,
            ToPort: 25,
            IpRanges: [{
                CidrIp: `${offendingIP}/32`,
                Description: 'Blocked for SMTP abuse'
            }]
        }]
    };
    
    await ec2.revokeSecurityGroupIngress(params).promise();
    return `Blocked ${offendingIP} for SMTP abuse`;
};

When investigating incidents, use these email header analysis methods:

# Parse received headers to identify traversal
received_headers = email_message.get_all('Received', [])
hop_path = [h.split('from')[1].split('by')[0].strip() for h in received_headers]
print(f"Email traveled through: {' -> '.join(hop_path)}")