External Attack Surface Audit: How FOFA, Shodan, and Censys Help You Find Forgotten Services and Leaks

Organizations routinely lose track of parts of their infrastructure – old services, forgotten certificates, and accidentally published configs. In this piece, we’ll look at what the outside world can see (via FOFA, Shodan, and Censys) and how to turn those search results into a concrete remediation plan.
TL;DR
If something is publicly exposed, chances are these platforms have already indexed it. Shodan collects service banners from active Internet scans; Censys is terrific at mapping hosts/certificates; FOFA gives you flexible dorks and APIs for fast asset discovery. Use them together to rebuild your external inventory, fix what matters, and set up lightweight monitoring so the same issue doesn’t come back. Stay in scope: only search assets you own or where you have explicit permission.
Why this matters now
Attack surface sprawl is normal – multi-cloud, contractors, side projects, legacy systems. The uncomfortable truth: these engines already know what’s hanging off your perimeter. Shodan’s crawler captures what services “say” in their banners. Censys lets you pivot on certificates and rich host metadata. FOFA ties it together with a flexible search language and accessible API. If you don’t use them, someone else might.
What each platform brings
FOFA
A cyberspace search engine with dork-style filters (‘title=‘, ‘body=‘, ‘icon_hash=‘) and a straightforward REST API. It supports Search-After pagination for large pulls, so you’re not juggling page numbers. Great for quick mapping and “show me everything that looks like us” pivots.
Shodan
The classic “search engine for devices.” It scans the Internet, records service banners and open ports, and lets you filter with ‘port:‘, ‘org:‘, ‘http.title:’, ‘ssl.*‘, and more. It also offers a REST API and a real-time streaming API.
Censys
Think “certificate and host intelligence.” Censys indexes hosts and X.509 certificates with a query language that targets fields like ‘services.tls.*'або 'services.http.response.html_title‘. There’s an actively maintained Python SDK that makes automation dead simple.
Short comparative overview
| You care about… | FOFA | Shodan | Censys |
|---|---|---|---|
| Index focus | Broad asset mapping; titles/bodies; favicon pivots | Service banners & ports from active scans | Hosts + deep certificate/CT coverage |
| Query feel | Dorks (title=, body=, icon_hash=) | Field filters (http.title:, http.html:, port:) | CenQL fields (services.tls.*, services.http.*) |
| API - інтерфейси | REST + Search-After | REST + Streaming | Platform API + Python SDK |
| When it shines | Fast mapping, “looks like us” pivots | Service fingerprinting at scale | Cert/SAN pivots; host/cert correlations |
High-signal dorks professionals actually use
Scope matters. Replace ‘example.com'і '<hash>‘ with your own data, keep logs, and get written permission when needed.
FOFA
1. Swagger / OpenAPI with auth hintstitle="Swagger UI" && (body="Bearer" || body="jwt")
Why: public API docs often expose endpoints and auth patterns you didn’t mean to share.
2. Open indexes leaking secretstitle="Index of /" && (body=".env" || body="id_rsa" || body="config.php")
Why: directory listings that spill credentials, backups, or config crumbs.
3. Elasticsearch nodes (tell-tale cluster metadata)port=9200 && body="cluster_name" && body="number_of_nodes"
Why: unauth’d ES often advertises itself plainly.
4. Favicon hash pivoticon_hash="<hash>"
Why: find sibling apps sharing your favicon—the easiest shadow-IT map you’ll ever build.
Shodan
1.Favicon hashhttp.favicon.hash:<hash>
Why: a staple for mapping related web assets quickly.
2. Exposed Docker Remote APIproduct:"Docker" port:2375
Why: still a recurring critical exposure in the wild.
3. Certificate subject pivotssl.cert.subject.cn:"example.com"
Why: catch services presenting your certs on unknown IPs.
4. Index listings with sensitive files http.title:"Index of /" http.html:".env" http.html:"config.php"
Why: the “obvious but real” leaks, with far less noise.
Censys
1. Certificate SAN/CN pivotservices.tls.certificates.leaf_data.names: "example.com"
Why: enumerate hosts tied to your domains via CT.
2. HTTP body fingerprint (copyright marker)services.http.response.body:"© copyright <company>"
Why: Surfaces hosts whose HTTP responses include your brand’s copyright string — handy for finding branded pages, embedded widgets, or skins tied to <company> across unknown hosts.
3. Elasticsearch, high-signal comboservices.port: 9200 AND services.service_name: "ELASTICSEARCH" AND services.http.response.body: "cluster_name"
Why: port + service ID + body fingerprint keeps false positives down.
4. Kibana / Grafana by HTML titleservices.port: 5601 AND services.http.response.html_title: "Kibana"services.port: 3000 AND services.http.response.html_title: "Grafana"
Why: default titles are reliable identifiers for forgotten dashboards.
What should feel “critical” in triage
- Credentials or keys in responses or repos; unauthenticated admin panels; exposed backups.
- Open data stores reachable from the Internet (Elasticsearch, MongoDB, Redis, AMQP).
- Outdated service banners tied to known CVEs.
- Weak, expired, or mismatched certificates visible in CT indexes.When in doubt, assume a motivated attacker will chain small leaks into a big one.
A simple playbook that works
Inventory → Verify → Fix → Monitor.
Start by capturing evidence (asset, port, fingerprint, first-seen). Verify ownership and impact without touching data. Fix with ACLs/auth/patches/rotations. Then monitor the exact query that found the issue so regressions ping you, not an attacker.
Automate the boring parts (API → filter → alert)
Below is a compact Python workflow that:
- queries FOFA for “Swagger UI” with JWT hints,
- queries Shodan for “Index of /” plus ‘.env’ ‘config.php’,
- queries Censys for hosts whose certs include your domain,
- filters results, and
- posts a short summary to Slack.
Setup:pip install requests shodan censys
Export credentials as environment variables:
‘FOFA_EMAIL‘, ‘FOFA_KEY‘, ‘SHODAN_API_KEY‘, ‘CENSYS_API_ID‘, ‘CENSYS_API_SECRET‘, ‘SLACK_WEBHOOK_URL‘.
import os, base64, requests
from typing import List, Tuple
import shodan
from censys.search import CensysHosts
# --- Config ---
ORG = "example.com" # your primary domain for Censys pivots
SLACK_WEBHOOK = os.getenv("SLACK_WEBHOOK_URL")
# --- Helpers ---
def post_slack(title: str, lines: List[str]) -> None:
if not SLACK_WEBHOOK or not lines:
return
text = f"*{title}*\n" + "\n".join(lines[:30])
requests.post(SLACK_WEBHOOK, json={"text": text}, timeout=15)
# --- FOFA: Swagger UI with auth hints ---
def fofa_swagger() -> List[Tuple[str, str, str]]:
email = os.getenv("FOFA_EMAIL"); key = os.getenv("FOFA_KEY")
if not (email and key): return []
query = 'title="Swagger UI" && (body="Bearer" || body="jwt")'
qbase64 = base64.b64encode(query.encode()).decode()
url = f"https://fofa.info/api/v1/search/all"
params = {
"email": email,
"key": key,
"qbase64": qbase64,
"fields": "host,port,title"
}
r = requests.get(url, params=params, timeout=30)
r.raise_for_status()
rows = r.json().get("results", [])
# Return tuples (host, port, title)
return [(str(h), str(p), str(t)) for h, p, t in rows]
# --- Shodan: Index listings leaking .env or id_rsa (fixed query) ---
def shodan_index_leaks() -> List[Tuple[str, int, str]]:
api_key = os.getenv("SHODAN_API_KEY")
if not api_key: return []
api = shodan.Shodan(api_key)
query = 'http.title:"Index of /" http.html:".env" http.html:"config.php"'
data = api.search(query, page=1) # mind your credits
out = []
for m in data.get("matches", []):
ip = m.get("ip_str"); port = m.get("port"); title = (m.get("http", {}) or {}).get("title")
if ip and port:
out.append((ip, int(port), title or ""))
return out
# --- Censys: hosts whose leaf cert references your domain ---
def censys_cert_hosts(domain: str) -> List[str]:
c = CensysHosts() # reads CENSYS_API_ID / CENSYS_API_SECRET from env
query = f'services.tls.certificates.leaf_data.names: "{domain}"'
results = []
for hit in c.search(query, per_page=50):
ip = hit.get("ip")
if ip:
results.append(ip)
if len(results) >= 200: # keep it light
break
return results
# --- Main run ---
if __name__ == "__main__":
try:
fofa_rows = fofa_swagger()
shodan_rows = shodan_index_leaks()
censys_ips = censys_cert_hosts(ORG)
# crude filters to surface likely “interesting” items
fofa_interesting = [f"- {h}:{p} — {t}" for h, p, t in fofa_rows if p in {"8080","9200","5601","3000"}]
shodan_interesting = [f"- {ip}:{port} — {title}" for ip, port, title in shodan_rows]
censys_lines = [f"- {ip} (cert SAN contains {ORG})" for ip in censys_ips]
if fofa_interesting:
post_slack("FOFA watch: Swagger UI with auth hints", fofa_interesting)
if shodan_interesting:
post_slack("Shodan watch: Index listings with secrets", shodan_interesting)
if censys_lines:
post_slack("Censys watch: Hosts presenting your domain in cert SAN", censys_lines)
except Exception as e:
post_slack("Automation error", [str(e)])
Running it on a sch.dule (cron):
# Every day at 09:05
5 9 * * * /usr/bin/python3 /opt/eas-watch/eas_watch.py >> /var/log/eas_watch.log 2>&1
Closing the loop
Now you’ve got three levers: discovery, triage, and automation. Start with a few focused dorks, confirm ownership and impact, fix the exposure, and let the script nudge you when something similar reappears. Over time, that daily nudge is what keeps “forgotten” from turning into “compromised.”
Інші Послуги
Insomnia Security Scanner
AI-powered web application security scanner by CQR. Automated vulnerability discovery, exploit verification, and detailed reporting for modern applications.
Дізнатися більшеЗахист інфраструктури CRYEYE
Аудит безпеки за допомогою CryEye забезпечує інформаційну безпеку підприємства, захищаючи всю інфраструктуру.
Дізнатися більшеТестування на проникнення
Знайдіть вразливості у всій інфраструктурі вашого бізнесу раніше, ніж це зроблять хакери! У межах консалтингу з тестування на проникнення ми підберемо методи пентестів та інші індивідуальні рекомендації з кібербезпеки для вашого бізнесу.
Дізнатися більшеСоціальна Інженерія
Simulate real-world phishing, vishing, and pretexting attacks to measure and improve your team's security awareness and response capabilities.
Дізнатися більшеТестування Продуктивності
Усі види тестування навантаження і продуктивності вашої системи від компанії CQR, що спеціалізується на онлайн-безпеці.
Дізнатися більшеAI-Powered Vulnerability Assessment
Leverage artificial intelligence to discover, prioritize, and remediate vulnerabilities across your digital assets faster and more accurately than traditional scanners.
Дізнатися більшеCloud Security Audit (AWS / GCP / Azure)
Comprehensive security review of your cloud environments — IAM policies, network controls, data exposure, and misconfigurations across all major cloud platforms.
Дізнатися більшеDevSecOps Integration
Embed security into every stage of your CI/CD pipeline. Automated SAST, DAST, SCA, and secret scanning so vulnerabilities are caught before they reach production.
Дізнатися більшеAPI Security Testing
In-depth testing of REST, GraphQL, and SOAP APIs for authentication flaws, authorization bypasses, injection vulnerabilities, and data leakage risks.
Дізнатися більшеMobile Application Penetration Testing
Manual and automated security testing for iOS and Android applications — reverse engineering, runtime analysis, traffic interception, and backend API assessment.
Дізнатися більшеIoT Security Assessment
Evaluate firmware, communication protocols, cloud backends, and physical interfaces of IoT devices to identify vulnerabilities before attackers do.
Дізнатися більшеBlockchain & Smart Contract Audit
Formal verification and manual code review of smart contracts on Ethereum, Solana, and other chains. Detect reentrancy, overflow, and logic flaws before deployment.
Дізнатися більшеRed Team Operations
Advanced adversary simulation using real attacker TTPs (MITRE ATT&CK) to test your detection, response, and overall security posture under realistic conditions.
Дізнатися більшеThreat Intelligence & Monitoring
Continuous monitoring of threat feeds, dark web, and attacker infrastructure to provide actionable intelligence specific to your organization and industry.
Дізнатися більшеZero Trust Architecture Review
Assess and design your Zero Trust security model — identity verification, micro-segmentation, least-privilege access, and continuous validation controls.
Дізнатися більшеCompliance Consulting (PCI DSS / SOC 2 / GDPR)
Expert guidance to achieve and maintain compliance with major security frameworks. Gap analysis, remediation roadmaps, and audit-readiness support.
Дізнатися більшеDark Web Monitoring
Continuous surveillance of dark web forums, marketplaces, and breach databases for leaked credentials, sensitive data, or mentions of your organization.
Дізнатися більшеPhishing Simulation & Awareness Training
Controlled phishing campaigns combined with interactive security awareness training to build a human firewall across your entire organization.
Дізнатися більшеSupply Chain Security Audit
Assess third-party vendor risks, open-source dependencies, and software supply chain integrity to prevent attacks like SolarWinds and Log4Shell.
Дізнатися більшеContainer & Kubernetes Security
Security review of Docker images, Kubernetes clusters, RBAC policies, network policies, and runtime configurations to harden your container infrastructure.
Дізнатися більшеWeb Application Firewall (WAF) Deployment
Professional WAF setup, rule tuning, and ongoing management to block SQL injection, XSS, CSRF, and other OWASP Top 10 threats in real time.
Дізнатися більшеBug Bounty Program Management
Full lifecycle management of your bug bounty program — scope definition, researcher coordination, triage, validation, and remediation tracking.
Дізнатися більшеOSINT Investigation Services
Open-source intelligence gathering on individuals, organizations, and infrastructure. Ideal for pre-engagement recon, fraud investigation, and competitive analysis.
Дізнатися більшеDigital Forensics & Incident Response
Rapid response to security breaches — evidence collection, malware analysis, attacker timeline reconstruction, and actionable remediation recommendations.
Дізнатися більше