|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+package fake
|
|
|
2
|
+
|
|
|
3
|
+import (
|
|
|
4
|
+ "crypto/tls"
|
|
|
5
|
+ "encoding/binary"
|
|
|
6
|
+ "encoding/json"
|
|
|
7
|
+ "fmt"
|
|
|
8
|
+ "net"
|
|
|
9
|
+ "os"
|
|
|
10
|
+ "sync"
|
|
|
11
|
+ "time"
|
|
|
12
|
+)
|
|
|
13
|
+
|
|
|
14
|
+const (
|
|
|
15
|
+ probeDialTimeout = 10 * time.Second
|
|
|
16
|
+ probeHandshakeTimeout = 10 * time.Second
|
|
|
17
|
+ defaultProbeCount = 15
|
|
|
18
|
+ defaultCacheTTL = 24 * time.Hour
|
|
|
19
|
+
|
|
|
20
|
+ tlsTypeChangeCipherSpec = 0x14
|
|
|
21
|
+ tlsTypeApplicationData = 0x17
|
|
|
22
|
+)
|
|
|
23
|
+
|
|
|
24
|
+// CertProbeResult holds the measured encrypted handshake size.
|
|
|
25
|
+type CertProbeResult struct {
|
|
|
26
|
+ Mean int `json:"mean"`
|
|
|
27
|
+ Jitter int `json:"jitter"`
|
|
|
28
|
+}
|
|
|
29
|
+
|
|
|
30
|
+// CertProbeCache is the on-disk format for cached probe results.
|
|
|
31
|
+type CertProbeCache struct {
|
|
|
32
|
+ Hostname string `json:"hostname"`
|
|
|
33
|
+ Port int `json:"port"`
|
|
|
34
|
+ Mean int `json:"mean"`
|
|
|
35
|
+ Jitter int `json:"jitter"`
|
|
|
36
|
+ ProbedAt time.Time `json:"probed_at"`
|
|
|
37
|
+}
|
|
|
38
|
+
|
|
|
39
|
+// LoadCachedProbe reads a cached probe result from path. Returns the result
|
|
|
40
|
+// and true if the cache exists, matches hostname:port, and is younger than ttl.
|
|
|
41
|
+// Otherwise returns zero value and false.
|
|
|
42
|
+func LoadCachedProbe(path, hostname string, port int, ttl time.Duration) (CertProbeResult, bool) {
|
|
|
43
|
+ if ttl <= 0 {
|
|
|
44
|
+ ttl = defaultCacheTTL
|
|
|
45
|
+ }
|
|
|
46
|
+
|
|
|
47
|
+ data, err := os.ReadFile(path)
|
|
|
48
|
+ if err != nil {
|
|
|
49
|
+ return CertProbeResult{}, false
|
|
|
50
|
+ }
|
|
|
51
|
+
|
|
|
52
|
+ var cache CertProbeCache
|
|
|
53
|
+ if err := json.Unmarshal(data, &cache); err != nil {
|
|
|
54
|
+ return CertProbeResult{}, false
|
|
|
55
|
+ }
|
|
|
56
|
+
|
|
|
57
|
+ if cache.Hostname != hostname || cache.Port != port {
|
|
|
58
|
+ return CertProbeResult{}, false
|
|
|
59
|
+ }
|
|
|
60
|
+
|
|
|
61
|
+ if time.Since(cache.ProbedAt) > ttl {
|
|
|
62
|
+ return CertProbeResult{}, false
|
|
|
63
|
+ }
|
|
|
64
|
+
|
|
|
65
|
+ if cache.Mean <= 0 {
|
|
|
66
|
+ return CertProbeResult{}, false
|
|
|
67
|
+ }
|
|
|
68
|
+
|
|
|
69
|
+ return CertProbeResult{Mean: cache.Mean, Jitter: cache.Jitter}, true
|
|
|
70
|
+}
|
|
|
71
|
+
|
|
|
72
|
+// SaveCachedProbe writes a probe result to path as JSON.
|
|
|
73
|
+func SaveCachedProbe(path, hostname string, port int, result CertProbeResult) error {
|
|
|
74
|
+ cache := CertProbeCache{
|
|
|
75
|
+ Hostname: hostname,
|
|
|
76
|
+ Port: port,
|
|
|
77
|
+ Mean: result.Mean,
|
|
|
78
|
+ Jitter: result.Jitter,
|
|
|
79
|
+ ProbedAt: time.Now(),
|
|
|
80
|
+ }
|
|
|
81
|
+
|
|
|
82
|
+ data, err := json.MarshalIndent(cache, "", " ")
|
|
|
83
|
+ if err != nil {
|
|
|
84
|
+ return err
|
|
|
85
|
+ }
|
|
|
86
|
+
|
|
|
87
|
+ return os.WriteFile(path, data, 0o644) //nolint: gosec
|
|
|
88
|
+}
|
|
|
89
|
+
|
|
|
90
|
+// ProbeCertSize connects to hostname:port via TLS multiple times and measures
|
|
|
91
|
+// the total ApplicationData payload bytes sent by the server during the
|
|
|
92
|
+// handshake (between ChangeCipherSpec and the first application-level data).
|
|
|
93
|
+// This corresponds to EncryptedExtensions + Certificate + CertificateVerify +
|
|
|
94
|
+// Finished in TLS 1.3, which is what the FakeTLS noise must mimic.
|
|
|
95
|
+func ProbeCertSize(hostname string, port int, count int) (CertProbeResult, error) {
|
|
|
96
|
+ if count <= 0 {
|
|
|
97
|
+ count = defaultProbeCount
|
|
|
98
|
+ }
|
|
|
99
|
+
|
|
|
100
|
+ addr := net.JoinHostPort(hostname, fmt.Sprintf("%d", port))
|
|
|
101
|
+ sizes := make([]int, 0, count)
|
|
|
102
|
+
|
|
|
103
|
+ for i := 0; i < count; i++ {
|
|
|
104
|
+ size, err := probeSingle(addr, hostname)
|
|
|
105
|
+ if err != nil {
|
|
|
106
|
+ if len(sizes) > 0 {
|
|
|
107
|
+ break // use what we have
|
|
|
108
|
+ }
|
|
|
109
|
+
|
|
|
110
|
+ return CertProbeResult{}, fmt.Errorf("probe %d failed: %w", i, err)
|
|
|
111
|
+ }
|
|
|
112
|
+
|
|
|
113
|
+ sizes = append(sizes, size)
|
|
|
114
|
+ }
|
|
|
115
|
+
|
|
|
116
|
+ if len(sizes) == 0 {
|
|
|
117
|
+ return CertProbeResult{}, fmt.Errorf("no successful probes")
|
|
|
118
|
+ }
|
|
|
119
|
+
|
|
|
120
|
+ // Calculate mean and jitter (max deviation from mean).
|
|
|
121
|
+ sum := 0
|
|
|
122
|
+ for _, s := range sizes {
|
|
|
123
|
+ sum += s
|
|
|
124
|
+ }
|
|
|
125
|
+
|
|
|
126
|
+ mean := sum / len(sizes)
|
|
|
127
|
+
|
|
|
128
|
+ maxDev := 0
|
|
|
129
|
+ for _, s := range sizes {
|
|
|
130
|
+ d := s - mean
|
|
|
131
|
+ if d < 0 {
|
|
|
132
|
+ d = -d
|
|
|
133
|
+ }
|
|
|
134
|
+
|
|
|
135
|
+ if d > maxDev {
|
|
|
136
|
+ maxDev = d
|
|
|
137
|
+ }
|
|
|
138
|
+ }
|
|
|
139
|
+
|
|
|
140
|
+ // Ensure minimum jitter of 100 bytes for variability.
|
|
|
141
|
+ if maxDev < 100 {
|
|
|
142
|
+ maxDev = 100
|
|
|
143
|
+ }
|
|
|
144
|
+
|
|
|
145
|
+ return CertProbeResult{Mean: mean, Jitter: maxDev}, nil
|
|
|
146
|
+}
|
|
|
147
|
+
|
|
|
148
|
+// probeSingle does one TLS handshake and measures ApplicationData bytes
|
|
|
149
|
+// received during the handshake.
|
|
|
150
|
+func probeSingle(addr, hostname string) (int, error) {
|
|
|
151
|
+ rawConn, err := net.DialTimeout("tcp", addr, probeDialTimeout)
|
|
|
152
|
+ if err != nil {
|
|
|
153
|
+ return 0, err
|
|
|
154
|
+ }
|
|
|
155
|
+ defer rawConn.Close() //nolint: errcheck
|
|
|
156
|
+
|
|
|
157
|
+ capture := &recordCapture{conn: rawConn}
|
|
|
158
|
+
|
|
|
159
|
+ tlsConn := tls.Client(capture, &tls.Config{
|
|
|
160
|
+ ServerName: hostname,
|
|
|
161
|
+ MinVersion: tls.VersionTLS12,
|
|
|
162
|
+ })
|
|
|
163
|
+ tlsConn.SetDeadline(time.Now().Add(probeHandshakeTimeout)) //nolint: errcheck
|
|
|
164
|
+
|
|
|
165
|
+ if err := tlsConn.Handshake(); err != nil {
|
|
|
166
|
+ return 0, err
|
|
|
167
|
+ }
|
|
|
168
|
+
|
|
|
169
|
+ tlsConn.Close() //nolint: errcheck
|
|
|
170
|
+
|
|
|
171
|
+ return capture.appDataBytes, nil
|
|
|
172
|
+}
|
|
|
173
|
+
|
|
|
174
|
+// recordCapture wraps a net.Conn and parses the raw TLS record stream to
|
|
|
175
|
+// measure ApplicationData payload sizes sent by the server during handshake.
|
|
|
176
|
+// It tracks record boundaries by maintaining a state machine over Read calls.
|
|
|
177
|
+type recordCapture struct {
|
|
|
178
|
+ conn net.Conn
|
|
|
179
|
+ mu sync.Mutex
|
|
|
180
|
+ appDataBytes int
|
|
|
181
|
+ seenCCS bool
|
|
|
182
|
+ done bool
|
|
|
183
|
+
|
|
|
184
|
+ // Record boundary tracking for the read side.
|
|
|
185
|
+ readRemaining int // bytes left in current record payload
|
|
|
186
|
+ readHeaderBuf [5]byte
|
|
|
187
|
+ readHeaderPos int
|
|
|
188
|
+}
|
|
|
189
|
+
|
|
|
190
|
+func (rc *recordCapture) Read(p []byte) (int, error) {
|
|
|
191
|
+ n, err := rc.conn.Read(p)
|
|
|
192
|
+ if n > 0 && !rc.done {
|
|
|
193
|
+ rc.mu.Lock()
|
|
|
194
|
+ rc.parseReadBytes(p[:n])
|
|
|
195
|
+ rc.mu.Unlock()
|
|
|
196
|
+ }
|
|
|
197
|
+
|
|
|
198
|
+ return n, err
|
|
|
199
|
+}
|
|
|
200
|
+
|
|
|
201
|
+func (rc *recordCapture) parseReadBytes(data []byte) {
|
|
|
202
|
+ for len(data) > 0 {
|
|
|
203
|
+ if rc.readRemaining > 0 {
|
|
|
204
|
+ // Consuming payload of current record.
|
|
|
205
|
+ consume := rc.readRemaining
|
|
|
206
|
+ if consume > len(data) {
|
|
|
207
|
+ consume = len(data)
|
|
|
208
|
+ }
|
|
|
209
|
+
|
|
|
210
|
+ rc.readRemaining -= consume
|
|
|
211
|
+ data = data[consume:]
|
|
|
212
|
+
|
|
|
213
|
+ continue
|
|
|
214
|
+ }
|
|
|
215
|
+
|
|
|
216
|
+ // Accumulate header bytes (5 bytes per record).
|
|
|
217
|
+ need := 5 - rc.readHeaderPos
|
|
|
218
|
+ if need > len(data) {
|
|
|
219
|
+ need = len(data)
|
|
|
220
|
+ }
|
|
|
221
|
+
|
|
|
222
|
+ copy(rc.readHeaderBuf[rc.readHeaderPos:], data[:need])
|
|
|
223
|
+ rc.readHeaderPos += need
|
|
|
224
|
+ data = data[need:]
|
|
|
225
|
+
|
|
|
226
|
+ if rc.readHeaderPos < 5 {
|
|
|
227
|
+ return // incomplete header
|
|
|
228
|
+ }
|
|
|
229
|
+
|
|
|
230
|
+ // Full header available.
|
|
|
231
|
+ recordType := rc.readHeaderBuf[0]
|
|
|
232
|
+ payloadLen := int(binary.BigEndian.Uint16(rc.readHeaderBuf[3:5]))
|
|
|
233
|
+ rc.readHeaderPos = 0
|
|
|
234
|
+ rc.readRemaining = payloadLen
|
|
|
235
|
+
|
|
|
236
|
+ if recordType == tlsTypeChangeCipherSpec {
|
|
|
237
|
+ rc.seenCCS = true
|
|
|
238
|
+ } else if recordType == tlsTypeApplicationData && rc.seenCCS {
|
|
|
239
|
+ rc.appDataBytes += payloadLen
|
|
|
240
|
+ }
|
|
|
241
|
+ }
|
|
|
242
|
+}
|
|
|
243
|
+
|
|
|
244
|
+func (rc *recordCapture) Write(p []byte) (int, error) {
|
|
|
245
|
+ // After client writes post-CCS data, server handshake records are done.
|
|
|
246
|
+ if rc.seenCCS && rc.appDataBytes > 0 {
|
|
|
247
|
+ rc.done = true
|
|
|
248
|
+ }
|
|
|
249
|
+
|
|
|
250
|
+ return rc.conn.Write(p)
|
|
|
251
|
+}
|
|
|
252
|
+
|
|
|
253
|
+func (rc *recordCapture) Close() error { return rc.conn.Close() }
|
|
|
254
|
+func (rc *recordCapture) LocalAddr() net.Addr { return rc.conn.LocalAddr() }
|
|
|
255
|
+func (rc *recordCapture) RemoteAddr() net.Addr { return rc.conn.RemoteAddr() }
|
|
|
256
|
+func (rc *recordCapture) SetDeadline(t time.Time) error { return rc.conn.SetDeadline(t) }
|
|
|
257
|
+func (rc *recordCapture) SetReadDeadline(t time.Time) error { return rc.conn.SetReadDeadline(t) }
|
|
|
258
|
+func (rc *recordCapture) SetWriteDeadline(t time.Time) error { return rc.conn.SetWriteDeadline(t) }
|
|
|
259
|
+
|
|
|
260
|
+// Ensure recordCapture implements net.Conn.
|
|
|
261
|
+var _ net.Conn = (*recordCapture)(nil)
|