tlspuffin/
put.rs

1use std::cell::RefCell;
2use std::collections::HashSet;
3use std::ffi::CString;
4use std::io::Read;
5use std::rc::Rc;
6
7use puffin::agent::AgentDescriptor;
8use puffin::algebra::dynamic_function::TypeShape;
9use puffin::claims::GlobalClaimList;
10use puffin::error::Error;
11use puffin::harness::{to_string, CError};
12use puffin::protocol::{OpaqueProtocolMessageFlight, ProtocolBehavior, ProtocolMessageDeframer};
13use puffin::put::{Put, PutOptions};
14use puffin::put_registry::Factory;
15use puffin::stream::Stream;
16use security_claims::Claim;
17
18use crate::claims::TlsClaim;
19use crate::protocol::{
20    AgentType, OpaqueMessageFlight, TLSDescriptorConfig, TLSProtocolBehavior, TLSProtocolTypes,
21    TLSVersion,
22};
23use crate::put_registry::bindings::{
24    AGENT, CLAIMER_CB, PEM, TLS_AGENT_DESCRIPTOR, TLS_AGENT_ROLE, TLS_PUT_INTERFACE, TLS_VERSION,
25};
26use crate::static_certs::{ALICE_CERT, ALICE_PRIVATE_KEY, BOB_CERT, BOB_PRIVATE_KEY, EVE_CERT};
27use crate::tls::rustls::msgs::deframer::MessageDeframer;
28
29/// Static configuration for creating a new agent state for the PUT
30#[derive(Clone, Debug)]
31pub struct TlsPutConfig {
32    pub descriptor: AgentDescriptor<TLSDescriptorConfig>,
33    pub claims: GlobalClaimList<TlsClaim>,
34    pub authenticate_peer: bool,
35    pub extract_deferred: Rc<RefCell<Option<TypeShape<TLSProtocolTypes>>>>,
36    pub use_clear: bool,
37}
38
39impl TlsPutConfig {
40    pub fn new(
41        agent_descriptor: &AgentDescriptor<TLSDescriptorConfig>,
42        claims: &GlobalClaimList<<TLSProtocolBehavior as ProtocolBehavior>::Claim>,
43        options: &PutOptions,
44    ) -> TlsPutConfig {
45        let use_clear = options
46            .get_option("use_clear")
47            .map(|value| value.parse().unwrap_or(false))
48            .unwrap_or(false);
49
50        TlsPutConfig {
51            descriptor: agent_descriptor.clone(),
52            claims: claims.clone(),
53            authenticate_peer: agent_descriptor.protocol_config.typ == AgentType::Client
54                && agent_descriptor.protocol_config.server_authentication
55                || agent_descriptor.protocol_config.typ == AgentType::Server
56                    && agent_descriptor.protocol_config.client_authentication,
57            extract_deferred: Rc::new(RefCell::new(None)),
58            use_clear,
59        }
60    }
61}
62
63#[derive(Clone, Debug)]
64pub struct CPut {
65    name: String,
66    harness_version: String,
67    library_version: String,
68    capabilities: HashSet<String>,
69    interface: TLS_PUT_INTERFACE,
70}
71
72impl CPut {
73    pub fn new(
74        name: impl Into<String>,
75        harness_version: impl Into<String>,
76        library_version: impl Into<String>,
77        capabilities: HashSet<String>,
78        interface: TLS_PUT_INTERFACE,
79    ) -> Self {
80        Self {
81            name: name.into(),
82            harness_version: harness_version.into(),
83            library_version: library_version.into(),
84            capabilities,
85            interface,
86        }
87    }
88}
89
90impl Factory<TLSProtocolBehavior> for CPut {
91    fn create(
92        &self,
93        agent_descriptor: &AgentDescriptor<TLSDescriptorConfig>,
94        claims: &GlobalClaimList<<TLSProtocolBehavior as ProtocolBehavior>::Claim>,
95        options: &PutOptions,
96    ) -> Result<Box<dyn Put<TLSProtocolBehavior>>, Error> {
97        Ok(Box::new(CAgent::new(
98            self,
99            TlsPutConfig::new(agent_descriptor, claims, options),
100        )?))
101    }
102
103    fn name(&self) -> String {
104        self.name.clone()
105    }
106
107    fn versions(&self) -> Vec<(String, String)> {
108        vec![
109            ("harness".to_string(), self.harness_version.clone()),
110            ("library".to_string(), self.library_version.clone()),
111        ]
112    }
113
114    fn rng_reseed(&self) {
115        if self.interface.rng_reseed.is_none() {
116            log::debug!("[RNG] reseed failed ({}): not supported", self.name());
117            return;
118        }
119
120        const DEFAULT_SEED: [u8; 8] = 42u64.to_le().to_ne_bytes();
121
122        log::debug!("[RNG] reseed ({})", self.name());
123        unsafe {
124            (self.interface.rng_reseed.unwrap())(DEFAULT_SEED.as_ptr(), DEFAULT_SEED.len());
125        }
126    }
127
128    fn supports(&self, capability: &str) -> bool {
129        self.capabilities.contains(capability)
130    }
131
132    fn clone_factory(&self) -> Box<dyn Factory<TLSProtocolBehavior>> {
133        Box::new(self.clone())
134    }
135}
136
137pub struct CAgent {
138    put: CPut,
139    config: TlsPutConfig,
140    deframer: MessageDeframer,
141    c_agent: AGENT,
142}
143
144macro_rules! pem {
145    ($pemder:expr) => {
146        PEM {
147            bytes: $pemder.0.as_ptr(),
148            length: $pemder.0.len(),
149        }
150    };
151}
152
153macro_rules! ccall {
154    ( $put:expr, $function_name:ident ) => {
155        ($put.interface.agent_interface.$function_name.unwrap())()
156    };
157    ( $put:expr, $function_name:ident, $($arg:expr),*) => {
158        ($put.interface.agent_interface.$function_name.unwrap())($($arg),*)
159    };
160}
161
162macro_rules! take_res {
163    ($call:expr) => {
164        *unsafe { Box::from_raw($call as *mut Result<String, CError>) }
165    };
166}
167
168macro_rules! r_ccall {
169    ( $put:expr, $function_name:ident ) => {
170        take_res!(ccall!($put, $function_name))
171    };
172    ( $put:expr, $function_name:ident, $($arg:expr),*) => {
173        take_res!(ccall!($put, $function_name, $($arg),*))
174    };
175}
176
177impl CAgent {
178    fn new(put: &CPut, config: TlsPutConfig) -> Result<Self, Error> {
179        let server_cert = pem!(ALICE_CERT);
180        let server_pkey = pem!(ALICE_PRIVATE_KEY);
181        let client_cert = pem!(BOB_CERT);
182        let client_pkey = pem!(BOB_PRIVATE_KEY);
183        let other_cert = pem!(EVE_CERT);
184
185        let server_store = [&client_cert as *const _, &other_cert];
186        let client_store = [&server_cert as *const _, &other_cert];
187        let ciphers_tls13 =
188            CString::new(config.descriptor.protocol_config.get_cipher_string_13()).unwrap();
189        let ciphers_tls12 =
190            CString::new(config.descriptor.protocol_config.get_cipher_string_12()).unwrap();
191        let ciphers_tlsboth =
192            CString::new(config.descriptor.protocol_config.get_cipher_string_both()).unwrap();
193        let groups = config
194            .descriptor
195            .protocol_config
196            .groups
197            .clone()
198            .map(|x| CString::new(x.clone()).unwrap());
199        let sigalgs = config
200            .descriptor
201            .protocol_config
202            .sigalgs
203            .clone()
204            .map(|x| CString::new(x.clone()).unwrap());
205
206        let descriptor = match config.descriptor.protocol_config.typ {
207            AgentType::Server => make_descriptor(
208                &config,
209                &server_cert,
210                &server_pkey,
211                &server_store,
212                &ciphers_tls13,
213                &ciphers_tls12,
214                &ciphers_tlsboth,
215                &groups,
216                &sigalgs,
217            ),
218            AgentType::Client => make_descriptor(
219                &config,
220                &client_cert,
221                &client_pkey,
222                &client_store,
223                &ciphers_tls13,
224                &ciphers_tls12,
225                &ciphers_tlsboth,
226                &groups,
227                &sigalgs,
228            ),
229        };
230
231        let c_agent = unsafe { (put.interface.create.unwrap())(&descriptor as *const _) };
232        if c_agent.is_null() {
233            return Err(Error::Put("C agent creation failed".to_owned()));
234        }
235
236        let mut agent = Self {
237            put: put.clone(),
238            config,
239            deframer: MessageDeframer::new(),
240            c_agent,
241        };
242
243        agent.register_claimer();
244
245        Ok(agent)
246    }
247
248    fn register_claimer(&mut self) {
249        unsafe {
250            use crate::claims::claims_helpers;
251
252            let claims = self.config.claims.clone();
253            let config_version = self.config.descriptor.protocol_config.tls_version;
254            let origin = self.config.descriptor.protocol_config.typ;
255            let agent_name = self.config.descriptor.name;
256
257            let claimer = make_claimer(move |claim: Claim| {
258                if let Some(data) = claims_helpers::to_claim_data(claim) {
259                    claims.deref_borrow_mut().claim_sized(TlsClaim {
260                        agent_name,
261                        origin,
262                        config_version,
263                        data,
264                        step: None,
265                    })
266                }
267            });
268
269            ccall!(
270                self.put,
271                register_claimer,
272                self.c_agent,
273                &claimer as *const _
274            );
275        }
276    }
277}
278
279impl Put<TLSProtocolBehavior> for CAgent {
280    fn progress(&mut self) -> Result<(), Error> {
281        r_ccall!(self.put, progress, self.c_agent)?;
282        Ok(())
283    }
284
285    fn reset(&mut self, new_name: puffin::agent::AgentName) -> Result<(), Error> {
286        self.config.descriptor.name = new_name;
287        r_ccall!(
288            self.put,
289            reset,
290            self.c_agent,
291            new_name.into(),
292            self.config.use_clear as u8
293        )?;
294        self.register_claimer();
295        Ok(())
296    }
297
298    fn descriptor(&self) -> &AgentDescriptor<TLSDescriptorConfig> {
299        &self.config.descriptor
300    }
301
302    fn describe_state(&self) -> String {
303        unsafe { to_string(ccall!(self.put, describe_state, self.c_agent)) }
304    }
305
306    fn is_state_successful(&self) -> bool {
307        unsafe { ccall!(self.put, is_state_successful, self.c_agent) }
308    }
309
310    fn shutdown(&mut self) -> String {
311        todo!()
312    }
313
314    fn version() -> String
315    where
316        Self: Sized,
317    {
318        todo!()
319    }
320}
321
322impl Stream<TLSProtocolBehavior> for CAgent {
323    fn add_to_inbound(&mut self, message: &puffin::algebra::ConcreteMessage) {
324        let mut written = 0usize;
325        let result = r_ccall!(
326            self.put,
327            add_inbound,
328            self.c_agent,
329            message.as_ptr(),
330            message.len(),
331            &mut written as *mut usize
332        );
333
334        if let Err(cerror) = result {
335            log::error!("C PUT agent add_to_inbound() failed: {}", cerror.reason);
336        }
337    }
338
339    fn take_message_from_outbound(
340        &mut self,
341        output_flight: &mut Option<
342            <TLSProtocolBehavior as ProtocolBehavior>::OpaqueProtocolMessageFlight,
343        >,
344    ) -> Result<(), Error> {
345        let mut flight = OpaqueMessageFlight::new();
346        loop {
347            if let Some(opaque_message) = self.deframer.pop_frame() {
348                flight.push(opaque_message);
349            } else {
350                let mut reader = CReader {
351                    put: &self.put,
352                    c_agent: self.c_agent,
353                };
354
355                match self.deframer.read(&mut reader) {
356                    Ok(v) => {
357                        if v == 0 {
358                            break;
359                        }
360                    }
361                    Err(err) => match err.kind() {
362                        std::io::ErrorKind::WouldBlock => {
363                            // This is not a hard error. It just means we will should read again
364                            // from the TCPStream in the next steps.
365                            break;
366                        }
367                        _ => {
368                            *output_flight = (!flight.messages.is_empty()).then_some(flight);
369                            return Err(err.into());
370                        }
371                    },
372                }
373            }
374        }
375
376        *output_flight = (!flight.messages.is_empty()).then_some(flight);
377
378        Ok(())
379    }
380}
381
382impl Drop for CAgent {
383    fn drop(&mut self) {
384        unsafe {
385            ccall!(self.put, destroy, self.c_agent);
386        }
387    }
388}
389
390fn make_descriptor(
391    config: &TlsPutConfig,
392    cert: *const PEM,
393    pkey: *const PEM,
394    store: &[*const PEM],
395    ciphers_tls13: &CString,
396    ciphers_tls12: &CString,
397    ciphers_tlsboth: &CString,
398    groups: &Option<CString>,
399    sigalgs: &Option<CString>,
400) -> TLS_AGENT_DESCRIPTOR {
401    // eprintln!("{:?}", cert);
402    // eprintln!("{:?}", pkey);
403    // for pem in store.iter() {
404    //     eprintln!("store cert pem ptr: {:?}", pem);
405    // }
406
407    TLS_AGENT_DESCRIPTOR {
408        name: config.descriptor.name.into(),
409        role: match config.descriptor.protocol_config.typ {
410            AgentType::Client => TLS_AGENT_ROLE::CLIENT,
411            AgentType::Server => TLS_AGENT_ROLE::SERVER,
412        },
413        tls_version: match config.descriptor.protocol_config.tls_version {
414            TLSVersion::V1_3 => TLS_VERSION::V1_3,
415            TLSVersion::V1_2 => TLS_VERSION::V1_2,
416            TLSVersion::Both => TLS_VERSION::Both,
417        },
418        client_authentication: config.descriptor.protocol_config.client_authentication,
419        server_authentication: config.descriptor.protocol_config.server_authentication,
420        cipher_string_tls13: ciphers_tls13.as_ptr(),
421        cipher_string_tls12: ciphers_tls12.as_ptr(),
422        cipher_string_tlsboth: ciphers_tlsboth.as_ptr(),
423        group_list: if let Some(group_list) = groups {
424            group_list.as_ref().as_ptr()
425        } else {
426            std::ptr::null()
427        },
428        sigalgs_list: if let Some(sigalgs_list) = sigalgs {
429            sigalgs_list.as_ref().as_ptr()
430        } else {
431            std::ptr::null()
432        },
433
434        cert,
435        pkey,
436
437        store: store.as_ptr(),
438        store_length: store.len() as libc::size_t,
439    }
440}
441
442extern "C" fn notify(ctx: *mut libc::c_void, c: *mut Claim) {
443    if c.is_null() || ctx.is_null() {
444        return;
445    }
446
447    let c = unsafe { *c };
448    let callback: &mut Box<dyn FnMut(Claim)> =
449        unsafe { &mut *(ctx as *mut std::boxed::Box<dyn FnMut(Claim)>) };
450
451    callback(c);
452}
453
454extern "C" fn destroy(ctx: *mut libc::c_void) {
455    let _: Box<Box<dyn FnMut(Claim)>> = unsafe { Box::from_raw(ctx as *mut _) };
456}
457
458fn make_claimer<F>(callback: F) -> CLAIMER_CB
459where
460    F: FnMut(Claim) + 'static,
461{
462    let cb: Box<Box<dyn FnMut(Claim)>> = Box::new(Box::new(callback));
463
464    CLAIMER_CB {
465        context: Box::into_raw(cb) as *mut _,
466        notify: Some(notify),
467        destroy: Some(destroy),
468    }
469}
470
471struct CReader<'a> {
472    put: &'a CPut,
473    c_agent: AGENT,
474}
475
476impl<'a> Read for CReader<'a> {
477    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
478        let mut readbytes = 0usize as libc::size_t;
479
480        let result = r_ccall!(
481            self.put,
482            take_outbound,
483            self.c_agent,
484            buf.as_mut_ptr(),
485            buf.len(),
486            &mut readbytes
487        );
488
489        match result {
490            Ok(_) => Ok(readbytes),
491            Err(cerror) => Err(cerror.into()),
492        }
493    }
494}