Skip to main content

turnloop_tls/
channel_binding.rs

1//! RFC 5929 certificate binding. This reads only the outer certificate envelope
2//! and signature AlgorithmIdentifier; certificate verification belongs to rustls.
3#[cfg(feature = "ring")]
4use ring::digest::{self, Digest};
5
6/// The hash RFC 5929 §4.1 selects for a certificate's tls-server-end-point.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum EndPointHash {
9    Sha256,
10    Sha384,
11    Sha512,
12}
13use EndPointHash::{Sha256, Sha384, Sha512};
14
15/// Hash a verified server leaf's DER for RFC 5929 §4.1 tls-server-end-point.
16/// RSA/ECDSA SHA-256/384/512 and RSA-PSS parameters are supported. MD5/SHA-1
17/// signatures use SHA-256. Unknown algorithms (including Ed25519), malformed DER
18/// and undefined bindings return `None`. This helper does not verify certificates
19/// and performs no allocation; call it after successful TLS authentication.
20#[cfg(feature = "ring")]
21pub fn tls_server_end_point(certificate: &[u8]) -> Option<Digest> {
22    let algorithm = match tls_server_end_point_hash(certificate)? {
23        Sha256 => &digest::SHA256,
24        Sha384 => &digest::SHA384,
25        Sha512 => &digest::SHA512,
26    };
27    Some(digest::digest(algorithm, certificate))
28}
29
30/// The hash `tls_server_end_point` would apply to this leaf's DER, for hosts
31/// that hash with their own crypto provider. `None` in exactly the same cases.
32pub fn tls_server_end_point_hash(certificate: &[u8]) -> Option<EndPointHash> {
33    signature_hash(certificate)
34}
35
36const RSA: &[u8] = b"\x2a\x86\x48\x86\xf7\x0d\x01\x01";
37const ECDSA: &[u8] = b"\x2a\x86\x48\xce\x3d\x04\x03";
38const SHA2: &[u8] = b"\x60\x86\x48\x01\x65\x03\x04\x02";
39const SHA1: &[u8] = b"\x2b\x0e\x03\x02\x1a";
40
41/// Definite, minimally encoded DER lengths only. Each sub-reader is bounded to
42/// its parent value; no offsets, recursion or heap storage escape that slice.
43struct Der<'a>(&'a [u8]);
44impl<'a> Der<'a> {
45    fn byte(&mut self) -> Option<u8> {
46        let (&first, rest) = self.0.split_first()?;
47        self.0 = rest;
48        Some(first)
49    }
50    fn value(&mut self, tag: u8) -> Option<&'a [u8]> {
51        if self.byte()? != tag {
52            return None;
53        }
54        let first = self.byte()?;
55        let len = if first < 128 {
56            first as usize
57        } else {
58            let count = (first & 127) as usize;
59            if count == 0 || count > size_of::<usize>() || self.0.first() == Some(&0) {
60                return None;
61            }
62            let mut len = 0usize;
63            for _ in 0..count {
64                len = len.checked_mul(256)?.checked_add(self.byte()? as usize)?;
65            }
66            if len < 128 {
67                return None;
68            }
69            len
70        };
71        let (value, rest) = self.0.split_at_checked(len)?;
72        self.0 = rest;
73        Some(value)
74    }
75    fn end(self) -> Option<()> {
76        self.0.is_empty().then_some(())
77    }
78    fn null_or_absent(self) -> Option<()> {
79        matches!(self.0, [] | [5, 0]).then_some(())
80    }
81    fn integer(&mut self) -> Option<usize> {
82        let value = self.value(2)?;
83        let first = *value.first()?;
84        if first & 128 != 0 || (value.len() > 1 && first == 0 && value[1] & 128 == 0) {
85            return None;
86        }
87        value
88            .iter()
89            .try_fold(0usize, |n, b| n.checked_mul(256)?.checked_add(*b as usize))
90    }
91}
92
93fn signature_hash(certificate: &[u8]) -> Option<EndPointHash> {
94    let mut der = Der(certificate);
95    let mut cert = Der(der.value(0x30)?);
96    der.end()?;
97    if cert.value(0x30)?.is_empty() {
98        // TBSCertificate is opaque to this reader.
99        return None;
100    }
101    let mut alg = Der(cert.value(0x30)?);
102    let oid = alg.value(6)?;
103    // Certificate signatures are octet-aligned BIT STRINGs, not empty strings.
104    let signature = cert.value(3)?;
105    if signature.len() < 2 || signature[0] != 0 {
106        return None;
107    }
108    cert.end()?;
109    if let Some(suffix) = oid.strip_prefix(RSA) {
110        if suffix == [10] {
111            // id-RSASSA-PSS
112            let params = alg.value(0x30)?;
113            alg.end()?;
114            return pss_hash(params);
115        }
116        alg.null_or_absent()?;
117        match suffix {
118            [4 | 5 | 11] => Some(Sha256), // MD5, SHA-1, SHA-256
119            [12] => Some(Sha384),
120            [13] => Some(Sha512),
121            _ => None,
122        }
123    } else if let Some(suffix) = oid.strip_prefix(ECDSA) {
124        alg.end()?; // ECDSA parameters MUST be absent.
125        match suffix {
126            [2] => Some(Sha256),
127            [3] => Some(Sha384),
128            [4] => Some(Sha512),
129            _ => None,
130        }
131    } else {
132        None
133    }
134}
135
136fn hash_identifier(bytes: &[u8]) -> Option<EndPointHash> {
137    let mut der = Der(bytes);
138    let mut alg = Der(der.value(0x30)?);
139    der.end()?;
140    let oid = alg.value(6)?;
141    alg.null_or_absent()?;
142    if oid == SHA1 {
143        return Some(Sha256);
144    }
145    match oid.strip_prefix(SHA2)? {
146        [1] => Some(Sha256),
147        [2] => Some(Sha384),
148        [3] => Some(Sha512),
149        _ => None,
150    }
151}
152
153fn pss_hash(parameters: &[u8]) -> Option<EndPointHash> {
154    // RFC 4055: absent hashAlgorithm defaults to SHA-1 (RFC 5929 -> SHA-256).
155    // MGF1's hash is validated separately; it does not select the binding hash.
156    let mut hash = Sha256;
157    let mut params = Der(parameters);
158    let mut previous = 0;
159    while let Some(&tag) = params.0.first() {
160        if !(0xa0..=0xa3).contains(&tag) || tag <= previous {
161            return None;
162        }
163        previous = tag;
164        let field = params.value(tag)?;
165        match tag {
166            0xa0 => hash = hash_identifier(field)?,
167            0xa1 => {
168                let mut der = Der(field);
169                let mut mgf = Der(der.value(0x30)?);
170                der.end()?;
171                if mgf.value(6)?.strip_prefix(RSA)? != [8] {
172                    // id-mgf1
173                    return None;
174                }
175                hash_identifier(mgf.0)?;
176            }
177            0xa2 | 0xa3 => {
178                let mut der = Der(field);
179                let integer = der.integer()?;
180                der.end()?;
181                if tag == 0xa3 && integer != 1 {
182                    return None;
183                }
184            }
185            _ => return None,
186        }
187    }
188    Some(hash)
189}