ja3_rustls/
grease.rs

1/// [RFC8701](https://www.rfc-editor.org/rfc/rfc8701.html) GREASE values
2use crate::utils::rand_in;
3
4/// These values, when interpreted as big-endian u8 tuples, are reserved GREASE values for cipher
5/// suites and Application-Layer Protocol Negotiation (ALPN).
6/// When interpreted as u16, are reserved GREASE values for extensions, named groups,
7/// signature algorithms, and versions:
8pub const GREASE_U16_BE: [u16; 16] = [
9    0x0A0A, 0x1A1A, 0x2A2A, 0x3A3A, 0x4A4A, 0x5A5A, 0x6A6A, 0x7A7A, 0x8A8A, 0x9A9A, 0xAAAA, 0xBABA,
10    0xCACA, 0xDADA, 0xEAEA, 0xFAFA,
11];
12/// These values are reserved as GREASE values for PskKeyExchangeModes:
13pub const GREASE_U8: [u8; 8] = [0x0B, 0x2A, 0x49, 0x68, 0x87, 0xA6, 0xC5, 0xE4];
14
15#[inline(always)]
16pub fn is_grease_u16_be(v: u16) -> bool {
17    v & 0x0F0F == 0x0A0A
18}
19
20#[inline(always)]
21pub fn is_grease_u8(v: u8) -> bool {
22    GREASE_U8.iter().any(|&vv| v == vv)
23}
24
25/// Generate a random GREASE value.
26///
27/// It is based on an insecure RNG unless the `rand` crate feature is activated.
28pub fn grease_u16_be() -> u16 {
29    GREASE_U16_BE[rand_in::<0, 16>()]
30}
31
32/// Generate a random GREASE value.
33///
34/// It is based on an insecure RNG unless the `rand` crate feature is activated.
35pub fn grease_u8() -> u8 {
36    GREASE_U8[rand_in::<0, 8>()]
37}
38
39/// Try to rewrite a GREASE value with a randomly generated one iff it is actally GREASE.
40/// Otherwise, the value is retuned as is.
41///
42/// It is based on an insecure RNG unless the `rand` crate feature is activated.
43#[inline(always)]
44pub fn try_regrease_u16_be(v: u16) -> u16 {
45    if is_grease_u16_be(v) {
46        grease_u16_be()
47    } else {
48        v
49    }
50}
51
52/// Try to rewrite a GREASE value with a randomly generated one iff it is actally GREASE.
53/// Otherwise, the value is retuned as is.
54///
55/// It is based on an insecure RNG unless the `rand` crate feature is activated.
56#[inline(always)]
57pub fn try_regrease_u8(v: u8) -> u8 {
58    if is_grease_u8(v) {
59        grease_u8()
60    } else {
61        v
62    }
63}