Experiment - Support for DBSC v2
Categories
(Enterprise Products :: Firefox, task, P5)
Tracking
(Not tracked)
People
(Reporter: beurdouche, Assigned: beurdouche)
Details
(Whiteboard: beurdouche-monitor)
Attachments
(10 external files)
| Assignee | ||
Updated•3 months ago
|
| Assignee | ||
Comment 1•3 months ago
|
||
DBSC needs to mint an asymmetric signing key and prove possession of it.
The servers in the checked-in WPT suite offer only RS256, and nss-rs has
no RSA support at all, so add it:
- rsa.rs: RSA keygen via PK11_GenerateKeyPairWithOpFlags with
PK11RSAGenParams, RSASSA-PKCS1-v1_5 over SHA-256 signing and
verification, and modulus/exponent export for building a JWK. - ec.rs: ec_keygen_with_flags, so callers can ask for a persistent
non-extractable signing key instead of the ephemeral extractable
session key ecdh_keygen always produces. sign_ecdsa_sha256 hashes
the message inside the token, unlike sign_ecdsa which expects a
digest. - p11.rs: PrivateKey::signature_len and PrivateKey::sign, which sizes
the output buffer from the key. ec::sign hardcodes 0x40 bytes, which
happens to be right for P-256 and is wrong for RSA and P-384.
PublicKey::read_raw_attribute, needed because SECKEYPublicKey is
opaque in these bindings so its u.rsa fields are unreachable.
The mechanism constants come from pkcs11-bindings, which allowlists
CKM_.* wholesale, so bindings.toml only gains PK11_SignatureLen and
PK11RSAGenParams.
Patched in-tree rather than upstream; .cargo-checksum.json updated to
match.
| Assignee | ||
Comment 2•3 months ago
|
||
Firefox has no way to create an asymmetric key that lives in a TPM or
Secure Enclave. nsIOSKeyStore is symmetric-only, nsIWebAuthnService is
bound to WebAuthn's RP-ID and attestation semantics with system UI that
cannot be suppressed, and osclientcerts signs with platform keys but
never creates them. DBSC needs such a key, and so does Lockstore, so
this lands as a standalone crate rather than inside either consumer.
The trait is modelled on Chromium's crypto::UnexportableKeyProvider for
the generate/open/wrapped-handle shape, with two departures:
- Mechanism and user-verification are orthogonal axes (ProviderKind
and AccessControl) rather than a flattened list, because a
(mechanism, verification) pair is a distinct security claim.
Lockstore mints one KEK type per pair, so it has to name them
separately. - PlatformKey can wrap/unwrap as well as sign. Chromium's key signs
only, which does not serve a KEK that must be unwrappable on just
this device. wrap takes the public half, so a KEK can be created
with no prompt and only cost a biometric check when used.
Public key material comes out as JWK components rather than SPKI: every
backend can produce those directly, whereas SPKI would mean a DER
encoder per backend.
Only the NSS softoken backend here, which is explicitly not
hardware-backed -- the handle blob is the PKCS#8 key -- and says so via
is_hardware_backed. It exists because tests need machine-independent
results, Linux has no platform TPM path, and it is the only way to serve
an RS256-only server on macOS given the Secure Enclave is P-256 only.
Secure Enclave and CNG/TPM backends follow, each behind
hardware_provider().
Keys are held as bytes and reopened per operation rather than kept as
live NSS objects: PlatformKey must be Send + Sync because DBSC signs off
the main thread, and NSS key handles are raw pointers that are not Sync.
Coverage is a C++ gtest over a cbindgen FFI, not RUST_TESTS: the
tools/rusttests build links no shared NSS, which is why nothing in
RUST_TESTS depends on nss-rs and why lockstore_rs's cargo tests are
excluded too.
| Assignee | ||
Comment 3•3 months ago
|
||
Keys are created with kSecAttrTokenIDSecureEnclave, so the private half
is generated inside the Enclave and never exists outside it. The handle
blob is a random application tag naming a keychain reference, not key
material, which is what makes this backend meaningfully different from
the software one.
This is also where wrap/unwrap becomes real. Encryption uses only the
public half, so wrapping never prompts, while unwrapping goes through the
Enclave and prompts if the key was created requiring user presence. That
asymmetry is the property a Lockstore KEK wants: created silently, and
only costing a Touch ID check when it is actually used.
Two API changes fall out of writing a second backend:
- KeyHandle records the usage, so a reopened key enforces what it was
generated with. Enclave keys can sign and agree, CNG keys cannot, and
without this a caller could work on macOS and fail on Windows. - select_algorithm takes the usage, because the answer depends on it.
The Enclave is P-256 only, so an RS256-only server -- which is what
the checked-in web-platform tests are -- cannot be served here at all
and must fall back to software.
Security.framework returns X9.62 DER signatures whereas JOSE wants raw
r || s, so the backend converts, with unit tests for the padding and
rejection cases.
Two things worth knowing about validation. The Enclave accepts these key
parameters -- SecKeyCreateRandomKey mints a key in com.apple.setoken --
but persisting it needs com.apple.application-identifier, which only
production and Nightly builds carry (added for platform passkeys);
developer builds do not, and the entitlement is restricted, so an ad-hoc
signature carrying it gets the process SIGKILLed. The gtests therefore
skip in a local build and the provider degrades to software rather than
failing at the point of use. Signing, key lookup and the ECIES round trip
consequently have not run yet; the DER conversion is unit-tested
directly.
| Assignee | ||
Comment 4•3 months ago
|
||
Keys go in MS_PLATFORM_KEY_STORAGE_PROVIDER, the TPM-backed provider, as
distinct from the software MS_KEY_STORAGE_PROVIDER. The handle blob is
just the CNG key name.
CNG keys are single-purpose, which is why KeyUsage is fixed at generation
across the whole crate: an ECDSA key signs and cannot agree, an ECDH key
the reverse. So KeyUsage::Wrap uses RSA-2048 with OAEP rather than ECDH.
One NCryptDecrypt call unwraps a 256-bit KEK, whereas ECDH would mean
deriving a secret and hand-rolling HKDF and an AEAD around it: more code,
most of it security-relevant, for nothing. TPM 1.2 is RSA-only anyway.
NCryptSignHash differs from the other two backends in taking a digest
rather than a message, so this one hashes first. Its ECDSA output is
already raw r || s, so unlike macOS no conversion is needed.
AccessControl::UserVerification is declined here. Raw CNG offers only
NCRYPT_UI_POLICY, a legacy CryptoAPI-style prompt rather than Windows
Hello; real Hello binding needs the WinRT KeyCredentialManager, which is a
much larger integration. Chromium's equivalent access control is
macOS-only for the same reason. Declining lets a caller degrade rather
than believe it got a guarantee.
This backend is type-checked against x86_64-pc-windows-msvc with the real
winapi, but has never been executed: it was written on macOS, and the
Windows CI machines are VMs with no usable TPM, so its gtests skip there
too. The module comment records how to reproduce the cross-check. Treat it
as unvalidated until it has run against real TPM hardware.
| Assignee | ||
Comment 5•3 months ago
|
||
The side-effect-free half of DBSC: parsing and serializing the
Secure-Session-* headers, the session configuration, assembling the proof
JWT, and deciding whether a request is in a session's scope and whether
its credentials are satisfied.
Kept free of nss-rs, xpcom and nsstring on purpose. Anything depending on
nss-rs cannot be listed in RUST_TESTS, because the tools/rusttests build
links no shared NSS, so this split is what buys the protocol ordinary unit
test coverage: 49 tests, checked against the exact strings the checked-in
web-platform tests produce. Signing, storage and channel plumbing follow in
dbsc_glue.
Several things the specification prose does not settle, taken from the
tests instead:
- The header names are Secure-Session-, not the Sec-Session- spelling
from earlier drafts. No server answers to the old names. - Response headers are structured fields but the request headers mostly
are not. Secure-Session-Response carries a bare JWT, because the
server splits it on '.', and Sec-Secure-Session-Id a bare identifier,
because the server passes it to int(). Quoting either as an sf-string
would break every server. Secure-Session-Skipped genuinely is a
structured field. - In scope_specification the last matching rule wins, and paths match as
prefixes. set-scope-specification.https.html pins this down by
including a file and then excluding the directory above it. - Credential matching compares Domain, Path, Secure, HttpOnly, SameSite
and Partitioned, and ignores Expires and Max-Age -- the latter describe
when a cookie dies rather than what it is, and a bound cookie's
lifetime changes constantly by design.
Two cases deliberately do not defer even though they are in scope: a
session with no credentials, which no refresh could ever satisfy, and a
request from a host outside allowed_refresh_initiators, where holding the
request would hand a third party a timing oracle.
Signing lives behind signing_input/assemble_jwt so the proof format is
testable without a key, and so this crate needs no dependency on
platform_keys.
| Assignee | ||
Comment 6•3 months ago
|
||
The half of DBSC that needs Gecko-adjacent machinery: a kvstore-backed
session store, key minting and signing through platform_keys, and a
cbindgen FFI for the C++ service that will drive it.
Division of labour. Rust owns the protocol, the store and the keys; C++
owns creating channels, computing origin attributes and registrable
domains, reading cookies, and holding a deferred channel open. The line
falls where the bindings are cheapest: there is no Rust binding for
OriginAttributes or nsILoadInfo, and writing one to reach the cookie
service from Rust would cost far more than passing a few strings the other
way.
Notable decisions:
- Session keys are <site>::<id>, so one site's sessions are a contiguous
range. The request path looks sessions up by site on every navigation,
and enumerating the whole store to do that is not acceptable. The
range's upper bound also stops example.test from matching
example.test.evil.test, which a naive prefix scan would. - Key minting asks each provider what it can do rather than picking a
provider and then an algorithm, so an RS256-only server automatically
falls through from the Secure Enclave, which is P-256 only, to
software. That is the case the checked-in web-platform tests exercise. - A session's signing algorithm is recovered from its stored key handle
rather than duplicated in the record, so the two cannot disagree. - Private browsing gets an in-memory store. Keeping those sessions out
of the profile entirely is a stronger guarantee than remembering to
delete them. - An unreadable refresh configuration terminates the session, rather
than leaving it in a state where we no longer know its scope. - The whole cookie list crosses the FFI as one JSON string. Parallel
arrays of names and attribute strings would be a worse boundary for no
gain.
Every call that touches hardware is marked as blocking in the header docs;
the C++ side has to run those off the main thread.
Coverage is 15 gtests over the FFI, which mint real keys, produce real
signatures, and decode the resulting JWTs to assert on what a server would
actually see -- including that a registration proof carries the jwk, a
refresh proof does not, and neither carries sub. dbsc_glue cannot be in
RUST_TESTS for the usual reason: it reaches nss-rs through platform_keys.
| Assignee | ||
Comment 7•3 months ago
|
||
Adds the parts of the necko integration that can be verified now, and stops
short of the parts that cannot.
Landing here:
- network.dbsc.* prefs, all off or conservative by default. The feature is
pref-off because Mozilla's standards position is negative
(mozilla/standards-positions#912) while explicitly leaving the door
open to implementing. - The Secure-Session-* header atoms. Note the spelling: earlier drafts
used Sec-Session-*, which no server answers to, and only
Sec-Secure-Session-Id carries the Sec- prefix. - DeviceBoundSessionService, the parent-process singleton that owns the
Rust service and the things DBSC needs from Gecko: the registrable
domain via nsIEffectiveTLDService, the request's cookies as the JSON
the FFI expects, and the defer decision. Rebuilding a Set-Cookie-style
attribute string from nsICookie is what lets credential matching stay
in Rust; note that SAMESITE_UNSET, not SAMESITE_NONE, is the value
meaning "attribute absent". - nsHttpChannel::ProcessSecureSessionHeaders, called from both
ContinueProcessResponse1 and HandleOverrideResponse -- the latter
duplicates that whole block for setResponseOverride-mocked responses,
and a handler added to only one of them fails silently. It currently
handles Secure-Session-Challenge, which caches a nonce and changes
nothing else.
Deliberately not landing yet: the registration and refresh fetches, and the
request deferral in ContinueConnect. Those need channel creation and a
state machine across background hops, and none of it can be exercised
without the xpcshell and web-platform harness. Wiring GetDeferDecision into
the channel before a refresh exists would hang requests, so the decision is
computed and exposed but not yet consumed.
GetDeferDecision, challenge caching and the clear-data entry points are
covered by the existing 15 dbsc_glue gtests through the FFI; the C++ layer
above them is exercised only by construction so far.
| Assignee | ||
Comment 8•3 months ago
|
||
Completes the integration: the registration and refresh fetches, and request
deferral in nsHttpChannel. 26 of the 27 checked-in web-platform tests now
run, 12 of their expectation files are deleted outright, and the rest record
what is genuinely still missing.
SecureSessionFetch drives one POST to a registration or refresh endpoint.
Both flows share a shape -- prove possession of the key, and on a 403 sign
the challenge the endpoint supplied and try once more. One retry rather than
a loop: a server answering 403 with a fresh challenge forever would have us
signing forever, and each signature costs a hardware operation. Registration
additionally has a bare first attempt for servers that put no challenge in
the advertising header.
Deferral follows the CORS-preflight skeleton, hooked in below ContinueConnect's
cache branches so a request served from cache never waits. On completion the
Cookie header is rebuilt via AddCookiesToRequest, which is idempotent because
it sets with merge=false -- DoAuthRetry relies on the same property.
Three things this turned up that are worth knowing:
- DBSC's own requests must be excluded from deferral. A refresh request is
inside the session's scope and missing the same cookie, so it gets
deferred to wait for the refresh that it is. Nothing is ever sent and
each deferral starts another; the first run made 68,000 defer decisions
and zero refresh requests. Marked with a channel property rather than new
IDL, since HttpBaseChannel is already an nsHashPropertyBag. - Concurrent refreshes have to be coalesced per session. Without it every
deferred request starts its own, which costs a signature and a request
each, hits the endpoint in a burst, and lands several Set-Cookie
responses at unpredictable times -- so a page that deletes the bound
cookie can watch it reappear. This was most of the test flakiness. - A relative refresh_url has to be resolved in C++, so the config is parsed
once in Rust to extract it and the absolute form handed back.
Remaining flakiness has one cause, documented in the suite's dir.ini:
21 of these tests expire the bound cookie and immediately assert it is gone
from document.cookie, which races the propagation of a parent-initiated
channel's cookie changes into the content process. Each passes in isolation;
about one per run flakes and which one rotates. Those subtests are marked
[PASS, FAIL] rather than disabled, and the behaviour they are named for is
covered by unit tests in the dbsc crate.
Still unimplemented, and recorded as FAIL rather than hidden: proactive
refresh ahead of expiry, federated key sharing, WebSockets, and one
Secure-Session-Skipped case where a request stale for two sessions reports
only the one it deferred on.
| Assignee | ||
Comment 9•3 months ago
|
||
The checked-in web-platform tests only ever advertise RS256, because that is
what their login.py sends, so the ES256 path had no coverage at all -- and
that is the path a Secure Enclave or a TPM 2.0 would actually serve. This
offers ES256 against a NodeHTTPSServer and asserts on the proof produced.
Covers the whole cycle end to end: registration off a response header,
storing the session, a request carrying the bound cookie, deferral once the
cookie is gone, the 403-and-challenge round trip, the refreshed cookie
reaching the wire, and clearSite removing the session so a stale cookie no
longer triggers a refresh.
The assertions worth having are the ones a server enforces and that are easy
to get backwards: the registration proof carries a P-256 JWK, the refresh
proof carries none, neither carries sub, aud names the endpoint, and
Sec-Secure-Session-Id is sent bare rather than as a quoted structured field.
It also exercises a relative refresh_url, which the browser has to resolve
because Rust has no URL parser.
Two testing-environment notes, neither a product issue.
network.cookieJarSettings.unblocked_for_testing has to be set or a channel
built without explicit cookie jar settings gets
CookieJarSettings::GetBlockingAll() and every Set-Cookie is refused -- the
cookieBehavior pref alone is not enough. And no hardware key is available in
a developer build, since the Secure Enclave needs a production code
signature, so this exercises ES256 through the software provider; on a
machine where hardware is usable the same test drives the hardware path,
which is the reason to offer ES256 here at all.
| Assignee | ||
Comment 10•3 months ago
|
||
Four pieces, plus a real bug the WPT suite led me to.
Clear-data. A device-bound session exists only to keep a set of cookies
alive, so it is cookie state: DeviceBoundSessionsCleaner hangs off
CLEAR_COOKIES rather than a flag of its own. That is the right semantics
anyway -- it is what makes Clear-Site-Data: cookies end a session, as the
specification requires, and clear-site-data.https.html now passes -- and it
avoids the fact that all 32 flag bits in nsIClearDataService are already
taken.
Private browsing gets a separate in-memory store rather than a flag on the
records. A session registered in a private window must not outlive it, and
never writing it to the profile is a stronger guarantee than remembering to
delete it. Discarded on last-pb-context-exited, which destroys the keys too.
The refresh quota bounds what a server can cost us, since each refresh is a
hardware signature plus a request. Deliberately set well above the honest
case at 60/minute: concurrent requests already coalesce onto one refresh, so
what remains is a server invalidating its own cookie on every response, and
there the cap only needs to bound the damage. A user silently losing their
session would be a worse failure than a few extra signatures. Joining an
in-flight refresh does not spend budget, and going over reports
quota_exceeded in Secure-Session-Skipped rather than the generic
server_error.
Glean records registration and refresh outcomes and, most usefully, which
provider minted each key -- the share of software is how much weaker the
deployed protection is than intended.
The bug: a refresh copied the triggering channel's origin attributes, so a
refresh triggered by a third-party subresource stored the bound cookie in
that subresource's partition, where the site itself cannot read it. The page
then saw two cookies of one name and could not delete the one it could see.
Dropping the partition key -- a session belongs to its site, not to whatever
document happened to notice it was stale -- turned the suite from "a random
file fails each run" into a deterministic result. userContextId and
privateBrowsingId stay, since those are jars a session legitimately lives in
one of.
The suite is now stable at 83/83 expected across repeated runs. 21 of those
are subtests marked [PASS, FAIL] for one remaining cause, documented in
dir.ini: they expire the bound cookie and immediately assert it is gone,
and that setup assertion is what fails, before the behaviour they are named
for. Worth noting the obvious explanation is wrong -- the delete and the read
are consecutive synchronous statements, so nothing can arrive between them;
the content process's list must hold an entry the delete does not match. Each
such behaviour is covered by unit tests in netwerk/dbsc/dbsc/ and gtests in
netwerk/dbsc/gtest.
Updated•3 months ago
|
Description
•