tlspuffin/tls/rustls/
error.rs

1use std::error::Error as StdError;
2use std::fmt;
3use std::time::SystemTimeError;
4
5use crate::tls::rustls::msgs::enums::{AlertDescription, ContentType, HandshakeType};
6use crate::tls::rustls::rand;
7
8/// Context around a corrupt TLS message payload that resulted in
9/// an error.
10#[derive(Debug, PartialEq, Clone)]
11pub struct CorruptMessagePayload {
12    location: &'static core::panic::Location<'static>,
13    kind: ContentType,
14}
15
16impl CorruptMessagePayload {
17    /// Returns the type of content we expected but found as corrupt.
18    pub fn content_type(&self) -> ContentType {
19        self.kind
20    }
21}
22
23/// rustls reports protocol errors using this type.
24#[derive(Debug, PartialEq, Clone)]
25pub enum Error {
26    /// We received a TLS message that isn't valid right now.
27    /// `expect_types` lists the message types we can expect right now.
28    /// `got_type` is the type we found.  This error is typically
29    /// caused by a buggy TLS stack (the peer or this one), a broken
30    /// network, or an attack.
31    InappropriateMessage {
32        /// Which types we expected
33        expect_types: Vec<ContentType>,
34        /// What type we received
35        got_type: ContentType,
36    },
37
38    /// We received a TLS handshake message that isn't valid right now.
39    /// `expect_types` lists the handshake message types we can expect
40    /// right now.  `got_type` is the type we found.
41    InappropriateHandshakeMessage {
42        /// Which handshake type we expected
43        expect_types: Vec<HandshakeType>,
44        /// What handshake type we received
45        got_type: HandshakeType,
46    },
47
48    /// The peer sent us a syntactically incorrect TLS message.
49    CorruptMessage,
50
51    /// The peer sent us a TLS message with invalid contents.
52    CorruptMessagePayload(CorruptMessagePayload),
53
54    /// The peer didn't give us any certificates.
55    NoCertificatesPresented,
56
57    /// The certificate verifier doesn't support the given type of name.
58    UnsupportedNameType,
59
60    /// We couldn't decrypt a message.  This is invariably fatal.
61    DecryptError,
62
63    /// We couldn't encrypt a message because it was larger than the allowed message size.
64    /// This should never happen if the application is using valid record sizes.
65    EncryptError,
66
67    /// The peer doesn't support a protocol version/feature we require.
68    /// The parameter gives a hint as to what version/feature it is.
69    PeerIncompatibleError(String),
70
71    /// The peer deviated from the standard TLS protocol.
72    /// The parameter gives a hint where.
73    PeerMisbehavedError(String),
74
75    /// We received a fatal alert.  This means the peer is unhappy.
76    AlertReceived(AlertDescription),
77
78    /// We received an invalidly encoded certificate from the peer.
79    InvalidCertificateEncoding,
80
81    /// We received a certificate with invalid signature type.
82    InvalidCertificateSignatureType,
83
84    /// We received a certificate with invalid signature.
85    InvalidCertificateSignature,
86
87    /// We received a certificate which includes invalid data.
88    InvalidCertificateData(String),
89
90    /// The presented SCT(s) were invalid.
91    InvalidSct(sct::Error),
92
93    /// A catch-all error for unlikely errors.
94    General(String),
95
96    /// We failed to figure out what time it currently is.
97    FailedToGetCurrentTime,
98
99    /// We failed to acquire random bytes from the system.
100    FailedToGetRandomBytes,
101
102    /// This function doesn't work until the TLS handshake
103    /// is complete.
104    HandshakeNotComplete,
105
106    /// The peer sent an oversized record/fragment.
107    PeerSentOversizedRecord,
108
109    /// An incoming connection did not support any known application protocol.
110    NoApplicationProtocol,
111
112    /// The `max_fragment_size` value supplied in configuration was too small,
113    /// or too large.
114    BadMaxFragmentSize,
115}
116
117impl Error {
118    #[track_caller]
119    pub fn corrupt_message(kind: ContentType) -> Self {
120        Self::CorruptMessagePayload(CorruptMessagePayload {
121            location: core::panic::Location::caller(),
122            kind,
123        })
124    }
125}
126
127fn join<T: fmt::Debug>(items: &[T]) -> String {
128    items
129        .iter()
130        .map(|x| format!("{:?}", x))
131        .collect::<Vec<String>>()
132        .join(" or ")
133}
134
135impl fmt::Display for Error {
136    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
137        match *self {
138            Self::InappropriateMessage {
139                ref expect_types,
140                ref got_type,
141            } => write!(
142                f,
143                "received unexpected message: got {:?} when expecting {}",
144                got_type,
145                join::<ContentType>(expect_types)
146            ),
147            Self::InappropriateHandshakeMessage {
148                ref expect_types,
149                ref got_type,
150            } => write!(
151                f,
152                "received unexpected handshake message: got {:?} when expecting {}",
153                got_type,
154                join::<HandshakeType>(expect_types)
155            ),
156            Self::CorruptMessagePayload(ref typ) => {
157                write!(f, "received corrupt message of type {:?}", typ)
158            }
159            Self::PeerIncompatibleError(ref why) => write!(f, "peer is incompatible: {}", why),
160            Self::PeerMisbehavedError(ref why) => write!(f, "peer misbehaved: {}", why),
161            Self::AlertReceived(ref alert) => write!(f, "received fatal alert: {:?}", alert),
162            Self::InvalidCertificateEncoding => {
163                write!(f, "invalid peer certificate encoding")
164            }
165            Self::InvalidCertificateSignatureType => {
166                write!(f, "invalid peer certificate signature type")
167            }
168            Self::InvalidCertificateSignature => {
169                write!(f, "invalid peer certificate signature")
170            }
171            Self::InvalidCertificateData(ref reason) => {
172                write!(f, "invalid peer certificate contents: {}", reason)
173            }
174            Self::CorruptMessage => write!(f, "received corrupt message"),
175            Self::NoCertificatesPresented => write!(f, "peer sent no certificates"),
176            Self::UnsupportedNameType => write!(f, "presented server name type wasn't supported"),
177            Self::DecryptError => write!(f, "cannot decrypt peer's message"),
178            Self::EncryptError => write!(f, "cannot encrypt message"),
179            Self::PeerSentOversizedRecord => write!(f, "peer sent excess record size"),
180            Self::HandshakeNotComplete => write!(f, "handshake not complete"),
181            Self::NoApplicationProtocol => write!(f, "peer doesn't support any known protocol"),
182            Self::InvalidSct(ref err) => write!(f, "invalid certificate timestamp: {:?}", err),
183            Self::FailedToGetCurrentTime => write!(f, "failed to get current time"),
184            Self::FailedToGetRandomBytes => write!(f, "failed to get random bytes"),
185            Self::BadMaxFragmentSize => {
186                write!(f, "the supplied max_fragment_size was too small or large")
187            }
188            Self::General(ref err) => write!(f, "unexpected error: {}", err),
189        }
190    }
191}
192
193impl From<SystemTimeError> for Error {
194    #[inline]
195    fn from(_: SystemTimeError) -> Self {
196        Self::FailedToGetCurrentTime
197    }
198}
199
200impl StdError for Error {}
201
202impl From<rand::GetRandomFailed> for Error {
203    fn from(_: rand::GetRandomFailed) -> Self {
204        Self::FailedToGetRandomBytes
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::{CorruptMessagePayload, Error};
211
212    #[test_log::test]
213    fn smoke() {
214        use sct;
215
216        use crate::tls::rustls::msgs::enums::{AlertDescription, ContentType, HandshakeType};
217
218        let _all = vec![
219            Error::InappropriateMessage {
220                expect_types: vec![ContentType::Alert],
221                got_type: ContentType::Handshake,
222            },
223            Error::InappropriateHandshakeMessage {
224                expect_types: vec![HandshakeType::ClientHello, HandshakeType::Finished],
225                got_type: HandshakeType::ServerHello,
226            },
227            Error::CorruptMessage,
228            Error::CorruptMessagePayload(CorruptMessagePayload {
229                location: core::panic::Location::caller(),
230                kind: ContentType::Alert,
231            }),
232            Error::NoCertificatesPresented,
233            Error::DecryptError,
234            Error::PeerIncompatibleError("no tls1.2".to_string()),
235            Error::PeerMisbehavedError("inconsistent something".to_string()),
236            Error::AlertReceived(AlertDescription::ExportRestriction),
237            Error::InvalidCertificateEncoding,
238            Error::InvalidCertificateSignatureType,
239            Error::InvalidCertificateSignature,
240            Error::InvalidCertificateData("Data".into()),
241            Error::InvalidSct(sct::Error::MalformedSct),
242            Error::General("undocumented error".to_string()),
243            Error::FailedToGetCurrentTime,
244            Error::FailedToGetRandomBytes,
245            Error::HandshakeNotComplete,
246            Error::PeerSentOversizedRecord,
247            Error::NoApplicationProtocol,
248            Error::BadMaxFragmentSize,
249        ];
250
251        /*for err in all {
252            // println!("{:?}:", err);
253            // println!("  fmt '{}'", err);
254        }*/
255    }
256
257    #[test_log::test]
258    fn rand_error_mapping() {
259        use super::rand;
260        let err: Error = rand::GetRandomFailed.into();
261        assert_eq!(err, Error::FailedToGetRandomBytes);
262    }
263
264    #[test_log::test]
265    fn time_error_mapping() {
266        use std::time::SystemTime;
267
268        let time_error = SystemTime::UNIX_EPOCH
269            .duration_since(SystemTime::now())
270            .unwrap_err();
271        let err: Error = time_error.into();
272        assert_eq!(err, Error::FailedToGetCurrentTime);
273    }
274}