falcotcp 0.1.4

Secure TCP server/client with AES-256-GCM encryption, authentication, and messaging. Ideal for trusted communication between services, with sync/async worker balancing.
Documentation
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use aes_gcm::{
    Aes256Gcm, AesGcm, KeyInit,
    aead::{Aead, OsRng, Payload, generic_array::GenericArray, rand_core::RngCore},
};
use async_std::{
    future::timeout,
    io::{ReadExt, WriteExt},
    net::{TcpListener, TcpStream},
    sync::Mutex,
    task::{self, yield_now},
};
use std::pin::Pin;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::SystemTime;
use std::{
    collections::HashMap,
    io::{Error, ErrorKind},
    str::FromStr,
    sync::Arc,
    time::Duration,
};

#[derive(PartialEq, Debug)]
pub enum RequestType {
    Authentication,
    Message,
    Ping,
}

pub struct Server {
    aesgcm: AesGcm<
        aes_gcm::aes::Aes256,
        aes_gcm::aes::cipher::typenum::UInt<
            aes_gcm::aes::cipher::typenum::UInt<
                aes_gcm::aes::cipher::typenum::UInt<
                    aes_gcm::aes::cipher::typenum::UInt<
                        aes_gcm::aes::cipher::typenum::UTerm,
                        aes_gcm::aead::consts::B1,
                    >,
                    aes_gcm::aead::consts::B1,
                >,
                aes_gcm::aead::consts::B0,
            >,
            aes_gcm::aead::consts::B0,
        >,
    >,
    message_handler: MessageHandler,
    listener: Arc<TcpListener>,
}

pub type MessageHandler =
    Arc<dyn Fn(Vec<u8>) -> Pin<Box<dyn Future<Output = Vec<u8>> + Send>> + Send + Sync + 'static>;

impl Server {
    pub async fn new(
        host: String,
        password: [u8; 32],
        message_handler: MessageHandler,
        workers: usize,
    ) -> Result<(), Error> {
        let aesgcm = Aes256Gcm::new(&GenericArray::from_slice(&password));
        let listener = Arc::new(TcpListener::bind(&host).await?);
        Server::start(
            Arc::new(Server {
                listener,
                message_handler,
                aesgcm,
            }),
            workers,
        )
        .await
    }

    pub async fn start(self: Arc<Server>, workers: usize) -> Result<(), std::io::Error> {
        if workers < 1 {
            return Err(std::io::Error::new(
                ErrorKind::InvalidInput,
                "Invalid workers count, the minimum is \"1\".",
            ));
        }

        let mut worker_list: Vec<(Arc<Mutex<usize>>, Sender<TcpStream>)> = Vec::new();

        for _ in 0..workers {
            let (sender, receiver): (Sender<TcpStream>, Receiver<TcpStream>) = channel();
            let cc = Arc::new(Mutex::new(0));
            worker_list.push((cc.clone(), sender));

            let server = self.clone();
            task::spawn(async move {
                let mut connections: Vec<(TcpStream, u128, bool)> = Vec::new();
                let mut connection_health: HashMap<u128, SystemTime> = HashMap::new();
                let mut cc_changed = false;

                loop {
                    if let Ok(stream) = receiver.try_recv() {
                        let num = {
                            let mut numba = [0u8; 16];
                            numba[..8].clone_from_slice(&OsRng::next_u64(&mut OsRng).to_be_bytes());
                            numba[8..].clone_from_slice(&OsRng::next_u64(&mut OsRng).to_be_bytes());
                            u128::from_be_bytes(numba)
                        };
                        connection_health.insert(num, SystemTime::now());
                        connections.push((stream, num, true));
                        cc_changed = true;
                    }

                    let mut delete: Vec<usize> = Vec::new();
                    let mut current: Option<usize> = None;

                    for (index, connection) in connections.iter_mut().enumerate() {
                        if !connection.2 {
                            continue;
                        }

                        if let Ok(dur) = connection_health.get(&connection.1).unwrap().elapsed() {
                            if dur.as_secs() > 60 {
                                delete.push(index);
                                connection.2 = false;
                                continue;
                            }
                        }

                        let stream = &mut connection.0;

                        let interaction_type = if let Ok(result) =
                            timeout(Duration::from_millis(10), async {
                                let mut buffer = [0u8; 1];
                                stream.read_exact(&mut buffer).await.map(|_| buffer[0])
                            })
                            .await
                        {
                            match result {
                                Ok(byte) => byte,
                                Err(_) => {
                                    delete.push(index);
                                    connection.2 = false;
                                    continue;
                                }
                            }
                        } else {
                            continue;
                        };

                        connection_health.insert(connection.1, SystemTime::now());

                        match interaction_type {
                            1 => {
                                current = Some(index);
                                break;
                            }
                            2 => {
                                connection_health.insert(connection.1, SystemTime::now());
                            }
                            _ => {
                                continue;
                            }
                        }
                    }

                    if let Some(index) = current {
                        if let Some(connection) = connections.get_mut(index) {
                            let stream = &mut connection.0;

                            let message_size = match timeout(Duration::from_secs(5), async {
                                let mut bytes = [0u8; 8];
                                stream
                                    .read_exact(&mut bytes)
                                    .await
                                    .map(|_| u64::from_be_bytes(bytes) as usize)
                            })
                            .await
                            {
                                Ok(Ok(size)) => size,
                                _ => {
                                    delete.push(index);
                                    connection.2 = false;
                                    continue;
                                }
                            };

                            let payload = match timeout(Duration::from_secs(5), async {
                                let mut bytes = vec![0u8; message_size];
                                stream.read_exact(&mut bytes).await.map(|_| bytes)
                            })
                            .await
                            {
                                Ok(Ok(bytes)) => {
                                    if bytes.len() < 12 {
                                        delete.push(index);
                                        connection.2 = false;
                                        continue;
                                    }

                                    let nonce = GenericArray::from_slice(&bytes[..12]);
                                    let ciphertext = Payload::from(&bytes[12..]);
                                    match server.aesgcm.decrypt(nonce, ciphertext) {
                                        Ok(decrypted) => decrypted,
                                        Err(_) => {
                                            delete.push(index);
                                            connection.2 = false;
                                            continue;
                                        }
                                    }
                                }
                                _ => {
                                    delete.push(index);
                                    connection.2 = false;
                                    continue;
                                }
                            };

                            let response = (server.message_handler)(payload).await;
                            let nonce = {
                                let mut dest: [u8; 12] = [0u8; 12];
                                OsRng::fill_bytes(&mut OsRng, &mut dest);
                                dest
                            };

                            if let Ok(encrypted) = server
                                .aesgcm
                                .encrypt(&GenericArray::from_slice(&nonce), response.as_slice())
                            {
                                let length = nonce.len() + encrypted.len();
                                let size: [u8; 8] = (length as u64).to_be_bytes();

                                let mut response_payload = size.to_vec();
                                response_payload.extend_from_slice(&nonce);
                                response_payload.extend_from_slice(&encrypted);

                                if stream.write_all(&response_payload).await.is_err()
                                    || stream.flush().await.is_err()
                                {
                                    delete.push(index);
                                    connection.2 = false;
                                }
                            }
                        }
                    }

                    if delete.len() > 0 {
                        delete.sort_unstable_by(|a, b| b.cmp(a));
                        for i in delete {
                            if i < connections.len() {
                                let connection = connections.remove(i);
                                connection_health.remove(&connection.1);
                                cc_changed = true;
                            }
                        }
                    }

                    if cc_changed {
                        cc_changed = false;
                        *cc.lock().await = connections.len();
                    }
                    yield_now().await;
                }
            });
        }

        loop {
            let (stream, _) = self.listener.accept().await?;
            let mut stream = stream;

            let mut request_type_buffer = [0u8; 1];
            if let Err(_) = stream.read_exact(&mut request_type_buffer).await {
                continue;
            };

            let request_type: RequestType = match u8::from_be_bytes(request_type_buffer) {
                0 => RequestType::Authentication,
                _ => {
                    continue;
                }
            };

            if RequestType::Authentication == request_type {
                let mut password: [u8; 156] = [0u8; 156];
                if let Err(_) = stream.read_exact(&mut password).await {
                    continue;
                } else {
                    let nonce = GenericArray::from_slice(&password[..12]);
                    let cipher = &password[12..];
                    let ciphertext = Payload::from(cipher);

                    if let Ok(_) = self.aesgcm.decrypt(nonce, ciphertext) {
                        let _ = stream.write_all(&[255u8]).await;
                        let _ = stream.flush().await;

                        let mut min_connections = usize::MAX;
                        let mut selected_worker = None;

                        for worker in &worker_list {
                            let count = *worker.0.lock().await;
                            if count < min_connections {
                                min_connections = count;
                                selected_worker = Some(&worker.1);
                            }
                        }

                        if let Some(sender) = selected_worker {
                            let _ = sender.send(stream);
                        }
                    } else {
                        yield_now().await;
                    }
                }
            }
        }
    }
}

pub struct Client {
    stream: TcpStream,
    aesgcm: Aes256Gcm,
}

impl Client {
    pub async fn new(address: &str, password: [u8; 32]) -> Result<Client, Error> {
        let address = match std::net::SocketAddr::from_str(address) {
            Ok(a) => a,
            Err(e) => return Err(Error::new(ErrorKind::Other, e.to_string())),
        };

        let mut stream = TcpStream::connect(&address).await?;
        let mut payload = vec![];

        payload.push(0u8);

        let nonce = {
            let mut dest: [u8; 12] = [0u8; 12];
            OsRng::fill_bytes(&mut OsRng, &mut dest);
            dest
        };

        let brick = {
            let mut dest: [u8; 128] = [0u8; 128];
            OsRng::fill_bytes(&mut OsRng, &mut dest);
            dest
        };

        payload.extend_from_slice(&nonce);
        let aesgcm = Aes256Gcm::new(&GenericArray::from_slice(&password));

        match aesgcm.encrypt(
            GenericArray::from_slice(&nonce),
            Payload::from(brick.as_slice()),
        ) {
            Ok(encrypted) => payload.extend_from_slice(&encrypted),
            Err(e) => return Err(Error::new(ErrorKind::Other, e.to_string())),
        }

        stream.write_all(&payload).await?;
        stream.flush().await?;

        let mut response = [0u8; 1];

        if let Err(_) = timeout(Duration::from_secs(5), stream.read_exact(&mut response)).await {
            return Err(Error::new(ErrorKind::TimedOut, "Authentication timeout"));
        }

        let success = response[0] == 255;
        if success {
            return Ok(Client { stream, aesgcm });
        }

        Err(Error::new(ErrorKind::ConnectionRefused, "Invalid password"))
    }

    pub async fn message(&mut self, bytes: Vec<u8>) -> Result<Vec<u8>, Error> {
        let nonce = {
            let mut dest: [u8; 12] = [0u8; 12];
            OsRng::fill_bytes(&mut OsRng, &mut dest);
            dest
        };

        let encrypted = match self.aesgcm.encrypt(
            GenericArray::from_slice(&nonce),
            Payload::from(bytes.as_slice()),
        ) {
            Ok(enc) => enc,
            Err(e) => return Err(Error::new(ErrorKind::Other, e.to_string())),
        };

        let total_size = nonce.len() + encrypted.len();
        let mut payload = Vec::new();
        payload.push(1u8);
        payload.extend_from_slice(&(total_size as u64).to_be_bytes());
        payload.extend_from_slice(&nonce);
        payload.extend_from_slice(&encrypted);

        self.stream.write_all(&payload).await?;
        self.stream.flush().await?;

        let mut response_size_bytes = [0u8; 8];
        self.stream.read_exact(&mut response_size_bytes).await?;
        let response_size = u64::from_be_bytes(response_size_bytes) as usize;

        let mut response_payload = vec![0u8; response_size];
        self.stream.read_exact(&mut response_payload).await?;

        if response_payload.len() < 12 {
            return Err(Error::new(ErrorKind::Other, "Response too small"));
        }

        let response_nonce = GenericArray::from_slice(&response_payload[..12]);
        let response_ciphertext = Payload::from(&response_payload[12..]);

        match self.aesgcm.decrypt(response_nonce, response_ciphertext) {
            Ok(decrypted) => Ok(decrypted),
            Err(e) => Err(Error::new(ErrorKind::Other, e.to_string())),
        }
    }

    pub async fn ping(&mut self) -> Result<(), Error> {
        self.stream.write_all(&[2u8]).await?;
        self.stream.flush().await?;
        Ok(())
    }
}