Skip to content

Commit

Permalink
Add Result alias (#271)
Browse files Browse the repository at this point in the history
Adds a `yubikey::Result` alias with `yubikey::Error` as the error type.

Since we only have one `Error` type, this simplifies the return types
where a `Result` is returned.
  • Loading branch information
tony-iqlusion authored Jul 11, 2021
1 parent 1051eaf commit de51b0c
Show file tree
Hide file tree
Showing 23 changed files with 197 additions and 210 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion cli/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub struct YubiKeyCli {

impl YubiKeyCli {
/// Print usage information
pub fn print_usage() -> Result<(), io::Error> {
pub fn print_usage() -> io::Result<()> {
let mut stdout = STDOUT.lock();
stdout.reset()?;

Expand Down
2 changes: 1 addition & 1 deletion cli/src/commands/readers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ impl ReadersCmd {
index: usize,
name: &str,
serial: Serial,
) -> Result<(), io::Error> {
) -> io::Result<()> {
stream.set_color(ColorSpec::new().set_bold(true))?;
write!(stream, "{:>3}:", index)?;
stream.reset()?;
Expand Down
2 changes: 1 addition & 1 deletion cli/src/commands/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl StatusCmd {
stream: &mut StandardStreamLock<'_>,
name: &str,
value: impl ToString,
) -> Result<(), io::Error> {
) -> io::Result<()> {
stream.set_color(ColorSpec::new().set_bold(true))?;
write!(stream, "{:>12}:", name)?;
stream.reset()?;
Expand Down
4 changes: 2 additions & 2 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub fn print_cert_info(
yubikey: &mut YubiKey,
slot: SlotId,
stream: &mut StandardStreamLock<'_>,
) -> Result<(), io::Error> {
) -> io::Result<()> {
let cert = match Certificate::read(yubikey, slot) {
Ok(c) => c,
Err(e) => {
Expand Down Expand Up @@ -82,7 +82,7 @@ fn print_cert_attr(
stream: &mut StandardStreamLock<'_>,
name: &str,
value: impl ToString,
) -> Result<(), io::Error> {
) -> io::Result<()> {
stream.set_color(ColorSpec::new().set_bold(true))?;
write!(stream, "{:>12}:", name)?;
stream.reset()?;
Expand Down
2 changes: 1 addition & 1 deletion cli/src/terminal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ impl Status {
}

/// Print the given message
fn print(self, stream: &StandardStream, msg: impl AsRef<str>) -> Result<(), io::Error> {
fn print(self, stream: &StandardStream, msg: impl AsRef<str>) -> io::Result<()> {
let mut s = stream.lock();
s.reset()?;
s.set_color(ColorSpec::new().set_fg(self.color).set_bold(self.bold))?;
Expand Down
4 changes: 2 additions & 2 deletions src/apdu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use crate::{error::Error, transaction::Transaction, Buffer};
use crate::{transaction::Transaction, Buffer, Result};
use log::trace;
use zeroize::{Zeroize, Zeroizing};

Expand Down Expand Up @@ -109,7 +109,7 @@ impl Apdu {
}

/// Transmit this APDU using the given card transaction
pub fn transmit(&self, txn: &Transaction<'_>, recv_len: usize) -> Result<Response, Error> {
pub fn transmit(&self, txn: &Transaction<'_>, recv_len: usize) -> Result<Response> {
trace!(">>> {:?}", self);
let response = Response::from(txn.transmit(&self.to_bytes(), recv_len)?);
trace!("<<< {:?}", &response);
Expand Down
10 changes: 5 additions & 5 deletions src/cccid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use crate::{error::Error, yubikey::YubiKey};
use crate::{Error, Result, YubiKey};
use getrandom::getrandom;
use std::fmt::{self, Debug, Display};
use subtle_encoding::hex;
Expand Down Expand Up @@ -68,7 +68,7 @@ pub struct CardId(pub [u8; CCCID_SIZE]);

impl CardId {
/// Generate a random CCC Card ID
pub fn generate() -> Result<Self, Error> {
pub fn generate() -> Result<Self> {
let mut id = [0u8; CCCID_SIZE];
getrandom(&mut id).map_err(|_| Error::RandomnessError)?;
Ok(Self(id))
Expand All @@ -81,14 +81,14 @@ pub struct Ccc(pub [u8; CCC_SIZE]);

impl Ccc {
/// Return CardId component of CCC
pub fn card_id(&self) -> Result<CardId, Error> {
pub fn card_id(&self) -> Result<CardId> {
let mut cccid = [0u8; CCCID_SIZE];
cccid.copy_from_slice(&self.0[CCC_ID_OFFS..(CCC_ID_OFFS + CCCID_SIZE)]);
Ok(CardId(cccid))
}

/// Get Cardholder Capability Container (CCC) ID
pub fn get(yubikey: &mut YubiKey) -> Result<Self, Error> {
pub fn get(yubikey: &mut YubiKey) -> Result<Self> {
let txn = yubikey.begin_transaction()?;
let response = txn.fetch_object(OBJ_CAPABILITY)?;

Expand All @@ -103,7 +103,7 @@ impl Ccc {

/// Set Cardholder Capability Container (CCC) ID
#[cfg(feature = "untested")]
pub fn set(&self, yubikey: &mut YubiKey) -> Result<(), Error> {
pub fn set(&self, yubikey: &mut YubiKey) -> Result<()> {
let mut buf = CCC_TMPL.to_vec();
buf[0..self.0.len()].copy_from_slice(&self.0);

Expand Down
39 changes: 17 additions & 22 deletions src/certificate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use crate::{
error::Error,
error::{Error, Result},
key::{sign_data, AlgorithmId, SlotId},
serialization::*,
transaction::Transaction,
Expand Down Expand Up @@ -82,13 +82,13 @@ impl From<[u8; 20]> for Serial {
}

impl TryFrom<&[u8]> for Serial {
type Error = ();
type Error = Error;

fn try_from(bytes: &[u8]) -> Result<Serial, ()> {
fn try_from(bytes: &[u8]) -> Result<Serial> {
if bytes.len() <= 20 {
Ok(Serial(BigUint::from_bytes_be(&bytes)))
} else {
Err(())
Err(Error::ParseError)
}
}
}
Expand All @@ -112,7 +112,7 @@ pub enum CertInfo {
impl TryFrom<u8> for CertInfo {
type Error = Error;

fn try_from(value: u8) -> Result<Self, Self::Error> {
fn try_from(value: u8) -> Result<Self> {
match value {
0x00 => Ok(CertInfo::Uncompressed),
0x01 => Ok(CertInfo::Gzip),
Expand Down Expand Up @@ -190,7 +190,7 @@ impl fmt::Debug for PublicKeyInfo {
}

impl PublicKeyInfo {
fn parse(subject_pki: &SubjectPublicKeyInfo<'_>) -> Result<Self, Error> {
fn parse(subject_pki: &SubjectPublicKeyInfo<'_>) -> Result<Self> {
match subject_pki.algorithm.algorithm.to_string().as_str() {
OID_RSA_ENCRYPTION => {
let pubkey = read_pki::rsa_pubkey(subject_pki.subject_public_key.data)?;
Expand Down Expand Up @@ -330,7 +330,7 @@ pub struct Certificate {
impl<'a> TryFrom<&'a [u8]> for Certificate {
type Error = Error;

fn try_from(bytes: &'a [u8]) -> Result<Self, Error> {
fn try_from(bytes: &'a [u8]) -> Result<Self> {
Self::from_bytes(bytes.to_vec())
}
}
Expand All @@ -350,7 +350,7 @@ impl Certificate {
subject: &[RelativeDistinguishedName<'_>],
subject_pki: PublicKeyInfo,
extensions: &[x509::Extension<'_, O>],
) -> Result<Self, Error> {
) -> Result<Self> {
let serial = serial.into();

let mut tbs_cert = Buffer::new(Vec::with_capacity(CB_OBJ_MAX));
Expand Down Expand Up @@ -453,7 +453,7 @@ impl Certificate {
}

/// Read a certificate from the given slot in the YubiKey
pub fn read(yubikey: &mut YubiKey, slot: SlotId) -> Result<Self, Error> {
pub fn read(yubikey: &mut YubiKey, slot: SlotId) -> Result<Self> {
let txn = yubikey.begin_transaction()?;
let buf = read_certificate(&txn, slot)?;

Expand All @@ -465,25 +465,20 @@ impl Certificate {
}

/// Write this certificate into the YubiKey in the given slot
pub fn write(
&self,
yubikey: &mut YubiKey,
slot: SlotId,
certinfo: CertInfo,
) -> Result<(), Error> {
pub fn write(&self, yubikey: &mut YubiKey, slot: SlotId, certinfo: CertInfo) -> Result<()> {
let txn = yubikey.begin_transaction()?;
write_certificate(&txn, slot, Some(&self.data), certinfo)
}

/// Delete a certificate located at the given slot of the given YubiKey
#[cfg(feature = "untested")]
pub fn delete(yubikey: &mut YubiKey, slot: SlotId) -> Result<(), Error> {
pub fn delete(yubikey: &mut YubiKey, slot: SlotId) -> Result<()> {
let txn = yubikey.begin_transaction()?;
write_certificate(&txn, slot, None, CertInfo::Uncompressed)
}

/// Initialize a local certificate struct from the given bytebuffer
pub fn from_bytes(cert: impl Into<Buffer>) -> Result<Self, Error> {
pub fn from_bytes(cert: impl Into<Buffer>) -> Result<Self> {
let cert = cert.into();

if cert.is_empty() {
Expand Down Expand Up @@ -544,7 +539,7 @@ impl AsRef<[u8]> for Certificate {
}

/// Read certificate
pub(crate) fn read_certificate(txn: &Transaction<'_>, slot: SlotId) -> Result<Buffer, Error> {
pub(crate) fn read_certificate(txn: &Transaction<'_>, slot: SlotId) -> Result<Buffer> {
let object_id = slot.object_id();

let buf = match txn.fetch_object(object_id) {
Expand Down Expand Up @@ -572,7 +567,7 @@ pub(crate) fn write_certificate(
slot: SlotId,
data: Option<&[u8]>,
certinfo: CertInfo,
) -> Result<(), Error> {
) -> Result<()> {
let object_id = slot.object_id();

if data.is_none() {
Expand Down Expand Up @@ -602,7 +597,7 @@ mod read_pki {
use rsa::{BigUint, RSAPublicKey};

use super::{OID_NIST_P256, OID_NIST_P384};
use crate::{error::Error, key::AlgorithmId};
use crate::{key::AlgorithmId, Error, Result};

/// From [RFC 8017](https://tools.ietf.org/html/rfc8017#appendix-A.1.1):
/// ```text
Expand All @@ -611,7 +606,7 @@ mod read_pki {
/// publicExponent INTEGER -- e
/// }
/// ```
pub(super) fn rsa_pubkey(encoded: &[u8]) -> Result<RSAPublicKey, Error> {
pub(super) fn rsa_pubkey(encoded: &[u8]) -> Result<RSAPublicKey> {
fn parse_rsa_pubkey(i: &[u8]) -> IResult<&[u8], DerObject<'_>, BerError> {
parse_der_sequence_defined!(i, parse_der_integer >> parse_der_integer)
}
Expand Down Expand Up @@ -650,7 +645,7 @@ mod read_pki {
/// -- specifiedCurve SpecifiedECDomain
/// }
/// ```
pub(super) fn ec_parameters(parameters: &DerObject<'_>) -> Result<AlgorithmId, Error> {
pub(super) fn ec_parameters(parameters: &DerObject<'_>) -> Result<AlgorithmId> {
let curve_oid = parameters.as_oid_val().map_err(|_| Error::InvalidObject)?;

match curve_oid.to_string().as_str() {
Expand Down
14 changes: 7 additions & 7 deletions src/chuid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use crate::{error::Error, yubikey::YubiKey};
use crate::{Error, Result, YubiKey};
use getrandom::getrandom;
use std::fmt::{self, Debug, Display};
use subtle_encoding::hex;
Expand Down Expand Up @@ -87,7 +87,7 @@ pub struct Uuid(pub [u8; CARDID_SIZE]);

impl Uuid {
/// Generate a random Cardholder Unique Identifier (CHUID) UUID
pub fn generate() -> Result<Self, Error> {
pub fn generate() -> Result<Self> {
let mut id = [0u8; CARDID_SIZE];
getrandom(&mut id).map_err(|_| Error::RandomnessError)?;
Ok(Self(id))
Expand All @@ -100,22 +100,22 @@ pub struct ChuId(pub [u8; CHUID_SIZE]);

impl ChuId {
/// Return FASC-N component of CHUID
pub fn fascn(&self) -> Result<[u8; FASCN_SIZE], Error> {
pub fn fascn(&self) -> Result<[u8; FASCN_SIZE]> {
let mut fascn = [0u8; FASCN_SIZE];
fascn.copy_from_slice(&self.0[CHUID_FASCN_OFFS..(CHUID_FASCN_OFFS + FASCN_SIZE)]);
Ok(fascn)
}

/// Return Card UUID/GUID component of CHUID
pub fn uuid(&self) -> Result<[u8; CARDID_SIZE], Error> {
pub fn uuid(&self) -> Result<[u8; CARDID_SIZE]> {
let mut uuid = [0u8; CARDID_SIZE];
uuid.copy_from_slice(&self.0[CHUID_GUID_OFFS..(CHUID_GUID_OFFS + CARDID_SIZE)]);
Ok(uuid)
}

/// Return expiration date component of CHUID
// TODO(tarcieri): parse expiration?
pub fn expiration(&self) -> Result<[u8; EXPIRATION_SIZE], Error> {
pub fn expiration(&self) -> Result<[u8; EXPIRATION_SIZE]> {
let mut expiration = [0u8; EXPIRATION_SIZE];
expiration.copy_from_slice(
&self.0[CHUID_EXPIRATION_OFFS..(CHUID_EXPIRATION_OFFS + EXPIRATION_SIZE)],
Expand All @@ -124,7 +124,7 @@ impl ChuId {
}

/// Get Cardholder Unique Identifier (CHUID)
pub fn get(yubikey: &mut YubiKey) -> Result<ChuId, Error> {
pub fn get(yubikey: &mut YubiKey) -> Result<ChuId> {
let txn = yubikey.begin_transaction()?;
let response = txn.fetch_object(OBJ_CHUID)?;

Expand All @@ -140,7 +140,7 @@ impl ChuId {

/// Set Cardholder Unique Identifier (CHUID)
#[cfg(feature = "untested")]
pub fn set(&self, yubikey: &mut YubiKey) -> Result<(), Error> {
pub fn set(&self, yubikey: &mut YubiKey) -> Result<()> {
let mut buf = CHUID_TMPL.to_vec();
buf[0..self.0.len()].copy_from_slice(&self.0);

Expand Down
5 changes: 2 additions & 3 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,10 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use crate::{
error::Error,
metadata::{AdminData, ProtectedData},
mgm::{MgmType, ADMIN_FLAGS_1_PROTECTED_MGM},
yubikey::{YubiKey, ADMIN_FLAGS_1_PUK_BLOCKED},
TAG_ADMIN_FLAGS_1, TAG_ADMIN_SALT, TAG_ADMIN_TIMESTAMP, TAG_PROTECTED_FLAGS_1,
Result, TAG_ADMIN_FLAGS_1, TAG_ADMIN_SALT, TAG_ADMIN_TIMESTAMP, TAG_PROTECTED_FLAGS_1,
TAG_PROTECTED_MGM,
};
use log::error;
Expand Down Expand Up @@ -68,7 +67,7 @@ pub struct Config {

impl Config {
/// Get YubiKey config
pub fn get(yubikey: &mut YubiKey) -> Result<Config, Error> {
pub fn get(yubikey: &mut YubiKey) -> Result<Config> {
let mut config = Config {
protected_data_available: false,
puk_blocked: false,
Expand Down
Loading

0 comments on commit de51b0c

Please sign in to comment.