threat intelligence

Performing Brand Monitoring for Impersonation

Monitor for brand impersonation attacks across domains, social media, mobile apps, and dark web channels to detect phishing campaigns, fake sites, and unauthorized brand usage targeting your organization.

brand-monitoringbrand-protectiondomain-monitoringimpersonationphishingsocial-mediathreat-intelligence
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Brand impersonation attacks exploit consumer trust through lookalike domains, fake social media profiles, counterfeit mobile apps, and phishing sites that mimic legitimate brands. In 2025, brand impersonation remained one of the most costly cyber threats, with AI-generated phishing emails achieving a 54% click-through rate. This skill covers building a comprehensive brand monitoring program that detects domain squatting, social media impersonation, fake mobile apps, unauthorized logo usage, and dark web brand mentions using automated scanning and alerting.

When to Use

  • When conducting security assessments that involve performing brand monitoring for impersonation
  • When following incident response procedures for related security events
  • When performing scheduled security testing or auditing activities
  • When validating security controls through hands-on testing

Prerequisites

  • Python 3.9+ with dnstwist, requests, beautifulsoup4, Levenshtein, tweepy libraries
  • API keys: VirusTotal, Google Safe Browsing, Twitter/X API, Shodan
  • List of brand assets: domains, trademarks, logos, executive names
  • Certificate Transparency monitoring (Certstream or crt.sh)
  • Understanding of domain registration and TLD landscape

Key Concepts

Attack Surface

Brand impersonation spans multiple channels: domain squatting (typosquatting, homoglyphs, TLD variations), phishing sites (cloned websites with stolen branding), social media (fake profiles impersonating executives or company), mobile apps (counterfeit apps in app stores), email spoofing (display name and domain impersonation), and dark web (brand mentions in forums, marketplaces).

Detection Approaches

Effective brand monitoring combines proactive scanning (domain permutation with dnstwist, CT log monitoring), web crawling (screenshot comparison, logo detection), social media monitoring (profile name matching, post content analysis), app store monitoring (name and icon similarity detection), and dark web monitoring (forum scraping, marketplace tracking).

Risk Prioritization

Not all impersonation is malicious. Risk factors include: active web content (especially login pages), SSL certificate present, MX records configured (email receiving capability), visual similarity to legitimate site, recent registration date, and hosting in regions associated with cybercrime.

Workflow

Step 1: Multi-Channel Brand Monitoring System

import subprocess
import requests
import json
from datetime import datetime
from urllib.parse import urlparse
import Levenshtein
 
class BrandMonitor:
    def __init__(self, brand_config):
        self.brand_name = brand_config["name"]
        self.domains = brand_config["domains"]
        self.keywords = brand_config["keywords"]
        self.executive_names = brand_config.get("executives", [])
        self.logo_hash = brand_config.get("logo_hash", "")
        self.findings = []
 
    def scan_domain_squatting(self):
        """Detect typosquatting and lookalike domains."""
        all_results = []
        for domain in self.domains:
            cmd = ["dnstwist", "--registered", "--format", "json",
                   "--nameservers", "8.8.8.8", "--threads", "30", domain]
            try:
                result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
                if result.returncode == 0:
                    domains = json.loads(result.stdout)
                    registered = [d for d in domains if d.get("dns_a") or d.get("dns_aaaa")]
                    all_results.extend(registered)
                    print(f"[+] Domain squatting scan for {domain}: "
                          f"{len(registered)} registered lookalikes")
            except (subprocess.TimeoutExpired, Exception) as e:
                print(f"[-] Error scanning {domain}: {e}")
 
        for entry in all_results:
            self.findings.append({
                "type": "domain_squatting",
                "indicator": entry.get("domain", ""),
                "fuzzer": entry.get("fuzzer", ""),
                "dns_a": entry.get("dns_a", []),
                "ssdeep_score": entry.get("ssdeep_score", 0),
                "detected_at": datetime.now().isoformat(),
            })
        return all_results
 
    def check_google_safe_browsing(self, urls, api_key):
        """Check URLs against Google Safe Browsing API."""
        url = f"https://safebrowsing.googleapis.com/v4/threatMatches:find?key={api_key}"
        body = {
            "client": {"clientId": "brand-monitor", "clientVersion": "1.0"},
            "threatInfo": {
                "threatTypes": ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE"],
                "platformTypes": ["ANY_PLATFORM"],
                "threatEntryTypes": ["URL"],
                "threatEntries": [{"url": u} for u in urls],
            },
        }
        resp = requests.post(url, json=body, timeout=15)
        if resp.status_code == 200:
            matches = resp.json().get("matches", [])
            print(f"[+] Google Safe Browsing: {len(matches)} threats found")
            return matches
        return []
 
    def monitor_social_media_impersonation(self, platform="twitter"):
        """Detect social media profiles impersonating brand or executives."""
        suspicious_profiles = []
        # Search for profiles with similar names
        for name in self.executive_names + [self.brand_name]:
            # Using a general search approach
            search_url = f"https://api.twitter.com/2/users/by/username/{name.replace(' ', '')}"
            # Note: In production, use authenticated Twitter API
            suspicious_profiles.append({
                "search_term": name,
                "platform": platform,
                "note": "Requires authenticated API access for full search",
            })
        return suspicious_profiles
 
    def monitor_app_stores(self):
        """Check for fake mobile apps impersonating the brand."""
        fake_apps = []
        for keyword in self.keywords:
            # Google Play Store search (unofficial)
            url = f"https://play.google.com/store/search?q={keyword}&c=apps"
            try:
                resp = requests.get(url, timeout=15, headers={
                    "User-Agent": "Mozilla/5.0"
                })
                if resp.status_code == 200:
                    # Parse results for brand name matches
                    from bs4 import BeautifulSoup
                    soup = BeautifulSoup(resp.text, "html.parser")
                    app_links = soup.find_all("a", href=lambda h: h and "/store/apps/details" in h)
                    for link in app_links:
                        app_name = link.get_text(strip=True)
                        if any(k.lower() in app_name.lower() for k in self.keywords):
                            fake_apps.append({
                                "name": app_name,
                                "url": f"https://play.google.com{link['href']}",
                                "platform": "google_play",
                                "keyword": keyword,
                            })
            except Exception as e:
                print(f"[-] App store search error: {e}")
        return fake_apps
 
    def generate_monitoring_report(self):
        report = {
            "brand": self.brand_name,
            "generated": datetime.now().isoformat(),
            "total_findings": len(self.findings),
            "findings_by_type": {},
            "high_priority": [],
        }
        for finding in self.findings:
            ftype = finding["type"]
            if ftype not in report["findings_by_type"]:
                report["findings_by_type"][ftype] = 0
            report["findings_by_type"][ftype] += 1
 
            # High priority: has web similarity or MX records
            if finding.get("ssdeep_score", 0) > 50:
                report["high_priority"].append(finding)
 
        with open(f"brand_monitoring_{self.brand_name.lower()}.json", "w") as f:
            json.dump(report, f, indent=2)
        print(f"[+] Brand monitoring report: {len(self.findings)} findings")
        return report
 
monitor = BrandMonitor({
    "name": "MyCompany",
    "domains": ["mycompany.com", "mycompany.org"],
    "keywords": ["mycompany", "mybrand", "myproduct"],
    "executives": ["CEO Name", "CTO Name"],
})
monitor.scan_domain_squatting()
report = monitor.generate_monitoring_report()

Step 2: Takedown Request Generation

def generate_takedown_request(finding, brand_info):
    """Generate abuse report for domain/site takedown."""
    request = f"""Subject: Abuse Report - Brand Impersonation / Phishing
 
Dear Abuse Team,
 
We are writing to report a domain that is impersonating {brand_info['name']}
for apparent phishing/fraud purposes.
 
Infringing Domain: {finding.get('indicator', '')}
IP Address: {', '.join(finding.get('dns_a', ['Unknown']))}
Detection Method: {finding.get('fuzzer', 'domain similarity analysis')}
Web Similarity Score: {finding.get('ssdeep_score', 'N/A')}%
Detection Date: {finding.get('detected_at', '')}
 
Our legitimate domain(s): {', '.join(brand_info['domains'])}
 
This domain appears to be impersonating our brand through {finding.get('fuzzer', 'typosquatting')}.
We request immediate suspension of this domain.
 
Evidence of infringement is available upon request.
 
Regards,
{brand_info['name']} Security Team
"""
    return request

Validation Criteria

  • Domain squatting detected through dnstwist permutation scanning
  • Google Safe Browsing checks identify known threats
  • Certificate transparency monitoring detects new phishing certificates
  • Social media monitoring identifies impersonation profiles
  • App store monitoring detects counterfeit applications
  • Takedown requests generated with required evidence

References

Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 1

api-reference.md4.4 KB

API Reference: Brand Impersonation Monitoring

Libraries Used

Library Purpose
requests HTTP client for CT log, WHOIS, and DNS APIs
dns.resolver DNS record lookups for impersonation detection
json Parse API responses and certificate data
re Pattern matching for brand name variations
datetime Track certificate issuance timelines

Installation

pip install requests dnspython

Certificate Transparency Log Monitoring

Search CT Logs via crt.sh

import requests
 
def search_ct_logs(domain):
    """Search Certificate Transparency logs for domain certificates."""
    resp = requests.get(
        "https://crt.sh/",
        params={"q": f"%.{domain}", "output": "json"},
        timeout=30,
    )
    resp.raise_for_status()
    certs = resp.json()
    return [
        {
            "id": c["id"],
            "common_name": c["common_name"],
            "issuer": c["issuer_name"],
            "not_before": c["not_before"],
            "not_after": c["not_after"],
        }
        for c in certs
    ]

Detect Suspicious Look-alike Domains

import re
 
def generate_typosquat_variants(domain):
    """Generate common typosquatting variants of a domain."""
    name, tld = domain.rsplit(".", 1)
    variants = set()
 
    # Character substitution (homoglyphs)
    homoglyphs = {"a": ["@", "4"], "e": ["3"], "i": ["1", "l"], "o": ["0"], "s": ["5", "$"]}
    for i, char in enumerate(name):
        for replacement in homoglyphs.get(char, []):
            variants.add(name[:i] + replacement + name[i+1:] + "." + tld)
 
    # Missing/extra characters
    for i in range(len(name)):
        variants.add(name[:i] + name[i+1:] + "." + tld)  # Omission
        variants.add(name[:i] + name[i] + name[i] + name[i+1:] + "." + tld)  # Repetition
 
    # Adjacent TLDs
    for alt_tld in ["com", "net", "org", "io", "co", "app", "dev"]:
        if alt_tld != tld:
            variants.add(name + "." + alt_tld)
 
    # Hyphen insertion
    for i in range(1, len(name)):
        variants.add(name[:i] + "-" + name[i:] + "." + tld)
 
    return variants

Check Domain Registration

def check_domain_whois(domain):
    """Check WHOIS data for a suspicious domain."""
    resp = requests.get(
        f"https://rdap.org/domain/{domain}",
        timeout=10,
    )
    if resp.status_code == 200:
        data = resp.json()
        return {
            "domain": domain,
            "registered": True,
            "registrar": data.get("entities", [{}])[0].get("vcardArray", [None, []])[1][0]
                if data.get("entities") else "Unknown",
            "events": data.get("events", []),
        }
    return {"domain": domain, "registered": False}

DNS Record Check

import dns.resolver
 
def check_dns_records(domain):
    """Check if a suspicious domain has active DNS records."""
    records = {}
    for rtype in ["A", "MX", "NS", "TXT"]:
        try:
            answers = dns.resolver.resolve(domain, rtype)
            records[rtype] = [str(r) for r in answers]
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            records[rtype] = []
    return {
        "domain": domain,
        "has_a_record": len(records.get("A", [])) > 0,
        "has_mx_record": len(records.get("MX", [])) > 0,
        "records": records,
    }

Monitor for Brand Mentions

def scan_for_impersonation(brand_domain, ct_results):
    """Identify certificates that may indicate impersonation."""
    suspicious = []
    for cert in ct_results:
        cn = cert["common_name"].lower()
        if brand_domain not in cn:
            continue
        # Flag if issued by free CA (common for phishing)
        if any(ca in cert["issuer"].lower() for ca in ["let's encrypt", "zerossl", "buypass"]):
            suspicious.append({
                **cert,
                "reason": "Brand name in cert from free CA",
                "risk": "high",
            })
    return suspicious

Output Format

{
  "brand": "example.com",
  "scan_date": "2025-01-15",
  "ct_certificates_found": 342,
  "suspicious_certificates": 5,
  "typosquat_domains_registered": 8,
  "findings": [
    {
      "domain": "examp1e.com",
      "type": "typosquat",
      "registered": true,
      "has_mx_record": true,
      "risk": "high",
      "detail": "Active mail server — possible phishing"
    }
  ]
}

Scripts 1

agent.py6.6 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Brand impersonation monitoring agent.

Monitors for brand impersonation by checking Certificate Transparency
logs for suspicious domain registrations, performing DNS lookups for
typosquatting domains, and scanning social media profile names. Uses
crt.sh API and DNS resolution to identify potential phishing domains.
"""
import argparse
import json
import os
import socket
import sys
from datetime import datetime, timezone

try:
    import requests
except ImportError:
    print("[!] 'requests' required: pip install requests", file=sys.stderr)
    sys.exit(1)


def generate_typosquat_variants(domain):
    """Generate common typosquatting domain variants."""
    name, tld = domain.rsplit(".", 1) if "." in domain else (domain, "com")
    variants = set()
    chars = "abcdefghijklmnopqrstuvwxyz0123456789"

    # Character omission
    for i in range(len(name)):
        variants.add(f"{name[:i]}{name[i+1:]}.{tld}")
    # Character swap
    for i in range(len(name) - 1):
        swapped = list(name)
        swapped[i], swapped[i+1] = swapped[i+1], swapped[i]
        variants.add(f"{''.join(swapped)}.{tld}")
    # Character replacement (adjacent keys)
    adjacent = {"a": "sq", "e": "wr", "i": "uo", "o": "ip", "u": "yi",
                "s": "ad", "n": "bm", "r": "et", "t": "ry", "l": "kp"}
    for i, c in enumerate(name):
        for adj in adjacent.get(c, ""):
            variants.add(f"{name[:i]}{adj}{name[i+1:]}.{tld}")
    # Character doubling
    for i in range(len(name)):
        variants.add(f"{name[:i]}{name[i]}{name[i:]}.{tld}")
    # Homoglyph substitution
    homoglyphs = {"o": "0", "l": "1", "i": "1", "e": "3", "a": "4", "s": "5"}
    for i, c in enumerate(name):
        if c in homoglyphs:
            variants.add(f"{name[:i]}{homoglyphs[c]}{name[i+1:]}.{tld}")
    # TLD variants
    for alt_tld in ["com", "net", "org", "io", "co", "info", "biz", "xyz"]:
        if alt_tld != tld:
            variants.add(f"{name}.{alt_tld}")
    # Prefix/suffix
    for prefix in ["my", "the", "get", "go", "login", "secure", "account"]:
        variants.add(f"{prefix}{name}.{tld}")
        variants.add(f"{name}{prefix}.{tld}")
    # Hyphen insertion
    for i in range(1, len(name)):
        variants.add(f"{name[:i]}-{name[i:]}.{tld}")

    variants.discard(domain)
    return sorted(variants)


def check_domain_resolution(domains, max_check=200):
    """Check which typosquat domains actually resolve."""
    resolved = []
    checked = 0
    for domain in domains[:max_check]:
        checked += 1
        try:
            ip = socket.gethostbyname(domain)
            resolved.append({
                "domain": domain,
                "ip": ip,
                "resolves": True,
                "severity": "HIGH",
            })
        except socket.gaierror:
            pass
    print(f"[+] Checked {checked} domains, {len(resolved)} resolve to an IP")
    return resolved


def search_certificate_transparency(domain):
    """Search crt.sh for certificates containing the brand name."""
    print(f"[*] Searching Certificate Transparency for: {domain}")
    findings = []
    try:
        resp = requests.get(
            f"https://crt.sh/?q=%25{domain}%25&output=json",
            timeout=30,
        )
        if resp.status_code == 200:
            certs = resp.json()
            seen_names = set()
            for cert in certs:
                common_name = cert.get("common_name", "")
                if common_name not in seen_names and domain not in common_name.split(".")[-2:]:
                    seen_names.add(common_name)
                    findings.append({
                        "type": "ct_log",
                        "common_name": common_name,
                        "issuer": cert.get("issuer_name", ""),
                        "not_before": cert.get("not_before", ""),
                        "not_after": cert.get("not_after", ""),
                        "severity": "MEDIUM",
                    })
            print(f"[+] Found {len(findings)} suspicious certificates")
    except requests.RequestException as e:
        print(f"[!] CT search error: {e}")
    return findings


def format_summary(domain, variants_count, resolved, ct_findings):
    """Print monitoring summary."""
    print(f"\n{'='*60}")
    print(f"  Brand Impersonation Monitoring Report")
    print(f"{'='*60}")
    print(f"  Brand Domain       : {domain}")
    print(f"  Typosquat Variants : {variants_count}")
    print(f"  Resolved Domains   : {len(resolved)}")
    print(f"  CT Log Matches     : {len(ct_findings)}")

    if resolved:
        print(f"\n  Active Typosquat Domains (resolving):")
        for r in resolved[:20]:
            print(f"    [{r['severity']:6s}] {r['domain']:40s} -> {r['ip']}")

    if ct_findings:
        print(f"\n  Certificate Transparency Findings:")
        for f in ct_findings[:15]:
            print(f"    {f['common_name']:40s} (issued: {f['not_before'][:10]})")


def main():
    parser = argparse.ArgumentParser(description="Brand impersonation monitoring agent")
    parser.add_argument("--domain", required=True, help="Brand domain to monitor (e.g., example.com)")
    parser.add_argument("--max-check", type=int, default=200, help="Max domains to DNS-check")
    parser.add_argument("--skip-ct", action="store_true", help="Skip Certificate Transparency search")
    parser.add_argument("--skip-dns", action="store_true", help="Skip DNS resolution check")
    parser.add_argument("--output", "-o", help="Output JSON report")
    parser.add_argument("--verbose", "-v", action="store_true")
    args = parser.parse_args()

    variants = generate_typosquat_variants(args.domain)
    print(f"[*] Generated {len(variants)} typosquat variants for {args.domain}")

    resolved = []
    if not args.skip_dns:
        resolved = check_domain_resolution(variants, args.max_check)

    ct_findings = []
    if not args.skip_ct:
        ct_findings = search_certificate_transparency(args.domain.split(".")[0])

    format_summary(args.domain, len(variants), resolved, ct_findings)

    report = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "tool": "Brand Monitor",
        "domain": args.domain,
        "variants_generated": len(variants),
        "resolved_domains": resolved,
        "ct_findings": ct_findings,
        "risk_level": (
            "CRITICAL" if len(resolved) > 10
            else "HIGH" if resolved
            else "MEDIUM" if ct_findings
            else "LOW"
        ),
    }

    if args.output:
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2)
        print(f"\n[+] Report saved to {args.output}")
    elif args.verbose:
        print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()
Keep exploring