-
Notifications
You must be signed in to change notification settings - Fork 20
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Abstract signing cryptography #21
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
//! (Signing) cryptography abstraction | ||
|
||
use openssl::{hash::MessageDigest, nid::Nid}; | ||
|
||
use crate::{error::CoseError, sign::SignatureAlgorithm}; | ||
|
||
#[cfg(feature = "key_openssl_pkey")] | ||
mod openssl_pkey; | ||
|
||
/// A public key that can verify an existing signature | ||
pub trait SigningPublicKey { | ||
/// This returns the signature algorithm and message digest to be used for this | ||
/// public key. | ||
fn get_parameters(&self) -> Result<(SignatureAlgorithm, MessageDigest), CoseError>; | ||
|
||
/// Given a digest and a signature, returns a boolean whether the signature | ||
/// was valid. | ||
fn verify(&self, digest: &[u8], signature: &[u8]) -> Result<bool, CoseError>; | ||
} | ||
|
||
/// Follows the recommandations put in place by the RFC and doesn't deal with potential | ||
/// mismatches: https://tools.ietf.org/html/rfc8152#section-8.1. | ||
pub fn ec_curve_to_parameters( | ||
curve_name: Nid, | ||
) -> Result<(SignatureAlgorithm, MessageDigest, usize), CoseError> { | ||
let sig_alg = match curve_name { | ||
// Recommended to use with SHA256 | ||
Nid::X9_62_PRIME256V1 => SignatureAlgorithm::ES256, | ||
// Recommended to use with SHA384 | ||
Nid::SECP384R1 => SignatureAlgorithm::ES384, | ||
// Recommended to use with SHA512 | ||
Nid::SECP521R1 => SignatureAlgorithm::ES512, | ||
_ => { | ||
return Err(CoseError::UnsupportedError(format!( | ||
"Curve name {:?} is not supported", | ||
curve_name | ||
))) | ||
} | ||
}; | ||
|
||
Ok(( | ||
sig_alg, | ||
sig_alg.suggested_message_digest(), | ||
sig_alg.key_length(), | ||
)) | ||
} | ||
|
||
/// A private key that can produce new signatures | ||
pub trait SigningPrivateKey: SigningPublicKey { | ||
/// Given a digest, returns a signature | ||
fn sign(&self, digest: &[u8]) -> Result<Vec<u8>, CoseError>; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
//! OpenSSL PKey(Ref) implementation for cryptography | ||
|
||
use openssl::{ | ||
bn::BigNum, | ||
ecdsa::EcdsaSig, | ||
hash::MessageDigest, | ||
pkey::{HasPrivate, HasPublic, PKey, PKeyRef}, | ||
}; | ||
|
||
use crate::{ | ||
crypto::{ec_curve_to_parameters, SigningPrivateKey, SigningPublicKey}, | ||
error::CoseError, | ||
sign::SignatureAlgorithm, | ||
}; | ||
|
||
impl<T> SigningPublicKey for PKey<T> | ||
where | ||
T: HasPublic, | ||
{ | ||
fn get_parameters(&self) -> Result<(SignatureAlgorithm, MessageDigest), CoseError> { | ||
self.as_ref().get_parameters() | ||
} | ||
|
||
fn verify(&self, digest: &[u8], signature: &[u8]) -> Result<bool, CoseError> { | ||
self.as_ref().verify(digest, signature) | ||
} | ||
} | ||
|
||
impl<T> SigningPublicKey for PKeyRef<T> | ||
where | ||
T: HasPublic, | ||
{ | ||
fn get_parameters(&self) -> Result<(SignatureAlgorithm, MessageDigest), CoseError> { | ||
let curve_name = self | ||
.ec_key() | ||
.map_err(|_| CoseError::UnsupportedError("Non-EC keys are not supported".to_string()))? | ||
.group() | ||
.curve_name() | ||
.ok_or_else(|| { | ||
CoseError::UnsupportedError("Anonymous EC keys are not supported".to_string()) | ||
})?; | ||
|
||
let curve_parameters = ec_curve_to_parameters(curve_name)?; | ||
|
||
Ok((curve_parameters.0, curve_parameters.1)) | ||
} | ||
|
||
fn verify(&self, digest: &[u8], signature: &[u8]) -> Result<bool, CoseError> { | ||
let key = self.ec_key().map_err(|_| { | ||
CoseError::UnsupportedError("Non-EC keys are not yet supported".to_string()) | ||
})?; | ||
|
||
let curve_name = key.group().curve_name().ok_or_else(|| { | ||
CoseError::UnsupportedError("Anonymous EC keys are not supported".to_string()) | ||
})?; | ||
|
||
let (_, _, key_length) = ec_curve_to_parameters(curve_name)?; | ||
|
||
// Recover the R and S factors from the signature contained in the object | ||
let (bytes_r, bytes_s) = signature.split_at(key_length); | ||
|
||
let r = BigNum::from_slice(bytes_r).map_err(CoseError::SignatureError)?; | ||
let s = BigNum::from_slice(bytes_s).map_err(CoseError::SignatureError)?; | ||
|
||
let sig = EcdsaSig::from_private_components(r, s).map_err(CoseError::SignatureError)?; | ||
sig.verify(digest, &key).map_err(CoseError::SignatureError) | ||
} | ||
} | ||
|
||
impl<T> SigningPrivateKey for PKey<T> | ||
where | ||
T: HasPrivate, | ||
{ | ||
fn sign(&self, digest: &[u8]) -> Result<Vec<u8>, CoseError> { | ||
self.as_ref().sign(digest) | ||
} | ||
} | ||
|
||
impl<T> SigningPrivateKey for PKeyRef<T> | ||
where | ||
T: HasPrivate, | ||
{ | ||
fn sign(&self, digest: &[u8]) -> Result<Vec<u8>, CoseError> { | ||
let key = self.ec_key().map_err(|_| { | ||
CoseError::UnsupportedError("Non-EC keys are not yet supported".to_string()) | ||
})?; | ||
|
||
let curve_name = key.group().curve_name().ok_or_else(|| { | ||
CoseError::UnsupportedError("Anonymous EC keys are not supported".to_string()) | ||
})?; | ||
|
||
let (_, _, key_length) = ec_curve_to_parameters(curve_name)?; | ||
|
||
// The spec defines the signature as: | ||
// Signature = I2OSP(R, n) | I2OSP(S, n), where n = ceiling(key_length / 8) | ||
// The Signer interface doesn't provide this, so this will use EcdsaSig interface instead | ||
// and concatenate R and S. | ||
// See https://tools.ietf.org/html/rfc8017#section-4.1 for details. | ||
let signature = EcdsaSig::sign(digest, &key).map_err(CoseError::SignatureError)?; | ||
let bytes_r = signature.r().to_vec(); | ||
let bytes_s = signature.s().to_vec(); | ||
|
||
// These should *never* exceed ceiling(key_length / 8) | ||
assert!(bytes_r.len() <= key_length); | ||
assert!(bytes_s.len() <= key_length); | ||
|
||
let mut signature_bytes = vec![0u8; key_length * 2]; | ||
|
||
// This is big-endian encoding so padding might be added at the start if the factor is | ||
// too short. | ||
let offset_copy = key_length - bytes_r.len(); | ||
signature_bytes[offset_copy..offset_copy + bytes_r.len()].copy_from_slice(&bytes_r); | ||
|
||
// This is big-endian encoding so padding might be added at the start if the factor is | ||
// too short. | ||
let offset_copy = key_length - bytes_s.len() + key_length; | ||
signature_bytes[offset_copy..offset_copy + bytes_s.len()].copy_from_slice(&bytes_s); | ||
|
||
Ok(signature_bytes) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you make openssl an optional dependency?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this would make more sense when we add a secondary crypto provider such as ring.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The traits as proposed in this PR can immediately be implemented by external crates, so I don't see why the OpenSSL dependency should be required.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So,
openssl
itself is still needed for encryption (which I did not abstract in this PR), and we still use it for things like computing digests before passing them to the crypto layer.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have submitted #28, which makes openssl a fully optional dependency (well, it is abstracted away, right now it's the only crypto implementation and you'll need one).