Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Arkworks Backend to manta-crypto #180

Merged
merged 18 commits into from
Aug 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
- [\#172](https://github.com/Manta-Network/manta-rs/pull/172) Add abstract Phase 2 for Groth16 trusted setup

### Changed
- [\#180](https://github.com/Manta-Network/manta-rs/pull/180) Start moving to new `arkworks` backend for `manta-crypto`
- [\#191](https://github.com/Manta-Network/manta-rs/pull/191) Move HTTP Utilities to `manta-util`

### Deprecated
Expand Down
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
[workspace]
resolver = "2"
members = ["manta-*", "workspace-hack"]
exclude = ["forks/cocoon"]
bhgomes marked this conversation as resolved.
Show resolved Hide resolved

[patch.crates-io]
cocoon = { path = "forks/cocoon" }
60 changes: 60 additions & 0 deletions forks/cocoon/.github/workflows/rust.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
name: Cocoon

on:
push:
branches:
- main

pull_request:
branches:
- main

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Run Rustfmt
run: cargo fmt -- --check
- name: Build
run: cargo build --verbose
- name: Build with no default features
run: cargo build --no-default-features
- name: Build with only "alloc" feature
run: cargo build --no-default-features --features="alloc"
- name: Run tests
run: cargo test --verbose

coverage:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Select Rust nightly build
run: rustup default nightly
- name: Test with profiling
env:
CARGO_INCREMENTAL: 0
RUSTFLAGS: >-
-Zprofile -Ccodegen-units=1 -Copt-level=0 -Clink-dead-code
-Coverflow-checks=off -Zpanic_abort_tests -Cpanic=abort
RUSTDOCFLAGS: >-
-Zprofile -Ccodegen-units=1 -Copt-level=0 -Clink-dead-code
-Coverflow-checks=off -Zpanic_abort_tests -Cpanic=abort
run: cargo test --all-features
- name: Install grcov
run: |
curl -L https://github.com/mozilla/grcov/releases/latest/download/grcov-x86_64-unknown-linux-gnu.tar.bz2 \
| tar jxf -
- name: Run grcov
run: |
mkdir coverage
./grcov ./target/debug/ -s . -t lcov --llvm --branch --ignore-not-existing --ignore "/*" \
--excl-line '#\[|=> panic!|unreachable!|Io\(std::io::Error\)' \
--excl-br-line '#\[|=> panic!|unreachable!|assert_..!' -o ./coverage/lcov.info
- name: Send to Coveralls
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
2 changes: 2 additions & 0 deletions forks/cocoon/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/target
Cargo.lock
51 changes: 51 additions & 0 deletions forks/cocoon/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
[package]
name = "cocoon"
version = "0.3.1"
description = "A simple protected container with strong encryption and format validation."
authors = ["Alexander Fadeev <fadeevab.com@gmail.com>"]
edition = "2018"
license = "MIT"
keywords = ["encryption", "storage", "keystore", "parser", "container"]
categories = ["cryptography", "no-std", "parser-implementations"]
homepage = "https://github.com/fadeevab/cocoon"
repository = "https://github.com/fadeevab/cocoon"
documentation = "https://docs.rs/cocoon"
readme = "README.md"

[dependencies]
aes-gcm = "0.9"
chacha20poly1305 = { version = "0.9", default-features = false }
hmac = "0.11"
pbkdf2 = { version = "0.9", default-features = false, features = ["sha2", "hmac"] }
rand = { version = "0.8", default-features = false, features = ["std_rng"] }
sha2 = { version = "0.9", default-features = false }
zeroize = { version = "1", default-features = false }

[dev-dependencies]
borsh = "0.9"

[features]
# Enables `std` feature by default.
default = ["std"]

# Enables all features, including support of simplified Cocoon API, using `rand::thread_rng`,
# and API related to `std::io`: wrap to writer, unwrap from reader.
std = ["alloc", "rand/std"]

# Enables `Vec` container. Can be used without `std` crate (in "no std" build).
alloc = ["chacha20poly1305/alloc"]

# Enables support of Cocoon::from_entropy() which gets random bytes from OsRng.
getrandom = ["rand/getrandom"]

# To speed up PBKDF2.
[profile.test]
opt-level = 3

# To speed up PBKDF2.
[profile.dev.package.sha2]
opt-level = 3

[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docs_rs"]
21 changes: 21 additions & 0 deletions forks/cocoon/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Alexander Fadeev

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
167 changes: 167 additions & 0 deletions forks/cocoon/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
[![Cocoon](https://github.com/fadeevab/cocoon/workflows/Cocoon/badge.svg?event=push)](https://github.com/fadeevab/cocoon)
[![crates.io](https://img.shields.io/crates/v/cocoon.svg)](https://crates.io/crates/cocoon)
[![docs.rs](https://docs.rs/cocoon/badge.svg)](https://docs.rs/cocoon/)
[![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/fadeevab/cocoon/LICENSE)
[![coverage](https://coveralls.io/repos/github/fadeevab/cocoon/badge.svg?branch=master)](https://coveralls.io/github/fadeevab/cocoon?branch=master)

# Cocoon

<img alt="Cocoon format" src="https://github.com/fadeevab/cocoon/raw/master/images/cocoon_format.svg" />

`MiniCocoon` and `Cocoon` are protected containers to wrap sensitive data with strong
[encryption](#cryptography) and format validation. A format of `MiniCocoon` and `Cocoon`
is developed for the following practical cases:

1. As an _encrypted file format_ to organize simple secure storage:
1. Key store.
2. Password store.
3. Sensitive data store.
2. For _encrypted data transfer_:
* As a secure in-memory container.

`Cocoon` is developed with security in mind. It aims to do the only one thing and do it
flawlessly. It has a minimal set of dependencies and a minimalist design to simplify control over
security aspects. It's a pure Rust implementation, and all dependencies are pure Rust
packages with disabled default features.

# Problem

Whenever you need to transmit and store data securely you reinvent the wheel: you have to
take care of how to encrypt data properly, how to handle randomly generated buffers,
then how to get data back, parse, and decrypt. Instead, you can use `MiniCocoon`
and `Cocoon`.

# Basic Usage

## 📌 Wrap/Unwrap

One party wraps private data into a container using `MiniCocoon::wrap`.
Another party (or the same one, or whoever knows the key) unwraps data
out of the container using `MiniCocoon::unwrap`.

`MiniCocoon` is preferred against `Cocoon` in a case of simple data encryption
because it generates a container with a smaller header without version control, and also
it allows to wrap data sequentially (wrap, wrap, wrap!) without performance drop
because of KDF calculation.
```rust
let cocoon = MiniCocoon::from_key(b"0123456789abcdef0123456789abcdef", &[0; 32]);

let wrapped = cocoon.wrap(b"my secret data")?;
assert_ne!(&wrapped, b"my secret data");

let unwrapped = cocoon.unwrap(&wrapped)?;
assert_eq!(unwrapped, b"my secret data");
```

## 📌 Dump/Parse

You can store data to file. Put data into `Vec` container, the data is going to be
encrypted _in place_ and stored in a file using the "cocoon" [format](#cocoon).

`Cocoon` is preferred as a long-time data storage, it has an extended header with a magic
number, options, and version control.
```rust
let mut data = b"my secret data".to_vec();
let cocoon = Cocoon::new(b"password");

cocoon.dump(data, &mut file)?;

let data = cocoon.parse(&mut file)?;
assert_eq!(&data, b"my secret data");
```

## 📌 Encrypt/Decrypt

You can encrypt data in place and avoid re-allocations. The method operates with a detached
meta-data (a container format prefix) in the array on the stack. It is suitable for "`no_std`"
build and whenever you want to evade re-allocations of a huge amount of data. You have to care
about how to store and transfer a data length and a container prefix though.

Both `MiniCocoon` and `Cocoon` have the same API, but prefixes are of different sizes.
`MiniCocoon` doesn't have the overhead of generating KDF on each encryption call, therefore
it's recommended for simple sequential encryption/decryption operations.
```rust
let mut data = "my secret data".to_owned().into_bytes();
let cocoon = MiniCocoon::from_key(b"0123456789abcdef0123456789abcdef", &[0; 32]);

let detached_prefix = cocoon.encrypt(&mut data)?;
assert_ne!(data, b"my secret data");

cocoon.decrypt(&mut data, &detached_prefix)?;
assert_eq!(data, b"my secret data");
```

# Study Case
You implement a database of secrets that must be stored in an encrypted file using a user
password. There are a lot of ways how your database can be represented in memory and how
it could be serialized. You handle these aspects on your own, e.g. you can use
`HashMap` to manage data and use `borsh`, or `bincode`,
to serialize the data. You can even compress a serialized buffer before encryption.

In the end, you use `Cocoon` to put the final image into an encrypted container.

```rust
use borsh::BorshSerialize;
use cocoon::{Cocoon, Error};

use std::collections::HashMap;
use std::fs::File;

// Your data can be represented in any way.
#[derive(BorshSerialize)]
struct Database {
inner: HashMap<String, String>,
}

fn main() -> Result<(), Error> {
let mut file = File::create("target/test.db")?;
let mut db = Database { inner: HashMap::new() };

// Over time you collect some kind of data.
db.inner.insert("my.email@example.com".to_string(), "eKPV$PM8TV5A2".to_string());

// You can choose how to serialize data. Also, you can compress it.
let encoded = db.try_to_vec().unwrap();

// Finally, you want to store your data secretly.
// Supply some password to Cocoon: password is any byte array, basically.
// Don't use a hard-coded password in real life!
// It could be a user-supplied password.
let cocoon = Cocoon::new(b"secret password");

// Dump the serialized database into a file as an encrypted container.
let container = cocoon.dump(encoded, &mut file)?;

Ok(())
}
```

# Cryptography

256-bit cryptography is chosen as a `Cocoon` baseline.

| Cipher (AEAD) | Key Derivation Function (KDF) |
|-------------------|----------------------------------|
| Chacha20-Poly1305 | PBKDF2-SHA256: 100000 iterations |
| AES256-GCM | |

* Key: 256-bit.
* Salt for KDF: random 128-bit + predefined part.
* Nonce for encryption: random 96-bit.

Key derivation parameters comply with NIST SP 800-132 recommendations (salt, iterations),
and cipher parameters (key, nonce, length) fit requirements of a particular cipher.
AEAD is chosen in order to authenticate encrypted data together with an unencrypted header.

# Zeroization

Encryption key is wrapped into zeroizing container
(provided by `zeroize` crate), which means that the key is erased automatically once it is dropped.

# How It Works

See more implementation details on
[![docs.rs](https://docs.rs/cocoon/badge.svg)](https://docs.rs/cocoon/), e.g.
1. the process of [container creation](https://docs.rs/cocoon/#container-creation),
2. customizable [crate features](https://docs.rs/cocoon/#crate-features),
3. and of course [API](https://docs.rs/cocoon/#cocoon).
3 changes: 3 additions & 0 deletions forks/cocoon/images/cocoon_creation_key.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading