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

Experimental implementation of CTX #324

Merged
merged 17 commits into from
Mar 11, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ features = ["alloc"]
default = [ "safe_api" ]
safe_api = [ "getrandom", "ct-codecs" ]
alloc = []
experimental = []

[dev-dependencies]
hex = "0.4.0"
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ MSRV may be changed at any point and will not be considered a SemVer breaking ch
- `serde`: Requires either `alloc` or `default`/`safe_api`.
- `alloc`: Argon2i in `hazardous` when `default`/`safe_api` is not available.
- `no_std`: Implicit feature that represents no heap allocations. Enabled by disabling default features and not selecting any additional features.
- `experimental`: These APIs may contain breaking changes in any non SemVer-breaking crate releases.

More detailed explanation of the features in the [wiki](https://github.com/orion-rs/orion/wiki/Crate-features).

Expand Down
6 changes: 3 additions & 3 deletions src/hazardous/aead/chacha20poly1305.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,10 @@ use core::convert::TryInto;
use zeroize::Zeroizing;

/// The initial counter used for encryption and decryption.
const ENC_CTR: u32 = 1;
pub(crate) const ENC_CTR: u32 = 1;

/// The initial counter used for Poly1305 key generation.
const AUTH_CTR: u32 = 0;
pub(crate) const AUTH_CTR: u32 = 0;

/// The maximum size of the plaintext (see [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439#section-2.8)).
pub const P_MAX: u64 = (u32::MAX as u64) * 64;
Expand All @@ -147,7 +147,7 @@ pub(crate) fn poly1305_key_gen(
}

/// Authenticates the ciphertext, ad and their lengths.
fn process_authentication(
pub(crate) fn process_authentication(
auth_ctx: &mut Poly1305,
ad: &[u8],
ciphertext: &[u8],
Expand Down
165 changes: 165 additions & 0 deletions src/hazardous/cae/chacha20poly1305blake2b.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
// MIT License

// Copyright (c) 2023 The orion Developers

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use crate::errors::UnknownCryptoError;
use crate::hazardous::aead;
use crate::hazardous::aead::chacha20poly1305::{poly1305_key_gen, process_authentication, ENC_CTR};
use crate::hazardous::hash::blake2::blake2b::Blake2b;
use crate::hazardous::mac::poly1305::Poly1305;
use crate::hazardous::mac::poly1305::POLY1305_OUTSIZE;
use crate::hazardous::stream::chacha20::{self, ChaCha20, CHACHA_BLOCKSIZE};
use crate::util;
use zeroize::Zeroizing;

pub use crate::hazardous::aead::chacha20poly1305::A_MAX;
pub use crate::hazardous::aead::chacha20poly1305::P_MAX;
pub use crate::hazardous::stream::chacha20::{Nonce, SecretKey};

/// The size of the BLAKE2b authentication tag.
pub const TAG_SIZE: usize = 32;

/// The maximum size of the ciphertext.
pub const C_MAX: u64 = P_MAX + (TAG_SIZE as u64);

#[must_use = "SECURITY WARNING: Experimental feature."]
/// CTX ChaCha20Poly1305 with BLAKE2b-256.
pub fn seal(
brycx marked this conversation as resolved.
Show resolved Hide resolved
secret_key: &SecretKey,
nonce: &Nonce,
plaintext: &[u8],
ad: Option<&[u8]>,
dst_out: &mut [u8],
) -> Result<(), UnknownCryptoError> {
if u64::try_from(plaintext.len()).map_err(|_| UnknownCryptoError)? > P_MAX {
return Err(UnknownCryptoError);
}

let ad = ad.unwrap_or(&[0u8; 0]);
#[allow(clippy::absurd_extreme_comparisons)]
if u64::try_from(ad.len()).map_err(|_| UnknownCryptoError)? > A_MAX {
return Err(UnknownCryptoError);
}

debug_assert!(POLY1305_OUTSIZE < TAG_SIZE);
match plaintext.len().checked_add(TAG_SIZE) {
Some(out_min_len) => {
if dst_out.len() < out_min_len {
return Err(UnknownCryptoError);
}
}
None => return Err(UnknownCryptoError),
};

let mut blake2b = Blake2b::new(32)?;
blake2b.update(secret_key.unprotected_as_bytes())?;
blake2b.update(nonce.as_ref())?;
blake2b.update(ad)?;

aead::chacha20poly1305::seal(
secret_key,
nonce,
plaintext,
Some(ad),
&mut dst_out[..plaintext.len() + POLY1305_OUTSIZE],
)?;
blake2b.update(&dst_out[plaintext.len()..plaintext.len() + POLY1305_OUTSIZE])?;
let tag = blake2b.finalize()?;

dst_out[plaintext.len()..plaintext.len() + TAG_SIZE].copy_from_slice(tag.as_ref());

Ok(())
}

#[must_use = "SECURITY WARNING: Experimental feature."]
/// CTX ChaCha20Poly1305 with BLAKE2b-256.
pub fn open(
secret_key: &SecretKey,
nonce: &Nonce,
ciphertext_with_tag: &[u8],
ad: Option<&[u8]>,
dst_out: &mut [u8],
) -> Result<(), UnknownCryptoError> {
if u64::try_from(ciphertext_with_tag.len()).map_err(|_| UnknownCryptoError)? > C_MAX {
return Err(UnknownCryptoError);
}
let ad = ad.unwrap_or(&[0u8; 0]);
#[allow(clippy::absurd_extreme_comparisons)]
if u64::try_from(ad.len()).map_err(|_| UnknownCryptoError)? > A_MAX {
return Err(UnknownCryptoError);
}
if ciphertext_with_tag.len() < TAG_SIZE {
return Err(UnknownCryptoError);
}
if dst_out.len() < ciphertext_with_tag.len() - TAG_SIZE {
return Err(UnknownCryptoError);
}

let mut blake2b = Blake2b::new(32)?;
blake2b.update(secret_key.unprotected_as_bytes())?;
blake2b.update(nonce.as_ref())?;
blake2b.update(ad)?;

let mut dec_ctx =
ChaCha20::new(secret_key.unprotected_as_bytes(), nonce.as_ref(), true).unwrap();
let mut tmp = Zeroizing::new([0u8; CHACHA_BLOCKSIZE]);
let mut auth_ctx = Poly1305::new(&poly1305_key_gen(&mut dec_ctx, &mut tmp));

let ciphertext_len = ciphertext_with_tag.len() - TAG_SIZE;
process_authentication(&mut auth_ctx, ad, &ciphertext_with_tag[..ciphertext_len])?;

blake2b.update(auth_ctx.finalize()?.unprotected_as_bytes())?;

util::secure_cmp(
blake2b.finalize()?.as_ref(),
&ciphertext_with_tag[ciphertext_len..],
)?;

if ciphertext_len != 0 {
dst_out[..ciphertext_len].copy_from_slice(&ciphertext_with_tag[..ciphertext_len]);
chacha20::xor_keystream(
&mut dec_ctx,
ENC_CTR,
tmp.as_mut(),
&mut dst_out[..ciphertext_len],
)?;
}

Ok(())
}

// Testing public functions in the module.
#[cfg(test)]
#[cfg(feature = "safe_api")]
mod public {
use super::*;
use crate::test_framework::aead_interface::{test_diff_params_err, AeadTestRunner};

#[quickcheck]
#[cfg(feature = "safe_api")]
fn prop_aead_interface(input: Vec<u8>, ad: Vec<u8>) -> bool {
let secret_key = SecretKey::generate();
let nonce = Nonce::from_slice(&[0u8; chacha20::IETF_CHACHA_NONCESIZE]).unwrap();
AeadTestRunner(seal, open, secret_key, nonce, &input, None, TAG_SIZE, &ad);
test_diff_params_err(&seal, &open, &input, TAG_SIZE);
true
}
}
31 changes: 31 additions & 0 deletions src/hazardous/cae/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// MIT License

// Copyright (c) 2023 The orion Developers

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

/// Fully-committing ChaCha20-Poly1305 with BLAKE2b based on the [CTX] construction by John Chan & Phillip Rogaway.
///
/// [CTX]: https://eprint.iacr.org/2022/1260
pub mod chacha20poly1305blake2b;

/// Fully-committing XChaCha20-Poly1305 with BLAKE2b based on the [CTX] construction by John Chan & Phillip Rogaway.
///
/// [CTX]: https://eprint.iacr.org/2022/1260
pub mod xchacha20poly1305blake2b;
21 changes: 21 additions & 0 deletions src/hazardous/cae/xchacha20poly1305blake2b.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// MIT License

// Copyright (c) 2023 The orion Developers

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
6 changes: 6 additions & 0 deletions src/hazardous/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,9 @@ pub mod stream;

/// Elliptic-Curve Cryptography.
pub mod ecc;

#[cfg(feature = "experimental")]
/// __WARNING:__ Experimental feature.
///
/// Fully-committing Authenticated Encryption.
pub mod cae;