Listen to this Post

Introduction
Look‑alike domains—also known as typosquatting or homograph domains—remain one of the most insidious entry points for credential harvesting, brand impersonation, and business email compromise (BEC) campaigns. Threat actors register domains that visually or phonetically mimic legitimate brands, exploiting common typing errors or Unicode homoglyphs to deceive users into visiting malicious sites. For Security Operations Center (SOC) and Threat Intelligence teams, proactively identifying these impersonating domains before they are weaponized is a critical defensive capability. This article explores how Python‑based automation can be leveraged to scan for, detect, and mitigate look‑alike phishing domains, drawing on open‑source intelligence (OSINT) feeds, DNS interrogation, and permutation algorithms to give defenders a decisive head start.
Learning Objectives
- Understand the mechanics of typosquatting, homograph attacks, and domain permutation generation for brand impersonation detection.
- Learn how to build a Python script that generates potential look‑alike domains and validates their registration status using DNS queries.
- Explore integration with threat intelligence APIs (URLhaus, PhishTank, VirusTotal) to enrich detected domains with reputation and maliciousness context.
- Implement automated alerting and reporting workflows to enable proactive domain takedown and incident response.
You Should Know
1. Understanding Look‑Alike Domain Generation Techniques
Look‑alike domains are crafted using several well‑documented techniques that attackers employ to deceive users. The most common methods include:
- Typosquatting (URL Hijacking): Registering domains that are common misspellings of a legitimate brand (e.g., `gooogle.com` instead of
google.com). Attackers bank on users making typographical errors when entering a URL. - Homograph Attacks: Using characters from different scripts (e.g., Cyrillic, Greek) that look identical to ASCII characters in certain fonts. For example, the Cyrillic ‘а’ (U+0430) can replace the Latin ‘a’ in `apple.com` to create
аррӏе.com—a domain visually indistinguishable from the real one. - Bitsquatting: Registering domains that differ by a single bit in the binary representation of the domain name, exploiting rare memory errors or network corruption.
- TLD Swaps: Registering the same brand name under different top‑level domains (e.g., `brand.security` instead of
brand.com) to trick users who assume all TLDs are legitimate. - Combosquatting: Adding keywords to a legitimate domain (e.g., `login-brand.com` or
brand-verify.net) to imply a trusted sub‑service.
To defend against these threats, SOC teams need a systematic way to generate all possible permutations of a brand’s domain name and then check which of those permutations are actually registered and potentially malicious.
- Building a Python Permutation Engine for Domain Generation
The core of any look‑alike detection tool is a permutation engine that takes a seed domain and produces a comprehensive list of variations. The open‑source tool `dnstwist` is a prime example of this approach. Written in Python, `dnstwist` implements a fuzzing algorithm that generates permutations based on:
- Common misspellings (keyboard adjacency errors)
- Omitted or repeated characters
- Homoglyph substitution (Unicode character replacement)
- Bitsquatting variations
- TLD swaps
Below is a simplified Python implementation that generates a basic set of typosquatting permutations for a given domain:
import itertools
import dns.resolver
def generate_typosquats(domain):
"""
Generate common typosquatting permutations for a given domain.
"""
parts = domain.split('.')
name = parts[bash]
tld = parts[bash] if len(parts) > 1 else 'com'
Common keyboard adjacency substitutions
keyboard_adj = {
'a': ['q', 'w', 's', 'z'],
's': ['a', 'w', 'e', 'd', 'x', 'z'],
'd': ['s', 'e', 'r', 'f', 'c', 'x'],
... (extend for all letters)
}
permutations = set()
Generate single-character substitutions
for i, char in enumerate(name):
if char in keyboard_adj:
for sub in keyboard_adj[bash]:
perm = name[:i] + sub + name[i+1:]
permutations.add(f"{perm}.{tld}")
Generate missing character permutations
for i in range(len(name) + 1):
for char in 'abcdefghijklmnopqrstuvwxyz':
perm = name[:i] + char + name[i:]
permutations.add(f"{perm}.{tld}")
Generate swapped adjacent characters
for i in range(len(name) - 1):
perm = list(name)
perm[bash], perm[i+1] = perm[i+1], perm[bash]
permutations.add(f"{''.join(perm)}.{tld}")
return list(permutations)
Step‑by‑step guide:
1. Define the seed domain (e.g., `brand.com`).
- Generate permutations using keyboard adjacency, missing characters, and adjacent swaps as shown above.
- For each permutation, perform a DNS lookup to check if the domain is registered (using
dns.resolver). - If the domain resolves (has an A, AAAA, or MX record), flag it for further investigation.
- Log or alert on active domains that closely resemble the brand.
For a production‑ready solution, leverage the full `dnstwist` package, which can be installed via `pip install dnstwist` or used directly from the command line:
dnstwist --registered brand.com
This command outputs a list of registered look‑alike domains along with their DNS records, making it an invaluable tool for threat hunting.
3. Enriching Detected Domains with Threat Intelligence APIs
Detecting a registered look‑alike domain is only half the battle. The next step is to determine whether that domain is actually malicious or benign. This is where threat intelligence feeds and APIs come into play. By integrating with services like URLhaus, PhishTank, and VirusTotal, SOC analysts can automatically enrich each detected domain with reputation data.
URLhaus (by abuse.ch) maintains a database of malicious URLs, including phishing sites, malware distributors, and command‑and‑control (C2) servers. Its API is free and does not require an API key, making it ideal for automation. A simple Python function to check a domain against URLhaus:
import requests
import json
def check_urlhaus(domain):
"""
Query the URLhaus API to check if a domain is known for malicious activity.
"""
url = "https://urlhaus-api.abuse.ch/v1/host/"
payload = {"host": domain}
response = requests.post(url, data=payload)
if response.status_code == 200:
data = response.json()
if data.get("query_status") == "ok":
return {
"malicious": True,
"threat": data.get("urlhaus_reference"),
"first_seen": data.get("firstseen")
}
return {"malicious": False}
PhishTank provides a community‑driven list of verified phishing URLs. While it requires an API key for real‑time lookups, the JSON feed can be downloaded and parsed periodically for offline enrichment. To integrate PhishTank:
import requests
def check_phishtank(domain, api_key):
"""
Check a domain against PhishTank's verified phishing database.
"""
url = "https://check.phishtank.com/checkurl/"
payload = {"url": f"http://{domain}", "format": "json", "app_key": api_key}
response = requests.post(url, data=payload)
if response.status_code == 200:
data = response.json()
if data.get("results", {}).get("in_database"):
return {"phishing": True, "verified": data["results"]["verified"]}
return {"phishing": False}
VirusTotal offers a more comprehensive threat intelligence engine, aggregating data from over 70 antivirus scanners and URL blocklists. Its API requires an API key but provides deep insights into domain reputation, detection ratios, and historical activity.
Step‑by‑step guide for enrichment:
- For each detected domain, query URLhaus and PhishTank (and optionally VirusTotal) using the functions above.
- Consolidate results into a single risk score (e.g.,
High,Medium,Low) based on the number and severity of positive hits. - Log enriched results to a centralized SIEM or dashboard for SOC analysts to review.
- Set up automated alerts for domains flagged as malicious by two or more sources, triggering an incident response workflow.
4. Automating Continuous Monitoring with Scheduled Scans
Look‑alike domains are registered and taken down constantly. A one‑time scan is insufficient for ongoing protection. SOC teams should implement scheduled scanning that runs every few hours or daily to catch newly registered impersonating domains. This can be achieved using `cron` on Linux or Task Scheduler on Windows.
Linux (cron) example:
Run domain scan every 6 hours 0 /6 /usr/bin/python3 /opt/lookalike_scanner.py --domain brand.com --output /var/log/lookalike_report.json
Windows Task Scheduler (PowerShell) example:
$action = New-ScheduledTaskAction -Execute "C:\Python39\python.exe" -Argument "C:\scripts\lookalike_scanner.py --domain brand.com --output C:\logs\report.json" $trigger = New-ScheduledTaskTrigger -Daily -At 6am Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "LookalikeDomainScan" -User "SYSTEM"
The Python script itself can be designed to:
- Read a list of target brands/domains from a configuration file.
- Generate permutations for each.
- Perform DNS lookups to identify registered domains.
- Enrich each active domain with threat intelligence.
- Generate a report (JSON, CSV, or HTML) and optionally send email alerts for high‑risk findings.
5. Mitigation and Takedown Workflow
Once a malicious look‑alike domain is confirmed, the SOC must initiate a takedown process. The typical workflow includes:
- Internal Validation: Confirm the domain is indeed malicious (e.g., by visiting it in a sandboxed environment or reviewing SSL certificates and content).
- Reporting to the Registrar: Submit an abuse report to the domain registrar, providing evidence of phishing or impersonation. Many registrars have dedicated abuse contact forms.
- Blocking at Network Level: Add the domain to the organization’s DNS blacklist, firewall rules, and email filtering systems to prevent any internal users from accessing it.
- Brand Protection Services: For large enterprises, consider using commercial brand protection services that specialize in automated takedown.
- Threat Intelligence Sharing: Submit the domain to URLhaus, PhishTank, and other open‑source feeds to protect the broader community.
6. Advanced Detection: Fuzzy Hashing and Webpage Similarity
Beyond DNS registration, sophisticated attackers may register a look‑alike domain but host a completely different webpage to evade simple detection. To counter this, `dnstwist` and similar tools can estimate webpage similarity using fuzzy hashes (e.g., ssdeep). By comparing the fuzzy hash of the suspected site’s content against the legitimate brand’s homepage, defenders can identify content‑based impersonation even if the domain name is not an exact permutation.
A simplified Python example using `ssdeep`:
import ssdeep import requests def compare_webpage_similarity(legit_url, suspect_url): """ Compare two webpages using fuzzy hashing to detect content similarity. """ legit_content = requests.get(legit_url).text suspect_content = requests.get(suspect_url).text legit_hash = ssdeep.hash(legit_content) suspect_hash = ssdeep.hash(suspect_content) similarity = ssdeep.compare(legit_hash, suspect_hash) return similarity Returns a score from 0 to 100
A similarity score above 70 typically indicates that the suspect site is a near‑exact copy of the legitimate one—a strong indicator of phishing.
What Undercode Say
- Key Takeaway 1: Proactive domain monitoring is a force multiplier for SOC teams. By automating the detection of look‑alike domains, organizations can shut down phishing infrastructure before it ever reaches end users, drastically reducing the attack surface.
- Key Takeaway 2: Open‑source intelligence (OSINT) feeds like URLhaus and PhishTank provide free, reliable data that can be seamlessly integrated into Python automation scripts, enabling cost‑effective threat enrichment without relying on expensive commercial services.
The collaboration between Yasir Khan and Tayyaba Shahzad on this Python‑based tool exemplifies the power of defensive cybersecurity automation. By combining domain permutation algorithms with DNS interrogation and threat intelligence APIs, they have created a practical, actionable solution that bridges the gap between detection and response. As the threat landscape evolves, such tools will become indispensable for organizations seeking to protect their brand reputation and customer trust. The shift from reactive incident response to proactive threat hunting is not just a best practice—it is a necessity in an era where phishing domains can be registered and weaponized in minutes.
Prediction
- +1 The adoption of AI‑assisted domain permutation engines will accelerate, with machine learning models predicting the most likely typosquatting variations based on user behavior data, further reducing false positives and improving detection accuracy.
- +1 Integration of look‑alike domain detection directly into Secure Email Gateways (SEGs) and web proxies will become standard, enabling real‑time blocking without manual SOC intervention.
- -1 Attackers will increasingly turn to internationalized domain names (IDNs) with complex homoglyphs that are difficult for traditional ASCII‑based permutation engines to detect, necessitating the development of Unicode‑aware detection algorithms.
- -1 The rise of domain‑generation algorithms (DGAs) used by malware families will make it harder to distinguish between benign look‑alike domains and algorithmically generated malicious ones, requiring more sophisticated behavioral analysis.
- +1 The cybersecurity community will continue to benefit from open‑source contributions like the tool developed by Shahzad and Khan, fostering a culture of collaboration that strengthens collective defense against phishing threats.
▶️ Related Video (90% Match):
🎯Let’s Practice For Free:
🎓 Live Courses & Certifications:
Join Undercode Academy for Verified Certifications
🚀 Request a Custom Project:
Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[email protected]
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands
IT/Security Reporter URL:
Reported By: Tayyaba Shahzad – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


