Skip to content

Email Header Analyzer — Go source

Paste raw email headers to trace the message path, detect spoofing, and check SPF/DKIM/DMARC authentication results. Runs entirely in your browser.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package emailheaderanalyzer ports src/lib/email-header-analyzer.ts (dual
// source: the web lib is TypeScript, the CLI lib is Go — kept in lock-step).
// It parses raw RFC 5322 email headers into structured data: unfolded header
// pairs, chronological Received hops with per-leg delays, SPF/DKIM/DMARC
// authentication results, and spoofing anomalies. Pure string parsing —
// stdlib only, deterministic, never panics. The table-driven tests in
// email_header_analyzer_test.go share vectors with
// src/lib/email-header-analyzer.test.ts so the two implementations are held
// to the same contract.
package emailheaderanalyzer

import (
	"fmt"
	"math"
	"net/mail"
	"regexp"
	"strings"
	"time"
)

// Header is one unfolded name/value header pair.
type Header struct {
	Name  string
	Value string
}

// Hop is one Received leg, in chronological order: Hops[0] is the OLDEST hop
// (Received headers list newest-first; ParseHeaders reverses them). Timestamp
// is nil when absent or unparseable; Delay (seconds elapsed since the
// previous, earlier hop) is nil when unknown.
type Hop struct {
	From      string
	By        string
	Timestamp *time.Time
	Delay     *float64
	Protocol  string
}

// AuthResult is one SPF/DKIM/DMARC mechanism outcome. Result is one of
// pass | fail | softfail | neutral | none | temperror | permerror | unknown.
// Policy is the DMARC policy from the p= token (DMARC only); Detail is the
// full authentication clause when present. Pointer fields are nil when the
// TS lib would return null.
type AuthResult struct {
	Result   string
	Domain   *string
	Selector *string
	Policy   *string
	Detail   *string
}

// AuthResults bundles the three authentication mechanisms.
type AuthResults struct {
	SPF   AuthResult
	DKIM  AuthResult
	DMARC AuthResult
}

// Severity mirrors AnomalySeverity in the TS lib.
type Severity string

const (
	SeverityCritical Severity = "critical"
	SeverityWarning  Severity = "warning"
	SeverityInfo     Severity = "info"
)

// Anomaly is one detected spoofing / integrity signal.
type Anomaly struct {
	Type     string
	Severity Severity
	Message  string
}

// ParsedHeaders is the full analysis result of ParseHeaders.
type ParsedHeaders struct {
	Headers   []Header
	Hops      []Hop
	Auth      AuthResults
	Anomalies []Anomaly
}

// suspiciousMailers holds tokens often seen in bulk-sending tools. Mirrors
// SUSPICIOUS_MAILERS in the TS lib (order matters: the first hit is reported).
var suspiciousMailers = []string{
	"bulk", "mass mail", "massmail", "storm", "flood", "bomber",
	"grabber", "harvest", "spambot", "stealth", "anonymous", "dark", "crack",
}

var (
	bracketAddrRe = regexp.MustCompile(`<([^<>\s]+)>`)
	bareAddrRe    = regexp.MustCompile(`[^\s<>,;"']+@[^\s<>,;"']+`)
	zoneCommentRe = regexp.MustCompile(`\([^)]*\)`)

	receivedFromRe = regexp.MustCompile(`(?i)\bfrom\s+([^\s(;]+)`)
	receivedByRe   = regexp.MustCompile(`(?i)\bby\s+([^\s(;]+)`)
	receivedWithRe = regexp.MustCompile(`(?i)\bwith\s+([^\s;()]+)`)
	dateGuessRe    = regexp.MustCompile(`\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s+[^\n]+`)

	trailingDotRe = regexp.MustCompile(`[.,]$`)
	resultWordRe  = regexp.MustCompile(`(?i)=\s*([a-z]+)\b`)
	policyRe      = regexp.MustCompile(`(?i)\bp=([a-z]+)`)

	// clauseToken patterns. The keys are embedded unescaped, exactly like the
	// TS lib's `new RegExp(`\\b${key}=([^\\s;)]+)`, 'i')` — a '.' inside a key
	// therefore matches any character there, in both twins.
	clauseTokenRes = map[string]*regexp.Regexp{
		"smtp.mailfrom": regexp.MustCompile(`(?i)\bsmtp.mailfrom=([^\s;)]+)`),
		"mailfrom":      regexp.MustCompile(`(?i)\bmailfrom=([^\s;)]+)`),
		"header.d":      regexp.MustCompile(`(?i)\bheader.d=([^\s;)]+)`),
		"header.i":      regexp.MustCompile(`(?i)\bheader.i=([^\s;)]+)`),
		"header.s":      regexp.MustCompile(`(?i)\bheader.s=([^\s;)]+)`),
		"header.from":   regexp.MustCompile(`(?i)\bheader.from=([^\s;)]+)`),
	}
)

// ParseHeaderLines splits raw header text into unfolded name/value pairs. It
// stops at the first empty line (the body separator). Continuation lines
// (RFC 5322 folding: leading space or tab) are appended to the previous value.
func ParseHeaderLines(raw string) []Header {
	lines := strings.Split(strings.ReplaceAll(raw, "\r\n", "\n"), "\n")
	headers := make([]Header, 0, len(lines))
	current := -1 // index into headers of the header a continuation line extends
	for _, line := range lines {
		if strings.TrimSpace(line) == "" {
			break // end of headers / blank separator
		}
		if isFold(line) && current >= 0 {
			headers[current].Value += " " + strings.TrimSpace(line)
			continue
		}
		colon := strings.Index(line, ":")
		if colon <= 0 {
			continue // not a header line — skip garbage
		}
		headers = append(headers, Header{
			Name:  strings.TrimSpace(line[:colon]),
			Value: strings.TrimSpace(line[colon+1:]),
		})
		current = len(headers) - 1
	}
	return headers
}

func isFold(line string) bool {
	return strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t")
}

// GetHeaders returns all values for a header name, case-insensitive, in file
// order.
func GetHeaders(headers []Header, name string) []string {
	lower := strings.ToLower(name)
	values := []string{}
	for _, h := range headers {
		if strings.ToLower(h.Name) == lower {
			values = append(values, h.Value)
		}
	}
	return values
}

// ExtractAddress extracts an email address from a header value: it prefers
// the <addr> form and falls back to the first bare address. It returns nil
// when no address is present.
func ExtractAddress(value string) *string {
	if m := bracketAddrRe.FindStringSubmatch(value); m != nil {
		return &m[1]
	}
	if m := bareAddrRe.FindStringSubmatch(value); m != nil {
		return &m[0]
	}
	return nil
}

// ParseRFC2822Date parses an RFC 2822 date, ignoring trailing "(ZONE)"
// comments, and returns nil when unparseable. The TS twin uses Date.parse;
// this port uses net/mail's RFC 5322 date parser on the comment-stripped
// value, which agrees on every shared vector.
func ParseRFC2822Date(value string) *time.Time {
	cleaned := strings.TrimSpace(zoneCommentRe.ReplaceAllString(value, " "))
	if cleaned == "" {
		return nil
	}
	ts, err := mail.ParseDate(cleaned)
	if err != nil {
		return nil
	}
	return &ts
}

// ParseReceived parses one Received header value into a Hop (Delay is filled
// in later by ParseHeaders). Empty From/By/Protocol mean the clause was
// absent; a nil Timestamp means no date could be parsed.
func ParseReceived(value string) Hop {
	var hop Hop
	if m := receivedFromRe.FindStringSubmatch(value); m != nil {
		hop.From = trailingDotRe.ReplaceAllString(m[1], "")
	}
	if m := receivedByRe.FindStringSubmatch(value); m != nil {
		hop.By = trailingDotRe.ReplaceAllString(m[1], "")
	}
	if m := receivedWithRe.FindStringSubmatch(value); m != nil {
		hop.Protocol = m[1]
	}
	// The timestamp follows the last ';' in the value.
	if lastSemi := strings.LastIndex(value, ";"); lastSemi != -1 {
		hop.Timestamp = ParseRFC2822Date(value[lastSemi+1:])
	}
	if hop.Timestamp == nil {
		// Some clients omit the ';'. Fall back to the first date-looking token.
		if guess := dateGuessRe.FindString(value); guess != "" {
			hop.Timestamp = ParseRFC2822Date(guess)
		}
	}
	return hop
}

func emptyAuthResult() AuthResult {
	return AuthResult{Result: "none"}
}

func resultWord(clause string) string {
	if m := resultWordRe.FindStringSubmatch(clause); m != nil {
		return strings.ToLower(m[1])
	}
	return "unknown"
}

func clauseToken(clause, key string) *string {
	re := clauseTokenRes[key]
	if re == nil {
		return nil
	}
	m := re.FindStringSubmatch(clause)
	if m == nil {
		return nil
	}
	v := trailingDotRe.ReplaceAllString(m[1], "")
	return &v
}

func orNil(a, b *string) *string {
	if a != nil {
		return a
	}
	return b
}

// ParseAuthResults parses Authentication-Results clauses. Example:
//
//	mx.google.com; spf=pass smtp.mailfrom=a@b.com; dkim=pass header.s=sel header.d=b.com;
//	dmarc=pass (p=REJECT) header.from=b.com
//
// The first result per mechanism wins.
func ParseAuthResults(values []string) AuthResults {
	auth := AuthResults{SPF: emptyAuthResult(), DKIM: emptyAuthResult(), DMARC: emptyAuthResult()}
	for _, value := range values {
		for _, rawClause := range strings.Split(value, ";") {
			clause := strings.TrimSpace(rawClause)
			lower := strings.ToLower(clause)
			var target *AuthResult
			var kind string
			switch {
			case strings.HasPrefix(lower, "spf="):
				target, kind = &auth.SPF, "spf"
			case strings.HasPrefix(lower, "dkim="):
				target, kind = &auth.DKIM, "dkim"
			case strings.HasPrefix(lower, "dmarc="):
				target, kind = &auth.DMARC, "dmarc"
			default:
				continue
			}
			if target.Result != "none" {
				continue // first result wins
			}
			target.Result = resultWord(clause)
			detail := clause
			target.Detail = &detail

			switch kind {
			case "spf":
				target.Domain = orNil(clauseToken(clause, "smtp.mailfrom"), clauseToken(clause, "mailfrom"))
			case "dkim":
				target.Domain = orNil(clauseToken(clause, "header.d"), clauseToken(clause, "header.i"))
				target.Selector = clauseToken(clause, "header.s")
			case "dmarc":
				target.Domain = clauseToken(clause, "header.from")
				if m := policyRe.FindStringSubmatch(clause); m != nil {
					p := strings.ToLower(m[1])
					target.Policy = &p
				}
			}
		}
	}
	return auth
}

func firstOr(values []string, fallback string) string {
	if len(values) > 0 {
		return values[0]
	}
	return fallback
}

func detectAnomalies(headers []Header, hops []Hop, auth AuthResults) []Anomaly {
	anomalies := []Anomaly{}

	// 1. From vs Return-Path mismatch — classic spoofing signal.
	fromAddr := ExtractAddress(firstOr(GetHeaders(headers, "From"), ""))
	returnPath := ExtractAddress(firstOr(GetHeaders(headers, "Return-Path"), ""))
	if fromAddr != nil && returnPath != nil && !strings.EqualFold(*fromAddr, *returnPath) {
		anomalies = append(anomalies, Anomaly{
			Type:     "from-return-path-mismatch",
			Severity: SeverityCritical,
			Message: fmt.Sprintf("Return-Path (%s) does not match From (%s) — the envelope sender differs from the displayed sender. Common in spoofing and mailing-list relay.",
				*returnPath, *fromAddr),
		})
	}

	// 2. Reply-To pointing somewhere other than From.
	replyTo := ExtractAddress(firstOr(GetHeaders(headers, "Reply-To"), ""))
	if fromAddr != nil && replyTo != nil && !strings.EqualFold(*replyTo, *fromAddr) {
		anomalies = append(anomalies, Anomaly{
			Type:     "reply-to-mismatch",
			Severity: SeverityWarning,
			Message: fmt.Sprintf("Reply-To (%s) differs from From (%s) — replies would go to a different address than the visible sender.",
				*replyTo, *fromAddr),
		})
	}

	// 3. Suspicious X-Mailer / User-Agent strings.
	mailer := firstOr(GetHeaders(headers, "X-Mailer"), firstOr(GetHeaders(headers, "User-Agent"), ""))
	if mailer != "" {
		lower := strings.ToLower(mailer)
		for _, s := range suspiciousMailers {
			if strings.Contains(lower, s) {
				anomalies = append(anomalies, Anomaly{
					Type:     "suspicious-mailer",
					Severity: SeverityWarning,
					Message: fmt.Sprintf("Mailer string %q contains a suspicious token (%q) often seen in bulk sending tools.", mailer, s),
				})
				break
			}
		}
	}

	// 4. Received chain gaps: unparseable/missing timestamps and time going backwards.
	for i, hop := range hops {
		if hop.Timestamp == nil {
			name := hop.From
			if name == "" {
				name = hop.By
			}
			if name == "" {
				name = "unknown"
			}
			anomalies = append(anomalies, Anomaly{
				Type:     "hop-missing-timestamp",
				Severity: SeverityInfo,
				Message: fmt.Sprintf("Hop %d (%s) has no parseable timestamp — delay for this leg cannot be computed.", i+1, name),
			})
			continue
		}
		if i > 0 && hops[i-1].Timestamp != nil {
			delta := hop.Timestamp.Sub(*hops[i-1].Timestamp).Seconds()
			if delta < 0 {
				anomalies = append(anomalies, Anomaly{
					Type:     "negative-delay",
					Severity: SeverityWarning,
					Message: fmt.Sprintf("Hop %d is timestamped %.1fs BEFORE hop %d — clock skew between servers or a forged Received header.",
						i+1, math.Abs(delta), i),
				})
			}
		}
	}

	// 5. No authentication results at all.
	if len(GetHeaders(headers, "Authentication-Results")) == 0 {
		anomalies = append(anomalies, Anomaly{
			Type:     "no-auth-results",
			Severity: SeverityInfo,
			Message: "No Authentication-Results header found — SPF/DKIM/DMARC status cannot be verified from this message.",
		})
	}

	return anomalies
}

// ParseHeaders parses raw email headers (RFC 5322) into structured data:
// unfolded headers, chronological Received hops with delays, SPF/DKIM/DMARC
// results, and spoofing anomalies. Hops[0] is the oldest hop (the Received
// chain is parsed bottom-up because RFC 5322 lists it newest-first).
func ParseHeaders(raw string) ParsedHeaders {
	headers := ParseHeaderLines(raw)

	received := GetHeaders(headers, "Received")
	hops := make([]Hop, 0, len(received))
	for _, v := range received {
		hops = append(hops, ParseReceived(v))
	}
	for i, j := 0, len(hops)-1; i < j; i, j = i+1, j-1 {
		hops[i], hops[j] = hops[j], hops[i]
	}
	for i := range hops {
		if i == 0 || hops[i].Timestamp == nil || hops[i-1].Timestamp == nil {
			continue
		}
		delay := hops[i].Timestamp.Sub(*hops[i-1].Timestamp).Seconds()
		hops[i].Delay = &delay
	}

	auth := ParseAuthResults(GetHeaders(headers, "Authentication-Results"))
	anomalies := detectAnomalies(headers, hops, auth)

	return ParsedHeaders{Headers: headers, Hops: hops, Auth: auth, Anomalies: anomalies}
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →