use std::fmt;
use anyhow::{anyhow, bail, Context, Result};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use sha2::{Digest, Sha256};
use x25519_dalek::{PublicKey, StaticSecret};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Suite {
#[default]
ChaChaPoly,
AesGcm,
}
impl Suite {
pub const ALL: [Suite; 2] = [Suite::ChaChaPoly, Suite::AesGcm];
pub const fn wire_name(self) -> &'static str {
match self {
Suite::ChaChaPoly => "25519_ChaChaPoly_SHA256",
Suite::AesGcm => "25519_AESGCM_SHA256",
}
}
pub const fn params(self) -> &'static str {
match self {
Suite::ChaChaPoly => "Noise_KKpsk2_25519_ChaChaPoly_SHA256",
Suite::AesGcm => "Noise_KKpsk2_25519_AESGCM_SHA256",
}
}
pub fn from_wire_name(name: &str) -> Option<Suite> {
Suite::ALL
.into_iter()
.find(|suite| suite.wire_name() == name)
}
}
impl fmt::Display for Suite {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.wire_name())
}
}
pub const NOISE_PARAMS: &str = Suite::ChaChaPoly.params();
pub const SENTINEL_PSK: [u8; 32] = [
0x1b, 0x5e, 0x24, 0xdb, 0xc1, 0xae, 0xd9, 0x5f, 0xc2, 0xa5, 0xa3, 0x38, 0xa9, 0x0c, 0x05, 0xdf,
0x44, 0xbd, 0x10, 0xf5, 0xec, 0x1f, 0x4c, 0xd6, 0x6c, 0xbf, 0x86, 0x27, 0x27, 0x67, 0xb9, 0xd3,
];
pub const SENTINEL_PSK_ID: &str = "GFsV9tLaSQm9HcFWpKsgYQOr7wFTvNUtkmFwuVz3zoo";
pub const MAX_MESSAGE_LEN: usize = 65_535;
pub const TAG_LEN: usize = 16;
pub const MAX_PLAINTEXT_LEN: usize = MAX_MESSAGE_LEN - TAG_LEN;
const PSK_ID_LABEL: &[u8] = b"sendspin-psk-id-v1";
const HANDSHAKE_MESSAGE_2: &[u8] = b"{}";
const KEY_CHARS: usize = 43;
pub fn psk_id_for(psk: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(PSK_ID_LABEL);
hasher.update(psk);
URL_SAFE_NO_PAD.encode(hasher.finalize())
}
#[derive(Clone, Copy)]
pub struct Identity {
pub public: [u8; 32],
pub secret: [u8; 32],
}
impl Identity {
pub fn generate() -> Identity {
let params = NOISE_PARAMS
.parse()
.expect("NOISE_PARAMS is a valid Noise protocol name");
let keypair = snow::Builder::new(params)
.generate_keypair()
.expect("the operating system CSPRNG is available");
let secret: [u8; 32] = keypair
.private
.as_slice()
.try_into()
.expect("an X25519 secret key is 32 bytes");
Identity::from_secret(secret)
}
pub fn from_secret_base64(s: &str) -> Result<Identity> {
let secret = decode_key(s).ok_or_else(|| {
anyhow!("identity secret is not a canonical 43-character unpadded base64url X25519 key")
})?;
Ok(Identity::from_secret(secret))
}
pub fn public_base64(&self) -> String {
URL_SAFE_NO_PAD.encode(self.public)
}
pub fn secret_base64(&self) -> String {
URL_SAFE_NO_PAD.encode(self.secret)
}
fn from_secret(secret: [u8; 32]) -> Identity {
Identity {
public: public_key_for(&secret),
secret,
}
}
fn validate(&self) -> Result<()> {
if public_key_for(&self.secret) != self.public {
bail!("identity public key does not match its secret key");
}
Ok(())
}
}
impl fmt::Debug for Identity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Identity")
.field("public", &self.public_base64())
.field("secret", &"<redacted>")
.finish()
}
}
pub struct Responder {
handshake: snow::HandshakeState,
suite: Suite,
}
impl Responder {
pub fn new(identity: &Identity, prologue: &[u8]) -> Result<Responder> {
let peer_public = initiator_key_from_prologue(prologue)?;
let suite = suite_from_prologue(prologue)?;
Responder::with_peer_suite(identity, &peer_public, suite, prologue)
}
pub fn with_suite(identity: &Identity, suite: Suite, prologue: &[u8]) -> Result<Responder> {
let peer_public = initiator_key_from_prologue(prologue)?;
let announced = suite_from_prologue(prologue)?;
if announced != suite {
bail!(
"the `client/init` in the prologue announces the cipher suite `{announced}`, so \
this handshake cannot run `{suite}`; a suite the peer did not announce is \
refused, never substituted"
);
}
Responder::with_peer_suite(identity, &peer_public, suite, prologue)
}
pub fn with_peer(
identity: &Identity,
peer_public: &[u8; 32],
prologue: &[u8],
) -> Result<Responder> {
Responder::with_peer_suite(identity, peer_public, Suite::default(), prologue)
}
pub fn with_peer_suite(
identity: &Identity,
peer_public: &[u8; 32],
suite: Suite,
prologue: &[u8],
) -> Result<Responder> {
identity.validate()?;
debug_assert_eq!(psk_id_for(&SENTINEL_PSK), SENTINEL_PSK_ID);
let params = suite
.params()
.parse()
.context("failed to parse the Noise protocol parameters")?;
let handshake = snow::Builder::new(params)
.local_private_key(&identity.secret)
.context("failed to set the local static key")?
.remote_public_key(peer_public)
.context("failed to set the peer static key")?
.psk(2, &SENTINEL_PSK)
.context("failed to set the handshake PSK")?
.prologue(prologue)
.context("failed to set the Noise prologue")?
.build_responder()
.context("failed to build the Noise responder")?;
Ok(Responder { handshake, suite })
}
pub fn suite(&self) -> Suite {
self.suite
}
pub fn set_psk(&mut self, psk: &[u8; 32]) -> Result<()> {
self.handshake
.set_psk(2, psk)
.context("failed to set the Noise handshake PSK")
}
pub fn read_message(&mut self, msg: &[u8]) -> Result<Vec<u8>> {
read_handshake_payload(&mut self.handshake, msg)
}
pub fn write_message(&mut self) -> Result<Vec<u8>> {
write_handshake_payload(&mut self.handshake, HANDSHAKE_MESSAGE_2)
}
pub fn handshake_finished(&self) -> bool {
self.handshake.is_handshake_finished()
}
pub fn into_transport(self) -> Result<TransportState> {
transport_from(self.handshake, self.suite)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PskOutcome {
SelectedKey,
SentinelFallback,
}
pub struct Initiator {
handshake: snow::HandshakeState,
suite: Suite,
selected_non_sentinel: bool,
}
impl Initiator {
pub fn new(
identity: &Identity,
peer_public: &[u8; 32],
suite: Suite,
prologue: &[u8],
) -> Result<Initiator> {
if let Some(announced) = announced_suite_from_prologue(prologue)? {
if announced != suite {
bail!(
"the `client/init` in the prologue announces the cipher suite `{announced}`, \
so this handshake cannot run `{suite}`; the suite a peer announced is \
refused when it differs, never substituted"
);
}
}
Initiator::build(identity, peer_public, suite, prologue)
}
pub fn with_announced_suite(
identity: &Identity,
peer_public: &[u8; 32],
prologue: &[u8],
) -> Result<Initiator> {
let suite = suite_from_prologue(prologue)?;
Initiator::build(identity, peer_public, suite, prologue)
}
fn build(
identity: &Identity,
peer_public: &[u8; 32],
suite: Suite,
prologue: &[u8],
) -> Result<Initiator> {
identity.validate()?;
debug_assert_eq!(psk_id_for(&SENTINEL_PSK), SENTINEL_PSK_ID);
let params = suite
.params()
.parse()
.context("failed to parse the Noise protocol parameters")?;
let handshake = snow::Builder::new(params)
.local_private_key(&identity.secret)
.context("failed to set the local static key")?
.remote_public_key(peer_public)
.context("failed to set the peer static key")?
.psk(2, &SENTINEL_PSK)
.context("failed to set the handshake PSK")?
.prologue(prologue)
.context("failed to set the Noise prologue")?
.build_initiator()
.context("failed to build the Noise initiator")?;
Ok(Initiator {
handshake,
suite,
selected_non_sentinel: false,
})
}
pub fn suite(&self) -> Suite {
self.suite
}
pub fn set_psk(&mut self, psk: &[u8; 32]) -> Result<()> {
self.handshake
.set_psk(2, psk)
.context("failed to set the Noise handshake PSK")?;
self.selected_non_sentinel = psk != &SENTINEL_PSK;
Ok(())
}
pub fn write_message(&mut self, payload: &[u8]) -> Result<Vec<u8>> {
write_handshake_payload(&mut self.handshake, payload)
}
pub fn read_message(&mut self, msg: &[u8]) -> Result<Vec<u8>> {
read_handshake_payload(&mut self.handshake, msg)
}
pub fn read_message_with_sentinel(&mut self, msg: &[u8]) -> Result<(PskOutcome, Vec<u8>)> {
if !self.selected_non_sentinel {
bail!(
"the selected PSK is the Sentinel key, so a failed read cannot be retried under \
the Sentinel key"
);
}
ensure_message_len(msg.len(), "handshake message")?;
let mut payload = vec![0u8; plaintext_capacity(msg.len(), "handshake message")?];
match self.handshake.read_message(msg, &mut payload) {
Ok(len) => {
payload.truncate(len);
return Ok((PskOutcome::SelectedKey, payload));
}
Err(error) if should_retry_under_sentinel(&error) => {}
Err(error) => return Err(error).context("failed to read the Noise handshake message"),
}
self.handshake
.set_psk(2, &SENTINEL_PSK)
.context("failed to set the Noise handshake PSK")?;
let len = self
.handshake
.read_message(msg, &mut payload)
.context("failed to read the Noise handshake message under the Sentinel key")?;
payload.truncate(len);
Ok((PskOutcome::SentinelFallback, payload))
}
pub fn handshake_finished(&self) -> bool {
self.handshake.is_handshake_finished()
}
pub fn into_transport(self) -> Result<TransportState> {
transport_from(self.handshake, self.suite)
}
}
fn read_handshake_payload(handshake: &mut snow::HandshakeState, msg: &[u8]) -> Result<Vec<u8>> {
ensure_message_len(msg.len(), "handshake message")?;
let mut payload = vec![0u8; plaintext_capacity(msg.len(), "handshake message")?];
let len = handshake
.read_message(msg, &mut payload)
.context("failed to read the Noise handshake message")?;
payload.truncate(len);
Ok(payload)
}
fn should_retry_under_sentinel(error: &snow::Error) -> bool {
matches!(error, snow::Error::Decrypt)
}
fn write_handshake_payload(
handshake: &mut snow::HandshakeState,
payload: &[u8],
) -> Result<Vec<u8>> {
let mut message = vec![0u8; MAX_MESSAGE_LEN];
let len = handshake
.write_message(payload, &mut message)
.context("failed to write the Noise handshake message")?;
message.truncate(len);
Ok(message)
}
fn transport_from(handshake: snow::HandshakeState, suite: Suite) -> Result<TransportState> {
let handshake_hash: [u8; 32] = handshake
.get_handshake_hash()
.try_into()
.context("the Noise handshake hash is not 32 bytes")?;
let state = handshake
.into_transport_mode()
.context("failed to finish the Noise handshake")?;
Ok(TransportState {
state,
handshake_hash,
suite,
})
}
pub struct TransportState {
state: snow::TransportState,
handshake_hash: [u8; 32],
suite: Suite,
}
impl TransportState {
pub fn suite(&self) -> Suite {
self.suite
}
pub fn handshake_hash(&self) -> &[u8; 32] {
&self.handshake_hash
}
pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>> {
ensure_plaintext_len(plaintext.len())?;
let mut message = vec![0u8; plaintext.len() + TAG_LEN];
let len = self
.state
.write_message(plaintext, &mut message)
.context("failed to encrypt the Noise transport message")?;
message.truncate(len);
Ok(message)
}
pub fn decrypt(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>> {
ensure_message_len(ciphertext.len(), "transport message")?;
let mut plaintext = vec![0u8; plaintext_capacity(ciphertext.len(), "transport message")?];
let len = self
.state
.read_message(ciphertext, &mut plaintext)
.context("failed to decrypt the Noise transport message")?;
plaintext.truncate(len);
Ok(plaintext)
}
}
fn initiator_key_from_prologue(prologue: &[u8]) -> Result<[u8; 32]> {
let mut server_id = None;
for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
{
let document = document.context("the prologue is not a sequence of JSON documents")?;
if document.get("type").and_then(serde_json::Value::as_str) != Some("server/init") {
continue;
}
if server_id.is_some() {
bail!("the prologue contains more than one `server/init` document");
}
let id = document
.pointer("/payload/server_id")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
anyhow!("the `server/init` document carries no string `payload.server_id`")
})?;
server_id = Some(decode_key(id).ok_or_else(|| {
anyhow!("`server_id` is not a canonical 43-character unpadded base64url X25519 key")
})?);
}
server_id.ok_or_else(|| {
anyhow!(
"the prologue contains no `server/init` document with a `server_id`, so the \
initiator's static public key is unknown; pass it with `Responder::with_peer`"
)
})
}
fn public_key_for(secret: &[u8; 32]) -> [u8; 32] {
PublicKey::from(&StaticSecret::from(*secret)).to_bytes()
}
fn suite_from_prologue(prologue: &[u8]) -> Result<Suite> {
let mut announced = None;
for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
{
let document = document.context("the prologue is not a sequence of JSON documents")?;
if let Some(suite) = client_init_suite(&document)? {
if announced.is_some() {
bail!("the prologue contains more than one `client/init` document");
}
announced = Some(suite);
}
}
announced.ok_or_else(|| {
anyhow!(
"the prologue contains no `client/init` document with a `suite`, so the cipher suite \
is unknown; a first handshake needs the init exchange, pass the suite with \
`Responder::with_peer_suite` on a re-handshake"
)
})
}
fn announced_suite_from_prologue(prologue: &[u8]) -> Result<Option<Suite>> {
let mut announced = None;
for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
{
let Ok(document) = document else {
return Ok(None);
};
if let Some(suite) = client_init_suite(&document)? {
if announced.is_some() {
bail!("the prologue contains more than one `client/init` document");
}
announced = Some(suite);
}
}
Ok(announced)
}
fn client_init_suite(document: &serde_json::Value) -> Result<Option<Suite>> {
if document.get("type").and_then(serde_json::Value::as_str) != Some("client/init") {
return Ok(None);
}
let name = document
.pointer("/payload/suite")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
anyhow!(
"the `client/init` document carries no string `payload.suite`; the cipher suite \
is required and is not assumed to be `{}`",
Suite::default()
)
})?;
Ok(Some(Suite::from_wire_name(name).ok_or_else(|| {
anyhow!(
"the `client/init` document announces the cipher suite `{name}`, which this build \
does not have; it supports {}",
Suite::ALL
.map(Suite::wire_name)
.map(|name| format!("`{name}`"))
.join(", ")
)
})?))
}
fn ensure_message_len(len: usize, what: &str) -> Result<()> {
if len > MAX_MESSAGE_LEN {
bail!(
"Noise {what} is {len} bytes, exceeding the maximum Noise message size of \
{MAX_MESSAGE_LEN} bytes"
);
}
Ok(())
}
fn ensure_plaintext_len(len: usize) -> Result<()> {
if len > MAX_PLAINTEXT_LEN {
bail!(
"plaintext is {len} bytes, exceeding the maximum Noise plaintext size of \
{MAX_PLAINTEXT_LEN} bytes (a {MAX_MESSAGE_LEN}-byte message including the \
{TAG_LEN}-byte tag); payloads are not fragmented at this layer"
);
}
Ok(())
}
fn plaintext_capacity(len: usize, what: &str) -> Result<usize> {
len.checked_sub(TAG_LEN).ok_or_else(|| {
anyhow!("Noise {what} is {len} bytes, shorter than the {TAG_LEN}-byte authentication tag")
})
}
fn decode_key(value: &str) -> Option<[u8; 32]> {
if value.len() != KEY_CHARS {
return None;
}
let bytes = URL_SAFE_NO_PAD.decode(value).ok()?;
if bytes.len() != 32 || URL_SAFE_NO_PAD.encode(&bytes) != value {
return None;
}
bytes.try_into().ok()
}
#[cfg(test)]
mod tests {
use super::*;
const CLIENT_INIT: &[u8] =
br#"{"type":"client/init","payload":{"client_id":"test-client","version":1}}"#;
fn server_init(server_id: &str) -> Vec<u8> {
format!(r#"{{"type":"server/init","payload":{{"server_id":"{server_id}","version":1}}}}"#)
.into_bytes()
}
fn prologue(server_id: &str) -> Vec<u8> {
let mut bytes = CLIENT_INIT.to_vec();
bytes.extend_from_slice(&server_init(server_id));
bytes
}
const TEST_PROLOGUE: &[u8] = b"client/init{}server/init{}";
const RECORD_PSK: [u8; 32] = [0x11; 32];
const MESSAGE_1_PAYLOAD: &[u8] = br#"{"psk_id":"test","psk_category":"sn"}"#;
fn peer_responder(
client: &Identity,
server: &Identity,
psk: &[u8; 32],
) -> snow::HandshakeState {
snow::Builder::new(
Suite::ChaChaPoly
.params()
.parse()
.expect("valid Noise parameters"),
)
.local_private_key(&client.secret)
.expect("set the local static key")
.remote_public_key(&server.public)
.expect("set the peer static key")
.psk(2, psk)
.expect("set the handshake PSK")
.prologue(TEST_PROLOGUE)
.expect("set the Noise prologue")
.build_responder()
.expect("build the Noise responder")
}
fn peer_write(peer: &mut snow::HandshakeState, payload: &[u8]) -> Vec<u8> {
let mut message = vec![0u8; MAX_MESSAGE_LEN];
let len = peer
.write_message(payload, &mut message)
.expect("write a Noise handshake message");
message.truncate(len);
message
}
fn peer_read(peer: &mut snow::HandshakeState, message: &[u8]) -> Vec<u8> {
let mut payload = vec![0u8; MAX_MESSAGE_LEN];
let len = peer
.read_message(message, &mut payload)
.expect("read a Noise handshake message");
payload.truncate(len);
payload
}
fn handshake_after_message_1(
initiator_psk: &[u8; 32],
peer_psk: &[u8; 32],
) -> (Initiator, snow::HandshakeState) {
let server = Identity::generate();
let client = Identity::generate();
let mut initiator =
Initiator::new(&server, &client.public, Suite::ChaChaPoly, TEST_PROLOGUE)
.expect("build the initiator");
initiator
.set_psk(initiator_psk)
.expect("select the initiator PSK");
let mut peer = peer_responder(&client, &server, peer_psk);
let message_1 = initiator
.write_message(MESSAGE_1_PAYLOAD)
.expect("write message 1");
assert_eq!(
peer_read(&mut peer, &message_1),
MESSAGE_1_PAYLOAD,
"message 1 must reach the peer whichever key each side selected"
);
(initiator, peer)
}
#[test]
fn the_prologue_carries_the_initiator_static_key() {
let identity = Identity::generate();
let key = initiator_key_from_prologue(&prologue(&identity.public_base64()))
.expect("server/init carries server_id");
assert_eq!(key, identity.public);
}
#[test]
fn a_prologue_without_a_server_init_is_rejected() {
let identity = Identity::generate();
for prologue in [&b""[..], CLIENT_INIT] {
let result = Responder::new(&identity, prologue);
assert!(
result.is_err(),
"a prologue without server/init must be rejected"
);
let err = result.err().expect("the rejection was asserted");
let message = format!("{err:#}");
assert!(
message.contains("server_id") && message.contains("with_peer"),
"error should name the missing key and the way out, got: {message}"
);
}
let result = Responder::new(&identity, b"not json at all");
assert!(
result.is_err(),
"a prologue that is not JSON must be rejected"
);
let err = result.err().expect("the rejection was asserted");
assert!(
format!("{err:#}").contains("prologue is not a sequence of JSON documents"),
"error should name the malformed prologue, got: {err:#}"
);
}
#[test]
fn prologue_with_duplicate_server_id_is_rejected() {
let identity = Identity::generate();
let first = Identity::generate().public_base64();
let second = Identity::generate().public_base64();
let mut prologue = prologue(&first);
prologue.extend_from_slice(&server_init(&second));
let result = Responder::new(&identity, &prologue);
assert!(result.is_err(), "two server/init documents are ambiguous");
let err = result.err().expect("the rejection was asserted");
assert!(
format!("{err:#}").contains("more than one `server/init`"),
"error should name the duplicate, got: {err:#}"
);
}
#[test]
fn an_identity_mismatch_is_rejected_before_the_handshake() {
let mut identity = Identity::generate();
identity.public = Identity::generate().public;
let prologue = prologue(&Identity::generate().public_base64());
let result = Responder::with_peer(&identity, &[0u8; 32], &prologue);
assert!(result.is_err(), "a mismatched identity must be rejected");
let err = result.err().expect("the rejection was asserted");
assert!(
format!("{err:#}").contains("does not match"),
"error should name the mismatch, got: {err:#}"
);
}
#[test]
fn a_server_init_without_a_usable_server_id_is_rejected() {
let identity = Identity::generate();
let mut missing = CLIENT_INIT.to_vec();
missing.extend_from_slice(br#"{"type":"server/init","payload":{"version":1}}"#);
let result = Responder::new(&identity, &missing);
assert!(result.is_err(), "a server/init without server_id must fail");
assert!(
format!("{:#}", result.err().expect("the rejection was asserted"))
.contains("payload.server_id"),
"the error must name the missing field"
);
let mut wrong_type = CLIENT_INIT.to_vec();
wrong_type.extend_from_slice(br#"{"type":"server/init","payload":{"server_id":42}}"#);
let result = Responder::new(&identity, &wrong_type);
assert!(result.is_err(), "a non-string server_id must fail");
assert!(
format!("{:#}", result.err().expect("the rejection was asserted"))
.contains("payload.server_id")
);
}
#[test]
fn a_server_id_that_is_not_a_canonical_key_is_rejected() {
let identity = Identity::generate();
for server_id in ["short", &"!".repeat(43), &"a".repeat(43)] {
let result = Responder::new(&identity, &prologue(server_id));
assert!(
result.is_err(),
"{server_id:?} must not be accepted as a key"
);
let message = format!("{:#}", result.err().expect("the rejection was asserted"));
assert!(
message.contains("canonical 43-character"),
"the error must name the encoding, got: {message}"
);
}
let id = "A".repeat(43);
assert_eq!(
initiator_key_from_prologue(&prologue(&id)).expect("a canonical key is accepted"),
{
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
let bytes = URL_SAFE_NO_PAD.decode(&id).expect("the id is base64url");
let mut key = [0u8; 32];
key.copy_from_slice(&bytes);
key
}
);
}
#[test]
fn identity_debug_redacts_the_secret() {
let identity = Identity::generate();
let text = format!("{identity:?}");
assert!(text.contains(&identity.public_base64()));
assert!(!text.contains(&identity.secret_base64()));
assert!(text.contains("<redacted>"));
}
#[test]
fn a_failed_read_can_be_retried_with_another_psk() {
let (mut initiator, mut peer) = handshake_after_message_1(&RECORD_PSK, &SENTINEL_PSK);
let message_2 = peer_write(&mut peer, b"{}");
let error = initiator
.read_message(&message_2)
.expect_err("a message 2 sealed with the Sentinel key must not authenticate");
assert_eq!(
error.downcast_ref::<snow::Error>(),
Some(&snow::Error::Decrypt),
"a wrong PSK is an authentication failure, not a length or state failure"
);
let (outcome, payload) = initiator
.read_message_with_sentinel(&message_2)
.expect("the same bytes authenticate under the Sentinel key");
assert_eq!(outcome, PskOutcome::SentinelFallback);
assert_eq!(payload, b"{}");
assert!(initiator.handshake_finished());
let peer_hash = peer.get_handshake_hash().to_vec();
let mut ours = initiator.into_transport().expect("initiator transport");
assert_eq!(
ours.handshake_hash().to_vec(),
peer_hash,
"the retried handshake derived a hash the peer does not share"
);
let mut theirs = peer.into_transport_mode().expect("the peer's transport");
let ciphertext = ours.encrypt(b"from the initiator").expect("encrypt");
let mut plaintext = vec![0u8; MAX_MESSAGE_LEN];
let len = theirs
.read_message(&ciphertext, &mut plaintext)
.expect("the peer decrypts");
assert_eq!(&plaintext[..len], b"from the initiator");
let mut ciphertext = vec![0u8; MAX_MESSAGE_LEN];
let len = theirs
.write_message(b"from the responder", &mut ciphertext)
.expect("the peer encrypts");
assert_eq!(
ours.decrypt(&ciphertext[..len]).expect("decrypt"),
b"from the responder"
);
}
#[test]
fn a_successful_read_is_not_retried() {
let (mut initiator, mut peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
let message_2 = peer_write(&mut peer, b"{}");
let (outcome, payload) = initiator
.read_message_with_sentinel(&message_2)
.expect("message 2 authenticates under the selected key");
assert_eq!(outcome, PskOutcome::SelectedKey);
assert_eq!(payload, b"{}");
assert!(initiator.handshake_finished());
}
#[test]
fn a_successful_read_returns_a_foreign_payload() {
let (mut initiator, mut peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
let message_2 = peer_write(&mut peer, b"not-empty");
let (outcome, payload) = initiator
.read_message_with_sentinel(&message_2)
.expect("message 2 authenticates under the selected key");
assert_eq!(outcome, PskOutcome::SelectedKey);
assert_eq!(payload, b"not-empty");
}
#[test]
fn the_sentinel_key_cannot_be_the_selected_key() {
let server = Identity::generate();
let client = Identity::generate();
let mut initiator =
Initiator::new(&server, &client.public, Suite::ChaChaPoly, TEST_PROLOGUE)
.expect("build the initiator");
initiator
.set_psk(&SENTINEL_PSK)
.expect("the Sentinel key is a valid PSK");
let error = initiator
.read_message_with_sentinel(&[0u8; 4])
.expect_err("there is no second key to retry under");
let text = format!("{error:#}");
assert!(
text.contains("Sentinel"),
"the error must name the Sentinel key, got: {text}"
);
assert!(!initiator.handshake_finished());
}
#[test]
fn the_last_psk_write_wins() {
let server = Identity::generate();
let client = Identity::generate();
let mut initiator =
Initiator::new(&server, &client.public, Suite::ChaChaPoly, TEST_PROLOGUE)
.expect("build the initiator");
initiator
.set_psk(&RECORD_PSK)
.expect("select the record's key");
initiator
.set_psk(&SENTINEL_PSK)
.expect("select the Sentinel key again");
let error = initiator
.read_message_with_sentinel(&[0u8; 4])
.expect_err("the Sentinel key was the last write, so there is nothing to retry under");
assert!(
format!("{error:#}").contains("Sentinel"),
"the error must name the Sentinel key, got: {error:#}"
);
}
#[test]
fn only_a_decrypt_failure_is_retried() {
assert!(should_retry_under_sentinel(&snow::Error::Decrypt));
for error in [
snow::Error::Input,
snow::Error::Dh,
snow::Error::Rng,
snow::Error::State(snow::error::StateProblem::NotTurnToRead),
] {
assert!(
!should_retry_under_sentinel(&error),
"{error:?} is not an authentication failure and must not be retried"
);
}
}
#[test]
fn a_frame_shorter_than_the_tag_is_not_retried() {
let (mut initiator, _peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
let error = initiator
.read_message_with_sentinel(&[0u8; 12])
.expect_err("12 bytes cannot carry an authentication tag");
assert!(
error.downcast_ref::<snow::Error>().is_none(),
"the capacity guard, not snow, must reject a frame below the tag length"
);
assert!(
format!("{error:#}").contains("16-byte"),
"the error must name the tag length, got: {error:#}"
);
}
#[test]
fn a_frame_in_the_input_band_is_not_retried() {
let (mut initiator, _peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
let error = initiator
.read_message_with_sentinel(&[0u8; 20])
.expect_err("20 bytes cannot carry a message-2 ephemeral key");
assert_eq!(
error.downcast_ref::<snow::Error>(),
Some(&snow::Error::Input)
);
assert!(
!format!("{error:#}").contains("under the Sentinel key"),
"a frame in the input band must not reach the retry, got: {error:#}"
);
}
#[test]
fn a_truncated_tag_is_retried_and_still_fails() {
let (mut initiator, _peer) = handshake_after_message_1(&RECORD_PSK, &RECORD_PSK);
let error = initiator
.read_message_with_sentinel(&[0u8; 40])
.expect_err("a truncated tag must not authenticate");
assert_eq!(
error.downcast_ref::<snow::Error>(),
Some(&snow::Error::Decrypt)
);
}
}