Skip to content

Commit be80b1a

Browse files
committed
Use manticore::Result and debug macros crate-wide
* Replace usage of `Result` with `crate::Result` nearly everywhere. The individual certificate parsers use the old `Result` type to avoid conflicts with the types returned by the `untrusted` crate, which is used for parsing. * Add some extra `From` implementations to the `debug_from!` macro to allow existing usage with the try operator `?`. Signed-off-by: Kesavan Yogeswaran <[email protected]>
1 parent 6f45848 commit be80b1a

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+325
-341
lines changed

e2e/src/support/rot.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ use manticore::protocol::spdm;
2929
use manticore::server;
3030
use manticore::server::pa_rot::PaRot;
3131
use manticore::session::ring::Session;
32+
use manticore::Result;
3233

3334
use crate::support::fakes;
3435
use crate::support::tcp;

e2e/src/support/tcp.rs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ use manticore::protocol::wire::WireEnum;
4747
use manticore::protocol::Command;
4848
use manticore::protocol::Message;
4949
use manticore::server;
50+
use manticore::Result;
51+
use manticore::{check, fail};
5052

5153
/// Sends `req` to a virtual RoT listening on `localhost:{port}`, using
5254
/// Cerberus-over-TCP.
@@ -84,7 +86,7 @@ pub fn send_cerberus<
8486
Ok(Ok(FromWire::from_wire(&mut r, arena)?))
8587
} else if header.command == cerberus::CommandType::Error {
8688
log::info!("deserializing {}", type_name::<protocol::Error<'a, Cmd>>());
87-
Ok(Err(FromWire::from_wire(&mut r, arena)?))
89+
Ok(Err(fail!(FromWire::from_wire(&mut r, arena)?)))
8890
} else {
8991
Err(net::Error::BadHeader.into())
9092
}
@@ -125,7 +127,7 @@ pub fn send_spdm<'a, Cmd: Command<'a, CommandType = spdm::CommandType>>(
125127
Ok(Ok(FromWire::from_wire(&mut r, arena)?))
126128
} else if header.command == spdm::CommandType::Error {
127129
log::info!("deserializing {}", type_name::<protocol::Error<'a, Cmd>>());
128-
Ok(Err(FromWire::from_wire(&mut r, arena)?))
130+
Ok(Err(fail!(FromWire::from_wire(&mut r, arena)?)))
129131
} else {
130132
Err(net::Error::BadHeader.into())
131133
}
@@ -140,7 +142,7 @@ impl io::Read for TcpReader {
140142
fn read_bytes(&mut self, out: &mut [u8]) -> Result<(), io::Error> {
141143
let Self { tcp, len } = self;
142144
if *len < out.len() {
143-
return Err(io::Error::BufferExhausted);
145+
return Err(fail!(io::Error::BufferExhausted));
144146
}
145147
tcp.read_exact(out).map_err(|e| {
146148
log::error!("{}", e);
@@ -365,22 +367,22 @@ impl<'req, H: Header + 'req> HostRequest<'req, H> for Inner<H> {
365367
fn header(&self) -> Result<H, net::Error> {
366368
if self.output_buffer.is_some() {
367369
log::error!("header() called out-of-order");
368-
return Err(net::Error::OutOfOrder);
370+
return Err(fail!(net::Error::OutOfOrder));
369371
}
370372
self.stream
371373
.as_ref()
372374
.map(|(h, _, _)| *h)
373-
.ok_or(net::Error::Disconnected)
375+
.ok_or_else(|| fail!(net::Error::Disconnected))
374376
}
375377

376378
fn payload(&mut self) -> Result<&mut dyn io::ReadZero<'req>, net::Error> {
377379
if self.stream.is_none() {
378380
log::error!("payload() called out-of-order");
379-
return Err(net::Error::Disconnected);
381+
return Err(fail!(net::Error::Disconnected));
380382
}
381383
if self.output_buffer.is_some() {
382384
log::error!("payload() called out-of-order");
383-
return Err(net::Error::OutOfOrder);
385+
return Err(fail!(net::Error::OutOfOrder));
384386
}
385387

386388
Ok(self)
@@ -392,11 +394,11 @@ impl<'req, H: Header + 'req> HostRequest<'req, H> for Inner<H> {
392394
) -> Result<&mut dyn HostResponse<'req>, net::Error> {
393395
if self.stream.is_none() {
394396
log::error!("payload() called out-of-order");
395-
return Err(net::Error::Disconnected);
397+
return Err(fail!(net::Error::Disconnected));
396398
}
397399
if self.output_buffer.is_some() {
398400
log::error!("payload() called out-of-order");
399-
return Err(net::Error::OutOfOrder);
401+
return Err(fail!(net::Error::OutOfOrder));
400402
}
401403

402404
self.output_buffer = Some(Writer::new(header));
@@ -408,13 +410,13 @@ impl<'req, H: Header + 'req> HostResponse<'req> for Inner<H> {
408410
fn sink(&mut self) -> Result<&mut dyn io::Write, net::Error> {
409411
if self.stream.is_none() {
410412
log::error!("sink() called out-of-order");
411-
return Err(net::Error::Disconnected);
413+
return Err(fail!(net::Error::Disconnected));
412414
}
413415

414416
self.output_buffer
415417
.as_mut()
416418
.map(|w| w as &mut dyn io::Write)
417-
.ok_or(net::Error::OutOfOrder)
419+
.ok_or_else(|| fail!(net::Error::OutOfOrder))
418420
}
419421

420422
fn finish(&mut self) -> Result<(), net::Error> {
@@ -434,7 +436,7 @@ impl<'req, H: Header + 'req> HostResponse<'req> for Inner<H> {
434436
self.output_buffer = None;
435437
Ok(())
436438
}
437-
_ => Err(net::Error::Disconnected),
439+
_ => Err(fail!(net::Error::Disconnected)),
438440
}
439441
}
440442
}
@@ -443,9 +445,7 @@ impl<H> io::Read for Inner<H> {
443445
fn read_bytes(&mut self, out: &mut [u8]) -> Result<(), io::Error> {
444446
let (_, len, stream) =
445447
self.stream.as_mut().ok_or(io::Error::Internal)?;
446-
if *len < out.len() {
447-
return Err(io::Error::BufferExhausted);
448-
}
448+
check!(*len >= out.len(), io::Error::BufferExhausted);
449449
stream.read_exact(out).map_err(|e| {
450450
log::error!("{}", e);
451451
io::Error::Internal

fuzz/targets/x509_unsigned.rs

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,13 @@ use manticore::cert::Cert;
1313
use manticore::cert::CertFormat;
1414
use manticore::crypto::sig;
1515
use manticore::protocol::cerberus::capabilities;
16+
use manticore::Result;
1617

1718
/// A `Ciphers` that blindly accepts all signatures.
1819
struct NoVerify;
1920

2021
impl sig::Verify for NoVerify {
21-
fn verify(
22-
&mut self,
23-
_: &[&[u8]],
24-
_: &[u8],
25-
) -> Result<(), sig::Error> {
22+
fn verify(&mut self, _: &[&[u8]], _: &[u8]) -> Result<(), sig::Error> {
2623
Ok(())
2724
}
2825
}
@@ -39,12 +36,7 @@ impl sig::Ciphers for NoVerify {
3936
}
4037

4138
fuzz_target!(|data: &[u8]| {
42-
let _ = Cert::parse(
43-
data,
44-
CertFormat::RiotX509,
45-
None,
46-
&mut NoVerify,
47-
);
39+
let _ = Cert::parse(data, CertFormat::RiotX509, None, &mut NoVerify);
4840

4941
// NOTE: we might actually succeed at creating a valid cert, so we can't
5042
// check for is_err() here.

src/cert/chain.rs

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use crate::cert::Cert;
1313
use crate::cert::CertFormat;
1414
use crate::cert::Error;
1515
use crate::crypto::sig;
16+
use crate::Result;
1617

1718
/// A trust chain collection.
1819
///
@@ -66,9 +67,7 @@ impl<'cert, const LEN: usize> SimpleChain<'cert, LEN> {
6667
ciphers: &mut impl sig::Ciphers,
6768
signer: Option<&'cert mut dyn sig::Sign>,
6869
) -> Result<Self, Error> {
69-
if raw_chain.len() > LEN {
70-
return Err(Error::ChainTooLong);
71-
}
70+
check!(raw_chain.len() <= LEN, Error::ChainTooLong);
7271

7372
let mut chain = ArrayVec::new();
7473
for (i, &raw_cert) in raw_chain.iter().enumerate() {
@@ -77,26 +76,21 @@ impl<'cert, const LEN: usize> SimpleChain<'cert, LEN> {
7776
let cert = Cert::parse(raw_cert, format, key, ciphers)?;
7877

7978
let prev = prev.unwrap_or(&cert);
80-
if prev.subject() != cert.issuer() {
81-
return Err(Error::BadChainLink);
82-
}
83-
if !prev.supports_cert_signing() {
84-
return Err(Error::BadChainLink);
85-
}
79+
check!(prev.subject() == cert.issuer(), Error::BadChainLink);
80+
check!(prev.supports_cert_signing(), Error::BadChainLink);
8681

8782
// None is also ok; it means the format (e.g. CWT) does not support
8883
// a CA bit.
89-
if prev.is_ca_cert() == Some(false) {
90-
return Err(Error::BadChainLink);
91-
}
84+
check!(prev.is_ca_cert() != Some(false), Error::BadChainLink);
9285

9386
// raw_chain.len() - i is the number of certificates that follow
9487
// `cert`; the path length constraint for `prev` is the number of
9588
// certs that follow it, except the leaf; these numbers are the
9689
// same.
97-
if !prev.is_within_path_len_constraint(raw_chain.len() - i) {
98-
return Err(Error::BadChainLink);
99-
}
90+
check!(
91+
prev.is_within_path_len_constraint(raw_chain.len() - i),
92+
Error::BadChainLink
93+
);
10094

10195
chain.push(cert);
10296
}

src/cert/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
1111
use crate::crypto::sig;
1212
use crate::io;
13+
use crate::Result;
1314

1415
// Note that all parsers leverage Brian Smith's `untrusted` crate to ensure
1516
// we don't walk off the end of the buffer. We may wind up building this
@@ -125,6 +126,7 @@ impl<'cert> Cert<'cert> {
125126
CertFormat::RiotX509 => x509::parse(cert, format, key, ciphers),
126127
CertFormat::OpenDiceCwt => cwt::parse(cert, key, ciphers),
127128
}
129+
.map_err(|e| fail!(e))
128130
}
129131

130132
/// Returns the slice this certificate was parsed from.

src/crypto/csrng.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,17 @@
44

55
//! Cryptographic random numbers.
66
7+
use crate::Result;
8+
79
/// An error returned by a CSRNG.
810
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
911
pub enum Error {
1012
/// Indicates an unspecified, internal error.
1113
Unspecified,
1214
}
1315

16+
debug_from!(Error);
17+
1418
/// A cryptographically-secure random number generator.
1519
///
1620
/// The sole purpose of this type is to fill buffers with random bytes,

src/crypto/hash.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use crate::mem::Arena;
1212
use crate::mem::ArenaExt as _;
1313
use crate::mem::OutOfMemory;
14+
use crate::Result;
1415

1516
#[cfg(feature = "arbitrary-derive")]
1617
use libfuzzer_sys::arbitrary::{self, Arbitrary};
@@ -68,6 +69,8 @@ pub enum Error {
6869
Unspecified,
6970
}
7071

72+
debug_from!(Error);
73+
7174
/// A hashing engine, which maintains the state for one digest.
7275
///
7376
/// Callers should not use the `raw` API directly; [`Hasher`] is a type-safe

src/crypto/ring/csrng.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use ring::rand::SecureRandom as _;
1010
use ring::rand::SystemRandom;
1111

1212
use crate::crypto::csrng;
13+
use crate::Result;
1314

1415
#[cfg(doc)]
1516
use crate::crypto;
@@ -36,6 +37,8 @@ impl Default for Csrng {
3637

3738
impl csrng::Csrng for Csrng {
3839
fn fill(&mut self, buf: &mut [u8]) -> Result<(), csrng::Error> {
39-
self.inner.fill(buf).map_err(|_| csrng::Error::Unspecified)
40+
self.inner
41+
.fill(buf)
42+
.map_err(|_| fail!(csrng::Error::Unspecified))
4043
}
4144
}

src/crypto/ring/ecdsa.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use ring::signature::EcdsaVerificationAlgorithm as EcdsaAlgo;
1010
use ring::signature::VerificationAlgorithm as _;
1111

1212
use crate::crypto::sig;
13+
use crate::Result;
1314

1415
/// A `ring`-based [`sig::Verify`] for DER-encoded ECDSA using the P-256 curve.
1516
pub struct VerifyP256 {
@@ -62,7 +63,7 @@ impl sig::Verify for VerifyP256 {
6263
message.as_slice().into(),
6364
signature.into(),
6465
)
65-
.map_err(|_| sig::Error::Unspecified)
66+
.map_err(|_| fail!(sig::Error::Unspecified))
6667
}
6768
}
6869

@@ -83,7 +84,7 @@ impl SignP256 {
8384
&ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING,
8485
pkcs8,
8586
)
86-
.map_err(|_| sig::Error::Unspecified)?;
87+
.map_err(|_| fail!(sig::Error::Unspecified))?;
8788
Ok(Self { keypair })
8889
}
8990

@@ -98,7 +99,7 @@ impl SignP256 {
9899
&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
99100
pkcs8,
100101
)
101-
.map_err(|_| sig::Error::Unspecified)?;
102+
.map_err(|_| fail!(sig::Error::Unspecified))?;
102103
Ok(Self { keypair })
103104
}
104105
}
@@ -133,7 +134,7 @@ impl sig::Sign for SignP256 {
133134
let sig = self
134135
.keypair
135136
.sign(&rng, &message)
136-
.map_err(|_| sig::Error::Unspecified)?;
137+
.map_err(|_| fail!(sig::Error::Unspecified))?;
137138
let signature = signature
138139
.get_mut(..sig.as_ref().len())
139140
.ok_or(sig::Error::Unspecified)?;

0 commit comments

Comments
 (0)