hashgate(8)
NAME
hashgate - make crawlers pay a proof of work before nginx lets them in
SYNOPSIS
hashgate
hashgate --version | --help
DESCRIPTION
Some parts of a web site are effectively infinite. A source forge renders every file at every commit, every pair of refs as a diff, every sort order of every issue list. A person reads a handful of those pages. A crawler that follows every link never finishes, and the site pays for each page it renders.
The usual answers do not work against the crawlers that do this. They rent pools of tens of thousands of addresses and use most of them exactly once, so a per-address rate limit never fills, and they ignore robots.txt. What they will not do at that scale is run a browser engine and spend a second of CPU on every address. hashgate charges exactly that.
It sits behind nginx's auth_request and answers one question on a tiny subrequest: may this request through? It is never in the data path. The page itself still streams straight from the upstream to the client.
How does a visitor get in?
- nginx asks
/verify. There is no valid cookie, so the answer is 401. - nginx serves the interstitial from
/challengeunder the original URL. - The page searches for a nonce n such that SHA-256 of exp
.mac.n hasHASHGATE_DIFFICULTYleading zero bits, sets it as a cookie, and reloads. /verifynow answers 204 and nginx proxies the request through.
At the default of 18 bits a real browser takes a second or two, once. The cookie then admits it to every gated location for HASHGATE_TTL.
What is the token?
exp.mac.nonce, where mac is HMAC-SHA256 of hashgate1|exp|prefix under the secret, truncated to 128 bits. There is no challenge store: the MAC is what proves this server issued that challenge, for that address prefix, with that expiry.
prefix is the client's IPv4 /24 or IPv6 /48, not its exact address. An IPv4 client reported as ::ffff:a.b.c.d by a dual-stack nginx counts as IPv4. A phone that changes address mid-session keeps its token. A pool of rented addresses pays once per block instead of solving once and replaying the cookie everywhere, and that is the part that costs a crawler something.
Which parts of a site should be gated?
Only the infinite ones. Everything a person, a feed reader or a git clone needs should stay open, so that the gate is never in the way of anything but the walk. Nothing about the token depends on the path, so adding locations raises the price for a crawler and not for a reader.
/verify gates unconditionally; the nginx location has already decided by path. /verify-filtered admits the request untested unless the original URI carries one of the query parameters in HASHGATE_FILTER_PARAMS. That is for pages that are a normal destination on their own but multiply without end through their sort and filter links. An nginx location cannot see the query string, which is why this is a route here and not a regex there.
The default list is the sort and filter parameters a Forgejo or Gitea issue or pull list renders: sort, state, labels, milestone, project, assignee, poster, type and archived. q, the search box, is deliberately not among them, since a search is one page view like any other. For any other site, set the list to whatever makes its pages combinatorial.
Does it ban anybody?
No. It reports. Once one prefix has been challenged HASHGATE_ABUSE_AFTER times without anyone in it ever solving, every further challenge from it emits an abuse line naming the client address. flagger(8) can act on that line; the rule ships as contrib/flagger/hashgate.toml and is deliberately not installed.
A single solve from anywhere in a prefix exempts it from abuse lines permanently. A /24 can be an office or a carrier NAT, and one real visitor in it is enough to keep the addresses around them out of a firewall.
OPTIONS
--version,-V- Print
hashgateand the version, and exit. --help,-h- Print a usage line and exit.
There are no other options. Configuration is entirely in the environment, which is where a systemd unit puts it.
ROUTES
All requests are expected from nginx on the same host. X-Real-IP is taken as the client address, and X-Original-URI as the URI the client asked for. A request without a usable X-Real-IP is taken to come from its peer, which is nginx, so every such client shares one prefix; the first one logs a warning.
/verify- 204 for a valid token, 401 otherwise.
/verify-filtered- As
/verify, but 204 without looking at the token when the original URI carries none of theHASHGATE_FILTER_PARAMS. Without anX-Original-URIheader it cannot tell, so it gates every request and logs a warning once: a missing nginx line then shows up as challenges, not as an open gate. /challenge- 200 with the interstitial page,
Cache-Control: no-store. /healthz- 200
ok.
Anything else is 404.
ENVIRONMENT
HASHGATE_LISTEN- Address and port to bind. Default
127.0.0.1:3001. Keep it on loopback:X-Real-IPis trusted only because nothing but the local nginx can reach the socket. HASHGATE_SECRET_FILE- The HMAC secret, at least 32 bytes after whitespace is removed. Used as given and never created. Unset, see SECRET.
HASHGATE_DIFFICULTY- Leading zero bits required, default
18. Each +1 doubles the expected work. 8 to 30; anything else is refused at startup. See NOTES before raising it. HASHGATE_TTL- Seconds a solved token stays valid, default
86400(24 hours). Also the cookie'smax-age. Longer is kinder to returning visitors; shorter makes a crawler that solved once pay again sooner. At least60. Changing it does not invalidate tokens already issued, which keep the expiry they were given. HASHGATE_COOKIE- Cookie name, default
hashgate. Letters, digits,_and-only. HASHGATE_LOGfull(default): a line per subrequest, plus the totals.summary: the totals andabuselines only.off: nothing but startup and errors.HASHGATE_STATS_INTERVAL- Seconds between the totals line, default
300. The same tick saves the state file and appliesHASHGATE_FORGET, so0, orHASHGATE_LOG=off, turns all three off. HASHGATE_ABUSE_AFTER- Unsolved challenges to one prefix before
abuselines start, default10.0disables them. HASHGATE_FORGET- Seconds between halvings of every prefix's challenge count, default
86400. Halving turns the count into a rate: without it any prefix that is challenged often enough, over months, crosses any threshold.0never forgets. Exemptions are never forgotten. HASHGATE_FILTER_PARAMS- Query parameter names that make
/verify-filtereddemand a token, separated by commas or spaces. Matched exactly against the keys of the original URI's query string, after decoding%XXand+the way the upstream will:%73ortissort, andsortdoes not matchsorting. Default: the Forgejo and Gitea list above. Empty is refused at startup, because/verify-filteredwould then never gate. It applies only to locations nginx sends to/verify-filtered. HASHGATE_STATE_FILE- Where the prefix counts are kept across restarts. Default
$STATE_DIRECTORY/prefixes.state; set it empty to keep them in memory. STATE_DIRECTORY- Set by systemd from
StateDirectory=. Holds the generated secret and the state file.
Under systemd, override any of these with a drop-in, systemctl edit hashgate:
[Service] Environment=HASHGATE_TTL=43200
SECRET
With no HASHGATE_SECRET_FILE, the secret is $STATE_DIRECTORY/secret, created on first start from 32 bytes of /dev/urandom with mode 0600. It is kept across restarts. With neither variable set, hashgate refuses to start.
To rotate it, stop the service, delete the file and start it again. Every outstanding token becomes invalid and every visitor is challenged once more; nothing else breaks.
To supply a secret from /etc instead, without making it readable by the service's dynamic user, hand it over as a credential in a drop-in:
[Service] LoadCredential=secret:/etc/hashgate/secret Environment=HASHGATE_SECRET_FILE=%d/secret
LOGGING
To standard error, so to the journal under the unit. Fields are key=value and never contain whitespace, so lines stay awk-able: spaces in a User-Agent become dots. uri and ua are cut to printable ASCII and capped in length, so a crafted request cannot forge a line.
hashgate: verify ip=203.0.113.9 prefix=203.0.113.0/24 verdict=ok uri=/a/b/compare/main...v1 ua=curl/8.0.1 hashgate: challenge ip=203.0.113.9 prefix=203.0.113.0/24 uri=/a/b/issues?sort=oldest ua=Mozilla/5.0.(X11;.Linux.x86_64) hashgate: abuse ip=203.0.113.9 prefix=203.0.113.0/24 reason=unsolved-challenges challenges=11 uri=/a/b/pulls?state=all ua=-
The verdicts:
ok- A solved token; admitted.
exempt- Admitted untested by
/verify-filtered. no-cookie- The ordinary first visit. It should dominate.
expired- Older than
HASHGATE_TTL. malformed- Not three dot-separated fields of the right shape.
bad-mac- Not issued by this server, for this prefix, with this expiry. Also what a visitor who moved to another prefix looks like, so not proof of anything.
bad-pow- Our challenge, without the work. A browser cannot produce this.
Every HASHGATE_STATS_INTERVAL the totals go out as one line, unless nothing changed:
hashgate: stats up=3600s challenge=482 ok=17 no-cookie=465 malformed=0 expired=0 bad-mac=3 bad-pow=1 exempt=2210 abuse=31 prefixes-challenged=84 prefixes-solved=2
prefixes-challenged against prefixes-solved is the pair to read. A pool that is being turned away shows many prefixes challenged and almost none solved. Both are capped at 50000 prefixes, and the line gains prefixes-capped=1 when that is reached.
Set LogRateLimitIntervalSec=0 on the unit, as the shipped one does, or journald drops lines under load and the counts have holes.
FILES
/usr/lib/systemd/system/hashgate.service- The unit.
DynamicUser=yes,StateDirectory=hashgate. /var/lib/hashgate/secret- The generated secret.
/var/lib/hashgate/prefixes.state- Challenge counts and exemptions per prefix, one line each, with the prefix in a trailing comment so the file can be read with less(1). It is parsed from the numeric id, never from the comment. Unparseable lines are skipped and counted in the startup line.
EXIT STATUS
0 after --version or --help. 1 when the configuration is invalid or the address cannot be bound. 2 on an unknown argument. Otherwise it runs until stopped.
EXAMPLES
The nginx side, inside a server {} block. contrib/nginx/hashgate.conf has the complete version, with the filtered route and comments.
location = /_hashgate/verify { internal; proxy_pass http://127.0.0.1:3001/verify; proxy_pass_request_body off; proxy_set_header Content-Length ""; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Original-URI $request_uri; }
location = /_hashgate/challenge { internal; proxy_pass http://127.0.0.1:3001/challenge; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Original-URI $request_uri; }
location @hashgate_open { proxy_pass http://127.0.0.1:3000; }
location ~ "^/+[^/]+/+[^/]+/+compare/+" { auth_request /_hashgate/verify; error_page 401 = /_hashgate/challenge; error_page 500 502 503 504 = @hashgate_open; proxy_pass http://127.0.0.1:3000; }
The 500 502 503 504 line makes the gate fail open: if hashgate is down, the location serves the real page instead of an error. Delete it to fail closed.
Check that it is answering:
curl -sS http://127.0.0.1:3001/healthz
NOTES
Raising HASHGATE_DIFFICULTY costs a crawler running native code almost nothing and costs every visitor in a JavaScript engine the whole increase. Measured in real browsers, 18 bits took 1-2 seconds and 19 bits 2-8. The page gives up after 60 seconds rather than appearing to hang.
Any change to the difficulty also invalidates the work in every outstanding token, which then reports bad-pow, and the shipped flagger rule scores that. Rotate the secret at the same time, and the same tokens report no-cookie instead.
At most 256 connections are handled at once; more wait in the listen backlog rather than costing a thread each. If no thread can be started at all, at TasksMax= for instance, requests are answered one at a time and the journal says so, at most once a minute.
Proof of work raises the price of a crawl; it does not make it infinite. A crawler that pays has done what the gate asks.
Without JavaScript there is no way through a gated location. Gate only what a person can do without.
SEE ALSO
flagger(8), systemd.exec(5), nginx(8)
<https://nginx.org/en/docs/http/ngx_http_auth_request_module.html>