tlspuffin/tls/rustls/msgs/
message.rs

1use std::any::TypeId;
2
3use comparable::Comparable;
4use extractable_macro::Extractable;
5use puffin::codec;
6use puffin::codec::{Codec, Reader, VecCodecWoSize};
7use puffin::error::Error::{Term, TermBug};
8use puffin::protocol::{EvaluatedTerm, ProtocolMessage};
9
10use crate::claims::*;
11use crate::protocol::{MessageFlight, OpaqueMessageFlight, TLSProtocolTypes};
12use crate::tls::rustls::error::Error;
13use crate::tls::rustls::hash_hs::HandshakeHash;
14use crate::tls::rustls::key::Certificate;
15use crate::tls::rustls::msgs::alert::AlertMessagePayload;
16use crate::tls::rustls::msgs::base::{Payload, PayloadU16, PayloadU24, PayloadU8};
17use crate::tls::rustls::msgs::ccs::ChangeCipherSpecPayload;
18use crate::tls::rustls::msgs::enums::ContentType::ApplicationData;
19use crate::tls::rustls::msgs::enums::ProtocolVersion::TLSv1_3;
20use crate::tls::rustls::msgs::enums::{
21    AlertDescription, AlertLevel, CipherSuite, Compression, ContentType, HandshakeType, NamedGroup,
22    ProtocolVersion, SignatureScheme,
23};
24use crate::tls::rustls::msgs::handshake::{
25    CertReqExtension, CertificateEntries, CertificateEntry, CertificateExtension,
26    CertificateExtensions, CipherSuites, ClientExtension, ClientExtensions, Compressions,
27    HandshakeMessagePayload, HelloRetryExtension, HelloRetryExtensions, KeyShareEntries,
28    KeyShareEntry, NewSessionTicketExtension, NewSessionTicketExtensions, PresharedKeyIdentity,
29    Random, ServerExtension, ServerExtensions, ServerName, ServerNameRequest, SessionID,
30    SupportedSignatureSchemes, VecU16OfPayloadU16, VecU16OfPayloadU8,
31};
32use crate::tls::rustls::msgs::heartbeat::HeartbeatPayload;
33
34#[derive(Debug, Clone, Extractable, Comparable)]
35#[extractable(TLSProtocolTypes)]
36pub enum MessagePayload {
37    Alert(AlertMessagePayload),
38    Handshake(HandshakeMessagePayload),
39    // this type is for TLS 1.2 encrypted handshake messages
40    TLS12EncryptedHandshake(Payload),
41    ChangeCipherSpec(ChangeCipherSpecPayload),
42    ApplicationData(Payload),
43    Heartbeat(HeartbeatPayload),
44}
45
46impl codec::CodecP for MessagePayload {
47    fn encode(&self, bytes: &mut Vec<u8>) {
48        MessagePayload::encode(self, bytes);
49    }
50
51    fn read(&mut self, _: &mut Reader) -> Result<(), puffin::error::Error> {
52        Err(puffin::error::Error::Codec(format!(
53            "Failed to read for type {:?}",
54            std::any::type_name::<MessagePayload>()
55        )))
56    }
57}
58
59impl PartialEq for MessagePayload {
60    fn eq(&self, other: &Self) -> bool {
61        match (self, other) {
62            (MessagePayload::Alert(_), MessagePayload::Alert(_)) => true,
63            (MessagePayload::Handshake(_), MessagePayload::Handshake(_)) => true,
64            (
65                MessagePayload::TLS12EncryptedHandshake(_),
66                MessagePayload::TLS12EncryptedHandshake(_),
67            ) => true,
68            (MessagePayload::ChangeCipherSpec(_), MessagePayload::ChangeCipherSpec(_)) => true,
69            (MessagePayload::ApplicationData(_), MessagePayload::ApplicationData(_)) => true,
70            (MessagePayload::Heartbeat(_), MessagePayload::Heartbeat(_)) => true,
71            (_, _) => false,
72        }
73    }
74}
75
76impl MessagePayload {
77    pub fn encode(&self, bytes: &mut Vec<u8>) {
78        match *self {
79            Self::Alert(ref x) => x.encode(bytes),
80            Self::Handshake(ref x) => x.encode(bytes),
81            Self::TLS12EncryptedHandshake(ref x) => x.encode(bytes),
82            Self::ChangeCipherSpec(ref x) => x.encode(bytes),
83            Self::ApplicationData(ref x) => x.encode(bytes),
84            Self::Heartbeat(ref x) => x.encode(bytes),
85        }
86    }
87
88    pub fn new(typ: ContentType, vers: ProtocolVersion, payload: Payload) -> Result<Self, Error> {
89        let fallback_payload = payload.clone();
90        let mut r = Reader::init(&payload.0);
91        let parsed = match typ {
92            ContentType::ApplicationData => return Ok(Self::ApplicationData(payload)),
93            ContentType::Alert => AlertMessagePayload::read(&mut r).map(MessagePayload::Alert),
94            ContentType::Handshake => {
95                HandshakeMessagePayload::read_version_exact(&mut r, vers)
96                    .map(MessagePayload::Handshake)
97                    // this type is for TLS 1.2 encrypted handshake messages
98                    .or(Some(MessagePayload::TLS12EncryptedHandshake(
99                        fallback_payload,
100                    )))
101            }
102            ContentType::ChangeCipherSpec => {
103                ChangeCipherSpecPayload::read(&mut r).map(MessagePayload::ChangeCipherSpec)
104            }
105            ContentType::Heartbeat => HeartbeatPayload::read(&mut r).map(MessagePayload::Heartbeat),
106            _ => None,
107        };
108
109        parsed.ok_or(Error::corrupt_message(typ))
110        /*        parsed
111        .filter(|_| !r.any_left())
112        .ok_or_else(|| Error::corrupt_message(typ))*/
113    }
114
115    /// Extract multiple messages payloads from one ApplicationData message
116    pub fn multiple_new(
117        typ: ContentType,
118        vers: ProtocolVersion,
119        payload: Payload,
120    ) -> Result<Vec<Self>, Error> {
121        let fallback_payload = &payload;
122        let mut r = Reader::init(&payload.0);
123        let mut parsed: Vec<Self> = vec![];
124        while r.any_left() {
125            let parsed_msg = match typ {
126                ContentType::ApplicationData => Some(Self::ApplicationData(payload.clone())),
127                ContentType::Alert => AlertMessagePayload::read(&mut r).map(MessagePayload::Alert),
128                ContentType::Handshake => {
129                    HandshakeMessagePayload::read_version(&mut r, vers)
130                        .map(MessagePayload::Handshake)
131                        // this type is for TLS 1.2 encrypted handshake messages
132                        .or(Some(MessagePayload::TLS12EncryptedHandshake(
133                            fallback_payload.clone(),
134                        )))
135                }
136                ContentType::ChangeCipherSpec => {
137                    ChangeCipherSpecPayload::read(&mut r).map(MessagePayload::ChangeCipherSpec)
138                }
139                ContentType::Heartbeat => {
140                    HeartbeatPayload::read(&mut r).map(MessagePayload::Heartbeat)
141                }
142                _ => None,
143            };
144            if let Some(msg) = parsed_msg {
145                parsed.push(msg);
146            }
147        }
148
149        Ok(parsed)
150    }
151
152    pub fn content_type(&self) -> ContentType {
153        match self {
154            Self::Alert(_) => ContentType::Alert,
155            Self::Handshake(_) => ContentType::Handshake,
156            Self::TLS12EncryptedHandshake(_) => ContentType::Handshake,
157            Self::ChangeCipherSpec(_) => ContentType::ChangeCipherSpec,
158            Self::ApplicationData(_) => ContentType::ApplicationData,
159            Self::Heartbeat(_) => ContentType::Heartbeat,
160        }
161    }
162}
163
164/// A TLS frame, named TLSPlaintext in the standard.
165///
166/// This type owns all memory for its interior parts. It is used to read/write from/to I/O
167/// buffers as well as for fragmenting, joining and encryption/decryption. It can be converted
168/// into a `Message` by decoding the payload.
169#[derive(Debug, Clone, Extractable, Comparable, PartialEq)]
170#[extractable(TLSProtocolTypes)]
171pub struct OpaqueMessage {
172    #[extractable_ignore]
173    pub typ: ContentType,
174    #[extractable_ignore]
175    pub version: ProtocolVersion,
176    #[extractable_ignore]
177    #[comparable_ignore]
178    pub payload: Payload,
179}
180
181impl codec::VecCodecWoSize for OpaqueMessage {}
182
183impl Codec for OpaqueMessage {
184    fn encode(&self, bytes: &mut Vec<u8>) {
185        self.typ.encode(bytes);
186        self.version.encode(bytes);
187        (self.payload.0.len() as u16).encode(bytes);
188        self.payload.encode(bytes);
189    }
190
191    fn read(reader: &mut Reader) -> Option<Self> {
192        Self::read(reader).ok()
193    }
194}
195
196impl OpaqueMessage {
197    /// Content type, version and size.
198    const HEADER_SIZE: u16 = 1 + 2 + 2;
199    /// This is the maximum on-the-wire size of a TLSCiphertext.
200    /// That's 2^14 payload bytes, a header, and a 2KB allowance
201    /// for ciphertext overheads.
202    const MAX_PAYLOAD: u16 = 16384 + 2048;
203    /// Maximum on-wire message size.
204    pub const MAX_WIRE_SIZE: usize = (Self::MAX_PAYLOAD + Self::HEADER_SIZE) as usize;
205
206    /// `MessageError` allows callers to distinguish between valid prefixes (might
207    /// become valid if we read more data) and invalid data.
208    pub fn read(r: &mut Reader) -> Result<Self, MessageError> {
209        #[cfg(not(feature = "enable-guards"))]
210        let typ = ContentType::read(r).unwrap_or(ApplicationData);
211        #[cfg(not(feature = "enable-guards"))]
212        let version = ProtocolVersion::read(r).unwrap_or(TLSv1_3);
213
214        #[cfg(feature = "enable-guards")]
215        let typ = ContentType::read(r).ok_or(MessageError::TooShortForHeader)?;
216        #[cfg(feature = "enable-guards")]
217        let version = ProtocolVersion::read(r).ok_or(MessageError::TooShortForHeader)?;
218
219        let len = u16::read(r).ok_or(MessageError::TooShortForHeader)?;
220
221        #[cfg(feature = "enable-guards")]
222        // Reject undersize messages
223        //  implemented per section 5.1 of RFC8446 (TLSv1.3)
224        //              per section 6.2.1 of RFC5246 (TLSv1.2)
225        if typ != ContentType::ApplicationData && len == 0 {
226            return Err(MessageError::IllegalLength);
227        }
228
229        #[cfg(feature = "enable-guards")]
230        // Reject oversize messages
231        if len >= Self::MAX_PAYLOAD {
232            return Err(MessageError::IllegalLength);
233        }
234
235        #[cfg(feature = "enable-guards")]
236        // Don't accept any new content-types.
237        if let ContentType::Unknown(_) = typ {
238            return Err(MessageError::IllegalContentType);
239        }
240
241        #[cfg(feature = "enable-guards")]
242        // Accept only versions 0x03XX for any XX.
243        match version {
244            ProtocolVersion::Unknown(ref v) if (v & 0xff00) != 0x0300 => {
245                return Err(MessageError::IllegalProtocolVersion);
246            }
247            _ => {}
248        };
249
250        let mut sub = r.sub(len as usize).ok_or(MessageError::TooShortForLength)?;
251        let payload = Payload::read(&mut sub);
252
253        Ok(Self {
254            typ,
255            version,
256            payload,
257        })
258    }
259
260    /// Force conversion into a plaintext message.
261    ///
262    /// This should only be used for messages that are known to be in plaintext. Otherwise, the
263    /// `OpaqueMessage` should be decrypted into a `PlainMessage` using a `MessageDecrypter`.
264    pub fn into_plain_message(self) -> PlainMessage {
265        PlainMessage {
266            version: self.version,
267            typ: self.typ,
268            payload: self.payload,
269        }
270    }
271}
272
273impl From<Message> for PlainMessage {
274    fn from(msg: Message) -> Self {
275        let typ = msg.payload.content_type();
276        let payload = match msg.payload {
277            MessagePayload::ApplicationData(payload) => payload,
278            _ => {
279                let mut buf = Vec::new();
280                msg.payload.encode(&mut buf);
281                Payload(buf)
282            }
283        };
284
285        Self {
286            typ,
287            version: msg.version,
288            payload,
289        }
290    }
291}
292
293/// A decrypted TLS frame
294///
295/// This type owns all memory for its interior parts. It can be decrypted from an OpaqueMessage
296/// or encrypted into an OpaqueMessage, and it is also used for joining and fragmenting.
297#[derive(Clone, Debug)]
298pub struct PlainMessage {
299    pub typ: ContentType,
300    pub version: ProtocolVersion,
301    pub payload: Payload,
302}
303
304impl PlainMessage {
305    pub fn into_unencrypted_opaque(self) -> OpaqueMessage {
306        OpaqueMessage {
307            version: self.version,
308            typ: self.typ,
309            payload: self.payload,
310        }
311    }
312
313    pub fn borrow(&self) -> BorrowedPlainMessage<'_> {
314        BorrowedPlainMessage {
315            version: self.version,
316            typ: self.typ,
317            payload: &self.payload.0,
318        }
319    }
320}
321
322/// A message with decoded payload
323#[derive(Debug, Clone, Comparable, PartialEq)]
324pub struct Message {
325    pub version: ProtocolVersion,
326    pub payload: MessagePayload,
327}
328
329// Make it VecCodecWoSize so that we have `Vec<T>: Codec` for free
330impl VecCodecWoSize for Message {}
331
332impl Codec for Message {
333    fn encode(&self, bytes: &mut Vec<u8>) {
334        Codec::encode(&self.create_opaque(), bytes);
335    }
336
337    fn read(reader: &mut Reader) -> Option<Self> {
338        <OpaqueMessage>::read(reader)
339            .ok()
340            .and_then(|op| Message::try_from(op).ok())
341    }
342}
343
344impl Message {
345    pub fn is_handshake_type(&self, hstyp: HandshakeType) -> bool {
346        // Bit of a layering violation, but OK.
347        if let MessagePayload::Handshake(ref hsp) = self.payload {
348            hsp.typ == hstyp
349        } else {
350            false
351        }
352    }
353
354    pub fn build_alert(level: AlertLevel, desc: AlertDescription) -> Self {
355        Self {
356            version: ProtocolVersion::TLSv1_2,
357            payload: MessagePayload::Alert(AlertMessagePayload {
358                level,
359                description: desc,
360            }),
361        }
362    }
363
364    pub fn build_key_update_notify() -> Self {
365        Self {
366            version: ProtocolVersion::TLSv1_3,
367            payload: MessagePayload::Handshake(HandshakeMessagePayload::build_key_update_notify()),
368        }
369    }
370}
371
372/// Parses a plaintext message into a well-typed [`Message`].
373///
374/// A [`PlainMessage`] must contain plaintext content. Encrypted content should be stored in an
375/// [`OpaqueMessage`] and decrypted before being stored into a [`PlainMessage`].
376impl TryFrom<PlainMessage> for Message {
377    type Error = Error;
378
379    fn try_from(plain: PlainMessage) -> Result<Self, Self::Error> {
380        Ok(Self {
381            version: plain.version,
382            payload: MessagePayload::new(plain.typ, plain.version, plain.payload)?,
383        })
384    }
385}
386
387impl TryFrom<OpaqueMessage> for Message {
388    type Error = Error;
389
390    fn try_from(value: OpaqueMessage) -> Result<Self, Self::Error> {
391        Message::try_from(value.into_plain_message())
392    }
393}
394
395/// A TLS frame, named TLSPlaintext in the standard.
396///
397/// This type differs from `OpaqueMessage` because it borrows
398/// its payload.  You can make a `OpaqueMessage` from an
399/// `BorrowMessage`, but this involves a copy.
400///
401/// This type also cannot decode its internals and
402/// cannot be read/encoded; only `OpaqueMessage` can do that.
403pub struct BorrowedPlainMessage<'a> {
404    pub typ: ContentType,
405    pub version: ProtocolVersion,
406    pub payload: &'a [u8],
407}
408
409#[derive(Debug)]
410pub enum MessageError {
411    TooShortForHeader,
412    TooShortForLength,
413    IllegalLength,
414    IllegalContentType,
415    IllegalProtocolVersion,
416}
417
418// Rationale for `any_get_encoding` and `try_read_bytes`:
419// 1. Messages of types Vec<Item> will be read and encoded without considering the size of the
420//    vector (reading until end of buffer). We consider such messages as "intermediate values",
421//    which are not meant to be directly used in struct fields such as
422//   `extensions` in `ClientHello`. We use `VecCodecWoSize` for that.
423//    In particular, an empty vector yield an empty bitstring and not [0].
424// 2. Field elements of struct messages such as `extensions` in `ClientHello` are wrapped into a
425//    constructor, whose `Codec` implementation consider the size of the vector, encoded into the
426//    appropriate number of bytes. This depends on the field under consideration. For the above
427//    example, we shall use `read_vec_u16` and `encode_vec_u16`.
428
429// For all Countable types, we encode list of items of such type by prefixing with the length
430// encoded in 2 bytes For each type: whether it produces empty bitstring for empty list ([]), and u8
431// or u16 length prefix (8/16)
432impl VecCodecWoSize for ClientExtension {} // []/u16
433impl VecCodecWoSize for ServerExtension {} // u16    (server has to return at least one extension it seems)
434impl VecCodecWoSize for HelloRetryExtension {} // ?/u16
435impl VecCodecWoSize for CertReqExtension {} // u16 -s
436impl VecCodecWoSize for CertificateExtension {} // u16 -s
437impl VecCodecWoSize for NewSessionTicketExtension {} //u16 -s
438impl VecCodecWoSize for Compression {} // u8
439impl VecCodecWoSize for Certificate {} // u24, no need?
440impl VecCodecWoSize for CertificateEntry {} // u24
441impl VecCodecWoSize for CipherSuite {} // u16
442impl VecCodecWoSize for PresharedKeyIdentity {} //u16
443impl VecCodecWoSize for NamedGroup {} //u16
444impl VecCodecWoSize for KeyShareEntry {} //u16
445                                         // impl VecCodecWoSize for ECPointFormat {} //u8
446                                         // impl VecCodecWoSize for PSKKeyExchangeMode {} //u8
447impl VecCodecWoSize for SignatureScheme {} //u16
448impl VecCodecWoSize for ServerName {} //u16
449
450#[macro_export]
451macro_rules! try_read {
452  ($bitstring:expr, $ti:expr, $T:ty, $($Ts:ty),+) => {
453      {
454      if $ti == TypeId::of::<$T>() {
455        log::trace!("Type match TypeID {:?}...!", core::any::type_name::<$T>());
456        <$T>::read_bytes($bitstring).ok_or(Term(format!(
457                "[try_read_bytes] Failed to read to type {:?} the bitstring {:?}",
458                core::any::type_name::<$T>(),
459                & $bitstring
460            ))).map(|v| Box::new(v) as Box<dyn EvaluatedTerm<TLSProtocolTypes>>)
461      } else {
462        try_read!($bitstring, $ti, $($Ts),+)
463      }
464      }
465  };
466
467  ($bitstring:expr, $ti:expr, $T:ty ) => {
468      {
469        if $ti == TypeId::of::<$T>() {
470            log::trace!("Type match TypeID {:?}...!", core::any::type_name::<$T>());
471            <$T>::read_bytes($bitstring).ok_or(Term(format!(
472                "[try_read_bytes] Failed to read to type {:?} the bitstring {:?}",
473                core::any::type_name::<$T>(),
474                &$bitstring
475            )).into()).map(|v| Box::new(v) as Box<dyn EvaluatedTerm<TLSProtocolTypes>>)
476        } else {
477                log::warn!("Failed to find a suitable type with typeID {:?} to read the bitstring {:?}", $ti, &$bitstring);
478                Err(TermBug(format!(
479                    "[try_read_bytes] Failed to find a suitable type with typeID {:?} to read the bitstring {:?}",
480                    $ti,
481                    &$bitstring
482                )))
483        }
484      }
485  };
486}
487
488/// To `read` an `EvaluatedTerm<PT>` out of a bitstring, we cannot simply use `Codec::read_bytes`
489/// since the type of the value to be initialized is not known, we only have the argument `ty` from
490/// which we can downcast and then call `read_bytes` on the appropriate type.
491/// `try_read_bytes` calls a macro `try_read` that does this.
492///  (There is no workaround for the uninitialized value type since we need to make Codec traits
493/// into dyn objects, hence it cannot have `Sized` as a supertrait.)
494pub fn try_read_bytes(
495    bitstring: &[u8],
496    ty: TypeId,
497) -> Result<Box<dyn EvaluatedTerm<TLSProtocolTypes>>, puffin::error::Error> {
498    log::trace!("Trying read...");
499    try_read!(
500        bitstring,
501        ty,
502        // We list all the types that have the Codec trait and that can be the type of a rustls
503        // message
504        // The uni-test `term_zoo::test_term_read_encode` tests this is exhaustive for the TLS
505        // signature at least
506        Message,
507        OpaqueMessage,
508        MessageFlight,
509        OpaqueMessageFlight,
510        Vec<Certificate>,
511        Certificate,
512        CertificateEntries,
513        Vec<CertificateEntry>,
514        CertificateEntry,
515        ServerExtensions,
516        Vec<ServerExtension>,
517        ClientExtensions,
518        Vec<ClientExtension>,
519        ClientExtension,
520        ServerExtension,
521        HelloRetryExtensions,
522        Vec<HelloRetryExtension>,
523        HelloRetryExtension,
524        Vec<CertReqExtension>,
525        CertReqExtension,
526        Vec<CertificateExtension>,
527        CertificateExtension,
528        CertificateExtensions,
529        Vec<NewSessionTicketExtension>,
530        NewSessionTicketExtension,
531        NewSessionTicketExtensions,
532        Random,
533        Compressions,
534        Vec<Compression>,
535        Compression,
536        SessionID,
537        // HandshakeHash,
538        // PrivateKey,
539        CipherSuites,
540        Vec<CipherSuite>,
541        CipherSuite,
542        Vec<PresharedKeyIdentity>,
543        PresharedKeyIdentity,
544        AlertMessagePayload,
545        SignatureScheme,
546        ProtocolVersion,
547        HandshakeHash,
548        TranscriptServerFinished,
549        TlsTranscript,
550        TranscriptPartialClientHello,
551        TranscriptServerHello,
552        TranscriptCertificate,
553        TranscriptClientFinished,
554        u64,
555        u32,
556        u16,
557        u8,
558        // Vec<u64>,
559        PayloadU24,
560        PayloadU16,
561        PayloadU8,
562        Vec<PayloadU24>,
563        Vec<PayloadU16>,
564        Vec<PayloadU8>,
565        VecU16OfPayloadU16,
566        VecU16OfPayloadU8,
567        Vec<u8>,
568        Option<Vec<u8>>,
569        Vec<NamedGroup>,
570        // ECPointFormatList,
571        // Vec<ECPointFormat>,
572        // ECPointFormat,
573        // PSKKeyExchangeModes,
574        // Vec<PSKKeyExchangeMode>,
575        // PSKKeyExchangeMode,
576        SupportedSignatureSchemes,
577        Vec<SignatureScheme>,
578        ServerNameRequest,
579        Vec<ServerName>,
580        ServerName,
581        KeyShareEntries,
582        Vec<KeyShareEntry>,
583        KeyShareEntry,
584        Vec<Vec<u8>>,
585        bool,
586        NamedGroup /* Option<Vec<Vec<u8>>>,
587                    * Result<Option<Vec<u8>>, FnError>,
588                    * Result<Vec<u8>, FnError>,
589                    * Result<bool, FnError>,
590                    * Result<Vec<u8>, FnError>,
591                    * Result<Vec<Vec<u8>>, FnError>,
592                    *
593                    * Message,
594                    * Result<Message FnError>,
595                    * MessagePayload,
596                    * ExtensionType, */
597    )
598}