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
use super::uuid::Uuid;
use once_cell::sync::Lazy;
use ring::{self, aead, digest, pbkdf2, rand};
use std::num::NonZeroU32;

/// The size of an encryption key, which must match the encryption algorithm
const KEY_LEN: usize = digest::SHA256_OUTPUT_LEN;
/// The encryption key type
pub type Key = [u8; KEY_LEN];
/// The database portion of a salt used for deriving keys from username and passwords.
pub type DbSalt = [u8; 16];

pub static SYSTEM_RNG: Lazy<rand::SystemRandom> = Lazy::new(rand::SystemRandom::new);

/// An intentionally ambiguous error
#[derive(Debug)]
pub struct UnspecifiedError {}

impl std::fmt::Display for UnspecifiedError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "Unspecified security error")
    }
}

impl std::convert::From<ring::error::Unspecified> for UnspecifiedError {
    fn from(_: ring::error::Unspecified) -> Self {
        UnspecifiedError {}
    }
}

impl std::error::Error for UnspecifiedError {}

/// A source of Nonces (numbers that you only use once).
#[derive(Debug, Clone)]
pub struct Nonce(u128);

impl Nonce {
    /// Generate a new, random source for Nonces.
    pub fn random() -> Result<Nonce, UnspecifiedError> {
        use rand::SecureRandom as _;
        let mut buf = [0u8; Self::len()];
        SYSTEM_RNG.fill(&mut buf)?;
        Ok(Nonce(u128::from_le_bytes(buf)))
    }

    /// Encoded the present nonce value as a little-endian array of bytes.
    pub fn to_le_bytes(&self) -> [u8; Self::len()] {
        self.0.to_le_bytes()
    }

    /// Decode a Nonce for a little-endian array of bytes.
    pub fn from_le_bytes(bytes: [u8; Self::len()]) -> Self {
        Nonce(u128::from_le_bytes(bytes))
    }

    /// The number of bytes needed to represent the Nonce.
    pub const fn len() -> usize {
        std::mem::size_of::<u128>()
    }
}

impl aead::NonceSequence for Nonce {
    fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> {
        use std::convert::TryInto as _;
        let nonce = aead::Nonce::assume_unique_for_key(
            (&self.to_le_bytes()[..12])
                .try_into()
                .map_err(|_| ring::error::Unspecified)?,
        );
        self.0 += 1;
        Ok(nonce)
    }
}

impl aead::NonceSequence for &mut Nonce {
    fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> {
        (*self).advance()
    }
}

/// Generate a random value that can be used when salting for encryption. The
/// value should be associated with the database and be constant. It does not
/// need to be a secret, though it should be unique to the database.
pub fn generate_db_salt() -> Result<DbSalt, UnspecifiedError> {
    use rand::SecureRandom as _;
    let mut salt: DbSalt = [0u8; 16];
    SYSTEM_RNG.fill(&mut salt)?;
    Ok(salt)
}

/// Derive a key suitable for encrypt based on the database's salt and the
/// user's name and password.
fn derive_key_from_credentials(db_salt: &DbSalt, username: &str, password: &str) -> Key {
    // Generate a salt based on the database's unique salt and the user's name.
    let mut salt = Vec::with_capacity(db_salt.len() + username.as_bytes().len());
    salt.extend(db_salt);
    salt.extend(username.as_bytes());

    // Derive key suitable for encryption/decryption
    let mut key: Key = [0; KEY_LEN];
    pbkdf2::derive(
        pbkdf2::PBKDF2_HMAC_SHA512,
        NonZeroU32::new(100_000).unwrap(),
        &salt,
        password.as_bytes(),
        &mut key,
    );
    key
}

/// Get an UnboundKey suitable for encrypt/decryption
fn unbound_key(key: &Key) -> Result<aead::UnboundKey, UnspecifiedError> {
    aead::UnboundKey::new(&aead::AES_256_GCM, key).map_err(|_| UnspecifiedError {})
}

/// Encrypt the plaintext in place using the specified key and incorporate the
/// associated data (which is not encrypted). The plaintext is consumed during
/// this process, even if it fails.
fn seal_in_place<A: AsRef<[u8]>>(
    key: &Key,
    aad: aead::Aad<A>,
    mut plaintext: Vec<u8>,
) -> Result<(Nonce, Vec<u8>), UnspecifiedError> {
    use aead::BoundKey as _;
    let nonce = Nonce::random()?;
    let mut key = aead::SealingKey::new(unbound_key(key)?, nonce.clone());
    key.seal_in_place_append_tag(aad, &mut plaintext)
        .map_err(|_| UnspecifiedError {})?;
    Ok((nonce, plaintext))
}

/// Decrypt the ciphertext with the given key, associated data, and nonce in
/// place. The ciphertext is consumed in this process, even if it fails.
fn open_in_place<A: AsRef<[u8]>>(
    key: &Key,
    aad: aead::Aad<A>,
    mut nonce: Nonce,
    mut ciphertext: Vec<u8>,
) -> Result<Vec<u8>, UnspecifiedError> {
    use aead::BoundKey as _;
    let mut key = aead::OpeningKey::new(unbound_key(key)?, &mut nonce);
    let size = key
        .open_in_place(aad, &mut ciphertext)
        .map_err(|_| UnspecifiedError {})?
        .len();
    ciphertext.truncate(size);
    Ok(ciphertext)
}

/// A type used to verify the username and password used to secure the database.
#[derive(Debug)]
pub struct CredentialGuard {
    /// The database's unique salt
    salt: DbSalt,
    /// The key derived from the user's name and password.
    credential_key: Key,
}

impl CredentialGuard {
    /// Generate a new CredentialGuard from the database's unique salt and the user's name
    /// and password.
    pub fn new(salt: DbSalt, username: &str, password: &str) -> CredentialGuard {
        let key = derive_key_from_credentials(&salt, username, password);
        CredentialGuard {
            salt,
            credential_key: key,
        }
    }

    /// Update the user's name and password
    pub fn update_credentials(&mut self, username: &str, password: &str) {
        self.credential_key = derive_key_from_credentials(&self.salt, username, password);
    }

    /// Try to decrypt the key using the current user's name and password. If
    /// successful, this CredentialGuard is consumed and a DataGuard is
    /// returned, which can be used to encrypt/decrypt data.
    /// Upon failure, this guard is returned and the guard's credentials should
    /// be updated before calling this function again.
    pub fn try_decrypt_key(self, mut encrypted_key: Vec<u8>) -> Result<DataGuard, Self> {
        // If we can decrypt the key, the credentials are valid.
        use std::convert::TryInto as _;
        // Split the encrypted data from the nonce at the end.
        let nonce_bytes = encrypted_key.split_off(encrypted_key.len() - Nonce::len());
        let nonce = Nonce::from_le_bytes(nonce_bytes.try_into().unwrap());
        if let Ok(key) = open_in_place(
            &self.credential_key,
            aead::Aad::empty(),
            nonce,
            encrypted_key,
        ) {
            // Replace the key derived from the user's credentials with the key
            // we just decrypted. All further encryption should be done with
            // this key.
            Ok(DataGuard {
                guard: self,
                key: key.try_into().unwrap(),
            })
        } else {
            Err(self)
        }
    }

    /// Generate a randome symmetric encryption key for securing data. The key
    /// is encrypted using the user's name and password and, as such, can be
    /// public.
    pub fn generate_encrypted_key(&self) -> Result<Vec<u8>, UnspecifiedError> {
        // Generate a random key to use for encrypted data and encrypt it using
        // the current credentials.
        use rand::SecureRandom as _;
        let mut buf = vec![0u8; KEY_LEN];
        SYSTEM_RNG.fill(&mut buf)?;
        assert!(buf.len() == KEY_LEN);
        let (nonce, mut encrypted_key) =
            seal_in_place(&self.credential_key, aead::Aad::empty(), buf)?;
        // Append the nonce to the end
        encrypted_key.extend_from_slice(&nonce.to_le_bytes());
        Ok(encrypted_key)
    }
}

/// A type used to encrypt/decrypt the contents of a database. It can only be
/// created from a CredentialGuard who's username and password have been verified.
#[derive(Debug)]
pub struct DataGuard {
    guard: CredentialGuard,
    key: Key,
}

impl DataGuard {
    /// Encrypt the plaintext associated with the Uuid in place using the
    /// specified key. The plaintext is consumed during this process, even if it
    /// fails.
    pub fn seal_in_place(
        &mut self,
        uuid: Uuid,
        plaintext: Vec<u8>,
    ) -> Result<Vec<u8>, UnspecifiedError> {
        let (nonce, mut encrypted_data) =
            seal_in_place(&self.key, aead::Aad::from(uuid.to_bytes()), plaintext)?;
        // Append the nonce to the end
        encrypted_data.extend_from_slice(&nonce.to_le_bytes()[..]);
        Ok(encrypted_data)
    }

    /// Decrypt the ciphertext with the given key, associated Uuid, and nonce in
    /// place. The ciphertext is consumed in this process, even if it fails.
    pub fn open_in_place(
        &mut self,
        uuid: Uuid,
        mut ciphertext: Vec<u8>,
    ) -> Result<Vec<u8>, UnspecifiedError> {
        use std::convert::TryInto as _;
        // Split the encrypted data from the nonce at the end.
        let nonce_bytes = ciphertext.split_off(ciphertext.len() - Nonce::len());
        let nonce = Nonce::from_le_bytes(nonce_bytes.try_into().unwrap());
        open_in_place(
            &self.key,
            aead::Aad::from(uuid.to_bytes()),
            nonce,
            ciphertext,
        )
    }
}

/// A type that can be encrypted
pub trait Seal: Sized {
    fn into_bytes(self) -> Vec<u8>;

    fn seal(self, uuid: Uuid, guard: &mut DataGuard) -> Result<Vec<u8>, UnspecifiedError> {
        guard.seal_in_place(uuid, self.into_bytes())
    }
}

/// A type that can be decrypted
pub trait Open: Sized {
    fn from_bytes(bytes: Vec<u8>) -> Result<Self, UnspecifiedError>;

    fn open(
        uuid: Uuid,
        ciphertext: Vec<u8>,
        guard: &mut DataGuard,
    ) -> Result<Self, UnspecifiedError> {
        let plaintext = guard.open_in_place(uuid, ciphertext)?;
        Open::from_bytes(plaintext)
    }
}

impl Seal for Vec<u8> {
    fn into_bytes(self) -> Vec<u8> {
        self
    }
}

impl Open for Vec<u8> {
    fn from_bytes(bytes: Vec<u8>) -> Result<Self, UnspecifiedError> {
        Ok(bytes)
    }
}

impl Seal for String {
    fn into_bytes(self) -> Vec<u8> {
        String::into_bytes(self)
    }
}

impl Open for String {
    fn from_bytes(bytes: Vec<u8>) -> Result<Self, UnspecifiedError> {
        Ok(String::from_utf8(bytes).unwrap())
    }
}

impl Seal for chrono::DateTime<chrono::Utc> {
    fn into_bytes(self) -> Vec<u8> {
        self.to_rfc3339().into_bytes()
    }
}

impl Open for chrono::DateTime<chrono::Utc> {
    fn from_bytes(bytes: Vec<u8>) -> Result<Self, UnspecifiedError> {
        Ok(
            chrono::DateTime::parse_from_rfc3339(std::str::from_utf8(&bytes).unwrap())
                .unwrap()
                .with_timezone(&chrono::Utc),
        )
    }
}

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

    #[test]
    fn seal_and_open() {
        let message = b"Hello, World";
        let username = "username";
        let password = "password";
        let salt = generate_db_salt().unwrap();
        let credential_key = derive_key_from_credentials(&salt, username, password);

        let data = message.to_vec();
        let (nonce, ciphertext) = seal_in_place(&credential_key, aead::Aad::empty(), data).unwrap();
        let extracted =
            open_in_place(&credential_key, aead::Aad::empty(), nonce, ciphertext).unwrap();
        assert_eq!(message, &*extracted);
    }
}