Files
aho_corasick
ansi_term
arrayvec
atty
backtrace
backtrace_sys
base64
bincode
bitflags
byteorder
bytes
c2_chacha
capnp
capnp_futures
capnp_rpc
cfg_if
chrono
clap
crossbeam_deque
crossbeam_epoch
crossbeam_queue
crossbeam_utils
ctrlc
daemon
failure
failure_derive
flexi_logger
fnv
futures
getrandom
glob
hid_io
api
device
module
protocol
hidapi
install_service
iovec
lazy_static
libc
lock_api
log
memchr
memoffset
mio
mio_uds
nanoid
net2
nix
nodrop
num_cpus
num_integer
num_traits
open
parking_lot
parking_lot_core
pem
ppv_lite86
proc_macro2
quote
rand
rand_chacha
rand_core
rand_hc
rand_isaac
rand_jitter
rand_os
rand_pcg
rand_xorshift
rcgen
regex
regex_syntax
remove_dir_all
ring
rustc_demangle
rustls
scoped_tls
scopeguard
sct
serde
slab
smallvec
spin
stream_cancel
strsim
syn
synstructure
tempfile
textwrap
thread_local
time
tokio
tokio_codec
tokio_core
tokio_current_thread
tokio_executor
tokio_fs
tokio_io
tokio_reactor
tokio_rustls
tokio_sync
tokio_tcp
tokio_threadpool
tokio_timer
tokio_udp
tokio_uds
unicode_width
unicode_xid
untrusted
vec_map
void
webpki
windows_service
x11
xcb
xkbcommon
yasna
  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
use std::fmt;
use std::error::Error;
use crate::msgs::enums::{ContentType, HandshakeType, AlertDescription};
use webpki;
use sct;

/// rustls reports protocol errors using this type.
#[derive(Debug, PartialEq, Clone)]
pub enum TLSError {
    /// We received a TLS message that isn't valid right now.
    /// `expect_types` lists the message types we can expect right now.
    /// `got_type` is the type we found.  This error is typically
    /// caused by a buggy TLS stack (the peer or this one), a broken
    /// network, or an attack.
    InappropriateMessage {
        /// Which types we expected
        expect_types: Vec<ContentType>,
        /// What type we received
        got_type: ContentType,
    },

    /// We received a TLS handshake message that isn't valid right now.
    /// `expect_types` lists the handshake message types we can expect
    /// right now.  `got_type` is the type we found.
    InappropriateHandshakeMessage {
        /// Which handshake type we expected
        expect_types: Vec<HandshakeType>,
        /// What handshake type we received
        got_type: HandshakeType,
    },

    /// The peer sent us a syntactically incorrect TLS message.
    CorruptMessage,

    /// The peer sent us a TLS message with invalid contents.
    CorruptMessagePayload(ContentType),

    /// The peer didn't give us any certificates.
    NoCertificatesPresented,

    /// We couldn't decrypt a message.  This is invariably fatal.
    DecryptError,

    /// The peer doesn't support a protocol version/feature we require.
    /// The parameter gives a hint as to what version/feature it is.
    PeerIncompatibleError(String),

    /// The peer deviated from the standard TLS protocol.
    /// The parameter gives a hint where.
    PeerMisbehavedError(String),

    /// We received a fatal alert.  This means the peer is unhappy.
    AlertReceived(AlertDescription),

    /// The presented certificate chain is invalid.
    WebPKIError(webpki::Error),

    /// The presented SCT(s) were invalid.
    InvalidSCT(sct::Error),

    /// A catch-all error for unlikely errors.
    General(String),

    /// We failed to figure out what time it currently is.
    FailedToGetCurrentTime,

    /// A syntactically-invalid DNS hostname was given.
    InvalidDNSName(String),

    /// This function doesn't work until the TLS handshake
    /// is complete.
    HandshakeNotComplete,

    /// The peer sent an oversized record/fragment.
    PeerSentOversizedRecord,
}

fn join<T: fmt::Debug>(items: &[T]) -> String {
    items.iter()
        .map(|x| format!("{:?}", x))
        .collect::<Vec<String>>()
        .join(" or ")
}

impl fmt::Display for TLSError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            TLSError::InappropriateMessage { ref expect_types, ref got_type } => {
                write!(f,
                       "{}: got {:?} when expecting {}",
                       self.description(),
                       got_type,
                       join::<ContentType>(expect_types))
            }
            TLSError::InappropriateHandshakeMessage { ref expect_types, ref got_type } => {
                write!(f,
                       "{}: got {:?} when expecting {}",
                       self.description(),
                       got_type,
                       join::<HandshakeType>(expect_types))
            }
            TLSError::CorruptMessagePayload(ref typ) => {
                write!(f, "{} of type {:?}", self.description(), typ)
            }
            TLSError::PeerIncompatibleError(ref why) |
            TLSError::PeerMisbehavedError(ref why) => write!(f, "{}: {}", self.description(), why),
            TLSError::AlertReceived(ref alert) => write!(f, "{}: {:?}", self.description(), alert),
            TLSError::WebPKIError(ref err) => write!(f, "{}: {:?}", self.description(), err),
            TLSError::CorruptMessage |
            TLSError::NoCertificatesPresented |
            TLSError::DecryptError |
            TLSError::PeerSentOversizedRecord |
            TLSError::HandshakeNotComplete => write!(f, "{}", self.description()),
            _ => write!(f, "{}: {:?}", self.description(), self),
        }
    }
}

impl Error for TLSError {
    fn description(&self) -> &str {
        match *self {
            TLSError::InappropriateMessage { .. } => "received unexpected message",
            TLSError::InappropriateHandshakeMessage { .. } => {
                "received unexpected handshake message"
            }
            TLSError::CorruptMessage |
                TLSError::CorruptMessagePayload(_) => "received corrupt message",
            TLSError::NoCertificatesPresented => "peer sent no certificates",
            TLSError::DecryptError => "cannot decrypt peer's message",
            TLSError::PeerIncompatibleError(_) => "peer is incompatible",
            TLSError::PeerMisbehavedError(_) => "peer misbehaved",
            TLSError::AlertReceived(_) => "received fatal alert",
            TLSError::WebPKIError(_) => "invalid certificate",
            TLSError::InvalidSCT(_) => "invalid certificate timestamp",
            TLSError::General(_) => "unexpected error", // (please file a bug),
            TLSError::FailedToGetCurrentTime => "failed to get current time",
            TLSError::InvalidDNSName(_) => "invalid DNS name",
            TLSError::HandshakeNotComplete => "handshake not complete",
            TLSError::PeerSentOversizedRecord => "peer sent excess record size",
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn smoke() {
        use super::TLSError;
        use std::error::Error;
        use crate::msgs::enums::{ContentType, HandshakeType, AlertDescription};
        use webpki;
        use sct;

        let all = vec![TLSError::InappropriateMessage {
                           expect_types: vec![ContentType::Alert],
                           got_type: ContentType::Handshake,
                       },
                       TLSError::InappropriateHandshakeMessage {
                           expect_types: vec![HandshakeType::ClientHello, HandshakeType::Finished],
                           got_type: HandshakeType::ServerHello,
                       },
                       TLSError::CorruptMessage,
                       TLSError::CorruptMessagePayload(ContentType::Alert),
                       TLSError::NoCertificatesPresented,
                       TLSError::DecryptError,
                       TLSError::PeerIncompatibleError("no tls1.2".to_string()),
                       TLSError::PeerMisbehavedError("inconsistent something".to_string()),
                       TLSError::AlertReceived(AlertDescription::ExportRestriction),
                       TLSError::WebPKIError(webpki::Error::ExtensionValueInvalid),
                       TLSError::InvalidSCT(sct::Error::MalformedSCT),
                       TLSError::General("undocumented error".to_string()),
                       TLSError::FailedToGetCurrentTime,
                       TLSError::InvalidDNSName("dns something".to_string()),
                       TLSError::HandshakeNotComplete,
                       TLSError::PeerSentOversizedRecord];

        for err in all {
            println!("{:?}:", err);
            println!("  desc '{}'", err.description());
            println!("  fmt '{}'", err);
        }
    }
}