Skip to main content

tentacle_secio/codec/
secure_stream.rs

1use bytes::{Buf, Bytes, BytesMut};
2use futures::{SinkExt, StreamExt};
3use log::{debug, trace};
4use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf};
5use tokio_util::codec::{Framed, length_delimited::LengthDelimitedCodec};
6
7use std::{
8    cmp::min,
9    io,
10    pin::Pin,
11    task::{Context, Poll},
12};
13
14use crate::{crypto::BoxStreamCipher, error::SecioError};
15
16/// Encrypted stream
17pub struct SecureStream<T> {
18    socket: Framed<T, LengthDelimitedCodec>,
19    decode_cipher: BoxStreamCipher,
20    encode_cipher: BoxStreamCipher,
21    /// denotes a sequence of bytes which are expected to be
22    /// found at the beginning of the stream and are checked for equality
23    nonce: Vec<u8>,
24    /// recv buffer
25    /// internal buffer for 'message too big'
26    ///
27    /// when the input buffer is not big enough to hold the entire
28    /// frame from the underlying Framed<>, the frame will be filled
29    /// into this buffer so that multiple following 'read' will eventually
30    /// get the message correctly
31    recv_buf: Bytes,
32}
33
34impl<T> SecureStream<T>
35where
36    T: AsyncRead + AsyncWrite + Unpin,
37{
38    /// New a secure stream
39    pub(crate) fn new(
40        socket: Framed<T, LengthDelimitedCodec>,
41        decode_cipher: BoxStreamCipher,
42        encode_cipher: BoxStreamCipher,
43        nonce: Vec<u8>,
44    ) -> Self {
45        SecureStream {
46            socket,
47            decode_cipher,
48            encode_cipher,
49            nonce,
50            recv_buf: Bytes::new(),
51        }
52    }
53
54    /// Decoding data
55    #[inline]
56    fn decode_buffer(&mut self, mut frame: BytesMut) -> Result<Bytes, SecioError> {
57        if self.decode_cipher.is_in_place() {
58            self.decode_cipher.decrypt_in_place(&mut frame)?;
59            Ok(frame.freeze())
60        } else {
61            Ok(Bytes::from(self.decode_cipher.decrypt(&frame)?))
62        }
63    }
64
65    pub(crate) async fn verify_nonce(&mut self) -> Result<(), SecioError> {
66        if !self.nonce.is_empty() {
67            let mut nonce = self.nonce.clone();
68            self.read_exact(&mut nonce).await?;
69
70            trace!(
71                "received nonce={}, my_nonce={}",
72                nonce.len(),
73                self.nonce.len()
74            );
75
76            let n = min(nonce.len(), self.nonce.len());
77            if nonce[..n] != self.nonce[..n] {
78                return Err(SecioError::NonceVerificationFailed);
79            }
80            self.nonce.drain(..n);
81            self.nonce.shrink_to_fit();
82        }
83
84        Ok(())
85    }
86
87    #[inline]
88    fn drain(&mut self, buf: &mut ReadBuf<'_>) -> usize {
89        if self.recv_buf.is_empty() {
90            return 0;
91        }
92
93        let n = ::std::cmp::min(buf.remaining(), self.recv_buf.len());
94
95        buf.put_slice(&self.recv_buf[..n]);
96        self.recv_buf.advance(n);
97
98        n
99    }
100
101    #[inline]
102    fn encode_buffer(&mut self, buf: &[u8]) -> Bytes {
103        let out = self.encode_cipher.encrypt(buf).unwrap();
104        Bytes::from(out)
105    }
106}
107
108impl<T> AsyncRead for SecureStream<T>
109where
110    T: AsyncRead + AsyncWrite + Unpin,
111{
112    fn poll_read(
113        mut self: Pin<&mut Self>,
114        cx: &mut Context<'_>,
115        buf: &mut ReadBuf<'_>,
116    ) -> Poll<io::Result<()>> {
117        // when there is something in recv_buffer
118        let copied = self.drain(buf);
119        if copied > 0 {
120            return Poll::Ready(Ok(()));
121        }
122
123        match self.socket.poll_next_unpin(cx) {
124            Poll::Ready(Some(Ok(t))) => {
125                trace!("poll_read raw.len={}", t.len());
126                let decoded = self
127                    .decode_buffer(t)
128                    .map_err::<io::Error, _>(|err| err.into())?;
129
130                // when input buffer is big enough
131                let n = decoded.len();
132                trace!("poll_read decoded.len={}", n);
133                if buf.remaining() >= n {
134                    buf.put_slice(&decoded);
135                    Poll::Ready(Ok(()))
136                } else {
137                    // fill internal recv buffer
138                    self.recv_buf = decoded;
139                    // drain for input buffer
140                    self.drain(buf);
141                    Poll::Ready(Ok(()))
142                }
143            }
144            Poll::Ready(Some(Err(err))) => Poll::Ready(Err(err)),
145            Poll::Ready(None) => {
146                debug!("connection shutting down");
147                Poll::Ready(Err(io::ErrorKind::BrokenPipe.into()))
148            }
149            Poll::Pending => Poll::Pending,
150        }
151    }
152}
153
154impl<T> AsyncWrite for SecureStream<T>
155where
156    T: AsyncRead + AsyncWrite + Unpin,
157{
158    fn poll_write(
159        mut self: Pin<&mut Self>,
160        cx: &mut Context<'_>,
161        buf: &[u8],
162    ) -> Poll<io::Result<usize>> {
163        match self.socket.poll_ready_unpin(cx) {
164            Poll::Ready(Ok(_)) => {
165                trace!("poll_write buf.len={}", buf.len());
166                let frame = self.encode_buffer(buf);
167                self.socket.start_send_unpin(frame)?;
168                let _ignore = self.socket.poll_flush_unpin(cx)?;
169                Poll::Ready(Ok(buf.len()))
170            }
171            Poll::Pending => Poll::Pending,
172            Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
173        }
174    }
175
176    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
177        self.socket.poll_flush_unpin(cx)
178    }
179
180    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
181        self.socket.poll_close_unpin(cx)
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::SecureStream;
188    use crate::crypto::{CryptoMode, cipher::CipherType, new_stream};
189    use bytes::{Bytes, BytesMut};
190    use futures::channel;
191    use tokio::{
192        io::{AsyncReadExt, AsyncWriteExt},
193        net::{TcpListener, TcpStream},
194    };
195    use tokio_util::codec::{Framed, length_delimited::LengthDelimitedCodec};
196
197    fn rt() -> &'static tokio::runtime::Runtime {
198        static RT: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
199        RT.get_or_init(|| tokio::runtime::Runtime::new().unwrap())
200    }
201
202    #[test]
203    fn secure_stream_drain_supports_partial_reads() {
204        use crate::crypto::StreamCipher;
205
206        struct NoopCipher;
207        impl StreamCipher for NoopCipher {
208            fn encrypt(&mut self, input: &[u8]) -> Result<Vec<u8>, crate::error::SecioError> {
209                Ok(input.to_vec())
210            }
211
212            fn decrypt(&mut self, input: &[u8]) -> Result<Vec<u8>, crate::error::SecioError> {
213                Ok(input.to_vec())
214            }
215        }
216
217        let (io, _peer) = tokio::io::duplex(64);
218        let mut stream = SecureStream::new(
219            Framed::new(io, LengthDelimitedCodec::new()),
220            Box::new(NoopCipher),
221            Box::new(NoopCipher),
222            Vec::new(),
223        );
224
225        stream.recv_buf = Bytes::from(b"hello world".to_vec());
226
227        let mut out1 = [0u8; 5];
228        let mut rb1 = tokio::io::ReadBuf::new(&mut out1);
229        assert_eq!(stream.drain(&mut rb1), 5);
230        assert_eq!(rb1.filled(), b"hello");
231
232        let mut out2 = [0u8; 16];
233        let mut rb2 = tokio::io::ReadBuf::new(&mut out2);
234        assert_eq!(stream.drain(&mut rb2), 6);
235        assert_eq!(rb2.filled(), b" world");
236        assert!(stream.recv_buf.is_empty());
237
238        let mut out3 = [0u8; 1];
239        let mut rb3 = tokio::io::ReadBuf::new(&mut out3);
240        assert_eq!(stream.drain(&mut rb3), 0);
241    }
242
243    fn test_decode_encode(cipher1: CipherType, cipher2: CipherType) {
244        let cipher_key = (0..cipher1.key_size())
245            .map(|_| rand::random::<u8>())
246            .collect::<Vec<_>>();
247
248        let data = b"hello world";
249
250        let mut encode_cipher = new_stream(cipher1, &cipher_key, CryptoMode::Encrypt);
251        let mut decode_cipher = new_stream(cipher2, &cipher_key, CryptoMode::Decrypt);
252
253        let encode_data = encode_cipher.encrypt(&data[..]).unwrap();
254
255        let decode_data = decode_cipher.decrypt(&encode_data).unwrap();
256
257        assert_eq!(&decode_data[..], &data[..]);
258    }
259
260    fn secure_codec_encode_then_decode(cipher: CipherType, send_nonce: bool) {
261        let cipher_key: [u8; 32] = rand::random();
262        let cipher_key_clone = cipher_key;
263        let key_size = cipher.key_size();
264        let hmac_key: [u8; 16] = rand::random();
265        let _hmac_key_clone = hmac_key;
266        let data = b"hello world";
267        let data_clone = data;
268        let nonce = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
269        let nonce2 = nonce.clone();
270
271        let (sender, receiver) = channel::oneshot::channel::<bytes::BytesMut>();
272        let (addr_sender, addr_receiver) = channel::oneshot::channel::<::std::net::SocketAddr>();
273        let rt = rt();
274
275        rt.spawn(async move {
276            let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
277            let listener_addr = listener.local_addr().unwrap();
278            let _res = addr_sender.send(listener_addr);
279            let (socket, _) = listener.accept().await.unwrap();
280
281            let mut handle = SecureStream::new(
282                Framed::new(socket, LengthDelimitedCodec::new()),
283                new_stream(cipher, &cipher_key_clone[..key_size], CryptoMode::Decrypt),
284                new_stream(cipher, &cipher_key_clone[..key_size], CryptoMode::Encrypt),
285                nonce2,
286            );
287
288            handle.verify_nonce().await.unwrap();
289
290            let mut data = [0u8; 11];
291            handle.read_exact(&mut data).await.unwrap();
292            let _res = sender.send(BytesMut::from(&data[..]));
293        });
294
295        rt.spawn(async move {
296            let listener_addr = addr_receiver.await.unwrap();
297            let stream = TcpStream::connect(&listener_addr).await.unwrap();
298            let mut handle = SecureStream::new(
299                Framed::new(stream, LengthDelimitedCodec::new()),
300                new_stream(cipher, &cipher_key_clone[..key_size], CryptoMode::Decrypt),
301                new_stream(cipher, &cipher_key_clone[..key_size], CryptoMode::Encrypt),
302                Vec::new(),
303            );
304
305            // if not send nonce to remote, handshake will unable to complete the final confirmation
306            // it will return error and shutdown this session
307            if send_nonce {
308                let _ignore = handle.write_all(&nonce).await;
309            }
310
311            let _res = handle.write_all(&data_clone[..]).await;
312        });
313
314        rt.block_on(async move {
315            let received = receiver.await.unwrap();
316            assert_eq!(received.to_vec(), data);
317        });
318    }
319
320    #[test]
321    fn test_encode_decode_aes128gcm() {
322        test_decode_encode(CipherType::Aes128Gcm, CipherType::Aes128Gcm);
323    }
324
325    #[test]
326    fn test_encode_decode_aes256gcm() {
327        test_decode_encode(CipherType::Aes256Gcm, CipherType::Aes256Gcm);
328    }
329
330    #[test]
331    fn test_encode_decode_chacha20poly1305() {
332        test_decode_encode(CipherType::ChaCha20Poly1305, CipherType::ChaCha20Poly1305);
333    }
334
335    #[should_panic]
336    #[test]
337    fn test_encode_decode_diff_cipher_1() {
338        test_decode_encode(CipherType::Aes128Gcm, CipherType::Aes256Gcm);
339    }
340
341    #[should_panic]
342    #[test]
343    fn test_encode_decode_diff_cipher_2() {
344        test_decode_encode(CipherType::Aes128Gcm, CipherType::ChaCha20Poly1305);
345    }
346
347    #[should_panic]
348    #[test]
349    fn test_encode_decode_diff_cipher_3() {
350        test_decode_encode(CipherType::Aes256Gcm, CipherType::Aes128Gcm);
351    }
352
353    #[should_panic]
354    #[test]
355    fn test_encode_decode_diff_cipher_4() {
356        test_decode_encode(CipherType::Aes256Gcm, CipherType::ChaCha20Poly1305);
357    }
358
359    #[should_panic]
360    #[test]
361    fn test_encode_decode_diff_cipher_5() {
362        test_decode_encode(CipherType::ChaCha20Poly1305, CipherType::Aes128Gcm);
363    }
364
365    #[should_panic]
366    #[test]
367    fn test_encode_decode_diff_cipher_6() {
368        test_decode_encode(CipherType::ChaCha20Poly1305, CipherType::Aes256Gcm);
369    }
370
371    #[test]
372    fn secure_codec_encode_then_decode_aes128gcm() {
373        secure_codec_encode_then_decode(CipherType::Aes128Gcm, true);
374    }
375
376    #[test]
377    fn secure_codec_encode_then_decode_aes256gcm() {
378        secure_codec_encode_then_decode(CipherType::Aes256Gcm, true);
379    }
380
381    #[test]
382    fn secure_codec_encode_then_decode_chacha20poly1305() {
383        secure_codec_encode_then_decode(CipherType::ChaCha20Poly1305, true);
384    }
385
386    #[should_panic]
387    #[test]
388    fn secure_codec_encode_then_decode_do_not_send_nonce_aes128gcm() {
389        secure_codec_encode_then_decode(CipherType::Aes128Gcm, false);
390    }
391
392    #[should_panic]
393    #[test]
394    fn secure_codec_encode_then_decode_do_not_send_nonce_aes256gcm() {
395        secure_codec_encode_then_decode(CipherType::Aes256Gcm, false);
396    }
397
398    #[should_panic]
399    #[test]
400    fn secure_codec_encode_then_decode_do_not_send_nonce_chacha20poly1305() {
401        secure_codec_encode_then_decode(CipherType::ChaCha20Poly1305, false);
402    }
403}