-
Notifications
You must be signed in to change notification settings - Fork 726
feat(bindings): add external psk apis #5061
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
Merged
Merged
Changes from 15 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
b95df96
feat(bindings): add external psk apis
jmayclin 4f3f7d5
address pr feedback
jmayclin 09623b0
address pr feedback
jmayclin 69f7990
address pr feedback
jmayclin 8a149cc
address pr feedback
jmayclin 01ccadb
specify lifetimes consistently
jmayclin 14db20e
address pr feedback
jmayclin f8094ec
address pr feedback
jmayclin 56d98d9
remove psk callback functionality
jmayclin 936e908
fix outdated docs
jmayclin 5a5a5a2
address pr feedback
jmayclin 0ef869f
fix: grep simple mistake should allow backtick
jmayclin 5de03b6
update stale docs with name change
jmayclin 98da4ef
address pr feedback
jmayclin 6989f83
address pr feedback
jmayclin 5e48088
address pr feedback
jmayclin 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
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,253 @@ | ||
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
use std::ptr::NonNull; | ||
|
||
use crate::{ | ||
enums::PskHmac, | ||
error::{Error, ErrorType, Fallible}, | ||
}; | ||
use s2n_tls_sys::*; | ||
|
||
#[derive(Debug)] | ||
pub struct Builder { | ||
psk: Psk, | ||
has_identity: bool, | ||
has_secret: bool, | ||
has_hmac: bool, | ||
} | ||
|
||
impl Builder { | ||
pub fn new() -> Result<Self, crate::error::Error> { | ||
crate::init::init(); | ||
let psk = Psk::allocate()?; | ||
Ok(Self { | ||
psk, | ||
has_identity: false, | ||
has_secret: false, | ||
has_hmac: false, | ||
}) | ||
} | ||
|
||
/// Set the public PSK identity. | ||
/// | ||
/// Corresponds to [s2n_psk_set_identity]. | ||
pub fn with_identity(&mut self, identity: &[u8]) -> Result<&mut Self, crate::error::Error> { | ||
jmayclin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
let identity_length = identity.len().try_into().map_err(|_| { | ||
Error::bindings( | ||
ErrorType::UsageError, | ||
"invalid psk identity", | ||
"The identity must be no longer than u16::MAX", | ||
) | ||
})?; | ||
unsafe { | ||
s2n_psk_set_identity( | ||
self.psk.as_s2n_ptr_mut(), | ||
identity.as_ptr(), | ||
identity_length, | ||
) | ||
.into_result() | ||
}?; | ||
self.has_identity = true; | ||
Ok(self) | ||
} | ||
|
||
/// Set the PSK secret. | ||
/// | ||
/// Secrets must be at least 16 bytes. | ||
/// | ||
/// Corresponds to [s2n_psk_set_secret]. | ||
pub fn with_secret(&mut self, secret: &[u8]) -> Result<&mut Self, crate::error::Error> { | ||
let secret_length = secret.len().try_into().map_err(|_| { | ||
Error::bindings( | ||
ErrorType::UsageError, | ||
"invalid psk secret", | ||
"The secret must be no longer than u16::MAX", | ||
) | ||
})?; | ||
|
||
// These checks are only in the Rust code. Adding them to C would be a | ||
// backwards incompatible change. | ||
//= https://www.rfc-editor.org/rfc/rfc9257.html#section-6 | ||
//# Each PSK ... MUST be at least 128 bits long | ||
if secret_length < (128 / 8) { | ||
return Err(Error::bindings( | ||
ErrorType::UsageError, | ||
"invalid psk secret", | ||
"PSK secret must be at least 128 bits", | ||
)); | ||
} | ||
unsafe { | ||
s2n_psk_set_secret(self.psk.as_s2n_ptr_mut(), secret.as_ptr(), secret_length) | ||
.into_result() | ||
}?; | ||
self.has_secret = true; | ||
Ok(self) | ||
} | ||
|
||
/// Set the HMAC function associated with the PSK. | ||
/// | ||
/// Corresponds to [s2n_psk_set_hmac]. | ||
pub fn with_hmac(&mut self, hmac: PskHmac) -> Result<&mut Self, crate::error::Error> { | ||
unsafe { s2n_psk_set_hmac(self.psk.as_s2n_ptr_mut(), hmac.into()).into_result() }?; | ||
self.has_hmac = true; | ||
Ok(self) | ||
} | ||
|
||
pub fn build(self) -> Result<Psk, crate::error::Error> { | ||
if !self.has_identity { | ||
Err(Error::bindings( | ||
crate::error::ErrorType::UsageError, | ||
"invalid psk", | ||
"You must set an identity using `with_identity`", | ||
)) | ||
} else if !self.has_secret { | ||
Err(Error::bindings( | ||
crate::error::ErrorType::UsageError, | ||
"invalid psk", | ||
"You must set a secret using `with_secret`", | ||
)) | ||
} else if !self.has_hmac { | ||
Err(Error::bindings( | ||
crate::error::ErrorType::UsageError, | ||
"invalid psk", | ||
"You must set an hmac `with_hmac`", | ||
)) | ||
} else { | ||
Ok(self.psk) | ||
} | ||
} | ||
} | ||
|
||
/// Psk represents an out-of-band pre-shared key. | ||
/// | ||
/// If two peers already have some mechanism to securely exchange secrets, then | ||
/// they can use Psks to authenticate rather than certificates. | ||
#[derive(Debug)] | ||
pub struct Psk { | ||
ptr: NonNull<s2n_psk>, | ||
} | ||
|
||
/// # Safety | ||
/// | ||
/// Safety: Psk objects can be sent across threads | ||
unsafe impl Send for Psk {} | ||
|
||
/// # Safety | ||
/// | ||
/// Safety: There are no methods that mutate the Psk. | ||
jmayclin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
unsafe impl Sync for Psk {} | ||
|
||
impl Psk { | ||
/// Allocate a new, uninitialized Psk. | ||
/// | ||
/// Corresponds to [s2n_external_psk_new]. | ||
fn allocate() -> Result<Self, crate::error::Error> { | ||
let psk = unsafe { s2n_external_psk_new().into_result() }?; | ||
Ok(Self { ptr: psk }) | ||
} | ||
|
||
pub fn builder() -> Result<Builder, crate::error::Error> { | ||
Builder::new() | ||
} | ||
|
||
pub(crate) fn as_s2n_ptr(&self) -> *const s2n_psk { | ||
self.ptr.as_ptr() as *const s2n_psk | ||
} | ||
|
||
fn as_s2n_ptr_mut(&mut self) -> *mut s2n_psk { | ||
self.ptr.as_ptr() | ||
} | ||
} | ||
|
||
impl Drop for Psk { | ||
/// Corresponds to [s2n_psk_free]. | ||
fn drop(&mut self) { | ||
// ignore failures. There isn't anything to be done to handle them, but | ||
// allowing the program to continue is preferable to crashing. | ||
let _ = unsafe { s2n_psk_free(&mut self.as_s2n_ptr_mut()).into_result() }; | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use crate::{config::Config, error::ErrorSource, security::DEFAULT_TLS13, testing::TestPair}; | ||
|
||
use super::*; | ||
|
||
/// `identity`, `secret`, and `hmac` are all required fields. If any of them | ||
/// aren't set, then `psk.build()` operation should fail. | ||
#[test] | ||
fn build_errors() -> Result<(), crate::error::Error> { | ||
const PERMUTATIONS: u8 = 0b111; | ||
|
||
for permutation in 0..PERMUTATIONS { | ||
let mut psk = Builder::new()?; | ||
if permutation & 0b001 != 0 { | ||
psk.with_identity(b"Alice")?; | ||
} | ||
if permutation & 0b010 != 0 { | ||
psk.with_secret(b"Rabbits don't actually jump. They instead push the world down")?; | ||
} | ||
if permutation & 0b100 != 0 { | ||
psk.with_hmac(PskHmac::SHA384)?; | ||
} | ||
assert!(psk.build().is_err()); | ||
} | ||
Ok(()) | ||
} | ||
|
||
//= https://www.rfc-editor.org/rfc/rfc9257.html#section-6 | ||
//= type=test | ||
//# Each PSK ... MUST be at least 128 bits long | ||
#[test] | ||
fn psk_secret_must_be_at_least_128_bits() -> Result<(), crate::error::Error> { | ||
// 120 bit key | ||
let secret = vec![5; 15]; | ||
|
||
let mut psk = Builder::new()?; | ||
let err = psk.with_secret(&secret).unwrap_err(); | ||
assert_eq!(err.source(), ErrorSource::Bindings); | ||
assert_eq!(err.kind(), ErrorType::UsageError); | ||
assert_eq!(err.name(), "invalid psk secret"); | ||
assert_eq!(err.message(), "PSK secret must be at least 128 bits"); | ||
Ok(()) | ||
} | ||
|
||
const TEST_PSK_IDENTITY: &[u8] = b"alice"; | ||
|
||
fn test_psk() -> Psk { | ||
let mut builder = Psk::builder().unwrap(); | ||
builder.with_identity(TEST_PSK_IDENTITY).unwrap(); | ||
builder | ||
.with_secret(b"contrary to popular belief, the moon is yogurt, not cheese") | ||
.unwrap(); | ||
builder.with_hmac(PskHmac::SHA384).unwrap(); | ||
builder.build().unwrap() | ||
} | ||
|
||
/// A PSK handshake using the basic "append_psk" workflow should complete | ||
/// successfully, and the correct negotiated psk identity should be returned. | ||
#[test] | ||
fn psk_handshake() -> Result<(), crate::error::Error> { | ||
let psk = test_psk(); | ||
let mut config = Config::builder(); | ||
config.set_security_policy(&DEFAULT_TLS13)?; | ||
let config = config.build()?; | ||
let mut test_pair = TestPair::from_config(&config); | ||
test_pair.client.append_psk(&psk)?; | ||
test_pair.server.append_psk(&psk)?; | ||
assert!(test_pair.handshake().is_ok()); | ||
|
||
for peer in [test_pair.client, test_pair.server] { | ||
let mut identity_buffer = [0; TEST_PSK_IDENTITY.len()]; | ||
assert_eq!( | ||
peer.negotiated_psk_identity_length()?, | ||
TEST_PSK_IDENTITY.len() | ||
); | ||
peer.negotiated_psk_identity(&mut identity_buffer)?; | ||
assert_eq!(identity_buffer, TEST_PSK_IDENTITY); | ||
} | ||
Ok(()) | ||
} | ||
} |
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.
I think it would be better to get the mutable pointer directly rather than casting
*const
->*mut
.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.
Assumption: There is an intention that s2n-tls C API's be const correct, but we just aren't there yet.
Given that this takes a
&Psk
, I wanted a visible red flag that we are casting away the "logical constness" of the underlying data.Let me know if you think the the friction is causing more noise than safety, and I'll go ahead and make
as_s2n_ptr_mut
take in&self
and just add a comment about the safety.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.
Yeah I worry about allowing
*const
->*mut
casts in general... I think it's better to just return the*mut
directly fromNonNull
and have some safety comments around it all.