Skip to content

About

Tool to watch Nginx access log and gather IPs. Uses SQLite for storage and includes web UI for browsing and filtering data.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

nginx-ipwatch

Tails an Nginx access log, performs WHOIS lookups on newly seen IP addresses, and persists results to SQLite. Includes a web UI for browsing and filtering the data.

What it tracks

Column Description
ip IP address (IPv4 or IPv6)
network CIDR block from WHOIS (e.g. 202.46.32.0/19)
country Country of registration (ISO code)
requests Running count of requests from this IP (all time)
last_seen UTC timestamp of most recent request
category Cloud provider, hosting/VPS or known crawler — see What the marks mean
client What the User-Agent claimed to be — see Client claims
user_agent The most recent User-Agent string seen from this IP (capped at 300 chars)

Alongside it, ip_hits keeps a coarse time series — one row per IP per 5-minute bucket with the requests made in that bucket — so the UI can report requests within a window rather than only all-time. It is trimmed to the retention window by the watcher:

Variable Default Description
HIT_BUCKET 300 Bucket width in seconds (smaller = sharper window edges, more rows)
HIT_RETENTION_DAYS 8 How long history is kept; must exceed the longest UI window (7 days)
PRUNE_INTERVAL 3600 Seconds between retention and labelling sweeps
PROVIDER_DIR /providers Directory of published provider range files; empty/missing = ASN data only
LABEL_BATCH 5000 Unlabelled rows categorised per sweep

What the marks mean

A request from 3.91.24.7 reads differently once you know it is an EC2 box, and a request from 66.249.66.1 differently again once you know it is Googlebot. Every IP therefore carries a category, worked out offline in two tiers:

  1. Published prefix lists — the ranges the operators publish themselves (AWS, Google Cloud, Google, Cloudflare, Googlebot and the Google special crawlers, Bingbot), fetched into /providers at image build time. An IP inside one of these is a fact, not a guess.
  2. ASN fallback — the IPtoASN table already loaded for GeoIP. It covers what no list can: Azure (Microsoft's range file has no stable URL — the filename carries a weekly date) and Facebook (published via whois), space the big providers hold by direct allocation rather than through their cloud products, and — by keyword on the AS name — the long tail of rented VPS, dedicated and colocation operators that publish nothing at all.

Crawlers beat infrastructure: Googlebot runs inside Google's own ranges, and "Googlebot" is the more useful thing to know. Categories are:

Mark Meaning
Googlebot / Bingbot / Facebook A known crawler, from its operator's own published range (or AS32934 for Facebook)
AWS / Google Cloud / Google / Microsoft/Azure / Cloudflare The IP belongs to that provider
Hosting/VPS An AS that looks like rented infrastructure — a machine in a datacentre rather than somebody's connection
(no mark) Nothing matched; for a public IP this usually means a consumer or business ISP

The interesting scanner signal is usually Hosting/VPS with no crawler mark. An unlabelled row and an unmarked one are different things: NULL means the labeller hasn't reached it yet, '' means it was checked and matched nothing, and the Unmarked (likely ISP) filter only shows the latter.

Labels are applied as IPs arrive and backfilled for older rows during maintenance sweeps. Refreshing the range files (a rebuilt image) does not revisit rows already labelled — run python backfill.py --relabel once for that.

Client claims and fake crawlers

The watcher also reads the User-Agent from each log line. Unlike everything else here, a UA is not evidence: it is typed by whoever sent the request. Googlebot/2.1 arriving from a rented VPS is simply a lie, and a common one.

So the claim is stored as a claim, and shown next to a verdict that compares it with the IP's category — the part that can't be faked:

Verdict Means
verified The IP is inside that crawler's published range
unverified The IP belongs to the operator, but isn't in the published crawler range
impersonating The UA claims a crawler the IP cannot belong to
declared Self-reported, and uncheckable — SEO crawlers and HTTP libraries publish no ranges

Only Googlebot, Bingbot and Facebook can be checked this way, because only they publish the ranges. Everything else (AhrefsBot, GPTBot, curl, python-requests, zgrab, sqlmap…) is reported as declared — the claim, never a fact.

Filter the IP view by ⚠ Impersonating a crawler to see the fakes, or by Tools & libraries for clients that aren't pretending to be browsers at all.

Log format: the UA is read as the last quoted field, which is where nginx's stock combined format puts it. A custom log_format that moves or omits $http_user_agent simply yields no client — nothing else breaks.

An IP that presents several User-Agents is shown as whatever it sent last; only one is stored. A scanner that mostly sends a browser UA and occasionally a bot one will therefore flip between them.

How IPs are resolved

GeoJS is the primary source, with RDAP/WHOIS and the bundled offline tables behind it:

  1. Private — RFC-1918 / loopback / link-local are stored as private with no lookup.
  2. Network cache — an IP inside an already-resolved CIDR reuses that block's data, for free.
  3. GeoJS — queried for the country, AS number and AS name.
  4. RDAP/WHOIS — asked for whatever GeoJS couldn't supply, throttled and retried with exponential backoff behind a rate-limit circuit breaker.
  5. Local GeoIP — the offline tables, as the last resort (and the first resort whenever GeoJS is disabled or in a cooldown, since they answer instantly and for free).

No lookup ever happens on the log-arrival path. A new IP is resolved from the cache or deferred, and the deferred backlog is resolved by a sweep that sends up to GEOJS_BATCH addresses in a single GeoJS request — so a scanner flood costs one request per 50 IPs, not one per IP. Because that is so cheap, the sweep runs every GEOJS_INTERVAL (60s) while GeoJS is answering, instead of the RDAP-paced BACKFILL_INTERVAL (900s).

GeoJS does not return a network CIDR. It gives country + ASN + AS name, so the network column is still filled from the local ASN ranges, or from RDAP when those miss. Everything else — country, and the AS data behind the cloud/hosting/crawler marks — comes from GeoJS when it answers, which is fresher than the bundled tables.

Variable Default Description
GEOJS 1 0 disables GeoJS entirely; resolution reverts to GeoIP → RDAP
GEOJS_URL https://get.geojs.io/v1/ip/geo.json Batch endpoint
GEOJS_BATCH 50 Addresses per request
GEOJS_TIMEOUT 10 Seconds per request
GEOJS_INTERVAL 60 Seconds between sweeps while GeoJS is answering
GEOJS_FAIL_STREAK 3 Consecutive failures that pause GeoJS
GEOJS_COOLDOWN 600 Seconds to stay paused after that

Anything none of the four can resolve stays NULL and can be resolved by hand — see Manual lookup.

Manual lookup (when a registry blocks you)

A registry can permanently ban your server from querying it. RIPE does this to a host that has queried too hard, and once it lands both port-43 WHOIS and RDAP stop answering every lookup:

$ whois 78.61.136.250
%ERROR:201: access denied for 95.216.220.179
% Sorry, access from your host has been permanently
% denied because of a repeated excessive querying.

The IPs then look unresolvable even though the data is perfectly public — it's your host that's blocked, not the data. The fix is to let somebody else make the registry query, which is what the Manual lookup box and the 🔍 button (shown on any row with no network) in the web UI do. Sources are tried in order (GeoJS first, but since it returns no CIDR its answer is merged with the first source that does supply one):

Source Notes
RIPEstat (stat.ripe.net) RIPE's data API — a separate service from the banned query service, keyless, IPv4 + IPv6, all RIRs. Its network-info call returns the BGP-announced prefix, which is more specific than the RIR allocation RDAP reports.
whois.com Scrapes the raw registry text they render. Fallback only: IPv4-only, and being HTML it breaks if they restyle the page.

The more specific prefix is the reason this is worth doing even when you aren't blocked. For 78.61.136.250, RDAP reports the registry allocation, while RIPEstat reports the routed block — a difference of 32x in how many unrelated hosts get lumped into one /networks row:

RDAP     78.61.0.0/17, 78.61.128.0/18, 78.61.192.0/21   (inetnum, ~32k addresses)
RIPEstat 78.61.136.0/22                                 (route, AS8764 — stored)

A lookup writes:

  • the queried IP — overwritten unconditionally; asking for it explicitly means the manual answer beats whatever GeoIP guessed
  • every unresolved IP in the same block (network IS NULL) — filled in, so one click clears a whole CIDR from the backlog. Already-resolved rows are left alone, so a click can't silently rewrite data you didn't ask about.

Results reach the watcher too: it re-primes its network cache from the database before each sweep, so IPs logged later in a manually-resolved block resolve from cache without a lookup of their own.

Looking up an IP the log has never seen is allowed (handy for checking a block), but nothing is stored — ip_access records observed traffic, not WHOIS answers. If a source returns a country but no network, the country is stored and network stays NULL so the automatic sweep can still improve it later.

If you're banned, it's also worth requesting an unblock from RIPE and lowering BACKFILL_BATCH / raising WHOIS_DELAY so it doesn't happen again.

Env var Default Meaning
PROXY_SOURCES ripestat,whoiscom Sources to try, in order. Drop one to disable it.
PROXY_LOOKUP_TIMEOUT 15 Seconds per HTTP request.
RIPESTAT_SOURCEAPP nginx-ipwatch Identifies this app to RIPEstat.
LOOKUP_MIN_INTERVAL 2.0 Minimum seconds between lookups (per web worker). Guards against a held-down button, not an access control.

GeoIP databases

The Docker image fetches offline databases from sapics/ip-location-db at build time:

  • Country — DB-IP Lite (dbip-country-*-num.csv), a geolocation database.
  • Network / ASN — IPtoASN (iptoasn-asn-*-num.csv, public domain); the matched range gives the network CIDR.

They're pure CSV loaded in-process — no extra Python dependency. To refresh them, rebuild with docker compose build --no-cache. To use different sources (e.g. GeoLite2), change the ADD URLs in the Dockerfile and the GEOIP_COUNTRY_DB / GEOIP_ASN_DB env vars (each a comma-separated list of CSV paths; IPv4 and IPv6 files can both be listed). If neither var points to a readable file, GeoIP is disabled and everything falls back to RDAP.

Country data © DB-IP, licensed under CC BY 4.0. ASN data from iptoasn.com (public domain).

Services

Service Description Default port
watcher Tails the log and writes to SQLite —
web Flask UI served by gunicorn 5000

Both share the same ./data volume.

Docker (recommended)

# Build and start both services
docker compose up -d

# Follow watcher logs (WHOIS lookups appear here)
docker compose logs -f watcher

# Stop everything
docker compose down

Open http://localhost:5000 in your browser.

The SQLite database is written to ./data/nginx_ips.db.

Customising paths

Edit docker-compose.yml — for example to watch a non-default log file:

services:
  watcher:
    volumes:
      - /var/log/nginx:/logs:ro
    environment:
      LOG_PATH: /logs/mysite.access.log

Or override at runtime without changing the file:

docker compose run --rm watcher python -u nginx-ipwatch.py /logs/other.log /data/other.db

Web UI features

  • Two views — per-IP (/) and per-network (/networks, aggregated by CIDR to surface coordinated activity from many IPs in one block)
  • Stats bar — unique IP count, request count, country count (all scoped to the selected period)
  • IP / network search — substring match across recorded IPs or networks
  • Country filter — dropdown of all seen countries (with flags); clicking a badge in the table filters by that country
  • Client column — what the User-Agent claimed, with a verdict badge (verified / unverified / impersonating / declared) and the raw UA on hover; filter by a specific bot, by kind, or by impersonating
  • Type column and filter — cloud/hosting/crawler marks with the provider's brand icon; filter by one provider, by anything marked, or by unmarked (likely ISP). Clicking a mark filters by it
  • Country flags — flag emoji shown next to each country code
  • Time-period filter — last hour, 3h/6h/12h/24h, today, yesterday, or last 7 days. Picking a window both limits the rows to IPs/networks active in it and scopes the request counts to it (so "Last hour" shows requests made in the last hour, not the all-time total). Windows snap outwards to whole buckets, so a count can include up to one extra HIT_BUCKET of older traffic. A database written before history existed falls back to filtering by last seen with all-time counts, and the UI says so.
  • Exclude filters — hide specific IPs, networks, or countries (comma-separated, multi-value); combines with the include filters
  • Sortable columns — click any column header to sort asc/desc
  • Pagination — 50 rows per page
  • Auto-refresh — optional 30-second page reload toggle
  • Manual lookup — resolve an IP through a third-party WHOIS source and store the result, for when a registry has blocked automatic lookups (details)

Running without Docker

Python 3.10+ required.

pip install -r requirements.txt

# watcher (terminal 1)
python nginx-ipwatch.py /var/log/nginx/access.log ./nginx_ips.db

# web UI (terminal 2)
DB_PATH=./nginx_ips.db gunicorn web:app --bind 0.0.0.0:5000

GeoIP is optional here — without it the watcher falls back to RDAP. To enable it, download the CSVs and point the env vars at them:

base=https://github.com/sapics/ip-location-db/releases/download/latest
mkdir -p geoip && cd geoip
for f in dbip-country-ipv4-num.csv dbip-country-ipv6-num.csv \
         iptoasn-asn-ipv4-num.csv iptoasn-asn-ipv6-num.csv; do curl -sLO "$base/$f"; done
cd ..

GEOIP_COUNTRY_DB=geoip/dbip-country-ipv4-num.csv,geoip/dbip-country-ipv6-num.csv \
GEOIP_ASN_DB=geoip/iptoasn-asn-ipv4-num.csv,geoip/iptoasn-asn-ipv6-num.csv \
python nginx-ipwatch.py /var/log/nginx/access.log ./nginx_ips.db

Querying SQLite directly

# Top talkers
sqlite3 data/nginx_ips.db \
  "SELECT ip, country, network, requests, last_seen FROM ip_access ORDER BY requests DESC LIMIT 20;"

# All IPs from a specific country
sqlite3 data/nginx_ips.db \
  "SELECT ip, network, requests FROM ip_access WHERE country = 'CN' ORDER BY requests DESC;"

# IPs seen in the last hour
sqlite3 data/nginx_ips.db \
  "SELECT ip, country, requests FROM ip_access WHERE last_seen >= datetime('now', '-1 hour');"

# Requests made in the last hour (from the bucketed history)
sqlite3 data/nginx_ips.db \
  "SELECT ip, SUM(requests) AS reqs FROM ip_hits \
   WHERE bucket >= strftime('%Y-%m-%d %H:%M:%S', 'now', '-1 hour') \
   GROUP BY ip ORDER BY reqs DESC LIMIT 20;"

Notes

  • The watcher starts at the end of the log file — it tracks new entries only, not history.
  • Log rotation is handled automatically via inode detection.
  • The web process opens the database read-only for all browsing. Its one write path is the manual lookup (POST /lookup), which uses a separate writable connection.
  • The UI has no authentication and the manual lookup makes outbound HTTP requests on demand, so keep it on a trusted network or behind your own auth — don't expose port 5000 to the internet.
  • All timestamps are stored in UTC.
  • Provider range files are refreshed by rebuilding the image; existing rows keep their labels until backfill.py --relabel is run.
  • Request history only reaches back to when the watcher first recorded it, and no further than HIT_RETENTION_DAYS.

License

Released under the MIT License. Made by 19 points.

About

Tool to watch Nginx access log and gather IPs. Uses SQLite for storage and includes web UI for browsing and filtering data.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages