2020-01-17 14:27:28 +01:00
|
|
|
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
|
2019-01-07 11:33:07 +01:00
|
|
|
// This file is part of Parity Ethereum.
|
2018-04-09 16:14:33 +02:00
|
|
|
|
2019-01-07 11:33:07 +01:00
|
|
|
// Parity Ethereum is free software: you can redistribute it and/or modify
|
2018-04-09 16:14:33 +02:00
|
|
|
// it under the terms of the GNU General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
|
2019-01-07 11:33:07 +01:00
|
|
|
// Parity Ethereum is distributed in the hope that it will be useful,
|
2018-04-09 16:14:33 +02:00
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU General Public License for more details.
|
|
|
|
|
|
|
|
// You should have received a copy of the GNU General Public License
|
2019-01-07 11:33:07 +01:00
|
|
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
2018-04-09 16:14:33 +02:00
|
|
|
|
|
|
|
//! Encryption providers.
|
|
|
|
|
|
|
|
use std::io::Read;
|
2018-04-10 13:51:29 +02:00
|
|
|
use std::str::FromStr;
|
2019-02-07 14:34:24 +01:00
|
|
|
use std::sync::Arc;
|
2018-04-09 16:14:33 +02:00
|
|
|
use std::iter::repeat;
|
|
|
|
use std::time::{Instant, Duration};
|
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::collections::hash_map::Entry;
|
|
|
|
use parking_lot::Mutex;
|
|
|
|
use ethereum_types::{H128, H256, Address};
|
|
|
|
use ethjson;
|
2019-10-23 13:03:46 +02:00
|
|
|
use crypto::publickey::{Signature, Public};
|
2018-04-10 13:56:56 +02:00
|
|
|
use crypto;
|
2018-04-09 16:14:33 +02:00
|
|
|
use futures::Future;
|
2018-04-10 13:51:29 +02:00
|
|
|
use fetch::{Fetch, Client as FetchClient, Method, BodyReader, Request};
|
2018-04-09 16:14:33 +02:00
|
|
|
use bytes::{Bytes, ToPretty};
|
2019-03-27 14:46:05 +01:00
|
|
|
use error::Error;
|
2018-04-10 13:51:29 +02:00
|
|
|
use url::Url;
|
2019-02-07 14:34:24 +01:00
|
|
|
use super::Signer;
|
2019-02-07 12:39:04 +01:00
|
|
|
use super::key_server_keys::address_to_key;
|
2018-04-09 16:14:33 +02:00
|
|
|
|
|
|
|
/// Initialization vector length.
|
|
|
|
const INIT_VEC_LEN: usize = 16;
|
|
|
|
|
|
|
|
/// Duration of storing retrieved keys (in ms)
|
|
|
|
const ENCRYPTION_SESSION_DURATION: u64 = 30 * 1000;
|
|
|
|
|
|
|
|
/// Trait for encryption/decryption operations.
|
|
|
|
pub trait Encryptor: Send + Sync + 'static {
|
|
|
|
/// Generate unique contract key && encrypt passed data. Encryption can only be performed once.
|
|
|
|
fn encrypt(
|
|
|
|
&self,
|
|
|
|
contract_address: &Address,
|
|
|
|
initialisation_vector: &H128,
|
|
|
|
plain_data: &[u8],
|
|
|
|
) -> Result<Bytes, Error>;
|
|
|
|
|
|
|
|
/// Decrypt data using previously generated contract key.
|
|
|
|
fn decrypt(
|
|
|
|
&self,
|
|
|
|
contract_address: &Address,
|
|
|
|
cypher: &[u8],
|
|
|
|
) -> Result<Bytes, Error>;
|
|
|
|
}
|
|
|
|
|
2019-06-25 08:15:13 +02:00
|
|
|
/// Configuration for key server encryptor
|
2018-04-09 16:14:33 +02:00
|
|
|
#[derive(Default, PartialEq, Debug, Clone)]
|
|
|
|
pub struct EncryptorConfig {
|
|
|
|
/// URL to key server
|
|
|
|
pub base_url: Option<String>,
|
|
|
|
/// Key server's threshold
|
|
|
|
pub threshold: u32,
|
|
|
|
/// Account used for signing requests to key server
|
|
|
|
pub key_server_account: Option<Address>,
|
|
|
|
}
|
|
|
|
|
|
|
|
struct EncryptionSession {
|
|
|
|
key: Bytes,
|
|
|
|
end_time: Instant,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// SecretStore-based encryption/decryption operations.
|
|
|
|
pub struct SecretStoreEncryptor {
|
|
|
|
config: EncryptorConfig,
|
|
|
|
client: FetchClient,
|
|
|
|
sessions: Mutex<HashMap<Address, EncryptionSession>>,
|
2019-08-15 17:59:22 +02:00
|
|
|
signer: Arc<dyn Signer>,
|
2018-04-09 16:14:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl SecretStoreEncryptor {
|
|
|
|
/// Create new encryptor
|
2019-02-07 14:34:24 +01:00
|
|
|
pub fn new(
|
|
|
|
config: EncryptorConfig,
|
|
|
|
client: FetchClient,
|
2019-08-15 17:59:22 +02:00
|
|
|
signer: Arc<dyn Signer>,
|
2019-02-07 14:34:24 +01:00
|
|
|
) -> Result<Self, Error> {
|
2018-04-09 16:14:33 +02:00
|
|
|
Ok(SecretStoreEncryptor {
|
|
|
|
config,
|
|
|
|
client,
|
2019-02-07 14:34:24 +01:00
|
|
|
signer,
|
2018-04-09 16:14:33 +02:00
|
|
|
sessions: Mutex::default(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Ask secret store for key && decrypt the key.
|
|
|
|
fn retrieve_key(
|
|
|
|
&self,
|
|
|
|
url_suffix: &str,
|
|
|
|
use_post: bool,
|
|
|
|
contract_address: &Address,
|
|
|
|
) -> Result<Bytes, Error> {
|
|
|
|
// check if the key was already cached
|
|
|
|
if let Some(key) = self.obtained_key(contract_address) {
|
|
|
|
return Ok(key);
|
|
|
|
}
|
2019-02-07 14:34:24 +01:00
|
|
|
let contract_address_signature = self.sign_contract_address(contract_address)?;
|
2019-03-27 14:46:05 +01:00
|
|
|
let requester = self.config.key_server_account.ok_or_else(|| Error::KeyServerAccountNotSet)?;
|
2018-04-09 16:14:33 +02:00
|
|
|
|
|
|
|
// key id in SS is H256 && we have H160 here => expand with assitional zeros
|
2019-06-03 15:36:21 +02:00
|
|
|
let contract_address_extended: H256 = (*contract_address).into();
|
2019-03-27 14:46:05 +01:00
|
|
|
let base_url = self.config.base_url.clone().ok_or_else(|| Error::KeyServerNotSet)?;
|
2018-04-09 16:14:33 +02:00
|
|
|
|
|
|
|
// prepare request url
|
|
|
|
let url = format!("{}/{}/{}{}",
|
|
|
|
base_url,
|
|
|
|
contract_address_extended.to_hex(),
|
|
|
|
contract_address_signature,
|
|
|
|
url_suffix,
|
|
|
|
);
|
|
|
|
|
|
|
|
// send HTTP request
|
|
|
|
let method = if use_post {
|
2018-10-22 09:40:50 +02:00
|
|
|
Method::POST
|
2018-04-09 16:14:33 +02:00
|
|
|
} else {
|
2018-10-22 09:40:50 +02:00
|
|
|
Method::GET
|
2018-04-09 16:14:33 +02:00
|
|
|
};
|
|
|
|
|
2019-03-27 14:46:05 +01:00
|
|
|
let url = Url::from_str(&url).map_err(|e| Error::Encrypt(e.to_string()))?;
|
2018-04-10 13:51:29 +02:00
|
|
|
let response = self.client.fetch(Request::new(url, method), Default::default()).wait()
|
2019-03-27 14:46:05 +01:00
|
|
|
.map_err(|e| Error::Encrypt(e.to_string()))?;
|
2018-04-09 16:14:33 +02:00
|
|
|
|
|
|
|
if response.is_not_found() {
|
2019-03-27 14:46:05 +01:00
|
|
|
return Err(Error::EncryptionKeyNotFound(*contract_address));
|
2018-04-09 16:14:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if !response.is_success() {
|
2019-03-27 14:46:05 +01:00
|
|
|
return Err(Error::Encrypt(response.status().canonical_reason().unwrap_or("unknown").into()));
|
2018-04-09 16:14:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// read HTTP response
|
|
|
|
let mut result = String::new();
|
|
|
|
BodyReader::new(response).read_to_string(&mut result)?;
|
|
|
|
|
|
|
|
// response is JSON string (which is, in turn, hex-encoded, encrypted Public)
|
2019-03-27 14:46:05 +01:00
|
|
|
let encrypted_bytes: ethjson::bytes::Bytes = result.trim_matches('\"').parse().map_err(|e| Error::Encrypt(e))?;
|
2018-04-09 16:14:33 +02:00
|
|
|
|
|
|
|
// decrypt Public
|
2019-02-07 14:34:24 +01:00
|
|
|
let decrypted_bytes = self.signer.decrypt(requester, &crypto::DEFAULT_MAC, &encrypted_bytes)?;
|
2018-04-09 16:14:33 +02:00
|
|
|
let decrypted_key = Public::from_slice(&decrypted_bytes);
|
|
|
|
|
|
|
|
// and now take x coordinate of Public as a key
|
2019-06-03 15:36:21 +02:00
|
|
|
let key: Bytes = decrypted_key.as_bytes()[..INIT_VEC_LEN].into();
|
2018-04-09 16:14:33 +02:00
|
|
|
|
|
|
|
// cache the key in the session and clear expired sessions
|
|
|
|
self.sessions.lock().insert(*contract_address, EncryptionSession{
|
|
|
|
key: key.clone(),
|
|
|
|
end_time: Instant::now() + Duration::from_millis(ENCRYPTION_SESSION_DURATION),
|
|
|
|
});
|
|
|
|
self.clean_expired_sessions();
|
|
|
|
Ok(key)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn clean_expired_sessions(&self) {
|
|
|
|
let mut sessions = self.sessions.lock();
|
|
|
|
sessions.retain(|_, session| session.end_time < Instant::now());
|
|
|
|
}
|
|
|
|
|
|
|
|
fn obtained_key(&self, contract_address: &Address) -> Option<Bytes> {
|
|
|
|
let mut sessions = self.sessions.lock();
|
|
|
|
let stored_session = sessions.entry(*contract_address);
|
|
|
|
match stored_session {
|
|
|
|
Entry::Occupied(session) => {
|
|
|
|
if Instant::now() > session.get().end_time {
|
|
|
|
session.remove_entry();
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
Some(session.get().key.clone())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Entry::Vacant(_) => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-07 14:34:24 +01:00
|
|
|
fn sign_contract_address(&self, contract_address: &Address) -> Result<Signature, Error> {
|
2019-03-27 14:46:05 +01:00
|
|
|
let key_server_account = self.config.key_server_account.ok_or_else(|| Error::KeyServerAccountNotSet)?;
|
2019-02-07 14:34:24 +01:00
|
|
|
Ok(self.signer.sign(key_server_account, address_to_key(contract_address))?)
|
2018-04-09 16:14:33 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Encryptor for SecretStoreEncryptor {
|
|
|
|
fn encrypt(
|
|
|
|
&self,
|
|
|
|
contract_address: &Address,
|
|
|
|
initialisation_vector: &H128,
|
|
|
|
plain_data: &[u8],
|
|
|
|
) -> Result<Bytes, Error> {
|
|
|
|
// retrieve the key, try to generate it if it doesn't exist yet
|
2019-02-07 14:34:24 +01:00
|
|
|
let key = match self.retrieve_key("", false, contract_address) {
|
2018-04-09 16:14:33 +02:00
|
|
|
Ok(key) => Ok(key),
|
2019-03-27 14:46:05 +01:00
|
|
|
Err(Error::EncryptionKeyNotFound(_)) => {
|
2018-08-29 14:31:04 +02:00
|
|
|
trace!(target: "privatetx", "Key for account wasnt found in sstore. Creating. Address: {:?}", contract_address);
|
2019-02-07 14:34:24 +01:00
|
|
|
self.retrieve_key(&format!("/{}", self.config.threshold), true, contract_address)
|
2018-04-09 16:14:33 +02:00
|
|
|
}
|
|
|
|
Err(err) => Err(err),
|
|
|
|
}?;
|
|
|
|
|
|
|
|
// encrypt data
|
2019-06-03 15:36:21 +02:00
|
|
|
let mut cypher = Vec::with_capacity(plain_data.len() + initialisation_vector.as_bytes().len());
|
2018-04-09 16:14:33 +02:00
|
|
|
cypher.extend(repeat(0).take(plain_data.len()));
|
2019-06-03 15:36:21 +02:00
|
|
|
crypto::aes::encrypt_128_ctr(&key, initialisation_vector.as_bytes(), plain_data, &mut cypher)
|
2019-03-27 14:46:05 +01:00
|
|
|
.map_err(|e| Error::Encrypt(e.to_string()))?;
|
2019-06-03 15:36:21 +02:00
|
|
|
cypher.extend_from_slice(&initialisation_vector.as_bytes());
|
2018-04-09 16:14:33 +02:00
|
|
|
|
|
|
|
Ok(cypher)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Decrypt data using previously generated contract key.
|
|
|
|
fn decrypt(
|
|
|
|
&self,
|
|
|
|
contract_address: &Address,
|
|
|
|
cypher: &[u8],
|
|
|
|
) -> Result<Bytes, Error> {
|
|
|
|
// initialization vector takes INIT_VEC_LEN bytes
|
|
|
|
let cypher_len = cypher.len();
|
|
|
|
if cypher_len < INIT_VEC_LEN {
|
2019-03-27 14:46:05 +01:00
|
|
|
return Err(Error::Decrypt("Invalid cypher".into()));
|
2018-04-09 16:14:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// retrieve existing key
|
2019-02-07 14:34:24 +01:00
|
|
|
let key = self.retrieve_key("", false, contract_address)?;
|
2018-04-09 16:14:33 +02:00
|
|
|
|
|
|
|
// use symmetric decryption to decrypt document
|
|
|
|
let (cypher, iv) = cypher.split_at(cypher_len - INIT_VEC_LEN);
|
|
|
|
let mut plain_data = Vec::with_capacity(cypher_len - INIT_VEC_LEN);
|
|
|
|
plain_data.extend(repeat(0).take(cypher_len - INIT_VEC_LEN));
|
2018-05-05 11:02:33 +02:00
|
|
|
crypto::aes::decrypt_128_ctr(&key, &iv, cypher, &mut plain_data)
|
2019-03-27 14:46:05 +01:00
|
|
|
.map_err(|e| Error::Decrypt(e.to_string()))?;
|
2018-04-09 16:14:33 +02:00
|
|
|
Ok(plain_data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Dummy encryptor.
|
|
|
|
#[derive(Default)]
|
|
|
|
pub struct NoopEncryptor;
|
|
|
|
|
|
|
|
impl Encryptor for NoopEncryptor {
|
|
|
|
fn encrypt(
|
|
|
|
&self,
|
|
|
|
_contract_address: &Address,
|
|
|
|
_initialisation_vector: &H128,
|
|
|
|
data: &[u8],
|
|
|
|
) -> Result<Bytes, Error> {
|
|
|
|
Ok(data.to_vec())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn decrypt(
|
|
|
|
&self,
|
|
|
|
_contract_address: &Address,
|
|
|
|
data: &[u8],
|
|
|
|
) -> Result<Bytes, Error> {
|
|
|
|
Ok(data.to_vec())
|
|
|
|
}
|
|
|
|
}
|