Skip to content

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 16 commits into from
Feb 7, 2025
Merged
40 changes: 40 additions & 0 deletions bindings/rust/extended/s2n-tls/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::{
config::Config,
enums::*,
error::{Error, Fallible, Pollable},
psk::Psk,
security,
};

Expand Down Expand Up @@ -1319,6 +1320,45 @@ impl Connection {
unsafe { s2n_connection_is_session_resumed(self.connection.as_ptr()) == 1 }
}

/// Append an external psk to a connection.
///
/// This may be called repeatedly to support multiple PSKs.
///
/// Corresponds to [s2n_connection_append_psk].
pub fn append_psk(&mut self, psk: &Psk) -> Result<(), Error> {
unsafe {
// SAFETY: *mut cast - s2n-tls does not treat the pointer as mutable.
s2n_connection_append_psk(self.as_ptr(), psk.as_s2n_ptr() as *mut _).into_result()?
Copy link
Contributor

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.

Copy link
Contributor Author

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.

Copy link
Contributor

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 from NonNull and have some safety comments around it all.

};
Ok(())
}

/// Corresponds to [s2n_connection_get_negotiated_psk_identity_length].
pub fn negotiated_psk_identity_length(&self) -> Result<usize, Error> {
let mut length = 0;
unsafe {
s2n_connection_get_negotiated_psk_identity_length(self.connection.as_ptr(), &mut length)
.into_result()?
};
Ok(length as usize)
}

/// Retrieve the negotiated psk identity. Use [Connection::negotiated_psk_identity_length]
/// to retrieve the length of the psk identity.
///
/// Corresponds to [s2n_connection_get_negotiated_psk_identity].
pub fn negotiated_psk_identity(&self, destination: &mut [u8]) -> Result<(), Error> {
unsafe {
s2n_connection_get_negotiated_psk_identity(
self.connection.as_ptr(),
destination.as_mut_ptr(),
destination.len().min(u16::MAX as usize) as u16,
)
.into_result()?;
}
Ok(())
}

/// Associates an arbitrary application context with the Connection to be later retrieved via
/// the [`Self::application_context()`] and [`Self::application_context_mut()`] APIs.
///
Expand Down
32 changes: 32 additions & 0 deletions bindings/rust/extended/s2n-tls/src/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,38 @@ impl From<PeerKeyUpdate> for s2n_peer_key_update::Type {
}
}

#[non_exhaustive]
#[derive(Debug)]
pub enum PskMode {
Resumption,
External,
}

impl From<PskMode> for s2n_psk_mode::Type {
fn from(input: PskMode) -> Self {
match input {
PskMode::Resumption => s2n_psk_mode::RESUMPTION,
PskMode::External => s2n_psk_mode::EXTERNAL,
}
}
}

#[non_exhaustive]
#[derive(Debug)]
pub enum PskHmac {
SHA256,
SHA384,
}

impl From<PskHmac> for s2n_psk_hmac::Type {
fn from(input: PskHmac) -> Self {
match input {
PskHmac::SHA256 => s2n_psk_hmac::SHA256,
PskHmac::SHA384 => s2n_psk_hmac::SHA384,
}
}
}

/// Corresponds to [s2n_serialization_version].
#[non_exhaustive]
#[derive(Debug, PartialEq, Copy, Clone)]
Expand Down
1 change: 1 addition & 0 deletions bindings/rust/extended/s2n-tls/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub mod enums;
pub mod fingerprint;
pub mod init;
pub mod pool;
pub mod psk;
#[cfg(feature = "unstable-renegotiate")]
pub mod renegotiate;
pub mod security;
Expand Down
253 changes: 253 additions & 0 deletions bindings/rust/extended/s2n-tls/src/psk.rs
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> {
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.
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(())
}
}
Loading