0.4.0 #3
15 changed files with 552 additions and 99 deletions
230
.gitignore
vendored
230
.gitignore
vendored
|
@ -1,4 +1,228 @@
|
||||||
**target/
|
# Created by https://www.gitignore.io/api/vim,rust,linux,emacs,windows,intellij+all,visualstudiocode
|
||||||
|
# Edit at https://www.gitignore.io/?templates=vim,rust,linux,emacs,windows,intellij+all,visualstudiocode
|
||||||
|
|
||||||
|
### Emacs ###
|
||||||
|
# -*- mode: gitignore; -*-
|
||||||
|
*~
|
||||||
|
\#*\#
|
||||||
|
/.emacs.desktop
|
||||||
|
/.emacs.desktop.lock
|
||||||
|
*.elc
|
||||||
|
auto-save-list
|
||||||
|
tramp
|
||||||
|
.\#*
|
||||||
|
|
||||||
|
# Org-mode
|
||||||
|
.org-id-locations
|
||||||
|
*_archive
|
||||||
|
|
||||||
|
# flymake-mode
|
||||||
|
*_flymake.*
|
||||||
|
|
||||||
|
# eshell files
|
||||||
|
/eshell/history
|
||||||
|
/eshell/lastdir
|
||||||
|
|
||||||
|
# elpa packages
|
||||||
|
/elpa/
|
||||||
|
|
||||||
|
# reftex files
|
||||||
|
*.rel
|
||||||
|
|
||||||
|
# AUCTeX auto folder
|
||||||
|
/auto/
|
||||||
|
|
||||||
|
# cask packages
|
||||||
|
.cask/
|
||||||
|
dist/
|
||||||
|
|
||||||
|
# Flycheck
|
||||||
|
flycheck_*.el
|
||||||
|
|
||||||
|
# server auth directory
|
||||||
|
/server/
|
||||||
|
|
||||||
|
# projectiles files
|
||||||
|
.projectile
|
||||||
|
|
||||||
|
# directory configuration
|
||||||
|
.dir-locals.el
|
||||||
|
|
||||||
|
# network security
|
||||||
|
/network-security.data
|
||||||
|
|
||||||
|
|
||||||
|
### Intellij+all ###
|
||||||
|
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
||||||
|
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||||
|
|
||||||
|
# User-specific stuff
|
||||||
|
.idea/**/workspace.xml
|
||||||
|
.idea/**/tasks.xml
|
||||||
|
.idea/**/usage.statistics.xml
|
||||||
|
.idea/**/dictionaries
|
||||||
|
.idea/**/shelf
|
||||||
|
|
||||||
|
# Generated files
|
||||||
|
.idea/**/contentModel.xml
|
||||||
|
|
||||||
|
# Sensitive or high-churn files
|
||||||
|
.idea/**/dataSources/
|
||||||
|
.idea/**/dataSources.ids
|
||||||
|
.idea/**/dataSources.local.xml
|
||||||
|
.idea/**/sqlDataSources.xml
|
||||||
|
.idea/**/dynamic.xml
|
||||||
|
.idea/**/uiDesigner.xml
|
||||||
|
.idea/**/dbnavigator.xml
|
||||||
|
|
||||||
|
# Gradle
|
||||||
|
.idea/**/gradle.xml
|
||||||
|
.idea/**/libraries
|
||||||
|
|
||||||
|
# Gradle and Maven with auto-import
|
||||||
|
# When using Gradle or Maven with auto-import, you should exclude module files,
|
||||||
|
# since they will be recreated, and may cause churn. Uncomment if using
|
||||||
|
# auto-import.
|
||||||
|
# .idea/modules.xml
|
||||||
|
# .idea/*.iml
|
||||||
|
# .idea/modules
|
||||||
|
# *.iml
|
||||||
|
# *.ipr
|
||||||
|
|
||||||
|
# CMake
|
||||||
|
cmake-build-*/
|
||||||
|
|
||||||
|
# Mongo Explorer plugin
|
||||||
|
.idea/**/mongoSettings.xml
|
||||||
|
|
||||||
|
# File-based project format
|
||||||
|
*.iws
|
||||||
|
|
||||||
|
# IntelliJ
|
||||||
|
out/
|
||||||
|
|
||||||
|
# mpeltonen/sbt-idea plugin
|
||||||
|
.idea_modules/
|
||||||
|
|
||||||
|
# JIRA plugin
|
||||||
|
atlassian-ide-plugin.xml
|
||||||
|
|
||||||
|
# Cursive Clojure plugin
|
||||||
|
.idea/replstate.xml
|
||||||
|
|
||||||
|
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||||
|
com_crashlytics_export_strings.xml
|
||||||
|
crashlytics.properties
|
||||||
|
crashlytics-build.properties
|
||||||
|
fabric.properties
|
||||||
|
|
||||||
|
# Editor-based Rest Client
|
||||||
|
.idea/httpRequests
|
||||||
|
|
||||||
|
# Android studio 3.1+ serialized cache file
|
||||||
|
.idea/caches/build_file_checksums.ser
|
||||||
|
|
||||||
|
### Intellij+all Patch ###
|
||||||
|
# Ignores the whole .idea folder and all .iml files
|
||||||
|
# See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360
|
||||||
|
|
||||||
|
.idea/
|
||||||
|
|
||||||
|
# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023
|
||||||
|
|
||||||
|
*.iml
|
||||||
|
modules.xml
|
||||||
|
.idea/misc.xml
|
||||||
|
*.ipr
|
||||||
|
|
||||||
|
# Sonarlint plugin
|
||||||
|
.idea/sonarlint
|
||||||
|
|
||||||
|
### Linux ###
|
||||||
|
|
||||||
|
# temporary files which can be created if a process still has a handle open of a deleted file
|
||||||
|
.fuse_hidden*
|
||||||
|
|
||||||
|
# KDE directory preferences
|
||||||
|
.directory
|
||||||
|
|
||||||
|
# Linux trash folder which might appear on any partition or disk
|
||||||
|
.Trash-*
|
||||||
|
|
||||||
|
# .nfs files are created when an open file is removed but is still being accessed
|
||||||
|
.nfs*
|
||||||
|
|
||||||
|
### Rust ###
|
||||||
|
# Generated by Cargo
|
||||||
|
# will have compiled files and executables
|
||||||
|
/target/
|
||||||
|
|
||||||
|
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||||
|
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||||
|
Cargo.lock
|
||||||
|
|
||||||
|
# These are backup files generated by rustfmt
|
||||||
**/*.rs.bk
|
**/*.rs.bk
|
||||||
*.cbor
|
|
||||||
*.yaml
|
### Vim ###
|
||||||
|
# Swap
|
||||||
|
[._]*.s[a-v][a-z]
|
||||||
|
[._]*.sw[a-p]
|
||||||
|
[._]s[a-rt-v][a-z]
|
||||||
|
[._]ss[a-gi-z]
|
||||||
|
[._]sw[a-p]
|
||||||
|
|
||||||
|
# Session
|
||||||
|
Session.vim
|
||||||
|
Sessionx.vim
|
||||||
|
|
||||||
|
# Temporary
|
||||||
|
.netrwhist
|
||||||
|
|
||||||
|
# Auto-generated tag files
|
||||||
|
tags
|
||||||
|
|
||||||
|
# Persistent undo
|
||||||
|
[._]*.un~
|
||||||
|
|
||||||
|
# Coc configuration directory
|
||||||
|
.vim
|
||||||
|
|
||||||
|
### VisualStudioCode ###
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/settings.json
|
||||||
|
!.vscode/tasks.json
|
||||||
|
!.vscode/launch.json
|
||||||
|
!.vscode/extensions.json
|
||||||
|
|
||||||
|
### VisualStudioCode Patch ###
|
||||||
|
# Ignore all local history of files
|
||||||
|
.history
|
||||||
|
|
||||||
|
### Windows ###
|
||||||
|
# Windows thumbnail cache files
|
||||||
|
Thumbs.db
|
||||||
|
Thumbs.db:encryptable
|
||||||
|
ehthumbs.db
|
||||||
|
ehthumbs_vista.db
|
||||||
|
|
||||||
|
# Dump file
|
||||||
|
*.stackdump
|
||||||
|
|
||||||
|
# Folder config file
|
||||||
|
[Dd]esktop.ini
|
||||||
|
|
||||||
|
# Recycle Bin used on file shares
|
||||||
|
$RECYCLE.BIN/
|
||||||
|
|
||||||
|
# Windows Installer files
|
||||||
|
*.cab
|
||||||
|
*.msi
|
||||||
|
*.msix
|
||||||
|
*.msm
|
||||||
|
*.msp
|
||||||
|
|
||||||
|
# Windows shortcuts
|
||||||
|
*.lnk
|
||||||
|
|
||||||
|
# End of https://www.gitignore.io/api/vim,rust,linux,emacs,windows,intellij+all,visualstudiocode
|
3
Cargo.lock
generated
3
Cargo.lock
generated
|
@ -83,8 +83,10 @@ dependencies = [
|
||||||
name = "coffer-client"
|
name = "coffer-client"
|
||||||
version = "0.4.0"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"coffer-common 0.4.0",
|
||||||
"env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
"env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"exec 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
"exec 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
|
"futures 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
|
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)",
|
"serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"serde_cbor 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
"serde_cbor 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
|
@ -104,6 +106,7 @@ dependencies = [
|
||||||
"serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)",
|
"serde 1.0.102 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"serde_cbor 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
"serde_cbor 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"sodiumoxide 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
|
"sodiumoxide 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
|
"tokio 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"toml 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)",
|
"toml 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
|
@ -16,4 +16,9 @@ serde = { version = "1.0", features = ["derive"]}
|
||||||
serde_yaml = "0.8"
|
serde_yaml = "0.8"
|
||||||
serde_cbor = "0.10.2"
|
serde_cbor = "0.10.2"
|
||||||
# Executing subcommand
|
# Executing subcommand
|
||||||
exec = "0.3.1"
|
exec = "0.3.1"
|
||||||
|
# Lighter alternative to tokio for
|
||||||
|
# driving shared frame creation
|
||||||
|
futures = "0.3.1"
|
||||||
|
|
||||||
|
coffer-common = { path = "../coffer-common" }
|
|
@ -1,17 +1,19 @@
|
||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
use log::{debug, error, info, trace, warn};
|
use log::{debug, error, info, trace, warn};
|
||||||
|
|
||||||
use std::net::SocketAddr;
|
|
||||||
|
|
||||||
use env_logger;
|
use env_logger;
|
||||||
|
|
||||||
use structopt::StructOpt;
|
use structopt::StructOpt;
|
||||||
use std::fs::File;
|
|
||||||
use std::error::Error;
|
use std:: {
|
||||||
use std::net::TcpStream;
|
net::{SocketAddr, TcpStream},
|
||||||
use std::path::PathBuf;
|
error::Error,
|
||||||
use std::io::BufRead;
|
path::PathBuf,
|
||||||
use std::io::BufReader;
|
io::{Write, Read},
|
||||||
use std::io::Write;
|
convert::{TryInto, TryFrom}
|
||||||
|
};
|
||||||
|
|
||||||
|
use coffer_common::certificate::Certificate;
|
||||||
|
use coffer_common::coffer::{CofferShard, CofferValue};
|
||||||
|
|
||||||
#[derive(StructOpt, Debug)]
|
#[derive(StructOpt, Debug)]
|
||||||
struct Args {
|
struct Args {
|
||||||
|
@ -19,9 +21,8 @@ struct Args {
|
||||||
#[structopt(short, long, parse(try_from_str), env = "COFFER_SERVER_ADDRESS", default_value = "127.0.0.1:9187")]
|
#[structopt(short, long, parse(try_from_str), env = "COFFER_SERVER_ADDRESS", default_value = "127.0.0.1:9187")]
|
||||||
server_address: SocketAddr,
|
server_address: SocketAddr,
|
||||||
|
|
||||||
/// Path to the request file sent to the server
|
#[structopt(short, long, parse(from_os_str), env = "COFFER_CLIENT_CERTIFICATE", hide_env_values = true)]
|
||||||
#[structopt(parse(from_os_str), env = "COFFER_REQUEST", hide_env_values = true)]
|
certificate: PathBuf,
|
||||||
secrets: PathBuf,
|
|
||||||
|
|
||||||
/// The subcommand spawned by coffer-client
|
/// The subcommand spawned by coffer-client
|
||||||
cmd: String,
|
cmd: String,
|
||||||
|
@ -34,14 +35,39 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
let args = Args::from_args();
|
let args = Args::from_args();
|
||||||
|
|
||||||
info!{"Connecting to coffer server"}
|
debug!{"Reading certificate"}
|
||||||
let stream: TcpStream = TcpStream::connect(args.server_address)?;
|
let cert = Certificate::new_from_cbor(&args.certificate)?;
|
||||||
|
|
||||||
info!{"Parsing key requests"}
|
debug!{"Connecting to coffer server"}
|
||||||
let keys = parse_from_path(&args.secrets)?;
|
let mut stream: TcpStream = TcpStream::connect(&args.server_address)?;
|
||||||
|
|
||||||
info!{"Reading secrets"}
|
debug!{"Sending hello"}
|
||||||
retrieve_secrets(&keys, stream)?;
|
let hello = framed(0x00, cert.public_key());
|
||||||
|
stream.write_all(&hello)?;
|
||||||
|
|
||||||
|
debug!{"Sending get"}
|
||||||
|
let get = framed(0x02, Vec::new());
|
||||||
|
stream.write_all(&get)?;
|
||||||
|
|
||||||
|
debug!{"Reading shard"}
|
||||||
|
let header = read_header(&mut stream).unwrap();
|
||||||
|
let shard = read_message(header.0, &mut stream).unwrap();
|
||||||
|
debug!{"Got encrypted shard {:?}", shard}
|
||||||
|
|
||||||
|
debug!{"Sending bye"}
|
||||||
|
let bye = framed(0x99, Vec::new());
|
||||||
|
stream.write_all(&bye)?;
|
||||||
|
|
||||||
|
debug!{"Decrypting shard"}
|
||||||
|
let shard_clear = cert.open(&shard).unwrap();
|
||||||
|
let shard_de = serde_cbor::from_slice::<CofferShard>(&shard_clear).unwrap();
|
||||||
|
|
||||||
|
debug!{"Setting environment"}
|
||||||
|
for (key, val) in shard_de.0 {
|
||||||
|
if let CofferValue::String(val_s) = val {
|
||||||
|
std::env::set_var(key.trim(), val_s.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
info!{"Spawning coffer'ed command, reaping coffer"}
|
info!{"Spawning coffer'ed command, reaping coffer"}
|
||||||
reap_coffer(&args.cmd, &args.cmd_args);
|
reap_coffer(&args.cmd, &args.cmd_args);
|
||||||
|
@ -49,27 +75,6 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||||
Err("Could not spawn sub-command".into())
|
Err("Could not spawn sub-command".into())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn retrieve_secrets(keys: &Vec<String>, mut stream: TcpStream) -> Result<(), Box<dyn Error>>{
|
|
||||||
for k in keys {
|
|
||||||
let buf = serde_cbor::to_vec(&k)?;
|
|
||||||
info!{"Sending key request {} as {:?}", k, buf}
|
|
||||||
stream.write_all(&buf.len().to_be_bytes())?;
|
|
||||||
stream.write_all(&buf)?;
|
|
||||||
|
|
||||||
info!{"Reading response"}
|
|
||||||
let mut reader = BufReader::new(&stream); // get buffered reader for line-wise reading from stream
|
|
||||||
|
|
||||||
// read line
|
|
||||||
let mut resp = String::new();
|
|
||||||
reader.read_line(&mut resp)?;
|
|
||||||
|
|
||||||
info!{"Retrieved secret. Setting environment"}
|
|
||||||
std::env::set_var(k.trim(), resp.trim());
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reap_coffer(cmd: &str, args: &Vec<String>) {
|
fn reap_coffer(cmd: &str, args: &Vec<String>) {
|
||||||
let mut cmd = exec::Command::new(cmd);
|
let mut cmd = exec::Command::new(cmd);
|
||||||
|
|
||||||
|
@ -80,8 +85,76 @@ fn reap_coffer(cmd: &str, args: &Vec<String>) {
|
||||||
error!{"Could not execute sub-command {}", err};
|
error!{"Could not execute sub-command {}", err};
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_from_path(path: &PathBuf) -> Result<Vec<String>, Box<dyn Error>> {
|
pub fn read_header<T>(reader: &mut T) -> Option<(u64, u8)>
|
||||||
let sec_file = File::open(path)?;
|
where T: Read
|
||||||
|
{
|
||||||
|
let mut header: [u8; 9] = [0u8;9]; // header buffer
|
||||||
|
match reader.read_exact(&mut header)
|
||||||
|
{
|
||||||
|
Ok(_) => debug!{"Read {} bytes for header", 9},
|
||||||
|
Err(err) => {
|
||||||
|
error!{"Error while reading header: {}", err}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(serde_yaml::from_reader::<_, Vec<String>>(sec_file)?)
|
trace!{"Header buffer {:?}", header}
|
||||||
|
|
||||||
|
let msg_size: u64 = u64::from_be_bytes(
|
||||||
|
header[0..8]
|
||||||
|
.try_into()
|
||||||
|
.unwrap());
|
||||||
|
|
||||||
|
let msg_type: u8 = u8::from_be_bytes(
|
||||||
|
header[8..9]
|
||||||
|
.try_into()
|
||||||
|
.unwrap());
|
||||||
|
|
||||||
|
debug!{"Message size: {}, Message type: {}", msg_size, msg_type}
|
||||||
|
Some((msg_size, msg_type))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_message<T>(msg_size: u64, reader: &mut T) -> Option<Vec<u8>>
|
||||||
|
where T: Read
|
||||||
|
{
|
||||||
|
// TODO: possible to use unallocated memory instead?
|
||||||
|
// -> https://doc.rust-lang.org/beta/std/mem/union.MaybeUninit.html
|
||||||
|
// TODO: 32 bit usize? Can't allocate a 64 bit length buffer anyway?
|
||||||
|
let mut message = Vec::with_capacity(msg_size.try_into().unwrap());
|
||||||
|
// need to set the size, because otherwise it is assumed to be 0, since
|
||||||
|
// the vec is allocated but uninitialized at this point, we don't want to
|
||||||
|
// pre-allocate a potentially huge buffer with 0x00, so unsafe set size.
|
||||||
|
unsafe {message.set_len(msg_size.try_into().unwrap());}
|
||||||
|
|
||||||
|
match reader.read_exact(&mut message)
|
||||||
|
{
|
||||||
|
Ok(_) => debug!{"Read {} bytes for message", msg_size},
|
||||||
|
Err(err) => {
|
||||||
|
error!{"Error while reading message: {}", err}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trace!{"Read message {:?}", message}
|
||||||
|
|
||||||
|
Some(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn framed(msg_type: u8, data: Vec<u8>) -> Vec<u8>
|
||||||
|
{
|
||||||
|
trace!{"Creating frame for type: {:?}, data: {:?}", msg_type, data}
|
||||||
|
|
||||||
|
// TODO magic number
|
||||||
|
let mut frame: Vec<u8> = Vec::with_capacity(data.len() + 72);
|
||||||
|
unsafe {frame.set_len(8);}
|
||||||
|
|
||||||
|
frame.splice(0..8, u64::try_from(data.len())
|
||||||
|
.unwrap()
|
||||||
|
.to_be_bytes()
|
||||||
|
.iter()
|
||||||
|
.cloned());
|
||||||
|
|
||||||
|
frame.push(msg_type);
|
||||||
|
frame.extend(&data);
|
||||||
|
|
||||||
|
frame
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,4 +23,6 @@ toml = "^0.5"
|
||||||
base64 = "^0.11"
|
base64 = "^0.11"
|
||||||
# Key management/Cryptography
|
# Key management/Cryptography
|
||||||
sodiumoxide = "^0.2"
|
sodiumoxide = "^0.2"
|
||||||
seckey = "^0.9"
|
seckey = "^0.9"
|
||||||
|
#Communication
|
||||||
|
tokio = { version="^0.2.9", features = ["full"]}
|
|
@ -17,6 +17,7 @@ pub fn generate_key(out: PathBuf) {
|
||||||
|
|
||||||
pub fn info(out: PathBuf) {
|
pub fn info(out: PathBuf) {
|
||||||
let cert = Certificate::new_from_cbor(out).unwrap();
|
let cert = Certificate::new_from_cbor(out).unwrap();
|
||||||
|
|
||||||
println!{"Public Key: {}", hex::encode_upper(cert.public_key())}
|
println!{"Public Key: {}", hex::encode_upper(cert.public_key())}
|
||||||
println!{"Secret Key: {}", hex::encode_upper(cert.secret_key())}
|
println!{"Secret Key: {}", hex::encode_upper(cert.secret_key())}
|
||||||
}
|
}
|
||||||
|
|
110
coffer-companion/src/client.rs
Normal file
110
coffer-companion/src/client.rs
Normal file
|
@ -0,0 +1,110 @@
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
use log::{debug, error, info, trace, warn};
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::convert::{TryFrom, TryInto};
|
||||||
|
use std::net::{TcpStream};
|
||||||
|
use std::io::{Write, Read};
|
||||||
|
|
||||||
|
use coffer_common::certificate::Certificate;
|
||||||
|
use coffer_common::coffer::CofferShard;
|
||||||
|
|
||||||
|
use serde_cbor;
|
||||||
|
|
||||||
|
pub fn print_get(out: PathBuf) {
|
||||||
|
let cert = Certificate::new_from_cbor(out).unwrap();
|
||||||
|
|
||||||
|
let hello = framed(0x00, cert.public_key());
|
||||||
|
let get = framed(0x02, Vec::new());
|
||||||
|
let bye = framed(0x99, Vec::new());
|
||||||
|
|
||||||
|
let mut listener = TcpStream::connect("127.0.0.1:9187").unwrap();
|
||||||
|
listener.write_all(&hello).unwrap();
|
||||||
|
|
||||||
|
listener.write_all(&get).unwrap();
|
||||||
|
|
||||||
|
let header = read_header(&mut listener).unwrap();
|
||||||
|
let shard = read_message(header.0, &mut listener).unwrap();
|
||||||
|
debug!{"Got encrypted shard {:?}", shard}
|
||||||
|
|
||||||
|
listener.write_all(&bye).unwrap();
|
||||||
|
|
||||||
|
let shard_clear = cert.open(&shard).unwrap();
|
||||||
|
let shard_de = serde_cbor::from_slice::<CofferShard>(&shard_clear).unwrap();
|
||||||
|
|
||||||
|
println!{"{:?}", shard_de}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn framed(msg_type: u8, data: Vec<u8>) -> Vec<u8>
|
||||||
|
{
|
||||||
|
trace!{"Creating frame for type: {:?}, data: {:?}", msg_type, data}
|
||||||
|
|
||||||
|
// TODO magic number
|
||||||
|
let mut frame: Vec<u8> = Vec::with_capacity(data.len() + 72);
|
||||||
|
unsafe {frame.set_len(8);}
|
||||||
|
|
||||||
|
frame.splice(0..8, u64::try_from(data.len())
|
||||||
|
.unwrap()
|
||||||
|
.to_be_bytes()
|
||||||
|
.iter()
|
||||||
|
.cloned());
|
||||||
|
|
||||||
|
frame.push(msg_type);
|
||||||
|
frame.extend(&data);
|
||||||
|
|
||||||
|
frame
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_header<T>(reader: &mut T) -> Option<(u64, u8)>
|
||||||
|
where T: Read
|
||||||
|
{
|
||||||
|
let mut header: [u8; 9] = [0u8;9]; // header buffer
|
||||||
|
match reader.read_exact(&mut header)
|
||||||
|
{
|
||||||
|
Ok(_) => debug!{"Read {} bytes for header", 9},
|
||||||
|
Err(err) => {
|
||||||
|
error!{"Error while reading header: {}", err}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
trace!{"Header buffer {:?}", header}
|
||||||
|
|
||||||
|
let msg_size: u64 = u64::from_be_bytes(
|
||||||
|
header[0..8]
|
||||||
|
.try_into()
|
||||||
|
.unwrap());
|
||||||
|
|
||||||
|
let msg_type: u8 = u8::from_be_bytes(
|
||||||
|
header[8..9]
|
||||||
|
.try_into()
|
||||||
|
.unwrap());
|
||||||
|
|
||||||
|
debug!{"Message size: {}, Message type: {}", msg_size, msg_type}
|
||||||
|
Some((msg_size, msg_type))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_message<T>(msg_size: u64, reader: &mut T) -> Option<Vec<u8>>
|
||||||
|
where T: Read
|
||||||
|
{
|
||||||
|
// TODO: possible to use unallocated memory instead?
|
||||||
|
// -> https://doc.rust-lang.org/beta/std/mem/union.MaybeUninit.html
|
||||||
|
// TODO: 32 bit usize? Can't allocate a 64 bit length buffer anyway?
|
||||||
|
let mut message = Vec::with_capacity(msg_size.try_into().unwrap());
|
||||||
|
// need to set the size, because otherwise it is assumed to be 0, since
|
||||||
|
// the vec is allocated but uninitialized at this point, we don't want to
|
||||||
|
// pre-allocate a potentially huge buffer with 0x00, so unsafe set size.
|
||||||
|
unsafe {message.set_len(msg_size.try_into().unwrap());}
|
||||||
|
|
||||||
|
match reader.read_exact(&mut message)
|
||||||
|
{
|
||||||
|
Ok(_) => debug!{"Read {} bytes for message", msg_size},
|
||||||
|
Err(err) => {
|
||||||
|
error!{"Error while reading message: {}", err}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trace!{"Read message {:?}", message}
|
||||||
|
|
||||||
|
Some(message)
|
||||||
|
}
|
|
@ -3,6 +3,7 @@ use structopt::StructOpt;
|
||||||
|
|
||||||
mod certificate;
|
mod certificate;
|
||||||
mod encrypt;
|
mod encrypt;
|
||||||
|
mod client;
|
||||||
|
|
||||||
#[derive(StructOpt, Debug)]
|
#[derive(StructOpt, Debug)]
|
||||||
enum Args {
|
enum Args {
|
||||||
|
@ -10,7 +11,7 @@ enum Args {
|
||||||
#[structopt(short, long, parse(from_os_str))]
|
#[structopt(short, long, parse(from_os_str))]
|
||||||
out: PathBuf,
|
out: PathBuf,
|
||||||
#[structopt(short, long)]
|
#[structopt(short, long)]
|
||||||
info: bool
|
info: bool,
|
||||||
},
|
},
|
||||||
Encrypt {
|
Encrypt {
|
||||||
#[structopt(short, long, parse(from_os_str))]
|
#[structopt(short, long, parse(from_os_str))]
|
||||||
|
@ -19,6 +20,10 @@ enum Args {
|
||||||
yaml: PathBuf,
|
yaml: PathBuf,
|
||||||
#[structopt(short, long, parse(from_os_str))]
|
#[structopt(short, long, parse(from_os_str))]
|
||||||
out: PathBuf
|
out: PathBuf
|
||||||
|
},
|
||||||
|
Client {
|
||||||
|
#[structopt(short, long, parse(from_os_str))]
|
||||||
|
certificate: PathBuf,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -30,6 +35,11 @@ fn main() {
|
||||||
if info { certificate::info(out) }
|
if info { certificate::info(out) }
|
||||||
else { certificate::generate_key(out) }
|
else { certificate::generate_key(out) }
|
||||||
}
|
}
|
||||||
_ => unimplemented![]
|
Args::Encrypt {certificate, yaml, out} => {
|
||||||
|
encrypt::encrypt_yaml(yaml, out, certificate)
|
||||||
|
}
|
||||||
|
Args::Client {certificate} => {
|
||||||
|
client::print_get(certificate)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -74,8 +74,10 @@ impl Coffer for CofferMap {
|
||||||
{
|
{
|
||||||
let lock = self.read();
|
let lock = self.read();
|
||||||
|
|
||||||
|
debug!{"Coffer {:?}", *lock}
|
||||||
|
|
||||||
let coffer_shard = lock.get(shard.as_ref())
|
let coffer_shard = lock.get(shard.as_ref())
|
||||||
.ok_or(CofferError::Msg("Shard {} not found"))?;
|
.ok_or(CofferError::Msg("Shard not found"))?;
|
||||||
|
|
||||||
let mut res = CofferShard(Vec::new());
|
let mut res = CofferShard(Vec::new());
|
||||||
|
|
||||||
|
|
|
@ -33,6 +33,9 @@ struct Args {
|
||||||
/// Address, the coffer server should bind to
|
/// Address, the coffer server should bind to
|
||||||
#[structopt(short, long, parse(try_from_str), env = "COFFER_SERVER_ADDRESS", default_value = "127.0.0.1:9187")]
|
#[structopt(short, long, parse(try_from_str), env = "COFFER_SERVER_ADDRESS", default_value = "127.0.0.1:9187")]
|
||||||
address: SocketAddr,
|
address: SocketAddr,
|
||||||
|
|
||||||
|
#[structopt(long, parse(from_os_str))]
|
||||||
|
client: PathBuf
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
|
@ -42,7 +45,12 @@ async fn main() {
|
||||||
|
|
||||||
_print_banner();
|
_print_banner();
|
||||||
|
|
||||||
let keyring = Keyring::new_from_path(&args.certificate);
|
let mut keyring = Keyring::new_from_path(&args.certificate);
|
||||||
|
|
||||||
|
// read in client key
|
||||||
|
let mut client_key = Vec::new();
|
||||||
|
File::open(&args.client).unwrap().read_to_end(&mut client_key).unwrap();
|
||||||
|
keyring.add_known_key(&client_key).unwrap();
|
||||||
|
|
||||||
// decrypt secrets file and put into coffer
|
// decrypt secrets file and put into coffer
|
||||||
let mut secrets_file = File::open(&args.secrets).unwrap();
|
let mut secrets_file = File::open(&args.secrets).unwrap();
|
||||||
|
|
|
@ -2,12 +2,9 @@
|
||||||
use log::{debug, error, info, trace, warn};
|
use log::{debug, error, info, trace, warn};
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::convert::{TryFrom, TryInto};
|
|
||||||
use std::net::Shutdown;
|
use std::net::Shutdown;
|
||||||
|
|
||||||
use tokio::io::{AsyncRead,
|
use tokio::io::AsyncWriteExt;
|
||||||
AsyncReadExt,
|
|
||||||
AsyncWriteExt};
|
|
||||||
use tokio::net::TcpStream;
|
use tokio::net::TcpStream;
|
||||||
|
|
||||||
use serde_cbor;
|
use serde_cbor;
|
||||||
|
@ -16,6 +13,7 @@ use quick_error::quick_error;
|
||||||
|
|
||||||
use coffer_common::coffer::Coffer;
|
use coffer_common::coffer::Coffer;
|
||||||
use coffer_common::keyring::Keyring;
|
use coffer_common::keyring::Keyring;
|
||||||
|
|
||||||
use hex;
|
use hex;
|
||||||
|
|
||||||
quick_error! {
|
quick_error! {
|
||||||
|
@ -84,13 +82,13 @@ where C: Coffer
|
||||||
|
|
||||||
// TODO restrict msg_size more, otherwise bad client could bring server
|
// TODO restrict msg_size more, otherwise bad client could bring server
|
||||||
// to allocate vast amounts of memory
|
// to allocate vast amounts of memory
|
||||||
let (msg_size, msg_type) = Self::read_header(&mut reader).await
|
let (msg_size, msg_type) = frame::read_header(&mut reader).await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
// TODO only read message if message expected by message type
|
// TODO only read message if message expected by message type
|
||||||
// currently relies on client sending good message
|
// currently relies on client sending good message
|
||||||
// (0x00 message size)
|
// (0x00 message size)
|
||||||
let message = Self::read_message(msg_size, &mut reader).await
|
let message = frame::read_message(msg_size, &mut reader).await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
match msg_type {
|
match msg_type {
|
||||||
|
@ -101,7 +99,54 @@ where C: Coffer
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn read_header<T>(reader: &mut T) -> Option<(u64, u8)>
|
async fn transit(&mut self, event: Request)
|
||||||
|
{
|
||||||
|
match (&self.state, event) {
|
||||||
|
(State::Start, Request::Hello(pk)) => {
|
||||||
|
debug!{"Reading public key"}
|
||||||
|
self.client = Some(pk);
|
||||||
|
self.state = State::Link;
|
||||||
|
}
|
||||||
|
|
||||||
|
(State::Link, Request::Get) => {
|
||||||
|
debug!{"Writing response"}
|
||||||
|
let shard_id = hex::encode_upper(self.client.as_ref().unwrap());
|
||||||
|
|
||||||
|
let res = self.coffer
|
||||||
|
.get_shard(shard_id)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let response = self.keyring.seal(
|
||||||
|
&self.client.as_ref().unwrap(),
|
||||||
|
&serde_cbor::to_vec(&res).unwrap()
|
||||||
|
).unwrap();
|
||||||
|
|
||||||
|
// TODO magic number
|
||||||
|
let frame = frame::framed(0x05u8, response).await;
|
||||||
|
trace!{"OkGet Frame: {:?}", frame}
|
||||||
|
// TODO Proper result handling
|
||||||
|
self.stream.write_all(&frame).await.unwrap();
|
||||||
|
self.stream.flush().await.unwrap();
|
||||||
|
|
||||||
|
self.state = State::Bye;
|
||||||
|
}
|
||||||
|
|
||||||
|
(State::Link, Request::Bye) => self.state = State::End,
|
||||||
|
(State::Bye, Request::Bye) => self.state = State::End,
|
||||||
|
|
||||||
|
_ => self.state = State::End
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mod frame {
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
use log::{debug, error, info, trace, warn};
|
||||||
|
|
||||||
|
use std::convert::{TryFrom, TryInto};
|
||||||
|
use tokio::io::{AsyncRead, AsyncReadExt};
|
||||||
|
|
||||||
|
pub async fn read_header<T>(reader: &mut T) -> Option<(u64, u8)>
|
||||||
where T: AsyncRead + Unpin
|
where T: AsyncRead + Unpin
|
||||||
{
|
{
|
||||||
let mut header: [u8; 9] = [0u8;9]; // header buffer
|
let mut header: [u8; 9] = [0u8;9]; // header buffer
|
||||||
|
@ -130,7 +175,7 @@ where C: Coffer
|
||||||
Some((msg_size, msg_type))
|
Some((msg_size, msg_type))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn read_message<T>(msg_size: u64, reader: &mut T) -> Option<Vec<u8>>
|
pub async fn read_message<T>(msg_size: u64, reader: &mut T) -> Option<Vec<u8>>
|
||||||
where T: AsyncRead + Unpin
|
where T: AsyncRead + Unpin
|
||||||
{
|
{
|
||||||
// TODO: possible to use unallocated memory instead?
|
// TODO: possible to use unallocated memory instead?
|
||||||
|
@ -155,45 +200,7 @@ where C: Coffer
|
||||||
Some(message)
|
Some(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn transit(&mut self, event: Request)
|
pub async fn framed(msg_type: u8, data: Vec<u8>) -> Vec<u8>
|
||||||
{
|
|
||||||
match (&self.state, event) {
|
|
||||||
(State::Start, Request::Hello(pk)) => {
|
|
||||||
debug!{"Reading public key"}
|
|
||||||
self.client = Some(pk);
|
|
||||||
self.state = State::Link;
|
|
||||||
}
|
|
||||||
|
|
||||||
(State::Link, Request::Get) => {
|
|
||||||
debug!{"Writing response"}
|
|
||||||
let shard_id = hex::encode(self.client.as_ref().unwrap());
|
|
||||||
|
|
||||||
let res = self.coffer
|
|
||||||
.get_shard(shard_id)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let response = self.keyring.seal(
|
|
||||||
&self.client.as_ref().unwrap(),
|
|
||||||
&serde_cbor::to_vec(&res).unwrap()
|
|
||||||
).unwrap();
|
|
||||||
|
|
||||||
// TODO magic number
|
|
||||||
let frame = Self::framed(0x05u8, response).await;
|
|
||||||
trace!{"OkGet Frame: {:?}", frame}
|
|
||||||
// TODO Proper result handling
|
|
||||||
self.stream.write_all(&frame).await.unwrap();
|
|
||||||
|
|
||||||
self.state = State::Bye;
|
|
||||||
}
|
|
||||||
|
|
||||||
(State::Link, Request::Bye) => self.state = State::End,
|
|
||||||
(State::Bye, Request::Bye) => self.state = State::End,
|
|
||||||
|
|
||||||
_ => self.state = State::End
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn framed(msg_type: u8, data: Vec<u8>) -> Vec<u8>
|
|
||||||
{
|
{
|
||||||
trace!{"Creating frame for type: {:?}, data: {:?}", msg_type, data}
|
trace!{"Creating frame for type: {:?}, data: {:?}", msg_type, data}
|
||||||
|
|
||||||
|
@ -212,4 +219,5 @@ where C: Coffer
|
||||||
|
|
||||||
frame
|
frame
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
1
testcoffer/client.cert
Normal file
1
testcoffer/client.cert
Normal file
|
@ -0,0 +1 @@
|
||||||
|
¢jpublic_keyX ñ†Õ*p—}†o<E280A0>9¼sÛL¸¬@$<24>öhG[þHAkprivate_keyX ÃÏÕÏ«øÿÉÑrÄñâhÔïD–I<E28093>„Ä\J<>p
|
1
testcoffer/coffer.enc
Normal file
1
testcoffer/coffer.enc
Normal file
|
@ -0,0 +1 @@
|
||||||
|
э┘ш┬s÷В█╢;ДAбG8ЁLeэоh╩zVПхB├&VеLГf╨~ЬН┤B.╧5▓ЛЭK*XЫ·▐~╘П╕╫B`@к,J\Ь}GC2▐K░ПЛd0ф┤v"чЛIAZ6O╩R ⌡KдWБj╡xohНv{╨и╡║c╛CЯшЁКD]░Зу┤?b░Ъ/h▓И┘ ≈$Щ7╕p|9²╛°AТЫ$?
|
4
testcoffer/coffer.yaml
Normal file
4
testcoffer/coffer.yaml
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
[test]
|
||||||
|
id = "F11C86D52A70977D866F813903BC73DB4CB8AC40249DF668475B1BFE48AD1E41"
|
||||||
|
key1 = "secret1"
|
||||||
|
key2 = "secret2"
|
1
testcoffer/server.cert
Normal file
1
testcoffer/server.cert
Normal file
|
@ -0,0 +1 @@
|
||||||
|
¢jpublic_keyX øûN%ý[#{<7B>‘Pú¤²-®j–fP<66>dx 4Ê[kprivate_keyX M†‚€»ÐÙ™‘â<E28098>ëgkÚ{ú³ÛCMÀ¸>;¿ô~3d+
|
Loading…
Reference in a new issue