diff --git a/CHANGELOG.md b/CHANGELOG.md index dff4aa4b..c0a80ba0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,7 +50,7 @@ The first release. Nothing is tagged yet. ### 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. +- A security log with a severity and a request ID on every entry, of sign ins, sessions "remember me" carried on, 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 about changes to how an account signs in and about suspicious attempts, sent from the start as far as your features go. Each is a notification you can swap for your own or turn off, and `SecurityNotice::toMailUsing()` writes them all from your own template. - `support_contact`, so every notice can say who to contact. @@ -58,8 +58,8 @@ The first release. Nothing is tagged yet. ### Tooling -- `keyring:install`, which asks which sign-in methods and features you want and publishes a config, a provider and your actions; `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. +- `keyring:install`, which asks which sign-in methods and features you want and publishes a config, a provider and your actions. Its defaults give an authenticator app that every user must set up, and `--factor=none` the password alone. Also `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`, `Cross-Origin-Opener-Policy: same-origin-allow-popups` 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 30685157..9a5b4d47 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Fortify keeps 2FA in three columns on `users`. That gives one TOTP per user, and - **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, 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.** The emails are sent from the start, and each can be swapped for your own notification, restyled or turned off. -- **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. +- **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, partly met, waiting on something you turn on, a deliberate deviation or your app's job, and the page says which and why. - **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. Every feature and sign-in method beyond the password is opt-in. See [Adding Features](docs/quick-start.md#adding-features). diff --git a/config/keyring.php b/config/keyring.php index f016992a..5075f9d1 100644 --- a/config/keyring.php +++ b/config/keyring.php @@ -188,8 +188,9 @@ | | Where users can reach you about their account: a page's URL or an email | address. Every notification is handed it as $contact, and Keyring's - | own end with "if this wasn't you and you need help, contact us" when - | it's set. Null leaves the line out. + | security notices, emailed code and email change notice end with "if + | this wasn't you and you need help, contact us" when it's set. Null + | leaves the line out. | */ diff --git a/docs/configuration.md b/docs/configuration.md index fd3abb17..b92dfa91 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -103,7 +103,7 @@ Signed-out users are sent to the route named `login`. 'middleware' => ['web', AddSecurityHeaders::class], ``` -Keyring registers its routes inside a group with this prefix, domain and middleware. `Keyring\Http\Middleware\AddSecurityHeaders` sends `Cache-Control: no-store, private`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY` and `Referrer-Policy: same-origin` on every Keyring response, and `Referrer-Policy: no-referrer` on the pages emailed links open. It leaves `X-Frame-Options` off a response that already says who may frame it, with a header of its own or a `frame-ancestors` directive, so a middleware listed after it here can allow framing. See [Links and Headers](security.md#links-and-headers). Take it out of the list if your app sets those headers itself, but keep the URLs of emailed links out of `Referer` headers some other way: they carry their token. +Keyring registers its routes inside a group with this prefix, domain and middleware. `Keyring\Http\Middleware\AddSecurityHeaders` sends `Cache-Control: no-store, private`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Cross-Origin-Opener-Policy: same-origin-allow-popups` and `Referrer-Policy: same-origin` on every Keyring response, and `Referrer-Policy: no-referrer` on the pages emailed links open. It leaves `X-Frame-Options` off a response that already says who may frame it, with a header of its own or a `frame-ancestors` directive, so a middleware listed after it here can allow framing. See [Links and Headers](security.md#links-and-headers). Take it out of the list if your app sets those headers itself, but keep the URLs of emailed links out of `Referer` headers some other way: they carry their token. If you set `routes` to `false`, Keyring registers nothing, and you call `Keyring::routes()` where you want them, for example inside your own group: diff --git a/docs/devices-and-sessions.md b/docs/devices-and-sessions.md index 273be9d3..ac4b2eeb 100644 --- a/docs/devices-and-sessions.md +++ b/docs/devices-and-sessions.md @@ -382,6 +382,8 @@ So a remembered sign in also sets a Keyring cookie holding that session's regist It's also refused while the account is [risk locked](risk.md#actions). +A session carried on this way dispatches `Keyring\Events\SessionResumed` and is logged as `session_resumed`, so the [security log](security-log-and-emails.md#entry-types) shows every time a browser was signed in, with a proof or without. + Your own `Auth::login($user, remember: true)` gets the Keyring cookie too, on the response that signs in, as long as that route has the middleware. A session given a new registry record (a mid-session [step-up](risk.md#actions), or `rotate()` on the `cookie` session driver) gets a new cookie for it. If Laravel's cookie first reaches a route without the middleware, Laravel signs it in there and Keyring notes that in the session. The next request the middleware sees is checked the same way. @@ -560,5 +562,6 @@ In `Keyring\Events`: | `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, 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) | +| `SessionResumed` | `user`, `session` (the `RegisteredSession` a remembered browser carries on as) | | `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 e8a7811a..a1798f2c 100644 --- a/docs/events.md +++ b/docs/events.md @@ -50,6 +50,7 @@ No event has a password, code or token among its properties. `Attempting`, `Fact | `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, 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` | +| `SessionResumed` | ["Remember me"](devices-and-sessions.md#remember-me) signed a browser back in after its session had gone unused, with nothing proved. | `user`, `session` (the `RegisteredSession` it carries on as) | | `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) | A user signing out on purpose is `LoggedOut`, not `SessionEnded`. The request that brought a used cookie also gets a `SessionEnded` with `reused`; `RememberMeReused` fires once, and only when there was still a session to end. See [Devices & Sessions](devices-and-sessions.md#events). diff --git a/docs/installation.md b/docs/installation.md index c4b033eb..f406a267 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -37,17 +37,17 @@ php artisan migrate The command asks three 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. +1. **Which sign-in methods besides the password?** An authenticator app by default, so a new app starts with a second factor. Untick it for the password alone. 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). -Without prompts (`--no-interaction`, or in CI) you get the same defaults. You can also answer with options: +Without prompts (`--no-interaction`, or in CI) you get the same defaults: an authenticator app that everyone must set up. You can also answer with options: ```bash php artisan keyring:install --factor=totp --factor=passkeys --feature=registration --feature=manage-authenticators --require-second-factor ``` -`--factor` takes `totp`, `passkeys`, `security-keys` or `email-codes`. `--feature` takes `registration`, `reset-passwords`, `email-verification`, `update-passwords`, `manage-authenticators`, `devices`, `email-changes` or `security-log`, and replaces the defaults (`registration`, `reset-passwords`, `email-verification`, `update-passwords` and `security-log`), so list those too if you want them. An unknown value stops the command before it writes anything, and an unknown feature in `config/keyring.php` stops the app booting, rather than leaving that feature off. `--require-second-factor` and `--optional-second-factor` answer the second question; requiring one without a sign-in method that counts stops the command too. +`--factor` takes `totp`, `passkeys`, `security-keys` or `email-codes`, or `none` for the password alone. `--feature` takes `registration`, `reset-passwords`, `email-verification`, `update-passwords`, `manage-authenticators`, `devices`, `email-changes` or `security-log`, and replaces the defaults (`registration`, `reset-passwords`, `email-verification`, `update-passwords` and `security-log`), so list those too if you want them. An unknown value stops the command before it writes anything, and an unknown feature in `config/keyring.php` stops the app booting, rather than leaving that feature off. `--require-second-factor` and `--optional-second-factor` answer the second question; requiring one without a sign-in method that counts stops the command too. Pass `--force` to overwrite files that already exist; without it, existing files are skipped, and with `config/keyring.php` already there it doesn't ask which features to turn on. It's safe to run again: a migration you already have is never added a second time under a new timestamp, and one a later version brought is added on its own. Running it again on an older install adds any new actions too, but leaves your provider alone, so register them there yourself. A new action's routes fail until you do, with an exception that says which `Keyring::*Using()` call is missing. A new email needs nothing: Keyring's emails are its own, so one a later version brings is sent from the start. diff --git a/docs/owasp-asvs.md b/docs/owasp-asvs.md index 4254fc90..2a5d0775 100644 --- a/docs/owasp-asvs.md +++ b/docs/owasp-asvs.md @@ -37,8 +37,8 @@ Both standards verify an application or a service, not a package. Keyring can me `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), -- five features: `registration`, `reset-passwords`, `email-verification`, `update-passwords` and `security-log`, +- the password, with [Keyring's password rules](protected-changes.md#password-rules), and an authenticator app as a second factor that every user must set up before going further, with recovery codes, +- six features: `registration`, `reset-passwords`, `email-verification`, `update-passwords`, `manage-authenticators` and `security-log`, - [registration that doesn't reveal who has an account](sign-in-flow.md#without-revealing-who-has-an-account), - eleven [security emails](security-log-and-emails.md#security-emails): new device, password changed, sign-in method added, sign-in method removed, second factor failed, recovery code used, new recovery codes, suspicious activity, account locked, email address changed, and email change undone, - three [risk signals](risk.md): a session turning up in another browser, repeated failed second factors, and a sign in that follows several failures, @@ -46,9 +46,9 @@ Both standards verify an application or a service, not a package. Keyring can me 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)). +It also has the main thing Level 2 adds: everyone signs in with a second factor ([6.3.3](#v63-general-authentication-security)). The rest of [Level 2](#level-2) is yours to set. Installing with `--factor=none`, unticking the authenticator app, or answering no to "Require a second factor for everyone?" gives that up, and leaves Level 1. -Three of those emails have nothing to announce in a default install: new device needs `Features::devices()`, second factor failed needs a sign-in method besides the password, and email change undone needs `Features::emailChanges()`. +Two of those emails have nothing to announce in a default install: new device needs `Features::devices()`, and email change undone needs `Features::emailChanges()`. An app that doesn't use the published `KeyringServiceProvider` gets the config defaults and the security emails, which are Keyring's own, and no risk signals until it registers some. @@ -69,7 +69,7 @@ Don't turn on `registration.reveal_taken`, add composition rules to the password Everything in Level 1, and: -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)): +1. **Require a second factor** ([6.3.3](#v63-general-authentication-security)). A default install does. If you installed without one, install again 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 @@ -155,7 +155,7 @@ 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::asExtraStep()` 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)). 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`. +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. Keyring's own risk response then emails the user about a sign in after a long quiet period or after several failures; a responder of your own has to do the same, as [Telling the User](risk.md#telling-the-user) shows. 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, and set `sessions.end_on_lapse`, so a session ends when AAL3 runs out instead of carrying on at a lower level. @@ -197,9 +197,9 @@ Everything in Level 2, and: |---|---|---|---| | 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 | 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.3 Multi-factor authentication is required; a hardware factor at Level 3 | 2 | Met by default | A default install registers an authenticator app and adds `keyring.enrolled`, so every user must set one up. Installing with `--factor=none`, or answering no to requiring a second factor, undoes it, as does taking the middleware out of your provider. Level 2: a second factor registered and `keyring.enrolled`. 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 | Keyring 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. `second_factor_failed` is sent once there's 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.5 Users are notified of suspicious authentication attempts | 3 | Partly | As installed, Keyring emails `second_factor_failed`, when the password was right and the next factor wasn't; `suspicious_activity`, when a sign in follows several failures, or what the risk signals find adds up to a level that notifies ([Telling the User](risk.md#telling-the-user)); and `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). Left to you: a new client (`new_device`) and a sign in after a long quiet period (`InactiveAccount`) need `Features::devices()`, and a sign in from an unusual place needs a [locator](devices-and-sessions.md#locations) and a location signal. A responder of your own replaces Keyring's, so have it notify for these too. 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::asExtraStep()`. 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 | Keyring 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. Setting one of these to `null` in `Keyring::notifications()` stops it being sent, 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). | @@ -224,7 +224,7 @@ Everything in Level 2, and: | 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 | 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.6 Any factor can be revoked | 3 | Met by default | `DELETE /user/authenticators/{id}` removes a sign-in method, with `Features::manageAuthenticators()`, which adding one needs anyway. Taking the feature out while users hold sign-in methods (after an import, say) leaves them no way to remove one. `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 | | @@ -234,7 +234,7 @@ Everything in Level 2, and: |---|---|---|---| | 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.3 Codes are protected from brute force | 2 | Met by default | Five wrong guesses per sign in, on top of the usual limits. Like the limits in 6.3.1, the numbers are options with no ceiling: keep them near their defaults. | | 6.6.4 Push notifications are rate limited | 3 | N/A | Keyring has no push factor. | #### V6.7 Cryptographic Authentication Mechanism @@ -284,7 +284,7 @@ Everything in Level 2, and: | | 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`. 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.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 one of its signed-in sessions makes ends every session the account has. A refused sign-in attempt ends nothing. 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 | 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). | @@ -302,7 +302,7 @@ Everything in Level 2, and: | | Level | | What to do | |---|---|---|---| | 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. | +| 7.6.2 A session is only created by the user's action | 2 | Yours | A sign in through Keyring is a POST that carries a proof. The three ways a session starts or carries on without one are in 6.3.4: "remember me", registration with `registration.reveal_taken`, and your own `Auth::login()`. For a social login, the redirect and consent are the provider's and your callback's. | ### The Other Chapters @@ -311,16 +311,17 @@ ASVS's other chapters are about your whole application. These are the requiremen | | | 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`, `keyring-pages` 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.1 Anti-automation controls | Met by default | The [rate limits](security.md#rate-limiting), and the `keyring`, `keyring-pages` 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 and a TOTP window over one step are refused, and an RSA floor under 2048 bits is raised to 2048. | | 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.4.8 A `Cross-Origin-Opener-Policy` on every page (Level 3) | Met by default | `same-origin-allow-popups` on every Keyring response, so a site that opens one of Keyring's pages keeps no handle on it, while a window the page opens itself, for a social login say, still answers to it. A response that already has the header keeps its own. Taking `AddSecurityHeaders` out of `keyring.middleware` removes it, and your other pages are yours. | | 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. | +| 8.2.4 Adaptive controls from contextual attributes (Level 3) | Partly | The [risk signals](risk.md) the published provider starts with look at failure history at sign in and at the browser a running session is in. The ones that go by the device (`NewDevice`, `InactiveAccount`) need `Features::devices()`, and the ones that go by place 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. | @@ -335,13 +336,13 @@ ASVS's other chapters are about your whole application. These are the requiremen | 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.2 Outbound calls don't follow redirects | Partly | 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). | +| 16.5.3 Fails securely | Deviates | The breach check in 16.5.2 lets a password through on an error, which is this requirement's own example. And 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. @@ -363,13 +364,13 @@ A session Keyring calls AAL3 has met NIST's rules for the authentication itself. ### 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. +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. If you write an SMS code factor, Sec. 3.1.3.3 and 3.2.9 become yours too. | 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.2 A phishing-resistant option is offered at AAL2 | Yours | Passkeys and security keys ship with Keyring. A default install registers an authenticator app, which a phishing page can relay, so offer one of them beside it. | | 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. | @@ -381,7 +382,7 @@ Where Keyring doesn't meet a section whatever you configure. Sections that aren' | 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). | +| 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, and a factor of your own that overrides `limits()` without the default list loses the cap. `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. | @@ -390,6 +391,7 @@ Where Keyring doesn't meet a section whatever you configure. Sections that aren' | 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.3 A compromised authenticator is suspended or invalidated promptly | Yours | Keyring refuses a sign in whose key counter went backwards and logs `clone_suspected`, but removes nothing by itself. Act on `Keyring\Events\CloneSuspected`, and on a user's report, by removing the authenticator. | | 4.6 A notice says who to contact | Needs setup | Set [`support_contact`](security-log-and-emails.md#a-support-contact), and Keyring's 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. | @@ -412,17 +414,17 @@ Keyring follows OWASP's Authentication, Session Management, Multifactor Authenti | 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 | 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. That holds while Laravel encrypts cookies, as the `web` group does: don't list Keyring's cookies under `encryptCookies(except:)`. | | 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 | Offer TOTP, and require MFA where you can | Met by default | A default install registers an authenticator app that everyone must set up. Installing with `--factor=none` gives it up: 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. An install with `--factor=none` has no second factor to fail. | +| Multifactor Authentication | Re-authenticate and notify when a factor changes | Met by default | `changes_middleware`, and the `authenticator_added` and `authenticator_removed` emails. Emptying the first or setting the emails to `null` undoes it. | | 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 | Rate limit reset requests per account | Yours | Laravel's broker `throttle`, which is on in a new Laravel app and 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). | @@ -442,7 +444,7 @@ 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`, `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. +- **Headers on your own pages.** Keyring's responses send `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: same-origin`, `X-Frame-Options: DENY` and `Cross-Origin-Opener-Policy: same-origin-allow-popups`. 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: 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. diff --git a/docs/protected-changes.md b/docs/protected-changes.md index 81eb7ca2..10ee8c29 100644 --- a/docs/protected-changes.md +++ b/docs/protected-changes.md @@ -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 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. +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-4 says the same (Sec. 3.1.1.2). People meet such rules with `Password1!`, which the length rules and the lists above deal with better. ## Resetting the Password diff --git a/docs/quick-start.md b/docs/quick-start.md index 50f800e4..a4909f4a 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -25,7 +25,7 @@ php artisan migrate > composer require entity/keyring:dev-main > ``` -`keyring:install` asks which sign-in methods you want besides the password, whether everyone must set up a second factor (when you picked one they can), which features to turn on, and whether to email users when their password, sign-in methods or email address change. Recovery codes come with any second sign-in method, so losing it isn't the end of an account. Accepting every default, or running with `--no-interaction`, gives you the password, registration, password resets, email verification, password changes, the security log and those emails. You can add the rest later: every action is published, so a feature works as soon as it's in the list. +`keyring:install` asks which sign-in methods you want besides the password, whether everyone must set up a second factor (when you picked one they can), and which features to turn on. Recovery codes come with any second sign-in method, so losing it isn't the end of an account. Accepting every default, or running with `--no-interaction`, gives you the password, an authenticator app that everyone must set up, registration, password resets, email verification, password changes, managing sign-in methods and the security log. Pass `--factor=none` for the password alone. You can add the rest later: every action is published, so a feature works as soon as it's in the list. Add the trait to your user model, and keep Laravel's `hashed` cast on the password. Registration leaves a new user signed out until they've verified their address, so nobody can use the form to find out who has an account. That needs `MustVerifyEmail` (the installer turns on email verification for you): diff --git a/docs/risk.md b/docs/risk.md index b46a02ab..8cf6acc9 100644 --- a/docs/risk.md +++ b/docs/risk.md @@ -73,7 +73,9 @@ 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). The `suspicious_activity` [notice](security-log-and-emails.md#email-types) is what's sent, and `keyring:install` registers it: +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`, which asks for a second factor and sends nothing, so Keyring's own response emails the user whenever either is found, whatever the level. The `suspicious_activity` [notice](security-log-and-emails.md#email-types) is what's sent. + +A responder of your own replaces Keyring's, this included. To keep it, notify for the two findings yourself: ```php use Keyring\Risk\Action; @@ -83,16 +85,18 @@ use Keyring\Risk\Risk; use Keyring\Risk\Signals\InactiveAccount; use Keyring\Risk\Signals\SuccessAfterFailures; -Keyring::risk() - ->push(InactiveAccount::class, SuccessAfterFailures::class) - ->respond(fn (Risk $risk, Checkpoint $at) => match ($risk->level) { +Keyring::risk()->respond(function (Risk $risk, Checkpoint $at) { + $action = match ($risk->level) { Level::Low => Action::allow(), - Level::Medium => $risk->has('inactive_account') || $risk->has('success_after_failures') - ? Action::stepUp()->notify() - : Action::stepUp(), + Level::Medium => Action::stepUp(), Level::High => Action::stepUp()->notify(), Level::Critical => Action::deny()->revokeAllSessions()->notify(), - }); + }; + + return $risk->has(InactiveAccount::FINDING) || $risk->has(SuccessAfterFailures::FINDING) + ? $action->notify() + : $action; +}); ``` The email lists what was found, such as "The first sign in for 120 days." @@ -118,9 +122,12 @@ 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 registered, as it is by `keyring:install`, 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, but the owner stays signed in everywhere else. + +Three findings are answered whatever the level: -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). +- A sign in that follows several failures (`SuccessAfterFailures`) or a long quiet period (`InactiveAccount`) adds `->notify()` to the action above. See [Telling the User](#telling-the-user). +- When `BreachedPassword` finds the password that was just used in a breach, `->requirePasswordChange()` is added. See [Requiring a New Password](#requiring-a-new-password). Set your own in `KeyringServiceProvider`: diff --git a/docs/security-log-and-emails.md b/docs/security-log-and-emails.md index 278c9910..1b423bb4 100644 --- a/docs/security-log-and-emails.md +++ b/docs/security-log-and-emails.md @@ -79,6 +79,7 @@ How long those lines are kept, and who can read them, is then up to that channel | `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, 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` | +| `session_resumed` | info | ["Remember me"](devices-and-sessions.md#remember-me) signed a browser back in after its session had gone unused. Nothing was proved, which is why it isn't a `signed_in`. | | | `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 | | | | `email_changed` | notice | | | @@ -261,7 +262,7 @@ Types you leave out keep Keyring's own. Every security notice is on from the sta 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. Keyring's own emails 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. +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. Keyring's own emails cover both as far as your features go. A sign in after a long quiet period, or after several failures, is announced by [Keyring's own risk response](risk.md#telling-the-user): a responder of yours has to do the same. [OWASP ASVS](owasp-asvs.md) has the whole list for each level. Calling `Keyring::notifications()` again adds to what you gave it before, and an unknown type throws an `InvalidArgumentException`, so a typo doesn't quietly leave an email as it was. diff --git a/docs/security.md b/docs/security.md index 1468a36d..e66d7808 100644 --- a/docs/security.md +++ b/docs/security.md @@ -120,7 +120,7 @@ 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. 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. +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, and the buttons on the pages emailed links open (confirming or undoing an email change, "this wasn't me", verifying an address) share 6 requests a minute per user, or per IP address for guests. Opening one of those pages is held to 60 a minute per IP address by its own limiter, `keyring-pages`, so a mail scanner that follows the link doesn't use up the six. Usernameless passkey options have a third, `keyring-login-options`, at 60 requests a minute per IP address, because the login page fetches them on every load for autofill. A request any of them refuses is logged as `rate_limited`, once for each wait. Apps can redefine each 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. The notice of a finished password reset is the exception, since the reset link went to that address. @@ -152,7 +152,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. 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()`. +- 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 built-in authenticator's user verification is never counted beside it. A factor of your own that reports only inherence does count beside an attested key, as NIST's "or a biometric comparison" allows (Sec. 2.3.1). 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::asExtraStep()`), 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. - A passkey or security key only counts as inherence when it actually verified the user that time. @@ -169,7 +169,7 @@ The failures in a row and the locks held until a reset are in your database eith - Every signed-in Keyring route checks Keyring's guard (`auth:{guard}`), and the step-up middleware reads the user from it, so another guard's user can't stand in. - Every signed-in session is in Keyring's registry and is checked on every `web` request (and any other group you add `keyring.session` to), so revoking one takes effect on its next request with any session driver. Timeouts and revocations only reach routes that run that middleware, and the [conformance suite](testing.md#the-conformance-suite) fails for a signed-in route that doesn't. - An account can have 100 sessions at once (`sessions.max`). A sign in beyond that ends the session unused longest and is never refused, so holding an account's sessions can't keep its owner out. See [How Many Sessions](devices-and-sessions.md#how-many-sessions). -- A session ends after two hours unused (`sessions.idle`) and 30 days after sign in (`sessions.absolute`), counted on its registry record, so neither depends on your session driver or `session.lifetime`. Each assurance level lapses on NIST SP 800-63B-4's clock (AAL2: 1 hour idle or 24 hours; AAL3: 15 minutes or 12 hours) until the user verifies again. A session past its level's limits is treated as the lower level, which NIST allows (Sec. 5.1), and stays signed in. With `sessions.end_on_lapse` it ends instead when the level it signed in at runs out, as Sec. 5.2 words it, and "remember me" brings nothing back. +- A session ends after two hours unused (`sessions.idle`) and 30 days after sign in (`sessions.absolute`), counted on its registry record, so neither depends on your session driver or `session.lifetime`. Each assurance level lapses on NIST SP 800-63B-4's clock (AAL2: 1 hour idle or 24 hours; AAL3: 15 minutes or 12 hours) until the user verifies again. A session past its level's limits is treated as the lower level and stays signed in, which is Keyring's reading of Sec. 5.1 and departs from Sec. 5.2. With `sessions.end_on_lapse` it ends instead when the level it signed in at runs out, as Sec. 5.2 words it, and "remember me" brings nothing back. - A browser that ticked "remember me" is the one exception to the two hours, on purpose: it may stay away for 14 days (`sessions.remember_idle`) and be signed back in, inside the same 30 days. After two hours unused it holds no level, so anything behind `keyring:aal2` or `keyring.fresh` asks it to verify again. See [Inactivity and "Remember Me"](devices-and-sessions.md#inactivity-and-remember-me). - "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. @@ -215,6 +215,7 @@ The failures in a row and the locks held until a reset are in your database eith - 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. - Every other Keyring response sends `Referrer-Policy: same-origin`, so other sites never see its URL and your own app still does. +- A site that opens one of Keyring's pages in a new window keeps no handle on it: each response is sent with `Cross-Origin-Opener-Policy: same-origin-allow-popups`, unless it already has that header. A window the page opens itself, for a social login say, still answers to it. - No Keyring response may be shown in a frame: each is sent with `X-Frame-Options: DENY`. That covers the pages that act on one press of a button (confirming an email change, undoing one, reporting a device, verifying an address) and the sign-in, challenge and confirm pages, which are what a page on another site would load invisibly and line its own button up over. A response that already says who may frame it is left as it is: one with an `X-Frame-Options` of its own, or a `Content-Security-Policy` with a `frame-ancestors` directive. See [A Content Security Policy](#a-content-security-policy). - An Inertia app keeps the policy of the page it first loaded. So when the form on an emailed link's page succeeds, Keyring answers Inertia with a full page visit (`409` with `X-Inertia-Location`), and the next page comes with its own policy. Otherwise every page after it would send no `Referer` either, signed in or not. @@ -266,7 +267,7 @@ A URL ends up in places a request's body doesn't: access logs, proxies, the brow ### 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. +- Sign ins, failed factors, lockouts, session starts and ends, sessions "remember me" carried on, and every change to how an account signs in are recorded as shipped. A session your own code starts with `Auth::login()` isn't. They go 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, 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, 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). @@ -289,7 +290,7 @@ Everything Keyring stores about a person, how it's protected, how long it stays | `keyring_password_holds` | That the user has to choose a new password, and the reason your app or a risk response gave: write nothing personal there. | Plain. | Until the password changes or the hold is called off. Deleted with a force deleted user. | | Your app's log (without `Features::securityLog()`) | The same as `keyring_events`, one line per event. | Whatever protects that log channel. | Whatever that channel keeps (`days` on a `daily` channel). | | The session | A sign in waiting for its second factor, an enrollment in progress (including the secret being set up), and what the session has verified. | Encrypted with `APP_KEY` inside the session, whichever session driver holds it. | 10 minutes for a pending login (`pending_logins.keep_for`), 15 for an enrollment (`enrollments.keep_for`), otherwise the session's life. | -| The rate limiter's cache store | Counts of attempts, keyed by a SHA-1 of the factor with the account, the typed username or the IP address. | Hashed keys, so the store holds no names or addresses to read back. | A minute for counts, up to 24 hours for locks, 30 days for the failures in a row counted under a typed username (`limits.remember_names_for`). | +| The rate limiter's cache store | Counts of attempts, keyed by a SHA-1 of the factor with the account, the typed username or the IP address. Also hashes of sent codes, marks for answered WebAuthn challenges and enrollments under way, and risk locks (in `risk.store`), which are kept under the user's ID. | Hashed keys, so the store holds no names or addresses to read back. A risk lock's key holds the user's ID as it is. | A minute for counts, up to 24 hours for locks, 30 days for the failures in a row counted under a typed username (`limits.remember_names_for`). | | Laravel's own tables | The reset token and address in `password_reset_tokens`, and `remember_token` on your users table. | Laravel hashes the reset token. | Laravel's `auth.passwords.*.expire`. Keyring deletes a user's reset tokens when they're deleted or their address changes. | To store less of an address, or none, see [What's Stored](security-log-and-emails.md#whats-stored): `Keyring::recordIpsUsing()` applies to devices, sessions and the log alike. Security emails pass the IP address and a description of the browser to the user they're about. @@ -308,7 +309,7 @@ Keyring sets the headers and cookies of its own responses. The rest of what a br | Trusted proxies, behind a load balancer | Reads the client's address and scheme from the request Laravel gives it | Work out which proxies to trust | | `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 | +| `X-Content-Type-Options: nosniff` on your own responses | Sends it, with `Cache-Control: no-store`, `X-Frame-Options: DENY`, a `Referrer-Policy` and a `Cross-Origin-Opener-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 @@ -371,7 +372,7 @@ 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`. +If you take Keyring's middleware out of `keyring.middleware`, its responses lose `no-store`, `nosniff`, `X-Frame-Options`, their opener policy 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 @@ -566,12 +567,12 @@ Keyring's code and config say what each thing does. This is where the choices co | 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 deleted user's sessions end with them, and an account the app keeps out loses all of its sessions the first time one of them makes a request | 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) | +| A "remember me" cookie that works once, with a used one ending the session | Refresh token rotation with reuse detection (RFC 9700, Section 4.14.2), applied to a cookie, and OWASP's Session Management Cheat Sheet for revoking every rotated ID of a session together | | **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 | @@ -602,10 +603,10 @@ Keyring's code and config say what each thing does. This is where the choices co | 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 | +| The emails Keyring sends about changes: password changed, sign-in method added or removed, recovery code used, new recovery codes, and with `Features::emailChanges()`, 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 sends about suspicious attempts: a failed second factor, a sign in after several failures or a long quiet period, an account locked, what the risk signals add up to, and with `Features::devices()`, a new device | OWASP ASVS 5.0.0, 6.3.5, and OWASP's Multifactor Authentication and Credential Stuffing Prevention Cheat Sheets | +| A line saying who to contact in every security notice, the emailed code and the email change notice, 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: failure history and a session changing browser as installed, and the device signals with `Features::devices()` | 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 | @@ -621,9 +622,10 @@ Keyring's code and config say what each thing does. This is where the choices co | 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 | +| Keyring's own breached-password lookup following no redirect (the default lookup is Laravel's, which follows them) | OWASP ASVS 5.0.0, 15.3.2 | +| A `Cross-Origin-Opener-Policy` on every Keyring response | OWASP ASVS 5.0.0, 3.4.8 | | **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 | +| Logging sign ins, failures, lockouts, sessions "remember me" carried on 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 5.0.0, 14.1 and 14.2.7 | @@ -633,7 +635,7 @@ Keyring's code and config say what each thing does. This is where the choices co 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. +- **Not every suspicious sign in is announced as installed.** OWASP ASVS 5.0.0's requirement 6.3.5 lists a sign in from an unusual client or place among them. A new device and a long quiet period are only known with `Features::devices()`, and a place only with a locator you supply, so a default install announces neither. A failed second factor and a sign in after several failures are announced from the start. - **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. @@ -646,7 +648,7 @@ Each of these is a choice. The reason is given once, here, and the [requirement- - **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. Keyring's 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 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.3 counts a check that passes on an error as failing open, and 16.5.2 asks that an outside service failing leaves the app secure. 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). diff --git a/src/Activity/RecordSecurityEvents.php b/src/Activity/RecordSecurityEvents.php index 70aec3bb..463bbc93 100644 --- a/src/Activity/RecordSecurityEvents.php +++ b/src/Activity/RecordSecurityEvents.php @@ -44,6 +44,7 @@ public function subscribe(Dispatcher $events): array Events\SessionsRevoked::class => 'sessionsRevoked', Events\SessionEnded::class => 'sessionEnded', Events\RememberMeReused::class => 'rememberMeReused', + Events\SessionResumed::class => 'sessionResumed', Events\EmailChangeRequested::class => 'emailChangeRequested', Events\EmailChanged::class => 'emailChanged', Events\EmailChangeReverted::class => 'emailChangeReverted', @@ -186,6 +187,15 @@ public function rememberMeReused(Events\RememberMeReused $event): void ]); } + /** + * "Remember me" signed a browser in again. It proved nothing, so the + * entry says so by being its own type and not a sign in. + */ + public function sessionResumed(Events\SessionResumed $event): void + { + $this->log->record('session_resumed', $event->user, device: $event->session->deviceId); + } + public function emailChangeRequested(Events\EmailChangeRequested $event): void { $this->log->record('email_change_requested', $event->user); diff --git a/src/Console/InstallCommand.php b/src/Console/InstallCommand.php index 02a09d32..4da4e791 100644 --- a/src/Console/InstallCommand.php +++ b/src/Console/InstallCommand.php @@ -9,6 +9,7 @@ use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; +use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Schema; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Str; @@ -23,7 +24,7 @@ #[AsCommand(name: 'keyring:install')] #[Description('Install Keyring: pick sign-in methods and features, then publish the config, migrations, a provider and your actions')] #[Signature('keyring:install - {--factor=* : A sign-in method to add besides the password: totp, passkeys, security-keys or email-codes} + {--factor=* : A sign-in method to add besides the password: totp (the default), passkeys, security-keys or email-codes, or none for the password alone} {--feature=* : A feature to turn on, replacing the defaults (registration, reset-passwords, email-verification, update-passwords and security-log): registration, reset-passwords, email-verification, update-passwords, manage-authenticators, devices, email-changes or security-log} {--require-second-factor : Make every user set up a second factor (the default with an authenticator app, passkeys or security keys)} {--optional-second-factor : Leave setting up a second factor to each user} @@ -52,6 +53,16 @@ class InstallCommand extends Command 'email-codes' => ['Email codes, as an extra step at sign in (not a second factor)', 'EmailCode::asExtraStep(),', 'a password and an emailed code is AAL1.'], ]; + /** + * The sign-in method picked unless another is: a second factor anyone + * can set up, with an app they may already have. OWASP ASVS 5.0.0 + * (6.3.3) has every user sign in with more than a password from Level 2. + */ + protected const array DEFAULT_FACTORS = ['totp']; + + /** What --factor takes to mean the password alone. */ + protected const string NO_FACTORS = 'none'; + /** * The sign-in methods that count as a second factor everyone can be made * to set up. An emailed code doesn't: the inbox also resets the password. @@ -87,7 +98,7 @@ class InstallCommand extends Command public function handle(Filesystem $files): int { $unknown = array_filter([ - '--factor' => [array_diff((array) $this->option('factor'), array_keys(self::FACTORS)), array_keys(self::FACTORS)], + '--factor' => [array_diff((array) $this->option('factor'), array_keys(self::FACTORS), [self::NO_FACTORS]), [...array_keys(self::FACTORS), self::NO_FACTORS]], '--feature' => [array_diff((array) $this->option('feature'), Features::all()), Features::all()], ], fn (array $option) => $option[0] !== []); @@ -162,6 +173,7 @@ public function handle(Filesystem $files): int $this->components->info('Once it\'s running, see "After Installing" in the "Installation" docs.'); $this->components->bulletList([ 'Sessions end after two hours unused. Set sessions.idle in config/keyring.php to change that', + ...Hash::getDefaultDriver() === 'bcrypt' ? ['Passwords are hashed with bcrypt, which reads 72 bytes: longer ones are refused, and that can be under 64 characters of non-Latin text. Set HASH_DRIVER=argon2id to take any up to passwords.max'] : [], 'Run the Laravel scheduler (schedule:run): it prunes the security log and other old records every day', 'Signed-in routes outside the web group need the keyring.session middleware', 'php artisan keyring:sign-out signs one user out everywhere, or everyone with --all', @@ -210,14 +222,16 @@ protected function factors(): array { $chosen = (array) $this->option('factor'); - if ($chosen === [] && $this->input->isInteractive()) { - $chosen = multiselect( + if ($chosen === []) { + $chosen = $this->input->isInteractive() ? multiselect( label: 'Which sign-in methods besides the password?', options: array_map(fn (array $factor) => $factor[0], self::FACTORS), + default: self::DEFAULT_FACTORS, hint: 'You can add more later in app/Providers/KeyringServiceProvider.php.', - ); + ) : self::DEFAULT_FACTORS; } + // "none" is in no list, so it leaves the password alone. return array_values(array_intersect(array_keys(self::FACTORS), $chosen)); } diff --git a/src/Events/SessionResumed.php b/src/Events/SessionResumed.php new file mode 100644 index 00000000..8a840d0b --- /dev/null +++ b/src/Events/SessionResumed.php @@ -0,0 +1,25 @@ + implode('-', str_split(Str::lower(Base32::encodeUnpadded(random_bytes(16))), 4)), diff --git a/src/Http/Middleware/AddSecurityHeaders.php b/src/Http/Middleware/AddSecurityHeaders.php index ea72da96..df7d8535 100644 --- a/src/Http/Middleware/AddSecurityHeaders.php +++ b/src/Http/Middleware/AddSecurityHeaders.php @@ -28,6 +28,10 @@ * reporting a device, verifying an address), which is what a page on * another site lines its own button up over. An app that has said how its * pages may be framed keeps its say. + * + * A page on another site that opens one of them in a new window keeps no + * handle on it. A window the page opens itself, for a social login say, + * still talks back to it. An app with an opener policy of its own keeps it. */ class AddSecurityHeaders { @@ -58,6 +62,10 @@ public function handle(Request $request, Closure $next): Response $response->headers->set('X-Frame-Options', 'DENY'); } + if (! $response->headers->has('Cross-Origin-Opener-Policy')) { + $response->headers->set('Cross-Origin-Opener-Policy', 'same-origin-allow-popups'); + } + return $response; } diff --git a/src/Http/Middleware/AuthenticateSession.php b/src/Http/Middleware/AuthenticateSession.php index 335e93a7..9c28dc9a 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\SessionResumed; use Keyring\Events\SessionsRevoked; use Keyring\KeyringManager; use Keyring\Login\SignIn; @@ -261,6 +262,8 @@ protected function resume(Request $request, Authenticatable&Model $user, bool $r $this->assurance->touch(); + SessionResumed::dispatch($user, $current->with(['deviceId' => $device->id ?? $current->deviceId])); + if ($device?->wasRecentlyCreated) { NewDeviceSignedIn::dispatch($user, $device); } diff --git a/src/Risk/RiskEngine.php b/src/Risk/RiskEngine.php index 24991094..99f9ff64 100644 --- a/src/Risk/RiskEngine.php +++ b/src/Risk/RiskEngine.php @@ -13,7 +13,9 @@ use Keyring\Events\RiskAssessed; use Keyring\Risk\Signals\BreachedPassword; use Keyring\Risk\Signals\ImpossibleTravel; +use Keyring\Risk\Signals\InactiveAccount; use Keyring\Risk\Signals\NewDevice; +use Keyring\Risk\Signals\SuccessAfterFailures; use Keyring\Sessions\Sessions; /** @@ -95,10 +97,16 @@ public function decide(Risk $risk, Checkpoint $checkpoint): 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. + * level, with two findings answered whatever they scored. + * + * A sign in that follows several failures, or a long quiet period, is + * told to the owner: OWASP ASVS 5.0.0 (6.3.5) names both, and on its own + * each only reaches the level that asks for a second factor. + * + * A password found in a breach is held for a new one. 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 { @@ -109,6 +117,10 @@ protected function defaultResponse(Risk $risk): Action Level::Critical => Action::deny()->revokeAllSessions()->notify(), }; + if ($risk->has(SuccessAfterFailures::FINDING) || $risk->has(InactiveAccount::FINDING)) { + $action = $action->notify(); + } + return $risk->has(BreachedPassword::FINDING) ? $action->requirePasswordChange() : $action; } diff --git a/src/Risk/Signals/InactiveAccount.php b/src/Risk/Signals/InactiveAccount.php index 634f9da8..1269c4ec 100644 --- a/src/Risk/Signals/InactiveAccount.php +++ b/src/Risk/Signals/InactiveAccount.php @@ -24,6 +24,9 @@ */ class InactiveAccount extends Signal { + /** What its finding is called, in Risk::has(). */ + public const string FINDING = 'inactive_account'; + public function __construct( protected SessionRegistry $sessions, protected int $score = 30, @@ -49,7 +52,7 @@ public function assess(Assessment $assessment): ?Finding return null; } - return new Finding('inactive_account', $this->score, sprintf('The first sign in for %d days.', $last->diffInDays(now()))); + return new Finding(self::FINDING, $this->score, sprintf('The first sign in for %d days.', $last->diffInDays(now()))); } /** diff --git a/src/Risk/Signals/SuccessAfterFailures.php b/src/Risk/Signals/SuccessAfterFailures.php index 7e8ab570..6dffa212 100644 --- a/src/Risk/Signals/SuccessAfterFailures.php +++ b/src/Risk/Signals/SuccessAfterFailures.php @@ -21,6 +21,9 @@ */ class SuccessAfterFailures extends Signal { + /** What its finding is called, in Risk::has(). */ + public const string FINDING = 'success_after_failures'; + public function __construct( protected SecurityLog $log, protected int $threshold = 5, @@ -33,7 +36,7 @@ public function assess(Assessment $assessment): ?Finding $failures = $this->log->count($assessment->user, 'factor_failed', Duration::seconds($this->within), since: 'signed_in'); return $failures >= $this->threshold - ? new Finding('success_after_failures', $this->score, "Signed in after {$failures} failed attempts in the last {$this->within}.") + ? new Finding(self::FINDING, $this->score, "Signed in after {$failures} failed attempts in the last {$this->within}.") : null; } } diff --git a/stubs/config/keyring.php b/stubs/config/keyring.php index fb6037d2..8a77db91 100644 --- a/stubs/config/keyring.php +++ b/stubs/config/keyring.php @@ -80,8 +80,8 @@ |-------------------------------------------------------------------------- | | Where users can reach you about their account: a page's URL or an email - | address. Keyring's emails then end by saying who to contact if - | something wasn't them. Null leaves that line out. + | address. Keyring's security emails then end by saying who to contact + | if something wasn't them. Null leaves that line out. | */ diff --git a/tests/Feature/CommandsTest.php b/tests/Feature/CommandsTest.php index 959597ad..aea4d0b6 100644 --- a/tests/Feature/CommandsTest.php +++ b/tests/Feature/CommandsTest.php @@ -71,8 +71,29 @@ $files->delete($files->glob(database_path('migrations/*_create_keyring_*'))); }); - it('installs the password, registration, resets, verification, password changes and the security log without asking', function () { + // OWASP ASVS 5.0.0, 6.3.3: with nothing asked, everyone signs in with + // more than a password. + it('installs an authenticator app everyone must set up, with recovery codes, without asking', function () { $this->artisan('keyring:install', ['--no-interaction' => true]) + ->expectsOutputToContain('Turned on managing sign-in methods') + ->expectsOutputToContain('Build your page for adding a sign-in method at /settings/security') + ->assertSuccessful(); + + $config = require config_path('keyring.php'); + $provider = file_get_contents($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); + + expect($config['features'])->toBe([Features::registration(), Features::resetPasswords(), Features::emailVerification(), Features::updatePasswords(), Features::manageAuthenticators(), Features::securityLog()]) + ->and($config['enrollment_url'])->toBe('/settings/security') + ->and($provider)->toContain('Password::class,')->toContain('Totp::class,')->toContain('RecoveryCodes::class,') + ->toContain('Keyring::require(Requirement::aal2()->ifEnrolled()->noDowngrade());') + ->toContain("appendMiddlewareToGroup('web', 'keyring.enrolled');") + ->not->toContain('WebAuthn')->not->toContain('EmailCode'); + + expectValidPhp($this->sandbox.'/app/Providers/KeyringServiceProvider.php'); + }); + + it('installs the password alone when asked to, with registration, resets, verification, password changes and the security log', function () { + $this->artisan('keyring:install', ['--factor' => ['none'], '--no-interaction' => true]) ->expectsOutputToContain('Nothing makes users set up a second factor') ->assertSuccessful(); @@ -176,7 +197,7 @@ expect(file_exists(config_path('keyring.php')))->toBeFalse(); })->with([ - 'the password alone' => [[], 'Requiring a second factor needs one users can set up. Add --factor=totp, --factor=passkeys, --factor=security-keys.'], + 'the password alone' => [['none'], 'Requiring a second factor needs one users can set up. Add --factor=totp, --factor=passkeys, --factor=security-keys.'], 'email codes' => [['email-codes'], 'Requiring a second factor needs one users can set up, and an emailed code isn\'t one. Add --factor=totp'], ]); @@ -213,7 +234,16 @@ ->toContain('Sessions end after two hours unused. Set sessions.idle in config/keyring.php to change that') ->toContain('Run the Laravel scheduler (schedule:run): it prunes the security log and other old records every day') ->toContain('Signed-in routes outside the web group need the keyring.session middleware') - ->toContain('php artisan keyring:sign-out signs one user out everywhere, or everyone with --all'); + ->toContain('php artisan keyring:sign-out signs one user out everywhere, or everyone with --all') + // The suite hashes with bcrypt, as a new Laravel app does. + ->toContain('Passwords are hashed with bcrypt, which reads 72 bytes') + ->toContain('Set HASH_DRIVER=argon2id to take any up to passwords.max'); + + config(['hashing.driver' => 'argon2id']); + (new Filesystem)->delete(config_path('keyring.php')); + + expect(Artisan::call('keyring:install', ['--no-interaction' => true, '--force' => true], $output))->toBe(0) + ->and($output->fetch())->not->toContain('bcrypt'); // What it says is so. expect((require __DIR__.'/../../config/keyring.php')['sessions']['idle'])->toBe('2h') diff --git a/tests/Feature/DevicesAndSessionsTest.php b/tests/Feature/DevicesAndSessionsTest.php index dad1fbab..41f8cca0 100644 --- a/tests/Feature/DevicesAndSessionsTest.php +++ b/tests/Feature/DevicesAndSessionsTest.php @@ -672,11 +672,24 @@ function withAppHeaders(array $headers): void 'a policy that only reports' => [['Content-Security-Policy-Report-Only' => "frame-ancestors 'self'"]], ]); +// OWASP ASVS 5.0.0, 3.4.8: a page another site opened keeps no window in +// common with it. A popup the page opens itself still answers to it. +it('keeps its windows apart from the site that opened them, and keeps the popups it opens', function () { + $this->inertia()->get('/login')->assertOk()->assertHeader('Cross-Origin-Opener-Policy', 'same-origin-allow-popups'); + $this->flushHeaders()->post('/login', ['email' => 'taylor@example.com', 'password' => 'password'])->assertRedirect()->assertHeader('Cross-Origin-Opener-Policy', 'same-origin-allow-popups'); +}); + +it('leaves the opener policy to an app that sends its own', function () { + withAppHeaders(['Cross-Origin-Opener-Policy' => 'same-origin']); + + $this->inertia()->get('/login')->assertOk()->assertHeader('Cross-Origin-Opener-Policy', 'same-origin'); +}); + it('leaves caching to an app that takes the middleware out of the config', function () { config(['keyring.middleware' => ['web']]); withFeatures(Features::all()); - $this->get('/login')->assertHeaderMissing('Referrer-Policy')->assertHeaderMissing('X-Content-Type-Options')->assertHeaderMissing('X-Frame-Options'); + $this->get('/login')->assertHeaderMissing('Referrer-Policy')->assertHeaderMissing('X-Content-Type-Options')->assertHeaderMissing('X-Frame-Options')->assertHeaderMissing('Cross-Origin-Opener-Policy'); }); it('cycles the remember token when a device is revoked', function () { diff --git a/tests/Feature/PasswordResetTest.php b/tests/Feature/PasswordResetTest.php index fd26019a..722d717b 100644 --- a/tests/Feature/PasswordResetTest.php +++ b/tests/Feature/PasswordResetTest.php @@ -5,13 +5,16 @@ use Illuminate\Hashing\BcryptHasher; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Hash; +use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Password; use Keyring\Changes\PasswordChanges; use Keyring\Contracts\SessionRegistry; use Keyring\Events\FactorVerified; +use Keyring\Events\PasswordChanged as PasswordChangedEvent; use Keyring\Facades\Keyring; use Keyring\Features; use Keyring\Models\Authenticator; +use Keyring\Notifications\PasswordChanged; use Keyring\Tests\Fixtures\User; beforeEach(function () { @@ -81,6 +84,23 @@ expect(Hash::check('another brand new passphrase', $this->plain->fresh()->password))->toBeTrue(); })->with(['signing others out' => true, 'staying signed in elsewhere' => false]); +// OWASP ASVS 5.0.0, 6.3.7. Other notices wait for a verified address: this +// one doesn't, because the reset link went to it. +it('tells an account whose address was never verified that its password was reset', function () { + Notification::fake(); + $this->plain->forceFill(['email_verified_at' => null])->save(); + + // Any other change says nothing to an address nobody has proved. + PasswordChangedEvent::dispatch($this->plain); + Notification::assertNothingSent(); + + $token = Password::broker()->createToken($this->plain); + $this->post(route('password.update'), ['token' => $token, 'email' => 'plain@example.com', 'password' => 'a brand new passphrase', 'password_confirmation' => 'a brand new passphrase']) + ->assertRedirect(route('login')); + + Notification::assertSentToTimes($this->plain, PasswordChanged::class, 1); +}); + it('keeps a reset link working after a refused new password', function () { $token = Password::broker()->createToken($this->plain); diff --git a/tests/Feature/RememberMeTest.php b/tests/Feature/RememberMeTest.php index 054123f7..5a64f5c1 100644 --- a/tests/Feature/RememberMeTest.php +++ b/tests/Feature/RememberMeTest.php @@ -200,6 +200,13 @@ function sessionEndedReasons(): array ->and($replaced->isActive(now()->getTimestamp()))->toBeFalse() ->and(app(SessionRegistry::class)->forUser($this->user))->toHaveCount(1); + // Logged as what it is: a browser signed in again, with nothing proved. + $entry = SecurityEvent::query()->where('type', 'session_resumed')->sole(); + + expect($entry->ip)->toBe('203.0.113.9') + ->and($entry->device_id)->toBe($record->deviceId) + ->and(SecurityEvent::query()->where('type', 'signed_in')->count())->toBe(1); + // It's the same session: when it started and when it ends haven't moved. expect($record->authenticatedAt)->toBe($old->authenticatedAt) ->and($record->expiresAt)->toBe($old->expiresAt) diff --git a/tests/Feature/RiskTest.php b/tests/Feature/RiskTest.php index 95c3bca9..9576d4c6 100644 --- a/tests/Feature/RiskTest.php +++ b/tests/Feature/RiskTest.php @@ -634,6 +634,19 @@ function lastSignedIn(int $daysAgo): string ->and($assessed->risk->reasons())->toBe(['The first sign in for 91 days.']); }); + // OWASP ASVS 5.0.0, 6.3.5: the owner hears of it without the app + // writing a response of its own. + it('is told to the owner, who may have nothing more to prove', function () { + Keyring::risk()->signals([InactiveAccount::class]); + $cookie = lastSignedIn(daysAgo: 91); + + signInAs(cookies: ['known_device' => $cookie])->assertRedirect('/dashboard'); + + $notice = Notification::sent($this->user, SuspiciousActivity::class)->sole(); + + expect($notice->reasons)->toBe('The first sign in for 91 days.'); + }); + it('is not found before then', function () { Keyring::risk()->signals([InactiveAccount::class])->respond(fn (Risk $risk) => $risk->has('inactive_account') ? Action::deny() : Action::allow()); $cookie = lastSignedIn(daysAgo: 89); @@ -721,6 +734,38 @@ function lastSignedIn(int $daysAgo): string ->and($assessed->risk->reasons())->toBe(['Signed in after 5 failed attempts in the last 1h.']); }); + // OWASP ASVS 5.0.0, 6.3.5: the owner hears of it without the app + // writing a response of its own. + it('is told to the owner, who may have nothing more to prove', function () { + config(['keyring.limits.per_account' => 100]); + Keyring::risk()->signals([SuccessAfterFailures::class]); + + foreach (range(1, 5) as $guess) { + signInAs(password: 'nope'); + } + + Notification::assertNothingSent(); + + signInAs()->assertRedirect('/dashboard'); + + $notice = Notification::sent($this->user, SuspiciousActivity::class)->sole(); + + expect($notice->reasons)->toBe('Signed in after 5 failed attempts in the last 1h.'); + }); + + it('is not told when the app answers for itself and says nothing', function () { + config(['keyring.limits.per_account' => 100]); + Keyring::risk()->signals([SuccessAfterFailures::class])->respond(fn (Risk $risk) => Action::allow()); + + foreach (range(1, 5) as $guess) { + signInAs(password: 'nope'); + } + + signInAs()->assertRedirect('/dashboard'); + + Notification::assertNotSentTo($this->user, SuspiciousActivity::class); + }); + it('is not found after fewer', function () { config(['keyring.limits.per_account' => 100]); Keyring::risk()->signals([app()->make(SuccessAfterFailures::class, ['score' => 95])]); diff --git a/tests/Feature/StandardsDocsTest.php b/tests/Feature/StandardsDocsTest.php index 7c340438..71ddcbea 100644 --- a/tests/Feature/StandardsDocsTest.php +++ b/tests/Feature/StandardsDocsTest.php @@ -7,6 +7,7 @@ use Keyring\Changes\ProtectedAttributes; use Keyring\Console\InstallCommand; use Keyring\Factors\FactorRegistry; +use Keyring\Features; use Keyring\KeyringManager; use Keyring\Support\Duration; @@ -17,8 +18,10 @@ $this->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, [], false))->call(new InstallCommand); + // What keyring:install sets up with its default answers: an authenticator + // app everyone must set up, which brings managing sign-in methods. + $this->features = array_values(array_intersect(Features::all(), [...$this->defaults['features'], Features::manageAuthenticators()])); + $this->provider = (fn () => $this->provider(new Filesystem, self::DEFAULT_FACTORS, true, test()->features))->call(new InstallCommand); }); it('lists the features a default install turns on', function () { @@ -26,8 +29,15 @@ $listed = Str::matchAll('/`([a-z-]+)`/', $line[2])->all(); - expect($listed)->toBe($this->defaults['features'])->toHaveCount(5) - ->and($line[1])->toBe('five'); + expect($listed)->toBe($this->features)->toHaveCount(6) + ->and($line[1])->toBe('six'); +}); + +it('says a default install has an authenticator app everyone must set up, which is what the installer writes', function () { + expect($this->page)->toContain('an authenticator app as a second factor that every user must set up before going further, with recovery codes') + ->and($this->provider)->toContain('Totp::class,')->toContain('RecoveryCodes::class,') + ->toContain("appendMiddlewareToGroup('web', 'keyring.enrolled');") + ->not->toContain('WebAuthn'); }); it('counts the security emails Keyring sends and the risk signals a default install registers', function () {