Skip to content

Commit 1aa6d59

Browse files
authored
feat(bindings): add external psk apis (#5061)
1 parent f129bf7 commit 1aa6d59

File tree

4 files changed

+320
-0
lines changed

4 files changed

+320
-0
lines changed

bindings/rust/extended/s2n-tls/src/connection.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use crate::{
1111
config::Config,
1212
enums::*,
1313
error::{Error, Fallible, Pollable},
14+
psk::Psk,
1415
security,
1516
};
1617

@@ -1319,6 +1320,47 @@ impl Connection {
13191320
unsafe { s2n_connection_is_session_resumed(self.connection.as_ptr()) == 1 }
13201321
}
13211322

1323+
/// Append an external psk to a connection.
1324+
///
1325+
/// This may be called repeatedly to support multiple PSKs.
1326+
///
1327+
/// Corresponds to [s2n_connection_append_psk].
1328+
pub fn append_psk(&mut self, psk: &Psk) -> Result<(), Error> {
1329+
unsafe {
1330+
// SAFETY: retrieving a *mut s2n_psk from &Psk: s2n-tls does not treat
1331+
// the pointer as mutable, and only holds the reference to copy the
1332+
// PSK onto the connection.
1333+
s2n_connection_append_psk(self.as_ptr(), psk.ptr.as_ptr()).into_result()?
1334+
};
1335+
Ok(())
1336+
}
1337+
1338+
/// Corresponds to [s2n_connection_get_negotiated_psk_identity_length].
1339+
pub fn negotiated_psk_identity_length(&self) -> Result<usize, Error> {
1340+
let mut length = 0;
1341+
unsafe {
1342+
s2n_connection_get_negotiated_psk_identity_length(self.connection.as_ptr(), &mut length)
1343+
.into_result()?
1344+
};
1345+
Ok(length as usize)
1346+
}
1347+
1348+
/// Retrieve the negotiated psk identity. Use [Connection::negotiated_psk_identity_length]
1349+
/// to retrieve the length of the psk identity.
1350+
///
1351+
/// Corresponds to [s2n_connection_get_negotiated_psk_identity].
1352+
pub fn negotiated_psk_identity(&self, destination: &mut [u8]) -> Result<(), Error> {
1353+
unsafe {
1354+
s2n_connection_get_negotiated_psk_identity(
1355+
self.connection.as_ptr(),
1356+
destination.as_mut_ptr(),
1357+
destination.len().min(u16::MAX as usize) as u16,
1358+
)
1359+
.into_result()?;
1360+
}
1361+
Ok(())
1362+
}
1363+
13221364
/// Associates an arbitrary application context with the Connection to be later retrieved via
13231365
/// the [`Self::application_context()`] and [`Self::application_context_mut()`] APIs.
13241366
///

bindings/rust/extended/s2n-tls/src/enums.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,38 @@ impl From<PeerKeyUpdate> for s2n_peer_key_update::Type {
229229
}
230230
}
231231

232+
#[non_exhaustive]
233+
#[derive(Debug)]
234+
pub enum PskMode {
235+
Resumption,
236+
External,
237+
}
238+
239+
impl From<PskMode> for s2n_psk_mode::Type {
240+
fn from(input: PskMode) -> Self {
241+
match input {
242+
PskMode::Resumption => s2n_psk_mode::RESUMPTION,
243+
PskMode::External => s2n_psk_mode::EXTERNAL,
244+
}
245+
}
246+
}
247+
248+
#[non_exhaustive]
249+
#[derive(Debug)]
250+
pub enum PskHmac {
251+
SHA256,
252+
SHA384,
253+
}
254+
255+
impl From<PskHmac> for s2n_psk_hmac::Type {
256+
fn from(input: PskHmac) -> Self {
257+
match input {
258+
PskHmac::SHA256 => s2n_psk_hmac::SHA256,
259+
PskHmac::SHA384 => s2n_psk_hmac::SHA384,
260+
}
261+
}
262+
}
263+
232264
/// Corresponds to [s2n_serialization_version].
233265
#[non_exhaustive]
234266
#[derive(Debug, PartialEq, Copy, Clone)]

bindings/rust/extended/s2n-tls/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ pub mod enums;
2323
pub mod fingerprint;
2424
pub mod init;
2525
pub mod pool;
26+
pub mod psk;
2627
#[cfg(feature = "unstable-renegotiate")]
2728
pub mod renegotiate;
2829
pub mod security;
Lines changed: 245 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,245 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
use std::ptr::NonNull;
5+
6+
use crate::{
7+
enums::PskHmac,
8+
error::{Error, ErrorType, Fallible},
9+
};
10+
use s2n_tls_sys::*;
11+
12+
#[derive(Debug)]
13+
pub struct Builder {
14+
psk: Psk,
15+
has_identity: bool,
16+
has_secret: bool,
17+
has_hmac: bool,
18+
}
19+
20+
impl Builder {
21+
pub fn new() -> Result<Self, crate::error::Error> {
22+
crate::init::init();
23+
let psk = Psk::allocate()?;
24+
Ok(Self {
25+
psk,
26+
has_identity: false,
27+
has_secret: false,
28+
has_hmac: false,
29+
})
30+
}
31+
32+
/// Set the public PSK identity.
33+
///
34+
/// Corresponds to [s2n_psk_set_identity].
35+
pub fn set_identity(&mut self, identity: &[u8]) -> Result<&mut Self, crate::error::Error> {
36+
let identity_length = identity.len().try_into().map_err(|_| {
37+
Error::bindings(
38+
ErrorType::UsageError,
39+
"invalid psk identity",
40+
"The identity must be no longer than u16::MAX",
41+
)
42+
})?;
43+
unsafe {
44+
s2n_psk_set_identity(self.psk.ptr.as_ptr(), identity.as_ptr(), identity_length)
45+
.into_result()
46+
}?;
47+
self.has_identity = true;
48+
Ok(self)
49+
}
50+
51+
/// Set the PSK secret.
52+
///
53+
/// Secrets must be at least 16 bytes.
54+
///
55+
/// Corresponds to [s2n_psk_set_secret].
56+
pub fn set_secret(&mut self, secret: &[u8]) -> Result<&mut Self, crate::error::Error> {
57+
let secret_length = secret.len().try_into().map_err(|_| {
58+
Error::bindings(
59+
ErrorType::UsageError,
60+
"invalid psk secret",
61+
"The secret must be no longer than u16::MAX",
62+
)
63+
})?;
64+
65+
// These checks are only in the Rust code. Adding them to C would be a
66+
// backwards incompatible change.
67+
//= https://www.rfc-editor.org/rfc/rfc9257.html#section-6
68+
//# Each PSK ... MUST be at least 128 bits long
69+
if secret_length < (128 / 8) {
70+
return Err(Error::bindings(
71+
ErrorType::UsageError,
72+
"invalid psk secret",
73+
"PSK secret must be at least 128 bits",
74+
));
75+
}
76+
unsafe {
77+
s2n_psk_set_secret(self.psk.ptr.as_ptr(), secret.as_ptr(), secret_length).into_result()
78+
}?;
79+
self.has_secret = true;
80+
Ok(self)
81+
}
82+
83+
/// Set the HMAC function associated with the PSK.
84+
///
85+
/// Corresponds to [s2n_psk_set_hmac].
86+
pub fn set_hmac(&mut self, hmac: PskHmac) -> Result<&mut Self, crate::error::Error> {
87+
unsafe { s2n_psk_set_hmac(self.psk.ptr.as_ptr(), hmac.into()).into_result() }?;
88+
self.has_hmac = true;
89+
Ok(self)
90+
}
91+
92+
pub fn build(self) -> Result<Psk, crate::error::Error> {
93+
if !self.has_identity {
94+
Err(Error::bindings(
95+
crate::error::ErrorType::UsageError,
96+
"invalid psk",
97+
"You must set an identity using `with_identity`",
98+
))
99+
} else if !self.has_secret {
100+
Err(Error::bindings(
101+
crate::error::ErrorType::UsageError,
102+
"invalid psk",
103+
"You must set a secret using `with_secret`",
104+
))
105+
} else if !self.has_hmac {
106+
Err(Error::bindings(
107+
crate::error::ErrorType::UsageError,
108+
"invalid psk",
109+
"You must set an hmac `with_hmac`",
110+
))
111+
} else {
112+
Ok(self.psk)
113+
}
114+
}
115+
}
116+
117+
/// Psk represents an out-of-band pre-shared key.
118+
///
119+
/// If two peers already have some mechanism to securely exchange secrets, then
120+
/// they can use Psks to authenticate rather than certificates.
121+
#[derive(Debug)]
122+
pub struct Psk {
123+
// SAFETY: `ptr.as_ptr()` allows a `*mut s2n_psk` to be returned from `&Psk`.
124+
// This is required because all s2n-tls C psk APIs take a mutable pointer.
125+
// This is only safe if the `*mut s2n_psk` from `&Psk` is still treated as
126+
// logically const by the s2n-tls C library.
127+
pub(crate) ptr: NonNull<s2n_psk>,
128+
}
129+
130+
/// # Safety
131+
///
132+
/// Safety: Psk objects can be sent across threads
133+
unsafe impl Send for Psk {}
134+
135+
/// # Safety
136+
///
137+
/// Safety: There are no methods that mutate the Psk through a shared reference
138+
/// (i.e., no interior mutability is exposed)
139+
unsafe impl Sync for Psk {}
140+
141+
impl Psk {
142+
/// Allocate a new, uninitialized Psk.
143+
///
144+
/// Corresponds to [s2n_external_psk_new].
145+
fn allocate() -> Result<Self, crate::error::Error> {
146+
let psk = unsafe { s2n_external_psk_new().into_result() }?;
147+
Ok(Self { ptr: psk })
148+
}
149+
150+
pub fn builder() -> Result<Builder, crate::error::Error> {
151+
Builder::new()
152+
}
153+
}
154+
155+
impl Drop for Psk {
156+
/// Corresponds to [s2n_psk_free].
157+
fn drop(&mut self) {
158+
// ignore failures. There isn't anything to be done to handle them, but
159+
// allowing the program to continue is preferable to crashing.
160+
let _ = unsafe { s2n_psk_free(&mut self.ptr.as_ptr()).into_result() };
161+
}
162+
}
163+
164+
#[cfg(test)]
165+
mod tests {
166+
use crate::{config::Config, error::ErrorSource, security::DEFAULT_TLS13, testing::TestPair};
167+
168+
use super::*;
169+
170+
/// `identity`, `secret`, and `hmac` are all required fields. If any of them
171+
/// aren't set, then `psk.build()` operation should fail.
172+
#[test]
173+
fn build_errors() -> Result<(), crate::error::Error> {
174+
const PERMUTATIONS: u8 = 0b111;
175+
176+
for permutation in 0..PERMUTATIONS {
177+
let mut psk = Builder::new()?;
178+
if permutation & 0b001 != 0 {
179+
psk.set_identity(b"Alice")?;
180+
}
181+
if permutation & 0b010 != 0 {
182+
psk.set_secret(b"Rabbits don't actually jump. They instead push the world down")?;
183+
}
184+
if permutation & 0b100 != 0 {
185+
psk.set_hmac(PskHmac::SHA384)?;
186+
}
187+
assert!(psk.build().is_err());
188+
}
189+
Ok(())
190+
}
191+
192+
//= https://www.rfc-editor.org/rfc/rfc9257.html#section-6
193+
//= type=test
194+
//# Each PSK ... MUST be at least 128 bits long
195+
#[test]
196+
fn psk_secret_must_be_at_least_128_bits() -> Result<(), crate::error::Error> {
197+
// 120 bit key
198+
let secret = vec![5; 15];
199+
200+
let mut psk = Builder::new()?;
201+
let err = psk.set_secret(&secret).unwrap_err();
202+
assert_eq!(err.source(), ErrorSource::Bindings);
203+
assert_eq!(err.kind(), ErrorType::UsageError);
204+
assert_eq!(err.name(), "invalid psk secret");
205+
assert_eq!(err.message(), "PSK secret must be at least 128 bits");
206+
Ok(())
207+
}
208+
209+
const TEST_PSK_IDENTITY: &[u8] = b"alice";
210+
211+
fn test_psk() -> Psk {
212+
let mut builder = Psk::builder().unwrap();
213+
builder.set_identity(TEST_PSK_IDENTITY).unwrap();
214+
builder
215+
.set_secret(b"contrary to popular belief, the moon is yogurt, not cheese")
216+
.unwrap();
217+
builder.set_hmac(PskHmac::SHA384).unwrap();
218+
builder.build().unwrap()
219+
}
220+
221+
/// A PSK handshake using the basic "append_psk" workflow should complete
222+
/// successfully, and the correct negotiated psk identity should be returned.
223+
#[test]
224+
fn psk_handshake() -> Result<(), crate::error::Error> {
225+
let psk = test_psk();
226+
let mut config = Config::builder();
227+
config.set_security_policy(&DEFAULT_TLS13)?;
228+
let config = config.build()?;
229+
let mut test_pair = TestPair::from_config(&config);
230+
test_pair.client.append_psk(&psk)?;
231+
test_pair.server.append_psk(&psk)?;
232+
assert!(test_pair.handshake().is_ok());
233+
234+
for peer in [test_pair.client, test_pair.server] {
235+
let mut identity_buffer = [0; TEST_PSK_IDENTITY.len()];
236+
assert_eq!(
237+
peer.negotiated_psk_identity_length()?,
238+
TEST_PSK_IDENTITY.len()
239+
);
240+
peer.negotiated_psk_identity(&mut identity_buffer)?;
241+
assert_eq!(identity_buffer, TEST_PSK_IDENTITY);
242+
}
243+
Ok(())
244+
}
245+
}

0 commit comments

Comments
 (0)