Rate-limit login attempts and password reset emails #13

Merged
matchu merged 1 commit from armin-bot/impress:claude/codebase-security-audit-3e2fxx into main 2026-11-08 14:24:07 -08:00
Contributor

This comes out of a security audit looking for practical, likely-exploitable issues. The main finding: nothing limited password guessing. POST /users/sign_in would check passwords as fast as we could answer, so an attacker could brute-force weak passwords, or replay credentials leaked from other sites ("credential stuffing"). Similarly, POST /users/password would send unlimited reset emails to anyone's inbox.

Companion PR for Impress 2020, whose login mutation checks the same passwords: OpenNeo/impress-2020#3

What this changes

Adds Rack::Attack throttles, next to the existing pets one:

Throttle Limit Key
logins/ip 30 per 5 min client IP (IPv6 grouped by /64)
logins/account 10 per 10 min the account being logged into
password_resets/ip 10 per hour client IP (IPv6 grouped by /64)
password_resets/account 3 per hour the account whose email was entered

Throttled browser requests get redirected back to the form, with a friendly flash message. JSON requests get a 429 with Retry-After.

Screenshots: throttled login and password reset

Login form, showing the too-many-attempts message

Password reset form, showing the too-many-emails message

A few details that matter for these to actually hold up:

  • Per-account limits look up the real account, the same way Devise does. Our utf8mb3_general_ci collation treats victim, VICTIM, Victim, and Víctim as the same name. If we keyed by the raw text, an attacker would get a fresh budget for every spelling.
  • Params are read the way Rails will read them, including JSON bodies. Rack's own req.params ignores JSON, which would let {"auth_user": …} requests skip the per-account limit.
  • Values are stringified like Devise does. Devise runs to_s on whatever it gets, so {"name": 12345} logs into the account named "12345". The per-account limit has to count that too. (The review subagent caught this one.)
  • Paths: Rack::Attack already normalizes //users//sign_in/ the same way the router does. We also match the optional format suffix the router accepts (/users/sign_in.json, .html, …).
  • IPv6 is grouped by /64, because one client usually controls a whole /64 and could otherwise get a fresh limit per address.

Bug fix along the way: the existing pets throttle's HTML response crashed with NoMethodError (so users saw a 500 page), because it wrote to env['action_dispatch.request.flash_hash'], which isn't loaded yet when Rack::Attack runs. All the throttles now share a helper that loads the flash, sets the message, and commits it to the session.

Usernames are public, so a per-account limit could let someone lock a user out on purpose, just by spamming bad passwords. To prevent that, a browser that has logged into an account before is exempt from that account's limits (the per-IP limits still apply). This is OWASP's "device cookie" approach. Every successful login (password, remember-me, or NeoPass) adds the account's ID to a signed, HttpOnly known_login_device cookie, which remembers up to 5 accounts.

So a griefer can only block password login for that account from browsers it's never been used on. Even then, it's for 10 minutes at a time, and NeoPass and password reset (which signs you in directly) still work.

Tradeoffs and notes

  • The limits count every attempt, not just failures. Real users don't log in 30 times in 5 minutes, even from a shared school network, so I don't expect false positives at these numbers. Easy to tune if needed.
  • Rack::Attack stores its counters in Rails.cache, which in production is the default FileStore, and that never deletes expired entries on its own. This was already true for the pets throttle (a file per IP per 30 seconds!), and these throttles add a few more files per attacker. If tmp/cache isn't already reset by each deploy, a periodic Rails.cache.cleanup (or another cache store) would be worth adding.

Testing

  • New spec/requests/rate_limits_spec.rb (17 examples) covers:
    • per-IP and per-account limits
    • case, accent, and whitespace variants hitting the same account
    • non-string (JSON number) usernames
    • nonexistent accounts
    • IPv6 /64 grouping
    • JSON bodies and path variants
    • the 429 for JSON requests
    • known devices being exempt, but only for their own accounts
    • GETs not counting
    • password-reset limits
    • the fixed pets responder
  • Mutation-checked: separately breaking the account lookup, the /64 grouping, Rails-style param parsing, stringification, and the known-device check (dropping it, or exempting any cookie) each makes exactly its own spec fail.
  • Passes on 6 random seeds, and each new example also passes on its own.
    • That last part needed a fix. Rails 8 loads routes lazily in tests, and Devise only sets up its login strategies when routes load, so if the first request in a test run is a login, it fails. The new spec loads routes up front, with a comment. (authenticated_at_spec only avoids this by accident, because it calls a path helper first.)
  • Full suite passes: bundle exec rspec (406 examples), plus the Test::Unit tests. I also reloaded the test DB, which had a stray Item left in it that broke homepage rendering.
  • Checked in a browser on a dev server:
    • After 11 bad logins, and after 4 reset requests, the forms show the messages in the screenshots above.
    • Known devices work end to end: an attacker's browser context gets throttled, while the victim's usual browser still logs in.
  • A fresh-eyes review subagent tried path, method-override, encoding, query-string, Unicode, and JSON variants. The only bypass it found was the non-string one above, now fixed.

Audit notes: what else I checked

No other likely-exploitable issues found in this app. Here's what I covered, so it's clear what "clean" means:

  • Authorization: every controller and route. Closet hangers, lists, outfits, Neopets connections, NeoPass, account settings, deletion, and the export are all scoped to current_user. ClosetHanger#list_belongs_to_user blocks moving items into someone else's list. Staff-only actions are gated. Shadowban and list-visibility rules are applied consistently.
  • CSRF: protect_from_forgery uses :null_session, and it runs before our other callbacks, so forged requests run logged-out. OmniAuth's request phase is POST-only with CSRF protection (omniauth-rails_csrf_protection), and the OIDC state is checked.
  • Open redirects: return_to and origin params flow into redirect_to in several places. Rails 8.1's action_on_open_redirect = :raise blocks external hosts, so these can only cause a 500, not a redirect.
  • XSS: HAML auto-escaping throughout. The html_safe/raw sites only wrap escaped content (content_tag, _html translations). List descriptions go through Sanitize::Config::BASIC. The petpage output is escaped inside its <textarea>.
  • SQL injection: all user input reaches SQL as bound parameters or through sanitize_sql_like. The few interpolations only use constants.
  • SSRF / files: outbound fetches only go to URLs from our own DB (taken from Neopets), and the media archive enforces the images.neopets.com origin. The public data dump only covers modeling tables (no user data).
  • Config: force_ssl, cookie sessions, Forwarded stripped (from the earlier advisory fix), MiniProfiler restricted in production, no secrets committed.

Worth knowing, not fixed here (lower risk, or needs a bigger decision):

  • Password hashing is a single HMAC-SHA256 (config/initializers/devise.rb). That's fast to brute-force if the openneo_id DB ever leaks. Moving to bcrypt (re-hashing on login) is the real fix, but Impress 2020's login verifies these same hashes, so it needs to be coordinated with that, or with retiring Impress 2020's login.
  • The Impress 2020 support secret is one static value, shared with every support staffer via a meta tag. It unlocks support mutations there, including looking up any user's email. Removing someone from staff doesn't revoke it; only rotating the secret does.
  • Impress 2020 writes the client-supplied X-Forwarded-For into current_sign_in_ip, which our shadowban check (User#likely_is?) trusts. The only effect: a shadowbanned user could make their own listings visible to one IP of their choosing.

🤖 Generated with Claude Code

https://claude.ai/code/session_014PWWd37NNMoRcoGZrnWKEs

This comes out of a security audit looking for practical, likely-exploitable issues. The main finding: **nothing limited password guessing.** `POST /users/sign_in` would check passwords as fast as we could answer, so an attacker could brute-force weak passwords, or replay credentials leaked from other sites ("credential stuffing"). Similarly, `POST /users/password` would send unlimited reset emails to anyone's inbox. Companion PR for Impress 2020, whose `login` mutation checks the same passwords: OpenNeo/impress-2020#3 ## What this changes Adds Rack::Attack throttles, next to the existing pets one: | Throttle | Limit | Key | |---|---|---| | `logins/ip` | 30 per 5 min | client IP (IPv6 grouped by /64) | | `logins/account` | 10 per 10 min | the account being logged into | | `password_resets/ip` | 10 per hour | client IP (IPv6 grouped by /64) | | `password_resets/account` | 3 per hour | the account whose email was entered | Throttled browser requests get redirected back to the form, with a friendly flash message. JSON requests get a `429` with `Retry-After`. <details><summary>Screenshots: throttled login and password reset</summary> ![Login form, showing the too-many-attempts message](https://code.openneo.net/attachments/e3770b19-a204-490a-898d-0574a5423084) ![Password reset form, showing the too-many-emails message](https://code.openneo.net/attachments/22a052f4-79c6-4f77-a48b-efc8e43cc803) </details> A few details that matter for these to actually hold up: - **Per-account limits look up the real account**, the same way Devise does. Our `utf8mb3_general_ci` collation treats `victim`, `VICTIM`, ` Victim `, and `Víctim` as the same name. If we keyed by the raw text, an attacker would get a fresh budget for every spelling. - **Params are read the way Rails will read them**, including JSON bodies. Rack's own `req.params` ignores JSON, which would let `{"auth_user": …}` requests skip the per-account limit. - **Values are stringified like Devise does.** Devise runs `to_s` on whatever it gets, so `{"name": 12345}` logs into the account named "12345". The per-account limit has to count that too. (The review subagent caught this one.) - **Paths:** Rack::Attack already normalizes `//users//sign_in/` the same way the router does. We also match the optional format suffix the router accepts (`/users/sign_in.json`, `.html`, …). - **IPv6 is grouped by /64**, because one client usually controls a whole /64 and could otherwise get a fresh limit per address. **Bug fix along the way:** the existing pets throttle's HTML response crashed with `NoMethodError` (so users saw a 500 page), because it wrote to `env['action_dispatch.request.flash_hash']`, which isn't loaded yet when Rack::Attack runs. All the throttles now share a helper that loads the flash, sets the message, and commits it to the session. ### Lockouts and the "known device" cookie Usernames are public, so a per-account limit could let someone lock a user out on purpose, just by spamming bad passwords. To prevent that, **a browser that has logged into an account before is exempt from that account's limits** (the per-IP limits still apply). This is OWASP's "device cookie" approach. Every successful login (password, remember-me, or NeoPass) adds the account's ID to a signed, HttpOnly `known_login_device` cookie, which remembers up to 5 accounts. So a griefer can only block password login for that account from browsers it's never been used on. Even then, it's for 10 minutes at a time, and NeoPass and password reset (which signs you in directly) still work. ### Tradeoffs and notes - The limits count every attempt, not just failures. Real users don't log in 30 times in 5 minutes, even from a shared school network, so I don't expect false positives at these numbers. Easy to tune if needed. - Rack::Attack stores its counters in `Rails.cache`, which in production is the default `FileStore`, and that **never deletes expired entries on its own**. This was already true for the pets throttle (a file per IP per 30 seconds!), and these throttles add a few more files per attacker. If `tmp/cache` isn't already reset by each deploy, a periodic `Rails.cache.cleanup` (or another cache store) would be worth adding. ## Testing - New `spec/requests/rate_limits_spec.rb` (17 examples) covers: - per-IP and per-account limits - case, accent, and whitespace variants hitting the same account - non-string (JSON number) usernames - nonexistent accounts - IPv6 /64 grouping - JSON bodies and path variants - the 429 for JSON requests - known devices being exempt, but only for their own accounts - GETs not counting - password-reset limits - the fixed pets responder - **Mutation-checked:** separately breaking the account lookup, the /64 grouping, Rails-style param parsing, stringification, and the known-device check (dropping it, or exempting any cookie) each makes exactly its own spec fail. - Passes on 6 random seeds, and each new example also passes on its own. - That last part needed a fix. Rails 8 loads routes lazily in tests, and Devise only sets up its login strategies when routes load, so **if the first request in a test run is a login, it fails**. The new spec loads routes up front, with a comment. (`authenticated_at_spec` only avoids this by accident, because it calls a path helper first.) - Full suite passes: `bundle exec rspec` (406 examples), plus the Test::Unit tests. I also reloaded the test DB, which had a stray `Item` left in it that broke homepage rendering. - Checked in a browser on a dev server: - After 11 bad logins, and after 4 reset requests, the forms show the messages in the screenshots above. - Known devices work end to end: an attacker's browser context gets throttled, while the victim's usual browser still logs in. - A fresh-eyes review subagent tried path, method-override, encoding, query-string, Unicode, and JSON variants. The only bypass it found was the non-string one above, now fixed. ## Audit notes: what else I checked **No other likely-exploitable issues found in this app.** Here's what I covered, so it's clear what "clean" means: - **Authorization:** every controller and route. Closet hangers, lists, outfits, Neopets connections, NeoPass, account settings, deletion, and the export are all scoped to `current_user`. `ClosetHanger#list_belongs_to_user` blocks moving items into someone else's list. Staff-only actions are gated. Shadowban and list-visibility rules are applied consistently. - **CSRF:** `protect_from_forgery` uses `:null_session`, and it runs before our other callbacks, so forged requests run logged-out. OmniAuth's request phase is POST-only with CSRF protection (`omniauth-rails_csrf_protection`), and the OIDC `state` is checked. - **Open redirects:** `return_to` and `origin` params flow into `redirect_to` in several places. Rails 8.1's `action_on_open_redirect = :raise` blocks external hosts, so these can only cause a 500, not a redirect. - **XSS:** HAML auto-escaping throughout. The `html_safe`/`raw` sites only wrap escaped content (`content_tag`, `_html` translations). List descriptions go through `Sanitize::Config::BASIC`. The petpage output is escaped inside its `<textarea>`. - **SQL injection:** all user input reaches SQL as bound parameters or through `sanitize_sql_like`. The few interpolations only use constants. - **SSRF / files:** outbound fetches only go to URLs from our own DB (taken from Neopets), and the media archive enforces the `images.neopets.com` origin. The public data dump only covers modeling tables (no user data). - **Config:** `force_ssl`, cookie sessions, `Forwarded` stripped (from the earlier advisory fix), MiniProfiler restricted in production, no secrets committed. **Worth knowing, not fixed here** (lower risk, or needs a bigger decision): - **Password hashing is a single HMAC-SHA256** (`config/initializers/devise.rb`). That's fast to brute-force if the `openneo_id` DB ever leaks. Moving to bcrypt (re-hashing on login) is the real fix, but Impress 2020's login verifies these same hashes, so it needs to be coordinated with that, or with retiring Impress 2020's login. - **The Impress 2020 support secret is one static value**, shared with every support staffer via a meta tag. It unlocks support mutations there, including looking up any user's email. Removing someone from staff doesn't revoke it; only rotating the secret does. - **Impress 2020 writes the client-supplied `X-Forwarded-For` into `current_sign_in_ip`**, which our shadowban check (`User#likely_is?`) trusts. The only effect: a shadowbanned user could make their own listings visible to one IP of their choosing. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_014PWWd37NNMoRcoGZrnWKEs
Until now, nothing limited how many passwords a client could try at
`POST /users/sign_in`, so an attacker could guess passwords (or replay
leaked credentials from other sites) as fast as our server would answer.
Likewise, `POST /users/password` would send unlimited reset emails to any
inbox.

Now, Rack::Attack throttles both, per client IP (with IPv6 grouped by /64)
and per target account. For the per-account limits, we look up the actual
account the same way Devise does, because our database collation treats
many spellings of a name or email as equivalent (case, accents, padding):
keying by the raw text would let an attacker get a fresh limit per
spelling. Likewise, we read params the way Rails will (including JSON
bodies), stringify values like Devise does (a JSON number `12345` logs into
the account named "12345"), and match the `.json`-style format suffixes the
router accepts.

To keep the per-account limits from becoming a way to lock someone out of
their account, a browser that has logged into an account before is exempt
from that account's limits (but not the per-IP ones). We remember this
with a signed "known device" cookie, set whenever someone logs in.

While here, fix the pets throttle's HTML response: it wrote to a flash hash
that isn't loaded yet when Rack::Attack runs, so throttled pet loads got a
500 error instead of the friendly redirect. We now load and commit the
flash ourselves, and share that for the new throttles' messages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014PWWd37NNMoRcoGZrnWKEs
Owner

Yet another useful note that clearing out Impress 2020 is not only simplifying for maintenance, but practical for users! It would unblock (and mostly even resolve) everything straggling.

Yet another useful note that clearing out Impress 2020 is not only simplifying for maintenance, but practical for users! It would unblock (and mostly even resolve) everything straggling.
matchu merged commit 9a52f0dbbb into main 2026-11-08 14:24:07 -08:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
OpenNeo/impress!13
No description provided.