Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat(noise): add WebTransport certhashes extension #3991

Merged
merged 3 commits into from
Jun 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions transports/noise/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@

- Remove deprecated APIs. See [PR 3511].

- Add `Config::with_webtransport_certhashes`. See [PR 3991].
This can be used by WebTransport implementers to send (responder) or verify (initiator) certhashes.

[PR 3511]: https://github.com/libp2p/rust-libp2p/pull/3511
[PR 3715]: https://github.com/libp2p/rust-libp2p/pull/3715
[PR 3715]: https://github.com/libp2p/rust-libp2p/pull/3991

## 0.42.2

Expand Down
6 changes: 4 additions & 2 deletions transports/noise/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ futures = "0.3.28"
libp2p-core = { workspace = true }
libp2p-identity = { workspace = true, features = ["ed25519"] }
log = "0.4"
quick-protobuf = "0.8"
multiaddr = { workspace = true }
multihash = { workspace = true }
once_cell = "1.18.0"
quick-protobuf = "0.8"
rand = "0.8.3"
sha2 = "0.10.0"
static_assertions = "1"
Expand All @@ -35,7 +37,7 @@ env_logger = "0.10.0"
futures_ringbuf = "0.4.0"
quickcheck = { workspace = true }

# Passing arguments to the docsrs builder in order to properly document cfg's.
# Passing arguments to the docsrs builder in order to properly document cfg's.
# More information: https://docs.rs/about/builds#cross-compiling
[package.metadata.docs.rs]
all-features = true
Expand Down
8 changes: 6 additions & 2 deletions transports/noise/src/generated/payload.proto
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
syntax = "proto3";

package payload.proto;

// Payloads for Noise handshake messages.

message NoiseExtensions {
repeated bytes webtransport_certhashes = 1;
repeated string stream_muxers = 2;
}

message NoiseHandshakePayload {
bytes identity_key = 1;
bytes identity_sig = 2;
bytes data = 3;
optional NoiseExtensions extensions = 4;
}
44 changes: 40 additions & 4 deletions transports/noise/src/generated/payload/proto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,48 @@ use quick_protobuf::{MessageInfo, MessageRead, MessageWrite, BytesReader, Writer
use quick_protobuf::sizeofs::*;
use super::super::*;

#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Debug, Default, PartialEq, Clone)]
pub struct NoiseExtensions {
pub webtransport_certhashes: Vec<Vec<u8>>,
pub stream_muxers: Vec<String>,
}

impl<'a> MessageRead<'a> for NoiseExtensions {
fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self> {
let mut msg = Self::default();
while !r.is_eof() {
match r.next_tag(bytes) {
Ok(10) => msg.webtransport_certhashes.push(r.read_bytes(bytes)?.to_owned()),
Ok(18) => msg.stream_muxers.push(r.read_string(bytes)?.to_owned()),
Ok(t) => { r.read_unknown(bytes, t)?; }
Err(e) => return Err(e),
}
}
Ok(msg)
}
}

impl MessageWrite for NoiseExtensions {
fn get_size(&self) -> usize {
0
+ self.webtransport_certhashes.iter().map(|s| 1 + sizeof_len((s).len())).sum::<usize>()
+ self.stream_muxers.iter().map(|s| 1 + sizeof_len((s).len())).sum::<usize>()
}

fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
for s in &self.webtransport_certhashes { w.write_with_tag(10, |w| w.write_bytes(&**s))?; }
for s in &self.stream_muxers { w.write_with_tag(18, |w| w.write_string(&**s))?; }
Ok(())
}
}
oblique marked this conversation as resolved.
Show resolved Hide resolved

#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Debug, Default, PartialEq, Clone)]
pub struct NoiseHandshakePayload {
pub identity_key: Vec<u8>,
pub identity_sig: Vec<u8>,
pub data: Vec<u8>,
pub extensions: Option<payload::proto::NoiseExtensions>,
}

impl<'a> MessageRead<'a> for NoiseHandshakePayload {
Expand All @@ -28,7 +64,7 @@ impl<'a> MessageRead<'a> for NoiseHandshakePayload {
match r.next_tag(bytes) {
Ok(10) => msg.identity_key = r.read_bytes(bytes)?.to_owned(),
Ok(18) => msg.identity_sig = r.read_bytes(bytes)?.to_owned(),
Ok(26) => msg.data = r.read_bytes(bytes)?.to_owned(),
Ok(34) => msg.extensions = Some(r.read_message::<payload::proto::NoiseExtensions>(bytes)?),
Ok(t) => { r.read_unknown(bytes, t)?; }
Err(e) => return Err(e),
}
Expand All @@ -42,13 +78,13 @@ impl MessageWrite for NoiseHandshakePayload {
0
+ if self.identity_key.is_empty() { 0 } else { 1 + sizeof_len((&self.identity_key).len()) }
+ if self.identity_sig.is_empty() { 0 } else { 1 + sizeof_len((&self.identity_sig).len()) }
+ if self.data.is_empty() { 0 } else { 1 + sizeof_len((&self.data).len()) }
+ self.extensions.as_ref().map_or(0, |m| 1 + sizeof_len((m).get_size()))
}

fn write_message<W: WriterBackend>(&self, w: &mut Writer<W>) -> Result<()> {
if !self.identity_key.is_empty() { w.write_with_tag(10, |w| w.write_bytes(&**&self.identity_key))?; }
if !self.identity_sig.is_empty() { w.write_with_tag(18, |w| w.write_bytes(&**&self.identity_sig))?; }
if !self.data.is_empty() { w.write_with_tag(26, |w| w.write_bytes(&**&self.data))?; }
if let Some(ref s) = self.extensions { w.write_with_tag(34, |w| w.write_message(s))?; }
Ok(())
}
}
Expand Down
8 changes: 8 additions & 0 deletions transports/noise/src/io/framed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,14 @@ impl<T> NoiseFramed<T, snow::HandshakeState> {
}
}

pub(crate) fn is_initiator(&self) -> bool {
self.session.is_initiator()
}

pub(crate) fn is_responder(&self) -> bool {
!self.session.is_initiator()
}

/// Converts the `NoiseFramed` into a `NoiseOutput` encrypted data stream
/// once the handshake is complete, including the static DH [`PublicKey`]
/// of the remote, if received.
Expand Down
67 changes: 67 additions & 0 deletions transports/noise/src/io/handshake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
mod proto {
#![allow(unreachable_pub)]
include!("../generated/mod.rs");
pub use self::payload::proto::NoiseExtensions;
pub use self::payload::proto::NoiseHandshakePayload;
}

Expand All @@ -32,7 +33,9 @@ use crate::{DecodeError, Error};
use bytes::Bytes;
use futures::prelude::*;
use libp2p_identity as identity;
use multihash::Multihash;
use quick_protobuf::{BytesReader, MessageRead, MessageWrite, Writer};
use std::collections::HashSet;
use std::io;

//////////////////////////////////////////////////////////////////////////////
Expand All @@ -49,6 +52,15 @@ pub(crate) struct State<T> {
dh_remote_pubkey_sig: Option<Vec<u8>>,
/// The known or received public identity key of the remote, if any.
id_remote_pubkey: Option<identity::PublicKey>,
/// The WebTransport certhashes of the responder, if any.
responder_webtransport_certhashes: Option<HashSet<Multihash<64>>>,
/// The received extensions of the remote, if any.
remote_extensions: Option<Extensions>,
}

/// Extensions
struct Extensions {
webtransport_certhashes: HashSet<Multihash<64>>,
}

impl<T> State<T> {
Expand All @@ -63,12 +75,15 @@ impl<T> State<T> {
session: snow::HandshakeState,
identity: KeypairIdentity,
expected_remote_key: Option<identity::PublicKey>,
responder_webtransport_certhashes: Option<HashSet<Multihash<64>>>,
) -> Self {
Self {
identity,
io: NoiseFramed::new(io, session),
dh_remote_pubkey_sig: None,
id_remote_pubkey: expected_remote_key,
responder_webtransport_certhashes,
remote_extensions: None,
}
}
}
Expand All @@ -77,6 +92,7 @@ impl<T> State<T> {
/// Finish a handshake, yielding the established remote identity and the
/// [`Output`] for communicating on the encrypted channel.
pub(crate) fn finish(self) -> Result<(identity::PublicKey, Output<T>), Error> {
let is_initiator = self.io.is_initiator();
let (pubkey, io) = self.io.into_transport()?;

let id_pk = self
Expand All @@ -91,10 +107,46 @@ impl<T> State<T> {
return Err(Error::BadSignature);
}

// Check WebTransport certhashes that responder reported back to us.
if is_initiator {
// We check only if we care (i.e. Config::with_webtransport_certhashes was used).
if let Some(expected_certhashes) = self.responder_webtransport_certhashes {
let ext = self.remote_extensions.ok_or_else(|| {
Error::UnknownWebTransportCerthashes(
expected_certhashes.to_owned(),
HashSet::new(),
)
})?;

let received_certhashes = ext.webtransport_certhashes;

// Expected WebTransport certhashes must be a strict subset
// of the reported ones.
if !expected_certhashes.is_subset(&received_certhashes) {
return Err(Error::UnknownWebTransportCerthashes(
expected_certhashes,
received_certhashes,
));
}
}
}

Ok((id_pk, io))
}
}

impl From<proto::NoiseExtensions> for Extensions {
fn from(value: proto::NoiseExtensions) -> Self {
Extensions {
webtransport_certhashes: value
.webtransport_certhashes
.into_iter()
.filter_map(|bytes| Multihash::read(&bytes[..]).ok())
.collect(),
}
}
}

//////////////////////////////////////////////////////////////////////////////
// Handshake Message Futures

Expand Down Expand Up @@ -149,6 +201,10 @@ where
state.dh_remote_pubkey_sig = Some(pb.identity_sig);
}

if let Some(extensions) = pb.extensions {
state.remote_extensions = Some(extensions.into());
}

Ok(())
}

Expand All @@ -164,6 +220,17 @@ where

pb.identity_sig = state.identity.signature.clone();

// If this is the responder then send WebTransport certhashes to initiator, if any.
if state.io.is_responder() {
if let Some(ref certhashes) = state.responder_webtransport_certhashes {
let ext = pb
.extensions
.get_or_insert_with(proto::NoiseExtensions::default);

ext.webtransport_certhashes = certhashes.iter().map(|hash| hash.to_bytes()).collect();
}
}

let mut msg = Vec::with_capacity(pb.get_size());

let mut writer = Writer::new(&mut msg);
Expand Down
44 changes: 42 additions & 2 deletions transports/noise/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,19 @@ use futures::prelude::*;
use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
use libp2p_identity as identity;
use libp2p_identity::PeerId;
use multiaddr::Protocol;
use multihash::Multihash;
use snow::params::NoiseParams;
use std::collections::HashSet;
use std::fmt::Write;
use std::pin::Pin;

/// The configuration for the noise handshake.
#[derive(Clone)]
pub struct Config {
dh_keys: AuthenticKeypair,
params: NoiseParams,
webtransport_certhashes: Option<HashSet<Multihash<64>>>,

/// Prologue to use in the noise handshake.
///
Expand All @@ -94,14 +99,25 @@ impl Config {
Ok(Self {
dh_keys: noise_keys,
params: PARAMS_XX.clone(),
webtransport_certhashes: None,
prologue: vec![],
})
}

/// Set the noise prologue.
pub fn with_prologue(mut self, prologue: Vec<u8>) -> Self {
self.prologue = prologue;
self
}

/// Set WebTransport certhashes extension.
///
/// In case of initiator, these certhashes will be used to validate the ones reported by
/// responder.
///
/// In case of responder, these certhashes will be reported to initiator.
pub fn with_webtransport_certhashes(mut self, certhashes: HashSet<Multihash<64>>) -> Self {
self.webtransport_certhashes = Some(certhashes).filter(|h| !h.is_empty());
self
}

Expand All @@ -114,7 +130,13 @@ impl Config {
)
.build_responder()?;

let state = State::new(socket, session, self.dh_keys.identity, None);
let state = State::new(
socket,
session,
self.dh_keys.identity,
None,
self.webtransport_certhashes,
);

Ok(state)
}
Expand All @@ -128,7 +150,13 @@ impl Config {
)
.build_initiator()?;

let state = State::new(socket, session, self.dh_keys.identity, None);
let state = State::new(
socket,
session,
self.dh_keys.identity,
None,
self.webtransport_certhashes,
);

Ok(state)
}
Expand Down Expand Up @@ -213,8 +241,20 @@ pub enum Error {
InvalidPayload(#[from] DecodeError),
#[error(transparent)]
SigningError(#[from] libp2p_identity::SigningError),
#[error("Expected WebTransport certhashes ({}) are not a subset of received ones ({})", certhashes_to_string(.0), certhashes_to_string(.1))]
UnknownWebTransportCerthashes(HashSet<Multihash<64>>, HashSet<Multihash<64>>),
}

#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct DecodeError(quick_protobuf::Error);

fn certhashes_to_string(certhashes: &HashSet<Multihash<64>>) -> String {
let mut s = String::new();

for hash in certhashes {
write!(&mut s, "{}", Protocol::Certhash(*hash)).unwrap();
}

s
}
4 changes: 2 additions & 2 deletions transports/noise/tests/smoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ fn xx() {

futures::executor::block_on(async move {
let (
(reported_client_id, mut client_session),
(reported_server_id, mut server_session),
(reported_client_id, mut server_session),
(reported_server_id, mut client_session),
thomaseizinger marked this conversation as resolved.
Show resolved Hide resolved
) = futures::future::try_join(
noise::Config::new(&server_id)
.unwrap()
Expand Down
Loading