Skip to content
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

Allow trait-based dynamic crypto implementations #36

Merged
merged 2 commits into from
Aug 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ece"
version = "1.0.1"
version = "1.1.0"
authors = ["Edouard Oger <eoger@fastmail.com>", "JR Conlin <jrconlin@gmail.com>"]
license = "MPL-2.0"
edition = "2018"
Expand All @@ -15,6 +15,7 @@ failure_derive = "0.1"
base64 = "0.10"
hkdf = { version = "0.7", optional = true }
lazy_static = { version = "1.2", optional = true }
once_cell = "0.2.6"
openssl = { version = "0.10", optional = true }
serde = { version = "1.0.91", features = ["derive"], optional = true }
sha2 = { version = "0.8", optional = true }
Expand Down
54 changes: 24 additions & 30 deletions src/aes128gcm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use crate::{
common::*,
crypto_backend::{Crypto, LocalKeyPair, RemotePublicKey},
crypto::{self, LocalKeyPair, RemotePublicKey},
error::*,
};
use byteorder::{BigEndian, ByteOrder};
Expand All @@ -26,27 +26,20 @@ const ECE_AES128GCM_NONCE_INFO: &str = "Content-Encoding: nonce\0";
// TODO: When done, remove the aes128gcm prefixes and the EC_ ones.
// As for now it makes it easier to Ctrl + F into ecec :)

pub struct Aes128GcmEceWebPush<C>
where
C: Crypto,
{
_marker: ::std::marker::PhantomData<C>,
}
impl<C> Aes128GcmEceWebPush<C>
where
C: Crypto,
{
pub struct Aes128GcmEceWebPush;
impl Aes128GcmEceWebPush {
/// Encrypts a Web Push message using the "aes128gcm" scheme. This function
/// automatically generates an ephemeral ECDH key pair.
pub fn encrypt(
remote_pub_key: &C::RemotePublicKey,
remote_pub_key: &dyn RemotePublicKey,
auth_secret: &[u8],
plaintext: &[u8],
params: WebPushParams,
) -> Result<Vec<u8>> {
let local_prv_key = C::generate_ephemeral_keypair()?;
let cryptographer = crypto::holder::get_cryptographer();
let local_prv_key = cryptographer.generate_ephemeral_keypair()?;
Self::encrypt_with_keys(
&local_prv_key,
&*local_prv_key,
remote_pub_key,
auth_secret,
plaintext,
Expand All @@ -57,17 +50,18 @@ where
/// Encrypts a Web Push message using the "aes128gcm" scheme, with an explicit
/// sender key. The sender key can be reused.
pub fn encrypt_with_keys(
local_prv_key: &C::LocalKeyPair,
remote_pub_key: &C::RemotePublicKey,
local_prv_key: &dyn LocalKeyPair,
remote_pub_key: &dyn RemotePublicKey,
auth_secret: &[u8],
plaintext: &[u8],
params: WebPushParams,
) -> Result<Vec<u8>> {
let cryptographer = crypto::holder::get_cryptographer();
let salt = match params.salt {
Some(salt) => salt,
None => {
let mut salt = [0u8; ECE_SALT_LENGTH];
C::random(&mut salt)?;
cryptographer.random_bytes(&mut salt)?;
salt.to_vec()
}
};
Expand Down Expand Up @@ -96,7 +90,7 @@ where

/// Decrypts a Web Push message encrypted using the "aes128gcm" scheme.
pub fn decrypt(
local_prv_key: &C::LocalKeyPair,
local_prv_key: &dyn LocalKeyPair,
auth_secret: &[u8],
payload: &[u8],
) -> Result<Vec<u8>> {
Expand Down Expand Up @@ -126,15 +120,13 @@ where
return Err(ErrorKind::ZeroCiphertext.into());
}
let ciphertext = &payload[ciphertext_start..];
let key = C::RemotePublicKey::from_raw(key_id)?;
Self::common_decrypt(local_prv_key, &key, auth_secret, salt, rs, ciphertext)
let cryptographer = crypto::holder::get_cryptographer();
let key = cryptographer.import_public_key(key_id)?;
Self::common_decrypt(local_prv_key, &*key, auth_secret, salt, rs, ciphertext)
}
}

impl<C> EceWebPush<C> for Aes128GcmEceWebPush<C>
where
C: Crypto,
{
impl EceWebPush for Aes128GcmEceWebPush {
/// Always returns false because "aes128gcm" uses
/// a padding scheme that doesn't need a trailer.
fn needs_trailer(_: u32, _: usize) -> bool {
Expand Down Expand Up @@ -174,12 +166,13 @@ where
/// key, sender public key, authentication secret, and sender salt.
fn derive_key_and_nonce(
ece_mode: EceMode,
local_prv_key: &C::LocalKeyPair,
remote_pub_key: &C::RemotePublicKey,
local_prv_key: &dyn LocalKeyPair,
remote_pub_key: &dyn RemotePublicKey,
auth_secret: &[u8],
salt: &[u8],
) -> Result<KeyAndNonce> {
let shared_secret = C::compute_ecdh_secret(remote_pub_key, local_prv_key)?;
let cryptographer = crypto::holder::get_cryptographer();
let shared_secret = cryptographer.compute_ecdh_secret(remote_pub_key, local_prv_key)?;
let raw_remote_pub_key = remote_pub_key.as_raw()?;
let raw_local_pub_key = local_prv_key.pub_as_raw()?;

Expand All @@ -189,19 +182,20 @@ where
EceMode::ENCRYPT => generate_info(&raw_remote_pub_key, &raw_local_pub_key),
EceMode::DECRYPT => generate_info(&raw_local_pub_key, &raw_remote_pub_key),
}?;
let ikm = C::hkdf_sha256(
let cryptographer = crypto::holder::get_cryptographer();
let ikm = cryptographer.hkdf_sha256(
auth_secret,
&shared_secret,
&ikm_info,
ECE_WEBPUSH_IKM_LENGTH,
)?;
let key = C::hkdf_sha256(
let key = cryptographer.hkdf_sha256(
salt,
&ikm,
ECE_AES128GCM_KEY_INFO.as_bytes(),
ECE_AES_KEY_LENGTH,
)?;
let nonce = C::hkdf_sha256(
let nonce = cryptographer.hkdf_sha256(
salt,
&ikm,
ECE_AES128GCM_NONCE_INFO.as_bytes(),
Expand Down
53 changes: 23 additions & 30 deletions src/aesgcm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

use crate::{
common::*,
crypto_backend::{Crypto, LocalKeyPair, RemotePublicKey},
crypto::{self, LocalKeyPair, RemotePublicKey},
error::*,
};
use std::collections::HashMap;
Expand Down Expand Up @@ -88,27 +88,20 @@ impl AesGcmEncryptedBlock {
}
}

pub struct AesGcmEceWebPush<C>
where
C: Crypto,
{
_marker: ::std::marker::PhantomData<C>,
}
impl<C> AesGcmEceWebPush<C>
where
C: Crypto,
{
pub struct AesGcmEceWebPush;
impl AesGcmEceWebPush {
/// Encrypts a Web Push message using the "aesgcm" scheme. This function
/// automatically generates an ephemeral ECDH key pair.
pub fn encrypt(
remote_pub_key: &C::RemotePublicKey,
remote_pub_key: &dyn RemotePublicKey,
auth_secret: &[u8],
plaintext: &[u8],
params: WebPushParams,
) -> Result<AesGcmEncryptedBlock> {
let local_prv_key = C::generate_ephemeral_keypair()?;
let cryptographer = crypto::holder::get_cryptographer();
let local_prv_key = cryptographer.generate_ephemeral_keypair()?;
Self::encrypt_with_keys(
&local_prv_key,
&*local_prv_key,
remote_pub_key,
auth_secret,
plaintext,
Expand All @@ -119,15 +112,16 @@ where
/// Encrypts a Web Push message using the "aesgcm" scheme, with an explicit
/// sender key. The sender key can be reused.
pub fn encrypt_with_keys(
local_prv_key: &C::LocalKeyPair,
remote_pub_key: &C::RemotePublicKey,
local_prv_key: &dyn LocalKeyPair,
remote_pub_key: &dyn RemotePublicKey,
auth_secret: &[u8],
plaintext: &[u8],
params: WebPushParams,
) -> Result<AesGcmEncryptedBlock> {
let cryptographer = crypto::holder::get_cryptographer();
let salt = {
let mut salt = [0u8; ECE_SALT_LENGTH];
C::random(&mut salt)?;
cryptographer.random_bytes(&mut salt)?;
salt.to_vec()
};
let raw_local_pub_key = local_prv_key.pub_as_raw()?;
Expand All @@ -150,14 +144,15 @@ where

/// Decrypts a Web Push message encrypted using the "aesgcm" scheme.
pub fn decrypt(
local_prv_key: &C::LocalKeyPair,
local_prv_key: &dyn LocalKeyPair,
auth_secret: &[u8],
block: &AesGcmEncryptedBlock,
) -> Result<Vec<u8>> {
let sender_key = C::RemotePublicKey::from_raw(&block.dh)?;
let cryptographer = crypto::holder::get_cryptographer();
let sender_key = cryptographer.import_public_key(&block.dh)?;
Self::common_decrypt(
local_prv_key,
&sender_key,
&*sender_key,
auth_secret,
&block.salt,
block.rs,
Expand All @@ -166,10 +161,7 @@ where
}
}

impl<C> EceWebPush<C> for AesGcmEceWebPush<C>
where
C: Crypto,
{
impl EceWebPush for AesGcmEceWebPush {
fn needs_trailer(rs: u32, ciphertextlen: usize) -> bool {
ciphertextlen as u32 % rs == 0
}
Expand Down Expand Up @@ -197,12 +189,13 @@ where
/// key, sender public key, authentication secret, and sender salt.
fn derive_key_and_nonce(
ece_mode: EceMode,
local_prv_key: &C::LocalKeyPair,
remote_pub_key: &C::RemotePublicKey,
local_prv_key: &dyn LocalKeyPair,
remote_pub_key: &dyn RemotePublicKey,
auth_secret: &[u8],
salt: &[u8],
) -> Result<KeyAndNonce> {
let shared_secret = C::compute_ecdh_secret(remote_pub_key, local_prv_key)?;
let cryptographer = crypto::holder::get_cryptographer();
let shared_secret = cryptographer.compute_ecdh_secret(remote_pub_key, local_prv_key)?;
let raw_remote_pub_key = remote_pub_key.as_raw()?;
let raw_local_pub_key = local_prv_key.pub_as_raw()?;

Expand All @@ -212,14 +205,14 @@ where
}?;
let keyinfo = generate_info("aesgcm", &keypair)?;
let nonceinfo = generate_info("nonce", &keypair)?;
let ikm = C::hkdf_sha256(
let ikm = cryptographer.hkdf_sha256(
auth_secret,
&shared_secret,
&ECE_WEBPUSH_AESGCM_AUTHINFO.as_bytes(),
ECE_WEBPUSH_IKM_LENGTH,
)?;
let key = C::hkdf_sha256(salt, &ikm, &keyinfo, ECE_AES_KEY_LENGTH)?;
let nonce = C::hkdf_sha256(salt, &ikm, &nonceinfo, ECE_NONCE_LENGTH)?;
let key = cryptographer.hkdf_sha256(salt, &ikm, &keyinfo, ECE_AES_KEY_LENGTH)?;
let nonce = cryptographer.hkdf_sha256(salt, &ikm, &nonceinfo, ECE_NONCE_LENGTH)?;
Ok((key, nonce))
}
}
Expand Down
31 changes: 15 additions & 16 deletions src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use crate::{crypto_backend::Crypto, error::*};
use crate::{
crypto::{self, LocalKeyPair, RemotePublicKey},
error::*,
};
use byteorder::{BigEndian, ByteOrder};
use std::cmp::min;

Expand Down Expand Up @@ -53,13 +56,10 @@ pub enum EceMode {

pub type KeyAndNonce = (Vec<u8>, Vec<u8>);

pub trait EceWebPush<C>
where
C: Crypto,
{
pub trait EceWebPush {
fn common_encrypt(
local_prv_key: &C::LocalKeyPair,
remote_pub_key: &C::RemotePublicKey,
local_prv_key: &dyn LocalKeyPair,
remote_pub_key: &dyn RemotePublicKey,
auth_secret: &[u8],
salt: &[u8],
rs: u32,
Expand Down Expand Up @@ -145,7 +145,8 @@ where
block_pad_len,
last_record,
)?;
let mut record = C::aes_gcm_128_encrypt(&key, &iv, &block, ECE_TAG_LENGTH)?;
let cryptographer = crypto::holder::get_cryptographer();
let mut record = cryptographer.aes_gcm_128_encrypt(&key, &iv, &block)?;
ciphertext.append(&mut record);
plaintext_start = plaintext_end;
counter += 1;
Expand All @@ -154,8 +155,8 @@ where
}

fn common_decrypt(
local_prv_key: &C::LocalKeyPair,
remote_pub_key: &C::RemotePublicKey,
local_prv_key: &dyn LocalKeyPair,
remote_pub_key: &dyn RemotePublicKey,
auth_secret: &[u8],
salt: &[u8],
rs: u32,
Expand Down Expand Up @@ -191,10 +192,8 @@ where
}
let iv = generate_iv(&nonce, count);
assert!(record.len() > ECE_TAG_LENGTH);
let block_len = record.len() - ECE_TAG_LENGTH;
let data = &record[0..block_len];
let tag = &record[block_len..];
let plaintext = C::aes_gcm_128_decrypt(&key, &iv, data, tag)?;
let cryptographer = crypto::holder::get_cryptographer();
let plaintext = cryptographer.aes_gcm_128_decrypt(&key, &iv, record)?;
let last_record = count == records_count - 1;
if plaintext.len() < Self::pad_size() {
return Err(ErrorKind::BlockTooShort.into());
Expand All @@ -215,8 +214,8 @@ where
fn unpad(block: &[u8], last_record: bool) -> Result<&[u8]>;
fn derive_key_and_nonce(
ece_mode: EceMode,
local_prv_key: &C::LocalKeyPair,
remote_pub_key: &C::RemotePublicKey,
local_prv_key: &dyn LocalKeyPair,
remote_pub_key: &dyn RemotePublicKey,
auth_secret: &[u8],
salt: &[u8],
) -> Result<KeyAndNonce>;
Expand Down