Hello,
I'm wrting a tcp proxy server, data must be encrypted between the client and server. I want to write
- a transparent stream writer which wraps the raw TCP writer, it will encrypt data before sending
- a transparent stream reader which wraps the raw TCP reader, it will decrypt data after reading
see the code snippet for the server, is this the right approach?
The client can not get right data after transferring data for some time, is it due to the cipher data is split during network transfer?
fn handle_client_conn() {
let (mut payload_reader, mut payload_writer) = payload_socket;
let (mut client_reader, mut client_writer) = client_socket;
let mut dec_reader = DecReader::new(client_reader);
let mut enc_writer = DecReader::new(client_writer);
async::spawn{
copy_stream(payload_reader, enc_writer); //transparent write payload data
}
copy_stream(dec_reader, payload_writer); //transparent read client request
}
pub struct DecReader {
inner: OwnedReadHalf,
crypt_cipher: ChaCha20,
}
impl AsyncRead for DecReader {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
match Pin::new(&mut self.inner).poll_read(cx, buf) {
Poll::Ready(x) => {
&self.crypt_cipher.apply_keystream(&mut buf); // decrypt data
Poll::Ready(Ok(()))
}
Poll::Pending => {
Poll::Pending
}
}
}
}
pub struct EncWriter {
inner: OwnedWriteHalf,
crypt_cipher: ChaCha20,
}
impl AsyncWrite for EncWriter {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
if buf.len() > 0 {
let mut wbuf = Vec::with_capacity(len);
wbuf.copy_from_slice(buf);
&self.crypt_cipher.apply_keystream(&mut wbuf); //encrypt data
return Pin::new(&mut self.inner).poll_write(cx, &wbuf);
}
Pin::new(&mut self.inner).poll_write(cx, buf)
}
}