Inventory what the internet can see of your own netblocks, domains and buckets: Shodan data filtered to your ranges, an allowlisted httpx checker for Django exposure signals, site-restricted search queries, S3-compatible bucket audits with moto, remediation and a recurring Django check.
Attackers rarely need a zero-day. A forgotten staging server with DEBUG = True, an admin login open to the world, a downloadable .git directory or a public bucket is enough. This tutorial shows how to see your own infrastructure the way the internet sees it, using scan data you query rather than scans you run, a checker that refuses to touch anything outside an allowlist, and a Django command that repeats the checks and alerts when something new appears.
Everything here applies only to IP ranges, domains and cloud accounts that your organisation owns or is explicitly authorised in writing to assess. The code enforces this in two places: queries are built only from your own netblocks, and the HTTP checker raises before sending a request to a host that is not on your allowlist. This tutorial does not cover finding, accessing or downloading anyone else's systems, buckets or data, and it does not cover exploitation. If a search result or scan record ever points to data that is not yours, do not open it; report it to the owner's security contact or a national CERT.
When you find something of your own exposed, the order is fixed: close it, then investigate. Investigation is about your systems (what was reachable, since when, was it accessed), not about tracing people.
/admin/, monitoring UIs and queue dashboards reachable from any address..git/, .env or backups, and web servers with directory listing enabled.Tested on Python 3.13 (3.12+ required) with Django 5.2.20, httpx 0.29.0, shodan 1.31.0, boto3 1.44.19 and moto 5.2.6, the latest stable releases at the time of writing. No real Shodan, Censys or cloud API is called: all external calls are mocked.
# requirements.txt
Django>=5.2,<6.0
httpx>=0.29.0,<1.0
shodan>=1.31.0,<2.0
boto3>=1.44.19,<2.0
moto[s3]>=5.2.6,<6.0 # tests only
Scope lives in settings, so every component reads the same definition. The values use documentation ranges and reserved domains; replace them with yours.
EXPOSURE_NETBLOCKS = ["203.0.113.0/24"]
EXPOSURE_EXPECTED = [("203.0.113.10", 80), ("203.0.113.10", 443)]
EXPOSURE_ALLOWED_HOSTS = ["www.example.com", "staging.example.com"]
EXPOSURE_BUCKETS = ["myproject-uploads"]
EXPOSURE_S3_ENDPOINT = None # e.g. "https://s3.example.net" for an S3-compatible provider
ADMIN_URL_PREFIX = "/admin/"
ADMIN_ALLOWED_NETWORKS = ["10.8.0.0/24", "192.0.2.0/28"]
import ipaddress
from django.conf import settings
class OutOfScope(Exception):
"""Raised before any request leaves the machine for a target we do not own."""
def own_networks():
return [ipaddress.ip_network(n) for n in settings.EXPOSURE_NETBLOCKS]
def require_own_network(cidr):
net = ipaddress.ip_network(cidr)
if not any(net.subnet_of(own) for own in own_networks()):
raise OutOfScope(cidr)
return net
def require_own_host(host):
if host not in settings.EXPOSURE_ALLOWED_HOSTS:
raise OutOfScope(host)
return host
Services such as Shodan and Censys continuously scan the IPv4 space and index banners, certificates and HTTP responses. Querying their index for your own netblocks shows what any attacker can already see, without you sending a single packet. Filters such as net: and hostname:, and the number of query credits, depend on your plan; check the provider's documentation before relying on them. Censys offers equivalent search filters on IP ranges and certificate names through its own API and SDK; the inventory logic below stays the same.
The API key comes from an environment variable, never from settings files in version control. The function filters twice: the query is built from a netblock that passed require_own_network, and each returned address is checked again before it is stored, so a data error at the provider never puts someone else's host into your inventory.
import ipaddress
import os
import shodan
from django.conf import settings
from .models import ExposedService
from .scope import own_networks, require_own_network
def shodan_client():
return shodan.Shodan(os.environ["SHODAN_API_KEY"])
def sync_from_shodan(api=None):
api = api or shodan_client()
own = own_networks()
expected = {tuple(x) for x in settings.EXPOSURE_EXPECTED}
unexpected = []
for cidr in settings.EXPOSURE_NETBLOCKS:
net = require_own_network(cidr)
for match in api.search_cursor(f"net:{net}"):
ip = ipaddress.ip_address(match["ip_str"])
if not any(ip in n for n in own):
continue # never store data about hosts outside our ranges
svc, created = ExposedService.objects.update_or_create(
ip=str(ip), port=match["port"], transport=match.get("transport", "tcp"),
defaults=dict(
product=match.get("product", ""),
hostnames=match.get("hostnames", []),
source="shodan",
expected=(str(ip), match["port"]) in expected,
),
)
if not svc.expected:
unexpected.append(svc)
return unexpected
The model stores one row per (ip, port, transport), so repeated syncs update instead of duplicating, and expected separates your baseline (80 and 443 on the web host) from surprises:
from django.db import models
class ExposedService(models.Model):
ip = models.GenericIPAddressField()
port = models.PositiveIntegerField()
transport = models.CharField(max_length=8, default="tcp")
product = models.CharField(max_length=200, blank=True)
hostnames = models.JSONField(default=list)
source = models.CharField(max_length=40)
expected = models.BooleanField(default=False)
first_seen = models.DateTimeField(auto_now_add=True)
last_seen = models.DateTimeField(auto_now=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=["ip", "port", "transport"], name="uniq_service")
]
class Finding(models.Model):
target = models.CharField(max_length=255)
kind = models.CharField(max_length=60)
severity = models.CharField(max_length=10)
detail = models.TextField()
first_seen = models.DateTimeField(auto_now_add=True)
last_seen = models.DateTimeField(auto_now=True)
resolved_at = models.DateTimeField(null=True, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=["target", "kind"], name="uniq_finding")
]
In the test, the mocked API returns an expected HTTPS service, an unexpected PostgreSQL port and a record for an address outside the netblock. Only the PostgreSQL port is reported, and the foreign record is dropped:
class ShodanTests(TestCase):
def test_inventory_marks_unexpected_and_drops_foreign_ips(self):
api = mock.Mock()
api.search_cursor.return_value = iter([
{"ip_str": "203.0.113.10", "port": 443, "transport": "tcp", "product": "nginx"},
{"ip_str": "203.0.113.25", "port": 5432, "transport": "tcp", "product": "PostgreSQL"},
{"ip_str": "198.51.100.1", "port": 22, "transport": "tcp"},
])
unexpected = sync_from_shodan(api)
api.search_cursor.assert_called_once_with("net:203.0.113.0/24")
self.assertEqual([(s.ip, s.port) for s in unexpected], [("203.0.113.25", 5432)])
self.assertEqual(ExposedService.objects.count(), 2)
def test_scope_guard(self):
with self.assertRaises(OutOfScope):
require_own_network("198.51.100.0/24")
Shodan can also push changes to you. api.create_alert("myproject", "203.0.113.0/24") registers a network alert for your own range, so you receive a notification when a new port appears instead of polling. Treat the scan data as a lagging view: an index can be days old, so a closed port may still be listed and a newly opened one may not be listed yet.
Scan data tells you which ports are open. The next question is what your Django sites reveal over HTTPS. The checker below sends a handful of ordinary GET requests to hosts on the allowlist only, never follows redirects (a redirect to a third-party host must not be fetched), and reports:
DEBUG = True;.git/HEAD and .env being served;/static/ and /media/.import re
import secrets
import httpx
from .scope import require_own_host
REQUIRED_HEADERS = [
"strict-transport-security",
"x-content-type-options",
"referrer-policy",
"content-security-policy",
]
def check_host(host, client):
"""Return (check, severity, detail) tuples for one host we own."""
require_own_host(host)
base = f"https://{host}"
def get(path):
return client.get(base + path, follow_redirects=False, timeout=10.0)
findings = []
home = get("/")
missing = [h for h in REQUIRED_HEADERS if h not in home.headers]
if missing:
findings.append(("headers", "medium", "missing: " + ", ".join(missing)))
probe = get(f"/exposure-probe-{secrets.token_hex(4)}/")
if probe.status_code == 404 and "DEBUG = True" in probe.text:
findings.append(("debug-page", "critical", "Django technical 404 page served"))
admin = get("/admin/login/")
if admin.status_code == 200 and "csrfmiddlewaretoken" in admin.text:
findings.append(("admin-reachable", "high", "/admin/ login form is public"))
git = get("/.git/HEAD")
if git.status_code == 200 and git.text.startswith("ref: "):
findings.append(("git-exposed", "critical", "/.git/ is downloadable"))
env = get("/.env")
if env.status_code == 200 and re.search(r"^[A-Z_]+=", env.text, re.M):
findings.append(("env-exposed", "critical", "/.env is served"))
for path in ("/static/", "/media/"):
listing = get(path)
if listing.status_code == 200 and "Index of /" in listing.text:
findings.append((f"listing{path}", "medium", f"directory listing at {path}"))
return findings
def default_client():
return httpx.Client(headers={"User-Agent": "myproject-exposure-check/1.0"})
Run the check from outside your network (a small external runner you control), otherwise the admin allowlist will make everything look fine. The tests never contact a real host: httpx.MockTransport serves a leaky or a hardened fake site from a handler function.
"/admin/login/": (200, '<input name="csrfmiddlewaretoken">'),
"/.git/HEAD": (200, "ref: refs/heads/main\n"),
"/.env": (200, "SECRET_KEY=dev\nDATABASE_URL=sqlite:///db\n"),
"/static/": (200, "<h1>Index of /static/</h1>"),
}
def site(leaky):
def handler(request):
path = request.url.path
if leaky and path in LEAKY:
return httpx.Response(LEAKY[path][0], text=LEAKY[path][1])
if path.startswith("/exposure-probe-"):
body = "you have <code>DEBUG = True</code> in" if leaky else "Not Found"
return httpx.Response(404, text=body)
headers = {} if leaky else {
"strict-transport-security": "max-age=31536000",
"x-content-type-options": "nosniff",
"referrer-policy": "same-origin",
"content-security-policy": "default-src 'self'",
}
return httpx.Response(200 if path == "/" else 404, headers=headers, text="ok")
return httpx.Client(transport=httpx.MockTransport(handler))
Calling check_host("staging.example.com", site(leaky=True)) returns:
('headers', 'medium', 'missing: strict-transport-security, x-content-type-options, referrer-policy, content-security-policy')
('debug-page', 'critical', 'Django technical 404 page served')
('admin-reachable', 'high', '/admin/ login form is public')
('git-exposed', 'critical', '/.git/ is downloadable')
('env-exposed', 'critical', '/.env is served')
('listing/static/', 'medium', 'directory listing at /static/')
Calling check_host("www.example.org", client) raises OutOfScope before any request is made; a test covers this.
Search engines index pages that were linked once and forgotten. Every query below starts with site: and your own domain; never drop that operator. Run them by hand in a browser, or through a search provider's official API under its terms; do not scrape result pages.
site:example.com inurl:admin
site:example.com intitle:"Index of /"
site:example.com ext:env OR ext:sql OR ext:bak OR ext:log
site:example.com "DEBUG = True"
site:staging.example.com
A hit means two jobs: fix the server (remove the file, add authentication) and then request removal from the index through the search engine's webmaster tools. A noindex header on staging hosts prevents the next leak; it is not access control.
Most providers implement the S3 API, so the same concepts apply across clouds:
"Principal": "*" and no condition grants it to everyone.AllUsers or AuthenticatedUsers groups are public.The audit reads these settings for buckets in your own account and the remediation turns on all four block settings, resets the ACL and removes unconditional public statements while keeping the rest of the policy:
import json
PUBLIC_GROUPS = {
"http://acs.amazonaws.com/groups/global/AllUsers",
"http://acs.amazonaws.com/groups/global/AuthenticatedUsers",
}
BLOCK_ALL = {
"BlockPublicAcls": True,
"IgnorePublicAcls": True,
"BlockPublicPolicy": True,
"RestrictPublicBuckets": True,
}
def is_public(st):
principal = st.get("Principal")
return (st["Effect"] == "Allow" and principal in ("*", {"AWS": "*"})
and "Condition" not in st)
def load_policy(s3, bucket):
try:
return json.loads(s3.get_bucket_policy(Bucket=bucket)["Policy"])
except s3.exceptions.ClientError:
return {"Version": "2012-10-17", "Statement": []}
def audit_bucket(s3, bucket):
issues = []
try:
cfg = s3.get_public_access_block(Bucket=bucket)["PublicAccessBlockConfiguration"]
if cfg != BLOCK_ALL:
issues.append(("bpa-partial", f"block public access incomplete: {cfg}"))
except s3.exceptions.ClientError as exc:
if exc.response["Error"]["Code"] != "NoSuchPublicAccessBlockConfiguration":
raise
issues.append(("bpa-missing", "no block public access configuration"))
for grant in s3.get_bucket_acl(Bucket=bucket)["Grants"]:
if grant["Grantee"].get("URI") in PUBLIC_GROUPS:
issues.append(("acl-public", f"ACL grants {grant['Permission']} to a public group"))
for st in load_policy(s3, bucket)["Statement"]:
if is_public(st):
issues.append(("policy-public", f"policy allows {st['Action']} to everyone"))
return issues
def remediate_bucket(s3, bucket):
s3.put_public_access_block(Bucket=bucket, PublicAccessBlockConfiguration=BLOCK_ALL)
s3.put_bucket_acl(Bucket=bucket, ACL="private")
policy = load_policy(s3, bucket)
kept = [st for st in policy["Statement"] if not is_public(st)]
if len(kept) == len(policy["Statement"]):
return
if kept:
s3.put_bucket_policy(Bucket=bucket, Policy=json.dumps({**policy, "Statement": kept}))
else:
s3.delete_bucket_policy(Bucket=bucket)
def share_object(s3, bucket, key, seconds=900):
return s3.generate_presigned_url(
"get_object", Params={"Bucket": bucket, "Key": key}, ExpiresIn=seconds
)
Point boto3.client("s3", endpoint_url=...) at your provider's endpoint for non-AWS storage; support for block-public-access and ACL calls varies, so verify each call against your provider's documentation. The demonstration runs entirely inside moto, with python storage_demo.py (the storage module has no Django dependency):
import json
import boto3
from moto import mock_aws
from exposure.storage import audit_bucket, remediate_bucket, share_object
PUBLIC_POLICY = {"Version": "2012-10-17", "Statement": [{
"Effect": "Allow", "Principal": "*", "Action": "s3:GetObject",
"Resource": "arn:aws:s3:::myproject-uploads/*"}]}
with mock_aws():
s3 = boto3.client("s3", region_name="eu-central-1")
s3.create_bucket(Bucket="myproject-uploads",
CreateBucketConfiguration={"LocationConstraint": "eu-central-1"})
s3.put_bucket_acl(Bucket="myproject-uploads", ACL="public-read")
s3.put_bucket_policy(Bucket="myproject-uploads", Policy=json.dumps(PUBLIC_POLICY))
for issue in audit_bucket(s3, "myproject-uploads"):
print("before:", issue)
remediate_bucket(s3, "myproject-uploads")
print("after:", audit_bucket(s3, "myproject-uploads"))
s3.put_object(Bucket="myproject-uploads", Key="invoices/2026-001.pdf", Body=b"%PDF")
print(share_object(s3, "myproject-uploads", "invoices/2026-001.pdf", 300))
before: ('bpa-missing', 'no block public access configuration')
before: ('acl-public', 'ACL grants READ to a public group')
before: ('policy-public', 'policy allows s3:GetObject to everyone')
after: []
https://myproject-uploads.s3.amazonaws.com/invoices/2026-001.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&...&X-Amz-Expires=300&...
Know what the mock does not prove. In our run, moto accepted a public-read ACL even after the block settings were enabled; a real provider would reject it. Mocks test your logic, not the provider's enforcement, so confirm enforcement once on a dedicated test bucket in your own account.
DEBUG, remove .git and .env from the web root, enable block public access. Prefer the smallest change that removes exposure now; the clean fix can follow.SECRET_KEY, database passwords and API keys in a served .env or in git history.A production settings module that imports the base settings and hardens them:
import os
from .settings import * # noqa: F401,F403
DEBUG = False
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
ALLOWED_HOSTS = ["www.example.com"]
CSRF_TRUSTED_ORIGINS = ["https://www.example.com"]
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # only behind your own proxy
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_REFERRER_POLICY = "same-origin"
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
X_FRAME_OPTIONS = "DENY"
ADMIN_URL_PREFIX = "/ops-7f3a/" # obscurity is not the control; the allowlist is
Only set SECURE_HSTS_INCLUDE_SUBDOMAINS and SECURE_HSTS_PRELOAD when every subdomain serves HTTPS; preloading is hard to undo. SECURE_PROXY_SSL_HEADER is only safe when your own proxy always sets or strips that header. The admin URL is moved by a setting that urls.py reads (path(settings.ADMIN_URL_PREFIX.lstrip("/"), admin.site.urls)), but the control is the allowlist middleware, which returns 404 to clients outside the VPN ranges:
import ipaddress
from django.conf import settings
from django.http import Http404
class AdminAllowlistMiddleware:
"""404 the admin for clients outside the VPN/office ranges.
REMOTE_ADDR must be the real client IP: set it from a header only
your own reverse proxy can write, never from raw X-Forwarded-For.
"""
def __init__(self, get_response):
self.get_response = get_response
self.networks = [ipaddress.ip_network(n) for n in settings.ADMIN_ALLOWED_NETWORKS]
def __call__(self, request):
if request.path.startswith(settings.ADMIN_URL_PREFIX):
client = ipaddress.ip_address(request.META["REMOTE_ADDR"])
if not any(client in net for net in self.networks):
raise Http404
return self.get_response(request)
Enforce the same rule at the proxy as well, so a middleware mistake is not the only barrier. Running manage.py check --deploy on the development settings gave this real output:
$ python manage.py check --deploy
System check identified some issues:
WARNINGS:
?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. ...
?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. ...
?: (security.W009) Your SECRET_KEY has less than 50 characters, less than 5 unique characters, or it's prefixed with 'django-insecure-' indicating that it was generated automatically by Django. ...
?: (security.W012) SESSION_COOKIE_SECURE is not set to True. ...
?: (security.W016) You have 'django.middleware.csrf.CsrfViewMiddleware' in your MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True. ...
?: (security.W018) You should not have DEBUG set to True in deployment.
?: (security.W020) ALLOWED_HOSTS must not be empty in deployment.
System check identified 7 issues (0 silenced).
$ DJANGO_SECRET_KEY=... python manage.py check --deploy --settings=myproject.settings_prod
System check identified no issues (0 silenced).
Run the second command in CI so a settings regression fails the build. The check inspects settings only; it cannot see a .git directory or an open port, which is why the external checks exist.
The management command runs the HTTP checks and the bucket audit, stores each finding once per (target, kind), alerts only on new findings and marks findings as resolved when they disappear:
import boto3
from django.conf import settings
from django.core.mail import mail_admins
from django.core.management.base import BaseCommand
from django.utils import timezone
from exposure.checker import check_host, default_client
from exposure.models import Finding
from exposure.storage import audit_bucket
class Command(BaseCommand):
help = "Check our own hosts and buckets for exposure signals"
def handle(self, **opts):
results = []
with default_client() as client:
for host in settings.EXPOSURE_ALLOWED_HOSTS:
results += [(host, *f) for f in check_host(host, client)]
s3 = boto3.client("s3", endpoint_url=settings.EXPOSURE_S3_ENDPOINT)
for bucket in settings.EXPOSURE_BUCKETS:
results += [(bucket, check, "high", detail)
for check, detail in audit_bucket(s3, bucket)]
now, new, seen = timezone.now(), [], set()
for target, check, severity, detail in results:
obj, created = Finding.objects.update_or_create(
target=target, kind=check,
defaults=dict(severity=severity, detail=detail, resolved_at=None),
)
seen.add(obj.pk)
if created:
new.append(obj)
fixed = Finding.objects.filter(resolved_at__isnull=True).exclude(pk__in=seen)
n_fixed = fixed.update(resolved_at=now)
if new:
mail_admins(f"{len(new)} new exposure finding(s)", "\n".join(
f"[{f.severity}] {f.target} {f.kind}: {f.detail}" for f in new))
self.stdout.write(f"open={len(seen)} new={len(new)} resolved={n_fixed}")
Schedule it daily from a runner outside your network with cron or a systemd timer, for example 15 6 * * * cd /srv/myproject && venv/bin/python manage.py exposure_scan, and run sync_from_shodan weekly to compare open ports with EXPOSURE_EXPECTED. The command test drives the full cycle with a mocked HTTP transport and a moto bucket:
class ScanCommandTests(TestCase):
def setUp(self):
self.s3 = boto3.client("s3", region_name="us-east-1")
self.s3.create_bucket(Bucket="myproject-uploads")
self.s3.put_bucket_policy(Bucket="myproject-uploads", Policy=json.dumps({
"Version": "2012-10-17", "Statement": [{
"Effect": "Allow", "Principal": "*", "Action": "s3:GetObject",
"Resource": "arn:aws:s3:::myproject-uploads/*"}]}))
def run_scan(self, leaky):
out = StringIO()
with mock.patch("exposure.management.commands.exposure_scan.default_client",
return_value=site(leaky)):
call_command("exposure_scan", stdout=out)
return out.getvalue().strip()
def test_new_findings_alert_once_then_resolve(self):
self.assertEqual(self.run_scan(leaky=True), "open=8 new=8 resolved=0")
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(self.run_scan(leaky=True), "open=8 new=0 resolved=0")
self.assertEqual(len(mail.outbox), 1)
from .storage import remediate_bucket
remediate_bucket(self.s3, "myproject-uploads")
self.assertEqual(self.run_scan(leaky=False), "open=0 new=0 resolved=8")
self.assertFalse(Finding.objects.filter(resolved_at__isnull=True).exists())
$ python manage.py test exposure -v 2
...
test_admin_hidden_from_internet (exposure.tests.AdminAllowlistTests.test_admin_hidden_from_internet) ... ok
test_admin_visible_on_vpn (exposure.tests.AdminAllowlistTests.test_admin_visible_on_vpn) ... ok
test_hardened_host (exposure.tests.CheckerTests.test_hardened_host) ... ok
test_leaky_host (exposure.tests.CheckerTests.test_leaky_host) ... ok
test_refuses_hosts_outside_allowlist (exposure.tests.CheckerTests.test_refuses_hosts_outside_allowlist) ... ok
test_new_findings_alert_once_then_resolve (exposure.tests.ScanCommandTests.test_new_findings_alert_once_then_resolve) ... ok
test_inventory_marks_unexpected_and_drops_foreign_ips (exposure.tests.ShodanTests.test_inventory_marks_unexpected_and_drops_foreign_ips) ... ok
test_scope_guard (exposure.tests.ShodanTests.test_scope_guard) ... ok
----------------------------------------------------------------------
Ran 8 tests in 0.678s
OK
.git, .env, directory listings and missing headers.site: set to your own domain, and request index removal after fixing.check --deploy with production settings in CI and schedule exposure_scan daily with alerts.Found a mistake in this tutorial? Let us know and we will fix it.