rama-http-types 0.3.0-rc1

rama http type defintions and high level utilities
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Ja4H implementation for Rama (in Rust).
//!
//! JA4H is part of the Ja4+ is copyrighted
//! and licensed by FoxIO. See license information below:
//!
//! > Copyright 2023 AOL Inc. All rights reserved.
//! > Portions Copyright 2023 FoxIO
//! >
//! > SPDX-License-Identifier: FoxIO License 1.1
//! >
//! > This software requires a license to use. See
//! > - <https://github.com/FoxIO-LLC/ja4#licensing>
//! > - <https://github.com/FoxIO-LLC/ja4/blob/main/License%20FAQ.md>

use itertools::Itertools as _;
use std::fmt::{self, Write};

use crate::{
    Method, Version,
    header::{ACCEPT_LANGUAGE, COOKIE, REFERER},
};

use crate::fingerprint::{HttpRequestInput, HttpRequestProvider};

#[derive(Clone)]
/// Input data for a "ja4h" hash.
/// or displaying it.
///
/// Computed using [`Ja4H::compute`].
pub struct Ja4H {
    req_method: HttpRequestMethod,
    version: HttpVersion,
    has_cookie_header: bool,
    has_referer_header: bool,
    language: Option<String>,
    headers: Vec<String>,
    cookie_pairs: Option<Vec<(String, Option<String>)>>,
}

impl Ja4H {
    /// Compute the [`Ja4H`] (hash).
    ///
    /// As specified by <https://blog.foxio.io/ja4%2B-network-fingerprinting>
    /// and reference implementations found at <https://github.com/FoxIO-LLC/ja4>.
    pub fn compute(req: impl HttpRequestProvider) -> Result<Self, Ja4HComputeError> {
        let HttpRequestInput {
            header_map,
            http_method,
            version,
        } = req.http_request_input();

        let req_method = HttpRequestMethod::from(http_method);
        let version: HttpVersion = version.try_into()?;

        let mut has_cookie_header = false;
        let mut has_referer_header = false;
        let mut language = None;

        let mut cookie_pairs = None;

        let headers: Vec<_> = header_map
            .into_ordered_iter()
            .filter_map(|(name, value)| {
                let header_name = &name;
                if header_name == ACCEPT_LANGUAGE {
                    language = std::str::from_utf8(value.as_bytes())
                        .ok()
                        .and_then(|s| s.split(',').next())
                        .and_then(|s| s.split(';').next())
                        .map(|s| {
                            s.trim()
                                .chars()
                                .filter(|c| c.is_alphabetic())
                                .take(4)
                                .map(|c| c.to_ascii_lowercase())
                                .collect()
                        });
                    Some(name.to_string())
                } else if header_name == COOKIE {
                    has_cookie_header = true;
                    // split on ; and then trim to handle different spacing, fixing the sorting issue
                    if let Ok(s) = std::str::from_utf8(value.as_bytes()) {
                        let pairs = cookie_pairs.get_or_insert_with(Vec::default);
                        pairs.extend(s.split(';').map(|cookie| {
                            let cookie = cookie.trim();
                            match cookie.split_once('=') {
                                None => (cookie.to_owned(), None),
                                Some((name, value)) => (name.to_owned(), Some(value.to_owned())),
                            }
                        }));
                        pairs.sort_unstable();
                    }
                    None
                } else if header_name == REFERER {
                    has_referer_header = true;
                    None
                } else {
                    Some(name.to_string())
                }
            })
            .collect();
        if headers.is_empty() {
            return Err(Ja4HComputeError::MissingHeaders);
        }

        Ok(Self {
            req_method,
            version,
            has_cookie_header,
            has_referer_header,
            language,
            headers,
            cookie_pairs,
        })
    }

    #[inline]
    #[must_use]
    pub fn to_human_string(&self) -> String {
        format!("{self:?}")
    }

    fn fmt_as(&self, f: &mut fmt::Formatter<'_>, hash_chunks: bool) -> fmt::Result {
        let req_method = &self.req_method;
        let version = self.version;
        let cookie_marker = if self.has_cookie_header { 'c' } else { 'n' };
        let referer_marker = if self.has_referer_header { 'r' } else { 'n' };
        let nr_headers = 99.min(self.headers.len());

        // application fingerprint: part I
        write!(
            f,
            "{req_method}{version}{cookie_marker}{referer_marker}{nr_headers:02}"
        )?;
        match self.language.as_deref() {
            Some(s) => format_str_truncate(4, s, f)?,
            None => write!(f, "0000")?,
        }

        // application fingerprint: part II
        debug_assert!(
            !self.headers.is_empty(),
            "validated in Ja4H::compute constructor"
        );
        let headers = self.headers.iter().join(",");

        // website cookie fingerprint
        let cookie_names = joined_cookie_names(self.cookie_pairs.iter().flatten());

        // user cookie fingerprint
        let cookie_pairs = joined_cookie_pairs(self.cookie_pairs.iter().flatten());

        if hash_chunks {
            write!(
                f,
                "_{}_{}_{}",
                hash12(headers),
                hash12(cookie_names),
                hash12(cookie_pairs),
            )
        } else {
            write!(f, "_{headers}_{cookie_names}_{cookie_pairs}")
        }
    }
}

impl fmt::Display for Ja4H {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_as(f, true)
    }
}

impl fmt::Debug for Ja4H {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_as(f, false)
    }
}

fn format_str_truncate(n: usize, s: &str, f: &mut fmt::Formatter) -> fmt::Result {
    let len = s.chars().count();
    if len > n {
        f.write_str(&s[..n])?;
    } else {
        f.write_str(s)?;
        for _ in 0..(n - len) {
            f.write_char('0')?;
        }
    }
    Ok(())
}

fn joined_cookie_names<'a, I>(cookie_pairs: I) -> String
where
    I: IntoIterator<Item = &'a (String, Option<String>)>,
{
    // Write into a single growing buffer; avoids one per-element `to_owned`
    // allocation in the JA4H hot path.
    let mut out = String::new();
    for (name, _) in cookie_pairs {
        debug_assert!(!name.is_empty());
        if !out.is_empty() {
            out.push(',');
        }
        out.push_str(name);
    }
    out
}

fn joined_cookie_pairs<'a, I>(cookie_pairs: I) -> String
where
    I: IntoIterator<Item = &'a (String, Option<String>)>,
{
    // Same rationale as `joined_cookie_names` — we previously allocated a
    // fresh `String` per cookie via `format!("{name}={value}")` before the
    // final join. Now everything is appended into a single buffer.
    let mut out = String::new();
    for (name, value) in cookie_pairs {
        debug_assert!(!name.is_empty());
        if !out.is_empty() {
            out.push(',');
        }
        out.push_str(name);
        if let Some(value) = value {
            out.push('=');
            out.push_str(value);
        }
    }
    out
}

#[derive(Debug, Clone)]
/// error identifying a failure in [`Ja4H::compute`]
pub enum Ja4HComputeError {
    /// triggered when the request's version is not recognised
    InvalidHttpVersion,
    /// no headers detected
    MissingHeaders,
}

impl fmt::Display for Ja4HComputeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidHttpVersion => {
                write!(f, "Ja4H Compute Error: unexpected http request version")
            }
            Self::MissingHeaders => {
                write!(f, "Ja4H Compute Error: missing http headers")
            }
        }
    }
}

impl std::error::Error for Ja4HComputeError {}

use super::hash12;

#[derive(Debug, Clone, PartialEq)]
struct HttpRequestMethod(Method);

impl fmt::Display for HttpRequestMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let code = match self.0 {
            Method::CONNECT => "co",
            Method::DELETE => "de",
            Method::GET => "ge",
            Method::HEAD => "he",
            Method::OPTIONS => "op",
            Method::PATCH => "pa",
            Method::POST => "po",
            Method::PUT => "pu",
            Method::TRACE => "tr",
            _ => {
                let mut c = self.0.as_str().chars();
                return write!(
                    f,
                    "{}{}",
                    c.next().map(|c| c.to_ascii_lowercase()).unwrap_or('0'),
                    c.next().map(|c| c.to_ascii_lowercase()).unwrap_or('0'),
                );
            }
        };
        f.write_str(code)
    }
}

impl From<Method> for HttpRequestMethod {
    #[inline]
    fn from(value: Method) -> Self {
        Self(value)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
enum HttpVersion {
    Http1_0,
    Http1_1,
    Http2,
    Http3,
}

impl TryFrom<Version> for HttpVersion {
    type Error = Ja4HComputeError;

    fn try_from(value: Version) -> Result<Self, Self::Error> {
        match value {
            Version::HTTP_10 => Ok(Self::Http1_0),
            Version::HTTP_11 => Ok(Self::Http1_1),
            Version::HTTP_2 => Ok(Self::Http2),
            Version::HTTP_3 => Ok(Self::Http3),
            _ => Err(Ja4HComputeError::InvalidHttpVersion),
        }
    }
}

impl fmt::Display for HttpVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let code = match self {
            Self::Http1_0 => "10",
            Self::Http1_1 => "11",
            Self::Http2 => "20",
            Self::Http3 => "30",
        };
        f.write_str(code)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{HeaderMap, Request};

    #[derive(Debug)]
    struct TestCase {
        description: &'static str,
        expected_ja4h_str_debug: &'static str,
        expected_ja4h_str_hash: &'static str,
        req: Request<()>,
    }

    macro_rules! test_case {
        (
            description: $description:literal,
            debug_str: $expected_ja4h_str_debug:literal,
            hash_str: $expected_ja4h_str_hash:literal,
            version: $version:expr,
            method: $method:expr,
            headers: {$(
                $header_name:literal: $header_value:literal,
            )+}
            $(,)?
        ) => {
            {
                let mut map = HeaderMap::default();
                $(
                    map.try_append(
                        $header_name,
                        crate::HeaderValue::from_str($header_value).unwrap()
                    ).unwrap();
                )+

                let (mut parts, body) = Request::new(()).into_parts();
                parts.method = $method;
                parts.version = $version;
                parts.uri = "/".parse::<rama_net::uri::Uri>().unwrap();
                parts.headers = map;

                let req = Request::from_parts(parts, body);

                TestCase {
                    description: $description,
                    expected_ja4h_str_debug: $expected_ja4h_str_debug,
                    expected_ja4h_str_hash: $expected_ja4h_str_hash,
                    req,
                }
            }
        };
    }

    #[test]
    fn test_ja4h_compute() {
        let test_cases = [
            test_case!(
                description: "rust_ja4_http_test_http_stats_into_out",
                debug_str: "ge11cr11enus_Host,Sec-Ch-Ua,Sec-Ch-Ua-Mobile,User-Agent,Sec-Ch-Ua-Platform,Accept,Sec-Fetch-Site,Sec-Fetch-Mode,Sec-Fetch-Dest,Accept-Encoding,Accept-Language_FastAB,_dd_s,countryCode,geoData,sato,stateCode,umto,usprivacy_FastAB=0=6859,1=8174,2=4183,3=3319,4=3917,5=2557,6=4259,7=6070,8=0804,9=6453,10=1942,11=4435,12=4143,13=9445,14=6957,15=8682,16=1885,17=1825,18=3760,19=0929,_dd_s=logs=1&id=b5c2d770-eaba-4847-8202-390c4552ff9a&created=1686159462724&expire=1686160422726,countryCode=US,geoData=purcellville|VA|20132|US|NA|-400|broadband|39.160|-77.700|511,sato=1,stateCode=VA,umto=1,usprivacy=1---",
                hash_str: "ge11cr11enus_974ebe531c03_0f2659b474bf_161698816dab",
                version: Version::HTTP_11,
                method: Method::GET,
                headers: {
                    "Host": "www.cnn.com",
                    "Cookie": "FastAB=0=6859,1=8174,2=4183,3=3319,4=3917,5=2557,6=4259,7=6070,8=0804,9=6453,10=1942,11=4435,12=4143,13=9445,14=6957,15=8682,16=1885,17=1825,18=3760,19=0929; sato=1; countryCode=US; stateCode=VA; geoData=purcellville|VA|20132|US|NA|-400|broadband|39.160|-77.700|511; usprivacy=1---; umto=1; _dd_s=logs=1&id=b5c2d770-eaba-4847-8202-390c4552ff9a&created=1686159462724&expire=1686160422726",
                    "Sec-Ch-Ua": "",
                    "Sec-Ch-Ua-Mobile": "?0",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.110 Safari/537.36",
                    "Sec-Ch-Ua-Platform": "\"\"",
                    "Accept": "*/*",
                    "Sec-Fetch-Site": "same-origin",
                    "Sec-Fetch-Mode": "cors",
                    "Sec-Fetch-Dest": "empty", // should not have duplicated headers
                    "Referer": "https://www.cnn.com/",
                    "Accept-Encoding": "gzip, deflate",
                    "Accept-Language": "en-US,en;q=0.9",
                },
            ),
            test_case!(
                description: "wireshark_ja4_firefox_133_macos_fp.ramaproxy.org_http11_plain",
                debug_str: "ge11cr09enus_Host,User-Agent,Accept,Accept-Language,Accept-Encoding,Connection,DNT,Sec-GPC,Priority_rama-fp_rama-fp=ready",
                hash_str: "ge11cr09enus_df50b14dec48_d733b88e2d70_774e52af4cfe",
                version: Version::HTTP_11,
                method: Method::GET,
                headers: {
                    "Host": "h1.fp.ramaproxy.org",
                    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:133.0) Gecko/20100101 Firefox/133.0",
                    "Accept": "text/css,*/*;q=0.1",
                    "Accept-Language": "en-US,en;q=0.5",
                    "Accept-Encoding": "gzip, deflate",
                    "Connection": "keep-alive",
                    "Referer": "http://h1.fp.ramaproxy.org/consent",
                    "Cookie": "rama-fp=ready",
                    "DNT": "1",
                    "Sec-GPC": "1",
                    "Priority": "u=2",
                },
            ),
            test_case!(
                description: "curl_ja4h_http2_cookies_different_order",
                debug_str: "ge20cn030000_authorization,user-agent,accept_alpha,sierra,zulu_alpha=bravo,sierra=echo,zulu=tango",
                hash_str: "ge20cn030000_a8ea46949477_7efd8825dc5a_f0c5f5a36bc1",
                version: Version::HTTP_2,
                method: Method::GET,
                headers: {
                    "authorization": "Basic d29yZDp3b3Jk",
                    "user-agent": "curl/7.81.0",
                    "accept": "*/*",
                    "cookie": "sierra=echo;alpha=bravo;zulu=tango",
                },
            ),
        ];
        for test_case in test_cases {
            let ja4h = Ja4H::compute(&test_case.req).expect(test_case.description);
            assert_eq!(
                test_case.expected_ja4h_str_debug,
                format!("{ja4h:?}"),
                "{}",
                test_case.description
            );
            assert_eq!(
                test_case.expected_ja4h_str_hash,
                format!("{ja4h}"),
                "{}",
                test_case.description
            );
        }
    }
}