tlspuffin/
protocol.rs

1use std::any::TypeId;
2
3use comparable::Comparable;
4use extractable_macro::Extractable;
5use puffin::agent::{AgentDescriptor, AgentName, ProtocolDescriptorConfig};
6use puffin::algebra::signature::Signature;
7use puffin::algebra::Matcher;
8use puffin::differential::TraceDifference;
9use puffin::error::Error;
10use puffin::protocol::{
11    CorpusBuilder, EvaluatedTerm, Extractable, OpaqueProtocolMessage, OpaqueProtocolMessageFlight,
12    ProtocolBehavior, ProtocolMessage, ProtocolMessageDeframer, ProtocolMessageFlight,
13    ProtocolTypes,
14};
15use puffin::trace::{Knowledge, Source, Trace};
16use puffin::{atom_extract_knowledge, codec, dummy_codec, dummy_extract_knowledge, term};
17use serde::{Deserialize, Serialize};
18
19use crate::claims::{
20    TlsClaim, TranscriptCertificate, TranscriptClientFinished, TranscriptClientHello,
21    TranscriptPartialClientHello, TranscriptServerFinished, TranscriptServerHello,
22};
23use crate::debug::{debug_message_with_info, debug_opaque_message_with_info};
24use crate::query::TlsQueryMatcher;
25use crate::tls::fn_impl::{
26    fn_decrypt_handshake_flight_with_secret, fn_false, fn_finished_get_cipher,
27    fn_finished_get_client_random, fn_finished_get_handshake_secret, fn_seq_0,
28    fn_server_hello_transcript, fn_true,
29};
30use crate::tls::rustls::hash_hs::HandshakeHash;
31use crate::tls::rustls::msgs::alert::AlertMessagePayload;
32use crate::tls::rustls::msgs::deframer::MessageDeframer;
33use crate::tls::rustls::msgs::handshake::{
34    CertReqExtension, CertificateEntry, CertificateExtension, CertificatePayloadTLS13,
35    CertificateRequestPayload, CertificateRequestPayloadTLS13, CertificateStatus,
36    ClientSessionTicket, DigitallySignedStruct, HandshakeMessagePayload, HelloRetryExtension,
37    NewSessionTicketExtension, NewSessionTicketPayloadTLS13, PresharedKeyIdentity, Random,
38    ServerExtension, SessionID, UnknownExtension,
39};
40use crate::tls::rustls::msgs::heartbeat::HeartbeatPayload;
41use crate::tls::rustls::msgs::message::{try_read_bytes, Message, MessagePayload, OpaqueMessage};
42use crate::tls::rustls::msgs::{self};
43use crate::tls::violation::TlsSecurityViolationPolicy;
44use crate::tls::TLS_SIGNATURE;
45
46#[derive(Debug, Clone, Comparable)]
47pub struct MessageFlight {
48    pub messages: Vec<Message>,
49}
50
51impl Extractable<TLSProtocolTypes> for MessageFlight {
52    fn extract_knowledge<'a>(
53        &'a self,
54        knowledges: &mut Vec<Knowledge<'a, TLSProtocolTypes>>,
55        _: Option<TlsQueryMatcher>,
56        source: &'a Source,
57    ) -> Result<(), Error> {
58        // Classify flight by the first non-CCS message. TLS 1.3 middlebox
59        // compatibility (e.g. LibreSSL) may prepend a dummy ChangeCipherSpec.
60        let matcher = self
61            .messages
62            .iter()
63            .find(|m| !matches!(m.payload, MessagePayload::ChangeCipherSpec(_)))
64            .map(|msg| match &msg.payload {
65                MessagePayload::Handshake(hs) => match hs.payload {
66                    msgs::handshake::HandshakePayload::ClientHello(_) => {
67                        TlsQueryMatcher::ClientHelloFlight
68                    }
69                    msgs::handshake::HandshakePayload::ServerHello(_) => {
70                        TlsQueryMatcher::ServerHelloFlight
71                    }
72                    _ => TlsQueryMatcher::OtherFlight,
73                },
74                MessagePayload::ApplicationData(_) => TlsQueryMatcher::EncryptedFlight,
75                _ => TlsQueryMatcher::OtherFlight,
76            });
77
78        knowledges.push(Knowledge {
79            source,
80            matcher,
81            data: self,
82        });
83
84        self.messages.extract_knowledge(knowledges, None, source)?;
85        Ok(())
86    }
87}
88
89impl ProtocolMessageFlight<TLSProtocolTypes, Message, OpaqueMessage, OpaqueMessageFlight>
90    for MessageFlight
91{
92    fn new() -> Self {
93        Self { messages: vec![] }
94    }
95
96    fn push(&mut self, msg: Message) {
97        self.messages.push(msg);
98    }
99
100    fn debug(&self, info: &str) {
101        log::debug!("{}: {:?}", info, self);
102    }
103}
104
105impl From<Message> for MessageFlight {
106    fn from(value: Message) -> Self {
107        Self {
108            messages: vec![value],
109        }
110    }
111}
112
113impl codec::Codec for MessageFlight {
114    fn encode(&self, bytes: &mut Vec<u8>) {
115        for msg in &self.messages {
116            msg.encode(bytes);
117        }
118    }
119
120    fn read(reader: &mut codec::Reader) -> Option<Self> {
121        let mut flight = Self::new();
122
123        while let Some(msg) = Message::read(reader) {
124            flight.push(msg);
125        }
126        Some(flight)
127    }
128}
129
130#[derive(Debug, Clone, Extractable, Comparable)]
131#[extractable(TLSProtocolTypes)]
132pub struct OpaqueMessageFlight {
133    pub messages: Vec<OpaqueMessage>,
134}
135
136impl OpaqueProtocolMessageFlight<TLSProtocolTypes, OpaqueMessage> for OpaqueMessageFlight {
137    fn new() -> Self {
138        Self { messages: vec![] }
139    }
140
141    fn push(&mut self, msg: OpaqueMessage) {
142        self.messages.push(msg);
143    }
144
145    fn debug(&self, info: &str) {
146        log::debug!("{}: {:?}", info, self);
147    }
148}
149
150impl codec::Codec for OpaqueMessageFlight {
151    fn encode(&self, bytes: &mut Vec<u8>) {
152        for msg in &self.messages {
153            msg.encode(bytes);
154        }
155    }
156
157    fn read(reader: &mut codec::Reader) -> Option<Self> {
158        let mut deframer = MessageDeframer::new();
159        let mut flight = Self::new();
160
161        let _ = deframer.read(&mut reader.rest());
162        while let Some(msg) = deframer.pop_frame() {
163            flight.push(msg);
164            // continue to read the buffer
165            let _ = deframer.read(&mut reader.rest());
166        }
167
168        Some(flight)
169    }
170}
171
172impl From<MessageFlight> for OpaqueMessageFlight {
173    fn from(value: MessageFlight) -> Self {
174        Self {
175            messages: value.messages.iter().map(|m| m.create_opaque()).collect(),
176        }
177    }
178}
179
180impl TryFrom<OpaqueMessageFlight> for MessageFlight {
181    type Error = ();
182
183    fn try_from(value: OpaqueMessageFlight) -> Result<Self, Self::Error> {
184        let flight = Self {
185            messages: value
186                .messages
187                .iter()
188                .filter_map(|m| (*m).clone().try_into().ok())
189                .collect(),
190        };
191
192        if flight.messages.is_empty() {
193            Err(())
194        } else {
195            Ok(flight)
196        }
197    }
198}
199
200impl From<OpaqueMessage> for OpaqueMessageFlight {
201    fn from(value: OpaqueMessage) -> Self {
202        Self {
203            messages: vec![value],
204        }
205    }
206}
207
208impl ProtocolMessage<TLSProtocolTypes, OpaqueMessage> for Message {
209    fn create_opaque(&self) -> OpaqueMessage {
210        msgs::message::PlainMessage::from(self.clone()).into_unencrypted_opaque()
211    }
212
213    fn debug(&self, info: &str) {
214        debug_message_with_info(info, self);
215    }
216}
217
218impl Extractable<TLSProtocolTypes> for Message {
219    /// Extracts knowledge from a [`crate::tls::rustls::msgs::message::Message`].
220    /// Only plaintext messages yield more knowledge than their binary payload.
221    /// If a message is an ApplicationData (TLS 1.3) or an encrypted Heartbeet
222    /// or Handhake message (TLS 1.2), then only the message itself and the
223    /// binary payload is returned.
224    fn extract_knowledge<'a>(
225        &'a self,
226        knowledges: &mut Vec<Knowledge<'a, TLSProtocolTypes>>,
227        _: Option<TlsQueryMatcher>,
228        source: &'a Source,
229    ) -> Result<(), Error> {
230        let matcher = match &self.payload {
231            MessagePayload::Alert(_) => Some(TlsQueryMatcher::Alert),
232            MessagePayload::Handshake(hs) => Some(TlsQueryMatcher::Handshake(Some(hs.typ))),
233            MessagePayload::ChangeCipherSpec(_) => None,
234            MessagePayload::ApplicationData(_) => Some(TlsQueryMatcher::ApplicationData),
235            MessagePayload::Heartbeat(_) => Some(TlsQueryMatcher::Heartbeat),
236            MessagePayload::TLS12EncryptedHandshake(_) => Some(TlsQueryMatcher::Handshake(None)),
237        };
238
239        knowledges.push(Knowledge {
240            source,
241            matcher,
242            data: self,
243        });
244
245        self.payload
246            .extract_knowledge(knowledges, matcher, source)?;
247        Ok(())
248    }
249}
250
251impl ProtocolMessageDeframer<TLSProtocolTypes> for MessageDeframer {
252    type OpaqueProtocolMessage = OpaqueMessage;
253
254    fn pop_frame(&mut self) -> Option<OpaqueMessage> {
255        self.frames.pop_front()
256    }
257
258    fn read(&mut self, rd: &mut dyn std::io::Read) -> std::io::Result<usize> {
259        self.read(rd)
260    }
261}
262
263impl OpaqueProtocolMessage<TLSProtocolTypes> for OpaqueMessage {
264    fn debug(&self, info: &str) {
265        debug_opaque_message_with_info(info, self);
266    }
267}
268
269atom_extract_knowledge!(TLSProtocolTypes, CertReqExtension);
270atom_extract_knowledge!(TLSProtocolTypes, CertificateEntry);
271atom_extract_knowledge!(TLSProtocolTypes, CertificateExtension);
272atom_extract_knowledge!(TLSProtocolTypes, CertificatePayloadTLS13);
273atom_extract_knowledge!(TLSProtocolTypes, CertificateRequestPayload);
274atom_extract_knowledge!(TLSProtocolTypes, CertificateRequestPayloadTLS13);
275atom_extract_knowledge!(TLSProtocolTypes, CertificateStatus);
276atom_extract_knowledge!(TLSProtocolTypes, DigitallySignedStruct);
277atom_extract_knowledge!(TLSProtocolTypes, HandshakeHash);
278atom_extract_knowledge!(TLSProtocolTypes, HelloRetryExtension);
279atom_extract_knowledge!(TLSProtocolTypes, NewSessionTicketExtension);
280atom_extract_knowledge!(TLSProtocolTypes, NewSessionTicketPayloadTLS13);
281atom_extract_knowledge!(TLSProtocolTypes, PresharedKeyIdentity);
282atom_extract_knowledge!(TLSProtocolTypes, Random);
283atom_extract_knowledge!(TLSProtocolTypes, ServerExtension);
284atom_extract_knowledge!(TLSProtocolTypes, SessionID);
285atom_extract_knowledge!(TLSProtocolTypes, u32);
286atom_extract_knowledge!(TLSProtocolTypes, u64);
287atom_extract_knowledge!(TLSProtocolTypes, u16);
288atom_extract_knowledge!(TLSProtocolTypes, u8);
289dummy_extract_knowledge!(TLSProtocolTypes, bool);
290dummy_codec!(TLSProtocolTypes, UnknownExtension);
291dummy_codec!(TLSProtocolTypes, ClientSessionTicket);
292
293impl Matcher for msgs::enums::HandshakeType {
294    fn matches(&self, matcher: &Self) -> bool {
295        matcher == self
296    }
297
298    fn specificity(&self) -> u32 {
299        1
300    }
301}
302
303#[derive(Serialize, Deserialize, Copy, Clone, Debug, Eq, PartialEq, Hash, Comparable)]
304pub enum AgentType {
305    Server,
306    Client,
307}
308
309#[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq, Hash, Comparable)]
310pub enum TLSVersion {
311    V1_3,
312    V1_2,
313    Both,
314}
315
316#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Hash)]
317pub struct TLSDescriptorConfig {
318    /// Whether the agent which holds this descriptor is a server.
319    pub typ: AgentType,
320    pub tls_version: TLSVersion,
321    /// If agent is a server:
322    ///   Make client auth. a requirement.
323    /// If agent is a client:
324    ///   Send a static certificate.
325    ///
326    /// Default: false
327    pub client_authentication: bool,
328    /// If agent is a server:
329    ///   No effect, servers always send certificates in TLS.
330    /// If agent is a client:
331    ///   Make server auth. a requirement.
332    ///
333    /// Default: true
334    pub server_authentication: bool,
335    /// Whether we want to try to reuse a previous agent. This is needed for TLS session resumption
336    /// as openssl agents rotate ticket keys if they are recreated.
337    pub try_reuse: bool,
338    /// List of available TLS ciphers - public for default() to be used
339    /// Not supposed to be used outside the public methods to manage 1.2/1.3/both
340    pub _cipher_string_tls13: String,
341    pub _cipher_string_tls12: String,
342    /// List of available TLS groups/curves
343    /// If `None`, use the default PUT groups
344    pub groups: Option<String>,
345    /// List of acceptable signature algorithms (OpenSSL sigalgs_list format,
346    /// e.g. "RSA-PSS+SHA256:RSA-PSS+SHA384").
347    /// If `None`, use the default PUT signature algorithms.
348    pub sigalgs: Option<String>,
349}
350
351impl TLSDescriptorConfig {
352    pub fn new_client(name: AgentName, tls_version: TLSVersion) -> AgentDescriptor<Self> {
353        let protocol_config = Self {
354            tls_version,
355            typ: AgentType::Client,
356            ..Self::default()
357        };
358
359        AgentDescriptor {
360            name,
361            protocol_config,
362        }
363    }
364
365    pub fn new_server(name: AgentName, tls_version: TLSVersion) -> AgentDescriptor<Self> {
366        let protocol_config = Self {
367            tls_version,
368            typ: AgentType::Server,
369            ..Self::default()
370        };
371
372        AgentDescriptor {
373            name,
374            protocol_config,
375        }
376    }
377
378    pub fn set_cipher_string_12(&mut self, cipher_string: String) {
379        self._cipher_string_tls12 = cipher_string;
380    }
381
382    pub fn set_cipher_string_13(&mut self, cipher_string: String) {
383        self._cipher_string_tls13 = cipher_string;
384    }
385
386    /// Sets both 1.2 and 1.3 cipher strings. If you need to specify two different cipher strings,
387    /// use `set_cipher_string_12` and `set_cipher_string_13` separately.
388    /// When using tlsversion::both both strings will be concatenated (and deduped).
389    /// Be careful if you set only one of them when using both.
390    pub fn set_cipher_string(&mut self, cipher_string: String) {
391        self._cipher_string_tls13 = cipher_string.clone();
392        self._cipher_string_tls12 = cipher_string;
393    }
394
395    fn concat_cipher_strings(&self) -> String {
396        // concat the two cipher strings with 1.3 first and remove duplicates
397        // Separate values between colon ":" to deduplicate
398        let combined = format!(
399            "{}:{}",
400            self._cipher_string_tls13, self._cipher_string_tls12
401        );
402        let mut seen = std::collections::HashSet::new();
403        combined
404            .split(':')
405            .filter(|s| !s.is_empty() && seen.insert(*s))
406            .collect::<Vec<_>>()
407            .join(":")
408    }
409
410    pub fn get_cipher_string_12(&self) -> String {
411        self._cipher_string_tls12.clone()
412    }
413
414    pub fn get_cipher_string_13(&self) -> String {
415        self._cipher_string_tls13.clone()
416    }
417
418    pub fn get_cipher_string_both(&self) -> String {
419        self.concat_cipher_strings()
420    }
421}
422
423impl ProtocolDescriptorConfig for TLSDescriptorConfig {
424    fn is_reusable_with(&self, other: &Self) -> bool {
425        self.typ == other.typ
426            && self.tls_version == other.tls_version
427            && self._cipher_string_tls13 == other._cipher_string_tls13
428            && self._cipher_string_tls12 == other._cipher_string_tls12
429            && self.groups == other.groups
430            && self.sigalgs == other.sigalgs
431    }
432}
433
434// Bulk strings are not well-supported across wolfssl versions (better in later ones)
435// We therefore use a custom list of ciphers.
436// In order:
437//  - TLS 1.3 (same name for standard and openssl)
438//  - TLS 1.2 (standard names)
439//  - TLS 1.2 (openssl names) openssl set_cipher_list method does not parse standard format
440// For the 1.2 lists we can make them follow one after the other because it either ignores a full
441// list or accepts it and ignores the second even if it is able the parse it because it already
442// exists.
443
444// Excluded ciphers:
445// - TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 / ECDHE-RSA-CHACHA20-POLY1305
446//
447// Exclusion with ! does not work for all implementations, we therefore have to make them invalid
448// by adding some text to the cipher name.
449const TLS_DEFAULT_CIPHER: &str = "\
450TLS_AES_256_GCM_SHA384:\
451TLS_CHACHA20_POLY1305_SHA256:\
452TLS_AES_128_GCM_SHA256:\
453\
454\
455TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:\
456TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:\
457TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:\
458TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:\
459TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:\
460TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256_EXCLUDED:\
461TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:\
462TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:\
463TLS_ECDHE_ECDSA_WITH_AES_256_CCM:\
464TLS_DHE_RSA_WITH_AES_256_CCM_8:\
465TLS_DHE_RSA_WITH_AES_256_CCM:\
466TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384:\
467TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:\
468TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384:\
469TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384:\
470TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:\
471TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:\
472TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:\
473TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:\
474TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:\
475TLS_ECDHE_ECDSA_WITH_AES_128_CCM:\
476TLS_DHE_RSA_WITH_AES_128_CCM_8:\
477TLS_DHE_RSA_WITH_AES_128_CCM:\
478TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256:\
479TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:\
480TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256:\
481TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256:\
482TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:\
483TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:\
484TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:\
485TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:\
486TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:\
487TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384:\
488TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:\
489TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256:\
490TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:\
491TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:\
492TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:\
493TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:\
494TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:\
495TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:\
496TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:\
497TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256:\
498TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:\
499TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:\
500TLS_DHE_RSA_WITH_AES_256_CBC_SHA:\
501TLS_DHE_DSS_WITH_AES_256_CBC_SHA:\
502TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA:\
503TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA:\
504TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:\
505TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:\
506TLS_DHE_RSA_WITH_AES_128_CBC_SHA:\
507TLS_DHE_PSK_WITH_AES_256_GCM_SHA384:\
508TLS_DHE_PSK_WITH_AES_128_GCM_SHA256:\
509TLS_DHE_PSK_WITH_AES_256_CBC_SHA384:\
510TLS_DHE_PSK_WITH_AES_128_CBC_SHA256:\
511TLS_DHE_DSS_WITH_AES_128_CBC_SHA:\
512TLS_DHE_RSA_WITH_SEED_CBC_SHA:\
513TLS_DHE_DSS_WITH_SEED_CBC_SHA:\
514TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA:\
515TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA:\
516TLS_RSA_WITH_AES_256_GCM_SHA384:\
517TLS_RSA_WITH_AES_256_CCM_8:\
518TLS_RSA_WITH_AES_256_CCM:\
519TLS_RSA_WITH_ARIA_256_GCM_SHA384:\
520TLS_RSA_WITH_AES_128_GCM_SHA256:\
521TLS_RSA_WITH_AES_128_CCM_8:\
522TLS_RSA_WITH_AES_128_CCM:\
523TLS_RSA_WITH_ARIA_128_GCM_SHA256:\
524TLS_RSA_WITH_AES_256_CBC_SHA256:\
525TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:\
526TLS_RSA_WITH_AES_128_CBC_SHA256:\
527TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:\
528TLS_RSA_WITH_AES_256_CBC_SHA:\
529TLS_RSA_WITH_CAMELLIA_256_CBC_SHA:\
530TLS_RSA_WITH_AES_128_CBC_SHA:\
531TLS_RSA_WITH_SEED_CBC_SHA:\
532TLS_RSA_WITH_CAMELLIA_128_CBC_SHA:\
533TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:\
534TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:\
535TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:\
536TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:\
537\
538\
539ECDHE-ECDSA-AES256-GCM-SHA384:\
540ECDHE-RSA-AES256-GCM-SHA384:\
541DHE-DSS-AES256-GCM-SHA384:\
542DHE-RSA-AES256-GCM-SHA384:\
543ECDHE-ECDSA-CHACHA20-POLY1305:\
544ECDHE-RSA-CHACHA20-POLY1305-EXCLUDED:\
545DHE-RSA-CHACHA20-POLY1305:\
546ECDHE-ECDSA-AES256-CCM8:\
547ECDHE-ECDSA-AES256-CCM:\
548DHE-RSA-AES256-CCM8:\
549DHE-RSA-AES256-CCM:\
550ECDHE-ECDSA-ARIA256-GCM-SHA384:\
551ECDHE-ARIA256-GCM-SHA384:\
552DHE-DSS-ARIA256-GCM-SHA384:\
553DHE-RSA-ARIA256-GCM-SHA384:\
554ECDHE-ECDSA-AES128-GCM-SHA256:\
555ECDHE-RSA-AES128-GCM-SHA256:\
556DHE-DSS-AES128-GCM-SHA256:\
557DHE-RSA-AES128-GCM-SHA256:\
558ECDHE-ECDSA-AES128-CCM8:\
559ECDHE-ECDSA-AES128-CCM:\
560DHE-RSA-AES128-CCM8:\
561DHE-RSA-AES128-CCM:\
562ECDHE-ECDSA-ARIA128-GCM-SHA256:\
563ECDHE-ARIA128-GCM-SHA256:\
564DHE-DSS-ARIA128-GCM-SHA256:\
565DHE-RSA-ARIA128-GCM-SHA256:\
566ECDHE-ECDSA-AES256-SHA384:\
567ECDHE-RSA-AES256-SHA384:\
568DHE-RSA-AES256-SHA256:\
569DHE-DSS-AES256-SHA256:\
570ECDHE-ECDSA-CAMELLIA256-SHA384:\
571ECDHE-RSA-CAMELLIA256-SHA384:\
572DHE-RSA-CAMELLIA256-SHA256:\
573DHE-DSS-CAMELLIA256-SHA256:\
574ECDHE-ECDSA-AES128-SHA256:\
575ECDHE-RSA-AES128-SHA256:\
576DHE-RSA-AES128-SHA256:\
577DHE-DSS-AES128-SHA256:\
578ECDHE-ECDSA-CAMELLIA128-SHA256:\
579ECDHE-RSA-CAMELLIA128-SHA256:\
580DHE-RSA-CAMELLIA128-SHA256:\
581DHE-DSS-CAMELLIA128-SHA256:\
582ECDHE-ECDSA-AES256-SHA:\
583ECDHE-RSA-AES256-SHA:\
584DHE-RSA-AES256-SHA:\
585DHE-DSS-AES256-SHA:\
586DHE-RSA-CAMELLIA256-SHA:\
587DHE-DSS-CAMELLIA256-SHA:\
588ECDHE-ECDSA-AES128-SHA:\
589ECDHE-RSA-AES128-SHA:\
590DHE-RSA-AES128-SHA:\
591DHE-PSK-AES256-GCM-SHA384:\
592DHE-PSK-AES128-GCM-SHA256:\
593DHE-PSK-AES256-CBC-SHA384:\
594DHE-PSK-AES128-CBC-SHA256:\
595DHE-DSS-AES128-SHA:\
596DHE-RSA-SEED-SHA:\
597DHE-DSS-SEED-SHA:\
598DHE-RSA-CAMELLIA128-SHA:\
599DHE-DSS-CAMELLIA128-SHA:\
600AES256-GCM-SHA384:\
601AES256-CCM8:\
602AES256-CCM:\
603ARIA256-GCM-SHA384:\
604AES128-GCM-SHA256:\
605AES128-CCM8:\
606AES128-CCM:\
607ARIA128-GCM-SHA256:\
608AES256-SHA256:\
609CAMELLIA256-SHA256:\
610AES128-SHA256:\
611CAMELLIA128-SHA256:\
612AES256-SHA:\
613CAMELLIA256-SHA:\
614AES128-SHA:\
615SEED-SHA:\
616CAMELLIA128-SHA:\
617ECDHE-PSK-AES128-CBC-SHA256:\
618PSK-CHACHA20-POLY1305:\
619ECDHE-PSK-CHACHA20-POLY1305:\
620DHE-PSK-CHACHA20-POLY1305:\
621";
622
623impl Default for TLSDescriptorConfig {
624    fn default() -> Self {
625        Self {
626            tls_version: TLSVersion::V1_3,
627            client_authentication: false,
628            server_authentication: true,
629            try_reuse: false,
630            typ: AgentType::Server,
631            _cipher_string_tls13: TLS_DEFAULT_CIPHER.into(),
632            _cipher_string_tls12: TLS_DEFAULT_CIPHER.into(),
633            groups: None,
634            sigalgs: None,
635        }
636    }
637}
638
639#[derive(Clone, PartialEq, Eq, Debug, Hash, Serialize, Deserialize)]
640pub struct TLSProtocolTypes;
641
642impl ProtocolTypes for TLSProtocolTypes {
643    type Matcher = TlsQueryMatcher;
644    type PUTConfig = TLSDescriptorConfig;
645
646    fn signature() -> &'static Signature<Self> {
647        &TLS_SIGNATURE
648    }
649
650    fn differential_fuzzing_whitelist() -> Option<Vec<TypeId>> {
651        Some(vec![
652            TypeId::of::<AlertMessagePayload>(),
653            TypeId::of::<HandshakeMessagePayload>(),
654            TypeId::of::<HeartbeatPayload>(),
655        ])
656    }
657
658    fn differential_fuzzing_terms_to_eval(
659        agents: &Vec<AgentDescriptor<Self::PUTConfig>>,
660    ) -> Vec<puffin::algebra::Term<Self>> {
661        let mut is_server = false;
662        let mut server = AgentName::new();
663        let mut is_client = false;
664        let mut client = AgentName::new();
665
666        // Indentify which kind of agents are present in the trace to add the corresponding
667        // decryption recipe and apply them on the correct agent
668        for agent in agents {
669            if agent.protocol_config.typ == AgentType::Server {
670                is_server = true;
671                server = agent.name;
672            } else if agent.protocol_config.typ == AgentType::Client {
673                is_client = true;
674                client = agent.name;
675            }
676        }
677
678        let mut terms = vec![];
679
680        if is_server {
681            terms.push(term! {
682                fn_decrypt_handshake_flight_with_secret(
683                ((server, 0)[Some(TlsQueryMatcher::ServerHelloFlight)]/MessageFlight),
684                (fn_server_hello_transcript(((server, 0)))),
685                fn_true,
686                fn_seq_0,  // sequence 0
687                (fn_finished_get_client_random(((server, 0)))),
688                (fn_finished_get_cipher(((server, 0)))),
689                (fn_finished_get_handshake_secret(((server, 2))))
690            )
691            });
692        }
693
694        if is_client {
695            terms.push(term! {
696                fn_decrypt_handshake_flight_with_secret(
697                ((client, 0)[Some(TlsQueryMatcher::EncryptedFlight)]/MessageFlight),
698                (fn_server_hello_transcript(((client, 0)))),
699                fn_false,
700                fn_seq_0,
701                (fn_finished_get_client_random(((client, 0)))),
702                (fn_finished_get_cipher(((client, 0)))),
703                (fn_finished_get_handshake_secret(((client, 0))))
704            )
705            });
706        }
707
708        terms
709    }
710
711    fn differential_fuzzing_claims_blacklist() -> Option<Vec<TypeId>> {
712        Some(vec![
713            TypeId::of::<TranscriptCertificate>(),
714            TypeId::of::<TranscriptClientFinished>(),
715            TypeId::of::<TranscriptClientHello>(),
716            TypeId::of::<TranscriptPartialClientHello>(),
717            TypeId::of::<TranscriptServerFinished>(),
718            TypeId::of::<TranscriptServerHello>(),
719        ])
720    }
721
722    /// Apply a set of minimal configuration that should work with as much PUT as possible
723    ///
724    /// Use a set of TLS 1.2 and TLS 1.3 ciphers and curves that are mandatory to implement
725    /// according to the TLS RFCs
726    fn differential_fuzzing_uniformise_put_config(trace: Trace<Self>) -> Trace<Self> {
727        let mut uniformized_trace = trace.clone();
728        for agent in uniformized_trace.descriptors.iter_mut() {
729            agent.protocol_config.set_cipher_string_12(String::from(
730                "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
731            ));
732            agent.protocol_config.set_cipher_string_13(String::from(
733                "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256",
734            ));
735            agent.protocol_config.groups = Some(String::from("P-256:P-384"));
736            // Align signature algorithms so implementations agree on CertificateVerify scheme.
737            // LibreSSL 4.2.1 does not support SSL_CTX_set1_sigalgs_list at runtime, so
738            // its preference order is patched at build time (see patch_sigalgs.cmake) to
739            // put SHA256 first, matching OpenSSL's default. We configure OpenSSL's sigalgs
740            // to match this same order (SHA256 > SHA384 > SHA512).
741            agent.protocol_config.sigalgs = Some(String::from(
742                "RSA-PSS+SHA256:RSA-PSS+SHA384:RSA-PSS+SHA512:RSA+SHA256:RSA+SHA384:RSA+SHA512",
743            ));
744        }
745
746        for t in uniformized_trace.prior_traces.iter_mut() {
747            *t = Self::differential_fuzzing_uniformise_put_config(t.to_owned());
748        }
749
750        uniformized_trace
751    }
752
753    fn differential_fuzzing_filter_diff(diff: &TraceDifference) -> bool {
754        if let TraceDifference::Knowledges(puffin::differential::KnowledgeDiff::InnerDifference {
755            index: _,
756            type_name: _,
757            diff,
758            source: _,
759        }) = diff
760        {
761            // OpenSSL sends an optional EllipticCurves extension when renegociating
762            if diff.contains("UnknownExtensionDesc { typ: EllipticCurves }") {
763                return false;
764            }
765        }
766        true
767    }
768}
769
770impl std::fmt::Display for TLSProtocolTypes {
771    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
772        write!(f, "")
773    }
774}
775
776#[derive(Clone, Debug, PartialEq)]
777pub struct TLSProtocolBehavior;
778
779impl ProtocolBehavior for TLSProtocolBehavior {
780    type Claim = TlsClaim;
781    type OpaqueProtocolMessage = OpaqueMessage;
782    type OpaqueProtocolMessageFlight = OpaqueMessageFlight;
783    type ProtocolMessage = Message;
784    type ProtocolMessageFlight = MessageFlight;
785    type ProtocolTypes = TLSProtocolTypes;
786    type SecurityViolationPolicy = TlsSecurityViolationPolicy;
787
788    /// The TLS signature is deep: a message is built through a chain of wrappers (`fn_message` ->
789    /// ... -> the payload struct), and a `ClientHello` carrying one extension needs depth 9.
790    const ZOO_MAX_DEPTH: u16 = 14;
791    /// Unbounded, that depth produced terms of up to 1198 nodes; 64 is well above what the zoo
792    /// produces in practice (99th percentile ~20) and below `TermConstraints::max_term_size`.
793    const ZOO_MAX_SIZE: usize = 64;
794    /// A few symbols need it: filling a quota for the likes of `fn_derive_psk`, `fn_fill_binder`
795    /// or `fn_get_client_key_share` costs seconds.
796    const ZOO_MAX_TRIES: usize = 140_000;
797
798    fn corpus_registry() -> Vec<(&'static str, CorpusBuilder<Self>)> {
799        vec![
800            ("default", crate::tls::seeds::create_corpus),
801            (
802                "differential_rfc",
803                crate::tls::differential_rfc_violations::create_corpus,
804            ),
805            (
806                "vulnerabilities",
807                crate::tls::vulnerabilities::create_corpus,
808            ),
809        ]
810    }
811
812    fn try_read_bytes(
813        bitstring: &[u8],
814        ty: TypeId,
815    ) -> Result<Box<dyn EvaluatedTerm<Self::ProtocolTypes>>, Error> {
816        try_read_bytes(bitstring, ty)
817    }
818}