Compare commits

..

2 Commits

Author SHA1 Message Date
wucke13
63ff75b93c remove anyhow
This is the first of a couple of commits aiming to completely remove anyhow in favor of using a mixture of `log` and a `thiserror` based enum. Partially fixes #93.
2023-06-17 22:43:45 +02:00
wucke13
5bebdd9284 fix broken devShell
The use of a fakecmake in the main step of the Rosenpass build removed real CMake from the devShell, essentially breaking cargo build from within it. This commit fixes that, by explicitly placing the real CMake in the devShell's nativeBuildInputs.
2023-06-17 22:41:56 +02:00
42 changed files with 1202 additions and 1847 deletions

View File

@@ -33,7 +33,7 @@ let systems_map = {
# aarch64-linux
i686-linux: ubuntu-latest,
x86_64-darwin: macos-13,
x86_64-darwin: macos-latest,
x86_64-linux: ubuntu-latest
}
@@ -64,7 +64,7 @@ let runner_setup = [
uses: "actions/checkout@v3"
}
{
uses: "cachix/install-nix-action@v22",
uses: "cachix/install-nix-action@v21",
with: { nix_path: "nixpkgs=channel:nixos-unstable" }
}
{

View File

@@ -15,7 +15,7 @@ jobs:
- i686-linux---rosenpass
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -31,7 +31,7 @@ jobs:
needs: []
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -48,7 +48,7 @@ jobs:
- i686-linux---rosenpass
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -63,7 +63,7 @@ jobs:
- ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -75,12 +75,12 @@ jobs:
x86_64-darwin---default:
name: Build x86_64-darwin.default
runs-on:
- macos-13
- macos-latest
needs:
- x86_64-darwin---rosenpass
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -92,13 +92,13 @@ jobs:
x86_64-darwin---release-package:
name: Build x86_64-darwin.release-package
runs-on:
- macos-13
- macos-latest
needs:
- x86_64-darwin---rosenpass
- x86_64-darwin---rosenpass-oci-image
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -110,11 +110,11 @@ jobs:
x86_64-darwin---rosenpass:
name: Build x86_64-darwin.rosenpass
runs-on:
- macos-13
- macos-latest
needs: []
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -126,12 +126,12 @@ jobs:
x86_64-darwin---rosenpass-oci-image:
name: Build x86_64-darwin.rosenpass-oci-image
runs-on:
- macos-13
- macos-latest
needs:
- x86_64-darwin---rosenpass
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -143,10 +143,10 @@ jobs:
x86_64-darwin---check:
name: Run Nix checks on x86_64-darwin
runs-on:
- macos-13
- macos-latest
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -163,7 +163,7 @@ jobs:
- x86_64-linux---rosenpass
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -180,7 +180,7 @@ jobs:
- x86_64-linux---proverif-patched
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -196,7 +196,7 @@ jobs:
needs: []
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -210,11 +210,11 @@ jobs:
runs-on:
- ubuntu-latest
needs:
- x86_64-linux---rosenpass-static-oci-image
- x86_64-linux---rosenpass-static
- x86_64-linux---rosenpass-static-oci-image
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -230,7 +230,7 @@ jobs:
needs: []
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -247,7 +247,7 @@ jobs:
- x86_64-linux---rosenpass
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -263,7 +263,7 @@ jobs:
needs: []
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -280,7 +280,7 @@ jobs:
- x86_64-linux---rosenpass-static
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -296,7 +296,7 @@ jobs:
needs: []
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -311,7 +311,7 @@ jobs:
- ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -326,7 +326,7 @@ jobs:
if: ${{ github.ref == 'refs/heads/main' }}
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12

View File

@@ -17,14 +17,6 @@ jobs:
with:
args: --check .
shellcheck:
name: Shellcheck
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run ShellCheck
uses: ludeeus/action-shellcheck@master
cargo-audit:
runs-on: ubuntu-latest
steps:
@@ -74,46 +66,3 @@ jobs:
# - https://github.com/rosenpass/rosenpass/issues/62
# - https://github.com/rust-lang/rust/issues/108378
- run: RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --document-private-items
cargo-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Install libsodium
run: sudo apt-get install -y libsodium-dev
# liboqs requires quite a lot of stack memory, thus we adjust
# the default stack size picked for new threads (which is used
# by `cargo test`) to be _big enough_. Setting it to 8 MiB
- run: RUST_MIN_STACK=8388608 cargo test
cargo-test-nix-devshell-x86_64-linux:
runs-on:
- ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
with:
name: rosenpass
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
- run: nix develop --command cargo test

View File

@@ -12,7 +12,7 @@ jobs:
- ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -30,10 +30,10 @@ jobs:
x86_64-darwin---release:
name: Build release artifacts for x86_64-darwin
runs-on:
- macos-13
- macos-latest
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12
@@ -54,7 +54,7 @@ jobs:
- ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: cachix/install-nix-action@v22
- uses: cachix/install-nix-action@v21
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v12

View File

@@ -1,17 +0,0 @@
# TODO use CI_JOB_TOKEN once https://gitlab.com/groups/gitlab-org/-/epics/6310 is fixed
pull-from-gh:
only: ["schedules"]
variables:
REMOTE: "https://github.com/rosenpass/rosenpass.git"
LOCAL: " git@gitlab.com:rosenpass/rosenpass.git"
GIT_STRATEGY: none
before_script:
- mkdir ~/.ssh/
- echo "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
- echo "$REPO_SSH_KEY" > ~/.ssh/id_ed25519
- chmod 600 --recursive ~/.ssh/
- git config --global user.email "ci@gitlab.com"
- git config --global user.name "CI"
script:
- git clone --mirror $REMOTE rosenpass
- cd rosenpass && git push --mirror $LOCAL

821
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,40 @@
[workspace]
resolver = "2"
[package]
name = "rosenpass"
version = "0.1.2-rc.4"
authors = ["Karolin Varner <karo@cupdev.net>", "wucke13 <wucke13@gmail.com>"]
edition = "2021"
license = "MIT OR Apache-2.0"
description = "Build post-quantum-secure VPNs with WireGuard!"
homepage = "https://rosenpass.eu/"
repository = "https://github.com/rosenpass/rosenpass"
readme = "readme.md"
members = [
"rosenpass",
"kmac-test-vectors",
]
[[bench]]
name = "handshake"
harness = false
[dependencies]
base64 = "0.21.1"
static_assertions = "1.1.0"
memoffset = "0.9.0"
libsodium-sys-stable = { version = "1.19.28", features = ["use-pkg-config"] }
oqs-sys = { version = "0.7.2", default-features = false, features = ['classic_mceliece', 'kyber'] }
lazy_static = "1.4.0"
thiserror = "1.0.40"
paste = "1.0.12"
log = { version = "0.4.17", optional = true }
env_logger = { version = "0.10.0", optional = true }
serde = { version = "1.0.163", features = ["derive"] }
toml = "0.7.4"
clap = { version = "4.3.0", features = ["derive"] }
mio = { version = "0.8.6", features = ["net", "os-poll"] }
[build-dependencies]
anyhow = "1.0.71"
[dev-dependencies]
criterion = "0.4.0"
test_bin = "0.4.0"
[features]
default = ["log", "env_logger"]

View File

@@ -1,8 +1,7 @@
use anyhow::Result;
use rosenpass::pqkem::KEM;
use rosenpass::{
pqkem::StaticKEM,
protocol::{CryptoServer, HandleMsgResult, MsgBuf, PeerPtr, SPk, SSk, SymKey},
pqkem::{EphemeralKEM, CCAKEM},
protocol::{CcaPk, CcaSk, CryptoServer, HandleMsgResult, MsgBuf, PeerPtr, SymKey},
sodium::sodium_init,
};
@@ -39,9 +38,9 @@ fn hs(ini: &mut CryptoServer, res: &mut CryptoServer) -> Result<()> {
Ok(())
}
fn keygen() -> Result<(SSk, SPk)> {
let (mut sk, mut pk) = (SSk::zero(), SPk::zero());
StaticKEM::keygen(sk.secret_mut(), pk.secret_mut())?;
fn keygen() -> Result<(CcaSk, CcaPk)> {
let (mut sk, mut pk) = (CcaSk::zero(), CcaPk::zero());
CCAKEM::keygen(sk.secret_mut(), pk.secret_mut())?;
Ok((sk, pk))
}
@@ -62,12 +61,12 @@ fn criterion_benchmark(c: &mut Criterion) {
let (mut a, mut b) = make_server_pair().unwrap();
c.bench_function("cca_secret_alloc", |bench| {
bench.iter(|| {
SSk::zero();
CcaSk::zero();
})
});
c.bench_function("cca_public_alloc", |bench| {
bench.iter(|| {
SPk::zero();
CcaPk::zero();
})
});
c.bench_function("keygen", |bench| {

View File

@@ -21,13 +21,13 @@ fn generate_man() -> String {
// This function is purposely stupid and redundant
let man = render_man("mandoc", "./doc/rosenpass.1");
if let Ok(man) = man {
return man;
if man.is_ok() {
return man.unwrap();
}
let man = render_man("groff", "./doc/rosenpass.1");
if let Ok(man) = man {
return man;
if man.is_ok() {
return man.unwrap();
}
// TODO: Link to online manual here

View File

@@ -12,13 +12,13 @@
.Sh DESCRIPTION
.Nm
performs cryptographic key exchanges that are secure against quantum-computers
and then outputs the keys.
These keys can then be passed to various services, such as wireguard or other
vpn services, as pre-shared-keys to achieve security against attackers with
and outputs the keys.
These keys can then be passed to various services such as wireguard or other
vpn services as pre-shared-keys to achieve security against attackers with
quantum computers.
.Pp
This is a research project and quantum computers are not thought to become
practical in fewer than ten years.
practical in less than ten years.
If you are not specifically tasked with developing post-quantum secure systems,
you probably do not need this tool.
.Ss COMMANDS
@@ -31,7 +31,7 @@ file secret!
Start a process to exchange keys with the specified peers.
You should specify at least one peer.
.Pp
Its
It's
.Ar OPTIONS
are as follows:
.Bl -tag -width Ds
@@ -39,7 +39,7 @@ are as follows:
Instructs
.Nm
to listen on the specified interface and port.
By default,
By default
.Nm
will listen on all interfaces and select a random port.
.It Ar verbose

View File

@@ -59,10 +59,6 @@ listening on the provided IP and port combination, allowing connections from
.Sh EXIT STATUS
.Ex -std
.Sh EXAMPLES
In this example, we will assume that the server has an interface bound to
192.168.0.1, that accepts incoming connections on port 9999/UDP for Rosenpass
and port 10000/UDP for WireGuard.
.Pp
To create a VPN connection, start by generating secret keys on both hosts.
.Bd -literal -offset indent
rp genkey server.rosenpass-secret

30
flake.lock generated
View File

@@ -8,11 +8,11 @@
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
"lastModified": 1699770036,
"narHash": "sha256-bZmI7ytPAYLpyFNgj5xirDkKuAniOkj1xHdv5aIJ5GM=",
"lastModified": 1686291735,
"narHash": "sha256-mpq2m6TN3ImqqUqA4u93NvkZu5vH//3spqjmPRbRlvA=",
"owner": "nix-community",
"repo": "fenix",
"rev": "81ab0b4f7ae9ebb57daa0edf119c4891806e4d3a",
"rev": "6e6a94c4d0cac4821b6452fbae46609b89a8ddcf",
"type": "github"
},
"original": {
@@ -26,11 +26,11 @@
"systems": "systems"
},
"locked": {
"lastModified": 1694529238,
"narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
"lastModified": 1685518550,
"narHash": "sha256-o2d0KcvaXzTrPRIo0kOLV0/QXHhDQ5DTi+OxcjO8xqY=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
"rev": "a1720a10a6cfe8234c0e93907ffe81be440f4cef",
"type": "github"
},
"original": {
@@ -46,11 +46,11 @@
]
},
"locked": {
"lastModified": 1698420672,
"narHash": "sha256-/TdeHMPRjjdJub7p7+w55vyABrsJlt5QkznPYy55vKA=",
"lastModified": 1679567394,
"narHash": "sha256-ZvLuzPeARDLiQUt6zSZFGOs+HZmE+3g4QURc8mkBsfM=",
"owner": "nix-community",
"repo": "naersk",
"rev": "aeb58d5e8faead8980a807c840232697982d47b9",
"rev": "88cd22380154a2c36799fe8098888f0f59861a15",
"type": "github"
},
"original": {
@@ -61,11 +61,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1698846319,
"narHash": "sha256-4jyW/dqFBVpWFnhl0nvP6EN4lP7/ZqPxYRjl6var0Oc=",
"lastModified": 1686237827,
"narHash": "sha256-fAZB+Zkcmc+qlauiFnIH9+2qgwM0NO/ru5pWEw3tDow=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "34bdaaf1f0b7fb6d9091472edc968ff10a8c2857",
"rev": "81ed90058a851eb73be835c770e062c6938c8a9e",
"type": "github"
},
"original": {
@@ -84,11 +84,11 @@
"rust-analyzer-src": {
"flake": false,
"locked": {
"lastModified": 1699715108,
"narHash": "sha256-yPozsobJU55gj+szgo4Lpcg1lHvGQYAT6Y4MrC80mWE=",
"lastModified": 1686239338,
"narHash": "sha256-c6Mm7UnDf3j3akY3YB3rELFA76QRbB8ttSBsh00LWi0=",
"owner": "rust-lang",
"repo": "rust-analyzer",
"rev": "5fcf5289e726785d20d3aa4d13d90a43ed248e83",
"rev": "9c03aa1ac2e67051db83a85baf3cfee902e4dd84",
"type": "github"
},
"original": {

View File

@@ -55,13 +55,14 @@
};
# parsed Cargo.toml
cargoToml = builtins.fromTOML (builtins.readFile ./rosenpass/Cargo.toml);
cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml);
# source files relevant for rust
src = pkgs.lib.sources.sourceFilesBySuffices ./. [
".lock"
".rs"
".toml"
src = pkgs.lib.sourceByRegex ./. [
"Cargo\\.(toml|lock)"
"build.rs"
"(src|benches)(/.*\\.(rs|md))?"
"rp"
];
# builds a bin path for all dependencies for the `rp` shellscript
@@ -111,9 +112,6 @@
version = cargoToml.package.version;
inherit src;
cargoBuildOptions = x: x ++ [ "-p" "rosenpass" ];
cargoTestOptions = x: x ++ [ "-p" "rosenpass" ];
doCheck = true;
nativeBuildInputs = with pkgs; [
@@ -159,6 +157,11 @@
'';
};
# liboqs requires quite a lot of stack memory, thus we adjust
# the default stack size picked for new threads (which is used
# by `cargo test`) to be _big enough_
RUST_MIN_STACK = 8 * 1024 * 1024; # 8 MiB
# We want to build for a specific target...
CARGO_BUILD_TARGET = target;
@@ -287,7 +290,7 @@
packages.proof-proverif = pkgs.stdenv.mkDerivation {
name = "rosenpass-proverif-proof";
version = "unstable";
src = pkgs.lib.sources.sourceByRegex ./. [
src = pkgs.lib.sourceByRegex ./. [
"analyze.sh"
"marzipan(/marzipan.awk)?"
"analysis(/.*)?"
@@ -306,6 +309,7 @@
#
devShells.default = pkgs.mkShell {
inherit (packages.proof-proverif) CRYPTOVERIF_LIB;
inherit (packages.rosenpass) RUST_MIN_STACK;
inputsFrom = [ packages.default ];
nativeBuildInputs = with pkgs; [
cmake # override the fakecmake from the main step above
@@ -318,6 +322,7 @@
};
devShells.coverage = pkgs.mkShell {
inputsFrom = [ packages.default ];
inherit (packages.rosenpass) RUST_MIN_STACK;
nativeBuildInputs = with pkgs; [ inputs.fenix.packages.${system}.complete.toolchain cargo-llvm-cov ];
};

View File

@@ -1,9 +0,0 @@
[package]
name = "kmac-test-vectors"
version = "0.1.0"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://github.com/rosenpass/rosenpass"
[dependencies]
xkcp-sys = "0.0.3"

View File

@@ -1,2 +0,0 @@
fn main() {
}

View File

@@ -177,31 +177,22 @@
}
@techreport{mceliece,
title = {{C}lassic {M}c{E}liece: conservative code-based cryptography (NIST Round 4 Submission)},
title = {{C}lassic {M}c{E}liece: conservative code-based cryptography},
author = {Martin R. Albrecht and Daniel J. Bernstein and Tung Chou and Carlos Cid and Jan Gilcher and Tanja Lange and Varun Maram and Ingo von Maurich and Rafael Misoczki and Ruben Niederhagen and Kenneth G. Paterson and Edoardo Persichetti and Christiane Peters and Peter Schwabe and Nicolas Sendrier and Jakub Szefer and Cen Jung Tjhai and Martin Tomlinson and Wen Wang},
year = 2022,
month = 10,
day = 23,
type = {NIST Post-Quantum Cryptography Round 4 Submission},
url = {https://classic.mceliece.org/mceliece-spec-20221023.pdf}
url = {https://classic.mceliece.org/}
}
@techreport{kyber,
title = {CRYSTALS-Kyber (NIST Round 3 Submission)},
title = {CRYSTALS-Kyber},
author = {Roberto Avanzi and Joppe Bos and Léo Ducas and Eike Kiltz and Tancrède Lepoint and
Vadim Lyubashevsky and John M. Schanck and Peter Schwabe and Gregor Seiler and Damien Stehlé},
year = 2020,
month = 10,
day = 1,
type = {NIST Post-Quantum Cryptography Selected Algorithm},
url = {https://pq-crystals.org/kyber/data/kyber-submission-nist-round3.zip}
}
@article{sha3,
title={SHA-3 derived functions: cSHAKE, KMAC, TupleHash, and ParallelHash},
author={Kelsey, John and Chang, Shu-jen and Perlner, Ray},
journal={NIST special publication},
volume={800},
pages={185},
year={2016}
url = {https://pq-crystals.org/kyber/}
}

View File

@@ -33,7 +33,6 @@ abstract: |
Rosenpass inherits most security properties from Post-Quantum WireGuard (PQWG). The security properties mentioned here are covered by the symbolic analysis in the Rosenpass repository.
## Secrecy
Three key encapsulations using the keypairs `sski`/`spki`, `sskr`/`spkr`, and `eski`/`epki` provide secrecy (see Section \ref{variables} for an introduction of the variables). Their respective ciphertexts are called `scti`, `sctr`, and `ectr` and the resulting keys are called `spti`, `sptr`, `epti`. A single secure encapsulation is sufficient to provide secrecy. We use two different KEMs (Key Encapsulation Mechanisms; see section \ref{skem}): Kyber and Classic McEliece.
## Authenticity
@@ -61,22 +60,12 @@ Note that while Rosenpass is secure against state disruption, using it does not
## Cryptographic Building Blocks
The following cryptographic building blocks are used:
| Use | Scheme | Version | Purpose |
| --- | --- | --- | --- |
| hash | KMAC[@sha3] | | SHA-3/Keccak based message authentication code |
| AEAD | ChaCha20-Poly1305[@rfc_chachapoly] | | Encryption with sequential nonce |
| XAEAD | XChaCha20-Poly1305[@draft_xchachapoly] | | Encryption with random nonce |
| SKEM | Classic McEliece 460896[@mceliece] | NIST Round 4 Submission | Key encapsulation with static keys |
| EKEM | Kyber-512[@kyber] | NIST Round 3 Submission (most recent) | Key encapsulation with ephemeral (random) keys |
All symmetric keys and hash values used in Rosenpass are 32 bytes long.
### Hash
A keyed hash function with one 32-byte input, one variable-size input, and one 32-byte output. As keyed hash function we use the KMAC[@sha3] with no (i.e. an empty) customization string.
A keyed hash function with one 32-byte input, one variable-size input, and one 32-byte output. As keyed hash function we use the HMAC construction [@rfc_hmac] with BLAKE2s [@rfc_blake2] as the inner hash function.
```pseudorust
hash(key, data) -> key
@@ -84,7 +73,7 @@ hash(key, data) -> key
### AEAD
Authenticated encryption with additional data for use with sequential nonces. We use ChaCha20-Poly1305 [@rfc_chachapoly] in the implementation.
Authenticated encryption with additional data for use with sequential nonces. We use ChaCha20Poly1305 [@rfc_chachapoly] in the implementation.
```pseudorust
AEAD::enc(key, nonce, plaintext, additional_data) -> ciphertext
@@ -93,7 +82,7 @@ AEAD::dec(key, nonce, ciphertext, additional_data) -> plaintext
### XAEAD
Authenticated encryption with additional data for use with random nonces. We use XChaCha20-Poly1305 [@draft_xchachapoly] in the implementation, a construction also used by WireGuard.
Authenticated encryption with additional data for use with random nonces. We use XChaCha20Poly1305 [@draft_xchachapoly] in the implementation, a construction also used by WireGuard.
```pseudorust
@@ -103,7 +92,7 @@ XAEAD::dec(key, nonce, ciphertext, additional_data) -> plaintext
### SKEM {#skem}
“Key Encapsulation Mechanism” (KEM) is the name of an interface widely used in post-quantum-secure protocols. KEMs can be seen as asymmetric encryption specifically for symmetric keys. Rosenpass uses two different KEMs. SKEM is the key encapsulation mechanism used with the static keypairs in Rosenpass. The public keys of these keypairs are not transmitted over the wire during the protocol. We use Classic McEliece 460896 (NIST Round 4 Submission; [@mceliece] which claims to be as hard to break as 192-bit AES. As one of the oldest post-quantum-secure KEMs, it enjoys wide trust among cryptographers, but it has not been chosen for standardization by NIST. Its ciphertexts and private keys are small (188 bytes and 13568 bytes), and its public keys are large (524160 bytes). This fits our use case: public keys are exchanged out-of-band, and only the small ciphertexts have to be transmitted during the handshake.
“Key Encapsulation Mechanism” (KEM) is the name of an interface widely used in post-quantum-secure protocols. KEMs can be seen as asymmetric encryption specifically for symmetric keys. Rosenpass uses two different KEMs. SKEM is the key encapsulation mechanism used with the static keypairs in Rosenpass. The public keys of these keypairs are not transmitted over the wire during the protocol. We use Classic McEliece 460896 [@mceliece] which claims to be as hard to break as 192-bit AES. As one of the oldest post-quantum-secure KEMs, it enjoys wide trust among cryptographers, but it has not been chosen for standardization by NIST. Its ciphertexts and private keys are small (188 bytes and 13568 bytes), and its public keys are large (524160 bytes). This fits our use case: public keys are exchanged out-of-band, and only the small ciphertexts have to be transmitted during the handshake.
```pseudorust
SKEM::enc(public_key) -> (ciphertext, shared_key)
@@ -112,7 +101,7 @@ SKEM::dec(secret_key, ciphertext) -> shared_key
### EKEM
Key encapsulation mechanism used with the ephemeral KEM keypairs in Rosenpass. The public keys of these keypairs need to be transmitted over the wire during the protocol. We use Kyber-512 [@kyber] (NIST Round 3 Submission), which has been selected in the NIST post-quantum cryptography competition and claims to be as hard to break as 128-bit AES. Its ciphertexts, public keys, and private keys are 768, 800, and 1632 bytes long, respectively, providing a good balance for our use case as both a public key and a ciphertext have to be transmitted during the handshake.
Key encapsulation mechanism used with the ephemeral KEM keypairs in Rosenpass. The public keys of these keypairs need to be transmitted over the wire during the protocol. We use Kyber-512 [@kyber], which has been selected in the NIST post-quantum cryptography competition and claims to be as hard to break as 128-bit AES. Its ciphertexts, public keys, and private keys are 768, 800, and 1632 bytes long, respectively, providing a good balance for our use case as both a public key and a ciphertext have to be transmitted during the handshake.
```pseudorust
EKEM::enc(public_key) -> (ciphertext, shared_key)
@@ -219,30 +208,6 @@ hs_enc = hash(hash(hash(0, PROTOCOL), "chaining key extract"), "handshake encryp
= lhash("chaining key extract", "handshake encryption")
```
## Protocol roles
There are two handshake roles:
- The initiator
- The responder
The initiator acts as a stateful client, directing the handshake process. The responder acts as a stateless server reacting to the initiator's messages while keeping no local state until the handshake is complete. Instead, the responder pushes their variables into an encrypted session cookie.
The number of concurrent responder-role handshakes with another client is unlimited to account for the possibility of an imposter trying to execute a handshake: Before completion of said handshake, there is no way to figure out which peer is an imposter and which peer is a legitimate client; any attempt to do so might lead to to a state-disruption attack -- denial of service on the protocol level.
There is no mechanism to negotiate which of the peers acts as initiator and responder, instead two parties may be processing separate handshakes in client role and in responder role at the same time.
Implementations must account for this possibility by aborting any ongoing initiator-role handshake upon accepting an InitConf package. Implementations should also use different back-off periods depending on whether the handshake was completed in initiator role or in responder role. The following values are used in the rust reference implementation:
- Initiator rekey interval: 130s
- Responder rekey interval: 120s
In practice these delays cause participants to take turns acting as initiator and acting as responder since the ten seconds difference is usually enough for the handshake with switched roles to complete before the old initiator's rekey timer goes to zero.
## Endianess
All numeric values are in little-endian format unless otherwise noted.
## Server State
### Global
@@ -257,7 +222,7 @@ The server needs to store the following variables:
Not mandated per se, but required in practice:
* `peers` A lookup table mapping the peer ID to the internal peer structure
* `sessions` A lookup table mapping the session ID to the ongoing initiator handshake or live session
* `index` A lookup table mapping the session ID to the ongoing initiator handshake or live session
### Peer
@@ -287,7 +252,7 @@ The responder stores no state. While the responder has access to all of the abov
The biscuit is encrypted with the `XAEAD` primitive and a randomly chosen nonce. The values `sidi` and `sidr` are transmitted publicly as part of InitConf, so they do not need to be present in the biscuit, but they are added to the biscuit's additional data to make sure the correct values are transmitted as part of InitConf.
The `biscuit_key` used to encrypt biscuits should be rotated frequently. The reference implementation uses a rotation interval of five minutes. Implementations should keep two biscuit keys in memory at any given time to avoid having to drop packages when `biscuit_key` is rotated.
The `biscuit_key` used to encrypt biscuits should be rotated every two minutes. Implementations should keep two biscuit keys in memory at any given time to avoid having to drop packages when `biscuit_key` is rotated.
### Live Session State
@@ -417,7 +382,7 @@ fn load_biscuit(nct) {
let pt : Biscuit = XAEAD::dec(k, n, ct, ad);
// Find the peer and apply retransmission protection
lookup_peer(pt.peerid);
assert(pt.biscuit_no >= peer.biscuit_used);
assert(pt.biscuit_no <= peer.biscuit_used);
// Restore the chaining key
ck ← pt.ck;
@@ -469,77 +434,8 @@ The initiator deals with packet loss by storing the messages it sends to the res
The responder does not need to do anything special to handle RespHello retransmission if the RespHello package is lost, the initiator retransmits InitHello and the responder can generate another RespHello package from that. InitConf retransmission needs to be handled specifically in the responder code because accepting an InitConf retransmission would reset the live session including the nonce counter, which would cause nonce reuse. Implementations must detect the case that `biscuit_no = biscuit_used` in ICR5, skip execution of ICR6 and ICR7, and just transmit another EmptyData package to confirm that the initiator can stop transmitting InitConf.
## Timers
The Rosenpass protocol uses various timer-triggered events during its operation. This section provides a listing of the timers used and gives the values used in the reference implementation. Other implementations may choose different values.
### Rekeying
Period after which the previous responder starts a new handshake in initiator role; period after which the previous initiator starts a new handshake in initiator role again; period after which a peer rejects an existing shared key.
```pseudorust
REKEY_AFTER_TIME_RESPONDER = 120s
REKEY_AFTER_TIME_INITIATOR = 130s
REJECT_AFTER_TIME = 180s
```
### Biscuits
Period after which the biscuit key is rotated.
```pseudorust
BISCUIT_EPOCH = 300s
```
### Retransmission
Delay after which all retransmission attempts are aborted; exponential backoff factor for retransmission delay; initial (minimum) retransmission delay; final (maximum) retransmission delay; retransmission jitter/variance factor.
```pseudorust
RETRANSMIT_ABORT = 120s
RETRANSMIT_DELAY_GROWTH = 2
RETRANSMIT_DELAY_BEGIN = 500ms
RETRANSMIT_DELAY_END = 10s
RETRANSMIT_DELAY_JITTER = 0.5
```
\printbibliography
\setupimage{landscape,fullpage,label=img:HandlingCode}
![Rosenpass Message Handling Code](graphics/rosenpass-wp-message-handling-code-rgb.svg)
\printbibliography
# Version history
## Protocol version 2 -- XXXX-XX-XX
During the implementation of go-rosenpass, Steffen Vogel found a number of problems ([issue #68](https://github.com/rosenpass/rosenpass/issues/68)) with the whitepaper. Version two of the document primarily addresses these issues:
### Features
- Use NIST Round 4 Submission of Classic McEliece
### Security issues
- Explicitly erase `eski` (forward secrecy). This is a minor security fix: Before this change the specification left erasing the secret key to the implementation. The reference implementation did erase `eski` but only after receiving the responder confirmation package (EmptyData at the time) instructing the initiator to stop retransmission of the InitConf package. With this change, `eski` is erased before transmission of the InitConf package.
### Bug fixes
- Handle race conditions when both peers complete concurrent handshakes in switched roles. Backwards compatible. Initially addressed in [397a776](https://github.com/rosenpass/rosenpass/commit/397a776c55b1feae1e8e5aceef01cf06bf56b6ed) "fix: Race condition due to concurrent handshake".
### Clarifications
- Add detailed information about when in the handshake process security properties are achieved.
- Extra section with a list of timers used.
- Rename the session id/session lookup table from `index` to `sessions`
- Indicate which version of Classic McEliece and Kyber is used
- Add a chart with the cryptographic building blocks used
### Mistakes/Inconsistencies
- Old `ct1` name was used for `sctr` (the static responder KEM ciphertext)
- Biscuit number was asserted to be smaller or equal to the peer's biscuit used variable, where it should have been bigger or equal to
- Fix a typo "key chaining extract" -> "chaining key extract"; "key chaining init" -> "chaining key init"
## Protocol version 1 -- 2023-03-04
Initial release.

View File

@@ -71,13 +71,6 @@ Rosenpass is packaged for more and more distributions, maybe also for the distri
[![Packaging status](https://repology.org/badge/vertical-allrepos/rosenpass.svg)](https://repology.org/project/rosenpass/versions)
# Mirrors
Don't want to use GitHub or only have an IPv6 connection? Rosenpass has set up two mirrors for this:
- [NotABug](https://notabug.org/rosenpass/rosenpass)
- [GitLab](https://gitlab.com/rosenpass/rosenpass/)
# Supported by
Funded through <a href="https://nlnet.nl/">NLNet</a> with financial support for the European Commission's <a href="https://nlnet.nl/assure">NGI Assure</a> program.

View File

@@ -1,45 +0,0 @@
[package]
name = "rosenpass"
version = "0.2.0"
authors = ["Karolin Varner <karo@cupdev.net>", "wucke13 <wucke13@gmail.com>"]
edition = "2021"
license = "MIT OR Apache-2.0"
description = "Build post-quantum-secure VPNs with WireGuard!"
homepage = "https://rosenpass.eu/"
repository = "https://github.com/rosenpass/rosenpass"
readme = "readme.md"
[[bench]]
name = "handshake"
harness = false
[dependencies]
anyhow = { version = "1.0.71", features = ["backtrace"] }
base64 = "0.21.1"
static_assertions = "1.1.0"
memoffset = "0.9.0"
libsodium-sys-stable = { version = "1.19.28", features = ["use-pkg-config"] }
oqs-sys = { git = "https://github.com/koraa/liboqs-rust.git", branch = "main", default-features = false, features = ['classic_mceliece', 'kyber'] }
lazy_static = "1.4.0"
thiserror = "1.0.40"
paste = "1.0.12"
log = { version = "0.4.17", optional = true }
env_logger = { version = "0.10.0", optional = true }
serde = { version = "1.0.163", features = ["derive"] }
toml = "0.7.4"
clap = { version = "4.3.0", features = ["derive"] }
mio = { version = "0.8.6", features = ["net", "os-poll"] }
sha3 = "0.10.8"
num-traits = "0.2.17"
digest = "0.10.7"
[build-dependencies]
anyhow = "1.0.71"
[dev-dependencies]
criterion = "0.4.0"
test_bin = "0.4.0"
stacker = "0.1.15"
[features]
default = ["log", "env_logger"]

View File

@@ -1,60 +0,0 @@
#[macro_use]
pub mod util;
#[macro_use]
pub mod symmetric;
pub mod coloring;
#[rustfmt::skip]
pub mod labeled_prf;
pub mod app_server;
pub mod cli;
pub mod config;
pub mod msgs;
pub mod pqkem;
pub mod prftree;
pub mod protocol;
#[derive(thiserror::Error, Debug)]
pub enum RosenpassError {
#[error("error in OQS")]
Oqs,
#[error("error from external library while calling OQS")]
OqsExternalLib,
#[error("buffer size mismatch, required {required_size} but found {actual_size}")]
BufferSizeMismatch {
required_size: usize,
actual_size: usize,
},
#[error("invalid message type")]
InvalidMessageType(u8),
}
impl RosenpassError {
/// Helper function to check a buffer size
fn check_buffer_size(required_size: usize, actual_size: usize) -> Result<(), Self> {
if required_size != actual_size {
Err(Self::BufferSizeMismatch {
required_size,
actual_size,
})
} else {
Ok(())
}
}
}
/// Extension trait to attach function calls to foreign types.
trait RosenpassMaybeError {
/// Checks whether something is an error or not
fn to_rg_error(&self) -> Result<(), RosenpassError>;
}
impl RosenpassMaybeError for oqs_sys::common::OQS_STATUS {
fn to_rg_error(&self) -> Result<(), RosenpassError> {
use oqs_sys::common::OQS_STATUS;
match self {
OQS_STATUS::OQS_SUCCESS => Ok(()),
OQS_STATUS::OQS_ERROR => Err(RosenpassError::Oqs),
OQS_STATUS::OQS_EXTERNAL_LIB_ERROR_OPENSSL => Err(RosenpassError::OqsExternalLib),
}
}
}

View File

@@ -1,204 +0,0 @@
use std::result::Result;
use digest::{Update, XofReader};
use crate::util::types::Leftright;
use crate::util::io::{WriteSecret, CountAndWriteSecret};
#[cfg(test)]
use crate::util::io::assemble_secret;
/// Variable length encoding for unsigned numbers as specified by in
/// NIST Special Publication 800-185.
///
/// This corresponds to left_encode(…) if `lr == Leftright::Left`
/// and to right_encode(…) if `lr == Leftright::Right`.
///
/// # Panics
///
/// This will panic if the number `v` is greater than $2^{2040}-1$,
/// i.e. if more than 255 bits are required to represent the number.
///
/// For the natively supported integers (u8…u128 and usize), this will not panic
/// unless usize is an u256 now.
///
/// # Example
///
/// ```
/// use crate::util::types::Leftright::*;
///
/// assert_eq!(assemble_secret(|w| leftright_encode(Left, w, 0)), assemble_secret(|w| left_encode(w, 0)));
/// assert_eq!(assemble_secret(|w| leftright_encode(Left, w, 1)), assemble_secret(|w| left_encode(w, 1)));
/// assert_eq!(assemble_secret(|w| leftright_encode(Left, w, 0xff)), assemble_secret(|w| left_encode(w, 0xff)));
/// assert_eq!(assemble_secret(|w| leftright_encode(Left, w, 0x100)), assemble_secret(|w| left_encode(w, 0x100)));
/// assert_eq!(assemble_secret(|w| leftright_encode(Left, w, 0x010203)), assemble_secret(|w| left_encode(w, 0x010203)));
///
/// assert_eq!(assemble_secret(|w| leftright_encode(Right, w, 0)), assemble_secret(|w| right_encode(w, 0)));
/// assert_eq!(assemble_secret(|w| leftright_encode(Right, w, 1)), assemble_secret(|w| right_encode(w, 1)));
/// assert_eq!(assemble_secret(|w| leftright_encode(Right, w, 0xff)), assemble_secret(|w| right_encode(w, 0xff)));
/// assert_eq!(assemble_secret(|w| leftright_encode(Right, w, 0x100)), assemble_secret(|w| right_encode(w, 0x100)));
/// assert_eq!(assemble_secret(|w| leftright_encode(Right, w, 0x010203)), assemble_secret(|w| right_encode(w, 0x010203)));
/// ```
pub(crate) fn leftright_encode<W, N>(lr: Leftright, dst: W, v: &N)
-> Result<(), W::Error>
where
W: WriteSecret,
N: ToBytes {
use Leftright::*;
let be = v.to_be_bytes();
let trailing_zeros = be.rev().take_while(|v| v == 0).count();
let num_bytes = std::max(1, be.len() - trailing_zeros);
assert!(num_bytes < 256);
match lr {
Left => {
dst.write(from_ref(num_bytes.into()))?;
dst.write(&be[..num_bytes])?;
},
Right => {
dst.write(&be[..num_bytes])?;
dst.write(from_ref(num_bytes.into()))?;
}
}
Ok(())
}
/// Variable length encoding for unsigned numbers as specified by in
/// NIST Special Publication 800-185.
///
/// First writes a single byte indication the width of the
/// encoded number to `dst` then writes the number in big-endian
/// format.
///
/// # Panics
///
/// This will panic if the number `v` is greater than $2^{2040}-1$,
/// i.e. if more than 255 bits are required to represent the number.
///
/// For the natively supported integers (u8…u128 and usize), this will not panic
/// unless usize is an u256 now.
///
/// # Example
///
/// ```
/// assert_eq!(assemble_secret(|w| left_encode(w, 0)), b"\1\0");
/// assert_eq!(assemble_secret(|w| left_encode(w, 1)), b"\1\1");
/// assert_eq!(assemble_secret(|w| left_encode(w, 0xff)), b"\1\0xff");
/// assert_eq!(assemble_secret(|w| left_encode(w, 0x100)), b"\1\0\1");
/// assert_eq!(assemble_secret(|w| left_encode(w, 0x010203)), b"\3\1\2\3");
/// ```
pub(crate) fn left_encode<W, N>(dst: W, v: &N)
-> Result<(), W::Error>
where
W: Write,
N: ToBytes {
nist_leftright_encode(Leftright::Left, dst, v)
}
/// Variable length encoding for unsigned numbers as specified by in
/// NIST Special Publication 800-185.
///
/// This uses the same format as `left_encode` but swaps length tag
/// and then length of the number itself.
///
/// # Panics
///
/// This will panic if the number `v` is greater than $2^{2040}-1$,
/// i.e. if more than 255 bits are required to represent the number.
///
/// For the natively supported integers (u8…u128 and usize), this will not panic
/// unless usize is an u256 now.
///
/// # Example
///
/// ```
/// assert_eq!(assemble_secret(|w| left_encode(w, 0)), b"\0\1");
/// assert_eq!(assemble_secret(|w| left_encode(w, 1)), b"\1\1");
/// assert_eq!(assemble_secret(|w| left_encode(w, 0xff)), b"\0xff\1");
/// assert_eq!(assemble_secret(|w| left_encode(w, 0x100)), b"\0\1\1");
/// assert_eq!(assemble_secret(|w| left_encode(w, 0x010203)), b"\1\2\3\3");
/// ```
pub(crate) fn right_encode<W, N>(dst: &mut W, v: &N)
-> Result<(), W::Error>
where
W: WriteSecret,
N: ToBytes {
nist_leftright_encode(Leftright::Right, dst, v)
}
/// Serialization for variable length strings as specified by in
/// NIST Special Publication 800-185.
///
/// This first writes the length of the string using `left_encode` to `dst`
/// then copies the string itself to `dst`.
///
/// # Example
///
/// ```
/// assert_eq!(assemble_secret(|w| encode_string(w, b"")), b"\1\0");
/// assert_eq!(assemble_secret(|w| encode_string(w, b"\0")), b"\1\1\0");
/// assert_eq!(assemble_secret(|w| encode_string(w, b"Hello")), b"\1\5Hello");
/// assert_eq!(assemble_secret(|w| encode_string(w, b"Hello World")), b"\1\x0AHello World");
/// ```
pub(crate) fn encode_string<W>(dst: W, str: &[u8])
-> Result<(), W::Error>
where
W: WriteSecret {
/// This will not panic unless `usize` is an u256 now.
left_encode(&mut dst, str.len())?;
w.write_all(str)?;
Ok(())
}
/// Serialize arbitrary data and then pad the output using zero bytes
/// as specified NIST Special Publication 800-185.
///
/// This first writes the width of the padding unit `pad_to` to `dst`
/// and then calls `f` to serialize arbitrary data. Finally, this function
/// writes null bytes until the total number of bytes written is a multiple
/// of `pad_to`.
///
/// # Example
///
/// ```
/// assert_eq!(assemble_secret(|w| bytepad(w, 5, |w| )), b"\1\5\0\0\0");
/// assert_eq!(assemble_secret(|w| bytepad(w, 5, |w| w.write_all(b"Hello"))), b"\1\5Hello\0\0\0");
/// assert_eq!(assemble_secret(|w| bytepad(w, 5, |w| w.write_all(b"Hello dearie!"))), b"\1\5Hello dearie!");
/// assert_eq!(assemble_secret(|w| bytepad(w, 5, |w| w.write_all(b"_"))), b"\1\5_\0\0");
/// ```
pub(crate) fn bytepad<W, Fn>(dst: W, pad_to: u64, f: Fn)
-> Result<(), W::Error>
where
W: WriteSecret,
Fn: FnOnce<CountAndWrite> {
let w = CountAndWrite::new(dst);
nist_left_encode(&mut w, pad_to)?;
f(w)?;
for _ in ..ceiling_remainder(w2.get_count(), pad_to) {
w.write_all(from_ref(0u8.into()))?;
}
Ok(())
}
///
#[inline]
pub(crate) fn kmac256(out: &mut [u8], key: &[u8], data: &[u8]) {
// A proper implementation of KMAC is currently not available in the sha3 crate, but they do
// provide cSHAKE which can be used to implement KMAC
//
// Issue:
// https://github.com/RustCrypto/MACs/issues/133
// "kmac: Towards an implementation"
//
// KMAC Spec:
// https://doi.org/10.6028/NIST.SP.800-185
// "SHA-3 derived functions: cSHAKE, KMAC, TupleHash, and ParallelHash"
// Page 10
use sha3::{CShake256, CShake256Core};
let hasher = CShake256::from_core(
CShake256Core::new_with_function_name(&"", &"KMAC"));
bytepad(hasher, 168, |w| encode_string(w, key)).guaranteed();
hasher.update(data);
right_encode(hasher, out.len()).guaranteed();
hasher.finalize_xof_into(out);
}

View File

@@ -1,9 +0,0 @@
//! Symmetric primitives & Libsodium bindings
pub(crate) mod sodium;
pub(crate) mod kmac;
pub(crate) mod kem;
pub(crate) use sodium::*;
pub(crate) use kmac::kmac256;
pub(crate) use kem::{KEM, StaticKEM, EphemeralKEM};

View File

@@ -1,186 +0,0 @@
use std::io::Write;
use crate::util::cpy_min;
use crate::util::result::{NeverFails, Guaranteed};
/// Errors
#[derive(Debug, PartialEq, Eq)]
enum BoundedWriteSecretError {
OutOfBounds,
}
/// A version of the Write trait for secret data
///
/// # Examples
///
/// ```
/// let buf = [0u8; 8]
/// assert_eq!(buf.write_secret(b"Hello"), Ok(()));
/// assert_eq!(&buf, b"Hello\0\0\0");
///
/// assert_eq!(buf.write_secret(b"You glorious world"), Err(BoundedWriteSecretError::OutOfBounds));
/// assert_eq!(&buf, b"Hello\0\0\0");
/// ```
pub(crate) trait WriteSecret {
type Error;
/// Atomic write operation: writes `buf` to the underlying container
///
/// The implementation must guarantee that the write operation either completes
/// successfully, otherwise no data must be written.
///
/// The implementation should take care to ensure that any intermediate buffers
/// are zeroized.
fn write_secret(&mut self, buf: &[u8]) -> std::Result<(), Self::Error>;
}
impl<T: AsRef<[u8]>> WriteSecret for T {
type Error = BoundedWriteSecretError;
fn write_secret(&mut self, buf: &[u8]) -> std::Result<(), Self::Error> {
let dst = self.as_ref();
if dst.len() >= buf.len() {
cpy_min(buf.len(), dst.len());
Ok(())
} else {
Err(CursorSecretWriteError::OutOfBounds)
}
}
}
/// Helper for make_write_secret to implement WriteSecret on the fly
#[derive(Debug, Clone)]
pub(crate) struct ClosureWriteSecret<Fn, E>
where
Fn: FnMut(&[u8]) -> std::Result<(), E> {
f: Fn
}
/// Implement WriteSecret on the fly
///
/// # Examples
///
/// ```
/// enum PasswordWriterError {
/// OutOfBounds
/// }
///
/// let password = [0u8; 12];
/// let ptr = 0usize;
/// let password_writer = make_write_secret(mut |buf| {
/// let new_ptr = ptr + buf.len();
/// if new_ptr > password.len() {
/// Err(PasswordWriterError::OutOfBounds)
/// } else {
/// (&mut password[ptr..]).copy_from_slice(buf));
/// ptr = new_ptr;
/// Ok(())
/// }
/// });
///
/// assert_eq!(password_writer.write_secret("This is"), Ok(()));
/// assert_eq!(&password, b"This is\0\0\0\0\0");
///
/// assert_eq!(password_writer.write_secret("a bad password"), Err(PasswordWriterError::OutOfBounds));
/// assert_eq!(&password, b"This is\0\0\0\0\0");
/// ```
pub(crate) fn make_write_secret<Fn, E>(f: Fn)
-> ClosureWriteSecret<Fn, E>
where
Fn: FnMut(&[u8]) -> std::Result<(), E> {
ClosureWriteSecret { f }
}
impl<Fn, Error> WriteSecret for ClosureWriteSecret<Fn, E> {
type Error = E;
fn write_secret<W: Write>(&mut self, buf: &[u8]) -> std::Result<(), Self::Error> {
self.f(buf)
}
}
impl<T: digest::Update> WriteSecret for T {
type Error = NeverFails;
fn write_secret<W: Write>(&mut self, buf: &[u8]) -> Guaranteed<()> {
self.update(buf);
Ok(())
}
}
impl<T: std::io::Write> WriteSecret for WriteSecretFromIoWrite<T> {
type Error = std::io::Error;
fn write_secret<W: Write>(&mut self, buf: &[u8]) -> std::io::Result<()> {
self.0.write_all(buf)
}
}
/// Helper for counting the number of byts written to a stream
///
/// # Examples
///
/// ```
/// let counter = CountAndWriteSecret::new(make_write_secret(|buf| -> std::Result<(), ()> {
/// Ok(())
/// }));
///
/// assert_eq!(counter.write_secret(b"hello"), Ok(()));
/// assert_eq!(counter.count(), 5);
///
/// let (dummy_writer, count) = counter.into_parts();
/// assert_eq!(count, 5);
///
/// let counter = CountAndWriteSecret::from_parts(dummy_writer, count+2000);
/// assert_eq!(counter.write_secret(b" world"), Ok(()));
/// assert_eq!(counter.count(), 2011);
/// ```
pub(crate) struct CountAndWriteSecret<W: WriteSecret> {
inner: W,
count: usize,
}
impl<W: WriteSecret> CountAndWriteSecret {
/// Create a new CountAndWriteSecret, wrapping the `inner` stream
pub(crate) fn new(inner: W) {
Self::from_parts(inner, 0)
}
/// Construct a new CountAndWriteSecret from an inner stream and a pre-existing count
pub(crate) fn from_parts(inner: W, count: usize) {
Self { inner, count }
}
/// Extract the inner stream and the current count
pub(crate) fn into_parts(self) -> (W, usize) {
(self.inner, self.count)
}
/// Retrieve the number of bytes written to the inner stream
pub(crate) fn count() -> usize {
self.count
}
}
impl<W: WriteSecret> WriteSecret for CountAndWriteSecret {
type Error = W::Error;
fn write_secret(&mut self, buf: &[u8]) -> std::Result<(), Self::Error> {
let no = self.inner.write(buf)?;
self.count += no;
Ok(no)
}
}
/// Construct a buffer through multiple .write_secret() calls,
/// returning the constructed buffer.
///
/// # Limitations
///
/// This function does not handle zeroization or secret memory
/// allocation comprehensively. It must only be used as a helper
/// during unit tests.
#[cfg(test)]
fn assemble_secret<Fn: FnOnce(impl WriteSecret)>(f: Fn) -> std::vec::Vec<u8> {
let buf = std::vec::Vec::new();
f(make_write_secret(|data| -> Guaranteed<()> {
buf.extend_from_slice(data);
Ok(())
}));
buf
}

View File

@@ -1,31 +0,0 @@
use core::ops::{Rem, Add, Sub};
/// Round lhs up to the next multiple of div
///
/// # Examples
///
/// ```
/// assert_eq!(round_up(10u8, 5u8), 10u8);
/// assert_eq!(round_up(.3f32, .2f32), .4f32);
/// assert_eq!(round_up(22u64, 17u64), 32u64);
/// ```
pub(crate) fn round_up<T>(lhs: T, div: T) -> T
where
T: Rem + Add {
lhs + (lhs % div)
}
/// Calculates the difference between val and the next highest multiple of div
///
/// # Examples
///
/// ```
/// assert_eq!(round_up(10u8, 5u8), 0u8);
/// assert_eq!(round_up(.3f32, .2f32), .1f32);
/// assert_eq!(round_up(22u64, 17u64), 32u64);
/// ```
pub(crate) fn gap_towards_multiple<T>(val: T, div: T)
where
T: Rem + Add + Sub {
round_up(val, div) - val
}

View File

@@ -1,88 +0,0 @@
use std::result::Result;
/// Trait for container types that guarantee successful unwrapping.
///
/// The `.guaranteed()` function can be used over unwrap to show that
/// the function will not panic.
///
/// Implementations must not panic.
pub(crate) trait GuaranteedValue {
type Value;
/// Extract the contained value while being panic-safe, like .unwrap()
///
/// # Panic Safety
///
/// Implementations of guaranteed() must not panic.
fn guaranteed(self) -> Self::Value;
}
/// An error type to indicate that an error will not occur.
///
/// This is a nullary enum; i.e. an instance of this enum can not be created.
pub(crate) enum NeverFails {}
/// A result type that never contains an error.
///
/// This is mostly useful in generic contexts.
///
/// # Examples
///
/// ```
/// use std::num::Wrapping;
/// use std::result::Result;
///
/// trait FailableAddition {
/// type Error;
/// fn failable_addition(&self, other: &Self) -> Result<Self, Self::Error>;
/// }
///
/// struct OverflowError;
///
/// impl<T> FailableAddition for Wrapping<T> {
/// type Error = NeverFails;
/// fn failable_addition(&self, other: &Self) -> Guaranteed<Self> {
/// self + other
/// }
/// }
///
/// impl<T> FailableAddition for u32 {
/// type Error = NeverFails;
/// fn failable_addition(&self, other: &Self) -> Guaranteed<Self> {
/// match self.checked_add(*other) {
/// Some(v) => Ok(v),
/// None => Err(OverflowError),
/// }
/// }
/// }
///
/// fn failable_multiply<T>(a: &T, b: u32)
/// -> Result<T, T::Error> {
/// where
/// T: FailableAddition<Error> {
/// let mut accu = a.failable_addition(a)?;
/// for _ in ..(b-1) {
/// accu.failable_addition(a)?;
/// }
/// Ok(accu)
/// }
///
/// // We can use .guaranteed() with Wrapping<u32>, since the operation uses
/// // the NeverFails error type.
/// // We can also use unwrap which just happens to not raise an error.
/// assert_eq!(failable_multiply(&Wrapping::new(42u32), 3).guaranteed(), 126);
/// assert_eq!(failable_multiply(&Wrapping::new(42u32), 3).unwrap(), 126);
///
/// // We can not use .guaranteed() with u32, since there can be an error.
/// // We can however use unwrap(), which may panic
/// assert_eq!(failable_multiply(&42u32, 3).guaranteed(), 126); // COMPILER ERROR
/// assert_eq!(failable_multiply(&42u32, 3).unwrap(), 126);
/// ```
pub(crate) type Guaranteed<T> = Result<T, NeverFails>;
impl<T> GuaranteedValue for Guaranteed<T> {
type Value = T;
fn guaranteed(self) -> Self::Value {
self.unwrap();
}
}

View File

@@ -1,6 +0,0 @@
/// Named boolean for arbitrary use to distinguish between
/// the directions left and right
pub(crate) enum Leftright {
Left,
Right
}

48
rp
View File

@@ -197,7 +197,7 @@ exchange() {
lip="${listen%:*}";
lport="${listen/*:/}";
if [[ "$lip" = "$lport" ]]; then
lip="[::]"
lip="[0::0]"
fi
shift;;
-h | -help | --help | help) usage; return 0;;
@@ -209,41 +209,15 @@ exchange() {
fatal "Needs at least one peer specified"
fi
# os dependent setup
case "$OSTYPE" in
linux-*) # could be linux-gnu or linux-musl
frag "
# Create the WireGuard interface
ip link add dev $(enquote "${dev}") type wireguard || true"
frag "
# Create the Wireguard interface
ip link add dev $(enquote "${dev}") type wireguard || true"
cleanup "
ip link del dev $(enquote "${dev}") || true"
cleanup "
ip link del dev $(enquote "${dev}") || true"
frag "
ip link set dev $(enquote "${dev}") up"
;;
freebsd*)
frag "
# load the WireGuard kernel module
kldload -n if_wg || fatal 'Cannot load if_wg kernel module'"
frag "
# Create the WireGuard interface
ifconfig wg create name $(enquote "${dev}") || true"
cleanup "
ifconfig $(enquote "${dev}") destroy || true"
frag "
ifconfig $(enquote "${dev}") up"
;;
*)
fatal "Your system $OSTYPE is not yet supported. We are happy to receive patches to address this :)"
;;
esac
frag "
ip link set dev $(enquote "${dev}") up"
frag "
# Deploy the classic wireguard private key
@@ -281,7 +255,7 @@ exchange() {
local arg; arg="$1"; shift
case "${arg}" in
peer) set -- "peer" "$@"; break;; # Next peer
endpoint) ip="${1%:*}"; port="${1##*:}"; shift;;
endpoint) ip="${1%:*}"; port="${1/*:/}"; shift;;
persistent-keepalive) keepalive="${1}"; shift;;
allowed-ips) allowedips="${1}"; shift;;
-h | -help | --help | help) usage; return 0;;
@@ -352,9 +326,7 @@ main() {
verbose=0
scriptdir="$(dirname "${script}")"
gitdir="$(detect_git_dir)" || true
if [[ -d /nix ]]; then
nixdir="$(readlink -f result/bin/rp | grep -Pio '^/nix/store/[^/]+(?=/bin/[^/]+)')" || true
fi
nixdir="$(readlink -f result/bin/rp | grep -Pio '^/nix/store/[^/]+(?=/bin/[^/]+)')" || true
binary="$(find_rosenpass_binary)"
# Parse command

View File

@@ -1,7 +1,4 @@
use anyhow::bail;
use anyhow::Result;
use log::{debug, error, info, warn};
use log::{error, info, warn};
use mio::Interest;
use mio::Token;
@@ -19,14 +16,15 @@ use std::path::PathBuf;
use std::process::Command;
use std::process::Stdio;
use std::slice;
use std::thread;
use std::time::Duration;
use crate::util::fopen_w;
use crate::RosenpassError;
use crate::{
config::Verbosity,
protocol::{CryptoServer, MsgBuf, PeerPtr, SPk, SSk, SymKey, Timing},
util::{b64_writer, fmt_b64},
Result,
};
const IPV4_ANY_ADDR: Ipv4Addr = Ipv4Addr::new(0, 0, 0, 0);
@@ -99,8 +97,8 @@ impl SocketPtr {
&mut srv.sockets[self.0]
}
pub fn send_to(&self, srv: &AppServer, buf: &[u8], addr: SocketAddr) -> anyhow::Result<()> {
self.get(srv).send_to(buf, addr)?;
pub fn send_to(&self, srv: &AppServer, buf: &[u8], addr: SocketAddr) -> Result<()> {
self.get(srv).send_to(&buf, addr)?;
Ok(())
}
}
@@ -182,7 +180,7 @@ impl Endpoint {
}
/// Start endpoint discovery from a hostname
pub fn discovery_from_hostname(hostname: String) -> anyhow::Result<Self> {
pub fn discovery_from_hostname(hostname: String) -> Result<Self> {
let host = HostPathDiscoveryEndpoint::lookup(hostname)?;
Ok(Endpoint::Discovery(host))
}
@@ -212,7 +210,7 @@ impl Endpoint {
Some(Self::discovery_from_addresses(addrs))
}
pub fn send(&self, srv: &AppServer, buf: &[u8]) -> anyhow::Result<()> {
pub fn send(&self, srv: &AppServer, buf: &[u8]) -> Result<()> {
use Endpoint::*;
match self {
SocketBoundAddress { socket, addr } => socket.send_to(srv, buf, *addr),
@@ -271,7 +269,7 @@ impl HostPathDiscoveryEndpoint {
}
/// Lookup a hostname
pub fn lookup(hostname: String) -> anyhow::Result<Self> {
pub fn lookup(hostname: String) -> Result<Self> {
Ok(Self {
addresses: ToSocketAddrs::to_socket_addrs(&hostname)?.collect(),
scouting_state: Cell::new((0, 0)),
@@ -292,16 +290,16 @@ impl HostPathDiscoveryEndpoint {
/// Attempt to reach the host
///
/// Will round-robin-try different socket-ip-combinations on each call.
pub fn send_scouting(&self, srv: &AppServer, buf: &[u8]) -> anyhow::Result<()> {
pub fn send_scouting(&self, srv: &AppServer, buf: &[u8]) -> Result<()> {
let (addr_off, sock_off) = self.scouting_state.get();
let mut addrs = (self.addresses)
let mut addrs = (&self.addresses)
.iter()
.enumerate()
.cycle()
.skip(addr_off)
.take(self.addresses.len());
let mut sockets = (srv.sockets)
let mut sockets = (&srv.sockets)
.iter()
.enumerate()
.cycle()
@@ -331,23 +329,19 @@ impl HostPathDiscoveryEndpoint {
}
}
bail!("Unable to send message: All sockets returned errors.")
error!("Unable to send message: All sockets returned errors.");
return Err(RosenpassError::RuntimeError);
}
}
impl AppServer {
pub fn new(
sk: SSk,
pk: SPk,
addrs: Vec<SocketAddr>,
verbosity: Verbosity,
) -> anyhow::Result<Self> {
pub fn new(sk: SSk, pk: SPk, addrs: Vec<SocketAddr>, verbosity: Verbosity) -> Result<Self> {
// setup mio
let mio_poll = mio::Poll::new()?;
let events = mio::Events::with_capacity(8);
// bind each SocketAddr to a socket
let maybe_sockets: Result<Vec<_>, _> =
let maybe_sockets: std::result::Result<Vec<_>, std::io::Error> =
addrs.into_iter().map(mio::net::UdpSocket::bind).collect();
let mut sockets = maybe_sockets?;
@@ -414,7 +408,8 @@ impl AppServer {
}
if sockets.is_empty() {
bail!("No sockets to listen on!")
error!("No sockets to listen on!");
return Err(RosenpassError::RuntimeError);
}
// register all sockets to mio
@@ -448,7 +443,7 @@ impl AppServer {
outfile: Option<PathBuf>,
outwg: Option<WireguardOut>,
hostname: Option<String>,
) -> anyhow::Result<AppPeerPtr> {
) -> Result<AppPeerPtr> {
let PeerPtr(pn) = self.crypt.add_peer(psk, pk)?;
assert!(pn == self.peers.len());
let initial_endpoint = hostname
@@ -464,7 +459,7 @@ impl AppServer {
Ok(AppPeerPtr(pn))
}
pub fn listen_loop(&mut self) -> anyhow::Result<()> {
pub fn listen_loop(&mut self) -> Result<()> {
const INIT_SLEEP: f64 = 0.01;
const MAX_FAILURES: i32 = 10;
let mut failure_cnt = 0;
@@ -485,10 +480,11 @@ impl AppServer {
let sleep = INIT_SLEEP * 2.0f64.powf(f64::from(failure_cnt - 1));
let tries_left = MAX_FAILURES - (failure_cnt - 1);
error!(
"unexpected error after processing {} messages: {:?} {}",
"unexpected error after processing {} messages: {:?}",
msgs_processed,
err,
err.backtrace()
// TODO do we need backtraces?
// err.backtrace()
);
if tries_left > 0 {
error!("re-initializing networking in {sleep}! {tries_left} tries left.");
@@ -496,11 +492,12 @@ impl AppServer {
continue;
}
bail!("too many network failures");
error!("too many network failures");
return Err(RosenpassError::RuntimeError);
}
}
pub fn event_loop(&mut self) -> anyhow::Result<()> {
pub fn event_loop(&mut self) -> Result<()> {
let (mut rx, mut tx) = (MsgBuf::zero(), MsgBuf::zero());
/// if socket address for peer is known, call closure
@@ -525,11 +522,9 @@ impl AppServer {
use AppPollResult::*;
use KeyOutputReason::*;
match self.poll(&mut *rx)? {
#[allow(clippy::redundant_closure_call)]
SendInitiation(peer) => tx_maybe_with!(peer, || self
.crypt
.initiate_handshake(peer.lower(), &mut *tx))?,
#[allow(clippy::redundant_closure_call)]
SendRetransmission(peer) => tx_maybe_with!(peer, || self
.crypt
.retransmit_handshake(peer.lower(), &mut *tx))?,
@@ -551,11 +546,9 @@ impl AppServer {
match self.crypt.handle_msg(&rx[..len], &mut *tx) {
Err(ref e) => {
self.verbose().then(|| {
info!(
"error processing incoming message from {:?}: {:?} {}",
endpoint,
e,
e.backtrace()
error!(
"error processing incoming message from {:?}: {:?}",
endpoint, e
);
});
}
@@ -583,12 +576,7 @@ impl AppServer {
}
}
pub fn output_key(
&self,
peer: AppPeerPtr,
why: KeyOutputReason,
key: &SymKey,
) -> anyhow::Result<()> {
pub fn output_key(&self, peer: AppPeerPtr, why: KeyOutputReason, key: &SymKey) -> Result<()> {
let peerid = peer.lower().get(&self.crypt).pidt()?;
let ap = peer.get_app(self);
@@ -623,7 +611,7 @@ impl AppServer {
}
if let Some(owg) = ap.outwg.as_ref() {
let mut child = Command::new("wg")
let child = Command::new("wg")
.arg("set")
.arg(&owg.dev)
.arg("peer")
@@ -633,27 +621,13 @@ impl AppServer {
.stdin(Stdio::piped())
.args(&owg.extra_params)
.spawn()?;
b64_writer(child.stdin.take().unwrap()).write_all(key.secret())?;
thread::spawn(move || {
let status = child.wait();
if let Ok(status) = status {
if status.success() {
debug!("successfully passed psk to wg")
} else {
error!("could not pass psk to wg {:?}", status)
}
} else {
error!("wait failed: {:?}", status)
}
});
b64_writer(child.stdin.unwrap()).write_all(key.secret())?;
}
Ok(())
}
pub fn poll(&mut self, rx_buf: &mut [u8]) -> anyhow::Result<AppPollResult> {
pub fn poll(&mut self, rx_buf: &mut [u8]) -> Result<AppPollResult> {
use crate::protocol::PollResult as C;
use AppPollResult as A;
loop {
@@ -678,7 +652,7 @@ impl AppServer {
&mut self,
buf: &mut [u8],
timeout: Timing,
) -> anyhow::Result<Option<(usize, Endpoint)>> {
) -> Result<Option<(usize, Endpoint)>> {
let timeout = Duration::from_secs_f64(timeout);
// if there is no time to wait on IO, well, then, lets not waste any time!

View File

@@ -1,7 +1,3 @@
use anyhow::{bail, ensure};
use clap::Parser;
use std::path::{Path, PathBuf};
use crate::app_server;
use crate::app_server::AppServer;
use crate::util::{LoadValue, LoadValueB64};
@@ -10,7 +6,12 @@ use crate::{
coloring::Secret,
pqkem::{StaticKEM, KEM},
protocol::{SPk, SSk, SymKey},
Result,
RosenpassError,
};
use clap::Parser;
use log::error;
use std::path::{Path, PathBuf};
use super::config;
@@ -98,25 +99,21 @@ pub enum Cli {
}
impl Cli {
pub fn run() -> anyhow::Result<()> {
pub fn run() -> Result<()> {
let cli = Self::parse();
use Cli::*;
match cli {
Man => {
let man_cmd = std::process::Command::new("man")
let _man_cmd = std::process::Command::new("man")
.args(["1", "rosenpass"])
.status();
if !(man_cmd.is_ok() && man_cmd.unwrap().success()) {
println!(include_str!(env!("ROSENPASS_MAN")));
}
}
GenConfig { config_file, force } => {
ensure!(
force || !config_file.exists(),
"config file {config_file:?} already exists"
);
if !force && config_file.exists() {
error!("config file {config_file:?} already exists");
return Err(RosenpassError::RuntimeError);
}
config::Rosenpass::example_config().store(config_file)?;
}
@@ -130,51 +127,52 @@ impl Cli {
// figure out where the key file is specified, in the config file or directly as flag?
let (pkf, skf) = match (config_file, public_key, secret_key) {
(Some(config_file), _, _) => {
ensure!(
config_file.exists(),
"config file {config_file:?} does not exist"
);
if !config_file.exists() {
error!("config file {config_file:?} does not exist");
return Err(RosenpassError::RuntimeError);
}
let config = config::Rosenpass::load(config_file)?;
(config.public_key, config.secret_key)
}
(_, Some(pkf), Some(skf)) => (pkf, skf),
_ => {
bail!("either a config-file or both public-key and secret-key file are required")
}
_ => return Err(RosenpassError::ConfigError(
"either a config-file or both public-key and secret-key file are required"
.into(),
)),
};
// check that we are not overriding something unintentionally
let mut problems = vec![];
let mut problems = false;
if !force && pkf.is_file() {
problems.push(format!(
"public-key file {pkf:?} exist, refusing to overwrite it"
));
problems = true;
error!("public-key file {pkf:?} exist, refusing to overwrite it");
}
if !force && skf.is_file() {
problems.push(format!(
"secret-key file {skf:?} exist, refusing to overwrite it"
));
problems = true;
error!("secret-key file {skf:?} exist, refusing to overwrite it");
}
if !problems.is_empty() {
bail!(problems.join("\n"));
if problems {
return Err(RosenpassError::RuntimeError);
}
// generate the keys and store them in files
let mut ssk = crate::protocol::SSk::random();
let mut spk = crate::protocol::SPk::random();
StaticKEM::keygen(ssk.secret_mut(), spk.secret_mut())?;
ssk.store_secret(skf)?;
spk.store_secret(pkf)?;
unsafe {
StaticKEM::keygen(ssk.secret_mut(), spk.secret_mut())?;
ssk.store_secret(skf)?;
spk.store_secret(pkf)?;
}
}
ExchangeConfig { config_file } => {
ensure!(
config_file.exists(),
"config file '{config_file:?}' does not exist"
);
if !config_file.exists() {
error!("config file '{config_file:?}' does not exist");
return Err(RosenpassError::RuntimeError);
}
let config = config::Rosenpass::load(config_file)?;
config.validate()?;
@@ -217,7 +215,7 @@ impl Cli {
Ok(())
}
fn event_loop(config: config::Rosenpass) -> anyhow::Result<()> {
fn event_loop(config: config::Rosenpass) -> Result<()> {
// load own keys
let sk = SSk::load(&config.secret_key)?;
let pk = SPk::load(&config.public_key)?;
@@ -250,11 +248,11 @@ impl Cli {
}
trait StoreSecret {
fn store_secret<P: AsRef<Path>>(&self, path: P) -> anyhow::Result<()>;
unsafe fn store_secret<P: AsRef<Path>>(&self, path: P) -> Result<()>;
}
impl<const N: usize> StoreSecret for Secret<N> {
fn store_secret<P: AsRef<Path>>(&self, path: P) -> anyhow::Result<()> {
unsafe fn store_secret<P: AsRef<Path>>(&self, path: P) -> Result<()> {
std::fs::write(path, self.secret())?;
Ok(())
}

View File

@@ -7,7 +7,7 @@
//! - the memory is mlocked, e.g. it is never swapped
use crate::{
classical_crypto::{rng, zeroize},
sodium::{rng, zeroize},
util::{cpy, mutating},
};
use lazy_static::lazy_static;

View File

@@ -6,10 +6,10 @@ use std::{
path::{Path, PathBuf},
};
use anyhow::{bail, ensure};
use log::{error, warn};
use serde::{Deserialize, Serialize};
use crate::util::fopen_w;
use crate::{util::fopen_w, Result, RosenpassError};
#[derive(Debug, Serialize, Deserialize)]
pub struct Rosenpass {
@@ -55,8 +55,6 @@ pub struct RosenpassPeer {
pub struct WireGuard {
pub device: String,
pub peer: String,
#[serde(default)]
pub extra_params: Vec<String>,
}
@@ -64,7 +62,7 @@ impl Rosenpass {
/// Load a config file from a file path
///
/// no validation is conducted
pub fn load<P: AsRef<Path>>(p: P) -> anyhow::Result<Self> {
pub fn load<P: AsRef<Path>>(p: P) -> Result<Self> {
let mut config: Self = toml::from_str(&fs::read_to_string(&p)?)?;
config.config_file_path = p.as_ref().to_owned();
@@ -72,7 +70,7 @@ impl Rosenpass {
}
/// Write a config to a file
pub fn store<P: AsRef<Path>>(&self, p: P) -> anyhow::Result<()> {
pub fn store<P: AsRef<Path>>(&self, p: P) -> Result<()> {
let serialized_config =
toml::to_string_pretty(&self).expect("unable to serialize the default config");
fs::write(p, serialized_config)?;
@@ -80,7 +78,7 @@ impl Rosenpass {
}
/// Commit the configuration to where it came from, overwriting the original file
pub fn commit(&self) -> anyhow::Result<()> {
pub fn commit(&self) -> Result<()> {
let mut f = fopen_w(&self.config_file_path)?;
f.write_all(toml::to_string_pretty(&self)?.as_bytes())?;
@@ -88,36 +86,40 @@ impl Rosenpass {
}
/// Validate a configuration
pub fn validate(&self) -> anyhow::Result<()> {
pub fn validate(&self) -> Result<()> {
// check the public-key file exists
ensure!(
self.public_key.is_file(),
"public-key file {:?} does not exist",
self.public_key
);
if !(self.public_key.is_file()) {
return Err(RosenpassError::ConfigError(format!(
"public-key file {:?} does not exist",
self.public_key
)));
}
// check the secret-key file exists
ensure!(
self.secret_key.is_file(),
"secret-key file {:?} does not exist",
self.secret_key
);
if !(self.secret_key.is_file()) {
return Err(RosenpassError::ConfigError(format!(
"secret-key file {:?} does not exist",
self.secret_key
)));
}
for (i, peer) in self.peers.iter().enumerate() {
// check peer's public-key file exists
ensure!(
peer.public_key.is_file(),
"peer {i} public-key file {:?} does not exist",
peer.public_key
);
if !(peer.public_key.is_file()) {
return Err(RosenpassError::ConfigError(format!(
"peer {i} public-key file {:?} does not exist",
peer.public_key
)));
}
// check endpoint is usable
if let Some(addr) = peer.endpoint.as_ref() {
ensure!(
addr.to_socket_addrs().is_ok(),
"peer {i} endpoint {} can not be parsed to a socket address",
addr
);
if !(addr.to_socket_addrs().is_ok()) {
return Err(RosenpassError::ConfigError(format!(
"peer {i} endpoint {} can not be parsed to a socket address",
addr
)));
}
}
// TODO warn if neither out_key nor exchange_command is defined
@@ -153,7 +155,7 @@ impl Rosenpass {
/// from chaotic args
/// Quest: the grammar is undecideable, what do we do here?
pub fn parse_args(args: Vec<String>) -> anyhow::Result<Self> {
pub fn parse_args(args: Vec<String>) -> Result<Self> {
let mut config = Self::new("", "");
#[derive(Debug, Hash, PartialEq, Eq)]
@@ -176,6 +178,7 @@ impl Rosenpass {
// TODO idea: use config.peers.len() to give index of peer with conflicting argument
use State::*;
let mut problem = false;
let mut state = Own;
let mut current_peer = None;
let p_exists = "a peer should exist by now";
@@ -185,9 +188,7 @@ impl Rosenpass {
(Own, "public-key", None) => OwnPublicKey,
(Own, "secret-key", None) => OwnSecretKey,
(Own, "private-key", None) => {
log::warn!(
"the private-key argument is deprecated, please use secret-key instead"
);
warn!("the private-key argument is deprecated, please use secret-key instead");
OwnSecretKey
}
(Own, "listen", None) => OwnListen,
@@ -196,14 +197,16 @@ impl Rosenpass {
Own
}
(Own, "peer", None) => {
ensure!(
already_set.contains(&OwnPublicKey),
"public-key file must be set"
);
ensure!(
already_set.contains(&OwnSecretKey),
"secret-key file must be set"
);
if !(already_set.contains(&OwnPublicKey)) {
return Err(RosenpassError::ConfigError(
"public-key file must be set".into(),
));
}
if !(already_set.contains(&OwnSecretKey)) {
return Err(RosenpassError::ConfigError(
"secret-key file must be set".into(),
));
}
already_set.clear();
current_peer = Some(RosenpassPeer::default());
@@ -211,18 +214,20 @@ impl Rosenpass {
Peer
}
(OwnPublicKey, pk, None) => {
ensure!(
already_set.insert(OwnPublicKey),
"public-key was already set"
);
if !(already_set.insert(OwnPublicKey)) {
return Err(RosenpassError::ConfigError(
"public-key was already set".into(),
));
}
config.public_key = pk.into();
Own
}
(OwnSecretKey, sk, None) => {
ensure!(
already_set.insert(OwnSecretKey),
"secret-key was already set"
);
if !(already_set.insert(OwnSecretKey)) {
return Err(RosenpassError::ConfigError(
"secret-key was already set".into(),
));
}
config.secret_key = sk.into();
Own
}
@@ -250,36 +255,45 @@ impl Rosenpass {
(Peer, "outfile", Some(_)) => PeerOutfile,
(Peer, "wireguard", Some(_)) => PeerWireguardDev,
(PeerPublicKey, pk, Some(peer)) => {
ensure!(
already_set.insert(PeerPublicKey),
"public-key was already set"
);
if !(already_set.insert(PeerPublicKey)) {
return Err(RosenpassError::ConfigError(
"public-key was already set".into(),
));
}
peer.public_key = pk.into();
Peer
}
(PeerEndpoint, e, Some(peer)) => {
ensure!(already_set.insert(PeerEndpoint), "endpoint was already set");
if !already_set.insert(PeerEndpoint) {
error!("endpoint was already set");
problem = true;
}
peer.endpoint = Some(e.to_owned());
Peer
}
(PeerPsk, psk, Some(peer)) => {
ensure!(already_set.insert(PeerEndpoint), "peer psk was already set");
if !already_set.insert(PeerEndpoint) {
error!("peer psk was already set");
problem = true;
}
peer.pre_shared_key = Some(psk.into());
Peer
}
(PeerOutfile, of, Some(peer)) => {
ensure!(
already_set.insert(PeerOutfile),
"peer outfile was already set"
);
if !(already_set.insert(PeerOutfile)) {
return Err(RosenpassError::ConfigError(
"peer outfile was already set".into(),
));
}
peer.key_out = Some(of.into());
Peer
}
(PeerWireguardDev, dev, Some(peer)) => {
ensure!(
already_set.insert(PeerWireguardDev),
"peer wireguard-dev was already set"
);
if !(already_set.insert(PeerWireguardDev)) {
return Err(RosenpassError::ConfigError(
"peer wireguard-dev was already set".into(),
));
}
assert!(peer.wg.is_none());
peer.wg = Some(WireGuard {
device: dev.to_string(),
@@ -289,10 +303,11 @@ impl Rosenpass {
PeerWireguardPeer
}
(PeerWireguardPeer, p, Some(peer)) => {
ensure!(
already_set.insert(PeerWireguardPeer),
"peer wireguard-peer was already set"
);
if !(already_set.insert(PeerWireguardPeer)) {
return Err(RosenpassError::ConfigError(
"peer wireguard-peer was already set".into(),
));
}
peer.wg.as_mut().expect(wg_exists).peer = p.to_string();
PeerWireguardExtraArgs
}
@@ -307,14 +322,16 @@ impl Rosenpass {
// error cases
(Own, x, None) => {
bail!("unrecognised argument {x}");
error!("unrecognised argument {x}");
return Err(RosenpassError::RuntimeError);
}
(Own | OwnPublicKey | OwnSecretKey | OwnListen, _, Some(_)) => {
panic!("current_peer is not None while in Own* state, this must never happen")
}
(State::Peer, arg, Some(_)) => {
bail!("unrecongnised argument {arg}");
error!("unrecongnised argument {arg}");
return Err(RosenpassError::RuntimeError);
}
(
Peer
@@ -333,6 +350,10 @@ impl Rosenpass {
};
}
if problem {
return Err(RosenpassError::RuntimeError);
}
if let Some(p) = current_peer {
// TODO ensure peer is propagated with sufficient information
config.peers.push(p);

View File

@@ -2,14 +2,12 @@
//! ensures their uniqueness
use {
crate::Result,
crate::{prftree::PrfTree, sodium::KEY_SIZE},
anyhow::Result,
};
const PROTOCOL : &str = "rosenpass 1 rosenpass.eu aead=chachapoly1305 hash=blake2s ekem=kyber512 skem=mceliece460896 xaead=xchachapoly1305";
pub fn protocol() -> Result<PrfTree> {
PrfTree::zero().mix(PROTOCOL.as_bytes())
PrfTree::zero().mix("Rosenpass v1 mceliece460896 Kyber512 ChaChaPoly1305 BLAKE2s".as_bytes())
}
// TODO Use labels that can serve as identifiers
@@ -42,8 +40,8 @@ macro_rules! prflabel_leaf {
prflabel_leaf!(_ckextract, mix, "mix");
prflabel_leaf!(_ckextract, hs_enc, "handshake encryption");
prflabel_leaf!(_ckextract, ini_enc, "initiator session encryption");
prflabel_leaf!(_ckextract, res_enc, "responder session encryption");
prflabel_leaf!(_ckextract, ini_enc, "initiator handshake encryption");
prflabel_leaf!(_ckextract, res_enc, "responder handshake encryption");
prflabel!(_ckextract, _user, "user");
prflabel!(_user, _rp, "rosenpass.eu");

131
src/lib.rs Normal file
View File

@@ -0,0 +1,131 @@
use protocol::{HandshakeStateMachine, PeerId, PeerPtr, SessionId};
#[macro_use]
pub mod util;
#[macro_use]
pub mod sodium;
pub mod coloring;
#[rustfmt::skip]
pub mod labeled_prf;
pub mod app_server;
pub mod cli;
pub mod config;
pub mod msgs;
pub mod pqkem;
pub mod prftree;
pub mod protocol;
#[derive(thiserror::Error, Debug)]
pub enum RosenpassError {
#[error("error in OQS")]
Oqs,
#[error("error from external library while calling OQS")]
OqsExternalLib,
#[error("error while calling into libsodium")]
LibsodiumError(&'static str),
#[error("buffer size mismatch, required {required_size} but only found {actual_size}")]
BufferSizeMismatch {
required_size: usize,
actual_size: usize,
},
#[error("invalid message type")]
InvalidMessageType(u8),
#[error("peer id {0:?} already taken")]
PeerIdAlreadyTaken(PeerId),
#[error("session id {0:?} already taken")]
SessionIdAlreadyTaken(SessionId),
#[error("{0}")]
NotImplemented(&'static str),
#[error("{0}")]
ConfigError(String),
#[error("see last log messages")]
RuntimeError,
#[error("{0}")]
IoError(#[from] std::io::Error),
#[error("{0}")]
TomlDeserError(#[from] toml::de::Error),
#[error("{0}")]
TomlSerError(#[from] toml::ser::Error),
#[error("invalid session id {0:?} was used")]
InvalidSessionId(SessionId),
#[error("no session available")]
NoSession,
#[error("the peer {0:?} does not exist")]
NoSuchPeer(PeerPtr),
#[error("the peer id {0:?} does not exist")]
NoSuchPeerId(PeerId),
#[error("the session {0:?} does not exist")]
NoSuchSessionId(SessionId),
#[error("no current handshake with peer {0:?}")]
NoCurrentHs(PeerPtr),
// TODO implement Display for Peer/Session ptr?
#[error("message seal broken")]
SealBroken,
#[error("received empty message")]
EmptyMessage,
#[error("biscuit with invalid number")]
InvalidBiscuitNo,
#[error("got unexpected message")]
UnexpectedMessage {
session: SessionId,
expected: Option<HandshakeStateMachine>,
got: Option<HandshakeStateMachine>,
},
#[error("???")]
StaleNonce,
}
/// Rosenpass Result type
pub type Result<T> = core::result::Result<T, RosenpassError>;
impl RosenpassError {
/// Helper function to check a buffer size
fn check_buffer_size(required_size: usize, actual_size: usize) -> Result<()> {
if required_size != actual_size {
Err(Self::BufferSizeMismatch {
required_size,
actual_size,
})
} else {
Ok(())
}
}
}
/// Extension trait to attach function calls to foreign types.
trait RosenpassMaybeError {
/// Checks whether something is an error or not
fn to_rg_error(&self) -> Result<()>;
}
impl RosenpassMaybeError for oqs_sys::common::OQS_STATUS {
fn to_rg_error(&self) -> Result<()> {
use oqs_sys::common::OQS_STATUS;
match self {
OQS_STATUS::OQS_SUCCESS => Ok(()),
OQS_STATUS::OQS_ERROR => Err(RosenpassError::Oqs),
OQS_STATUS::OQS_EXTERNAL_LIB_ERROR_OPENSSL => Err(RosenpassError::OqsExternalLib),
}
}
}

View File

@@ -6,7 +6,7 @@
//! This is a generalization of a PRF operating
//! on a sequence of inputs instead of a single input.
//!
//! Like a Dec function the Iprf features efficient
//! Like a Dec function the Iprf features efficient
//! incrementability.
//!
//! You can also think of an Iprf as a Dec function with
@@ -27,7 +27,7 @@ pub fn prf_into(out: &mut [u8], key: &[u8], data: &[u8]) {
hmac_into(out, key, data).unwrap()
}
pub fn prf(key: &[u8], data: &[u8]) -> [u8; KEY_SIZE] {
pub fn prf(key: &[u8], data: &[u8]) -> [u8; KEY_SIZE]{
mutating([0u8; KEY_SIZE], |r| prf_into(r, key, data))
}
@@ -40,11 +40,11 @@ impl Iprf {
IprfBranch(self.0)
}
// TODO: Protocol! Use domain separation to ensure that
// TODO: Protocol! Use domain separation to ensure that
fn mix(self, v: &[u8]) -> Self {
Self(prf(&self.0, v))
}
fn mix_secret<const N: usize>(self, v: Secret<N>) -> SecretIprf {
SecretIprf::prf_invoc(&self.0, v.secret())
}
@@ -70,9 +70,8 @@ impl IprfBranch {
impl SecretIprf {
fn prf_invoc(k: &[u8], d: &[u8]) -> SecretIprf {
mutating(SecretIprf(Secret::zero()), |r| {
prf_into(k, d, r.secret_mut())
})
mutating(SecretIprf(Secret::zero()), |r|
prf_into(k, d, r.secret_mut()))
}
fn from_key(k: Secret<N>) -> SecretIprf {

View File

@@ -143,7 +143,7 @@ macro_rules! data_lense(
pub fn check_size(len: usize) -> Result<(), RosenpassError>{
let required_size = $( $len + )+ 0;
let actual_size = len;
if required_size != actual_size {
if required_size < actual_size {
Err(RosenpassError::BufferSizeMismatch {
required_size,
actual_size,
@@ -199,53 +199,23 @@ macro_rules! data_lense(
type __ContainerType;
/// Create a lense to the byte slice
fn [< $type:snake >] $(< $($generic : LenseView),* >)? (self) -> Result< $type<Self::__ContainerType, $( $($generic),+ )? >, RosenpassError>;
/// Create a lense to the byte slice, automatically truncating oversized buffers
fn [< $type:snake _ truncating >] $(< $($generic : LenseView),* >)? (self) -> Result< $type<Self::__ContainerType, $( $($generic),+ )? >, RosenpassError>;
fn [< $type:snake >] $(< $($generic),* >)? (self) -> Result< $type<Self::__ContainerType, $( $($generic),+ )? >, RosenpassError>;
}
impl<'a> [< $type Ext >] for &'a [u8] {
type __ContainerType = &'a [u8];
fn [< $type:snake >] $(< $($generic : LenseView),* >)? (self) -> Result< $type<Self::__ContainerType, $( $($generic),+ )? >, RosenpassError> {
$type::<Self::__ContainerType, $( $($generic),+ )? >::check_size(self.len())?;
fn [< $type:snake >] $(< $($generic),* >)? (self) -> Result< $type<Self::__ContainerType, $( $($generic),+ )? >, RosenpassError> {
Ok($type ( self, $( $( ::core::marker::PhantomData::<$generic> ),+ )? ))
}
fn [< $type:snake _ truncating >] $(< $($generic : LenseView),* >)? (self) -> Result< $type<Self::__ContainerType, $( $($generic),+ )? >, RosenpassError> {
let required_size = $( $len + )+ 0;
let actual_size = self.len();
if actual_size < required_size {
return Err(RosenpassError::BufferSizeMismatch {
required_size,
actual_size,
});
}
[< $type Ext >]::[< $type:snake >](&self[..required_size])
}
}
impl<'a> [< $type Ext >] for &'a mut [u8] {
type __ContainerType = &'a mut [u8];
fn [< $type:snake >] $(< $($generic : LenseView),* >)? (self) -> Result< $type<Self::__ContainerType, $( $($generic),+ )? >, RosenpassError> {
$type::<Self::__ContainerType, $( $($generic),+ )? >::check_size(self.len())?;
fn [< $type:snake >] $(< $($generic),* >)? (self) -> Result< $type<Self::__ContainerType, $( $($generic),+ )? >, RosenpassError> {
Ok($type ( self, $( $( ::core::marker::PhantomData::<$generic> ),+ )? ))
}
fn [< $type:snake _ truncating >] $(< $($generic : LenseView),* >)? (self) -> Result< $type<Self::__ContainerType, $( $($generic),+ )? >, RosenpassError> {
let required_size = $( $len + )+ 0;
let actual_size = self.len();
if actual_size < required_size {
return Err(RosenpassError::BufferSizeMismatch {
required_size,
actual_size,
});
}
[< $type Ext >]::[< $type:snake >](&mut self[..required_size])
}
}
});
);
@@ -291,10 +261,10 @@ data_lense! { RespHello :=
ecti: EphemeralKEM::CT_LEN,
/// Classic McEliece Ciphertext
scti: StaticKEM::CT_LEN,
/// Responders handshake state in encrypted form
biscuit: BISCUIT_CT_LEN,
/// Empty encrypted message (just an auth tag)
auth: sodium::AEAD_TAG_LEN
auth: sodium::AEAD_TAG_LEN,
/// Responders handshake state in encrypted form
biscuit: BISCUIT_CT_LEN
}
data_lense! { InitConf :=

168
src/pqkem.rs Normal file
View File

@@ -0,0 +1,168 @@
//! Traits and implementations for Key Encapsulation Mechanisms (KEMs)
//!
//! KEMs are the interface provided by almost all post-quantum
//! secure key exchange mechanisms.
//!
//! Conceptually KEMs are akin to public-key encryption, but instead of encrypting
//! arbitrary data, KEMs are limited to the transmission of keys, randomly chosen during
//!
//! encapsulation.
//! The [KEM] Trait describes the basic API offered by a Key Encapsulation
//! Mechanism. Two implementations for it are provided, [StaticKEM] and [EphemeralKEM].
use crate::{RosenpassError, RosenpassMaybeError};
/// Key Encapsulation Mechanism
///
/// The KEM interface defines three operations: Key generation, key encapsulation and key
/// decapsulation.
pub trait KEM {
/// Secrete Key length
const SK_LEN: usize;
/// Public Key length
const PK_LEN: usize;
/// Ciphertext length
const CT_LEN: usize;
/// Shared Secret length
const SHK_LEN: usize;
/// Generate a keypair consisting of secret key (`sk`) and public key (`pk`)
///
/// `keygen() -> sk, pk`
fn keygen(sk: &mut [u8], pk: &mut [u8]) -> Result<(), RosenpassError>;
/// From a public key (`pk`), generate a shared key (`shk`, for local use)
/// and a cipher text (`ct`, to be sent to the owner of the `pk`).
///
/// `encaps(pk) -> shk, ct`
fn encaps(shk: &mut [u8], ct: &mut [u8], pk: &[u8]) -> Result<(), RosenpassError>;
/// From a secret key (`sk`) and a cipher text (`ct`) derive a shared key
/// (`shk`)
///
/// `decaps(sk, ct) -> shk`
fn decaps(shk: &mut [u8], sk: &[u8], ct: &[u8]) -> Result<(), RosenpassError>;
}
/// A KEM that is secure against Chosen Ciphertext Attacks (CCA).
/// In the context of rosenpass this is used for static keys.
/// Uses [Classic McEliece](https://classic.mceliece.org/) 460896 from liboqs.
///
/// Classic McEliece is chosen because of its high security margin and its small
/// ciphertexts. The public keys are humongous, but (being static keys) the are never transmitted over
/// the wire so this is not a big problem.
pub struct StaticKEM;
/// # Safety
///
/// This Trait impl calls unsafe [oqs_sys] functions, that write to byte
/// slices only identified using raw pointers. It must be ensured that the raw
/// pointers point into byte slices of sufficient length, to avoid UB through
/// overwriting of arbitrary data. This is checked in the following code before
/// the unsafe calls, and an early return with an Err occurs if the byte slice
/// size does not match the required size.
///
/// __Note__: This requirement is stricter than necessary, it would suffice
/// to only check that the buffers are big enough, allowing them to be even
/// bigger. However, from a correctness point of view it does not make sense to
/// allow bigger buffers.
impl KEM for StaticKEM {
const SK_LEN: usize = oqs_sys::kem::OQS_KEM_classic_mceliece_460896_length_secret_key as usize;
const PK_LEN: usize = oqs_sys::kem::OQS_KEM_classic_mceliece_460896_length_public_key as usize;
const CT_LEN: usize = oqs_sys::kem::OQS_KEM_classic_mceliece_460896_length_ciphertext as usize;
const SHK_LEN: usize =
oqs_sys::kem::OQS_KEM_classic_mceliece_460896_length_shared_secret as usize;
fn keygen(sk: &mut [u8], pk: &mut [u8]) -> Result<(), RosenpassError> {
RosenpassError::check_buffer_size(sk.len(), Self::SK_LEN)?;
RosenpassError::check_buffer_size(pk.len(), Self::PK_LEN)?;
unsafe {
oqs_sys::kem::OQS_KEM_classic_mceliece_460896_keypair(pk.as_mut_ptr(), sk.as_mut_ptr())
.to_rg_error()
}
}
fn encaps(shk: &mut [u8], ct: &mut [u8], pk: &[u8]) -> Result<(), RosenpassError> {
RosenpassError::check_buffer_size(shk.len(), Self::SHK_LEN)?;
RosenpassError::check_buffer_size(ct.len(), Self::CT_LEN)?;
RosenpassError::check_buffer_size(pk.len(), Self::PK_LEN)?;
unsafe {
oqs_sys::kem::OQS_KEM_classic_mceliece_460896_encaps(
ct.as_mut_ptr(),
shk.as_mut_ptr(),
pk.as_ptr(),
)
.to_rg_error()
}
}
fn decaps(shk: &mut [u8], sk: &[u8], ct: &[u8]) -> Result<(), RosenpassError> {
RosenpassError::check_buffer_size(shk.len(), Self::SHK_LEN)?;
RosenpassError::check_buffer_size(sk.len(), Self::SK_LEN)?;
RosenpassError::check_buffer_size(ct.len(), Self::CT_LEN)?;
unsafe {
oqs_sys::kem::OQS_KEM_classic_mceliece_460896_decaps(
shk.as_mut_ptr(),
ct.as_ptr(),
sk.as_ptr(),
)
.to_rg_error()
}
}
}
/// Implements a KEM that is secure against Chosen Plaintext Attacks (CPA).
/// In the context of rosenpass this is used for ephemeral keys.
/// Currently the implementation uses
/// [Kyber 512](https://openquantumsafe.org/liboqs/algorithms/kem/kyber) from liboqs.
///
/// This is being used for ephemeral keys; since these are use-once the first post quantum
/// wireguard paper claimed that CPA security would be sufficient. Nonetheless we choose kyber
/// which provides CCA security since there are no publicly vetted KEMs out there which provide
/// only CPA security.
pub struct EphemeralKEM;
/// # Safety
///
/// This Trait impl calls unsafe [oqs_sys] functions, that write to byte
/// slices only identified using raw pointers. It must be ensured that the raw
/// pointers point into byte slices of sufficient length, to avoid UB through
/// overwriting of arbitrary data. This is checked in the following code before
/// the unsafe calls, and an early return with an Err occurs if the byte slice
/// size does not match the required size.
///
/// __Note__: This requirement is stricter than necessary, it would suffice
/// to only check that the buffers are big enough, allowing them to be even
/// bigger. However, from a correctness point of view it does not make sense to
/// allow bigger buffers.
impl KEM for EphemeralKEM {
const SK_LEN: usize = oqs_sys::kem::OQS_KEM_kyber_512_length_secret_key as usize;
const PK_LEN: usize = oqs_sys::kem::OQS_KEM_kyber_512_length_public_key as usize;
const CT_LEN: usize = oqs_sys::kem::OQS_KEM_kyber_512_length_ciphertext as usize;
const SHK_LEN: usize = oqs_sys::kem::OQS_KEM_kyber_512_length_shared_secret as usize;
fn keygen(sk: &mut [u8], pk: &mut [u8]) -> Result<(), RosenpassError> {
RosenpassError::check_buffer_size(sk.len(), Self::SK_LEN)?;
RosenpassError::check_buffer_size(pk.len(), Self::PK_LEN)?;
unsafe {
oqs_sys::kem::OQS_KEM_kyber_512_keypair(pk.as_mut_ptr(), sk.as_mut_ptr()).to_rg_error()
}
}
fn encaps(shk: &mut [u8], ct: &mut [u8], pk: &[u8]) -> Result<(), RosenpassError> {
RosenpassError::check_buffer_size(shk.len(), Self::SHK_LEN)?;
RosenpassError::check_buffer_size(ct.len(), Self::CT_LEN)?;
RosenpassError::check_buffer_size(pk.len(), Self::PK_LEN)?;
unsafe {
oqs_sys::kem::OQS_KEM_kyber_512_encaps(ct.as_mut_ptr(), shk.as_mut_ptr(), pk.as_ptr())
.to_rg_error()
}
}
fn decaps(shk: &mut [u8], sk: &[u8], ct: &[u8]) -> Result<(), RosenpassError> {
RosenpassError::check_buffer_size(shk.len(), Self::SHK_LEN)?;
RosenpassError::check_buffer_size(sk.len(), Self::SK_LEN)?;
RosenpassError::check_buffer_size(ct.len(), Self::CT_LEN)?;
unsafe {
oqs_sys::kem::OQS_KEM_kyber_512_decaps(shk.as_mut_ptr(), ct.as_ptr(), sk.as_ptr())
.to_rg_error()
}
}
}

View File

@@ -1,10 +1,8 @@
//! Implementation of the tree-like structure used for the label derivation in [labeled_prf](crate::labeled_prf)
use {
crate::{
coloring::Secret,
sodium::{hmac, hmac_into, KEY_SIZE},
},
anyhow::Result,
use crate::{
coloring::Secret,
sodium::{hmac, hmac_into, KEY_SIZE},
Result,
};
// TODO Use a proper Dec interface

View File

@@ -23,10 +23,10 @@
//! pqkem::{StaticKEM, KEM},
//! protocol::{SSk, SPk, MsgBuf, PeerPtr, CryptoServer, SymKey},
//! };
//! # fn main() -> anyhow::Result<()> {
//! # fn main() -> Result<(), rosenpass::RosenpassError> {
//!
//! // always init libsodium before anything
//! rosenpass::sodium::sodium_init()?;
//! rosenpass::sodium::sodium_init().unwrap();
//!
//! // initialize secret and public key for peer a ...
//! let (mut peer_a_sk, mut peer_a_pk) = (SSk::zero(), SPk::zero());
@@ -42,31 +42,32 @@
//! let mut b = CryptoServer::new(peer_b_sk, peer_b_pk.clone());
//!
//! // introduce peers to each other
//! a.add_peer(Some(psk.clone()), peer_b_pk)?;
//! b.add_peer(Some(psk), peer_a_pk)?;
//! a.add_peer(Some(psk.clone()), peer_b_pk).unwrap();
//! b.add_peer(Some(psk), peer_a_pk).unwrap();
//!
//! // declare buffers for message exchange
//! let (mut a_buf, mut b_buf) = (MsgBuf::zero(), MsgBuf::zero());
//!
//! // let a initiate a handshake
//! let mut maybe_len = Some(a.initiate_handshake(PeerPtr(0), a_buf.as_mut_slice())?);
//! let length = a.initiate_handshake(PeerPtr(0), a_buf.as_mut_slice());
//!
//! // let a and b communicate
//! while let Some(len) = maybe_len {
//! maybe_len = b.handle_msg(&a_buf[..len], &mut b_buf[..])?.resp;
//! std::mem::swap(&mut a, &mut b);
//! std::mem::swap(&mut a_buf, &mut b_buf);
//! // let b respond to a and a respond to b, in two rounds
//! for _ in 0..2 {
//! b.handle_msg(&a_buf[..], &mut b_buf[..]);
//! a.handle_msg(&b_buf[..], &mut a_buf[..]);
//! }
//!
//! // all done! Extract the shared keys and ensure they are identical
//! let a_key = a.osk(PeerPtr(0))?;
//! let b_key = b.osk(PeerPtr(0))?;
//! assert_eq!(a_key.secret(), b_key.secret(),
//! let a_key = a.osk(PeerPtr(0));
//! let b_key = b.osk(PeerPtr(0));
//! assert_eq!(a_key.unwrap().secret(), b_key.unwrap().secret(),
//! "the key exchanged failed to establish a shared secret");
//! # Ok(())
//! # }
//! ```
use log::{trace, warn};
use crate::{
coloring::*,
labeled_prf as lprf,
@@ -75,8 +76,8 @@ use crate::{
prftree::{SecretPrfTree, SecretPrfTreeBranch},
sodium::*,
util::*,
Result, RosenpassError,
};
use anyhow::{bail, ensure, Context, Result};
use std::collections::hash_map::{
Entry::{Occupied, Vacant},
HashMap,
@@ -103,7 +104,7 @@ pub const BCE: Timing = -3600.0 * 24.0 * 356.0 * 10_000.0;
// regarding unexpectedly large numbers in system APIs as this is < i16::MAX
pub const UNENDING: Timing = 3600.0 * 8.0;
// Rekey every two minutes,
// From the wireguard paper; rekey every two minutes,
// discard the key if no rekey is achieved within three
pub const REKEY_AFTER_TIME_RESPONDER: Timing = 120.0;
pub const REKEY_AFTER_TIME_INITIATOR: Timing = 130.0;
@@ -486,10 +487,8 @@ impl CryptoServer {
let peerid = peer.pidt()?;
let peerno = self.peers.len();
match self.index.entry(IndexKey::Peer(peerid)) {
Occupied(_) => bail!(
"Cannot insert peer with id {:?}; peer with this id already registered.",
peerid
),
// TODO improve type handling, use PeerPtr
Occupied(_) => return Err(RosenpassError::PeerIdAlreadyTaken(peerid)),
Vacant(e) => e.insert(peerno),
};
self.peers.push(peer);
@@ -501,7 +500,7 @@ impl CryptoServer {
pub fn register_session(&mut self, id: SessionId, peer: PeerPtr) -> Result<()> {
match self.index.entry(IndexKey::Sid(id)) {
Occupied(p) if PeerPtr(*p.get()) == peer => {} // Already registered
Occupied(_) => bail!("Cannot insert session with id {:?}; id is in use.", id),
Occupied(_) => return Err(RosenpassError::SessionIdAlreadyTaken(id)),
Vacant(e) => {
e.insert(peer.0);
}
@@ -523,8 +522,11 @@ impl CryptoServer {
};
}
pub fn find_peer(&self, id: PeerId) -> Option<PeerPtr> {
self.index.get(&IndexKey::Peer(id)).map(|no| PeerPtr(*no))
pub fn find_peer(&self, id: PeerId) -> Result<PeerPtr> {
self.index
.get(&IndexKey::Peer(id))
.map(|no| PeerPtr(*no))
.ok_or_else(|| RosenpassError::NoSuchPeerId(id))
}
// lookup_session in whitepaper
@@ -737,7 +739,7 @@ impl CryptoServer {
// TODO remove unnecessary copying between global tx_buf and per-peer buf
// TODO move retransmission storage to io server
pub fn initiate_handshake(&mut self, peer: PeerPtr, tx_buf: &mut [u8]) -> Result<usize> {
let mut msg = tx_buf.envelope_truncating::<InitHello<()>>()?; // Envelope::<InitHello>::default(); // TODO
let mut msg = tx_buf.envelope::<InitHello<()>>()?; // Envelope::<InitHello>::default(); // TODO
self.handle_initiation(peer, msg.payload_mut().init_hello()?)?;
let len = self.seal_and_commit_msg(peer, MsgType::InitHello, msg)?;
peer.hs()
@@ -782,19 +784,23 @@ impl CryptoServer {
/// | t2 | `InitConf` | -> | |
/// | t3 | | <- | `EmptyData` |
pub fn handle_msg(&mut self, rx_buf: &[u8], tx_buf: &mut [u8]) -> Result<HandleMsgResult> {
let seal_broken = "Message seal broken!";
// length of the response. We assume no response, so None for now
let mut len = 0;
let mut exchanged = false;
ensure!(!rx_buf.is_empty(), "received empty message, ignoring it");
if rx_buf.is_empty() {
trace!("received empty message, ignoring it");
return Err(RosenpassError::EmptyMessage);
}
let peer = match rx_buf[0].try_into() {
Ok(MsgType::InitHello) => {
let msg_in = rx_buf.envelope::<InitHello<&[u8]>>()?;
ensure!(msg_in.check_seal(self)?, seal_broken);
if msg_in.check_seal(self)? {
return Err(RosenpassError::SealBroken);
}
let mut msg_out = tx_buf.envelope_truncating::<RespHello<&mut [u8]>>()?;
let mut msg_out = tx_buf.envelope::<RespHello<&mut [u8]>>()?;
let peer = self.handle_init_hello(
msg_in.payload().init_hello()?,
msg_out.payload_mut().resp_hello()?,
@@ -804,9 +810,11 @@ impl CryptoServer {
}
Ok(MsgType::RespHello) => {
let msg_in = rx_buf.envelope::<RespHello<&[u8]>>()?;
ensure!(msg_in.check_seal(self)?, seal_broken);
if msg_in.check_seal(self)? {
return Err(RosenpassError::SealBroken);
}
let mut msg_out = tx_buf.envelope_truncating::<InitConf<&mut [u8]>>()?;
let mut msg_out = tx_buf.envelope::<InitConf<&mut [u8]>>()?;
let peer = self.handle_resp_hello(
msg_in.payload().resp_hello()?,
msg_out.payload_mut().init_conf()?,
@@ -819,9 +827,11 @@ impl CryptoServer {
}
Ok(MsgType::InitConf) => {
let msg_in = rx_buf.envelope::<InitConf<&[u8]>>()?;
ensure!(msg_in.check_seal(self)?, seal_broken);
if msg_in.check_seal(self)? {
return Err(RosenpassError::SealBroken);
}
let mut msg_out = tx_buf.envelope_truncating::<EmptyData<&mut [u8]>>()?;
let mut msg_out = tx_buf.envelope::<EmptyData<&mut [u8]>>()?;
let peer = self.handle_init_conf(
msg_in.payload().init_conf()?,
msg_out.payload_mut().empty_data()?,
@@ -832,15 +842,23 @@ impl CryptoServer {
}
Ok(MsgType::EmptyData) => {
let msg_in = rx_buf.envelope::<EmptyData<&[u8]>>()?;
ensure!(msg_in.check_seal(self)?, seal_broken);
if msg_in.check_seal(self)? {
return Err(RosenpassError::SealBroken);
}
self.handle_resp_conf(msg_in.payload().empty_data()?)?
}
Ok(MsgType::DataMsg) => bail!("DataMsg handling not implemented!"),
Ok(MsgType::CookieReply) => bail!("CookieReply handling not implemented!"),
Err(_) => {
bail!("CookieReply handling not implemented!")
Ok(MsgType::DataMsg) => {
return Err(RosenpassError::NotImplemented(
"DataMsg handling not implemented!",
))
}
Ok(MsgType::CookieReply) => {
return Err(RosenpassError::NotImplemented(
"CookieReply handling not implemented!",
))
}
Err(e) => return Err(e),
};
Ok(HandleMsgResult {
@@ -1119,10 +1137,10 @@ impl CryptoServer {
impl IniHsPtr {
pub fn store_msg_for_retransmission(&self, srv: &mut CryptoServer, msg: &[u8]) -> Result<()> {
let ih = self
.get_mut(srv)
.as_mut()
.with_context(|| format!("No current handshake for peer {:?}", self.peer()))?;
let ih = self.get_mut(srv).as_mut().ok_or_else(|| {
warn!("No current handshake for peer {:?}", self.peer());
RosenpassError::NoCurrentHs(self.peer())
})?;
cpy_min(msg, &mut *ih.tx_buf);
ih.tx_count = 0;
ih.tx_len = msg.len();
@@ -1131,20 +1149,20 @@ impl IniHsPtr {
}
pub fn apply_retransmission(&self, srv: &mut CryptoServer, tx_buf: &mut [u8]) -> Result<usize> {
let ih = self
.get_mut(srv)
.as_mut()
.with_context(|| format!("No current handshake for peer {:?}", self.peer()))?;
let ih = self.get_mut(srv).as_mut().ok_or_else(|| {
warn!("No current handshake for peer {:?}", self.peer());
RosenpassError::NoCurrentHs(self.peer())
})?;
cpy_min(&ih.tx_buf[..ih.tx_len], tx_buf);
Ok(ih.tx_len)
}
pub fn register_retransmission(&self, srv: &mut CryptoServer) -> Result<()> {
let tb = srv.timebase.clone();
let ih = self
.get_mut(srv)
.as_mut()
.with_context(|| format!("No current handshake for peer {:?}", self.peer()))?;
let ih = self.get_mut(srv).as_mut().ok_or_else(|| {
warn!("No current handshake for peer {:?}", self.peer());
RosenpassError::NoCurrentHs(self.peer())
})?;
// Base delay, exponential increase, ±50% jitter
ih.tx_retry_at = tb.now()
+ RETRANSMIT_DELAY_BEGIN
@@ -1254,7 +1272,7 @@ impl HandshakeState {
) -> Result<&mut Self> {
let mut shk = Secret::<SHK_LEN>::zero();
T::encaps(shk.secret_mut(), ct, pk)?;
self.mix(pk)?.mix(ct)?.mix(shk.secret())
self.mix(pk)?.mix(shk.secret())?.mix(ct)
}
pub fn decaps_and_mix<T: KEM, const SHK_LEN: usize>(
@@ -1265,7 +1283,7 @@ impl HandshakeState {
) -> Result<&mut Self> {
let mut shk = Secret::<SHK_LEN>::zero();
T::decaps(shk.secret_mut(), sk, ct)?;
self.mix(pk)?.mix(ct)?.mix(shk.secret())
self.mix(pk)?.mix(shk.secret())?.mix(ct)
}
pub fn store_biscuit(
@@ -1348,18 +1366,16 @@ impl HandshakeState {
hs.mix(biscuit_ct)?;
// Look up the associated peer
let peer = srv
.find_peer(pid) // TODO: FindPeer should return a Result<()>
.with_context(|| format!("Could not decode biscuit for peer {pid:?}: No such peer."))?;
let peer = srv.find_peer(pid)?;
// Defense against replay attacks; implementations may accept
// the most recent biscuit no again (bn = peer.bn_{prev}) which
// indicates retransmission
// TODO: Handle retransmissions without involving the crypto code
ensure!(
sodium_bigint_cmp(biscuit.biscuit_no(), &*peer.get(srv).biscuit_used) >= 0,
"Rejecting biscuit: Outdated biscuit number"
);
if sodium_bigint_cmp(biscuit.biscuit_no(), &*peer.get(srv).biscuit_used) >= 0 {
warn!("Rejecting biscuit: Outdated biscuit number");
return Err(RosenpassError::InvalidBiscuitNo);
}
Ok((peer, no, hs))
}
@@ -1393,11 +1409,10 @@ impl CryptoServer {
///
/// Fail if no session is available with the peer
pub fn osk(&self, peer: PeerPtr) -> Result<SymKey> {
let session = peer
.session()
.get(self)
.as_ref()
.with_context(|| format!("No current session for peer {:?}", peer))?;
let session = peer.session().get(self).as_ref().ok_or_else(|| {
warn!("No current session for peer {peer:?}");
RosenpassError::NoSuchPeer(peer)
})?;
Ok(session.ck.mix(&lprf::osk()?)?.into_secret())
}
}
@@ -1477,8 +1492,7 @@ impl CryptoServer {
let peer = {
let mut peerid = PeerId::zero();
core.decrypt_and_mix(&mut *peerid, ih.pidic())?;
self.find_peer(peerid)
.with_context(|| format!("No such peer {peerid:?}."))?
self.find_peer(peerid)?
};
// IHR7
@@ -1520,13 +1534,12 @@ impl CryptoServer {
mut ic: InitConf<&mut [u8]>,
) -> Result<PeerPtr> {
// RHI2
let sid = SessionId::from_slice(rh.sidi());
let peer = self
.lookup_handshake(SessionId::from_slice(rh.sidi()))
.with_context(|| {
format!(
"Got RespHello packet for non-existent session {:?}",
rh.sidi()
)
.lookup_handshake(sid)
.ok_or_else(|| {
warn!("Got RespHello packet for non-existent session {sid:?}");
RosenpassError::NoSuchSessionId(sid)
})?
.peer();
@@ -1547,13 +1560,14 @@ impl CryptoServer {
let exp = hs!().next;
let got = HandshakeStateMachine::RespHello;
ensure!(
exp == got,
"Unexpected package in session {:?}. Expected {:?}, got {:?}.",
SessionId::from_slice(rh.sidi()),
exp,
got
);
if exp != got {
warn!("Unexpected package in session {sid:?}. Expected {exp:?}, got {got:?}.",);
return Err(RosenpassError::UnexpectedMessage {
session: sid,
expected: Some(exp),
got: Some(got),
});
}
let mut core = hs!().core.clone();
core.sidr.copy_from_slice(rh.sidr());
@@ -1604,10 +1618,6 @@ impl CryptoServer {
// ICI7
peer.session()
.insert(self, core.enter_live(self, HandshakeRole::Initiator)?)?;
// RHI8
hs_mut!().eski.zeroize();
hs_mut!().core.erase();
hs_mut!().next = HandshakeStateMachine::RespConf;
@@ -1674,11 +1684,10 @@ impl CryptoServer {
// instead of a generic PeerPtr::send(&Server, Option<&[u8]>) -> Either<EmptyData, Data>
// because data transmission is a stub currently. This software is supposed to be used
// as a key exchange service feeding a PSK into some classical (i.e. non post quantum)
let ses = peer
.session()
.get_mut(self)
.as_mut()
.context("Cannot send acknowledgement. No session.")?;
let ses = peer.session().get_mut(self).as_mut().ok_or_else(|| {
warn!("Cannot send acknowledgement. No session.");
RosenpassError::NoSession
})?;
rc.sid_mut().copy_from_slice(&ses.sidt.value);
rc.ctr_mut().copy_from_slice(&ses.txnm.to_le_bytes());
ses.txnm += 1; // Increment nonce before encryption, just in case an error is raised
@@ -1692,30 +1701,39 @@ impl CryptoServer {
pub fn handle_resp_conf(&mut self, rc: EmptyData<&[u8]>) -> Result<PeerPtr> {
let sid = SessionId::from_slice(rc.sid());
let hs = self
.lookup_handshake(sid)
.with_context(|| format!("Got RespConf packet for non-existent session {sid:?}"))?;
let hs = self.lookup_handshake(sid).ok_or_else(|| {
warn!("Got RespConf packet for non-existent session {sid:?}");
RosenpassError::InvalidSessionId(sid)
})?;
let ses = hs.peer().session();
let exp = hs.get(self).as_ref().map(|h| h.next);
let got = Some(HandshakeStateMachine::RespConf);
ensure!(
exp == got,
"Unexpected package in session {:?}. Expected {:?}, got {:?}.",
sid,
exp,
got
);
if exp != got {
warn!("Unexpected package in session {sid:?}. Expected {exp:?}, got {got:?}.",);
return Err(RosenpassError::UnexpectedMessage {
session: sid,
expected: exp,
got,
});
}
// Validate the message
{
let s = ses.get_mut(self).as_mut().with_context(|| {
format!("Cannot validate EmptyData message. Missing encryption session for {sid:?}")
// TODO get rid of as_mut necessity
let s = ses.get_mut(self).as_mut().ok_or_else(|| {
warn!("Cannot validate EmptyData message. Missing encryption session for {sid:?}");
RosenpassError::NoSuchSessionId(sid)
})?;
// the unwrap can not fail, because the slice returned by ctr() is
// guaranteed to have the correct size
let n = u64::from_le_bytes(rc.ctr().try_into().unwrap());
ensure!(n >= s.txnt, "Stale nonce");
if n < s.txnt {
trace!("Stale nonce");
return Err(RosenpassError::StaleNonce);
}
s.txnt = n;
aead_dec_into(
// pt, k, n, ad, ct
@@ -1738,94 +1756,27 @@ impl CryptoServer {
mod test {
use super::*;
#[test]
/// Ensure that the protocol implementation can deal with truncated
/// messages and with overlong messages.
///
/// This test performs a complete handshake between two randomly generated
/// servers; instead of delivering the message correctly at first messages
/// of length zero through about 1.2 times the correct message size are delivered.
///
/// Producing an error is expected on each of these messages.
///
/// Finally the correct message is delivered and the same process
/// starts again in the other direction.
///
/// Through all this, the handshake should still successfully terminate;
/// i.e. an exchanged key must be produced in both servers.
fn handles_incorrect_size_messages() {
fn init_crypto_server() -> CryptoServer {
// always init libsodium before anything
crate::sodium::sodium_init().unwrap();
stacker::grow(8 * 1024 * 1024, || {
const OVERSIZED_MESSAGE: usize = ((MAX_MESSAGE_LEN as f32) * 1.2) as usize;
type MsgBufPlus = Public<OVERSIZED_MESSAGE>;
const PEER0: PeerPtr = PeerPtr(0);
let (mut me, mut they) = make_server_pair().unwrap();
let (mut msgbuf, mut resbuf) = (MsgBufPlus::zero(), MsgBufPlus::zero());
// Process the entire handshake
let mut msglen = Some(me.initiate_handshake(PEER0, &mut *resbuf).unwrap());
loop {
if let Some(l) = msglen {
std::mem::swap(&mut me, &mut they);
std::mem::swap(&mut msgbuf, &mut resbuf);
msglen = test_incorrect_sizes_for_msg(&mut me, &*msgbuf, l, &mut *resbuf);
} else {
break;
}
}
assert_eq!(
me.osk(PEER0).unwrap().secret(),
they.osk(PEER0).unwrap().secret()
);
});
}
/// Used in handles_incorrect_size_messages() to first deliver many truncated
/// and overlong messages, finally the correct message is delivered and the response
/// returned.
fn test_incorrect_sizes_for_msg(
srv: &mut CryptoServer,
msgbuf: &[u8],
msglen: usize,
resbuf: &mut [u8],
) -> Option<usize> {
resbuf.fill(0);
for l in 0..(((msglen as f32) * 1.2) as usize) {
if l == msglen {
continue;
}
let res = srv.handle_msg(&msgbuf[..l], resbuf);
assert!(matches!(res, Err(_))); // handle_msg should raise an error
assert!(!resbuf.iter().find(|x| **x != 0).is_some()); // resbuf should not have been changed
}
// Apply the proper handle_msg operation
srv.handle_msg(&msgbuf[..msglen], resbuf).unwrap().resp
}
fn keygen() -> Result<(SSk, SPk)> {
// TODO: Copied from the benchmark; deduplicate
// initialize secret and public key for the crypto server
let (mut sk, mut pk) = (SSk::zero(), SPk::zero());
StaticKEM::keygen(sk.secret_mut(), pk.secret_mut())?;
Ok((sk, pk))
StaticKEM::keygen(sk.secret_mut(), pk.secret_mut()).expect("unable to generate keys");
CryptoServer::new(sk, pk)
}
fn make_server_pair() -> Result<(CryptoServer, CryptoServer)> {
// TODO: Copied from the benchmark; deduplicate
let psk = SymKey::random();
let ((ska, pka), (skb, pkb)) = (keygen()?, keygen()?);
let (mut a, mut b) = (
CryptoServer::new(ska, pka.clone()),
CryptoServer::new(skb, pkb.clone()),
);
a.add_peer(Some(psk.clone()), pkb)?;
b.add_peer(Some(psk), pka)?;
Ok((a, b))
/// The determination of the message type relies on reading the first byte of the message. Only
/// after that the length of the message is checked against the specified message type. This
/// test ensures that nothing breaks in the case of an empty message.
#[test]
#[should_panic = "called `Result::unwrap()` on an `Err` value: received empty message, ignoring it"]
fn handle_empty_message() {
let mut crypt = init_crypto_server();
let empty_rx_buf = [0u8; 0];
let mut tx_buf = [0u8; 0];
crypt.handle_msg(&empty_rx_buf, &mut tx_buf).unwrap();
}
}

View File

@@ -1,16 +1,11 @@
//! bindings and helpers for accessing libsodium functions
//! Bindings and helpers for accessing libsodium functions
use crate::util::*;
use anyhow::{ensure, Result};
use crate::{util::*, Result, RosenpassError};
use libsodium_sys as libsodium;
use log::trace;
use static_assertions::const_assert_eq;
use std::slice::from_ref;
use std::os::raw::{c_ulonglong, c_void};
use std::ptr::{null as nullptr, null_mut as nullptr_mut};
use std::io::Write;
use std::cmp::max;
use num_traits::{Zero, ToBytes};
pub const AEAD_TAG_LEN: usize = libsodium::crypto_aead_chacha20poly1305_IETF_ABYTES as usize;
pub const AEAD_NONCE_LEN: usize = libsodium::crypto_aead_chacha20poly1305_IETF_NPUBBYTES as usize;
@@ -30,9 +25,11 @@ const_assert_eq!(KEY_SIZE, libsodium::crypto_generichash_BYTES as usize);
macro_rules! sodium_call {
($name:ident, $($args:expr),*) => { attempt!({
ensure!(unsafe{libsodium::$name($($args),*)} > -1,
"Error in libsodium's {}.", stringify!($name));
Ok(())
if unsafe{libsodium::$name($($args),*)} > -1 {
Ok(())
}else{
Err(RosenpassError::LibsodiumError(concat!("Error in libsodium's {}.", stringify!($name))))
}
})};
($name:ident) => { sodium_call!($name, ) };
}
@@ -191,6 +188,30 @@ pub fn xaead_dec_into(
Ok(())
}
#[inline]
fn blake2b_flexible(out: &mut [u8], key: &[u8], data: &[u8]) -> Result<()> {
const KEY_MIN: usize = libsodium::crypto_generichash_KEYBYTES_MIN as usize;
const KEY_MAX: usize = libsodium::crypto_generichash_KEYBYTES_MAX as usize;
const OUT_MIN: usize = libsodium::crypto_generichash_BYTES_MIN as usize;
const OUT_MAX: usize = libsodium::crypto_generichash_BYTES_MAX as usize;
assert!(key.is_empty() || (KEY_MIN <= key.len() && key.len() <= KEY_MAX));
assert!(OUT_MIN <= out.len() && out.len() <= OUT_MAX);
let kptr = match key.len() {
// NULL key
0 => nullptr(),
_ => key.as_ptr(),
};
sodium_call!(
crypto_generichash_blake2b,
out.as_mut_ptr(),
out.len(),
data.as_ptr(),
data.len() as c_ulonglong,
kptr,
key.len()
)
}
// TODO: Use proper streaming hash; for mix_hash too.
#[inline]
pub fn hash_into(out: &mut [u8], data: &[u8]) -> Result<()> {
@@ -231,7 +252,12 @@ pub fn mac16(key: &[u8], data: &[u8]) -> Result<[u8; 16]> {
pub fn hmac_into(out: &mut [u8], key: &[u8], data: &[u8]) -> Result<()> {
// Not bothering with padding; the implementation
// uses appropriately sized keys.
ensure!(key.len() == KEY_SIZE);
if key.len() != KEY_SIZE {
return Err(crate::RosenpassError::BufferSizeMismatch {
required_size: KEY_SIZE,
actual_size: key.len(),
});
}
const IPAD: [u8; KEY_SIZE] = [0x36u8; KEY_SIZE];
let mut temp_key = [0u8; KEY_SIZE];

View File

@@ -1,9 +1,9 @@
//! Helper functions and macros
use anyhow::{ensure, Context, Result};
use base64::{
display::Base64Display as B64Display, read::DecoderReader as B64Reader,
write::EncoderWriter as B64Writer,
};
use log::error;
use std::{
borrow::{Borrow, BorrowMut},
cmp::min,
@@ -13,25 +13,11 @@ use std::{
time::{Duration, Instant},
};
// TODO: Move everything except module declarations out of this file
pub(crate) mod types;
pub(crate) mod math;
pub(crate) mod result;
pub(crate) mod io;
use crate::{
coloring::{Public, Secret},
Result,
};
use crate::coloring::{Public, Secret};
/// Xors a and b element-wise and writes the result into a.
///
/// # Examples
///
/// ```
/// use rosenpass::util::xor_into;
/// let mut a = String::from("hello").into_bytes();
/// let b = b"world";
/// xor_into(&mut a, b);
/// assert_eq!(&a, b"\x1f\n\x1e\x00\x0b");
/// ```
#[inline]
pub fn xor_into(a: &mut [u8], b: &[u8]) {
assert!(a.len() == b.len());
@@ -75,7 +61,7 @@ pub fn cpy_min<T: BorrowMut<[u8]> + ?Sized, F: Borrow<[u8]> + ?Sized>(src: &F, d
#[macro_export]
macro_rules! attempt {
($block:expr) => {
(|| -> ::anyhow::Result<_> { $block })()
(|| -> crate::Result<_> { $block })()
};
}
@@ -167,8 +153,12 @@ impl<R: Read> ReadExactToEnd for R {
fn read_exact_to_end(&mut self, buf: &mut [u8]) -> Result<()> {
let mut dummy = [0u8; 8];
self.read_exact(buf)?;
ensure!(self.read(&mut dummy)? == 0, "File too long!");
Ok(())
if self.read(&mut dummy)? != 0 {
error!("File too long!");
Err(crate::RosenpassError::RuntimeError)
} else {
Ok(())
}
}
}
@@ -189,11 +179,11 @@ trait StoreValue {
}
trait StoreSecret {
fn store_secret<P: AsRef<Path>>(&self, path: P) -> Result<()>;
unsafe fn store_secret<P: AsRef<Path>>(&self, path: P) -> Result<()>;
}
impl<T: StoreValue> StoreSecret for T {
fn store_secret<P: AsRef<Path>>(&self, path: P) -> Result<()> {
unsafe fn store_secret<P: AsRef<Path>>(&self, path: P) -> Result<()> {
self.store(path)
}
}
@@ -202,9 +192,10 @@ impl<const N: usize> LoadValue for Secret<N> {
fn load<P: AsRef<Path>>(path: P) -> Result<Self> {
let mut v = Self::random();
let p = path.as_ref();
fopen_r(p)?
.read_exact_to_end(v.secret_mut())
.with_context(|| format!("Could not load file {p:?}"))?;
fopen_r(p)?.read_exact_to_end(v.secret_mut()).map_err(|e| {
error!("Could not load file {p:?}");
e
})?;
Ok(v)
}
}
@@ -222,13 +213,16 @@ impl<const N: usize> LoadValueB64 for Secret<N> {
// not worth it right now.
b64_reader(&mut fopen_r(p)?)
.read_exact(v.secret_mut())
.with_context(|| format!("Could not load base64 file {p:?}"))?;
.map_err(|e| {
error!("Could not load base64 file {p:?}");
e
})?;
Ok(v)
}
}
impl<const N: usize> StoreSecret for Secret<N> {
fn store_secret<P: AsRef<Path>>(&self, path: P) -> Result<()> {
unsafe fn store_secret<P: AsRef<Path>>(&self, path: P) -> Result<()> {
std::fs::write(path, self.secret())?;
Ok(())
}