Skip to content

Commit 39c7dae

Browse files
committed
clean up sstream
1 parent 9c679a9 commit 39c7dae

File tree

5 files changed

+91
-66
lines changed

5 files changed

+91
-66
lines changed

src/error.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,12 @@
22
pub enum Error {
33
#[error("Error from `snow`: {0}")]
44
Snow(#[from] snow::Error),
5+
#[error("Error from `crypto_secretstream`: {0}")]
6+
SecretStream(crypto_secretstream::aead::Error),
7+
}
8+
9+
impl From<crypto_secretstream::aead::Error> for Error {
10+
fn from(value: crypto_secretstream::aead::Error) -> Self {
11+
Error::SecretStream(value)
12+
}
513
}

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ mod message;
125125
mod mqueue;
126126
mod noise;
127127
mod protocol;
128-
mod sstream;
128+
pub mod sstream;
129129
#[cfg(test)]
130130
mod test_utils;
131131
mod util;

src/noise.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,7 @@ mod test {
514514
panic!()
515515
}
516516
#[tokio::test]
517-
async fn encrypted() -> Result<()> {
517+
async fn encrypted_one() -> Result<()> {
518518
let hello = b"hello".to_vec();
519519
let world = b"world".to_vec();
520520
let (lc, rc) = create_result_connected();

src/sstream.rs

Lines changed: 80 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,42 @@
1-
#![allow(dead_code)]
1+
//! Create a sodium secret stream using the IK pattern
22
use crypto_secretstream::{Header, Key, PullStream, PushStream, Tag};
33
use rand::rngs::OsRng;
44
use snow::{params::NoiseParams, Builder, HandshakeState};
5+
use std::fmt::Debug;
56

67
use crate::{crypto::write_stream_id, Error};
78

89
const PARAMS: &str = "Noise_IK_25519_ChaChaPoly_BLAKE2b";
910
const STREAM_ID_LENGTH: usize = 32;
1011
const RAW_HEADER_MSG_LEN: usize = STREAM_ID_LENGTH + Header::BYTES;
1112
const SNOW_CIPHERKEYLEN: usize = 32;
13+
const PUBLIC_KEYLEN: usize = 32;
1214

13-
struct InitiatorConfig {
14-
remote_public_key: [u8; 32],
15+
#[derive(Debug)]
16+
/// Data for creating an initiator
17+
pub struct InitiatorConfig {
18+
remote_public_key: [u8; PUBLIC_KEYLEN],
1519
}
20+
1621
impl InitiatorConfig {
17-
fn new(remote_public_key: [u8; 32]) -> Self {
22+
/// Create a new [`InitiatorConfig`]
23+
pub fn new(remote_public_key: [u8; PUBLIC_KEYLEN]) -> Self {
1824
Self { remote_public_key }
1925
}
2026
}
2127

22-
struct IkSecretStream<Step> {
28+
#[derive(Debug)]
29+
/// Secret Stream protocol state
30+
pub struct IkSecretStream<Step> {
2331
is_initiator: bool,
2432
state: HandshakeState,
2533
msg_buf: [u8; 1024],
2634
_step: Step,
2735
}
2836

2937
impl<Step> IkSecretStream<Step> {
30-
// split handshake into (tx, rx)
31-
fn split_handshake(&mut self) -> ([u8; SNOW_CIPHERKEYLEN], [u8; SNOW_CIPHERKEYLEN]) {
38+
/// split handshake into (tx, rx)
39+
pub fn split_handshake(&mut self) -> ([u8; SNOW_CIPHERKEYLEN], [u8; SNOW_CIPHERKEYLEN]) {
3240
let (a, b) = self.state.dangerously_get_raw_split();
3341
if self.is_initiator {
3442
(a, b)
@@ -38,27 +46,51 @@ impl<Step> IkSecretStream<Step> {
3846
}
3947
}
4048

41-
struct InitiatorInitial;
42-
struct ResponderInitial;
43-
struct InitiatorInitialSent;
44-
struct ResponderReplied {
49+
/// Initial initiator state
50+
#[derive(Debug)]
51+
pub struct InitiatorInitial;
52+
53+
/// Initial responder state
54+
#[derive(Debug)]
55+
pub struct ResponderInitial;
56+
57+
/// Initiator has sent the first message
58+
#[derive(Debug)]
59+
pub struct InitiatorInitialSent;
60+
61+
/// No decryptor yet
62+
pub struct EncryptorReady {
4563
rx: Key,
4664
pusher: PushStream,
4765
handshake_hash: Vec<u8>,
4866
}
4967

50-
struct InitiatorEnc {
51-
pusher: PushStream,
52-
rx: Key,
53-
handshake_hash: Vec<u8>,
54-
}
55-
struct Ready {
68+
/// Encryptor and decryptor
69+
pub struct Ready {
5670
puller: PullStream,
5771
pusher: PushStream,
5872
}
73+
impl Debug for EncryptorReady {
74+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75+
f.debug_struct("InitiatorEnc")
76+
.field("rx", &"Key(..)")
77+
.field("pusher", &"PushStream(..)")
78+
.field("handshake_hash", &self.handshake_hash)
79+
.finish()
80+
}
81+
}
82+
impl Debug for Ready {
83+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84+
f.debug_struct("Ready")
85+
.field("pusher", &"PushStream(..)")
86+
.field("puller", &"PullStream(..)")
87+
.finish()
88+
}
89+
}
5990

6091
impl IkSecretStream<InitiatorInitial> {
61-
fn new_initiator(config: InitiatorConfig) -> Result<Self, Error> {
92+
/// Create an initiator of a secret stream
93+
pub fn new_initiator(config: InitiatorConfig) -> Result<Self, Error> {
6294
let params: NoiseParams = PARAMS.parse().expect("known to work");
6395
let kp = Builder::new(params.clone()).generate_keypair()?;
6496
let state = Builder::new(params.clone())
@@ -74,7 +106,8 @@ impl IkSecretStream<InitiatorInitial> {
74106
})
75107
}
76108

77-
fn make_first_msg(
109+
/// Create the first message the initiator sends to the responder
110+
pub fn make_first_msg(
78111
mut self,
79112
prologue: &[u8],
80113
) -> Result<(IkSecretStream<InitiatorInitialSent>, Vec<u8>), Error> {
@@ -99,7 +132,8 @@ impl IkSecretStream<InitiatorInitial> {
99132
}
100133

101134
impl IkSecretStream<ResponderInitial> {
102-
fn new_responder(private: &[u8]) -> Result<Self, Error> {
135+
/// Create a responder of a secret stream
136+
pub fn new_responder(private: &[u8]) -> Result<Self, Error> {
103137
let params: NoiseParams = PARAMS.parse().expect("known to work");
104138
let state = Builder::new(params.clone())
105139
.local_private_key(&private)?
@@ -112,10 +146,11 @@ impl IkSecretStream<ResponderInitial> {
112146
})
113147
}
114148

115-
fn read_first_msg(
149+
/// Read the first message of the protocol, create the next two messages to send to the initiator.
150+
pub fn read_first_msg(
116151
mut self,
117152
msg: &[u8],
118-
) -> Result<(IkSecretStream<ResponderReplied>, [Vec<u8>; 2]), Error> {
153+
) -> Result<(IkSecretStream<EncryptorReady>, [Vec<u8>; 2]), Error> {
119154
self.state.read_message(msg, &mut self.msg_buf)?;
120155
let len = self.state.write_message(&[], &mut self.msg_buf)?;
121156
let hs_msg = self.msg_buf[..len].to_vec();
@@ -147,7 +182,7 @@ impl IkSecretStream<ResponderInitial> {
147182
is_initiator,
148183
state,
149184
msg_buf,
150-
_step: ResponderReplied {
185+
_step: EncryptorReady {
151186
rx: Key::from(rx),
152187
pusher,
153188
handshake_hash,
@@ -159,7 +194,11 @@ impl IkSecretStream<ResponderInitial> {
159194
}
160195

161196
impl IkSecretStream<InitiatorInitialSent> {
162-
fn receive_msg(mut self, msg: &[u8]) -> Result<(IkSecretStream<InitiatorEnc>, Vec<u8>), Error> {
197+
/// Recieve the last message to complet the handsake
198+
pub fn receive_msg(
199+
mut self,
200+
msg: &[u8],
201+
) -> Result<(IkSecretStream<EncryptorReady>, Vec<u8>), Error> {
163202
self.state.read_message(msg, &mut self.msg_buf)?;
164203

165204
let (tx, rx) = self.split_handshake();
@@ -191,7 +230,7 @@ impl IkSecretStream<InitiatorInitialSent> {
191230
is_initiator,
192231
state,
193232
msg_buf,
194-
_step: InitiatorEnc {
233+
_step: EncryptorReady {
195234
pusher,
196235
rx: Key::from(rx),
197236
handshake_hash,
@@ -201,12 +240,13 @@ impl IkSecretStream<InitiatorInitialSent> {
201240
))
202241
}
203242
}
204-
impl IkSecretStream<InitiatorEnc> {
205-
fn receive_msg(self, msg: &[u8]) -> Result<IkSecretStream<Ready>, Error> {
243+
impl IkSecretStream<EncryptorReady> {
244+
/// Recieve message the last message, used to set up the decryption stream
245+
pub fn receive_msg(self, msg: &[u8]) -> Result<IkSecretStream<Ready>, Error> {
206246
let Self {
207247
is_initiator,
208248
_step:
209-
InitiatorEnc {
249+
EncryptorReady {
210250
pusher,
211251
rx,
212252
handshake_hash,
@@ -217,11 +257,12 @@ impl IkSecretStream<InitiatorEnc> {
217257
// Read the received message from the other peer
218258
let mut expected_stream_id: [u8; STREAM_ID_LENGTH] = [0; STREAM_ID_LENGTH];
219259
write_stream_id(&handshake_hash, !is_initiator, &mut expected_stream_id);
220-
if expected_stream_id != msg[..32] {
260+
if expected_stream_id != msg[..STREAM_ID_LENGTH] {
221261
panic!()
222262
}
223263

224-
let header: [u8; 24] = msg[32..].try_into().expect("TODO wrong size");
264+
let header: [u8; Header::BYTES] =
265+
msg[STREAM_ID_LENGTH..].try_into().expect("TODO wrong size");
225266
let puller = PullStream::init(header.into(), &rx);
226267
Ok(IkSecretStream {
227268
is_initiator,
@@ -232,42 +273,18 @@ impl IkSecretStream<InitiatorEnc> {
232273
}
233274
}
234275

235-
impl IkSecretStream<ResponderReplied> {
236-
fn receive_msg(self, msg: &[u8]) -> Result<IkSecretStream<Ready>, Error> {
237-
let Self {
238-
is_initiator,
239-
_step:
240-
ResponderReplied {
241-
pusher,
242-
rx,
243-
handshake_hash,
244-
},
245-
state,
246-
msg_buf,
247-
} = self;
248-
// Read the received message from the other peer
249-
let mut expected_stream_id: [u8; STREAM_ID_LENGTH] = [0; STREAM_ID_LENGTH];
250-
write_stream_id(&handshake_hash, !is_initiator, &mut expected_stream_id);
251-
if expected_stream_id != msg[..32] {
252-
panic!()
253-
}
254-
255-
let header: [u8; 24] = msg[32..].try_into().expect("TODO wrong size");
256-
let puller = PullStream::init(header.into(), &rx);
257-
Ok(IkSecretStream {
258-
is_initiator,
259-
state,
260-
msg_buf,
261-
_step: Ready { puller, pusher },
262-
})
263-
}
264-
}
265-
266276
impl IkSecretStream<Ready> {
267-
fn push(&mut self, msg: &mut Vec<u8>, associated_data: &[u8], tag: Tag) -> Result<(), Error> {
277+
/// Encrypt a message in place
278+
pub fn push(
279+
&mut self,
280+
msg: &mut Vec<u8>,
281+
associated_data: &[u8],
282+
tag: Tag,
283+
) -> Result<(), Error> {
268284
Ok(self._step.pusher.push(msg, associated_data, tag)?)
269285
}
270-
fn pull(&mut self, msg: &mut Vec<u8>, associated_data: &[u8]) -> Result<Tag, Error> {
286+
/// Decrypt a message in place
287+
pub fn pull(&mut self, msg: &mut Vec<u8>, associated_data: &[u8]) -> Result<Tag, Error> {
271288
Ok(self._step.puller.pull(msg, associated_data)?)
272289
}
273290
}

src/test_utils.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ pub(crate) fn log() {
8787
.with_bracketed_fields(true)
8888
.with_indent_lines(true)
8989
.with_thread_ids(false)
90-
.with_thread_names(true)
90+
//.with_thread_names(true)
9191
//.with_span_modes(true)
9292
;
9393

0 commit comments

Comments
 (0)