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
/*!
E.g.

```
use tox_encryptsave::*;

let plaintext = b"pls no encrypt";
let password = b"123456";

// to encrypt data
let encrypted = pass_encrypt(plaintext, password)
    .expect("Failed to encrypt >.<\"");

// confirm that the data is encrypted
assert_ne!(plaintext, encrypted.as_slice());
assert!(is_encrypted(&encrypted));

// decrypted is same as plaintext
assert_eq!(plaintext,
           pass_decrypt(&encrypted, password).unwrap().as_slice());
```
*/

use failure::Fail;

use tox_crypto::pwhash::{
    MEMLIMIT_INTERACTIVE, OPSLIMIT_INTERACTIVE,
    Salt, OpsLimit,
    gen_salt, derive_key
};

use tox_crypto::{
    NONCEBYTES, MACBYTES,
    Nonce, PrecomputedKey,
    gen_nonce,
    secretbox, sha256
};

/// Length in bytes of the salt used to encrypt/decrypt data.
pub use tox_crypto::pwhash::SALTBYTES as SALT_LENGTH;
/// Length in bytes of the key used to encrypt/decrypt data.
pub use tox_crypto::PRECOMPUTEDKEYBYTES as KEY_LENGTH;

/// Length (in bytes) of [`MAGIC_NUMBER`](./constant.MAGIC_NUMBER.html).
pub const MAGIC_LENGTH: usize = 8;
/** Bytes used to verify whether given data has been encrypted using **TES**.

    Located at the beginning of the encrypted data.
*/
pub const MAGIC_NUMBER: &[u8; MAGIC_LENGTH] = b"toxEsave";
/** Minimal size in bytes of an encrypted file.

I.e. the amount of bytes that data will "gain" after encryption.
*/
pub const EXTRA_LENGTH: usize = MAGIC_LENGTH + SALT_LENGTH + NONCEBYTES + MACBYTES;

/** Key and `Salt` that are used to encrypt/decrypt data.
*/
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PassKey {
    // allocate stuff on heap to make sure that sensitive data is not moved
    // around on stack
    /// Salt is saved along with encrypted data and used to decrypt it.
    salt: Box<Salt>,
    /// Key used to encrypt/decrypt data. **DO NOT SAVE**.
    key: Box<PrecomputedKey>
}

impl PassKey {
    /**
    Create a new `PassKey` with a random `Salt`.

    **Note that `passphrase` memory is not being zeroed after it has been
    used**. Code that provides `passphrase` should take care of zeroing that
    memory.

    Can fail for the same reasons as [`PassKey::with_salt()`]
    (./struct.PassKey.html#method.with_salt), that is:

      * passphrase is empty
      * deriving key failed (can happen due to OOM)

    E.g.

    ```
    use tox_encryptsave::*;

    // fails with an empty passphrase
    assert_eq!(PassKey::from_passphrase(&[]), Err(KeyDerivationError::Null));
    ```
    */
    pub fn from_passphrase(passphrase: &[u8]) -> Result<PassKey, KeyDerivationError> {
        PassKey::with_salt(passphrase, gen_salt())
    }

    /** Create a new `PassKey` with provided `Salt`, rather than using a random
        one.

    **Note that `passphrase` memory is not being zeroed after it has been
    used**. Code that provides `passphrase` should take care of zeroing that
    memory.

    ## Fails when:

      * passphrase is empty
      * deriving key failed (can happen due to OOM)

    E.g.

    ```
    use tox_crypto::pwhash::gen_salt;
    use tox_encryptsave::*;

    assert_eq!(PassKey::with_salt(&[], gen_salt()), Err(KeyDerivationError::Null));
    ```
    */
    pub fn with_salt(passphrase: &[u8], salt: Salt) -> Result<PassKey, KeyDerivationError> {
        if passphrase.is_empty() { return Err(KeyDerivationError::Null) };

        let sha256::Digest(passhash) = sha256::hash(passphrase);
        let OpsLimit(ops) = OPSLIMIT_INTERACTIVE;
        let mut key = secretbox::Key([0; secretbox::KEYBYTES]);

        let maybe_key = PrecomputedKey::from_slice({
            // securely zeroes the key when `kb` goes out of scope
            let secretbox::Key(ref mut kb) = key;
            derive_key(
                kb,
                &passhash,
                &salt,
                OpsLimit(ops * 2),
                MEMLIMIT_INTERACTIVE
            ).or(Err(KeyDerivationError::Failed))?
        });

        let salt = Box::new(salt);
        let key = Box::new(maybe_key.ok_or(KeyDerivationError::Failed)?);

        Ok(PassKey { salt, key })
    }

    /**
    Encrypts provided `data` with `self` `PassKey`.

    Encrypted data is bigger than supplied data by [`EXTRA_LENGTH`]
    (./constant.EXTRA_LENGTH.html).

    ## Fails when:

      * provided `data` is empty

    E.g.

    ```
    use tox_encryptsave::*;

                                          // ↓ don't
    let passkey = PassKey::from_passphrase(&[0]).expect("Failed to unwrap PassKey!");

    assert_eq!(passkey.encrypt(&[]), Err(EncryptionError::Null));
    ```
    */
    pub fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>, EncryptionError> {
        if data.is_empty() { return Err(EncryptionError::Null) };

        let mut output = Vec::with_capacity(EXTRA_LENGTH + data.len());
        let nonce = gen_nonce();

        output.extend_from_slice(MAGIC_NUMBER);
        output.extend_from_slice(&self.salt.0);
        output.extend_from_slice(&nonce.0);
        output.append(&mut tox_crypto::encrypt_data_symmetric(
            &self.key,
            &nonce,
            data
        ));

        Ok(output)
    }

    /**
    Decrypts provided `data` with `self` `PassKey`.

    Decrypted data is smaller by [`EXTRA_LENGTH`](./constant.EXTRA_LENGTH.html)
    than encrypted data.

    ## Fails when:

      * provided `data` is empty
      * size of provided `data` is less than `EXTRA_LENGTH`
      * format of provided `data` is wrong
      * decrypting `data` fails
        - could be due to OOM or by providing bytes that aren't encrypted after
          encrypted part

    E.g.

    ```
    use tox_encryptsave::*;

                                          // ↓ don't
    let passkey = PassKey::from_passphrase(&[0]).expect("Failed to unwrap PassKey!");

    // empty data
    assert_eq!(passkey.decrypt(&[]), Err(DecryptionError::Null));
    ```
    */
    pub fn decrypt(&self, data: &[u8]) -> Result<Vec<u8>, DecryptionError> {
        if data.is_empty() { return Err(DecryptionError::Null) };
        if data.len() <= EXTRA_LENGTH { return Err(DecryptionError::InvalidLength) };
        if !is_encrypted(data) { return Err(DecryptionError::BadFormat) };

        let nonce = Nonce::from_slice(&data[
            MAGIC_LENGTH+SALT_LENGTH..MAGIC_LENGTH+SALT_LENGTH+NONCEBYTES
        ]).ok_or(DecryptionError::BadFormat)?;

        let output = tox_crypto::decrypt_data_symmetric(
            &self.key,
            &nonce,
            &data[MAGIC_LENGTH+SALT_LENGTH+NONCEBYTES..]
        ).or(Err(DecryptionError::Failed))?;

        Ok(output)
    }
}

/// Check if given piece of data appears to be encrypted by **TES**.
#[inline]
pub fn is_encrypted(data: &[u8]) -> bool {
    data.starts_with(MAGIC_NUMBER)
}

/**
Try to encrypt given data with provided passphrase.

**Note that `passphrase` memory is not being zeroed after it has been
used**. Code that provides `passphrase` should take care of zeroing that
memory.

# Fails when:

  * `data` is empty
  * `passphrase` is empty
  * deriving key failed (can happen due to OOM)

E.g.

```
use tox_encryptsave::*;

// empty data
assert_eq!(pass_encrypt(&[], &[0]), Err(EncryptionError::Null));

// empty passphrase
assert_eq!(pass_encrypt(&[0], &[]), Err(KeyDerivationError::Null.into()));
```
*/
pub fn pass_encrypt(data: &[u8], passphrase: &[u8]) -> Result<Vec<u8>, EncryptionError> {
    PassKey::from_passphrase(passphrase)?.encrypt(data)
}

/**
Try to decrypt given **TES** data with provided passphrase.

**Note that `passphrase` memory is not being zeroed after it has been
used**. Code that provides `passphrase` should take care of zeroing that
memory.

Decrypted data is smaller by [`EXTRA_LENGTH`](./constant.EXTRA_LENGTH.html)
than encrypted data.

## Fails when:

  * provided `data` is empty
  * size of provided `data` is less than `EXTRA_LENGTH`
  * format of provided `data` is wrong
  * decrypting `data` fails
    - could be due to OOM or by providing bytes that aren't encrypted after
      encrypted part
  * `passphrase` is empty

```
use tox_encryptsave::*;

// with an empty data
assert_eq!(pass_decrypt(&[], &[0]), Err(DecryptionError::Null));

// when there's not enough data to decrypt
assert_eq!(pass_decrypt(MAGIC_NUMBER, &[0]), Err(DecryptionError::InvalidLength));

let encrypted = pass_encrypt(&[0, 0], &[0]).expect("Failed to pass_encrypt!");

// when passphrase is empty
assert_eq!(pass_decrypt(&encrypted, &[]), Err(KeyDerivationError::Null.into()));

// when data format is wrong
for pos in 0..MAGIC_LENGTH {
    let mut enc = encrypted.clone();
    if enc[pos] == 0 { enc[pos] = 1; } else { enc[pos] = 0; }
    assert_eq!(pass_decrypt(&enc, &[0]), Err(DecryptionError::BadFormat));
}

{ // there are more or less bytes than the encrypted ones
    let mut enc = encrypted.clone();
    enc.push(0);
    assert_eq!(pass_decrypt(&enc, &[0]), Err(DecryptionError::Failed));

    // less
    enc.pop();
    enc.pop();
    assert_eq!(pass_decrypt(&enc, &[0]), Err(DecryptionError::Failed));
}
```
*/
pub fn pass_decrypt(data: &[u8], passphrase: &[u8]) -> Result<Vec<u8>, DecryptionError> {
    if data.is_empty() { return Err(DecryptionError::Null) }
    if data.len() <= EXTRA_LENGTH { return Err(DecryptionError::InvalidLength) }
    if !is_encrypted(data) { return Err(DecryptionError::BadFormat) }

    let salt = get_salt(data).ok_or(KeyDerivationError::Failed)?;
    PassKey::with_salt(passphrase, salt)?.decrypt(data)
}

/** Get `Salt` from data encrypted with **TES**.

## Fails when:

  * `data` doesn't appear to be a **TES**
  * number of bytes in `data` is not enough

E.g.

```
use tox_encryptsave::*;

assert_eq!(get_salt(&[]), None);
```
*/
pub fn get_salt(data: &[u8]) -> Option<Salt> {
    if is_encrypted(data)
        && data.len() >= MAGIC_LENGTH + SALT_LENGTH
    {
        Salt::from_slice(&data[MAGIC_LENGTH..MAGIC_LENGTH+SALT_LENGTH])
    } else {
        None
    }
}

/// Deriving secret key for [`PassKey`](./struct.PassKey.html).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Fail)]
pub enum KeyDerivationError {
    /// Provided passphrase is empty.
    #[fail(display = "Provided passphrase is empty")]
    Null,
    /// Failed to derive key, most likely due to OOM.
    // TODO: ↑ link to the used sodium memory constant * 2
    #[fail(display = "Failed to derive key, most likely due to OOM")]
    Failed
}

/// Error encrypting data.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Fail)]
pub enum EncryptionError {
    /// Data provided for encryption is empty.
    #[fail(display = "Data provided for encryption is empty")]
    Null,
    /// Failed to derive key – [`KeyDerivationError`]
    /// (./enum.KeyDerivationError.html)
    #[fail(display = "Failed to derive key: {}", _0)]
    KeyDerivation(KeyDerivationError),
}

impl From<KeyDerivationError> for EncryptionError {
    fn from(err: KeyDerivationError) -> EncryptionError {
        EncryptionError::KeyDerivation(err)
    }
}

/// Error when trying to decrypt data.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Fail)]
pub enum DecryptionError {
    /// Data to be decrypted is empty.
    #[fail(display = "Data to be decrypted is empty")]
    Null,
    /// There's not enough data to decrypt.
    #[fail(display = "There's not enough data to decrypt")]
    InvalidLength,
    /// Provided data has invalid format, incompatible with **TES**.
    #[fail(display = "Provided data has invalid format, incompatible with TES")]
    BadFormat,
    /// Deriving key failed.
    #[fail(display = "Deriving key failed: {}", _0)]
    KeyDerivation(KeyDerivationError),
    /**
    Failure due to encrypted data being invalid.

    Can happen when:

     * data is invalid
       - note that it can happen due to bitrot – i.e. even a single byte
         getting corrupted can render data ~impossible to decrypt
     * not all encrypted bytes were provided
     * some bytes that aren't encrypted were provided after encrypted bytes
    */
    #[fail(display = "Failure due to encrypted data being invalid")]
    Failed
}

impl From<KeyDerivationError> for DecryptionError {
    fn from(err: KeyDerivationError) -> DecryptionError {
        DecryptionError::KeyDerivation(err)
    }
}


// PassKey::

// PassKey::new()

#[test]
fn pass_key_new_test() {
    let passwd = [42; 123];
    let pk = PassKey::from_passphrase(&passwd).expect("Failed to unwrap PassKey!");

    assert_ne!(pk.salt.0.as_ref(), &passwd as &[u8]);
    assert_ne!(pk.salt.0.as_ref(), [0; SALT_LENGTH].as_ref());
    assert_ne!(pk.key.0.as_ref(), &passwd as &[u8]);
    assert_ne!(pk.key.0, [0; KEY_LENGTH]);
}

// PassKey::with_salt()

#[test]
fn pass_key_with_salt_test() {
    let passwd = [42; 123];
    let salt = gen_salt();
    let pk = PassKey::with_salt(&passwd, salt).unwrap();

    assert_eq!(&*pk.salt, &salt);
    assert_ne!(pk.key.0.as_ref(), &passwd as &[u8]);
    assert_ne!(pk.key.0, [0; KEY_LENGTH]);
}