puffin/
trace.rs

1//! This module define the execution [`Trace`]s.
2//!
3//! Each [`Trace`]s consist of several [`Step`]s, of which each has either an [`OutputAction`] or
4//! [`InputAction`]. This is a declarative way of modeling communication between [`Agent`]s. The
5//! [`TraceContext`] holds data, also known as [`Knowledge`], which is created by [`Agent`]s
6//! during the concrete execution of the Trace. It also holds the [`Agent`]s with the references to
7//! concrete PUT.
8//!
9//! ### Serializability of Traces
10//!
11//! Each trace is serializable to JSON or even binary data. This helps at reproducing discovered
12//! security vulnerabilities during fuzzing. If a trace triggers a security vulnerability we can
13//! store it on disk and replay it when investigating the case.
14//! As traces depend on concrete implementations as discussed in the next section we need to link
15//! serialized data like strings or numerical IDs to functions implemented in Rust.
16
17use core::fmt;
18use std::any::TypeId;
19use std::cmp::PartialEq;
20use std::collections::HashMap;
21use std::fmt::{Debug, Display};
22use std::hash::Hash;
23use std::marker::PhantomData;
24use std::mem;
25use std::result::Result;
26use std::vec::IntoIter;
27
28use comparable::Comparable;
29use serde::{Deserialize, Serialize, Serializer};
30
31use crate::agent::{Agent, AgentDescriptor, AgentName};
32use crate::algebra::bitstrings::Payloads;
33use crate::algebra::dynamic_function::TypeShape;
34use crate::algebra::{remove_prefix, Matcher, Term, TermType};
35use crate::claims::{Claim, GlobalClaimList, SecurityViolationPolicy};
36use crate::differential::TraceDifference;
37use crate::error::Error;
38use crate::fuzzer::stats_stage::{
39    ALL_EXEC, ALL_EXEC_AGENT_SUCCESS, ALL_EXEC_SUCCESS, ERROR_AGENT, ERROR_CODEC, ERROR_EXTRACTION,
40    ERROR_FN, ERROR_IO, ERROR_PUT, ERROR_STREAM, ERROR_TERM, ERROR_TERMBUG,
41};
42use crate::fuzzer::utils::TracePath;
43use crate::protocol::{EvaluatedTerm, ProtocolBehavior, ProtocolTypes};
44use crate::put::PutDescriptor;
45use crate::put_registry::PutRegistry;
46use crate::stream::Stream;
47use crate::trace::Action::Input;
48
49#[derive(Debug, Deserialize, Serialize, Clone, Hash, Eq, PartialEq)]
50pub struct Query<M> {
51    pub source: Option<Source>,
52    pub matcher: Option<M>,
53    pub counter: u16, // in case an agent sends multiple messages of the same type
54}
55
56impl<M: Matcher> fmt::Display for Query<M> {
57    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58        write!(
59            f,
60            "({:?}, {})[{:?}]",
61            self.source, self.counter, self.matcher
62        )
63    }
64}
65
66/// [Source] stores the origin of a knowledge, whether the agent name or
67/// the label of the precomputation that produced it
68#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize, Serialize)]
69pub enum Source {
70    Agent(AgentName),
71    Label(Option<String>),
72}
73
74impl fmt::Display for Source {
75    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
76        match self {
77            Self::Agent(x) => write!(f, "agent:{x}"),
78            Self::Label(x) => write!(f, "label:{x:?}"),
79        }
80    }
81}
82
83/// [Knowledge] describes an atomic piece of knowledge inferred by the
84/// [`crate::protocol::Extractable::extract_knowledge`] function
85/// [Knowledge] is made of the data, the source of the output, the
86/// TLS message type and the internal type.
87#[derive(Debug)]
88pub struct Knowledge<'a, PT: ProtocolTypes> {
89    pub source: &'a Source,
90    pub matcher: Option<PT::Matcher>,
91    pub data: &'a dyn EvaluatedTerm<PT>,
92}
93
94/// [`RawKnowledge`] stores
95#[derive(Debug)]
96pub struct RawKnowledge<PT: ProtocolTypes> {
97    pub source: Source,
98    /// the step of the trace that produced this knowledge
99    pub step: Option<StepNumber>,
100    pub matcher: Option<PT::Matcher>,
101    pub associated_term: Option<Term<PT>>,
102    pub data: Box<dyn EvaluatedTerm<PT>>,
103}
104
105impl<PT: ProtocolTypes> fmt::Display for RawKnowledge<PT> {
106    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
107        write!(f, "({})/{:?}", self.source, self.matcher)
108    }
109}
110
111impl<'a, PT: ProtocolTypes> IntoIterator for &'a RawKnowledge<PT> {
112    type IntoIter = IntoIter<Knowledge<'a, PT>>;
113    type Item = Knowledge<'a, PT>;
114
115    fn into_iter(self) -> Self::IntoIter {
116        let mut knowledges = vec![];
117        let _ = self
118            .data
119            .extract_knowledge(&mut knowledges, self.matcher.clone(), &self.source);
120        knowledges.into_iter()
121    }
122}
123
124impl<PT: ProtocolTypes> Knowledge<'_, PT> {
125    pub fn specificity(&self) -> u32 {
126        self.matcher.specificity()
127    }
128}
129
130impl<PT: ProtocolTypes> Knowledge<'_, PT> {
131    pub fn debug_print<PB>(&self, ctx: &TraceContext<PB>, source: &Source)
132    where
133        PB: ProtocolBehavior<ProtocolTypes = PT>,
134    {
135        let data_type_id = self.data.type_id();
136        log::debug!(
137            "New knowledge {}: {}  (counter: {})",
138            &self,
139            remove_prefix(self.data.type_name()),
140            ctx.number_matching_message_with_source(source.clone(), data_type_id, &self.matcher)
141        );
142        log::debug!("Knowledge data: {:?}", self.data);
143    }
144}
145
146impl<PT: ProtocolTypes> fmt::Display for Knowledge<'_, PT> {
147    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
148        write!(f, "({})/{:?}", self.source, self.matcher)
149    }
150}
151
152#[derive(Debug, Default)]
153pub struct KnowledgeStore<PT: ProtocolTypes> {
154    raw_knowledge: Vec<RawKnowledge<PT>>,
155}
156
157impl<PT: ProtocolTypes> KnowledgeStore<PT> {
158    #[must_use]
159    pub const fn new() -> Self {
160        Self {
161            raw_knowledge: vec![],
162        }
163    }
164
165    pub fn add_raw_knowledge<T: EvaluatedTerm<PT> + 'static>(
166        &mut self,
167        data: T,
168        step: Option<StepNumber>,
169        source: Source,
170        term: Option<Term<PT>>,
171    ) {
172        log::trace!("Adding raw knowledge for {:?}", &data);
173
174        self.raw_knowledge.push(RawKnowledge {
175            source,
176            matcher: None,
177            data: Box::new(data),
178            associated_term: term,
179            step,
180        });
181    }
182
183    pub fn add_raw_boxed_knowledge(
184        &mut self,
185        data: Box<dyn EvaluatedTerm<PT>>,
186        step: Option<StepNumber>,
187        source: Source,
188        term: Option<Term<PT>>,
189    ) {
190        log::trace!("Adding raw knowledge : {:?}", &data);
191
192        self.raw_knowledge.push(RawKnowledge {
193            source,
194            matcher: None,
195            data,
196            associated_term: term,
197            step,
198        });
199    }
200
201    pub fn number_matching_message_with_source(
202        &self,
203        source: Source,
204        type_id: TypeId,
205        tls_message_type: &Option<PT::Matcher>,
206    ) -> usize {
207        self.raw_knowledge
208            .iter()
209            .filter(|raw| raw.source == source)
210            .flatten()
211            .filter(|knowledge| {
212                knowledge.matcher == *tls_message_type && knowledge.data.type_id() == type_id
213            })
214            .count()
215    }
216
217    /// Count the number of sub-messages of type `type_id` in the output message.
218    pub fn number_matching_message(
219        &self,
220        type_id: TypeId,
221        tls_message_type: &Option<PT::Matcher>,
222    ) -> usize {
223        self.raw_knowledge
224            .iter()
225            .flatten()
226            .filter(|knowledge| {
227                knowledge.matcher == *tls_message_type && knowledge.data.type_id() == type_id
228            })
229            .count()
230    }
231
232    /// Returns the variable which matches best -> highest specificity
233    /// If we want a variable with lower specificity, then we can just query less specific
234    pub fn find_variable(
235        &self,
236        query_type_shape: TypeShape<PT>,
237        query: &Query<PT::Matcher>,
238    ) -> Option<&dyn EvaluatedTerm<PT>> {
239        log::trace!(
240            "Looking for variable {:?} with query_type_shape {:?} and query {:?}",
241            self,
242            query_type_shape,
243            query
244        );
245        let query_type_id: TypeId = query_type_shape.into();
246
247        let mut possibilities: Vec<Knowledge<PT>> = self
248            .raw_knowledge
249            .iter()
250            .filter(|raw| query.source.is_none() || query.source.as_ref().unwrap() == &raw.source)
251            .flatten()
252            .filter(|knowledge| {
253                query_type_id == knowledge.data.type_id()
254                    && knowledge.matcher.matches(&query.matcher)
255            })
256            .collect();
257
258        possibilities.sort_by_key(Knowledge::specificity);
259
260        possibilities
261            .get(query.counter as usize)
262            .map(|possibility| possibility.data)
263    }
264
265    pub fn knowledges(&self) -> &Vec<RawKnowledge<PT>> {
266        &self.raw_knowledge
267    }
268
269    pub fn compare(&self, other: &Self) -> Result<(), Vec<TraceDifference>> {
270        let whitelist = PT::differential_fuzzing_whitelist();
271
272        let mut differences: Vec<TraceDifference> = vec![];
273
274        let mut first_store: Vec<Knowledge<'_, PT>> = self
275            .knowledges()
276            .iter()
277            .flatten()
278            .filter(|x| filter_knowledge(x, &whitelist))
279            .collect();
280        let mut second_store: Vec<Knowledge<'_, PT>> = other
281            .knowledges()
282            .iter()
283            .flatten()
284            .filter(|x| filter_knowledge(x, &whitelist))
285            .collect();
286        let first_store_count = first_store.len();
287        let second_store_count = second_store.len();
288
289        if first_store_count > second_store_count {
290            second_store.extend((second_store_count..first_store_count).map(|_| Knowledge {
291                source: &Source::Label(None),
292                matcher: None,
293                data: &(),
294            }))
295        } else {
296            first_store.extend((first_store_count..second_store_count).map(|_| Knowledge {
297                source: &Source::Label(None),
298                matcher: None,
299                data: &(),
300            }))
301        }
302
303        log::trace!("Comparing knowledge stores");
304        let _ = std::iter::zip(first_store, second_store)
305            .enumerate()
306            .for_each(|(idx, (x, y))| {
307                log::trace!(
308                    "{} (source:{}) | {} (source:{})",
309                    x.data.type_name(),
310                    x.source,
311                    y.data.type_name(),
312                    y.source
313                );
314                x.data
315                    .find_differences(y.data, &mut differences, idx, x.source, y.source);
316            });
317
318        match differences.is_empty() {
319            false => Err(differences),
320            true => Ok(()),
321        }
322    }
323}
324
325/// Should a specific knowledge be kept
326fn filter_knowledge<PT: ProtocolTypes>(
327    knowledge: &Knowledge<PT>,
328    whitelist: &Option<Vec<TypeId>>,
329) -> bool {
330    if whitelist.is_none() {
331        return true;
332    }
333
334    if let Some(list) = whitelist {
335        if !list.iter().any(|x| x == &knowledge.data.type_id()) {
336            return false;
337        }
338    }
339
340    true
341}
342
343#[derive(Debug)]
344pub struct Spawner<PB: ProtocolBehavior> {
345    registry: PutRegistry<PB>,
346    descriptors: HashMap<AgentName, PutDescriptor>,
347    default: PutDescriptor,
348}
349
350impl<PB: ProtocolBehavior> Spawner<PB> {
351    pub fn new(registry: impl Into<PutRegistry<PB>>) -> Self {
352        let registry = registry.into();
353        Self {
354            default: registry.default_put().clone(),
355            registry,
356            descriptors: Default::default(),
357        }
358    }
359
360    #[must_use]
361    pub fn with_mapping(mut self, descriptors: &[(AgentName, PutDescriptor)]) -> Self {
362        self.descriptors.extend(descriptors.iter().cloned());
363        self
364    }
365
366    pub fn spawn(
367        &self,
368        claims: &GlobalClaimList<PB::Claim>,
369        descriptor: &AgentDescriptor<<PB::ProtocolTypes as ProtocolTypes>::PUTConfig>,
370    ) -> Result<Agent<PB>, Error> {
371        let put_descriptor = self
372            .descriptors
373            .get(&descriptor.name)
374            .cloned()
375            .unwrap_or_else(|| self.default.clone());
376
377        let factory = self
378            .registry
379            .find_by_id(&put_descriptor.factory)
380            .ok_or_else(|| {
381                Error::Agent(format!(
382                    "unable to find PUT {} factory in binary",
383                    &put_descriptor.factory
384                ))
385            })?;
386
387        let put = factory.create(descriptor, claims, &put_descriptor.options)?;
388        Ok(Agent::new(descriptor.clone(), put))
389    }
390}
391
392impl<PB: ProtocolBehavior + PartialEq> PartialEq for Spawner<PB> {
393    fn eq(&self, other: &Self) -> bool {
394        self.registry == other.registry
395            && self.descriptors == other.descriptors
396            && self.default == other.default
397    }
398}
399
400impl<PB: ProtocolBehavior> Clone for Spawner<PB> {
401    fn clone(&self) -> Self {
402        Self {
403            registry: self.registry.clone(),
404            descriptors: self.descriptors.clone(),
405            default: self.default.clone(),
406        }
407    }
408}
409
410#[derive(Debug, PartialEq, Clone, Copy)]
411pub struct ConfigTrace {
412    pub with_bit_level: bool,
413    pub with_reseed: bool,
414    /// This is used in differential fuzzing
415    pub check_security_violation: bool,
416}
417impl Default for ConfigTrace {
418    fn default() -> Self {
419        ConfigTrace {
420            with_bit_level: true,
421            with_reseed: true,
422            check_security_violation: true,
423        }
424    }
425}
426
427/// The [`TraceContext`] represents the state of an execution.
428///
429/// The [`TraceContext`] contains a list of [`EvaluatedTerm`], which is known as the knowledge
430/// of the attacker. [`EvaluatedTerm`] can contain data of various types like for example
431/// client and server extensions, cipher suits or session ID It also holds the concrete
432/// references to the [`Agent`]s and the underlying streams, which contain the messages
433/// which have need exchanged and are not yet processed by an output step.
434#[derive(Debug)]
435pub struct TraceContext<PB: ProtocolBehavior> {
436    /// The knowledge of the attacker
437    pub knowledge_store: KnowledgeStore<PB::ProtocolTypes>,
438    agents: Vec<Agent<PB>>,
439    claims: GlobalClaimList<PB::Claim>,
440    pub config_trace: ConfigTrace,
441
442    spawner: Spawner<PB>,
443
444    phantom: PhantomData<PB>,
445    /// The number of steps that have been successfully executed
446    pub executed_until: usize,
447}
448
449impl<PB: ProtocolBehavior> fmt::Display for TraceContext<PB> {
450    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
451        write!(
452            f,
453            "Knowledge [not displaying other fields] (size={}):",
454            self.knowledge_store.raw_knowledge.len()
455        )?;
456        for k in &self.knowledge_store.raw_knowledge {
457            write!(f, "\n   {k},          --  {k:?}")?;
458        }
459        Ok(())
460    }
461}
462
463impl<PB: ProtocolBehavior + PartialEq> PartialEq for TraceContext<PB> {
464    fn eq(&self, other: &Self) -> bool {
465        self.agents == other.agents
466            && self.spawner == other.spawner
467            && format!("{:?}", self.knowledge_store.raw_knowledge)
468                == format!("{:?}", other.knowledge_store.raw_knowledge)
469            && format!("{:?}", self.claims) == format!("{:?}", other.claims)
470            && self.config_trace == other.config_trace
471    }
472}
473
474impl<PB: ProtocolBehavior> TraceContext<PB> {
475    #[must_use]
476    pub fn new(spawner: Spawner<PB>) -> Self {
477        Self::new_config(spawner, ConfigTrace::default())
478    }
479
480    pub fn new_config(spawner: Spawner<PB>, config_trace: ConfigTrace) -> Self {
481        // We keep a global list of all claims throughout the execution. Each claim is identified
482        // by the AgentName. A rename of an Agent does not interfere with this.
483        let claims = GlobalClaimList::<PB::Claim>::new();
484
485        Self {
486            knowledge_store: KnowledgeStore::new(),
487            agents: vec![],
488            claims,
489            config_trace,
490            spawner,
491            phantom: Default::default(),
492            executed_until: 0,
493        }
494    }
495
496    pub fn verify_security_violations(&self) -> Result<(), Error> {
497        let claims = self.claims.deref_borrow();
498        claims.log();
499        if let Some(msg) = PB::SecurityViolationPolicy::check_violation(claims.slice()) {
500            // [TODO] Lucca: versus checking at each step ? Could detect violation earlier, before a
501            // blocking state is reached ? [BENCH] benchmark the efficiency loss of doing so
502            // Max: We only check for Finished claims right now, so its fine to check only at the
503            // end
504            return Err(Error::SecurityClaim(msg));
505        }
506        Ok(())
507    }
508
509    /// Count the number of sub-messages of type `type_id` with the correct source
510    pub fn number_matching_message_with_source(
511        &self,
512        source: Source,
513        type_id: TypeId,
514        tls_message_type: &Option<<PB::ProtocolTypes as ProtocolTypes>::Matcher>,
515    ) -> usize {
516        self.knowledge_store
517            .number_matching_message_with_source(source, type_id, tls_message_type)
518    }
519
520    /// Count the number of sub-messages of type `type_id` in the output message.
521    pub fn number_matching_message(
522        &self,
523        type_id: TypeId,
524        tls_message_type: &Option<<PB::ProtocolTypes as ProtocolTypes>::Matcher>,
525    ) -> usize {
526        self.knowledge_store
527            .number_matching_message(type_id, tls_message_type)
528    }
529
530    #[must_use]
531    pub fn find_claim(
532        &self,
533        agent_name: AgentName,
534        query_type_shape: TypeShape<PB::ProtocolTypes>,
535    ) -> Option<Box<dyn EvaluatedTerm<PB::ProtocolTypes>>> {
536        self.claims
537            .deref_borrow()
538            .find_last_claim(agent_name, query_type_shape)
539            .map(super::claims::Claim::inner)
540    }
541
542    /// Returns the variable which matches best -> highest specificity
543    /// If we want a variable with lower specificity, then we can just query less specific
544    pub fn find_variable(
545        &self,
546        query_type_shape: TypeShape<PB::ProtocolTypes>,
547        query: &Query<<PB::ProtocolTypes as ProtocolTypes>::Matcher>,
548    ) -> Option<&dyn EvaluatedTerm<PB::ProtocolTypes>> {
549        log::trace!(
550            "Looking for variable in {:?} with query {:?}",
551            self.knowledge_store,
552            query
553        );
554        self.knowledge_store.find_variable(query_type_shape, query)
555    }
556
557    pub fn spawn(
558        &mut self,
559        descriptor: &AgentDescriptor<<PB::ProtocolTypes as ProtocolTypes>::PUTConfig>,
560    ) -> Result<(), Error> {
561        let agent = self.spawner.spawn(&self.claims, descriptor)?;
562        self.agents.push(agent);
563
564        Ok(())
565    }
566
567    pub fn find_agent_mut(&mut self, name: AgentName) -> Result<&mut Agent<PB>, Error> {
568        let mut iter = self.agents.iter_mut();
569
570        iter.find(|agent| agent.name() == name).ok_or_else(|| {
571            Error::Agent(format!(
572                "Could not find agent {name}. Did you forget to call spawn_agents?"
573            ))
574        })
575    }
576
577    pub fn find_agent(&self, name: AgentName) -> Result<&Agent<PB>, Error> {
578        let mut iter = self.agents.iter();
579        iter.find(|agent| agent.name() == name).ok_or_else(|| {
580            Error::Agent(format!(
581                "Could not find agent {name}. Did you forget to call spawn_agents?"
582            ))
583        })
584    }
585
586    #[must_use]
587    pub fn agents_successful(&self) -> bool {
588        self.agents
589            .iter()
590            .all(super::agent::Agent::is_state_successful)
591    }
592
593    /// Compare with another `TraceContext` and return a Vec of differences
594    pub fn compare(
595        &self,
596        other: &Self,
597        descriptors: &Vec<AgentDescriptor<<PB::ProtocolTypes as ProtocolTypes>::PUTConfig>>,
598    ) -> Vec<TraceDifference> {
599        let mut res = vec![];
600
601        // Decrypting knowledges
602        let terms: Vec<Term<PB::ProtocolTypes>> =
603            PB::ProtocolTypes::differential_fuzzing_terms_to_eval(descriptors);
604
605        let mut self_store = KnowledgeStore::new();
606        let mut other_store = KnowledgeStore::new();
607
608        for t in terms {
609            let self_eval = t.evaluate_dy(self);
610            let other_eval = t.evaluate_dy(other);
611            log::trace!("Evaluate term : {}", t);
612            log::trace!("Trying term evaluation for first PUT : {:?}", self_eval);
613            log::trace!("Trying term evaluation for second PUT : {:?}", other_eval);
614            if let Ok(decrypted) = self_eval {
615                self_store.add_raw_boxed_knowledge(
616                    decrypted,
617                    None,
618                    Source::Label(Some("Decryption".into())),
619                    None,
620                );
621            }
622            if let Ok(decrypted) = other_eval {
623                other_store.add_raw_boxed_knowledge(
624                    decrypted,
625                    None,
626                    Source::Label(Some("Decryption".into())),
627                    None,
628                );
629            }
630        }
631
632        // Comparing the claims
633        #[cfg(not(feature = "ddyf-disable-claims"))]
634        res.extend(
635            self.claims
636                .compare(&other.claims)
637                .err()
638                .map_or(vec![], |x| x),
639        );
640
641        // Comparing the knowledges
642        #[cfg(not(feature = "ddyf-disable-knowledges"))]
643        res.extend(
644            self.knowledge_store
645                .compare(&other.knowledge_store)
646                .err()
647                .map_or(vec![], |x| x),
648        );
649
650        // Comparing the computed terms
651        #[cfg(not(feature = "ddyf-disable-decryption"))]
652        res.extend(self_store.compare(&other_store).err().map_or(vec![], |x| x));
653
654        res
655    }
656}
657
658#[derive(Clone, Deserialize, Serialize, Hash, Default)]
659pub struct MetadataTrace {
660    /// The path focus of the trace, which is used to focus on a specific part of the trace for
661    /// HAVOC mutations during a FocusScheduledMutator
662    path_focus: Option<TracePath>,
663}
664
665#[derive(Clone, Deserialize, Serialize, Hash)]
666#[serde(bound = "PT: ProtocolTypes")]
667pub struct Trace<PT: ProtocolTypes> {
668    pub descriptors: Vec<AgentDescriptor<PT::PUTConfig>>,
669    pub steps: Vec<Step<PT>>,
670    pub prior_traces: Vec<Trace<PT>>,
671    pub metadata_trace: MetadataTrace,
672}
673
674/// Identify a step and a (prior) trace
675#[derive(Clone, Debug, Deserialize, Serialize, Hash, PartialEq, Eq, Comparable)]
676pub struct StepNumber {
677    /// identify the trace (allow to differentiate between prior traces)
678    pub trace: usize,
679    /// The step number in the trace
680    pub step: usize,
681}
682
683impl StepNumber {
684    pub fn new(trace: usize, step: usize) -> Self {
685        Self { trace, step }
686    }
687}
688
689/// Store the result of a trace execution for displaying or serializing
690#[derive(Serialize)]
691#[serde(bound = "PT: ProtocolTypes")]
692pub struct ExecutionResult<PT: ProtocolTypes> {
693    put: String,
694    error: Option<String>,
695    execution: TraceExecution<PT>,
696}
697
698impl<PT: ProtocolTypes> ExecutionResult<PT> {
699    pub fn from<PB>(
700        put: String,
701        error: Option<String>,
702        trace: &Trace<PT>,
703        ctx: TraceContext<PB>,
704        export_terms: bool,
705        export_knowledges: bool,
706        export_claims: bool,
707        export_raw: bool,
708    ) -> Self
709    where
710        PB: ProtocolBehavior<ProtocolTypes = PT>,
711    {
712        let mut ctx = ctx;
713        Self {
714            put,
715            error,
716            execution: TraceExecution::from(
717                trace,
718                &mut ctx,
719                export_terms,
720                export_knowledges,
721                export_claims,
722                export_raw,
723            ),
724        }
725    }
726}
727
728impl<PT: ProtocolTypes> Display for ExecutionResult<PT> {
729    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
730        writeln!(f, "Trace execution")?;
731        writeln!(f, "PUT: {}\n", self.put)?;
732
733        self.execution.print(f, 0)?;
734
735        match self.error {
736            None => writeln!(f, "Success"),
737            Some(_) => writeln!(f, "Error : {}", self.error.clone().unwrap_or("".into())),
738        }
739    }
740}
741
742/// Store the result of a trace execution to be printed in the cli or serialized
743/// for automated analysis
744#[derive(Serialize)]
745#[serde(bound = "PT: ProtocolTypes")]
746pub struct TraceExecution<PT: ProtocolTypes> {
747    prior_traces: Vec<TraceExecution<PT>>,
748    agents: Vec<AgentDescriptor<PT::PUTConfig>>,
749    /// Total number of step in the trace
750    number_of_steps: usize,
751    /// Number of steps executed before error
752    executed_until: usize,
753    /// Execution result of each step
754    steps: Vec<StepExecution<PT>>,
755    // Other knowledges (eg. post computations)
756    extra_knowledges: Option<Vec<(Source, Box<dyn EvaluatedTerm<PT>>)>>,
757}
758
759/// Get a trace and return a `TraceExecution` containing the selected informations (terms,
760/// knowledges, claims, raw bytes)
761impl<PT: ProtocolTypes> TraceExecution<PT> {
762    pub fn from<PB>(
763        trace: &Trace<PT>,
764        ctx: &mut TraceContext<PB>,
765        export_terms: bool,
766        export_knowledges: bool,
767        export_claims: bool,
768        export_raw: bool,
769    ) -> Self
770    where
771        PB: ProtocolBehavior<ProtocolTypes = PT>,
772    {
773        let mut steps = Vec::with_capacity(trace.steps.len());
774
775        let trace_number = Self::count_prior_traces(trace) - 1;
776
777        for (idx, step) in trace.steps.iter().enumerate() {
778            let knowledges = if export_knowledges {
779                let mut step_knowledges = Vec::new();
780                let mut old_knowledges = Vec::new();
781
782                mem::swap(&mut old_knowledges, &mut ctx.knowledge_store.raw_knowledge);
783
784                for k in old_knowledges {
785                    if k.step == Some(StepNumber::new(trace_number, idx)) {
786                        step_knowledges.push(k.data);
787                    } else {
788                        ctx.knowledge_store.raw_knowledge.push(k);
789                    }
790                }
791                Some(step_knowledges)
792                // TODO : Bump rust version to 1.87 to use `extract_if` instead of mem:swap code
793                // Some(
794                //     ctx.knowledge_store
795                //         .raw_knowledge
796                //         .extract_if(.., |k| k.step == Some(StepNumber::new(trace_number, idx)))
797                //         .map(|k| k.data)
798                //         .collect(),
799                // )
800            } else {
801                None
802            };
803
804            // Get the claims emitted at the current step
805            let claims = if export_claims {
806                Some(
807                    ctx.claims
808                        .deref_borrow()
809                        .iter()
810                        .filter(|c| c.get_step() == Some(StepNumber::new(trace_number, idx)))
811                        .map(|c| c.inner())
812                        .collect(),
813                )
814            } else {
815                None
816            };
817
818            steps.push(StepExecution {
819                step_number: idx,
820                action: ActionType::from(step.action.clone(), export_terms, export_raw, ctx),
821                agent: step.agent,
822                knowledges,
823                claims,
824            });
825        }
826
827        let extra_knowledges = if export_knowledges {
828            let mut knowledges = Vec::new();
829            let mut old_knowledges = Vec::new();
830
831            mem::swap(&mut old_knowledges, &mut ctx.knowledge_store.raw_knowledge);
832
833            for k in old_knowledges {
834                if k.step == None {
835                    knowledges.push((k.source, k.data));
836                } else {
837                    ctx.knowledge_store.raw_knowledge.push(k);
838                }
839            }
840            Some(knowledges)
841            // TODO : Bump rust version to 1.87 to use `extract_if` instead of mem:swap code
842            // Some(
843            //     ctx.knowledge_store
844            //         .raw_knowledge
845            //         .extract_if(.., |k| k.step == None)
846            //         .map(|k| (k.source, k.data))
847            //         .collect(),
848            // )
849        } else {
850            None
851        };
852
853        Self {
854            agents: trace.descriptors.clone(),
855            number_of_steps: trace.steps.len(),
856            executed_until: ctx.executed_until,
857            steps,
858            // right now we exclude prior traces
859            // TODO: add prior traces
860            prior_traces: Vec::new(),
861            extra_knowledges,
862        }
863    }
864
865    fn count_prior_traces(trace: &Trace<PT>) -> usize {
866        let prior: usize = trace
867            .prior_traces
868            .iter()
869            .fold(0, |acc, p| acc + Self::count_prior_traces(p));
870        1 + prior
871    }
872
873    pub fn print(&self, f: &mut std::fmt::Formatter<'_>, depth: usize) -> std::fmt::Result {
874        let tabs = "\t".repeat(depth);
875
876        for (idx, p) in self.prior_traces.iter().enumerate() {
877            writeln!(f, "{tabs}==== Executing prior trace #{} ====", idx)?;
878            p.print(f, depth + 1)?;
879        }
880
881        writeln!(f, "{tabs}Agents:")?;
882        for (idx, agent) in self.agents.iter().enumerate() {
883            writeln!(f, "{tabs}\t {}: {:?}", idx, agent)?;
884        }
885
886        writeln!(f, "{tabs} Executed until step {}", self.executed_until)?;
887
888        writeln!(f)?;
889
890        for s in &self.steps {
891            s.print(f, depth)?;
892        }
893
894        if let Some(knowledges) = &self.extra_knowledges {
895            println!("{tabs}Extra knowledges :");
896            for k in knowledges {
897                println!("{tabs}>>> [{}] {:?}", k.0, k.1);
898            }
899        }
900
901        writeln!(f)
902    }
903}
904
905#[derive(Serialize)]
906#[serde(bound = "PT: ProtocolTypes")]
907pub struct StepExecution<PT: ProtocolTypes> {
908    step_number: usize,
909    action: ActionType,
910    agent: AgentName,
911    knowledges: Option<Vec<Box<dyn EvaluatedTerm<PT>>>>,
912    claims: Option<Vec<Box<dyn EvaluatedTerm<PT>>>>,
913}
914
915#[derive(Serialize)]
916enum ActionType {
917    Input {
918        recipe: Option<String>,
919        raw: Option<String>,
920        precomputations: Option<Vec<(String, String)>>,
921    },
922    Output,
923}
924
925impl ActionType {
926    fn from<PB: ProtocolBehavior>(
927        value: Action<PB::ProtocolTypes>,
928        export_terms: bool,
929        export_raw: bool,
930        ctx: &TraceContext<PB>,
931    ) -> Self {
932        match value {
933            Input(input_action) => ActionType::Input {
934                recipe: match export_terms {
935                    true => Some(input_action.recipe.to_string()),
936                    false => None,
937                },
938                raw: match export_raw {
939                    true => match input_action.recipe.evaluate(ctx) {
940                        Ok(v) => Some(
941                            v.iter()
942                                .map(|b| format!("{:02x}", b).to_string())
943                                .collect::<String>(),
944                        ),
945                        Err(_) => None,
946                    },
947                    false => None,
948                },
949                precomputations: match export_terms {
950                    true => Some(
951                        input_action
952                            .precomputations
953                            .iter()
954                            .map(|p| (p.label.clone().unwrap_or("".into()), p.recipe.to_string()))
955                            .collect(),
956                    ),
957                    false => None,
958                },
959            },
960            Action::Output(_) => ActionType::Output,
961        }
962    }
963}
964
965/// Allow serializing Box<dyn EvaluatedTerm<_>>
966impl<PT: ProtocolTypes> Serialize for Box<dyn EvaluatedTerm<PT>> {
967    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
968    where
969        S: Serializer,
970    {
971        serializer.serialize_str(&format!("{:?}", self))
972    }
973}
974
975impl<PT: ProtocolTypes> StepExecution<PT> {
976    pub fn print(&self, f: &mut std::fmt::Formatter<'_>, depth: usize) -> std::fmt::Result {
977        let tabs = "\t".repeat(depth);
978        writeln!(f, "{tabs}==== Executing step #{} ====", self.step_number)?;
979
980        match &self.action {
981            ActionType::Input {
982                recipe,
983                raw,
984                precomputations,
985            } => {
986                println!("{tabs}Action: Input (attacker -> agent.{})", self.agent);
987                if let Some(p) = precomputations {
988                    for (precomputation_name, precomputation_recipe) in p {
989                        println!(
990                            "{tabs}Precomputation {}: {}",
991                            precomputation_name, precomputation_recipe
992                        );
993                    }
994                }
995                if let Some(r) = raw {
996                    println!("{tabs}Raw: {}", r);
997                }
998                if let Some(r) = recipe {
999                    println!("{tabs}Term: {}", r);
1000                }
1001            }
1002            ActionType::Output => {
1003                println!("{tabs}Action: Output (agent.{} -> attacker)", self.agent);
1004            }
1005        }
1006
1007        if let Some(knowledges) = &self.knowledges {
1008            for k in knowledges {
1009                println!("{tabs}>>> {:?}", k);
1010            }
1011        }
1012        if let Some(claims) = &self.claims {
1013            for c in claims {
1014                println!("{tabs}+++ {:?}", c);
1015            }
1016        }
1017
1018        writeln!(f)
1019    }
1020}
1021
1022/// A [`Trace`] consists of several [`Step`]s. Each has either a [`OutputAction`] or an
1023/// [`InputAction`]. Each [`Step`]s references an [`Agent`] by name. Furthermore, a trace also has a
1024/// list of *`AgentDescriptors`* which act like a blueprint to spawn [`Agent`]s with a corresponding
1025/// server or client role and a specific TLs version. Essentially they are an [`Agent`] without a
1026/// stream.
1027impl<PT: ProtocolTypes> Trace<PT> {
1028    /// Recursively collect all agent descriptors from this trace and its prior traces.
1029    /// This is needed for differential testing: agents in prior traces must also be
1030    /// mapped to the correct PUT, otherwise they silently fall back to the default.
1031    pub fn all_descriptors(&self) -> Vec<&AgentDescriptor<PT::PUTConfig>> {
1032        let mut result: Vec<&AgentDescriptor<PT::PUTConfig>> = Vec::new();
1033        for prior in &self.prior_traces {
1034            result.extend(prior.all_descriptors());
1035        }
1036        result.extend(self.descriptors.iter());
1037        result
1038    }
1039
1040    pub fn spawn_agents<PB: ProtocolBehavior<ProtocolTypes = PT>>(
1041        &self,
1042        ctx: &mut TraceContext<PB>,
1043    ) -> Result<(), Error> {
1044        for descriptor in &self.descriptors {
1045            if let Some(reusable) = ctx
1046                .agents
1047                .iter_mut()
1048                .find(|existing| existing.is_reusable_with(descriptor))
1049            {
1050                // rename if it already exists and we want to reuse
1051                reusable.reset(descriptor.name)?;
1052            } else {
1053                // only spawn completely new if not yet existing
1054                ctx.spawn(descriptor)?;
1055            };
1056        }
1057
1058        Ok(())
1059    }
1060
1061    pub fn execute_until_step_wrap<PB>(
1062        &self,
1063        ctx: &mut TraceContext<PB>,
1064        stop_at_step: usize,
1065        trace_number: &mut usize,
1066        check_security_violation: bool,
1067    ) -> Result<(), Error>
1068    where
1069        PB: ProtocolBehavior<ProtocolTypes = PT>,
1070    {
1071        for trace in &self.prior_traces {
1072            // Call wrap function to avoid counting these sub-executions in ALL_EXEC and
1073            // ALL_EXEC_SUCCESS counters
1074            trace
1075                .execute_until_step_wrap(
1076                    ctx,
1077                    trace.steps.len(),
1078                    trace_number,
1079                    check_security_violation,
1080                )
1081                .map_err(|e| {
1082                    log::warn!("[execute_until_step_wrap] fail executing prior traces {trace}");
1083                    e
1084                })?;
1085        }
1086
1087        self.spawn_agents(ctx)?;
1088        let steps = &self.steps[0..stop_at_step];
1089        ctx.executed_until = 0;
1090        for (i, step) in steps.iter().enumerate() {
1091            log::debug!("Executing step #{}", i);
1092            step.execute(StepNumber::new(*trace_number, i), ctx)?;
1093
1094            if check_security_violation {
1095                ctx.verify_security_violations()?;
1096            }
1097            ctx.executed_until = i + 1;
1098        }
1099
1100        *trace_number += 1;
1101
1102        Ok(())
1103    }
1104
1105    pub fn execute_until_step<PB>(
1106        &self,
1107        ctx: &mut TraceContext<PB>,
1108        stop_at_step: usize,
1109        trace_number: &mut usize,
1110        check_security_violation: bool,
1111    ) -> Result<(), Error>
1112    where
1113        PB: ProtocolBehavior<ProtocolTypes = PT>,
1114    {
1115        ALL_EXEC.increment();
1116        let res =
1117            self.execute_until_step_wrap(ctx, stop_at_step, trace_number, check_security_violation);
1118
1119        if let Err(e) = res {
1120            match &e {
1121                Error::Fn(_) => ERROR_FN.increment(),
1122                Error::Term(_e) => ERROR_TERM.increment(),
1123                Error::TermBug(_e) => ERROR_TERMBUG.increment(),
1124                Error::Put(_) => ERROR_PUT.increment(),
1125                Error::Codec(_) => ERROR_CODEC.increment(),
1126                Error::IO(_) => ERROR_IO.increment(),
1127                Error::Agent(_) => ERROR_AGENT.increment(),
1128                Error::Stream(_) => ERROR_STREAM.increment(),
1129                Error::Extraction() => ERROR_EXTRACTION.increment(),
1130                Error::SecurityClaim(_) => {}
1131                Error::Difference {
1132                    put1_status: _,
1133                    put2_status: _,
1134                    differences: _,
1135                } => {}
1136            }
1137            return Err(e);
1138        }
1139
1140        ALL_EXEC_SUCCESS.increment();
1141        if cfg!(feature = "introspection") && ctx.agents_successful() {
1142            ALL_EXEC_AGENT_SUCCESS.increment();
1143        }
1144
1145        Ok(())
1146    }
1147
1148    pub fn execute<PB>(
1149        &self,
1150        ctx: &mut TraceContext<PB>,
1151        trace_number: &mut usize,
1152        check_security_violation: bool,
1153    ) -> Result<(), Error>
1154    where
1155        PB: ProtocolBehavior<ProtocolTypes = PT>,
1156    {
1157        self.execute_until_step(
1158            ctx,
1159            self.steps.len(),
1160            trace_number,
1161            check_security_violation,
1162        )
1163    }
1164
1165    pub fn serialize_postcard(&self) -> Result<Vec<u8>, postcard::Error> {
1166        postcard::to_allocvec(&self)
1167    }
1168
1169    pub fn deserialize_postcard(slice: &[u8]) -> Result<Self, postcard::Error> {
1170        postcard::from_bytes::<Self>(slice)
1171    }
1172
1173    #[must_use]
1174    pub fn all_payloads(&self) -> Vec<&Payloads> {
1175        self.steps
1176            .iter()
1177            .filter_map(|e| match &e.action {
1178                Input(r) => Some(&r.recipe),
1179                _ => None,
1180            })
1181            .flat_map(|t| t.all_payloads())
1182            .collect()
1183    }
1184
1185    pub fn all_payloads_mut(&mut self) -> Vec<&mut Payloads> {
1186        self.steps
1187            .iter_mut()
1188            .filter_map(|e| match &mut e.action {
1189                Input(r) => Some(&mut r.recipe),
1190                _ => None,
1191            })
1192            .flat_map(|t| t.all_payloads_mut())
1193            .collect()
1194    }
1195
1196    #[must_use]
1197    pub fn is_symbolic(&self) -> bool {
1198        self.steps.iter().all(|e| match &e.action {
1199            Input(r) => r.recipe.is_symbolic(),
1200            _ => true,
1201        })
1202    }
1203
1204    /// Remove the steps after (excluding) `after_step`
1205    pub fn truncate_at_step(&mut self, after_step: usize) {
1206        log::debug!("Truncating trace at step {after_step}");
1207        self.steps.truncate(after_step);
1208    }
1209
1210    /// Size of trace (summing all input sizes, counting one for output)
1211    pub fn size(&self) -> usize {
1212        self.steps.iter().fold(0, |acc, s| match &s.action {
1213            Action::Input(inp) => acc + inp.recipe.size(),
1214            Action::Output(_) => acc + 1,
1215        })
1216    }
1217
1218    /// Sets in the metadata the focus of the trace to a specific [`TracePath`].
1219    pub fn set_focus(&mut self, trace_path: TracePath) {
1220        log::debug!("[Set_focus] Setting focus to {trace_path:?}");
1221        self.metadata_trace.path_focus = Some(trace_path);
1222    }
1223
1224    /// Clear from the metadata any focus
1225    pub fn clear_focus(&mut self) {
1226        log::debug!("[clear_focus] clear focus");
1227        self.metadata_trace.path_focus = None;
1228    }
1229
1230    /// Returns the current focus path from the metadata, if any
1231    pub fn get_focus(&self) -> Option<&TracePath> {
1232        log::debug!("[get_focus] get_focus {:?}", self.metadata_trace.path_focus);
1233        self.metadata_trace.path_focus.as_ref()
1234    }
1235}
1236impl<PT: ProtocolTypes> Default for Trace<PT> {
1237    fn default() -> Self {
1238        Self {
1239            descriptors: vec![],
1240            steps: vec![],
1241            prior_traces: vec![],
1242            metadata_trace: Default::default(),
1243        }
1244    }
1245}
1246
1247impl<PT: ProtocolTypes> fmt::Debug for Trace<PT> {
1248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1249        write!(f, "Trace with {} steps", self.steps.len())
1250    }
1251}
1252
1253impl<PT: ProtocolTypes> fmt::Display for Trace<PT> {
1254    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1255        write!(f, "Trace:")?;
1256        for step in &self.steps {
1257            write!(f, "\n{} -> {}", step.agent, step.action)?;
1258        }
1259        Ok(())
1260    }
1261}
1262
1263impl<PT: ProtocolTypes> AsRef<Self> for Trace<PT> {
1264    fn as_ref(&self) -> &Self {
1265        self
1266    }
1267}
1268
1269#[derive(Serialize, Deserialize, Clone, Debug, Hash)]
1270#[serde(bound = "PT: ProtocolTypes")]
1271pub struct Step<PT: ProtocolTypes> {
1272    pub agent: AgentName,
1273    pub action: Action<PT>,
1274}
1275
1276impl<PT: ProtocolTypes> Step<PT> {
1277    pub fn execute<PB>(
1278        &self,
1279        step_number: StepNumber,
1280        ctx: &mut TraceContext<PB>,
1281    ) -> Result<(), Error>
1282    where
1283        PB: ProtocolBehavior<ProtocolTypes = PT>,
1284    {
1285        match &self.action {
1286            Action::Input(input) => {
1287                let exec = input.execute(self.agent, ctx);
1288                // NOTE force output after each InputAction step
1289                let _ = (OutputAction {
1290                    phantom: Default::default(),
1291                })
1292                .read_state(self.agent, step_number, ctx);
1293                exec
1294            }
1295            Action::Output(output) => output.execute(self.agent, step_number, ctx),
1296        }
1297    }
1298}
1299
1300/// There are two action types [`OutputAction`] and [`InputAction`].
1301///
1302/// Both actions drive the internal state machine of an [`Agent`] forward by calling `progress()`.
1303/// The [`OutputAction`] first forwards the state machine and then extracts knowledge from the
1304/// TLS messages produced by the underlying stream by calling  `take_message_from_outbound(...)`.
1305/// The [`InputAction`] evaluates the recipe term and injects the newly produced message
1306/// into the *inbound channel* of the [`Agent`] referenced through the corresponding [`Step`]s
1307/// by calling `add_to_inbound(...)` and then drives the state machine forward.
1308/// Therefore, the difference is that one step *increases* the knowledge of the attacker,
1309/// whereas the other action *uses* the available knowledge.
1310#[derive(Serialize, Deserialize, Clone, Debug, Hash)]
1311#[serde(bound = "PT: ProtocolTypes")]
1312pub enum Action<PT: ProtocolTypes> {
1313    Input(InputAction<PT>),
1314    Output(OutputAction<PT>),
1315}
1316
1317impl<PT: ProtocolTypes> fmt::Display for Action<PT> {
1318    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1319        match self {
1320            Self::Input(input) => write!(f, "{input}"),
1321            Self::Output(output) => write!(f, "{output}"),
1322        }
1323    }
1324}
1325
1326/// Advance the [`Agent`]'s state and process the produced output.
1327///
1328/// The [`OutputAction`] first forwards the state machine and then extracts knowledge from the TLS
1329/// messages produced by the underlying stream by calling  `take_message_from_outbound(...)`. An
1330/// output action is automatically called after each input step.
1331#[derive(Serialize, Deserialize, Clone, Debug, Hash)]
1332pub struct OutputAction<PT> {
1333    phantom: PhantomData<PT>,
1334}
1335
1336impl<PT: ProtocolTypes> OutputAction<PT> {
1337    #[must_use]
1338    pub fn new_step(agent: AgentName) -> Step<PT> {
1339        Step {
1340            agent,
1341            action: Action::Output(Self {
1342                phantom: Default::default(),
1343            }),
1344        }
1345    }
1346
1347    fn execute<PB>(
1348        &self,
1349        agent_name: AgentName,
1350        step: StepNumber, // the current step of the trace
1351        ctx: &mut TraceContext<PB>,
1352    ) -> Result<(), Error>
1353    where
1354        PB: ProtocolBehavior<ProtocolTypes = PT>,
1355    {
1356        ctx.find_agent_mut(agent_name)?.progress()?;
1357
1358        self.read_state(agent_name, step.clone(), ctx)?;
1359
1360        Ok(())
1361    }
1362
1363    fn read_state<PB>(
1364        &self,
1365        agent_name: AgentName,
1366        step: StepNumber,
1367        ctx: &mut TraceContext<PB>,
1368    ) -> Result<(), Error>
1369    where
1370        PB: ProtocolBehavior<ProtocolTypes = PT>,
1371    {
1372        let source = Source::Agent(agent_name);
1373        let agent = ctx.find_agent_mut(agent_name)?;
1374
1375        let mut flight = None;
1376
1377        let res = agent.take_message_from_outbound(&mut flight);
1378
1379        if let Some(opaque_flight) = flight {
1380            ctx.knowledge_store.add_raw_knowledge(
1381                opaque_flight.clone(),
1382                Some(step.clone()),
1383                source.clone(),
1384                None,
1385            );
1386
1387            if let Ok(flight) = TryInto::<PB::ProtocolMessageFlight>::try_into(opaque_flight) {
1388                ctx.knowledge_store
1389                    .add_raw_knowledge(flight, Some(step.clone()), source, None);
1390            }
1391        }
1392
1393        // Iterate on claimlist from the end to set the step number on the last claims collected
1394        for claim in ctx.claims.deref_borrow_mut().iter_mut().rev() {
1395            if claim.get_step().is_none() {
1396                // if the claim doesn't have a step number, it has been created during the last step
1397                claim.set_step(Some(step.clone()));
1398            } else {
1399                // all prior claims should already have a number
1400                break;
1401            }
1402        }
1403
1404        res
1405    }
1406}
1407
1408impl<PT: ProtocolTypes> fmt::Display for OutputAction<PT> {
1409    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1410        write!(f, "OutputAction")
1411    }
1412}
1413
1414#[derive(Serialize, Deserialize, Clone, Debug, Hash)]
1415#[serde(bound = "PT: ProtocolTypes")]
1416pub struct Precomputation<PT: ProtocolTypes> {
1417    pub label: Option<String>,
1418    pub recipe: Term<PT>,
1419}
1420
1421/// Provide inputs to the [`Agent`].
1422///
1423/// The [`InputAction`] evaluates the recipe term and injects the newly produced message
1424/// into the *inbound channel* of the [`Agent`] referenced through the corresponding [`Step`]s
1425/// by calling `add_to_inbound(...)` and then drives the state machine forward.
1426#[derive(Serialize, Deserialize, Clone, Debug, Hash)]
1427#[serde(bound = "PT: ProtocolTypes")]
1428pub struct InputAction<PT: ProtocolTypes> {
1429    pub precomputations: Vec<Precomputation<PT>>,
1430    pub recipe: Term<PT>,
1431}
1432
1433/// Processes messages in the inbound channel. Uses the recipe field to evaluate to a rustls Message
1434/// or a `MultiMessage`.
1435impl<PT: ProtocolTypes> InputAction<PT> {
1436    pub fn new_step(agent: AgentName, recipe: Term<PT>) -> Step<PT> {
1437        Step {
1438            agent,
1439            action: Action::Input(Self {
1440                recipe,
1441                precomputations: vec![],
1442            }),
1443        }
1444    }
1445
1446    fn execute<PB>(&self, agent_name: AgentName, ctx: &mut TraceContext<PB>) -> Result<(), Error>
1447    where
1448        PB: ProtocolBehavior<ProtocolTypes = PT>,
1449    {
1450        for precomputation in &self.precomputations {
1451            let eval = precomputation.recipe.evaluate_dy(ctx)?; // We do not accept payloads in precomputation recipes
1452            ctx.knowledge_store.add_raw_boxed_knowledge(
1453                eval,
1454                None,
1455                Source::Label(precomputation.label.clone()),
1456                Some(precomputation.recipe.clone()),
1457            );
1458        }
1459
1460        let message = self.recipe.evaluate(ctx)?;
1461        let agent = ctx.find_agent_mut(agent_name)?;
1462
1463        agent.add_to_inbound(&message);
1464        agent.progress()
1465    }
1466}
1467
1468impl<PT: ProtocolTypes> fmt::Display for InputAction<PT> {
1469    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1470        write!(f, "InputAction:\n{}", self.recipe)
1471    }
1472}
1473
1474/// This macro defines the precomputation syntax to add precomputations to an input action step
1475///
1476/// Example of precomputation with TLS
1477///
1478/// ```ignore
1479/// input_action! {
1480///     // Here we are precomputing a decryption of TLS extension and using it in the following term
1481///     "decrypted_extensions" = term!{fn_decrypt_handshake_flight(
1482///         ((server, 0)/MessageFlight),
1483///         (@server_hello_transcript),
1484///         (fn_get_server_key_share(((server, 0)[Some(TlsQueryMatcher::Handshake(Some(HandshakeType::ServerHello)))]))),
1485///         fn_no_psk,
1486///         fn_named_group_secp384r1,
1487///         fn_true,
1488///         fn_seq_0  // sequence 0
1489///     )}
1490///     =>
1491///     // This term will be sent to the PUT by the input action
1492///     term!{fn_append_transcript(
1493///         (@server_hello_transcript),
1494///         (
1495///             // We can query our precomputation
1496///             (!"decrypted_extensions", 0)[
1497///                 Some(TlsQueryMatcher::Handshake(Some(HandshakeType::EncryptedExtensions)))
1498///             ] / Message
1499///         )
1500///     )}
1501/// };
1502/// ```
1503///
1504/// The following syntaxes are accepted :
1505/// ```ignore
1506/// # use puffin::input_action;
1507/// # use puffin::term;
1508/// # use puffin::trace::Precomputation;
1509/// # use puffin::trace::InputAction;
1510///
1511/// input_action!{term!{fn_msg()}};
1512/// input_action!{term!{fn_precomputation()} => term!{fn_msg()}};
1513/// input_action!{"this_is_a_label" = term!{fn_precomputation()} => term!{fn_msg()}};
1514/// input_action!{
1515///     "this_is_a_label" = term!{fn_precomputation_1()} =>
1516///         term!{fn_precomputation_2()} =>
1517///             term!{fn_msg()}
1518/// };
1519/// // the latter is equivalent to
1520/// input_action!{
1521///     "this_is_a_label" = term!{fn_precomputation_1()}, term!{fn_precomputation_2()} =>
1522///         term!{fn_msg()}
1523/// };
1524/// ```
1525///
1526/// All the previous examples respectively produce
1527/// ```ignore
1528/// # use puffin::trace::Precomputation;
1529/// # use puffin::trace::InputAction;
1530/// # use puffin::term;
1531/// # use crate::algebra::test_signature::fn_msg;
1532///
1533/// InputAction {
1534///     recipe: term!{fn_msg()},
1535///     precomputations: vec![],
1536/// };
1537/// InputAction {
1538///     recipe: term!{fn_msg()},
1539///     precomputations: vec![Precomputation{label: "".into(), recipe: term!{fn_precomputation()}}],
1540/// };
1541/// InputAction {
1542///     recipe: term!{fn_msg()},
1543///     precomputations: vec![Precomputation{label: "this_is_a_label".into(), recipe:
1544/// term!{fn_precomputation()}}], };
1545/// InputAction {
1546///     recipe: term!{fn_msg()},
1547///     precomputations: vec![
1548///         Precomputation{label: "this_is_a_label".into(), recipe: term!{fn_precomputation_1()}},
1549///         Precomputation{label: "".into(), recipe: term!{fn_precomputation_2()}}
1550///     ],
1551/// };
1552/// ```
1553#[macro_export]
1554macro_rules! input_action {
1555    (@internal [$($label:expr, $precomp:expr);+] $recipe:expr) => {
1556        InputAction {
1557            recipe: $recipe,
1558            precomputations: vec![$(Precomputation{label: $label, recipe: $precomp}),*],
1559        }
1560    };
1561
1562    (@internal [$($precomps:tt)+] $other_name:literal = $other_precomp:expr => $($tail:tt)+) => {
1563        input_action!{@internal [$($precomps)+; Some($other_name.into()), $other_precomp] $($tail)+ }
1564    };
1565
1566    (@internal [$($precomps:tt)+] $other_name:literal = $other_precomp:expr, $($tail:tt)+) => {
1567        input_action!{@internal [$($precomps)+; Some($other_name.into()), $other_precomp] $($tail)+ }
1568    };
1569
1570    (@internal [$($precomps:tt)+] $other_precomp:expr => $($tail:tt)+) => {
1571        input_action!{@internal [$($precomps)+; None, $other_precomp] $($tail)+ }
1572    };
1573
1574    (@internal [$($precomps:tt)+] $other_precomp:expr, $($tail:tt)+) => {
1575        input_action!{@internal [$($precomps)+; None, $other_precomp] $($tail)+ }
1576    };
1577
1578    ($precomp_name:literal = $precomp:expr => $($tail:tt)+) => {
1579        input_action!{@internal [Some($precomp_name.into()), $precomp] $($tail)+ }
1580    };
1581
1582    ($precomp_name:literal = $precomp:expr , $($tail:tt)+) => {
1583        input_action!{@internal [Some($precomp_name.into()), $precomp] $($tail)+ }
1584    };
1585
1586    ($precomp:expr => $($tail:tt)+) => {
1587        input_action!{@internal [None, $precomp] $($tail)+ }
1588    };
1589
1590    ($precomp:expr, $($tail:tt)+) => {
1591        input_action!{@internal [None, $precomp] $($tail)+ }
1592    };
1593
1594    ($recipe:expr) => {
1595        InputAction {
1596            recipe: $recipe,
1597            precomputations: vec![],
1598        }
1599    };
1600}
1601
1602#[cfg(test)]
1603mod tests {
1604    use crate::algebra::test_signature::{
1605        fn_encrypt12, fn_finished, fn_new_random, fn_seq_0, fn_seq_1,
1606    };
1607    use crate::term;
1608    use crate::trace::{InputAction, Precomputation};
1609
1610    #[test]
1611    fn test_input_action_macro() {
1612        let action0 = input_action! {term!{fn_seq_0()}};
1613        assert_eq!(action0.precomputations.len(), 0);
1614
1615        let action1 = input_action! {
1616            term!{fn_new_random()} =>
1617                "a" = term!{fn_new_random()} =>
1618                    term!{
1619                        fn_encrypt12(fn_finished,fn_seq_0)
1620                    }
1621        };
1622        assert_eq!(action1.precomputations.len(), 2);
1623        assert_eq!(action1.precomputations[0].label, None);
1624        assert_eq!(action1.precomputations[1].label, Some("a".into()));
1625
1626        let action2 = input_action! {
1627            "a" = term!{fn_new_random()}, "b" = term!{fn_finished()} =>
1628                term!{
1629                    fn_encrypt12(fn_finished,fn_seq_0)
1630                }
1631        };
1632        assert_eq!(action2.precomputations.len(), 2);
1633        assert_eq!(action2.precomputations[0].label, Some("a".into()));
1634        assert_eq!(action2.precomputations[1].label, Some("b".into()));
1635
1636        let action3 = input_action! {
1637            "a" = term!{fn_new_random()} => term!{fn_finished()} =>
1638                term!{
1639                    fn_encrypt12(fn_finished,fn_seq_0)
1640                }
1641        };
1642        assert_eq!(action3.precomputations.len(), 2);
1643        assert_eq!(action3.precomputations[0].label, Some("a".into()));
1644        assert_eq!(action3.precomputations[1].label, None);
1645
1646        let action4 = input_action! {
1647            term!{fn_finished()}, "a" = term!{fn_new_random()} =>
1648                term!{
1649                    fn_encrypt12(fn_finished,fn_seq_0)
1650                }
1651        };
1652        assert_eq!(action4.precomputations.len(), 2);
1653        assert_eq!(action4.precomputations[0].label, None);
1654        assert_eq!(action4.precomputations[1].label, Some("a".into()));
1655
1656        let action5 = input_action! {
1657            term!{fn_finished()}, "a" = term!{fn_new_random()} =>
1658                "b" = term!{fn_seq_0()} =>
1659                    term!{fn_seq_1()} =>
1660                        "c" = term!{fn_seq_0()} =>
1661                            term!{fn_seq_0()}, "d" = term!{fn_seq_0()}, "e" = term!{fn_seq_0()} =>
1662                                term!{
1663                                    fn_encrypt12(fn_finished,fn_seq_0)
1664                                }
1665        };
1666        assert_eq!(action5.precomputations.len(), 8);
1667        assert_eq!(action5.precomputations[0].label, None);
1668        assert_eq!(action5.precomputations[1].label, Some("a".into()));
1669        assert_eq!(action5.precomputations[2].label, Some("b".into()));
1670        assert_eq!(action5.precomputations[3].label, None);
1671        assert_eq!(action5.precomputations[4].label, Some("c".into()));
1672        assert_eq!(action5.precomputations[5].label, None);
1673        assert_eq!(action5.precomputations[6].label, Some("d".into()));
1674        assert_eq!(action5.precomputations[7].label, Some("e".into()));
1675    }
1676}