diff --git a/reality.go b/reality.go index 28da544c2a..b5a57b0ce0 100644 --- a/reality.go +++ b/reality.go @@ -143,6 +143,14 @@ type RealityConfig struct { // not probe the target again. postHandshake atomic.Pointer[realityPostHandshakeCache] + // replay remembers the ClientHellos already accepted (reality_replay.go). + // It is created lazily and shared with clones. + replay atomic.Pointer[realityReplayGuard] + + // noPostHandshakeWarm keeps the post-handshake patterns from being learned + // ahead of the first client. Tests that count the target's connections set it. + noPostHandshakeWarm bool + // mldsa65 caches the private key expanded from Mldsa65Seed. mldsa65 atomic.Pointer[realityMldsa65Key] ecdhKey atomic.Pointer[realityECDHKey] @@ -166,9 +174,11 @@ func (a *RealityConfig) Clone() *RealityConfig { HandshakeTimeout: a.HandshakeTimeout, Mldsa65Seed: a.Mldsa65Seed, RequireX25519MLKEM768: a.RequireX25519MLKEM768, + noPostHandshakeWarm: a.noPostHandshakeWarm, Config: *a.Config.Clone(), } c.postHandshake.Store(a.postHandshakeCache()) + c.replay.Store(a.replayGuard()) c.ecdhKey.Store(a.ecdhKey.Load()) return c } @@ -416,6 +426,8 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* config.Log("REALITY remoteAddr: %v", remoteAddr) } + config.warmPostHandshake() + target, err := config.DialContext(ctx, config.Type, config.Dest) if err != nil { conn.Close() @@ -497,7 +509,15 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* (config.MaxClientVer == nil || realityValue(hs.ClientVer[:]...) <= realityValue(config.MaxClientVer...)) && (config.MaxTimeDiff == 0 || config.time().Sub(hs.ClientTime).Abs() <= config.MaxTimeDiff) && (config.ShortIds[hs.ClientShortId]) { - hs.c.conn = conn + // A second copy of an accepted ClientHello is a recording sent + // again: it goes to the target, as a stranger's does. + if config.replayGuard().seen(hs.clientHello.random, config.time(), config.replayWindow()) { + if config.Log != nil { + config.Log("REALITY remoteAddr: %v replayed ClientHello", remoteAddr) + } + } else { + hs.c.conn = conn + } } break } @@ -603,6 +623,10 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* s2cSaved = s2cSaved[handshakeLen:] handshakeLen = 0 } + // The target's answer names the cipher suite: the pattern of its + // post-handshake records can be asked for now, while the client's + // Finished is still on its way. + config.postHandshakeCache().start(config, hs.postHandshakeKey()) start := time.Now() err = hs.handshake() if config.Log != nil { diff --git a/reality_post_handshake.go b/reality_post_handshake.go index b046e04e2a..cfb1be9f4d 100644 --- a/reality_post_handshake.go +++ b/reality_post_handshake.go @@ -10,8 +10,16 @@ package tls // on the live connection, because the real client's Finished is never // forwarded to the target once the client has been authenticated. Instead, the // wire lengths of those records are learned once per (target, SNI, ALPN, -// cipher suite) with an asynchronous probe handshake and replayed as empty -// application_data records of the same length after the client's Finished. +// cipher suite) with a probe handshake and replayed as empty application_data +// records of the same length after the client's Finished. +// +// A client that came before the pattern was learned would get no such records +// while the target sends them: the first connection after a start would look +// unlike every later one and unlike the target. So the patterns of the usual +// handshakes are learned ahead, on the first connection of any kind +// (warmPostHandshake), the probe of a new key starts as soon as the target's +// ServerHello names the cipher suite, and a client whose pattern is still being +// learned waits for it, for a short bounded time. import ( "context" @@ -50,8 +58,22 @@ var ( // realityPostHandshakeRetryInterval is the minimum delay before a failed // probe is attempted again for the same key. realityPostHandshakeRetryInterval = time.Minute + // realityPostHandshakeQuiet ends a probe's collection early: once the + // target has sent nothing for this long, or for as long as the probe's own + // dial and handshake took if that is longer, it is taken to be done. A + // target sends these records right after the client's Finished, so the + // whole collect window is only for one that keeps sending. + realityPostHandshakeQuiet = 400 * time.Millisecond + // realityPostHandshakeWait bounds how long a client waits for a pattern + // that is being learned, counted from the start of the probe: a probe that + // hangs holds up only the clients of its first moments. + realityPostHandshakeWait = 2 * time.Second ) +// realityWarmServerNames bounds the server names whose patterns are learned +// ahead; a config with more learns the rest on demand. +const realityWarmServerNames = 4 + // realityPostHandshakeKey identifies a learned post-handshake record pattern. // The key space is bounded by RealityConfig.ServerNames, the three ALPN modes // and the TLS 1.3 cipher suites, because lookups only happen for authenticated @@ -65,7 +87,8 @@ type realityPostHandshakeKey struct { } type realityPostHandshakeEntry struct { - done chan struct{} // closed when the probe finished; fields below are valid after that + started time.Time // when the probe began + done chan struct{} // closed when the probe finished; fields below are valid after that lens []uint16 ok bool @@ -76,38 +99,95 @@ type realityPostHandshakeEntry struct { type realityPostHandshakeCache struct { mu sync.Mutex entries map[realityPostHandshakeKey]*realityPostHandshakeEntry + warmed bool // warmPostHandshake ran } func newRealityPostHandshakeCache() *realityPostHandshakeCache { return &realityPostHandshakeCache{entries: make(map[realityPostHandshakeKey]*realityPostHandshakeEntry)} } -// lookup returns the learned record lengths for key. When nothing has been -// learned yet it starts at most one probe for the key and returns ok=false -// without blocking. -func (c *realityPostHandshakeCache) lookup(config *RealityConfig, key realityPostHandshakeKey) (lens []uint16, ok bool) { +// start returns the entry of key, beginning at most one probe for it: when +// nothing was learned yet, or when the last probe failed long enough ago. It +// does not block. +func (c *realityPostHandshakeCache) start(config *RealityConfig, key realityPostHandshakeKey) *realityPostHandshakeEntry { c.mu.Lock() defer c.mu.Unlock() if e := c.entries[key]; e != nil { select { case <-e.done: - if e.ok { - return e.lens, true - } - if time.Since(e.finished) < realityPostHandshakeRetryInterval { - return nil, false + if e.ok || time.Since(e.finished) < realityPostHandshakeRetryInterval { + return e } // A stale failure: probe again below. default: - return nil, false // probe in flight + return e // probe in flight } } - e := &realityPostHandshakeEntry{done: make(chan struct{})} + e := &realityPostHandshakeEntry{started: time.Now(), done: make(chan struct{})} c.entries[key] = e go e.run(config, key) - return nil, false + return e +} + +// lookup returns the learned record lengths for key. A pattern that is still +// being learned is waited for until realityPostHandshakeWait after its probe +// began; past that, and after a probe that failed, it returns ok=false at once. +func (c *realityPostHandshakeCache) lookup(config *RealityConfig, key realityPostHandshakeKey) (lens []uint16, ok bool) { + e := c.start(config, key) + select { + case <-e.done: + default: + wait := time.Until(e.started.Add(realityPostHandshakeWait)) + if wait <= 0 { + return nil, false + } + timer := time.NewTimer(wait) + defer timer.Stop() + select { + case <-e.done: + case <-timer.C: + return nil, false + } + } + if !e.ok { + return nil, false + } + return e.lens, true +} + +// warmPostHandshake learns, once for a config and its clones, the patterns of +// the handshakes clients usually make: each server name with h2 and each +// TLS 1.3 cipher suite. It is called on every connection and returns at once; +// the probes run one after another in the background, so the first client +// after a start finds its pattern learned and neither waits for it nor differs +// from the clients after it. +func (a *RealityConfig) warmPostHandshake() { + if a.noPostHandshakeWarm { + return + } + c := a.postHandshakeCache() + c.mu.Lock() + warmed := c.warmed + c.warmed = true + c.mu.Unlock() + if warmed { + return + } + names := make([]string, 0, realityWarmServerNames) + for name, on := range a.ServerNames { + if on && name != "" && len(names) < realityWarmServerNames { + names = append(names, name) + } + } + go func() { + for _, name := range names { + for _, suite := range []uint16{TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256} { + <-c.start(a, realityPostHandshakeKey{network: a.Type, dest: a.Dest, serverName: name, alpn: realityALPNH2, cipherSuite: suite}).done + } + } + }() } func (e *realityPostHandshakeEntry) run(config *RealityConfig, key realityPostHandshakeKey) { @@ -188,6 +268,7 @@ func realityProbePostHandshakeRecords(config *RealityConfig, key realityPostHand ctx, cancel := context.WithTimeout(context.Background(), realityPostHandshakeProbeTimeout) defer cancel() + began := time.Now() target, err := config.DialContext(ctx, key.network, key.dest) if err != nil { return nil, err @@ -204,6 +285,12 @@ func realityProbePostHandshakeRecords(config *RealityConfig, key realityPostHand if err := uconn.HandshakeContext(ctx); err != nil { return nil, err } + // The target answers within about a round trip, and the dial and the + // handshake just took several: a target farther away gets longer. + quiet := realityPostHandshakeQuiet + if took := time.Since(began); took > quiet { + quiet = took + } if state := uconn.ConnectionState(); state.Version != VersionTLS13 || state.CipherSuite != key.cipherSuite { return nil, errors.New("REALITY: probe negotiated unexpected parameters") } @@ -214,14 +301,20 @@ func realityProbePostHandshakeRecords(config *RealityConfig, key realityPostHand data := append([]byte(nil), uconn.rawInput.Bytes()...) // Bound the collection: a read deadline where supported, and a hard close - // for transports that ignore deadlines. + // for transports that ignore deadlines. It ends when the target hangs up, + // when it has been quiet for long enough, or at the end of the window. stop := time.AfterFunc(realityPostHandshakeCollectWindow, func() { target.Close() }) defer stop.Stop() - target.SetReadDeadline(time.Now().Add(realityPostHandshakeCollectWindow)) + end := time.Now().Add(realityPostHandshakeCollectWindow) const maxCollect = (realityMaxPostHandshakeRecords + 1) * realityMaxPostHandshakeRecordLen buf := make([]byte, 4096) for len(data) <= maxCollect { + deadline := time.Now().Add(quiet) + if deadline.After(end) { + deadline = end + } + target.SetReadDeadline(deadline) n, err := target.Read(buf) data = append(data, buf[:n]...) if err != nil { @@ -313,20 +406,25 @@ func (a *RealityConfig) postHandshakeCache() *realityPostHandshakeCache { return a.postHandshake.Load() } +// postHandshakeKey is the key of the pattern this handshake has to imitate. +// It is known once the target's ServerHello was read. +func (hs *realityServerHandshakeStateTLS13) postHandshakeKey() realityPostHandshakeKey { + return realityPostHandshakeKey{ + network: hs.Config.Type, + dest: hs.Config.Dest, + serverName: hs.clientHello.serverName, + alpn: realityALPNMode(hs.clientHello.alpnProtocols), + cipherSuite: hs.hello.cipherSuite, + } +} + // imitatePostHandshakeRecords is called after the client's Finished was // verified. It replays the target's learned post-handshake records, minus the // ones already mirrored in the first flight. Without a usable cache entry it // changes nothing. func (hs *realityServerHandshakeStateTLS13) imitatePostHandshakeRecords() error { config := hs.Config - key := realityPostHandshakeKey{ - network: config.Type, - dest: config.Dest, - serverName: hs.clientHello.serverName, - alpn: realityALPNMode(hs.clientHello.alpnProtocols), - cipherSuite: hs.hello.cipherSuite, - } - lens, ok := config.postHandshakeCache().lookup(config, key) + lens, ok := config.postHandshakeCache().lookup(config, hs.postHandshakeKey()) if !ok { return nil } diff --git a/reality_post_handshake_test.go b/reality_post_handshake_test.go index 7447eb0456..a1c7f37a31 100644 --- a/reality_post_handshake_test.go +++ b/reality_post_handshake_test.go @@ -26,6 +26,8 @@ func init() { // probe goroutine can race with a later test changing them. realityPostHandshakeCollectWindow = 500 * time.Millisecond realityPostHandshakeProbeTimeout = 2 * time.Second + realityPostHandshakeQuiet = 150 * time.Millisecond + realityPostHandshakeWait = time.Second } const realityTestServerName = "example.golang" @@ -121,6 +123,9 @@ func newRealityTestConfig(t *testing.T, dest string) (*RealityConfig, *ecdh.Publ ServerNames: map[string]bool{realityTestServerName: true}, PrivateKey: priv, ShortIds: map[[8]byte]bool{realityTestShortID: true}, + // The tests count the target's connections and the probes: each learns + // its pattern on demand. TestRealityPostHandshakeWarm turns it back on. + noPostHandshakeWarm: true, } config.SessionTicketsDisabled = true return config, pubKey @@ -365,9 +370,9 @@ func toUint16s(lens []int) []uint16 { } // Scenario A and B: the target sends records only after it received the -// client's Finished. The first REALITY connection (nothing learned yet) shows -// the mismatch; once the probe finished the REALITY server reproduces the -// target's record lengths. +// client's Finished. The first REALITY connection (nothing learned yet) waits +// for the probe and reproduces the target's record lengths as every later one +// does. func TestRealityPostHandshakeRecordsImitated(t *testing.T) { tt := newRealityTestTarget(t, realityTestTargetConfig(nil, false), map[string][]int{"": {300, 150}}, true) config, pub := newRealityTestConfig(t, tt.addr()) @@ -379,8 +384,8 @@ func TestRealityPostHandshakeRecordsImitated(t *testing.T) { } got, suite := realityTestConnect(t, addr, pub, nil, realityTestSuites) - if len(got) != 0 { - t.Fatalf("cold connection records = %v, want none (nothing learned yet)", got) + if !reflect.DeepEqual(got, want) { + t.Fatalf("cold connection records = %v, want %v: the first client must not differ from the next", got, want) } e := realityTestWaitProbe(t, config, realityTestKey(config, nil, suite)) @@ -462,8 +467,8 @@ func TestRealityPostHandshakeALPN(t *testing.T) { want := realityTestObserveTarget(t, tt, tc.alpn, realityTestSuites) learned[tc.name] = want got, suite := realityTestConnect(t, addr, pub, tc.alpn, realityTestSuites) - if len(got) != 0 { - t.Fatalf("%s: cold connection records = %v, want none", tc.name, got) + if !reflect.DeepEqual(got, want) { + t.Fatalf("%s: cold connection records = %v, want %v", tc.name, got, want) } e := realityTestWaitProbe(t, config, realityTestKey(config, tc.alpn, suite)) if !e.ok || !reflect.DeepEqual(e.lens, toUint16s(want)) { @@ -817,3 +822,102 @@ func (c *countingWriter) Write(b []byte) (int, error) { c.n += n return n, err } + +// The patterns of the usual handshakes are learned ahead, on the first +// connection of any kind: a stranger's is enough. The first client then finds +// its pattern learned, gets the target's records at once and causes no probe. +func TestRealityPostHandshakeWarm(t *testing.T) { + alpn := []string{"h2", "http/1.1"} + tt := newRealityTestTarget(t, realityTestTargetConfig(alpn, false), map[string][]int{"h2": {300, 400}}, true) + config, pub := newRealityTestConfig(t, tt.addr()) + config.noPostHandshakeWarm = false + addr := newRealityTestServer(t, config) + + stranger, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + stranger.Close() + + cache := config.postHandshakeCache() + for _, suite := range realityTestSuites { + key := realityTestKey(config, alpn, suite) + var e *realityPostHandshakeEntry + for deadline := time.Now().Add(10 * time.Second); e == nil; { + cache.mu.Lock() + e = cache.entries[key] + cache.mu.Unlock() + if e == nil { + if time.Now().After(deadline) { + t.Fatalf("suite %x was not learned ahead", suite) + } + time.Sleep(10 * time.Millisecond) + } + } + select { + case <-e.done: + case <-time.After(10 * time.Second): + t.Fatalf("suite %x: the probe did not finish", suite) + } + if !e.ok || len(e.lens) != 2 { + t.Fatalf("suite %x: ok=%v lens=%v, want the two records of h2", suite, e.ok, e.lens) + } + } + if n := realityTestCacheSize(config); n != len(realityTestSuites) { + t.Fatalf("cache holds %d entries, want one per cipher suite", n) + } + probes := tt.completed.Load() + if probes != int32(len(realityTestSuites)) { + t.Fatalf("target completed %d handshakes, want one probe per cipher suite", probes) + } + + want := realityTestObserveTarget(t, tt, alpn, realityTestSuites) + began := time.Now() + got, _ := realityTestConnect(t, addr, pub, alpn, realityTestSuites) + if !reflect.DeepEqual(got, want) { + t.Fatalf("the first client's records = %v, want %v", got, want) + } + if took := time.Since(began); took > realityPostHandshakeWait/2 { + t.Fatalf("the first client took %v: it waited for a pattern that was learned ahead", took) + } + if n := tt.completed.Load(); n != probes+1 { // the observation alone + t.Fatalf("target completed %d handshakes, want %d: the client caused a probe", n, probes+1) + } + // A second config's clone does not learn again. + config.Clone().warmPostHandshake() + time.Sleep(50 * time.Millisecond) + if n := tt.completed.Load(); n != probes+1 { + t.Fatalf("a clone learned the patterns again: %d handshakes", n) + } +} + +// A client waits for a pattern that is being learned only for a bounded time, +// counted from the start of the probe: a probe that hangs holds up the clients +// of its first moments and none after them. +func TestRealityPostHandshakeWaitIsBounded(t *testing.T) { + release := make(chan struct{}) + t.Cleanup(func() { close(release) }) + targetConfig := realityTestTargetConfig(nil, false) + targetConfig.GetConfigForClient = func(chi *ClientHelloInfo) (*Config, error) { + if len(chi.CipherSuites) == 1 { // only the probe pins a single suite + <-release + return nil, errors.New("probe rejected") + } + return nil, nil + } + tt := newRealityTestTarget(t, targetConfig, nil, true) + config, pub := newRealityTestConfig(t, tt.addr()) + addr := newRealityTestServer(t, config) + + began := time.Now() + realityTestConnect(t, addr, pub, nil, realityTestSuites) + first := time.Since(began) + if first < realityPostHandshakeWait/2 || first > realityPostHandshakeWait+time.Second { + t.Fatalf("the first client took %v, want about %v", first, realityPostHandshakeWait) + } + began = time.Now() + realityTestConnect(t, addr, pub, nil, realityTestSuites) + if next := time.Since(began); next > realityPostHandshakeWait/2 { + t.Fatalf("a later client took %v: it waited for the hanging probe again", next) + } +} diff --git a/reality_replay.go b/reality_replay.go new file mode 100644 index 0000000000..bfcc722724 --- /dev/null +++ b/reality_replay.go @@ -0,0 +1,92 @@ +package tls + +// REALITY server: a ClientHello authenticates once. +// +// The proof of a REALITY client sits in its ClientHello, so whoever recorded +// one on the wire can send it again. The time in it (MaxTimeDiff) only bounds +// for how long. A replayed ClientHello would pass the check, and the server +// would answer it itself: the sender cannot finish that handshake, but how the +// server behaves towards it is not how the target would, and that tells the two +// apart. The server therefore remembers the ClientHellos it accepted for as +// long as their time stays valid, and hands a second copy to the target as it +// does with any stranger, so the copy gets the target's own answer. + +import ( + "sync" + "time" +) + +const ( + // realityReplayGeneration bounds the ClientHellos remembered in one + // generation. A server that accepts more than this within the window + // starts the next generation early: memory stays bounded, at the price of + // forgetting the oldest ones before their time is up. + realityReplayGeneration = 1 << 16 + // realityReplayDefaultWindow is how long a ClientHello is remembered when + // the config sets no MaxTimeDiff, that is, when its time is not checked + // and it would otherwise be accepted forever. + realityReplayDefaultWindow = time.Hour +) + +// realityReplayGuard remembers accepted ClientHellos by their random, which the +// client draws anew for each one and which the proof covers, so no other +// ClientHello carries the same. Two generations are kept: an entry lives for at +// least one window and at most two. It is shared by a RealityConfig and all +// its clones. +type realityReplayGuard struct { + mu sync.Mutex + cur map[[32]byte]struct{} + old map[[32]byte]struct{} + turned time.Time // when cur was started +} + +// seen records the ClientHello with the given random and reports whether it was +// recorded before, within window at least. +func (g *realityReplayGuard) seen(random []byte, now time.Time, window time.Duration) bool { + var id [32]byte + copy(id[:], random) + + g.mu.Lock() + defer g.mu.Unlock() + if g.cur == nil { + g.cur = make(map[[32]byte]struct{}) + g.turned = now + } + if _, ok := g.cur[id]; ok { + return true + } + if _, ok := g.old[id]; ok { + return true + } + // The clock going back does not turn the generations early. + if age := now.Sub(g.turned); age >= window || len(g.cur) >= realityReplayGeneration { + g.old = g.cur + g.cur = make(map[[32]byte]struct{}) + g.turned = now + } + g.cur[id] = struct{}{} + return false +} + +// replayWindow is how long an accepted ClientHello has to be remembered: its +// time is valid from MaxTimeDiff before the server's clock to MaxTimeDiff +// after it, twice MaxTimeDiff in all. +func (a *RealityConfig) replayWindow() time.Duration { + if a.MaxTimeDiff <= 0 { + return realityReplayDefaultWindow + } + return 2 * a.MaxTimeDiff +} + +// replayGuard returns the guard shared by this config and its clones, creating +// it on first use. +func (a *RealityConfig) replayGuard() *realityReplayGuard { + if g := a.replay.Load(); g != nil { + return g + } + g := new(realityReplayGuard) + if a.replay.CompareAndSwap(nil, g) { + return g + } + return a.replay.Load() +} diff --git a/reality_replay_test.go b/reality_replay_test.go new file mode 100644 index 0000000000..9ad0aebe9c --- /dev/null +++ b/reality_replay_test.go @@ -0,0 +1,210 @@ +package tls + +import ( + "context" + "io" + "net" + "reflect" + "strings" + "sync" + "testing" + "time" +) + +func TestRealityReplayGuard(t *testing.T) { + var g realityReplayGuard + now := time.Unix(1_800_000_000, 0) + id := func(b byte) []byte { + r := make([]byte, 32) + r[0], r[31] = b, b + return r + } + const window = 10 * time.Minute + if g.seen(id(1), now, window) { + t.Fatal("the first ClientHello was taken for a copy") + } + if !g.seen(id(1), now.Add(time.Second), window) { + t.Fatal("a copy passed") + } + if g.seen(id(2), now.Add(time.Second), window) { + t.Fatal("another ClientHello was taken for a copy") + } + // A generation later the first one is still remembered: an entry lives + // for at least one window. + if g.seen(id(3), now.Add(window+time.Second), window) { + t.Fatal("a new ClientHello after the turn was taken for a copy") + } + if !g.seen(id(1), now.Add(window+2*time.Second), window) { + t.Fatal("a copy passed within the window after the generations turned") + } + // Two turns later it is forgotten: its time ran out long before. + if g.seen(id(4), now.Add(2*window+3*time.Second), window) { + t.Fatal("a new ClientHello was taken for a copy") + } + if g.seen(id(1), now.Add(2*window+4*time.Second), window) { + t.Fatal("a ClientHello is remembered past two windows") + } + // A clock set back does not make the guard forget. + if !g.seen(id(4), now, window) { + t.Fatal("a copy passed after the clock went back") + } +} + +// Memory stays bounded: a full generation turns early, and what it held is +// still remembered as the old one. +func TestRealityReplayGuardIsBounded(t *testing.T) { + var g realityReplayGuard + now := time.Unix(1_800_000_000, 0) + r := make([]byte, 32) + put := func(i int) bool { + r[0], r[1], r[2] = byte(i), byte(i>>8), byte(i>>16) + return g.seen(r, now, time.Hour) + } + for i := 0; i < realityReplayGeneration+10; i++ { + if put(i) { + t.Fatalf("ClientHello %d was taken for a copy", i) + } + } + if len(g.cur) > realityReplayGeneration || len(g.old) > realityReplayGeneration { + t.Fatalf("generations hold %d and %d entries, want at most %d each", len(g.cur), len(g.old), realityReplayGeneration) + } + if !put(realityReplayGeneration - 1) { + t.Fatal("a ClientHello of the generation just turned was forgotten") + } +} + +func TestRealityReplayWindow(t *testing.T) { + if got := (&RealityConfig{MaxTimeDiff: 10 * time.Minute}).replayWindow(); got != 20*time.Minute { + t.Fatalf("window = %v, want both sides of the time check", got) + } + if got := (&RealityConfig{}).replayWindow(); got != realityReplayDefaultWindow { + t.Fatalf("window without a time check = %v, want %v", got, realityReplayDefaultWindow) + } + config := &RealityConfig{} + clone := config.Clone() + if clone.replayGuard() != config.replayGuard() || clone.Clone().replayGuard() != config.replayGuard() { + t.Fatal("clones do not share the replay guard") + } +} + +// realitySentConn keeps a copy of everything written to the wrapped connection. +type realitySentConn struct { + net.Conn + mu sync.Mutex + sent []byte +} + +func (c *realitySentConn) Write(b []byte) (int, error) { + c.mu.Lock() + c.sent = append(c.sent, b...) + c.mu.Unlock() + return c.Conn.Write(b) +} + +// realityTestLog collects what a RealityConfig logs. +type realityTestLog struct { + mu sync.Mutex + lines []string +} + +func (l *realityTestLog) add(format string, v ...any) { + l.mu.Lock() + l.lines = append(l.lines, format) + l.mu.Unlock() +} + +func (l *realityTestLog) count(part string) int { + l.mu.Lock() + defer l.mu.Unlock() + n := 0 + for _, line := range l.lines { + if strings.Contains(line, part) { + n++ + } + } + return n +} + +// A ClientHello a client authenticated with is accepted once. Sent again, as +// someone who recorded it on the wire would send it, it is handed to the target +// like a stranger's: what comes back is the target's own answer, and the +// REALITY server does not answer it itself. +func TestRealityReplayedClientHelloGoesToTheTarget(t *testing.T) { + tt := newRealityTestTarget(t, realityTestTargetConfig(nil, false), nil, true) + config, pub := newRealityTestConfig(t, tt.addr()) + config.MaxTimeDiff = time.Minute + log := new(realityTestLog) + config.Log = log.add + addr := newRealityTestServer(t, config) + + // A real client: its ClientHello is recorded on its way out. + raw, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer raw.Close() + rec := &realitySentConn{Conn: raw} + uconn := UClient(rec, &Config{ServerName: realityTestServerName, InsecureSkipVerify: true, SessionTicketsDisabled: true}, HelloCustom) + spec := realityProbeClientHelloSpec(realityPostHandshakeKey{serverName: realityTestServerName, cipherSuite: realityTestSuites[0]}) + if err := uconn.ApplyPreset(spec); err != nil { + t.Fatal(err) + } + realityTestAuthenticate(t, uconn, pub) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := uconn.HandshakeContext(ctx); err != nil { + t.Fatalf("handshake: %v", err) + } + marker := make([]byte, len(realityTestMarker)) + uconn.SetReadDeadline(time.Now().Add(10 * time.Second)) + if _, err := io.ReadFull(uconn, marker); err != nil || string(marker) != string(realityTestMarker) { + t.Fatalf("the client was not served by the REALITY server: %q %v", marker, err) + } + rec.mu.Lock() + sent := append([]byte(nil), rec.sent...) + rec.mu.Unlock() + if len(sent) < recordHeaderLen || recordType(sent[0]) != recordTypeHandshake { + t.Fatalf("no ClientHello recorded: %d bytes sent", len(sent)) + } + hello := sent[:recordHeaderLen+int(sent[3])<<8+int(sent[4])] + if log.count("replayed ClientHello") != 0 { + t.Fatal("the client's own ClientHello was taken for a copy") + } + completed := tt.completed.Load() + + // The same bytes again, on a new connection. The target answers them + // itself: its first flight comes back, and nothing after it, for whoever + // replays cannot finish the handshake. + answer := func(to string) []int { + c, err := net.Dial("tcp", to) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if _, err := c.Write(hello); err != nil { + t.Fatal(err) + } + c.SetReadDeadline(time.Now().Add(time.Second)) + got, _ := io.ReadAll(c) + return realityTestRecordLens(t, got) + } + viaReality := answer(addr) + if n := log.count("replayed ClientHello"); n != 1 { + t.Fatalf("the copy was noticed %d times, want once", n) + } + // The signature in the target's flight is a byte or two longer or shorter + // from one handshake to the next, so the flights are compared by their + // shape: as many records, the same ServerHello and ChangeCipherSpec. + direct := answer(tt.addr()) + if len(direct) < 3 || len(viaReality) != len(direct) || !reflect.DeepEqual(viaReality[:2], direct[:2]) { + t.Fatalf("a replayed ClientHello got records %v through the REALITY server, the target itself answers %v", viaReality, direct) + } + if tt.completed.Load() != completed { + t.Fatal("the target completed a handshake with a replayed ClientHello") + } + + // A new ClientHello of the same client is served as before. + if _, _ = realityTestConnect(t, addr, pub, nil, realityTestSuites); log.count("replayed ClientHello") != 1 { + t.Fatal("a fresh ClientHello was taken for a copy") + } +}