From 7d4c24f081b2c02b38d2f6f6ebb5541695880ed7 Mon Sep 17 00:00:00 2001 From: Ilka Schulz Date: Sat, 20 Jun 2026 16:42:20 +0200 Subject: [PATCH] fix regressions from upgrading dependency in rosenpass/ --- .../src/api/boilerplate/byte_slice_ext.rs | 6 +-- rosenpass/src/api/boilerplate/message_type.rs | 6 +-- rosenpass/src/api/boilerplate/payload.rs | 20 +++++----- rosenpass/src/api/boilerplate/request_ref.rs | 32 +++++++++------- .../src/api/boilerplate/request_response.rs | 6 +-- rosenpass/src/api/boilerplate/response_ref.rs | 32 +++++++++------- rosenpass/src/api/boilerplate/server.rs | 6 +-- rosenpass/src/msgs.rs | 18 ++++----- rosenpass/src/protocol/protocol.rs | 37 ++++++++++--------- rosenpass/src/protocol/test.rs | 20 ++++++---- rosenpass/src/protocol/zerocopy.rs | 10 ++--- .../tests/api-integration-tests-api-setup.rs | 2 +- rosenpass/tests/api-integration-tests.rs | 2 +- util/src/zerocopy/ref_maker.rs | 3 +- wireguard-broker/src/api/server.rs | 8 ++-- 15 files changed, 111 insertions(+), 97 deletions(-) diff --git a/rosenpass/src/api/boilerplate/byte_slice_ext.rs b/rosenpass/src/api/boilerplate/byte_slice_ext.rs index 283b886d..9f764157 100644 --- a/rosenpass/src/api/boilerplate/byte_slice_ext.rs +++ b/rosenpass/src/api/boilerplate/byte_slice_ext.rs @@ -1,4 +1,4 @@ -use zerocopy::{ByteSlice, Ref}; +use zerocopy::{Ref, SplitByteSlice}; use rosenpass_util::zerocopy::{RefMaker, ZerocopySliceExt}; @@ -7,7 +7,7 @@ use super::{ ResponseMsgType, ResponseRef, SupplyKeypairRequest, SupplyKeypairResponse, }; -pub trait ByteSliceRefExt: ByteSlice { +pub trait ByteSliceRefExt: SplitByteSlice { /// Shorthand for the typed use of [ZerocopySliceExt::zk_ref_maker]. fn msg_type_maker(self) -> RefMaker { self.zk_ref_maker() @@ -259,4 +259,4 @@ pub trait ByteSliceRefExt: ByteSlice { } } -impl ByteSliceRefExt for B {} +impl ByteSliceRefExt for B {} diff --git a/rosenpass/src/api/boilerplate/message_type.rs b/rosenpass/src/api/boilerplate/message_type.rs index ab1ec82f..d2508fb8 100644 --- a/rosenpass/src/api/boilerplate/message_type.rs +++ b/rosenpass/src/api/boilerplate/message_type.rs @@ -1,6 +1,6 @@ use hex_literal::hex; use rosenpass_util::zerocopy::RefMaker; -use zerocopy::ByteSlice; +use zerocopy::{ByteSlice, Ref}; use crate::RosenpassError::{self, InvalidApiMessageType}; @@ -171,10 +171,10 @@ pub trait RefMakerRawMsgTypeExt { impl RefMakerRawMsgTypeExt for RefMaker { fn parse_request_msg_type(self) -> anyhow::Result { - Ok(self.parse()?.read().try_into()?) + Ok(Ref::read(&self.parse()?).try_into()?) } fn parse_response_msg_type(self) -> anyhow::Result { - Ok(self.parse()?.read().try_into()?) + Ok(Ref::read(&self.parse()?).try_into()?) } } diff --git a/rosenpass/src/api/boilerplate/payload.rs b/rosenpass/src/api/boilerplate/payload.rs index 2185279f..c8131273 100644 --- a/rosenpass/src/api/boilerplate/payload.rs +++ b/rosenpass/src/api/boilerplate/payload.rs @@ -1,5 +1,5 @@ use rosenpass_util::zerocopy::ZerocopyMutSliceExt; -use zerocopy::{IntoBytes, ByteSliceMut, FromBytes, Ref}; +use zerocopy::{ByteSliceMut, FromBytes, Immutable, IntoBytes, KnownLayout, Ref}; use super::{Message, RawMsgType, RequestMsgType, ResponseMsgType}; @@ -12,7 +12,7 @@ pub const MAX_REQUEST_FDS: usize = 2; /// Message envelope for API messages #[repr(packed)] -#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, KnownLayout, Immutable, PartialEq, Eq)] pub struct Envelope { /// Which message this is pub msg_type: RawMsgType, @@ -27,7 +27,7 @@ pub type ResponseEnvelope = Envelope; #[allow(missing_docs)] #[repr(packed)] -#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, Immutable, PartialEq, Eq)] pub struct PingRequestPayload { /// Randomly generated connection id pub echo: [u8; 256], @@ -68,7 +68,7 @@ impl Message for PingRequest { #[allow(missing_docs)] #[repr(packed)] -#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, Immutable, PartialEq, Eq)] pub struct PingResponsePayload { /// Randomly generated connection id pub echo: [u8; 256], @@ -109,7 +109,7 @@ impl Message for PingResponse { #[allow(missing_docs)] #[repr(packed)] -#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, Immutable, PartialEq, Eq)] pub struct SupplyKeypairRequestPayload {} #[allow(missing_docs)] @@ -169,7 +169,7 @@ pub mod supply_keypair_response_status { #[allow(missing_docs)] #[repr(packed)] -#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, Immutable, PartialEq, Eq)] pub struct SupplyKeypairResponsePayload { #[allow(missing_docs)] pub status: u128, @@ -210,7 +210,7 @@ impl Message for SupplyKeypairResponse { #[allow(missing_docs)] #[repr(packed)] -#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, Immutable, PartialEq, Eq)] pub struct AddListenSocketRequestPayload {} #[allow(missing_docs)] @@ -264,7 +264,7 @@ pub mod add_listen_socket_response_status { #[allow(missing_docs)] #[repr(packed)] -#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, Immutable, PartialEq, Eq)] pub struct AddListenSocketResponsePayload { pub status: u128, } @@ -304,7 +304,7 @@ impl Message for AddListenSocketResponse { #[allow(missing_docs)] #[repr(packed)] -#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, Immutable, PartialEq, Eq)] pub struct AddPskBrokerRequestPayload {} #[allow(missing_docs)] @@ -359,7 +359,7 @@ pub mod add_psk_broker_response_status { #[allow(missing_docs)] #[repr(packed)] -#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, Hash, IntoBytes, FromBytes, Immutable, PartialEq, Eq)] pub struct AddPskBrokerResponsePayload { pub status: u128, } diff --git a/rosenpass/src/api/boilerplate/request_ref.rs b/rosenpass/src/api/boilerplate/request_ref.rs index 49e8a328..74997edc 100644 --- a/rosenpass/src/api/boilerplate/request_ref.rs +++ b/rosenpass/src/api/boilerplate/request_ref.rs @@ -1,6 +1,6 @@ -use anyhow::ensure; +use anyhow::{anyhow, ensure}; -use zerocopy::{ByteSlice, ByteSliceMut, Ref}; +use zerocopy::{ByteSlice, ByteSliceMut, Ref, SplitByteSlice}; use super::{ByteSliceRefExt, MessageAttributes, PingRequest, RequestMsgType}; @@ -13,7 +13,7 @@ struct RequestRefMaker { msg_type: RequestMsgType, } -impl RequestRef { +impl RequestRef { /// Produce a [RequestRef] from a raw message buffer, /// reading the type from the buffer /// @@ -95,7 +95,7 @@ impl From> for RequestRef { } } -impl RequestRefMaker { +impl RequestRefMaker { fn new(buf: B) -> anyhow::Result { let msg_type = buf.deref().request_msg_type_from_prefix()?; Ok(Self { buf, msg_type }) @@ -125,7 +125,9 @@ impl RequestRefMaker { self.ensure_fit()?; let point = self.target_size(); let Self { buf, msg_type } = self; - let (buf, _) = buf.split_at(point); + let (buf, _) = buf + .split_at(point) + .map_err(|_| anyhow!("RequestRefMaker::from_prefix: can not split buffer"))?; Ok(Self { buf, msg_type }) } @@ -134,7 +136,9 @@ impl RequestRefMaker { self.ensure_fit()?; let point = self.buf.len() - self.target_size(); let Self { buf, msg_type } = self; - let (buf, _) = buf.split_at(point); + let (buf, _) = buf + .split_at(point) + .map_err(|_| anyhow!("RequestRefMaker::from_suffix: can not split buffer"))?; Ok(Self { buf, msg_type }) } @@ -168,10 +172,10 @@ where /// See [Self::parse]. pub fn bytes(&self) -> &[u8] { match self { - Self::Ping(r) => r.bytes(), - Self::SupplyKeypair(r) => r.bytes(), - Self::AddListenSocket(r) => r.bytes(), - Self::AddPskBroker(r) => r.bytes(), + Self::Ping(r) => Ref::bytes(r), + Self::SupplyKeypair(r) => Ref::bytes(r), + Self::AddListenSocket(r) => Ref::bytes(r), + Self::AddPskBroker(r) => Ref::bytes(r), } } } @@ -183,10 +187,10 @@ where /// Access the byte data of this reference; mutably pub fn bytes_mut(&mut self) -> &[u8] { match self { - Self::Ping(r) => r.bytes_mut(), - Self::SupplyKeypair(r) => r.bytes_mut(), - Self::AddListenSocket(r) => r.bytes_mut(), - Self::AddPskBroker(r) => r.bytes_mut(), + Self::Ping(r) => Ref::bytes_mut(r), + Self::SupplyKeypair(r) => Ref::bytes_mut(r), + Self::AddListenSocket(r) => Ref::bytes_mut(r), + Self::AddPskBroker(r) => Ref::bytes_mut(r), } } } diff --git a/rosenpass/src/api/boilerplate/request_response.rs b/rosenpass/src/api/boilerplate/request_response.rs index 17f75969..d04b3e0d 100644 --- a/rosenpass/src/api/boilerplate/request_response.rs +++ b/rosenpass/src/api/boilerplate/request_response.rs @@ -1,7 +1,7 @@ use rosenpass_util::zerocopy::{ RefMaker, ZerocopyEmancipateExt, ZerocopyEmancipateMutExt, ZerocopySliceExt, }; -use zerocopy::{ByteSlice, ByteSliceMut, Ref}; +use zerocopy::{ByteSlice, ByteSliceMut, Ref, SplitByteSliceMut}; use super::{Message, PingRequest, PingResponse}; use super::{RequestRef, ResponseRef, ZerocopyResponseMakerSetupMessageExt}; @@ -22,14 +22,14 @@ pub trait RequestMsg: Sized + Message { } /// Setup a response maker from a buffer prefix (through [Message::setup]) for this request message type - fn setup_response_from_prefix( + fn setup_response_from_prefix( buf: B, ) -> anyhow::Result> { Self::zk_response_maker(buf).from_prefix()?.setup_msg() } /// Setup a response maker from a buffer suffix (through [Message::setup]) for this request message type - fn setup_response_from_suffix( + fn setup_response_from_suffix( buf: B, ) -> anyhow::Result> { Self::zk_response_maker(buf).from_prefix()?.setup_msg() diff --git a/rosenpass/src/api/boilerplate/response_ref.rs b/rosenpass/src/api/boilerplate/response_ref.rs index a1ab3805..a8a463cf 100644 --- a/rosenpass/src/api/boilerplate/response_ref.rs +++ b/rosenpass/src/api/boilerplate/response_ref.rs @@ -1,7 +1,7 @@ // TODO: This is copied verbatim from ResponseRef…not pretty -use anyhow::ensure; +use anyhow::{anyhow, ensure}; -use zerocopy::{ByteSlice, ByteSliceMut, Ref}; +use zerocopy::{ByteSlice, ByteSliceMut, Ref, SplitByteSlice}; use super::{ByteSliceRefExt, MessageAttributes, PingResponse, ResponseMsgType}; @@ -16,7 +16,7 @@ struct ResponseRefMaker { msg_type: ResponseMsgType, } -impl ResponseRef { +impl ResponseRef { /// Produce a [ResponseRef] from a raw message buffer, /// reading the type from the buffer /// @@ -99,7 +99,7 @@ impl From> for ResponseRef { } } -impl ResponseRefMaker { +impl ResponseRefMaker { fn new(buf: B) -> anyhow::Result { let msg_type = buf.deref().response_msg_type_from_prefix()?; Ok(Self { buf, msg_type }) @@ -129,7 +129,9 @@ impl ResponseRefMaker { self.ensure_fit()?; let point = self.target_size(); let Self { buf, msg_type } = self; - let (buf, _) = buf.split_at(point); + let (buf, _) = buf + .split_at(point) + .map_err(|_| anyhow!("ResponseRefMaker::from_prefix: can not split buffer"))?; Ok(Self { buf, msg_type }) } @@ -138,7 +140,9 @@ impl ResponseRefMaker { self.ensure_fit()?; let point = self.buf.len() - self.target_size(); let Self { buf, msg_type } = self; - let (buf, _) = buf.split_at(point); + let (buf, _) = buf + .split_at(point) + .map_err(|_| anyhow!("ResponseRefMaker::from_suffix: can not split buiffer"))?; Ok(Self { buf, msg_type }) } @@ -172,10 +176,10 @@ where /// See [Self::parse]. pub fn bytes(&self) -> &[u8] { match self { - Self::Ping(r) => r.bytes(), - Self::SupplyKeypair(r) => r.bytes(), - Self::AddListenSocket(r) => r.bytes(), - Self::AddPskBroker(r) => r.bytes(), + Self::Ping(r) => Ref::bytes(r), + Self::SupplyKeypair(r) => Ref::bytes(r), + Self::AddListenSocket(r) => Ref::bytes(r), + Self::AddPskBroker(r) => Ref::bytes(r), } } } @@ -187,10 +191,10 @@ where /// Access the byte data of this reference; mutably pub fn bytes_mut(&mut self) -> &[u8] { match self { - Self::Ping(r) => r.bytes_mut(), - Self::SupplyKeypair(r) => r.bytes_mut(), - Self::AddListenSocket(r) => r.bytes_mut(), - Self::AddPskBroker(r) => r.bytes_mut(), + Self::Ping(r) => Ref::bytes_mut(r), + Self::SupplyKeypair(r) => Ref::bytes_mut(r), + Self::AddListenSocket(r) => Ref::bytes_mut(r), + Self::AddPskBroker(r) => Ref::bytes_mut(r), } } } diff --git a/rosenpass/src/api/boilerplate/server.rs b/rosenpass/src/api/boilerplate/server.rs index 72a2461a..0f6df611 100644 --- a/rosenpass/src/api/boilerplate/server.rs +++ b/rosenpass/src/api/boilerplate/server.rs @@ -1,6 +1,6 @@ use super::{ByteSliceRefExt, Message, PingRequest, PingResponse, RequestRef, RequestResponsePair}; use std::{collections::VecDeque, os::fd::OwnedFd}; -use zerocopy::{ByteSlice, ByteSliceMut}; +use zerocopy::{ByteSlice, ByteSliceMut, SplitByteSlice, SplitByteSliceMut}; /// The rosenpass API implementation functions. /// @@ -182,8 +182,8 @@ pub trait Server { res: ResBuf, ) -> anyhow::Result where - ReqBuf: ByteSlice, - ResBuf: ByteSliceMut, + ReqBuf: SplitByteSlice, + ResBuf: SplitByteSliceMut, { let req = req.parse_request_from_prefix()?; // TODO: This is not pretty; This match should be moved into RequestRef diff --git a/rosenpass/src/msgs.rs b/rosenpass/src/msgs.rs index e2cb21bf..66e8fc38 100644 --- a/rosenpass/src/msgs.rs +++ b/rosenpass/src/msgs.rs @@ -9,7 +9,7 @@ //! To achieve this we utilize the zerocopy library. //! use std::mem::size_of; -use zerocopy::{IntoBytes, FromBytes}; +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; use super::RosenpassError; use rosenpass_cipher_traits::primitives::{Aead as _, Kem}; @@ -76,7 +76,7 @@ pub type MsgEnvelopeCookie = [u8; COOKIE_SIZE]; /// assert_eq!(ih3.msg_type, 42); /// ``` #[repr(packed)] -#[derive(IntoBytes, FromBytes, Clone)] +#[derive(IntoBytes, FromBytes, KnownLayout, Immutable, Clone)] pub struct Envelope { /// [MsgType] of this message pub msg_type: u8, @@ -126,7 +126,7 @@ pub struct Envelope { /// assert_eq!(ih.payload.sidi, [1,2,3,4]); /// ``` #[repr(packed)] -#[derive(IntoBytes, FromBytes)] +#[derive(IntoBytes, FromBytes, KnownLayout, Immutable)] pub struct InitHello { /// Randomly generated connection id pub sidi: [u8; 4], @@ -175,7 +175,7 @@ pub struct InitHello { /// assert_eq!(ih.payload.sidi, [1,2,3,4]); /// ``` #[repr(packed)] -#[derive(IntoBytes, FromBytes)] +#[derive(IntoBytes, FromBytes, KnownLayout, Immutable)] pub struct RespHello { /// Randomly generated connection id pub sidr: [u8; 4], @@ -226,7 +226,7 @@ pub struct RespHello { /// assert_eq!(ih.payload.sidi, [1,2,3,4]); /// ``` #[repr(packed)] -#[derive(IntoBytes, FromBytes, Debug)] +#[derive(IntoBytes, FromBytes, KnownLayout, Immutable, Debug)] pub struct InitConf { /// Copied from InitHello pub sidi: [u8; 4], @@ -284,7 +284,7 @@ pub struct InitConf { /// assert_eq!(ih.payload.sid, [1,2,3,4]); /// ``` #[repr(packed)] -#[derive(IntoBytes, FromBytes, Clone, Copy)] +#[derive(IntoBytes, FromBytes, KnownLayout, Immutable, Clone, Copy)] pub struct EmptyData { /// Copied from RespHello pub sid: [u8; 4], @@ -311,7 +311,7 @@ pub struct EmptyData { /// /// [Envelope] and [InitHello] contain some extra examples on how to use structures from the [::zerocopy] crate. #[repr(packed)] -#[derive(IntoBytes, FromBytes)] +#[derive(IntoBytes, FromBytes, KnownLayout, Immutable)] pub struct Biscuit { /// H(spki) – Ident ifies the initiator pub pidi: [u8; KEY_LEN], @@ -336,7 +336,7 @@ pub struct Biscuit { /// /// [Envelope] and [InitHello] contain some extra examples on how to use structures from the [::zerocopy] crate. #[repr(packed)] -#[derive(IntoBytes, FromBytes)] +#[derive(IntoBytes, FromBytes, Immutable)] pub struct CookieReplyInner { /// [MsgType] of this message pub msg_type: u8, @@ -363,7 +363,7 @@ pub struct CookieReplyInner { /// /// [Envelope] and [InitHello] contain some extra examples on how to use structures from the [::zerocopy] crate. #[repr(packed)] -#[derive(IntoBytes, FromBytes)] +#[derive(IntoBytes, FromBytes, KnownLayout, Immutable)] pub struct CookieReply { pub inner: CookieReplyInner, pub padding: [u8; size_of::>() - size_of::()], diff --git a/rosenpass/src/protocol/protocol.rs b/rosenpass/src/protocol/protocol.rs index 87acaafd..61b9d88a 100644 --- a/rosenpass/src/protocol/protocol.rs +++ b/rosenpass/src/protocol/protocol.rs @@ -17,7 +17,7 @@ use std::{ use anyhow::{Context, Result, bail, ensure}; use assert_tv::{TestVector, TestVectorNOP}; use memoffset::span_of; -use zerocopy::{IntoBytes, FromBytes, Ref}; +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Ref}; use rosenpass_cipher_traits::primitives::{ Aead as _, AeadWithNonceInCiphertext, Kem, KeyedHashInstance, @@ -435,7 +435,7 @@ impl Debug for KnownResponse #[test] fn known_response_format() { - use zerocopy::FromZeroes; + use zerocopy::FromZeros; let v = KnownResponse::<[u8; 32]> { received_at: 42.0, @@ -508,7 +508,10 @@ impl KnownResponseHasher { /// # Panic & Safety /// /// Panics in case of a problem with this underlying hash function - pub fn hash(&self, msg: &Envelope) -> KnownResponseHash { + pub fn hash( + &self, + msg: &Envelope, + ) -> KnownResponseHash { let data = &msg.as_bytes()[span_of!(Envelope, msg_type..cookie)]; // This function is only used internally and results are not propagated // to outside the peer. Thus, it uses SHAKE256 exclusively. @@ -2030,8 +2033,8 @@ impl CryptoServer { let mut expected = [0u8; COOKIE_SIZE]; - let msg_in = Ref::<&[u8], Envelope>::new(rx_buf) - .ok_or(RosenpassError::BufferSizeMismatch)?; + let msg_in = Ref::<&[u8], Envelope>::from_bytes(rx_buf) + .map_err(|_| RosenpassError::BufferSizeMismatch)?; expected.copy_from_slice( &hash_domains::cookie(KeyedHash::keyed_shake256())? .mix(&cookie_value)? @@ -2175,7 +2178,7 @@ impl CryptoServer { let peer = match msg_type { Ok(MsgType::InitHello) => { let msg_in: Ref<&[u8], Envelope> = - Ref::new(rx_buf).ok_or(RosenpassError::BufferSizeMismatch)?; + Ref::from_bytes(rx_buf).map_err(|_| RosenpassError::BufferSizeMismatch)?; // At this point, we do not know the hash functon used by the peer, thus we try both, // with a preference for SHAKE256. @@ -2209,7 +2212,7 @@ impl CryptoServer { } Ok(MsgType::RespHello) => { let msg_in: Ref<&[u8], Envelope> = - Ref::new(rx_buf).ok_or(RosenpassError::BufferSizeMismatch)?; + Ref::from_bytes(rx_buf).map_err(|_| RosenpassError::BufferSizeMismatch)?; let mut msg_out = truncating_cast_into::>(tx_buf)?; let peer = self.handle_resp_hello(&msg_in.payload, &mut msg_out.payload)?; @@ -2226,7 +2229,7 @@ impl CryptoServer { } Ok(MsgType::InitConf) => { let msg_in: Ref<&[u8], Envelope> = - Ref::new(rx_buf).ok_or(RosenpassError::BufferSizeMismatch)?; + Ref::from_bytes(rx_buf).map_err(|_| RosenpassError::BufferSizeMismatch)?; let mut msg_out = truncating_cast_into::>(tx_buf)?; @@ -2245,7 +2248,7 @@ impl CryptoServer { .map(|v| v.response.borrow()) // Invalid! Found peer no with cache in index but the cache does not exist .unwrap(); - copy_slice(cached.as_bytes()).to(msg_out.as_bytes_mut()); + copy_slice(cached.as_bytes()).to(msg_out.as_mut_bytes()); peer } @@ -2294,13 +2297,13 @@ impl CryptoServer { } Ok(MsgType::EmptyData) => { let msg_in: Ref<&[u8], Envelope> = - Ref::new(rx_buf).ok_or(RosenpassError::BufferSizeMismatch)?; + Ref::from_bytes(rx_buf).map_err(|_| RosenpassError::BufferSizeMismatch)?; self.handle_resp_conf(&msg_in, seal_broken.to_string())? } Ok(MsgType::CookieReply) => { let msg_in: Ref<&[u8], CookieReply> = - Ref::new(rx_buf).ok_or(RosenpassError::BufferSizeMismatch)?; + Ref::from_bytes(rx_buf).map_err(|_| RosenpassError::BufferSizeMismatch)?; let peer = self.handle_cookie_reply(&msg_in)?; len = 0; peer @@ -2342,7 +2345,7 @@ impl CryptoServer { /// To save some code, the function returns the size of the message, /// but the same could be easily achieved by calling [size_of] with the /// message type or by calling [IntoBytes::as_bytes] on the message reference. - pub fn seal_and_commit_msg( + pub fn seal_and_commit_msg( &mut self, peer: PeerPtr, msg_type: MsgType, @@ -3065,7 +3068,7 @@ impl IniHsPtr { impl Envelope where - M: IntoBytes + FromBytes, + M: IntoBytes + FromBytes + Immutable, { /// Internal business logic: Calculate the message authentication code (`mac`) and also append cookie value pub fn seal(&mut self, peer: PeerPtr, srv: &CryptoServer) -> Result<()> { @@ -3094,7 +3097,7 @@ where impl Envelope where - M: IntoBytes + FromBytes, + M: IntoBytes + FromBytes + Immutable, { /// Internal business logic: Check the message authentication code produced by [Self::seal] pub fn check_seal(&self, srv: &CryptoServer, shake_or_blake: KeyedHash) -> Result { @@ -3309,7 +3312,7 @@ impl HandshakeState { let test_values: StoreBiscuitTestValues = TV::initialize_values(); let mut biscuit = Secret::::zero(); // pt buffer let mut biscuit: Ref<&mut [u8], Biscuit> = - Ref::new(biscuit.secret_mut().as_mut_slice()).unwrap(); + Ref::from_bytes(biscuit.secret_mut().as_mut_slice()).unwrap(); // calculate pt contents biscuit @@ -3371,9 +3374,9 @@ impl HandshakeState { // Allocate and decrypt the biscuit data let mut biscuit = Secret::::zero(); // pt buf let mut biscuit: Ref<&mut [u8], Biscuit> = - Ref::new(biscuit.secret_mut().as_mut_slice()).unwrap(); + Ref::from_bytes(biscuit.secret_mut().as_mut_slice()).unwrap(); XAead.decrypt_with_nonce_in_ctxt( - biscuit.as_bytes_mut(), + biscuit.as_mut_bytes(), bk.get(srv).value.secret(), &ad, biscuit_ct, diff --git a/rosenpass/src/protocol/test.rs b/rosenpass/src/protocol/test.rs index cd295cf7..4b1a4b7e 100644 --- a/rosenpass/src/protocol/test.rs +++ b/rosenpass/src/protocol/test.rs @@ -2,7 +2,7 @@ use std::{borrow::BorrowMut, fmt::Display, net::SocketAddrV4, ops::DerefMut}; use anyhow::{Context, Result}; use serial_test::serial; -use zerocopy::{IntoBytes, FromBytes}; +use zerocopy::{FromBytes, FromZeros, Immutable, IntoBytes, KnownLayout, Ref}; use rosenpass_cipher_traits::primitives::Kem; use rosenpass_ciphers::StaticKem; @@ -539,10 +539,10 @@ fn init_conf_retransmission(protocol_version: ProtocolVersion) -> anyhow::Result srv.initiate_handshake(peer, buf.as_mut_slice())? .discard_result(); let msg = truncating_cast_into::>(buf.borrow_mut())?; - Ok(msg.read()) + Ok(Ref::read(&msg)) } - fn proc_msg( + fn proc_msg( srv: &mut CryptoServer, rx: &Envelope, ) -> anyhow::Result> { @@ -552,7 +552,7 @@ fn init_conf_retransmission(protocol_version: ProtocolVersion) -> anyhow::Result .context("Failed to produce RespHello message")? .discard_result(); let msg = truncating_cast_into::>(buf.borrow_mut())?; - Ok(msg.read()) + Ok(Ref::read(&msg)) } fn proc_init_hello( @@ -583,17 +583,21 @@ fn init_conf_retransmission(protocol_version: ProtocolVersion) -> anyhow::Result } // TODO: Implement Clone on our message types - fn clone_msg(msg: &Msg) -> anyhow::Result { - Ok(truncating_cast_into_nomut::(msg.as_bytes())?.read()) + fn clone_msg( + msg: &Msg, + ) -> anyhow::Result { + Ok(Ref::read(&truncating_cast_into_nomut::( + msg.as_bytes(), + )?)) } - fn break_payload( + fn break_payload( srv: &mut CryptoServer, peer: PeerPtr, msg: &Envelope, ) -> anyhow::Result> { let mut msg = clone_msg(msg)?; - msg.as_bytes_mut()[memoffset::offset_of!(Envelope, payload)] ^= 0x01; + msg.as_mut_bytes()[memoffset::offset_of!(Envelope, payload)] ^= 0x01; msg.seal(peer, srv)?; // Recalculate seal; we do not want to focus on "seal broken" errs Ok(msg) } diff --git a/rosenpass/src/protocol/zerocopy.rs b/rosenpass/src/protocol/zerocopy.rs index 3e8639b6..63bd75c5 100644 --- a/rosenpass/src/protocol/zerocopy.rs +++ b/rosenpass/src/protocol/zerocopy.rs @@ -2,20 +2,20 @@ use std::mem::size_of; -use zerocopy::{FromBytes, Ref}; +use zerocopy::{FromBytes, Immutable, KnownLayout, Ref}; use crate::RosenpassError; /// Used to parse a network message using [zerocopy] -pub fn truncating_cast_into( +pub fn truncating_cast_into( buf: &mut [u8], ) -> Result, RosenpassError> { - Ref::new(&mut buf[..size_of::()]).ok_or(RosenpassError::BufferSizeMismatch) + Ref::from_bytes(&mut buf[..size_of::()]).map_err(|_| RosenpassError::BufferSizeMismatch) } /// Used to parse a network message using [zerocopy], mutably -pub fn truncating_cast_into_nomut( +pub fn truncating_cast_into_nomut( buf: &[u8], ) -> Result, RosenpassError> { - Ref::new(&buf[..size_of::()]).ok_or(RosenpassError::BufferSizeMismatch) + Ref::from_bytes(&buf[..size_of::()]).map_err(|_| RosenpassError::BufferSizeMismatch) } diff --git a/rosenpass/tests/api-integration-tests-api-setup.rs b/rosenpass/tests/api-integration-tests-api-setup.rs index e9fd7530..fb0b3595 100644 --- a/rosenpass/tests/api-integration-tests-api-setup.rs +++ b/rosenpass/tests/api-integration-tests-api-setup.rs @@ -27,7 +27,7 @@ use rosenpass_util::{ }; use std::os::fd::{AsFd, AsRawFd}; use tempfile::TempDir; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; struct KillChild(std::process::Child); diff --git a/rosenpass/tests/api-integration-tests.rs b/rosenpass/tests/api-integration-tests.rs index 340cede3..72a3dcfa 100644 --- a/rosenpass/tests/api-integration-tests.rs +++ b/rosenpass/tests/api-integration-tests.rs @@ -14,7 +14,7 @@ use rosenpass_util::{ }; use rosenpass_util::{mem::DiscardResultExt, zerocopy::ZerocopySliceExt}; use tempfile::TempDir; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use rosenpass::config::ProtocolVersion; use rosenpass::protocol::basic_types::SymKey; diff --git a/util/src/zerocopy/ref_maker.rs b/util/src/zerocopy/ref_maker.rs index 34a0f8f4..8ff3633f 100644 --- a/util/src/zerocopy/ref_maker.rs +++ b/util/src/zerocopy/ref_maker.rs @@ -158,9 +158,8 @@ impl RefMaker { } } impl RefMaker { - /// Splits the buffer into two `RefMaker`s, with the first containing the - /// first containing the beginning `point` bytes and the second containing the + /// first containing the beginning `point` bytes and the second containing the /// following bytes. /// /// # Errors diff --git a/wireguard-broker/src/api/server.rs b/wireguard-broker/src/api/server.rs index aa1ec66c..7467524e 100644 --- a/wireguard-broker/src/api/server.rs +++ b/wireguard-broker/src/api/server.rs @@ -78,10 +78,10 @@ where let typ = msgs::MsgType::try_from(*typ)?; let msgs::MsgType::SetPsk = typ; // Assert type - let req = - zerocopy::Ref::<&[u8], Envelope>::from_bytes(req).map_err(|_| InvalidMessage)?; - let mut res = - zerocopy::Ref::<&mut [u8], Envelope>::from_bytes(res).map_err(|_| InvalidMessage)?; + let req = zerocopy::Ref::<&[u8], Envelope>::from_bytes(req) + .map_err(|_| InvalidMessage)?; + let mut res = zerocopy::Ref::<&mut [u8], Envelope>::from_bytes(res) + .map_err(|_| InvalidMessage)?; res.msg_type = msgs::MsgType::SetPsk as u8; self.handle_set_psk(&req.payload, &mut res.payload)?;