Skip to main content

rtci_dtls/signature_hash_algorithm/
mod.rs

1#[cfg(test)]
2mod signature_hash_algorithm_test;
3
4use std::fmt;
5
6use crate::crypto::*;
7use shared::error::*;
8
9// HashAlgorithm is used to indicate the hash algorithm used
10// https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-18
11// Supported hash hash algorithms
12#[derive(Copy, Clone, Debug, PartialEq, Eq)]
13/// The hash algorithms that may be paired with a signature algorithm.
14#[non_exhaustive]
15pub enum HashAlgorithm {
16    /// `MD2` (`0`).
17    Md2 = 0, // Blacklisted
18    /// `MD5` (`1`).
19    Md5 = 1, // Blacklisted
20    /// `SHA1` (`2`).
21    Sha1 = 2, // Blacklisted
22    /// `SHA224` (`3`).
23    Sha224 = 3,
24    /// `SHA256` (`4`).
25    Sha256 = 4,
26    /// `SHA384` (`5`).
27    Sha384 = 5,
28    /// `SHA512` (`6`).
29    Sha512 = 6,
30    /// `Intrinsic` (`8`): the hash is part of the signature algorithm. The value of Ed25519
31    /// (`0x0807`) and of the RSASSA-PSS schemes (`0x0804` to `0x0806`), whose first byte this is.
32    Ed25519 = 8,
33    /// An algorithm this crate does not implement.
34    Unsupported,
35}
36
37impl From<u8> for HashAlgorithm {
38    fn from(val: u8) -> Self {
39        match val {
40            0 => HashAlgorithm::Md2,
41            1 => HashAlgorithm::Md5,
42            2 => HashAlgorithm::Sha1,
43            3 => HashAlgorithm::Sha224,
44            4 => HashAlgorithm::Sha256,
45            5 => HashAlgorithm::Sha384,
46            6 => HashAlgorithm::Sha512,
47            8 => HashAlgorithm::Ed25519,
48            _ => HashAlgorithm::Unsupported,
49        }
50    }
51}
52
53impl fmt::Display for HashAlgorithm {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match *self {
56            HashAlgorithm::Md2 => write!(f, "md2"),
57            HashAlgorithm::Md5 => write!(f, "md5"), // [RFC3279]
58            HashAlgorithm::Sha1 => write!(f, "sha-1"), // [RFC3279]
59            HashAlgorithm::Sha224 => write!(f, "sha-224"), // [RFC4055]
60            HashAlgorithm::Sha256 => write!(f, "sha-256"), // [RFC4055]
61            HashAlgorithm::Sha384 => write!(f, "sha-384"), // [RFC4055]
62            HashAlgorithm::Sha512 => write!(f, "sha-512"), // [RFC4055]
63            HashAlgorithm::Ed25519 => write!(f, "null"), // [RFC4055]
64            _ => write!(f, "unknown or unsupported hash algorithm"),
65        }
66    }
67}
68
69impl HashAlgorithm {
70    pub(crate) fn insecure(&self) -> bool {
71        matches!(
72            *self,
73            HashAlgorithm::Md2 | HashAlgorithm::Md5 | HashAlgorithm::Sha1
74        )
75    }
76
77    pub(crate) fn invalid(&self) -> bool {
78        matches!(*self, HashAlgorithm::Md2)
79    }
80}
81
82// https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-16
83#[derive(Copy, Clone, Debug, PartialEq, Eq)]
84/// The signature algorithms this crate can verify and produce.
85#[non_exhaustive]
86pub enum SignatureAlgorithm {
87    /// `RSA` (`1`).
88    Rsa = 1,
89    /// `ECDSA` (`3`).
90    Ecdsa = 3,
91    /// `ED25519` (`7`).
92    Ed25519 = 7,
93    /// `rsa_pss_rsae_sha256` (`0x0804`, RFC 8446 section 4.2.3): RSASSA-PSS with SHA-256
94    /// over a key with the rsaEncryption OID. Paired with the hash value `8` (intrinsic).
95    RsaPssRsaeSha256 = 4,
96    /// `rsa_pss_rsae_sha384` (`0x0805`).
97    RsaPssRsaeSha384 = 5,
98    /// `rsa_pss_rsae_sha512` (`0x0806`).
99    RsaPssRsaeSha512 = 6,
100    /// An algorithm this crate does not implement.
101    Unsupported = 0xff,
102}
103
104impl SignatureAlgorithm {
105    /// Whether the signature is made with an RSA key: PKCS#1 v1.5 or RSASSA-PSS.
106    pub fn is_rsa(self) -> bool {
107        matches!(
108            self,
109            Self::Rsa | Self::RsaPssRsaeSha256 | Self::RsaPssRsaeSha384 | Self::RsaPssRsaeSha512
110        )
111    }
112}
113
114impl From<u8> for SignatureAlgorithm {
115    fn from(val: u8) -> Self {
116        match val {
117            1 => SignatureAlgorithm::Rsa,
118            3 => SignatureAlgorithm::Ecdsa,
119            7 => SignatureAlgorithm::Ed25519,
120            4 => SignatureAlgorithm::RsaPssRsaeSha256,
121            5 => SignatureAlgorithm::RsaPssRsaeSha384,
122            6 => SignatureAlgorithm::RsaPssRsaeSha512,
123            _ => SignatureAlgorithm::Unsupported,
124        }
125    }
126}
127
128#[derive(Copy, Clone, Debug, PartialEq, Eq)]
129/// A signature and hash pair, as negotiated for certificate verification.
130pub struct SignatureHashAlgorithm {
131    /// The hash to digest the signed data with.
132    pub hash: HashAlgorithm,
133    /// The signature algorithm to apply.
134    pub signature: SignatureAlgorithm,
135}
136
137impl SignatureHashAlgorithm {
138    /// The pair as the 16-bit SignatureScheme of RFC 8446 section 4.2.3: the hash byte, then
139    /// the signature byte.
140    pub fn scheme_code(&self) -> u16 {
141        u16::from_be_bytes([self.hash as u8, self.signature as u8])
142    }
143
144    /// The pair for a 16-bit SignatureScheme.
145    pub fn from_scheme_code(code: u16) -> Self {
146        let [hash, signature] = code.to_be_bytes();
147        Self {
148            hash: hash.into(),
149            signature: signature.into(),
150        }
151    }
152
153    /// Whether the pair may sign a TLS 1.3 CertificateVerify (RFC 8446 section 4.4.3): ECDSA
154    /// with the curve its hash names, Ed25519, or RSASSA-PSS. RSA PKCS#1 v1.5 and SHA-1 may
155    /// not.
156    pub(crate) fn is_tls13_signature(&self) -> bool {
157        matches!(
158            (self.signature, self.hash),
159            (
160                SignatureAlgorithm::Ecdsa,
161                HashAlgorithm::Sha256 | HashAlgorithm::Sha384
162            ) | (
163                SignatureAlgorithm::Ed25519
164                    | SignatureAlgorithm::RsaPssRsaeSha256
165                    | SignatureAlgorithm::RsaPssRsaeSha384
166                    | SignatureAlgorithm::RsaPssRsaeSha512,
167                HashAlgorithm::Ed25519
168            )
169        )
170    }
171
172    pub(crate) fn crypto_scheme(&self) -> Result<crypto::SignatureScheme> {
173        match (self.signature, self.hash) {
174            (SignatureAlgorithm::Ed25519, _) => Ok(crypto::SignatureScheme::Ed25519),
175            (SignatureAlgorithm::RsaPssRsaeSha256, HashAlgorithm::Ed25519) => {
176                Ok(crypto::SignatureScheme::RsaPssSha256)
177            }
178            (SignatureAlgorithm::RsaPssRsaeSha384, HashAlgorithm::Ed25519) => {
179                Ok(crypto::SignatureScheme::RsaPssSha384)
180            }
181            (SignatureAlgorithm::RsaPssRsaeSha512, HashAlgorithm::Ed25519) => {
182                Ok(crypto::SignatureScheme::RsaPssSha512)
183            }
184            (SignatureAlgorithm::Ecdsa, HashAlgorithm::Sha256) => {
185                Ok(crypto::SignatureScheme::EcdsaP256Sha256)
186            }
187            (SignatureAlgorithm::Ecdsa, HashAlgorithm::Sha384) => {
188                Ok(crypto::SignatureScheme::EcdsaP384Sha384)
189            }
190            (SignatureAlgorithm::Rsa, HashAlgorithm::Sha1) => {
191                Ok(crypto::SignatureScheme::RsaPkcs1Sha1)
192            }
193            (SignatureAlgorithm::Rsa, HashAlgorithm::Sha256) => {
194                Ok(crypto::SignatureScheme::RsaPkcs1Sha256)
195            }
196            (SignatureAlgorithm::Rsa, HashAlgorithm::Sha384) => {
197                Ok(crypto::SignatureScheme::RsaPkcs1Sha384)
198            }
199            (SignatureAlgorithm::Rsa, HashAlgorithm::Sha512) => {
200                Ok(crypto::SignatureScheme::RsaPkcs1Sha512)
201            }
202            _ => Err(Error::ErrKeySignatureVerifyUnimplemented),
203        }
204    }
205
206    // is_compatible checks that given private key is compatible with the signature scheme.
207    pub(crate) fn is_compatible(&self, private_key: &CryptoPrivateKey) -> bool {
208        self.crypto_scheme()
209            .is_ok_and(|scheme| private_key.signing_key.supports(scheme))
210    }
211}
212
213pub(crate) fn default_signature_schemes() -> Vec<SignatureHashAlgorithm> {
214    vec![
215        SignatureHashAlgorithm {
216            hash: HashAlgorithm::Sha256,
217            signature: SignatureAlgorithm::Ecdsa,
218        },
219        SignatureHashAlgorithm {
220            hash: HashAlgorithm::Sha384,
221            signature: SignatureAlgorithm::Ecdsa,
222        },
223        SignatureHashAlgorithm {
224            hash: HashAlgorithm::Sha512,
225            signature: SignatureAlgorithm::Ecdsa,
226        },
227        SignatureHashAlgorithm {
228            hash: HashAlgorithm::Sha256,
229            signature: SignatureAlgorithm::Rsa,
230        },
231        SignatureHashAlgorithm {
232            hash: HashAlgorithm::Sha384,
233            signature: SignatureAlgorithm::Rsa,
234        },
235        SignatureHashAlgorithm {
236            hash: HashAlgorithm::Sha512,
237            signature: SignatureAlgorithm::Rsa,
238        },
239        SignatureHashAlgorithm {
240            hash: HashAlgorithm::Ed25519,
241            signature: SignatureAlgorithm::Ed25519,
242        },
243        // RSASSA-PSS (RFC 8446 section 4.2.3), which TLS 1.3 requires of an RSA key and
244        // TLS 1.2 may use. After PKCS#1 v1.5, so that a DTLS 1.2 handshake signs as before
245        // with a peer that lists both.
246        SignatureHashAlgorithm {
247            hash: HashAlgorithm::Ed25519,
248            signature: SignatureAlgorithm::RsaPssRsaeSha256,
249        },
250        SignatureHashAlgorithm {
251            hash: HashAlgorithm::Ed25519,
252            signature: SignatureAlgorithm::RsaPssRsaeSha384,
253        },
254        SignatureHashAlgorithm {
255            hash: HashAlgorithm::Ed25519,
256            signature: SignatureAlgorithm::RsaPssRsaeSha512,
257        },
258    ]
259}
260
261// select Signature Scheme returns most preferred and compatible scheme.
262pub(crate) fn select_signature_scheme(
263    sigs: &[SignatureHashAlgorithm],
264    private_key: &CryptoPrivateKey,
265) -> Result<SignatureHashAlgorithm> {
266    for ss in sigs {
267        if ss.is_compatible(private_key) {
268            return Ok(*ss);
269        }
270    }
271
272    Err(Error::ErrNoAvailableSignatureSchemes)
273}
274
275/// The pairs a client that sends no signature_algorithms extension is taken to accept
276/// (RFC 5246 7.4.1.4.1): SHA-1 with the signature algorithm of the negotiated key exchange.
277pub(crate) fn default_remote_signature_schemes() -> Vec<SignatureHashAlgorithm> {
278    vec![
279        SignatureHashAlgorithm {
280            hash: HashAlgorithm::Sha1,
281            signature: SignatureAlgorithm::Rsa,
282        },
283        SignatureHashAlgorithm {
284            hash: HashAlgorithm::Sha1,
285            signature: SignatureAlgorithm::Ecdsa,
286        },
287    ]
288}
289
290/// The most preferred of `local` (in its order) that the peer lists in `remote` and
291/// `private_key` can sign with: the pair for a ServerKeyExchange (RFC 5246 7.4.3) or a
292/// CertificateVerify (7.4.8).
293pub(crate) fn select_common_signature_scheme(
294    local: &[SignatureHashAlgorithm],
295    remote: &[SignatureHashAlgorithm],
296    private_key: &CryptoPrivateKey,
297) -> Result<SignatureHashAlgorithm> {
298    local
299        .iter()
300        .find(|scheme| remote.contains(scheme) && scheme.is_compatible(private_key))
301        .copied()
302        .ok_or(Error::ErrNoAvailableSignatureSchemes)
303}
304
305/// The certificate type (RFC 5246 7.4.4, RFC 8422 5.5) a certificate with `private_key` is:
306/// rsa_sign for an RSA key, ecdsa_sign for an ECDSA or EdDSA one.
307pub(crate) fn client_certificate_type(
308    private_key: &CryptoPrivateKey,
309) -> crate::client_certificate_type::ClientCertificateType {
310    use crate::client_certificate_type::ClientCertificateType;
311
312    let is_rsa = [
313        HashAlgorithm::Sha1,
314        HashAlgorithm::Sha256,
315        HashAlgorithm::Sha384,
316        HashAlgorithm::Sha512,
317    ]
318    .into_iter()
319    .any(|hash| {
320        SignatureHashAlgorithm {
321            hash,
322            signature: SignatureAlgorithm::Rsa,
323        }
324        .is_compatible(private_key)
325    });
326    if is_rsa {
327        ClientCertificateType::RsaSign
328    } else {
329        ClientCertificateType::EcdsaSign
330    }
331}
332
333// SignatureScheme identifies a signature algorithm supported by TLS. See
334// RFC 8446, Section 4.2.3.
335#[derive(Copy, Clone, Debug, PartialEq, Eq)]
336/// A TLS signature scheme, which names a signature and hash together ([RFC 8446] ยง4.2.3).
337#[non_exhaustive]
338pub enum SignatureScheme {
339    // RSASSA-PKCS1-v1_5 algorithms.
340    /// `PKCS1_WITH_SHA256` (`0x0401`).
341    Pkcs1WithSha256 = 0x0401,
342    /// `PKCS1_WITH_SHA384` (`0x0501`).
343    Pkcs1WithSha384 = 0x0501,
344    /// `PKCS1_WITH_SHA512` (`0x0601`).
345    Pkcs1WithSha512 = 0x0601,
346
347    // RSASSA-PSS algorithms with public key OID rsaEncryption.
348    /// `PSS_WITH_SHA256` (`0x0804`).
349    PssWithSha256 = 0x0804,
350    /// `PSS_WITH_SHA384` (`0x0805`).
351    PssWithSha384 = 0x0805,
352    /// `PSS_WITH_SHA512` (`0x0806`).
353    PssWithSha512 = 0x0806,
354
355    // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
356    /// `ECDSA_WITH_P256_AND_SHA256` (`0x0403`).
357    EcdsaWithP256AndSha256 = 0x0403,
358    /// `ECDSA_WITH_P384_AND_SHA384` (`0x0503`).
359    EcdsaWithP384AndSha384 = 0x0503,
360    /// `ECDSA_WITH_P521_AND_SHA512` (`0x0603`).
361    EcdsaWithP521AndSha512 = 0x0603,
362
363    // EdDSA algorithms.
364    /// `ED25519` (`0x0807`).
365    Ed25519 = 0x0807,
366
367    // Legacy signature and hash algorithms for TLS 1.2.
368    /// `PKCS1_WITH_SHA1` (`0x0201`).
369    Pkcs1WithSha1 = 0x0201,
370    /// `ECDSA_WITH_SHA1` (`0x0203`).
371    EcdsaWithSha1 = 0x0203,
372}
373
374// parse_signature_schemes translates []tls.SignatureScheme to []signatureHashAlgorithm.
375// It returns default signature scheme list if no SignatureScheme is passed.
376pub(crate) fn parse_signature_schemes(
377    sigs: &[u16],
378    insecure_hashes: bool,
379) -> Result<Vec<SignatureHashAlgorithm>> {
380    if sigs.is_empty() {
381        return Ok(default_signature_schemes());
382    }
383
384    let mut out = vec![];
385    for ss in sigs {
386        let sig: SignatureAlgorithm = ((*ss & 0xFF) as u8).into();
387        if sig == SignatureAlgorithm::Unsupported {
388            return Err(Error::ErrInvalidSignatureAlgorithm);
389        }
390        let h: HashAlgorithm = (((*ss >> 8) & 0xFF) as u8).into();
391        if h == HashAlgorithm::Unsupported || h.invalid() {
392            return Err(Error::ErrInvalidHashAlgorithm);
393        }
394        if h.insecure() && !insecure_hashes {
395            continue;
396        }
397        out.push(SignatureHashAlgorithm {
398            hash: h,
399            signature: sig,
400        })
401    }
402
403    if out.is_empty() {
404        Err(Error::ErrNoAvailableSignatureSchemes)
405    } else {
406        Ok(out)
407    }
408}