Skip to content

Configuration

Django settings

Setting Required Description
GEOIP_PATH Recommended Path to the GeoLite2/GeoIP2 Country .mmdb file, or a directory containing GeoLite2-Country.mmdb
NAI_SECURITY_EXEMPT_PATHS Optional Paths that skip every middleware check. A trailing * exempts a subtree
NAI_SECURITY_TRUST_PROXY_HEADERS Optional Number of reverse proxies in front of the app. Default 0 — X-Forwarded-For ignored, so clients cannot spoof their IP
NAI_SECURITY_APPROVED_PROXIES Optional IPs/CIDRs allowed to set X-Forwarded-For. Default: loopback and private ranges only. Required if your proxy has a public address
NAI_SECURITY_PASSIVE_MAX_BYTES Optional Bytes of each response body PassiveScanMiddleware reads. Default 65536
NAI_SECURITY_GEOIP_RELEASE Optional Release tag download_geoip fetches. Default is the tag pinned in the command
NAI_SECURITY_GEOIP_SHA256 Optional Expected SHA-256 of that release's .mmdb. Required for any non-default release

Reverse proxies

NAI_SECURITY_TRUST_PROXY_HEADERS is a count, not a switch:

Deployment Value
No proxy — gunicorn or runserver exposed directly 0 (default)
One nginx / one load balancer 1
nginx behind Cloudflare 2

The client sits that many hops from the right of X-Forwarded-For: each proxy appends the peer it heard from, so the leftmost entry is whatever the client prepended. A chain shorter than the count falls back to REMOTE_ADDR.

The count alone is not a trust decision. A forwarded chain is only honoured when REMOTE_ADDR — the one address a client cannot set — is an approved proxy. Unset, NAI_SECURITY_APPROVED_PROXIES approves loopback and the private ranges (127.0.0.0/8, ::1/128, 10/8, 172.16/12, 192.168/16, fc00::/7), which covers nginx or gunicorn on the same host or network. A proxy that reaches the app from a public address — a cloud load balancer, a CDN such as Cloudflare — must be listed:

NAI_SECURITY_APPROVED_PROXIES = ["173.245.48.0/20", "103.21.244.0/22"]  # your CDN's ranges

Listing anything replaces the defaults, so include loopback if you also proxy locally. An entry that is not an IP or CIDR is logged and approves nothing. If the app can be reached directly from the internet, no part of a forwarded chain is evidence of anything — that is the case this exists for.

X-Real-IP is not read — the client sets it as easily as a proxy does.

True is accepted as 1, and a digit string ("3", straight out of an env var) is read. Anything else — a negative number, "yes", a list — resolves to 0 and trusts nothing, rather than raising a 500 on every request. nai_security.W007 reports it at deploy time.

Count too low and you read a proxy's address for every client; too high and no chain ever matches, so every client is REMOTE_ADDR. Either way IP blocks and whitelists apply to the wrong address.

Exempt paths

An exempt path skips every check — IP, country, user-agent and path blocking — and is matched before SecuritySettings is loaded. That is deliberate: it is what lets /health/ still answer when the database is down. It also means an exempt path is entirely unprotected, so keep the list short.

Default exempt paths:

  • /health/
  • /ready/
  • /favicon.ico

Override:

NAI_SECURITY_EXEMPT_PATHS = [
    "/health/",
    "/health",
    "/ready/",
    "/ready",
    "/favicon.ico",
    "/metrics/",
    "/exports/*",  # trailing * exempts the whole subtree
]

A trailing * exempts a prefix, which is the only way to exempt a parameterized route such as /exports/<uuid>.sql. Prefixes anchor on / segments, so /export* covers /export and /export/2026.sql but not /exports-internal/.env. Entries and request paths are both normalized first, so /exports/* cannot be reached as /exports/../.env.

A bare '*' raises ImproperlyConfigured at startup: it exempted every request and silently disabled the middleware. Remove the middleware instead.

Runtime settings (admin / DB)

Most knobs live in the singleton model SecuritySettings (Django admin), not in settings.py:

  • Enable/disable IP, country, user-agent and path blocking
  • Auto-block thresholds / durations
  • Login anomaly flags
  • Sync toggles for disposable domains / bad bots
  • Axes: max attempts, cooloff minutes, attempt expiry
  • log_retention_days — how long SecurityLog rows are kept (default 90, 0 = forever); enforced by the security.cleanup_security_logs task
  • signature_detection_enabled (default on) / signature_blocking_enabled (default off) — see Injection signatures
  • passive_scan_enabled (default on) — gates PassiveScanMiddleware, which you must add to MIDDLEWARE yourself

Changes apply without restart (cached values are invalidated on save).

Path blocking

path_blocking_enabled (on by default) returns 403 and logs a PATH_BLOCK event for any request to a dotfile path (/.git, /.env, /.ssh, /.aws, …) or to /server-status, /server-info, /phpinfo, /wp-config.php, /web.config, /id_rsa.

Paths are normalized before matching, so //.git/config and /./.git/config are caught too.

Also blocked by file extension, since none of these is a legitimate Django route:

Group Extensions
Editor / backup leftovers .bak .old .orig .save .swp .swo .tmp
Data and key material .sql .log .pem .key .sqlite .sqlite3 .db
Scripts Django never executes .php .php5 .phtml .asp .aspx .jsp .cgi

Archives (.zip .tar .tar.gz .tgz .rar .7z .gz .bz2) are blocked only at the site root — /backup.zip is a leak, /media/user/report.zip is an ordinary download.

If a real route collides with one of these, list it in NAI_SECURITY_EXEMPT_PATHS; exempt paths are checked before any blocking rule. /.well-known/ stays reachable so ACME / Let's Encrypt renewal is unaffected — but it is not a shelter: /.well-known/.git/config is still blocked.

Header stripping

ResponseHeaderMiddleware removes response headers that identify the stack. Opt-in:

MIDDLEWARE = [
    "nai_security.middleware.ResponseHeaderMiddleware",  # first — sees the final response
    ...,
]

Django unwinds the response through middleware in reverse, so listing it first is what lets it strip headers added by everything below it.

Default list: Server, X-Powered-By, X-AspNet-Version, X-AspNetMvc-Version, X-Runtime, X-Generator, X-Drupal-Cache, X-Varnish. Replace it wholesale with:

NAI_SECURITY_STRIP_HEADERS = ["Server", "X-Powered-By"]  # [] disables stripping

Deleting a header that is not present is not an error, and matching is case-insensitive.

It only reaches headers Django owns. gunicorn and nginx set Server after Django returns — strip those at that layer (server_tokens off;).

Deploy checks

nai-security registers eight checks under the deploy tag, so they run alongside Django's own security.W0xx checks:

python manage.py check --deploy
ID Flags
nai_security.W001 A URL pattern resolves to a path SecurityMiddleware blocks — the view is unreachable
nai_security.W002 The admin is mounted at a default, guessable prefix (admin/, django-admin/)
nai_security.W003 Django is serving static/ or media/ through the URLconf with DEBUG=False
nai_security.W004 ResponseHeaderMiddleware is not in MIDDLEWARE, so responses may advertise the stack
nai_security.W005 ALLOWED_HOSTS contains '*' — any Host header is accepted
nai_security.W006 CORS allows every origin (worse when combined with credentials)
nai_security.W007 NAI_SECURITY_TRUST_PROXY_HEADERS is unset or not a proxy count (every client IP is REMOTE_ADDR), or it is set while NAI_SECURITY_APPROVED_PROXIES names no proxy network
nai_security.W008 Country rules are enabled but the GeoIP database is missing or unreadable
nai_security.W009 robots.txt has a Disallow: entry naming the admin or a path the perimeter blocks
nai_security.W010 Django 6.0+ sends no Content-Security-Policy: ContentSecurityPolicyMiddleware is missing, or SECURE_CSP and SECURE_CSP_REPORT_ONLY are both empty

W005 and W006 do inspect settings, but ones Django's own checks miss: security.W020 fires only when ALLOWED_HOSTS is empty, so ['*'] — the configuration that actually enables host-header injection — passes it silently. Django ships no CORS checks at all.

W001–W003 inspect the URLconf, which Django never looks at. Included URLconfs are followed, so path('api/', include(...)) is reported with its full prefix. An unloadable ROOT_URLCONF makes them return nothing rather than crash manage.py check.

W010 is silent on Django 5.2, which has no built-in CSP, and when django-csp's csp.middleware.CSPMiddleware is installed. A policy set by nginx or a CDN is invisible to it — silence it with SILENCED_SYSTEM_CHECKS = ["nai_security.W010"].

W007 and W008 read runtime state rather than settings alone. W008 also reads SecuritySettings, and stays silent if the database is unreachable — it reports a misconfigured perimeter, not a broken one.

They are warnings, so check --deploy still exits 0. To gate a build on them:

python manage.py check --deploy --fail-level WARNING

Injection signatures

Every request is matched against thirteen patterns across five surfaces — query string, form body, cookies, User-Agent, Referer:

Class Rule ids
SQL injection SQLI_UNION SQLI_BOOLEAN SQLI_STACKED SQLI_TIME SQLI_ERROR SQLI_INLINE_COMMENT
Other injection NOSQL_OPERATOR GRAPHQL_INTROSPECTION LDAP_INJECTION XPATH_INJECTION SSTI_TEMPLATE XXE_ENTITY HQL_INJECTION

Percent-encoding is decoded up to three times and inline /* */ comments are stripped before matching, so the usual obfuscations do not hide a payload.

Log-only is the default and you should keep it that way until you have looked. A match writes a SIGNATURE_MATCH row to SecurityLog with the rule id in details. Set signature_blocking_enabled once you have confirmed your own traffic does not match; the search box of a site about databases will.

Non-form request bodies are not read — buffering a JSON or upload body on every request is a cost the perimeter refuses to pay by default.

Passive response scan

nai_security.middleware.PassiveScanMiddleware is opt-in. Added to MIDDLEWARE, it inspects text/html, text/plain and application/json responses for:

Rule id Finds
PRIVATE_KEY -----BEGIN ... PRIVATE KEY----- in a response body
DBMS_ERROR Database error text (MySQL/Postgres/Oracle/SQLite/SQLSTATE)
STACK_TRACE Python, Java or PHP tracebacks
SECRET_IN_COMMENT password / secret / api_key / token inside an HTML comment
INTERNAL_IP RFC1918, loopback or link-local addresses
MISSING_HEADERS An HTML response without X-Content-Type-Options, X-Frame-Options, Referrer-Policy or Content-Security-Policy

Findings are recorded as one PASSIVE_ALERT row per response. It never blocks, never edits a response, and skips streaming and file responses. A failure inside the scan is logged and swallowed — a reporting layer must not be why a page 500s.

Country modes

  • Blocklist mode: use BlockedCountry
  • Allowlist mode: use AllowedCountry (only listed countries pass)

Configure which mode is active in SecuritySettings.

Both modes fail closed: an IP whose country cannot be resolved — no GeoIP database, or a lookup miss — is denied. Blocklist mode fails closed only while a BlockedCountry row exists, so an install that blocks no country is unaffected; allowlist mode denies regardless, and an empty allowlist denies every country rather than allowing all of them. Keep a WhitelistedIP row for your own address, or a missing .mmdb locks you out of the admin too. nai_security.W008 warns about either. A fail-closed denial is logged as COUNTRY_BLOCK with an empty country code.

Optional package settings

django-axes

See Axes-Integration.

django-ratelimit

Use django-ratelimit decorators/middleware as usual — they are not replaced.

RateLimitLoggingMiddleware does two things: it enforces the active RateLimitRule rows (per client IP, fixed window, longest matching path prefix wins, 429 past the limit) before the view runs, and it logs when request.limited is true after it. A request it denies never reaches the view, so django-ratelimit cannot count or 429 the same request a second time. Exempt paths, loopback clients, WhitelistedIP, and WhitelistedUser with rate_limit or all are never limited.

Localhost behavior

A loopback client (127.0.0.1, ::1) bypasses blocking checks so local development keeps working — but only when the request carries no forwarded headers and REMOTE_ADDR is a real IP. nginx proxying to gunicorn on 127.0.0.1, or over a unix socket where REMOTE_ADDR is empty, otherwise made every request look local and turned the whole perimeter off.