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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
use std::fmt::Debug;

use puffin::agent::{AgentName, AgentType, TLSVersion};
use puffin::algebra::dynamic_function::TypeShape;
use puffin::claims::Claim;
use puffin::dummy_extract_knowledge;
use puffin::error::Error;
use puffin::protocol::{EvaluatedTerm, ProtocolTypes};
use puffin::trace::{Knowledge, Source};
use puffin::variable_data::VariableData;
use smallvec::SmallVec;

use crate::protocol::TLSProtocolTypes;

#[cfg(not(has_instr = "claimer"))]
pub mod dummy_registration {
    #[no_mangle]
    pub extern "C" fn register_claimer(
        _tls_like: *const ::std::os::raw::c_void,
        _claimer: security_claims::claim_t,
        _ctx: *mut ::std::os::raw::c_void,
    ) {
        // NOTE dummy implementation when the C ffi implementation is missing
    }

    #[no_mangle]
    pub extern "C" fn deregister_claimer(
        _tls_like: *const ::std::os::raw::c_void,
    ) -> *mut ::std::os::raw::c_void {
        // NOTE dummy implementation when the C ffi implementation is missing
        ::std::ptr::null_mut()
    }
}

#[derive(Debug, Clone)]
pub struct TlsTranscript(pub [u8; 64], pub i32);

#[derive(Debug, Clone)]
pub struct TranscriptClientHello(pub TlsTranscript);
impl Transcript for TranscriptClientHello {
    fn as_slice(&self) -> &[u8] {
        let transcript = &self.0;
        &transcript.0[..transcript.1 as usize]
    }
}
dummy_extract_knowledge!(TLSProtocolTypes, TranscriptClientHello);

#[derive(Debug, Clone)]
pub struct TranscriptPartialClientHello(pub TlsTranscript);
impl Transcript for TranscriptPartialClientHello {
    fn as_slice(&self) -> &[u8] {
        let transcript = &self.0;
        &transcript.0[..transcript.1 as usize]
    }
}
dummy_extract_knowledge!(TLSProtocolTypes, TranscriptPartialClientHello);

#[derive(Debug, Clone)]
pub struct TranscriptServerHello(pub TlsTranscript);
impl Transcript for TranscriptServerHello {
    fn as_slice(&self) -> &[u8] {
        let transcript = &self.0;
        &transcript.0[..transcript.1 as usize]
    }
}
dummy_extract_knowledge!(TLSProtocolTypes, TranscriptServerHello);

#[derive(Debug, Clone)]
pub struct TranscriptServerFinished(pub TlsTranscript);
impl Transcript for TranscriptServerFinished {
    fn as_slice(&self) -> &[u8] {
        let transcript = &self.0;
        &transcript.0[..transcript.1 as usize]
    }
}
dummy_extract_knowledge!(TLSProtocolTypes, TranscriptServerFinished);

#[derive(Debug, Clone)]
pub struct TranscriptClientFinished(pub TlsTranscript);
impl Transcript for TranscriptClientFinished {
    fn as_slice(&self) -> &[u8] {
        let transcript = &self.0;
        &transcript.0[..transcript.1 as usize]
    }
}
dummy_extract_knowledge!(TLSProtocolTypes, TranscriptClientFinished);

#[derive(Debug, Clone)]
pub struct TranscriptCertificate(pub TlsTranscript);
impl Transcript for TranscriptCertificate {
    fn as_slice(&self) -> &[u8] {
        let transcript = &self.0;
        &transcript.0[..transcript.1 as usize]
    }
}
dummy_extract_knowledge!(TLSProtocolTypes, TranscriptCertificate);

pub trait Transcript {
    fn as_slice(&self) -> &[u8];
}

#[derive(Debug, Clone)]
pub struct ClientHello;
dummy_extract_knowledge!(TLSProtocolTypes, ClientHello);
#[derive(Debug, Clone)]
pub struct ServerHello;
dummy_extract_knowledge!(TLSProtocolTypes, ServerHello);
#[derive(Debug, Clone)]
pub struct Certificate;
dummy_extract_knowledge!(TLSProtocolTypes, Certificate);
#[derive(Debug, Clone)]
pub struct CertificateVerify;
dummy_extract_knowledge!(TLSProtocolTypes, CertificateVerify);
#[derive(Debug, Clone)]
pub struct Finished {
    pub outbound: bool,

    pub client_random: SmallVec<[u8; 32]>,
    pub server_random: SmallVec<[u8; 32]>,
    pub session_id: SmallVec<[u8; 32]>,

    pub authenticate_peer: bool,
    /// DER encoded certificate. DER works, because:
    ///     DER is a subset of BER providing for exactly one way to encode an ASN.1 value.
    ///     (<https://en.wikipedia.org/wiki/X.690#DER_encoding>)
    pub peer_certificate: SmallVec<[u8; 32]>,

    pub master_secret: SmallVec<[u8; 32]>,

    pub chosen_cipher: u16,
    pub available_ciphers: SmallVec<[u16; 20]>,

    pub signature_algorithm: i32,
    pub peer_signature_algorithm: i32,
    /* TODO: tmp_skey_type peer_tmp_skey_type
                   // TLS 1.2
                   if let Some(server_kex) = claims.iter().find(|(_agent, claim)| {
                       claim.write == 1
                           && claim.server == 1
                           && claim.typ == ClaimType::CLAIM_SERVER_DONE
                   }) {
                       if server_kex.1.tmp_skey_type != client.peer_tmp_skey_type {
                           return Some("Mismatching ephemeral kex method");
                       }
                   } else {
                       return Some("Server Done not found in server claims");
                   }
                   // TLS 1.3
                   if client.tmp_skey_type != server.tmp_skey_type {
                       return Some("Mismatching ephemeral kex method");
                   }
    */
    /* TODO: tmp_skey_group_id
                   // TLS 1.3
                    if client.tmp_skey_group_id != server.tmp_skey_group_id {
                        return Some("Mismatching groups");
                    }
    */
}
dummy_extract_knowledge!(TLSProtocolTypes, Finished);

#[derive(Debug, Clone)]
pub enum ClaimDataTranscript {
    ClientHello(TranscriptClientHello),
    PartialClientHello(TranscriptPartialClientHello),
    ServerHello(TranscriptServerHello),
    Certificate(TranscriptCertificate),
    ServerFinished(TranscriptServerFinished),
    ClientFinished(TranscriptClientFinished),
}

#[derive(Debug, Clone)]
pub enum ClaimDataMessage {
    ClientHello(ClientHello),
    ServerHello(ServerHello),
    Certificate(Certificate),
    CertificateVerify(CertificateVerify),
    Finished(Finished),
}

#[derive(Debug, Clone)]
pub enum ClaimData {
    Transcript(ClaimDataTranscript),
    Message(ClaimDataMessage),
}

#[derive(Debug, Clone)]
pub struct TlsClaim {
    pub agent_name: AgentName,
    pub origin: AgentType,
    pub protocol_version: TLSVersion,
    pub data: ClaimData,
}

impl Claim<TLSProtocolTypes> for TlsClaim {
    fn agent_name(&self) -> AgentName {
        self.agent_name
    }

    fn id(&self) -> TypeShape<TLSProtocolTypes> {
        type Message = ClaimDataMessage;
        type Transcript = ClaimDataTranscript;
        type Type = TypeShape<TLSProtocolTypes>;
        match &self.data {
            ClaimData::Message(message) => match message {
                Message::ClientHello(_) => Type::of::<ClientHello>(),
                Message::ServerHello(_) => Type::of::<ServerHello>(),
                Message::Certificate(_) => Type::of::<Certificate>(),
                Message::CertificateVerify(_) => Type::of::<CertificateVerify>(),
                Message::Finished(_) => Type::of::<Finished>(),
            },
            ClaimData::Transcript(transcript) => match transcript {
                Transcript::ClientHello(_) => Type::of::<TranscriptClientHello>(),
                Transcript::PartialClientHello(_) => Type::of::<TranscriptPartialClientHello>(),
                Transcript::ServerHello(_) => Type::of::<TranscriptServerHello>(),
                Transcript::ServerFinished(_) => Type::of::<TranscriptServerFinished>(),
                Transcript::ClientFinished(_) => Type::of::<TranscriptClientFinished>(),
                Transcript::Certificate(_) => Type::of::<TranscriptCertificate>(),
            },
        }
    }

    fn inner(&self) -> Box<dyn EvaluatedTerm<TLSProtocolTypes>> {
        type Message = ClaimDataMessage;
        type Transcript = ClaimDataTranscript;
        match &self.data {
            ClaimData::Message(message) => match message {
                Message::ClientHello(claim) => claim.boxed_term(),
                Message::ServerHello(claim) => claim.boxed_term(),
                Message::Certificate(claim) => claim.boxed_term(),
                Message::CertificateVerify(claim) => claim.boxed_term(),
                Message::Finished(claim) => claim.boxed_term(),
            },
            ClaimData::Transcript(transcript) => match transcript {
                Transcript::ClientHello(claim) => claim.boxed_term(),
                Transcript::PartialClientHello(claim) => claim.boxed_term(),
                Transcript::ServerHello(claim) => claim.boxed_term(),
                Transcript::ServerFinished(claim) => claim.boxed_term(),
                Transcript::ClientFinished(claim) => claim.boxed_term(),
                Transcript::Certificate(claim) => claim.boxed_term(),
            },
        }
    }
}

impl EvaluatedTerm<TLSProtocolTypes> for TlsClaim {
    fn extract_knowledge(
        &self,
        _knowledges: &mut Vec<puffin::trace::Knowledge<TLSProtocolTypes>>,
        _matcher: Option<<TLSProtocolTypes as puffin::protocol::ProtocolTypes>::Matcher>,
        _source: &puffin::trace::Source,
    ) -> Result<(), puffin::error::Error> {
        Ok(())
    }
}

pub mod claims_helpers {
    use puffin::agent::TLSVersion;
    use smallvec::SmallVec;

    use crate::claims::{
        ClaimData, ClaimDataMessage, ClaimDataTranscript, Finished, TlsTranscript,
        TranscriptCertificate, TranscriptClientFinished, TranscriptClientHello,
        TranscriptPartialClientHello, TranscriptServerFinished, TranscriptServerHello,
    };

    pub fn to_claim_data(
        protocol_version: TLSVersion,
        claim: security_claims::Claim,
    ) -> Option<ClaimData> {
        match claim.typ {
            // Transcripts
            security_claims::ClaimType::CLAIM_TRANSCRIPT_CH => Some(ClaimData::Transcript(
                ClaimDataTranscript::ClientHello(TranscriptClientHello(TlsTranscript(
                    claim.transcript.data,
                    claim.transcript.length,
                ))),
            )),
            security_claims::ClaimType::CLAIM_TRANSCRIPT_PARTIAL_CH => Some(ClaimData::Transcript(
                ClaimDataTranscript::PartialClientHello(TranscriptPartialClientHello(
                    TlsTranscript(claim.transcript.data, claim.transcript.length),
                )),
            )),
            security_claims::ClaimType::CLAIM_TRANSCRIPT_CH_SH => Some(ClaimData::Transcript(
                ClaimDataTranscript::ServerHello(TranscriptServerHello(TlsTranscript(
                    claim.transcript.data,
                    claim.transcript.length,
                ))),
            )),
            security_claims::ClaimType::CLAIM_TRANSCRIPT_CH_SERVER_FIN => {
                Some(ClaimData::Transcript(ClaimDataTranscript::ServerFinished(
                    TranscriptServerFinished(TlsTranscript(
                        claim.transcript.data,
                        claim.transcript.length,
                    )),
                )))
            }
            security_claims::ClaimType::CLAIM_TRANSCRIPT_CH_CLIENT_FIN => {
                Some(ClaimData::Transcript(ClaimDataTranscript::ClientFinished(
                    TranscriptClientFinished(TlsTranscript(
                        claim.transcript.data,
                        claim.transcript.length,
                    )),
                )))
            }
            security_claims::ClaimType::CLAIM_TRANSCRIPT_CH_CERT => Some(ClaimData::Transcript(
                ClaimDataTranscript::Certificate(TranscriptCertificate(TlsTranscript(
                    claim.transcript.data,
                    claim.transcript.length,
                ))),
            )),
            // Messages
            // Transcripts in these messages are not up-to-date. They get updated after the Message
            // has been processed
            security_claims::ClaimType::CLAIM_FINISHED => {
                Some(ClaimData::Message(ClaimDataMessage::Finished(Finished {
                    outbound: claim.write > 0,
                    client_random: SmallVec::from(claim.client_random.data),
                    server_random: SmallVec::from(claim.server_random.data),
                    session_id: SmallVec::from_slice(
                        &claim.session_id.data[..claim.session_id.length as usize],
                    ),
                    authenticate_peer: false,             // FIXME
                    peer_certificate: Default::default(), // FIXME
                    master_secret: match protocol_version {
                        TLSVersion::V1_3 => SmallVec::from_slice(&claim.master_secret.secret),
                        TLSVersion::V1_2 => SmallVec::from_slice(&claim.master_secret_12.secret),
                    },
                    chosen_cipher: claim.chosen_cipher.data,
                    available_ciphers: SmallVec::from_iter(
                        claim.available_ciphers.ciphers[..claim.available_ciphers.length as usize]
                            .iter()
                            .map(|cipher| cipher.data),
                    ),
                    signature_algorithm: claim.signature_algorithm,
                    peer_signature_algorithm: claim.peer_signature_algorithm,
                })))
            }
            security_claims::ClaimType::CLAIM_CLIENT_HELLO => None,
            security_claims::ClaimType::CLAIM_CCS => None,
            security_claims::ClaimType::CLAIM_END_OF_EARLY_DATA => None,
            security_claims::ClaimType::CLAIM_CERTIFICATE => None,
            security_claims::ClaimType::CLAIM_KEY_EXCHANGE => None,
            // FIXME it is weird that this returns the correct transcript
            security_claims::ClaimType::CLAIM_CERTIFICATE_VERIFY => {
                if claim.write == 0 {
                    Some(ClaimData::Transcript(ClaimDataTranscript::ServerFinished(
                        TranscriptServerFinished(TlsTranscript(
                            claim.transcript.data,
                            claim.transcript.length,
                        )),
                    )))
                } else {
                    None
                }
            }
            security_claims::ClaimType::CLAIM_KEY_UPDATE => None,
            security_claims::ClaimType::CLAIM_HELLO_REQUEST => None,
            security_claims::ClaimType::CLAIM_SERVER_HELLO => None,
            security_claims::ClaimType::CLAIM_CERTIFICATE_REQUEST => None,
            security_claims::ClaimType::CLAIM_SERVER_DONE => None,
            security_claims::ClaimType::CLAIM_SESSION_TICKET => None,
            security_claims::ClaimType::CLAIM_CERTIFICATE_STATUS => None,
            security_claims::ClaimType::CLAIM_EARLY_DATA => None,
            security_claims::ClaimType::CLAIM_ENCRYPTED_EXTENSIONS => None,
            _ => None,
        }
    }
}