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 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
// Copyright 2022 The Matrix.org Foundation C.I.C.
// Copyright 2021 Damir Jelić
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![doc = include_str!("../README.md")]
#![warn(missing_debug_implementations, missing_docs)]
use blake3::{derive_key, Hash};
use chacha20poly1305::{
aead::{Aead, Error as EncryptionError, NewAead},
Key as ChachaKey, XChaCha20Poly1305, XNonce,
};
use displaydoc::Display;
use hmac::Hmac;
use pbkdf2::pbkdf2;
use rand::{thread_rng, Error as RandomError, Fill};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use sha2::Sha256;
use zeroize::Zeroize;
const VERSION: u8 = 1;
const KDF_SALT_SIZE: usize = 32;
const XNONCE_SIZE: usize = 24;
#[cfg(not(test))]
const KDF_ROUNDS: u32 = 200_000;
#[cfg(test)]
const KDF_ROUNDS: u32 = 1000;
type MacKeySeed = [u8; 32];
/// Error type for the `StoreCipher` operations.
#[derive(Debug, Display, thiserror::Error)]
pub enum Error {
/// Failed to serialize or deserialize a value {0}
Serialization(#[from] serde_json::Error),
/// Error encrypting or decrypting a value {0}
Encryption(#[from] EncryptionError),
/// Coulnd't generate enough randomness for a cryptographic operation: {0}
Random(#[from] RandomError),
/// Unsupported ciphertext version, expected {0}, got {1}
Version(u8, u8),
/// The ciphertext had an invalid length, expected {0}, got {1}
Length(usize, usize),
}
/// An encryption key that can be used to encrypt data for key/value stores.
///
/// # Examples
///
/// ```
/// # let example = || {
/// use matrix_sdk_store_encryption::StoreCipher;
/// use serde_json::{json, value::Value};
///
/// let store_cipher = StoreCipher::new()?;
///
/// // Export the store cipher and persist it in your key/value store
/// let export = store_cipher.export("secret-passphrase")?;
///
/// let value = json!({
/// "some": "data",
/// });
///
/// let encrypted = store_cipher.encrypt_value(&value)?;
/// let decrypted: Value = store_cipher.decrypt_value(&encrypted)?;
///
/// assert_eq!(value, decrypted);
/// # anyhow::Ok(()) };
/// ```
#[allow(missing_debug_implementations)]
pub struct StoreCipher {
inner: Keys,
}
impl StoreCipher {
/// Generate a new random store cipher.
pub fn new() -> Result<Self, Error> {
Ok(Self { inner: Keys::new()? })
}
/// Encrypt the store cipher using the given passphrase and export it.
///
/// This method can be used to persist the `StoreCipher` in the key/value
/// store in a safe manner.
///
/// The `StoreCipher` can later on be restored using
/// [`StoreCipher::import`].
///
/// # Arguments
///
/// * `passphrase` - The passphrase that should be used to encrypt the
/// store cipher.
///
/// # Examples
///
/// ```
/// # let example = || {
/// use matrix_sdk_store_encryption::StoreCipher;
/// use serde_json::json;
///
/// let store_cipher = StoreCipher::new()?;
///
/// // Export the store cipher and persist it in your key/value store
/// let export = store_cipher.export("secret-passphrase");
///
/// // Save the export in your key/value store.
/// # anyhow::Ok(()) };
/// ```
pub fn export(&self, passphrase: &str) -> Result<Vec<u8>, Error> {
let mut rng = thread_rng();
let mut salt = [0u8; KDF_SALT_SIZE];
salt.try_fill(&mut rng)?;
let key = StoreCipher::expand_key(passphrase, &salt, KDF_ROUNDS);
let key = ChachaKey::from_slice(key.as_ref());
let cipher = XChaCha20Poly1305::new(key);
let nonce = Keys::get_nonce()?;
let mut keys = [0u8; 64];
keys[0..32].copy_from_slice(self.inner.encryption_key.as_ref());
keys[32..64].copy_from_slice(self.inner.mac_key_seed.as_ref());
let ciphertext = cipher.encrypt(XNonce::from_slice(&nonce), keys.as_ref())?;
keys.zeroize();
let store_cipher = EncryptedStoreCipher {
kdf_info: KdfInfo::Pbkdf2ToChaCha20Poly1305 { rounds: KDF_ROUNDS, kdf_salt: salt },
ciphertext_info: CipherTextInfo::ChaCha20Poly1305 { nonce, ciphertext },
};
Ok(serde_json::to_vec(&store_cipher).expect("Can't serialize the store cipher"))
}
/// Restore a store cipher from an encrypted export.
///
/// # Arguments
///
/// * `passphrase` - The passphrase that was used to encrypt the store
/// cipher.
///
/// * `encrypted` - The exported and encrypted version of the store cipher.
///
/// # Examples
///
/// ```
/// # let example = || {
/// use matrix_sdk_store_encryption::StoreCipher;
/// use serde_json::json;
///
/// let store_cipher = StoreCipher::new()?;
///
/// // Export the store cipher and persist it in your key/value store
/// let export = store_cipher.export("secret-passphrase")?;
///
/// // This is now the same as `store_cipher`.
/// let imported = StoreCipher::import("secret-passphrase", &export)?;
///
/// // Save the export in your key/value store.
/// # anyhow::Ok(()) };
/// ```
pub fn import(passphrase: &str, encrypted: &[u8]) -> Result<Self, Error> {
let encrypted: EncryptedStoreCipher = serde_json::from_slice(encrypted)?;
let key = match encrypted.kdf_info {
KdfInfo::Pbkdf2ToChaCha20Poly1305 { rounds, kdf_salt } => {
Self::expand_key(passphrase, &kdf_salt, rounds)
}
};
let key = ChachaKey::from_slice(key.as_ref());
let mut decrypted = match encrypted.ciphertext_info {
CipherTextInfo::ChaCha20Poly1305 { nonce, ciphertext } => {
let cipher = XChaCha20Poly1305::new(key);
let nonce = XNonce::from_slice(&nonce);
cipher.decrypt(nonce, ciphertext.as_ref())?
}
};
if decrypted.len() != 64 {
decrypted.zeroize();
Err(Error::Length(64, decrypted.len()))
} else {
let mut encryption_key = Box::new([0u8; 32]);
let mut mac_key_seed = Box::new([0u8; 32]);
encryption_key.copy_from_slice(&decrypted[0..32]);
mac_key_seed.copy_from_slice(&decrypted[32..64]);
let keys = Keys { encryption_key, mac_key_seed };
decrypted.zeroize();
Ok(Self { inner: keys })
}
}
/// Hash a key before it is inserted into the key/value store.
///
/// This prevents the key names from leaking to parties which do not have
/// the ability to decrypt the key/value store.
///
/// # Arguments
///
/// * `table_name` - The name of the key/value table this key will be
/// inserted into. This can also contain additional unique data. It will be
/// used to derive a table-specific cryptographic key which will be used
/// in a keyed hash function. This ensures data independence between the
/// different tables of the key/value store.
///
/// * `key` - The key to be hashed, prior to insertion into the key/value
/// store.
///
/// **Note**: This is a one-way transformation; you cannot obtain the
/// original key from its hash.
///
/// # Examples
///
/// ```
/// # let example = || {
/// use matrix_sdk_store_encryption::StoreCipher;
/// use serde_json::json;
///
/// let store_cipher = StoreCipher::new()?;
///
/// let key = "bulbasaur";
///
/// // Hash the key so people don't know which pokemon we have collected.
/// let hashed_key = store_cipher.hash_key("list-of-pokemon", key.as_ref());
///
/// // It's now safe to insert the key into our key/value store.
/// # anyhow::Ok(()) };
/// ```
pub fn hash_key(&self, table_name: &str, key: &[u8]) -> [u8; 32] {
let mac_key = self.inner.get_mac_key_for_table(table_name);
mac_key.mac(key).into()
}
/// Encrypt a value before it is inserted into the key/value store.
///
/// A value can be decrypted using the [`StoreCipher::decrypt_value()`]
/// method.
///
/// # Arguments
///
/// * `value` - A value that should be encrypted, any value that implements
/// `Serialize` can be given to this method. The value will be serialized as
/// json before it is encrypted.
///
/// # Examples
///
/// ```
/// # let example = || {
/// use matrix_sdk_store_encryption::StoreCipher;
/// use serde_json::{json, value::Value};
///
/// let store_cipher = StoreCipher::new()?;
///
/// let value = json!({
/// "some": "data",
/// });
///
/// let encrypted = store_cipher.encrypt_value(&value)?;
/// let decrypted: Value = store_cipher.decrypt_value(&encrypted)?;
///
/// assert_eq!(value, decrypted);
/// # anyhow::Ok(()) };
/// ```
pub fn encrypt_value(&self, value: &impl Serialize) -> Result<Vec<u8>, Error> {
Ok(serde_json::to_vec(&self.encrypt_value_typed(value)?)?)
}
/// Encrypt a value before it is inserted into the key/value store.
///
/// A value can be decrypted using the
/// [`StoreCipher::decrypt_value_typed()`] method. This is the lower
/// level function to `encrypt_value`, but returns the
/// full `EncryptdValue`-type
///
/// # Arguments
///
/// * `value` - A value that should be encrypted, any value that implements
/// `Serialize` can be given to this method. The value will be serialized as
/// json before it is encrypted.
///
///
/// # Examples
///
/// ```no_run
/// # let example = || {
/// use matrix_sdk_store_encryption::StoreCipher;
/// use serde_json::{json, value::Value};
///
/// let store_cipher = StoreCipher::new()?;
///
/// let value = json!({
/// "some": "data",
/// });
///
/// let encrypted = store_cipher.encrypt_value_typed(&value)?;
/// let decrypted: Value = store_cipher.decrypt_value_typed(encrypted)?;
///
/// assert_eq!(value, decrypted);
/// # anyhow::Ok(()) };
/// ```
pub fn encrypt_value_typed(&self, value: &impl Serialize) -> Result<EncryptedValue, Error> {
let data = serde_json::to_vec(value)?;
self.encrypt_value_data(data)
}
/// Encrypt some data before it is inserted into the key/value store.
///
/// A value can be decrypted using the [`StoreCipher::decrypt_value_data()`]
/// method. This is the lower level function to `encrypt_value`
///
/// # Arguments
///
/// * `data` - A value that should be encrypted, encoded as a `Vec<u8>`
///
/// # Examples
///
/// ```
/// # let example = || {
/// use matrix_sdk_store_encryption::StoreCipher;
/// use serde_json::{json, value::Value};
///
/// let store_cipher = StoreCipher::new()?;
///
/// let value = serde_json::to_vec(&json!({
/// "some": "data",
/// }))?;
///
/// let encrypted = store_cipher.encrypt_value_data(value.clone())?;
/// let decrypted = store_cipher.decrypt_value_data(encrypted)?;
///
/// assert_eq!(value, decrypted);
/// # anyhow::Ok(()) };
/// ```
pub fn encrypt_value_data(&self, mut data: Vec<u8>) -> Result<EncryptedValue, Error> {
let nonce = Keys::get_nonce()?;
let cipher = XChaCha20Poly1305::new(self.inner.encryption_key());
let ciphertext = cipher.encrypt(XNonce::from_slice(&nonce), data.as_ref())?;
data.zeroize();
Ok(EncryptedValue { version: VERSION, ciphertext, nonce })
}
/// Decrypt a value after it was fetchetd from the key/value store.
///
/// A value can be encrypted using the [`StoreCipher::encrypt_value()`]
/// method.
///
/// # Arguments
///
/// * `value` - The ciphertext of a value that should be decrypted.
///
/// The method will deserialize the decrypted value into the expected type.
///
/// # Examples
///
/// ```
/// # let example = || {
/// use matrix_sdk_store_encryption::StoreCipher;
/// use serde_json::{json, value::Value};
///
/// let store_cipher = StoreCipher::new()?;
///
/// let value = json!({
/// "some": "data",
/// });
///
/// let encrypted = store_cipher.encrypt_value(&value)?;
/// let decrypted: Value = store_cipher.decrypt_value(&encrypted)?;
///
/// assert_eq!(value, decrypted);
/// # anyhow::Ok(()) };
/// ```
pub fn decrypt_value<T: DeserializeOwned>(&self, value: &[u8]) -> Result<T, Error> {
let value: EncryptedValue = serde_json::from_slice(value)?;
self.decrypt_value_typed(value)
}
/// Decrypt a value after it was fetchetd from the key/value store.
///
/// A value can be encrypted using the
/// [`StoreCipher::encrypt_value_typed()`] method. Lower level method to
/// [`StoreCipher::decrypt_value_typed()`]
///
/// # Arguments
///
/// * `value` - The EncryptedValue of a value that should be decrypted.
///
/// The method will deserialize the decrypted value into the expected type.
///
/// # Examples
///
/// ```
/// # let example = || {
/// use matrix_sdk_store_encryption::StoreCipher;
/// use serde_json::{json, value::Value};
///
/// let store_cipher = StoreCipher::new()?;
///
/// let value = json!({
/// "some": "data",
/// });
///
/// let encrypted = store_cipher.encrypt_value_typed(&value)?;
/// let decrypted: Value = store_cipher.decrypt_value_typed(encrypted)?;
///
/// assert_eq!(value, decrypted);
/// # anyhow::Ok(()) };
/// ```
pub fn decrypt_value_typed<T: DeserializeOwned>(
&self,
value: EncryptedValue,
) -> Result<T, Error> {
let mut plaintext = self.decrypt_value_data(value)?;
let ret = serde_json::from_slice(&plaintext);
plaintext.zeroize();
Ok(ret?)
}
/// Decrypt a value after it was fetchetd from the key/value store.
///
/// A value can be encrypted using the [`StoreCipher::encrypt_value_data()`]
/// method. Lower level method to [`StoreCipher::decrypt_value()`].
///
/// # Arguments
///
/// * `value` - The EncryptedValue of a value that should be decrypted.
///
/// The method will return the raw decrypted value
///
/// # Examples
///
/// ```
/// # let example = || {
/// use matrix_sdk_store_encryption::StoreCipher;
/// use serde_json::{json, value::Value};
///
/// let store_cipher = StoreCipher::new()?;
///
/// let value = serde_json::to_vec(&json!({
/// "some": "data",
/// }))?;
///
/// let encrypted = store_cipher.encrypt_value_data(value.clone())?;
/// let decrypted = store_cipher.decrypt_value_data(encrypted)?;
///
/// assert_eq!(value, decrypted);
/// # anyhow::Ok(()) };
/// ```
pub fn decrypt_value_data(&self, value: EncryptedValue) -> Result<Vec<u8>, Error> {
if value.version != VERSION {
return Err(Error::Version(VERSION, value.version));
}
let cipher = XChaCha20Poly1305::new(self.inner.encryption_key());
let nonce = XNonce::from_slice(&value.nonce);
Ok(cipher.decrypt(nonce, value.ciphertext.as_ref())?)
}
/// Expand the given passphrase into a KEY_SIZE long key.
fn expand_key(passphrase: &str, salt: &[u8], rounds: u32) -> Box<[u8; 32]> {
let mut key = Box::new([0u8; 32]);
pbkdf2::<Hmac<Sha256>>(passphrase.as_bytes(), salt, rounds, &mut *key);
key
}
}
#[derive(Zeroize)]
#[zeroize(drop)]
struct MacKey(Box<[u8; 32]>);
impl MacKey {
fn mac(&self, input: &[u8]) -> Hash {
blake3::keyed_hash(&self.0, input)
}
}
/// Encrypted value, ready for storage, as created by the
/// [`StoreCipher::encrypt_value_data()`]
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct EncryptedValue {
version: u8,
ciphertext: Vec<u8>,
nonce: [u8; XNONCE_SIZE],
}
#[derive(Zeroize)]
#[zeroize(drop)]
struct Keys {
encryption_key: Box<[u8; 32]>,
mac_key_seed: Box<MacKeySeed>,
}
impl Keys {
fn new() -> Result<Self, Error> {
let mut encryption_key = Box::new([0u8; 32]);
let mut mac_key_seed = Box::new([0u8; 32]);
let mut rng = thread_rng();
encryption_key.try_fill(&mut rng)?;
mac_key_seed.try_fill(&mut rng)?;
Ok(Self { encryption_key, mac_key_seed })
}
fn encryption_key(&self) -> &ChachaKey {
ChachaKey::from_slice(self.encryption_key.as_slice())
}
fn mac_key_seed(&self) -> &MacKeySeed {
&self.mac_key_seed
}
fn get_mac_key_for_table(&self, table_name: &str) -> MacKey {
let mut key = MacKey(Box::new([0u8; 32]));
let mut output = derive_key(table_name, self.mac_key_seed());
key.0.copy_from_slice(&output);
output.zeroize();
key
}
fn get_nonce() -> Result<[u8; XNONCE_SIZE], RandomError> {
let mut nonce = [0u8; XNONCE_SIZE];
let mut rng = thread_rng();
nonce.try_fill(&mut rng)?;
Ok(nonce)
}
}
/// Version specific info for the key derivation method that is used.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
enum KdfInfo {
/// The PBKDF2 to Chacha key derivation variant.
Pbkdf2ToChaCha20Poly1305 {
/// The number of PBKDF rounds that were used when deriving the store
/// key.
rounds: u32,
/// The salt that was used when the passphrase was expanded into a store
/// key.
kdf_salt: [u8; KDF_SALT_SIZE],
},
}
/// Version specific info for encryption method that is used to encrypt our
/// store cipher.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
enum CipherTextInfo {
/// A store cipher encrypted using the ChaCha20Poly1305 AEAD.
ChaCha20Poly1305 {
/// The nonce that was used to encrypt the ciphertext.
nonce: [u8; XNONCE_SIZE],
/// The encrypted store cipher.
ciphertext: Vec<u8>,
},
}
/// An encrypted version of our store cipher, this can be safely stored in a
/// database.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
struct EncryptedStoreCipher {
/// Info about the key derivation method that was used to expand the
/// passphrase into an encryption key.
pub kdf_info: KdfInfo,
/// The ciphertext with it's accompanying additional data that is needed to
/// decrypt the store cipher.
pub ciphertext_info: CipherTextInfo,
}
#[cfg(test)]
mod tests {
use serde_json::{json, Value};
use super::{Error, StoreCipher};
#[test]
fn generating() {
StoreCipher::new().unwrap();
}
#[test]
fn exporting_store_cipher() -> Result<(), Error> {
let passphrase = "it's a secret to everybody";
let store_cipher = StoreCipher::new()?;
let value = json!({
"some": "data"
});
let encrypted_value = store_cipher.encrypt_value(&value)?;
let encrypted = store_cipher.export(passphrase)?;
let decrypted = StoreCipher::import(passphrase, &encrypted)?;
assert_eq!(store_cipher.inner.encryption_key, decrypted.inner.encryption_key);
assert_eq!(store_cipher.inner.mac_key_seed, decrypted.inner.mac_key_seed);
let decrypted_value: Value = decrypted.decrypt_value(&encrypted_value)?;
assert_eq!(value, decrypted_value);
Ok(())
}
#[test]
fn encrypting_values() -> Result<(), Error> {
let event = json!({
"content": {
"body": "Bee Gees - Stayin' Alive",
"info": {
"duration": 2140786u32,
"mimetype": "audio/mpeg",
"size": 1563685u32
},
"msgtype": "m.audio",
"url": "mxc://example.org/ffed755USFFxlgbQYZGtryd"
},
});
let store_cipher = StoreCipher::new()?;
let encrypted = store_cipher.encrypt_value(&event)?;
let decrypted: Value = store_cipher.decrypt_value(&encrypted)?;
assert_eq!(event, decrypted);
Ok(())
}
#[test]
fn encrypting_keys() -> Result<(), Error> {
let store_cipher = StoreCipher::new()?;
let first = store_cipher.hash_key("some_table", b"It's dangerous to go alone");
let second = store_cipher.hash_key("some_table", b"It's dangerous to go alone");
let third = store_cipher.hash_key("another_table", b"It's dangerous to go alone");
let fourth = store_cipher.hash_key("another_table", b"It's dangerous to go alone");
let fifth = store_cipher.hash_key("another_table", b"It's not dangerous to go alone");
assert_eq!(first, second);
assert_ne!(first, third);
assert_eq!(third, fourth);
assert_ne!(fourth, fifth);
Ok(())
}
}