2020-09-14 14:38:52 +00:00
|
|
|
// Copyright 2020 The Matrix.org Foundation C.I.C.
|
|
|
|
//
|
|
|
|
// 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.
|
|
|
|
|
2020-09-16 10:05:44 +00:00
|
|
|
use std::{
|
|
|
|
collections::BTreeMap,
|
|
|
|
io::{Error as IoError, ErrorKind, Read},
|
|
|
|
};
|
|
|
|
|
2020-09-14 14:38:52 +00:00
|
|
|
use aes_ctr::{
|
2020-10-19 16:23:48 +00:00
|
|
|
cipher::{NewStreamCipher, SyncStreamCipher},
|
2020-09-14 14:38:52 +00:00
|
|
|
Aes256Ctr,
|
|
|
|
};
|
2020-09-16 10:05:44 +00:00
|
|
|
use base64::DecodeError;
|
2021-05-12 10:56:29 +00:00
|
|
|
use getrandom::getrandom;
|
2021-05-25 19:33:38 +00:00
|
|
|
use matrix_sdk_common::events::room::{EncryptedFile, JsonWebKey, JsonWebKeyInit};
|
2021-05-12 10:56:29 +00:00
|
|
|
use serde::{Deserialize, Serialize};
|
2020-09-14 14:38:52 +00:00
|
|
|
use sha2::{Digest, Sha256};
|
2021-05-12 10:56:29 +00:00
|
|
|
use thiserror::Error;
|
|
|
|
use zeroize::Zeroizing;
|
2020-09-14 14:38:52 +00:00
|
|
|
|
2020-12-08 15:10:46 +00:00
|
|
|
use crate::utilities::{decode, decode_url_safe, encode, encode_url_safe};
|
2020-09-14 15:06:36 +00:00
|
|
|
|
2020-09-14 14:38:52 +00:00
|
|
|
const IV_SIZE: usize = 16;
|
|
|
|
const KEY_SIZE: usize = 32;
|
2020-09-16 10:39:23 +00:00
|
|
|
const VERSION: &str = "v2";
|
2020-09-14 14:38:52 +00:00
|
|
|
|
2020-09-16 10:05:44 +00:00
|
|
|
/// A wrapper that transparently encrypts anything that implements `Read` as an
|
|
|
|
/// Matrix attachment.
|
|
|
|
#[derive(Debug)]
|
2020-09-14 14:38:52 +00:00
|
|
|
pub struct AttachmentDecryptor<'a, R: 'a + Read> {
|
|
|
|
inner_reader: &'a mut R,
|
|
|
|
expected_hash: Vec<u8>,
|
|
|
|
sha: Sha256,
|
|
|
|
aes: Aes256Ctr,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, R: Read> Read for AttachmentDecryptor<'a, R> {
|
|
|
|
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
|
|
|
let read_bytes = self.inner_reader.read(buf)?;
|
|
|
|
|
|
|
|
if read_bytes == 0 {
|
2020-09-14 18:06:44 +00:00
|
|
|
let hash = self.sha.finalize_reset();
|
2020-09-16 10:05:44 +00:00
|
|
|
|
2020-09-14 18:06:44 +00:00
|
|
|
if hash.as_slice() == self.expected_hash.as_slice() {
|
2020-09-14 14:38:52 +00:00
|
|
|
Ok(0)
|
|
|
|
} else {
|
2021-05-12 15:00:47 +00:00
|
|
|
Err(IoError::new(ErrorKind::Other, "Hash missmatch while decrypting"))
|
2020-09-14 14:38:52 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
self.sha.update(&buf[0..read_bytes]);
|
|
|
|
self.aes.apply_keystream(&mut buf[0..read_bytes]);
|
|
|
|
|
|
|
|
Ok(read_bytes)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-16 10:05:44 +00:00
|
|
|
/// Error type for attachment decryption.
|
|
|
|
#[derive(Error, Debug)]
|
|
|
|
pub enum DecryptorError {
|
|
|
|
/// Some data in the encrypted attachment coldn't be decoded, this may be a
|
|
|
|
/// hash, the secret key, or the initialization vector.
|
|
|
|
#[error(transparent)]
|
|
|
|
Decode(#[from] DecodeError),
|
|
|
|
/// A hash is missing from the encryption info.
|
|
|
|
#[error("The encryption info is missing a hash")]
|
|
|
|
MissingHash,
|
|
|
|
/// The supplied key or IV has an invalid length.
|
|
|
|
#[error("The supplied key or IV has an invalid length.")]
|
|
|
|
KeyNonceLength,
|
|
|
|
/// The supplied data was encrypted with an unknown version of the
|
|
|
|
/// attachment encryption spec.
|
|
|
|
#[error("Unknown version for the encrypted attachment.")]
|
|
|
|
UnknownVersion,
|
|
|
|
}
|
|
|
|
|
2020-09-14 14:38:52 +00:00
|
|
|
impl<'a, R: Read + 'a> AttachmentDecryptor<'a, R> {
|
2020-09-16 10:05:44 +00:00
|
|
|
/// Wrap the given reader decrypting all the data we read from it.
|
|
|
|
///
|
|
|
|
/// # Arguments
|
|
|
|
///
|
|
|
|
/// * `reader` - The `Reader` that should be wrapped and decrypted.
|
|
|
|
///
|
|
|
|
/// * `info` - The encryption info that is necessary to decrypt data from
|
|
|
|
/// the reader.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
/// ```
|
|
|
|
/// # use std::io::{Cursor, Read};
|
|
|
|
/// # use matrix_sdk_crypto::{AttachmentEncryptor, AttachmentDecryptor};
|
|
|
|
/// let data = "Hello world".to_owned();
|
|
|
|
/// let mut cursor = Cursor::new(data.clone());
|
|
|
|
///
|
|
|
|
/// let mut encryptor = AttachmentEncryptor::new(&mut cursor);
|
|
|
|
///
|
|
|
|
/// let mut encrypted = Vec::new();
|
|
|
|
/// encryptor.read_to_end(&mut encrypted).unwrap();
|
|
|
|
/// let info = encryptor.finish();
|
|
|
|
///
|
|
|
|
/// let mut cursor = Cursor::new(encrypted);
|
|
|
|
/// let mut decryptor = AttachmentDecryptor::new(&mut cursor, info).unwrap();
|
|
|
|
/// let mut decrypted_data = Vec::new();
|
|
|
|
/// decryptor.read_to_end(&mut decrypted_data).unwrap();
|
|
|
|
///
|
|
|
|
/// let decrypted = String::from_utf8(decrypted_data).unwrap();
|
|
|
|
/// ```
|
|
|
|
pub fn new(
|
|
|
|
input: &'a mut R,
|
|
|
|
info: EncryptionInfo,
|
|
|
|
) -> Result<AttachmentDecryptor<'a, R>, DecryptorError> {
|
2020-09-16 10:39:23 +00:00
|
|
|
if info.version != VERSION {
|
2020-09-16 10:05:44 +00:00
|
|
|
return Err(DecryptorError::UnknownVersion);
|
|
|
|
}
|
|
|
|
|
2021-05-12 15:00:47 +00:00
|
|
|
let hash = decode(info.hashes.get("sha256").ok_or(DecryptorError::MissingHash)?)?;
|
2020-09-16 10:05:44 +00:00
|
|
|
let key = Zeroizing::from(decode_url_safe(info.web_key.k)?);
|
|
|
|
let iv = decode(info.iv)?;
|
2020-09-14 14:38:52 +00:00
|
|
|
|
|
|
|
let sha = Sha256::default();
|
2020-09-16 10:05:44 +00:00
|
|
|
let aes = Aes256Ctr::new_var(&key, &iv).map_err(|_| DecryptorError::KeyNonceLength)?;
|
2020-09-14 14:38:52 +00:00
|
|
|
|
2021-05-12 15:00:47 +00:00
|
|
|
Ok(AttachmentDecryptor { inner_reader: input, expected_hash: hash, sha, aes })
|
2020-09-14 14:38:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-16 10:05:44 +00:00
|
|
|
/// A wrapper that transparently encrypts anything that implements `Read`.
|
2020-09-14 18:06:44 +00:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct AttachmentEncryptor<'a, R: Read + 'a> {
|
2020-09-14 14:38:52 +00:00
|
|
|
finished: bool,
|
2020-09-14 18:06:44 +00:00
|
|
|
inner_reader: &'a mut R,
|
2020-09-14 14:38:52 +00:00
|
|
|
web_key: JsonWebKey,
|
|
|
|
iv: String,
|
|
|
|
hashes: BTreeMap<String, String>,
|
|
|
|
aes: Aes256Ctr,
|
|
|
|
sha: Sha256,
|
|
|
|
}
|
|
|
|
|
2020-09-14 18:06:44 +00:00
|
|
|
impl<'a, R: Read + 'a> Read for AttachmentEncryptor<'a, R> {
|
|
|
|
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
|
|
|
let read_bytes = self.inner_reader.read(buf)?;
|
2020-09-14 14:38:52 +00:00
|
|
|
|
2020-09-14 18:06:44 +00:00
|
|
|
if read_bytes == 0 {
|
|
|
|
let hash = self.sha.finalize_reset();
|
2021-05-12 15:00:47 +00:00
|
|
|
self.hashes.entry("sha256".to_owned()).or_insert_with(|| encode(hash));
|
2020-09-14 18:06:44 +00:00
|
|
|
Ok(0)
|
|
|
|
} else {
|
|
|
|
self.aes.apply_keystream(&mut buf[0..read_bytes]);
|
|
|
|
self.sha.update(&buf[0..read_bytes]);
|
2020-09-14 14:38:52 +00:00
|
|
|
|
2020-09-14 18:06:44 +00:00
|
|
|
Ok(read_bytes)
|
|
|
|
}
|
2020-09-14 14:38:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-14 18:06:44 +00:00
|
|
|
impl<'a, R: Read + 'a> AttachmentEncryptor<'a, R> {
|
2020-09-16 10:05:44 +00:00
|
|
|
/// Wrap the given reader encrypting all the data we read from it.
|
|
|
|
///
|
|
|
|
/// After all the reads are done, and all the data is encrypted that we wish
|
|
|
|
/// to encrypt a call to [`finish()`](#method.finish) is necessary to get
|
|
|
|
/// the decryption key for the data.
|
|
|
|
///
|
|
|
|
/// # Arguments
|
|
|
|
///
|
|
|
|
/// * `reader` - The `Reader` that should be wrapped and enrypted.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// Panics if we can't generate enough random data to create a fresh
|
|
|
|
/// encryption key.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
/// ```
|
|
|
|
/// # use std::io::{Cursor, Read};
|
|
|
|
/// # use matrix_sdk_crypto::AttachmentEncryptor;
|
|
|
|
/// let data = "Hello world".to_owned();
|
|
|
|
/// let mut cursor = Cursor::new(data.clone());
|
|
|
|
///
|
|
|
|
/// let mut encryptor = AttachmentEncryptor::new(&mut cursor);
|
|
|
|
///
|
|
|
|
/// let mut encrypted = Vec::new();
|
|
|
|
/// encryptor.read_to_end(&mut encrypted).unwrap();
|
|
|
|
/// let key = encryptor.finish();
|
|
|
|
/// ```
|
2020-09-14 18:06:44 +00:00
|
|
|
pub fn new(reader: &'a mut R) -> Self {
|
2020-09-16 10:05:44 +00:00
|
|
|
let mut key = Zeroizing::new([0u8; KEY_SIZE]);
|
|
|
|
let mut iv = Zeroizing::new([0u8; IV_SIZE]);
|
2020-09-14 14:38:52 +00:00
|
|
|
|
2020-09-16 10:05:44 +00:00
|
|
|
getrandom(&mut *key).expect("Can't generate randomness");
|
2020-09-14 14:38:52 +00:00
|
|
|
// Only populate the the first 8 bits with randomness, the rest is 0
|
|
|
|
// initialized.
|
|
|
|
getrandom(&mut iv[0..8]).expect("Can't generate randomness");
|
|
|
|
|
2021-05-17 00:21:30 +00:00
|
|
|
let web_key = JsonWebKey::from(JsonWebKeyInit {
|
2020-09-14 14:38:52 +00:00
|
|
|
kty: "oct".to_owned(),
|
|
|
|
key_ops: vec!["encrypt".to_owned(), "decrypt".to_owned()],
|
|
|
|
alg: "A256CTR".to_owned(),
|
2020-09-16 10:05:44 +00:00
|
|
|
k: encode_url_safe(&*key),
|
2020-09-14 14:38:52 +00:00
|
|
|
ext: true,
|
2021-05-17 00:21:30 +00:00
|
|
|
});
|
2020-09-16 10:05:44 +00:00
|
|
|
let encoded_iv = encode(&*iv);
|
2020-09-14 14:38:52 +00:00
|
|
|
|
2020-09-16 10:05:44 +00:00
|
|
|
let aes = Aes256Ctr::new_var(&*key, &*iv).expect("Cannot create AES encryption object.");
|
2020-09-14 14:38:52 +00:00
|
|
|
|
|
|
|
AttachmentEncryptor {
|
|
|
|
finished: false,
|
2020-09-14 18:06:44 +00:00
|
|
|
inner_reader: reader,
|
2020-09-14 14:38:52 +00:00
|
|
|
iv: encoded_iv,
|
|
|
|
web_key,
|
|
|
|
hashes: BTreeMap::new(),
|
|
|
|
aes,
|
|
|
|
sha: Sha256::default(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-16 10:05:44 +00:00
|
|
|
/// Consume the encryptor and get the encryption key.
|
2020-09-14 14:38:52 +00:00
|
|
|
pub fn finish(mut self) -> EncryptionInfo {
|
|
|
|
let hash = self.sha.finalize();
|
2021-05-12 15:00:47 +00:00
|
|
|
self.hashes.entry("sha256".to_owned()).or_insert_with(|| encode(hash));
|
2020-09-14 14:38:52 +00:00
|
|
|
|
|
|
|
EncryptionInfo {
|
2020-09-16 10:39:23 +00:00
|
|
|
version: VERSION.to_string(),
|
2020-09-14 14:38:52 +00:00
|
|
|
hashes: self.hashes,
|
|
|
|
iv: self.iv,
|
|
|
|
web_key: self.web_key,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-15 14:19:48 +00:00
|
|
|
/// Struct holding all the information that is needed to decrypt an encrypted
|
|
|
|
/// file.
|
2020-09-14 14:38:52 +00:00
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
|
|
pub struct EncryptionInfo {
|
|
|
|
#[serde(rename = "v")]
|
2021-02-15 14:19:48 +00:00
|
|
|
/// The version of the encryption scheme.
|
2020-09-14 18:06:44 +00:00
|
|
|
pub version: String,
|
2021-02-15 14:19:48 +00:00
|
|
|
/// The web key that was used to encrypt the file.
|
2020-09-14 18:06:44 +00:00
|
|
|
pub web_key: JsonWebKey,
|
2021-02-15 14:19:48 +00:00
|
|
|
/// The initialization vector that was used to encrypt the file.
|
2020-09-14 18:06:44 +00:00
|
|
|
pub iv: String,
|
2021-02-15 14:19:48 +00:00
|
|
|
/// The hashes that can be used to check the validity of the file.
|
2020-09-14 18:06:44 +00:00
|
|
|
pub hashes: BTreeMap<String, String>,
|
2020-09-14 14:38:52 +00:00
|
|
|
}
|
|
|
|
|
2021-05-25 19:33:38 +00:00
|
|
|
impl From<EncryptedFile> for EncryptionInfo {
|
|
|
|
fn from(file: EncryptedFile) -> Self {
|
|
|
|
Self { version: file.v, web_key: file.key, iv: file.iv, hashes: file.hashes }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-14 14:38:52 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
2020-09-14 18:27:30 +00:00
|
|
|
use std::io::{Cursor, Read};
|
2020-09-14 14:38:52 +00:00
|
|
|
|
2021-05-12 10:56:29 +00:00
|
|
|
use serde_json::json;
|
|
|
|
|
|
|
|
use super::{AttachmentDecryptor, AttachmentEncryptor, EncryptionInfo};
|
|
|
|
|
2020-09-14 14:38:52 +00:00
|
|
|
const EXAMPLE_DATA: &[u8] = &[
|
|
|
|
179, 154, 118, 127, 186, 127, 110, 33, 203, 33, 33, 134, 67, 100, 173, 46, 235, 27, 215,
|
|
|
|
172, 36, 26, 75, 47, 33, 160,
|
|
|
|
];
|
|
|
|
|
|
|
|
fn example_key() -> EncryptionInfo {
|
|
|
|
let info = json!({
|
|
|
|
"v": "v2",
|
|
|
|
"web_key": {
|
|
|
|
"kty": "oct",
|
|
|
|
"alg": "A256CTR",
|
|
|
|
"ext": true,
|
|
|
|
"k": "Voq2nkPme_x8no5-Tjq_laDAdxE6iDbxnlQXxwFPgE4",
|
|
|
|
"key_ops": ["encrypt", "decrypt"]
|
|
|
|
},
|
|
|
|
"iv": "i0DovxYdJEcAAAAAAAAAAA",
|
|
|
|
"hashes": {
|
|
|
|
"sha256": "ANdt819a8bZl4jKy3Z+jcqtiNICa2y0AW4BBJ/iQRAU"
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
serde_json::from_value(info).unwrap()
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn encrypt_decrypt_cycle() {
|
|
|
|
let data = "Hello world".to_owned();
|
2020-09-14 18:06:44 +00:00
|
|
|
let mut cursor = Cursor::new(data.clone());
|
2020-09-14 14:38:52 +00:00
|
|
|
|
|
|
|
let mut encryptor = AttachmentEncryptor::new(&mut cursor);
|
|
|
|
|
|
|
|
let mut encrypted = Vec::new();
|
|
|
|
|
2020-09-14 18:06:44 +00:00
|
|
|
encryptor.read_to_end(&mut encrypted).unwrap();
|
|
|
|
let key = encryptor.finish();
|
2020-09-14 14:38:52 +00:00
|
|
|
assert_ne!(encrypted.as_slice(), data.as_bytes());
|
|
|
|
|
2020-09-14 18:06:44 +00:00
|
|
|
let mut cursor = Cursor::new(encrypted);
|
2020-09-16 10:05:44 +00:00
|
|
|
let mut decryptor = AttachmentDecryptor::new(&mut cursor, key).unwrap();
|
2020-09-14 14:38:52 +00:00
|
|
|
let mut decrypted_data = Vec::new();
|
|
|
|
|
|
|
|
decryptor.read_to_end(&mut decrypted_data).unwrap();
|
|
|
|
|
|
|
|
let decrypted = String::from_utf8(decrypted_data).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(data, decrypted);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn real_decrypt() {
|
|
|
|
let mut cursor = Cursor::new(EXAMPLE_DATA.to_vec());
|
|
|
|
let key = example_key();
|
|
|
|
|
2020-09-16 10:05:44 +00:00
|
|
|
let mut decryptor = AttachmentDecryptor::new(&mut cursor, key).unwrap();
|
2020-09-14 14:38:52 +00:00
|
|
|
let mut decrypted_data = Vec::new();
|
|
|
|
|
|
|
|
decryptor.read_to_end(&mut decrypted_data).unwrap();
|
|
|
|
let decrypted = String::from_utf8(decrypted_data).unwrap();
|
|
|
|
|
|
|
|
assert_eq!("It's a secret to everybody", decrypted);
|
|
|
|
}
|
2020-09-18 15:49:44 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn decrypt_invalid_hash() {
|
|
|
|
let mut cursor = Cursor::new("fake message");
|
|
|
|
let key = example_key();
|
|
|
|
|
|
|
|
let mut decryptor = AttachmentDecryptor::new(&mut cursor, key).unwrap();
|
|
|
|
let mut decrypted_data = Vec::new();
|
|
|
|
|
|
|
|
assert!(decryptor.read_to_end(&mut decrypted_data).is_err())
|
|
|
|
}
|
2020-09-14 14:38:52 +00:00
|
|
|
}
|