tlspuffin/
claims.rs

1use std::fmt::Debug;
2
3use comparable::Comparable;
4use puffin::agent::AgentName;
5use puffin::algebra::dynamic_function::TypeShape;
6use puffin::claims::Claim;
7use puffin::error::Error;
8use puffin::protocol::{EvaluatedTerm, Extractable, ProtocolTypes};
9use puffin::trace::{Knowledge, Source, StepNumber};
10use puffin::{codec, dummy_codec, dummy_extract_knowledge, dummy_extract_knowledge_codec};
11use security_claims::ClaimTLSVersion;
12use smallvec::SmallVec;
13
14use crate::protocol::{AgentType, TLSProtocolTypes, TLSVersion};
15
16#[derive(Debug, Clone, PartialEq, Comparable)]
17pub struct TlsTranscript(pub [u8; 64], pub i32);
18
19impl codec::Codec for TlsTranscript {
20    fn encode(&self, b: &mut Vec<u8>) {
21        if self.1 > 64 {
22            // We should never encode transcripts of size != 64
23            return;
24        }
25
26        b.push(self.1 as u8);
27        b.extend(&self.0[..self.1 as usize]);
28    }
29
30    fn read(r: &mut codec::Reader) -> Option<Self> {
31        let length = u8::read(r)?;
32        if length > 64 {
33            return None;
34        }
35        let mut t = [0u8; 64];
36        if let Some(bytes) = r.take(length as usize) {
37            t[..bytes.len()].copy_from_slice(bytes);
38        }
39        Some(TlsTranscript(t, length as i32))
40    }
41}
42dummy_extract_knowledge!(TLSProtocolTypes, TlsTranscript);
43
44#[derive(Debug, Clone, Comparable, PartialEq)]
45pub struct TranscriptClientHello(#[comparable_ignore] pub TlsTranscript);
46impl Transcript for TranscriptClientHello {
47    fn as_slice(&self) -> &[u8] {
48        let transcript = &self.0;
49        &transcript.0[..transcript.1 as usize]
50    }
51}
52
53impl codec::Codec for TranscriptClientHello {
54    fn encode(&self, b: &mut Vec<u8>) {
55        self.0.encode(b);
56    }
57
58    fn read(r: &mut codec::Reader) -> Option<Self> {
59        <TlsTranscript as codec::Codec>::read(r).map(TranscriptClientHello)
60    }
61}
62
63dummy_extract_knowledge!(TLSProtocolTypes, TranscriptClientHello);
64
65#[derive(Debug, Clone, Comparable, PartialEq)]
66pub struct TranscriptPartialClientHello(#[comparable_ignore] pub TlsTranscript);
67
68impl Transcript for TranscriptPartialClientHello {
69    fn as_slice(&self) -> &[u8] {
70        let transcript = &self.0;
71        &transcript.0[..transcript.1 as usize]
72    }
73}
74
75impl codec::Codec for TranscriptPartialClientHello {
76    fn encode(&self, b: &mut Vec<u8>) {
77        self.0.encode(b);
78    }
79
80    fn read(r: &mut codec::Reader) -> Option<Self> {
81        <TlsTranscript as codec::Codec>::read(r).map(TranscriptPartialClientHello)
82    }
83}
84
85dummy_extract_knowledge!(TLSProtocolTypes, TranscriptPartialClientHello);
86
87#[derive(Debug, Clone, Comparable, PartialEq)]
88pub struct TranscriptServerHello(#[comparable_ignore] pub TlsTranscript);
89
90impl Transcript for TranscriptServerHello {
91    fn as_slice(&self) -> &[u8] {
92        log::debug!("TranscriptServerHello.as_slice: {self:?}");
93        let transcript = &self.0;
94        &transcript.0[..transcript.1 as usize]
95    }
96}
97
98impl codec::Codec for TranscriptServerHello {
99    fn encode(&self, b: &mut Vec<u8>) {
100        self.0.encode(b)
101    }
102
103    fn read(r: &mut codec::Reader) -> Option<Self> {
104        <TlsTranscript as codec::Codec>::read(r).map(TranscriptServerHello)
105    }
106}
107
108dummy_extract_knowledge!(TLSProtocolTypes, TranscriptServerHello);
109
110#[derive(Debug, Clone, Comparable, PartialEq)]
111pub struct TranscriptServerFinished(#[comparable_ignore] pub TlsTranscript);
112
113impl Transcript for TranscriptServerFinished {
114    fn as_slice(&self) -> &[u8] {
115        let transcript = &self.0;
116        &transcript.0[..transcript.1 as usize]
117    }
118}
119
120impl codec::Codec for TranscriptServerFinished {
121    fn encode(&self, b: &mut Vec<u8>) {
122        self.0.encode(b);
123    }
124
125    fn read(r: &mut codec::Reader) -> Option<Self> {
126        <TlsTranscript as codec::Codec>::read(r).map(TranscriptServerFinished)
127    }
128}
129
130dummy_extract_knowledge!(TLSProtocolTypes, TranscriptServerFinished);
131
132#[derive(Debug, Clone, Comparable, PartialEq)]
133pub struct TranscriptClientFinished(#[comparable_ignore] pub TlsTranscript);
134
135impl Transcript for TranscriptClientFinished {
136    fn as_slice(&self) -> &[u8] {
137        let transcript = &self.0;
138        &transcript.0[..transcript.1 as usize]
139    }
140}
141
142impl codec::Codec for TranscriptClientFinished {
143    fn encode(&self, b: &mut Vec<u8>) {
144        self.0.encode(b);
145    }
146
147    fn read(r: &mut codec::Reader) -> Option<Self> {
148        <TlsTranscript as codec::Codec>::read(r).map(TranscriptClientFinished)
149    }
150}
151
152dummy_extract_knowledge!(TLSProtocolTypes, TranscriptClientFinished);
153
154#[derive(Debug, Clone, PartialEq, Comparable)]
155pub struct TranscriptCertificate(#[comparable_ignore] pub TlsTranscript);
156impl Transcript for TranscriptCertificate {
157    fn as_slice(&self) -> &[u8] {
158        let transcript = &self.0;
159        &transcript.0[..transcript.1 as usize]
160    }
161}
162dummy_extract_knowledge!(TLSProtocolTypes, TranscriptCertificate);
163
164impl codec::Codec for TranscriptCertificate {
165    fn encode(&self, b: &mut Vec<u8>) {
166        self.0.encode(b);
167    }
168
169    fn read(r: &mut codec::Reader) -> Option<Self> {
170        <TlsTranscript as codec::Codec>::read(r).map(TranscriptCertificate)
171    }
172}
173
174pub trait Transcript {
175    fn as_slice(&self) -> &[u8];
176}
177
178#[derive(Debug, Clone, Comparable, PartialEq)]
179pub struct ClientHello;
180// We do not expect to encode/read claims!
181dummy_extract_knowledge_codec!(TLSProtocolTypes, ClientHello);
182#[derive(Debug, Clone, Comparable, PartialEq)]
183pub struct ServerHello;
184dummy_extract_knowledge_codec!(TLSProtocolTypes, ServerHello);
185#[derive(Debug, Clone, Comparable, PartialEq)]
186pub struct Certificate;
187dummy_extract_knowledge_codec!(TLSProtocolTypes, Certificate);
188#[derive(Debug, Clone, Comparable, PartialEq)]
189pub struct CertificateVerify;
190dummy_extract_knowledge_codec!(TLSProtocolTypes, CertificateVerify);
191#[derive(Debug, Clone, Comparable, PartialEq)]
192pub struct Finished {
193    #[comparable_ignore]
194    pub outbound: bool,
195
196    #[comparable_ignore]
197    pub client_random: SmallVec<[u8; 32]>,
198    #[comparable_ignore]
199    pub server_random: SmallVec<[u8; 32]>,
200    #[comparable_ignore]
201    pub session_id: SmallVec<[u8; 32]>,
202
203    #[comparable_ignore]
204    pub authenticate_peer: bool,
205    /// DER encoded certificate. DER works, because:
206    ///     DER is a subset of BER providing for exactly one way to encode an ASN.1 value.
207    ///     (<https://en.wikipedia.org/wiki/X.690#DER_encoding>)
208    #[comparable_ignore]
209    pub peer_certificate: SmallVec<[u8; 32]>,
210    // #[comparable_synthetic {
211    //     // Since we cant compare SmallVec
212    //     let certificate_vec_u8 = |x: &Self| -> Vec<u8> { x.peer_certificate.as_slice().to_vec()
213    // }; }]
214    #[comparable_ignore]
215    pub early_secret: SmallVec<[u8; 32]>,
216    #[comparable_ignore]
217    pub handshake_secret: SmallVec<[u8; 32]>,
218    #[comparable_ignore]
219    pub master_secret: SmallVec<[u8; 32]>,
220
221    pub tls_version: ClaimTLSVersion,
222
223    pub chosen_cipher: u16,
224
225    // We ignore the list of ciphers because OpenSSL shows TLS 1.2 and 1.3 ciphers while wolfSSL
226    // shows only TLS 1.2 xor 1.3 ciphers
227    #[comparable_ignore]
228    pub available_ciphers: SmallVec<[u16; 20]>,
229    // #[comparable_synthetic {
230    //     // Since we cant compare SmallVec
231    //     let available_ciphers_vec_u16= |x: &Self| -> Vec<u16> {
232    // x.available_ciphers.as_slice().to_vec() }; }]
233
234    // FIXME: Right now we could not align sigalgs, should be fixed in https://github.com/tlspuffin/tlspuffin/pull/468
235    #[comparable_ignore]
236    pub signature_algorithm: i32,
237    #[comparable_ignore]
238    pub peer_signature_algorithm: i32,
239    /* TODO: tmp_skey_type peer_tmp_skey_type
240                   // TLS 1.2
241                   if let Some(server_kex) = claims.iter().find(|(_agent, claim)| {
242                       claim.write == 1
243                           && claim.server == 1
244                           && claim.typ == ClaimType::CLAIM_SERVER_DONE
245                   }) {
246                       if server_kex.1.tmp_skey_type != client.peer_tmp_skey_type {
247                           return Some("Mismatching ephemeral kex method");
248                       }
249                   } else {
250                       return Some("Server Done not found in server claims");
251                   }
252                   // TLS 1.3
253                   if client.tmp_skey_type != server.tmp_skey_type {
254                       return Some("Mismatching ephemeral kex method");
255                   }
256    */
257    /* TODO: tmp_skey_group_id
258                   // TLS 1.3
259                    if client.tmp_skey_group_id != server.tmp_skey_group_id {
260                        return Some("Mismatching groups");
261                    }
262    */
263}
264dummy_extract_knowledge_codec!(TLSProtocolTypes, Finished);
265
266#[derive(Debug, Clone, Comparable, PartialEq)]
267pub enum ClaimDataTranscript {
268    ClientHello(TranscriptClientHello),
269    PartialClientHello(TranscriptPartialClientHello),
270    ServerHello(TranscriptServerHello),
271    Certificate(TranscriptCertificate),
272    ServerFinished(TranscriptServerFinished),
273    ClientFinished(TranscriptClientFinished),
274}
275
276#[derive(Debug, Clone, Comparable, PartialEq)]
277pub enum ClaimDataMessage {
278    ClientHello(ClientHello),
279    ServerHello(ServerHello),
280    Certificate(Certificate),
281    CertificateVerify(CertificateVerify),
282    Finished(Finished),
283}
284
285#[derive(Debug, Clone, Comparable, PartialEq)]
286pub enum ClaimData {
287    Transcript(ClaimDataTranscript),
288    Message(ClaimDataMessage),
289}
290
291#[derive(Debug, Clone, Comparable, PartialEq)]
292pub struct TlsClaim {
293    pub agent_name: AgentName,
294    pub origin: AgentType,
295    pub config_version: TLSVersion,
296    pub data: ClaimData,
297    #[comparable_ignore]
298    pub step: Option<StepNumber>,
299}
300
301dummy_codec!(TLSProtocolTypes, TlsClaim);
302
303impl Claim for TlsClaim {
304    type PT = TLSProtocolTypes;
305
306    fn agent_name(&self) -> AgentName {
307        self.agent_name
308    }
309
310    fn id(&self) -> TypeShape<TLSProtocolTypes> {
311        type Message = ClaimDataMessage;
312        type Transcript = ClaimDataTranscript;
313        type Type = TypeShape<TLSProtocolTypes>;
314        match &self.data {
315            ClaimData::Message(message) => match message {
316                Message::ClientHello(_) => Type::of::<ClientHello>(),
317                Message::ServerHello(_) => Type::of::<ServerHello>(),
318                Message::Certificate(_) => Type::of::<Certificate>(),
319                Message::CertificateVerify(_) => Type::of::<CertificateVerify>(),
320                Message::Finished(_) => Type::of::<Finished>(),
321            },
322            ClaimData::Transcript(transcript) => match transcript {
323                Transcript::ClientHello(_) => Type::of::<TranscriptClientHello>(),
324                Transcript::PartialClientHello(_) => Type::of::<TranscriptPartialClientHello>(),
325                Transcript::ServerHello(_) => Type::of::<TranscriptServerHello>(),
326                Transcript::ServerFinished(_) => Type::of::<TranscriptServerFinished>(),
327                Transcript::ClientFinished(_) => Type::of::<TranscriptClientFinished>(),
328                Transcript::Certificate(_) => Type::of::<TranscriptCertificate>(),
329            },
330        }
331    }
332
333    fn inner(&self) -> Box<dyn EvaluatedTerm<TLSProtocolTypes>> {
334        type Message = ClaimDataMessage;
335        type Transcript = ClaimDataTranscript;
336        match &self.data {
337            ClaimData::Message(message) => match message {
338                Message::ClientHello(claim) => claim.boxed(),
339                Message::ServerHello(claim) => claim.boxed(),
340                Message::Certificate(claim) => claim.boxed(),
341                Message::CertificateVerify(claim) => claim.boxed(),
342                Message::Finished(claim) => claim.boxed(),
343            },
344            ClaimData::Transcript(transcript) => match transcript {
345                Transcript::ClientHello(claim) => claim.boxed(),
346                Transcript::PartialClientHello(claim) => claim.boxed(),
347                Transcript::ServerHello(claim) => claim.boxed(),
348                Transcript::ServerFinished(claim) => claim.boxed(),
349                Transcript::ClientFinished(claim) => claim.boxed(),
350                Transcript::Certificate(claim) => claim.boxed(),
351            },
352        }
353    }
354
355    fn set_step(&mut self, step: Option<StepNumber>) {
356        self.step = step;
357    }
358
359    fn get_step(&self) -> Option<StepNumber> {
360        self.step.clone()
361    }
362}
363
364impl Extractable<TLSProtocolTypes> for TlsClaim {
365    fn extract_knowledge(
366        &self,
367        _knowledges: &mut Vec<puffin::trace::Knowledge<TLSProtocolTypes>>,
368        _matcher: Option<<TLSProtocolTypes as puffin::protocol::ProtocolTypes>::Matcher>,
369        _source: &puffin::trace::Source,
370    ) -> Result<(), puffin::error::Error> {
371        Ok(())
372    }
373}
374
375pub mod claims_helpers {
376    use security_claims::ClaimTLSVersion;
377    use smallvec::SmallVec;
378
379    use crate::claims::{
380        ClaimData, ClaimDataMessage, ClaimDataTranscript, Finished, TlsTranscript,
381        TranscriptCertificate, TranscriptClientFinished, TranscriptClientHello,
382        TranscriptPartialClientHello, TranscriptServerFinished, TranscriptServerHello,
383    };
384
385    pub fn to_claim_data(claim: security_claims::Claim) -> Option<ClaimData> {
386        match claim.typ {
387            // Transcripts
388            security_claims::ClaimType::CLAIM_TRANSCRIPT_CH => Some(ClaimData::Transcript(
389                ClaimDataTranscript::ClientHello(TranscriptClientHello(TlsTranscript(
390                    claim.transcript.data,
391                    claim.transcript.length,
392                ))),
393            )),
394            security_claims::ClaimType::CLAIM_TRANSCRIPT_PARTIAL_CH => Some(ClaimData::Transcript(
395                ClaimDataTranscript::PartialClientHello(TranscriptPartialClientHello(
396                    TlsTranscript(claim.transcript.data, claim.transcript.length),
397                )),
398            )),
399            security_claims::ClaimType::CLAIM_TRANSCRIPT_CH_SH => Some(ClaimData::Transcript(
400                ClaimDataTranscript::ServerHello(TranscriptServerHello(TlsTranscript(
401                    claim.transcript.data,
402                    claim.transcript.length,
403                ))),
404            )),
405            security_claims::ClaimType::CLAIM_TRANSCRIPT_CH_SERVER_FIN => {
406                Some(ClaimData::Transcript(ClaimDataTranscript::ServerFinished(
407                    TranscriptServerFinished(TlsTranscript(
408                        claim.transcript.data,
409                        claim.transcript.length,
410                    )),
411                )))
412            }
413            security_claims::ClaimType::CLAIM_TRANSCRIPT_CH_CLIENT_FIN => {
414                Some(ClaimData::Transcript(ClaimDataTranscript::ClientFinished(
415                    TranscriptClientFinished(TlsTranscript(
416                        claim.transcript.data,
417                        claim.transcript.length,
418                    )),
419                )))
420            }
421            security_claims::ClaimType::CLAIM_TRANSCRIPT_CH_CERT => Some(ClaimData::Transcript(
422                ClaimDataTranscript::Certificate(TranscriptCertificate(TlsTranscript(
423                    claim.transcript.data,
424                    claim.transcript.length,
425                ))),
426            )),
427            // Messages
428            // Transcripts in these messages are not up-to-date. They get updated after the Message
429            // has been processed
430            security_claims::ClaimType::CLAIM_FINISHED => {
431                let peer_certificate = if claim.peer_authentication == 1
432                    && matches!(claim.peer_cert.data_length, 1..10240)
433                {
434                    SmallVec::from_slice(
435                        &claim.peer_cert.data[..claim.peer_cert.data_length as usize],
436                    )
437                } else {
438                    Default::default()
439                };
440                Some(ClaimData::Message(ClaimDataMessage::Finished(Finished {
441                    outbound: claim.write > 0,
442                    client_random: SmallVec::from(claim.client_random.data),
443                    server_random: SmallVec::from(claim.server_random.data),
444                    session_id: SmallVec::from_slice(
445                        &claim.session_id.data[..claim.session_id.length as usize],
446                    ),
447                    authenticate_peer: claim.peer_authentication == 1,
448                    peer_certificate,
449                    early_secret: SmallVec::from_slice(&claim.early_secret.secret),
450                    handshake_secret: SmallVec::from_slice(&claim.handshake_secret.secret),
451                    master_secret: match claim.version.data {
452                        ClaimTLSVersion::CLAIM_TLS_VERSION_V1_3
453                        | ClaimTLSVersion::CLAIM_TLS_VERSION_UNDEFINED => {
454                            SmallVec::from_slice(&claim.master_secret.secret)
455                        }
456                        ClaimTLSVersion::CLAIM_TLS_VERSION_V1_2 => {
457                            SmallVec::from_slice(&claim.master_secret_12.secret)
458                        }
459                    },
460                    tls_version: claim.version.data,
461                    chosen_cipher: claim.chosen_cipher.data,
462                    available_ciphers: SmallVec::from_iter(
463                        claim.available_ciphers.ciphers[..claim.available_ciphers.length as usize]
464                            .iter()
465                            .map(|cipher| cipher.data),
466                    ),
467                    signature_algorithm: claim.signature_algorithm,
468                    peer_signature_algorithm: claim.peer_signature_algorithm,
469                })))
470            }
471            security_claims::ClaimType::CLAIM_CLIENT_HELLO => None,
472            security_claims::ClaimType::CLAIM_CCS => None,
473            security_claims::ClaimType::CLAIM_END_OF_EARLY_DATA => None,
474            security_claims::ClaimType::CLAIM_CERTIFICATE => None,
475            security_claims::ClaimType::CLAIM_KEY_EXCHANGE => None,
476            security_claims::ClaimType::CLAIM_CERTIFICATE_VERIFY => Some(ClaimData::Transcript(
477                ClaimDataTranscript::ServerFinished(TranscriptServerFinished(TlsTranscript(
478                    claim.transcript.data,
479                    claim.transcript.length,
480                ))),
481            )),
482            security_claims::ClaimType::CLAIM_KEY_UPDATE => None,
483            security_claims::ClaimType::CLAIM_HELLO_REQUEST => None,
484            security_claims::ClaimType::CLAIM_SERVER_HELLO => None,
485            security_claims::ClaimType::CLAIM_CERTIFICATE_REQUEST => None,
486            security_claims::ClaimType::CLAIM_SERVER_DONE => None,
487            security_claims::ClaimType::CLAIM_SESSION_TICKET => None,
488            security_claims::ClaimType::CLAIM_CERTIFICATE_STATUS => None,
489            security_claims::ClaimType::CLAIM_EARLY_DATA => None,
490            security_claims::ClaimType::CLAIM_ENCRYPTED_EXTENSIONS => None,
491            _ => None,
492        }
493    }
494}