taper / server /README.md
abr00kx's picture
Round 2 security fixes (part 4)
cce9364 verified
|
Raw History Blame Contribute Delete
17.7 kB

taper-server

Barebones Taper homeserver: one WebSocket gateway, allowlisted federation, encrypted media, optional encrypted-at-rest storage. It's for poking at the protocol, not for running anywhere real.

npm install
npm start          # open http://127.0.0.1:8080/_taper/gateway/v1/
npm test           # end-to-end tests over real sockets
                    # (includes a search of the server's files and live memory for
                    # every secret the tests sent: none may be there)
node test-tor-live.js   # a live run over real Tor; a few minutes, see its header

Environment variables: PORT, HOST, TAPER_SERVER_NAME (default localhost), TAPER_RETENTION_MS (can only be shorter than 21 days), TAPER_HEARTBEAT_MS, TAPER_TOKEN_TTL_MS (default 7 days; a token in use is renewed, up to TAPER_TOKEN_MAX_MS from when it was issued, default 30 days), TAPER_TLS_CERT / TAPER_TLS_KEY (PEM files), TAPER_REGISTER_POW_BITS (registration challenge, default 20), TAPER_INVITE_ONLY (1 requires a single-use ti_… invite token from admin.js invite), TAPER_OTK_CLAIM_LIMIT (max one-time key claims per requester/device per 5 min, default 4), TAPER_OTK_DEVICE_LIMIT (max total one-time key claims per target device per 5 min across all requesters, default 16), TAPER_MAX_UNAUTH_CONNS (max concurrent unauthenticated WebSocket connections, default 256), TAPER_MAX_MEDIA_TOTAL_BYTES (global in-RAM media cap across all users, default 256 MiB), TAPER_MIN_RETENTION_MS (minimum per-room t.room.retention lifetime, default 60000 ms), TAPER_FEDERATION_TRUST_ROTATION (1 disables strict peer key pinning, dev only), TAPER_BUDGET_SCALE (multiplies the daily read budgets, default 1), TAPER_CANARIES (comma-separated room and user IDs that act as tripwires), TAPER_DISPATCH_BATCH_MS (dispatch batching window, default 200; 0 turns it off), and the cover-site settings below.

Looking like a website

Nothing outside the gateway says "Taper". Any request that isn't a gateway handshake on the right path, including a WebSocket handshake on any other path, gets the cover website: the files in TAPER_COVER_DIR, or a plain "Welcome" page and an ordinary 404. There are no banners, Server headers or protocol errors.

  • TAPER_GATEWAY_PATH: the gateway path. Give it to users in invite links. With TLS the server refuses to start unless it holds at least 22 random base64url characters (128 bits); the default /_taper/gateway/v1 is for local development only.
  • TAPER_FEDERATION_PATH: the same, for federation (required with TLS when federating). Server keys are served at {federation path}/keys, so only peers that know the path can fetch them.
  • TAPER_CLIENT_DIR: the web client the server hosts at {gateway path}/ (default ../client; off disables it). Only the client's runtime files are served, with a strict CSP and Referrer-Policy: no-referrer.
  • TAPER_WELL_KNOWN=1|0: serve /.well-known/taper/client, which reveals the gateway path. On by default without TLS, off by default with it.

Each connection gets its own heartbeat interval (the base ±20%), and dispatches are held for a random part of the batching window and sent together, so timing doesn't mirror the sender's.

Storage

By default everything is in memory and a restart wipes it. Set TAPER_DATA_DIR (and TAPER_KEY_DIR, which must be somewhere else) to keep data in SQLite (Node's built-in node:sqlite) with crypto-shredding:

  • Events and queued to-device messages are encrypted with AES-256-GCM under a key for the period they belong to (TAPER_KEY_PERIOD_MS, default one day). Current room state is re-encrypted under the current key each period.
  • Keys live only in TAPER_KEY_DIR; the server refuses to start if it's the data directory or inside it. A copy of the database alone is unreadable.
  • Once everything a key protects has expired, the key file is overwritten and deleted, and its rows are dropped. Every copy of that data, including backups and SQLite's free pages, becomes unreadable at once.
  • Accounts (OPAQUE records), hashed tokens, security-key records and public keys are stored without that layer: they aren't message content. Key backup parts are sealed like events. The database carries a format version (PRAGMA user_version), and a server refuses a database from a newer one.
TAPER_DATA_DIR=/var/lib/taper/data TAPER_KEY_DIR=/run/taper/keys npm start

Put the key directory on separate storage that isn't backed up with the data (ideally a separate volume or a secrets store).

Security keys, accounts and operator tools

  • TAPER_WEBAUTHN_ROOTS: a directory of PEM certificates. A security key whose attestation chain reaches one of them gets the level attested; every other key is unattested. Empty by default, so every key is unattested until an operator adds roots they trust (for example a manufacturer's attestation CA, which the operator must fetch and check themselves). The attestation certificate and the device's model are never stored.
  • TAPER_WEBAUTHN_ORIGINS: optional comma-separated list of page origins that may use security keys. Without it, the page that opened the socket decides, within the rules in the spec.
  • TAPER_ADMIN_SOCKET: a Unix socket for the operator's command line (created 0600). Then, as the operator: node admin.js users | stats | suspend USER | unsuspend USER | revoke USER | unlock USER | delete USER | limits [NAME VALUE]. unlock clears the security keys of someone who lost them all: it is a way round the keys, so check who is asking first. The limits are registration_open, register_pow_bits, rate_burst, rate_per_sec and budget_scale; changes apply at once and last until the next restart. The log records the action, never the account.

Operators can't read messages. They can remove accounts, sign people out, close registration (an invite is the gateway link, so to revoke one, change TAPER_GATEWAY_PATH) and slow things down.

Federation

Experimental. Room version 13 State Resolution v2.1, power levels, kicks/bans, t.room.server_acl, cross-server SAS verification, persistent signing keys with old_verify_keys rotation, TOFU peer key pinning and per-peer budgets are implemented; media does not cross servers yet. The server says so when it starts with peers configured. Use it to test.

Servers federate over WebSockets with the servers listed in TAPER_FEDERATION_PEERS (allowlist mode: name=ws://host:port/_taper/federation/v1, comma-separated) and no others. Each connection is authenticated once, by both sides, by signing a transcript of both nonces (and the TLS channel binding, under TLS) with short-lived request keys. Retired request keys are published with their private halves at {federation path}/keys, so recorded handshakes prove nothing. Every event carries its server's Ed25519 signature over its redacted form, and receivers check it and the event ID.

Over Tor: set TAPER_TOR_SOCKS=127.0.0.1:9050 and every outbound federation connection (the socket and the key fetch) goes through Tor's SOCKS port (socks.js), each peer on its own circuits, with names resolved by Tor, never by DNS here. Peers can then be onion services (name=ws://<address>.onion/path). Plain ws:// is refused for anything but onion and loopback addresses. See deploy/README.md, "Running on Tor", and test-tor.js / test-tor-live.js.

What works across servers: invites, joins (make_join/send_join with full state/signature/Room v13 auth verification), Room v13 State Resolution v2.1, soft-fail against current state, events in both directions, device list updates, key queries and claims, cross-server SAS verification, and to-device messages. Not yet: media from other servers, outbound federation retry queues, and backfill.

TAPER_SERVER_NAME=a.test PORT=8080 TAPER_FEDERATION_PEERS=b.test=ws://127.0.0.1:8090/_taper/federation/v1 npm start
TAPER_SERVER_NAME=b.test PORT=8090 TAPER_FEDERATION_PEERS=a.test=ws://127.0.0.1:8080/_taper/federation/v1 npm start

Scraping resistance

Each account has daily budgets: history events served, state fetches, key lookups, joins and invites (new accounts get a tenth). Heavy use or touching a canary raises the account's tier: elevated halves the budgets and asks for a 16-bit proof-of-work challenge every tenth budgeted request; high cuts budgets to a fifth and asks for a 20-bit challenge every time. Tiers fall back after six hours; nothing bans automatically. Registration always needs a challenge. A request that needs one fails with T_CHALLENGE_REQUIRED and a challenge; the client retries with challenge_response beside body in the request frame (see client/pow.js). Only counters are kept, reset daily.

TLS

With a certificate and key, the gateway serves wss:// with TLS 1.3 only, preferring the hybrid post-quantum group X25519MLKEM768 (falling back to X25519 for clients without it). Without them it serves plain ws://, and refuses to start unless HOST is a loopback address.

openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 30 \
  -subj /CN=localhost -addext subjectAltName=IP:127.0.0.1 -keyout key.pem -out cert.pem
TAPER_TLS_CERT=cert.pem TAPER_TLS_KEY=key.pem \
  TAPER_GATEWAY_PATH=/$(head -c 24 /dev/urandom | base64 | tr '+/' '-_') npm start

Credentials

Passwords never reach the server. Registration and login use OPAQUE (RFC 9807, configuration taper-opaque-v1: ristretto255, SHA-512, Argon2id with 64 MiB, 3 passes, 4 lanes on the client) through @serenity-kit/opaque. The server stores only each user's OPAQUE record, and its OPAQUE secret (OPRF seed and key pair) in TAPER_KEY_DIR/opaque.secret. Losing that file locks every user out, so back it up, separately from the period keys, which must never be backed up.

  • Unknown users get a response built from a fake record, so login doesn't reveal which accounts exist.
  • Every message's exact size is checked before it reaches the library.
  • Logins that never send KE3 count as failures; after five in an hour, a name's logins need a proof-of-work challenge.
  • Replacing a cross-signing identity needs fresh OPAQUE proof (auth: {type: "t.login.opaque", login_id, ke3}).

Access tokens are 256-bit random values, stored only as SHA-256 hashes, and expire.

Connecting by hand

python3 -m websockets ws://127.0.0.1:8080/_taper/gateway/v1

Registering and logging in need OPAQUE, so they can't be typed by hand: use the dev client, or client/opaque.js from Node, and paste the access token into identify.

The server closes connections that don't heartbeat within 1.5 × the interval (30 s by default), so for manual use start the server with TAPER_HEARTBEAT_MS=600000, or paste {"op":"heartbeat"} now and then.

{"op":"request","id":1,"method":"t.opaque.register.start","body":{"username":"alice","registration_request":"..."}}
{"op":"identify","body":{"access_token":"tp_..."}}
{"op":"request","id":2,"method":"t.room.create","body":{"join_rule":"public"}}
{"op":"request","id":3,"method":"t.room.send","body":{"room_id":"!...","type":"t.room.encrypted","txn_id":"t1","content":{"algorithm":"t.megolm.v1.aes-sha2","ciphertext":"aGk","session_id":"s1","binding":"AAAAAAAAAAAAAAAAAAAAAA"}}}

Frames

Every text frame is JSON: {"op": ..., ...}. Binary frames carry media chunks ([op u8][16-byte transfer id][u32 BE index][65536 bytes]).

Every frame is padded, in both directions. A text frame gets a top-level pad property of filler so its UTF-8 length is exactly padme(max(L, 256)), and receivers ignore pad. Every media chunk is a full 64 KiB, the last one zero-padded. See padding.js and the spec's Cryptography and Transport, "Padding".

op direction fields
hello S→C body: {heartbeat_interval_ms, server_name, gateway_version, room_version, retention_ms, connection_id}, sent on connect
identify C→S body: {access_token}, answered with ready
ready S→C body: {session_id, user_id, device_id, rooms: {joined, invited}}
resume C→S body: {access_token, session_id, seq}: replays missed dispatches, then sends resumed. The session is kept for 5 minutes after a disconnect
resumed S→C body: {session_id, seq}
heartbeat C→S answered with heartbeat_ack
request C→S id, method, body, challenge_response?
response S→C id, ok: true, body or id, ok: false, error: {errcode, error, retry_after_ms?}
dispatch S→C seq, type, body, expires_ts?
reconnect S→C body: {url, reason}, then the server closes the connection; reconnect and resume

Dispatch types: t.room.event ({room_id, event}), t.room.invite ({room_id, inviter, state}), t.room.joined ({room_id, state}), t.to_device ({events: [{sender, type, content}]}), t.device_lists ({changed}), t.keys.counts ({one_time_key_counts}). ready also carries one_time_key_counts.

Close codes: 4000 reconnect, 4001 unknown op, 4002 bad frame, 4003 not identified in time, 4004 bad token or logged out, 4005 already identified, 4007 can't resume (identify again), 4009 heartbeat timeout.

Methods

Allowed before identify (see client/opaque.js for the client side):

method body returns
t.opaque.register.start {username, registration_request} (needs a challenge) {registration_response, registration_id}
t.opaque.register.finish {registration_id, registration_record} {user_id, access_token, device_id}
t.opaque.login.start {username, ke1} {ke2, login_id}
t.opaque.login.finish {login_id, ke3} {user_id, access_token, device_id}

After identify:

method body returns
t.whoami {user_id, device_id}
t.secrets.get / t.secrets.put {} / {secrets, auth?} the sealed identity-recovery blob; replacing it needs OPAQUE auth (and a key touch, if the account has security keys)
t.password.change.start / .finish see the spec, "Password change" re-registers OPAQUE and re-seals the identity copy and key backup together; signs other devices out
t.backup.put / get / clear {part, blob} / {} / {} room-key backup parts, dropped 21 days after their day
t.webauthn.list, .challenge, .register.start, .register.finish, .remove, .settings see the spec, "Security keys" FIDO2 keys; t.webauthn.login (before identify) is the second login step
t.account.delete {auth, key_auth?} removes the account; the name stays reserved
t.logout {}, then closes every session for the device
t.rooms.list {joined: [{room_id, state, timeline}], invited: [...]}
t.room.create {join_rule?: "invite"|"public", invite?: [user_id]}; names are encrypted state, set afterwards {room_id}
t.room.invite {room_id, user_id} {}
t.room.join {room_id} {room_id}
t.room.leave {room_id} {}
t.room.send {room_id, type, content, txn_id} {event_id}
t.room.messages {room_id, before?, limit?} {chunk, before}, oldest first; pass before back to page further
t.room.event {room_id, event_id} the event, or T_EXPIRED
t.room.state {room_id} {room_id, state}
t.room.state.set {room_id, type, content} for t.room.name, t.room.topic or t.room.join_rules {event_id}

End-to-end encryption (bodies follow the Matrix key APIs, so the client's crypto library can use them directly):

method body returns
t.keys.upload {device_keys?, one_time_keys?, fallback_keys?} {one_time_key_counts}
t.keys.query {device_keys: {user_id: [device_id…]}} {device_keys, failures, …}
t.keys.claim {one_time_keys: {user_id: {device_id: algorithm}}} {one_time_keys, failures}
t.keys.device_signing.upload {master_key, self_signing_key, user_signing_key, auth?: {password}}; replacing an existing identity needs auth {}
t.keys.signatures.upload {user_id: {key_id: signed object}}: own devices signed by the self-signing key, other users' master keys by the user-signing key {failures}
t.to_device.send {event_type, txn_id, messages: {user_id: {device_id or "*": content}}} {}

The server verifies the Ed25519 self-signature on device keys and on every one-time and fallback key (Canonical JSON), refuses to let a device's keys change, and only shows keys to, or relays to-device messages between, users who share a room. To-device messages for offline devices are queued until the device connects (and dropped after the retention period).

Spec rules enforced

  • Rooms are version 13. Message events must be t.room.encrypted (Megolm, with a binding of at least 128 bits) or t.room.redaction (carrying only redacts; reasons are stripped). The server never sees plaintext.
  • Event IDs hash the redacted event, so they don't commit to message content.
  • History visibility is joined: you only see events from after your join.
  • Message events are purged after the retention period (21 days by default) and served with unsigned.expires_ts. Current state is kept.
  • No compression on the socket (CRIME/BREACH), 256 KiB frame limit, 20-request burst / 10 per second per connection.

Not here yet

Federated media transfer, and discovery beyond a stub /.well-known/taper/client.