portal-lib 0.1.0

A Secure file transfer library, written in Rust. The library utilizes SPAKE2 for key negotiation over an insecure channel, and ChaCha20Poly1305 Authenticated Encryption to encrypt the file with the derived shared symmetric key. This enables two peers to transfer a file over any channel without needing to trust the intermediary relay.
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! portal-lib
//!
//! A small Protocol Library for [Portal](https://github.com/landhb/portal) - An encrypted file transfer utility 
//!
//! This crate enables a consumer to: 
//!
//! - Create/serialize/deserialize Portal request/response messages.
//! - Negoticate a symmetric key with a peer using [SPAKE2](https://docs.rs/spake2/0.2.0/spake2) 
//! - Encrypt files with [Chacha20poly1305](https://blog.cloudflare.com/it-takes-two-to-chacha-poly/) using the [RustCrypto implementation](https://github.com/rusticata/tls-parser)
//! - Send/receive files through a Portal relay
//!
//!
//! Example of SPAKE2 key negotiation:
//!
//! ```rust,no_run
//! // receiver
//! let dir = Some(Direction::Receiver);
//! let pass ="test".to_string();
//! let (mut receiver,receiver_msg) = Portal::init(dir,"id".to_string(),pass,None);
//!
//! // sender
//! let dir = Some(Direction::Sender);
//! let pass ="test".to_string();
//! let (mut sender,sender_msg) = Portal::init(dir,"id".to_string(),pass,None);
//!
//! receiver.confirm_peer(&sender_msg).unwrap();
//! sender.confirm_peer(&receiver_msg).unwrap();
//!
//! assert_eq!(receiver.key,sender.key);
//! ```
//!
//! Example of Sending a file:
//!
//! ```rust,no_run
//! // open file read-only for sending
//! let mut file = portal.load_file(fpath)?;
//!
//! // Encrypt the file and share state 
//! file.encrypt()?;
//! file.sync_file_state(&mut client)?;
//!
//! // This will be empty for files created with create_file()
//! let chunks = portal.get_chunks(&file,portal::CHUNK_SIZE);
//!
//! for data in chunks.into_iter() {
//!     client.write_all(&data)?;
//!     total += data.len(); 
//! }
//! ```
//!
//! Example of Receiving a file:
//!
//! ```rust,no_run
//! // create outfile
//! let mut file = portal.create_file(&fname, fsize)?;
//!
//! // Receive until connection is done
//! let len = match file.download_file(&client,|x| {pb.set_position(x)})?;
//!
//! assert_eq!(len as u64, fsize);
//!
//! // Decrypt the file
//! file.decrypt()?;
//! ```


use anyhow::Result;
use serde::{Serialize, Deserialize};
use std::fs::File;
use memmap::MmapOptions;
use std::fs::OpenOptions;

// Key Exchange
use spake2::{Ed25519Group, Identity, Password, SPAKE2,Group};
use sha2::{Sha256, Digest};

// File encryption
use chacha20poly1305::{ChaCha20Poly1305, Key}; 
use chacha20poly1305::aead::{NewAead};

pub mod errors;
mod file;
mod chunks;


use errors::PortalError;
use file::PortalFile;
use chunks::PortalChunks;

pub const DEFAULT_PORT: u16 = 13265;
pub const CHUNK_SIZE: usize = 65535;


/**
 * The primary interface into the library
 */
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct Portal{

    // Information to correlate
    // connections on the relay
    id: String,
    direction: Option<Direction>,

    // Metadata to be exchanged
    // between peers
    filename: Option<String>,
    filesize: u64,

    // Never serialized or sent to the relay
    #[serde(skip)]
    state: Option<SPAKE2<Ed25519Group>>,

    // Never serialized or sent to the relay
    #[serde(skip)]
    key: Option<Vec<u8>>,
}



#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub enum Direction {
    Sender,
    Receiver,
}


impl Portal {
    
    /**
     * Initialize 
     */
    pub fn init(direction: Option<Direction>, 
                id: String,
                password: String,
                mut filename: Option<String>) -> (Portal,Vec<u8>) {

        
        // hash the ID string
        let mut hasher = Sha256::new();
        hasher.update(&id);
        let id_bytes = hasher.finalize();
        let id_hash = hex::encode(&id_bytes);

        let (s1, outbound_msg) = SPAKE2::<Ed25519Group>::start_symmetric(
           &Password::new(&password.as_bytes()),
           &Identity::new(&id_bytes));
       
        // if a file was provided, trim it to just the file name
        if let Some(file) = filename {
            let f = std::path::Path::new(&file);
            let f = f.file_name().unwrap().to_str().unwrap();
            filename = Some(f.to_string());
        }

        return (Portal {
            direction: direction,
            id: id_hash,
            filename: filename,
            filesize: 0,
            state: Some(s1),
            key: None,
        }, outbound_msg);
    }

    /**
     * Construct from a stream reader, consuming the bytes
     */
    pub fn read_response_from<R>(reader: R) -> Result<Portal> 
    where
        R: std::io::Read {
        Ok(bincode::deserialize_from::<R,Portal>(reader)?)
    }

    /**
     * Receive the bytes necessary for a confirmation message
     * from a stream reader, consuming the bytes
     */
    pub fn read_confirmation_from<R>(mut reader: R) -> Result<[u8;33]> 
    where
       R: std::io::Read {
        assert_eq!(33,Portal::get_peer_msg_size());
        let mut res = [0u8;33];
        reader.read(&mut res)?;
        Ok(res)
    }

    /**
     * Attempt to deserialize from a vector
     */
    pub fn parse(data: &Vec<u8>) -> Result<Portal> {
        Ok(bincode::deserialize(&data)?)
    }

    pub fn serialize(&self) -> Result<Vec<u8>> {
        Ok(bincode::serialize(&self)?)
    }

    pub fn get_file_size(&self) -> u64 {
        self.filesize
    }

    pub fn set_file_size(&mut self, size: u64) {
        self.filesize = size;
    } 

    pub fn get_file_name<'a>(&'a self) -> Result<&'a str> {
        match &self.filename {
            Some(f) => Ok(f.as_str()),
            None => Err(PortalError::NoneError.into()),
        }
    }

    pub fn get_id(&self) -> &String {
        &self.id
    }

    pub fn get_direction(&self) -> Option<Direction> {
        self.direction.clone()
    }

    pub fn set_id(&mut self, id: String) {
        self.id = id;
    }

    pub fn set_direction(&mut self, direction: Option<Direction>) {
        self.direction = direction;
    }

    /*
     * mmap's a file into memory for reading
     */
    pub fn load_file<'a>(&'a self, f: &str) -> Result<PortalFile>  {
        let file = File::open(f)?;
        let mmap = unsafe { MmapOptions::new().map_copy(&file)? };

        let key = self.key.as_ref().ok_or_else(|| PortalError::NoPeer)?;
        let cha_key = Key::from_slice(&key[..]);

        let cipher = ChaCha20Poly1305::new(cha_key);
        

        //Ok(PortalFile::Immutable(PortalFileImmutable::init(mmap,state)))
        Ok(PortalFile::init(mmap,cipher))
    }


    /*
     * mmap's a file into memory for writing
     */
    pub fn create_file<'a>(&'a self, f: &str, size: u64) -> Result<PortalFile>  {

        let file = OpenOptions::new()
                       .read(true)
                       .write(true)
                       .create(true)
                       .open(&f)?;

        file.set_len(size)?;

        let key = self.key.as_ref().ok_or_else(|| PortalError::NoPeer)?;


        let mmap = unsafe {
            MmapOptions::new().map_mut(&file)?
        };

        let cha_key = Key::from_slice(&key[..]);

        let cipher = ChaCha20Poly1305::new(cha_key);

        //Ok(PortalFile::Mutable(PortalFileMutable::init(file,state)))
        Ok(PortalFile::init(mmap,cipher))
    }

    /**
     * Returns an iterator over the chunks to send it over the
     * network
     */
    pub fn get_chunks<'a>(&self, data: &'a PortalFile, chunk_size: usize) -> PortalChunks<'a,u8> {


        PortalChunks::init(
            &data.mmap[..], // TODO: verify that this is zero-copy/move
            chunk_size,
        )
    }


    pub fn confirm_peer(&mut self, msg_data: &[u8]) -> Result<()> {

        // after calling finish() the SPAKE2 struct will be consumed
        // so we must replace the value stored in self.state
        let state = std::mem::replace(&mut self.state, None);

        let state = state.ok_or_else(|| PortalError::BadState)?;

        self.key = match state.finish(msg_data) {
            Ok(res) => Some(res),
            Err(_) => {return Err(PortalError::BadMsg.into());}
        };

        Ok(())
    }

    fn get_peer_msg_size() -> usize {
        // The exchanged message is the CompressedEdwardsY + 1 byte for the SPAKE direction
        let edwards_point = <spake2::Ed25519Group as Group>::Element::default();
        let compressed = edwards_point.compress();
        std::mem::size_of_val(&compressed)+1
    }

}

#[cfg(test)]
mod tests {
    use super::{Portal,Direction};

    #[test]
    fn key_derivation() {

        // receiver
        let dir = Some(Direction::Receiver);
        let pass ="test".to_string();
        let (mut receiver,receiver_msg) = Portal::init(dir,"id".to_string(),pass,None);

        // sender
        let dir = Some(Direction::Sender);
        let pass ="test".to_string();
        let (mut sender,sender_msg) = Portal::init(dir,"id".to_string(),pass,None);

        receiver.confirm_peer(&sender_msg).unwrap();
        sender.confirm_peer(&receiver_msg).unwrap();

        assert_eq!(receiver.key,sender.key);
    }

    #[test]
    fn portal_load_file() {
        let dir = Some(Direction::Receiver);
        let pass ="test".to_string();
        let (_receiver,receiver_msg) = Portal::init(dir,"id".to_string(),pass,None);

        // sender
        let dir = Some(Direction::Sender);
        let pass ="test".to_string();
        let (mut sender,_sender_msg) = Portal::init(dir,"id".to_string(),pass,None);

        // Confirm
        sender.confirm_peer(&receiver_msg).unwrap();

        // TODO change test file
        let _file = sender.load_file("/etc/passwd").unwrap();
    }

    #[test]
    fn portalfile_chunks_iterator() {
        
        // receiver
        let dir = Some(Direction::Receiver);
        let pass ="test".to_string();
        let (_receiver,receiver_msg) = Portal::init(dir,"id".to_string(),pass,None);

        // sender
        let dir = Some(Direction::Sender);
        let pass ="test".to_string();
        let (mut sender,_sender_msg) = Portal::init(dir,"id".to_string(),pass,None);

        // Confirm
        sender.confirm_peer(&receiver_msg).unwrap();

        // TODO change test file
        let file = sender.load_file("/etc/passwd").unwrap();

        let chunk_size = 10;
        let chunks = sender.get_chunks(&file,chunk_size);
        for v in chunks.into_iter() {
            assert!(v.len() <= chunk_size);
        }


        let chunk_size = 1024;
        let chunks = sender.get_chunks(&file,chunk_size);
        for v in chunks.into_iter() {
            assert!(v.len() <= chunk_size);
        }

    }

    #[test]
    fn portal_createfile() {
        // receiver
        let dir = Some(Direction::Receiver);
        let pass ="test".to_string();
        let (mut receiver,receiver_msg) = Portal::init(dir,"id".to_string(),pass,None);

        // sender
        let dir = Some(Direction::Sender);
        let pass ="test".to_string();
        let (mut sender,sender_msg) = Portal::init(dir,"id".to_string(),pass,None);

        // Confirm
        sender.confirm_peer(&receiver_msg).unwrap();
        receiver.confirm_peer(&sender_msg).unwrap();

        // TODO change test file
        let _file_dst = receiver.create_file("/tmp/passwd",4096).unwrap();
    }

    #[test]
    fn portal_write_chunk() {
        // receiver
        let dir = Some(Direction::Receiver);
        let pass ="test".to_string();
        let (mut receiver,receiver_msg) = Portal::init(dir,"id".to_string(),pass,None);

        // sender
        let dir = Some(Direction::Sender);
        let pass ="test".to_string();
        let (mut sender,sender_msg) = Portal::init(dir,"id".to_string(),pass,None);

        // Confirm
        sender.confirm_peer(&receiver_msg).unwrap();
        receiver.confirm_peer(&sender_msg).unwrap();

        // TODO change test file
        let file_src = sender.load_file("/etc/passwd").unwrap();
        let mut file_dst = receiver.create_file("/tmp/passwd",4096).unwrap();

        let chunk_size = 4096;
        let chunks = sender.get_chunks(&file_src,chunk_size);

        for v in chunks.into_iter() {

            assert!(v.len() <= chunk_size);

            // test writing chunk
            file_dst.write_given_chunk(&v).unwrap();
        } 
    }

    #[test]
    #[should_panic]
    fn portal_createfile_no_peer() {
        let dir = Some(Direction::Sender);
        let pass = "test".to_string();
        let (portal,_msg) = Portal::init(dir,"id".to_string(),pass, None);

        // will panic due to lack of peer
        let _file_dst = portal.create_file("/tmp/passwd",4096).unwrap();
    }

    #[test]
    #[should_panic]
    fn portal_loadfile_no_peer() {
        let dir = Some(Direction::Sender);
        let pass = "test".to_string();
        let (portal,_msg) = Portal::init(dir,"id".to_string(),pass, None);

        // will panic due to lack of peer
        let _file_src = portal.load_file("/etc/passwd").unwrap();
    }

}