tox 0.0.5

Implementation of toxcore in pure Rust - P2P, distributed, encrypted, easy to use DHT-based network.
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/*! Onion UDP Packets
*/

mod onion_announce_request;
mod onion_announce_response;
mod inner_onion_request;
mod inner_onion_response;
mod onion_data_request;
mod onion_data_response;
mod onion_request_0;
mod onion_request_1;
mod onion_request_2;
mod onion_response_1;
mod onion_response_2;
mod onion_response_3;

pub use self::onion_announce_request::*;
pub use self::onion_announce_response::*;
pub use self::inner_onion_request::*;
pub use self::inner_onion_response::*;
pub use self::onion_data_request::*;
pub use self::onion_data_response::*;
pub use self::onion_request_0::*;
pub use self::onion_request_1::*;
pub use self::onion_request_2::*;
pub use self::onion_response_1::*;
pub use self::onion_response_2::*;
pub use self::onion_response_3::*;

use toxcore::binary_io::*;
use toxcore::crypto_core::*;
use toxcore::dht::packed_node::PackedNode;

use nom::{be_u16, le_u8, rest};
use std::net::{
    IpAddr,
    Ipv4Addr,
    Ipv6Addr,
    SocketAddr,
};
use std::io::{Error, ErrorKind};

/// IPv4 is padded with 12 bytes of zeroes so that both IPv4 and
/// IPv6 have the same stored size.
pub const IPV4_PADDING_SIZE: usize = 12;

/// Size of serialized `IpPort` struct.
pub const SIZE_IPPORT: usize = 19;

/// Size of first `OnionReturn` struct with no inner `OnionReturn`s.
pub const ONION_RETURN_1_SIZE: usize = secretbox::NONCEBYTES + SIZE_IPPORT + MACBYTES; // 59
/// Size of second `OnionReturn` struct with one inner `OnionReturn`.
pub const ONION_RETURN_2_SIZE: usize = secretbox::NONCEBYTES + SIZE_IPPORT + MACBYTES + ONION_RETURN_1_SIZE; // 118
/// Size of third `OnionReturn` struct with two inner `OnionReturn`s.
pub const ONION_RETURN_3_SIZE: usize = secretbox::NONCEBYTES + SIZE_IPPORT + MACBYTES + ONION_RETURN_2_SIZE; // 177

/// The maximum size of onion packet including public key, nonce, packet kind
/// byte, onion return.
pub const ONION_MAX_PACKET_SIZE: usize = 1400;

/** Transport protocol type: `UDP` or `TCP`.

The binary representation of `ProtocolType` is a single bit: 0 for `UDP`, 1 for
`TCP`. If encoded as standalone value, the bit is stored in the least
significant bit of a byte.

*/
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ProtocolType {
    /// `UDP` type if the least significant bit is 0.
    UDP,
    /// `TCP` type if the least significant bit is 1.
    TCP
}

/** `IpAddr` with a port number. IPv4 is padded with 12 bytes of zeros
so that both IPv4 and IPv6 have the same stored size.

Serialized form:

Length      | Content
----------- | ------
`1`         | IpType
`4` or `16` | IPv4 or IPv6 address
`0` or `12` | Padding for IPv4
`2`         | Port

*/
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IpPort {
    /// Type of protocol
    pub protocol: ProtocolType,
    /// IP address
    pub ip_addr: IpAddr,
    /// Port number
    pub port: u16
}

impl FromBytes for IpPort {
    named!(from_bytes<IpPort>, alt!(call!(IpPort::from_udp_bytes) | call!(IpPort::from_tcp_bytes)));
}

impl ToBytes for IpPort {
    fn to_bytes<'a>(&self, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
        do_gen!(buf,
            gen_be_u8!(self.ip_type()) >>
            gen_call!(|buf, ip_addr| IpAddr::to_bytes(ip_addr, buf), &self.ip_addr) >>
            gen_cond!(self.ip_addr.is_ipv4(), gen_slice!(&[0; IPV4_PADDING_SIZE])) >>
            gen_be_u16!(self.port)
        )
    }
}

impl IpPort {
    /** Get IP Type byte.

    * 1st bit - protocol
    * 4th bit - address family

    Value | Type
    ----- | ----
    `2`   | UDP IPv4
    `10`  | UDP IPv6
    `130` | TCP IPv4
    `138` | TCP IPv6

    */
    fn ip_type(&self) -> u8 {
        if self.ip_addr.is_ipv4() {
            match self.protocol {
                ProtocolType::UDP => 2,
                ProtocolType::TCP => 130,
            }
        } else {
            match self.protocol {
                ProtocolType::UDP => 10,
                ProtocolType::TCP => 138,
            }
        }
    }

    named!(
        #[allow(unused_variables)]
        #[doc = "Parse `IpPort` with UDP protocol type."],
        from_udp_bytes<IpPort>,
        do_parse!(
            ip_addr: switch!(le_u8,
                2 => terminated!(
                    map!(Ipv4Addr::from_bytes, IpAddr::V4),
                    take!(IPV4_PADDING_SIZE)
                ) |
                10 => map!(Ipv6Addr::from_bytes, IpAddr::V6)
            ) >>
            port: be_u16 >>
            (IpPort { protocol: ProtocolType::UDP, ip_addr, port })
        )
    );

    named!(
        #[allow(unused_variables)]
        #[doc = "Parse `IpPort` with TCP protocol type."],
        from_tcp_bytes<IpPort>,
        do_parse!(
            ip_addr: switch!(le_u8,
                130 => terminated!(
                    map!(Ipv4Addr::from_bytes, IpAddr::V4),
                    take!(IPV4_PADDING_SIZE)
                ) |
                138 => map!(Ipv6Addr::from_bytes, IpAddr::V6)
            ) >>
            port: be_u16 >>
            (IpPort { protocol: ProtocolType::TCP, ip_addr, port })
        )
    );

    /// Write `IpPort` with UDP protocol type.
    pub fn to_udp_bytes<'a>(&self, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
        do_gen!(buf,
            gen_cond!(self.protocol == ProtocolType::TCP, |buf| gen_error(buf, 0)) >>
            gen_call!(|buf, ip_port| IpPort::to_bytes(ip_port, buf), self)
        )
    }

    /// Write `IpPort` with TCP protocol type.
    pub fn to_tcp_bytes<'a>(&self, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
        do_gen!(buf,
            gen_cond!(self.protocol == ProtocolType::UDP, |buf| gen_error(buf, 0)) >>
            gen_call!(|buf, ip_port| IpPort::to_bytes(ip_port, buf), self)
        )
    }

    /// Create new `IpPort` from `SocketAddr` with UDP type.
    pub fn from_udp_saddr(saddr: SocketAddr) -> IpPort {
        IpPort {
            protocol: ProtocolType::UDP,
            ip_addr: saddr.ip(),
            port: saddr.port()
        }
    }

    /// Create new `IpPort` from `SocketAddr` with TCP type.
    pub fn from_tcp_saddr(saddr: SocketAddr) -> IpPort {
        IpPort {
            protocol: ProtocolType::TCP,
            ip_addr: saddr.ip(),
            port: saddr.port()
        }
    }

    /// Convert `IpPort` to `SocketAddr`.
    pub fn to_saddr(&self) -> SocketAddr {
        SocketAddr::new(self.ip_addr, self.port)
    }
}

/** Encrypted onion return addresses. Payload contains encrypted with symmetric
key `IpPort` and possibly inner `OnionReturn`.

When DHT node receives OnionRequest packet it appends `OnionReturn` to the end
of the next request packet it will send. So when DHT node receives OnionResponse
packet it will know where to send the next response packet by decrypting
`OnionReturn` from received packet. If node can't decrypt `OnionReturn` that
means that onion path is expired and packet should be dropped.

Serialized form:

Length                | Content
--------              | ------
`24`                  | `Nonce`
`35` or `94` or `153` | Payload

where payload is encrypted inner `OnionReturn`

*/
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OnionReturn {
    /// Nonce for the current encrypted payload
    pub nonce: secretbox::Nonce,
    /// Encrypted payload
    pub payload: Vec<u8>
}

impl FromBytes for OnionReturn {
    named!(from_bytes<OnionReturn>, do_parse!(
        nonce: call!(secretbox::Nonce::from_bytes) >>
        payload: rest >>
        (OnionReturn { nonce, payload: payload.to_vec() })
    ));
}

impl ToBytes for OnionReturn {
    fn to_bytes<'a>(&self, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
        do_gen!(buf,
            gen_slice!(self.nonce.as_ref()) >>
            gen_slice!(self.payload)
        )
    }
}

impl OnionReturn {
    fn inner_to_bytes<'a>(ip_port: &IpPort, inner: Option<&OnionReturn>, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
        do_gen!(buf,
            gen_call!(|buf, ip_port| IpPort::to_bytes(ip_port, buf), ip_port) >>
            gen_call!(|buf, inner| match inner {
                Some(inner) => OnionReturn::to_bytes(inner, buf),
                None => Ok(buf)
            }, inner)
        )
    }

    named!(inner_from_bytes<(IpPort, Option<OnionReturn>)>, do_parse!(
        ip_port: call!(IpPort::from_bytes) >>
        rest_len: rest_len >>
        inner: cond!(rest_len > 0, OnionReturn::from_bytes) >>
        (ip_port, inner)
    ));

    /// Create new `OnionReturn` object using symmetric key for encryption.
    pub fn new(symmetric_key: &secretbox::Key, ip_port: &IpPort, inner: Option<&OnionReturn>) -> OnionReturn {
        let nonce = secretbox::gen_nonce();
        let mut buf = [0; ONION_RETURN_2_SIZE + SIZE_IPPORT];
        let (_, size) = OnionReturn::inner_to_bytes(ip_port, inner, (&mut buf, 0)).unwrap();
        let payload = secretbox::seal(&buf[..size], &nonce, symmetric_key);

        OnionReturn { nonce, payload }
    }

    /** Decrypt payload with symmetric key and try to parse it as `IpPort` with possibly inner `OnionReturn`.

    Returns `Error` in case of failure:

    - fails to decrypt
    - fails to parse as `IpPort` with possibly inner `OnionReturn`
    */
    pub fn get_payload(&self, symmetric_key: &secretbox::Key) -> Result<(IpPort, Option<OnionReturn>), Error> {
        let decrypted = secretbox::open(&self.payload, &self.nonce, symmetric_key)
            .map_err(|()| {
                debug!("Decrypting OnionReturn failed!");
                Error::new(ErrorKind::Other, "OnionReturn decrypt error.")
            })?;
        match OnionReturn::inner_from_bytes(&decrypted) {
            IResult::Incomplete(e) => {
                debug!(target: "Onion", "Inner onion return deserialize error: {:?}", e);
                Err(Error::new(ErrorKind::Other,
                    format!("Inner onion return deserialize error: {:?}", e)))
            },
            IResult::Error(e) => {
                debug!(target: "Onion", "Inner onion return deserialize error: {:?}", e);
                Err(Error::new(ErrorKind::Other,
                    format!("Inner onion return deserialize error: {:?}", e)))
            },
            IResult::Done(_, inner) => {
                Ok(inner)
            }
        }
    }
}

/** Represents the result of sent `AnnounceRequest`.

Also known as `is_stored` number.

*/
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AnnounceStatus {
    /// Failed to announce ourselves or find requested node
    Failed = 0,
    /// Requested node is found by its long term `PublicKey`
    Found = 1,
    /// We successfully announced ourselves
    Announced = 2
}

impl FromBytes for AnnounceStatus {
    named!(from_bytes<AnnounceStatus>, switch!(le_u8,
        0 => value!(AnnounceStatus::Failed) |
        1 => value!(AnnounceStatus::Found) |
        2 => value!(AnnounceStatus::Announced)
    ));
}

impl ToBytes for AnnounceStatus {
    fn to_bytes<'a>(&self, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
        gen_be_u8!(buf, *self as u8)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const ONION_RETURN_1_PAYLOAD_SIZE: usize = ONION_RETURN_1_SIZE - secretbox::NONCEBYTES;

    encode_decode_test!(
        ip_port_udp_encode_decode,
        IpPort {
            protocol: ProtocolType::UDP,
            ip_addr: "5.6.7.8".parse().unwrap(),
            port: 12345
        }
    );

    encode_decode_test!(
        ip_port_tcp_encode_decode,
        IpPort {
            protocol: ProtocolType::TCP,
            ip_addr: "5.6.7.8".parse().unwrap(),
            port: 12345
        }
    );

    encode_decode_test!(
        onion_return_encode_decode,
        OnionReturn {
            nonce: secretbox::gen_nonce(),
            payload: vec![42; ONION_RETURN_1_PAYLOAD_SIZE]
        }
    );

    encode_decode_test!(announce_status_failed, AnnounceStatus::Failed);

    encode_decode_test!(announce_status_found, AnnounceStatus::Found);

    encode_decode_test!(announce_status_accounced, AnnounceStatus::Announced);

    #[test]
    fn ip_port_from_to_udp_saddr() {
        let ip_port_1 = IpPort {
            protocol: ProtocolType::UDP,
            ip_addr: "5.6.7.8".parse().unwrap(),
            port: 12345
        };
        let ip_port_2 = IpPort::from_udp_saddr(ip_port_1.to_saddr());
        assert_eq!(ip_port_2, ip_port_1);
    }

    #[test]
    fn ip_port_from_to_tcp_saddr() {
        let ip_port_1 = IpPort {
            protocol: ProtocolType::TCP,
            ip_addr: "5.6.7.8".parse().unwrap(),
            port: 12345
        };
        let ip_port_2 = IpPort::from_tcp_saddr(ip_port_1.to_saddr());
        assert_eq!(ip_port_2, ip_port_1);
    }

    #[test]
    fn onion_return_encrypt_decrypt() {
        let alice_symmetric_key = secretbox::gen_key();
        let bob_symmetric_key = secretbox::gen_key();
        // alice encrypt
        let ip_port_1 = IpPort {
            protocol: ProtocolType::UDP,
            ip_addr: "5.6.7.8".parse().unwrap(),
            port: 12345
        };
        let onion_return_1 = OnionReturn::new(&alice_symmetric_key, &ip_port_1, None);
        // bob encrypt
        let ip_port_2 = IpPort {
            protocol: ProtocolType::UDP,
            ip_addr: "7.8.5.6".parse().unwrap(),
            port: 54321
        };
        let onion_return_2 = OnionReturn::new(&bob_symmetric_key, &ip_port_2, Some(&onion_return_1));
        // bob can decrypt it's return address
        let (decrypted_ip_port_2, decrypted_onion_return_1) = onion_return_2.get_payload(&bob_symmetric_key).unwrap();
        assert_eq!(decrypted_ip_port_2, ip_port_2);
        assert_eq!(decrypted_onion_return_1.unwrap(), onion_return_1);
        // alice can decrypt it's return address
        let (decrypted_ip_port_1, none) = onion_return_1.get_payload(&alice_symmetric_key).unwrap();
        assert_eq!(decrypted_ip_port_1, ip_port_1);
        assert!(none.is_none());
    }

    #[test]
    fn onion_return_encrypt_decrypt_invalid_key() {
        let alice_symmetric_key = secretbox::gen_key();
        let bob_symmetric_key = secretbox::gen_key();
        let eve_symmetric_key = secretbox::gen_key();
        // alice encrypt
        let ip_port_1 = IpPort {
            protocol: ProtocolType::UDP,
            ip_addr: "5.6.7.8".parse().unwrap(),
            port: 12345
        };
        let onion_return_1 = OnionReturn::new(&alice_symmetric_key, &ip_port_1, None);
        // bob encrypt
        let ip_port_2 = IpPort {
            protocol: ProtocolType::UDP,
            ip_addr: "7.8.5.6".parse().unwrap(),
            port: 54321
        };
        let onion_return_2 = OnionReturn::new(&bob_symmetric_key, &ip_port_2, Some(&onion_return_1));
        // eve can't decrypt return addresses
        assert!(onion_return_1.get_payload(&eve_symmetric_key).is_err());
        assert!(onion_return_2.get_payload(&eve_symmetric_key).is_err());
    }

    #[test]
    fn onion_return_decrypt_invalid() {
        let symmetric_key = secretbox::gen_key();
        let nonce = secretbox::gen_nonce();
        // Try long invalid array
        let invalid_payload = [42; 123];
        let invalid_payload_encoded = secretbox::seal(&invalid_payload, &nonce, &symmetric_key);
        let invalid_onion_return = OnionReturn {
            nonce,
            payload: invalid_payload_encoded
        };
        assert!(invalid_onion_return.get_payload(&symmetric_key).is_err());
        // Try short incomplete array
        let invalid_payload = [];
        let invalid_payload_encoded = secretbox::seal(&invalid_payload, &nonce, &symmetric_key);
        let invalid_onion_return = OnionReturn {
            nonce,
            payload: invalid_payload_encoded
        };
        assert!(invalid_onion_return.get_payload(&symmetric_key).is_err());
    }
}