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
/*! Cookie struct
*/

use super::*;
use nom::number::complete::be_u64;

use std::time::SystemTime;

use tox_binary_io::*;
use tox_crypto::*;
use crate::dht::errors::*;

/// Number of seconds that generated cookie is valid
pub const COOKIE_TIMEOUT: u64 = 15;

/** Cookie is a struct that holds two public keys of a node: long term key and
short term DHT key.

When Alice establishes `net_crypto` connection with Bob she sends
`CookieRequest` packet to Bob with her public keys and receives encrypted
`Cookie` with these keys from `CookieResponse` packet. When Alice obtains a
`Cookie` she uses it to send `CryptoHandshake` packet. This packet will contain
received from Bob cookie and new `Cookie` generated by Alice. Then Bob checks
his `Coocke` and uses `Cookie` from Alice to send `CryptoHandshake` packet to
her.

Only node that encrypted a `Cookie` can decrypt it so when node gets
`CryptoHandshake` packet with `Cookie` it can check that the sender of this
packet received a cookie response.

Cookie also contains the time when it was generated. It's considered invalid
after 15 seconds have elapsed since the moment of generation.

Serialized form:

Length | Content
------ | ------
`8`    | Cookie timestamp
`32`   | Long term `PublicKey`
`32`   | DHT `PublicKey`

*/
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Cookie {
    /// Time when this cookie was generated
    pub time: u64,
    /// Long term `PublicKey`
    pub real_pk: PublicKey,
    /// DHT `PublicKey`
    pub dht_pk: PublicKey,
}

impl Cookie {
    /// Create new `Cookie`
    pub fn new(real_pk: PublicKey, dht_pk: PublicKey) -> Cookie {
        Cookie {
            time: unix_time(SystemTime::now()),
            real_pk,
            dht_pk,
        }
    }

    /** Check if this cookie is timed out.

    Cookie considered timed out after 15 seconds since it was created.

    */
    pub fn is_timed_out(&self) -> bool {
        self.time + COOKIE_TIMEOUT < unix_time(SystemTime::now())
    }
}

impl FromBytes for Cookie {
    named!(from_bytes<Cookie>, do_parse!(
        time: be_u64 >>
        real_pk: call!(PublicKey::from_bytes) >>
        dht_pk: call!(PublicKey::from_bytes) >>
        eof!() >>
        (Cookie { time, real_pk, dht_pk })
    ));
}

impl ToBytes for Cookie {
    fn to_bytes<'a>(&self, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
        do_gen!(buf,
            gen_be_u64!(self.time) >>
            gen_slice!(self.real_pk.as_ref()) >>
            gen_slice!(self.dht_pk.as_ref())
        )
    }
}

/** Encrypted with symmetric key `Cookie`.

Serialized form:

Length | Content
------ | ------
`24`   | Nonce
`88`   | Payload

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

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

impl ToBytes for EncryptedCookie {
    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.as_slice())
        )
    }
}

impl EncryptedCookie {
    /// Create `EncryptedCookie` from `Cookie` encrypting it with `symmetric_key`
    pub fn new(symmetric_key: &secretbox::Key, payload: &Cookie) -> EncryptedCookie {
        let nonce = secretbox::gen_nonce();
        let mut buf = [0; 72];
        let (_, size) = payload.to_bytes((&mut buf, 0)).unwrap();
        let payload = secretbox::seal(&buf[..size], &nonce, symmetric_key);

        EncryptedCookie {
            nonce,
            payload,
        }
    }
    /** Decrypt payload with symmetric key and try to parse it as `Cookie`.

    Returns `Error` in case of failure:

    - fails to decrypt
    - fails to parse `Cookie`
    */
    pub fn get_payload(&self, symmetric_key: &secretbox::Key) -> Result<Cookie, GetPayloadError> {
        let decrypted = secretbox::open(&self.payload, &self.nonce, symmetric_key)
            .map_err(|()| {
                GetPayloadError::decrypt()
            })?;
        match Cookie::from_bytes(&decrypted) {
            Err(error) => {
                Err(GetPayloadError::deserialize(error, decrypted.clone()))
            },
            Ok((_, payload)) => {
                Ok(payload)
            }
        }
    }
    /// Calculate SHA512 hash of encrypted cookie together with nonce
    pub fn hash(&self) -> sha512::Digest {
        let mut buf = [0; 112];
        let (_, size) = self.to_bytes((&mut buf, 0)).unwrap();
        sha512::hash(&buf[..size])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use nom::{Err, error::ErrorKind};

    encode_decode_test!(
        tox_crypto::crypto_init().unwrap(),
        cookie_encode_decode,
        Cookie {
            time: 12345,
            real_pk: gen_keypair().0,
            dht_pk: gen_keypair().0,
        }
    );

    encode_decode_test!(
        tox_crypto::crypto_init().unwrap(),
        encrypted_cookie_encode_decode,
        EncryptedCookie {
            nonce: secretbox::gen_nonce(),
            payload: vec![42; 88],
        }
    );

    #[test]
    fn cookie_encrypt_decrypt() {
        crypto_init().unwrap();
        let symmetric_key = secretbox::gen_key();
        let payload = Cookie::new(gen_keypair().0, gen_keypair().0);
        // encode payload with symmetric key
        let encrypted_cookie = EncryptedCookie::new(&symmetric_key, &payload);
        // decode payload with symmetric key
        let decoded_payload = encrypted_cookie.get_payload(&symmetric_key).unwrap();
        // payloads should be equal
        assert_eq!(decoded_payload, payload);
    }

    #[test]
    fn cookie_encrypt_decrypt_invalid_key() {
        crypto_init().unwrap();
        let symmetric_key = secretbox::gen_key();
        let eve_symmetric_key = secretbox::gen_key();
        let payload = Cookie::new(gen_keypair().0, gen_keypair().0);
        // encode payload with symmetric key
        let encrypted_cookie = EncryptedCookie::new(&symmetric_key, &payload);
        // try to decode payload with eve's symmetric key
        let decoded_payload = encrypted_cookie.get_payload(&eve_symmetric_key);
        assert!(decoded_payload.is_err());
        assert_eq!(*decoded_payload.err().unwrap().kind(), GetPayloadErrorKind::Decrypt);
    }

    #[test]
    fn cookie_encrypt_decrypt_invalid() {
        crypto_init().unwrap();
        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_encrypted_cookie = EncryptedCookie {
            nonce,
            payload: invalid_payload_encoded
        };
        let decoded_payload = invalid_encrypted_cookie.get_payload(&symmetric_key);
        let error = decoded_payload.err().unwrap();
        assert_eq!(*error.kind(), GetPayloadErrorKind::Deserialize {
            error: Err::Error((vec![42; 51], ErrorKind::Eof)),
            payload: invalid_payload.to_vec()
        });
        // Try short incomplete array
        let invalid_payload = [];
        let invalid_payload_encoded = secretbox::seal(&invalid_payload, &nonce, &symmetric_key);
        let invalid_encrypted_cookie = EncryptedCookie {
            nonce,
            payload: invalid_payload_encoded
        };
        let decoded_payload = invalid_encrypted_cookie.get_payload(&symmetric_key);
        let error = decoded_payload.err().unwrap();
        assert_eq!(*error.kind(), GetPayloadErrorKind::Deserialize {
            error: Err::Error((vec![], ErrorKind::Eof)),
            payload: invalid_payload.to_vec()
        });
    }

    #[test]
    fn cookie_timed_out() {
        crypto_init().unwrap();
        let mut cookie = Cookie::new(gen_keypair().0, gen_keypair().0);
        assert!(!cookie.is_timed_out());
        cookie.time -= COOKIE_TIMEOUT + 1;
        assert!(cookie.is_timed_out());
    }

    #[test]
    fn hash_depends_on_all_fields() {
        crypto_init().unwrap();
        let nonce = secretbox::gen_nonce();
        let payload = vec![42; 88];
        let cookie = EncryptedCookie {
            nonce,
            payload: payload.clone()
        };

        let cookie_1 = EncryptedCookie {
            nonce,
            payload: vec![43; 88]
        };
        let cookie_2 = EncryptedCookie {
            nonce: secretbox::gen_nonce(),
            payload
        };

        assert_ne!(cookie.hash(), cookie_1.hash());
        assert_ne!(cookie.hash(), cookie_2.hash());
    }
}