Skip to content

Commit

Permalink
Feature/replace binascii (mobilecoinfoundation#1958)
Browse files Browse the repository at this point in the history
* Remove dependency on binascii.

* Revert erroneous install_sgx.sh change.

* Fixed a possible issue in which a buffer was being allocated with 2 bytes per hex char instead of 2 hex chars per byte.

* Enacting PR suggestions: base64 size fixes, encoders that allocate, etc.

* Update attest/core/src/nonce.rs

Co-authored-by: Remoun Metyas <[email protected]>

* Update attest/core/src/sigrl.rs

Nit: Add newline

Co-authored-by: Remoun Metyas <[email protected]>

* Update attest/core/src/traits.rs

Use $crate::B64_CONFIG directly.

Co-authored-by: Remoun Metyas <[email protected]>

* Formatting fixes.

* Update attest/core/src/types/pib.rs

Co-authored-by: Remoun Metyas <[email protected]>

* Update attest/core/src/types/pib.rs

Co-authored-by: Remoun Metyas <[email protected]>

* Update crypto/keys/src/traits.rs

Co-authored-by: Remoun Metyas <[email protected]>

* Update attest/core/src/error.rs

Co-authored-by: Remoun Metyas <[email protected]>

* Improved names for types

* Update fog/report/cli/Cargo.toml

Co-authored-by: Remoun Metyas <[email protected]>

* Sort dependencies in Keys

* Sort deps, run cargo fmt

Co-authored-by: Millie C <[email protected]>
Co-authored-by: Remoun Metyas <[email protected]>
  • Loading branch information
3 people authored May 27, 2022
1 parent 5a0be43 commit d979002
Show file tree
Hide file tree
Showing 24 changed files with 116 additions and 227 deletions.
10 changes: 5 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion attest/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ mc-sgx-css = { path = "../../sgx/css" }
mc-sgx-types = { path = "../../sgx/types" }
mc-util-encodings = { path = "../../util/encodings" }

binascii = "0.1.2"
base64 = { version = "0.13", default-features = false, features = ["alloc"] }
bitflags = "1.2"
chrono = { version = "0.4.19", default-features = false, features = ["alloc"] }
digest = "0.10"
displaydoc = { version = "0.2", default-features = false }
hex = { version = "0.4", default-features = false, features = ["alloc"] }
hex_fmt = "0.3"
prost = { version = "0.10", default-features = false }
rjson = "0.3.1"
Expand Down
22 changes: 11 additions & 11 deletions attest/core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
},
};
use alloc::{string::String, vec::Vec};
use binascii::ConvertError;
use base64::DecodeError;
use bitflags::bitflags;
use core::{
fmt::{Display, Error as FmtError, Formatter, Result as FmtResult},
Expand All @@ -34,8 +34,8 @@ pub enum EpidPseudonymError {
SizeMismatch,
}

impl From<ConvertError> for EpidPseudonymError {
fn from(src: ConvertError) -> Self {
impl From<DecodeError> for EpidPseudonymError {
fn from(src: DecodeError) -> Self {
EpidPseudonymError::Decode(src.into())
}
}
Expand Down Expand Up @@ -156,8 +156,8 @@ pub enum PibError {
Convert(EncodingError),
}

impl From<ConvertError> for PibError {
fn from(src: ConvertError) -> PibError {
impl From<DecodeError> for PibError {
fn from(src: DecodeError) -> PibError {
PibError::Convert(src.into())
}
}
Expand Down Expand Up @@ -239,8 +239,8 @@ pub enum QuoteError {
InvalidUtf8,
}

impl From<ConvertError> for QuoteError {
fn from(src: ConvertError) -> Self {
impl From<base64::DecodeError> for QuoteError {
fn from(src: base64::DecodeError) -> Self {
QuoteError::Encoding(src.into())
}
}
Expand Down Expand Up @@ -322,8 +322,8 @@ pub enum QuoteVerifyError {
QuotedReportMismatch,
}

impl From<ConvertError> for QuoteVerifyError {
fn from(src: ConvertError) -> Self {
impl From<DecodeError> for QuoteVerifyError {
fn from(src: DecodeError) -> Self {
QuoteVerifyError::Decode(src.into())
}
}
Expand Down Expand Up @@ -616,8 +616,8 @@ pub enum TargetInfoError {
Convert(EncodingError),
}

impl From<ConvertError> for TargetInfoError {
fn from(src: ConvertError) -> Self {
impl From<DecodeError> for TargetInfoError {
fn from(src: DecodeError) -> Self {
TargetInfoError::Convert(src.into())
}
}
Expand Down
39 changes: 11 additions & 28 deletions attest/core/src/ias/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ use crate::{
epid_group_id::EpidGroupId, measurement::Measurement, pib::PlatformInfoBlob,
report_data::ReportDataMask,
},
B64_CONFIG,
};
use alloc::{
string::{String, ToString},
vec::Vec,
};
use binascii::{b64decode, b64encode, hex2bin};
use core::{
convert::{TryFrom, TryInto},
f64::EPSILON,
Expand Down Expand Up @@ -87,15 +87,11 @@ impl FromBase64 for EpidPseudonym {

/// Parse a Base64-encoded string into a 128-byte EpidPseudonym
fn from_base64(src: &str) -> Result<Self, EncodingError> {
let mut buffer = [0u8; EPID_PSEUDONYM_LEN + 4];
let buflen = {
let output = b64decode(src.as_bytes(), &mut buffer[..])?;
output.len()
};
if buflen != EPID_PSEUDONYM_LEN {
let buffer = base64::decode_config(src, B64_CONFIG)?;
if buffer.len() != EPID_PSEUDONYM_LEN {
return Err(EncodingError::InvalidInputLength);
}
let (left, right) = buffer.split_at(buflen / 2);
let (left, right) = buffer.split_at(buffer.len() / 2);
Ok(Self {
b: Vec::from(left),
k: Vec::from(right),
Expand All @@ -111,10 +107,7 @@ impl ToBase64 for EpidPseudonym {
let mut inbuf = Vec::with_capacity(self.b.len() + self.k.len());
inbuf.extend_from_slice(&self.b);
inbuf.extend_from_slice(&self.k);
match b64encode(&inbuf, dest) {
Ok(buffer) => Ok(buffer.len()),
Err(_e) => Err(EPID_PSEUDONYM_LEN + 4),
}
Ok(base64::encode_config_slice(&inbuf, B64_CONFIG, dest))
}
}
}
Expand Down Expand Up @@ -411,14 +404,10 @@ impl<'src> TryFrom<&'src VerificationReport> for VerificationReportData {
let pse_manifest_hash = match data.remove("pseManifestHash") {
Some(v) => {
let value: String = v.try_into()?;
let mut result = Vec::with_capacity(value.len() * 3 / 4 + 4);
let result_len = {
let result_slice = hex2bin(value.as_bytes(), &mut result)
.map_err(|e| PseManifestHashError::Parse(e.into()))?;
result_slice.len()
};
result.truncate(result_len);
Some(result)
Some(
hex::decode(value.as_bytes())
.map_err(|e| PseManifestHashError::Parse(e.into()))?,
)
}
None => None,
};
Expand Down Expand Up @@ -493,14 +482,8 @@ impl FromHex for VerificationSignature {
type Error = EncodingError;

fn from_hex(s: &str) -> Result<Self, EncodingError> {
// base64 strlength = 4 * (bytelen / 3) + padding
let mut data = vec![0u8; 3 * ((s.len() + 4) / 4)];
let buflen = {
let buffer = b64decode(s.as_bytes(), data.as_mut_slice())?;
buffer.len()
};
data.truncate(buflen);
Ok(VerificationSignature::from(data))
// 2 hex chars per byte
Ok(hex::decode(s)?.into())
}
}

Expand Down
3 changes: 3 additions & 0 deletions attest/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,6 @@ pub use crate::{

/// The IAS version we support
pub const IAS_VERSION: f64 = 4.0;

// Expected format for base64 strings
pub(crate) const B64_CONFIG: base64::Config = base64::STANDARD;
11 changes: 6 additions & 5 deletions attest/core/src/nonce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
use alloc::vec;

use crate::{error::NonceError, impl_sgx_newtype_for_bytestruct, traits::bin2hex};
use crate::{error::NonceError, impl_sgx_newtype_for_bytestruct};
use alloc::vec::Vec;
use binascii::hex2bin;
use core::{
convert::{AsRef, Into, TryFrom, TryInto},
fmt::{Display, Formatter, Result as FmtResult},
Expand Down Expand Up @@ -139,15 +138,17 @@ impl FromHex for IasNonce {
return Err(EncodingError::InvalidInputLength);
}
let mut retval = Self::default();
hex2bin(s.as_bytes(), &mut retval.0[..])?;
hex::decode_to_slice(s, &mut retval.0[..])?;
Ok(retval)
}
}

impl ToHex for IasNonce {
fn to_hex(&self, dest: &mut [u8]) -> Result<usize, usize> {
match bin2hex(self.as_ref(), dest) {
Ok(buffer) => Ok(buffer.len()),
let bytes = self.as_ref();
match hex::encode_to_slice(bytes, dest) {
// Return the number of bytes used, per ToHex spec.
Ok(()) => Ok(bytes.len() * 2),
Err(_e) => Err(IAS_NONCE_STR_LENGTH),
}
}
Expand Down
13 changes: 4 additions & 9 deletions attest/core/src/quote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,9 @@ use crate::{
basename::Basename, epid_group_id::EpidGroupId, measurement::Measurement,
report_body::ReportBody, report_data::ReportDataMask,
},
ProductId, SecurityVersion,
ProductId, SecurityVersion, B64_CONFIG,
};
use alloc::vec::Vec;
use binascii::{b64decode, b64encode};
use core::{
cmp::{max, min},
convert::{TryFrom, TryInto},
Expand Down Expand Up @@ -386,9 +385,8 @@ impl FromBase64 for Quote {

// Create an output buffer of at least MINSIZE bytes
let mut retval = Quote::with_capacity(expected_len)?;
match b64decode(s.as_bytes(), retval.0.as_mut_slice()) {
Ok(buffer) => {
let bufferlen = buffer.len();
match base64::decode_config_slice(s.as_bytes(), B64_CONFIG, retval.0.as_mut_slice()) {
Ok(bufferlen) => {
if bufferlen != QUOTE_IAS_SIZE && bufferlen != retval.intel_size() {
// The size of the decoded bytes does not match the size embedded in the bytes,
// and we're not handling an IAS/no-signature quote
Expand Down Expand Up @@ -422,10 +420,7 @@ impl ToBase64 for Quote {
if dest.len() < required_len {
Err(required_len)
} else {
match b64encode(&self.0[..], dest) {
Ok(buffer) => Ok(buffer.len()),
Err(_e) => Err(required_len),
}
Ok(base64::encode_config_slice(&self.0[..], B64_CONFIG, dest))
}
}
}
Expand Down
16 changes: 4 additions & 12 deletions attest/core/src/sigrl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@

//! SigRL Type
use alloc::vec;

use crate::B64_CONFIG;
use alloc::{borrow::ToOwned, vec::Vec};
use binascii::b64decode;
use core::{
fmt::{Display, Formatter, Result as FmtResult},
ops::Deref,
Expand Down Expand Up @@ -70,14 +68,8 @@ impl FromBase64 for SigRL {
type Error = EncodingError;

fn from_base64(s: &str) -> Result<Self, EncodingError> {
let mut data;
if s.is_empty() {
// Ensure size of data remains 0 if empty string
data = vec![];
} else {
data = vec![0u8; 4 * (s.len() / 3) + 4];
b64decode(s.as_bytes(), data.as_mut_slice())?;
}
Ok(SigRL { data })
Ok(SigRL {
data: base64::decode_config(s.as_bytes(), B64_CONFIG)?,
})
}
}
25 changes: 11 additions & 14 deletions attest/core/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,15 @@

//! Trait definitions for rust structures with an FFI analogue
// Re-export macros our macros are using
pub(crate) use alloc::format as _alloc_format;

// Re-export types our macros are using
pub(crate) use alloc::vec::Vec;
pub(crate) use binascii::{b64decode, b64encode, bin2hex, hex2bin};
pub(crate) use alloc::{format as _alloc_format, vec::Vec};
pub(crate) use base64::{decode_config_slice as b64_decode, encode_config_slice as b64_encode};
pub(crate) use core::{
cmp::{Ord, Ordering},
convert::TryFrom,
fmt::{Debug, Display, Formatter, Result as FmtResult},
hash::{Hash, Hasher},
};
pub(crate) use hex::{decode_to_slice as hex_decode, encode_to_slice as hex_encode};
pub(crate) use hex_fmt::HexFmt;
pub(crate) use mc_util_encodings::{
base64_buffer_size, base64_size, Error as EncodingError, FromBase64, FromHex, IntelLayout,
Expand Down Expand Up @@ -355,7 +352,7 @@ macro_rules! impl_base64str_for_bytestruct {

// Create an output buffer of at least MINSIZE bytes
let mut retval = Self::default();
$crate::traits::b64decode(s.as_bytes(), &mut (retval.0).$fieldname[..])?;
$crate::traits::b64_decode(s.as_bytes(), $crate::B64_CONFIG, &mut (retval.0).$fieldname[..])?;
Ok(retval)
}
}
Expand All @@ -366,10 +363,9 @@ macro_rules! impl_base64str_for_bytestruct {
if dest.len() < required_buffer_len {
Err(required_buffer_len)
} else {
match $crate::traits::b64encode(&(self.0).$fieldname[..], dest) {
Ok(buffer) => Ok(buffer.len()),
Err(_convert) => Err(required_buffer_len)
}
Ok(
$crate::traits::b64_encode(&(self.0).$fieldname[..], $crate::B64_CONFIG, dest)
)
}
}
}
Expand All @@ -392,15 +388,16 @@ macro_rules! impl_hexstr_for_bytestruct {
}

let mut retval = Self::default();
$crate::traits::hex2bin(s.as_bytes(), &mut (retval.0).$fieldname[..])?;
$crate::traits::hex_decode(s.as_bytes(), &mut (retval.0).$fieldname[..])?;
Ok(retval)
}
}

impl $crate::traits::ToHex for $wrapper {
fn to_hex(&self, dest: &mut [u8]) -> core::result::Result<usize, usize> {
match $crate::traits::bin2hex(&(self.0).$fieldname[..], dest) {
Ok(buffer) => Ok(buffer.len()),
let source = &(self.0).$fieldname[..];
match $crate::traits::hex_encode(source, dest) {
Ok(()) => Ok(source.len()*2),
Err(_e) => Err($size * 2),
}
}
Expand Down
Loading

0 comments on commit d979002

Please sign in to comment.