fix regressions from upgrading dependency in rosenpass/

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