1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
/*
 * Created on Sun Jul 25 2021
 *
 * Copyright (c) storycraft. Licensed under the MIT Licence.
 */

pub mod client;
pub mod server;

use futures::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use rsa::{PaddingScheme, RsaPrivateKey, RsaPublicKey};

use self::{client::to_handshake_packet, server::decode_handshake_head};

use super::{
    crypto::{CryptoError, CryptoStore},
    stream::SecureStream,
    SecureHandshake,
};
use crate::secure::SECURE_HANDSHAKE_HEAD_SIZE;

use std::{
    convert::TryInto,
    io::{self, Read, Write},
};

#[derive(Debug)]
pub enum SecureHandshakeError {
    Bincode(bincode::Error),
    Io(io::Error),
    Crypto(CryptoError),
    InvalidKey,
}

impl From<bincode::Error> for SecureHandshakeError {
    fn from(err: bincode::Error) -> Self {
        Self::Bincode(err)
    }
}

impl From<io::Error> for SecureHandshakeError {
    fn from(err: io::Error) -> Self {
        Self::Io(err)
    }
}

impl From<CryptoError> for SecureHandshakeError {
    fn from(err: CryptoError) -> Self {
        Self::Crypto(err)
    }
}

/// Client side connection
pub struct SecureClientSession {
    key: RsaPublicKey,
}

impl SecureClientSession {
    pub fn new(key: RsaPublicKey) -> Self {
        Self { key }
    }
}

impl SecureClientSession {
    /// Do client handshake
    pub fn handshake<S: Write>(
        &self,
        secure_stream: &mut SecureStream<S>,
    ) -> Result<(), SecureHandshakeError> {
        let handshake = to_handshake_packet(secure_stream.crypto(), &self.key)?;

        secure_stream.stream_mut().write_all(&handshake)?;

        Ok(())
    }

    /// Do client handshake async
    pub async fn handshake_async<'a, S: AsyncWrite + Unpin>(
        &self,
        secure_stream: &'a mut SecureStream<S>,
    ) -> Result<(), SecureHandshakeError> {
        let handshake = to_handshake_packet(secure_stream.crypto(), &self.key)?;

        secure_stream.stream_mut().write_all(&handshake).await?;

        Ok(())
    }
}

/// Server side connection
#[derive(Debug)]
pub struct SecureServerSession {
    key: RsaPrivateKey,
    current_handshake: Option<SecureHandshake>,
}

impl SecureServerSession {
    pub fn new(key: RsaPrivateKey) -> Self {
        Self {
            key,
            current_handshake: None,
        }
    }

    /// Do server handshake and returns CryptoStore on success
    pub fn handshake<S: Read>(
        &mut self,
        stream: &mut S,
    ) -> Result<CryptoStore, SecureHandshakeError> {
        let mut handshake = match self.current_handshake.take() {
            Some(header) => header,
            None => {
                let mut handshake_head_buf = [0_u8; SECURE_HANDSHAKE_HEAD_SIZE];
                stream.read_exact(&mut handshake_head_buf)?;

                decode_handshake_head(&handshake_head_buf)?
            }
        };

        if let Err(err) = stream.read_exact(&mut handshake.encrypted_key) {
            self.current_handshake = Some(handshake);

            return Err(SecureHandshakeError::from(err));
        }

        let key = self
            .key
            .decrypt(
                PaddingScheme::new_oaep::<sha1::Sha1>(),
                &handshake.encrypted_key,
            )
            .map_err(|_| CryptoError::CorruptedData)?;

        Ok(CryptoStore::new_with_key(
            key.try_into()
                .map_err(|_| SecureHandshakeError::InvalidKey)?,
        ))
    }

    /// Do server handshake async and returns CryptoStore on success
    pub async fn handshake_async<'a, S: AsyncRead + Unpin>(
        &'a mut self,
        stream: &'a mut S,
    ) -> Result<CryptoStore, SecureHandshakeError> {
        let mut handshake = match self.current_handshake.take() {
            Some(header) => header,
            None => {
                let mut handshake_head_buf = [0_u8; SECURE_HANDSHAKE_HEAD_SIZE];
                stream.read_exact(&mut handshake_head_buf).await?;

                decode_handshake_head(&handshake_head_buf)?
            }
        };

        if let Err(err) = stream.read_exact(&mut handshake.encrypted_key).await {
            self.current_handshake = Some(handshake);

            return Err(SecureHandshakeError::from(err));
        }

        let key = self
            .key
            .decrypt(
                PaddingScheme::new_oaep::<sha1::Sha1>(),
                &handshake.encrypted_key,
            )
            .map_err(|_| CryptoError::CorruptedData)?;

        Ok(CryptoStore::new_with_key(
            key.try_into()
                .map_err(|_| SecureHandshakeError::InvalidKey)?,
        ))
    }
}