-
Notifications
You must be signed in to change notification settings - Fork 323
Expose cryptography backends via CryptoProvider #452
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
Open
arckoor
wants to merge
3
commits into
Keats:master
Choose a base branch
from
arckoor:custom-provider
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+557
−257
Open
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 hidden or 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 hidden or 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 hidden or 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,138 @@ | ||
| use jsonwebtoken::{ | ||
| Algorithm, AlgorithmFamily, DecodingKey, EncodingKey, Header, Validation, | ||
| crypto::{CryptoProvider, JwkUtils, JwtSigner, JwtVerifier}, | ||
| decode, encode, | ||
| errors::{Error, ErrorKind}, | ||
| signature::{Error as SigError, Signer, Verifier}, | ||
| }; | ||
| use serde::{Deserialize, Serialize}; | ||
|
|
||
| fn new_signer(algorithm: &Algorithm, key: &EncodingKey) -> Result<Box<dyn JwtSigner>, Error> { | ||
| let jwt_signer = match algorithm { | ||
| Algorithm::EdDSA => Box::new(EdDSASigner::new(key)?) as Box<dyn JwtSigner>, | ||
| _ => unimplemented!(), | ||
| }; | ||
|
|
||
| Ok(jwt_signer) | ||
| } | ||
|
|
||
| fn new_verifier(algorithm: &Algorithm, key: &DecodingKey) -> Result<Box<dyn JwtVerifier>, Error> { | ||
| let jwt_verifier = match algorithm { | ||
| Algorithm::EdDSA => Box::new(EdDSAVerifier::new(key)?) as Box<dyn JwtVerifier>, | ||
| _ => unimplemented!(), | ||
| }; | ||
|
|
||
| Ok(jwt_verifier) | ||
| } | ||
|
|
||
| struct EdDSASigner(botan::Privkey); | ||
|
|
||
| impl EdDSASigner { | ||
| fn new(encoding_key: &EncodingKey) -> Result<Self, Error> { | ||
| if encoding_key.family() != AlgorithmFamily::Ed { | ||
| return Err(ErrorKind::InvalidKeyFormat.into()); | ||
| } | ||
|
|
||
| Ok(Self( | ||
| botan::Privkey::load_der(encoding_key.inner()) | ||
| .map_err(|_| ErrorKind::InvalidEddsaKey)?, | ||
| )) | ||
| } | ||
| } | ||
|
|
||
| impl Signer<Vec<u8>> for EdDSASigner { | ||
| fn try_sign(&self, msg: &[u8]) -> std::result::Result<Vec<u8>, SigError> { | ||
| let mut rng = botan::RandomNumberGenerator::new_system().map_err(SigError::from_source)?; | ||
| let mut signer = botan::Signer::new(&self.0, "Pure").map_err(SigError::from_source)?; | ||
| signer.update(msg).map_err(SigError::from_source)?; | ||
| signer.finish(&mut rng).map_err(SigError::from_source) | ||
| } | ||
| } | ||
|
|
||
| impl JwtSigner for EdDSASigner { | ||
| fn algorithm(&self) -> Algorithm { | ||
| Algorithm::EdDSA | ||
| } | ||
| } | ||
|
|
||
| struct EdDSAVerifier(botan::Pubkey); | ||
|
|
||
| impl EdDSAVerifier { | ||
| fn new(decoding_key: &DecodingKey) -> Result<Self, Error> { | ||
| if decoding_key.family() != AlgorithmFamily::Ed { | ||
| return Err(ErrorKind::InvalidKeyFormat.into()); | ||
| } | ||
|
|
||
| Ok(Self( | ||
| botan::Pubkey::load_ed25519(decoding_key.as_bytes()) | ||
| .map_err(|_| ErrorKind::InvalidEddsaKey)?, | ||
| )) | ||
| } | ||
| } | ||
|
|
||
| impl Verifier<Vec<u8>> for EdDSAVerifier { | ||
| fn verify(&self, msg: &[u8], signature: &Vec<u8>) -> std::result::Result<(), SigError> { | ||
| let mut verifier = botan::Verifier::new(&self.0, "Pure").map_err(SigError::from_source)?; | ||
| verifier.update(msg).map_err(SigError::from_source)?; | ||
| verifier | ||
| .finish(signature) | ||
| .map_err(SigError::from_source)? | ||
| .then_some(()) | ||
| .ok_or(SigError::new()) | ||
| } | ||
| } | ||
|
|
||
| impl JwtVerifier for EdDSAVerifier { | ||
| fn algorithm(&self) -> Algorithm { | ||
| Algorithm::EdDSA | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] | ||
| pub struct Claims { | ||
| sub: String, | ||
| exp: u64, | ||
| } | ||
|
|
||
| fn main() { | ||
| // create and install our custom provider | ||
| let my_crypto_provider = CryptoProvider { | ||
| signer_factory: new_signer, | ||
| verifier_factory: new_verifier, | ||
| // the default impl uses dummy functions that panic, but we don't need them here | ||
| jwk_utils: JwkUtils::default(), | ||
| }; | ||
| my_crypto_provider.install_default().unwrap(); | ||
|
|
||
| // generate a new key | ||
| let (privkey, pubkey) = { | ||
| let key = botan::Privkey::create( | ||
| "Ed25519", | ||
| "", | ||
| &mut botan::RandomNumberGenerator::new_system().unwrap(), | ||
| ) | ||
| .unwrap(); | ||
| (key.pem_encode().unwrap(), key.pubkey().unwrap().pem_encode().unwrap()) | ||
| }; | ||
| let my_claims = Claims { sub: "me".to_owned(), exp: 10000000000 }; | ||
|
|
||
| // our crypto provider only supports EdDSA | ||
| let header = Header::new(Algorithm::EdDSA); | ||
|
|
||
| let token = | ||
| match encode(&header, &my_claims, &EncodingKey::from_ed_pem(privkey.as_bytes()).unwrap()) { | ||
| Ok(t) => t, | ||
| Err(_) => panic!(), // in practice you would return an error | ||
| }; | ||
|
|
||
| let claims = match decode::<Claims>( | ||
| token, | ||
| &DecodingKey::from_ed_pem(pubkey.as_bytes()).unwrap(), | ||
| &Validation::new(Algorithm::EdDSA), | ||
| ) { | ||
| Ok(c) => c.claims, | ||
| Err(_) => panic!(), | ||
| }; | ||
|
|
||
| assert_eq!(my_claims, claims); | ||
| } | ||
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
| @@ -1,4 +1,61 @@ | ||
| pub(crate) mod ecdsa; | ||
| pub(crate) mod eddsa; | ||
| pub(crate) mod hmac; | ||
| pub(crate) mod rsa; | ||
| use aws_lc_rs::{ | ||
| digest, | ||
| signature::{self as aws_sig, KeyPair}, | ||
| }; | ||
|
|
||
| use crate::{ | ||
| Algorithm, DecodingKey, EncodingKey, | ||
| crypto::{CryptoProvider, JwkUtils, JwtSigner, JwtVerifier}, | ||
| errors::{self, Error, ErrorKind}, | ||
| jwk::{EllipticCurve, ThumbprintHash}, | ||
| }; | ||
|
|
||
| mod ecdsa; | ||
| mod eddsa; | ||
| mod hmac; | ||
| mod rsa; | ||
|
|
||
| fn extract_rsa_public_key_components(key_content: &[u8]) -> errors::Result<(Vec<u8>, Vec<u8>)> { | ||
| let key_pair = aws_sig::RsaKeyPair::from_der(key_content) | ||
| .map_err(|e| ErrorKind::InvalidRsaKey(e.to_string()))?; | ||
| let public = key_pair.public_key(); | ||
| let components = aws_sig::RsaPublicKeyComponents::<Vec<u8>>::from(public); | ||
| Ok((components.n, components.e)) | ||
| } | ||
|
|
||
| fn extract_ec_public_key_coordinates( | ||
| key_content: &[u8], | ||
| alg: Algorithm, | ||
| ) -> errors::Result<(EllipticCurve, Vec<u8>, Vec<u8>)> { | ||
| use aws_lc_rs::signature::{ | ||
| ECDSA_P256_SHA256_FIXED_SIGNING, ECDSA_P384_SHA384_FIXED_SIGNING, EcdsaKeyPair, | ||
| }; | ||
|
|
||
| let (signing_alg, curve, pub_elem_bytes) = match alg { | ||
| Algorithm::ES256 => (&ECDSA_P256_SHA256_FIXED_SIGNING, EllipticCurve::P256, 32), | ||
| Algorithm::ES384 => (&ECDSA_P384_SHA384_FIXED_SIGNING, EllipticCurve::P384, 48), | ||
| _ => return Err(ErrorKind::InvalidEcdsaKey.into()), | ||
| }; | ||
|
|
||
| let key_pair = EcdsaKeyPair::from_pkcs8(signing_alg, key_content) | ||
| .map_err(|_| ErrorKind::InvalidEcdsaKey)?; | ||
|
|
||
| let pub_bytes = key_pair.public_key().as_ref(); | ||
| if pub_bytes[0] != 4 { | ||
| return Err(ErrorKind::InvalidEcdsaKey.into()); | ||
| } | ||
|
|
||
| let (x, y) = pub_bytes[1..].split_at(pub_elem_bytes); | ||
| Ok((curve, x.to_vec(), y.to_vec())) | ||
| } | ||
|
|
||
| fn compute_digest(data: &[u8], hash_function: ThumbprintHash) -> Vec<u8> { | ||
| let algorithm = match hash_function { | ||
| ThumbprintHash::SHA256 => &digest::SHA256, | ||
| ThumbprintHash::SHA384 => &digest::SHA384, | ||
| ThumbprintHash::SHA512 => &digest::SHA512, | ||
| }; | ||
| digest::digest(algorithm, data).as_ref().to_vec() | ||
| } | ||
|
|
||
| define_default_provider!("aws_lc_rs", "https://github.com/aws/aws-lc-rs"); |
This file contains hidden or 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 hidden or 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,90 @@ | ||
| #[cfg(any(feature = "rust_crypto", feature = "aws_lc_rs"))] | ||
| macro_rules! define_default_provider { | ||
| ($name:literal, $link:literal) => { | ||
| #[doc = "The default [`CryptoProvider`] backed by [`"] | ||
| #[doc = $name] | ||
| #[doc = "`]"] | ||
| #[doc = concat!("The default [`CryptoProvider`] backed by [`", $name, "`]")] | ||
| #[doc = ""] | ||
| #[doc = concat!("[`", $name, "`]: ", $link)] | ||
| pub const DEFAULT_PROVIDER: CryptoProvider = CryptoProvider { | ||
| signer_factory: new_signer, | ||
| verifier_factory: new_verifier, | ||
| jwk_utils: JwkUtils { | ||
| extract_rsa_public_key_components, | ||
| extract_ec_public_key_coordinates, | ||
| compute_digest, | ||
| }, | ||
| }; | ||
|
|
||
| #[doc = "Create a new [`JwtSigner`] for a given [`Algorithm`]."] | ||
| pub fn new_signer( | ||
| algorithm: &Algorithm, | ||
| key: &EncodingKey, | ||
| ) -> Result<Box<dyn JwtSigner>, Error> { | ||
| let jwt_signer = match algorithm { | ||
| Algorithm::HS256 => Box::new(hmac::Hs256Signer::new(key)?) as Box<dyn JwtSigner>, | ||
| Algorithm::HS384 => Box::new(hmac::Hs384Signer::new(key)?) as Box<dyn JwtSigner>, | ||
| Algorithm::HS512 => Box::new(hmac::Hs512Signer::new(key)?) as Box<dyn JwtSigner>, | ||
| Algorithm::ES256 => Box::new(ecdsa::Es256Signer::new(key)?) as Box<dyn JwtSigner>, | ||
| Algorithm::ES384 => Box::new(ecdsa::Es384Signer::new(key)?) as Box<dyn JwtSigner>, | ||
| Algorithm::RS256 => Box::new(rsa::Rsa256Signer::new(key)?) as Box<dyn JwtSigner>, | ||
| Algorithm::RS384 => Box::new(rsa::Rsa384Signer::new(key)?) as Box<dyn JwtSigner>, | ||
| Algorithm::RS512 => Box::new(rsa::Rsa512Signer::new(key)?) as Box<dyn JwtSigner>, | ||
| Algorithm::PS256 => Box::new(rsa::RsaPss256Signer::new(key)?) as Box<dyn JwtSigner>, | ||
| Algorithm::PS384 => Box::new(rsa::RsaPss384Signer::new(key)?) as Box<dyn JwtSigner>, | ||
| Algorithm::PS512 => Box::new(rsa::RsaPss512Signer::new(key)?) as Box<dyn JwtSigner>, | ||
| Algorithm::EdDSA => Box::new(eddsa::EdDSASigner::new(key)?) as Box<dyn JwtSigner>, | ||
| }; | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. that will get more complex if we start supporting some alg in some backend like #461 |
||
|
|
||
| Ok(jwt_signer) | ||
| } | ||
|
|
||
| #[doc = "Create a new [`JwtVerifier`] for a given [`Algorithm`]."] | ||
| pub fn new_verifier( | ||
| algorithm: &Algorithm, | ||
| key: &DecodingKey, | ||
| ) -> Result<Box<dyn super::JwtVerifier>, Error> { | ||
| let jwt_encoder = match algorithm { | ||
| Algorithm::HS256 => { | ||
| Box::new(hmac::Hs256Verifier::new(key)?) as Box<dyn JwtVerifier> | ||
| } | ||
| Algorithm::HS384 => { | ||
| Box::new(hmac::Hs384Verifier::new(key)?) as Box<dyn JwtVerifier> | ||
| } | ||
| Algorithm::HS512 => { | ||
| Box::new(hmac::Hs512Verifier::new(key)?) as Box<dyn JwtVerifier> | ||
| } | ||
| Algorithm::ES256 => { | ||
| Box::new(ecdsa::Es256Verifier::new(key)?) as Box<dyn JwtVerifier> | ||
| } | ||
| Algorithm::ES384 => { | ||
| Box::new(ecdsa::Es384Verifier::new(key)?) as Box<dyn JwtVerifier> | ||
| } | ||
| Algorithm::RS256 => { | ||
| Box::new(rsa::Rsa256Verifier::new(key)?) as Box<dyn JwtVerifier> | ||
| } | ||
| Algorithm::RS384 => { | ||
| Box::new(rsa::Rsa384Verifier::new(key)?) as Box<dyn JwtVerifier> | ||
| } | ||
| Algorithm::RS512 => { | ||
| Box::new(rsa::Rsa512Verifier::new(key)?) as Box<dyn JwtVerifier> | ||
| } | ||
| Algorithm::PS256 => { | ||
| Box::new(rsa::RsaPss256Verifier::new(key)?) as Box<dyn JwtVerifier> | ||
| } | ||
| Algorithm::PS384 => { | ||
| Box::new(rsa::RsaPss384Verifier::new(key)?) as Box<dyn JwtVerifier> | ||
| } | ||
| Algorithm::PS512 => { | ||
| Box::new(rsa::RsaPss512Verifier::new(key)?) as Box<dyn JwtVerifier> | ||
| } | ||
| Algorithm::EdDSA => { | ||
| Box::new(eddsa::EdDSAVerifier::new(key)?) as Box<dyn JwtVerifier> | ||
| } | ||
| }; | ||
|
|
||
| Ok(jwt_encoder) | ||
| } | ||
| }; | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.