-
Notifications
You must be signed in to change notification settings - Fork 42
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add common RollingTicketer data type
- Loading branch information
Showing
13 changed files
with
500 additions
and
3 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
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,90 @@ | ||
/* | ||
* Copyright 2024 ByteDance and/or its affiliates. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
use anyhow::anyhow; | ||
use openssl::cipher::Cipher; | ||
use openssl::cipher_ctx::CipherCtxRef; | ||
use openssl::error::ErrorStack; | ||
use openssl::hmac::HMacCtxRef; | ||
use openssl::md::Md; | ||
use openssl::rand; | ||
use openssl::ssl::TicketKeyStatus; | ||
|
||
use crate::net::{RollingTicketKey, TicketKeyName, TICKET_KEY_LENGTH, TICKET_KEY_NAME_LENGTH}; | ||
|
||
pub struct OpensslTicketKey { | ||
name: TicketKeyName, | ||
lifetime: u32, | ||
key: [u8; TICKET_KEY_LENGTH], | ||
} | ||
|
||
impl OpensslTicketKey { | ||
pub(super) fn encrypt_init( | ||
&self, | ||
key_name: &mut [u8], | ||
iv: &[u8], | ||
cipher_ctx: &mut CipherCtxRef, | ||
hmac_ctx: &mut HMacCtxRef, | ||
) -> Result<TicketKeyStatus, ErrorStack> { | ||
if key_name.len() != TICKET_KEY_NAME_LENGTH { | ||
return Ok(TicketKeyStatus::FAILED); | ||
} | ||
key_name.copy_from_slice(self.name.as_ref()); | ||
|
||
cipher_ctx.encrypt_init(Some(Cipher::aes_256_cbc()), Some(&self.key), Some(iv))?; | ||
hmac_ctx.init_ex(Some(&self.key), Md::sha256())?; | ||
|
||
Ok(TicketKeyStatus::SUCCESS) | ||
} | ||
|
||
pub(super) fn decrypt_init( | ||
&self, | ||
iv: &[u8], | ||
cipher_ctx: &mut CipherCtxRef, | ||
hmac_ctx: &mut HMacCtxRef, | ||
) -> Result<(), ErrorStack> { | ||
hmac_ctx.init_ex(Some(&self.key), Md::sha256())?; | ||
cipher_ctx.decrypt_init(Some(Cipher::aes_256_cbc()), Some(&self.key), Some(iv))?; | ||
Ok(()) | ||
} | ||
} | ||
|
||
impl RollingTicketKey for OpensslTicketKey { | ||
fn new(lifetime: u32) -> anyhow::Result<Self> { | ||
let mut key = [0u8; TICKET_KEY_LENGTH]; | ||
rand::rand_bytes(&mut key).map_err(|e| anyhow!("failed to generate random key: {e}"))?; | ||
|
||
let mut key_name = [0u8; TICKET_KEY_NAME_LENGTH]; | ||
rand::rand_bytes(&mut key_name) | ||
.map_err(|e| anyhow!("failed to generate random key name: {e}"))?; | ||
|
||
Ok(OpensslTicketKey { | ||
name: key_name.into(), | ||
lifetime, | ||
key, | ||
}) | ||
} | ||
|
||
#[inline] | ||
fn name(&self) -> &TicketKeyName { | ||
&self.name | ||
} | ||
|
||
#[inline] | ||
fn lifetime(&self) -> u32 { | ||
self.lifetime | ||
} | ||
} |
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,57 @@ | ||
/* | ||
* Copyright 2024 ByteDance and/or its affiliates. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
use openssl::cipher_ctx::CipherCtxRef; | ||
use openssl::error::ErrorStack; | ||
use openssl::hmac::HMacCtxRef; | ||
use openssl::ssl::TicketKeyStatus; | ||
|
||
use super::OpensslTicketKey; | ||
use crate::net::{RollingTicketKey, RollingTicketer}; | ||
|
||
impl RollingTicketer<OpensslTicketKey> { | ||
pub fn encrypt_init( | ||
&self, | ||
key_name: &mut [u8], | ||
iv: &[u8], | ||
cipher_ctx: &mut CipherCtxRef, | ||
hmac_ctx: &mut HMacCtxRef, | ||
) -> Result<TicketKeyStatus, ErrorStack> { | ||
self.enc_key | ||
.load() | ||
.encrypt_init(key_name, iv, cipher_ctx, hmac_ctx) | ||
} | ||
|
||
pub fn decrypt_init( | ||
&self, | ||
key_name: &[u8], | ||
iv: &[u8], | ||
cipher_ctx: &mut CipherCtxRef, | ||
hmac_ctx: &mut HMacCtxRef, | ||
) -> Result<TicketKeyStatus, ErrorStack> { | ||
let Some(key) = self.get_decrypt_key(key_name) else { | ||
return Ok(TicketKeyStatus::FAILED); | ||
}; | ||
|
||
key.decrypt_init(iv, cipher_ctx, hmac_ctx)?; | ||
|
||
if self.enc_key.load().name().constant_time_eq(key_name) { | ||
Ok(TicketKeyStatus::SUCCESS) | ||
} else { | ||
Ok(TicketKeyStatus::SUCCESS_AND_RENEW) | ||
} | ||
} | ||
} |
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,15 @@ | ||
/* | ||
* Copyright 2024 ByteDance and/or its affiliates. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ |
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,147 @@ | ||
/* | ||
* Copyright 2024 ByteDance and/or its affiliates. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
use std::sync::atomic::{AtomicUsize, Ordering}; | ||
|
||
use anyhow::anyhow; | ||
use ring::aead; | ||
use ring::rand::{SecureRandom, SystemRandom}; | ||
|
||
use crate::net::{RollingTicketKey, TicketKeyName, TICKET_KEY_LENGTH, TICKET_KEY_NAME_LENGTH}; | ||
|
||
pub struct RustlsTicketKey { | ||
name: TicketKeyName, | ||
lifetime: u32, | ||
key: aead::LessSafeKey, | ||
|
||
/// Tracks the largest ciphertext produced by `encrypt`, and | ||
/// uses it to early-reject `decrypt` queries that are too long. | ||
/// | ||
/// Accepting excessively long ciphertexts means a "Partitioning | ||
/// Oracle Attack" (see <https://eprint.iacr.org/2020/1491.pdf>) | ||
/// can be more efficient, though also note that these are thought | ||
/// to be cryptographically hard if the key is full-entropy (as it | ||
/// is here). | ||
maximum_ciphertext_len: AtomicUsize, | ||
} | ||
|
||
impl RustlsTicketKey { | ||
/// Encrypt `message` and return the ciphertext. | ||
pub(super) fn encrypt(&self, message: &[u8]) -> Option<Vec<u8>> { | ||
// Random nonce, because a counter is a privacy leak. | ||
let mut nonce_buf = [0u8; aead::NONCE_LEN]; | ||
SystemRandom::new().fill(&mut nonce_buf).ok()?; | ||
let nonce = aead::Nonce::assume_unique_for_key(nonce_buf); | ||
let aad = aead::Aad::from(&self.name); | ||
|
||
// ciphertext structure is: | ||
// key_name: [u8; 16] | ||
// nonce: [u8; 12] | ||
// message: [u8, _] | ||
// tag: [u8; 16] | ||
|
||
let mut ciphertext = Vec::with_capacity( | ||
TICKET_KEY_NAME_LENGTH | ||
+ nonce_buf.len() | ||
+ message.len() | ||
+ self.key.algorithm().tag_len(), | ||
); | ||
ciphertext.extend(self.name.as_ref()); | ||
ciphertext.extend(nonce_buf); | ||
ciphertext.extend(message); | ||
let ciphertext = self | ||
.key | ||
.seal_in_place_separate_tag( | ||
nonce, | ||
aad, | ||
&mut ciphertext[TICKET_KEY_NAME_LENGTH + nonce_buf.len()..], | ||
) | ||
.map(|tag| { | ||
ciphertext.extend(tag.as_ref()); | ||
ciphertext | ||
}) | ||
.ok()?; | ||
|
||
self.maximum_ciphertext_len | ||
.fetch_max(ciphertext.len(), Ordering::SeqCst); | ||
Some(ciphertext) | ||
} | ||
|
||
/// Decrypt `ciphertext` and recover the original message. | ||
pub(super) fn decrypt(&self, ciphertext: &[u8]) -> Option<Vec<u8>> { | ||
if ciphertext.len() > self.maximum_ciphertext_len.load(Ordering::SeqCst) { | ||
return None; | ||
} | ||
|
||
let (alleged_key_name, ciphertext) = try_split_at(ciphertext, TICKET_KEY_NAME_LENGTH)?; | ||
let (nonce, ciphertext) = try_split_at(ciphertext, aead::NONCE_LEN)?; | ||
|
||
// This won't fail since `nonce` has the required length. | ||
let nonce = aead::Nonce::try_assume_unique_for_key(nonce).ok()?; | ||
|
||
let mut out = Vec::from(ciphertext); | ||
|
||
let plain_len = self | ||
.key | ||
.open_in_place(nonce, aead::Aad::from(alleged_key_name), &mut out) | ||
.ok()? | ||
.len(); | ||
out.truncate(plain_len); | ||
|
||
Some(out) | ||
} | ||
} | ||
|
||
/// Non-panicking `let (nonce, ciphertext) = ciphertext.split_at(...)`. | ||
fn try_split_at(slice: &[u8], mid: usize) -> Option<(&[u8], &[u8])> { | ||
match mid > slice.len() { | ||
true => None, | ||
false => Some(slice.split_at(mid)), | ||
} | ||
} | ||
|
||
impl RollingTicketKey for RustlsTicketKey { | ||
fn new(lifetime: u32) -> anyhow::Result<Self> { | ||
let mut key = [0u8; TICKET_KEY_LENGTH]; | ||
SystemRandom::new() | ||
.fill(&mut key) | ||
.map_err(|_| anyhow!("failed to generate random key"))?; | ||
|
||
let key = aead::UnboundKey::new(&aead::AES_256_GCM, &key).unwrap(); | ||
|
||
let mut key_name = [0u8; TICKET_KEY_NAME_LENGTH]; | ||
SystemRandom::new() | ||
.fill(&mut key_name) | ||
.map_err(|_| anyhow!("failed to generate random key name"))?; | ||
|
||
Ok(RustlsTicketKey { | ||
name: key_name.into(), | ||
lifetime, | ||
key: aead::LessSafeKey::new(key), | ||
maximum_ciphertext_len: AtomicUsize::new(0), | ||
}) | ||
} | ||
|
||
#[inline] | ||
fn name(&self) -> &TicketKeyName { | ||
&self.name | ||
} | ||
|
||
#[inline] | ||
fn lifetime(&self) -> u32 { | ||
self.lifetime | ||
} | ||
} |
Oops, something went wrong.