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
use rand::prelude::*;
use serde::{Serialize, Deserialize};
use serde::export::Formatter;
use chrono::Utc;

#[derive(Debug, Clone)]
pub struct SecretKey(pub String);
impl SecretKey {
    #[allow(unused)]
    pub fn generate() -> Self {
        let mut key = [0u8; 32];
        rand::thread_rng().fill_bytes(&mut key);
        Self(base64::encode_config(&key, base64::URL_SAFE_NO_PAD))
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all="snake_case")]
pub enum ServerHello {
    Success {
        sub_domain: String,
    },
    SubDomainInUse,
    InvalidSubDomain,
    AuthFailed,
}

impl ServerHello {
    #[allow(unused)]
    pub fn random_domain() -> String {
        let mut rng = rand::thread_rng();
        std::iter::repeat(())
            .map(|_| rng.sample(rand::distributions::Alphanumeric))
            .take(8)
            .collect::<String>()
            .to_lowercase()
    }
}

const CLIENT_HELLO_TTL_SECONDS:i64 = 300;

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ClientHello {
    pub id: ClientId,
    pub sub_domain: Option<String>,
    // epoch
    unix_seconds: i64,
    //hex encoded
    signature: String,
}

impl ClientHello {
    pub fn generate(id: ClientId, secret_key: &SecretKey, sub_domain: Option<String>) -> (Self, ClientId) {
        let unix_seconds = Utc::now().timestamp();

        let input = format!("{}", unix_seconds);
        let signature = hmac_sha256::HMAC::mac(input.as_bytes(), secret_key.0.as_bytes());

        (ClientHello {
            id: id.clone(), sub_domain, unix_seconds, signature: hex::encode(signature)
        }, id)
    }

    #[allow(unused)]
    pub fn verify(secret_key: &SecretKey, data: &[u8]) -> Result<Self, Box<dyn std::error::Error>> {
        let client_hello:ClientHello = serde_json::from_slice(&data)?;

        if (Utc::now().timestamp() - client_hello.unix_seconds).abs() > CLIENT_HELLO_TTL_SECONDS {
            return Err("Expired client hello".into())
        }

        let input = format!("{}", client_hello.unix_seconds);
        let expected = hmac_sha256::HMAC::mac(input.as_bytes(), secret_key.0.as_bytes());

        if hex::encode(expected) != client_hello.signature {
            return Err("Bad signature in client hello".into())
        }

        Ok(client_hello)
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
#[serde(transparent)]
pub struct ClientId(String);

impl std::fmt::Display for ClientId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}
impl ClientId {
    pub fn generate() -> Self {
        let mut id = [0u8; 32];
        rand::thread_rng().fill_bytes(&mut id);
        ClientId(base64::encode_config(&id, base64::URL_SAFE_NO_PAD))
    }
}


#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StreamId([u8; 8]);

impl StreamId {
    #[allow(unused)]
    pub fn generate() -> StreamId {
        let mut id = [0u8; 8];
        rand::thread_rng().fill_bytes(&mut id);
        StreamId(id)
    }

    pub fn to_string(&self) -> String {
        format!("stream_{}", base64::encode_config(&self.0, base64::URL_SAFE_NO_PAD))
    }
}

#[derive(Debug, Clone)]
pub enum ControlPacket {
    Init(StreamId),
    Data(StreamId, Vec<u8>),
    Refused(StreamId),
    Ping,
}

pub const PING_INTERVAL:u64 = 4;

const EMPTY_STREAM:StreamId = StreamId([0xF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);

impl ControlPacket {
    pub fn serialize(self) -> Vec<u8> {
        match self {
            ControlPacket::Init(sid) => [vec![0x01], sid.0.to_vec()].concat(),
            ControlPacket::Data(sid, data) => [vec![0x02], sid.0.to_vec(), data].concat(),
            ControlPacket::Refused(sid) => [vec![0x03], sid.0.to_vec()].concat(),
            ControlPacket::Ping => [vec![0x04], EMPTY_STREAM.0.to_vec()].concat()
        }
    }

    pub fn deserialize(data: &[u8]) -> Result<Self, Box<dyn std::error::Error>> {
        if data.len() < 9 {
            return Err("invalid DataPacket, missing stream id".into())
        }

        let mut stream_id = [0u8; 8];
        stream_id.clone_from_slice(&data[1..9]);
        let stream_id = StreamId(stream_id);

        let packet = match data[0] {
            0x01 => ControlPacket::Init(stream_id),
            0x02 => ControlPacket::Data(stream_id, data[9..].to_vec()),
            0x03 => ControlPacket::Refused(stream_id),
            0x04 => ControlPacket::Ping,
            _ => return Err("invalid control byte in DataPacket".into())
        };

        Ok(packet)
    }
}