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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/*!

## Sync Client

```
use networking::{ArtificeConfig, ArtificeHost, ArtificePeer};
use std::fs::File;
use std::io::Read;
fn main() {
    let mut config_file = File::open("host.json").unwrap();
    let mut conf_vec = String::new();
    config_file.read_to_string(&mut conf_vec).unwrap();
    let config: ArtificeConfig = serde_json::from_str(&conf_vec).unwrap();
    let mut file = File::open("peer.json").unwrap();
    let mut invec = Vec::new();
    file.read_to_end(&mut invec).unwrap();
    let string = String::from_utf8(invec).unwrap();
    // println!("invec: {}", invec);
    let peer: ArtificePeer = serde_json::from_str(&string).unwrap();
    let host = ArtificeHost::client_only(&config);
    let mut stream = host.connect(peer).unwrap();
    let mut buffer = Vec::new();
    println!("about to read from sream");
    println!(
        "got {} bytes from server",
        stream.recv(&mut buffer).unwrap()
    );
    println!("read from stream");
    let string = String::from_utf8(buffer).unwrap();
    println!("got message: {} from server", string);
    //stream.write(&buffer).unwrap();
}

```

## Sync Server
```
use networking::{ArtificeConfig, ArtificeHost, ArtificePeer};
use std::fs::File;
use std::io::{Read};
fn main() {
    let mut config_file = File::open("host.json").unwrap();
    let mut conf_vec = String::new();
    config_file.read_to_string(&mut conf_vec).unwrap();
    let config: ArtificeConfig = serde_json::from_str(&conf_vec).unwrap();
    let host = ArtificeHost::from_host_data(&config).unwrap();
    let mut file = File::open("peer.json").unwrap();
    let mut invec = String::new();
    file.read_to_string(&mut invec).unwrap();
    let peer: ArtificePeer = serde_json::from_str(&invec).unwrap();
    for netstream in host {
        let mut stream = netstream.unwrap();
        println!("about to write to stream");
        stream
            .send(&"hello world".to_string().into_bytes())
            .unwrap();
        // do something with the stream example:
        if *stream.peer() == peer {
            // correct peer
        }
    }
}

```
*/
#![feature(maybe_uninit_ref)]
#![feature(ip)]
#[macro_use]
extern crate serde_derive;
/// contains blowfish encryption wrapper, as well as storage solution (serde) for BigUint principly BigNum
pub mod encryption;
pub use encryption::*;
/// contains the ArtificePeer struct
pub mod peers;
/// used for permission requests in the manager crate
pub mod query;
use crate::encryption::{BigNum, PrivKeyComp, PubKeyPair};
use futures::task::{Context, Poll};
pub use peers::*;
use rsa::{PublicKeyParts, RSAPrivateKey, RSAPublicKey};
use std::net::SocketAddr;
use std::{
    io::{Read, Write},
    net::{TcpListener, TcpStream, UdpSocket},
    pin::Pin,
    sync::{
        mpsc::{channel, RecvTimeoutError, Sender},
        Arc, Mutex,
    },
    thread,
    time::Duration,
};
/// used to build and configure the local host
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ArtificeConfig {
    broadcast: bool,
    address: Layer3Addr,
    port: u16,
    host: ArtificeHostData,
}
impl ArtificeConfig {
    /// used to create new host, primarily designed for use by the installer crate
    pub fn generate(address: Layer3Addr) -> Self {
        let broadcast = false;
        let port = 6464;
        let host = ArtificeHostData::default();
        Self {
            broadcast,
            address,
            port,
            host,
        }
    }
    pub fn host_data(&self) -> ArtificeHostData {
        self.host.clone()
    }
    pub fn broadcast(&self) -> bool {
        self.broadcast
    }
    pub fn port(&self) -> u16 {
        self.port
    }
    pub fn address(&self) -> Layer3Addr {
        self.address
    }
}

/// provides a means of saving private keys to files, because the process of generating the keys takes a really long time, but creating them from existing values does not
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct ArtificeHostData {
    priv_key: PrivKeyComp,
    global_peer_hash: String,
}
impl Default for ArtificeHostData {
    fn default() -> Self {
        let global_peer_hash = random_string(50);
        let priv_key = PrivKeyComp::generate().unwrap();
        Self {
            priv_key,
            global_peer_hash,
        }
    }
}
impl ArtificeHostData {
    pub fn private_key(&self) -> PrivKeyComp {
        self.priv_key.clone()
    }
    pub fn global_peer_hash(&self) -> String {
        self.global_peer_hash.clone()
    }
}
/// contains peer information sent accross the network in an effort to prevent man in the middle attacks
#[derive(Debug, Clone, Eq, Serialize, Deserialize)]
pub struct Header {
    peer: ArtificePeer,
    pubkey: PubKeyPair,
    packet_len: usize,
}
impl PartialEq for Header {
    fn eq(&self, other: &Self) -> bool {
        self.peer == other.peer && self.pubkey == other.pubkey
    }
}
impl Header {
    pub fn new(peer: ArtificePeer, pubkey: PubKeyPair) -> Self {
        Self {
            peer,
            pubkey,
            packet_len: 0,
        }
    }
    pub fn peer(&self) -> &ArtificePeer {
        &self.peer
    }
    pub fn pubkey(&self) -> RSAPublicKey {
        RSAPublicKey::new(self.pubkey.n(), self.pubkey.e()).unwrap()
    }
    pub fn packet_len(&self) -> usize {
        self.packet_len
    }
    pub fn set_len(&mut self, len: usize) {
        self.packet_len = len;
    }
}
/// the TcpStream version of the artifice network, implements encryption automatically in its implementation of std::io::Write, and std::io::Read
#[derive(Debug, Clone)]
pub struct NetworkStream {
    header: Header,
    stream: Arc<Mutex<TcpStream>>,
    priv_key: RSAPrivateKey,
}
impl NetworkStream {
    pub fn new(stream: TcpStream, priv_key: RSAPrivateKey, peer: ArtificePeer) -> Self {
        let pubkey = RSAPublicKey::from(&priv_key);
        let header = Header::new(
            peer,
            PubKeyPair::from_parts(
                BigNum::from_biguint(pubkey.n().clone()),
                BigNum::from_biguint(pubkey.e().clone()),
            ),
        );
        Self {
            header,
            stream: Arc::new(Mutex::new(stream)),
            priv_key,
        }
    }
    pub fn peer(&self) -> &ArtificePeer {
        self.header.peer()
    }
    pub fn pubkey(&self) -> RSAPublicKey {
        self.header.pubkey()
    }
    /// implented in place of std::io::Read, because reading to empty vec fails
    pub fn recv(&mut self, outbuf: &mut Vec<u8>) -> std::io::Result<usize> {
        let mut buffer: [u8; 65535] = [0; 65535];
        let mut stream = self.stream.lock().unwrap();
        let mut buf = Vec::new();
        let mut data_len = stream.read(&mut buffer)?;
        while data_len == 0 {
            data_len = stream.read(&mut buffer)?;
        }
        let dec_data = match rsa_decrypt(&self.priv_key, &buffer, data_len) {
            Ok(dec_data) => dec_data,
            Err(_e) => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::PermissionDenied,
                    "decryption failure",
                ));
            }
        };
        let header_len = u16::from_be_bytes([dec_data[0], dec_data[1]]) as usize;
        let header_str = match String::from_utf8(dec_data[2..header_len + 2].to_vec()) {
            Ok(header_str) => header_str,
            Err(_e) => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::PermissionDenied,
                    "couldn't read input as string",
                ))
            }
        };
        //Ok((serde_json::from_str(&header_str).expect("couldn't deserialize header"), header_len))
        let header: Header = serde_json::from_str(&header_str).expect("coun't deserialize header");
        // verify that a man in the middle attack hasn't occured
        // let (header, header_len) = get_headers(&self.priv_key, &dec_data, data_len)?;
        if header != self.header {
            return Err(std::io::Error::new(
                std::io::ErrorKind::PermissionDenied,
                "headers are different",
            ));
        }
        // add data not part of the header from the first packet to the greater vector
        if header.packet_len() + header_len < 65535 {
            buf.extend_from_slice(&dec_data[header_len + 2..header_len + header.packet_len() + 2]);
        } else {
            buf.extend_from_slice(&dec_data[header_len..65535]);
        }
        //hadle further packets
        while data_len < header.packet_len() + header_len as usize {
            let mut temp_len = stream.read(&mut buffer)?;
            while temp_len == 0 {
                temp_len = stream.read(&mut buffer)?;
            }
            data_len += temp_len;
            let dec_buffer = match rsa_decrypt(&self.priv_key, &buffer, temp_len) {
                Ok(dec_buffer) => dec_buffer,
                Err(_e) => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::PermissionDenied,
                        "unable to decrypt data",
                    ));
                }
            };
            buffer = [0; 65535];
            buf.extend_from_slice(&dec_buffer);
        }
        println!("buf len: {}", buf.len());
        let string = String::from_utf8(buf.clone()).unwrap();
        println!("got message: {} from server", string);
        outbuf.append(&mut buf);
        Ok(buf.len())
    }
    /// send data to the peer
    pub fn send(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        println!("buf: {:?}", buf);
        let key = self.peer().pubkeypair();
        let public_key = RSAPublicKey::new(key.n(), key.e()).unwrap();
        let mut buffer = Vec::new();
        self.header.set_len(buf.len());
        let bytes = serde_json::to_string(&self.header).unwrap().into_bytes();
        let header_len: [u8; 2] = (bytes.len() as u16).to_be_bytes();
        buffer.push(header_len[0]);
        buffer.push(header_len[1]);
        buffer.extend_from_slice(bytes.as_slice());
        buffer.extend_from_slice(buf);
        let enc_data = rsa_encrypt(&public_key, &buffer).expect("failed to encrypt");
        let mut stream = self.stream.lock().unwrap();
        stream.write(&enc_data)
    }
}
/// the in execution host struct built from AritificeConfig
pub struct ArtificeHost {
    priv_key: RSAPrivateKey,
    broadcast: bool,
    socket_addr: SocketAddr,
    listener: Option<TcpListener>,
}
impl futures::future::Future for ArtificeHost {
    type Output = std::io::Result<NetworkStream>;
    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Self::Output> {
        match self.next() {
            Some(res) => Poll::Ready(res),
            None => Poll::Pending,
        }
    }
}
impl std::iter::Iterator for ArtificeHost {
    type Item = std::io::Result<NetworkStream>;
    fn next(&mut self) -> Option<Self::Item> {
        match &self.listener {
            Some(listener) => match listener.incoming().next() {
                Some(resstream) => match resstream {
                    Ok(mut stream) => {
                        let mut buffer: [u8; 65535] = [0; 65535];
                        let mut data_len = match stream.read(&mut buffer) {
                            Ok(bytes) => bytes,
                            Err(e) => return Some(Err(e)),
                        };
                        while data_len == 0 {
                            data_len = stream.read(&mut buffer).unwrap();
                        }
                        let dec_data = rsa_decrypt(&self.priv_key, &buffer[0..data_len], data_len)
                            .expect("decryption failed"); /* {
                                                              Ok(data) => data,
                                                              Err(_e) => {
                                                                  return Some(Err(std::io::Error::new(
                                                                      std::io::ErrorKind::PermissionDenied,
                                                                      "unauthorized connection",
                                                                  )))
                                                              }
                                                          };*/
                        let peer =
                            serde_json::from_str(&String::from_utf8(dec_data).unwrap()).unwrap();
                        Some(Ok(NetworkStream::new(stream, self.priv_key.clone(), peer)))
                    }
                    Err(e) => Some(Err(e)),
                },
                None => None,
            },
            None => Some(Err(std::io::Error::new(
                std::io::ErrorKind::PermissionDenied,
                "this host is peer only",
            ))),
        }
    }
}

impl ArtificeHost {
    pub fn from_host_data(config: &ArtificeConfig) -> std::io::Result<Self> {
        let broadcast = config.broadcast();
        let data = config.host_data();
        let port = config.port();
        let address = config.address();
        let socket_addr = address.to_socket_addr(port);
        let priv_key_comp = data.private_key();
        let priv_key = RSAPrivateKey::from_components(
            priv_key_comp.n().into_inner(),
            priv_key_comp.e().into_inner(),
            priv_key_comp.d().into_inner(),
            priv_key_comp
                .primes()
                .into_iter()
                .map(|v| v.into_inner())
                .collect(),
        );
        let listener = Some(TcpListener::bind(socket_addr)?);
        Ok(Self {
            priv_key,
            broadcast,
            socket_addr,
            listener,
        })
    }
    pub fn connect(&self, peer: ArtificePeer) -> std::io::Result<NetworkStream> {
        let mut stream = TcpStream::connect(peer.socket_addr())?;
        // encrypt the peer before sending
        let key = peer.pubkeypair();
        let public_key = RSAPublicKey::new(key.n(), key.e()).expect("couldn't create key");
        let data = serde_json::to_string(&peer).unwrap().into_bytes();
        let enc_data = rsa_encrypt(&public_key, &data).unwrap();
        stream.write(&enc_data)?;
        Ok(NetworkStream::new(stream, self.priv_key.clone(), peer))
    }
    /// designed only for testing but may be used for non global peers
    pub fn client_only(config: &ArtificeConfig) -> Self {
        let broadcast = config.broadcast();
        let data = config.host_data();
        let port = config.port();
        let address = config.address();
        let socket_addr = address.to_socket_addr(port);
        let priv_key_comp = data.private_key();
        let priv_key = RSAPrivateKey::from_components(
            priv_key_comp.n().into_inner(),
            priv_key_comp.e().into_inner(),
            priv_key_comp.d().into_inner(),
            priv_key_comp
                .primes()
                .into_iter()
                .map(|v| v.into_inner())
                .collect(),
        );
        let listener = None;
        Self {
            priv_key,
            broadcast,
            socket_addr,
            listener,
        }
    }
    /// broadcast the information about this peer to other peers on the network
    /// returns a sender that can be used to stop broadcasting
    pub fn begin_broadcast(&self) -> std::io::Result<Sender<bool>> {
        let (sender, recv) = channel();
        let socket = UdpSocket::bind(self.socket_addr)?;
        socket.set_broadcast(true)?;
        if !self.broadcast {
            return Err(std::io::Error::new(
                std::io::ErrorKind::PermissionDenied,
                "this host is not configured to broadcast",
            ));
        }
        thread::spawn(move || loop {
            match recv.recv_timeout(Duration::from_millis(200)) {
                Ok(_) => break,
                Err(e) => match e {
                    RecvTimeoutError::Timeout => continue,
                    RecvTimeoutError::Disconnected => break,
                },
            }
        });
        Ok(sender)
    }
}