From 79ae5cab5a4246fc508b26348c07fae58309d1e9 Mon Sep 17 00:00:00 2001 From: Bryan Kersting Date: Fri, 21 Feb 2025 00:36:43 -0800 Subject: [PATCH] Fix unsound Rust reference in np_ffi_CredentialSlab_add_v0_credential Currently, in the Rust implementation of `np_ffi_CredentialSlab_add_v0_credential`, we take the underlying buffer of the passed `V0MatchableCredential` and turn it into a Rust `&[u8]` by calling `unsafe slice::from_raw_parts`. The safety contract of `from_raw_parts` states that the passed pointer can neither be null, nor be unaligned. In the `advertisment_decoder_rust_impl.cc` we have a code path that leads to a null pointer being passed, though. We get a nullpointer if we pass a `std::vector` of size 0. This change fixes the issue by making sure we always pass a non-null buffer. PiperOrigin-RevId: 729417182 --- .../implementation/advertisement_decoder_rust_impl.cc | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/presence/implementation/advertisement_decoder_rust_impl.cc b/presence/implementation/advertisement_decoder_rust_impl.cc index 0f7227b3..7edb11bd 100644 --- a/presence/implementation/advertisement_decoder_rust_impl.cc +++ b/presence/implementation/advertisement_decoder_rust_impl.cc @@ -215,9 +215,14 @@ AdvertisementDecoderImpl::InitializeCredentialBook( nearby_protocol::CredentialSlab slab; for (const auto& credential : (*credentials_map) [internal::IdentityType::IDENTITY_TYPE_PRIVATE_GROUP]) { - std::vector metadata_bytes( - credential.encrypted_metadata_bytes_v0().begin(), - credential.encrypted_metadata_bytes_v0().end()); + // Make sure the vector is not empty, as this is a prerequisite of the Rust + // code we call into. + std::vector metadata_bytes(1); + if (!credential.encrypted_metadata_bytes_v0().empty()) { + metadata_bytes = + std::vector(credential.encrypted_metadata_bytes_v0().begin(), + credential.encrypted_metadata_bytes_v0().end()); + } nearby_protocol::MatchedCredentialData matched_cred(credential.id(), metadata_bytes);