~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
271 lines · 18.2 KB Raw History
// The guard every request the spaces make goes through (spec/PROXY.md, "SSRF
// protection"; spec/SPACES-SYNC.md, "Environment", "Registering", "Sending
// updates"; spec/SPACES-CREDENTIALS.md, "Issuers' keys", "Verifying a client
// attestation"; spec/SPACES-POLICIES.md, "Asking a managing app:
// checkAccess"), held to the server alone, near the end of the spaces run: the
// reference runs without SSRF protection, and follows redirects.
//
//   1. as the run starts the server, protection off: a did:web on localhost
//      is read over http, follows no redirect, and is read up to 65536 bytes,
//      as an issuer's (a revocation's service auth); a syncer's endpoint on
//      localhost is confirmed over http, and one that redirects is not;
//   2. the server started again without PDS_DISABLE_SSRF_PROTECTION: every
//      fetch the spaces make is sent something naming localhost or
//      127.0.0.1, at plain TCP listeners of the harness that count
//      connections; each request is refused, and no listener sees one; and
//      the syncer registered over http before is sent no update;
//
// and then the server is started again as the run starts it.

import crypto from 'node:crypto'
import { createServer as createHttpServer } from 'node:http'
import { createServer as createTcpServer } from 'node:net'
import { once } from 'node:events'
import { isDeepStrictEqual } from 'node:util'
import * as plc from '@did-plc/lib'
import { Secp256k1Keypair } from '@atproto/crypto'
import * as S from './lib/spec.mjs'

const T = 'com.example.group'
const R = 'com.atproto.space.notifyCredentialsRevoked'
const NRU = 'com.atproto.space.notifyRepoUpdate'
const AUTHORIZE = 'com.atproto.space.authorizeSpaceSync'
const CONFIRM = 'com.atproto.space.confirmRegistration'
const now = () => Math.floor(Date.now() / 1000)
const b64 = (o) => Buffer.from(JSON.stringify(o)).toString('base64url')
const jti = () => crypto.randomBytes(16).toString('hex')
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms))
/// The TID of now, as a space repo's rev.
function tid(ms = Date.now()) {
  let n = (BigInt(Math.floor(ms)) * 1000n) << 10n
  let s = ''
  for (let i = 0; i < 13; i++) { s = '234567abcdefghijklmnopqrstuvwxyz'[Number(n & 31n)] + s; n >>= 5n }
  return s
}

/// A plain TCP listener on 127.0.0.1 (and ::1, on the same port, where it
/// can) that counts the connections made to it and closes each at once.
export async function countingListener() {
  const l = { connections: 0 }
  const accept = (sock) => { l.connections++; sock.destroy() }
  const v4 = createTcpServer(accept)
  v4.listen(0, '127.0.0.1')
  await once(v4, 'listening')
  l.port = v4.address().port
  const v6 = createTcpServer(accept)
  await new Promise((ok) => { v6.once('error', ok); v6.listen(l.port, '::1', ok) })
  l.close = () => { v4.close(); v6.close() }
  return l
}

/// A JWT signed with a secp256k1 key.
async function sign(key, header, payload) {
  const input = `${b64(header)}.${b64(payload)}`
  return `${input}.${Buffer.from(await key.sign(new Uint8Array(Buffer.from(input)))).toString('base64url')}`
}

export async function checkSsrf(h) {
  const { net, cand, env, restartWith, fail, count, front, rand } = h
  /// A syncer's token: 32 bytes of the run's seed, base64url.
  const token = () => Buffer.from(Array.from({ length: 32 }, () => Math.floor(rand() * 256))).toString('base64url')
  const peer = net.extraPdses[0]
  const plcUrl = net.plc.url

  async function call(base, nsid, { params, body, token, headers = {} } = {}) {
    const url = new URL(`${base}/xrpc/${nsid}`)
    for (const [k, v] of Object.entries(params ?? {})) url.searchParams.set(k, v)
    const hs = { ...headers }
    if (token) hs.authorization = `Bearer ${token}`
    if (body !== undefined) hs['content-type'] = 'application/json'
    const res = await fetch(url, { method: body === undefined ? 'GET' : 'POST', headers: hs, body: body === undefined ? undefined : JSON.stringify(body) })
    const text = await res.text()
    let parsed = null
    try { parsed = text ? JSON.parse(text) : null } catch { parsed = { unparsed: text.slice(0, 200) } }
    return { status: res.status, body: parsed }
  }
  const shape = (res) => (res.status >= 400 ? { status: res.status, error: res.body?.error ?? null } : { status: res.status })
  const err = (error, status = 400) => ({ status, error })
  /// One request to the server, held to `want` (a status and error, or 200).
  async function expect(kind, request, send, want) {
    const g = shape(await send())
    const ok = want === 200 ? g.status === 200 : isDeepStrictEqual(g, want)
    if (!ok) await fail(cand, kind, request, want, g)
    count(kind.replace(/: .*/, ''))
  }

  // The parties: an authority on the server, with a space that reads
  // publicly, and a user on the second alpha PDS.
  const f = front()
  const made = await call(cand.url, 'com.atproto.server.createAccount', { body: { handle: `${f}.test`, email: `${f}@example.com`, password: `pw-${f}` } })
  if (made.status !== 200) await fail(cand, 'createAccount for the guard\'s checks', {}, 'an account', shape(made))
  const A = { did: made.body.did, token: made.body.accessJwt }
  const g = front()
  const userMade = await call(peer.url, 'com.atproto.server.createAccount', { body: { handle: `${g}${(await (await fetch(`${peer.url}/xrpc/com.atproto.server.describeServer`)).json()).availableUserDomains[0]}`, email: `${g}@example.com`, password: `pw-${g}` } })
  const user = { did: userMade.body?.did, token: userMade.body?.accessJwt }
  const space = `at://${A.did}/space/${T}/guard`
  const created = await call(cand.url, 'com.atproto.space.createSpace', { token: A.token, body: { spaceType: T, skey: 'guard', policy: { $type: 'com.atproto.memberspace.policy', publicRead: true } } })
  if (created.status !== 200) await fail(cand, 'createSpace for the guard\'s checks', {}, 'the space created', shape(created))
  /// A space credential for the public space, from the server, and its headers.
  async function credentialHeaders() {
    const key = S.newP256()
    const res = await call(cand.url, AUTHORIZE, { body: { space, credentialKey: key.did } })
    if (res.status !== 200) await fail(cand, 'authorizeSpaceSync of a public space', {}, 'a credential', shape(res))
    return S.signCredential(key, res.body.credential, A.did)
  }
  const revocation = (iss, key) => async () => call(cand.url, R, { headers: { authorization: `Bearer ${await sign(key, { typ: 'JWT', alg: 'ES256K' }, { iss, aud: A.did, lxm: R, iat: now(), exp: now() + 60, jti: jti() })}` }, body: { space: `at://${iss}/space/${T}/x`, credentials: ['j'] } })
  /// authorizeSpaceSync of the public space, registering `endpoint`.
  const register = (endpoint, token) => () => call(cand.url, AUTHORIZE, { body: { space, credentialKey: S.newP256().did, notify: { endpoint, token } } })

  // ==== 1. protection off, as the run starts the server ====================================

  /// A did:web on localhost whose document an HTTP listener of the harness
  /// serves, padded to `pad` bytes, or answers `302` to `redirect`'s.
  async function webHost({ pad, redirect } = {}) {
    const w = { hits: [], key: await Secp256k1Keypair.create() }
    const srv = createHttpServer((req, res) => {
      w.hits.push(req.url)
      if (redirect) return res.writeHead(302, { location: `http://localhost:${redirect.port}${req.url}` }).end()
      if (req.url !== '/.well-known/did.json') return res.writeHead(404).end()
      const doc = { '@context': ['https://www.w3.org/ns/did/v1', 'https://w3id.org/security/multikey/v1'], id: w.served ?? w.did, verificationMethod: [{ id: `${w.served ?? w.did}#atproto`, type: 'Multikey', controller: w.served ?? w.did, publicKeyMultibase: (w.servedKey ?? w.key).did().slice('did:key:'.length) }] }
      let text = JSON.stringify(doc)
      if (pad) text = JSON.stringify({ ...doc, pad: 'x'.repeat(Math.max(0, pad - text.length - 10)) })
      res.writeHead(200, { 'content-type': 'application/json' }).end(text)
    })
    srv.listen(0, '127.0.0.1')
    await once(srv, 'listening')
    w.port = srv.address().port
    w.did = `did:web:localhost%3A${w.port}`
    w.close = () => srv.close()
    return w
  }
  /// A syncer's endpoint on localhost: an HTTP listener of the harness that
  /// confirms any registration, its answer padded to `pad` bytes, records
  /// what it is sent, and answers notifySpaceUpdate 200; or answers `302` to
  /// `redirect`'s.
  async function syncerHost({ redirect, pad } = {}) {
    const s = { seen: [] }
    const srv = createHttpServer((req, res) => {
      const chunks = []
      req.on('data', (c) => chunks.push(c))
      req.on('end', () => {
        let body = null
        try { body = JSON.parse(Buffer.concat(chunks).toString('utf8') || 'null') } catch {}
        s.seen.push({ method: req.method, url: req.url, body })
        if (redirect) return res.writeHead(302, { location: `http://localhost:${redirect.port}${req.url}` }).end()
        if (req.url === `/xrpc/${CONFIRM}`) {
          let text = JSON.stringify({ challenge: body?.challenge })
          if (pad) text = JSON.stringify({ challenge: body?.challenge, pad: 'x'.repeat(Math.max(0, pad - text.length - 10)) })
          return res.writeHead(200, { 'content-type': 'application/json' }).end(text)
        }
        res.writeHead(200).end()
      })
    })
    srv.listen(0, '127.0.0.1')
    await once(srv, 'listening')
    s.port = srv.address().port
    s.url = `http://localhost:${s.port}`
    s.close = () => srv.close()
    return s
  }
  // The syncer registered here, kept for the guard on: it must then be sent
  // no update.
  const kept = await syncerHost()
  const keptToken = token()
  {
    // As an issuer's: a revocation's service auth.
    const plain = await webHost()
    await expect('the guard, off: a revocation from a did:web on localhost, served over http', { iss: 'did:web:localhost%3A<port>' }, revocation(plain.did, plain.key), 200)
    if (!plain.hits.includes('/.well-known/did.json')) await fail(cand, 'the guard, off: a did:web on localhost read over http', {}, 'GET /.well-known/did.json', plain.hits)
    const target = await webHost()
    const moved = await webHost({ redirect: target })
    target.served = moved.did
    target.servedKey = moved.key
    await expect('the guard, off: a revocation from a did:web whose host redirects', { iss: 'did:web:localhost%3A<port>, answering 302' }, revocation(moved.did, moved.key), err('AuthenticationRequired', 401))
    if (target.hits.length) await fail(cand, 'the guard, off: a did:web document\'s redirect not followed', {}, 'no request to the redirect\'s target', target.hits)
    const big = await webHost({ pad: 70000 })
    await expect('the guard, off: a revocation from a did:web whose document is 70000 bytes', {}, revocation(big.did, big.key), err('AuthenticationRequired', 401))
    const fits = await webHost({ pad: 60000 })
    await expect('the guard, off: a revocation from a did:web whose document is 60000 bytes', {}, revocation(fits.did, fits.key), 200)
    // As a syncer's: its endpoint confirmed over http, but not through a
    // redirect, and with its answer read up to 524288 bytes; the reference
    // follows the redirect and reads any size (spec/SPACES-SYNC.md,
    // "Environment", "Registering", "Where the reference departs from this
    // page").
    await expect('the guard, off: a registration at http://localhost:<port>', {}, register(kept.url, keptToken), 200)
    if (!kept.seen.some((r) => r.method === 'POST' && r.url === `/xrpc/${CONFIRM}`)) await fail(cand, 'the guard, off: a syncer\'s endpoint on localhost confirmed over http', {}, `POST /xrpc/${CONFIRM}`, kept.seen.map((r) => `${r.method} ${r.url}`))
    const target2 = await syncerHost()
    const moved2 = await syncerHost({ redirect: target2 })
    await expect('the guard, off: a registration at an endpoint that redirects', {}, register(moved2.url, token()), err('RegistrationNotConfirmed'))
    if (target2.seen.length) await fail(cand, 'the guard, off: a syncer\'s redirect not followed', {}, 'no request to the redirect\'s target', target2.seen.map((r) => `${r.method} ${r.url}`))
    const long = await syncerHost({ pad: 600000 })
    await expect('the guard, off: a registration whose confirmation is 600000 bytes', {}, register(long.url, token()), err('RegistrationNotConfirmed'))
    const short = await syncerHost({ pad: 500000 })
    await expect('the guard, off: a registration whose confirmation is 500000 bytes', {}, register(short.url, token()), 200)
    for (const w of [plain, target, moved, big, fits, target2, moved2, long, short]) w.close()
  }

  // ==== 2. protection on ===================================================================

  const guarded = Object.fromEntries(Object.entries(env).filter(([k]) => k !== 'PDS_DISABLE_SSRF_PROTECTION'))
  await restartWith(guarded)
  const L = await countingListener()
  const hosts = [`localhost%3A${L.port}`, `127.0.0.1%3A${L.port}`]
  /// A request that must be refused as `want`, with no connection to the listener.
  async function refused(kind, request, send, want) {
    const before = L.connections
    await expect(`the guard, on: ${kind}`, request, send, want)
    await sleep(200)
    if (L.connections !== before) await fail(cand, `the guard, on: ${kind}: no connection`, request, 'no connection to the listener', `${L.connections - before} connections`)
  }
  const key = await Secp256k1Keypair.create()
  for (const host of hosts) {
    const iss = `did:web:${host}`
    const named = { iss: `did:web:${host.replace(String(L.port), '<port>')}` }
    await refused(`a revocation from ${named.iss}`, named, revocation(iss, key), err('AuthenticationRequired', 401))
    await refused(`notifyRepoUpdate from ${named.iss}`, named, async () => call(cand.url, NRU, { headers: { authorization: `Bearer ${await sign(key, { typ: 'JWT', alg: 'ES256K' }, { iss, aud: `${A.did}#atproto_pds`, lxm: NRU, iat: now(), exp: now() + 60, jti: jti() })}` }, body: { space, repo: iss, repoRev: tid(), data: { $bytes: Buffer.alloc(32, 1).toString('base64') } } }), err('AuthenticationRequired', 401))
    await refused(`a delegation token from ${named.iss}`, named, async () => call(cand.url, AUTHORIZE, { body: { space, credentialKey: S.newP256().did, delegationToken: await sign(key, { alg: 'ES256K', typ: 'atproto-space-delegation+jwt', kid: '#atproto' }, { iss, sub: space, aud: `${A.did}#atproto_pds`, iat: now(), exp: now() + 60, jti: jti() }) } }), err('InvalidDelegationToken'))
    await refused(`a credential from ${named.iss}`, named, async () => {
      const own = `at://${iss}/space/${T}/x`
      const holder = S.newP256()
      const credential = await sign(key, { alg: 'ES256K', typ: 'atproto-space-credential+jwt', kid: '#atproto' }, { iss, sub: own, cnf: { kid: holder.did }, iat: now(), exp: now() + 600, jti: jti() })
      return call(cand.url, 'com.atproto.space.listWriters', { params: { space: own }, headers: S.signCredential(holder, credential, iss) })
    }, err('BadJwtIss', 401))
  }
  for (const endpoint of [`http://localhost:${L.port}`, `https://localhost:${L.port}`, `https://127.0.0.1:${L.port}`])
    await refused(`a registration at ${endpoint.replace(String(L.port), '<port>')}`, {}, register(endpoint, token()), err('RegistrationNotConfirmed'))
  for (const host of [`127.0.0.1:${L.port}`, `localhost:${L.port}`]) {
    const id = `https://${host}/client-metadata.json`
    const what = `an attestation of a client at https://${host.replace(String(L.port), '<port>')}`
    await refused(what, {}, async () => call(cand.url, AUTHORIZE, { body: { space, credentialKey: S.newP256().did, clientAttestation: await sign(key, { alg: 'ES256', typ: 'atproto-client-attestation+jwt', kid: 'k1' }, { iss: id, sub: id, aud: `${A.did}#atproto_pds`, iat: now(), exp: now() + 60, jti: jti() }) } }), err('InvalidClientAttestation'))
  }
  // The syncer registered over http while protection was off: a change of
  // the space is not sent to it (spec/SPACES-SYNC.md, "Environment",
  // "Sending updates").
  {
    const before = kept.seen.length
    const w = await call(cand.url, 'com.atproto.space.createRecord', { token: A.token, body: { space, repo: A.did, collection: 'com.example.post', rkey: 'guard', record: { $type: 'com.example.post', text: 'guard', createdAt: '2026-11-08T00:00:00.000Z' } } })
    if (w.status !== 200) await fail(cand, 'the guard, on: a write into the space registered for', {}, 'written', shape(w))
    await sleep(1500)
    if (kept.seen.length !== before) await fail(cand, 'the guard, on: an update to a syncer at http://localhost:<port>', {}, 'not sent', kept.seen.slice(before).map((r) => `${r.method} ${r.url}`))
    count('the guard, on')
    kept.close()
  }
  // Managing apps: a did:plc whose endpoints are the listener, and a did:web
  // on it (spec/SPACES-POLICIES.md, "Asking a managing app: checkAccess").
  const appKey = await Secp256k1Keypair.create()
  const ends = { plain: `http://127.0.0.1:${L.port}`, tls: `https://127.0.0.1:${L.port}`, named: `https://localhost:${L.port}` }
  const op = await plc.signOperation({ type: 'plc_operation', rotationKeys: [appKey.did()], alsoKnownAs: [], verificationMethods: { atproto: appKey.did() }, services: Object.fromEntries(Object.entries(ends).map(([k, v]) => [k, { type: 'AtprotoManagingApp', endpoint: v }])), prev: null }, appKey)
  const appDid = await plc.didForCreateOp(op)
  await new plc.Client(plcUrl).sendOperation(appDid, op)
  const apps = [...Object.entries(ends).map(([k, v]) => [`${appDid}#${k}`, `a did:plc's endpoint ${v.replace(String(L.port), '<port>')}`]), [`did:web:localhost%3A${L.port}#forum`, 'did:web:localhost%3A<port>#forum']]
  for (const [i, [app, what]] of apps.entries()) {
    const skey = `managed${i}`
    const m = await call(cand.url, 'com.atproto.space.createSpace', { token: A.token, body: { spaceType: T, skey, policy: { $type: 'com.atproto.managedspace.policy', managingApp: app } } })
    if (m.status !== 200) await fail(cand, 'createSpace of a managedspace for the guard\'s checks', { managingApp: what }, 'the space created', shape(m))
    const managed = `at://${A.did}/space/${T}/${skey}`
    const token = (await call(peer.url, 'com.atproto.space.getDelegationToken', { token: user.token, params: { space: managed } })).body?.token
    await refused(`a user's credential of a managedspace whose app is ${what}`, { managingApp: what }, () => call(cand.url, AUTHORIZE, { body: { space: managed, credentialKey: S.newP256().did, delegationToken: token } }), err('UpstreamFailure', 502))
  }
  L.close()
  await restartWith(env)
}