Compare commits

...

22 Commits

Author SHA1 Message Date
Karolin Varner
7003671cde fix: Regression caused by benchmarks
CI keeps failing for external pull requests as GH's permission
model was not fully accounted for
2025-07-09 10:08:05 +02:00
Karolin Varner
91fc50c1e1 Specify WireGuard OSK as a protocol extension & allow for custom OSK domain separators (#664)
Some checks failed
QC / cargo-doc (push) Has been cancelled
QC / cargo-test (push) Has been cancelled
QC / cargo-test-nix-devshell-x86_64-linux (push) Has been cancelled
QC / cargo-fuzz (push) Has been cancelled
QC / codecov (push) Has been cancelled
Regressions / multi-peer (push) Has been cancelled
Regressions / boot-race (push) Has been cancelled
Supply-Chain / Deny dependencies with vulnerabilities or incompatible licenses (push) Has been cancelled
Supply-Chain / Supply Chain Report (push) Has been cancelled
Supply-Chain / Vet Dependencies (push) Has been cancelled
rosenpass-ciphers - primitives - benchmark / ciphers-primitives-bench-status (push) Has been cancelled
rosenpass - protocol - benchmark / ciphers-protocol-bench-status (push) Has been cancelled
Build Docker Images / docker-image-rp (amd64) (push) Has been cancelled
Build Docker Images / docker-image-rp (arm64) (push) Has been cancelled
Build Docker Images / docker-image-rosenpass (amd64) (push) Has been cancelled
Build Docker Images / docker-image-rosenpass (arm64) (push) Has been cancelled
Build Docker Images / merge-digests (rosenpass) (push) Has been cancelled
Build Docker Images / merge-digests (rp) (push) Has been cancelled
Nix on Mac / Build aarch64-darwin.default (push) Has been cancelled
Nix on Mac / Build aarch64-darwin.release-package (push) Has been cancelled
Nix on Mac / Build aarch64-darwin.rosenpass-oci-image (push) Has been cancelled
Nix / Build i686-linux.default (push) Has been cancelled
Nix / Build i686-linux.rosenpass-oci-image (push) Has been cancelled
Nix / Build x86_64-linux.default (push) Has been cancelled
Nix / Build x86_64-linux.proof-proverif (push) Has been cancelled
Nix / Build x86_64-linux.release-package (push) Has been cancelled
Nix / Build x86_64-linux.rosenpass-oci-image (push) Has been cancelled
Nix / Build aarch64-linux.rosenpass-oci-image (push) Has been cancelled
Nix / Build x86_64-linux.rosenpass-static-oci-image (push) Has been cancelled
Dependent Issues / check (push) Has been cancelled
2025-07-07 12:05:19 +02:00
Karolin Varner
b1a7d94295 feat: Support for custom osk (output key) domain separators in Rosenpass app
Some checks failed
rosenpass-ciphers - primitives - benchmark / prim-benchmark (i686-linux) (push) Has been cancelled
rosenpass-ciphers - primitives - benchmark / prim-benchmark (x86_64-linux) (push) Has been cancelled
rosenpass - protocol - benchmark / proto-benchmark (i686-linux) (push) Has been cancelled
rosenpass - protocol - benchmark / proto-benchmark (x86_64-linux) (push) Has been cancelled
rosenpass-ciphers - primitives - benchmark / ciphers-primitives-bench-status (push) Has been cancelled
rosenpass - protocol - benchmark / ciphers-protocol-bench-status (push) Has been cancelled
This allows for custom protocol extensions with custom domain
separators to be used without modifying the Rosenpass source code
2025-06-25 19:48:29 +02:00
Karolin Varner
48b7bb2f14 feat(whitepaper): Introduce protocol extensions & specify WG integration as one 2025-06-25 19:48:29 +02:00
Karolin Varner
77e3682820 chore: Whitespace issues in the whitepaper 2025-06-25 19:48:29 +02:00
Karolin Varner
8bad02bcda feat: Disallow unknown fields in rosenpass and rp configuration 2025-06-25 19:48:29 +02:00
Karolin Varner
864407f90b chore: Fix module documentation for app_server 2025-06-25 19:38:51 +02:00
Karolin Varner
4deee59e90 chore: Restructure imports in various places 2025-06-25 19:38:51 +02:00
Karolin Varner
c82ed332f6 Start splitting protocol.rs into multiple files (#655)
Some checks failed
QC / cargo-doc (push) Has been cancelled
QC / cargo-test (push) Has been cancelled
QC / cargo-test-nix-devshell-x86_64-linux (push) Has been cancelled
QC / cargo-fuzz (push) Has been cancelled
QC / codecov (push) Has been cancelled
Regressions / multi-peer (push) Has been cancelled
Regressions / boot-race (push) Has been cancelled
Supply-Chain / Deny dependencies with vulnerabilities or incompatible licenses (push) Has been cancelled
Supply-Chain / Supply Chain Report (push) Has been cancelled
Supply-Chain / Vet Dependencies (push) Has been cancelled
Nix / Build i686-linux.default (push) Has been cancelled
Nix / Build i686-linux.rosenpass-oci-image (push) Has been cancelled
Nix / Build x86_64-linux.default (push) Has been cancelled
Nix / Build x86_64-linux.proof-proverif (push) Has been cancelled
Build Docker Images / docker-image-rosenpass (arm64) (push) Has been cancelled
rosenpass-ciphers - primitives - benchmark / ciphers-primitives-bench-status (push) Has been cancelled
rosenpass - protocol - benchmark / ciphers-protocol-bench-status (push) Has been cancelled
Build Docker Images / docker-image-rp (amd64) (push) Has been cancelled
Build Docker Images / docker-image-rp (arm64) (push) Has been cancelled
Build Docker Images / docker-image-rosenpass (amd64) (push) Has been cancelled
Build Docker Images / merge-digests (rosenpass) (push) Has been cancelled
Build Docker Images / merge-digests (rp) (push) Has been cancelled
Nix on Mac / Build aarch64-darwin.default (push) Has been cancelled
Nix on Mac / Build aarch64-darwin.release-package (push) Has been cancelled
Nix on Mac / Build aarch64-darwin.rosenpass-oci-image (push) Has been cancelled
Nix / Build x86_64-linux.release-package (push) Has been cancelled
Nix / Build x86_64-linux.rosenpass-oci-image (push) Has been cancelled
Nix / Build aarch64-linux.rosenpass-oci-image (push) Has been cancelled
Nix / Build x86_64-linux.rosenpass-static-oci-image (push) Has been cancelled
Dependent Issues / check (push) Has been cancelled
2025-06-24 14:50:52 +02:00
Karolin Varner
5ced547a07 chore: PeerIndex split from protocol.rs
Some checks failed
rosenpass-ciphers - primitives - benchmark / prim-benchmark (i686-linux) (push) Has been cancelled
rosenpass-ciphers - primitives - benchmark / prim-benchmark (x86_64-linux) (push) Has been cancelled
rosenpass - protocol - benchmark / proto-benchmark (i686-linux) (push) Has been cancelled
rosenpass - protocol - benchmark / proto-benchmark (x86_64-linux) (push) Has been cancelled
rosenpass-ciphers - primitives - benchmark / ciphers-primitives-bench-status (push) Has been cancelled
rosenpass - protocol - benchmark / ciphers-protocol-bench-status (push) Has been cancelled
2025-06-24 14:01:31 +02:00
Karolin Varner
bdaedc4e2a chore: CookieStore split from protocol.rs 2025-06-24 14:01:31 +02:00
Karolin Varner
4e77e67f10 chore: Split utils for zerocopy in protocol into own file 2025-06-24 14:01:31 +02:00
Karolin Varner
f33c3a6928 chore: Split protocol testutils into own file 2025-06-24 14:01:31 +02:00
Karolin Varner
348650d507 chore: protocol::test should not import super::* 2025-06-24 14:01:31 +02:00
Karolin Varner
c318cf7bac chore: Split protocol tests into own file 2025-06-24 14:01:31 +02:00
Karolin Varner
d9a6430472 chore: Remove unused type SymHash 2025-06-24 14:01:31 +02:00
Karolin Varner
9656fa7025 chore: Split basic types from protocol.rs into own file 2025-06-24 14:01:31 +02:00
Karolin Varner
53ddad30f1 fix: Incorrect reference in protocol.rs
REKEY_TIMEOUT is not used at all
2025-06-24 14:01:31 +02:00
Karolin Varner
7e8e502bca chore: Split constants from protocol.rs into own file 2025-06-24 14:01:31 +02:00
Karolin Varner
d81649c1d1 chore: Restructure imports in protocol.rs 2025-06-24 14:01:31 +02:00
Karolin Varner
da642186f2 chore: Move timing related thing out of protocol.rs 2025-06-24 14:01:31 +02:00
Karolin Varner
ad6d053015 fix: Missing imports (CI Failure on Main) (#663) 2025-06-24 12:35:43 +02:00
38 changed files with 1994 additions and 1268 deletions

View File

@@ -3,11 +3,6 @@ secret_key = "rp-a-secret-key"
listen = ["127.0.0.1:9999"]
verbosity = "Verbose"
[api]
listen_path = []
listen_fd = []
stream_fd = []
[[peers]]
public_key = "rp-b-public-key"
endpoint = "127.0.0.1:9998"

View File

@@ -3,11 +3,6 @@ secret_key = "rp-b-secret-key"
listen = ["127.0.0.1:9998"]
verbosity = "Verbose"
[api]
listen_path = []
listen_fd = []
stream_fd = []
[[peers]]
public_key = "rp-a-public-key"
endpoint = "127.0.0.1:9999"

View File

@@ -4,7 +4,7 @@ permissions:
contents: write
on:
pull_request:
#pull_request:
push:
env:

View File

@@ -4,7 +4,7 @@ permissions:
contents: write
on:
pull_request:
#pull_request:
push:
env:

View File

@@ -83,6 +83,33 @@ impl HashDomain {
Ok(Self(new_key, self.1))
}
/// Version of [Self::mix] that accepts an iterator and mixes all values from the iterator into
/// this hash domain.
///
/// # Examples
///
/// ```rust
/// use rosenpass_ciphers::{hash_domain::HashDomain, KeyedHash};
///
/// let hasher = HashDomain::zero(KeyedHash::keyed_shake256());
/// assert_eq!(
/// hasher.clone().mix(b"Hello")?.mix(b"World")?.into_value(),
/// hasher.clone().mix_many([b"Hello", b"World"])?.into_value()
/// );
///
/// Ok::<(), anyhow::Error>(())
/// ```
pub fn mix_many<I, T>(mut self, it: I) -> Result<Self>
where
I: IntoIterator<Item = T>,
T: AsRef<[u8]>,
{
for e in it {
self = self.mix(e.as_ref())?;
}
Ok(self)
}
/// Creates a new [SecretHashDomain] by mixing in a new key `v`
/// by calling [SecretHashDomain::invoke_primitive] with this
/// [HashDomain]'s key as `k` and `v` as `d`.
@@ -161,6 +188,46 @@ impl SecretHashDomain {
Self::invoke_primitive(self.0.secret(), v, self.1)
}
/// Version of [Self::mix] that accepts an iterator and mixes all values from the iterator into
/// this hash domain.
///
/// # Examples
///
/// ```rust
/// use rosenpass_ciphers::{hash_domain::HashDomain, KeyedHash};
///
/// rosenpass_secret_memory::secret_policy_use_only_malloc_secrets();
///
/// let hasher = HashDomain::zero(KeyedHash::keyed_shake256());
/// assert_eq!(
/// hasher
/// .clone()
/// .turn_secret()
/// .mix(b"Hello")?
/// .mix(b"World")?
/// .into_secret()
/// .secret(),
/// hasher
/// .clone()
/// .turn_secret()
/// .mix_many([b"Hello", b"World"])?
/// .into_secret()
/// .secret(),
/// );
/// Ok::<(), anyhow::Error>(())
/// ```
pub fn mix_many<I, T>(mut self, it: I) -> Result<Self>
where
I: IntoIterator<Item = T>,
T: AsRef<[u8]>,
{
for e in it {
self = self.mix(e.as_ref())?;
}
Ok(self)
}
/// Creates a new [SecretHashDomain] by mixing in a new key `v`
/// by calling [SecretHashDomain::invoke_primitive] with the key of this
/// [HashDomainNamespace] as `k` and `v` as `d`.

View File

@@ -2,6 +2,7 @@
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage{fontspec}
\usepackage{dirtytalk}
%font fallback
\directlua{luaotfload.add_fallback

View File

@@ -8,13 +8,15 @@ author:
- Lisa Schmidt = {Scientific Illustrator \\url{mullana.de}}
- Prabhpreet Dua
abstract: |
Rosenpass is used to create post-quantum-secure VPNs. Rosenpass computes a shared key, WireGuard (WG) [@wg] uses the shared key to establish a secure connection. Rosenpass can also be used without WireGuard, deriving post-quantum-secure symmetric keys for another application. The Rosenpass protocol builds on “Post-quantum WireGuard” (PQWG) [@pqwg] and improves it by using a cookie mechanism to provide security against state disruption attacks.
Rosenpass is a post-quantum-secure authenticated key exchange protocol. Its main practical use case is creating post-quantum-secure VPNs by combining WireGuard and Rosenpass.
The WireGuard implementation enjoys great trust from the cryptography community and has excellent performance characteristics. To preserve these features, the Rosenpass application runs side-by-side with WireGuard and supplies a new post-quantum-secure pre-shared key (PSK) every two minutes. WireGuard itself still performs the pre-quantum-secure key exchange and transfers any transport data with no involvement from Rosenpass at all.
In this combination, Rosenpass generates a post-quantum-secure shared key every two minutes that is then used by WireGuard (WG) [@wg] to establish a secure connection. Rosenpass can also be used without WireGuard, providing post-quantum-secure symmetric keys for other applications, as long as the other application accepts a pre-shared key and provides cryptographic security based on the pre-shared key alone.
The Rosenpass protocol builds on “Post-quantum WireGuard” (PQWG) [@pqwg] and improves it by using a cookie mechanism to provide security against state disruption attacks. From a cryptographic perspective, Rosenpass can be thought of as a post-quantum secure variant of the Noise IK[@noise] key exchange. \say{Noise IK} means that the protocol makes both parties authenticate themselves, but that the initiator knows before the protocol starts which other party they are communicating with. There is no negotiation step where the responder communicates their identity to the initiator.
The Rosenpass project consists of a protocol description, an implementation written in Rust, and a symbolic analysis of the protocols security using ProVerif [@proverif]. We are working on a cryptographic security proof using CryptoVerif [@cryptoverif].
This document is a guide for engineers and researchers implementing the protocol; a scientific paper discussing the security properties of Rosenpass is work in progress.
This document is a guide for engineers and researchers implementing the protocol.
---
\enlargethispage{5mm}
@@ -31,7 +33,7 @@ abstract: |
# Security
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.
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.
@@ -154,16 +156,18 @@ Rosenpass uses two types of ID variables. See Figure \ref{img:HashingTree} for h
The first lower-case character indicates whether the variable is a session ID (`sid`) or a peer ID (`pid`). The final character indicates the role using the characters `i`, `r`, `m`, or `t`, for `initiator`, `responder`, `mine`, or `theirs` respectively.
### Symmetric Keys
Rosenpass uses two symmetric key variables `psk` and `osk` in its interface, and maintains the entire handshake state in a variable called the chaining key.
### Symmetric Keys {#symmetric-keys}
Rosenpass uses two main symmetric key variables `psk` and `osk` in its interface, and maintains the entire handshake state in a variable called the chaining key.
* `psk`: A pre-shared key that can be optionally supplied as input to Rosenpass.
* `osk`: The output shared key, generated by Rosenpass and supplied to WireGuard for use as its pre-shared key.
* `ck`: The chaining key.
* `osk`: The output shared key, generated by Rosenpass. The main use case is to supply the key to WireGuard for use as its pre-shared key.
* `ck`: The chaining key. This refers to various intermediate keys produced during the execution of the protocol, before the final `osk` is produced.
We mix all key material (e.g. `psk`) into the chaining key and derive symmetric keys such as `osk` from it. We authenticate public values by mixing them into the chaining key; in particular, we include the entire protocol transcript in the chaining key, i.e., all values transmitted over the network.
The protocol allows for multiple `osk`s to be generated; each of these keys is labeled with a domain separator to make sure different key usages are always given separate keys. The domain separator for using Rosenpass and WireGuard together is a token generated using the domain separator sequence `["rosenpass.eu", "wireguard psk"]` (see Fig. \ref{img:HashingTree}), as described in \ref{protocol-extension-wireguard-psk}. Third-parties using Rosenpass-keys for other purposes are asked to define their own protocol-extensions. Standard protocol extensions are described in \ref{protocol-extensions}.
We mix all key material (e.g. `psk`) into the chaining key, and derive symmetric keys such as `osk` from it. We authenticate public values by mixing them into the chaining key; in particular, we include the entire protocol transcript in the chaining key, i.e., all values transmitted over the network.
## Hashes
@@ -182,7 +186,7 @@ Using one hash function for multiple purposes can cause real-world security issu
\setupimage{landscape,fullpage,label=img:HashingTree}
![Rosenpass Hashing Tree](graphics/rosenpass-wp-hashing-tree-rgb.svg)
Each tree node $\circ{}$ in Figure 3 represents the application of the keyed hash function, using the previous chaining key value as first parameter. The root of the tree is the zero key. In level one, the `PROTOCOL` identifier is applied to the zero key to generate a label unique across cryptographic protocols (unless the same label is deliberately used elsewhere). In level two, purpose identifiers are applied to the protocol label to generate labels to use with each separate hash function application within the Rosenpass protocol. The following layers contain the inputs used in each separate usage of the hash function: Beneath the identifiers `"mac"`, `"cookie"`, `"peer id"`, and `"biscuit additional data"` are hash functions or message authentication codes with a small number of inputs. The second, third, and fourth column in Figure 3 cover the long sequential branch beneath the identifier `"chaining key init"` representing the entire protocol execution, one column for each message processed during the handshake. The leaves beneath `"chaining key extract"` in the left column represent pseudo-random labels for use when extracting values from the chaining key during the protocol execution. These values such as `mix >` appear as outputs in the left column, and then as inputs `< mix` in the other three columns.
Each tree node $\circ{}$ in Figure \ref{img:HashingTree} represents the application of the keyed hash function, using the previous chaining key value as first parameter. The root of the tree is the zero key. In level one, the `PROTOCOL` identifier is applied to the zero key to generate a label unique across cryptographic protocols (unless the same label is deliberately used elsewhere). In level two, purpose identifiers are applied to the protocol label to generate labels to use with each separate hash function application within the Rosenpass protocol. The following layers contain the inputs used in each separate usage of the hash function: Beneath the identifiers `"mac"`, `"cookie"`, `"peer id"`, and `"biscuit additional data"` are hash functions or message authentication codes with a small number of inputs. The second, third, and fourth column in Figure \ref{img:HashingTree} cover the long sequential branch beneath the identifier `"chaining key init"` representing the entire protocol execution, one column for each message processed during the handshake. The leaves beneath `"chaining key extract"` in the left column represent pseudo-random labels for use when extracting values from the chaining key during the protocol execution. These values such as `mix >` appear as outputs in the left column, and then as inputs `< mix` in the other three columns.
The protocol identifier depends on the hash function used with the respective peer is defined as follows if BLAKE2s [@rfc_blake2] is used:
@@ -289,7 +293,7 @@ fn lookup_session(sid);
The protocol framework used by Rosenpass allows arbitrarily many different keys to be extracted using labels for each key. The `extract_key` function is used to derive protocol-internal keys, its labels are under the “chaining key extract” node in Figure \ref{img:HashingTree}. The export key function is used to export application keys.
Third-party applications using the protocol are supposed to choose a unique label (e.g., their domain name) and use that as their own namespace for custom labels. The Rosenpass project itself uses the rosenpass.eu namespace.
Third-party applications using the protocol are supposed to define a protocol extension (see \ref{protocol-extensions}) and choose a globally unique label, such as their domain name for custom labels of their own. The Rosenpass project itself uses the `["rosenpass.eu"]` namespace in the WireGuard PSK protocol extension (see \ref{protocol-extension-wireguard-psk}).
Applications can cache or statically compile the pseudo-random label values into their binary to improve performance.
@@ -395,7 +399,7 @@ fn load_biscuit(nct) {
// In December 2024, the InitConf retransmission mechanisim was redesigned
// in a backwards-compatible way. See the changelog.
//
//
// -- 2024-11-30, Karolin Varner
if (protocol_version!(< "0.3.0")) {
// Ensure that the biscuit is used only once
@@ -421,6 +425,18 @@ fn enter_live() {
txkr ← extract_key("responder payload encryption");
txnm ← 0;
txnt ← 0;
// Setup output keys for protocol extensions such as the
// WireGuard PSK protocol extension.
setup_osks();
}
```
The final step `setup_osks()` can be defined by protocol extensions (see \ref{protocol-extensions}) to set up `osk`s for custom use cases. By default, the WireGuard PSK (see \ref{protocol-extension-wireguard-psk}) is active.
```pseudorust
fn setup_osks() {
... // Defined by protocol extensions
}
```
@@ -448,11 +464,11 @@ ICR5 and ICR6 perform biscuit replay protection using the biscuit number. This i
### Denial of Service Mitigation and Cookies
Rosenpass derives its cookie-based DoS mitigation technique for a responder when receiving InitHello messages from Wireguard [@wg].
Rosenpass derives its cookie-based DoS mitigation technique for a responder when receiving InitHello messages from Wireguard [@wg].
When the responder is under load, it may choose to not process further InitHello handshake messages, but instead to respond with a cookie reply message (see Figure \ref{img:MessageTypes}).
The sender of the exchange then uses this cookie in order to resend the message and have it accepted the following time by the reciever.
The sender of the exchange then uses this cookie in order to resend the message and have it accepted the following time by the reciever.
For an initiator, Rosenpass ignores all messages when under load.
@@ -465,7 +481,7 @@ cookie_value = lhash("cookie-value", cookie_secret, initiator_host_info)[0..16]
cookie_encrypted = XAEAD(lhash("cookie-key", spkm), nonce, cookie_value, mac_peer)
```
where `cookie_secret` is a secret variable that changes every two minutes to a random value. Moreover, `lhash` is always instantiated with SHAKE256 when computing `cookie_value` for compatability reasons. `initiator_host_info` is used to identify the initiator host, and is implementation-specific for the client. This paramaters used to identify the host must be carefully chosen to ensure there is a unique mapping, especially when using IPv4 and IPv6 addresses to identify the host (such as taking care of IPv6 link-local addresses). `cookie_value` is a truncated 16 byte value from the above hash operation. `mac_peer` is the `mac` field of the peer's handshake message to which message is the reply.
where `cookie_secret` is a secret variable that changes every two minutes to a random value. Moreover, `lhash` is always instantiated with SHAKE256 when computing `cookie_value` for compatability reasons. `initiator_host_info` is used to identify the initiator host, and is implementation-specific for the client. This paramaters used to identify the host must be carefully chosen to ensure there is a unique mapping, especially when using IPv4 and IPv6 addresses to identify the host (such as taking care of IPv6 link-local addresses). `cookie_value` is a truncated 16 byte value from the above hash operation. `mac_peer` is the `mac` field of the peer's handshake message to which message is the reply.
#### Envelope `mac` Field
@@ -495,13 +511,13 @@ else {
Here, `seconds_since_update(peer.cookie_value)` is the amount of time in seconds ellapsed since last cookie was received, and `COOKIE_WIRE_DATA` are the message contents of all bytes of the retransmitted message prior to the `cookie` field.
The inititator can use an invalid value for the `cookie` value, when the responder is not under load, and the responder must ignore this value.
However, when the responder is under load, it may reject InitHello messages with the invalid `cookie` value, and issue a cookie reply message.
However, when the responder is under load, it may reject InitHello messages with the invalid `cookie` value, and issue a cookie reply message.
### Conditions to trigger DoS Mechanism
This whitepaper does not mandate any specific mechanism to detect responder contention (also mentioned as the under load condition) that would trigger use of the cookie mechanism.
For the reference implemenation, Rosenpass has derived inspiration from the Linux implementation of Wireguard. This implementation suggests that the reciever keep track of the number of messages it is processing at a given time.
For the reference implemenation, Rosenpass has derived inspiration from the Linux implementation of Wireguard. This implementation suggests that the reciever keep track of the number of messages it is processing at a given time.
On receiving an incoming message, if the length of the message queue to be processed exceeds a threshold `MAX_QUEUED_INCOMING_HANDSHAKES_THRESHOLD`, the client is considered under load and its state is stored as under load. In addition, the timestamp of this instant when the client was last under load is stored. When recieving subsequent messages, if the client is still in an under load state, the client will check if the time ellpased since the client was last under load has exceeded `LAST_UNDER_LOAD_WINDOW` seconds. If this is the case, the client will update its state to normal operation, and process the message in a normal fashion.
@@ -520,23 +536,159 @@ The responder uses less complex form of the same mechanism: The responder never
### Interaction with cookie reply system
The cookie reply system does not interfere with the retransmission logic discussed above.
The cookie reply system does not interfere with the retransmission logic discussed above.
When the initator is under load, it will ignore processing any incoming messages.
When a responder is under load and it receives an InitHello handshake message, the InitHello message will be discarded and a cookie reply message is sent. The initiator, then on the reciept of the cookie reply message, will store a decrypted `cookie_value` to set the `cookie` field to subsequently sent messages. As per the retransmission mechanism above, the initiator will send a retransmitted InitHello message with a valid `cookie` value appended. On receiving the retransmitted handshake message, the responder will validate the `cookie` value and resume with the handshake process.
When a responder is under load and it receives an InitHello handshake message, the InitHello message will be discarded and a cookie reply message is sent. The initiator, then on the reciept of the cookie reply message, will store a decrypted `cookie_value` to set the `cookie` field to subsequently sent messages. As per the retransmission mechanism above, the initiator will send a retransmitted InitHello message with a valid `cookie` value appended. On receiving the retransmitted handshake message, the responder will validate the `cookie` value and resume with the handshake process.
When the responder is under load and it recieves an InitConf message, the message will be directly processed without checking the validity of the cookie field.
# Protocol extensions {#protocol-extensions}
The main extension point for the Rosenpass protocol is to generate `osk`s (speak output shared keys, see Sec. \ref{symmetric-keys}) for purposes other than using them to secure WireGuard. By default, the Rosenpass application generates keys for the WireGuard PSK (see \ref{protocol-extension-wireguard-psk}). It would not be impossible to use the keys generated for WireGuard in other use cases, but this might lead to attacks[@oraclecloning]. Specifying a custom protocol extension in practice just means settling on alternative domain separators (see Sec. \ref{symmetric-keys}, Fig. \ref{img:HashingTree}).
## Using custom domain separators in the Rosenpass application
The Rosenpass application supports protocol extensions to change the OSK domain separator without modification of the source code.
The following example configuration file can be used to execute Rosenpass in outfile mode with custom domain separators.
In this mode, the Rosenpass application will write keys to the file specified with `key_out` and send notifications when new keys are exchanged via standard out.
This can be used to embed Rosenpass into third-party application.
```toml
# peer-a.toml
public_key = "peer-a.pk"
secret_key = "peer-a.sk"
listen = ["[::1]:6789"]
verbosity = "Verbose"
[[peers]]
public_key = "peer-b.pk"
key_out = "peer-a.osk" # path to store the key
osk_organization = "myorg.com"
osk_label = ["My Custom Messenger app", "Backend VPN Example Subusecase"]
```
## Extension: WireGuard PSK {#protocol-extension-wireguard-psk}
The WireGuard PSK protocol extension is active by default; this is the mode where Rosenpass is used to provide post-quantum security for WireGuard. Hybrid security (i.e. redundant pre-quantum and post-quantum security) is achieved because WireGuard provides pre-quantum security, with or without Rosenpass.
This extension uses the `"rosenpass.eu"` namespace for user-labels and specifies a single additional user-label:
* `["rosenpass.eu", "wireguard psk"]`
The label's full domain separator is
* `[PROTOCOL, "user", "rosenpass.eu", "wireguard psk"]`
and can be seen in Figure \ref{img:HashingTree}.
We require two extra per-peer configuration variables:
* `wireguard_interface` — Name of a local network interface. Identifies local WireGuard interface we are supplying a PSK to.
* `wireguard_peer` — A WireGuard public key. Identifies the particular WireGuard peer whose connection we are supplying PSKs for.
When creating the WireGuard interface for use with Rosenpass, the PSK used by WireGuard must be initialized to a random value; otherwise, WireGuard can establish an insecure key before Rosenpass had a change to exchange its own key.
```pseudorust
fn on_wireguard_setup() {
// We use a random PSK to make sure the other side will never
// have a matching PSK when the WireGuard interface is created.
//
// Never use a fixed value here as this would lead to an attack!
let fake_wireguard_psk = random_key();
// How the interface is create
let wg_peer = WireGuard::setup_peer()
.public_key(wireguard_peer)
... // Supply any custom peerconfiguration
.psk(fake_wireguard_psk);
// The random PSK must be supplied before the
// WireGuard interface comes up
WireGuard::setup_interface()
.name(wireguard_interface)
... // Supply any custom configuration
.add_peer(wg_peer)
.create();
}
```
Every time a key is successfully negotiated, we upload the key to WireGuard.
For this protocol extension, the `setup_osks()` function is thus defined as:
```pseudorust
fn setup_osks() {
// Generate WireGuard OSK (output shared key) from Rosenpass'
// perspective, respectively the PSK (preshared key) from
// WireGuard's perspective
let wireguard_psk = export_key("rosenpass.eu", "wireguard psk");
/// Supply the PSK to WireGuard
WireGuard::get_interface(wireguard_interface)
.get_peer(wireguard_peer)
.set_psk(wireguard_psk);
}
```
The Rosenpass protocol uses key renegotiation, just like WireGuard.
If no new `osk` is produced within a set amount of time, the OSK generated by Rosenpass times out.
In this case, the WireGuard PSK must be overwritten with a random key.
This interaction is visualized in Figure \ref{img:ExtWireguardPSKHybridSecurity}.
```pseudorust
fn on_key_timeout() {
// Generate a random deliberately invalid WireGuard PSK.
// Never use a fixed value here as this would lead to an attack!
let fake_wireguard_psk = random_key();
// Securely erase the PSK currently used by WireGuard by
// overwriting it with the fake key we just generated.
WireGuard::get_interface(wireguard_interface)
.get_peer(wireguard_peer)
.set_psk(fake_wireguard_psk);
}
```
\setupimage{label=img:ExtWireguardPSKHybridSecurity,fullpage}
![Rosenpass + WireGuard: Hybrid Security](graphics/rosenpass-wireguard-hybrid-security.pdf)
# Changelog
### 0.3.x
#### 2025-06-24 Specifying the `osk` used for WireGuard as a protocol extension
\vspace{0.5em}
Author: Karolin varner
PR: [#664](https://github.com/rosenpass/rosenpass/pull/664)
\vspace{0.5em}
We introduce the concept of protocol extensions to make the option of using Rosenpass for purposes other than encrypting WireGuard more explicit. This captures the status-quo in a better way and does not constitute a functional change of the protocol.
When we designed the Rosenpass protocol, we built it with support for alternative `osk`-labels in mind.
This is why we specified the domain separator for the `osk` to be `[PROTOCOL, "user", "rosenpass.eu", "wireguard psk"]`.
By choosing alternative values for the namespace (e.g. `"myorg.eu"` instead of `"rosenpass.eu`) and the label (e.g. `"MyApp Symmetric Encryption"`), the protocol could easily accommodate alternative usage scenarios.
By introducing the concept of protocol extensions, we make this possibility explicit.
1. Reworded the abstract to make it clearer that Rosenpass can be used for other purposes than to secure WireGuard
2. Reworded Section Symmetric Keys, adding references to the new section on protocol extension
3. Added a `setup_osks()` function in section Hashes, to make the reference to protocol extensions explicit
4. Added a new section on protocol extensions and the standard extension for using Rosenpass with WireGuard
5. Added a new graphic to showcase how Rosenpass and WireGuard interact
5. Minor formatting and intra-document references fixes
#### 2025-05-22 - SHAKE256 keyed hash
\vspace{0.5em}
Author: David Niehues
PR: [#653](https://github.com/rosenpass/rosenpass/pull/653)
PR: [#653](https://github.com/rosenpass/rosenpass/pull/653)
\vspace{0.5em}
@@ -554,9 +706,11 @@ In order to maintain compatablity without introducing an explcit version number
\vspace{0.5em}
Author: Karolin Varner
Issue: [#331](https://github.com/rosenpass/rosenpass/issues/331)
PR: [#513](https://github.com/rosenpass/rosenpass/pull/513)
Author: Karolin Varner
Issue: [#331](https://github.com/rosenpass/rosenpass/issues/331)
PR: [#513](https://github.com/rosenpass/rosenpass/pull/513)
\vspace{0.5em}
@@ -574,7 +728,7 @@ By removing all retransmission handling code from the cryptographic protocol, we
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.
\end{quote}
by
by
\begin{quote}
The responder uses less complex form of the same mechanism: The responder never retransmits RespHello, instead the responder generates a new RespHello message if InitHello is retransmitted. Responder confirmation messages of completed handshake (EmptyData) messages are retransmitted by storing the most recent InitConf messages (or their hashes) and caching the associated EmptyData messages. Through this cache, InitConf retransmission is detected and the associated EmptyData message is retransmitted.
@@ -597,7 +751,7 @@ By removing all retransmission handling code from the cryptographic protocol, we
\begin{minted}{pseudorust}
// In December 2024, the InitConf retransmission mechanisim was redesigned
// in a backwards-compatible way. See the changelog.
//
//
// -- 2024-11-30, Karolin Varner
if (protocol_version!(< "0.3.0")) {
// Ensure that the biscuit is used only once
@@ -611,9 +765,11 @@ By removing all retransmission handling code from the cryptographic protocol, we
\vspace{0.5em}
Author: Prabhpreet Dua
Issue: [#137](https://github.com/rosenpass/rosenpass/issues/137)
PR: [#142](https://github.com/rosenpass/rosenpass/pull/142)
Author: Prabhpreet Dua
Issue: [#137](https://github.com/rosenpass/rosenpass/issues/137)
PR: [#142](https://github.com/rosenpass/rosenpass/pull/142)
\vspace{0.5em}

View File

@@ -44,6 +44,7 @@ let
xifthen
xkeyval
xurl
dirtytalk
;
}
);

View File

@@ -1,15 +1,16 @@
use anyhow::Result;
use rosenpass::protocol::{
CryptoServer, HandleMsgResult, MsgBuf, PeerPtr, ProtocolVersion, SPk, SSk, SymKey,
};
use std::ops::DerefMut;
use anyhow::Result;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use rosenpass_cipher_traits::primitives::Kem;
use rosenpass_ciphers::StaticKem;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use rosenpass_secret_memory::secret_policy_try_use_memfd_secrets;
use rosenpass::protocol::basic_types::{MsgBuf, SPk, SSk, SymKey};
use rosenpass::protocol::osk_domain_separator::OskDomainSeparator;
use rosenpass::protocol::{CryptoServer, HandleMsgResult, PeerPtr, ProtocolVersion};
fn handle(
tx: &mut CryptoServer,
msgb: &mut MsgBuf,
@@ -54,8 +55,18 @@ fn make_server_pair(protocol_version: ProtocolVersion) -> Result<(CryptoServer,
CryptoServer::new(ska, pka.clone()),
CryptoServer::new(skb, pkb.clone()),
);
a.add_peer(Some(psk.clone()), pkb, protocol_version.clone())?;
b.add_peer(Some(psk), pka, protocol_version)?;
a.add_peer(
Some(psk.clone()),
pkb,
protocol_version.clone(),
OskDomainSeparator::default(),
)?;
b.add_peer(
Some(psk),
pka,
protocol_version,
OskDomainSeparator::default(),
)?;
Ok((a, b))
}

View File

@@ -1,12 +1,9 @@
use std::{
collections::HashMap,
hint::black_box,
io::{self, Write},
ops::DerefMut,
time::{Duration, Instant},
};
use std::io::{self, Write};
use std::time::{Duration, Instant};
use std::{collections::HashMap, hint::black_box, ops::DerefMut};
use anyhow::Result;
use libcrux_test_utils::tracing::{EventType, Trace as _};
use rosenpass_cipher_traits::primitives::Kem;
@@ -14,9 +11,9 @@ use rosenpass_ciphers::StaticKem;
use rosenpass_secret_memory::secret_policy_try_use_memfd_secrets;
use rosenpass_util::trace_bench::RpEventType;
use rosenpass::protocol::{
CryptoServer, HandleMsgResult, MsgBuf, PeerPtr, ProtocolVersion, SPk, SSk, SymKey,
};
use rosenpass::protocol::basic_types::{MsgBuf, SPk, SSk, SymKey};
use rosenpass::protocol::osk_domain_separator::OskDomainSeparator;
use rosenpass::protocol::{CryptoServer, HandleMsgResult, PeerPtr, ProtocolVersion};
const ITERATIONS: usize = 100;
@@ -77,8 +74,18 @@ fn make_server_pair(protocol_version: ProtocolVersion) -> Result<(CryptoServer,
CryptoServer::new(ska, pka.clone()),
CryptoServer::new(skb, pkb.clone()),
);
a.add_peer(Some(psk.clone()), pkb, protocol_version.clone())?;
b.add_peer(Some(psk), pka, protocol_version)?;
a.add_peer(
Some(psk.clone()),
pkb,
protocol_version.clone(),
OskDomainSeparator::default(),
)?;
b.add_peer(
Some(psk),
pka,
protocol_version,
OskDomainSeparator::default(),
)?;
Ok((a, b))
}

View File

@@ -158,10 +158,10 @@ where
);
// Actually read the secrets
let mut sk = crate::protocol::SSk::zero();
let mut sk = crate::protocol::basic_types::SSk::zero();
sk_io.read_exact_til_end(sk.secret_mut()).einvalid_req()?;
let mut pk = crate::protocol::SPk::zero();
let mut pk = crate::protocol::basic_types::SPk::zero();
pk_io.read_exact_til_end(pk.borrow_mut()).einvalid_req()?;
// Retrieve the construction site

View File

@@ -8,6 +8,7 @@ use crate::app_server::AppServer;
/// Configuration options for the Rosenpass API
#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ApiConfig {
/// Where in the file-system to create the unix socket the rosenpass API will be listening for
/// connections on

View File

@@ -1,56 +1,34 @@
/// This contains the bulk of the rosenpass server IO handling code whereas
/// the actual cryptographic code lives in the [crate::protocol] module
use anyhow::bail;
//! This contains the bulk of the rosenpass server IO handling code whereas
//! the actual cryptographic code lives in the [crate::protocol] module
use anyhow::Context;
use anyhow::Result;
use std::collections::{HashMap, VecDeque};
use std::io::{stdout, ErrorKind, Write};
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
use std::time::{Duration, Instant};
use std::{cell::Cell, fmt::Debug, io, path::PathBuf, slice};
use anyhow::{bail, Context, Result};
use derive_builder::Builder;
use log::{error, info, warn};
use mio::Interest;
use mio::Token;
use rosenpass_secret_memory::Public;
use rosenpass_secret_memory::Secret;
use rosenpass_util::build::ConstructionSite;
use rosenpass_util::file::StoreValueB64;
use rosenpass_util::functional::run;
use rosenpass_util::functional::ApplyExt;
use rosenpass_util::io::IoResultKindHintExt;
use rosenpass_util::io::SubstituteForIoErrorKindExt;
use rosenpass_util::option::SomeExt;
use rosenpass_util::result::OkExt;
use rosenpass_wireguard_broker::WireguardBrokerMio;
use rosenpass_wireguard_broker::{WireguardBrokerCfg, WG_KEY_LEN};
use mio::{Interest, Token};
use zerocopy::AsBytes;
use std::cell::Cell;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::fmt::Debug;
use std::io;
use std::io::stdout;
use std::io::ErrorKind;
use std::io::Write;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;
use std::net::SocketAddrV4;
use std::net::SocketAddrV6;
use std::net::ToSocketAddrs;
use std::path::PathBuf;
use std::slice;
use std::time::Duration;
use std::time::Instant;
use crate::config::ProtocolVersion;
use crate::protocol::BuildCryptoServer;
use crate::protocol::HostIdentification;
use crate::{
config::Verbosity,
protocol::{CryptoServer, MsgBuf, PeerPtr, SPk, SSk, SymKey, Timing},
};
use rosenpass_util::attempt;
use rosenpass_util::b64::B64Display;
use rosenpass_util::functional::{run, ApplyExt};
use rosenpass_util::io::{IoResultKindHintExt, SubstituteForIoErrorKindExt};
use rosenpass_util::{
b64::B64Display, build::ConstructionSite, file::StoreValueB64, option::SomeExt, result::OkExt,
};
use rosenpass_secret_memory::{Public, Secret};
use rosenpass_wireguard_broker::{WireguardBrokerCfg, WireguardBrokerMio, WG_KEY_LEN};
use crate::config::{ProtocolVersion, Verbosity};
use crate::protocol::basic_types::{MsgBuf, SPk, SSk, SymKey};
use crate::protocol::osk_domain_separator::OskDomainSeparator;
use crate::protocol::timing::Timing;
use crate::protocol::{BuildCryptoServer, CryptoServer, HostIdentification, PeerPtr};
/// The maximum size of a base64 encoded symmetric key (estimate)
pub const MAX_B64_KEY_SIZE: usize = 32 * 5 / 3;
@@ -1036,6 +1014,7 @@ impl AppServer {
/// # Examples
///
/// See [Self::new].
#[allow(clippy::too_many_arguments)]
pub fn add_peer(
&mut self,
psk: Option<SymKey>,
@@ -1044,11 +1023,16 @@ impl AppServer {
broker_peer: Option<BrokerPeer>,
hostname: Option<String>,
protocol_version: ProtocolVersion,
osk_domain_separator: OskDomainSeparator,
) -> anyhow::Result<AppPeerPtr> {
let PeerPtr(pn) = match &mut self.crypto_site {
ConstructionSite::Void => bail!("Crypto server construction site is void"),
ConstructionSite::Builder(builder) => builder.add_peer(psk, pk, protocol_version),
ConstructionSite::Product(srv) => srv.add_peer(psk, pk, protocol_version.into())?,
ConstructionSite::Builder(builder) => {
builder.add_peer(psk, pk, protocol_version, osk_domain_separator)
}
ConstructionSite::Product(srv) => {
srv.add_peer(psk, pk, protocol_version.into(), osk_domain_separator)?
}
};
assert!(pn == self.peers.len());
@@ -1337,7 +1321,7 @@ impl AppServer {
break A::SendRetransmission(AppPeerPtr(no))
}
Some(C::Sleep(timeout)) => timeout, // No event from crypto-server, do IO
None => crate::protocol::UNENDING, // Crypto server is uninitialized, do IO
None => crate::protocol::timing::UNENDING, // Crypto server is uninitialized, do IO
};
// Perform IO (look for a message)

View File

@@ -17,7 +17,7 @@ use std::path::PathBuf;
use crate::app_server::AppServerTest;
use crate::app_server::{AppServer, BrokerPeer};
use crate::protocol::{SPk, SSk, SymKey};
use crate::protocol::basic_types::{SPk, SSk, SymKey};
use super::config;
@@ -491,6 +491,7 @@ impl CliArgs {
broker_peer,
cfg_peer.endpoint.clone(),
cfg_peer.protocol_version.into(),
cfg_peer.osk_domain_separator.try_into()?,
)?;
}
@@ -607,8 +608,8 @@ impl CliArgs {
/// generate secret and public keys, store in files according to the paths passed as arguments
pub fn generate_and_save_keypair(secret_key: PathBuf, public_key: PathBuf) -> anyhow::Result<()> {
let mut ssk = crate::protocol::SSk::random();
let mut spk = crate::protocol::SPk::random();
let mut ssk = crate::protocol::basic_types::SSk::random();
let mut spk = crate::protocol::basic_types::SPk::random();
StaticKem.keygen(ssk.secret_mut(), spk.deref_mut())?;
ssk.store_secret(secret_key)?;
spk.store(public_key)

View File

@@ -7,20 +7,19 @@
//! - TODO: support `~` in <https://github.com/rosenpass/rosenpass/issues/237>
//! - TODO: provide tooling to create config file from shell <https://github.com/rosenpass/rosenpass/issues/247>
use crate::protocol::{SPk, SSk};
use rosenpass_util::file::LoadValue;
use std::{
collections::HashSet,
fs,
io::Write,
net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs},
path::{Path, PathBuf},
};
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::{collections::HashSet, fs, io::Write};
use anyhow::{bail, ensure};
use rosenpass_util::file::{fopen_w, Visibility};
use serde::{Deserialize, Serialize};
use rosenpass_util::file::{fopen_w, LoadValue, Visibility};
use crate::protocol::basic_types::{SPk, SSk};
use crate::protocol::osk_domain_separator::OskDomainSeparator;
use crate::app_server::AppServer;
#[cfg(feature = "experiment_api")]
@@ -36,6 +35,7 @@ fn empty_api_config() -> crate::api::config::ApiConfig {
///
/// i.e. configuration for the `rosenpass exchange` and `rosenpass exchange-config` commands
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Rosenpass {
// TODO: Raise error if secret key or public key alone is set during deserialization
// SEE: https://github.com/serde-rs/serde/issues/2793
@@ -77,6 +77,7 @@ pub struct Rosenpass {
/// Public key and secret key locations.
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)]
#[serde(deny_unknown_fields)]
pub struct Keypair {
/// path to the public key file
pub public_key: PathBuf,
@@ -104,6 +105,7 @@ impl Keypair {
///
/// - TODO: replace this type with [`log::LevelFilter`], also see <https://github.com/rosenpass/rosenpass/pull/246>
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Copy, Clone)]
#[serde(deny_unknown_fields)]
pub enum Verbosity {
Quiet,
Verbose,
@@ -111,6 +113,7 @@ pub enum Verbosity {
/// The protocol version to be used by a peer.
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Copy, Clone, Default)]
#[serde(deny_unknown_fields)]
pub enum ProtocolVersion {
#[default]
V02,
@@ -119,6 +122,7 @@ pub enum ProtocolVersion {
/// Configuration data for a single Rosenpass peer
#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RosenpassPeer {
/// path to the public key of the peer
pub public_key: PathBuf,
@@ -150,10 +154,78 @@ pub struct RosenpassPeer {
#[serde(default)]
/// The protocol version to use for the exchange
pub protocol_version: ProtocolVersion,
/// Allows using a custom domain separator
#[serde(flatten)]
pub osk_domain_separator: RosenpassPeerOskDomainSeparator,
}
/// Configuration for [crate::protocol::osk_domain_separator::OskDomainSeparator]
///
/// Refer to its documentation for more information and examples of how to use this.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RosenpassPeerOskDomainSeparator {
/// If Rosenpass is used for purposes other then securing WireGuard,
/// a custom domain separator and domain separator must be specified.
///
/// Use `osk_organization` to indicate the organization who specifies the use case
/// and `osk_label` for a specific purpose within that organization.
///
/// ```toml
/// [[peer]]
/// public_key = "my_public_key"
/// ...
/// osk_organization = "myorg.com"
/// osk_label = ["My Custom Messenger app"]
/// ```
pub osk_organization: Option<String>,
// If Rosenpass is used for purposes other then securing WireGuard,
/// a custom domain separator and domain separator must be specified.
///
/// Use `osk_organization` to indicate the organization who specifies the use case
/// and `osk_label` for a specific purpose within that organization.
///
/// ```toml
/// [[peer]]
/// public_key = "my_public_key"
/// ...
/// osk_namespace = "myorg.com"
/// osk_label = ["My Custom Messenger app"]
/// ```
pub osk_label: Option<Vec<String>>,
}
impl RosenpassPeerOskDomainSeparator {
pub fn org_and_label(&self) -> anyhow::Result<Option<(&String, &Vec<String>)>> {
match (&self.osk_organization, &self.osk_label) {
(None, None) => Ok(None),
(Some(org), Some(label)) => Ok(Some((&org, &label))),
(Some(_), None) => bail!("Specified osk_organization but not osk_label in config file. You need to specify both, or none."),
(None, Some(_)) => bail!("Specified osk_label but not osk_organization in config file. You need to specify both, or none."),
}
}
pub fn validate(&self) -> anyhow::Result<()> {
let _org_and_label: Option<(_, _)> = self.org_and_label()?;
Ok(())
}
}
impl TryFrom<RosenpassPeerOskDomainSeparator> for OskDomainSeparator {
type Error = anyhow::Error;
fn try_from(val: RosenpassPeerOskDomainSeparator) -> anyhow::Result<Self> {
match val.org_and_label()? {
None => Ok(OskDomainSeparator::default()),
Some((org, label)) => Ok(OskDomainSeparator::custom_utf8(org, label)),
}
}
}
/// Information for supplying exchanged keys directly to WireGuard
#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WireGuard {
/// Name of the WireGuard interface to supply with pre-shared keys generated by the Rosenpass
/// key exchange
@@ -337,6 +409,10 @@ impl Rosenpass {
);
}
}
if let Err(e) = peer.osk_domain_separator.validate() {
bail!("Invalid OSK domain separation configuration for peer {i}: {e}");
}
}
Ok(())

View File

@@ -295,25 +295,21 @@ hash_domain_ns!(
/// We do recommend that third parties base their specific domain separators
/// on a internet domain and/or mix in much more specific information.
///
/// We only really use this to derive a output key for wireguard; see [osk].
///
/// See [_ckextract].
///
/// # Examples
///
/// See the [module](self) documentation on how to use the hash domains in general.
_ckextract, _user, "user");
_ckextract, cke_user, "user");
hash_domain_ns!(
/// Chaining key domain separator for any rosenpass specific purposes.
///
/// We only really use this to derive a output key for wireguard; see [osk].
///
/// See [_ckextract].
///
/// # Examples
///
/// See the [module](self) documentation on how to use the hash domains in general.
_user, _rp, "rosenpass.eu");
cke_user, cke_user_rosenpass, "rosenpass.eu");
hash_domain!(
/// Chaining key domain separator for deriving the key sent to WireGuard.
///
@@ -325,4 +321,4 @@ hash_domain!(
/// Check out its source code!
///
/// See the [module](self) documentation on how to use the hash domains in general.
_rp, osk, "wireguard psk");
cke_user_rosenpass, ext_wireguard_psk_osk, "wireguard psk");

View File

@@ -0,0 +1,38 @@
//! Key types and other fundamental types used in the Rosenpass protocol
use rosenpass_cipher_traits::primitives::{Aead, Kem};
use rosenpass_ciphers::{EphemeralKem, StaticKem, XAead, KEY_LEN};
use rosenpass_secret_memory::{Public, PublicBox, Secret};
use crate::msgs::{BISCUIT_ID_LEN, MAX_MESSAGE_LEN, SESSION_ID_LEN};
/// Static public key
///
/// Using [PublicBox] instead of [Public] because Classic McEliece keys are very large.
pub type SPk = PublicBox<{ StaticKem::PK_LEN }>;
/// Static secret key
pub type SSk = Secret<{ StaticKem::SK_LEN }>;
/// Ephemeral public key
pub type EPk = Public<{ EphemeralKem::PK_LEN }>;
pub type ESk = Secret<{ EphemeralKem::SK_LEN }>;
/// Symmetric key
pub type SymKey = Secret<KEY_LEN>;
/// Variant of [SymKey] for use cases where the value is public
pub type PublicSymKey = [u8; 32];
/// Peer ID (derived from the public key, see the hash derivations in the [whitepaper](https://rosenpass.eu/whitepaper.pdf))
pub type PeerId = Public<KEY_LEN>;
/// Session ID
pub type SessionId = Public<SESSION_ID_LEN>;
/// Biscuit ID
pub type BiscuitId = Public<BISCUIT_ID_LEN>;
/// Nonce for use with random-nonce AEAD
pub type XAEADNonce = Public<{ XAead::NONCE_LEN }>;
/// Buffer capably of holding any Rosenpass protocol message
pub type MsgBuf = Public<MAX_MESSAGE_LEN>;
/// Server-local peer number; this is just the index in [super::CryptoServer::peers]
pub type PeerNo = usize;

View File

@@ -1,12 +1,14 @@
use super::{CryptoServer, PeerPtr, SPk, SSk, SymKey};
use crate::config::ProtocolVersion;
use rosenpass_util::{
build::Build,
mem::{DiscardResultExt, SwapWithDefaultExt},
result::ensure_or,
};
use thiserror::Error;
use rosenpass_util::mem::{DiscardResultExt, SwapWithDefaultExt};
use rosenpass_util::{build::Build, result::ensure_or};
use crate::config::ProtocolVersion;
use super::basic_types::{SPk, SSk, SymKey};
use super::osk_domain_separator::OskDomainSeparator;
use super::{CryptoServer, PeerPtr};
#[derive(Debug, Clone)]
/// A pair of matching public/secret keys used to launch the crypto server.
///
@@ -47,7 +49,8 @@ impl Keypair {
/// # Example
///
/// ```rust
/// use rosenpass::protocol::{Keypair, SSk, SPk};
/// use rosenpass::protocol::basic_types::{SSk, SPk};
/// use rosenpass::protocol::Keypair;
///
/// // We have to define the security policy before using Secrets.
/// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets;
@@ -66,12 +69,13 @@ impl Keypair {
/// Creates a new "empty" key pair. All bytes are initialized to zero.
///
/// See [SSk:zero()][crate::protocol::SSk::zero] and [SPk:zero()][crate::protocol::SPk::zero], respectively.
/// See [SSk:zero()][SSk::zero] and [SPk:zero()][SPk::zero], respectively.
///
/// # Example
///
/// ```rust
/// use rosenpass::protocol::{Keypair, SSk, SPk};
/// use rosenpass::protocol::basic_types::{SSk, SPk};
/// use rosenpass::protocol::Keypair;
///
/// // We have to define the security policy before using Secrets.
/// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets;
@@ -90,7 +94,7 @@ impl Keypair {
/// Creates a new (securely-)random key pair. The mechanism is described in [rosenpass_secret_memory::Secret].
///
/// See [SSk:random()][crate::protocol::SSk::random] and [SPk:random()][crate::protocol::SPk::random], respectively.
/// See [SSk:random()][SSk::random] and [SPk:random()][SPk::random], respectively.
pub fn random() -> Self {
Self::new(SSk::random(), SPk::random())
}
@@ -127,7 +131,7 @@ pub struct MissingKeypair;
///
/// There are multiple ways of creating a crypto server:
///
/// 1. Provide the key pair at initialization time (using [CryptoServer::new][crate::protocol::CryptoServer::new])
/// 1. Provide the key pair at initialization time (using [CryptoServer::new][CryptoServer::new])
/// 2. Provide the key pair at a later time (using [BuildCryptoServer::empty])
///
/// With BuildCryptoServer, you can gradually configure parameters as they become available.
@@ -145,19 +149,23 @@ pub struct MissingKeypair;
///
/// ```rust
/// use rosenpass_util::build::Build;
/// use rosenpass::protocol::{BuildCryptoServer, Keypair, PeerParams, SPk, SymKey};
/// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets;
///
/// use rosenpass::config::ProtocolVersion;
///
/// use rosenpass::protocol::basic_types::{SPk, SymKey};
/// use rosenpass::protocol::{BuildCryptoServer, Keypair, PeerParams};
/// use rosenpass::protocol::osk_domain_separator::OskDomainSeparator;
///
/// // We have to define the security policy before using Secrets.
/// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets;
/// secret_policy_use_only_malloc_secrets();
///
/// let keypair = Keypair::random();
/// let peer1 = PeerParams { psk: Some(SymKey::random()), pk: SPk::random(), protocol_version: ProtocolVersion::V02 };
/// let peer2 = PeerParams { psk: None, pk: SPk::random(), protocol_version: ProtocolVersion::V02 };
/// let peer1 = PeerParams { psk: Some(SymKey::random()), pk: SPk::random(), protocol_version: ProtocolVersion::V02, osk_domain_separator: OskDomainSeparator::default() };
/// let peer2 = PeerParams { psk: None, pk: SPk::random(), protocol_version: ProtocolVersion::V02, osk_domain_separator: OskDomainSeparator::default() };
///
/// let mut builder = BuildCryptoServer::new(Some(keypair.clone()), vec![peer1]);
/// builder.add_peer(peer2.psk.clone(), peer2.pk, ProtocolVersion::V02);
/// builder.add_peer(peer2.psk.clone(), peer2.pk, ProtocolVersion::V02, OskDomainSeparator::default());
///
/// let server = builder.build().expect("build failed");
/// assert_eq!(server.peers.len(), 2);
@@ -187,16 +195,17 @@ impl Build<CryptoServer> for BuildCryptoServer {
let mut srv = CryptoServer::new(sk, pk);
for (
idx,
PeerParams {
for (idx, params) in self.peers.into_iter().enumerate() {
let PeerParams {
psk,
pk,
protocol_version,
},
) in self.peers.into_iter().enumerate()
{
let PeerPtr(idx2) = srv.add_peer(psk, pk, protocol_version.into())?;
osk_domain_separator,
} = params;
let PeerPtr(idx2) =
srv.add_peer(psk, pk, protocol_version.into(), osk_domain_separator)?;
assert!(idx == idx2, "Peer id changed during CryptoServer construction from {idx} to {idx2}. This is a developer error.")
}
@@ -205,13 +214,13 @@ impl Build<CryptoServer> for BuildCryptoServer {
}
#[derive(Debug)]
/// Cryptographic key(s) identifying the connected [peer][crate::protocol::Peer] ("client")
/// Cryptographic key(s) identifying the connected [peer][super::Peer] ("client")
/// for a given session that is being managed by the crypto server.
///
/// Each peer must be identified by a [public key (SPk)][crate::protocol::SPk].
/// Optionally, a [symmetric key (SymKey)][crate::protocol::SymKey]
/// Each peer must be identified by a [public key (SPk)][SPk].
/// Optionally, a [symmetric key (SymKey)][SymKey]
/// can be provided when setting up the connection.
/// For more information on the intended usage and security considerations, see [Peer::psk][crate::protocol::Peer::psk] and [Peer::spkt][crate::protocol::Peer::spkt].
/// For more information on the intended usage and security considerations, see [Peer::psk][super::Peer::psk] and [Peer::spkt][super::Peer::spkt].
pub struct PeerParams {
/// Pre-shared (symmetric) encryption keys that should be used with this peer.
pub psk: Option<SymKey>,
@@ -219,6 +228,7 @@ pub struct PeerParams {
pub pk: SPk,
/// The used protocol version.
pub protocol_version: ProtocolVersion,
pub osk_domain_separator: OskDomainSeparator,
}
impl BuildCryptoServer {
@@ -317,13 +327,16 @@ impl BuildCryptoServer {
///
/// ```rust
/// use rosenpass::config::ProtocolVersion;
///
/// use rosenpass_util::build::Build;
/// use rosenpass::protocol::basic_types::{SymKey, SPk};
/// use rosenpass::protocol::{BuildCryptoServer, Keypair};
/// use rosenpass::protocol::osk_domain_separator::OskDomainSeparator;
///
/// // We have to define the security policy before using Secrets.
/// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets;
/// secret_policy_use_only_malloc_secrets();
///
/// use rosenpass_util::build::Build;
/// use rosenpass::protocol::{BuildCryptoServer, Keypair, SymKey, SPk};
///
/// // Deferred initialization: Create builder first, add some peers later
/// let keypair_option = Some(Keypair::random());
/// let mut builder = BuildCryptoServer::new(keypair_option, Vec::new());
@@ -335,7 +348,7 @@ impl BuildCryptoServer {
/// // Now we've found a peer that should be added to the configuration
/// let pre_shared_key = SymKey::random();
/// let public_key = SPk::random();
/// builder.with_added_peer(Some(pre_shared_key.clone()), public_key.clone(), ProtocolVersion::V02);
/// builder.with_added_peer(Some(pre_shared_key.clone()), public_key.clone(), ProtocolVersion::V02, OskDomainSeparator::default());
///
/// // New server instances will then start with the peer being registered already
/// let server = builder.build().expect("build failed");
@@ -350,12 +363,14 @@ impl BuildCryptoServer {
psk: Option<SymKey>,
pk: SPk,
protocol_version: ProtocolVersion,
osk_domain_separator: OskDomainSeparator,
) -> &mut Self {
// TODO: Check here already whether peer was already added
self.peers.push(PeerParams {
psk,
pk,
protocol_version,
osk_domain_separator,
});
self
}
@@ -366,9 +381,10 @@ impl BuildCryptoServer {
psk: Option<SymKey>,
pk: SPk,
protocol_version: ProtocolVersion,
osk_domain_separator: OskDomainSeparator,
) -> PeerPtr {
let id = PeerPtr(self.peers.len());
self.with_added_peer(psk, pk, protocol_version);
self.with_added_peer(psk, pk, protocol_version, osk_domain_separator);
id
}
@@ -381,19 +397,23 @@ impl BuildCryptoServer {
/// Extracting the server configuration from a builder:
///
/// ```rust
/// // We have to define the security policy before using Secrets.
/// use rosenpass_util::build::Build;
/// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets;
///
/// use rosenpass::config::ProtocolVersion;
/// use rosenpass::hash_domains::protocol;
/// use rosenpass_secret_memory::secret_policy_use_only_malloc_secrets;
/// secret_policy_use_only_malloc_secrets();
///
/// use rosenpass_util::build::Build;
/// use rosenpass::protocol::{BuildCryptoServer, Keypair, SymKey, SPk};
/// use rosenpass::protocol::basic_types::{SymKey, SPk};
/// use rosenpass::protocol::{BuildCryptoServer, Keypair};
/// use rosenpass::protocol::osk_domain_separator::OskDomainSeparator;
///
/// // We have to define the security policy before using Secrets.
/// secret_policy_use_only_malloc_secrets();
///
/// let keypair = Keypair::random();
/// let peer_pk = SPk::random();
/// let mut builder = BuildCryptoServer::new(Some(keypair.clone()), vec![]);
/// builder.add_peer(None, peer_pk, ProtocolVersion::V02);
/// builder.add_peer(None, peer_pk, ProtocolVersion::V02, OskDomainSeparator::default());
///
/// // Extract configuration parameters from the decomissioned builder
/// let (keypair_option, peers) = builder.take_parts();

View File

@@ -0,0 +1,64 @@
//! Constants and configuration values used in the rosenpass core protocol
use crate::msgs::MAC_SIZE;
use super::timing::Timing;
/// Time after which the responder attempts to rekey the session
///
/// 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;
/// Time after which the initiator attempts to rekey the session.
///
/// This happens ten seconds after [REKEY_AFTER_TIME_RESPONDER], so
/// parties would usually switch roles after every handshake.
///
/// From the wireguard paper: rekey every two minutes,
/// discard the key if no rekey is achieved within three
pub const REKEY_AFTER_TIME_INITIATOR: Timing = 130.0;
/// Time after which either party rejects the current key.
///
/// At this point a new key should have been negotiated.
///
/// Rejection happens 50-60 seconds after key renegotiation
/// to allow for a graceful handover.
/// From the wireguard paper: rekey every two minutes,
/// discard the key if no rekey is achieved within three
pub const REJECT_AFTER_TIME: Timing = 180.0;
/// The length of the `cookie_secret` in the [whitepaper](https://rosenpass.eu/whitepaper.pdf)
pub const COOKIE_SECRET_LEN: usize = MAC_SIZE;
/// The life time of the `cookie_secret` in the [whitepaper](https://rosenpass.eu/whitepaper.pdf)
pub const COOKIE_SECRET_EPOCH: Timing = 120.0;
/// Length of a cookie value (see info about the cookie mechanism in the [whitepaper](https://rosenpass.eu/whitepaper.pdf))
pub const COOKIE_VALUE_LEN: usize = MAC_SIZE;
/// Time after which to delete a cookie, as the initiator, for a certain peer (see info about the cookie mechanism in the [whitepaper](https://rosenpass.eu/whitepaper.pdf))
pub const PEER_COOKIE_VALUE_EPOCH: Timing = 120.0;
/// Seconds until the biscuit key is changed; we issue biscuits
/// using one biscuit key for one epoch and store the biscuit for
/// decryption for a second epoch
///
/// The biscuit mechanism is used to make sure the responder is stateless in our protocol.
pub const BISCUIT_EPOCH: Timing = 300.0;
/// The initiator opportunistically retransmits their messages; it applies an increasing delay
/// between each retreansmission. This is the factor by which the delay grows after each
/// retransmission.
pub const RETRANSMIT_DELAY_GROWTH: Timing = 2.0;
/// The initiator opportunistically retransmits their messages; it applies an increasing delay
/// between each retreansmission. This is the initial delay between retransmissions.
pub const RETRANSMIT_DELAY_BEGIN: Timing = 0.5;
/// The initiator opportunistically retransmits their messages; it applies an increasing delay
/// between each retreansmission. This is the maximum delay between retransmissions.
pub const RETRANSMIT_DELAY_END: Timing = 10.0;
/// The initiator opportunistically retransmits their messages; it applies an increasing delay
/// between each retreansmission. This is the jitter (randomness) applied to the retransmission
/// delay.
pub const RETRANSMIT_DELAY_JITTER: Timing = 0.5;
/// This is the maximum delay that can separate two events for us to consider the events to have
/// happened at the same time.
pub const EVENT_GRACE: Timing = 0.0025;

View File

@@ -0,0 +1,98 @@
//! Cryptographic key management for cookies and biscuits used in the protocol
//!
//! Cookies in general are conceptually similar to browser cookies;
//! i.e. mechanisms to store information in the party connected to via network.
//!
//! In our case specifically we refer to any mechanisms in the Rosenpass protocol
//! where a peer stores some information in the other party that is cryptographically
//! protected using a temporary, randomly generated key. This file contains the mechanisms
//! used to store the secret keys.
//!
//! We have two cookie-mechanisms in particular:
//!
//! - Rosenpass "biscuits" — the mechanism used to make sure the Rosenpass protocol is stateless
//! with respect to the responder
//! - WireGuard's cookie mechanism to enable proof of IP ownership; Rosenpass has experimental
//! support for this mechanism
//!
//! The CookieStore type is also used to store cookie secrets sent from the responder to the
//! initiator. This is a bad design and we should separate out this functionality.
//!
//! TODO: CookieStore should not be used for cookie secrets sent from responder to initiator.
//! TODO: Move cookie lifetime management functionality into here
use rosenpass_ciphers::KEY_LEN;
use rosenpass_secret_memory::Secret;
use super::{constants::COOKIE_SECRET_LEN, timing::Timing};
/// Container for storing cookie secrets like [BiscuitKey] or [CookieSecret].
///
/// This is really just a secret key and a time stamp of creation. Concrete
/// usages (such as for the biscuit key) impose a time limit about how long
/// a key can be used and the time of creation is used to impose that time limit.
///
/// # Examples
///
/// ```
/// use rosenpass_util::time::Timebase;
/// use rosenpass::protocol::{timing::BCE, basic_types::SymKey, cookies::CookieStore};
///
/// rosenpass_secret_memory::secret_policy_try_use_memfd_secrets();
///
/// let fixed_secret = SymKey::random();
/// let timebase = Timebase::default();
///
/// let mut store = CookieStore::<32>::new();
/// assert_ne!(store.value.secret(), SymKey::zero().secret());
/// assert_eq!(store.created_at, BCE);
///
/// let time_before_call = timebase.now();
/// store.update(&timebase, fixed_secret.secret());
/// assert_eq!(store.value.secret(), fixed_secret.secret());
/// assert!(store.created_at < timebase.now());
/// assert!(store.created_at > time_before_call);
///
/// // Same as new()
/// store.erase();
/// assert_ne!(store.value.secret(), SymKey::zero().secret());
/// assert_eq!(store.created_at, BCE);
///
/// let secret_before_call = store.value.clone();
/// let time_before_call = timebase.now();
/// store.randomize(&timebase);
/// assert_ne!(store.value.secret(), secret_before_call.secret());
/// assert!(store.created_at < timebase.now());
/// assert!(store.created_at > time_before_call);
/// ```
#[derive(Debug)]
pub struct CookieStore<const N: usize> {
/// Time of creation of the secret key
pub created_at: Timing,
/// The secret key
pub value: Secret<N>,
}
/// Stores cookie secret, which is used to create a rotating the cookie value
///
/// Concrete value is in [super::CryptoServer::cookie_secrets].
///
/// The pointer type is [super::ServerCookieSecretPtr].
pub type CookieSecret = CookieStore<COOKIE_SECRET_LEN>;
/// Storage for our biscuit keys.
///
/// The biscuit keys encrypt what we call "biscuits".
/// These biscuits contain the responder state for a particular handshake. By moving
/// state into these biscuits, we make sure the responder is stateless.
///
/// A Biscuit is like a fancy cookie. To avoid state disruption attacks,
/// the responder doesn't store state. Instead the state is stored in a
/// Biscuit, that is encrypted using the [BiscuitKey] which is only known to
/// the Responder. Thus secrecy of the Responder state is not violated, still
/// the responder can avoid storing this state.
///
/// Concrete value is in [super::CryptoServer::biscuit_keys].
///
/// The pointer type is [super::BiscuitKeyPtr].
pub type BiscuitKey = CookieStore<KEY_LEN>;

View File

@@ -0,0 +1,45 @@
//! Quick lookup of values in [super::CryptoServer]
use std::collections::HashMap;
use super::basic_types::{PeerId, PeerNo, SessionId};
use super::KnownResponseHash;
/// Maps various keys to peer (numbers).
///
/// See:
/// - [super::CryptoServer::index]
/// - [super::CryptoServer::peers]
/// - [PeerNo]
/// - [super::PeerPtr]
/// - [super::Peer]
pub type PeerIndex = HashMap<PeerIndexKey, PeerNo>;
/// We maintain various indices in [super::CryptoServer::index], mapping some key to a particular
/// [PeerNo], i.e. to an index in [super::CryptoServer::peers]. These are the possible index key.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum PeerIndexKey {
/// Lookup of a particular peer given the [PeerId], i.e. a value derived from the peers public
/// key as created by [super::CryptoServer::pidm] or [super::Peer::pidt].
///
/// The peer id is used by the initiator to tell the responder about its identity in
/// [crate::msgs::InitHello].
///
/// See also the pointer types [super::PeerPtr].
Peer(PeerId),
/// Lookup of a particular session id.
///
/// This is used to look up both established sessions (see
/// [super::CryptoServer::lookup_session]) and ongoing handshakes (see [super::CryptoServer::lookup_handshake]).
///
/// Lookup of a peer to get an established session or a handshake is sufficient, because a peer
/// contains a limited number of sessions and handshakes ([super::Peer::session] and [super::Peer::handshake] respectively).
///
/// See also the pointer types [super::IniHsPtr] and [super::SessionPtr].
Sid(SessionId),
/// Lookup of a cached response ([crate::msgs::Envelope]<[crate::msgs::EmptyData]>) to an [crate::msgs::InitConf] (i.e.
/// [crate::msgs::Envelope]<[crate::msgs::InitConf]>) message.
///
/// See [super::KnownInitConfResponsePtr] on how this value is maintained.
KnownInitConfResponse(KnownResponseHash),
}

View File

@@ -24,12 +24,15 @@
//!
//! ```
//! use std::ops::DerefMut;
//!
//! use rosenpass_secret_memory::policy::*;
//! use rosenpass_cipher_traits::primitives::Kem;
//! use rosenpass_ciphers::StaticKem;
//! use rosenpass::{
//! protocol::{SSk, SPk, MsgBuf, PeerPtr, CryptoServer, SymKey},
//! };
//!
//! use rosenpass::protocol::basic_types::{SSk, SPk, MsgBuf, SymKey};
//! use rosenpass::protocol::{PeerPtr, CryptoServer};
//! use rosenpass::protocol::osk_domain_separator::OskDomainSeparator;
//!
//! # fn main() -> anyhow::Result<()> {
//! // Set security policy for storing secrets
//!
@@ -50,8 +53,8 @@
//! 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, ProtocolVersion::V03)?;
//! b.add_peer(Some(psk), peer_a_pk, ProtocolVersion::V03)?;
//! a.add_peer(Some(psk.clone()), peer_b_pk, ProtocolVersion::V03, OskDomainSeparator::default())?;
//! b.add_peer(Some(psk), peer_a_pk, ProtocolVersion::V03, OskDomainSeparator::default())?;
//!
//! // declare buffers for message exchange
//! let (mut a_buf, mut b_buf) = (MsgBuf::zero(), MsgBuf::zero());
@@ -76,8 +79,20 @@
//! ```
mod build_crypto_server;
pub use build_crypto_server::*;
pub mod basic_types;
pub mod constants;
pub mod cookies;
pub mod index;
pub mod osk_domain_separator;
pub mod testutils;
pub mod timing;
pub mod zerocopy;
#[allow(clippy::module_inception)]
mod protocol;
pub use build_crypto_server::*;
pub use protocol::*;
#[cfg(test)]
mod test;

View File

@@ -0,0 +1,91 @@
//! Management of domain separators for the OSK (output key) in the rosenpass protocol
//!
//! The domain separator is there to ensure that keys are bound to the purpose they are used for.
//!
//! See the whitepaper section on protocol extensions for more details on how this is used.
//!
//! # See also
//!
//! - [crate::protocol::Peer]
//! - [crate::protocol::CryptoServer::add_peer]
//! - [crate::protocol::CryptoServer::osk]
//!
//! # Examples
//!
//! There are some basic examples of using custom domain separators in the examples of
//! [super::CryptoServer::poll]. Look for the test function `test_osk_label_mismatch()`
//! in particular.
use rosenpass_ciphers::subtle::keyed_hash::KeyedHash;
use rosenpass_util::result::OkExt;
use crate::hash_domains;
use super::basic_types::PublicSymKey;
/// The OSK (output shared key) domain separator to use for a specific peer
///
#[derive(Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Default)]
pub enum OskDomainSeparator {
/// By default we use the domain separator that indicates that the resulting keys
/// are used by WireGuard to establish a connection
#[default]
ExtensionWireguardPsk,
/// Used for user-defined domain separators
Custom {
/// A globally unique string identifying the vendor or group who defines this domain
/// separator (we use our domain ourselves "rosenpass.eu")
namespace: Vec<u8>,
/// Any custom labels within that namespace. Could be descriptive prose.
labels: Vec<Vec<u8>>,
},
}
impl OskDomainSeparator {
/// Construct [OskDomainSeparator::ExtensionWireguardPsk]
pub fn for_wireguard_psk() -> Self {
Self::ExtensionWireguardPsk
}
/// Construct [OskDomainSeparator::Custom] from strings
pub fn custom_utf8<I, T>(namespace: &str, label: I) -> Self
where
I: IntoIterator<Item = T>,
T: AsRef<str>,
{
let namespace = namespace.as_bytes().to_owned();
let labels = label
.into_iter()
.map(|e| e.as_ref().as_bytes().to_owned())
.collect::<Vec<_>>();
Self::Custom { namespace, labels }
}
/// Variant of [Self::custom_utf8] that takes just one label (instead of a sequence)
pub fn custom_utf8_single_label(namespace: &str, label: &str) -> Self {
Self::custom_utf8(namespace, std::iter::once(label))
}
/// The domain separator is not just an encoded string, it instead uses
/// [rosenpass_ciphers::hash_domain::HashDomain], starting from [hash_domains::cke_user].
///
/// This means, that the domain separator is really a sequence of multiple different domain
/// separators, each of which is allowed to be quite long. This is very useful as it allows
/// users to avoid specifying complex, prosaic domain separators. To ensure that this does not
/// force us create extra overhead when the protocol is executed, this sequence of strings is
/// compressed into a single, fixed-length hash of all the inputs. This hash could be created
/// at program startup and cached.
///
/// This function generates this fixed-length hash.
pub fn compress_with(&self, hash_choice: KeyedHash) -> anyhow::Result<PublicSymKey> {
use OskDomainSeparator as O;
match &self {
O::ExtensionWireguardPsk => hash_domains::ext_wireguard_psk_osk(hash_choice),
O::Custom { namespace, labels } => hash_domains::cke_user(hash_choice)?
.mix(namespace)?
.mix_many(labels)?
.into_value()
.ok(),
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,703 @@
use std::{borrow::BorrowMut, fmt::Display, net::SocketAddrV4, ops::DerefMut};
use anyhow::{Context, Result};
use serial_test::serial;
use zerocopy::{AsBytes, FromBytes, FromZeroes};
use rosenpass_cipher_traits::primitives::Kem;
use rosenpass_ciphers::StaticKem;
use rosenpass_secret_memory::Public;
use rosenpass_util::mem::DiscardResultExt;
use crate::msgs::{EmptyData, Envelope, InitConf, InitHello, MsgType, RespHello, MAX_MESSAGE_LEN};
use super::basic_types::{MsgBuf, SPk, SSk, SymKey};
use super::constants::REKEY_AFTER_TIME_RESPONDER;
use super::osk_domain_separator::OskDomainSeparator;
use super::zerocopy::{truncating_cast_into, truncating_cast_into_nomut};
use super::{
CryptoServer, HandleMsgResult, HostIdentification, KnownInitConfResponsePtr, PeerPtr,
PollResult, ProtocolVersion,
};
struct VecHostIdentifier(Vec<u8>);
impl HostIdentification for VecHostIdentifier {
fn encode(&self) -> &[u8] {
&self.0
}
}
impl Display for VecHostIdentifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl From<Vec<u8>> for VecHostIdentifier {
fn from(v: Vec<u8>) -> Self {
VecHostIdentifier(v)
}
}
fn setup_logging() {
use std::io::Write;
let mut log_builder = env_logger::Builder::from_default_env(); // sets log level filter from environment (or defaults)
log_builder.filter_level(log::LevelFilter::Info);
log_builder.format_timestamp_nanos();
log_builder.format(|buf, record| {
let ts_format = buf.timestamp_nanos().to_string();
writeln!(buf, "{}: {}", &ts_format[14..], record.args())
});
let _ = log_builder.try_init();
}
#[test]
#[serial]
fn handles_incorrect_size_messages_v02() {
handles_incorrect_size_messages(ProtocolVersion::V02)
}
#[test]
#[serial]
fn handles_incorrect_size_messages_v03() {
handles_incorrect_size_messages(ProtocolVersion::V03)
}
/// 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(protocol_version: ProtocolVersion) {
setup_logging();
rosenpass_secret_memory::secret_policy_try_use_memfd_secrets();
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(protocol_version).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());
while 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);
}
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!(res.is_err()); // handle_msg should raise an error
assert!(!resbuf.iter().any(|x| *x != 0)); // 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
let (mut sk, mut pk) = (SSk::zero(), SPk::zero());
StaticKem.keygen(sk.secret_mut(), pk.deref_mut())?;
Ok((sk, pk))
}
fn make_server_pair(protocol_version: ProtocolVersion) -> 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,
protocol_version.clone(),
OskDomainSeparator::default(),
)?;
b.add_peer(
Some(psk),
pka,
protocol_version,
OskDomainSeparator::default(),
)?;
Ok((a, b))
}
#[test]
#[serial]
fn test_regular_exchange_v02() {
test_regular_exchange(ProtocolVersion::V02)
}
#[test]
#[serial]
fn test_regular_exchange_v03() {
test_regular_exchange(ProtocolVersion::V03)
}
fn test_regular_exchange(protocol_version: ProtocolVersion) {
setup_logging();
rosenpass_secret_memory::secret_policy_try_use_memfd_secrets();
stacker::grow(8 * 1024 * 1024, || {
type MsgBufPlus = Public<MAX_MESSAGE_LEN>;
let (mut a, mut b) = make_server_pair(protocol_version).unwrap();
let mut a_to_b_buf = MsgBufPlus::zero();
let mut b_to_a_buf = MsgBufPlus::zero();
let ip_a: SocketAddrV4 = "127.0.0.1:8080".parse().unwrap();
let mut ip_addr_port_a = ip_a.ip().octets().to_vec();
ip_addr_port_a.extend_from_slice(&ip_a.port().to_be_bytes());
let _ip_b: SocketAddrV4 = "127.0.0.1:8081".parse().unwrap();
let init_hello_len = a.initiate_handshake(PeerPtr(0), &mut *a_to_b_buf).unwrap();
let init_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap();
assert_eq!(init_msg_type, MsgType::InitHello);
//B handles InitHello, sends RespHello
let HandleMsgResult { resp, .. } = b
.handle_msg(&a_to_b_buf.as_slice()[..init_hello_len], &mut *b_to_a_buf)
.unwrap();
let resp_hello_len = resp.unwrap();
let resp_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap();
assert_eq!(resp_msg_type, MsgType::RespHello);
let HandleMsgResult {
resp,
exchanged_with,
} = a
.handle_msg(&b_to_a_buf[..resp_hello_len], &mut *a_to_b_buf)
.unwrap();
let init_conf_len = resp.unwrap();
let init_conf_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap();
assert_eq!(exchanged_with, Some(PeerPtr(0)));
assert_eq!(init_conf_msg_type, MsgType::InitConf);
//B handles InitConf, sends EmptyData
let HandleMsgResult {
resp: _,
exchanged_with,
} = b
.handle_msg(&a_to_b_buf.as_slice()[..init_conf_len], &mut *b_to_a_buf)
.unwrap();
let empty_data_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap();
assert_eq!(exchanged_with, Some(PeerPtr(0)));
assert_eq!(empty_data_msg_type, MsgType::EmptyData);
});
}
#[test]
#[serial]
fn test_regular_init_conf_retransmit_v02() {
test_regular_init_conf_retransmit(ProtocolVersion::V02)
}
#[test]
#[serial]
fn test_regular_init_conf_retransmit_v03() {
test_regular_init_conf_retransmit(ProtocolVersion::V03)
}
fn test_regular_init_conf_retransmit(protocol_version: ProtocolVersion) {
setup_logging();
rosenpass_secret_memory::secret_policy_try_use_memfd_secrets();
stacker::grow(8 * 1024 * 1024, || {
type MsgBufPlus = Public<MAX_MESSAGE_LEN>;
let (mut a, mut b) = make_server_pair(protocol_version).unwrap();
let mut a_to_b_buf = MsgBufPlus::zero();
let mut b_to_a_buf = MsgBufPlus::zero();
let ip_a: SocketAddrV4 = "127.0.0.1:8080".parse().unwrap();
let mut ip_addr_port_a = ip_a.ip().octets().to_vec();
ip_addr_port_a.extend_from_slice(&ip_a.port().to_be_bytes());
let _ip_b: SocketAddrV4 = "127.0.0.1:8081".parse().unwrap();
let init_hello_len = a.initiate_handshake(PeerPtr(0), &mut *a_to_b_buf).unwrap();
let init_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap();
assert_eq!(init_msg_type, MsgType::InitHello);
//B handles InitHello, sends RespHello
let HandleMsgResult { resp, .. } = b
.handle_msg(&a_to_b_buf.as_slice()[..init_hello_len], &mut *b_to_a_buf)
.unwrap();
let resp_hello_len = resp.unwrap();
let resp_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap();
assert_eq!(resp_msg_type, MsgType::RespHello);
//A handles RespHello, sends InitConf, exchanges keys
let HandleMsgResult {
resp,
exchanged_with,
} = a
.handle_msg(&b_to_a_buf[..resp_hello_len], &mut *a_to_b_buf)
.unwrap();
let init_conf_len = resp.unwrap();
let init_conf_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap();
assert_eq!(exchanged_with, Some(PeerPtr(0)));
assert_eq!(init_conf_msg_type, MsgType::InitConf);
//B handles InitConf, sends EmptyData
let HandleMsgResult {
resp: _,
exchanged_with,
} = b
.handle_msg(&a_to_b_buf.as_slice()[..init_conf_len], &mut *b_to_a_buf)
.unwrap();
let empty_data_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap();
assert_eq!(exchanged_with, Some(PeerPtr(0)));
assert_eq!(empty_data_msg_type, MsgType::EmptyData);
//B handles InitConf again, sends EmptyData
let HandleMsgResult {
resp: _,
exchanged_with,
} = b
.handle_msg(&a_to_b_buf.as_slice()[..init_conf_len], &mut *b_to_a_buf)
.unwrap();
let empty_data_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap();
assert!(exchanged_with.is_none());
assert_eq!(empty_data_msg_type, MsgType::EmptyData);
});
}
#[test]
#[serial]
#[cfg(feature = "experiment_cookie_dos_mitigation")]
fn cookie_reply_mechanism_responder_under_load_v02() {
cookie_reply_mechanism_initiator_bails_on_message_under_load(ProtocolVersion::V02)
}
#[test]
#[serial]
#[cfg(feature = "experiment_cookie_dos_mitigation")]
fn cookie_reply_mechanism_responder_under_load_v03() {
cookie_reply_mechanism_initiator_bails_on_message_under_load(ProtocolVersion::V03)
}
#[cfg(feature = "experiment_cookie_dos_mitigation")]
fn cookie_reply_mechanism_responder_under_load(protocol_version: ProtocolVersion) {
use std::{thread::sleep, time::Duration};
use super::{Lifecycle, MortalExt};
setup_logging();
rosenpass_secret_memory::secret_policy_try_use_memfd_secrets();
stacker::grow(8 * 1024 * 1024, || {
type MsgBufPlus = Public<MAX_MESSAGE_LEN>;
let (mut a, mut b) = make_server_pair(protocol_version.clone()).unwrap();
let mut a_to_b_buf = MsgBufPlus::zero();
let mut b_to_a_buf = MsgBufPlus::zero();
let ip_a: SocketAddrV4 = "127.0.0.1:8080".parse().unwrap();
let mut ip_addr_port_a = ip_a.ip().octets().to_vec();
ip_addr_port_a.extend_from_slice(&ip_a.port().to_be_bytes());
let _ip_b: SocketAddrV4 = "127.0.0.1:8081".parse().unwrap();
let init_hello_len = a.initiate_handshake(PeerPtr(0), &mut *a_to_b_buf).unwrap();
let socket_addr_a = std::net::SocketAddr::V4(ip_a);
let mut ip_addr_port_a = match socket_addr_a.ip() {
std::net::IpAddr::V4(ipv4) => ipv4.octets().to_vec(),
std::net::IpAddr::V6(ipv6) => ipv6.octets().to_vec(),
};
ip_addr_port_a.extend_from_slice(&socket_addr_a.port().to_be_bytes());
let ip_addr_port_a: VecHostIdentifier = ip_addr_port_a.into();
//B handles handshake under load, should send cookie reply message with invalid cookie
let HandleMsgResult { resp, .. } = b
.handle_msg_under_load(
&a_to_b_buf.as_slice()[..init_hello_len],
&mut *b_to_a_buf,
&ip_addr_port_a,
)
.unwrap();
let cookie_reply_len = resp.unwrap();
//A handles cookie reply message
a.handle_msg(&b_to_a_buf[..cookie_reply_len], &mut *a_to_b_buf)
.unwrap();
assert_eq!(PeerPtr(0).cv().lifecycle(&a), Lifecycle::Young);
let expected_cookie_value =
crate::hash_domains::cookie_value(protocol_version.keyed_hash())
.unwrap()
.mix(
b.active_or_retired_cookie_secrets()[0]
.unwrap()
.get(&b)
.value
.secret(),
)
.unwrap()
.mix(ip_addr_port_a.encode())
.unwrap()
.into_value()[..16]
.to_vec();
assert_eq!(
PeerPtr(0).cv().get(&a).map(|x| &x.value.secret()[..]),
Some(&expected_cookie_value[..])
);
let retx_init_hello_len = loop {
match a.poll().unwrap() {
PollResult::SendRetransmission(peer) => {
break a.retransmit_handshake(peer, &mut *a_to_b_buf).unwrap();
}
PollResult::Sleep(time) => {
sleep(Duration::from_secs_f64(time));
}
_ => {}
}
};
let retx_msg_type: MsgType = a_to_b_buf.value[0].try_into().unwrap();
assert_eq!(retx_msg_type, MsgType::InitHello);
//B handles retransmitted message
let HandleMsgResult { resp, .. } = b
.handle_msg_under_load(
&a_to_b_buf.as_slice()[..retx_init_hello_len],
&mut *b_to_a_buf,
&ip_addr_port_a,
)
.unwrap();
let _resp_hello_len = resp.unwrap();
let resp_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap();
assert_eq!(resp_msg_type, MsgType::RespHello);
});
}
#[test]
#[serial]
#[cfg(feature = "experiment_cookie_dos_mitigation")]
fn cookie_reply_mechanism_initiator_bails_on_message_under_load_v02() {
cookie_reply_mechanism_initiator_bails_on_message_under_load(ProtocolVersion::V02)
}
#[test]
#[serial]
#[cfg(feature = "experiment_cookie_dos_mitigation")]
fn cookie_reply_mechanism_initiator_bails_on_message_under_load_v03() {
cookie_reply_mechanism_initiator_bails_on_message_under_load(ProtocolVersion::V03)
}
#[cfg(feature = "experiment_cookie_dos_mitigation")]
fn cookie_reply_mechanism_initiator_bails_on_message_under_load(protocol_version: ProtocolVersion) {
setup_logging();
rosenpass_secret_memory::secret_policy_try_use_memfd_secrets();
stacker::grow(8 * 1024 * 1024, || {
type MsgBufPlus = Public<MAX_MESSAGE_LEN>;
let (mut a, mut b) = make_server_pair(protocol_version).unwrap();
let mut a_to_b_buf = MsgBufPlus::zero();
let mut b_to_a_buf = MsgBufPlus::zero();
let ip_a: SocketAddrV4 = "127.0.0.1:8080".parse().unwrap();
let mut ip_addr_port_a = ip_a.ip().octets().to_vec();
ip_addr_port_a.extend_from_slice(&ip_a.port().to_be_bytes());
let ip_b: SocketAddrV4 = "127.0.0.1:8081".parse().unwrap();
//A initiates handshake
let init_hello_len = a.initiate_handshake(PeerPtr(0), &mut *a_to_b_buf).unwrap();
//B handles InitHello message, should respond with RespHello
let HandleMsgResult { resp, .. } = b
.handle_msg(&a_to_b_buf.as_slice()[..init_hello_len], &mut *b_to_a_buf)
.unwrap();
let resp_hello_len = resp.unwrap();
let resp_msg_type: MsgType = b_to_a_buf.value[0].try_into().unwrap();
assert_eq!(resp_msg_type, MsgType::RespHello);
let socket_addr_b = std::net::SocketAddr::V4(ip_b);
let mut ip_addr_port_b = [0u8; 18];
let mut ip_addr_port_b_len = 0;
match socket_addr_b.ip() {
std::net::IpAddr::V4(ipv4) => {
ip_addr_port_b[0..4].copy_from_slice(&ipv4.octets());
ip_addr_port_b_len += 4;
}
std::net::IpAddr::V6(ipv6) => {
ip_addr_port_b[0..16].copy_from_slice(&ipv6.octets());
ip_addr_port_b_len += 16;
}
};
ip_addr_port_b[ip_addr_port_b_len..ip_addr_port_b_len + 2]
.copy_from_slice(&socket_addr_b.port().to_be_bytes());
ip_addr_port_b_len += 2;
let ip_addr_port_b: VecHostIdentifier =
ip_addr_port_b[..ip_addr_port_b_len].to_vec().into();
//A handles RespHello message under load, should not send cookie reply
assert!(a
.handle_msg_under_load(
&b_to_a_buf[..resp_hello_len],
&mut *a_to_b_buf,
&ip_addr_port_b
)
.is_err());
});
}
#[test]
fn init_conf_retransmission_v02() -> Result<()> {
init_conf_retransmission(ProtocolVersion::V02)
}
#[test]
fn init_conf_retransmission_v03() -> Result<()> {
init_conf_retransmission(ProtocolVersion::V03)
}
fn init_conf_retransmission(protocol_version: ProtocolVersion) -> anyhow::Result<()> {
rosenpass_secret_memory::secret_policy_try_use_memfd_secrets();
fn keypair() -> Result<(SSk, SPk)> {
let (mut sk, mut pk) = (SSk::zero(), SPk::zero());
StaticKem.keygen(sk.secret_mut(), pk.deref_mut())?;
Ok((sk, pk))
}
fn proc_initiation(srv: &mut CryptoServer, peer: PeerPtr) -> Result<Envelope<InitHello>> {
let mut buf = MsgBuf::zero();
srv.initiate_handshake(peer, buf.as_mut_slice())?
.discard_result();
let msg = truncating_cast_into::<Envelope<InitHello>>(buf.borrow_mut())?;
Ok(msg.read())
}
fn proc_msg<Rx: AsBytes + FromBytes, Tx: AsBytes + FromBytes>(
srv: &mut CryptoServer,
rx: &Envelope<Rx>,
) -> anyhow::Result<Envelope<Tx>> {
let mut buf = MsgBuf::zero();
srv.handle_msg(rx.as_bytes(), buf.as_mut_slice())?
.resp
.context("Failed to produce RespHello message")?
.discard_result();
let msg = truncating_cast_into::<Envelope<Tx>>(buf.borrow_mut())?;
Ok(msg.read())
}
fn proc_init_hello(
srv: &mut CryptoServer,
ih: &Envelope<InitHello>,
) -> anyhow::Result<Envelope<RespHello>> {
proc_msg::<InitHello, RespHello>(srv, ih)
}
fn proc_resp_hello(
srv: &mut CryptoServer,
rh: &Envelope<RespHello>,
) -> anyhow::Result<Envelope<InitConf>> {
proc_msg::<RespHello, InitConf>(srv, rh)
}
fn proc_init_conf(
srv: &mut CryptoServer,
rh: &Envelope<InitConf>,
) -> anyhow::Result<Envelope<EmptyData>> {
proc_msg::<InitConf, EmptyData>(srv, rh)
}
fn poll(srv: &mut CryptoServer) -> anyhow::Result<()> {
// Discard all events; just apply the side effects
while !matches!(srv.poll()?, PollResult::Sleep(_)) {}
Ok(())
}
// TODO: Implement Clone on our message types
fn clone_msg<Msg: AsBytes + FromBytes>(msg: &Msg) -> anyhow::Result<Msg> {
Ok(truncating_cast_into_nomut::<Msg>(msg.as_bytes())?.read())
}
fn break_payload<Msg: AsBytes + FromBytes>(
srv: &mut CryptoServer,
peer: PeerPtr,
msg: &Envelope<Msg>,
) -> anyhow::Result<Envelope<Msg>> {
let mut msg = clone_msg(msg)?;
msg.as_bytes_mut()[memoffset::offset_of!(Envelope<Msg>, payload)] ^= 0x01;
msg.seal(peer, srv)?; // Recalculate seal; we do not want to focus on "seal broken" errs
Ok(msg)
}
fn check_faulty_proc_init_conf(srv: &mut CryptoServer, ic_broken: &Envelope<InitConf>) {
let mut buf = MsgBuf::zero();
let res = srv.handle_msg(ic_broken.as_bytes(), buf.as_mut_slice());
assert!(res.is_err());
}
// we this as a closure in orer to use the protocol_version variable in it.
let check_retransmission = |srv: &mut CryptoServer,
ic: &Envelope<InitConf>,
ic_broken: &Envelope<InitConf>,
rc: &Envelope<EmptyData>|
-> Result<()> {
// Processing the same RespHello package again leads to retransmission (i.e. exactly the
// same output)
let rc_dup = proc_init_conf(srv, ic)?;
assert_eq!(rc.as_bytes(), rc_dup.as_bytes());
// Though if we directly call handle_resp_hello() we get an error since
// retransmission is not being handled by the cryptographic code
let mut discard_resp_conf = EmptyData::new_zeroed();
let res = srv.handle_init_conf(
&ic.payload,
&mut discard_resp_conf,
protocol_version.clone().keyed_hash(),
);
assert!(res.is_err());
// Obviously, a broken InitConf message should still be rejected
check_faulty_proc_init_conf(srv, ic_broken);
Ok(())
};
let (ska, pka) = keypair()?;
let (skb, pkb) = keypair()?;
// initialize server and a pre-shared key
let mut a = CryptoServer::new(ska, pka.clone());
let mut b = CryptoServer::new(skb, pkb.clone());
// introduce peers to each other
let b_peer = a.add_peer(
None,
pkb,
protocol_version.clone(),
OskDomainSeparator::default(),
)?;
let a_peer = b.add_peer(
None,
pka,
protocol_version.clone(),
OskDomainSeparator::default(),
)?;
// Execute protocol up till the responder confirmation (EmptyData)
let ih1 = proc_initiation(&mut a, b_peer)?;
let rh1 = proc_init_hello(&mut b, &ih1)?;
let ic1 = proc_resp_hello(&mut a, &rh1)?;
let rc1 = proc_init_conf(&mut b, &ic1)?;
// Modified version of ic1 and rc1, for tests that require it
let ic1_broken = break_payload(&mut a, b_peer, &ic1)?;
assert_ne!(ic1.as_bytes(), ic1_broken.as_bytes());
// Modified version of rc1, for tests that require it
let rc1_broken = break_payload(&mut b, a_peer, &rc1)?;
assert_ne!(rc1.as_bytes(), rc1_broken.as_bytes());
// Retransmission works as designed
check_retransmission(&mut b, &ic1, &ic1_broken, &rc1)?;
// Even with a couple of poll operations in between (which clears the cache
// after a time out of two minutes…we should never hit this time out in this
// cache)
for _ in 0..4 {
poll(&mut b)?;
check_retransmission(&mut b, &ic1, &ic1_broken, &rc1)?;
}
// We can even validate that the data is coming out of the cache by changing the cache
// to use our broken messages. It does not matter that these messages are cryptographically
// broken since we insert them manually into the cache
// a_peer.known_init_conf_response()
KnownInitConfResponsePtr::insert_for_request_msg(
&mut b,
a_peer,
&ic1_broken,
rc1_broken.clone(),
);
check_retransmission(&mut b, &ic1_broken, &ic1, &rc1_broken)?;
// Lets reset to the correct message though
KnownInitConfResponsePtr::insert_for_request_msg(&mut b, a_peer, &ic1, rc1.clone());
// Again, nothing changes after calling poll
poll(&mut b)?;
check_retransmission(&mut b, &ic1, &ic1_broken, &rc1)?;
// Except if we jump forward into the future past the point where the responder
// starts to initiate rekeying; in this case, the automatic time out is triggered and the cache is cleared
super::testutils::time_travel_forward(&mut b, REKEY_AFTER_TIME_RESPONDER);
// As long as we do not call poll, everything is fine
check_retransmission(&mut b, &ic1, &ic1_broken, &rc1)?;
// But after we do, the response is gone and can not be recreated
// since the biscuit is stale
poll(&mut b)?;
check_faulty_proc_init_conf(&mut b, &ic1); // ic1 is now effectively broken
assert!(b.peers[0].known_init_conf_response.is_none()); // The cache is gone
Ok(())
}

View File

@@ -0,0 +1,54 @@
//! Helpers used in tests
use std::ops::DerefMut;
use rosenpass_cipher_traits::primitives::Kem;
use rosenpass_ciphers::StaticKem;
use super::{
basic_types::{SPk, SSk},
osk_domain_separator::OskDomainSeparator,
CryptoServer, PeerPtr, ProtocolVersion,
};
/// Helper for tests and examples
pub struct ServerForTesting {
pub peer: PeerPtr,
pub peer_keys: (SSk, SPk),
pub srv: CryptoServer,
}
/// TODO: Document that the protocol version is only used for creating the peer for testing
impl ServerForTesting {
pub fn new(protocol_version: ProtocolVersion) -> anyhow::Result<Self> {
let (mut sskm, mut spkm) = (SSk::zero(), SPk::zero());
StaticKem.keygen(sskm.secret_mut(), spkm.deref_mut())?;
let mut srv = CryptoServer::new(sskm, spkm);
let (mut sskt, mut spkt) = (SSk::zero(), SPk::zero());
StaticKem.keygen(sskt.secret_mut(), spkt.deref_mut())?;
let peer = srv.add_peer(
None,
spkt.clone(),
protocol_version,
OskDomainSeparator::default(),
)?;
let peer_keys = (sskt, spkt);
Ok(ServerForTesting {
peer,
peer_keys,
srv,
})
}
pub fn tuple(self) -> (PeerPtr, (SSk, SPk), CryptoServer) {
(self.peer, self.peer_keys, self.srv)
}
}
/// Time travel forward in time
pub fn time_travel_forward(srv: &mut CryptoServer, secs: f64) {
let dur = std::time::Duration::from_secs_f64(secs);
srv.timebase.0 = srv.timebase.0.checked_sub(dur).unwrap();
}

View File

@@ -0,0 +1,46 @@
//! Time-keeping related utilities for the Rosenpass protocol
use super::constants::EVENT_GRACE;
/// A type for time, e.g. for backoff before re-tries
pub type Timing = f64;
/// Magic time stamp to indicate some object is ancient; "Before Common Era"
///
/// This is for instance used as a magic time stamp indicating age when some
/// cryptographic object certainly needs to be refreshed.
///
/// Using this instead of Timing::MIN or Timing::INFINITY to avoid floating
/// point math weirdness.
pub const BCE: Timing = -3600.0 * 24.0 * 356.0 * 10_000.0;
/// Magic time stamp to indicate that some process is not time-limited
///
/// Actually it's eight hours; This is intentional to avoid weirdness
/// regarding unexpectedly large numbers in system APIs as this is < i16::MAX
pub const UNENDING: Timing = 3600.0 * 8.0;
/// An even `ev` has happened relative to a point in time `now`
/// if the `ev` does not lie in the future relative to now.
///
/// An event lies in the future relative to `now` if
/// does not lie in the past or present.
///
/// An event `ev` lies in the past if `ev < now`. It lies in the
/// present if the absolute difference between `ev` and `now` is
/// smaller than [EVENT_GRACE].
///
/// Think of this as `ev <= now` for with [EVENT_GRACE] applied.
///
/// # Examples
///
/// ```
/// use rosenpass::protocol::{timing::has_happened, constants::EVENT_GRACE};
/// assert!(has_happened(EVENT_GRACE * -1.0, 0.0));
/// assert!(has_happened(0.0, 0.0));
/// assert!(has_happened(EVENT_GRACE * 0.999, 0.0));
/// assert!(!has_happened(EVENT_GRACE * 1.001, 0.0));
/// ```
pub fn has_happened(ev: Timing, now: Timing) -> bool {
(ev - now) < EVENT_GRACE
}

View File

@@ -0,0 +1,21 @@
//! Helpers for working with the zerocopy crate
use std::mem::size_of;
use zerocopy::{FromBytes, Ref};
use crate::RosenpassError;
/// Used to parse a network message using [zerocopy]
pub fn truncating_cast_into<T: FromBytes>(
buf: &mut [u8],
) -> Result<Ref<&mut [u8], T>, RosenpassError> {
Ref::new(&mut buf[..size_of::<T>()]).ok_or(RosenpassError::BufferSizeMismatch)
}
/// Used to parse a network message using [zerocopy], mutably
pub fn truncating_cast_into_nomut<T: FromBytes>(
buf: &[u8],
) -> Result<Ref<&[u8], T>, RosenpassError> {
Ref::new(&buf[..size_of::<T>()]).ok_or(RosenpassError::BufferSizeMismatch)
}

View File

@@ -15,7 +15,7 @@ use rosenpass::api::{
supply_keypair_response_status,
};
use rosenpass::config::ProtocolVersion;
use rosenpass::protocol::SymKey;
use rosenpass::protocol::basic_types::SymKey;
use rosenpass_util::{
b64::B64Display,
file::LoadValueB64,
@@ -106,6 +106,7 @@ fn api_integration_api_setup(protocol_version: ProtocolVersion) -> anyhow::Resul
extra_params: vec![],
}),
protocol_version: protocol_version.clone(),
osk_domain_separator: Default::default(),
}],
};
@@ -127,6 +128,7 @@ fn api_integration_api_setup(protocol_version: ProtocolVersion) -> anyhow::Resul
pre_shared_key: None,
wg: None,
protocol_version: protocol_version.clone(),
osk_domain_separator: Default::default(),
}],
};

View File

@@ -17,7 +17,7 @@ use tempfile::TempDir;
use zerocopy::AsBytes;
use rosenpass::config::ProtocolVersion;
use rosenpass::protocol::SymKey;
use rosenpass::protocol::basic_types::SymKey;
struct KillChild(std::process::Child);
@@ -83,6 +83,7 @@ fn api_integration_test(protocol_version: ProtocolVersion) -> anyhow::Result<()>
pre_shared_key: None,
wg: None,
protocol_version: protocol_version.clone(),
osk_domain_separator: Default::default(),
}],
};
@@ -104,6 +105,7 @@ fn api_integration_test(protocol_version: ProtocolVersion) -> anyhow::Result<()>
pre_shared_key: None,
wg: None,
protocol_version: protocol_version.clone(),
osk_domain_separator: Default::default(),
}],
};

View File

@@ -1,21 +1,14 @@
use std::{
net::SocketAddr,
ops::DerefMut,
str::FromStr,
sync::mpsc,
thread::{self, sleep},
time::Duration,
};
use std::thread::{self, sleep};
use std::{net::SocketAddr, ops::DerefMut, str::FromStr, sync::mpsc, time::Duration};
use rosenpass::config::ProtocolVersion;
use rosenpass::{
app_server::{AppServer, AppServerTest, MAX_B64_KEY_SIZE},
protocol::{SPk, SSk, SymKey},
};
use rosenpass_cipher_traits::primitives::Kem;
use rosenpass_ciphers::StaticKem;
use rosenpass_util::{file::LoadValueB64, functional::run, mem::DiscardResultExt, result::OkExt};
use rosenpass::app_server::{AppServer, AppServerTest, MAX_B64_KEY_SIZE};
use rosenpass::protocol::basic_types::{SPk, SSk, SymKey};
use rosenpass::{config::ProtocolVersion, protocol::osk_domain_separator::OskDomainSeparator};
#[test]
fn key_exchange_with_app_server_v02() -> anyhow::Result<()> {
key_exchange_with_app_server(ProtocolVersion::V02)
@@ -69,7 +62,8 @@ fn key_exchange_with_app_server(protocol_version: ProtocolVersion) -> anyhow::Re
outfile,
broker_peer,
hostname,
protocol_version.clone(),
protocol_version,
OskDomainSeparator::default(),
)?;
srv.app_srv.event_loop()

View File

@@ -9,29 +9,49 @@ use rosenpass_cipher_traits::primitives::Kem;
use rosenpass_ciphers::StaticKem;
use rosenpass_util::result::OkExt;
use rosenpass::protocol::{
testutils::time_travel_forward, CryptoServer, HostIdentification, MsgBuf, PeerPtr, PollResult,
ProtocolVersion, SPk, SSk, SymKey, Timing, UNENDING,
};
use rosenpass::protocol::basic_types::{MsgBuf, SPk, SSk, SymKey};
use rosenpass::protocol::osk_domain_separator::OskDomainSeparator;
use rosenpass::protocol::testutils::time_travel_forward;
use rosenpass::protocol::timing::{Timing, UNENDING};
use rosenpass::protocol::{CryptoServer, HostIdentification, PeerPtr, PollResult, ProtocolVersion};
// TODO: Most of the utility functions in here should probably be moved to
// rosenpass::protocol::testutils;
#[test]
fn test_successful_exchange_with_poll_v02() -> anyhow::Result<()> {
test_successful_exchange_with_poll(ProtocolVersion::V02)
test_successful_exchange_with_poll(ProtocolVersion::V02, OskDomainSeparator::default())
}
#[test]
fn test_successful_exchange_with_poll_v03() -> anyhow::Result<()> {
test_successful_exchange_with_poll(ProtocolVersion::V03)
test_successful_exchange_with_poll(ProtocolVersion::V03, OskDomainSeparator::default())
}
fn test_successful_exchange_with_poll(protocol_version: ProtocolVersion) -> anyhow::Result<()> {
#[test]
fn test_successful_exchange_with_poll_v02_custom_domain_separator() -> anyhow::Result<()> {
test_successful_exchange_with_poll(
ProtocolVersion::V02,
OskDomainSeparator::custom_utf8_single_label("example.org", "Example Label"),
)
}
#[test]
fn test_successful_exchange_with_poll_v03_custom_domain_separator() -> anyhow::Result<()> {
test_successful_exchange_with_poll(
ProtocolVersion::V03,
OskDomainSeparator::custom_utf8_single_label("example.org", "Example Label"),
)
}
fn test_successful_exchange_with_poll(
protocol_version: ProtocolVersion,
osk_domain_separator: OskDomainSeparator,
) -> anyhow::Result<()> {
// Set security policy for storing secrets; choose the one that is faster for testing
rosenpass_secret_memory::policy::secret_policy_use_only_malloc_secrets();
let mut sim = RosenpassSimulator::new(protocol_version)?;
let mut sim = RosenpassSimulator::new(protocol_version, osk_domain_separator)?;
sim.poll_loop(150)?; // Poll 75 times
let transcript = sim.transcript;
@@ -104,7 +124,7 @@ fn test_successful_exchange_under_packet_loss(
rosenpass_secret_memory::policy::secret_policy_use_only_malloc_secrets();
// Create the simulator
let mut sim = RosenpassSimulator::new(protocol_version)?;
let mut sim = RosenpassSimulator::new(protocol_version, OskDomainSeparator::default())?;
// Make sure the servers are set to under load condition
sim.srv_a.under_load = true;
@@ -181,6 +201,94 @@ fn test_successful_exchange_under_packet_loss(
Ok(())
}
#[test]
fn test_osk_label_mismatch() -> anyhow::Result<()> {
// Set security policy for storing secrets; choose the one that is faster for testing
rosenpass_secret_memory::policy::secret_policy_use_only_malloc_secrets();
let ds_wg = OskDomainSeparator::for_wireguard_psk();
let ds_custom1 = OskDomainSeparator::custom_utf8("example.com", ["Example Label"]);
let ds_custom2 =
OskDomainSeparator::custom_utf8("example.com", ["Example Label", "Second Token"]);
// Create the simulator
let mut sim = RosenpassSimulator::new(ProtocolVersion::V03, ds_custom1.clone())?;
assert_eq!(sim.srv_a.srv.peers[0].osk_domain_separator, ds_custom1);
assert_eq!(sim.srv_b.srv.peers[0].osk_domain_separator, ds_custom1);
// Deliberately produce a label mismatch
sim.srv_b.srv.peers[0].osk_domain_separator = ds_custom2.clone();
assert_eq!(sim.srv_a.srv.peers[0].osk_domain_separator, ds_custom1);
assert_eq!(sim.srv_b.srv.peers[0].osk_domain_separator, ds_custom2);
// Perform the key exchanges
for _ in 0..300 {
let ev = sim.poll()?;
assert!(!matches!(ev, TranscriptEvent::CompletedExchange(_)),
"We deliberately provoked a mismatch in OSK domain separator, but still saw a successfully completed key exchange");
// Wait for a key exchange that failed with a KeyMismatch event
let (osk_a_custom1, osk_b_custom2) = match ev {
TranscriptEvent::FailedExchangeWithKeyMismatch(osk_a, osk_b) => {
(osk_a.clone(), osk_b.clone())
}
_ => continue,
};
// The OSKs have been produced through the call to the function CryptoServer::osk(…)
assert_eq!(
sim.srv_a.srv.osk(PeerPtr(0))?.secret(),
osk_a_custom1.secret()
);
assert_eq!(
sim.srv_b.srv.osk(PeerPtr(0))?.secret(),
osk_b_custom2.secret()
);
// They are not matching (obviously)
assert_ne!(osk_a_custom1.secret(), osk_b_custom2.secret());
// We can manually generate OSKs with matching labels
let osk_a_custom2 = sim
.srv_a
.srv
.osk_with_domain_separator(PeerPtr(0), &ds_custom2)?;
let osk_b_custom1 = sim
.srv_b
.srv
.osk_with_domain_separator(PeerPtr(0), &ds_custom1)?;
let osk_a_wg = sim
.srv_a
.srv
.osk_with_domain_separator(PeerPtr(0), &ds_wg)?;
let osk_b_wg = sim
.srv_b
.srv
.osk_with_domain_separator(PeerPtr(0), &ds_wg)?;
// The key exchange may have failed for some other reason, in this case we expect a
// successful-but-label-mismatch exchange later in the protocol
if osk_a_custom1.secret() != osk_b_custom1.secret() {
continue;
}
// But if one of the labeled keys match, all should match
assert_eq!(osk_a_custom2.secret(), osk_b_custom2.secret());
assert_eq!(osk_a_wg.secret(), osk_b_wg.secret());
// But the three keys do not match each other
assert_ne!(osk_a_custom1.secret(), osk_a_custom2.secret());
assert_ne!(osk_a_custom1.secret(), osk_a_wg.secret());
assert_ne!(osk_a_custom2.secret(), osk_a_wg.secret());
// The test succeeded
return Ok(());
}
panic!("Test did not succeed even after allowing for a large number of communication rounds");
}
type MessageType = u8;
/// Lets record the events that are produced by Rosenpass
@@ -193,6 +301,7 @@ enum TranscriptEvent {
event: ServerEvent,
},
CompletedExchange(SymKey),
FailedExchangeWithKeyMismatch(SymKey, SymKey),
}
#[derive(Debug)]
@@ -292,7 +401,10 @@ struct SimulatorServer {
impl RosenpassSimulator {
/// Set up the simulator
fn new(protocol_version: ProtocolVersion) -> anyhow::Result<Self> {
fn new(
protocol_version: ProtocolVersion,
osk_domain_separator: OskDomainSeparator,
) -> anyhow::Result<Self> {
// Set up the first server
let (mut peer_a_sk, mut peer_a_pk) = (SSk::zero(), SPk::zero());
StaticKem.keygen(peer_a_sk.secret_mut(), peer_a_pk.deref_mut())?;
@@ -305,8 +417,18 @@ impl RosenpassSimulator {
// Generate a PSK and introduce the Peers to each other.
let psk = SymKey::random();
let peer_a = srv_a.add_peer(Some(psk.clone()), peer_b_pk, protocol_version.clone())?;
let peer_b = srv_b.add_peer(Some(psk), peer_a_pk, protocol_version.clone())?;
let peer_a = srv_a.add_peer(
Some(psk.clone()),
peer_b_pk,
protocol_version.clone(),
osk_domain_separator.clone(),
)?;
let peer_b = srv_b.add_peer(
Some(psk),
peer_a_pk,
protocol_version.clone(),
osk_domain_separator.clone(),
)?;
// Set up the individual server data structures
let srv_a = SimulatorServer::new(srv_a, peer_b);
@@ -566,10 +688,18 @@ impl ServerPtr {
None => return Ok(()),
};
// Make sure the OSK of server A always comes first
let (osk_a, osk_b) = match self == ServerPtr::A {
true => (osk, other_osk),
false => (other_osk, osk),
};
// Issue the successful exchange event if the OSKs are equal;
// be careful to use constant time comparison for things like this!
if rosenpass_constant_time::memcmp(osk.secret(), other_osk.secret()) {
self.enqueue_upcoming_poll_event(sim, TE::CompletedExchange(osk));
if rosenpass_constant_time::memcmp(osk_a.secret(), osk_b.secret()) {
self.enqueue_upcoming_poll_event(sim, TE::CompletedExchange(osk_a));
} else {
self.enqueue_upcoming_poll_event(sim, TE::FailedExchangeWithKeyMismatch(osk_a, osk_b));
}
Ok(())

View File

@@ -1,20 +1,21 @@
use anyhow::Error;
use std::{
future::Future, net::SocketAddr, ops::DerefMut, path::PathBuf, pin::Pin, process::Command,
sync::Arc,
};
use anyhow::{Error, Result};
use serde::Deserialize;
use std::future::Future;
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::Arc;
use std::{net::SocketAddr, path::PathBuf, process::Command};
use rosenpass::config::ProtocolVersion;
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
use crate::key::WG_B64_LEN;
use anyhow::Result;
use rosenpass::config::ProtocolVersion;
/// Used to define a peer for the rosenpass connection that consists of
/// a directory for storing public keys and optionally an IP address and port of the endpoint,
/// for how long the connection should be kept alive and a list of allowed IPs for the peer.
#[derive(Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExchangePeer {
/// Directory where public keys are stored
pub public_keys_dir: PathBuf,
@@ -31,6 +32,7 @@ pub struct ExchangePeer {
/// Options for the exchange operation of the `rp` binary.
#[derive(Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExchangeOptions {
/// Whether the cli output should be verbose.
pub verbose: bool,
@@ -206,7 +208,10 @@ pub async fn exchange(options: ExchangeOptions) -> Result<()> {
use rosenpass::{
app_server::{AppServer, BrokerPeer},
config::Verbosity,
protocol::{SPk, SSk, SymKey},
protocol::{
basic_types::{SPk, SSk, SymKey},
osk_domain_separator::OskDomainSeparator,
},
};
use rosenpass_secret_memory::Secret;
use rosenpass_util::file::{LoadValue as _, LoadValueB64};
@@ -360,6 +365,7 @@ pub async fn exchange(options: ExchangeOptions) -> Result<()> {
broker_peer,
peer.endpoint.map(|x| x.to_string()),
peer.protocol_version,
OskDomainSeparator::for_wireguard_psk(),
)?;
// Configure routes, equivalent to `ip route replace <allowed_ips> dev <dev>` and set up

View File

@@ -9,7 +9,7 @@ use anyhow::{anyhow, Result};
use rosenpass_util::file::{LoadValueB64, StoreValue, StoreValueB64};
use zeroize::Zeroize;
use rosenpass::protocol::{SPk, SSk};
use rosenpass::protocol::basic_types::{SPk, SSk};
use rosenpass_cipher_traits::primitives::Kem;
use rosenpass_ciphers::StaticKem;
use rosenpass_secret_memory::{file::StoreSecret as _, Public, Secret};
@@ -118,7 +118,7 @@ pub fn pubkey(private_keys_dir: &Path, public_keys_dir: &Path) -> Result<()> {
mod tests {
use std::fs;
use rosenpass::protocol::{SPk, SSk};
use rosenpass::protocol::basic_types::{SPk, SSk};
use rosenpass_secret_memory::secret_policy_try_use_memfd_secrets;
use rosenpass_secret_memory::Secret;
use rosenpass_util::file::LoadValue;

View File

@@ -561,7 +561,7 @@ mod tests {
let mut file = FdIo(open_nullfd()?);
let mut buf = [0; 10];
assert!(matches!(file.read(&mut buf), Ok(0) | Err(_)));
assert!(matches!(file.write(&buf), Err(_)));
assert!(file.write(&buf).is_err());
Ok(())
}

View File

@@ -618,7 +618,7 @@ mod tests {
#[test]
fn test_lpe_error_conversion_downcast_invalid() {
let pos_error = PositionOutOfBufferBounds;
let sanity_error = SanityError::PositionOutOfBufferBounds(pos_error.into());
let sanity_error = SanityError::PositionOutOfBufferBounds(pos_error);
match MessageLenSanityError::try_from(sanity_error) {
Ok(_) => panic!("Conversion should always fail (incompatible enum variant)"),
Err(err) => assert!(matches!(err, PositionOutOfBufferBounds)),

View File

@@ -302,6 +302,6 @@ mod test_forgetting {
drop_was_called.store(false, SeqCst);
let forgetting = Forgetting::new(SetFlagOnDrop(drop_was_called.clone()));
drop(forgetting);
assert_eq!(drop_was_called.load(SeqCst), false);
assert!(!drop_was_called.load(SeqCst));
}
}