diff --git a/CHANGELOG.md b/CHANGELOG.md index 46c11f7f..21ea6579 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,22 +4,62 @@ The first release. Nothing is tagged yet. +### Signing In + - Sign in, sign out, registration, password resets and email verification, with your own actions and pages. -- Registration that doesn't reveal who has an account: the same answer for a free and a taken address, with new users signing in once they've verified theirs. -- Factors behind one contract: password, authenticator apps, passkeys, security keys, email codes and recovery codes, plus your own. +- Registration that doesn't reveal who has an account: the same answer for a free and a taken address, with new users signing in once they've verified theirs. `registration.reveal_taken` says when an address is taken instead. +- Factors behind one contract: password, authenticator apps, passkeys, security keys, email codes and recovery codes, plus your own. Many authenticators per user, with a default and "try another way". +- Passkeys and security keys from one WebAuthn driver: ES256 and EdDSA by default, RS256 when you ask for it, a challenge that is answered once and runs out on the server, and sign in with Laravel's `@laravel/passkeys` client. - `WebAuthn::securityKeys()->requireAttestation()` to only add hardware keys whose attestation chains to root certificates you list, and `allowOnly()` to limit them to certain models by AAGUID. -- Many authenticators per user, with a default and "try another way". -- Policies built from assurance levels, with `ifEnrolled()` and `noDowngrade()`. -- Step-up middleware: `keyring:aal2` and `keyring.fresh:15m`. -- Devices and sessions: trusted devices, new-device emails with a "this wasn't me" link, a list of the user's sessions to end one by one, and signing out everywhere else, on any session driver. A limit on sessions per account, and idle and absolute timeouts. -- "Remember me" tied to the session it was ticked for: it carries that session on and can't outlast its timeouts, a revocation or a risk response. Its cookie works once and is replaced each time. A used one sent again ends the session for everyone holding it, with a `RememberMeReused` event and a `remember_me_reused` log entry. -- Protected `email` and `password` attributes, with email changes confirmed from both addresses and revertable from the old one. -- Risk signals with an action for each level. -- A security log, "was this you?" alerts and security emails, each a notification published into your app. -- `keyring:install`, `keyring:import fortify`, `keyring:prune`, and `keyring:sign-out` to end one user's sessions or everyone's. +- Authenticator app codes that work once, with SHA-1, SHA-256 or SHA-512, and a window of one time step or none. +- Email codes as an extra step at sign in. They are opt-in and never count as a second factor. +- Recovery codes of 128 random bits, stored as keyed hashes, with a flag that says when a used set should be replaced. - `Keyring::attempt()` to start a sign in from your own route, for social logins and the like. -- `Keyring::allowSignInWhen()` to keep banned or unapproved accounts out, however they try to sign in. +- `Keyring::allowSignInWhen()` to keep banned or unapproved accounts out, however they try to sign in. The first request it refuses ends every session the account has. +- A verification pipeline you can add steps to, with the steps that enforce Keyring's guarantees protected from being removed by accident. + +### Policies and Step-Up + +- Policies built from assurance levels that follow NIST SP 800-63B-4: AAL2 needs a factor the user has, and AAL3 an attested key that can't leave its device. `ifEnrolled()` and `noDowngrade()` say how a policy treats users who can't meet it yet, or who have a passkey. +- `keyring.enrolled` to make everyone set up a second factor, which the installer adds when you pick one. +- Step-up middleware: `keyring:aal2` and `keyring.fresh:15m`, with a shared confirm flow. Changing how an account signs in takes the strongest proof the account can give. + +### Sessions and Devices + +- A registry of signed-in sessions that works on any session driver: a list of the user's sessions to end one by one, signing out everywhere else, a limit on sessions per account, and idle and absolute timeouts kept on the server. +- Assurance levels that lapse on NIST's clock, with `sessions.end_on_lapse` to end the session with its level. +- "Remember me" tied to the session it was ticked for: it carries that session on and can't outlast its timeouts, a revocation or a risk response. Its cookie works once and is replaced each time. A used one sent again ends the session for everyone holding it, with a `RememberMeReused` event and a `remember_me_reused` log entry. +- Devices: trusted devices, new-device emails with a "this wasn't me" link, and a limit on devices per account. +- `Secure`, `__Host-` prefixed cookies named for what they do (`known_device`, `remembered_session`). +- `keyring:sign-out` to end one user's sessions or everyone's. + +### Account Changes + +- Protected `email` and `password` attributes, which only change through Keyring's flows once it handles them. +- Email changes confirmed from both addresses and revertable from the old one, with the old address reserved while they can be undone. +- Password changes that take the current password, and resets that sign nobody in, end every session and leave second factors alone. +- Password rules that follow OWASP ASVS 5.0.0 and NIST SP 800-63B-4: 15 characters alone or 8 with a second factor, no composition rules, a bundled list of the most common passwords, your own context words, a breach check that can refuse what it couldn't check, and Unicode normalised to NFC. - `Keyring::requirePasswordChange()`, and a risk action of the same name, to hold a user until they choose a new password when theirs is known to someone else. -- Rate limits per account, per typed username and per IP address, with locks that double, a cap on failures in a row, and `limits.lock_after` to keep an account locked until its password is reset. -- Test helpers, a fake, factories, a virtual WebAuthn authenticator and a conformance suite. -- `@entity/keyring`, a browser package for WebAuthn, enrollment and the challenge page, with Vue and React bindings. Passkey sign in works with Laravel's `@laravel/passkeys` client too. +- Emailed links that only act on a button press, with the token or signature posted in the body, built from `APP_URL` and opened on pages that send no referrer. + +### Rate Limits and Risk + +- Rate limits per account, per typed username and per IP address, with locks that double, a count of their own for browsers the account has signed in from, a cap on failures in a row kept in the database, and `limits.lock_after` to keep an account locked until its password is reset. +- A timebox around every verification, so a refusal takes the same time whatever the reason. +- Risk signals with an action for each level: a new device, a new country, impossible travel, a session turning up in another browser, repeated failed second factors, a sign in after several failures or after a long quiet period, a recently changed email address and a password found in a breach. A new app starts with the ones its features can feed, and a password found in a breach holds its user until they choose another. + +### Logging and Emails + +- A security log with a severity and a request ID on every entry, of sign ins, failures, lockouts, changes and what was refused, capped so a refused request can't fill it. Without the table it goes to your app's log. +- "Was this you?" alerts at the next sign in. +- Security emails, each a notification published into your app. The installer registers the ones about changes to how an account signs in and about suspicious attempts, as far as your features go. +- `support_contact`, so every notice can say who to contact. +- `Keyring\Events\*` for everything above, with Laravel's own auth events raised beside them. + +### Tooling + +- `keyring:install`, which asks which sign-in methods and features you want and publishes a provider, your actions and your notifications; `keyring:import fortify`; and `keyring:prune`, scheduled daily. +- Security headers on Keyring's responses: `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY` and a referrer policy. +- Test helpers, a fake, factories, a virtual WebAuthn authenticator and a conformance suite that checks your setup still keeps Keyring's guarantees. +- `@entity/keyring`, a browser package for WebAuthn, enrollment, sessions and the challenge page, with Vue and React bindings. +- Documentation of where Keyring stands on every requirement of OWASP ASVS 5.0.0 and NIST SP 800-63B-4 that bears on it, and of each place it deliberately does something else. diff --git a/README.md b/README.md index 7aefcd89..6a026d01 100644 --- a/README.md +++ b/README.md @@ -12,11 +12,12 @@ Fortify keeps 2FA in three columns on `users`. That gives one TOTP per user, and - **Devices and sessions:** new-device events, "this wasn't me" links, a sessions list, and "sign out everywhere else". It works with **any session driver** (database, cache, file, cookie). - **Step-up:** `keyring:aal2` and `keyring.fresh:15m` middleware. A passkey or code counts, not just the password, and users with a second factor must use it. - **Protected account changes:** once Keyring handles them, `email` and `password` can only change through its flows. Email changes are confirmed from both addresses and can be reverted. -- **Risk signals:** new device, new country, impossible travel, a session cookie showing up in another browser, repeated failures. Each level maps to an action. +- **Risk signals:** new device, new country, impossible travel, a session cookie showing up in another browser, repeated failures, a password found in a breach. Each level maps to an action, and a new app starts with the signals its features can feed. - **A security log and security emails.** Every email is a notification class in your app, yours to reword, restyle or send another way. +- **Built on OWASP ASVS 5.0.0 and NIST SP 800-63B-4:** [one page](docs/owasp-asvs.md) goes through both, requirement by requirement. Each is met, or stated as a deliberate deviation or as your app's job, with the reason. - **Headless:** like Fortify, Keyring renders your pages with props and answers JSON, with swappable responses and published actions. A browser package handles WebAuthn and the challenge page for Vue and React. -Everything beyond signing in is opt-in. See [Adding Features](docs/quick-start.md#adding-features). +Every feature and sign-in method beyond the password is opt-in. See [Adding Features](docs/quick-start.md#adding-features). > Work in progress: not tagged or production-tested yet. @@ -88,7 +89,7 @@ npm install @entity/keyring - [Recipes](docs/recipes.md) - [Testing](docs/testing.md) - [Security](docs/security.md) -- [OWASP ASVS](docs/owasp-asvs.md) +- [OWASP ASVS and NIST SP 800-63B](docs/owasp-asvs.md) The [changelog](CHANGELOG.md) lists what each release changes, and the [upgrade guide](UPGRADE.md) covers anything you need to do when updating. diff --git a/config/keyring.php b/config/keyring.php index beb22866..5b2719bc 100644 --- a/config/keyring.php +++ b/config/keyring.php @@ -174,12 +174,27 @@ | | Where a user who has to choose a new password is sent from every other | page until they have: after Keyring::requirePasswordChange($user), or a - | risk response with requirePasswordChange(). Null answers 403. + | risk response with requirePasswordChange(), which is Keyring's own for + | the BreachedPassword signal. Null answers 403. | */ 'password_change_url' => null, + /* + |-------------------------------------------------------------------------- + | Support Contact + |-------------------------------------------------------------------------- + | + | Where users can reach you about their account: a page's URL or an email + | address. Every notification is handed it as $contact, and the published + | ones end with "if this wasn't you and you need help, contact us" when + | it's set. Null leaves the line out. + | + */ + + 'support_contact' => null, + /* |-------------------------------------------------------------------------- | Devices @@ -227,8 +242,8 @@ | "levels" are how long each assurance level keeps counting: past them the | user stays signed in, and routes that need the level ask them to verify | again. With "end_on_lapse" a session ends instead when the level it - | signed in at runs out, as NIST SP 800-63B words it, and "remember me" - | brings nothing back. "remember_cookie" names the cookie that ties + | signed in at runs out, as NIST SP 800-63B-4 words it (Sec. 5.2), and + | "remember me" brings nothing back. "remember_cookie" names the cookie that ties | "remember me" to the session it was ticked for: null is | remembered_session, prefixed over HTTPS like the device cookie. Each one | works once and is replaced. For "remember_grace" a browser's other @@ -299,7 +314,8 @@ | than truncate it: the real limit is then 72 bytes, which is 72 plain | characters but only 36 accented or Cyrillic ones, 24 Chinese, Japanese | or Korean ones, or 18 emoji. Set HASH_DRIVER=argon2id to take every - | password up to "max", as OWASP ASVS 6.2.9 asks (at least 64 characters). + | password up to "max": OWASP ASVS 5.0.0 (6.2.9) asks for at least 64 + | characters. | | "uncompromised" checks new passwords against Have I Been Pwned over the | network. Null runs it in production only, so local and test runs make @@ -330,9 +346,12 @@ |-------------------------------------------------------------------------- | | Signal scores add up (0-100) into a level. Pick signals and what to do at - | each level with Keyring::risk()->signals([...])->respond(fn ...). By - | default: medium asks for another factor, high also notifies, critical - | refuses the sign in, or on a signed-in request signs out every session. + | each level with Keyring::risk()->signals([...])->respond(fn ...), in + | your KeyringServiceProvider: keyring:install starts it with the signals + | your features can feed. By default: medium asks for another factor, high + | also notifies, critical refuses the sign in, or on a signed-in request + | signs out every session. A password found in a breach also holds its + | user until they choose a new one. | */ @@ -432,7 +451,7 @@ | | Default attempts per minute, per account and per IP address, and the | failures in a row one of an account's authenticators allows however - | slowly they come (100 is the most NIST SP 800-63B allows, null is no + | slowly they come (100 is the most NIST SP 800-63B-4 allows, null is no | cap). They're counted in the database, and at the cap the authenticator | is refused until a password reset or Keyring::unlock() clears it, or a | second factor is removed and added again. "consecutive_elsewhere" is diff --git a/docs/README.md b/docs/README.md index f1ecad54..160613a1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -25,8 +25,8 @@ Keyring is an authentication backend for Laravel. It handles sign in, registrati - [Risk](risk.md): risk signals and what to do about them. - [Security Log & Emails](security-log-and-emails.md): the activity log, "was this you?" alerts and security emails. - [Events](events.md): every event Keyring dispatches and what it carries. -- [Security](security.md): what Keyring guarantees, and its known limitations. -- [OWASP ASVS](owasp-asvs.md): what to turn on for each level of ASVS 5.0's authentication and session management chapters. +- [Security](security.md): what Keyring guarantees, where each choice comes from, and its known limitations. +- [OWASP ASVS and NIST SP 800-63B](owasp-asvs.md): where Keyring stands on every requirement of ASVS 5.0.0 that bears on it, what to turn on for each level, and what its assurance levels mean in NIST's terms. ## Building Your App diff --git a/docs/authenticators.md b/docs/authenticators.md index 29f4f0c0..eaf69951 100644 --- a/docs/authenticators.md +++ b/docs/authenticators.md @@ -101,16 +101,18 @@ Authenticator apps and email codes take an optional `name` when beginning or con A wrong proof fails with `keyring::keyring.invalid`, and an expired or missing enrollment, or one that was already confirmed, with `keyring::keyring.enrollment_expired`, both on the factor's field (`code`, or `credential` for passkeys and security keys). Email enrollment codes keep their guess count between tries, like email codes at sign in. -On success, the response contains the new authenticator, presented the same way as on the challenge page: +On success, the response contains the new authenticator, as its factor's `present()` gives it: ```json { "status": "authenticator-added", - "authenticator": { "factor": "totp", "id": "01JC4...", "name": "Authenticator app" }, + "authenticator": { "factor": "totp", "id": "01JC4...", "name": "Authenticator app", "createdAt": "2026-11-08T14:05:00+00:00", "lastUsedAt": null }, "recoveryCodes": ["jbsw-y3dp-ehpk-3pxp-jbsw-y3dp-eh", "..."] } ``` +`createdAt` and `lastUsedAt` are when it was added and last used to sign in or confirm, as ISO 8601 dates, for the list on your settings page: OWASP's Passkey Security Cheat Sheet has a page that manages credentials show both. The [challenge page](sign-in-flow.md#page-props) gets the same shape without them. + `recoveryCodes` is only there when Keyring generated recovery codes along with this authenticator (see below). The user's first saved authenticator becomes their default (never recovery codes). A passkey or security key that's already registered, to anyone, can't be registered again. Confirming a factor that allows only one per user (`email-code`, `recovery`) replaces the one they had. @@ -163,7 +165,7 @@ It also forgets the failures counted against it. An authenticator that failed to The password can't be removed this way. It isn't stored in `keyring_authenticators`. -Removing the user's last second factor (the last one beyond recovery codes and email codes) also needs their current password in the request as `password`. Their password may have been as short as `min_with_mfa` while it had a second factor beside it, and on its own NIST SP 800-63B asks for `min_without_mfa`. Keyring only stores a hash, so it checks the length then: a missing or wrong password, or one that's too short, gets an error on `password` asking them to change it first. +Removing the user's last second factor (the last one beyond recovery codes and email codes) also needs their current password in the request as `password`. Their password may have been as short as `min_with_mfa` while it had a second factor beside it, and on its own NIST SP 800-63B-4 asks for `min_without_mfa` (15 characters, Sec. 3.1.1.2). Keyring only stores a hash, so it checks the length then: a missing or wrong password, or one that's too short, gets an error on `password` asking them to change it first. ## Signing Out Other Sessions diff --git a/docs/configuration.md b/docs/configuration.md index 0a3ce114..5a6b3090 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -26,7 +26,7 @@ Keyring is configured in two places: - `config/keyring.php` holds values: your features, timeouts, limits, route options. - `app/Providers/KeyringServiceProvider.php` holds behaviour: which factors exist, the policy, risk responses, swapped responses and pages. These calls go in the provider's `boot()` method. -`keyring:install` publishes a short config with the options most apps change: `guard`, `username`, `home`, `features`, `registration` and `enrollment_url`. Every other option on this page keeps its default until you copy it into that file. Keyring merges your file over its defaults key by key, so you can copy just the part you change, such as `'sessions' => ['absolute' => '7d']`. Lists, like `features`, are replaced whole. `php artisan vendor:publish --tag=keyring-config` gives you the full file instead. +`keyring:install` publishes a short config with the options most apps change: `guard`, `username`, `home`, `features`, `registration`, `enrollment_url` and `support_contact`. Every other option on this page keeps its default until you copy it into that file. Keyring merges your file over its defaults key by key, so you can copy just the part you change, such as `'sessions' => ['absolute' => '7d']`. Lists, like `features`, are replaced whole. `php artisan vendor:publish --tag=keyring-config` gives you the full file instead. ## Durations @@ -164,6 +164,12 @@ More routes those users can still reach meanwhile, by route name, with `*` as a Where a user who has to choose a new password is sent from every other page until they have. Null answers `403`. See [Requiring a Password Change](protected-changes.md#requiring-a-password-change). +```php +'support_contact' => null, +``` + +Where users can reach you about their account: a page's URL (`'https://example.com/support'`) or an email address (`'support@example.com'`). Every notification is handed it as `$contact`, and the published security notices, the emailed code and the email change notice end with "If this wasn't you and you need help, contact us" and a link to it. `null` leaves the line out. See [Security Emails](security-log-and-emails.md#a-support-contact). + ```php 'enrollments' => [ 'keep_for' => '15m', @@ -263,9 +269,9 @@ See [Devices & Sessions](devices-and-sessions.md#the-session-registry). See [Password Rules](protected-changes.md#password-rules). `broker` is the password broker used for resets; `null` is your default broker. -`min_with_mfa` and `min_without_mfa` are counted in characters, and neither can be set below 8, the shortest password OWASP ASVS 6.2.1 and NIST SP 800-63B allow. With a lower one Keyring throws a `LogicException` as the app boots, and again wherever the option is read, instead of quietly using 8. +`min_with_mfa` and `min_without_mfa` are counted in characters, and neither can be set below 8, the shortest password OWASP ASVS 5.0.0 (6.2.1) and NIST SP 800-63B-4 (Sec. 3.1.1.2) allow. With a lower one Keyring throws a `LogicException` as the app boots, and again wherever the option is read, instead of quietly using 8. -`max` is counted in characters, and how much of it you get depends on the hasher. Bcrypt, Laravel's default, only reads the first 72 bytes of a password, so with bcrypt Keyring refuses anything longer instead of ignoring the end of it. That makes the real limit 72 bytes, not 128 characters: 72 plain characters, but only 36 accented or Cyrillic ones, 24 Chinese, Japanese or Korean ones, or 18 emoji. OWASP ASVS 6.2.9 asks that passwords of at least 64 characters are allowed, which bcrypt can't promise. Hash with argon2id to take every password up to `max`: +`max` is counted in characters, and how much of it you get depends on the hasher. Bcrypt, Laravel's default, only reads the first 72 bytes of a password, so with bcrypt Keyring refuses anything longer instead of ignoring the end of it. That makes the real limit 72 bytes, not 128 characters: 72 plain characters, but only 36 accented or Cyrillic ones, 24 Chinese, Japanese or Korean ones, or 18 emoji. OWASP ASVS 5.0.0 (6.2.9) asks that passwords of at least 64 characters are allowed, which bcrypt can't promise. Hash with argon2id to take every password up to `max`: ```ini HASH_DRIVER=argon2id @@ -275,13 +281,13 @@ HASH_VERIFY=false Keyring doesn't hash a password before bcrypt to get around the limit: the hashes would no longer be ones Laravel's own hasher can check. The [conformance suite](testing.md#the-conformance-suite) fails on bcrypt until you switch or say you're keeping it. -`context` is your list of words a password mustn't be made up of: the names of your organisation, products, systems, projects, departments and roles. It's the documented list OWASP ASVS 6.1.2 asks for, and Keyring always adds your app's name and what it knows about the user. See [Context-Specific Words](protected-changes.md#context-specific-words) for how they're compared. +`context` is your list of words a password mustn't be made up of: the names of your organisation, products, systems, projects, departments and roles. It's the documented list OWASP ASVS 5.0.0 (6.1.2) asks for, and Keyring always adds your app's name and what it knows about the user. See [Context-Specific Words](protected-changes.md#context-specific-words) for how they're compared. `uncompromised` checks new passwords against Have I Been Pwned over the network. The default, `null`, runs it only when the app is in production, so local development and tests make no network calls. Set `true` or `false` to choose for every environment. The check is Laravel's (`Password::uncompromised()`), and it fails open: when Have I Been Pwned can't be reached, times out or answers with an error, Laravel reports the exception and lets the password through. On those requests only the [bundled list](protected-changes.md#password-rules) of common passwords stands between a user and a breached password. -Set `refuse_unchecked` to `true` to refuse instead. Keyring then makes the request itself, the same way (only the first five characters of the password's SHA-1 leave your server), and a password it gets no answer about is refused with `keyring::keyring.password_unchecked`, which asks the user to try again in a moment. The cost is that nobody can register, or change or reset a password, while the service is unreachable from your servers. It only applies where `uncompromised` runs, and waits up to 10 seconds for an answer. +Set `refuse_unchecked` to `true` to refuse instead. Keyring then makes the request itself, the same way (only the first five characters of the password's SHA-1 leave your server), and a password it gets no answer about is refused with `keyring::keyring.password_unchecked`, which asks the user to try again in a moment. The cost is that nobody can register, or change or reset a password, while the service is unreachable from your servers. It only applies where `uncompromised` runs, and waits up to 10 seconds for an answer. It asks `api.pwnedpasswords.com` and nowhere else: a redirect isn't followed, and counts as no answer. Laravel's check goes through whatever `Illuminate\Contracts\Validation\UncompromisedVerifier` is bound in the container, so you can bind one of your own, say for a copy of the breach data you host yourself. `refuse_unchecked` doesn't use it, since a verifier can only answer yes or no: leave the option off, and have your verifier answer `false` when it can't check. @@ -351,7 +357,7 @@ The table is `Features::securityLog()`, which is on by default. Without it the s `timebox` is the minimum time a refused verification takes, so timing doesn't reveal whether an account exists or whether a password refused for another reason was right. It covers every pipeline step, so a request refused by a rate limit or by validation waits too. Verifications that go through return straight away. -`limits` are the default attempts per minute for each factor, per account and per IP address, and `consecutive`, the failures in a row one of an account's authenticators allows before it's refused for that account (`null` for no cap, and 100 is the most NIST SP 800-63B allows). Those are counted in the `keyring_failure_counts` table, and nothing brings a refused authenticator back by itself: see [At the Cap](security.md#at-the-cap). `consecutive_elsewhere` is how many of them may come from browsers the account hasn't signed in from, which keeps the rest for the owner's own. It only applies with `Features::devices()` on, and `null` keeps nothing back. `remember_names_for` is how long the cache keeps the failures in a row counted under each typed username, which is what the sign-in form answers from. +`limits` are the default attempts per minute for each factor, per account and per IP address, and `consecutive`, the failures in a row one of an account's authenticators allows before it's refused for that account (`null` for no cap, and 100 is the most NIST SP 800-63B-4 allows, Sec. 3.2.2). Those are counted in the `keyring_failure_counts` table, and nothing brings a refused authenticator back by itself: see [At the Cap](security.md#at-the-cap). `consecutive_elsewhere` is how many of them may come from browsers the account hasn't signed in from, which keeps the rest for the owner's own. It only applies with `Features::devices()` on, and `null` keeps nothing back. `remember_names_for` is how long the cache keeps the failures in a row counted under each typed username, which is what the sign-in form answers from. The per-minute counts and their locks are kept in the cache store Laravel's rate limiter uses: `cache.limiter` in `config/cache.php`, or your default store. Point it at a database or Redis store. Octane's in-memory `octane` store fills up, isn't atomic across workers and is emptied by a restart: see [Octane's Cache Store](security.md#octanes-cache-store). @@ -363,12 +369,17 @@ Keyring's form routes (registration, password reset, enrollment confirmation, em use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; +use Keyring\Support\TooManyAttempts; -RateLimiter::for('keyring', fn (Request $request) => Limit::perMinute(10)->by($request->user()?->id ?: $request->ip())); +RateLimiter::for('keyring', fn (Request $request) => Limit::perMinute(10) + ->by($request->user()?->id ?: $request->ip()) + ->response(new TooManyAttempts('keyring'))); ``` `GET /login/{factor}/options` uses its own limiter, `keyring-login-options`, which allows 60 requests a minute per IP address. Login pages fetch the options on every load for passkey autofill, and when the limit is hit autofill stops offering passkeys until the next minute. Define the same limiter to change it. +`TooManyAttempts` is what Keyring's own two limiters answer with: Laravel's usual `429`, after dispatching `Keyring\Events\RateLimited`, which the security log records as [`rate_limited`](security-log-and-emails.md#entry-types). Laravel has no event of its own for a refused request, so a limiter you define without that `response()` still limits and writes nothing to the log. + ## Messages and Translations Keyring's text lives in two translation files under the `keyring::` namespace: diff --git a/docs/devices-and-sessions.md b/docs/devices-and-sessions.md index 647776a2..273be9d3 100644 --- a/docs/devices-and-sessions.md +++ b/docs/devices-and-sessions.md @@ -65,11 +65,11 @@ An account keeps its 50 most recently seen devices (`devices.limit`). A sign in Each device records a readable name built from the user agent (the browser and the operating system, as in ":browser on :platform"), the last IP address and location, and when it was first and last seen. The user agent is never a factor. It's only a weak risk signal: `SessionFingerprintChanged` notices when a session's browser or platform changes. -A browser shared by several accounts has one cookie and a device for each account that signed in on it. Keyring only reuses a cookie that another account already has a device for. Anything else the browser sends is ignored and replaced with a new random token. Keyring can't tell which browser holds a cookie, so a value planted from another account's device is reused too, and the device counts as recognised, until a login on it proves a second factor. Every login that verifies two categories gives the browser a new cookie, so the previous one stops working. +A browser shared by several accounts has one cookie and a device for each account that signed in on it. Keyring only reuses a cookie that another account already has a device for. Anything else the browser sends is ignored and replaced with a new random token. Keyring can't tell which browser holds a cookie, so a value planted from another account's device is reused too, and the device counts as recognised, until a login on it proves a second factor. Every login that reaches AAL2 gives the browser a new cookie, so the previous one stops working. ### Trusted Devices -When `devices.trust_for` isn't `null`, the challenge page offers "don't ask again on this device" (`canTrustDevice`). Posting `trust: true` during the login marks the device trusted for that long (30 days by default), counted from the moment it's granted. It only counts when that login verified two factors, such as a password and an authenticator app's code, and, with `Features::emailVerification()` on, the email address is verified. An [emailed code](factors.md#email-codes) isn't a factor, so a login that used one beside the password isn't offered trust (`canTrustDevice` is false) and can't earn it. Sending it with the password, or after a login that only used the password, is ignored. Granting trust gives the browser a new cookie, so trust never rests on a cookie that was planted or copied before the login. Other accounts on the same browser move to the new cookie too. +When `devices.trust_for` isn't `null`, the challenge page offers "don't ask again on this device" (`canTrustDevice`). Posting `trust: true` during the login marks the device trusted for that long (30 days by default), counted from the moment it's granted. It only counts when that login reached AAL2, with a password and an authenticator app's code, say, and, with `Features::emailVerification()` on, the email address is verified. An [emailed code](factors.md#email-codes) isn't a factor, so a login that used one beside the password isn't offered trust (`canTrustDevice` is false) and can't earn it. Sending it with the password, or after a login that only used the password, is ignored. Granting trust gives the browser a new cookie, so trust never rests on a cookie that was planted or copied before the login. Other accounts on the same browser move to the new cookie too. Trust on its own changes nothing. It's for your [policy](policies.md#deciding-per-user-and-attempt) to use: @@ -83,7 +83,7 @@ Revoking a device stops trusting it. Signing out everywhere else stops trusting ### New Device Sign Ins -A sign in from a new device dispatches `Keyring\Events\NewDeviceSignedIn`. Turn on the `new_device` [security email](security-log-and-emails.md#security-emails), or send your own: +A sign in from a new device dispatches `Keyring\Events\NewDeviceSignedIn`. The `new_device` [security email](security-log-and-emails.md#security-emails) tells the user, and `keyring:install` registers it when devices are on. Or send your own: ```php use Illuminate\Support\Facades\Event; @@ -464,7 +464,7 @@ app(SessionRegistry::class)->revokeEveryone(); // everyone Keyring::unlock($user); // let a locked-out user try again ``` -`Keyring::unlock()` is the other half of looking after an account: it lifts a [risk lock](risk.md#actions) and the [sign-in lockouts](security.md#rate-limiting) on it, as a completed password reset does. To keep someone out for good, use [`Keyring::allowSignInWhen()`](sign-in-flow.md#who-may-sign-in), which also ends their sessions. +`Keyring::unlock()` is the other half of looking after an account: it lifts a [risk lock](risk.md#actions) and the [sign-in lockouts](security.md#rate-limiting) on it, as a completed password reset does. To keep someone out for good, use [`Keyring::allowSignInWhen()`](sign-in-flow.md#who-may-sign-in) and call `signOutEverywhere()` as you set your flag: by itself the gate ends the account's sessions when the first of them next makes a request. Like every sign-out that isn't the browser's own, these take effect on a session's next request [where the session middleware runs](#the-session-middleware). @@ -495,7 +495,7 @@ Ticking "remember me" asks to stay signed in on that browser between visits, so - A remembered session isn't ended by `idle`. It's ended by `remember_idle`, 14 days without a request, and by `absolute`, 30 days after the sign in, which coming back never restarts. - Once it has been unused for `idle`, it keeps nothing it proved. A browser that comes back on its cookies starts with no level at all, and one whose Laravel session outlived the two hours has every level lapsed. Either way, routes behind [`keyring:aal2`](step-up.md#raising-assurance) or [`keyring.fresh`](step-up.md#fresh-verification) ask the user to verify again, and so do Keyring's own routes for changing how someone signs in. -- So a remembered browser left unattended still opens whatever sits behind `auth` alone. Put anything that shouldn't be reachable that way behind a level or a fresh verification, or don't offer "remember me": leave the `remember` field off your login form, or set `remember_idle` to the same as `idle`. +- So a remembered browser left unattended still opens whatever sits behind `auth` alone. Put anything that shouldn't be reachable that way behind a level or a fresh verification, or don't offer "remember me": leave the `remember` field off your login form, or set `remember_idle` to the same as `idle`. NIST SP 800-63B-4 (Sec. 5.1) doesn't take a cookie in place of authentication at all, so an app that follows it leaves the checkbox out: see [Known Limitations](security.md#where-keyring-departs-from-a-standard). Set `remember_idle` no shorter than `idle`, or ticking the box would sign people out sooner. @@ -558,7 +558,7 @@ In `Keyring\Events`: |---|---| | `NewDeviceSignedIn` | `user`, `device`, and `revokeUrl($days = null)` | | `DeviceRevoked` | `user`, `device`, `reported` (whether it came from the "this wasn't me" link) | -| `SessionsRevoked` | `user`, `count`: after signing out everywhere else, ending one session, or an administrator's `keyring:sign-out` for one user | +| `SessionsRevoked` | `user`, `count`: after signing out everywhere else, ending one session, an administrator's `keyring:sign-out` for one user, or the first request refused for an account the app keeps out | | `RememberMeReused` | `user`, `session` (the `RegisteredSession` that was ended) | | `AccessRefused` | `user`, `resource` (`device`), `id`: a request to sign out a device that isn't the user's, answered with a 404 | | `LinkRefused` | `link` (the route's name), `reason` (`signature` or `expired`): a "this wasn't me" link that was refused | diff --git a/docs/events.md b/docs/events.md index 1c8c1560..2b1d6b51 100644 --- a/docs/events.md +++ b/docs/events.md @@ -48,7 +48,7 @@ No event has a password, code or token among its properties. `Attempting`, `Fact |---|---|---| | `NewDeviceSignedIn` | Someone signed in from a device the account hasn't used before. | `user`, `device`, and `revokeUrl($days = null)` (valid for `devices.report_link_for` unless you pass days) for a ["this wasn't me" link](devices-and-sessions.md#the-this-wasnt-me-link) | | `DeviceRevoked` | A device was signed out. | `user`, `device`, `reported` (true when it came from the "this wasn't me" link) | -| `SessionsRevoked` | Sessions were signed out: "sign out everywhere else", one session ended from the sessions list, or an administrator's `keyring:sign-out` for the user. | `user`, `count` | +| `SessionsRevoked` | Sessions were signed out: "sign out everywhere else", one session ended from the sessions list, an administrator's `keyring:sign-out` for the user, or the first request refused for an account [the app keeps out](sign-in-flow.md#who-may-sign-in). | `user`, `count` | | `SessionEnded` | Keyring signed a session out on its own. | `user`, `reason`: `revoked`, `expired`, `idle`, `other_user`, `reused`, `risk` or `not_allowed` | | `RememberMeReused` | A ["remember me" cookie was used twice](devices-and-sessions.md#a-cookie-used-twice), so two browsers held the same ones, and the session was ended for both. | `user`, `session` (the `RegisteredSession` that was ended: its device, IP address and user agent are those of whoever used the cookie first) | @@ -93,6 +93,7 @@ An assessment that ends in `Action::allow()` dispatches nothing. See [Risk](risk | Event | When | Properties | |---|---|---| | `AccessRefused` | A signed-in user asked for an authenticator, device or session that isn't theirs, or that doesn't exist (both get the same 404, so the event doesn't tell them apart), or opened an email verification link made for another account. | `user`, `resource` (`authenticator`, `device`, `session` or `email_verification`), `id` (what was asked for, as it was sent; for a session, its handle) | +| `RateLimited` | The form limiter refused a request to one of Keyring's routes outside the sign-in limits: registration, a reset, a change, an emailed link, or passkey options. | `user` (whoever is signed in, otherwise null), `limiter` (`keyring` or `keyring-login-options`), `route` (its name), `retryAfter` (seconds) | | `EnrollmentRefused` | A sign-in method wasn't added. | `user`, `factor`, `reason`: `invalid` (the factor turned the confirmation down: a wrong code, a key it won't take) or `not_allowed` (the account may not add one yet) | | `AuthenticatorRemovalRefused` | A sign-in method was kept, because removing it would have left the user unable to sign in the way their policy requires. | `user`, `authenticator` | | `LinkRefused` | An emailed link was refused: a change that doesn't exist, a wrong or ended token, or a signature that didn't match or had expired. | `link`, `reason` (see [Refused Links](security-log-and-emails.md#refused-links)), `user` (whose email change it was, otherwise null) | @@ -100,6 +101,21 @@ An assessment that ends in `Action::allow()` dispatches nothing. See [Risk](risk None of these changes what the person who was refused sees. Each fires every time, however often it's repeated: only the [security log](security-log-and-emails.md#refusals-that-repeat) limits how many it writes down. A form that fails ordinary validation dispatches nothing. +That makes them the place to count from. Keyring keeps no metrics of its own, so if you watch for credential stuffing, feed your counters from a listener: + +```php +use Illuminate\Support\Facades\Event; +use Keyring\Events\FactorFailed; +use Keyring\Events\Lockout; +use Keyring\Events\RateLimited; + +Event::listen(fn (FactorFailed $event) => Metrics::increment('auth.failed', ['factor' => $event->factor])); +Event::listen(fn (Lockout $event) => Metrics::increment('auth.locked_out', ['factor' => $event->factor])); +Event::listen(fn (RateLimited $event) => Metrics::increment('auth.rate_limited', ['route' => $event->route])); +``` + +`Metrics` stands for whatever your app reports to. + ## Laravel's Auth Events Keyring signs users in and out through the guard, so Laravel's `Login`, `Logout`, `Registered` and `Verified` events fire as usual. `Registered` is dispatched once the response has been sent, unless [`registration.reveal_taken`](sign-in-flow.md#registration) is on, so the verification email it sends doesn't show in how long a new address takes to answer. Like Fortify, it also dispatches these next to its own, so listeners and packages built for them keep working: diff --git a/docs/extending.md b/docs/extending.md index 89c64d91..61e5b7a4 100644 --- a/docs/extending.md +++ b/docs/extending.md @@ -47,7 +47,7 @@ This page lists them all, with where each is explained. [Recipes](recipes.md) ha | The models | `Keyring::useAuthenticatorModel()` and the other four | [The Keyring Facade](configuration.md#the-keyring-facade) | | Which attributes are protected | `protected`, `Keyring::withoutProtection()` | [Protected Changes](protected-changes.md) | -Risk signals, security notices, the security log, devices and every sign-in method but the password are off until you turn them on. +Devices, email changes and every sign-in method but the password are off until you turn them on. [Risk signals](risk.md) and [security notices](security-log-and-emails.md#security-emails) are whatever your `KeyringServiceProvider` lists: the one `keyring:install` publishes starts with a set of each, and an app without it has none. ## Replacing a Controller or Service diff --git a/docs/factors.md b/docs/factors.md index e0ba9d4a..bdd6a638 100644 --- a/docs/factors.md +++ b/docs/factors.md @@ -42,7 +42,7 @@ Keyring::factors([ ]); ``` -Without `Keyring::factors()`, Keyring uses the password alone. `keyring:install` writes the list for the methods you pick. To let users set the others up, turn on [`Features::manageAuthenticators()`](authenticators.md). NIST SP 800-63B asks for at least one phishing-resistant option, which passkeys are. +Without `Keyring::factors()`, Keyring uses the password alone. `keyring:install` writes the list for the methods you pick. To let users set the others up, turn on [`Features::manageAuthenticators()`](authenticators.md). NIST SP 800-63B-4 asks for at least one phishing-resistant option wherever AAL2 is offered (Sec. 2.2.2), which passkeys are. The list accepts class names (resolved from the container), instances, and closures that receive the container: @@ -89,7 +89,7 @@ A typed password is put in Unicode's NFC form before it's checked, like every pa Time-based one-time passwords (RFC 6238). Enrolling returns a 32 character secret, an `otpauth://` URL and an SVG QR code. -By default a code is accepted one 30 second time step either side of now (the `window` constructor argument), so one code can work for up to about 90 seconds. **That default does not meet OWASP ASVS 5.0.0 requirement 6.5.5**, which gives a TOTP a maximum lifetime of 30 seconds. Keyring keeps it because RFC 6238 (section 5.2) recommends allowing one step for clocks that have drifted and for the time a code takes to arrive, and with none a code typed near the end of its step is refused, which is a large share of honest sign ins. +By default a code is accepted one 30 second time step either side of now (the `window` constructor argument), so one code can work for up to about 90 seconds. **That default does not meet OWASP ASVS 5.0.0 requirement 6.5.5**, which gives a TOTP a maximum lifetime of 30 seconds. Keyring keeps it because RFC 6238 recommends accepting one earlier step for the time a code takes to arrive (Section 5.2) and allows a limit on clock drift either way (Section 6), and with none a code typed near the end of its step is refused, which is a large share of honest sign ins. To meet 6.5.5 to the letter, give the factor a window of zero, so a code only works during its own step: @@ -191,6 +191,8 @@ Every verification proves one or more **categories**, from `Keyring\Enums\Catego Policies count distinct categories, not verifications, so a password and a PIN together are still one factor. See [Policies](policies.md). +AAL2 and AAL3 need `Possession` among what was proved, as NIST SP 800-63B-4 does (Sec. 2.2.1): a biometric is only taken together with the authenticator it unlocks. So if you write a factor that checks something the user is, report `Inherence` only when the check was made by a device they hold, and report `Possession` with it. A factor that reports `Inherence` alone can be asked for as a second step, and the session stays at AAL1. + A factor declares the categories it expects in `categories()`, which Keyring uses to plan what to offer. The categories that count are the ones in the `Verification` returned by `verify()`. That's how a security key only counts as inherence when it actually verified the user that time. ## Writing a Code Factor @@ -328,7 +330,7 @@ The contract's methods: | `rules()` | `code` required, up to 64 characters | Validation for a verification request. Keyring checks them against the request's body, not the query string of a `POST`, so a field you require can't arrive in the URL. | | `limits($request, $attempt)` | per account and per IP, from config | Rate limits. See [Rate Limiting](security.md#rate-limiting). | | `errorKey()` | `code` | The form field failures are reported on. | -| `present($authenticator)` | `factor`, `id`, `name` | How the authenticator appears on the challenge page and in "try another way". | +| `present($authenticator)` | `factor`, `id`, `name`, `createdAt`, `lastUsedAt` | How the authenticator appears on a settings page and in the answers to adding or renaming one. The challenge page and "try another way" get the same without `createdAt` and `lastUsedAt`. | Helpers on `Keyring\Factors\Factor`: diff --git a/docs/frontend.md b/docs/frontend.md index 89c3e3f2..b284af29 100644 --- a/docs/frontend.md +++ b/docs/frontend.md @@ -284,10 +284,10 @@ await removeAuthenticator(added.authenticator.id) | Function | Does | |---|---| | `beginEnrollment(factor, data?)` | `POST /user/authenticators/{factor}`. Resolves to `{ factor, enrollment }`. | -| `confirmEnrollment(factor, enrollment, data?)` | `POST /user/authenticators/{factor}/confirm`. For `passkey` and `security-key`, runs the browser ceremony first; if the server rejects the response, the challenge is spent, so start again with `beginEnrollment()`. Resolves to `{ authenticator, recoveryCodes? }`. | +| `confirmEnrollment(factor, enrollment, data?)` | `POST /user/authenticators/{factor}/confirm`. For `passkey` and `security-key`, runs the browser ceremony first; if the server rejects the response, the challenge is spent, so start again with `beginEnrollment()`. Resolves to `{ authenticator, recoveryCodes? }`, where `authenticator` is typed `Authenticator`: `factor`, `id`, `name`, `createdAt` and `lastUsedAt`, with a factor's own extras. | | `enroll(factor, data?)` | Both, one after the other. `data` goes to both requests. | -| `renameAuthenticator(id, name)` | `PATCH` with `name`. | -| `makeDefault(id)` | `PATCH` with `default: true`. | +| `renameAuthenticator(id, name)` | `PATCH` with `name`. Resolves to `{ authenticator }`. | +| `makeDefault(id)` | `PATCH` with `default: true`. Resolves to `{ authenticator }`. | | `removeAuthenticator(id, password?, { signOutOthers }?)` | `DELETE`. Removing the user's last second factor also needs their password. `signOutOthers: true` [ends the user's other sessions](authenticators.md#signing-out-other-sessions) too; when adding, pass `sign_out_others: true` in `data` to `confirmEnrollment()` or `enroll()`. | | `isWebAuthn(enrollment)` | Whether `confirmEnrollment()` runs the browser ceremony: true when the server sent WebAuthn creation options, whatever the factor's key. | @@ -387,13 +387,15 @@ If you registered the routes yourself, override the ones you moved: ```ts configureRoutes({ - enroll: factor => `/account/authenticators/${factor}`, - confirmEnrollment: factor => `/account/authenticators/${factor}/confirm`, - authenticator: id => `/account/authenticators/${id}`, + enroll: factor => `/account/authenticators/${encodeURIComponent(factor)}`, + confirmEnrollment: factor => `/account/authenticators/${encodeURIComponent(factor)}/confirm`, + authenticator: id => `/account/authenticators/${encodeURIComponent(id)}`, }) ``` -The keys are `prefix`, `login`, `loginOptions`, `loginWith`, `challenge`, `verify`, `send`, `challengeBase`, `enroll`, `confirmEnrollment` and `authenticator`. `challengeBase(purpose)` is the prefix the challenge routes share (`/login/challenge` for `login`, `/confirm` for `confirm`), so changing it moves all three. An override is used as written, without the `prefix`: +The keys are `prefix`, `login`, `loginOptions`, `loginWith`, `challenge`, `verify`, `send`, `challengeBase`, `enroll`, `confirmEnrollment`, `authenticator`, `sessions` and `session`. `challengeBase(purpose)` is the prefix the challenge routes share (`/login/challenge` for `login`, `/confirm` for `confirm`), so changing it moves all three. + +Keyring's own paths put a factor's key or an ID in as one encoded path segment, and throw a `TypeError` for `.` and `..`, which a browser resolves away however they're written. So a value that isn't what the server issued, with a `/` or a `?` in it, can't send the request and the user's cookies to another path. An override is used as written, without the `prefix`, so encode what yours is given too: ```ts configureRoutes({ diff --git a/docs/installation.md b/docs/installation.md index 0e270d4a..e8c02ff8 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -40,7 +40,7 @@ The command asks four things: 1. **Which sign-in methods besides the password?** None by default. Recovery codes come with any of them. Email codes are listed as what they are, an extra step at sign in and not a second factor: a password and an emailed code is still AAL1 (see [Email Codes](factors.md#what-turning-email-codes-on-means)), and the provider says so above their line. 2. **Require a second factor for everyone?** Asked when you picked an authenticator app, passkeys or security keys, and yes by default. Users still sign in with what they have, then every page sends them to `/settings/security` until they've set one up (see [Requiring a Second Factor](policies.md#requiring-a-second-factor)). It isn't asked with the password alone or with only email codes, where nobody could meet it: then nothing requires a second factor. 3. **Which features?** Registration, password resets, email verification, changing the password and the security log by default, plus managing sign-in methods when you picked one. Registration always brings email verification, because by default [new users sign in once they've verified their address](sign-in-flow.md#without-revealing-who-has-an-account). -4. **Email users when their password, sign-in methods or email address change?** Yes by default: password changed, sign-in method added or removed, recovery code used, new recovery codes made, email address changed and account locked. +4. **Email users when their password, sign-in methods or email address change?** Yes by default: password changed, sign-in method added or removed, recovery code used, new recovery codes made, email address changed, account locked and a suspicious sign in or session, and with the features that give them something to announce, a sign in on a new device (devices), a second factor that failed after the right password (any sign-in method besides the password) and an email change undone (email changes). See [Security Emails](security-log-and-emails.md#security-emails). Without prompts (`--no-interaction`, or in CI) you get the same defaults. You can also answer with options: @@ -60,11 +60,11 @@ If you're moving from Fortify, read [Upgrading From Fortify](upgrading-from-fort | File | What it is | |---|---| -| `config/keyring.php` | A short config: the guard, username, home, your features, how registration answers and your enrollment page. Every other option keeps Keyring's default; copy any from [Configuration](configuration.md) to change it. | +| `config/keyring.php` | A short config: the guard, username, home, your features, how registration answers, your enrollment page and your support contact. Every other option keeps Keyring's default; copy any from [Configuration](configuration.md) to change it. | | `database/migrations/*_create_keyring_*_table.php` | Seven tables: `keyring_authenticators`, `keyring_devices`, `keyring_sessions`, `keyring_pending_changes`, `keyring_events`, `keyring_failure_counts` and `keyring_password_holds`. They're all created, so turning a feature on later needs no new migration. Tables for features you don't use stay empty. | -| `app/Providers/KeyringServiceProvider.php` | Where you register sign-in methods, the policy, your actions and your emails. It lists the sign-in methods you picked, adds the `keyring.enrolled` middleware when a second factor is required, and it's added to `bootstrap/providers.php` for you. | +| `app/Providers/KeyringServiceProvider.php` | Where you register sign-in methods, the policy, the risk signals, your actions and your emails. It lists the sign-in methods you picked, adds the `keyring.enrolled` middleware when a second factor is required, turns on the [risk signals](risk.md) your features can feed and lists the rest commented out, and it's added to `bootstrap/providers.php` for you. | | `app/Actions/Keyring/*.php` | Your code for the features that need it, all published and registered so a feature works as soon as you turn it on: registration (`CreateNewUser`), password resets (`ResetUserPassword`), password changes (`UpdateUserPassword`), email change requests (`ValidateEmailChange`), and the password rules they share (`PasswordValidationRules`). Keyring does the security work around them. | -| `app/Notifications/Keyring/*.php` | Every email Keyring sends, as ordinary Laravel notifications that are yours to reword, restyle or send another way. The ones a flow needs are registered, and so are the security notices about changes unless you said no to them; the rest are listed commented out. See [Security Emails](security-log-and-emails.md#security-emails). | +| `app/Notifications/Keyring/*.php` | Every email Keyring sends, as ordinary Laravel notifications that are yours to reword, restyle or send another way. The ones a flow needs are registered, and so are the security notices unless you said no to them; one with nothing to announce until a feature is on is listed commented out. See [Security Emails](security-log-and-emails.md#security-emails). | You can publish files on their own with the `keyring-config`, `keyring-migrations` and `keyring-lang` tags. `keyring-config` publishes the full config file, with every option and its default: diff --git a/docs/owasp-asvs.md b/docs/owasp-asvs.md index 78396b8e..bacd8e6f 100644 --- a/docs/owasp-asvs.md +++ b/docs/owasp-asvs.md @@ -1,4 +1,4 @@ -# OWASP ASVS +# OWASP ASVS and NIST SP 800-63B - [Introduction](#introduction) - [What a Default Install Gives You](#what-a-default-install-gives-you) @@ -8,47 +8,58 @@ - [Requirement by Requirement](#requirement-by-requirement) - [V6 Authentication](#v6-authentication) - [V7 Session Management](#v7-session-management) + - [The Other Chapters](#the-other-chapters) +- [NIST SP 800-63B-4](#nist-sp-800-63b-4) + - [What Keyring's Levels Mean](#what-keyrings-levels-mean) + - [Section by Section](#section-by-section) +- [The OWASP Cheat Sheets](#the-owasp-cheat-sheets) - [What Is Left to Your App](#what-is-left-to-your-app) ## Introduction -This page says what to turn on to meet the [OWASP Application Security Verification Standard 5.0.0](https://github.com/OWASP/ASVS/tree/v5.0.0_release/5.0) in the two chapters Keyring covers: V6 Authentication and V7 Session Management. It has a setup for each of ASVS's three levels, then every requirement in both chapters with what Keyring does about it and what's left for you. +This page says where Keyring stands against three things: the [OWASP Application Security Verification Standard 5.0.0](https://github.com/OWASP/ASVS/tree/v5.0.0/5.0), [NIST SP 800-63B-4](https://pages.nist.gov/800-63-4/sp800-63b.html), and the OWASP cheat sheets on authentication. For ASVS it has a setup for each of the three levels, then every requirement in V6 Authentication and V7 Session Management, then the requirements in the other chapters that bear on an authentication package. For NIST it says what Keyring's AAL1, AAL2 and AAL3 mean and what your app has to supply for each. -ASVS verifies an application, not a package. Keyring can meet a requirement, give you the means to, or have nothing to do with it, and the tables below say which: +Both standards verify an application or a service, not a package. Keyring can meet a requirement, give you the means to, do something else on purpose, or have nothing to do with it. The tables say which: | | Means | |---|---| | **Met** | Keyring does it whatever you configure. | -| **Met by default** | Keyring does it as installed. The row says which option or edit would undo it. | +| **Met by default** | Keyring does it as installed. The row says which option or edit would undo it. Unless the row says so, nothing refuses or warns about that change. | | **Needs setup** | Keyring can do it once you turn something on. The row says what. | -| **Partly** | Keyring covers some of it. The row says what's missing and what to do instead. | +| **Partly** | Keyring covers some of it. The row says what's missing and what to do about it. | +| **Deviates** | Keyring does something else, on purpose. The row says what, why, and how to meet the requirement to the letter where you can. | | **Yours** | It's about your pages, your process or your infrastructure. | -| **Not met** | Keyring doesn't do it and has no option for it. | | **N/A** | Keyring has nothing the requirement applies to. | -Each level includes the ones below it. The other ASVS chapters (TLS, input validation, access control, your own pages' headers and so on) are your app's throughout. +"As installed" means `php artisan keyring:install` with its default answers, and the defaults in `config/keyring.php`. Each ASVS level includes the ones below it. ## What a Default Install Gives You `php artisan keyring:install` with every default accepted, or with `--no-interaction`, sets up: - the password as the only sign-in method, with [Keyring's password rules](protected-changes.md#password-rules), -- `Features::registration()`, `resetPasswords()`, `emailVerification()`, `updatePasswords()` and `securityLog()`, +- five features: `registration`, `reset-passwords`, `email-verification`, `update-passwords` and `security-log`, - [registration that doesn't reveal who has an account](sign-in-flow.md#without-revealing-who-has-an-account), -- the emails that tell users their password, sign-in methods, recovery codes or email address changed, that a recovery code was used, or that their account was locked, -- rate limits, the timebox, the session registry and a 30 day limit on every session. +- eight [security emails](security-log-and-emails.md#security-emails): password changed, sign-in method added, sign-in method removed, recovery code used, new recovery codes, email address changed, account locked, and suspicious activity, +- three [risk signals](risk.md): a session turning up in another browser, repeated failed second factors, and a sign in that follows several failures, +- rate limits, the timebox, the session registry, and on every session a two hour inactivity limit (14 days for a browser that ticked "remember me"), a 30 day limit overall and a limit of 100 sessions per account. -That covers Level 1, apart from what your own pages have to do. Nothing in it asks for a second factor, because there isn't one to set up: pick one when installing and the installer's next question, "Require a second factor for everyone?", defaults to yes. +That covers Level 1, apart from what your own pages have to do and two things below: passwords are normalised before they're hashed ([6.2.8](#v62-password-security)), and an account you disable should be signed out everywhere by your own code ([7.4.2](#v74-session-termination)). + +It doesn't cover Level 2. Nothing in it asks for a second factor, because there isn't one to set up. That is the one thing you have to choose: pick a second sign-in method when installing and the installer's next question, "Require a second factor for everyone?", defaults to yes ([6.3.3](#v63-general-authentication-security)). + +An app that doesn't use the published `KeyringServiceProvider` gets the config defaults and nothing else: no security emails and no risk signals until it registers some. ## Level 1 Start from the default install, then: -1. Keep a server-side session driver (`SESSION_DRIVER=database`, Laravel's default, or `redis` or `file`). The `cookie` driver can't destroy an old session ([7.2.4](#v72-fundamental-session-management-security)). -2. Keep the rate limiter's cache store (`cache.limiter`, or your default) somewhere that holds its keys between requests and that your deploys don't clear, such as a database or Redis store and not [Octane's `octane` store](security.md#octanes-cache-store): the limits, the locks, sent codes and answered WebAuthn challenges all live there ([6.3.1](#v63-general-authentication-security)). +1. Keep a server-side session driver (`SESSION_DRIVER=database`, Laravel's default, or `redis` or `file`). The `cookie` driver has nothing on the server to destroy, so Keyring ends an old copy through its registry instead, which doesn't reach a sign in that isn't finished ([7.2.4](#v72-fundamental-session-management-security)). +2. Keep the rate limiter's cache store (`cache.limiter`, or your default) somewhere that holds its keys between requests and that your deploys don't clear, such as a database or Redis store and not [Octane's `octane` store](security.md#octanes-cache-store): the per-minute limits, their locks, sent codes and answered WebAuthn challenges live there. Failures in a row, and the cap, are in your database ([6.3.1](#v63-general-authentication-security)). 3. Build your forms so passwords are masked and can be pasted and filled by a password manager ([6.2.6, 6.2.7](#v62-password-security)). 4. Give users a form that posts to `PUT /user/password` ([6.2.2](#v62-password-security)). -5. Put a sign-out button on every signed-in page, though ASVS only asks for it from Level 2. +5. Where your app disables an account, call `app(Sessions::class)->signOutEverywhere($user)` as you set the flag ([7.4.2](#v74-session-termination)). +6. Put a sign-out button on every signed-in page, though ASVS only asks for it from Level 2. Don't turn on `registration.reveal_taken`, add composition rules to the password, or remove a [mandatory pipeline step](sign-in-flow.md#mandatory-steps). @@ -56,7 +67,7 @@ Don't turn on `registration.reveal_taken`, add composition rules to the password Everything in Level 1, and: -1. **Require a second factor.** Install with an authenticator app, passkeys or security keys and answer yes to "Require a second factor for everyone?", or set it up yourself ([Requiring a Second Factor](policies.md#requiring-a-second-factor)): +1. **Require a second factor** ([6.3.3](#v63-general-authentication-security)). Install with an authenticator app, passkeys or security keys and answer yes to "Require a second factor for everyone?", or set it up yourself ([Requiring a Second Factor](policies.md#requiring-a-second-factor)): ```php // app/Providers/KeyringServiceProvider.php @@ -80,38 +91,39 @@ Everything in Level 1, and: Features::emailVerification(), Features::updatePasswords(), Features::manageAuthenticators(), - Features::devices(), Features::securityLog(), ], 'enrollment_url' => '/settings/security', ``` -2. **Hash with argon2id**, so a 64 character password in any script is accepted ([6.2.9](#v62-password-security)). The [conformance suite](testing.md#the-conformance-suite) fails on bcrypt until you do, or say you're keeping it: +2. **Decide about "remember me".** `keyring.enrolled` checks what the account has, not what the session proved, and a remembered browser comes back signed in with nothing proved. If every page needs two factors, put `keyring:aal2` on your routes or set `sessions.end_on_lapse`, and leave the checkbox off your login form ([An App Whose Every Page Needs AAL2](recipes.md#an-app-whose-every-page-needs-aal2)). + +3. **Hash with argon2id**, so a 64 character password in any script is accepted ([6.2.9](#v62-password-security)). Keyring doesn't change your hasher for you. The [conformance suite](testing.md#the-conformance-suite) fails on bcrypt until you do, or say you're keeping it: ```ini HASH_DRIVER=argon2id ``` -3. **Set an inactivity timeout** ([7.3.1](#v73-session-timeout)). Keyring ships without one: +4. **Accept authenticator app codes for 30 seconds only** ([6.5.5](#v65-general-multi-factor-authentication-requirements)). In `Keyring::factors()`, in place of `Totp::class`: ```php - 'sessions' => [ - 'idle' => '30m', - ], + fn ($app) => $app->make(Totp::class, ['window' => 0]), ``` -4. **Accept authenticator app codes for 30 seconds only** ([6.5.5](#v65-general-multi-factor-authentication-requirements)). In `Keyring::factors()`, in place of `Totp::class`: +5. **Check the inactivity timeout** ([7.3.1](#v73-session-timeout)). Keyring ships with two hours, and 14 days for a browser that ticked "remember me". Shorten either to what your risk analysis says: ```php - fn ($app) => $app->make(Totp::class, ['window' => 0]), + 'sessions' => [ + 'idle' => '30m', + ], ``` -5. **Turn on `Features::devices()`**, so users can see where they're signed in and sign out elsewhere ([7.4.3, 7.5.2](#v75-defenses-against-session-abuse)), and offer "sign out everywhere else" after a sign-in method is added or removed. -6. **Write down** your list of words a password must not be made up of and put it in `passwords.context` ([6.1.2, 6.2.11](#v62-password-security)), your session timeouts and why you chose them ([7.1.1](#v71-session-management-documentation)), and that an account may have any number of sessions ([7.1.2](#v71-session-management-documentation)). -7. **Give administrators a way to end a user's sessions** ([7.4.5](#v74-session-termination)), and a process for someone who has lost their second factor and their recovery codes ([6.4.4](#v64-authentication-factor-lifecycle-and-recovery)). +6. **Show users their sessions** ([7.5.2](#v75-defenses-against-session-abuse)): build the page from `GET /user/sessions`, and send `sign_out_others` with a new or removed sign-in method ([7.4.3](#v74-session-termination)). No feature is needed. +7. **Write down** your list of words a password must not be made up of and put it in `passwords.context` ([6.1.2, 6.2.11](#v62-password-security)), your session timeouts and why you chose them ([7.1.1](#v71-session-management-documentation)), and how many sessions an account may have (100 unless you change `sessions.max`, the oldest ended first) ([7.1.2](#v71-session-management-documentation)). +8. **Decide who may run `php artisan keyring:sign-out`** ([7.4.5](#v74-session-termination)), and a process for someone who has lost their second factor and their recovery codes ([6.4.4](#v64-authentication-factor-lifecycle-and-recovery)). -Email codes meet Keyring's `aal2` at sign in but not NIST's, and Level 3 rules them out. Leave `EmailCode::asSecondFactor()` out unless you need it. +Email codes count toward no assurance level: a password and an emailed code is an AAL1 session, in Keyring's levels as in NIST's, and doesn't pass `keyring:aal2` or `keyring.enrolled`. Level 3 rules them out altogether. Leave `EmailCode::asSecondFactor()` out unless you need it. ## Level 3 @@ -141,22 +153,12 @@ Everything in Level 2, and: With `ifEnrolled()` a new user signs in with their password, and `keyring.enrolled:aal3` keeps them on your enrollment page until they've added a key; from then on they need it every time. Drop `ifEnrolled()` if you hand out keys before an account first signs in. See [Requiring Attestation](passkeys.md#requiring-attestation). Without attestation, "hardware" is only what the key says about itself. 2. **No email codes, and no SMS** ([6.3.6](#v63-general-authentication-security), [6.6.1](#v66-out-of-band-authentication-mechanisms)). Don't register `EmailCode::asSecondFactor()` or an SMS factor of your own. Recovery codes can't meet `aal3` either, so a lost key goes to your support process. -3. **Tell users about suspicious sign ins** ([6.3.5](#v63-general-authentication-security)). Register the notices the installer leaves commented out, keep the security log on, and pick [risk signals](risk.md) with a response that notifies, as [Telling the User](risk.md#telling-the-user) shows for a sign in after a long quiet period or after several failures: - - ```php - Keyring::notifications([ - 'new_device' => Notifications\NewDevice::class, - 'second_factor_failed' => Notifications\SecondFactorFailed::class, - 'suspicious_activity' => Notifications\SuspiciousActivity::class, - 'clone_suspected' => Notifications\CloneSuspected::class, - 'email_change_reverted' => Notifications\EmailChangeReverted::class, - ]); - ``` - +3. **Tell users about suspicious sign ins** ([6.3.5](#v63-general-authentication-security)). Turn on `Features::devices()`, which brings the `new_device` notice and the `NewDevice` and `InactiveAccount` signals in a new install; in an existing one, uncomment them in your `KeyringServiceProvider`. Keep the security log on. Then have your risk response notify for a sign in after a long quiet period or after several failures, as [Telling the User](risk.md#telling-the-user) shows: by itself each of those only asks for a second factor. For a sign in from an unusual place, bind a [locator](devices-and-sessions.md#locations) and add `NewCountry` or `ImpossibleTravel`. 4. **Keep the default registration** ([6.3.8](#v63-general-authentication-security)): `registration.reveal_taken` stays `false`. 5. **Ask again before your most sensitive operations** ([7.5.3](#v75-defenses-against-session-abuse)): `keyring:aal3` or `keyring.fresh:5m` on those routes. AAL3 lapses after 15 minutes idle or 12 hours. -6. **Shorten the inactivity timeout** to what your risk analysis says, 15 minutes being NIST's figure for AAL3. +6. **Shorten the inactivity timeout** to what your risk analysis says, 15 minutes being NIST's figure for AAL3, and set `sessions.end_on_lapse`, so a session ends when AAL3 runs out instead of carrying on at a lower level. 7. **Restrict who can write** to `keyring_authenticators` and to your attestation root files ([6.7.1](#v67-cryptographic-authentication-mechanism)). +8. **Put a bot check in front of your forms** if your risk analysis calls for one ([2.4.2](#the-other-chapters)). Keyring has none: see [Bot Checks](security.md#bot-checks). ## Requirement by Requirement @@ -168,37 +170,37 @@ Everything in Level 2, and: |---|---|---|---| | 6.1.1 Rate limiting and lockout are documented | 1 | Met | Keyring's are in [Rate Limiting](security.md#rate-limiting), with how they avoid locking the owner out. Your own security documentation can point there; write down any limit you change. | | 6.1.2 A documented list of context-specific words | 2 | Yours | Write the list: the names of your organisation, products, systems, projects and teams. It goes in `passwords.context`, and [Context-Specific Words](protected-changes.md#context-specific-words) documents what Keyring adds to it. | -| 6.1.3 Every authentication pathway is documented | 2 | Met | Keyring's are in [The Sign In Flow](sign-in-flow.md). Add your own: a social login, or anywhere you call `Auth::login()`. | +| 6.1.3 Every authentication pathway is documented | 2 | Met | Keyring's are in [The Sign In Flow](sign-in-flow.md), with ["remember me"](devices-and-sessions.md#remember-me) and sessions your own `Auth::login()` starts in [Devices & Sessions](devices-and-sessions.md#the-session-middleware). Add your own: a social login, or anywhere you call `Auth::login()`. | #### V6.2 Password Security | | Level | | What to do | |---|---|---|---| -| 6.2.1 At least 8 characters | 1 | Met by default | 15 without a second factor, 8 with one, and Keyring throws on a configured minimum under 8. Keep `PasswordRules::for()` in your published actions. | -| 6.2.2 Users can change their password | 1 | Met by default | `Features::updatePasswords()` is on in a default install. Build the form that posts to [`PUT /user/password`](protected-changes.md#changing-the-password). | +| 6.2.1 At least 8 characters | 1 | Met by default | 15 without a second factor, 8 with one, and Keyring throws at boot on a configured minimum under 8. The rules run in your published actions, which are yours to edit: keep `PasswordRules::for()` in them. | +| 6.2.2 Users can change their password | 1 | Met by default | `Features::updatePasswords()` is on in a default install, and taking it out removes the route. Build the form that posts to [`PUT /user/password`](protected-changes.md#changing-the-password). | | 6.2.3 A change needs the current and the new password | 1 | Met | Keyring checks `current_password` itself, whatever your action does. A user with no password, who signs in with a passkey alone, sets one with a fresh verification. | -| 6.2.4 Checked against at least the top 3,000 passwords | 1 | Met by default | The bundled list holds the 10,000 most common passwords of 8 characters or more and the 3,000 most common of 15 or more, and runs in every environment. Keep `PasswordRules::for()` in your published actions. | +| 6.2.4 Checked against at least the top 3,000 passwords | 1 | Met by default | The bundled list holds the 10,000 most common passwords of 8 characters or more and the 3,000 most common of 15 or more, and runs in every environment. Keep `PasswordRules::for()` in your published actions. The list is cut for minimums up to 15: raise `min_without_mfa` past that and fewer than 3,000 of its entries are long enough to matter (1,775 of 16 or more). | | 6.2.5 No composition rules | 1 | Met by default | Don't add `mixedCase()`, `numbers()` or `symbols()` through the rules' `$adjust` callback. A longer minimum is fine. | | 6.2.6 Password fields are masked | 1 | Yours | Use `type="password"` on your forms. A "show" toggle is allowed. | | 6.2.7 Paste and password managers are permitted | 1 | Yours | Don't block paste, and set `autocomplete="current-password"` or `"new-password"`. Keyring's browser package touches neither. | -| 6.2.8 The password is verified exactly as typed | 1 | Met | Nothing is cut short or has its case changed. Keyring does put a password in Unicode's NFC form before hashing or checking it, as NIST SP 800-63B recommends, so the same password matches from every keyboard. | -| 6.2.9 Passwords of at least 64 characters are permitted | 2 | Needs setup | Set `HASH_DRIVER=argon2id`. With bcrypt, Laravel's default, Keyring refuses anything over 72 bytes rather than cut it short, which turns away 64 characters of accented or non-Latin text. The conformance suite flags bcrypt. | +| 6.2.8 The password is verified exactly as received | 1 | Deviates | Nothing is cut short or has its case changed. Keyring does put a password in Unicode's NFC form before hashing or checking it, as NIST SP 800-63B-4 recommends (Sec. 3.1.1.2). That is a change the requirement's wording doesn't allow for, made so the same password matches from every keyboard. It can't be turned off. | +| 6.2.9 Passwords of at least 64 characters are permitted | 2 | Deviates | With bcrypt, Laravel's default, Keyring refuses anything over 72 bytes rather than cut it short, which turns away 64 characters of accented or non-Latin text. It doesn't pre-hash to fit, because Laravel's own hasher couldn't check the result. Set `HASH_DRIVER=argon2id` to meet the requirement: Keyring doesn't change your hasher for you. The conformance suite flags bcrypt. | | 6.2.10 No periodic rotation | 2 | Met | Keyring has no password expiry. Don't add one. | -| 6.2.11 The context word list is enforced | 2 | Needs setup | Put your list (6.1.2) in `passwords.context`. Keyring refuses a password made up of nothing but listed words, the app's name, the user's name, the name part of their email address and their organisation's part of its domain, with digits and punctuation taken out and look-alike spellings such as `k3yr1ng` read as letters. A longer passphrase that only has one of them in it passes. | +| 6.2.11 The context word list is enforced | 2 | Met by default | The check is on, and knows your app's name, the user's name, the name part of their email address and their organisation's part of its domain. Your own list (6.1.2) is empty until you put it in `passwords.context`. Keyring refuses a password made up of nothing but listed words, with digits and punctuation taken out and look-alike spellings such as `k3yr1ng` read as letters. A longer passphrase that only has one of them in it passes, by design. | | 6.2.12 Checked against breached passwords | 2 | Met by default | In production, through Have I Been Pwned. `passwords.uncompromised => false` turns it off, and `true` runs it everywhere. Laravel's check lets a password through when the service can't be reached: set `passwords.refuse_unchecked` to refuse it instead. | #### V6.3 General Authentication Security | | Level | | What to do | |---|---|---|---| -| 6.3.1 Credential stuffing and brute force controls | 1 | Met by default | Per account, per typed username, per IP address and in a row, all inside the timebox. Keep the `limits` options near their defaults, and keep the limiter's cache store somewhere that holds its keys and that your deploys don't clear. See [Rate Limiting](security.md#rate-limiting). | +| 6.3.1 Credential stuffing and brute force controls | 1 | Met by default | Per account, per typed username, per IP address and in a row, all inside the timebox. Every number is an option with no floor: keep the `limits` options near their defaults (`consecutive => null` removes the cap), and keep the limiter's cache store somewhere that holds its keys and that your deploys don't clear. Removing the pipeline step fails the conformance suite. See [Rate Limiting](security.md#rate-limiting). | | 6.3.2 No default accounts | 1 | Met | Keyring creates no users. Don't seed any in production. | -| 6.3.3 Multi-factor authentication is required; a hardware factor at Level 3 | 2 | Needs setup | Level 2: a second factor registered and `keyring.enrolled`, which the installer sets up when you answer yes to requiring one. Level 3: `Requirement::aal3()`, `keyring.enrolled:aal3` and `requireAttestation()`. See [Level 2](#level-2) and [Level 3](#level-3). Until a user enrolls they are signed in, and held at your enrollment page. | -| 6.3.4 No undocumented pathways, and consistent strength across them | 2 | Met | Every sign in runs one pipeline. Start a social login with [`Keyring::attempt()`](sign-in-flow.md#starting-a-sign-in-yourself) rather than `Auth::login()`, which registers a session at no assurance level. | -| 6.3.5 Users are notified of suspicious authentication attempts | 3 | Needs setup | Register the `new_device`, `second_factor_failed`, `suspicious_activity` and `clone_suspected` notices, turn on `Features::devices()`, keep `Features::securityLog()`, and pick [risk signals](risk.md), among them `InactiveAccount` and `SuccessAfterFailures`, with a response that notifies ([Telling the User](risk.md#telling-the-user)). `account_locked`, which a default install registers, is only sent with `limits.lock_after`; an ordinary lockout that lifts by itself emails nobody, so listen for `Lockout` if you want to. | -| 6.3.6 Email isn't an authentication factor | 3 | Met by default | Don't register `EmailCode::asSecondFactor()`. | -| 6.3.7 Users are notified when authentication details change | 3 | Met by default | A default install mails a changed or reset password, a sign-in method added or removed, new recovery codes, a recovery code used and a changed email address. Also register `email_change_reverted`. Renaming a sign-in method or changing the default one sends nothing. Each kind is capped at five an hour per account, with every event still in the security log. Installing with `--no-emails` turns them off. | -| 6.3.8 Valid users can't be deduced from sign in, registration or forgot password | 3 | Met by default | All three answer the same for every address, in the same time. Keep `registration.reveal_taken` off. A username of your own that must be unique will still say when it's taken. See [Registration](sign-in-flow.md#without-revealing-who-has-an-account). | +| 6.3.3 Multi-factor authentication is required; a hardware factor at Level 3 | 2 | Needs setup | A default install has no second factor to require. Level 2: a second factor registered and `keyring.enrolled`, which the installer sets up when you pick one and answer yes to requiring it. Level 3: `Requirement::aal3()`, `keyring.enrolled:aal3` and `requireAttestation()`. See [Level 2](#level-2) and [Level 3](#level-3). Until a user enrolls they are signed in, and held at your enrollment page. `keyring.enrolled` checks the account, not the session: see "remember me" in [Level 2](#level-2). | +| 6.3.4 No undocumented pathways, and consistent strength across them | 2 | Met | Every proof runs one pipeline. Three things don't go through it: "remember me", which carries a session on at no level; registration with `registration.reveal_taken`, which signs the new user in on their password without asking the policy; and your own `Auth::login()`, registered at no level. Start a social login with [`Keyring::attempt()`](sign-in-flow.md#starting-a-sign-in-yourself) instead. | +| 6.3.5 Users are notified of suspicious authentication attempts | 3 | Partly | A default install emails `account_locked`, when the password or a passkey is refused until a reset (at the cap on failures in a row, or sooner with `limits.lock_after`; an ordinary lockout that lifts by itself emails nobody), and `suspicious_activity`, when what the risk signals find adds up to a level that notifies. It adds `second_factor_failed` once you pick a sign-in method besides the password, and `new_device` with `Features::devices()`. Left to you: a sign in after a long quiet period or after several failures is found (`InactiveAccount`, `SuccessAfterFailures`) but each alone only asks for a second factor, so have your response notify for them ([Telling the User](risk.md#telling-the-user)); and a sign in from an unusual place needs a [locator](devices-and-sessions.md#locations) and a location signal. See [Level 3](#level-3). Each kind is capped at five an hour per account. | +| 6.3.6 Email isn't an authentication factor | 3 | Met by default | Don't register `EmailCode::asSecondFactor()`. The factor throws without that explicit opt-in, and an emailed code never counts toward a level. | +| 6.3.7 Users are notified when authentication details change | 3 | Met by default | A default install mails a changed or reset password, a sign-in method added or removed, new recovery codes, a recovery code used and a changed email address, and an undone email change once `Features::emailChanges()` is on. Renaming a sign-in method or changing the default one sends nothing. An account whose address isn't verified is sent none of these, except the notice of the reset that proves it. A password your own code sets with `Keyring::withoutProtection()` is logged, not announced: dispatch `Keyring\Events\PasswordChanged` yourself if users should hear of it. Installing with `--no-emails`, or without the published provider, sends none, and nothing warns. | +| 6.3.8 Valid users can't be deduced from sign in, registration or forgot password | 3 | Met by default | All three answer the same for every address, in the same time. Keep `registration.reveal_taken` off: with it on, registration says when an address is taken, and the conformance check is skipped, not failed. A username of your own that must be unique will still say when it's taken, and mail that bounces is outside the request. See [Registration](sign-in-flow.md#without-revealing-who-has-an-account). | #### V6.4 Authentication Factor Lifecycle and Recovery @@ -209,26 +211,26 @@ Everything in Level 2, and: | 6.4.3 Password reset doesn't bypass multi-factor authentication | 2 | Met | A reset signs nobody in, and leaves second factors and their limits alone. | | 6.4.4 A lost factor is recovered with identity proofing | 2 | Yours | Recovery codes are Keyring's only way back in. For someone who has lost those too, your support process decides what they must prove before an administrator removes their authenticators. | | 6.4.5 Renewal reminders for factors that expire | 3 | N/A | Nothing Keyring issues expires. | -| 6.4.6 Administrators can start a reset but not choose the password | 3 | Yours | In your admin tool, send a reset link with `Password::broker()->sendResetLink(['email' => $user->email])`. Don't set a user's password with `Keyring::withoutProtection()`. | +| 6.4.6 Administrators can start a reset but not choose the password | 3 | Yours | In your admin tool, send a reset link with `Password::broker(config('keyring.passwords.broker'))->sendResetLink(['email' => $user->email])`. Don't set a user's password with `Keyring::withoutProtection()`. | #### V6.5 General Multi-Factor Authentication Requirements | | Level | | What to do | |---|---|---|---| | 6.5.1 Codes work once | 2 | Met | On any session driver. A sent code's state is kept in the rate limiter's cache store, which has to hold its keys between requests. | -| 6.5.2 Lookup secrets under 112 bits are stored salted and hashed | 2 | Met | Recovery codes are stored as a keyed hash, which the requirement allows from 112 bits. Keyring's own carry 120, those imported from Fortify 119, and nothing shorter is stored or accepted. | +| 6.5.2 Lookup secrets under 112 bits are stored salted and hashed | 2 | Met | Recovery codes are stored as a keyed hash, which the requirement allows from 112 bits. Keyring's own carry 128, those imported from Fortify 119, and nothing shorter is stored or accepted. | | 6.5.3 Secrets come from a secure random generator | 2 | Met | | | 6.5.4 Codes have at least 20 bits of entropy | 2 | Met | Emailed codes are eight digits, and a code factor set to fewer than six is refused. | -| 6.5.5 Out-of-band codes last 10 minutes at most, authenticator app codes 30 seconds | 2 | Needs setup | Sent codes last 10 minutes, and a longer life is refused. Authenticator app codes are accepted for up to about 90 seconds by default, which [doesn't meet the requirement](factors.md#authenticator-apps-totp): register `Totp` with `window` set to `0` ([Level 2](#level-2)). | -| 6.5.6 Any factor can be revoked | 3 | Needs setup | `Features::manageAuthenticators()` lets users remove a sign-in method, and `Features::devices()` a device. | -| 6.5.7 Biometrics only as a secondary factor | 3 | Met | A key's user verification only counts together with possession of the key. | +| 6.5.5 Out-of-band codes last 10 minutes at most, authenticator app codes 30 seconds | 2 | Deviates | Sent codes last 10 minutes, and a longer life is refused. Authenticator app codes are accepted for up to about 90 seconds by default, which [doesn't meet the requirement](factors.md#authenticator-apps-totp): one time step either side of now, for delay and clocks that have drifted (RFC 6238, Sections 5.2 and 6). A code still works once. Register `Totp` with `window` set to `0` to meet it ([Level 2](#level-2)). | +| 6.5.6 Any factor can be revoked | 3 | Met | `DELETE /user/authenticators/{id}` removes a sign-in method, with `Features::manageAuthenticators()`, which adding one needs anyway. `Features::devices()` adds revoking a device. | +| 6.5.7 Biometrics only as a secondary factor | 3 | Met | A key's user verification only counts together with possession of the key, and AAL2 needs a factor the user has. | | 6.5.8 Authenticator app codes use the server's time | 3 | Met | | #### V6.6 Out-of-Band Authentication Mechanisms | | Level | | What to do | |---|---|---|---| -| 6.6.1 Phone and SMS codes are restricted, and absent at Level 3 | 2 | Yours | Keyring ships no SMS factor. If you [build one](recipes.md#sms-codes), offer an authenticator app or passkeys beside it and tell users it's the weaker choice. Don't register it at Level 3. | +| 6.6.1 Phone and SMS codes are restricted, and absent at Level 3 | 2 | N/A | Keyring ships no SMS factor. It becomes yours if you [build one](recipes.md#sms-codes): offer an authenticator app or passkeys beside it, tell users it's the weaker choice, and don't register it at Level 3. | | 6.6.2 A code is bound to the request it was made for | 2 | Met | | | 6.6.3 Codes are protected from brute force | 2 | Met | Five wrong guesses per sign in, on top of the usual limits. | | 6.6.4 Push notifications are rate limited | 3 | N/A | Keyring has no push factor. | @@ -237,7 +239,7 @@ Everything in Level 2, and: | | Level | | What to do | |---|---|---|---| -| 6.7.1 Keys used to verify assertions are protected from modification | 3 | Yours | No Keyring route writes a stored public key. Restrict who can write to the `keyring_authenticators` table and to the files in `webauthn.attestation_roots`. | +| 6.7.1 Keys used to verify assertions are protected from modification | 3 | Yours | No Keyring route takes a public key from a request to replace a stored one: it's written when a key is added, behind a fresh verification, and rewritten from the stored record each time the key signs in. Keyring keeps no integrity check of its own on the row, so restrict who can write to the `keyring_authenticators` table and to the files in `webauthn.attestation_roots`. | | 6.7.2 Challenges are at least 64 bits and unique | 3 | Met | | #### V6.8 Authentication with an Identity Provider @@ -245,7 +247,7 @@ Everything in Level 2, and: | | Level | | What to do | |---|---|---|---| | 6.8.1 An identity can't be spoofed through another provider | 2 | Yours | In your factor, find users by the provider and the provider's ID together, never by email address. See [Social Login](recipes.md#social-login-with-socialite). | -| 6.8.2 Signatures on assertions are validated | 2 | Yours | That's the library you use for the provider. Keyring never sees an assertion. | +| 6.8.2 Signatures on assertions are validated | 2 | N/A | Keyring never sees an assertion. If you add a provider, that's the library you use for it. | | 6.8.3 SAML assertions are used once | 2 | N/A | Keyring doesn't process SAML. | | 6.8.4 Authentication strength claimed by the provider is verified | 2 | Yours | The recipe counts a social login as one factor whatever the provider did, and Keyring then asks for the user's own second factor. To rely on the provider's `acr`, `amr` or `auth_time` instead, check them in your factor. | @@ -255,8 +257,8 @@ Everything in Level 2, and: | | Level | | What to do | |---|---|---|---| -| 7.1.1 Timeouts are documented and justified | 2 | Yours | Write down the values you chose and why. Keyring's defaults and where they come from are in [Timeouts](devices-and-sessions.md#timeouts): no inactivity limit of its own, 30 days overall, and each assurance level lapsing on NIST SP 800-63B's clock. Say so if "remember me" is allowed to outlast your inactivity limit. | -| 7.1.2 The number of concurrent sessions and what happens at the limit is documented | 2 | Not met | Keyring doesn't limit how many sessions an account has, and has no option to. Document that the number is unlimited and that users can list and end them (7.5.2). | +| 7.1.1 Timeouts are documented and justified | 2 | Met | Keyring's defaults and where they come from are in [Timeouts](devices-and-sessions.md#timeouts): two hours unused, 14 days for a remembered browser, 30 days overall, and each assurance level lapsing on NIST SP 800-63B-4's clock. Its reasons for letting "remember me" outlast the idle limit, and for lowering a session's level rather than ending it, are there too. Write down the values you chose and why. | +| 7.1.2 The number of concurrent sessions and what happens at the limit is documented | 2 | Met | An account can have 100 sessions at once (`sessions.max`). A sign in beyond that ends the one unused longest and is never refused. See [How Many Sessions](devices-and-sessions.md#how-many-sessions). Write down the number you chose. | | 7.1.3 Federated session lifetimes are documented | 2 | Yours | Keyring's session carries on after an identity provider's ends, and there's no single logout. Document how yours relate. | #### V7.2 Fundamental Session Management Security @@ -266,31 +268,31 @@ Everything in Level 2, and: | 7.2.1 Session tokens are verified on the backend | 1 | Met | On every `web` request. Add `keyring.session` to any other route group users are signed in on. | | 7.2.2 Tokens are generated dynamically | 1 | Met | | | 7.2.3 Tokens are random with at least 128 bits | 1 | Met | | -| 7.2.4 A new token on authentication, and the old one ended | 1 | Met by default | With a server-side session driver. Laravel's `cookie` driver has nothing on the server to destroy, so a copied cookie keeps working after a step-up. | +| 7.2.4 A new token on authentication, and the old one ended | 1 | Met by default | With a server-side session driver the old session is destroyed. On Laravel's `cookie` driver Keyring signs the old copy out through its registry after a sign in or a step-up, where the session middleware runs, but not between the steps of a sign in that isn't finished. | #### V7.3 Session Timeout | | Level | | What to do | |---|---|---|---| -| 7.3.1 An inactivity timeout | 2 | Needs setup | Set `sessions.idle`. With `null`, the default, inactivity is left to Laravel's `session.lifetime`, and a browser that ticked "remember me" has no inactivity timeout at all inside the overall limit. Routes behind `keyring:aal2` or `keyring.fresh` ask again either way. | -| 7.3.2 An absolute maximum lifetime | 2 | Met by default | `sessions.absolute`, 30 days. Choose the length from your risk analysis; it can't be turned off. Keep `sessions.middleware` on. | +| 7.3.1 An inactivity timeout | 2 | Met by default | `sessions.idle`, two hours, counted on the server. A browser that ticked "remember me" has `sessions.remember_idle`, 14 days, and comes back with nothing proved. `null` for either hands inactivity back to Laravel's `session.lifetime` or removes it. Routes behind `keyring:aal2` or `keyring.fresh` ask again either way. | +| 7.3.2 An absolute maximum lifetime | 2 | Met by default | `sessions.absolute`, 30 days. Choose the length from your risk analysis; it can't be turned off, and any length is accepted. Keep `sessions.middleware` on. | #### V7.4 Session Termination | | Level | | What to do | |---|---|---|---| -| 7.4.1 A terminated session can't be used again | 1 | Met by default | Keep `sessions.middleware` on, and add `keyring.session` to signed-in route groups outside `web`. | -| 7.4.2 Sessions end when an account is disabled or deleted | 1 | Met | Deleting a user revokes their sessions. To disable one, use [`Keyring::allowSignInWhen()`](sign-in-flow.md#who-may-sign-in), not a global scope. | -| 7.4.3 The option to end other sessions after a factor changes | 2 | Partly | A password change offers it (`sign_out_others`, on by default), and a reset and an applied email change do it. Adding or removing a sign-in method ends no other session: turn on `Features::devices()` and offer "sign out everywhere else" (`DELETE /user/devices`) on your settings page. | +| 7.4.1 A terminated session can't be used again | 1 | Met by default | Keep `sessions.middleware` on, and add `keyring.session` to signed-in route groups outside `web`. The conformance suite names signed-in routes without it. | +| 7.4.2 Sessions end when an account is disabled or deleted | 1 | Partly | Deleting a user revokes their sessions. Disabling one is your app's flag, read by [`Keyring::allowSignInWhen()`](sign-in-flow.md#who-may-sign-in): while it's set no session works, and the first request it refuses ends every session the account has. A session only finds out when it makes a request, though, so if none does before the account is let back, they all still work. Call `app(Sessions::class)->signOutEverywhere($user)` as you set your flag to end them there and then. | +| 7.4.3 The option to end other sessions after a factor changes | 2 | Met | A password change ends the other sessions unless told not to, a reset ends them all, an applied email change ends the others, and adding or removing a sign-in method or making new recovery codes ends them when the request sends `sign_out_others`. `DELETE /user/sessions` is always there. Offer the choice on your settings page. | | 7.4.4 Sign out is easy to find on every signed-in page | 2 | Yours | Put a button that posts to `/logout` in your layout. | -| 7.4.5 Administrators can end a user's sessions, or everyone's | 2 | Partly | For one user, call `app(Sessions::class)->signOutEverywhere($user)` from your admin tool. Keyring has no call for every user at once: run that over your users. | +| 7.4.5 Administrators can end a user's sessions, or everyone's | 2 | Met | `php artisan keyring:sign-out {user}` ends one user's sessions and `--all` everyone's. From code: `Sessions::signOutEverywhere($user)` and `SessionRegistry::revokeEveryone()`. See [For Administrators](devices-and-sessions.md#for-administrators). | #### V7.5 Defenses Against Session Abuse | | Level | | What to do | |---|---|---|---| -| 7.5.1 Re-authentication before changing sign-in details | 2 | Met by default | `changes_middleware` is `keyring.fresh:15m`. Don't empty it. For an attribute of your own that affects recovery (a phone number), put `keyring.fresh` on the route that changes it. | -| 7.5.2 Users can see and end their sessions | 2 | Needs setup | `Features::devices()` adds the list and the routes to end one device or all others, behind a fresh verification. It lists devices, each with its sessions: a session your own `Auth::login()` started from a browser Keyring hasn't seen isn't listed, and "sign out everywhere else" ends it. | +| 7.5.1 Re-authentication before changing sign-in details | 2 | Met by default | `changes_middleware` is `keyring.fresh:15m`. Don't empty it: the conformance suite checks, when a factor can be enrolled. For an attribute of your own that affects recovery (a phone number), put `keyring.fresh` on the route that changes it. | +| 7.5.2 Users can see and end their sessions | 2 | Met by default | `GET /user/sessions` lists every session, and `DELETE /user/sessions/{id}` and `DELETE /user/sessions` end one or all the others behind a fresh verification, whatever features are on. Keep `changes_middleware`. Build the page. | | 7.5.3 Further authentication before highly sensitive operations | 3 | Yours | Put `keyring.fresh:5m`, `keyring:aal2` or `keyring:aal3` on those routes. See [Step-Up](step-up.md). | #### V7.6 Federated Re-authentication @@ -300,15 +302,149 @@ Everything in Level 2, and: | 7.6.1 Session lifetime between your app and an identity provider behaves as documented | 2 | Yours | Keyring reads nothing from the provider after sign in. If the provider's limits must be honoured, your factor has to arrange it. | | 7.6.2 A session is only created by the user's action | 2 | Yours | Keyring's own sessions start on a POST that carries a proof. For a social login, the redirect and consent are the provider's and your callback's. | +### The Other Chapters + +ASVS's other chapters are about your whole application. These are the requirements in them that Keyring's own code and routes bear on. Where a row says Keyring meets one, that is for Keyring's routes and what it stores: the rest of your app is yours. + +| | | What it means for your app | +|---|---|---| +| 1.2.2 URLs are built with untrusted data encoded | Met | Server side, links are built from named routes. The browser package encodes every factor key and ID it puts in a path. A route you override with `configureRoutes()` is used as written, so [encode in yours](frontend.md#changing-routes). | +| 2.4.1 Anti-automation controls | Met by default | The [rate limits](security.md#rate-limiting), and the `keyring` and `keyring-login-options` limiters on the other forms. All are options, and you can redefine the limiters: only a password minimum under 8, a sent code under six digits or over ten minutes, a TOTP window over one step and an RSA floor under 2048 bits are refused. | +| 2.4.2 Flows require realistic human timing (Level 3) | Yours | Keyring has no bot check and no minimum time on a form. Where a CAPTCHA or a challenge goes is in [Bot Checks](security.md#bot-checks). | +| 3.3.1, 3.3.3 `Secure` cookies with a `__Host-` or `__Secure-` prefix | Met by default | Keyring's two cookies, over HTTPS. A name you set yourself (`devices.cookie`, `sessions.remember_cookie`) is used as written, so the prefix is yours to add. Laravel's session cookie is yours to name and secure: see [Secure Cookies](security.md#secure-cookies). | +| 3.4.1 `Strict-Transport-Security` on every response | Yours | Keyring sends none: it would only cover its own routes. See [HTTPS and HSTS](security.md#https-and-hsts). | +| 3.4.3 A `Content-Security-Policy` | Yours | Keyring renders through your layout, so what a policy must allow is yours to say. See [A Content Security Policy](security.md#a-content-security-policy). | +| 3.4.4, 3.4.5 `nosniff` and a referrer policy on every response | Met by default | On every Keyring response. Taking `AddSecurityHeaders` out of `keyring.middleware` removes them. Your other responses are yours. | +| 3.4.6 `frame-ancestors` so pages can't be framed | Yours | Keyring sends `X-Frame-Options: DENY` on its own responses, which keeps its pages out of frames. The requirement asks for `frame-ancestors` in a content security policy, on every response, and that policy is your app's. | +| 3.5.1 Cross-origin requests to sensitive functionality are checked | Met by default | Keyring's routes are in the `web` group, so Laravel's CSRF check covers them. Don't except Keyring's paths from it, and keep it if you replace `keyring.middleware`. | +| 4.1.3 Headers an intermediary sets can't be overridden by the user | Met by default | Keyring reads the client's address from Laravel's request, which follows your trusted proxies. `HeaderLocator` trusts request headers: only use it behind a proxy that sets them and can't be bypassed. | +| 8.2.4 Adaptive controls from contextual attributes (Level 3) | Met by default | The [risk signals](risk.md) the published provider starts with, at sign in and on every request. Location signals need a locator you supply. An app without the published provider has none until it picks some. | +| 11.1.1 A key management policy | Yours | Keyring derives a key per purpose from `APP_KEY` and never uses it directly ([Keys](security.md#keys)). Who holds `APP_KEY`, how often it rotates and how it's destroyed is your organisation's policy. | +| 11.2.2 Algorithms and keys can be replaced | Partly | The password hash, `APP_KEY`, the cipher, the WebAuthn algorithms and the TOTP digest can all be changed. The keyed hash (HMAC-SHA-256) and the token hash (SHA-256) are fixed in code, and stored hashes carry no tag saying which scheme made them. See [Changing an Algorithm](security.md#changing-an-algorithm) for what a change would take. | +| 11.2.3 At least 128 bits of security | Met by default | Until you add RS256 to `webauthn.algorithms` (112 bits at 2048) or turn on `requireAttestation()`, whose makers' certificates may be RSA-2048. Both are opt-in. | +| 11.3.2 Approved ciphers and modes | Yours | Encryption is Laravel's, with your `app.cipher`. The default, AES-256-CBC with a MAC, is a legacy mode in ASVS's Appendix C: set `app.cipher` to `aes-256-gcm` for an approved one. | +| 11.4.1 Approved hash functions | Deviates | TOTP codes are made with HMAC-SHA-1 by default, a legacy algorithm in Appendix C, because it's the only digest every authenticator app makes. Give the factor [another digest](factors.md#authenticator-apps-totp) if your users' apps support it. | +| 11.4.2 Passwords stored with an approved, costly function | Yours | Keyring calls Laravel's `Hash` and rehashes at sign in when your settings change. The algorithm and its cost are yours: Laravel's defaults meet Appendix C, and Keyring doesn't check what you set. | +| 11.6.1 Approved signature algorithms | Met by default | ES256 and EdDSA. RS256 and attestation chains signed with RSASSA-PKCS1-v1_5, which Appendix C doesn't approve, are both opt-in. | +| 12.2.1 TLS for every connection (all of V12) | Yours | Your web server's. Keyring's one outbound call, the breached-password lookup, is over HTTPS with certificate verification on. | +| 13.3.1 Secrets kept out of source code | Yours | Keyring holds no secret of its own: everything derives from your environment. | +| 14.2.1 Sensitive data in the body or headers, never the URL | Deviates | Every request that proves or changes something carries its password, code, token or signature in the body. An emailed link is the exception: it has to carry its token in the URL of the page it opens, once. See [Tokens in Emailed Links](security.md#tokens-in-emailed-links). | +| 14.2.2 Sensitive data isn't cached | Met by default | `Cache-Control: no-store, private` on every Keyring response, from the same middleware as 3.4.4. | +| 14.2.3 Sensitive data isn't sent to untrusted parties | Met by default | The breached-password lookup sends five characters of a SHA-1, never the password. `passwords.uncompromised => false` turns the call off. | +| 14.2.7 Sensitive data is deleted on a schedule | Met by default | Keyring schedules `keyring:prune` daily. It needs your scheduler running, and `prune_at => null` leaves scheduling to you. | +| 15.1.2 An inventory of third-party libraries | Yours | Keyring declares its dependencies by version range and ships no lock file, as any library does. The resolved list is your `composer.lock`. | +| 15.3.2 Outbound calls don't follow redirects | Met | The one call Keyring makes itself, the breached-password lookup with `passwords.refuse_unchecked`, follows none. Without that option the lookup is Laravel's verifier and not Keyring's, and it follows redirects as Laravel's HTTP client does: bind an `UncompromisedVerifier` of your own if that matters to you. | +| 15.3.4 The client's IP address comes from trusted fields | Yours | Configure Laravel's [trusted proxies](security.md#trusted-proxies). Keyring uses the address Laravel gives it for limits and logs. | +| 16.2.2 Timestamps in UTC or with an offset | Partly | An entry written to your app's log carries its time with an offset. The `keyring_events` table keeps `created_at` in your `app.timezone`, without one: leave that at UTC, Laravel's default. See [Times](security-log-and-emails.md#times). | +| 16.3.3 Security events and attempts to bypass controls are logged | Deviates | Refused links, signatures, tokens, records and pipeline steps are logged, and so is a refusal by a rate limit. Form validation failures aren't, on purpose: a missing field is an ordinary mistake. Laravel's CSRF refusals are the framework's. | +| 16.4.2 Logs are protected and shipped elsewhere | Yours | Keyring writes to your database or your log channel. Who can read and change them, and where they're copied, is yours. | +| 16.5.2 Works securely when an outside service fails | Deviates | When Have I Been Pwned can't be reached, a new password is let through, leaving the bundled list of common passwords, so an outage doesn't stop registrations. `passwords.refuse_unchecked` refuses it instead. | +| 16.5.3 Fails securely | Deviates | The per-minute limits, their locks and risk locks are in the cache, so clearing it lifts them. The cap on failures in a row, which is what ends guessing, is in the database. See [Rate Limiting](security.md#rate-limiting). | + +The rest of those chapters either doesn't apply to an authentication package or is your app's and its deployment's: file handling, OAuth, WebRTC, TLS configuration, your own forms' validation and your own pages' output. + +## NIST SP 800-63B-4 + +Keyring is built on Revision 4 of NIST SP 800-63B, and its assurance levels are named after NIST's. The document is written for a credential service provider, which is your app and your organisation together, so no library can follow all of it. This section says what Keyring's levels do mean, and what's left. + +### What Keyring's Levels Mean + +A session's level is worked out from what it has proved, and when ([Assurance Levels](policies.md#assurance-levels)). + +| Level | What the session proved | What Keyring holds it to | What your app supplies | +|---|---|---|---| +| AAL1 | One authentication factor: a password, usually. | A password of 15 characters or more when it's the account's only factor (Sec. 3.1.1.2). A session that ends 30 days after sign in (Sec. 2.1.3), and after two hours unused, which NIST doesn't ask for at this level. | Nothing more. Keep `sessions.absolute` at 30 days or under, and `passwords.min_without_mfa` at 15. | +| AAL2 | Two factors of different kinds, one of them something the user has (Sec. 2.2.1): a password and an authenticator app's code, or a passkey that verified the user. An emailed code isn't a factor (Sec. 3.1.3.1), and neither is a biometric without the authenticator it unlocks (Sec. 3.2.3). | The level lapses after an hour unused or 24 hours (Sec. 2.2.3), and getting it back takes every factor again, which is more than NIST asks. By default the session then carries on as AAL1. | A second factor, registered and [required](policies.md#requiring-a-second-factor). A phishing-resistant option on offer (Sec. 2.2.2): register passkeys or security keys. `keyring:aal2` on what needs the level, or `sessions.end_on_lapse` if nothing may be reached below it, and no "remember me" checkbox (Sec. 5.1). | +| AAL3 | A phishing-resistant key that can't leave its device and was added with a verified attestation, with its own user verification or a password (Sec. 2.3.1 and 2.3.2). A passkey that syncs never reaches it. | The level lapses after 15 minutes unused or 12 hours (Sec. 2.3.3). | [`requireAttestation()`](passkeys.md#requiring-attestation) and the root certificates you trust. Authenticators validated to FIPS 140, limited to those models with [`allowOnly()`](passkeys.md#allowing-only-certain-models), and server cryptography validated the same way: Keyring can't supply or check either. `sessions.end_on_lapse`. Keep `sessions.levels.aal3.absolute` at 12 hours or under. | + +A session Keyring calls AAL3 has met NIST's rules for the authentication itself. Whether your service is AAL3 also depends on the validated hardware and cryptography above, and on the rest of the document. + +### Section by Section + +Where Keyring doesn't meet a section whatever you configure. Sections that aren't listed are met, or are about things Keyring doesn't make: authenticator hardware, biometric sensors, identity proofing, federation. + +| Section | | What it means for your app | +|---|---|---| +| 2.1.3 A definite overall timeout at AAL1, 30 days at most | Met by default | `sessions.absolute` is 30 days. A longer one is accepted. | +| 2.2.1 AAL2 takes a physical authenticator | Met | `Requirement::aal2()` needs a possession factor. A factor of your own that reports only inherence leaves a session at AAL1. `Requirement::factors(2)` is any two kinds, and isn't AAL2. | +| 2.2.2 A phishing-resistant option is offered at AAL2 | Yours | Passkeys and security keys ship with Keyring. A default install registers only the password, so offer one. | +| 2.2.3 AAL2 lapses after an hour idle or 24 hours | Met by default | `sessions.levels.aal2`. Longer limits are accepted. | +| 2.3.2 AAL3 authenticators and verifier cryptography are validated to FIPS 140 | Yours | Everything a library can check about the key is checked. The validation is yours to buy and to run on. | +| 2.3.3 AAL3 lapses after 12 hours at most | Met by default | `sessions.levels.aal3`. A longer `absolute` is accepted, and breaks the rule. | +| 2.4 Security controls, records retention, privacy and redress | Yours | [What Keyring Keeps](security.md#what-keyring-keeps) lists what's stored and for how long, to write your own policy from. | +| 3.1.1.1 No composition rules | Met by default | Don't add any to your published action. | +| 3.1.1.2 A password used alone is at least 15 characters | Met by default | `passwords.min_without_mfa`. Anything from 8 up is accepted, and under 15 breaks the rule. | +| 3.1.1.2 Passwords of at least 64 characters are permitted | Deviates | Bcrypt stops at 72 bytes, so 64 characters of multi-byte text may not fit: see ASVS [6.2.9](#v62-password-security). Use argon2id. | +| 3.1.1.2 A change is forced on evidence of compromise | Needs setup | Passwords never expire. Keyring holds a user until they choose a new password when your app calls `Keyring::requirePasswordChange()`, and by itself when the `BreachedPassword` signal finds the password just used in a breach. That signal makes a network call at every sign in, so it's [off until you turn it on](risk.md#requiring-a-new-password). | +| 3.1.1.2 New passwords are compared against a blocklist | Met by default | The common list and the context words can't be turned off. The breach check can (`passwords.uncompromised`), and lets a password through when the service is down unless you set `passwords.refuse_unchecked`. | +| 3.1.1.2 Guidance on choosing a password, password managers and paste allowed | Yours | Keyring ships no pages, and its validation takes any string. Its refusal messages say what to do instead. | +| 3.1.1.2 A keyed hash or encryption under a separately stored key (recommended) | Deviates | Not built in: the hash column is shared with the rest of your app, where the key lives is your infrastructure's decision, and rotating it locks everyone out. [Peppering Passwords](security.md#peppering-passwords) shows how to add one. | +| 3.2.2 No more than 100 failures in a row on one authenticator | Met by default | `limits.consecutive`. A higher number, or `null`, is accepted. `Keyring::unlock()` switches a disabled authenticator back on without binding it again, which NIST doesn't provide for: see [At the Cap](security.md#at-the-cap). | +| 4.1.2.1 A new authenticator is bound at the highest level the account can reach | Met by default | `changes_middleware`. Emptying it fails the conformance suite and nothing else. Keyring always asks for the highest the account can reach, where NIST would also take the level the new authenticator will be used at. | +| 4.1.2.1 The subscriber is told when an authenticator is added | Met by default | `authenticator_added`, from the published provider. A notice that isn't registered isn't sent, and nothing warns. | +| 4.2.1.1 A used recovery code is replaced with a new one | Deviates | Keyring uses the code up and doesn't issue another by itself, because a new code is only worth something once its owner has seen and saved it. `shouldReplaceRecoveryCodes()` says when a set has had one used: send the user to [make a new set](authenticators.md#recovery-codes). Until your app does, this rule isn't met. | +| 4.2.1.1 A replacement recovery code is announced | Met by default | `recovery_codes_generated`. | +| 4.2.1.2 A code sent by email lasts 24 hours at most | Yours | Reset links are Laravel's broker's: `auth.passwords.*.expire`, 60 minutes in a new app. Keyring doesn't cap it. | +| 4.2.1.2 At least two verified recovery addresses | Yours | Keyring has one, the `email` attribute. A second address, verified before it's used, is your app's to build: see [Known Limitations](security.md#known-limitations). | +| 4.2.3 Account recovery is announced | Met by default | `password_changed` after a reset, and `recovery_code_used`. | +| 4.6 At least two notification addresses, and every notice sent to all of them | Yours | Keyring mails your user model as Laravel does, at one address. Return more from `routeNotificationForMail()`: see [A Support Contact](security-log-and-emails.md#a-support-contact). | +| 4.6 A notice says who to contact | Needs setup | Set [`support_contact`](security-log-and-emails.md#a-support-contact), and the published notices end with it. It's `null` until you do. | +| 5.1 A cookie isn't used instead of authentication | Deviates | "Remember me" brings a browser back signed in, with nothing proved, after its session idled out. Keyring binds it to the session it was ticked for, lets it work once, and gives the session it resumes no level, so anything behind `keyring:aal1`, `keyring:aal2` or `keyring.fresh` asks again. Routes behind `auth` alone are reachable on the cookie. Leave the checkbox off your login form, or set `sessions.end_on_lapse`, where you follow this section. | +| 5.1 Requests that change something carry a CSRF token | Met by default | Laravel's, on the `web` group. | +| 5.1.1 Session cookies are `Secure` and narrowly scoped | Met by default | Keyring's own, which hold only random identifiers. Laravel's session cookie is `Secure` once you set `SESSION_SECURE_COOKIE`. | +| 5.2 A session ends when its inactivity or overall timeout passes | Deviates | By default a session past its level's limits carries on at the lower level, which Sec. 5.1 allows and which keeps it inside AAL1's own limits. `sessions.end_on_lapse` ends it instead. See [Ending a Session With Its Level](devices-and-sessions.md#ending-a-session-with-its-level). | + +## The OWASP Cheat Sheets + +Keyring follows OWASP's Authentication, Session Management, Multifactor Authentication, Forgot Password, Password Storage, Credential Stuffing Prevention, Cross-Site Request Forgery Prevention, Logging and Passkey Security cheat sheets. [Standards](security.md#standards) says which choice comes from which. These are the recommendations that depend on your setup, or that Keyring doesn't follow: + +| Cheat sheet | Recommendation | | What it means for your app | +|---|---|---|---| +| Authentication | Verify an email address used as a username | Met by default | New users sign in once they've verified theirs. `registration.reveal_taken` signs them in first. | +| Authentication | Password length, characters and no composition rules | Met by default | As ASVS 6.2.1 to 6.2.9: use argon2id for 64 characters of any script. | +| Authentication | A password strength meter | Yours | Your registration page's. | +| Authentication | Don't get in the way of password managers | Yours | Your forms'. | +| Authentication | Re-authenticate for sensitive features | Met by default | `changes_middleware`. | +| Authentication | Re-authenticate after a risk event | Met by default | The risk signals in the published provider. | +| Authentication | Registration doesn't say an ID is in use | Met by default | Until you set `registration.reveal_taken`. | +| Authentication | Throttle logins per account, with growing lockouts | Met by default | The numbers are options. | +| Authentication | A CAPTCHA after failed attempts | Yours | See [Bot Checks](security.md#bot-checks). | +| Session Management | Session ID names that aren't descriptive | Met by default | Keyring's cookies are `known_device` and `remembered_session`. Laravel's session cookie is yours to name. | +| Session Management | Store only a hash of a session token | Deviates | The registry keeps its IDs as they are. See [Storage](security.md#storage) for why one alone signs nobody in. | +| Session Management | Idle and absolute timeouts on the server | Met by default | `sessions.idle => null` removes Keyring's idle limit. | +| Session Management | `no-store` on sensitive responses, `Clear-Site-Data` at sign out | Met by default | On Keyring's routes, through `keyring.middleware`. | +| Session Management | Bind the session to client properties and notice changes | Met by default | The `SessionFingerprintChanged` signal in the published provider. | +| Multifactor Authentication | Offer TOTP, and require MFA where you can | Needs setup | Pick a second sign-in method: see [Level 2](#level-2). | +| Multifactor Authentication | Tell the user when a second factor fails after the right password | Met by default | The "was this you?" alert, and the `second_factor_failed` email once you've picked a second sign-in method. | +| Multifactor Authentication | Re-authenticate and notify when a factor changes | Met by default | `changes_middleware`, and the notices in the published provider. | +| Multifactor Authentication | No fallback from a phishing-resistant factor to a weaker one | Met by default | `noDowngrade()`, in the policy the installer writes. A policy of your own has to say it. Recovery codes stay on offer. | +| Password Storage | Argon2id, or bcrypt for legacy systems | Yours | Your `hashing.driver`. Laravel's default is bcrypt. | +| Password Storage | A pepper kept apart from the database | Deviates | Not built in. See [Peppering Passwords](security.md#peppering-passwords). | +| Forgot Password | Rate limit reset requests per account | Met by default | Laravel's broker `throttle`, which Keyring doesn't set: keep it. The conformance suite fails without one. See [Resetting the Password](protected-changes.md#resetting-the-password). | +| Forgot Password | After a reset: no automatic sign in, sessions ended, the user emailed | Met by default | The email is `password_changed`, from the published provider. | +| Credential Stuffing Prevention | Per-IP limits that aren't the only defence | Met by default | The numbers are options. | +| Credential Stuffing Prevention | Metrics from each defence | Partly | Keyring dispatches an event and writes a log entry for each. Counting them is a listener of yours: see [Events](events.md). | +| Credential Stuffing Prevention | Find leaked passwords | Met by default | `passwords.uncompromised`. | +| Credential Stuffing Prevention | Tell users of unusual events, show recent sign ins and sessions | Met by default | The notices and signals in the published provider, and `GET /user/sessions`. The pages are yours. | +| Cross-Site Request Forgery Prevention | The framework's protection on every request that changes state | Met by default | Laravel's, on the `web` group. | +| Cross-Site Request Forgery Prevention | Client code doesn't build request targets from untrusted input | Met | The browser package encodes what it puts in a path. | +| Logging | Log sign ins, failures, refusals and input validation failures | Deviates | Everything but validation failures, as ASVS 16.3.3 above. | +| Logging | Logging can't be used to exhaust resources | Met by default | `security_log.refusals => null` removes the cap. | +| Passkey Security | Attestation off by default; when on, check the chain and its status | Deviates | Off by default. With `requireAttestation()`, the chain is checked against your roots and no revocation list is fetched: withdraw trust by removing the root. | +| Passkey Security | Generic errors, even timing, no silent fallback | Met by default | `noDowngrade()`, as above. | +| Passkey Security | A managed list of credentials, with when each was created and last used | Met | A factor's `present()` gives `createdAt` and `lastUsedAt`. The page is yours. | + ## What Is Left to Your App -Whatever level you aim for, these are outside what a package can do: +Whatever you aim for, these are outside what a package can do: - **TLS everywhere**, with `SESSION_SECURE_COOKIE=true` and trusted proxies configured, so rate limits see real addresses. - **Your pages.** Keyring ships none: masked password fields, paste and password managers left alone, a visible sign-out button, and telling users the risks of a weaker factor are in your templates. -- **Headers on your own pages.** Keyring's responses send `Cache-Control: no-store`, `Referrer-Policy: same-origin` and `X-Frame-Options: DENY`. A content security policy and the rest are yours, for every page. +- **Headers on your own pages.** Keyring's responses send `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: same-origin` and `X-Frame-Options: DENY`. A content security policy and the rest are yours, for every page. - **Your mail provider.** Verification links, reset links and security notices are only as private and as prompt as the mail that carries them. Its bounce and delivery reports sit outside the request, where Keyring can't make two answers look alike. -- **Your session and cache stores.** A server-side session driver, and a rate limiter store that doesn't lose its keys: limits, locks, sent codes and answered WebAuthn challenges are kept there. +- **Your session and cache stores.** A server-side session driver, and a rate limiter store that doesn't lose its keys: the per-minute limits, their locks, sent codes and answered WebAuthn challenges are kept there; failures in a row are in your database. - **Your documentation.** ASVS asks for your password word list, your session timeouts and your sign-in pathways in writing. -- **Your administrators.** Who may end sessions, send reset links or remove a lost authenticator, and what a user must prove first. +- **Your administrators.** Who may run `keyring:sign-out`, send reset links or remove a lost authenticator, and what a user must prove first. +- **A second address.** NIST asks for two notification addresses and two recovery addresses. Keyring has the one on your user model. +- **Bot checks.** A CAPTCHA or a challenge in front of your forms, if you want one. - **Identity providers.** Everything about a federated sign in beyond starting Keyring's session. diff --git a/docs/passkeys.md b/docs/passkeys.md index c6e45bee..634e7457 100644 --- a/docs/passkeys.md +++ b/docs/passkeys.md @@ -107,7 +107,7 @@ The list covers the signature on an [attestation statement](#requiring-attestati ### RS256 and Windows Hello -RS256 is left out because OWASP ASVS 5.0 doesn't approve it: its padding (PKCS #1 v1.5) is on the disallowed list of Appendix C, and the 2048 bit keys that use it give 112 bits of strength where ASVS 11.2.3 asks for 128. ES256 and Ed25519 are approved and give 128. NIST SP 800-63B asks for 112, so RS256 with a 2048 bit key meets NIST but not ASVS. +RS256 is left out because OWASP ASVS 5.0.0 doesn't approve it: its padding (PKCS #1 v1.5) is on the disallowed list of Appendix C, and the 2048 bit keys that use it give 112 bits of strength where ASVS 11.2.3 asks for 128. ES256 and Ed25519 are approved and give 128. NIST SP 800-63B-4 asks for 112 (Sec. 3.1.6.2), so RS256 with a 2048 bit key meets NIST but not ASVS. The cost of leaving it out falls on Windows. Windows Hello signed with RS256 alone for years, and still does on some machines: older builds, and ones where it has no TPM that makes ES256 keys. There the browser can't create a passkey with Windows Hello while RS256 isn't offered, and the user is shown a phone or a security key to use, or an error. They can still add a passkey from a phone or a hardware key, or sign in with their password and another second factor. @@ -119,7 +119,7 @@ If those users matter more to you than ASVS conformance here, add it, last so ev Record that as a deviation from ASVS 11.6.1 and 11.2.3 if you assess against it. -With RS256 on, Keyring refuses an RSA key shorter than `minimum_rsa_bits`, both when it's added and at every sign in, and never takes one under 2048 bits however low that's set (RFC 8230 requires 2048 for RS256). Raising it to 3072 would give RSA the 128 bits ASVS asks for, but Windows Hello's RSA keys are 2048 bits, so in practice it refuses the keys RS256 was turned on for, after the browser has already made them. If you want 128 bits throughout, leave RS256 off. +With RS256 on, Keyring refuses an RSA key shorter than `minimum_rsa_bits`, both when it's added and at every sign in, and never takes one under 2048 bits however low that's set (RFC 8812, Section 2, requires 2048 bits for RS256). Raising it to 3072 would give RSA the 128 bits ASVS asks for, but Windows Hello's RSA keys are 2048 bits, so in practice it refuses the keys RS256 was turned on for, after the browser has already made them. If you want 128 bits throughout, leave RS256 off. ## Attestation and AAGUIDs diff --git a/docs/policies.md b/docs/policies.md index 178e6e69..037585cd 100644 --- a/docs/policies.md +++ b/docs/policies.md @@ -30,9 +30,9 @@ A `Keyring\Login\Requirement` counts **distinct categories** (knowledge, possess | | Means | |---|---| | `Requirement::aal1()` | Any one category. | -| `Requirement::aal2()` | Two categories. | +| `Requirement::aal2()` | Two categories, one of them possession. See [Assurance Levels](#assurance-levels). | | `Requirement::aal3()` | Two categories from an attested, phishing-resistant key that can't leave its device, by itself or with a password. See [Assurance Levels](#assurance-levels). | -| `Requirement::factors(3)` | That many categories (at least 1). | +| `Requirement::factors(3)` | That many categories of any kind (at least 1). `factors(2)` is two without asking which, so it's less than `aal2()`. | | `Requirement::steps(2)` | That many categories of any kind, one of them a factor: a password and an email code will do. | | `Requirement::for(Assurance::AAL2)` | The requirement for an assurance level. | | `->including(Category::Possession)` | That category must be among those verified. | @@ -45,7 +45,7 @@ A `Keyring\Login\Requirement` counts **distinct categories** (knowledge, possess Requirements are immutable. Each modifier returns a new instance, and PHP warns if you discard it: ```php -$requirement = Requirement::aal2()->including(Category::Possession)->phishingResistant(); +$requirement = Requirement::aal2()->including(Category::Knowledge)->phishingResistant(); ``` ## Assurance Levels @@ -65,6 +65,8 @@ Keyring works out an assurance level from what a user has proved in their sessio A user-verified passkey proves possession and inherence in one step, so it reaches AAL2 on its own. +AAL2 is two categories, one of which is possession: something the user has. NIST SP 800-63B-4 (Sec. 2.2.1) takes a password or a biometric only together with a physical authenticator, and never a biometric by itself (Sec. 3.2.3). Every factor Keyring ships fits: inherence only ever comes from a passkey or security key that verified the user, which is possession too. It matters for [a factor of your own](factors.md#categories): one that reports `Knowledge` and `Inherence`, or `Inherence` alone, leaves a session at AAL1 however it's combined with a password. + AAL3 is narrower than "two factors with a hardware key". NIST asks for a key that can't be exported, with a second factor that is the key's own activation or a password (Sec. 2.3.1 and 2.3.2). So Keyring needs all of this: - The key is phishing resistant and reports that it can't sync: the backup-eligible flag, read on every sign in. A key that hasn't reported it counts as synced. @@ -91,7 +93,7 @@ Without `ifEnrolled()`, users who can't meet the requirement can't sign in at al ## Requiring a Second Factor -`ifEnrolled()` lets users without a second factor carry on with just a password. To make everyone add one (OWASP ASVS 6.3.3 asks for this at level 2), add the `keyring.enrolled` middleware to the routes they must not reach without one, usually the whole app: +`ifEnrolled()` lets users without a second factor carry on with just a password. To make everyone add one (OWASP ASVS 5.0.0 asks for this at Level 2, in requirement 6.3.3), add the `keyring.enrolled` middleware to the routes they must not reach without one, usually the whole app: ```php // bootstrap/app.php diff --git a/docs/protected-changes.md b/docs/protected-changes.md index 0dedb5ac..81eb7ca2 100644 --- a/docs/protected-changes.md +++ b/docs/protected-changes.md @@ -189,7 +189,7 @@ However a change is cancelled, the old address's "this wasn't me" link keeps wor | Field | | |---|---| -| `current_password` | Required when the user has a password. Keyring checks it itself, with the `Keyring\Rules\CurrentPassword` rule, so a change always takes the current password whatever your action does (OWASP ASVS 6.2.3). A fresh verification can be a passkey or a code, which doesn't show the user knows the password they're replacing. | +| `current_password` | Required when the user has a password. Keyring checks it itself, with the `Keyring\Rules\CurrentPassword` rule, so a change always takes the current password whatever your action does (OWASP ASVS 5.0.0, 6.2.3). A fresh verification can be a passkey or a code, which doesn't show the user knows the password they're replacing. | | `password`, `password_confirmation` | The new password, checked by the published action against the [password rules](#password-rules). | | `sign_out_others` | Optional boolean, `true` by default. Read by Keyring. | @@ -209,7 +209,7 @@ Keyring runs your action as one of its own flows, so it may change the protected ## Requiring a Password Change -Keyring never expires passwords. When there's evidence one is known to someone else, it can hold the user until they choose another, as NIST SP 800-63B-4 asks (Sec. 3.1.1.2). Place a hold from your own code, or from a [risk response](risk.md#requiring-a-new-password): +Keyring never expires passwords. When there's evidence one is known to someone else, it can hold the user until they choose another, as NIST SP 800-63B-4 asks (Sec. 3.1.1.2). Keyring places a hold itself in one case: with the [`BreachedPassword`](risk.md#requiring-a-new-password) signal on, when the password someone just signed in with is found in a breach. Place one from your own code for anything else you learn, or from a [risk response](risk.md#requiring-a-new-password) of your own: ```php use Keyring\Facades\Keyring; @@ -249,10 +249,10 @@ The check runs in `Keyring\Http\Middleware\RequirePasswordChange`, which Keyring - breached passwords rejected, in production by default. Laravel's check lets a password through when Have I Been Pwned can't be reached; set [`passwords.refuse_unchecked`](configuration.md#passwords) to refuse it instead, - the most common passwords rejected always, whatever their case and with or without spaces around them, from a list bundled with Keyring: the 10,000 most common of 8 characters or more and the 3,000 most common of 15 or more, 13,052 in all, taken from SecLists (MIT licensed). `resources/passwords/README.md` in the package records the exact source, - no passwords made up of [context-specific words](#context-specific-words): the site's name, the words you list, and the user's name, email username and email domain, -- with bcrypt, Laravel's default, passwords over 72 bytes are rejected, because bcrypt silently ignores the rest. That's 72 plain characters but as few as 18 emoji, so 64 characters don't always fit. Set `HASH_DRIVER=argon2id` to accept every password up to `max`, which is what OWASP ASVS 6.2.9 needs (see [Passwords](configuration.md#passwords)), +- with bcrypt, Laravel's default, passwords over 72 bytes are rejected, because bcrypt silently ignores the rest. That's 72 plain characters but as few as 18 emoji, so 64 characters don't always fit. Set `HASH_DRIVER=argon2id` to accept every password up to `max`, which is what OWASP ASVS 5.0.0 (6.2.9) needs (see [Passwords](configuration.md#passwords)), - and `confirmed`, so the request needs `password_confirmation`. -Passwords may hold any Unicode characters, and Keyring puts each one in Unicode's NFC form before it's measured, hashed or checked, as NIST SP 800-63B recommends. The same "é" is one code point from some keyboards and two from others, and without this a password set on one device could fail on another. The rules above count what will be hashed: a character is one code point of the NFC form. Keyring's routes do this for the input they hand your actions (`password`, `password_confirmation` and `current_password`) and for every password they check. If your own code sets a password some other way, such as a seeder, an admin tool or a route of your own, pass it through `PasswordRules::normalize()` first: +Passwords may hold any Unicode characters, and Keyring puts each one in Unicode's NFC form before it's measured, hashed or checked, as NIST SP 800-63B-4 recommends (Sec. 3.1.1.2). The same "é" is one code point from some keyboards and two from others, and without this a password set on one device could fail on another. The rules above count what will be hashed: a character is one code point of the NFC form. Keyring's routes do this for the input they hand your actions (`password`, `password_confirmation` and `current_password`) and for every password they check. If your own code sets a password some other way, such as a seeder, an admin tool or a route of your own, pass it through `PasswordRules::normalize()` first: ```php $user->password = Hash::make(PasswordRules::normalize($password)); @@ -264,7 +264,7 @@ A password hashed without it only matters when it has characters that aren't alr ### Context-Specific Words -A password that is just the name of your app, your company or its owner is easy to guess for anyone who knows where it's used. OWASP ASVS 6.1.2 asks you to keep a list of such words, and 6.2.11 to use it to stop easy-to-guess passwords. The list goes in the `passwords.context` option: +A password that is just the name of your app, your company or its owner is easy to guess for anyone who knows where it's used. OWASP ASVS 5.0.0 (6.1.2) asks you to keep a list of such words, and 6.2.11 to use it to stop easy-to-guess passwords. The list goes in the `passwords.context` option: ```php 'passwords' => [ @@ -284,7 +284,7 @@ Put in the names of your organisation, products, systems, projects, departments How they're compared: -- The whole password is compared, not the words inside it, as NIST SP 800-63B asks (Sec. 3.1.1.2). A password is refused when, with its digits, spaces and punctuation taken out, it is one of these words or several of them run together: `acme2026!`, `Taylor.Otwell.1990` and `acmeacmeacme` are refused. A passphrase that happens to have one in it is as hard to guess as any other, so `acme sells the best anvils` passes. Refusing it would be a composition rule by another name. +- The whole password is compared, not the words inside it, as NIST SP 800-63B-4 asks (Sec. 3.1.1.2). A password is refused when, with its digits, spaces and punctuation taken out, it is one of these words or several of them run together: `acme2026!`, `Taylor.Otwell.1990` and `acmeacmeacme` are refused. A passphrase that happens to have one in it is as hard to guess as any other, so `acme sells the best anvils` passes. Refusing it would be a composition rule by another name. - Case doesn't matter, and each value is also taken word by word, split at anything that isn't a letter or a digit: `Acme Rockets` counts `acme` and `rockets`. - Characters that stand in for letters count as those letters: `0` as `o`, `1` and `l` as `i`, `3` as `e`, `4` and `@` as `a`, `5` and `$` as `s`, `7` as `t`. So `k3yr1ng` is `keyring`. - Words under four characters don't count, because they turn up by chance. The exception is your app's name or a listed entry as a whole, which counts from three characters, so an app called `IBM` refuses `ibm-ibm-ibm`. Two characters or fewer never count. @@ -302,7 +302,7 @@ protected function passwordRules((Authenticatable&Model)|null $user = null, arra } ``` -Ask for more length, not for kinds of character. A composition rule (`mixedCase()`, `letters()`, `numbers()`, `symbols()`, or a pattern of your own that a password has to match) takes your app out of OWASP ASVS 6.2.5, which wants passwords of any composition accepted, and NIST SP 800-63B says the same. People meet such rules with `Password1!`, which the length rules and the lists above deal with better. +Ask for more length, not for kinds of character. A composition rule (`mixedCase()`, `letters()`, `numbers()`, `symbols()`, or a pattern of your own that a password has to match) takes your app out of OWASP ASVS 5.0.0 (6.2.5), which wants passwords of any composition accepted, and NIST SP 800-63B says the same. People meet such rules with `Password1!`, which the length rules and the lists above deal with better. ## Resetting the Password @@ -319,7 +319,22 @@ The email is Laravel's own `Illuminate\Auth\Notifications\ResetPassword`, sent t - dispatches `Keyring\Events\PasswordReset`, and Laravel's `Illuminate\Auth\Events\PasswordReset`, - redirects to the login page with the `password-reset` status. It never signs the user in, so the policy still applies at their next login. -Resets use Laravel's password broker (`passwords.broker`, or your default), so its token expiry and throttling apply. A reset link stops working as soon as the password changes through Keyring, the account's email address changes, or the user is deleted. Password reset keeps working while an account is locked, and lifts the lock, so a lock can't keep the owner out for good. +Resets use Laravel's password broker (`passwords.broker`, or your default), so two of its settings in `config/auth.php` are part of the flow: + +```php +'passwords' => [ + 'users' => [ + 'provider' => 'users', + 'table' => 'password_reset_tokens', + 'expire' => 60, + 'throttle' => 60, + ], +], +``` + +`throttle` is the seconds an account waits between reset links, and it's the only limit on how often one account is mailed. Keyring's own limit on `POST /forgot-password` is the [form limiter](configuration.md#pending-logins-timebox-and-rate-limits), 6 a minute per sender, which does nothing about many senders asking for one account. A new Laravel app has 60 seconds; Keyring neither sets it nor checks it when the app runs, so keep it, and the [conformance suite](testing.md#the-conformance-suite) fails when it's missing or zero. A request the broker throttles gets the same `reset-link-sent` answer as any other. `expire` is the minutes a link works for. OWASP's Forgot Password Cheat Sheet asks for both, and NIST SP 800-63B-4 (Sec. 4.2.1.2) for a link that lasts 24 hours at most: Keyring doesn't cap `expire`, so don't raise it past 1440. + +A reset link stops working as soon as the password changes through Keyring, the account's email address changes, or the user is deleted. Password reset keeps working while an account is locked, and lifts the lock, so a lock can't keep the owner out for good. ## Email Verification diff --git a/docs/quick-start.md b/docs/quick-start.md index 118707e3..aab68663 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -100,7 +100,6 @@ class SecurityController ->map(fn (Authenticator $authenticator) => [ ...$authenticator->factor()->present($authenticator), 'isDefault' => $authenticator->is_default, - 'lastUsedAt' => $authenticator->last_used_at?->toIso8601String(), ]) ->values(), 'enrollable' => Keyring::registered() @@ -120,7 +119,7 @@ class SecurityController | Prop | What it holds | |---|---| -| `authenticators` | What the user has set up. `present()` gives each one's `factor`, `id` and `name`, plus `hint` (a masked address) for email codes, and `remaining` and `replace` for recovery codes. The password is a virtual authenticator with no row of its own, so it's left out. | +| `authenticators` | What the user has set up. `present()` gives each one's `factor`, `id`, `name`, and `createdAt` and `lastUsedAt` (when it was added and last used, as ISO 8601 dates), plus `hint` (a masked address) for email codes, and `remaining` and `replace` for recovery codes. The password is a virtual authenticator with no row of its own, so it's left out. | | `enrollable` | The keys of the factors a user can add, such as `totp` and `passkey`, for your "add" buttons. It includes `recovery`, which only works once the user has another second factor, so show it as "generate recovery codes" next to those rather than as a way to sign in. | | `devices` | Where the user is signed in, with `Features::devices()`. The same list as [`GET /user/devices`](devices-and-sessions.md#listing-and-revoking-devices). | | `activity` | Recent [security log](security-log-and-emails.md#showing-recent-activity) entries, with `Features::securityLog()`. | @@ -184,10 +183,11 @@ use Keyring\Features; | `emailChanges()` | Email changes confirmed by the new address and undoable from the old one. Changing the email elsewhere then throws. | [Protected Changes](protected-changes.md#changing-the-email-address) | | `securityLog()` | A log of sign ins, failures, refusals and changes in `keyring_events`, and "was this you?" alerts. On unless you take it out, and then the events go to your app's log instead. | [Security Log & Emails](security-log-and-emails.md) | -A few more things are opt-in, but aren't in the features list: +A few more things aren't in the features list. They're in your `KeyringServiceProvider`, where `keyring:install` wrote a starting set of each: -- [Security emails](security-log-and-emails.md#security-emails): the `Keyring::notifications([...])` list in your `KeyringServiceProvider`, and the classes in `app/Notifications/Keyring`. -- [Risk signals](risk.md): `Keyring::risk()->signals([...])` in your `KeyringServiceProvider`. +- [Security emails](security-log-and-emails.md#security-emails): the `Keyring::notifications([...])` list, and the classes in `app/Notifications/Keyring`. The ones a feature needs are commented out until it's on. +- [Risk signals](risk.md): the `Keyring::risk()->signals([...])` list. Turning on devices is when to uncomment `NewDevice` and `InactiveAccount`. +- A [support contact](security-log-and-emails.md#a-support-contact) for those emails to name: `support_contact` in `config/keyring.php`. - [Requiring a second factor](policies.md#requiring-a-second-factor): the `keyring.enrolled` middleware, with `enrollment_url` set to your page for adding one. `keyring:install` sets both up when you answer yes to requiring one. Step-up sends users there too when they don't have what a route needs. ## Adding Sign-In Methods diff --git a/docs/recipes.md b/docs/recipes.md index 8e9d3154..16043151 100644 --- a/docs/recipes.md +++ b/docs/recipes.md @@ -176,11 +176,14 @@ public function toMail(object $notifiable): MailMessage 'details' => array_map(fn (string $label, string $value) => ['label' => $label, 'value' => $value], array_keys($details), $details), 'actionText' => $this->action(), 'actionUrl' => $this->action() === null ? null : $this->url, + 'contact' => $this->contact, ], ); } ``` +`$this->contact` is your [support contact](security-log-and-emails.md#a-support-contact), `null` until you set one. A template of your own has to show it itself: the published one does so in the `toMail()` this replaces. + Two things that catch people out: - **Keep `=>` and `>` out of the Blade inside ``.** Maizzle writes them as HTML entities, which breaks the directive. Pass a list of `['label' => ..., 'value' => ...]` rather than looping over keys and values, and write `@if ($details !== [])` rather than a count. @@ -543,7 +546,17 @@ use App\Models\User; Keyring::allowSignInWhen(fn (User $user) => $user->approved_at !== null); ``` -Withdrawing an approval signs the account out on its next request. See [Who May Sign In](sign-in-flow.md#who-may-sign-in). +Withdrawing an approval signs the account out on its next request, and that request ends its other sessions too. To end them all as you withdraw it, without waiting for a request, sign the account out yourself: + +```php +use Keyring\Sessions\Sessions; + +$user->forceFill(['approved_at' => null])->save(); + +app(Sessions::class)->signOutEverywhere($user); +``` + +See [Who May Sign In](sign-in-flow.md#who-may-sign-in). Approval can also be what lets a user add a sign-in method, in place of verifying their email address: diff --git a/docs/risk.md b/docs/risk.md index 32ea063c..b46a02ab 100644 --- a/docs/risk.md +++ b/docs/risk.md @@ -17,16 +17,35 @@ Risk signals look for things that make a sign in or session suspicious: a new device, a new country, a session cookie turning up in another browser. Each signal that fires adds a score. The scores add up (capped at 100) to a **level**, and you decide what to do at each level. -Risk is off until you pick signals in your `KeyringServiceProvider`: +The signals are picked in your `KeyringServiceProvider`. The one `keyring:install` publishes starts with those that make no network call and need nothing your app hasn't got, each one on only when the feature it reads from is: ```php -use Keyring\Risk\Signals\NewDevice; -use Keyring\Risk\Signals\SessionFingerprintChanged; +use Keyring\Risk\Signals; -Keyring::risk()->signals([NewDevice::class, SessionFingerprintChanged::class]); +Keyring::risk()->signals([ + Signals\SessionFingerprintChanged::class, + // These two read the security log: Features::securityLog(). + Signals\RepeatedFactorFailures::class, + Signals\SuccessAfterFailures::class, + // These two go by an account's devices: Features::devices(). + Signals\NewDevice::class, + Signals\InactiveAccount::class, + // Signals\RecentlyChangedRecovery::class, + // Signals\BreachedPassword::class, + // Signals\NewCountry::class, + // Signals\ImpossibleTravel::class, +]); ``` -Once signals are picked, Keyring responds to them as shown below unless you set your own responses. Without a [locator](devices-and-sessions.md#locations), the location signals never fire. The device signals and `InactiveAccount` need [`Features::devices()`](devices-and-sessions.md), and `RepeatedFactorFailures` and `SuccessAfterFailures` need [`Features::securityLog()`](security-log-and-emails.md). +With the installer's default features that is `SessionFingerprintChanged`, `RepeatedFactorFailures` and `SuccessAfterFailures`; `NewDevice` and `InactiveAccount` are written commented out until you turn on [`Features::devices()`](devices-and-sessions.md). The other four stay off until you turn them on yourself: + +- `BreachedPassword` makes a network call at every sign in, and [holds a user whose password it finds](#requiring-a-new-password) until they choose another. +- `NewCountry` and `ImpossibleTravel` need a [locator](devices-and-sessions.md#locations), and never fire without one. +- `RecentlyChangedRecovery` needs `Features::emailChanges()`. It's left off because of what the scores add up to, below. + +Keyring responds to what the signals find [as shown below](#responding-to-risk) unless you set your own responses. The starting set is chosen so that those responses can't keep out a user who has only a password. A step-up asks for a second factor from a user who has one and does nothing to one who hasn't, and the signals that can fire for such a user (`NewDevice`, `InactiveAccount` and `SuccessAfterFailures`) add up to 75, short of the 90 at which a sign in is refused. `RepeatedFactorFailures` only counts failures that follow a correct password, so it takes someone who knows the password to raise it. Adding `RecentlyChangedRecovery`, or raising a score, can take a password-only user past 90: check the sums when you change the list. + +An app that doesn't use the published provider has no signals until it calls `Keyring::risk()->signals([...])`. ## Built-in Signals @@ -42,7 +61,7 @@ In `Keyring\Risk\Signals`: | `InactiveAccount` | The account last signed in 90 days ago or more (the `after` option), and none of its sessions has been used since. | 30 | login | | `SuccessAfterFailures` | The first factor was right after five or more failed attempts on the account (the `threshold` option) in the last hour (`within`), counted since it last signed in. | 30 | login | | `SessionFingerprintChanged` | A signed-in session now comes from a different browser or platform than the one it was last seen in. IP changes alone don't count. | 60 | every request | -| `BreachedPassword` | The password just used appears in a public breach list. Not on by default: it makes a network call at sign in. | 40 | login | +| `BreachedPassword` | The password just used appears in a public breach list. It makes a network call at sign in, so the published provider leaves it off. Whatever it scores, Keyring's own response to it [holds the user until they choose a new password](#requiring-a-new-password). | 40 | login | `SessionFingerprintChanged` compares with the browser the session was last seen in, and acts on each change once. A cookie used by two browsers at once flips back and forth, so with the default response the owner is asked to verify again, and emailed, on every switch. To end such a session instead, have [your responder](#actions) answer `Action::reauthenticate()` at `Checkpoint::Request`. @@ -54,7 +73,7 @@ In `Keyring\Risk\Signals`: ### Telling the User -OWASP ASVS 5.0.0 requirement 6.3.5 asks that users hear about a sign in after a long quiet period, or one that follows several failures. On its own each of these two reaches `Level::Medium`, where Keyring asks for a second factor but sends nothing. Together they reach `Level::High`, which notifies. To email the user whenever either is found, without refusing anyone, answer for them in [your responder](#responding-to-risk) and register the `suspicious_activity` [notice](security-log-and-emails.md#email-types): +OWASP ASVS 5.0.0 requirement 6.3.5 asks that users hear about a sign in after a long quiet period, or one that follows several failures. On its own each of these two reaches `Level::Medium`, where Keyring asks for a second factor but sends nothing. Together they reach `Level::High`, which notifies. To email the user whenever either is found, without refusing anyone, answer for them in [your responder](#responding-to-risk). The `suspicious_activity` [notice](security-log-and-emails.md#email-types) is what's sent, and `keyring:install` registers it: ```php use Keyring\Risk\Action; @@ -99,7 +118,9 @@ Without your own responder, Keyring does this at every checkpoint: | High | `Action::stepUp()->notify()` | | Critical | `Action::deny()->revokeAllSessions()->notify()` | -At login, `revokeAllSessions()` is always ignored: a critical login is refused and the `suspicious_activity` email goes out if it's turned on, but the owner stays signed in everywhere else. +At login, `revokeAllSessions()` is always ignored: a critical login is refused and the `suspicious_activity` email goes out if it's registered, as it is by `keyring:install`, but the owner stays signed in everywhere else. + +One finding is answered whatever the level: when `BreachedPassword` finds the password that was just used in a breach, `->requirePasswordChange()` is added to the action above. See [Requiring a New Password](#requiring-a-new-password). Set your own in `KeyringServiceProvider`: @@ -139,14 +160,30 @@ Build an action with one of the static constructors and chain extras: | `Action::deny()` | Refuse the sign in with the usual "these credentials don't match" error. | Sign the session out. | | `->revokeAllSessions()` | Nothing, even from your own responder. Otherwise anyone with only the password could sign the owner out whenever they liked. | Sign out every session of the user, including this one, change their "remember me" token, stop trusting their devices and cancel any pending email change (`Sessions::signOutEverywhere()`). | | `->lockFor('1h')` | Refuse sign ins for that long. Trusted devices stay trusted, for the same reason sessions aren't revoked. | Refuse sign ins for that long, from now, and stop trusting the user's devices. | -| `->notify()` | Send the `suspicious_activity` security email, if it's turned on. | The same. | +| `->notify()` | Send the `suspicious_activity` security email, if it's registered. | The same. | | `->requirePasswordChange()` | Hold the user until they choose a new password. The sign in goes ahead unless the action also denies it, and the hold is there for whoever signs in next. | Hold them from this request on. | Locks are kept in the cache store named in `risk.store`. Clearing that store lifts every lock, so if it's your default store, `php artisan cache:clear` does too: give locks a persistent store of their own where that matters. A database or Redis store is the one to use. Octane's `octane` store loses every lock when the server restarts, among [other things](security.md#octanes-cache-store). While locked, every sign in fails with the usual generic error, and a "remember me" cookie is signed out instead of let back in. Sessions that are already signed in carry on. Password reset still works and lifts the lock, so a lock can't keep the owner out for good. Otherwise a lock lifts on its own when it expires. ### Requiring a New Password -NIST SP 800-63B-4 (Sec. 3.1.1.2) never has passwords changed on a schedule, and always has one changed when there's evidence it was compromised. Stepping up, notifying and locking don't do that: the password someone else knows is still the password. `requirePasswordChange()` holds the user on your change-password page until it isn't, which is the response for a signal about the password itself: +NIST SP 800-63B-4 (Sec. 3.1.1.2) never has passwords changed on a schedule, and always has one changed when there's evidence it was compromised. Stepping up, notifying and locking don't do that: the password someone else knows is still the password. `requirePasswordChange()` holds the user on your change-password page until it isn't, which is the response for a signal about the password itself. + +Keyring's own response does this for `BreachedPassword`. Turn the signal on, tell Keyring where your change-password form is, and a user who signs in with a password found in a breach is held until they choose another: + +```php +// app/Providers/KeyringServiceProvider.php +use Keyring\Risk\Signals\BreachedPassword; + +Keyring::risk()->push(BreachedPassword::class); + +// config/keyring.php +'password_change_url' => '/settings/password', +``` + +The sign in itself goes ahead as the level says (a second factor at the signal's own score of 40, when the user has one), and the hold is logged as `risk_password_change`. Without a `password_change_url` a held user gets a `403` on every page, so set it before turning the signal on. + +A responder of your own replaces all of Keyring's response, this part included. Keep it by answering for the finding: ```php use Keyring\Risk\Signals\BreachedPassword; @@ -154,7 +191,7 @@ use Keyring\Risk\Signals\BreachedPassword; Keyring::risk() ->push(BreachedPassword::class) ->respond(fn (Risk $risk) => match (true) { - $risk->has('breached_password') => Action::stepUp()->requirePasswordChange()->notify(), + $risk->has(BreachedPassword::FINDING) => Action::stepUp()->requirePasswordChange()->notify(), $risk->level === Level::Critical => Action::deny()->revokeAllSessions()->notify(), $risk->isElevated() => Action::stepUp(), default => Action::allow(), @@ -275,4 +312,4 @@ Keyring::require(fn (User $user, Attempt $attempt) => $attempt->risk?->has('new_ ## Events and Logging -When an action does anything, Keyring dispatches `Keyring\Events\RiskAssessed` with `user`, `risk`, `action` and `checkpoint` (the `Checkpoint` enum, `Checkpoint::Login` or `Checkpoint::Request`), and logs it under the strongest thing it did: `risk_denied`, `risk_reauthenticate`, `risk_locked`, `risk_step_up`, `risk_revoked_sessions` or `risk_notified`, with the checkpoint (`login` or `request`), score and reasons. +When an action does anything, Keyring dispatches `Keyring\Events\RiskAssessed` with `user`, `risk`, `action` and `checkpoint` (the `Checkpoint` enum, `Checkpoint::Login` or `Checkpoint::Request`), and logs it under the strongest thing it did: `risk_denied`, `risk_reauthenticate`, `risk_locked`, `risk_password_change`, `risk_step_up`, `risk_revoked_sessions` or `risk_notified`, with the checkpoint (`login` or `request`), score and reasons. diff --git a/docs/security-log-and-emails.md b/docs/security-log-and-emails.md index bf9dab48..bf545ec6 100644 --- a/docs/security-log-and-emails.md +++ b/docs/security-log-and-emails.md @@ -5,6 +5,7 @@ - [Entry Types](#entry-types) - [Severity](#severity) - [Request IDs](#request-ids) + - [Times](#times) - [Refusals That Repeat](#refusals-that-repeat) - [Refused Links](#refused-links) - [Showing Recent Activity](#showing-recent-activity) @@ -13,6 +14,7 @@ - ["Was This You?" Alerts](#was-this-you-alerts) - [Security Emails](#security-emails) - [Email Types](#email-types) + - [A Support Contact](#a-support-contact) - [Emails a Flow Needs](#emails-a-flow-needs) - [Your Own Templates](#your-own-templates) - [Slack, SMS and Other Channels](#slack-sms-and-other-channels) @@ -44,7 +46,7 @@ The one exception is `protection_bypassed`. If that entry can't be written, [`Ke ### Without the Table -Take `Features::securityLog()` out of your features and nothing is written to `keyring_events`, but the events are still recorded: each one becomes a line in your app's log, so there is never nothing. The line is `Keyring: {type}` at the entry's [severity](#severity), with the user (`{morph class}:{id}`), `factor`, `device_id`, `ip`, `user_agent`, `request_id` and `meta` as its context. `channel` names the log channel, and `null` is your default one: +Take `Features::securityLog()` out of your features and nothing is written to `keyring_events`, but the events are still recorded: each one becomes a line in your app's log, so there is never nothing. The line is `Keyring: {type}` at the entry's [severity](#severity), with `at` (the time, [with its offset](#times)), the user (`{morph class}:{id}`), `factor`, `device_id`, `ip`, `user_agent`, `request_id` and `meta` as its context. `channel` names the log channel, and `null` is your default one: ```php // config/logging.php @@ -66,6 +68,7 @@ How long those lines are kept, and who can read them, is then up to that channel | `factor_failed` | warning | A factor failed. | | | `second_factor_failed` | warning | A factor failed during a login after a correct password. | | | `locked_out` | warning | A rate limit started refusing an IP address for a factor, whether the answer said so or was that of a wrong password. [Logged once](#refusals-that-repeat), not for each request it refuses. Not linked to a user. | `retry_after` | +| `rate_limited` | warning | The [form limiter](configuration.md#pending-logins-timebox-and-rate-limits) started refusing requests to one of Keyring's other routes: registration, a reset, a change, an emailed link, or passkey options. [Logged once](#refusals-that-repeat) for each wait, per route. Linked to the signed-in user when there is one. | `limiter` (`keyring` or `keyring-login-options`), `route` (its name), `retry_after` | | `account_locked` | warning | Failed attempts got the password or a passkey refused until a password reset: the cap on failures in a row, or `limits.lock_after`. | | | `signed_out` | info | The user signed out. | | | `authenticator_added`, `authenticator_removed` | notice | | `name` | @@ -74,7 +77,7 @@ How long those lines are kept, and who can read them, is then up to that channel | `new_device` | notice | A sign in from a new device. | `device` | | `device_revoked` | info | A device was signed out. | `device` | | `device_reported` | warning | A device was signed out from the "this wasn't me" link. | `device` | -| `sessions_revoked` | info | "Sign out everywhere else", one session ended from the sessions list, or an administrator's `keyring:sign-out` for the user. | `count` | +| `sessions_revoked` | info | "Sign out everywhere else", one session ended from the sessions list, an administrator's `keyring:sign-out` for the user, or the first request refused for an account [the app keeps out](sign-in-flow.md#who-may-sign-in). | `count` | | `session_ended` | info | Keyring signed a session out on its own. | `reason`: `revoked`, `expired`, `idle`, `other_user`, `reused`, `risk` or `not_allowed` | | `remember_me_reused` | warning | A ["remember me" cookie was used twice](devices-and-sessions.md#a-cookie-used-twice), and the session ended for both browsers. The entry's address and user agent are the request that brought the used one; `device_id` is the device the ended session was on. | `device` | | `email_change_requested` | info | | | @@ -84,7 +87,7 @@ How long those lines are kept, and who can read them, is then up to that channel | `password_reset` | notice | A reset completed and cleared the account's [sign-in lockouts](security.md#rate-limiting). | `sign_in_locks_cleared` | | `protection_bypassed` | warning | `Keyring::withoutProtection()` was used. Linked to the signed-in user who did it. | `reason` | | `clone_suspected` | critical | A passkey or security key's counter went backwards. | `name` | -| `risk_step_up`, `risk_reauthenticate`, `risk_notified` | notice | A risk action did something. | `checkpoint`, `score`, `reasons` | +| `risk_step_up`, `risk_reauthenticate`, `risk_notified`, `risk_password_change` | notice | A risk action did something. `risk_password_change` is the user being [held until they choose a new password](protected-changes.md#requiring-a-password-change). | `checkpoint`, `score`, `reasons` | | `risk_denied`, `risk_locked`, `risk_revoked_sessions` | warning | A risk action refused, locked or signed out. | `checkpoint`, `score`, `reasons` | | `access_refused` | warning | A signed-in user asked for an authenticator, device or session that isn't theirs, or that doesn't exist (a 404 either way), or opened an email verification link made for another account (a 403). | `resource` (`authenticator`, `device`, `session` or `email_verification`), `id` (what was asked for, cut to 64 characters; for a session, its [handle](devices-and-sessions.md#listing-and-ending-sessions), never its registry ID) | | `enrollment_refused` | warning | A sign-in method wasn't added. | `reason`: `invalid` (the factor turned the confirmation down: a wrong code, a key it won't take) or `not_allowed` (the account [may not add one yet](authenticators.md#who-may-enroll)) | @@ -140,12 +143,18 @@ Context::add('trace_id', (string) Str::uuid()); Set `security_log.context_key` to the key you use, hidden or not. Then your own log lines for the request carry the same ID as its entries, and so does a queued job the request dispatched. When nothing is there, Keyring makes a UUID for the request and keeps it in the hidden context, so it adds nothing to your log lines. An ID longer than 64 characters is cut to fit. Set the key to `null` to leave `request_id` empty. +### Times + +An entry's `created_at` is a plain timestamp in your app's timezone (`app.timezone`), as every Laravel timestamp is. The column holds no offset, so an app set to a local timezone logs local times that can't be told from UTC by looking at the table. Leave `app.timezone` at `UTC`, which is Laravel's default and what OWASP ASVS 5.0.0 (16.2.2) recommends for a log, and convert for display. If yours isn't UTC, say so wherever the table is read or copied to. + +An entry written to [your app's log](#without-the-table) carries its time with its offset as `at`, such as `2026-11-08T14:05:09+00:00`, because Laravel stamps a log line without one. Keeping your servers' clocks in step is yours. + ### Refusals That Repeat Whoever is refused can ask again as often as they like, and entries are kept for months, so a refusal isn't allowed to fill the table a request at a time: -- **A lock is logged when it starts.** `locked_out` is written once per factor and IP address, and not again until the wait that lock gave is over. Every request it refuses in between still dispatches the `Lockout` event (and Laravel's), so listeners of yours see each one. -- **Refusals are counted.** `locked_out`, `access_refused`, `enrollment_refused`, `authenticator_removal_refused`, `link_refused`, `verification_refused`, and `factor_failed` for a name nobody has, are each written at most `security_log.refusals` times every `refusals_per` (20 an hour). They're counted about the account the entry is linked to, or per IP address when it's linked to nobody. +- **A lock is logged when it starts.** `locked_out` is written once per factor and IP address, and not again until the wait that lock gave is over. Every request it refuses in between still dispatches the `Lockout` event (and Laravel's), so listeners of yours see each one. `rate_limited` is the same for the form limiter: once per route for the account or IP address it's refusing, until that limiter has room again, with `RateLimited` dispatched for every refused request. +- **Refusals are counted.** `locked_out`, `rate_limited`, `access_refused`, `enrollment_refused`, `authenticator_removal_refused`, `link_refused`, `verification_refused`, and `factor_failed` for a name nobody has, are each written at most `security_log.refusals` times every `refusals_per` (20 an hour). They're counted about the account the entry is linked to, or per IP address when it's linked to nobody. - **The log says where it stopped.** The first entry left out is replaced by one `refusals_limited` entry naming its type, so a gap in the log is never silent. A failed factor for a real account isn't counted this way: the account's own [rate limits](security.md#rate-limiting) already bound how often it can fail, and the `RepeatedFactorFailures` and `SuccessAfterFailures` risk signals count those entries. Set `refusals` to `null` to write every refusal. The counts live in the rate limiter's cache store, like the limits themselves. @@ -250,19 +259,30 @@ Keyring::notifications([ 'recovery_codes_generated' => Notifications\RecoveryCodesGenerated::class, 'email_changed' => Notifications\EmailChanged::class, 'account_locked' => Notifications\AccountLocked::class, - // 'new_device' => Notifications\NewDevice::class, - // 'second_factor_failed' => Notifications\SecondFactorFailed::class, - // ... + 'new_device' => Notifications\NewDevice::class, + 'second_factor_failed' => Notifications\SecondFactorFailed::class, + 'suspicious_activity' => Notifications\SuspiciousActivity::class, + 'email_change_reverted' => Notifications\EmailChangeReverted::class, + // 'clone_suspected' => Notifications\CloneSuspected::class, ]); ``` -A security notice that isn't listed isn't sent, so that list is how you turn one on or off. NIST SP 800-63B asks for `authenticator_added`, `authenticator_removed`, `password_changed` and `recovery_code_used`, and `keyring:install` registers those four with `recovery_codes_generated`, `email_changed` and `account_locked` unless you answer no (or pass `--no-emails`), whichever sign-in methods you picked. Every notice's class is published either way, so turning another on or off is one line in that list. +A security notice that isn't listed isn't sent, so that list is how you turn one on or off. Unless you answer no (or pass `--no-emails`), `keyring:install` registers: + +- `password_changed`, `authenticator_added`, `authenticator_removed`, `recovery_code_used`, `recovery_codes_generated`, `email_changed`, `account_locked` and `suspicious_activity`, whichever sign-in methods and features you picked, +- `new_device` when `Features::devices()` is on, +- `second_factor_failed` when you picked a sign-in method besides the password, +- `email_change_reverted` when `Features::emailChanges()` is on. + +One of the last three that has nothing to announce yet is written commented out, with `clone_suspected`, so turning it on later is one line. Every notice's class is published either way. Nothing warns about a notice that isn't registered: with `--no-emails`, or in an app that doesn't use the published provider, no security notice is sent until you list some. -OWASP ASVS 5.0.0 asks for more. Requirement 6.3.7 is a notice after a change to how someone signs in: `password_changed`, `authenticator_added`, `authenticator_removed`, `recovery_codes_generated` and `email_changed`, which the installer has registered. Requirement 6.3.5 is a notice of a suspicious attempt: `new_device`, `second_factor_failed`, `account_locked`, and `suspicious_activity` with the [risk signals](risk.md#built-in-signals) you pick. Register the ones that are still commented out to meet it. [OWASP ASVS](owasp-asvs.md) has the whole list for each level. +NIST SP 800-63B-4 requires a notice when an authenticator is bound to an account (Sec. 4.1.2.1: `authenticator_added`, and `password_changed` for a new password), when an account is recovered (Sec. 4.2.3: `password_changed` after a reset, and `recovery_code_used`) and when recovery codes are replaced (Sec. 4.2.1.1: `recovery_codes_generated`). It recommends one when an authenticator is removed (Sec. 4.5: `authenticator_removed`). + +OWASP ASVS 5.0.0 asks for two kinds. Requirement 6.3.7 is a notice after a change to how someone signs in: `password_changed`, `authenticator_added`, `authenticator_removed`, `recovery_codes_generated`, `email_changed` and `email_change_reverted`. Requirement 6.3.5 is a notice of a suspicious attempt: `new_device`, `second_factor_failed`, `account_locked`, and `suspicious_activity` for what the [risk signals](risk.md#built-in-signals) find. The installer's defaults cover both as far as your features go, with one thing left to you for 6.3.5: a sign in after a long quiet period, or after several failures, is only announced once [your risk response notifies for it](risk.md#telling-the-user). [OWASP ASVS](owasp-asvs.md) has the whole list for each level. Calling `Keyring::notifications()` again adds to the list, `null` takes a type out, and an unknown type throws an `InvalidArgumentException`, so a typo doesn't quietly turn an email off. -An account is sent each kind of notice five times an hour at most (`limits.notices` every `limits.notices_per`), so nobody can make your app mail one person without end, by signing in from a new browser over and over, say. The [security log](#the-security-log) records every event either way. A `MustVerifyEmail` user gets none until their address is verified, because until then it's only what someone typed when registering. +An account is sent each kind of notice five times an hour at most (`limits.notices` every `limits.notices_per`), so nobody can make your app mail one person without end, by signing in from a new browser over and over, say. The [security log](#the-security-log) records every event either way. A `MustVerifyEmail` user gets none until their address is verified, because until then it's only what someone typed when registering. The one exception is `password_changed` after a password reset: the reset link went to that address, so whoever finished the reset reads its mailbox. The classes are ordinary Laravel notifications and they're yours: change the wording, the channels or the whole template, or register a different class altogether. Keyring builds each one through the container and passes what it has to say as named constructor arguments, so a class takes only the ones it wants. @@ -285,7 +305,7 @@ The security notices, each sent to the user: | `email_changed` | An email change applied. Sent to both the old and the new address. | | | `email_change_reverted` | An email change was undone. Sent to the current address, and to the new one when the change had applied. | | -Every notice is also passed `when` (the time as text, in the app's timezone), `at` (the same moment as a date, to format for the user's own timezone or language), and the `device` and `ip` of the request that caused it. The copy of `email_change_reverted` sent to the new address leaves those two out, since that address may be whoever took the account. +Every notice is also passed `when` (the time as text, in the app's timezone), `at` (the same moment as a date, to format for the user's own timezone or language), the `device` and `ip` of the request that caused it, and `contact`, [your support contact](#a-support-contact). The copy of `email_change_reverted` sent to the new address leaves those two out, since that address may be whoever took the account. Renaming a sign-in method, or choosing another as the default, sends nothing: neither changes what can sign in to the account. @@ -293,6 +313,29 @@ Renaming a sign-in method, or choosing another as the default, sends nothing: ne The published notices share an abstract `SecurityNotice` in the same folder, which holds the constructor, `via()` and `toMail()`. Each notice only says its subject and intro. They're queued once any open database transaction commits, so a change that's rolled back is never announced. +### A Support Contact + +NIST SP 800-63B-4 (Sec. 4.6) has a notice give clear instructions, including contact information, for a recipient who says the event wasn't theirs. Keyring can't know where your support is, so tell it: + +```php +// config/keyring.php +'support_contact' => 'https://example.com/support', // or 'support@example.com' +``` + +Every notification Keyring builds is then handed it as `contact`, a security notice or an email a flow needs alike. The published security notices, `VerificationCode` and `EmailChangeNotice` end with "If this wasn't you and you need help, contact us" and the contact, as a link when it's a URL or an email address (`Keyring\Support\MailText::contact()` writes the line). The three emails that say nothing happened and can be ignored (`ConfirmEmailChange`, `EmailAddressInUse` and `AlreadyRegistered`) don't show it. Left at `null`, the default, no email has the line: set it before you say your notices follow NIST. + +The same section has notices go to every address an account has, and asks for at least two. Keyring knows one, the `email` attribute, and mails your user model as Laravel does. To send every notice to more than one address, return them from the model: + +```php +// app/Models/User.php +public function routeNotificationForMail(): array +{ + return array_filter([$this->email, $this->backup_email]); +} +``` + +That also changes where Laravel's own mail notifications go, which is usually what you want. Keeping the second address, and verifying it before it's used, is your app's to build: see [Known Limitations](security.md#known-limitations). A notice's `via()` is yours too, so one can also go to another channel, like SMS or a push message. + ### Emails a Flow Needs Five emails are part of a flow rather than a notice. The flow can't work without one, so it throws `Keyring\Exceptions\MissingNotification`, naming the type, when none is registered: diff --git a/docs/security.md b/docs/security.md index 5fdaefef..ed2438a4 100644 --- a/docs/security.md +++ b/docs/security.md @@ -19,6 +19,7 @@ - [Secure Cookies](#secure-cookies) - [A Content Security Policy](#a-content-security-policy) - [Headers on Your Other Responses](#headers-on-your-other-responses) + - [Bot Checks](#bot-checks) - [Cryptography](#cryptography) - [Keys](#keys) - [Algorithms](#algorithms) @@ -28,12 +29,14 @@ - [What a Request Costs](#what-a-request-costs) - [Standards](#standards) - [Known Limitations](#known-limitations) + - [Where Keyring Departs From a Standard](#where-keyring-departs-from-a-standard) + - [Other Limits](#other-limits) ## Introduction -Keyring is built on OWASP's authentication, session management and forgot password guidance, and on NIST SP 800-63B-4. Its assurance levels follow NIST SP 800-63B-4 as far as a library can check. This page lists what it promises, so you can check your setup against it, and where it stops. +Keyring is built on OWASP ASVS 5.0.0, OWASP's cheat sheets on authentication, and NIST SP 800-63B-4. Its assurance levels follow NIST SP 800-63B-4 as far as a library can check. This page lists what it promises, so you can check your setup against it, and where it stops: [Standards](#standards) says where each choice comes from, and [Known Limitations](#known-limitations) where Keyring does something other than a standard says. -The [conformance suite](testing.md#the-conformance-suite) tests several of these guarantees against your own configuration. [OWASP ASVS](owasp-asvs.md) says what to turn on for each level of ASVS 5.0's authentication and session management chapters, requirement by requirement. +The [conformance suite](testing.md#the-conformance-suite) tests several of these guarantees against your own configuration. [OWASP ASVS and NIST SP 800-63B](owasp-asvs.md) goes through ASVS 5.0.0 requirement by requirement, says what to turn on for each of its levels, and what your app has to supply for each of NIST's. Guarantees about a [feature](quick-start.md#adding-features), such as devices or email changes, apply once that feature is on. @@ -47,22 +50,21 @@ Guarantees about a [feature](quick-start.md#adding-features), such as devices or - A password longer than its stored hash can check (72 bytes for bcrypt) fails like a wrong one, with the same error, timing and throttling, wherever Keyring checks a password: signing in, step-up, removing the last second factor and the current password on a change. The over-long value never reaches the hasher. - Passwords are put in Unicode's NFC form before they're measured, hashed or checked, so one set on a device that composes characters one way still works on a device that composes them another. - Pending logins are encrypted JSON in the session, never `serialize()`d, and expire after `pending_logins.keep_for`, as soon as the user's password or email address changes, or when `keyring.guard` is no longer the guard they started under. An emailed code could have gone to the address the account no longer has, so an email change and its undo both end a sign in that was waiting for one. -- The session ID is regenerated and the old one destroyed when a user proves a factor (signing in or stepping up), changes their password or signs out everywhere else, so a copied session cookie stops working, and someone who planted a session ID before the password step doesn't share the pending login. +- The session ID is regenerated and the old one destroyed when a user proves a factor (signing in or stepping up), changes their password or signs out everywhere else, so a copied session cookie stops working, and someone who planted a session ID before the password step doesn't share the pending login. On Laravel's `cookie` session driver, where there is nothing on the server to destroy, the old copy is signed out through its registry record instead. - A password reset never signs anyone in, so the policy still applies at the next login. - Registration doesn't reveal whether an address has an account, unless you set `registration.reveal_taken`. A free address, a taken one, one reserved for its previous owner and one whose account you keep out get the same response, status, cookies and session, after the same validation, in at least `timebox`, with one password hash each and every email sent after the response. Nobody is signed in by registering. Whether an address is taken is decided by Keyring, not by your action, so the guarantee doesn't depend on how the action is written, as long as it doesn't check for itself. See [Registration](sign-in-flow.md#without-revealing-who-has-an-account). - With that registration, an account can't be signed in until its address is verified, and a correct password is answered like a wrong one until then. Verifying takes the emailed link and the password together, so neither someone who registered an address they can't read mail for, nor its owner who never chose that password, ends up with a verified account. A finished password reset also verifies the address. - Checking a password can rehash it under the app's current settings. The new hash is only saved over the one that was checked, under a row lock, so a sign in that overlaps a reset can't write the old password back, and whatever device trust it was given is withdrawn when it's ended. - A login attempt can't sign the owner out. Risk responses at login never revoke sessions, change the "remember me" token or stop trusting devices, even from a custom responder. -- Keyring's responses send `Cache-Control: no-store, private`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY` and `Referrer-Policy: same-origin` (`no-referrer` on the pages emailed links open), and signing out sends `Clear-Site-Data`. ### Rate Limiting Every factor has its own limits, checked in the pipeline before the proof is looked at: -- **Per account**: `limits.per_account` attempts a minute (5). The account is the user: Keyring finds who a typed username belongs to before it counts, so every way of typing it shares one limit, guesses at login and when confirming count together, and two accounts never share a count however alike their usernames look. Browsers the account has signed in from before (they carry one of its device cookies) count in a bucket of their own, so someone guessing from elsewhere can't lock the owner out (OWASP's "device cookies"). They share that one bucket between them: a device cookie is made at every sign in from a new browser, so someone who could once sign in may hold any number, and with a bucket each they'd get the account's allowance of guesses once per cookie. A browser stops counting as known when a password reset or change, or a sign-out everywhere, takes the account back, until it signs in again. +- **Per account**: `limits.per_account` attempts a minute (5). The account is the user: Keyring finds who a typed username belongs to before it counts, so every way of typing it shares one limit, guesses at login and when confirming count together, and two accounts never share a count however alike their usernames look. Browsers the account has signed in from before (they carry one of its device cookies) count in a bucket of their own, so someone guessing from elsewhere can't lock the owner out, an idea taken from the OWASP Community page on device cookies. They share that one bucket between them: a device cookie is made at every sign in from a new browser, so someone who could once sign in may hold any number, and with a bucket each they'd get the account's allowance of guesses once per cookie. A browser stops counting as known when a password reset or change, or a sign-out everywhere, takes the account back, until it signs in again. - **Per typed username**: a sign in that names its account is counted under the name as typed as well, with the same numbers, whether or not anyone has it. Only this count says so when it refuses (the `429`). The account's own limit refuses quietly: the attempt is answered like a wrong password, in the same time, without the password being looked at. So a name is answered from its own history, and locking an account under one name doesn't show which other names belong to it, or which names have an account at all. - **Per IP address**: `limits.per_ip` attempts a minute (20), shared by every account on that address. A browser carrying the account's device cookie counts per IP for that account alone, so others on a shared address can't hold it up, and an attacker holding several of the account's device cookies still gets one count. Behind a load balancer, configure Laravel's [trusted proxies](#trusted-proxies), or every user shares the balancer's address. -- **In a row**: `limits.consecutive` failures (100, the most NIST SP 800-63B allows) on one of an account's authenticators, however slowly they come. Each authenticator app, security key and set of recovery codes has a count of its own, and so does the password. They're counted in the database, so clearing the cache doesn't start them over, and at the cap the authenticator is refused for the account until that's dealt with: nothing brings it back by itself (see [At the Cap](#at-the-cap)). `null` turns the cap off. Without it, guessing just under the per-minute limit would never stop. With `Features::devices()` on, browsers the account hasn't signed in from may only make `limits.consecutive_elsewhere` (80) of those failures. The rest are kept for the owner's own browsers, so someone guessing elsewhere can't use the whole cap up, and the two never add up to more than it. +- **In a row**: `limits.consecutive` failures (100, the most NIST SP 800-63B-4 allows, Sec. 3.2.2) on one of an account's authenticators, however slowly they come. Each authenticator app, security key and set of recovery codes has a count of its own, and so does the password. They're counted in the database, so clearing the cache doesn't start them over, and at the cap the authenticator is refused for the account until that's dealt with: nothing brings it back by itself (see [At the Cap](#at-the-cap)). `null` turns the cap off. Without it, guessing just under the per-minute limit would never stop. With `Features::devices()` on, browsers the account hasn't signed in from may only make `limits.consecutive_elsewhere` (80) of those failures. The rest are kept for the owner's own browsers, so someone guessing elsewhere can't use the whole cap up, and the two never add up to more than it. How they count: @@ -78,9 +80,9 @@ The per-minute counts, their locks and each typed name's own failures are kept i #### At the Cap -An authenticator that has failed `limits.consecutive` times in a row is disabled for that account, as NIST asks, and stays disabled until it's set up again. What that takes depends on the factor: +An authenticator that has failed `limits.consecutive` times in a row is disabled for that account, as NIST SP 800-63B-4 asks (Sec. 3.2.2), and stays disabled until it's set up again. What that takes depends on the factor: -- **One that can start a sign in** (the password, a passkey): a completed password reset, a new password chosen while signed in, or `Keyring::unlock($user)`. The sign-in form says to reset the password (`keyring::keyring.locked`), and Keyring dispatches `AccountLocked` and logs `account_locked`. Register the [`account_locked` notice](security-log-and-emails.md#email-types) to email the owner, who may not have been the one guessing. +- **One that can start a sign in** (the password, a passkey): a completed password reset, a new password chosen while signed in, or `Keyring::unlock($user)`. The sign-in form says to reset the password (`keyring::keyring.locked`), and Keyring dispatches `AccountLocked` and logs `account_locked`. The [`account_locked` notice](security-log-and-emails.md#email-types), which `keyring:install` registers, emails the owner, who may not have been the one guessing. - **A second factor**: the user signs in another way (another factor, or a recovery code), removes it and adds it again. The challenge page says so (`keyring::keyring.factor_locked`, with a `429`), and each refused attempt dispatches `Lockout` with a `retryAfter` of `null`. A password reset doesn't bring it back, since a reset only proves the mailbox. From a support tool of your own, `Keyring::unlock($user, 'totp')` clears one factor's failures and locks, whichever kind it is: @@ -110,7 +112,7 @@ By default every lock lifts by itself, the longest after a day, and it takes the ], ``` -An account locked that many times within a day on a factor that can start a sign in is then refused as it would be at the cap, however few failures that took. Locks double, so with the default one-minute window the fifth comes after about a quarter of an hour of steady guessing and at most eleven fit in a day: a higher number never holds anything. The sign-in form says to reset the password (`keyring::keyring.locked`) in place of counting down, and Keyring dispatches `AccountLocked` and logs `account_locked`. Register the [`account_locked` notice](security-log-and-emails.md#email-types) to email the owner that the account is locked and that resetting the password unlocks it. Like every security notice it isn't sent until you register it. +An account locked that many times within a day on a factor that can start a sign in is then refused as it would be at the cap, however few failures that took. Locks double, so with the default one-minute window the fifth comes after about a quarter of an hour of steady guessing and at most eleven fit in a day: a higher number never holds anything. The sign-in form says to reset the password (`keyring::keyring.locked`) in place of counting down, and Keyring dispatches `AccountLocked` and logs `account_locked`. The [`account_locked` notice](security-log-and-emails.md#email-types) emails the owner that the account is locked and that resetting the password unlocks it. `keyring:install` registers it; like every security notice, an app that hasn't registered it sends nothing. The lock ends with a completed password reset, a new password chosen while signed in, or `Keyring::unlock($user)`. It's kept in the database beside the failures in a row, so neither time nor a cleared cache lifts it. @@ -118,9 +120,9 @@ It follows the other limits' rules. Browsers the account has signed in from befo It's off by default: the cap ends the guessing either way, and this only gets someone who guesses fast there sooner, in a quarter of an hour in place of a day and a half. -Factors can set their own limits by overriding `limits()`. A factor that leaves out what the default `limits()` returns leaves out the cap on failures in a row too, so add to the list rather than replacing it. A reset only clears the keys the default `limits()` builds, so a factor with its own per-account keys should clear them in a `PasswordReset` listener. Other routes use Laravel's throttle middleware with the named `keyring` limiter: registration, password reset requests, resets, password changes, email change requests, enrollment confirmations, removing an authenticator, verification emails, the emailed email-change links and the "this wasn't me" link share 6 requests a minute per user, or per IP address for guests. Usernameless passkey options have their own limiter, `keyring-login-options`, at 60 requests a minute per IP address, because the login page fetches them on every load for autofill. Apps can redefine either limiter (see [Rate Limits](configuration.md#pending-logins-timebox-and-rate-limits)). Each account can be sent three codes per factor every 10 minutes (`limits.codes` and `limits.codes_per`), however many sign ins, step-ups or enrollments ask for them. +Factors can set their own limits by overriding `limits()`. A factor that leaves out what the default `limits()` returns leaves out the cap on failures in a row too, so add to the list rather than replacing it. A reset only clears the keys the default `limits()` builds, so a factor with its own per-account keys should clear them in a `PasswordReset` listener. Other routes use Laravel's throttle middleware with the named `keyring` limiter: registration, password reset requests, resets, password changes, email change requests, enrollment confirmations, removing an authenticator, verification emails, the emailed email-change links and the "this wasn't me" link share 6 requests a minute per user, or per IP address for guests. Usernameless passkey options have their own limiter, `keyring-login-options`, at 60 requests a minute per IP address, because the login page fetches them on every load for autofill. A request either one refuses is logged as `rate_limited`, once for each wait. Apps can redefine either limiter (see [Rate Limits](configuration.md#pending-logins-timebox-and-rate-limits)). Each account can be sent three codes per factor every 10 minutes (`limits.codes` and `limits.codes_per`), however many sign ins, step-ups or enrollments ask for them. -Mail that isn't a guess at anything has a count of its own, since a sign in that succeeds is never counted and the form limiter only counts the sender. An account is sent each kind of [security notice](security-log-and-emails.md#security-emails) five times an hour at most (`limits.notices` and `limits.notices_per`), with every event still in the security log. An account can ask to change its email address that often, and a typed address is mailed about a change that often, whichever accounts ask. An address is mailed by registration that often too (the verification link, another one for an account that never verified, or the notice that someone tried to register with it), however many times the form is sent. No security notice goes to a `MustVerifyEmail` user whose address isn't verified: whoever registered typed it, so it may be anyone's. +Mail that isn't a guess at anything has a count of its own, since a sign in that succeeds is never counted and the form limiter only counts the sender. An account is sent each kind of [security notice](security-log-and-emails.md#security-emails) five times an hour at most (`limits.notices` and `limits.notices_per`), with every event still in the security log. An account can ask to change its email address that often, and a typed address is mailed about a change that often, whichever accounts ask. An address is mailed by registration that often too (the verification link, another one for an account that never verified, or the notice that someone tried to register with it), however many times the form is sent. No security notice goes to a `MustVerifyEmail` user whose address isn't verified: whoever registered typed it, so it may be anyone's. The notice of a finished password reset is the exception, since the reset link went to that address. #### Octane's Cache Store @@ -139,7 +141,7 @@ The failures in a row and the locks held until a reset are in your database eith - TOTP codes can't be reused: each authenticator stores the last accepted time step, updated under a database row lock, so two requests with the same code can't both pass. - A TOTP code is accepted one 30 second step either side of now at most, and only during its own step with a [window of zero](factors.md#authenticator-apps-totp). No wider window can be set. - Each recovery code works once, used up under the same kind of row lock. Two different codes used at the same time both stay valid until used. -- A set that has had a code used says so until it's replaced (`shouldReplaceRecoveryCodes()`), for your app to send the user to make a new one. NIST SP 800-63B-4 (Sec. 4.2.1.1) asks for a new code after each use. Keyring doesn't issue one on its own, since only the user can save it, so that rule is met once your app sends them and they do. +- A set that has had a code used says so until it's replaced (`shouldReplaceRecoveryCodes()`), for your app to send the user to make a new one. Keyring doesn't issue one by itself: see [Known Limitations](#where-keyring-departs-from-a-standard). - Email codes are random, eight digits (shown as two groups of four, `1234 5678`; spaces are ignored), expire after 10 minutes, allow five wrong guesses per pending attempt, and are replaced by any newer code. A newer code doesn't reset the count, and at the limit the user has to start signing in again. A sent code only verifies the authenticator it was sent to. - No factor that sends codes, the built-in email codes or [one of your own](factors.md#writing-a-code-factor), can be registered with codes shorter than six digits or that last longer than ten minutes. Keyring throws a `LogicException` instead. - A sent code works once on every session driver. Its state isn't in the session: the code waiting to be typed (as a keyed hash), the wrong guesses at it and the fact that it was used are kept in the cache store the rate limits use (`cache.limiter`), under the pending sign in, step-up or enrollment it was sent for. A right code is used up the moment it's checked, even when a later step refuses the sign in, and of two requests that send it together one is refused. A newer code ends the one before it, and the guesses stay counted, whichever copy of the session the browser sends. That goes for every code factor, at sign in, step-up and enrollment. If that cache store is cleared, pending codes go with it and the user asks for another. @@ -149,7 +151,7 @@ The failures in a row and the locks held until a reset are in your database eith ### Second Factors and Step-Up -- Policies count distinct categories, so two factors of the same kind are never treated as multi-factor. +- Policies count distinct categories, so two factors of the same kind are never treated as multi-factor. AAL2 further needs one of the two to be something the user has (NIST SP 800-63B-4, Sec. 2.2.1): a password beside a factor that is only a biometric is an AAL1 session. - Assurance levels follow NIST SP 800-63B-4 as far as a library can check. A passkey that syncs reaches AAL2. AAL3 needs a phishing-resistant key that reports on every sign in that it can't leave its device, that was added with a verified attestation, and that either verified the user itself or was used with a password: another authenticator's user verification is never counted beside it. A key nothing vouches for stays at AAL2, though a policy or route can still ask for one with `deviceBound()`. - NIST AAL3 further needs authenticators and verifier cryptography validated to FIPS 140. Keyring can't supply or check either, so a session it calls AAL3 has met NIST's rules for the authentication and nothing more. - Email codes are opt-in (`EmailCode::asSecondFactor()`), since NIST doesn't accept email as an authenticator and the inbox can also reset the password. A code is a step at sign in and never a factor: a password and an emailed code is an AAL1 session, doesn't pass `keyring:aal2` or `keyring.enrolled`, doesn't earn a trusted device, and can't stand in for a possession factor the account has. @@ -172,18 +174,18 @@ The failures in a row and the locks held until a reset are in your database eith - "Remember me" can't outlast the session it was ticked for. Laravel's cookie alone signs nobody in: the browser also holds a Keyring cookie naming that session's registry record, and coming back carries the session on with the limits it started with and nothing proved. Once the record has timed out, been revoked or been ended by a risk response, both cookies are refused, even from a client that kept them after being told to delete them. - A "remember me" cookie works once. Coming back moves the session to a new record and gives the browser a new cookie, so a copy of the pair brings back nothing the browser it was taken from hasn't already had. If a used cookie is sent again, or a browser is still signed in on the record it named, two browsers held the same pair: the session ends for both, with a `RememberMeReused` event and a `remember_me_reused` log entry. The one exception is the same browser's other requests in the few seconds after (`sessions.remember_grace`), which join the session the first one resumed. They can't start another, and sending the cookie again doesn't make those seconds any longer. - A resumed session's device, IP address and browser are those of the request that resumed it, on a record of its own. A browser still on the record from before is never compared with them. -- Signing in and every step-up give the session a new ID and end the one before: destroyed on the server, and on Laravel's `cookie` session driver, where there is nothing to destroy, signed out through its registry record. - A user can always see their sessions and end any one of them or all the others (`/user/sessions`), whatever features are on. Ending needs a fresh verification, looking doesn't. Only their own can be found. - A session's registry ID, which its "remember me" cookie carries, is never sent to a page. The sessions list names each one by a keyed hash of it, which can't be turned back into the ID or used as a cookie. - A session whose registry record has gone missing is signed out rather than started over. - An administrator can end one user's sessions, or everyone's, with `php artisan keyring:sign-out`. "Remember me" brings none of them back. See [For Administrators](devices-and-sessions.md#for-administrators). +- An account your app stops letting sign in ([`allowSignInWhen()`](sign-in-flow.md#who-may-sign-in)) is refused wherever a session starts or carries on, and the first request that's refused ends every session the account has, with its "remember me" cookies and trusted devices. Until one of its sessions makes a request they're still on record, so call `Sessions::signOutEverywhere()` as you set your flag to end them there and then. - Signing a user out everywhere and a session moving to a new record take turns, so a "remember me" cookie coming back at that moment can't carry a session past the sign-out. - A revocation can't be undone by a request saving a stale copy of its session. - Laravel's session ID is never stored by Keyring or written to the security log. - Devices are recognised by a random, httpOnly cookie, stored as a hash. A device is never a factor, only an input to your policy and risk signals. - Keyring's two cookies (the device cookie and the "remember me" one) are httpOnly and `SameSite=Lax`. Once the app is served over HTTPS (`APP_URL` is `https`, or `session.secure` is on) they are always `Secure` and carry the `__Host-` prefix, or `__Secure-` when your cookies are shared with subdomains. See [Keyring's Cookies](devices-and-sessions.md#keyrings-cookies). - Signing out everywhere also stops trusting the other devices and cancels pending email changes, so whoever had the account can't skip the second factor on a device they trusted or finish a change they started. -- A device is only trusted after a login that verified two categories, never after the password alone. A login that verifies two categories, and any grant of trust, gives the browser a new cookie, so neither can rest on a cookie planted in the browser before the user signed in. +- A device is only trusted after a login that reached AAL2, never after the password alone or with an emailed code. A login that reaches AAL2, and any grant of trust, gives the browser a new cookie, so neither can rest on a cookie planted in the browser before the user signed in. - Every device stops being trusted when the password changes, an authenticator is removed, an email change is applied or a signed-in request places a risk lock. A lock placed by a login attempt doesn't, as above. ### Account Changes @@ -204,10 +206,11 @@ The failures in a row and the locks held until a reset are in your database eith - New passwords are checked against the 10,000 most common of 8 characters or more and the 3,000 most common of 15 or more, in every environment, and against your app's name, the words you list in `passwords.context` and the user's own name and email address, with look-alike characters read as letters. The whole password is compared, as NIST SP 800-63B-4 Sec. 3.1.1.2 requires: one made up of those words is refused, and a passphrase that only has one in it is not. - In production, new passwords are also checked against breach lists (Have I Been Pwned). That check lets a password through when the service can't be reached, unless you set `passwords.refuse_unchecked`. - New passwords are refused rather than silently cut short by bcrypt. With bcrypt that limit is 72 bytes, so hash with argon2id to accept every password up to `passwords.max`. -- Passwords never expire. A user can be held until they choose a new one, by a risk response or by your app, when there's evidence theirs is compromised (NIST SP 800-63B-4, Sec. 3.1.1.2). The hold outlasts signing out and clearing the cache, ends with a password change or reset, and is never placed on an account without a password. +- Passwords never expire. A user is held until they choose a new one when there's evidence theirs is compromised (NIST SP 800-63B-4, Sec. 3.1.1.2): by your app, by a risk response of yours, or by Keyring's own response when the `BreachedPassword` signal, which is off until you turn it on, finds the password they just signed in with in a breach. The hold outlasts signing out and clearing the cache, ends with a password change or reset, and is never placed on an account without a password. ### Links and Headers +- Every Keyring response is sent with `Cache-Control: no-store, private` and `X-Content-Type-Options: nosniff`, and signing out sends `Clear-Site-Data`. The referrer policy and the frame header are below. - Every emailed link (password reset, email change, email verification, "this wasn't me") is built from `APP_URL`, never from the request that caused the email: not its `Host` header, and not an `X-Forwarded-Prefix` your proxy passed on. - Signed links are signed over the path and query only, and checked with `keyring.signed:relative` (Laravel's `signed` middleware, with refused links logged), so a forged `Host` header can't redirect them. - Pages opened from emailed links (password resets, email verification, email changes, "this wasn't me") have the link's token or signature in their URL, so they're sent with `Referrer-Policy: no-referrer`: nothing the page loads is told its URL, your own assets and analytics included. A failed form still finds its way back, because Keyring notes the page in the session. @@ -225,6 +228,21 @@ Keyring::linkRootUsing(fn () => tenant()->url); Work it out from something the server knows. The request's `Host` header is whatever the sender says, and a link built from it sends a real reset token to their site. The signature covers the path and query, so links keep working under any root. +#### Tokens in Emailed Links + +An emailed link has to carry what makes it work, so its token or signature is in the URL of the page it opens. OWASP ASVS 5.0.0 (14.2.1) wants nothing sensitive in a URL, and for these links Keyring can't meet that. What it does is above: the page changes nothing and posts the token in the body of the request that acts, it's sent with `Referrer-Policy: no-referrer` and `Cache-Control: no-store`, and none of the links lasts long. A reset link stops working once it's used, or after `auth.passwords.*.expire` (60 minutes in a new app). An email change's confirming links last 24 hours (`email_changes.confirmable_for`) and its undo link a week (`revertable_for`), and each works once. A verification link lasts `auth.verification.expire` (60 minutes). + +The reset link also carries the account's email address, as Laravel's own does, and it stays. Laravel's broker finds a reset by its address: its table is keyed by the address and holds the token as a password hash, which can't be looked up. So the form has to post the address, and a link without it leaves the user to type it into a field that most reset pages, Laravel's starter kits' among them, show filled in and read-only. The address is also less than the token: it's who the email was sent to. To keep it out of the URL all the same, build the link yourself and have your page ask for the address. Keyring leaves a callback of yours alone: + +```php +use Illuminate\Auth\Notifications\ResetPassword; +use Keyring\Support\Url; + +ResetPassword::createUrlUsing(fn (User $user, string $token) => Url::route('password.reset', ['token' => $token])); +``` + +`Url::route()` builds from `APP_URL`, as Keyring's own link does. The `reset-password` page then gets an empty `email`. + ### Request Input A URL ends up in places a request's body doesn't: access logs, proxies, the browser's history. Laravel's `$request->input()` reads the query string as well as the body, so a password sent as `POST /login?password=...` would work, and be logged. @@ -239,19 +257,19 @@ A URL ends up in places a request's body doesn't: access logs, proxies, the brow - TOTP secrets are encrypted with `APP_KEY`. [Cryptography](#cryptography) lists every algorithm and key. - Recovery codes and email codes are stored as keyed hashes (HMAC-SHA-256). A recovery code is only stored with 112 random bits or more: Keyring's own have 128, those imported from Fortify 119, and no other form is stored or accepted. A sent code is far shorter, so its hash is kept in your cache for ten minutes at most and allowed five guesses. -- Keyed hashes never use `APP_KEY` itself. Each kind (recovery codes, one-time codes, reserved addresses, WebAuthn user handles) has a key of its own, derived from `APP_KEY` with HKDF, so a hash made for one can't pass as another and none is made with the key Laravel encrypts and signs with. +- Keyed hashes never use `APP_KEY` itself. Each kind (recovery codes, one-time codes, reserved addresses, WebAuthn user handles, session handles) has a key of its own, derived from `APP_KEY` with HKDF, so a hash made for one can't pass as another and none is made with the key Laravel encrypts and signs with. - Email change tokens are stored as SHA-256 hashes, and the addresses in a pending change are encrypted. - Device tokens are stored as SHA-256 hashes. +- A session's registry ID is stored as it is: see [Algorithms](#algorithms) for why one read from the database signs nobody in. - WebAuthn credential IDs longer than 512 characters are refused rather than cut short. - WebAuthn user handles are an HMAC of the user's model and ID, never the ID or email, so two user models with the same ID don't share one. -- The security log never holds passwords, codes, tokens or session IDs. ### Logging - Sign ins, failed factors, lockouts, session starts and ends, and every change to how an account signs in are recorded as shipped: in the [security log](security-log-and-emails.md) table, which is on by default, or in your app's log when you turn the table off. There is no setting that records nothing. -- What was refused is recorded too: a request for someone else's authenticator, device or verification link, a sign-in method that wasn't added, a removal that would have left the account unable to sign in, an emailed link with a wrong, ended or expired token or signature, and a verification the pipeline's final gate turned away. None of it changes the answer the requester gets. +- What was refused is recorded too: a request for someone else's authenticator, device or verification link, a sign-in method that wasn't added, a removal that would have left the account unable to sign in, an emailed link with a wrong, ended or expired token or signature, a request the form rate limiter turned away, and a verification the pipeline's final gate turned away. None of it changes the answer the requester gets. - No entry holds a password, code, token, signature, session ID or request body, in the table or in the app's log. Form validation errors aren't logged. -- Every entry carries a severity and the ID of the request that wrote it. +- Every entry carries a severity, the ID of the request that wrote it and the time. In the table the time is in your `app.timezone`, which is UTC unless you changed it; in your app's log it's written with its offset. See [Times](security-log-and-emails.md#times). - A refused request can't fill the log. A lock is logged once when it starts, not for each request it refuses, and refusals are capped per account or IP address, with one entry to say where the log stopped. See [Refusals That Repeat](security-log-and-emails.md#refusals-that-repeat). - A log write that fails never fails the sign in, with one exception: `Keyring::withoutProtection()` doesn't run unless its entry was written. - Old entries, devices, ended email changes and ended sessions are deleted every day by a task Keyring schedules itself, and a force deleted user's records are deleted with them. @@ -291,6 +309,7 @@ Keyring sets the headers and cookies of its own responses. The rest of what a br | `SESSION_SECURE_COOKIE=true` | Makes its own two cookies `Secure` and gives them the `__Host-` prefix | Change the flags or name of Laravel's session, CSRF or "remember me" cookies | | A `Content-Security-Policy`, with `frame-ancestors` | Sends `X-Frame-Options: DENY` on its own responses, unless yours already say who may frame them | Send a policy: your layout and assets decide what one has to allow. Stop your other pages being framed | | `X-Content-Type-Options: nosniff` on your own responses | Sends it, with `Cache-Control: no-store`, `X-Frame-Options: DENY` and a `Referrer-Policy`, on every Keyring response | Add headers to routes that aren't Keyring's | +| A bot check, if your forms need one | Limits how often anything can be tried, and makes every refusal take as long as the next | Tell a person from a script: no CAPTCHA, no challenge, no minimum time to fill in a form | ### HTTPS and HSTS @@ -353,6 +372,50 @@ Your other pages get nothing from Keyring, so send the policy on every HTML resp Keyring's middleware (`Keyring\Http\Middleware\AddSecurityHeaders`) is on Keyring's routes only. Send `X-Content-Type-Options: nosniff` on the rest of your app too, so a browser never treats a response as a type it doesn't say it is, and decide your own `Referrer-Policy` and `Cache-Control` for pages that show account details. A small middleware on your `web` and `api` groups, or your web server's config, covers all of it. If you take Keyring's middleware out of `keyring.middleware`, its responses lose `no-store`, `nosniff`, `X-Frame-Options` and their referrer policy unless yours send them. The pages emailed links open have a token in their URL, so they need `Referrer-Policy: no-referrer`. + +### Bot Checks + +Keyring slows guessing down with [rate limits](#rate-limiting) and doesn't try to tell a person from a script. It has no CAPTCHA, no challenge and no minimum time between showing a form and taking its answer. OWASP ASVS 5.0.0 asks for realistic human timing at Level 3 (2.4.2), and OWASP's Authentication Cheat Sheet suggests a CAPTCHA after failed attempts. Which service to use, when to show it and what to do for the people it gets wrong are your app's decisions, so the check is yours to add. + +For signing in, it's a [pipeline step](sign-in-flow.md#writing-a-step) of your own, put before the limits so a request that fails it is never counted as an attempt on anyone's account: + +```php +namespace App\Keyring; + +use Closure; +use Illuminate\Validation\ValidationException; +use Keyring\Pipeline\Context; + +class CheckForBots +{ + public function __construct( + protected BotCheck $bots, + ) {} + + public function handle(Context $context, Closure $next): Context + { + // Where a sign in starts. A challenge page only comes after a right password. + if ($context->identifying && ! $this->bots->passes($context->request)) { + throw ValidationException::withMessages(['captcha' => __('Please confirm you are not a robot.')]); + } + + return $next($context); + } +} +``` + +```php +// app/Providers/KeyringServiceProvider.php +use Keyring\Pipeline\Steps; +use Keyring\Pipeline\Steps\EnsureNotThrottled; + +Keyring::pipeline(fn (Steps $steps) => $steps->before(EnsureNotThrottled::class, CheckForBots::class)); +``` + +`BotCheck` stands for whatever you use: a CAPTCHA's server-side verification, or a signed timestamp from your form that says how long ago it was shown. The step runs inside the timebox, so a refusal takes as long as any other. + +Registration, password reset requests and the other forms don't go through the pipeline. For those, add a middleware of your own to [`keyring.middleware`](configuration.md#routes) that checks the routes you name (`register.store`, `password.email`). + ## Cryptography Everything Keyring does with a key or an algorithm, and where. It adds no cipher or hash of its own: each one below is PHP's, Laravel's or a library's. @@ -379,10 +442,11 @@ Rotating `APP_KEY` with the old key in `APP_PREVIOUS_KEYS` keeps encrypted value | HMAC-SHA-256 under a purpose key | Recovery codes; emailed codes, and those of your own code factors, while they wait in the cache to be typed; the lookup hash of an address an email change holds; the WebAuthn user handle; the handle a page knows a session by | Values that are only ever compared or looked up, never read back. | | SHA-256, unkeyed | Device tokens and email change tokens (confirm, current address, revert) | Long random tokens, so a copy of the table can't be used as one. Each has well over 128 bits, which is why a plain hash is enough. | | SHA-256, unkeyed | The mark a pending login keeps of the user's password hash and address, inside the encrypted session | Noticing that either changed. Not a secret. | -| HMAC-SHA-1, or HMAC-SHA-256 or HMAC-SHA-512 where the factor is [set up with one](factors.md#authenticator-apps-totp) | TOTP codes (RFC 6238), six digits every 30 seconds | A legacy algorithm in OWASP ASVS's terms, kept as the default because it's the one every authenticator app makes. | +| None: stored as it is | A session's registry ID, in `keyring_sessions` or the cache | Nothing, on purpose. The ID isn't a credential by itself. It only does anything from inside a Laravel session, which is kept on the server or, with the `cookie` driver, in a cookie encrypted with `APP_KEY`, or from inside the "remember me" cookie, which is encrypted the same way and only works beside Laravel's own. Someone who can read the table can make none of those without the key. Laravel keeps its own session IDs and `remember_token` the same way. | +| HMAC-SHA-1, or HMAC-SHA-256 or HMAC-SHA-512 where the factor is [set up with one](factors.md#authenticator-apps-totp) | TOTP codes (RFC 6238), six digits every 30 seconds | A legacy algorithm in OWASP ASVS 5.0.0's Appendix C (requirement 11.4.1), kept as the default because it's the one every authenticator app makes, and several ignore a request for another. | | Laravel's hash manager, with your `hashing.driver`: bcrypt by default, or Argon2id | Passwords, the hash an unknown account spends, and the reset tokens Laravel's broker stores | Keyring calls `Hash` and never picks the algorithm or its cost. | | ECDSA with P-256 and SHA-256 (ES256), Ed25519 (EdDSA), and RSASSA-PKCS1-v1_5 with SHA-256 (RS256, off by default, 2048 bits at least) | Signatures from passkeys and security keys, limited to [`webauthn.algorithms`](passkeys.md#signature-algorithms) | Proof of holding the key. SHA-256 also hashes the client data and the relying party ID, as WebAuthn defines. | -| X.509 path validation: ECDSA, Ed25519, Ed448 or RSASSA-PKCS1-v1_5 signatures over SHA-224 or longer, RSA keys of 2048 bits at least, never SHA-1 | Attestation chains, only for a factor with [`requireAttestation()`](passkeys.md#requiring-attestation) | Which maker's key this is. The algorithms are whatever the maker signed its certificates with, so this accepts RSA with PKCS #1 v1.5 padding, which ASVS doesn't approve: several makers' roots use it. Off by default. | +| X.509 path validation: ECDSA, Ed25519, Ed448 or RSASSA-PKCS1-v1_5 signatures over SHA-224 or longer, RSA keys of 2048 bits at least, never SHA-1 | Attestation chains, only for a factor with [`requireAttestation()`](passkeys.md#requiring-attestation) | Which maker's key this is. The algorithms are whatever the maker signed its certificates with, so this accepts RSA with PKCS #1 v1.5 padding, which ASVS doesn't approve: several makers' roots use it (requirement 11.6.1). Off by default. | | HMAC-SHA-256 with `APP_KEY`, by Laravel's URL signing | The email verification link and the "this wasn't me" link | That the link was made by your app, for that route, and hasn't expired. | | SHA-1, unkeyed | The address in Laravel's email verification link; shortening the cache keys of the rate limits, sent codes and enrollments; and the breached-password lookup, where Have I Been Pwned's API is asked by the first five characters of a SHA-1 | Nothing rests on it: the link is signed as above, a cache key isn't a secret, and the lookup is the API's own format, whether Laravel makes it or Keyring does (`passwords.refuse_unchecked`). | @@ -413,12 +477,14 @@ All of it comes from the operating system's generator, through PHP's `random_byt | The cipher | `app.cipher` | Laravel only reads what the current cipher wrote, so every authenticator secret and pending change has to be decrypted and saved again in a migration of your own before the old cipher goes. Pending logins and enrollments end. | | The WebAuthn algorithms | `webauthn.algorithms` and `webauthn.minimum_rsa_bits` | Adding one changes nothing stored. Removing one refuses the keys that sign with it, and their owners add a new key: a key's algorithm can't be changed. | | The TOTP digest | The factor's `algorithm` | Only apps added afterwards use it. An authenticator keeps the digest it was set up with, so moving everyone means each user adding their app again. | -| The keyed hash (HMAC-SHA-256) or how its keys are derived | Fixed in code | A new release would have to re-make them: reserved address hashes can be recomputed from the encrypted address, recovery codes can't be (only the hash is kept) and would be issued again, and a WebAuthn user handle stays for as long as the user has a key that knows it. Stored hashes carry no version tag. | +| The keyed hash (HMAC-SHA-256) or how its keys are derived | Fixed in code | A new release would have to re-make them: reserved address hashes can be recomputed from the encrypted address, recovery codes can't be (only the hash is kept) and would be issued again, and a WebAuthn user handle stays for as long as the user has a key that knows it. | | The token hash (SHA-256) | Fixed in code | Tokens can't be rehashed, since only the hash is kept. Device cookies and pending email change links would be issued again. | +Those last two are where Keyring stops short of OWASP ASVS 5.0.0's requirement 11.2.2, that any algorithm can be swapped. Its stored hashes carry no tag saying which scheme made them, so a release that changed one couldn't take the old and the new side by side: it would have to re-make what can be re-made and issue the rest again, as the table says. A tag is only worth having on the day of such a change, and neither algorithm has a weakness to move away from, so Keyring doesn't carry one yet. + ### Peppering Passwords -NIST SP 800-63B suggests, beyond the salted hash, a keyed hash or encryption of it under a secret kept apart from the database, often called a pepper. Keyring doesn't build one in, for three reasons. The password hash is your `users.password` column and Laravel's hasher, shared with everything else in your app that checks a password, so a pepper only Keyring knew about would break those. A pepper is only worth having when its key lives somewhere the database's attacker can't reach, and where that is (an HSM, a secrets manager, at least a separate environment variable) is your infrastructure's decision. And losing or rotating it locks out every user at once, so it needs a plan that belongs to whoever runs the app. +NIST SP 800-63B-4 recommends (Sec. 3.1.1.2), beyond the salted hash, a keyed hash or encryption of it under a secret kept apart from the database, often called a pepper. OWASP's Password Storage Cheat Sheet suggests the same. Keyring doesn't build one in, for three reasons. The password hash is your `users.password` column and Laravel's hasher, shared with everything else in your app that checks a password, so a pepper only Keyring knew about would break those. A pepper is only worth having when its key lives somewhere the database's attacker can't reach, and where that is (an HSM, a secrets manager, at least a separate environment variable) is your infrastructure's decision. And losing or rotating it locks out every user at once, so it needs a plan that belongs to whoever runs the app. Keyring checks and sets passwords through Laravel's `Hash`, so a pepper goes in there and covers every flow: signing in, confirming, password changes, resets and the rehash at sign in. Register a driver that wraps the one you use now: @@ -485,72 +551,115 @@ The operations below are the expensive ones, each with what stops a stranger fro | WebAuthn verification: decoding the response and checking one signature | Adding a key, and every sign in or step-up with one | At sign in, the factor's rate limits, checked before the response is read; adding a key is behind the `keyring` limiter and a fresh verification. Usernameless options are limited to 60 a minute per IP address. An RSA key is bounded to 16,384 bits by the library, since the work grows with the key. | | Attestation: a certificate chain of at most six, checked against each root you list for the model | Adding a key to a factor with `requireAttestation()` | The `keyring` limiter on enrollment, the cap on chain length, and nothing being fetched: no revocation lookups, no metadata download. | | Mail | A reset link, an email change, a verification link, an emailed code, a security notice | Reset and email-change mail is sent after the response. A verification link and an emailed code are sent during the request, unless you queue those notifications: a code is limited to three per factor every 10 minutes per account (`limits.codes`). The published security notices are queued, five of a kind an hour per account (`limits.notices`). The routes that ask for mail are behind the `keyring` limiter. | +| The risk signals' lookups: a few indexed queries on the security log, the account's devices and its sessions | A sign in that gets its first factor right, for the signals the published provider turns on, and one comparison of browser names on each signed-in request | They run after a correct first factor, which the rate limits bound. Each signal is a line in your provider to take out. | | A session lock | Sign in, challenge and enrollment routes | Requests in one session wait for each other, for up to Laravel's 10 seconds, and one that waited that long fails. One session can't hold up another. | ## Standards -Keyring's code and config say what each thing does. This is where the choices come from: +Keyring's code and config say what each thing does. This is where the choices come from. A row that says Keyring departs from a requirement has its reason under [Known Limitations](#known-limitations), and [OWASP ASVS and NIST SP 800-63B](owasp-asvs.md) has the standards the other way round: every requirement, and what Keyring does about it. | What Keyring does | From | |---|---| -| Assurance levels, and what reaches AAL2 and AAL3, as far as a library can check. AAL3 takes an attested key that can't leave its device, with its own user verification or a password. Validated authenticators and verifier cryptography, which NIST AAL3 also needs, are yours to supply | NIST SP 800-63B-4, Sec. 2 and Appendix B | -| Each level lapsing after idle and overall limits (AAL2: 1 hour, 24 hours; AAL3: 15 minutes, 12 hours). The session carries on at the level that's left, or ends with `sessions.end_on_lapse` | NIST SP 800-63B-4, Sec. 2.2.3, 2.3.3, 5.1 and 5.2 | -| A cap of 100 failures in a row on each of an account's authenticators, kept in the database, after which it's refused until it's set up again. A lower number for browsers the account hasn't signed in from is NIST's "additional technique" for keeping an attacker from locking the owner out. `Keyring::unlock()` switches one back on without binding it again, which NIST doesn't provide for | NIST SP 800-63B-4, Sec. 3.2.2 | -| Proving the strongest combination the account can give before adding a sign-in method, whatever the sign-in policy asks | NIST SP 800-63B-4, Sec. 4.1.2.1 | -| Passkeys and security keys as a phishing-resistant option | NIST SP 800-63B | -| Email codes being opt-in, and counting toward no level: a password and an emailed code is AAL1 | NIST SP 800-63B-4, Sec. 3.1.3.1, which doesn't accept email as an authenticator | -| The emails `keyring:install` turns on: password changed, sign-in method added or removed, recovery code used, new recovery codes, email address changed, account locked | NIST SP 800-63B, OWASP's Authentication Cheat Sheet and OWASP ASVS 5.0.0, 6.3.7 | -| Registration that answers the same for every address | OWASP ASVS 5.0.0, 6.3.8 | -| A notice after each change to how someone signs in, once registered: the password, a sign-in method added or removed, new recovery codes, the email address | OWASP ASVS 5.0.0, 6.3.7 | -| A notice of a suspicious attempt, once registered: a new device, a failed second factor, a locked account, and what the risk signals find, such as a sign in after a long quiet period or after several failures | OWASP ASVS 5.0.0, 6.3.5 | -| Password lengths: 8 with a second factor, 15 without, and no setting below 8 | OWASP ASVS 5.0.0, 6.2.1, and NIST SP 800-63B (15 for a password used alone, 8 as part of multi-factor) | +| **Assurance levels and sessions** | | +| Assurance levels, and what reaches AAL2 and AAL3, as far as a library can check. AAL2 takes two kinds of factor, one of them something the user has. AAL3 takes an attested key that can't leave its device, with its own user verification or a password. Validated authenticators and verifier cryptography, which NIST AAL3 also needs, are yours to supply | NIST SP 800-63B-4, Sec. 2.2.1, 2.3.1, 2.3.2 and Appendix B | +| Each level lapsing after idle and overall limits (AAL2: 1 hour, 24 hours; AAL3: 15 minutes, 12 hours). The session carries on at the level that's left, or ends with `sessions.end_on_lapse` | NIST SP 800-63B-4, Sec. 2.2.3, 2.3.3, 5.1 and 5.2. Carrying on departs from Sec. 5.2 | +| An idle and an absolute timeout on every session, kept on the server, with a longer idle one for "remember me" as a stated decision | OWASP ASVS 5.0.0, 7.3.1 and 7.3.2, and OWASP's Session Management Cheat Sheet. "Remember me" departs from NIST SP 800-63B-4, Sec. 5.1 | +| A new session ID, and the old session ended, on every sign in and step-up | OWASP ASVS 5.0.0, 7.2.4 | +| A session that is signed out, revoked or timed out can't be used again | OWASP ASVS 5.0.0, 7.4.1 | +| A deleted user's sessions end with them, and an account the app keeps out loses all of its sessions at the first request it's refused | OWASP ASVS 5.0.0, 7.4.2 (for ending them sooner, see [Who May Sign In](sign-in-flow.md#who-may-sign-in)) | +| A stated number of sessions per account, and what happens at it | OWASP ASVS 5.0.0, 7.1.2 | +| The option to end other sessions after any change to a sign-in method | OWASP ASVS 5.0.0, 7.4.3 | +| A command for administrators to end one user's sessions or everyone's | OWASP ASVS 5.0.0, 7.4.5 | +| Users seeing their sessions, and ending any or all of them after verifying again | OWASP ASVS 5.0.0, 7.5.2 | +| A "remember me" cookie that works once, with a used one ending the session | OWASP's Session Management Cheat Sheet, and refresh token rotation with reuse detection (RFC 9700) | +| **Rate limits** | | +| A cap of 100 failures in a row on each of an account's authenticators, kept in the database, after which it's refused until it's set up again. A lower number for browsers the account hasn't signed in from is one of the additional, risk-based techniques NIST allows for keeping an attacker from locking the owner out. `Keyring::unlock()` switches an authenticator back on without binding it again, which NIST doesn't provide for | NIST SP 800-63B-4, Sec. 3.2.2 | +| Locks that double each time, and a count of its own for the browsers the account has signed in from | OWASP's Authentication Cheat Sheet (exponential lockout) and the OWASP Community page "Slow Down Online Guessing Attacks with Device Cookies", adapted: known browsers share one bucket, and the cookie is a random token stored hashed | +| Limits per account, per typed username and per IP address on every factor, and a limiter on the other forms | OWASP ASVS 5.0.0, 2.4.1 and 6.3.1, and OWASP's Credential Stuffing Prevention Cheat Sheet | +| **Passwords** | | +| Password lengths: 8 with a second factor, 15 without, and no setting below 8 | OWASP ASVS 5.0.0, 6.2.1, and NIST SP 800-63B-4, Sec. 3.1.1.2 (15 for a password used alone, 8 as part of multi-factor) | | A password change taking the current password as well as the new one | OWASP ASVS 5.0.0, 6.2.3 | | Refusing the most common passwords: the top 10,000 of 8 characters or more and the top 3,000 of 15 or more | OWASP ASVS 5.0.0, 6.2.4 (at least the top 3,000 that fit the policy) | -| No composition rules, and any characters accepted | OWASP ASVS 5.0.0, 6.2.5, and NIST SP 800-63B | -| Passwords of at least 64 characters allowed, never silently cut short: up to `passwords.max` with argon2id, 72 bytes with bcrypt | OWASP ASVS 5.0.0, 6.2.9, and NIST SP 800-63B. Met with `HASH_DRIVER=argon2id`, not with bcrypt | -| Refusing passwords made up of the app's name, the words in `passwords.context`, or the user's name and email address, comparing the whole password | OWASP ASVS 5.0.0, 6.2.11, with 6.1.2 for the list, which is yours to fill in; NIST SP 800-63B-4 Sec. 3.1.1.2 for comparing the whole password | -| Refusing breached passwords, in production by default | OWASP ASVS 5.0.0, 6.2.12, and NIST SP 800-63B | -| Passwords of any Unicode characters, normalized to NFC before hashing | NIST SP 800-63B, password verifiers | -| Passwords never expiring, and a forced change on evidence of compromise when a risk response or your app asks for one | NIST SP 800-63B-4, Sec. 3.1.1.2 | +| No composition rules, and any characters accepted | OWASP ASVS 5.0.0, 6.2.5, and NIST SP 800-63B-4, Sec. 3.1.1.2 | +| Passwords of at least 64 characters allowed, never silently cut short: up to `passwords.max` with argon2id, 72 bytes with bcrypt | OWASP ASVS 5.0.0, 6.2.9, and NIST SP 800-63B-4, Sec. 3.1.1.2. Met with `HASH_DRIVER=argon2id`, not with bcrypt | +| Refusing passwords made up of the app's name, the words in `passwords.context`, or the user's name and email address, comparing the whole password | OWASP ASVS 5.0.0, 6.2.11, with 6.1.2 for the list, which is yours to fill in; NIST SP 800-63B-4, Sec. 3.1.1.2, for comparing the whole password | +| Refusing breached passwords, in production by default | OWASP ASVS 5.0.0, 6.2.12, and NIST SP 800-63B-4, Sec. 3.1.1.2 | +| Passwords of any Unicode characters, normalised to NFC before hashing | NIST SP 800-63B-4, Sec. 3.1.1.2. This departs from the letter of OWASP ASVS 5.0.0, 6.2.8 (verified exactly as received): nothing is truncated or has its case changed, but the bytes are normalised | +| Passwords never expiring, and a user held until they choose a new one on evidence of compromise: when your app says so, and by default when the `BreachedPassword` signal finds the password just used in a breach | NIST SP 800-63B-4, Sec. 3.1.1.2 | +| **Factors and codes** | | +| Passkeys and security keys as a phishing-resistant option | NIST SP 800-63B-4, Sec. 2.2.2 and 3.2.5 | +| Email codes being opt-in, and counting toward no level: a password and an emailed code is AAL1 | NIST SP 800-63B-4, Sec. 3.1.3.1, which doesn't accept email as an authenticator, and OWASP ASVS 5.0.0, 6.3.6 | | Two factors of the same kind not counting as two, and no weaker fallback for a user with a phishing-resistant factor | OWASP's Multifactor Authentication Cheat Sheet | -| Making everyone add a second factor with `keyring.enrolled` | OWASP ASVS 6.3.3 | -| Locks that double each time, and a count of its own for the browsers the account has signed in from | OWASP's Authentication Cheat Sheet and its "device cookies" guidance | -| Single-use codes: random, short-lived, limited guesses, stored hashed, a resend replacing the last | OWASP's Authentication Cheat Sheet | +| Making everyone add a second factor with `keyring.enrolled`, which the installer sets up once a second factor is picked | OWASP ASVS 5.0.0, 6.3.3 | +| Proving the strongest combination the account can give before adding a sign-in method, whatever the sign-in policy asks | NIST SP 800-63B-4, Sec. 4.1.2.1 | +| A recent verification before changing how someone signs in | OWASP's Authentication Cheat Sheet, and OWASP ASVS 5.0.0, 7.5.1 | +| Single-use codes: random, short-lived, limited guesses, stored hashed, a resend replacing the last, and bound to the sign in they were sent for | OWASP's Multifactor Authentication Cheat Sheet (One-Time Password Handling and Storage), and OWASP ASVS 5.0.0, 6.6.2 and 6.6.3 | | TOTP codes, recovery codes and sent codes that work once, whatever the session driver | OWASP ASVS 5.0.0, 6.5.1 | | Recovery codes with at least 112 random bits, which is what lets them be kept as keyed hashes rather than salted password hashes | OWASP ASVS 5.0.0, 6.5.2 | -| Sent codes of at least six digits | OWASP ASVS 5.0.0, 6.5.4 | -| Sent codes that last ten minutes at most | OWASP ASVS 5.0.0, 6.5.5 | -| TOTP codes accepted one time step either side of now, and no further | RFC 6238, section 5.2. This default deviates from OWASP ASVS 5.0.0, 6.5.5 (a 30 second maximum), which a window of zero meets: see [Known Limitations](#known-limitations) | -| Password resets: the same answer for every address, links built from `APP_URL`, no automatic sign in, every session signed out | OWASP's Forgot Password Cheat Sheet | -| Email changes confirmed from both addresses, and not trusting an address that just changed | OWASP's Authentication and Multifactor Authentication Cheat Sheets | -| A recent verification before changing how someone signs in | OWASP's Authentication Cheat Sheet | +| Sent codes of at least six digits, that last ten minutes at most | OWASP ASVS 5.0.0, 6.5.4 and 6.5.5 | +| TOTP codes accepted one time step either side of now, and no further | RFC 6238, Section 5.2 (one step back for delay) and Section 6 (a limit on drift either way). This default departs from OWASP ASVS 5.0.0, 6.5.5 (a 30 second maximum), which a window of zero meets | +| A passkey challenge of 32 random bytes that runs out on the server and is answered once | OWASP's Passkey Security Cheat Sheet, and OWASP ASVS 5.0.0, 6.7.2 | +| A sign-in method presented with when it was added and last used | OWASP's Passkey Security Cheat Sheet | +| ES256 and EdDSA signatures by default, and RS256 only when asked for, with keys of 2048 bits at least | OWASP ASVS 5.0.0, 11.2.3 and 11.6.1, and RFC 8812, Section 2 | +| **Notices and risk** | | +| The emails `keyring:install` turns on about changes: password changed, sign-in method added or removed, recovery code used, new recovery codes, email address changed, and an email change undone | NIST SP 800-63B-4 (Sec. 4.1.2.1, 4.2.1.1, 4.2.3, 4.5 and 4.6), OWASP's Forgot Password, Multifactor Authentication and Passkey Security Cheat Sheets, and OWASP ASVS 5.0.0, 6.3.7 | +| The emails it turns on about suspicious attempts: account locked, a new device, a failed second factor, and what the risk signals find | OWASP ASVS 5.0.0, 6.3.5, and OWASP's Multifactor Authentication and Credential Stuffing Prevention Cheat Sheets | +| A line in every notice saying who to contact, once `support_contact` is set | NIST SP 800-63B-4, Sec. 4.6 | +| Risk signals in the published provider, at sign in and on every request | OWASP ASVS 5.0.0, 8.2.4, and OWASP's Authentication and Session Management Cheat Sheets | +| **Account changes and registration** | | +| Registration that answers the same for every address | OWASP ASVS 5.0.0, 6.3.8 | +| Password resets: the same answer for every address, links built from `APP_URL`, no automatic sign in, every session signed out, second factors left as they are | OWASP's Forgot Password Cheat Sheet, and OWASP ASVS 5.0.0, 6.4.3 | +| The conformance suite failing an app whose password broker has no `throttle` | OWASP's Forgot Password Cheat Sheet (rate limiting per account) | +| Email changes confirmed from both addresses, and not trusting an address that just changed | OWASP's Authentication Cheat Sheet (changing a registered email address) and Forgot Password Cheat Sheet (recovery after suspected compromise) | +| **Headers, cookies and links** | | | Never caching auth pages and responses | OWASP's Session Management Cheat Sheet | -| `X-Content-Type-Options: nosniff` on every response, and a referrer policy | OWASP ASVS 3.4.4 and 3.4.5 | -| `X-Frame-Options: DENY` on every response, unless the app's own policy says who may frame it | OWASP's Clickjacking Defense Cheat Sheet. OWASP ASVS 3.4.6 asks for `frame-ancestors` in a content security policy, which is your app's to send | -| `Secure` cookies with the `__Host-` prefix | OWASP ASVS 3.3.1 and 3.3.3, and OWASP's Session Management Cheat Sheet | +| `X-Content-Type-Options: nosniff` and a referrer policy on every Keyring response | OWASP ASVS 5.0.0, 3.4.4 and 3.4.5 | +| `X-Frame-Options: DENY` on every Keyring response, unless the app's own policy says who may frame it | OWASP's Clickjacking Defense Cheat Sheet. OWASP ASVS 5.0.0, 3.4.6, asks for `frame-ancestors` in a content security policy, which is your app's to send | +| `Secure` cookies with the `__Host-` prefix | OWASP ASVS 5.0.0, 3.3.1 and 3.3.3, and OWASP's Session Management Cheat Sheet | | Cookie names that say what the cookie is for and not what set it (`known_device`, `remembered_session`) | OWASP's Session Management Cheat Sheet, on session ID name fingerprinting | | No referrer from pages whose URL holds a token | OWASP's Forgot Password Cheat Sheet | -| Emailed links that only act on a `POST`, with the token or signature in its body | OWASP ASVS 3.5.3 and 14.2.1, and OWASP's Cross-Site Request Forgery Prevention Cheat Sheet | -| Passwords, codes, credentials and tokens read from the body, never the query string of a `POST` | OWASP ASVS 14.2.1 and 15.3.7 | -| A passkey challenge that runs out on the server | OWASP's guidance on passkey challenges | -| A stated number of sessions per account, and what happens at it | OWASP ASVS 7.1.2 | -| A command for administrators to end one user's sessions or everyone's | OWASP ASVS 7.4.5 | -| The option to end other sessions after any change to a sign-in method | OWASP ASVS 7.4.3 | -| Users seeing their sessions, and ending any or all of them after verifying again | OWASP ASVS 7.5.2 | -| An idle and an absolute timeout on every session, kept on the server, with a longer idle one for "remember me" as a stated decision | OWASP ASVS 7.3.1 and 7.3.2, and OWASP's Session Management Cheat Sheet | -| Logging sign ins, failures, lockouts and session ends by default, and what was refused: someone else's record, a link's token or signature, a skipped pipeline step | OWASP ASVS 16.3.1 to 16.3.3 | +| Emailed links that only act on a `POST`, with the token or signature in its body | OWASP ASVS 5.0.0, 3.5.3, and 14.2.1 for the request that acts (the emailed link itself still has to carry its token in the URL once), and OWASP's Cross-Site Request Forgery Prevention Cheat Sheet | +| Passwords, codes, credentials and tokens read from the body, never the query string of a `POST` | OWASP ASVS 5.0.0, 14.2.1 and 15.3.7 | +| The browser package encoding what it puts in a URL path | OWASP ASVS 5.0.0, 1.2.2 | +| Keyring's own breached-password lookup following no redirect | OWASP ASVS 5.0.0, 15.3.2 | +| **Logging and storage** | | +| Logging sign ins, failures, lockouts and session ends by default, and what was refused: someone else's record, a link's token or signature, a rate-limited form, a skipped pipeline step | OWASP ASVS 5.0.0, 16.3.1 to 16.3.3 | | A severity and a request ID on every entry, no secrets in any, and a cap on entries a refused request can cause | OWASP's Logging Cheat Sheet | -| A list of what's stored and how it's protected, deleted on a schedule Keyring sets up itself | OWASP ASVS 14.1 and 14.2.7 | -| A "remember me" cookie that works once, with a used one ending the session | OWASP's Session Management Cheat Sheet, and refresh token rotation with reuse detection (RFC 9700) | +| A list of what's stored and how it's protected, deleted on a schedule Keyring sets up itself | OWASP ASVS 5.0.0, 14.1 and 14.2.7 | ## Known Limitations +### Where Keyring Departs From a Standard + +Each of these is a choice. The reason is given once, here, and the [requirement-by-requirement page](owasp-asvs.md) says what each means for an app that has to meet the requirement. + +- **A default install doesn't require a second factor.** With the installer's default answers the password is the only sign-in method, so there's nothing to require, and OWASP ASVS 5.0.0's requirement 6.3.3 (Level 2) isn't met. Which second factor your users get is your choice to make: pick one and the installer requires it of everyone unless you say otherwise. +- **Passwords are normalised before they're hashed.** OWASP ASVS 5.0.0 requirement 6.2.8 has a password verified exactly as received. Keyring cuts nothing short and changes no case, but it does put every password in Unicode's NFC form first, as NIST SP 800-63B-4 recommends (Sec. 3.1.1.2). The same "é" is one code point from some keyboards and two from others, and without this a password set on one device could fail on another. +- **Bcrypt stops passwords at 72 bytes.** It's Laravel's default hasher, and it ignores everything after the first 72 bytes, so with it Keyring refuses a longer password: 72 plain characters, but as few as 18 emoji, whatever `passwords.max` says. OWASP ASVS 5.0.0 requirement 6.2.9 asks for at least 64 characters, of any kind, to be allowed, and NIST SP 800-63B-4 recommends the same (Sec. 3.1.1.2). Set `HASH_DRIVER=argon2id` for that. Keyring doesn't pre-hash passwords to fit, which would leave hashes Laravel's own hasher can't check. See [Passwords](configuration.md#passwords). +- **By default a TOTP code works for longer than OWASP ASVS allows.** ASVS 5.0.0 requirement 6.5.5 gives a time-based one-time password a maximum lifetime of 30 seconds. Keyring accepts a code one time step either side of now unless told otherwise, so one code can work for up to about 90 seconds, and as shipped it does not meet that requirement. The default follows RFC 6238, which recommends accepting one earlier step for the time a code takes to arrive (Section 5.2) and allows a limit on clock drift either way (Section 6): with none, a code typed near the end of its 30 seconds fails, and so does every code from a phone whose clock is half a minute out. A code still works only once. To meet 6.5.5 exactly, register the factor with [a window of zero](factors.md#authenticator-apps-totp). A window wider than one step is refused. +- **TOTP codes are made with HMAC-SHA-1.** OWASP ASVS 5.0.0 lists it as a legacy algorithm (Appendix C, requirement 11.4.1). It's the default because it's the only digest every authenticator app makes, and several ignore a request for another without saying so, which would leave their users with codes that never work. Where you know your users' apps, [set the factor up with SHA-256 or SHA-512](factors.md#authenticator-apps-totp). +- **Windows Hello keys that only sign RS256 aren't taken by default.** RS256 isn't an algorithm OWASP ASVS approves, so `webauthn.algorithms` leaves it out, and on a machine whose Windows Hello makes nothing else, a passkey can't be created with it. See [RS256 and Windows Hello](passkeys.md#rs256-and-windows-hello) for who that affects and how to turn it on. Turning it on, or requiring attestation, whose makers sign their certificates the same way, takes Keyring outside ASVS's requirements 11.2.3 and 11.6.1. +- **Attestation is off unless you ask for it, only covers hardware keys, and checks no revocation list.** By default any WebAuthn authenticator is accepted and AAGUIDs aren't verified, so no session reaches AAL3. A factor set up with `requireAttestation()` checks `packed` and `fido-u2f` attestation against root certificates you list, and can then be limited to certain models. Platform formats (`tpm`, `android-key`, `apple`) aren't read. OWASP's Passkey Security Cheat Sheet has a verifier check a chain's status too: Keyring fetches nothing while a key is being added, so a maker's certificate that has been revoked is still accepted until you take its root out of your list. See [Attestation and AAGUIDs](passkeys.md#attestation-and-aaguids). +- **A used recovery code isn't replaced automatically.** NIST SP 800-63B-4 (Sec. 4.2.1.1) has a new code issued after each use. Keyring uses the code up and stops there, because a new one is only worth something once its owner has seen and saved it, and a sign in is no place to show it. The set says a code has been used (`shouldReplaceRecoveryCodes()`), and the rule is met once your app sends the user to [make a new set](authenticators.md#recovery-codes). +- **"Remember me" signs a browser back in without a factor.** NIST SP 800-63B-4 (Sec. 5.1) doesn't accept a cookie in place of authentication. A browser that ticked "remember me" comes back signed in after its session idled out, for up to 14 days (`sessions.remember_idle`), because that is what the checkbox is for. Keyring ties the cookie to the session it was ticked for, lets it work once and gives the session it resumes no assurance level, so routes behind `keyring:aal1`, `keyring:aal2` or `keyring.fresh` ask again, but a route behind `auth` alone is reached on the cookie. Where you follow that section, leave the checkbox off your login form or set `sessions.end_on_lapse`. See [Inactivity and "Remember Me"](devices-and-sessions.md#inactivity-and-remember-me). +- **A session outlives its assurance level.** NIST SP 800-63B-4 (Sec. 5.2) ends a session when its inactivity or overall timeout passes. By default Keyring lowers the session's level instead: a session that signed in with two factors stops being AAL2 after an hour idle or 24 hours and carries on as AAL1, under the limits every session has. Sec. 5.1 allows a session to be treated as a lower level, and ending it would sign out the people who set up a second factor after an hour away while leaving everyone else signed in for 30 days. `sessions.end_on_lapse` ends it. See [Ending a Session With Its Level](devices-and-sessions.md#ending-a-session-with-its-level). +- **An account has one email address.** NIST SP 800-63B-4 asks for at least two addresses to send notices to (Sec. 4.6) and two to recover an account through (Sec. 4.2.1.2). Keyring knows the one in your user model's `email` attribute: it's where reset links, emailed codes and security notices go. A library with one attribute to read can't supply a second. To send every notice to more than one address, return them from `routeNotificationForMail()` ([A Support Contact](security-log-and-emails.md#a-support-contact) shows how). A second address that can recover the account, verified before it's used, is your app's to build. +- **A notice doesn't say who to contact until you say where.** NIST SP 800-63B-4 (Sec. 4.6) has a notice carry contact information. The published notices have the line and leave it out while [`support_contact`](security-log-and-emails.md#a-support-contact) is `null`, since only you know where your support is. +- **No pepper.** NIST SP 800-63B-4 (Sec. 3.1.1.2) and OWASP's Password Storage Cheat Sheet recommend one. See [Peppering Passwords](#peppering-passwords) for why it isn't built in and how to add it. +- **The breach check fails open by default.** Laravel's check lets a new password through when Have I Been Pwned can't be reached, leaving the bundled list of common passwords, so that an outage elsewhere doesn't stop registrations. OWASP ASVS 5.0.0's requirement 16.5.2 would have it refuse. Set `passwords.refuse_unchecked` to refuse the password instead, at the cost of no new passwords while the service is unreachable. Outside production the check doesn't run at all unless `passwords.uncompromised` is `true`. +- **The per-minute limits are kept in the cache.** Clearing the limiter's cache store starts the per-minute counts over and lifts their locks and risk locks, which OWASP ASVS 5.0.0's requirement 16.5.3 counts as failing open. A count on every attempt belongs somewhere fast, and what ends guessing doesn't depend on it: the failures in a row and the locks held until a reset are in your database. See [Rate Limiting](#rate-limiting). +- **An emailed link carries its token in its URL.** It has to, and OWASP ASVS 5.0.0's requirement 14.2.1 doesn't allow for it. See [Tokens in Emailed Links](#tokens-in-emailed-links) for what Keyring does about it, and why the reset link carries the address too. +- **Stored hashes don't say which scheme made them, and session registry IDs aren't hashed.** See [Changing an Algorithm](#changing-an-algorithm) and [Algorithms](#algorithms). +- **Form validation failures aren't logged.** OWASP ASVS 5.0.0's requirement 16.3.3 and OWASP's Logging Cheat Sheet list them among what to log. A missing field or a malformed address is an ordinary mistake and says nothing about an attempt on an account, and logging each would bury what does. Everything Keyring refuses for a reason is logged. +- **The log table's times have no offset.** OWASP ASVS 5.0.0's requirement 16.2.2 wants UTC or an explicit offset. `keyring_events.created_at` is a plain timestamp in your `app.timezone`, as every Laravel timestamp is. Leave `app.timezone` at UTC, its default. See [Times](security-log-and-emails.md#times). +- **A disabled account's sessions end when one of them is next used.** OWASP ASVS 5.0.0's requirement 7.4.2 ends them when the account is disabled. Keyring doesn't know that moment, because the flag is your app's: call `Sessions::signOutEverywhere()` as you set it. See [Who May Sign In](sign-in-flow.md#who-may-sign-in). +- **No bot check.** See [Bot Checks](#bot-checks). + +### Other Limits + - **Lockouts still reach new browsers.** Someone who knows a user's email can keep that account locked by guessing faster than the per-minute limit, and after 80 wrong passwords in a row (20 minutes at the quickest) the password is refused from every browser the account hasn't signed in from until its owner resets it. See [At the Cap](#at-the-cap). If they guess under one of the account's names and the owner types another, the owner is told the password is wrong rather than to wait, because saying more would tell a stranger the two names are one account. With `Features::devices()` on, browsers the owner has signed in from before keep their own limit and keep working. Without devices, the lock reaches every browser while the guessing goes on, and so does the cap. A password reset clears the password's counts and locks, but not a second factor's. - **Which browsers are known is kept in the cache.** A browser stops counting as known when the account is taken back, and that's recorded in the limiter's cache store with the mark a reset replaces. If the store loses its keys, a browser from before the reset counts as known again. It still can't pass the cap: known browsers and everyone else share it. - **A run of failures can begin with a few at once.** Once a kind of browser (the account's own, or everyone else) has failures on record, each of its attempts is counted before its proof is looked at. Its first aren't, so that an ordinary sign in writes nothing, and as many as the per-minute limit lets through at once (`limits.per_account`, 5) can be checked together. Each is counted when it fails. With the defaults that can't pass the cap. It could if `limits.consecutive_elsewhere`, or what's left of `limits.consecutive` above it, were set lower than `limits.per_account`. -- **By default a TOTP code works for longer than OWASP ASVS allows.** ASVS 5.0.0 requirement 6.5.5 gives a time-based one-time password a maximum lifetime of 30 seconds. Keyring accepts a code one time step either side of now unless told otherwise, so one code can work for up to about 90 seconds, and as shipped it does not meet that requirement. The default follows RFC 6238 (section 5.2), which recommends allowing one step for clock drift and delay: with none, a code typed near the end of its 30 seconds fails, and so does every code from a phone whose clock is half a minute out. A code still works only once. To meet 6.5.5 exactly, register the factor with [a window of zero](factors.md#authenticator-apps-totp). A window wider than one step is refused. -- **Windows Hello keys that only sign RS256 aren't taken by default.** RS256 isn't an algorithm OWASP ASVS approves, so `webauthn.algorithms` leaves it out, and on a machine whose Windows Hello makes nothing else, a passkey can't be created with it. See [RS256 and Windows Hello](passkeys.md#rs256-and-windows-hello) for who that affects and how to turn it on. -- **Attestation is off unless you ask for it, and only covers hardware keys.** By default any WebAuthn authenticator is accepted and AAGUIDs aren't verified, so no session reaches AAL3. A factor set up with `requireAttestation()` checks `packed` and `fido-u2f` attestation against root certificates you list, and can then be limited to certain models. Platform formats (`tpm`, `android-key`, `apple`) aren't read, and certificates aren't looked up for revocation. See [Attestation and AAGUIDs](passkeys.md#attestation-and-aaguids). - **No clone detection for synced passkeys.** Their counters are usually always zero. - **Protection only covers Eloquent saves.** Query builder updates and `saveQuietly()` skip the protected attribute check. - **Changing `APP_KEY` invalidates short-lived data.** Pending email codes stop working, and a user's first passkey after the change gets a different user handle (later ones reuse the handle their keys already have). Recovery codes and reserved email addresses keep working when the old key is in `APP_PREVIOUS_KEYS`, as encrypted values such as TOTP secrets do. @@ -560,8 +669,6 @@ Keyring's code and config say what each thing does. This is where the choices co - **Laravel's `cookie` session driver can't destroy an old session.** The session lives in the cookie, so nothing on the server can delete a copy of one. Keyring ends copies through the registry instead: a sign in, a step-up, a password change, signing out everywhere else and an applied email change all move the session to a new registry record and revoke the old one, and signing out revokes it, so a copy made before any of them is signed out on its next request. Three things remain. A copy keeps working until the next of those happens, or the session is revoked or times out, because until then it's the same cookie as the original. It's only turned away where the [session middleware](devices-and-sessions.md#the-session-middleware) runs. And a sign in that isn't finished has no record to swap, so the ID changes between its steps leave an earlier copy holding the pending login as it was, which the next entry covers. A server-side session driver has none of the three. - **The `cookie` session driver lets a browser send back what its session held.** With that driver the session lives in the browser, so it can send an earlier copy of its own cookie, and a pending login or enrollment is kept in the session. Nothing that must happen only once depends on it. TOTP steps and recovery codes are used up in your database. A sent code, its wrong guesses, the code that replaced it, each enrollment's one confirmation and each WebAuthn challenge's one answer are kept in your cache, with the limits on attempts per account and per IP address and codes sent, and failures in a row are counted in your database. Two things remain. An earlier copy returns a pending sign in or step-up to an earlier point, which only means proving a factor again: a WebAuthn challenge it still holds was either never answered, and is as good as it was, or was answered, and is refused. And what the cache remembers lasts as long as the cache does. If the rate limiter's store is cleared or drops keys, an answered challenge that hasn't yet expired (5 to 15 minutes from when it was issued) is forgotten, and whoever holds both an earlier copy of the session and the signed answer the key gave could send that answer again. A key that counts its signatures still refuses it, because the count hasn't moved on. A synced passkey, whose count stays at zero, would be accepted. The same goes for a used code and a confirmed enrollment, so keep that store somewhere [your deploys don't clear](#rate-limiting). A server-side session driver has neither: the challenge is gone from the one session there is. - **A request overlapping a session ID change can undo or lose it.** Laravel saves the session when each request ends, so a request still running when the ID changes can save the old session again, and a copied cookie would then keep working. A request sent with the old ID just after the change finds no session, and that browser has to sign in again. -- **The breach check fails open by default.** Laravel's check lets a new password through when Have I Been Pwned can't be reached, leaving the bundled list of common passwords. Set `passwords.refuse_unchecked` to refuse the password instead, at the cost of no new passwords while the service is unreachable. Outside production the check doesn't run at all unless `passwords.uncompromised` is `true`. -- **Bcrypt stops passwords at 72 bytes.** It's Laravel's default hasher, and it ignores everything after the first 72 bytes, so with it Keyring refuses a longer password: 72 plain characters, but as few as 18 emoji, whatever `passwords.max` says. OWASP ASVS 6.2.9 asks for at least 64 characters, of any kind, to be allowed. Set `HASH_DRIVER=argon2id` for that. Keyring doesn't pre-hash passwords to fit, which would leave hashes Laravel's own hasher can't check. See [Passwords](configuration.md#passwords). - **Location signals need trustworthy data.** `HeaderLocator` trusts request headers, so only use it behind a proxy that sets them and can't be bypassed. - **Session guards only.** Pending logins and step-up live in the session, so stateless API clients and mobile apps can't use the sign in flow directly. - **Work in progress.** Keyring hasn't been tagged or used in production yet. diff --git a/docs/sign-in-flow.md b/docs/sign-in-flow.md index a23a1c58..c9ce5231 100644 --- a/docs/sign-in-flow.md +++ b/docs/sign-in-flow.md @@ -110,14 +110,26 @@ Keyring asks wherever a session starts or carries on: - Every way of starting a sign in: the password, a passkey, and any factor of your own. - A sign in that's waiting for its second factor. - A "remember me" cookie. The session it would have carried on is ended, so the same cookies don't sign the account back in once it's allowed again. -- Each request of a session that's already signed in. It's signed out, with a `session_ended` entry whose reason is `not_allowed`. +- Each request of a session that's already signed in. It's signed out, with a `session_ended` entry whose reason is `not_allowed`. The first request that's refused also ends every other session the account has, with its "remember me" cookies, trusted devices and any pending email change (a `sessions_revoked` entry), so a session that stayed away doesn't work again once the account is let back. - Registration that [signs new users in](#saying-when-an-address-is-taken), which leaves this one signed out. An account that's turned away gets the same answer as one that doesn't exist. So does one whose address isn't verified yet, when registration [doesn't reveal who has an account](#without-revealing-who-has-an-account). What doesn't sign anyone in still works for it: a password reset, and the emailed links that confirm or undo an email change or report a device. The callback runs on every signed-in request, so answer from the user it's given rather than with a query. -Use this rather than a global scope on the user model to keep an account out. A scope makes the account look missing to Keyring, which ends nothing: its sessions, "remember me" cookies, trusted devices and any pending email change are all still there when the scope shows the account again, and no event fires to clear them. `allowSignInWhen()` ends each session on its next request. +Keyring only finds out that an account is kept out when one of its sessions makes a request. Until then the sessions are still in the registry, and they would work again if the account were let back before any of them came. To end them as you set your flag, sign the account out yourself: + +```php +use Keyring\Sessions\Sessions; + +$user->forceFill(['banned' => true])->save(); + +app(Sessions::class)->signOutEverywhere($user); +``` + +That is also what OWASP ASVS 5.0.0 (7.4.2) asks for: a disabled account's sessions end when it's disabled, not when they're next used. + +Use `allowSignInWhen()` rather than a global scope on the user model to keep an account out. A scope makes the account look missing to Keyring, which ends nothing: its sessions, "remember me" cookies, trusted devices and any pending email change are all still there when the scope shows the account again, and no event fires to clear them. Failed attempts count against the user your finder returns, however the username was typed, so an account has one limit whether someone guesses at its email address or its username. Keyring calls the finder once to count the attempt and again to check it, so keep it to a lookup. @@ -184,7 +196,7 @@ The page (`challenge` for logins, `confirm` for step-up) receives: |---|---| | `purpose` | `login` or `confirm`. | | `factor` | The key of the factor to verify now. | -| `authenticator` | How the factor presents this authenticator. Always `factor`, `id` and `name`. `id` is `null` for the password. Email codes add `hint`, a masked address like `t•••@example.com`. Recovery codes add `remaining`, and `replace`: whether a code has been used, so the user should [make a new set](authenticators.md#recovery-codes). | +| `authenticator` | How the factor presents this authenticator, without the dates a [settings page](authenticators.md#adding-an-authenticator) gets: whoever has only the password isn't told when its owner last signed in. Always `factor`, `id` and `name`. `id` is `null` for the password. Email codes add `hint`, a masked address like `t•••@example.com`. Recovery codes add `remaining`, and `replace`: whether a code has been used, so the user should [make a new set](authenticators.md#recovery-codes). | | `challenge` | Factor-specific props. See below. | | `alternatives` | The user's other authenticators that would help, for "try another way". Same shape as `authenticator`. | | `canTrustDevice` | Whether to show "don't ask again on this device". `true` for logins with `Features::devices()` on and `devices.trust_for` not `null`. | @@ -220,7 +232,7 @@ Post the proof to `POST /login/challenge/{factor}`: | `code` | `totp`, `email-code`, `recovery` and most custom factors. | | `credential` | `passkey`, `security-key`: the browser's WebAuthn response, as an object or a JSON string. | | `authenticator` | Optional. The authenticator ID. Defaults to the one the page showed, or the only one of that factor. | -| `trust` | Optional boolean. Trust this device for `devices.trust_for`, once this login has verified two categories. | +| `trust` | Optional boolean. Trust this device for `devices.trust_for`, once this login has reached AAL2. | For WebAuthn, the browser may answer with any of the user's keys of that factor, not just the one shown, and Keyring accepts it. @@ -260,7 +272,7 @@ Change both to fit your app, but leave out any check that the address is free. K ### Without Revealing Who Has an Account -By default (`registration.reveal_taken` is `false`), nobody can use the form to find out whether an address has an account. This is what OWASP ASVS 6.3.8 asks of registration. +By default (`registration.reveal_taken` is `false`), nobody can use the form to find out whether an address has an account. This is what OWASP ASVS 5.0.0 (6.3.8) asks of registration. - The answer is always the same: a redirect to the login page with the `registration-received` status ("Thanks for registering. We've emailed that address with what to do next."), or that status as JSON. Nobody is signed in. - Validation errors from your action are shown as usual. They're the same for every address, because your action never looks at whether it's taken. diff --git a/docs/step-up.md b/docs/step-up.md index 32653ee6..a4b9b3e8 100644 --- a/docs/step-up.md +++ b/docs/step-up.md @@ -62,7 +62,7 @@ app(SessionAssurance::class)->level()->atLeast(Assurance::AAL2); `keyring.fresh:15m` lets the request through when the user verified, in the last 15 minutes, the strongest combination their account can give, and at least as much as signing in would ask of them. The window takes any [duration](configuration.md#durations) and defaults to `15m`. -NIST SP 800-63B-4 (Sec. 4.1.2.1) has a new authenticator bound at the highest level the account can authenticate at, so what's asked here follows the account, not the sign-in policy: +NIST SP 800-63B-4 (Sec. 4.1.2.1) has a new authenticator bound at the highest level the account can authenticate at, or the level the new one will be used at if that is lower. Keyring always asks for the highest, so what's asked here follows the account, not the sign-in policy: - Users with only a password confirm with their password, so an account can always add its first sign-in method. - Users with two factors prove both again, even where the policy would sign them in with one. A stolen session plus one phished factor can't add, remove or change anything. diff --git a/docs/testing.md b/docs/testing.md index 5328eedd..931841bb 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -280,6 +280,7 @@ The suite checks that: - signing out revokes the registered session, - every route that uses the `auth` middleware for Keyring's guard also runs [`keyring.session`](devices-and-sessions.md#the-session-middleware), so a session that was revoked or timed out doesn't keep working there, - passwords of 64 characters are allowed: `passwords.max` is at least 64, and the hasher isn't bcrypt, which stops at 72 bytes, +- the password broker Keyring uses has a `throttle`, so one account can't be sent [a reset link](protected-changes.md#resetting-the-password) as often as anyone asks (skipped without `Features::resetPasswords()`), - no mandatory pipeline step was removed or replaced with `dangerouslyRemove()` or `dangerouslyReplace()`. If you take out a [mandatory step](sign-in-flow.md#mandatory-steps) on purpose, return its class from `keyringAcknowledgedDangerousSteps()` in your test class. If your `CreatesNewUsers` action validates fields other than `name`, `email`, `password` and `password_confirmation`, return a form it accepts from `keyringRegistration(string $email)`. diff --git a/js/src/enroll.ts b/js/src/enroll.ts index c5bb9c38..926c83ff 100644 --- a/js/src/enroll.ts +++ b/js/src/enroll.ts @@ -1,6 +1,6 @@ import { json } from './http.js' import { routes } from './routes.js' -import type { Enrollment } from './types.js' +import type { Authenticator, Enrollment } from './types.js' import { createCredential } from './webauthn.js' /** @@ -27,7 +27,7 @@ export async function confirmEnrollment(factor: string, enrollment: Record, recoveryCodes?: string[] }>('POST', routes.confirmEnrollment(factor), payload) + return json<{ authenticator: Authenticator, recoveryCodes?: string[] }>('POST', routes.confirmEnrollment(factor), payload) } /** @@ -41,11 +41,11 @@ export async function enroll(factor: string, data: Record = {}) } export function renameAuthenticator(id: string, name: string) { - return json('PATCH', routes.authenticator(id), { name }) + return json<{ authenticator: Authenticator }>('PATCH', routes.authenticator(id), { name }) } export function makeDefault(id: string) { - return json('PATCH', routes.authenticator(id), { default: true }) + return json<{ authenticator: Authenticator }>('PATCH', routes.authenticator(id), { default: true }) } /** diff --git a/js/src/routes.ts b/js/src/routes.ts index 3b873e89..04f353d0 100644 --- a/js/src/routes.ts +++ b/js/src/routes.ts @@ -13,17 +13,32 @@ export const routes = { set login(path: string) { login = path }, - loginOptions: (factor: string) => `${prefix}/login/${factor}/options`, - loginWith: (factor: string) => `${prefix}/login/${factor}`, - challenge: (purpose: Purpose, factor?: string) => `${routes.challengeBase(purpose)}${factor ? `/${factor}` : ''}`, - verify: (purpose: Purpose, factor: string) => `${routes.challengeBase(purpose)}/${factor}`, - send: (purpose: Purpose, factor: string) => `${routes.challengeBase(purpose)}/${factor}/send`, + loginOptions: (factor: string) => `${prefix}/login/${segment(factor)}/options`, + loginWith: (factor: string) => `${prefix}/login/${segment(factor)}`, + challenge: (purpose: Purpose, factor?: string) => `${routes.challengeBase(purpose)}${factor ? `/${segment(factor)}` : ''}`, + verify: (purpose: Purpose, factor: string) => `${routes.challengeBase(purpose)}/${segment(factor)}`, + send: (purpose: Purpose, factor: string) => `${routes.challengeBase(purpose)}/${segment(factor)}/send`, challengeBase: (purpose: Purpose) => `${prefix}${purpose === 'login' ? '/login/challenge' : '/confirm'}`, - enroll: (factor: string) => `${prefix}/user/authenticators/${factor}`, - confirmEnrollment: (factor: string) => `${prefix}/user/authenticators/${factor}/confirm`, - authenticator: (id: string) => `${prefix}/user/authenticators/${id}`, + enroll: (factor: string) => `${prefix}/user/authenticators/${segment(factor)}`, + confirmEnrollment: (factor: string) => `${prefix}/user/authenticators/${segment(factor)}/confirm`, + authenticator: (id: string) => `${prefix}/user/authenticators/${segment(id)}`, sessions: () => `${prefix}/user/sessions`, - session: (id: string) => `${prefix}/user/sessions/${id}`, + session: (id: string) => `${prefix}/user/sessions/${segment(id)}`, +} + +/** + * A factor's key or an ID as one path segment, whatever it holds. The server + * issues these, but nothing says a page passes one on untouched, and a slash + * or a question mark in one would aim the request, with the user's cookies, + * at another path. "." and ".." have no encoding a browser won't resolve + * away, so they're refused. + */ +function segment(value: string): string { + if (value === '.' || value === '..') { + throw new TypeError(`Keyring can't put [${value}] in a URL path.`) + } + + return encodeURIComponent(value) } export type Purpose = 'login' | 'confirm' diff --git a/js/src/types.ts b/js/src/types.ts index 0799dd34..07dc4831 100644 --- a/js/src/types.ts +++ b/js/src/types.ts @@ -1,5 +1,8 @@ import type { Purpose } from './routes.js' +/** + * A sign-in method as the challenge page offers it. + */ export interface AuthenticatorSummary { factor: string id: string | null @@ -9,6 +12,16 @@ export interface AuthenticatorSummary { replace?: boolean } +/** + * A sign-in method as a factor presents it everywhere else: in the answer to + * adding or renaming one, and on your settings page. The dates are ISO 8601. + * `lastUsedAt` is null until it's first used. + */ +export interface Authenticator extends AuthenticatorSummary { + createdAt: string | null + lastUsedAt: string | null +} + /** * Props Keyring sends to the challenge and confirm pages. */ diff --git a/js/tests/helpers.test.ts b/js/tests/helpers.test.ts index 85825790..8e541234 100644 --- a/js/tests/helpers.test.ts +++ b/js/tests/helpers.test.ts @@ -47,6 +47,44 @@ describe('routes', () => { expect(routes.authenticator('abc')).toBe('/user/authenticators/abc') }) + // OWASP ASVS 5.0.0, 1.2.2: a value put into a URL is encoded for where + // it goes, so it can't aim the request at another path. + test('keep a factor or an ID inside its own path segment, whatever it holds', () => { + expect(routes.authenticator('../sessions')).toBe('/user/authenticators/..%2Fsessions') + expect(routes.authenticator('abc/confirm')).toBe('/user/authenticators/abc%2Fconfirm') + expect(routes.authenticator('abc?default=1#x')).toBe('/user/authenticators/abc%3Fdefault%3D1%23x') + expect(routes.session('9f2c/../../logout')).toBe('/user/sessions/9f2c%2F..%2F..%2Flogout') + expect(routes.session('a b%2Fc')).toBe('/user/sessions/a%20b%252Fc') + expect(routes.enroll('totp/../../password')).toBe('/user/authenticators/totp%2F..%2F..%2Fpassword') + expect(routes.confirmEnrollment('totp?x')).toBe('/user/authenticators/totp%3Fx/confirm') + expect(routes.loginOptions('passkey/../..')).toBe('/login/passkey%2F..%2F../options') + expect(routes.loginWith('passkey#')).toBe('/login/passkey%23') + expect(routes.challenge('login', 'totp/send')).toBe('/login/challenge/totp%2Fsend') + expect(routes.verify('confirm', 'totp?')).toBe('/confirm/totp%3F') + expect(routes.send('confirm', 'email-code/x')).toBe('/confirm/email-code%2Fx/send') + + // Where each of those lands is the segment it was given, on this origin. + for (const path of [routes.authenticator('../sessions'), routes.session('9f2c/../../logout'), routes.loginOptions('passkey/../..')]) { + expect(new URL(path, 'https://app.example').pathname).toBe(path) + } + }) + + test('leave the keys and IDs the server issues as they are', () => { + expect(routes.verify('login', 'email-code')).toBe('/login/challenge/email-code') + expect(routes.enroll('security-key')).toBe('/user/authenticators/security-key') + expect(routes.authenticator('01JCM8Q3ZV7W9X2Y4T6R8S0A1B')).toBe('/user/authenticators/01JCM8Q3ZV7W9X2Y4T6R8S0A1B') + expect(routes.challenge('login')).toBe('/login/challenge') + }) + + test('refuse a segment a browser would resolve away, encoded or not', () => { + for (const dots of ['.', '..']) { + expect(() => routes.authenticator(dots)).toThrow(TypeError) + expect(() => routes.session(dots)).toThrow(TypeError) + expect(() => routes.loginWith(dots)).toThrow(TypeError) + expect(() => routes.verify('confirm', dots)).toThrow(TypeError) + } + }) + test('use an overridden route as written', () => { configureRoutes({ prefix: 'account', login: '/sign-in' }) diff --git a/src/Activity/RecordSecurityEvents.php b/src/Activity/RecordSecurityEvents.php index 8455fc9e..70aec3bb 100644 --- a/src/Activity/RecordSecurityEvents.php +++ b/src/Activity/RecordSecurityEvents.php @@ -32,6 +32,7 @@ public function subscribe(Dispatcher $events): array Events\Confirmed::class => 'confirmed', Events\FactorFailed::class => 'factorFailed', Events\Lockout::class => 'lockout', + Events\RateLimited::class => 'rateLimited', Events\AccountLocked::class => 'accountLocked', Events\LoggedOut::class => 'loggedOut', Events\AuthenticatorAdded::class => 'authenticatorAdded', @@ -110,6 +111,20 @@ public function lockout(Events\Lockout $event): void $this->log->recordRefusal('locked_out', factor: $event->factor, meta: ['retry_after' => $event->retryAfter], once: $event->factor, for: $event->retryAfter ?? Duration::seconds(config('keyring.limits.longest_lock'))); } + /** + * Like a lock, a full limiter refuses every request until it has room + * again, and is logged once for that wait: per limiter and route, for + * the account that's signed in or the IP address that asked. + */ + public function rateLimited(Events\RateLimited $event): void + { + $this->log->recordRefusal('rate_limited', $event->user, meta: [ + 'limiter' => $event->limiter, + 'route' => $event->route, + 'retry_after' => $event->retryAfter, + ], once: $event->limiter.'|'.$event->route, for: $event->retryAfter); + } + public function accountLocked(Events\AccountLocked $event): void { $this->log->record('account_locked', $event->user, $event->factor); diff --git a/src/Activity/SecurityLog.php b/src/Activity/SecurityLog.php index f263c58a..f707b6bc 100644 --- a/src/Activity/SecurityLog.php +++ b/src/Activity/SecurityLog.php @@ -205,11 +205,14 @@ protected function keep(SecurityEvent $event, bool $orWrite = false): ?SecurityE /** * The entry as a line in the app's log, at its own severity, with what - * the table would hold as its context. + * the table would hold as its context. The time is given with its + * offset: Laravel stamps a log line without one, so a line alone + * wouldn't say which timezone it was written in. */ protected function write(SecurityEvent $event): void { Log::channel(config('keyring.security_log.channel'))->log($event->severity->value, 'Keyring: '.$event->type, array_filter([ + 'at' => $event->created_at->toIso8601String(), 'user' => $event->authenticatable_id === null ? null : $event->authenticatable_type.':'.$event->authenticatable_id, 'factor' => $event->factor, 'device_id' => $event->device_id, diff --git a/src/Concerns/ManagesNotifications.php b/src/Concerns/ManagesNotifications.php index af22af4d..5f244eb1 100644 --- a/src/Concerns/ManagesNotifications.php +++ b/src/Concerns/ManagesNotifications.php @@ -53,14 +53,16 @@ public function hasNotification(string $type): bool } /** - * The app's notification of a type, or null when it hasn't one. + * The app's notification of a type, or null when it hasn't one. Each is + * also handed where to reach the app's support ("support_contact"), as + * $contact, for the ones that say who to turn to. * * @param array $arguments */ public function notification(string $type, array $arguments = []): ?Notification { return $this->hasNotification($type) - ? app($this->notifications[$type], $arguments) + ? app($this->notifications[$type], ['contact' => config('keyring.support_contact'), ...$arguments]) : null; } diff --git a/src/Console/ImportCommand.php b/src/Console/ImportCommand.php index 4376ee86..da3bd5a5 100644 --- a/src/Console/ImportCommand.php +++ b/src/Console/ImportCommand.php @@ -33,7 +33,7 @@ * * Recovery codes come across as keyed hashes of the codes exactly as * Fortify showed them, case included, which is what keeps them above the - * 112 random bits OWASP ASVS 6.5.2 asks of a code stored that way. + * 112 random bits OWASP ASVS 5.0.0 (6.5.2) asks of a code stored that way. */ #[AsCommand(name: 'keyring:import')] #[Description('Import authenticators from Fortify (TOTP, recovery codes and passkeys)')] diff --git a/src/Console/InstallCommand.php b/src/Console/InstallCommand.php index 21d8c3cc..d483ea74 100644 --- a/src/Console/InstallCommand.php +++ b/src/Console/InstallCommand.php @@ -4,6 +4,7 @@ namespace Keyring\Console; +use Closure; use Illuminate\Auth\EloquentUserProvider; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; @@ -64,7 +65,8 @@ class InstallCommand extends Command * The security notices registered unless the answer is no, and how the * question names each. One is only offered once its notification is * among the published ones, so a notice can be listed here before the - * release that brings its class. + * release that brings its class. One with nothing to announce in this + * app yet (announces) is listed commented out. */ protected const array NOTICES = [ 'password_changed' => 'password changed', @@ -74,6 +76,26 @@ class InstallCommand extends Command 'recovery_codes_generated' => 'new recovery codes made', 'email_changed' => 'email address changed', 'account_locked' => 'account locked', + 'new_device' => 'signed in on a new device', + 'second_factor_failed' => 'second factor failed after the right password', + 'suspicious_activity' => 'suspicious sign in or session', + 'email_change_reverted' => 'email change undone', + ]; + + /** + * The risk signals the provider starts with, and the feature each reads + * from. One whose feature is off is left commented out, there to turn on + * with it. They need no network call and nothing the app hasn't got, and + * their scores can't add up to a refused sign in for a user with only a + * password. The rest are in the provider commented out, each with what + * it needs. + */ + protected const array SIGNALS = [ + 'SessionFingerprintChanged' => null, + 'RepeatedFactorFailures' => 'security-log', + 'SuccessAfterFailures' => 'security-log', + 'NewDevice' => 'devices', + 'InactiveAccount' => 'devices', ]; /** @@ -133,7 +155,7 @@ public function handle(Filesystem $files): int if ($writesProvider) { $files->ensureDirectoryExists(dirname($provider)); - $files->put($provider, $this->provider($files, $factors, $this->emails($files), $enrolled)); + $files->put($provider, $this->provider($files, $factors, $this->emails($files, $features, $factors), $enrolled, $features)); } else { $this->components->warn("Skipped {$provider}, it already exists."); } @@ -152,6 +174,7 @@ public function handle(Filesystem $files): int in_array(Features::emailVerification(), $features, true) ? 'Make your User model implement MustVerifyEmail' : null, $this->migrated() ? null : 'Run php artisan migrate', 'Build the auth/* pages Keyring renders, see the "Quick Start" docs', + $writesConfig ? 'Set support_contact in config/keyring.php to a page or an address users can reach you at: the emails then say who to contact if something wasn\'t them' : null, match (true) { $enrolled && config('keyring.enrollment_url') === null && ! $writesConfig => 'Set enrollment_url in config/keyring.php to your page for adding a sign-in method: users are sent there until they have a second factor', $enrolled => 'Build your page for adding a sign-in method at '.self::ENROLLMENT_URL.', or point enrollment_url in config/keyring.php at yours: users are sent there until they have a second factor', @@ -195,7 +218,11 @@ protected function requiresSecondFactor(array $factors): bool }; } - protected function emails(Filesystem $files): bool + /** + * @param list $features + * @param list $factors + */ + protected function emails(Filesystem $files, array $features, array $factors): bool { return match (true) { $this->option('emails') => true, @@ -203,7 +230,10 @@ protected function emails(Filesystem $files): bool $this->input->isInteractive() => confirm( label: 'Email users when their password, sign-in methods or email address change?', default: true, - hint: Str::ucfirst(implode(', ', array_map(fn (string $type) => self::NOTICES[$type], $this->notices($files)))).'.', + hint: Str::ucfirst(implode(', ', array_map( + fn (string $type) => self::NOTICES[$type], + array_filter($this->notices($files), fn (string $type) => $this->announces($type, $features, $factors)), + ))).'.', ), default => true, }; @@ -222,6 +252,25 @@ protected function notices(Filesystem $files): array )); } + /** + * Whether a notice has anything to announce in this app: a new device + * takes devices, an undone email change takes email changes, and a + * failed second factor takes a sign-in method to ask for after the + * password. + * + * @param list $features + * @param list $factors + */ + protected function announces(string $type, array $features, array $factors): bool + { + return match ($type) { + 'new_device' => in_array(Features::devices(), $features, true), + 'email_change_reverted' => in_array(Features::emailChanges(), $features, true), + 'second_factor_failed' => $factors !== [], + default => true, + }; + } + protected function userModelHasKeyring(): bool { $provider = Keyring::provider(); @@ -318,12 +367,14 @@ protected function config(Filesystem $files, array $features, bool $enrolled): s /** * The provider with only the chosen sign-in methods, the middleware that - * makes everyone set up a second factor when that was asked for, and the - * security notices left commented when they weren't wanted. + * makes everyone set up a second factor when that was asked for, the + * risk signals the features can feed, and the security notices left + * commented when they weren't wanted. * * @param list $factors + * @param list $features */ - protected function provider(Filesystem $files, array $factors, bool $emails, bool $enrolled): string + protected function provider(Filesystem $files, array $factors, bool $emails, bool $enrolled, array $features = self::FEATURES): string { $remove = $factors === [] ? ['RecoveryCodes::class,'] : []; @@ -342,15 +393,37 @@ protected function provider(Filesystem $files, array $factors, bool $emails, boo }, ); - return $this->withNotices($files, $this->withoutUnusedImports($this->withoutOrphanedComments(implode("\n", $lines))), $emails); + return $this->withNotices( + $files, + $this->withSignals($this->withoutUnusedImports($this->withoutOrphanedComments(implode("\n", $lines))), $features), + fn (string $type) => $emails && $this->announces($type, $features, $factors), + ); + } + + /** + * Comment out each risk signal whose feature is off: it would find + * nothing, and it's there to turn on with the feature. + * + * @param list $features + */ + protected function withSignals(string $provider, array $features): string + { + $off = array_keys(array_filter(self::SIGNALS, fn (?string $feature) => $feature !== null && ! in_array($feature, $features, true))); + + return $off === [] + ? $provider + : (string) preg_replace('/^( +)(Signals\\\\(?:'.implode('|', $off).')::class,)$/m', '$1// $2', $provider); } /** * List each security notice on offer in the provider, after the one * before it when the stub doesn't have it yet, and commented out when - * the notices weren't wanted. One that isn't on offer is taken out. + * it isn't registered: the notices weren't wanted, or this one has + * nothing to announce yet. One that isn't on offer is taken out. + * + * @param Closure(string): bool $registers */ - protected function withNotices(Filesystem $files, string $provider, bool $emails): string + protected function withNotices(Filesystem $files, string $provider, Closure $registers): string { $offered = $this->notices($files); $after = "'already_registered' => "; @@ -365,7 +438,7 @@ protected function withNotices(Filesystem $files, string $provider, bool $emails continue; } - $line = fn (array $match) => $match[1].($emails ? '' : '// ').$entry."\n"; + $line = fn (array $match) => $match[1].($registers($type) ? '' : '// ').$entry."\n"; $provider = (string) (preg_match($listed, $provider) === 1 ? preg_replace_callback($listed, $line, $provider) diff --git a/src/Contracts/Factor.php b/src/Contracts/Factor.php index 7dd36a71..5ecd6d8f 100644 --- a/src/Contracts/Factor.php +++ b/src/Contracts/Factor.php @@ -102,7 +102,9 @@ public function limits(Request $request, ?Attempt $attempt): array; public function errorKey(): string; /** - * How this authenticator is shown in "try another way". + * How this authenticator is shown: on a page that manages them, and on + * the challenge page and in "try another way", which leave out when it + * was added and last used (createdAt, lastUsedAt). * * @return array */ diff --git a/src/Enums/Assurance.php b/src/Enums/Assurance.php index 43b66d76..61c3dfd3 100644 --- a/src/Enums/Assurance.php +++ b/src/Enums/Assurance.php @@ -23,15 +23,17 @@ enum Assurance: int case AAL1 = 1; /** - * At least two factors from different categories. An emailed code isn't - * one, so a password and a code is AAL1. + * Two factors from different categories, one of them something the user + * has: NIST never takes a biometric without the authenticator it + * unlocks. An emailed code isn't a factor, so a password and a code is + * AAL1. */ case AAL2 = 2; /** - * Two categories, from a phishing-resistant key that can't leave its - * device, was added with a verified attestation, and either verified - * the user itself or was used with a password. + * Two factors, one of them a phishing-resistant key that can't leave its + * device and was added with a verified attestation. The other is that + * key verifying the user itself, or a password. */ case AAL3 = 3; diff --git a/src/Enums/Severity.php b/src/Enums/Severity.php index 393fecd4..5b32e2cf 100644 --- a/src/Enums/Severity.php +++ b/src/Enums/Severity.php @@ -30,9 +30,10 @@ public static function of(string $type): self { return match ($type) { 'new_device', 'authenticator_added', 'authenticator_removed', 'recovery_code_used', 'email_changed', - 'password_changed', 'password_reset', 'risk_step_up', 'risk_reauthenticate', 'risk_notified' => self::Notice, + 'password_changed', 'password_reset', 'risk_step_up', 'risk_reauthenticate', 'risk_notified', + 'risk_password_change' => self::Notice, - 'factor_failed', 'second_factor_failed', 'locked_out', 'account_locked', 'device_reported', + 'factor_failed', 'second_factor_failed', 'locked_out', 'rate_limited', 'account_locked', 'device_reported', 'remember_me_reused', 'email_change_reverted', 'protection_bypassed', 'access_refused', 'enrollment_refused', 'authenticator_removal_refused', 'link_refused', 'refusals_limited', 'risk_denied', 'risk_locked', 'risk_revoked_sessions' => self::Warning, diff --git a/src/Events/RateLimited.php b/src/Events/RateLimited.php new file mode 100644 index 00000000..8c6f18b9 --- /dev/null +++ b/src/Events/RateLimited.php @@ -0,0 +1,32 @@ +length < self::MIN_LENGTH, LogicException::class, sprintf( - 'The [%s] factor sends %d digit codes. Keyring refuses codes shorter than %d digits: fewer are too easy to guess (OWASP ASVS 6.5.4).', + 'The [%s] factor sends %d digit codes. Keyring refuses codes shorter than %d digits: fewer are too easy to guess (OWASP ASVS 5.0.0, 6.5.4).', $this->key(), $this->length, self::MIN_LENGTH, )); throw_if($this->ttl < 1 || $this->ttl > self::MAX_TTL, LogicException::class, sprintf( - 'The [%s] factor keeps its codes for %d seconds. Keyring refuses a code that lasts longer than %d seconds, or no time at all: a sent code has ten minutes at most (OWASP ASVS 6.5.5).', + 'The [%s] factor keeps its codes for %d seconds. Keyring refuses a code that lasts longer than %d seconds, or no time at all: a sent code has ten minutes at most (OWASP ASVS 5.0.0, 6.5.5).', $this->key(), $this->ttl, self::MAX_TTL, )); } diff --git a/src/Factors/Factor.php b/src/Factors/Factor.php index 3bc162cb..eebb3d14 100644 --- a/src/Factors/Factor.php +++ b/src/Factors/Factor.php @@ -82,12 +82,18 @@ public function errorKey(): string return 'code'; } + /** + * With when it was added and last used, for a page that manages them. + * Null for one with no record of its own, like the password. + */ public function present(Authenticator $authenticator): array { return [ 'factor' => $this->key(), 'id' => $authenticator->isVirtual() ? null : $authenticator->id, 'name' => $authenticator->name, + 'createdAt' => $authenticator->isVirtual() ? null : $authenticator->created_at?->toIso8601String(), + 'lastUsedAt' => $authenticator->last_used_at?->toIso8601String(), ]; } diff --git a/src/Factors/RecoveryCodes.php b/src/Factors/RecoveryCodes.php index b133aa41..9e30a997 100644 --- a/src/Factors/RecoveryCodes.php +++ b/src/Factors/RecoveryCodes.php @@ -27,7 +27,7 @@ * Stored as keyed hashes, never in plain text. * * A keyed hash is quick to work out, so it's only enough for a code too long - * to guess: OWASP ASVS 6.5.2 asks for 112 random bits, and a slow, salted + * to guess: OWASP ASVS 5.0.0 (6.5.2) asks for 112 random bits, and a slow, salted * password hash for anything with fewer. So a code is only stored, and only * accepted, in one of two forms that have them: * @@ -220,7 +220,7 @@ protected function hash(#[\SensitiveParameter] string $code): string { return KeyedHash::make(KeyedHash::RECOVERY_CODES, $this->canonical($code) ?? throw new InvalidArgumentException( 'Keyring only stores recovery codes with 112 random bits or more: its own (26 base32 characters) or Fortify\'s (20 letters and digits). ' - .'A shorter code is too easy to guess to be kept as a keyed hash (OWASP ASVS 6.5.2).', + .'A shorter code is too easy to guess to be kept as a keyed hash (OWASP ASVS 5.0.0, 6.5.2).', )); } diff --git a/src/Factors/Totp.php b/src/Factors/Totp.php index 4d8879ac..6530c089 100644 --- a/src/Factors/Totp.php +++ b/src/Factors/Totp.php @@ -47,9 +47,10 @@ class Totp extends Factor implements Enrollable /** * A window of 1 takes the step before and the step after now as well, - * as RFC 6238 recommends for a clock that's a little off, so a code - * works for up to 90 seconds. OWASP ASVS 6.5.5 caps a code's life at 30 - * seconds, which is a window of 0. Nothing wider than 1 is accepted. + * as RFC 6238 allows for delay (Sec. 5.2) and a clock that's a little + * off (Sec. 6), so a code works for up to 90 seconds. OWASP ASVS 5.0.0 + * (6.5.5) caps a code's life at 30 seconds, which is a window of 0. + * Nothing wider than 1 is accepted. * * @throws LogicException * @throws InvalidArgumentException @@ -61,7 +62,7 @@ public function __construct( protected string $algorithm = 'sha1', ) { throw_if($window < 0 || $window > self::MAX_WINDOW, LogicException::class, sprintf( - 'The [%s] factor was given a window of %d. Keyring accepts 0 (a code works for its own 30 seconds, as OWASP ASVS 6.5.5 asks) or 1 (one step either side, for clocks that are a little off): a wider one keeps every code working for minutes.', + 'The [%s] factor was given a window of %d. Keyring accepts 0 (a code works for its own 30 seconds, as requirement 6.5.5 of OWASP ASVS 5.0.0 asks) or 1 (one step either side, for clocks that are a little off): a wider one keeps every code working for minutes.', self::KEY, $window, )); diff --git a/src/Http/Controllers/ChallengeController.php b/src/Http/Controllers/ChallengeController.php index c5a33a09..f35b0e1c 100644 --- a/src/Http/Controllers/ChallengeController.php +++ b/src/Http/Controllers/ChallengeController.php @@ -6,6 +6,7 @@ use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Keyring\Contracts\SendsCodes; use Keyring\Enums\Purpose; @@ -79,11 +80,11 @@ public function show(Request $request, ?string $factor = null): mixed return $this->keyring->render($purpose === Purpose::Login ? 'challenge' : $purpose->value, [ 'purpose' => $purpose->value, 'factor' => $authenticator->factor, - 'authenticator' => $authenticator->factor()->present($authenticator), + 'authenticator' => $this->option($authenticator), 'challenge' => $challenge, 'alternatives' => $options ->reject(fn (Authenticator $option) => $option->id === $authenticator->id) - ->map(fn (Authenticator $option) => $option->factor()->present($option)) + ->map($this->option(...)) ->values() ->all(), 'canTrustDevice' => $this->canTrustDevice($attempt, $authenticator), @@ -91,6 +92,19 @@ public function show(Request $request, ?string $factor = null): mixed ]); } + /** + * An authenticator as the challenge page offers it: what tells it from + * the others, without when it was added or last used. At sign in the + * page is shown to whoever has the password, who has no call to learn + * when its owner was last here. + * + * @return array + */ + protected function option(Authenticator $authenticator): array + { + return Arr::except($authenticator->factor()->present($authenticator), ['createdAt', 'lastUsedAt']); + } + /** * Whether "don't ask again on this device" could be earned here. Trust * takes a login that proved two factors, which an emailed code beside diff --git a/src/Http/Middleware/AuthenticateSession.php b/src/Http/Middleware/AuthenticateSession.php index 59644f2c..335e93a7 100644 --- a/src/Http/Middleware/AuthenticateSession.php +++ b/src/Http/Middleware/AuthenticateSession.php @@ -14,6 +14,7 @@ use Keyring\Events\NewDeviceSignedIn; use Keyring\Events\RememberMeReused; use Keyring\Events\SessionEnded; +use Keyring\Events\SessionsRevoked; use Keyring\KeyringManager; use Keyring\Login\SignIn; use Keyring\Risk\Assessment; @@ -68,7 +69,7 @@ public function handle(Request $request, Closure $next): Response // isn't left signed in, whatever kept them so: a session, a "remember // me" cookie, or a sign in the app started. if (! $this->keyring->allowsSignIn($user)) { - return $this->signOut($request, 'not_allowed'); + return $this->keepOut($request, $user); } $session = $this->sessions->current($request); @@ -136,6 +137,23 @@ protected function ended(RegisteredSession $session, Authenticatable $user, int }; } + /** + * Sign out someone the app no longer lets sign in. The first request + * that's refused ends every session the account has, with its "remember + * me" cookies and trusted devices: one that stayed away while the account + * was kept out would otherwise work again the moment it's let back. + * After that there are none left, so the account's other browsers are + * only signed out themselves as each finds out. + */ + protected function keepOut(Request $request, Authenticatable $user): Response + { + if ($this->sessions->registry()->forUser($user)->isNotEmpty()) { + SessionsRevoked::dispatch($user, $this->sessions->signOutEverywhere($user)); + } + + return $this->signOut($request, 'not_allowed'); + } + /** * Register a session that started some other way, like an app's own * Auth::login(). diff --git a/src/Http/Middleware/RequireFreshVerification.php b/src/Http/Middleware/RequireFreshVerification.php index 793eb9e4..1325691b 100644 --- a/src/Http/Middleware/RequireFreshVerification.php +++ b/src/Http/Middleware/RequireFreshVerification.php @@ -83,9 +83,11 @@ protected function requirement(Request $request): Requirement /** * The most the account's authenticators can prove together, whatever * the policy asks at sign in. NIST SP 800-63B-4 (Sec. 4.1.2.1) has a new - * authenticator bound at the highest level the account can reach, or a - * user who holds a key that can't leave its device could add another - * after proving only a password and a code. + * authenticator bound at the highest level the account can reach, or at + * the level the new one will be used at if that's lower. Keyring always + * asks for the highest: otherwise a user who holds a key that can't + * leave its device could add another after proving only a password and + * a code. * * A key nothing vouches for is asked for too: if it is what it says, it * is the best the account has. A recovery code is taken in a lost key's diff --git a/src/KeyringManager.php b/src/KeyringManager.php index 57acece3..02fdf528 100644 --- a/src/KeyringManager.php +++ b/src/KeyringManager.php @@ -348,7 +348,9 @@ public function recordedIp(Request $request): ?string * one nobody has approved yet. Keyring asks wherever a session starts or * carries on: every factor that can start a sign in, a sign in waiting * for its second factor, "remember me", and each request of a session - * that's already signed in, which is signed out once the answer is no. + * that's already signed in. Once the answer is no, that request is signed + * out and every other session of the account ends with it. To end them + * before any of them makes a request, call Sessions::signOutEverywhere(). * An account that's turned away is answered like one that doesn't exist. * So is one that hasn't verified its address yet, when registration * hides who has an account. @@ -461,7 +463,9 @@ public function unlock(Authenticatable&Model $user, ?string $factor = null): voi * every page sends them to keyring.password_change_url until the * password changes, by them or by a reset. Signing out doesn't shake it * off. Returns false for an account with no password, which is left - * alone. A risk response does the same with requirePasswordChange(). + * alone. A risk response does the same with requirePasswordChange(), + * as Keyring's own does when the BreachedPassword signal finds the + * password just used in a breach. */ public function requirePasswordChange(Authenticatable&Model $user, ?string $reason = null): bool { diff --git a/src/KeyringServiceProvider.php b/src/KeyringServiceProvider.php index 3f3ef404..068602be 100644 --- a/src/KeyringServiceProvider.php +++ b/src/KeyringServiceProvider.php @@ -44,6 +44,7 @@ use Keyring\Sessions\Sessions; use Keyring\Support\Duration; use Keyring\Support\PasswordRules; +use Keyring\Support\TooManyAttempts; use Keyring\Support\Url; use Keyring\WebAuthn\ConfiguredRoots; @@ -224,7 +225,9 @@ protected function configureEmailLinks(): void /** * The limit on Keyring's form routes (registration, resets, enrollment), * and on usernameless login options. Define your own "keyring" or - * "keyring-login-options" limiter to change them. + * "keyring-login-options" limiter to change them. Each answers a refused + * request with TooManyAttempts, which is Laravel's 429 and what gets the + * refusal into the security log. */ protected function configureRateLimiting(): void { @@ -232,12 +235,16 @@ protected function configureRateLimiting(): void // cache store, and a provider that boots after this one may be what // registers that store (Octane's "octane" store). $this->callAfterResolving(RateLimiter::class, function (RateLimiter $limiter) { - $limiter->for('keyring', fn (Request $request) => Limit::perMinute(6)->by($this->app->make(KeyringManager::class)->guard()->id() ?: $request->ip())); + $limiter->for('keyring', fn (Request $request) => Limit::perMinute(6) + ->by($this->app->make(KeyringManager::class)->guard()->id() ?: $request->ip()) + ->response(new TooManyAttempts('keyring'))); // The login page asks for these on every load, for passkey autofill, // and an office shares one address, so six a minute would be too few. // One a second still limits how many challenges a script can make. - $limiter->for('keyring-login-options', fn (Request $request) => Limit::perMinute(60)->by($request->ip())); + $limiter->for('keyring-login-options', fn (Request $request) => Limit::perMinute(60) + ->by($request->ip()) + ->response(new TooManyAttempts('keyring-login-options'))); }); } diff --git a/src/Login/Requirement.php b/src/Login/Requirement.php index 7c0cc1b0..bc6d562d 100644 --- a/src/Login/Requirement.php +++ b/src/Login/Requirement.php @@ -16,6 +16,8 @@ * factor: two of the same kind aren't multi-factor. Only authentication * factors count. "Steps" counts every category, so an emailed code, which * isn't one, can still be asked for without being taken for a factor. + * The assurance levels ask for more than a count: from AAL2 up, one of the + * factors has to be something the user has. */ final readonly class Requirement { @@ -43,9 +45,16 @@ public static function aal1(): self return new self(factors: 1); } + /** + * AAL2: two factors, one of them something the user has. NIST SP + * 800-63B-4 (Sec. 2.2.1) takes a password or a biometric only beside a + * physical authenticator, never the two alone. A passkey that verified + * the user is both at once. For two categories of any kind, ask for + * factors(2). + */ public static function aal2(): self { - return new self(factors: 2); + return new self(factors: 2, categories: [Category::Possession]); } /** @@ -57,7 +66,7 @@ public static function aal2(): self */ public static function aal3(): self { - return self::aal2()->including(Category::Possession)->attestedKey(); + return self::aal2()->attestedKey(); } public static function factors(int $count): self diff --git a/src/Notifications/SendSecurityNotifications.php b/src/Notifications/SendSecurityNotifications.php index df494025..aa1bd167 100644 --- a/src/Notifications/SendSecurityNotifications.php +++ b/src/Notifications/SendSecurityNotifications.php @@ -58,9 +58,13 @@ public function passwordChanged(Events\PasswordChanged $event): void $this->send($event->user, 'password_changed'); } + /** + * The reset link went to the account's address, so whoever finished the + * reset reads that mailbox. It's told even if nobody verified it before. + */ public function passwordReset(Events\PasswordReset $event): void { - $this->send($event->user, 'password_changed'); + $this->send($event->user, 'password_changed', addressProven: true); } public function authenticatorAdded(Events\AuthenticatorAdded $event): void @@ -142,7 +146,7 @@ public function emailChangeReverted(Events\EmailChangeReverted $event): void /** * @param array $with what this notice has beyond when, device and IP */ - protected function send(Authenticatable|AnonymousNotifiable $user, string $type, array $with = [], bool $describeRequest = true): void + protected function send(Authenticatable|AnonymousNotifiable $user, string $type, array $with = [], bool $describeRequest = true, bool $addressProven = false): void { // A model without Notifiable (say, staff that sign in through // another guard) has nowhere to send it, so it's skipped rather than @@ -153,7 +157,7 @@ protected function send(Authenticatable|AnonymousNotifiable $user, string $type, // An address nobody has verified may be anyone's: whoever registered // typed it. It hears about the account once it's proved to be theirs. - if ($user instanceof MustVerifyEmail && ! $user->hasVerifiedEmail()) { + if (! $addressProven && $user instanceof MustVerifyEmail && ! $user->hasVerifiedEmail()) { return; } diff --git a/src/Pipeline/ConsecutiveLimit.php b/src/Pipeline/ConsecutiveLimit.php index 3c175306..e1b64eed 100644 --- a/src/Pipeline/ConsecutiveLimit.php +++ b/src/Pipeline/ConsecutiveLimit.php @@ -10,7 +10,7 @@ /** * Failures in a row on one of an account's authenticators, however slowly - * they come: 100 by default, NIST SP 800-63B's cap. They're counted in the + * they come: 100 by default, NIST SP 800-63B-4's cap. They're counted in the * database, so clearing the cache doesn't start the count over, and at the * cap the authenticator is refused for the account until that's dealt with. * Nothing brings it back by itself. diff --git a/src/Risk/RiskEngine.php b/src/Risk/RiskEngine.php index c59ee013..24991094 100644 --- a/src/Risk/RiskEngine.php +++ b/src/Risk/RiskEngine.php @@ -11,6 +11,7 @@ use Keyring\Changes\PasswordHolds; use Keyring\Contracts\Signal; use Keyring\Events\RiskAssessed; +use Keyring\Risk\Signals\BreachedPassword; use Keyring\Risk\Signals\ImpossibleTravel; use Keyring\Risk\Signals\NewDevice; use Keyring\Sessions\Sessions; @@ -84,12 +85,7 @@ public function decide(Risk $risk, Checkpoint $checkpoint): Action { $action = $this->responder !== null ? ($this->responder)($risk, $checkpoint) - : match ($risk->level) { - Level::Low => Action::allow(), - Level::Medium => Action::stepUp(), - Level::High => Action::stepUp()->notify(), - Level::Critical => Action::deny()->revokeAllSessions()->notify(), - }; + : $this->defaultResponse($risk); // A login attempt hasn't proved who's behind it. If it could revoke // anything, someone with only the password could sign the owner out @@ -97,6 +93,25 @@ public function decide(Risk $risk, Checkpoint $checkpoint): Action return $checkpoint === Checkpoint::Login ? $action->withoutRevokingSessions() : $action; } + /** + * Keyring's own answer, until the app gives one with respond(): by + * level, and a hold for a new password whenever the one just used was + * found in a breach, whatever that scored. A step-up or a notice leaves + * a password someone else knows as the password, and NIST SP 800-63B-4 + * (Sec. 3.1.1.2) has one changed when there's evidence it's compromised. + */ + protected function defaultResponse(Risk $risk): Action + { + $action = match ($risk->level) { + Level::Low => Action::allow(), + Level::Medium => Action::stepUp(), + Level::High => Action::stepUp()->notify(), + Level::Critical => Action::deny()->revokeAllSessions()->notify(), + }; + + return $risk->has(BreachedPassword::FINDING) ? $action->requirePasswordChange() : $action; + } + /** * Decide what to do about the risk and carry out the parts that don't * depend on where we are: announce it, sign out everywhere, lock, hold diff --git a/src/Risk/Signals/BreachedPassword.php b/src/Risk/Signals/BreachedPassword.php index dde38fa2..fafacc06 100644 --- a/src/Risk/Signals/BreachedPassword.php +++ b/src/Risk/Signals/BreachedPassword.php @@ -15,10 +15,14 @@ /** * The password that was just used appears in known breaches (Have I Been * Pwned, via k-anonymity, so the password never leaves the server). Makes a - * network call at sign in, so it isn't on by default. + * network call at sign in, so it isn't on by default. Keyring's own response + * to it holds the user until they choose another (RiskEngine). */ class BreachedPassword extends Signal { + /** What its finding is called, in Risk::has() and a password hold's reason. */ + public const string FINDING = 'breached_password'; + public function __construct( protected UncompromisedVerifier $verifier, protected int $score = 40, @@ -37,6 +41,6 @@ public function assess(Assessment $assessment): ?Finding // As it was hashed, which is the form a breach list would have too. return $this->verifier->verify(['value' => PasswordRules::normalize($password), 'threshold' => 0]) ? null - : new Finding('breached_password', $this->score, 'The password appears in a known data breach.'); + : new Finding(self::FINDING, $this->score, 'The password appears in a known data breach.'); } } diff --git a/src/Support/MailText.php b/src/Support/MailText.php index c17dbf29..cd9e1437 100644 --- a/src/Support/MailText.php +++ b/src/Support/MailText.php @@ -24,6 +24,23 @@ public static function plain(string $text): HtmlString )); } + /** + * A line that ends with where to reach the app's support: its + * "support_contact", which is a page or an email address. Either is + * written as a Markdown link, which the plain-text part shows in full. + * Anything else, like a phone number, stays plain text. + */ + public static function contact(string $text, string $contact): HtmlString + { + $href = match (true) { + filter_var($contact, FILTER_VALIDATE_EMAIL) !== false => 'mailto:'.$contact, + Str::startsWith($contact, ['https://', 'http://']) && preg_match('/[\s<>()]/', $contact) === 0 => $contact, + default => null, + }; + + return new HtmlString(self::plain($text).' '.($href === null ? self::plain($contact) : '['.self::plain($contact).']('.$href.')')); + } + /** * An address with all but the first letter of its name hidden, to hint * at it without giving it away: t•••@example.com. diff --git a/src/Support/PasswordRules.php b/src/Support/PasswordRules.php index 3c6d5745..6fce0d72 100644 --- a/src/Support/PasswordRules.php +++ b/src/Support/PasswordRules.php @@ -22,7 +22,7 @@ */ final class PasswordRules { - /** The shortest password any setting may allow (OWASP ASVS 6.2.1, NIST SP 800-63B). */ + /** The shortest password any setting may allow (OWASP ASVS 5.0.0 6.2.1, NIST SP 800-63B-4 Sec. 3.1.1.2). */ public const int SHORTEST = 8; /** @@ -138,8 +138,9 @@ private static function notCommon(): Closure * can't be reached: it reports the failure and answers "not breached". * With passwords.refuse_unchecked on, Keyring asks itself, the same way * (only the first five characters of the password's SHA-1 are sent), and - * refuses a password it got no answer about. One too short to be taken - * anyway isn't sent. + * refuses a password it got no answer about. It only ever asks that one + * host: it follows no redirect. One too short to be taken anyway isn't + * sent. */ private static function notBreached(int $min): Closure { @@ -150,7 +151,9 @@ private static function notBreached(int $min): Closure $hash = Str::upper(sha1($value)); - $range = rescue(fn () => Http::withHeaders(['Add-Padding' => 'true'])->timeout(10)->get(self::BREACHES.substr($hash, 0, 5))->throw()->body()); + // One host and no other: a redirect isn't followed, and what + // comes back in its place is no answer. + $range = rescue(fn () => Http::withHeaders(['Add-Padding' => 'true'])->timeout(10)->withoutRedirecting()->get(self::BREACHES.substr($hash, 0, 5))->throw()->body()); // A range that was read always lists hashes, so anything else is no answer. if (! is_string($range) || preg_match('/^[0-9A-F]{35}:\d/mi', $range) !== 1) { @@ -172,7 +175,7 @@ private static function notBreached(int $min): Closure * with or without digits and punctuation around them. Characters that * stand in for letters count as those letters. * - * The password is compared whole, as NIST SP 800-63B asks: a passphrase + * The password is compared whole, as NIST SP 800-63B-4 asks (Sec. 3.1.1.2): a passphrase * that happens to have a name in it is as hard to guess as one without, * and refusing it would be a composition rule by another name. "Taylor * rides a blue bicycle" passes, and "taylor.otwell.2026" doesn't. @@ -292,7 +295,7 @@ private static function plain(string $value): string /** * A password as Keyring hashes and checks it: in Unicode's NFC form, as - * NIST SP 800-63B asks. The same "é" is one code point from one keyboard + * NIST SP 800-63B-4 recommends (Sec. 3.1.1.2). The same "é" is one code point from one keyboard * and two from another, and without this the two wouldn't match. Bytes * that aren't UTF-8 have no form to put them in and stay as they are. */ diff --git a/src/Support/TooManyAttempts.php b/src/Support/TooManyAttempts.php new file mode 100644 index 00000000..ab41ccf8 --- /dev/null +++ b/src/Support/TooManyAttempts.php @@ -0,0 +1,40 @@ +by(...)->response(new TooManyAttempts('keyring')) + */ +final readonly class TooManyAttempts +{ + public function __construct( + public string $limiter, + ) {} + + /** + * @param array $headers + */ + public function __invoke(Request $request, array $headers): never + { + RateLimited::dispatch( + $request->user(config('keyring.guard')), + $this->limiter, + $request->route()?->getName(), + (int) ($headers['Retry-After'] ?? 0), + ); + + throw new ThrottleRequestsException('Too Many Attempts.', null, $headers); + } +} diff --git a/src/Testing/KeyringConformance.php b/src/Testing/KeyringConformance.php index b33b98e9..7f364960 100644 --- a/src/Testing/KeyringConformance.php +++ b/src/Testing/KeyringConformance.php @@ -140,6 +140,27 @@ public function test_keyring_takes_passwords_of_64_characters(): void ); } + /** + * Keyring's own limit on asking for a reset link is per sender. How + * often one account can be sent one is the broker's "throttle", which is + * Laravel's setting and yours: 60 seconds in a new app. + */ + public function test_keyring_limits_how_often_an_account_is_sent_a_reset_link(): void + { + if (! Features::enabled(Features::resetPasswords())) { + $this->markTestSkipped('Password resets are off: turn on Features::resetPasswords().'); + } + + $option = 'auth.passwords.'.(config('keyring.passwords.broker') ?? config('auth.defaults.passwords')).'.throttle'; + + $this->assertGreaterThan( + 0, + (int) config($option), + "The [{$option}] option is missing or zero, so one account can be sent a reset link as often as anyone asks, from as many addresses as they have. " + .'Set it to the seconds an account waits between links: 60 is what a new Laravel app has.', + ); + } + public function test_keyring_gives_the_same_error_for_wrong_passwords_and_unknown_accounts(): void { $user = $this->keyringUser(); diff --git a/src/UserKeyring.php b/src/UserKeyring.php index 81a53aeb..6ac7a471 100644 --- a/src/UserKeyring.php +++ b/src/UserKeyring.php @@ -105,7 +105,7 @@ public function has(Category $category): bool */ public function hasSecondFactor(): bool { - return $this->withoutFallbacks()->canMeet(Requirement::aal2()->including(Category::Possession)); + return $this->withoutFallbacks()->canMeet(Requirement::aal2()); } /** diff --git a/src/WebAuthn/Ceremonies.php b/src/WebAuthn/Ceremonies.php index 51e51a6f..2e89a5bf 100644 --- a/src/WebAuthn/Ceremonies.php +++ b/src/WebAuthn/Ceremonies.php @@ -61,8 +61,9 @@ class Ceremonies { /** - * The shortest RSA key an app can settle for, in bits: what RFC 8230 - * asks of RS256, and the 112 bits of strength NIST SP 800-63B wants. + * The shortest RSA key an app can settle for, in bits: what RFC 8812 + * (Section 2) asks of RS256, and the 112 bits of strength NIST SP + * 800-63B-4 wants (Sec. 3.1.6.2). */ public const int SHORTEST_RSA_KEY = 2048; diff --git a/stubs/app/Actions/Keyring/PasswordValidationRules.php b/stubs/app/Actions/Keyring/PasswordValidationRules.php index d790c75d..7bff287c 100644 --- a/stubs/app/Actions/Keyring/PasswordValidationRules.php +++ b/stubs/app/Actions/Keyring/PasswordValidationRules.php @@ -20,7 +20,8 @@ trait PasswordValidationRules * PasswordRules::for($user, fn (Password $rule) => $rule->rules(['min:20'])) * * Leave out rules about which characters it has (mixedCase(), symbols()): - * OWASP ASVS 6.2.5 and NIST want any composition accepted. + * OWASP ASVS 5.0.0 (6.2.5) and NIST SP 800-63B-4 (Sec. 3.1.1.2) want any + * composition accepted. * * @param User|null $user null at registration * @param list $context the name and email it mustn't contain while there's no user yet (non-strings are ignored) diff --git a/stubs/app/Notifications/Keyring/EmailChangeNotice.php b/stubs/app/Notifications/Keyring/EmailChangeNotice.php index 768421a9..f28a393b 100644 --- a/stubs/app/Notifications/Keyring/EmailChangeNotice.php +++ b/stubs/app/Notifications/Keyring/EmailChangeNotice.php @@ -19,11 +19,13 @@ class EmailChangeNotice extends Notification { /** * @param string $email the new address, with most of its name hidden + * @param string|null $contact "support_contact" from config/keyring.php: a URL or an address */ public function __construct( public string $email, #[\SensitiveParameter] public string $revertUrl, #[\SensitiveParameter] public ?string $confirmUrl = null, + public ?string $contact = null, ) {} /** @@ -49,8 +51,12 @@ public function toMail(object $notifiable): MailMessage ->action(__('Confirm the change'), $this->confirmUrl); } - return $message + $message ->line(__('Wasn\'t you? This link cancels the change and signs you out everywhere:')) ->line($this->revertUrl); + + return $this->contact === null + ? $message + : $message->line(MailText::contact(__('If this wasn\'t you and you need help, contact us:'), $this->contact)); } } diff --git a/stubs/app/Notifications/Keyring/SecurityNotice.php b/stubs/app/Notifications/Keyring/SecurityNotice.php index 219c0428..3d90a675 100644 --- a/stubs/app/Notifications/Keyring/SecurityNotice.php +++ b/stubs/app/Notifications/Keyring/SecurityNotice.php @@ -27,7 +27,8 @@ abstract class SecurityNotice extends Notification implements ShouldQueueAfterCo * Keyring fills in whichever of these the notice has. Some hold what * users and browsers sent (a key's name, a user agent), cut to one line, * so escape them for wherever you show them. $when is $at as text in - * the app's timezone: format $at yourself for the user's own. + * the app's timezone: format $at yourself for the user's own. $contact + * is "support_contact" from config/keyring.php: a URL or an address. */ public function __construct( public string $when, @@ -38,6 +39,7 @@ public function __construct( public ?int $remaining = null, public ?string $reasons = null, public ?string $url = null, + public ?string $contact = null, ) {} abstract protected function subject(): string; @@ -81,6 +83,10 @@ public function toMail(object $notifiable): MailMessage $message->action($this->action(), $this->url); } - return $message->line(__('If this wasn\'t you, change your password and check your sign-in methods straight away.')); + $message->line(__('If this wasn\'t you, change your password and check your sign-in methods straight away.')); + + return $this->contact === null + ? $message + : $message->line(MailText::contact(__('If this wasn\'t you and you need help, contact us:'), $this->contact)); } } diff --git a/stubs/app/Notifications/Keyring/VerificationCode.php b/stubs/app/Notifications/Keyring/VerificationCode.php index fb61fea4..8c3973fa 100644 --- a/stubs/app/Notifications/Keyring/VerificationCode.php +++ b/stubs/app/Notifications/Keyring/VerificationCode.php @@ -6,10 +6,12 @@ use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; +use Keyring\Support\MailText; /** * The code for signing in with an email code, or for adding one as a sign-in * method ($enrolling). Not queued, so it arrives while the user waits. + * $contact is "support_contact" from config/keyring.php: a URL or an address. */ class VerificationCode extends Notification { @@ -17,6 +19,7 @@ public function __construct( #[\SensitiveParameter] public string $code, public int $minutes, public bool $enrolling = false, + public ?string $contact = null, ) {} /** @@ -29,7 +32,7 @@ public function via(object $notifiable): array public function toMail(object $notifiable): MailMessage { - return new MailMessage() + $message = new MailMessage() ->subject(__('Your verification code')) ->line(__('Your verification code is:')) ->line('**'.trim(chunk_split($this->code, 4, ' ')).'**') @@ -37,5 +40,9 @@ public function toMail(object $notifiable): MailMessage ->line($this->enrolling ? __('If you didn\'t ask to add this email as a sign-in method, someone may be signed in to your account. Please change your password.') : __('If you didn\'t try to sign in, someone may know your password. Please change it.')); + + return $this->contact === null + ? $message + : $message->line(MailText::contact(__('If this wasn\'t you and you need help, contact us:'), $this->contact)); } } diff --git a/stubs/app/Providers/KeyringServiceProvider.php b/stubs/app/Providers/KeyringServiceProvider.php index d4785b24..95958fad 100644 --- a/stubs/app/Providers/KeyringServiceProvider.php +++ b/stubs/app/Providers/KeyringServiceProvider.php @@ -18,6 +18,7 @@ use Keyring\Factors\Totp; use Keyring\Factors\WebAuthn; use Keyring\Login\Requirement; +use Keyring\Risk\Signals; class KeyringServiceProvider extends ServiceProvider { @@ -42,6 +43,31 @@ public function boot(): void // sends them to the "enrollment_url" in config/keyring.php. $this->app->make(Kernel::class)->appendMiddlewareToGroup('web', 'keyring.enrolled'); + // What makes a sign in or a session look like someone else's. Each + // signal that fires adds to a score, and Keyring answers the total: a + // second factor from a user who has one, then a notice, and at the + // top a refused sign in. The ones that are on can't add up to that + // for a user who signs in with a password alone. See "Risk". + Keyring::risk()->signals([ + Signals\SessionFingerprintChanged::class, + // These two read the security log: Features::securityLog(). + Signals\RepeatedFactorFailures::class, + Signals\SuccessAfterFailures::class, + // These two go by an account's devices: Features::devices(). + Signals\NewDevice::class, + Signals\InactiveAccount::class, + // Off: with the ones above it could refuse a user who has no + // second factor to give. It needs Features::emailChanges(). + // Signals\RecentlyChangedRecovery::class, + // Off: it asks Have I Been Pwned at every sign in, and holds a + // user whose password it finds until they choose another. Set + // "password_change_url" in config/keyring.php before turning it on. + // Signals\BreachedPassword::class, + // Off: these two need a locator, "devices.locator" in the config. + // Signals\NewCountry::class, + // Signals\ImpossibleTravel::class, + ]); + // Your code for the account changes, in app/Actions/Keyring. Keyring // does the security work around them. Keyring::createUsersUsing(CreateNewUser::class); @@ -51,7 +77,8 @@ public function boot(): void // The emails Keyring sends, in app/Notifications/Keyring. They're // yours to restyle or send another way, and a security notice that - // isn't listed here isn't sent. See "Security Log & Emails". + // isn't listed here isn't sent. One that's commented out has nothing + // to announce until its feature is on. See "Security Log & Emails". Keyring::notifications([ 'verification_code' => Notifications\VerificationCode::class, 'confirm_email_change' => Notifications\ConfirmEmailChange::class, @@ -65,11 +92,11 @@ public function boot(): void 'recovery_codes_generated' => Notifications\RecoveryCodesGenerated::class, 'email_changed' => Notifications\EmailChanged::class, 'account_locked' => Notifications\AccountLocked::class, - // 'new_device' => Notifications\NewDevice::class, - // 'second_factor_failed' => Notifications\SecondFactorFailed::class, - // 'suspicious_activity' => Notifications\SuspiciousActivity::class, + 'new_device' => Notifications\NewDevice::class, + 'second_factor_failed' => Notifications\SecondFactorFailed::class, + 'suspicious_activity' => Notifications\SuspiciousActivity::class, + 'email_change_reverted' => Notifications\EmailChangeReverted::class, // 'clone_suspected' => Notifications\CloneSuspected::class, - // 'email_change_reverted' => Notifications\EmailChangeReverted::class, ]); } } diff --git a/stubs/config/keyring.php b/stubs/config/keyring.php index 9a862f6a..60a152fd 100644 --- a/stubs/config/keyring.php +++ b/stubs/config/keyring.php @@ -74,6 +74,19 @@ 'enrollment_url' => null, + /* + |-------------------------------------------------------------------------- + | Support Contact + |-------------------------------------------------------------------------- + | + | Where users can reach you about their account: a page's URL or an email + | address. The emails in app/Notifications/Keyring then end by saying who + | to contact if something wasn't them. Null leaves that line out. + | + */ + + 'support_contact' => null, + /* |-------------------------------------------------------------------------- | Everything Else diff --git a/tests/Feature/AuthenticatorManagementTest.php b/tests/Feature/AuthenticatorManagementTest.php index a4464d9f..259ce551 100644 --- a/tests/Feature/AuthenticatorManagementTest.php +++ b/tests/Feature/AuthenticatorManagementTest.php @@ -25,6 +25,7 @@ use Keyring\Factors\Password; use Keyring\Factors\RecoveryCodes; use Keyring\Factors\Totp; +use Keyring\Factors\WebAuthn; use Keyring\Login\Attempt; use Keyring\Login\Requirement; use Keyring\Models\Authenticator; @@ -566,3 +567,64 @@ function signInWithRecoveryCode(string $code): TestResponse expect(Keyring::for($this->user)->shouldReplaceRecoveryCodes())->toBeTrue(); }); }); + +// OWASP's Passkey Security Cheat Sheet has a page that manages credentials +// show when each was created and last used. +describe('what a sign-in method shows of itself', function () { + it('says when it was added and when it was last used, as a settings page needs', function (Closure $make) { + Keyring::factors([Password::class, Totp::class, RecoveryCodes::class, WebAuthn::passkeys(), WebAuthn::securityKeys()]); + $this->travelTo('2026-11-08 09:30:00'); + $authenticator = $make($this->user); + + expect($authenticator->factor()->present($authenticator)) + ->toMatchArray(['createdAt' => '2026-11-08T09:30:00+00:00', 'lastUsedAt' => null]); + + $this->travelTo('2026-11-10 17:45:10'); + $authenticator->markAsUsed(); + + expect($authenticator->factor()->present($authenticator)) + ->toMatchArray(['id' => $authenticator->id, 'createdAt' => '2026-11-08T09:30:00+00:00', 'lastUsedAt' => '2026-11-10T17:45:10+00:00']); + })->with([ + 'a passkey' => [fn (User $user) => Authenticator::factory()->passkey()->for($user, 'authenticatable')->create()], + 'a security key' => [fn (User $user) => Authenticator::factory()->securityKey()->for($user, 'authenticatable')->create()], + 'an authenticator app' => [fn (User $user) => Authenticator::factory()->totp()->for($user, 'authenticatable')->create()], + 'recovery codes' => [fn (User $user) => Authenticator::factory()->recoveryCodes()->for($user, 'authenticatable')->create()], + ]); + + it('has neither for the password, which has no record of its own', function () { + $password = $this->user->keyring->of('password')->sole(); + + expect($password->factor()->present($password))->toMatchArray(['id' => null, 'createdAt' => null, 'lastUsedAt' => null]); + }); + + it('says so in the answer to adding or renaming one', function () { + $this->travelTo('2026-11-08 09:30:00'); + $this->actingAs($this->user)->withAssurance(Assurance::AAL1); + + $secret = $this->postJson(route('keyring.authenticators.store', 'totp'))->assertOk()->json('enrollment.secret'); + $added = $this->postJson(route('keyring.authenticators.confirm', 'totp'), ['code' => totpCode($secret)]) + ->assertOk() + ->assertJsonPath('authenticator.createdAt', '2026-11-08T09:30:00+00:00'); + + $this->withAssurance(Assurance::AAL2)->patchJson(route('keyring.authenticators.update', $added->json('authenticator.id')), ['name' => 'Phone']) + ->assertOk() + ->assertJsonPath('authenticator.name', 'Phone') + ->assertJsonPath('authenticator.createdAt', '2026-11-08T09:30:00+00:00'); + }); + + // Only a password has been proved there, and whoever has it has no + // call to learn when its owner last signed in. + it('keeps both off the challenge page', function () { + $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(['last_used_at' => now()]); + Authenticator::factory()->recoveryCodes()->for($this->user, 'authenticatable')->create(['last_used_at' => now()]); + + $this->post('/logout'); + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect(route('keyring.login.challenge')); + + $props = $this->inertia()->get(route('keyring.login.challenge'))->assertOk()->json('props'); + + expect($props['authenticator'])->toBe(['factor' => 'totp', 'id' => $totp->id, 'name' => $totp->name]) + ->and($props['alternatives'])->toHaveCount(1) + ->and($props['alternatives'][0])->toHaveKeys(['factor', 'id', 'name', 'remaining', 'replace'])->not->toHaveKeys(['createdAt', 'lastUsedAt']); + }); +}); diff --git a/tests/Feature/CommandsTest.php b/tests/Feature/CommandsTest.php index fcf20db8..589bff73 100644 --- a/tests/Feature/CommandsTest.php +++ b/tests/Feature/CommandsTest.php @@ -5,6 +5,7 @@ use App\Actions\Keyring\ResetUserPassword; use App\Actions\Keyring\UpdateUserPassword; use App\Actions\Keyring\ValidateEmailChange; +use App\Notifications\Keyring\SuspiciousActivity; use App\Providers\KeyringServiceProvider; use Illuminate\Console\Scheduling\Event; use Illuminate\Console\Scheduling\Schedule; @@ -14,6 +15,10 @@ use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Event as Events; +use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Http; +use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Str; @@ -22,7 +27,9 @@ use Keyring\Contracts\SessionRegistry; use Keyring\Contracts\UpdatesUserPasswords; use Keyring\Contracts\ValidatesEmailChanges; +use Keyring\Devices\NullLocator; use Keyring\Enums\Assurance; +use Keyring\Events\RiskAssessed; use Keyring\Facades\Keyring; use Keyring\Factors\Password; use Keyring\Factors\RecoveryCodes; @@ -32,6 +39,13 @@ use Keyring\Models\Authenticator; use Keyring\Models\PendingChange; use Keyring\Models\SecurityEvent; +use Keyring\Risk\Checkpoint; +use Keyring\Risk\Level; +use Keyring\Risk\Signals\InactiveAccount; +use Keyring\Risk\Signals\NewDevice; +use Keyring\Risk\Signals\RepeatedFactorFailures; +use Keyring\Risk\Signals\SessionFingerprintChanged; +use Keyring\Risk\Signals\SuccessAfterFailures; use Keyring\Sessions\RegisteredSession; use Keyring\Testing\VirtualAuthenticator; use Keyring\Tests\Fixtures\SoftDeletingUser; @@ -70,6 +84,8 @@ ->toBe((require __DIR__.'/../../config/keyring.php')['features']) ->and($config['registration'])->toBe(['reveal_taken' => false]) ->and($config['enrollment_url'])->toBeNull() + // There to fill in: nobody but the app knows where its support is. + ->and($config)->toHaveKey('support_contact', null) ->and(file_get_contents(config_path('keyring.php')))->toContain('// Features::devices(),') // The emails a flow needs are registered, and the notices about changes. ->and($provider)->toContain(" 'verification_code' => Notifications\VerificationCode::class,") @@ -81,7 +97,18 @@ ->toContain(" 'recovery_codes_generated' => Notifications\RecoveryCodesGenerated::class,") ->toContain(" 'email_changed' => Notifications\EmailChanged::class,") ->toContain(" 'account_locked' => Notifications\AccountLocked::class,") + // What the risk signals find is announced. The notices with + // nothing to announce yet are there to turn on. + ->toContain(" 'suspicious_activity' => Notifications\SuspiciousActivity::class,") ->toContain(" // 'new_device' => Notifications\NewDevice::class,") + ->toContain(" // 'second_factor_failed' => Notifications\SecondFactorFailed::class,") + ->toContain(" // 'email_change_reverted' => Notifications\EmailChangeReverted::class,") + // The risk signals the default features can feed, and the rest + // there to turn on. + ->toContain(" Signals\SessionFingerprintChanged::class,\n") + ->toContain(" Signals\SuccessAfterFailures::class,\n") + ->toContain(" // Signals\NewDevice::class,\n") + ->toContain(" // Signals\BreachedPassword::class,\n") // Every notification there is, whichever are registered. ->and(array_map(basename(...), glob($this->sandbox.'/app/Notifications/Keyring/*.php'))) ->toEqualCanonicalizing(array_map(basename(...), glob(__DIR__.'/../../stubs/app/Notifications/Keyring/*.php'))) @@ -126,7 +153,13 @@ expect($config['features'])->toBe([Features::updatePasswords(), Features::manageAuthenticators(), Features::devices()]) ->and($provider)->toContain(" 'recovery_code_used' => Notifications\RecoveryCodeUsed::class,") - ->toContain(" // 'new_device' => Notifications\NewDevice::class,") + // Devices are on and there's a second factor to fail, so both are announced. + ->toContain(" 'new_device' => Notifications\NewDevice::class,") + ->toContain(" 'second_factor_failed' => Notifications\SecondFactorFailed::class,") + ->toContain(" 'suspicious_activity' => Notifications\SuspiciousActivity::class,") + ->toContain(" // 'email_change_reverted' => Notifications\EmailChangeReverted::class,") + ->toContain(" // 'clone_suspected' => Notifications\CloneSuspected::class,") + ->toContain(" Signals\NewDevice::class,\n") ->toContain('Totp::class,')->toContain('RecoveryCodes::class,')->toContain('WebAuthn::passkeys(),')->toContain('Keyring::require(') ->not->toContain('securityKeys')->not->toContain('EmailCode'); @@ -243,10 +276,15 @@ }); it('can leave out the security emails', function () { - $this->artisan('keyring:install', ['--factor' => ['totp'], '--no-emails' => true, '--no-interaction' => true])->assertSuccessful(); + $this->artisan('keyring:install', ['--factor' => ['totp'], '--no-emails' => true, '--no-interaction' => true]) + // The emails say who to contact once the app says where that is. + ->expectsOutputToContain('Set support_contact in config/keyring.php') + ->assertSuccessful(); expect(file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php')) ->toContain(" // 'password_changed' => Notifications\PasswordChanged::class,") + ->toContain(" // 'second_factor_failed' => Notifications\SecondFactorFailed::class,") + ->toContain(" // 'suspicious_activity' => Notifications\SuspiciousActivity::class,") ->toContain(" // 'authenticator_added' => Notifications\AuthenticatorAdded::class,") ->toContain(" // 'email_changed' => Notifications\EmailChanged::class,") ->toContain(" 'email_change_notice' => Notifications\EmailChangeNotice::class,") @@ -329,6 +367,11 @@ public function get($path, $lock = false) {$prefix}'recovery_codes_generated' => Notifications\\RecoveryCodesGenerated::class, {$prefix}'email_changed' => Notifications\\EmailChanged::class, {$prefix}'account_locked' => Notifications\\AccountLocked::class, + // 'new_device' => Notifications\\NewDevice::class, + // 'second_factor_failed' => Notifications\\SecondFactorFailed::class, + {$prefix}'suspicious_activity' => Notifications\\SuspiciousActivity::class, + // 'email_change_reverted' => Notifications\\EmailChangeReverted::class, + // 'clone_suspected' => Notifications\\CloneSuspected::class, PHP) ->toBe($provider(published: true, listed: false)) @@ -338,6 +381,165 @@ public function get($path, $lock = false) ->toBe($provider(published: false, listed: false)); })->with(['with the emails' => true, 'without them' => false]); +it('registers a notice only once the app has something for it to announce', function (array $features, array $factors, array $registered, array $commented) { + $provider = (fn () => $this->provider(new Filesystem, $factors, true, false, $features))->call(new InstallCommand); + + foreach ($registered as $type) { + expect($provider)->toContain(" '{$type}' => Notifications\\".Str::studly($type)."::class,\n"); + } + + foreach ($commented as $type) { + expect($provider)->toContain(" // '{$type}' => Notifications\\".Str::studly($type)."::class,\n"); + } +})->with([ + 'the default features and the password alone' => [ + ['registration', 'reset-passwords', 'email-verification', 'update-passwords', 'security-log'], [], + ['password_changed', 'account_locked', 'suspicious_activity'], + ['new_device', 'second_factor_failed', 'email_change_reverted', 'clone_suspected'], + ], + 'devices' => [ + ['devices'], [], + ['new_device', 'suspicious_activity'], + ['second_factor_failed', 'email_change_reverted'], + ], + 'email changes' => [ + ['email-changes'], [], + ['email_changed', 'email_change_reverted'], + ['new_device', 'second_factor_failed'], + ], + 'a second sign-in method' => [ + ['manage-authenticators'], ['totp'], + ['second_factor_failed'], + ['new_device', 'email_change_reverted'], + ], + 'an emailed code, which is asked for after the password too' => [ + ['manage-authenticators'], ['email-codes'], + ['second_factor_failed'], + ['new_device', 'email_change_reverted'], + ], + 'everything' => [ + Features::all(), ['totp', 'passkeys'], + ['new_device', 'second_factor_failed', 'suspicious_activity', 'email_change_reverted'], + ['clone_suspected'], + ], +]); + +describe('the risk signals a new provider starts with', function () { + /** + * The provider keyring:install writes for these features, and the + * signal lines in it: [on, commented out]. + * + * @param list $features + * @return array{list, list} + */ + function publishedSignals(array $features): array + { + $provider = (fn () => $this->provider(new Filesystem, [], true, false, $features))->call(new InstallCommand); + + preg_match_all('/^ +(\/\/ )?Signals\\\\(\w+)::class,$/m', $provider, $lines, PREG_SET_ORDER); + + return [ + array_column(array_filter($lines, fn (array $line) => $line[1] === ''), 2), + array_column(array_filter($lines, fn (array $line) => $line[1] !== ''), 2), + ]; + } + + it('turns on the ones a feature that is on can feed, and leaves the rest there commented out', function (array $features, array $on, array $off) { + expect(publishedSignals($features))->toBe([$on, [...$off, 'RecentlyChangedRecovery', 'BreachedPassword', 'NewCountry', 'ImpossibleTravel']]); + })->with([ + 'the default features' => [ + ['registration', 'reset-passwords', 'email-verification', 'update-passwords', 'security-log'], + ['SessionFingerprintChanged', 'RepeatedFactorFailures', 'SuccessAfterFailures'], + ['NewDevice', 'InactiveAccount'], + ], + 'devices too' => [ + ['security-log', 'devices'], + ['SessionFingerprintChanged', 'RepeatedFactorFailures', 'SuccessAfterFailures', 'NewDevice', 'InactiveAccount'], + [], + ], + 'devices without the security log' => [ + ['devices'], + ['SessionFingerprintChanged', 'NewDevice', 'InactiveAccount'], + ['RepeatedFactorFailures', 'SuccessAfterFailures'], + ], + 'neither' => [ + [], + ['SessionFingerprintChanged'], + ['RepeatedFactorFailures', 'SuccessAfterFailures', 'NewDevice', 'InactiveAccount'], + ], + // Email changes turn nothing on: the signal that reads them stays off. + 'every feature' => [ + Features::all(), + ['SessionFingerprintChanged', 'RepeatedFactorFailures', 'SuccessAfterFailures', 'NewDevice', 'InactiveAccount'], + [], + ], + ]); + + it('writes a provider that is valid PHP whichever are on', function (array $features) { + $path = sys_get_temp_dir().'/keyring-provider-'.uniqid().'.php'; + file_put_contents($path, (fn () => $this->provider(new Filesystem, [], true, false, $features))->call(new InstallCommand)); + + expectValidPhp($path); + File::delete($path); + })->with(['none of them' => [[]], 'all of them' => [Features::all()]]); + + it('makes no network call and needs no locator', function () { + // The stub as a whole, which has every signal a feature can turn on. + new KeyringServiceProvider($this->app)->boot(); + Http::preventStrayRequests(); + config(['keyring.devices.locator' => NullLocator::class]); + + $signals = [...Keyring::risk()->signalsFor(Checkpoint::Login), ...Keyring::risk()->signalsFor(Checkpoint::Request)]; + + expect(array_map(get_class(...), $signals))->toEqualCanonicalizing([ + SessionFingerprintChanged::class, RepeatedFactorFailures::class, SuccessAfterFailures::class, NewDevice::class, InactiveAccount::class, + ]); + + $this->post('/login', ['email' => taylor()->email, 'password' => 'password'])->assertRedirect('/dashboard'); + $this->get('/user/sessions')->assertOk(); + }); + + // A step-up asks for a second factor from a user who has one. Refusing + // the sign in is what would keep someone out, and it takes a score the + // signals that are on can't reach for a user with a password alone. + it('cannot keep out a user who signs in with a password alone, with every one of them finding something', function () { + new KeyringServiceProvider($this->app)->boot(); + Keyring::factors([Password::class]); + Notification::fake(); + $user = taylor(); + + // Last signed in a hundred days ago, in another browser. + $this->post('/login', ['email' => $user->email, 'password' => 'password'])->assertRedirect('/dashboard'); + $this->post('/logout'); + $this->travel(100)->days(); + $this->flushSession(); + $this->defaultCookies = []; + + // Then five wrong passwords, and the right one. + config(['keyring.limits.per_account' => 100]); + + foreach (range(1, 5) as $guess) { + $this->post('/login', ['email' => $user->email, 'password' => 'wrong-'.$guess])->assertSessionHasErrors('email'); + } + + Events::listen(RiskAssessed::class, function (RiskAssessed $event) use (&$assessed) { + $assessed = $event; + }); + + $this->post('/login', ['email' => $user->email, 'password' => 'password'])->assertRedirect('/dashboard'); + $this->assertAuthenticatedAs($user); + + expect(array_column($assessed->risk->toArray(), 'signal'))->toEqualCanonicalizing(['success_after_failures', 'new_device', 'inactive_account']) + ->and($assessed->risk->level)->toBe(Level::High) + ->and($assessed->action->deny)->toBeFalse() + ->and($assessed->action->lockSeconds)->toBeNull(); + + // They're told, and nothing they could reach before is closed to them. + Notification::assertSentTo($user, SuspiciousActivity::class); + $this->get('/user/sessions')->assertOk(); + }); +}); + function passkeysTable(): void { Schema::create('passkeys', function (Blueprint $table) { diff --git a/tests/Feature/ConformanceTest.php b/tests/Feature/ConformanceTest.php index 05cb8ce8..7217de10 100644 --- a/tests/Feature/ConformanceTest.php +++ b/tests/Feature/ConformanceTest.php @@ -12,6 +12,7 @@ use Keyring\Factors\RecoveryCodes; use Keyring\Factors\Totp; use Keyring\Factors\WebAuthn; +use Keyring\Features; use Keyring\Http\Middleware\AuthenticateSession; use Keyring\Pipeline\Steps; use Keyring\Pipeline\Steps\EnsureNotThrottled; @@ -185,6 +186,56 @@ public function test_the_suite_fails_when_the_longest_password_allowed_is_under_ $this->test_keyring_takes_passwords_of_64_characters(); } + /** + * @param array $config + */ + #[DataProvider('brokersWithoutAThrottle')] + public function test_the_suite_fails_when_reset_links_are_not_limited_per_account(array $config, string $names): void + { + if (! Features::enabled(Features::resetPasswords())) { + $this->markTestSkipped('Password resets are off.'); + } + + config($config); + + try { + $this->test_keyring_limits_how_often_an_account_is_sent_a_reset_link(); + } catch (AssertionFailedError $failure) { + $this->assertStringContainsString($names, $failure->getMessage()); + + return; + } + + $this->fail('A broker without a throttle went unnoticed.'); + } + + /** + * @return array> + */ + public static function brokersWithoutAThrottle(): array + { + $staff = ['provider' => 'users', 'table' => 'password_reset_tokens', 'expire' => 60]; + + return [ + 'no throttle' => [['auth.passwords.users.throttle' => null], 'auth.passwords.users.throttle'], + 'a throttle of nothing' => [['auth.passwords.users.throttle' => 0], 'auth.passwords.users.throttle'], + 'the setting left out' => [['auth.passwords.users' => ['provider' => 'users', 'table' => 'password_reset_tokens', 'expire' => 60]], 'auth.passwords.users.throttle'], + 'the broker keyring was told to use' => [['auth.passwords.staff' => $staff, 'keyring.passwords.broker' => 'staff'], 'auth.passwords.staff.throttle'], + ]; + } + + public function test_the_suite_reads_the_throttle_of_the_broker_keyring_uses(): void + { + // The default broker has none, and it isn't the one that sends Keyring's links. + config([ + 'auth.passwords.users.throttle' => 0, + 'auth.passwords.staff' => ['provider' => 'users', 'table' => 'password_reset_tokens', 'expire' => 60, 'throttle' => 30], + 'keyring.passwords.broker' => 'staff', + ]); + + $this->test_keyring_limits_how_often_an_account_is_sent_a_reset_link(); + } + public function test_the_suite_fails_when_a_mandatory_step_was_taken_out(): void { Keyring::pipeline(fn (Steps $steps) => $steps->dangerouslyRemove(EnsureNotThrottled::class)); diff --git a/tests/Feature/CustomFactorTest.php b/tests/Feature/CustomFactorTest.php index 91bf3dca..b6fef42a 100644 --- a/tests/Feature/CustomFactorTest.php +++ b/tests/Feature/CustomFactorTest.php @@ -3,14 +3,22 @@ declare(strict_types=1); use App\Notifications\Keyring\VerificationCode; +use Illuminate\Http\Request; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Notification; +use Illuminate\Support\Facades\Route; use Keyring\Enums\Assurance; +use Keyring\Enums\Category; use Keyring\Facades\Keyring; use Keyring\Factors\EmailCode; +use Keyring\Factors\Factor; use Keyring\Factors\Password; use Keyring\Factors\Totp; +use Keyring\Login\Attempt; +use Keyring\Login\Requirement; +use Keyring\Login\Verification; use Keyring\Models\Authenticator; +use Keyring\Sessions\SessionAssurance; use Keyring\Tests\Fixtures\SmsCode; class FiveDigitSmsCode extends SmsCode @@ -25,6 +33,27 @@ class QuarterHourSmsCode extends SmsCode protected int $ttl = 900; } +/** + * A factor that is only something the user is: nothing they hold comes with it. + */ +class VoicePrint extends Factor +{ + public function key(): string + { + return 'voice'; + } + + public function categories(Authenticator $authenticator): array + { + return [Category::Inherence]; + } + + public function verify(Attempt $attempt, Authenticator $authenticator, Request $request): ?Verification + { + return $request->input('code') === 'my voice is my passport' ? $this->verified($authenticator) : null; + } +} + beforeEach(function () { SmsCode::$sent = []; Keyring::factors([Password::class, Totp::class, EmailCode::asSecondFactor(), SmsCode::class]); @@ -118,6 +147,66 @@ class QuarterHourSmsCode extends SmsCode expect(fn () => Keyring::factor('sms'))->toThrow(LogicException::class, 'Keyring refuses codes shorter than 6 digits'); }); +// NIST SP 800-63B-4 (Sec. 2.2.1) takes a biometric only with the +// authenticator it unlocks, so AAL2 needs something the user has. +describe('a factor that is nothing the user holds', function () { + beforeEach(function () { + Keyring::factors([Password::class, Totp::class, VoicePrint::class]); + Authenticator::factory()->for($this->user, 'authenticatable')->create(['factor' => 'voice', 'name' => 'Voice']); + + Route::middleware(['web', 'auth', 'keyring:aal2'])->get('/billing', fn () => 'billing'); + Route::middleware(['web', 'auth', 'keyring.enrolled'])->get('/app', fn () => 'app'); + config(['keyring.enrollment_url' => '/settings/security']); + }); + + it('is asked for beside the password, and leaves the session at aal1', function () { + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect(route('keyring.login.challenge')); + $this->post(route('keyring.login.verify', 'voice'), ['code' => 'my voice is my passport', 'trust' => true])->assertRedirect('/dashboard'); + + expect(app(SessionAssurance::class)->level())->toBe(Assurance::AAL1) + ->and($this->user->devices()->whereNotNull('trusted_until')->count())->toBe(0); + + // Nothing it proved reaches AAL2, and the account has nothing that would. + $this->get('/billing')->assertRedirect('/settings/security')->assertSessionHas('status', 'enroll-first'); + $this->get('/app')->assertRedirect('/settings/security'); + }); + + it('doesn\'t count as the account\'s second factor', function () { + $keyring = $this->user->keyring; + + expect($keyring->hasSecondFactor())->toBeFalse() + ->and($keyring->canMeet(Requirement::aal2()))->toBeFalse() + ->and($keyring->canMeet(Requirement::factors(2)))->toBeTrue(); + }); + + it('is refused where the policy asks for aal2 outright', function () { + Keyring::require(Requirement::aal2()); + + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password']); + + $this->get(route('keyring.login.challenge')) + ->assertRedirect('/login') + ->assertSessionHasErrors(['email' => __('keyring::keyring.unavailable')]); + $this->assertGuest(); + }); + + it('reaches aal2 once something the user has is proved with it', function () { + $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); + + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect(route('keyring.login.challenge')); + + // The voice print can't finish the sign in now, so it isn't offered. + $this->post(route('keyring.login.verify', 'voice'), ['code' => 'my voice is my passport']); + $this->assertGuest(); + + $this->post(route('keyring.login.verify', 'totp'), ['code' => totpCode($totp->secret)])->assertRedirect('/dashboard'); + + expect(app(SessionAssurance::class)->level())->toBe(Assurance::AAL2); + $this->get('/billing')->assertOk(); + $this->get('/app')->assertOk(); + }); +}); + // What holds for email codes holds for any code factor: its codes' state is // on the server, whatever copy of the session the browser sends. describe('a browser that sends back an earlier copy of its session', function () { diff --git a/tests/Feature/ExtendingTest.php b/tests/Feature/ExtendingTest.php index 3be84f65..166e2c0c 100644 --- a/tests/Feature/ExtendingTest.php +++ b/tests/Feature/ExtendingTest.php @@ -18,6 +18,7 @@ use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rules\Password; +use Illuminate\Validation\ValidationException; use Keyring\Changes\EmailChanges; use Keyring\Contracts\ResetsUserPasswords; use Keyring\Contracts\Responses\StatusResponse; @@ -37,6 +38,7 @@ use Keyring\Login\Attempt; use Keyring\Login\Requirement; use Keyring\Login\Verification; +use Keyring\Models\Authenticator; use Keyring\Models\PendingChange; use Keyring\Models\SecurityEvent; use Keyring\Pipeline\Context; @@ -450,3 +452,102 @@ public function update(Authenticatable&Model $user, array $input): void expect($notification->via($this->user))->toBe(['mail']) ->and(renderedMail($notification->toMail($this->user))['text'])->not->toBeEmpty()->not->toContain(':name')->not->toContain(':remaining')->not->toContain(':reasons'); })->with(KeyringManager::NOTIFICATIONS); + +// "Bot Checks" in docs/security.md: a check of the app's own goes before +// the limits, so a request it turns away is nobody's failed attempt. +it('lets a step of the app\'s own turn a request away before it counts against anyone', function () { + Keyring::pipeline(fn (Steps $steps) => $steps->before(EnsureNotThrottled::class, ChecksForBots::class)); + + foreach (range(1, 8) as $attempt) { + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'wrong'])->assertSessionHasErrors('captcha'); + } + + expect(loggedTypes())->toBe([]); + + // Past the check, the account has every guess it had. + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password', 'human' => 'yes'])->assertRedirect('/dashboard'); + + // A challenge page comes after a right password, so it isn't asked again there. + $this->post('/logout'); + $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password', 'human' => 'yes'])->assertRedirect(route('keyring.login.challenge')); + $this->post(route('keyring.login.verify', 'totp'), ['code' => totpCode($totp->secret)])->assertRedirect('/dashboard'); +}); + +class ChecksForBots +{ + public function handle(Context $context, Closure $next): Context + { + if ($context->identifying && $context->request->input('human') !== 'yes') { + throw ValidationException::withMessages(['captcha' => 'Please confirm you are not a robot.']); + } + + return $next($context); + } +} + +// NIST SP 800-63B-4, Sec. 4.6: a notice says who to contact when the +// recipient says the event wasn't theirs. +describe('a support contact', function () { + /** + * The published notification of a type, as Keyring would build it. + */ + function publishedNotification(string $type): Illuminate\Notifications\Notification + { + sendNotifications(); + + return Keyring::requiredNotification($type, [ + 'when' => 'Monday', 'code' => '12345678', 'minutes' => 10, + 'email' => 'n•••@example.com', 'revertUrl' => 'https://example.com/revert', + ]); + } + + it('is in every notice about the account once the app sets one', function (string $type) { + config(['keyring.support_contact' => 'https://example.com/support?from=email']); + + $mail = renderedMail(publishedNotification($type)->toMail($this->user)); + + expect($mail['text'])->toContain('contact us')->toContain('https://example.com/support?from=email') + ->and($mail['html'])->toContain('href="https://example.com/support?from=email"'); + })->with([...array_slice(KeyringManager::NOTIFICATIONS, 0, 12), 'verification_code', 'email_change_notice']); + + it('links an email address as one', function () { + config(['keyring.support_contact' => 'help@example.com']); + + $mail = renderedMail(publishedNotification('password_changed')->toMail($this->user)); + + expect($mail['html'])->toContain('href="mailto:help@example.com"')->toContain('>help@example.com') + ->and($mail['text'])->toContain('contact us: [help@example.com](mailto:help@example.com)'); + }); + + it('leaves anything that isn\'t a page or an address as plain text', function () { + config(['keyring.support_contact' => 'Call 020 7946 0000 [or](https://evil.example) visit reception']); + + $mail = renderedMail(publishedNotification('password_changed')->toMail($this->user)); + + expect($mail['html'])->toContain('contact us: Call 020 7946 0000 [or](https://evil.example) visit reception')->not->toContain('href="https://evil.example"') + ->and($mail['text'])->toContain('contact us: Call 020 7946 0000 [or](https://evil.example) visit reception'); + }); + + it('is left out until then', function (string $type) { + $notification = publishedNotification($type); + + expect($notification->contact)->toBeNull() + ->and(renderedMail($notification->toMail($this->user))['text'])->not->toContain('contact us'); + })->with(['password_changed', 'verification_code', 'email_change_notice']); + + it('is handed to a notification of the app\'s own that asks for it, and to no other', function () { + config(['keyring.support_contact' => 'help@example.com']); + Keyring::notifications(['password_changed' => WantsTheContact::class, 'new_device' => WantsNothing::class]); + + expect(Keyring::notification('password_changed', ['when' => 'Monday'])->contact)->toBe('help@example.com') + ->and(Keyring::notification('new_device', ['when' => 'Monday']))->toBeInstanceOf(WantsNothing::class); + }); +}); + +class WantsTheContact extends Illuminate\Notifications\Notification +{ + public function __construct(public ?string $contact = null) {} +} + +class WantsNothing extends Illuminate\Notifications\Notification {} diff --git a/tests/Feature/MailLimitsTest.php b/tests/Feature/MailLimitsTest.php index d7d3976b..f1cce52c 100644 --- a/tests/Feature/MailLimitsTest.php +++ b/tests/Feature/MailLimitsTest.php @@ -9,6 +9,7 @@ use App\Notifications\Keyring\PasswordChanged; use App\Notifications\Keyring\RecoveryCodesGenerated as RecoveryCodesGeneratedNotice; use Illuminate\Support\Facades\Notification; +use Illuminate\Support\Facades\Password; use Illuminate\Testing\TestResponse; use Keyring\Enums\Assurance; use Keyring\Events\AccountLocked as AccountLockedEvent; @@ -87,6 +88,23 @@ function signInFromNewBrowser(string $email = 'taylor@example.com'): void expect(SecurityEvent::query()->where('type', 'new_device')->count())->toBe(1); }); + // The reset link went to the address, so whoever finished the reset + // reads its mailbox: the notice goes there whoever typed it at first. + it('tells an address nobody had verified that its password was reset', function (bool $hidden) { + if (! $hidden) { + revealTakenAddresses(); + } + $this->user->forceFill(['email_verified_at' => null])->save(); + $token = Password::broker()->createToken($this->user); + + $this->post(route('password.update'), ['token' => $token, 'email' => 'taylor@example.com', 'password' => 'a-brand-new-long-password-1', 'password_confirmation' => 'a-brand-new-long-password-1']) + ->assertSessionHasNoErrors(); + + Notification::assertSentToTimes($this->user, PasswordChanged::class, 1); + // Where registration hides who has an account, the reset verifies the address too. + expect($this->user->fresh()->hasVerifiedEmail())->toBe($hidden); + })->with(['where registration hides who has an account' => true, 'where it says when an address is taken' => false]); + it('holds the newer notices to the same budget, with every event still logged', function () { $codes = Authenticator::factory()->recoveryCodes()->for($this->user, 'authenticatable')->create(); diff --git a/tests/Feature/PasswordHoldTest.php b/tests/Feature/PasswordHoldTest.php index 41d703f0..73031ef6 100644 --- a/tests/Feature/PasswordHoldTest.php +++ b/tests/Feature/PasswordHoldTest.php @@ -2,14 +2,17 @@ declare(strict_types=1); +use Illuminate\Contracts\Validation\UncompromisedVerifier; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Password; use Illuminate\Support\Facades\Route; use Keyring\Changes\PasswordHolds; use Keyring\Enums\Assurance; +use Keyring\Enums\Severity; use Keyring\Events\PasswordChangeRequired; use Keyring\Events\RiskAssessed; use Keyring\Facades\Keyring; +use Keyring\Login\Requirement; use Keyring\Models\Authenticator; use Keyring\Models\PasswordHold; use Keyring\Risk\Action; @@ -17,6 +20,7 @@ use Keyring\Risk\Checkpoint; use Keyring\Risk\Finding; use Keyring\Risk\Risk; +use Keyring\Risk\Signals\BreachedPassword; use Keyring\Risk\Signals\Signal; // NIST SP 800-63B-4, Sec. 3.1.1.2: no periodic changes, and a forced one @@ -237,6 +241,75 @@ function chooseNewPassword(string $current = 'password', string $new = 'a much l expect(PasswordHold::query()->exists())->toBeFalse(); }); + describe('by default, when the password just used is found in a breach', function () { + beforeEach(function () { + // Have I Been Pwned knows every password. + $this->app->instance(UncompromisedVerifier::class, new class implements UncompromisedVerifier + { + public function verify($data): bool + { + return false; + } + }); + + Keyring::risk()->signals([BreachedPassword::class]); + }); + + it('holds the user until they choose another, and logs that it did', function () { + signInWithPassword(); + + expect(app(PasswordHolds::class)->reason($this->user))->toBe('breached_password') + ->and(logEntry('risk_password_change')) + ->severity->toBe(Severity::Notice) + ->meta->toMatchArray(['checkpoint' => 'login', 'reasons' => ['The password appears in a known data breach.']]); + + $this->get('/home')->assertRedirect('/settings/password'); + + chooseNewPassword(); + $this->get('/home')->assertOk(); + }); + + it('does so whatever the finding scores', function () { + Keyring::risk()->signals([app()->make(BreachedPassword::class, ['score' => 1])]); + + signInWithPassword(); + + expect(Keyring::requiresPasswordChange($this->user))->toBeTrue(); + }); + + it('still asks for the second factor the level calls for', function () { + $totp = Authenticator::factory()->totp()->for($this->user, 'authenticatable')->create(); + Keyring::require(Requirement::aal1()); + + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect(route('keyring.login.challenge')); + $this->post(route('keyring.login.verify', 'totp'), ['code' => totpCode($totp->secret)])->assertRedirect('/dashboard'); + + $this->get('/home')->assertRedirect('/settings/password'); + }); + + it('leaves the answer to a responder of the app\'s own', function () { + Keyring::risk()->respond(fn (Risk $risk) => $risk->isElevated() ? Action::stepUp() : Action::allow()); + + signInWithPassword(); + + expect(Keyring::requiresPasswordChange($this->user))->toBeFalse(); + }); + }); + + it('holds nobody by default for a finding that isn\'t about the password', function () { + Keyring::risk()->signals([new class extends Signal + { + public function assess(Assessment $assessment): Finding + { + return new Finding('new_country', 40, 'Signing in from a new country (FR).'); + } + }]); + + signInWithPassword(); + + expect(Keyring::requiresPasswordChange($this->user))->toBeFalse(); + }); + it('says what it does', function () { expect(Action::allow()->requirePasswordChange()) ->changePassword->toBeTrue() diff --git a/tests/Feature/PasswordRulesTest.php b/tests/Feature/PasswordRulesTest.php index 275a16ca..d41d4311 100644 --- a/tests/Feature/PasswordRulesTest.php +++ b/tests/Feature/PasswordRulesTest.php @@ -340,6 +340,22 @@ function passes(string $password, mixed ...$arguments): bool && ! str_contains($request->url().$request->body(), substr($this->hash, 5))); }); + // OWASP ASVS 5.0.0, 15.3.2: an outbound call doesn't go where a + // redirect sends it. + it('follows no redirect, and counts one as no answer', function (int $status) { + config(['keyring.passwords.refuse_unchecked' => true]); + Http::fake([ + 'api.pwnedpasswords.com/*' => Http::response('', $status, ['Location' => 'https://elsewhere.example/range/'.substr($this->hash, 0, 5)]), + // Somewhere that would call every password clean. + 'elsewhere.example/*' => ($this->range)(), + ]); + + expect(($this->errors)())->toBe([__('keyring::keyring.password_unchecked')]); + + Http::assertSentCount(1); + Http::assertNotSent(fn (Request $request) => ! str_starts_with($request->url(), 'https://api.pwnedpasswords.com/')); + })->with([301, 302, 307, 308]); + it('asks nothing about a password too short to be taken, or with the breach check off', function () { config(['keyring.passwords.refuse_unchecked' => true]); Http::fake(['api.pwnedpasswords.com/*' => Http::response('', 503)]); diff --git a/tests/Feature/ProtectedChangesTest.php b/tests/Feature/ProtectedChangesTest.php index 7854f360..25efef8c 100644 --- a/tests/Feature/ProtectedChangesTest.php +++ b/tests/Feature/ProtectedChangesTest.php @@ -23,6 +23,7 @@ use Keyring\Facades\Keyring; use Keyring\Models\Authenticator; use Keyring\Sessions\Sessions; +use Keyring\Support\Url; use Keyring\Tests\Fixtures\User; beforeEach(function () { @@ -304,6 +305,40 @@ function linkIn(object $notification, string $text): string Notification::assertSentTo($this->user, ResetPassword::class, fn (ResetPassword $notification) => str_starts_with($notification->toMail($this->user)->actionUrl, 'https://app.example.com/reset-password/')); }); + // The broker finds a reset by its address, so the form has to post + // one. Keyring's link carries it to save typing it. An app that wants + // it out of the URL builds the link itself and has its page ask. + it('still resets from a link of the app\'s own that leaves the address out', function () { + $before = ResetPassword::$createUrlCallback; + ResetPassword::createUrlUsing(fn (User $user, string $token) => Url::route('password.reset', ['token' => $token])); + + try { + $this->post(route('password.email'), ['email' => 'taylor@example.com']); + + $link = null; + Notification::assertSentTo($this->user, ResetPassword::class, function (ResetPassword $notification) use (&$link) { + $link = $notification->toMail($this->user)->actionUrl; + + return true; + }); + + expect($link)->toStartWith(config('app.url').'/reset-password/')->not->toContain('taylor')->not->toContain('email='); + + $this->inertia()->get($link)->assertOk()->assertJsonPath('props.email', ''); + + $this->flushHeaders()->post(route('password.update'), [ + 'token' => basename(parse_url($link, PHP_URL_PATH)), + 'email' => 'taylor@example.com', + 'password' => 'correct horse battery staple', + 'password_confirmation' => 'correct horse battery staple', + ])->assertRedirect(route('login')); + + expect(Hash::check('correct horse battery staple', $this->user->fresh()->password))->toBeTrue(); + } finally { + ResetPassword::$createUrlCallback = $before; + } + }); + it('resets without signing in, and signs out every session', function () { Event::fake([PasswordReset::class]); $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password']); diff --git a/tests/Feature/RememberMeTest.php b/tests/Feature/RememberMeTest.php index 8352136b..054123f7 100644 --- a/tests/Feature/RememberMeTest.php +++ b/tests/Feature/RememberMeTest.php @@ -654,27 +654,42 @@ function sessionEndedReasons(): array expect(sessionEndedReasons())->toBe(['risk']); }); - it('stays refused once the lock is lifted, or the account is let back in', function (Closure $keepOut, Closure $letBack) { + it('stays refused once the lock is lifted', function () { $cookies = rememberedSignIn(); - $keepOut($this->user); + app(RiskLocks::class)->lock($this->user, 3600); $this->flushSession(); browser($cookies)->get('/outside')->assertOk(); browser($cookies)->get('/home')->assertRedirect('/login'); - $letBack($this->user); + app(RiskLocks::class)->unlock($this->user); expectKeptCookiesRefused($cookies); - })->with([ - 'a risk lock' => [ - fn (User $user) => app(RiskLocks::class)->lock($user, 3600), - fn (User $user) => app(RiskLocks::class)->unlock($user), - ], - 'an account the app keeps out' => [ - fn () => Keyring::allowSignInWhen(fn () => false), - fn () => Keyring::allowSignInWhen(fn () => true), - ], - ]); + }); + + it('stays refused once the account is let back in', function () { + $cookies = rememberedSignIn(); + Keyring::allowSignInWhen(fn () => false); + + $this->flushSession(); + browser($cookies)->get('/outside')->assertOk(); + browser($cookies)->get('/home')->assertRedirect('/login'); + + Keyring::allowSignInWhen(fn () => true); + + // Keeping the account out ended everything it had, Laravel's own + // cookie included, so nothing of Keyring's is even asked. + $this->flushSession(); + browser($cookies)->get('/home')->assertRedirect('/login'); + $this->assertGuest(); + + $this->flushSession(); + browser($cookies)->getJson('/home')->assertUnauthorized(); + $this->assertGuest(); + + expect(app(SessionRegistry::class)->forUser($this->user))->toBeEmpty() + ->and(sessionEndedReasons())->toBe(['not_allowed']); + }); }); describe('a "remember me" cookie that has been used', function () { diff --git a/tests/Feature/SecurityLogDocsTest.php b/tests/Feature/SecurityLogDocsTest.php index bc21728b..f16a7489 100644 --- a/tests/Feature/SecurityLogDocsTest.php +++ b/tests/Feature/SecurityLogDocsTest.php @@ -11,7 +11,7 @@ $documented = collect($rows)->flatMap(fn (array $row) => array_fill_keys(Str::matchAll('/`([a-z_]+)`/', $row[1])->all(), $row[2])); $recorded = Str::matchAll("/record(?:OrFail|Refusal)?\\(\\s*'([a-z_]+)'[,)]/", file_get_contents(__DIR__.'/../../src/Activity/RecordSecurityEvents.php').file_get_contents(__DIR__.'/../../src/Activity/SecurityLog.php')) - ->merge(['device_reported', 'device_revoked', 'risk_denied', 'risk_reauthenticate', 'risk_locked', 'risk_step_up', 'risk_revoked_sessions', 'risk_notified']) + ->merge(['device_reported', 'device_revoked', 'risk_denied', 'risk_reauthenticate', 'risk_locked', 'risk_step_up', 'risk_revoked_sessions', 'risk_notified', 'risk_password_change']) ->unique(); expect($recorded->diff($documented->keys())->values()->all())->toBe([]) diff --git a/tests/Feature/SecurityLogLimitsTest.php b/tests/Feature/SecurityLogLimitsTest.php index c087e21c..9835e1c8 100644 --- a/tests/Feature/SecurityLogLimitsTest.php +++ b/tests/Feature/SecurityLogLimitsTest.php @@ -3,11 +3,16 @@ declare(strict_types=1); use Illuminate\Auth\Events\Lockout as LaravelLockout; +use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Http\Request; use Illuminate\Support\Facades\Event; +use Illuminate\Support\Facades\Notification; +use Illuminate\Support\Facades\RateLimiter; use Keyring\Enums\Severity; use Keyring\Events\Lockout; +use Keyring\Events\RateLimited; use Keyring\Models\SecurityEvent; +use Keyring\Support\TooManyAttempts; beforeEach(function () { $this->user = taylor(); @@ -108,3 +113,88 @@ expect(array_column(written($log), 1))->toBe(['factor_failed', 'factor_failed', 'refusals_limited']); }); + +// OWASP ASVS 5.0.0, 16.3.3: a control that refuses is logged. The form +// limiter is one, on the routes the sign-in limits don't cover. +describe('the form limiter', function () { + it('logs once when it starts refusing, and answers as it always did', function () { + $refused = 0; + Event::listen(function (RateLimited $event) use (&$refused) { + $refused++; + }); + + // The limiter counts a request before anything looks at it, so an + // empty form fills it as well as a real one. + $statuses = array_map(fn () => $this->postJson('/forgot-password')->getStatusCode(), range(1, 9)); + $last = $this->postJson('/forgot-password', ['email' => 'nobody@example.com']); + + expect($statuses)->toBe([422, 422, 422, 422, 422, 422, 429, 429, 429]) + ->and($refused)->toBe(4) + ->and(logEntry('rate_limited')) + ->severity->toBe(Severity::Warning) + ->authenticatable_id->toBeNull() + ->ip->toBe('127.0.0.1') + ->and(logEntry('rate_limited')->meta)->toMatchArray(['limiter' => 'keyring', 'route' => 'password.email']) + ->and(logEntry('rate_limited')->meta['retry_after'])->toBeGreaterThan(0)->toBeLessThanOrEqual(60); + + // Laravel's own answer, as before. + $last->assertStatus(429)->assertHeader('Retry-After')->assertHeader('X-RateLimit-Limit', '6')->assertJsonPath('message', 'Too Many Attempts.'); + }); + + it('logs it against the account when someone is signed in', function () { + Notification::fake(); + // Where an account can be signed in before its address is verified. + revealTakenAddresses(); + $this->user->forceFill(['email_verified_at' => null])->save(); + $this->actingAs($this->user); + + foreach (range(1, 8) as $request) { + $this->post(route('verification.send')); + } + + expect(logEntry('rate_limited'))->authenticatable_id->toBe($this->user->id) + ->and(logEntry('rate_limited')->meta)->toMatchArray(['limiter' => 'keyring', 'route' => 'verification.send']); + }); + + it('logs the limit on passkey options too', function () { + foreach (range(1, 63) as $request) { + $this->getJson(route('keyring.login.options', 'passkey')); + } + + expect(logEntry('rate_limited')->meta)->toMatchArray(['limiter' => 'keyring-login-options', 'route' => 'keyring.login.options']); + }); + + it('logs again once the wait is over, and for each address it turns away', function () { + $fill = fn (string $ip = '127.0.0.1') => array_map(fn () => $this->withServerVariables(['REMOTE_ADDR' => $ip])->post('/forgot-password'), range(1, 8)); + + $fill(); + $fill('203.0.113.9'); + $this->travel(61)->seconds(); + $fill(); + + expect(SecurityEvent::query()->where('type', 'rate_limited')->oldest('id')->pluck('ip')->all())->toBe(['127.0.0.1', '203.0.113.9', '127.0.0.1']); + }); + + it('cannot be used to fill the log', function () { + config(['keyring.security_log.refusals' => 2]); + + // A minute apart, so each round is a refusal the log hasn't noted. + foreach (range(1, 5) as $round) { + array_map(fn () => $this->post('/forgot-password'), range(1, 7)); + $this->travel(61)->seconds(); + } + + expect(loggedTypes())->toBe(['rate_limited', 'rate_limited', 'refusals_limited']); + }); + + it('logs for a limiter of the app\'s own that answers the same way, and not for one that doesn\'t', function (bool $logs) { + RateLimiter::for('keyring', fn (Request $request) => $logs + ? Limit::perMinute(2)->by($request->ip())->response(new TooManyAttempts('keyring')) + : Limit::perMinute(2)->by($request->ip())); + + $statuses = array_map(fn () => $this->post('/forgot-password')->getStatusCode(), range(1, 3)); + + expect($statuses)->toBe([302, 302, 429]) + ->and(SecurityEvent::query()->where('type', 'rate_limited')->count())->toBe($logs ? 1 : 0); + })->with([true, false]); +}); diff --git a/tests/Feature/SecurityLogTest.php b/tests/Feature/SecurityLogTest.php index a59278b7..8da03109 100644 --- a/tests/Feature/SecurityLogTest.php +++ b/tests/Feature/SecurityLogTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Carbon\CarbonImmutable; use Illuminate\Database\Eloquent\Attributes\Table; use Illuminate\Http\Request; use Illuminate\Support\Facades\Context; @@ -65,6 +66,27 @@ function nextRequest(): void ->and($lines[1][2]['meta'])->toBe(['factors' => ['password']]); }); +// OWASP ASVS 5.0.0, 16.2.2: a time that says which timezone it's in. +// Laravel's own log lines are stamped without one. +it('gives each line its time with an offset, whatever timezone the app keeps', function (string $timezone, string $at) { + config(['app.timezone' => $timezone]); + date_default_timezone_set($timezone); + // The same moment everywhere, on the clock the app keeps. + $this->travelTo(CarbonImmutable::parse('2026-11-08 14:05:09', 'UTC')->setTimezone($timezone)); + config(['logging.default' => 'memory']); + $log = logTo(); + withFeatures([]); + + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password']); + + expect(written($log)[0][2]['at'])->toBe($at); + + date_default_timezone_set('UTC'); +})->with([ + 'utc' => ['UTC', '2026-11-08T14:05:09+00:00'], + 'a local timezone' => ['Europe/Paris', '2026-11-08T15:05:09+01:00'], +]); + it('writes to the channel the app names', function () { $default = logTo('default-channel'); $security = logTo('security'); @@ -96,7 +118,7 @@ function nextRequest(): void Keyring::withoutProtection(fn () => null, reason: 'support ticket 42'); - expect(written($log))->toBe([['warning', 'protection_bypassed', ['ip' => '127.0.0.1', 'user_agent' => 'Symfony', 'request_id' => Context::getHidden(SecurityLog::REQUEST_ID), 'meta' => ['reason' => 'support ticket 42']]]]); + expect(written($log))->toBe([['warning', 'protection_bypassed', ['at' => now()->toIso8601String(), 'ip' => '127.0.0.1', 'user_agent' => 'Symfony', 'request_id' => Context::getHidden(SecurityLog::REQUEST_ID), 'meta' => ['reason' => 'support ticket 42']]]]); config(['logging.default' => 'broken', 'logging.channels.broken' => ['driver' => 'monolog', 'handler' => BrokenLogHandler::class]]); $ran = false; diff --git a/tests/Feature/SignInGateTest.php b/tests/Feature/SignInGateTest.php index ee273813..8b0358c6 100644 --- a/tests/Feature/SignInGateTest.php +++ b/tests/Feature/SignInGateTest.php @@ -112,6 +112,64 @@ function ban(User $user): void ->and(SecurityEvent::query()->where('type', 'session_ended')->sole()->meta['reason'])->toBe('not_allowed'); }); +describe('an account kept out while some of its sessions stay away', function () { + beforeEach(function () { + // Signed in on a laptop that makes no request while the account is + // banned, with "remember me" ticked and the browser trusted. + $response = $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password', 'remember' => true]); + $this->laptop = session()->all(); + $this->laptopCookies = collect([Auth::guard()->getRecallerName(), 'remembered_session']) + ->mapWithKeys(fn (string $name) => [$name => $response->getCookie($name)->getValue()]) + ->all(); + $this->user->devices()->forceCreate(['token_hash' => hash('sha256', 'laptop'), 'trusted_until' => now()->addDay()]); + + // And on a phone, which does. + $this->flushSession(); + Auth::forgetGuards(); + $this->defaultCookies = []; + $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password']); + Auth::forgetGuards(); + }); + + it('ends them all with the first request it refuses', function () { + ban($this->user); + + $this->get('/home')->assertRedirect('/login'); + + expect(app(SessionRegistry::class)->forUser($this->user))->toBeEmpty() + ->and($this->user->devices()->whereNotNull('trusted_until')->count())->toBe(0) + ->and(logEntry('sessions_revoked')->meta)->toBe(['count' => 2]) + ->and(logEntry('session_ended')->meta)->toBe(['reason' => 'not_allowed']); + + // Let back in, the laptop is signed out: its session and its + // "remember me" both ended with the phone's. + $this->user->forceFill(['name' => 'Taylor'])->save(); + + sendBackSession($this->laptop); + $this->get('/home')->assertRedirect('/login'); + $this->assertGuest(); + + $this->flushSession(); + Auth::forgetGuards(); + $this->withOnlyCookies($this->laptopCookies)->get('/home')->assertRedirect('/login'); + $this->assertGuest(); + }); + + it('ends them once, not again for each session that then finds out', function () { + ban($this->user); + + $this->get('/home')->assertRedirect('/login'); + $token = $this->user->refresh()->getRememberToken(); + + sendBackSession($this->laptop); + $this->get('/home')->assertRedirect('/login'); + + expect(SecurityEvent::query()->where('type', 'sessions_revoked')->count())->toBe(1) + ->and(SecurityEvent::query()->where('type', 'session_ended')->count())->toBe(2) + ->and($this->user->refresh()->getRememberToken())->toBe($token); + }); +}); + it('refuses a "remember me" cookie', function () { $response = $this->post('/login', ['email' => 'taylor@example.com', 'password' => 'password', 'remember' => true]); $cookies = collect([Auth::guard()->getRecallerName(), 'remembered_session']) diff --git a/tests/Feature/StandardsDocsTest.php b/tests/Feature/StandardsDocsTest.php new file mode 100644 index 00000000..c8bd430a --- /dev/null +++ b/tests/Feature/StandardsDocsTest.php @@ -0,0 +1,89 @@ +page = file_get_contents(__DIR__.'/../../docs/owasp-asvs.md'); + $this->defaults = require __DIR__.'/../../config/keyring.php'; + + // What keyring:install writes with its default answers. + $this->provider = (fn () => $this->provider(new Filesystem, [], true, false))->call(new InstallCommand); +}); + +it('lists the features a default install turns on', function () { + preg_match('/^- (\w+) features: (.+),$/m', $this->page, $line); + + $listed = Str::matchAll('/`([a-z-]+)`/', $line[2])->all(); + + expect($listed)->toBe($this->defaults['features'])->toHaveCount(5) + ->and($line[1])->toBe('five'); +}); + +it('counts the security emails and risk signals a default install registers', function () { + $notices = Str::matchAll("/^ +'([a-z_]+)' => Notifications/m", $this->provider) + ->reject(fn (string $type) => in_array($type, ['verification_code', 'confirm_email_change', 'email_change_notice', 'email_address_in_use', 'already_registered'], true)) + ->values(); + $signals = Str::matchAll('/^ +Signals\\\\(\w+)::class,$/m', $this->provider); + + preg_match('/^- (\w+) \[security emails\]\([^)]+\): (.+),$/m', $this->page, $emails); + preg_match('/^- (\w+) \[risk signals\]\([^)]+\): (.+),$/m', $this->page, $risk); + + expect($notices->all())->toBe(['password_changed', 'authenticator_added', 'authenticator_removed', 'recovery_code_used', 'recovery_codes_generated', 'email_changed', 'account_locked', 'suspicious_activity']) + ->and($emails[1])->toBe('eight') + // One phrase for each, in the order the provider lists them. + ->and(preg_split('/, (?:and )?/', $emails[2]))->toHaveCount($notices->count()) + ->and($signals->all())->toBe(['SessionFingerprintChanged', 'RepeatedFactorFailures', 'SuccessAfterFailures']) + ->and($risk[1])->toBe('three') + ->and(preg_split('/, (?:and )?/', $risk[2]))->toHaveCount($signals->count()); +}); + +it('gives the session limits the config ships with', function () { + $sessions = $this->defaults['sessions']; + + expect($this->page)->toContain('a two hour inactivity limit (14 days for a browser that ticked "remember me"), a 30 day limit overall and a limit of 100 sessions per account') + ->and(Duration::seconds($sessions['idle']))->toBe(2 * 3600) + ->and(Duration::seconds($sessions['remember_idle']))->toBe(14 * 86400) + ->and(Duration::seconds($sessions['absolute']))->toBe(30 * 86400) + ->and($sessions['max'])->toBe(100) + ->and($sessions['levels'])->toBe(['aal2' => ['idle' => '1h', 'absolute' => '24h'], 'aal3' => ['idle' => '15m', 'absolute' => '12h']]) + ->and($sessions['end_on_lapse'])->toBeFalse() + ->and($this->defaults['limits']['consecutive'])->toBe(100) + ->and($this->defaults['passwords']['min_without_mfa'])->toBe(15) + ->and($this->defaults['passwords']['min_with_mfa'])->toBe(8) + ->and($this->defaults['support_contact'])->toBeNull(); +}); + +it('has a row for every requirement of ASVS 5.0.0 chapters V6 and V7, each with a status the page defines', function () { + $requirements = [ + '6.1' => 3, '6.2' => 12, '6.3' => 8, '6.4' => 6, '6.5' => 8, '6.6' => 4, '6.7' => 2, '6.8' => 4, + '7.1' => 3, '7.2' => 4, '7.3' => 2, '7.4' => 5, '7.5' => 3, '7.6' => 2, + ]; + + preg_match_all('/^\| \*\*([^*]+)\*\* \| /m', Str::between($this->page, "## Introduction\n", "\n## What a Default Install"), $legend); + preg_match_all('/^\| ((?:6|7)\.\d+\.\d+) [^|]+\| (\d) \| ([^|]+) \|/m', $this->page, $rows, PREG_SET_ORDER); + + $expected = collect($requirements)->flatMap(fn (int $count, string $section) => array_map(fn (int $n) => "{$section}.{$n}", range(1, $count))); + $statuses = collect($rows)->mapWithKeys(fn (array $row) => [$row[1] => trim($row[3])]); + + expect($expected)->toHaveCount(66) + ->and($statuses->keys()->all())->toBe($expected->all()) + ->and($statuses->unique()->diff($legend[1])->values()->all())->toBe([]); +}); + +it('uses only those statuses in its other tables', function () { + preg_match_all('/^\| \*\*([^*]+)\*\* \| /m', Str::between($this->page, "## Introduction\n", "\n## What a Default Install"), $legend); + + $tables = Str::between($this->page, "### The Other Chapters\n", "\n## What Is Left to Your App"); + preg_match_all('/^\|(?: [^|]+\|){1,2} (Met by default|Met|Needs setup|Partly|Deviates|Yours|N\/A|[A-Z][a-z]+(?: [a-z]+)*) \| [^|]+\|$/m', $tables, $rows); + + expect(count($rows[1]))->toBeGreaterThan(80) + ->and(array_values(array_diff(array_unique($rows[1]), $legend[1])))->toBe([]); +}); diff --git a/tests/Unit/RequirementTest.php b/tests/Unit/RequirementTest.php index 5b0919b0..37eca2c6 100644 --- a/tests/Unit/RequirementTest.php +++ b/tests/Unit/RequirementTest.php @@ -23,6 +23,46 @@ function verified(string $factor, array $categories, bool $phishingResistant = f ->and(Requirement::aal1()->isMetBy([]))->toBeFalse(); }); +it('takes aal2 to need something the user has', function () { + $password = verified('password', [Category::Knowledge]); + $voice = verified('voice', [Category::Inherence]); + $spokenPhrase = verified('spoken-phrase', [Category::Knowledge, Category::Inherence]); + $totp = verified('totp', [Category::Possession]); + $passkey = verified('webauthn', [Category::Possession, Category::Inherence], phishingResistant: true); + + // NIST takes a biometric only with the authenticator it unlocks, so a + // password and a factor that is nothing but one stays at AAL1. + expect(Requirement::aal2()->isMetBy([$password, $voice]))->toBeFalse() + ->and(Requirement::aal2()->isMetBy([$spokenPhrase]))->toBeFalse() + ->and(Assurance::of([$password, $voice]))->toBe(Assurance::AAL1) + ->and(Assurance::of([$spokenPhrase]))->toBe(Assurance::AAL1) + ->and(Requirement::named('aal2')->isMetBy([$password, $voice]))->toBeFalse() + // With a factor the user holds it is AAL2, whichever comes second. + ->and(Assurance::of([$password, $totp]))->toBe(Assurance::AAL2) + ->and(Assurance::of([$voice, $totp]))->toBe(Assurance::AAL2) + ->and(Assurance::of([$passkey]))->toBe(Assurance::AAL2) + // And two categories of any kind can still be asked for by name. + ->and(Requirement::factors(2)->isMetBy([$password, $voice]))->toBeTrue(); +}); + +it('offers nothing that can\'t get an attempt to aal2, and asks for what there is where that is all a user has', function () { + $password = verified('password', [Category::Knowledge]); + $voice = verified('voice', [Category::Inherence]); + $totp = verified('totp', [Category::Possession]); + + expect(Requirement::aal2()->wouldProgress([$password], $voice))->toBeFalse() + ->and(Requirement::aal2()->wouldProgress([$password], $totp))->toBeTrue() + ->and(Requirement::aal2()->wouldProgress([$totp], $password))->toBeTrue() + ->and(Requirement::aal2()->wouldProgress([$totp], $voice))->toBeTrue() + // ifEnrolled(): both of what they have, which still isn't AAL2. + ->and(Requirement::aal2()->limitedTo([$password, $voice])) + ->factors->toBe(2) + ->categories->toBe([]) + ->and(Requirement::aal2()->limitedTo([$password, $voice])->isMetBy([$password]))->toBeFalse() + ->and(Requirement::aal2()->limitedTo([$password, $voice])->isMetBy([$password, $voice]))->toBeTrue() + ->and(Requirement::fromArray(Requirement::aal2()->toArray()))->toEqual(Requirement::aal2()); +}); + it('lets a user verified passkey finish aal2 on its own, and aal3 only when it can\'t sync and was attested', function () { $synced = verified('webauthn', [Category::Possession, Category::Inherence], phishingResistant: true); $bound = verified('webauthn', [Category::Possession, Category::Inherence], phishingResistant: true, deviceBound: true);