Encrypt content sent to the server

This implements client-side encryption, so that users' task information
is not availble to the server (or to anyone who does not have the
`encryption_secret`).
This commit is contained in:
Dustin J. Mitchell
2020-12-26 16:37:31 +00:00
parent 6b70b47aa0
commit a8d45c67c6
8 changed files with 206 additions and 26 deletions

View File

@@ -0,0 +1,131 @@
use crate::server::HistorySegment;
use failure::{format_err, Fallible};
use std::convert::TryFrom;
use std::io::Read;
use tindercrypt::cryptors::RingCryptor;
use uuid::Uuid;
pub(super) struct Secret(pub(super) Vec<u8>);
impl From<Vec<u8>> for Secret {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
impl AsRef<[u8]> for Secret {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
/// A cleartext payload containing a history segment.
pub(super) struct HistoryCleartext {
pub(super) parent_version_id: Uuid,
pub(super) history_segment: HistorySegment,
}
impl HistoryCleartext {
/// Seal the payload into its ciphertext
pub(super) fn seal(self, secret: &Secret) -> Fallible<HistoryCiphertext> {
let cryptor = RingCryptor::new().with_aad(self.parent_version_id.as_bytes());
let ciphertext = cryptor.seal_with_passphrase(secret.as_ref(), &self.history_segment)?;
Ok(HistoryCiphertext(ciphertext))
}
}
/// An ecrypted payload containing a history segment
pub(super) struct HistoryCiphertext(pub(super) Vec<u8>);
impl HistoryCiphertext {
pub(super) fn open(
self,
secret: &Secret,
parent_version_id: Uuid,
) -> Fallible<HistoryCleartext> {
let cryptor = RingCryptor::new().with_aad(parent_version_id.as_bytes());
let plaintext = cryptor.open(secret.as_ref(), &self.0)?;
Ok(HistoryCleartext {
parent_version_id,
history_segment: plaintext,
})
}
}
impl TryFrom<ureq::Response> for HistoryCiphertext {
type Error = failure::Error;
fn try_from(resp: ureq::Response) -> Result<HistoryCiphertext, failure::Error> {
if let Some("application/vnd.taskchampion.history-segment") = resp.header("Content-Type") {
let mut reader = resp.into_reader();
let mut bytes = vec![];
reader.read_to_end(&mut bytes)?;
Ok(Self(bytes))
} else {
Err(format_err!("Response did not have expected content-type"))
}
}
}
impl AsRef<[u8]> for HistoryCiphertext {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn round_trip() {
let parent_version_id = Uuid::new_v4();
let history_segment = b"HISTORY REPEATS ITSELF".to_vec();
let secret = Secret(b"SEKRIT".to_vec());
let history_cleartext = HistoryCleartext {
parent_version_id,
history_segment: history_segment.clone(),
};
let history_ciphertext = history_cleartext.seal(&secret).unwrap();
let history_cleartext = history_ciphertext.open(&secret, parent_version_id).unwrap();
assert_eq!(history_cleartext.history_segment, history_segment);
assert_eq!(history_cleartext.parent_version_id, parent_version_id);
}
#[test]
fn round_trip_bad_key() {
let parent_version_id = Uuid::new_v4();
let history_segment = b"HISTORY REPEATS ITSELF".to_vec();
let secret = Secret(b"SEKRIT".to_vec());
let history_cleartext = HistoryCleartext {
parent_version_id,
history_segment: history_segment.clone(),
};
let history_ciphertext = history_cleartext.seal(&secret).unwrap();
let secret = Secret(b"BADSEKRIT".to_vec());
assert!(history_ciphertext.open(&secret, parent_version_id).is_err());
}
#[test]
fn round_trip_bad_pvid() {
let parent_version_id = Uuid::new_v4();
let history_segment = b"HISTORY REPEATS ITSELF".to_vec();
let secret = Secret(b"SEKRIT".to_vec());
let history_cleartext = HistoryCleartext {
parent_version_id,
history_segment: history_segment.clone(),
};
let history_ciphertext = history_cleartext.seal(&secret).unwrap();
let bad_parent_version_id = Uuid::new_v4();
assert!(history_ciphertext
.open(&secret, bad_parent_version_id)
.is_err());
}
}

View File

@@ -0,0 +1,119 @@
use crate::server::{AddVersionResult, GetVersionResult, HistorySegment, Server, VersionId};
use failure::{format_err, Fallible};
use std::convert::TryInto;
use uuid::Uuid;
mod crypto;
use crypto::{HistoryCiphertext, HistoryCleartext, Secret};
pub struct RemoteServer {
origin: String,
client_id: Uuid,
encryption_secret: Secret,
agent: ureq::Agent,
}
/// A RemoeServer communicates with a remote server over HTTP (such as with
/// taskchampion-sync-server).
impl RemoteServer {
/// Construct a new RemoteServer. The `origin` is the sync server's protocol and hostname
/// without a trailing slash, such as `https://tcsync.example.com`. Pass a client_id to
/// identify this client to the server. Multiple replicas synchronizing the same task history
/// should use the same client_id.
pub fn new(origin: String, client_id: Uuid, encryption_secret: Vec<u8>) -> RemoteServer {
RemoteServer {
origin,
client_id,
encryption_secret: encryption_secret.into(),
agent: ureq::agent(),
}
}
}
/// Convert a ureq::Response to an Error
fn resp_to_error(resp: ureq::Response) -> failure::Error {
return format_err!(
"error {}: {}",
resp.status(),
resp.into_string()
.unwrap_or_else(|e| format!("(could not read response: {})", e))
);
}
/// Read a UUID-bearing header or fail trying
fn get_uuid_header(resp: &ureq::Response, name: &str) -> Fallible<Uuid> {
let value = resp
.header(name)
.ok_or_else(|| format_err!("Response does not have {} header", name))?;
let value = Uuid::parse_str(value)
.map_err(|e| format_err!("{} header is not a valid UUID: {}", name, e))?;
Ok(value)
}
impl Server for RemoteServer {
fn add_version(
&mut self,
parent_version_id: VersionId,
history_segment: HistorySegment,
) -> Fallible<AddVersionResult> {
let url = format!(
"{}/client/{}/add-version/{}",
self.origin, self.client_id, parent_version_id
);
let history_cleartext = HistoryCleartext {
parent_version_id,
history_segment,
};
let history_ciphertext = history_cleartext.seal(&self.encryption_secret)?;
let resp = self
.agent
.post(&url)
.timeout_connect(10_000)
.timeout_read(60_000)
.set(
"Content-Type",
"application/vnd.taskchampion.history-segment",
)
.send_bytes(history_ciphertext.as_ref());
if resp.ok() {
let version_id = get_uuid_header(&resp, "X-Version-Id")?;
Ok(AddVersionResult::Ok(version_id))
} else if resp.status() == 409 {
let parent_version_id = get_uuid_header(&resp, "X-Parent-Version-Id")?;
Ok(AddVersionResult::ExpectedParentVersion(parent_version_id))
} else {
Err(resp_to_error(resp))
}
}
fn get_child_version(&mut self, parent_version_id: VersionId) -> Fallible<GetVersionResult> {
let url = format!(
"{}/client/{}/get-child-version/{}",
self.origin, self.client_id, parent_version_id
);
let resp = self
.agent
.get(&url)
.timeout_connect(10_000)
.timeout_read(60_000)
.call();
if resp.ok() {
let parent_version_id = get_uuid_header(&resp, "X-Parent-Version-Id")?;
let version_id = get_uuid_header(&resp, "X-Version-Id")?;
let history_ciphertext: HistoryCiphertext = resp.try_into()?;
let history_segment = history_ciphertext
.open(&self.encryption_secret, parent_version_id)?
.history_segment;
Ok(GetVersionResult::Version {
version_id,
parent_version_id,
history_segment,
})
} else if resp.status() == 404 {
Ok(GetVersionResult::NoSuchVersion)
} else {
Err(resp_to_error(resp))
}
}
}