#!/usr/bin/env bash
set -euo pipefail

# Email Header Phishing Analysis Helper
#
# Purpose:
#   Extract and summarize full email headers from a raw .eml file to support
#   phishing analysis using routing and authentication signals.
#
# What it does:
#   - Extracts the header block from a raw email source
#   - Counts and displays Received lines
#   - Prints key fields: From, Return-Path, Reply-To, Message-ID,
#     Authentication-Results, DKIM-Signature, MIME-Version, Content-Type
#   - Provides simple heuristics to help spot suspicious patterns
#
# Safe by design:
#   - Read-only operations only
#   - No network calls
#   - No file modifications
#   - No destructive actions
#
# Usage:
#   ./email-header-check.sh suspicious-message.eml
#   cat suspicious-message.eml | ./email-header-check.sh -
#
# Optional:
#   -h, --help   Show usage

usage() {
  cat <<'EOF'
Usage:
  email-header-check.sh <raw-email.eml | ->

Examples:
  email-header-check.sh suspicious-message.eml
  cat suspicious-message.eml | email-header-check.sh -

Notes:
  - Input must be the raw message source, not a forwarded copy or screenshot.
  - The script reads the header block only and does not alter the message.
EOF
}

if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then
  usage
  exit 0
fi

if [[ $# -ne 1 ]]; then
  usage >&2
  exit 1
fi

input_path="$1"

if [[ "$input_path" != "-" && ! -f "$input_path" ]]; then
  echo "Error: file not found: $input_path" >&2
  exit 1
fi

if [[ "$input_path" != "-" && ! -r "$input_path" ]]; then
  echo "Error: file is not readable: $input_path" >&2
  exit 1
fi

extract_headers() {
  # Print everything up to the first blank line.
  sed -n '1,/^$/p'
}

print_field() {
  local label="$1"
  local pattern="$2"
  local value
  value="$(grep -iE "^${pattern}:" <<<"$headers" || true)"
  if [[ -n "$value" ]]; then
    echo "$label"
    echo "$value"
  else
    echo "$label"
    echo "(not found)"
  fi
  echo
}

if [[ "$input_path" == "-" ]]; then
  headers="$(extract_headers)"
else
  headers="$(extract_headers < "$input_path")"
fi

if [[ -z "$headers" ]]; then
  echo "Error: no headers found. Make sure the input is a raw email source." >&2
  exit 1
fi

echo "== Header Summary =="
echo

received_count="$(grep -ci '^Received:' <<<"$headers" || true)"
echo "Received lines: $received_count"
echo

print_field "From:" "From"
print_field "Return-Path:" "Return-Path"
print_field "Reply-To:" "Reply-To"
print_field "Message-ID:" "Message-ID"
print_field "Authentication-Results:" "Authentication-Results"
print_field "DKIM-Signature:" "DKIM-Signature"
print_field "MIME-Version:" "MIME-Version"
print_field "Content-Type:" "Content-Type"

echo "== Received Chain (top to bottom as present in the header) =="
echo
if grep -qi '^Received:' <<<"$headers"; then
  grep -i '^Received:' <<<"$headers"
else
  echo "(none found)"
fi

echo
echo "== Quick Triage Notes =="

# Simple, non-definitive checks that help an analyst investigate further.
from_addr="$(grep -i '^From:' <<<"$headers" | head -n1 || true)"
reply_to_addr="$(grep -i '^Reply-To:' <<<"$headers" | head -n1 || true)"
return_path_addr="$(grep -i '^Return-Path:' <<<"$headers" | head -n1 || true)"
auth_results="$(grep -i '^Authentication-Results:' <<<"$headers" | head -n1 || true)"

echo "- Confirm the message was analyzed from a raw source, not a forwarded copy."
if [[ "$received_count" -eq 0 ]]; then
  echo "- No Received lines found; the sample may be incomplete or sanitized."
else
  echo "- Review the Received chain from bottom to top to identify the earliest trusted hop."
fi

if [[ -n "$reply_to_addr" && -n "$from_addr" && "$reply_to_addr" != "$from_addr" ]]; then
  echo "- Reply-To differs from From; validate whether this is expected before trusting the message."
else
  echo "- Reply-To and From appear aligned or Reply-To is absent; continue checking routing and authentication."
fi

if [[ -n "$return_path_addr" && -n "$from_addr" && "$return_path_addr" != "$from_addr" ]]; then
  echo "- Return-Path differs from From; this can be normal, but compare domains and mail-flow patterns."
else
  echo "- Return-Path and From appear aligned or Return-Path is absent; compare against known mail flow."
fi

if [[ -n "$auth_results" ]]; then
  echo "- Authentication-Results present; inspect SPF, DKIM, and DMARC verdicts for pass/fail details."
else
  echo "- No Authentication-Results header found; the receiving system may not have added one."
fi

echo
cat <<'EOF'
Next steps:
  1) Compare sender domains against approved organizational or vendor mail domains.
  2) Verify the earliest untrusted Received hop and check IP/host consistency.
  3) Confirm SPF, DKIM, and DMARC results in Authentication-Results.
  4) Cross-check Message-ID and MIME structure for anomalies.
  5) Escalate to mail security or incident response if the message remains suspicious.
EOF