Skip to content

Commit

Permalink
feat(noise): add WebTransport certhashes extension
Browse files Browse the repository at this point in the history
  • Loading branch information
oblique committed Jun 5, 2023
1 parent 49eed8c commit cf3880b
Show file tree
Hide file tree
Showing 10 changed files with 366 additions and 12 deletions.
49 changes: 49 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
7 changes: 5 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 = "0.17.1"
multihash = { version = "0.17.0", default-features = false }
once_cell = "1.18.0"
quick-protobuf = "0.8"
rand = "0.8.3"
sha2 = "0.10.0"
static_assertions = "1"
Expand All @@ -34,8 +36,9 @@ snow = { version = "0.9.2", features = ["default-resolver"], default-features =
env_logger = "0.10.0"
futures_ringbuf = "0.4.0"
quickcheck = { workspace = true }
multihash = { version = "0.17.0", features = ["sha2"] }

# 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(())
}
}

#[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
64 changes: 64 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>>,
/// The received extensions of the remote, if any.
remote_extensions: Option<Extensions>,
}

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

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>>,
) -> 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,43 @@ 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())
})?;

// Expected WebTransport certhashes must be a strict subset
// of the reported ones.
let unknown_certhashes = expected_certhashes
.difference(&ext.webtransport_certhashes)
.cloned()
.collect::<HashSet<_>>();

if !unknown_certhashes.is_empty() {
return Err(Error::UnknownWebTransportCerthashes(unknown_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 +198,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 +217,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
Loading

0 comments on commit cf3880b

Please sign in to comment.