specters 4.1.4

Rust HTTP client with browser-like Chrome and Firefox fingerprints across TLS, HTTP/1.1, HTTP/2, HTTP/3, and WebSockets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use crate::url::{Host, Url};
use base64::Engine;
use bytes::Bytes;
use http::Uri;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::time::timeout as tokio_timeout;

use crate::headers::Headers;
use crate::transport::connector::MaybeHttpsStream;

use super::{WebSocketError, WebSocketResult};

const ACCEPT_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
const MAX_HANDSHAKE_BYTES: usize = 64 * 1024;

#[derive(Debug, Clone)]
pub(crate) struct WebSocketUrl {
    pub(crate) original: Url,
    pub(crate) http_equivalent: Url,
    pub(crate) request_target: String,
    pub(crate) host_header: String,
    pub(crate) uri: Uri,
    pub(crate) secure: bool,
}

#[derive(Debug, Clone)]
pub(crate) struct HandshakeRequest {
    pub(crate) url: WebSocketUrl,
    pub(crate) headers: Headers,
    pub(crate) key: String,
}

#[derive(Debug)]
pub(crate) struct HandshakeResponse {
    pub(crate) stream: MaybeHttpsStream,
    pub(crate) headers: Headers,
    pub(crate) buffered: Bytes,
    pub(crate) protocol: Option<String>,
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct HandshakeTimeouts {
    pub(crate) connect: Option<Duration>,
    pub(crate) handshake: Option<Duration>,
}

pub(crate) fn map_websocket_url(url: Url) -> WebSocketResult<WebSocketUrl> {
    let secure = match url.scheme() {
        "ws" => false,
        "wss" => true,
        scheme => {
            return Err(WebSocketError::protocol(
                &url,
                format!("unsupported WebSocket URL scheme `{}` for {}", scheme, url),
            ))
        }
    };

    if url.host_str().is_none() {
        return Err(WebSocketError::protocol(
            &url,
            format!("WebSocket URL missing host: {}", url),
        ));
    }

    let mut http_equivalent = url.clone();
    http_equivalent
        .set_scheme(if secure { "https" } else { "http" })
        .map_err(|_| WebSocketError::protocol(&url, "failed to map WebSocket URL scheme"))?;

    let request_target = origin_form_target(&url);
    let host_header = host_header(&url);
    let uri = http_equivalent
        .as_str()
        .parse::<Uri>()
        .map_err(|err| WebSocketError::protocol(&url, format!("invalid mapped URI: {}", err)))?;

    Ok(WebSocketUrl {
        original: url,
        http_equivalent,
        request_target,
        host_header,
        uri,
        secure,
    })
}

pub(crate) fn build_handshake_request(
    url: WebSocketUrl,
    default_headers: &Headers,
    user_headers: &Headers,
    subprotocols: &[String],
    cookie_header: Option<String>,
) -> WebSocketResult<HandshakeRequest> {
    let protocols = validate_subprotocols(&url.original, subprotocols)?;
    let key = generate_key(&url.original)?;
    let mut headers = Headers::new();

    copy_non_critical_headers(default_headers, &mut headers);
    copy_non_critical_headers(user_headers, &mut headers);

    if !headers.contains("host") {
        headers.insert("Host", url.host_header.clone());
    }

    if !headers.contains("cookie") {
        if let Some(cookie_header) = cookie_header {
            headers.insert("Cookie", cookie_header);
        }
    }

    headers.remove("upgrade");
    headers.remove("connection");
    headers.remove("sec-websocket-key");
    headers.remove("sec-websocket-version");
    headers.remove("sec-websocket-protocol");
    headers.remove("sec-websocket-extensions");

    headers.insert("Upgrade", "websocket");
    headers.insert("Connection", "Upgrade");
    headers.insert("Sec-WebSocket-Key", key.clone());
    headers.insert("Sec-WebSocket-Version", "13");
    if !protocols.is_empty() {
        headers.insert("Sec-WebSocket-Protocol", protocols.join(", "));
    }

    Ok(HandshakeRequest { url, headers, key })
}

pub(crate) async fn perform_handshake(
    mut stream: MaybeHttpsStream,
    request: &HandshakeRequest,
    offered_protocols: &[String],
    timeout: Option<Duration>,
) -> WebSocketResult<HandshakeResponse> {
    let request_bytes = serialize_request(request);
    let fut = async {
        stream
            .write_all(&request_bytes)
            .await
            .map_err(|err| WebSocketError::io(&request.url.original, err))?;
        stream
            .flush()
            .await
            .map_err(|err| WebSocketError::io(&request.url.original, err))?;

        let (headers, buffered) = read_response_headers(&request.url.original, &mut stream).await?;
        validate_response(
            &request.url.original,
            &headers,
            &request.key,
            offered_protocols,
        )?;
        let protocol = headers
            .get("sec-websocket-protocol")
            .map(|value| value.trim().to_string());

        Ok(HandshakeResponse {
            stream,
            headers,
            buffered,
            protocol,
        })
    };

    match timeout {
        Some(duration) => {
            tokio_timeout(duration, fut)
                .await
                .map_err(|_| WebSocketError::Timeout {
                    url: request.url.original.to_string(),
                    operation: format!("handshake after {:?}", duration),
                })?
        }
        None => fut.await,
    }
}

pub(crate) fn expected_accept(key: &str) -> String {
    let mut bytes = Vec::with_capacity(key.len() + ACCEPT_GUID.len());
    bytes.extend_from_slice(key.as_bytes());
    bytes.extend_from_slice(ACCEPT_GUID.as_bytes());
    let digest = boring::sha::sha1(&bytes);
    base64::engine::general_purpose::STANDARD.encode(digest)
}

fn serialize_request(request: &HandshakeRequest) -> Vec<u8> {
    let mut bytes = Vec::new();
    bytes.extend_from_slice(format!("GET {} HTTP/1.1\r\n", request.url.request_target).as_bytes());
    for (name, value) in request.headers.iter_ordered() {
        bytes.extend_from_slice(name.as_bytes());
        bytes.extend_from_slice(b": ");
        bytes.extend_from_slice(value.as_bytes());
        bytes.extend_from_slice(b"\r\n");
    }
    bytes.extend_from_slice(b"\r\n");
    bytes
}

async fn read_response_headers(
    url: &Url,
    stream: &mut MaybeHttpsStream,
) -> WebSocketResult<(Headers, Bytes)> {
    let mut buffer = Vec::with_capacity(4096);
    let mut scratch = [0u8; 1024];

    loop {
        if let Some(end) = find_header_end(&buffer) {
            let remainder = buffer.split_off(end + 4);
            let headers = parse_response(url, &buffer[..end + 4])?;
            return Ok((headers, Bytes::from(remainder)));
        }

        if buffer.len() >= MAX_HANDSHAKE_BYTES {
            return Err(WebSocketError::protocol(
                url,
                "WebSocket handshake response exceeded 65536 bytes",
            ));
        }

        let read = stream
            .read(&mut scratch)
            .await
            .map_err(|err| WebSocketError::io(url, err))?;
        if read == 0 {
            return Err(WebSocketError::protocol(
                url,
                "connection closed before WebSocket handshake completed",
            ));
        }
        buffer.extend_from_slice(&scratch[..read]);
    }
}

fn parse_response(url: &Url, bytes: &[u8]) -> WebSocketResult<Headers> {
    let mut header_storage = [httparse::EMPTY_HEADER; 96];
    let mut response = httparse::Response::new(&mut header_storage);
    let status = response.parse(bytes).map_err(|err| {
        WebSocketError::protocol(url, format!("invalid handshake response: {}", err))
    })?;

    if !status.is_complete() {
        return Err(WebSocketError::protocol(
            url,
            "incomplete handshake response",
        ));
    }

    if response.code != Some(101) {
        return Err(WebSocketError::InvalidStatus {
            url: url.to_string(),
            status: response.code.unwrap_or(0),
        });
    }

    let mut headers = Headers::new();
    for header in response.headers.iter() {
        let value = std::str::from_utf8(header.value)
            .map_err(|_| WebSocketError::protocol(url, "handshake response header is not UTF-8"))?;
        headers.append(header.name.to_string(), value.to_string());
    }

    Ok(headers)
}

fn validate_response(
    url: &Url,
    headers: &Headers,
    key: &str,
    offered_protocols: &[String],
) -> WebSocketResult<()> {
    let upgrade = headers
        .get("upgrade")
        .ok_or_else(|| WebSocketError::protocol(url, "missing Upgrade header"))?;
    if !contains_token(upgrade, "websocket") {
        return Err(WebSocketError::protocol(url, "invalid Upgrade header"));
    }

    let connection = headers
        .get("connection")
        .ok_or_else(|| WebSocketError::protocol(url, "missing Connection header"))?;
    if !contains_token(connection, "upgrade") {
        return Err(WebSocketError::protocol(
            url,
            "Connection header does not contain Upgrade",
        ));
    }

    let accept =
        headers
            .get("sec-websocket-accept")
            .ok_or_else(|| WebSocketError::InvalidAccept {
                url: url.to_string(),
            })?;
    if accept.trim() != expected_accept(key) {
        return Err(WebSocketError::InvalidAccept {
            url: url.to_string(),
        });
    }

    if headers.contains("sec-websocket-extensions") {
        return Err(WebSocketError::UnexpectedExtension {
            url: url.to_string(),
        });
    }

    if let Some(protocol) = headers.get("sec-websocket-protocol") {
        let protocol = protocol.trim();
        if !offered_protocols.iter().any(|offered| offered == protocol) {
            return Err(WebSocketError::UnexpectedSubprotocol {
                url: url.to_string(),
            });
        }
    }

    Ok(())
}

fn validate_subprotocols(url: &Url, values: &[String]) -> WebSocketResult<Vec<String>> {
    let mut seen = Vec::<String>::new();
    for value in values {
        let value = value.trim();
        if value.is_empty() || !is_token(value) {
            return Err(WebSocketError::protocol(
                url,
                "WebSocket subprotocols must be non-empty RFC token values",
            ));
        }
        if seen.iter().any(|existing| existing == value) {
            return Err(WebSocketError::protocol(
                url,
                "WebSocket subprotocols must be unique",
            ));
        }
        seen.push(value.to_string());
    }
    Ok(seen)
}

fn copy_non_critical_headers(source: &Headers, target: &mut Headers) {
    for (name, value) in source.iter_ordered() {
        if !is_websocket_controlled_header(name) {
            target.append(name.to_string(), value.to_string());
        }
    }
}

fn is_websocket_controlled_header(name: &str) -> bool {
    matches!(
        name.to_ascii_lowercase().as_str(),
        "upgrade"
            | "connection"
            | "sec-websocket-key"
            | "sec-websocket-version"
            | "sec-websocket-protocol"
            | "sec-websocket-extensions"
    )
}

fn generate_key(url: &Url) -> WebSocketResult<String> {
    let mut bytes = [0u8; 16];
    getrandom::fill(&mut bytes)
        .map_err(|err| WebSocketError::protocol(url, format!("failed to generate key: {}", err)))?;
    Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
}

fn origin_form_target(url: &Url) -> String {
    let mut target = url.path().to_string();
    if target.is_empty() {
        target.push('/');
    }
    if let Some(query) = url.query() {
        target.push('?');
        target.push_str(query);
    }
    target
}

fn host_header(url: &Url) -> String {
    let host = match url.host() {
        Some(Host::Ipv6(addr)) => format!("[{}]", addr),
        Some(host) => host.to_string(),
        None => "localhost".to_string(),
    };
    match url.port() {
        Some(port) => format!("{}:{}", host, port),
        None => host,
    }
}

fn contains_token(value: &str, token: &str) -> bool {
    value
        .split(',')
        .any(|part| part.trim().eq_ignore_ascii_case(token))
}

fn is_token(value: &str) -> bool {
    value.bytes().all(|byte| {
        matches!(
            byte,
            b'!' | b'#'
                | b'$'
                | b'%'
                | b'&'
                | b'\''
                | b'*'
                | b'+'
                | b'-'
                | b'.'
                | b'^'
                | b'_'
                | b'`'
                | b'|'
                | b'~'
                | b'0'..=b'9'
                | b'a'..=b'z'
                | b'A'..=b'Z'
        )
    })
}

fn find_header_end(buffer: &[u8]) -> Option<usize> {
    buffer.windows(4).position(|window| window == b"\r\n\r\n")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn host_header_wraps_ipv6_literals_with_brackets() {
        let url = Url::parse("ws://[::1]:9443/socket").unwrap();
        let mapped = map_websocket_url(url).unwrap();

        assert_eq!(mapped.host_header, "[::1]:9443");
    }
}