Misaligned pointer dereference in `Ref` due to incomplete `ByteSlice` move-stability contract

Đang mở Phù hợp với người mới
#3,766 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
1/5
Thời gian dự kiến
Dưới một giờ
Mức phù hợp với người mới
88/100
Loại issue
Tài liệu
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
rust
Lĩnh vực
documentation

Hướng nghiên cứu

Bắt đầu với hợp đồng an toàn của ByteSlice trong zerocopy/src/byte_slice.rs:37-52, sau đó đọc Ref::from_bytes trong zerocopy/src/ref.rs:311-320 và ví dụ tests/poc.rs đính kèm để có thêm ngữ cảnh. Công việc được xem là hoàn tất khi hợp đồng nêu rõ khả năng ổn định khi di chuyển và loại trừ việc lưu trữ inline, mà không thay đổi phần triển khai.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

See also: #716

Agent-discovered bug, and agent-authored writeup.

Summary

The # Safety contract on pub unsafe trait ByteSlice (zerocopy/src/byte_slice.rs:37-52) requires dereference stability across calls on a single binding b: B:

Given B: ByteSlice and b: B, two calls, each to either b.deref() or b.deref_mut(), must return a byte slice with the same address and length. This must hold even if the two calls are separated by an arbitrary sequence of calls to methods on ByteSlice, ByteSliceMut, IntoByteSlice, or IntoByteSliceMut, or on their super-traits.

The contract does not require that the slice address returned by deref() / deref_mut() be independent of the address of b itself (i.e., stable across moves of b). Consequently, a type with inline storage (such as struct Inline([u8; N]) whose Deref returns &self.0[..]) satisfies the documented # Safety contract as written.

However, Ref::<B, T>::from_bytes (zerocopy/src/ref.rs:311-320) validates the size and alignment of source.deref() before moving source by value into Ref::new_unchecked(source):

pub fn from_bytes(source: B) -> Result<Ref<B, T>, CastError<B, T>> {
    static_assert_dst_is_not_zst!(T);
    if let Err(e) =
        Ptr::from_ref(source.deref()).try_cast_into_no_leftover::<T, BecauseImmutable>(None)
    {
        return Err(e.with_src(()).with_src(source));
    }
    // SAFETY: `try_cast_into_no_leftover` validates size and alignment.
    Ok(unsafe { Ref::new_unchecked(source) })
}

Subsequent operations on Ref<B, T>—such as Ref::read (zerocopy/src/ref.rs:769), Ref::write (zerocopy/src/ref.rs:794), <Ref as Deref>::deref (zerocopy/src/ref.rs:823), and <Ref as DerefMut>::deref_mut (zerocopy/src/ref.rs:872)—call b.deref() on the relocated B inside Ref and assume its pointer is still aligned for T. When B uses inline storage with alignment 1, moving source into Ref (or moving Ref itself) changes the address of the slice and can misalign it relative to T, causing a misaligned pointer dereference (Undefined Behavior).

Affected Files
  • zerocopy/src/byte_slice.rs
  • zerocopy/src/ref.rs

Proof of Concept & Attachments

poc.rs
//! POC: `ByteSlice` safety contract omits move-stability; `Ref` validates
//! alignment pre-move and assumes it post-move.
//!
//! This test contains exactly ONE `unsafe` keyword: the
//! `unsafe impl ByteSlice for Inline {}` line. That impl satisfies the
//! *documented* `# Safety` contract on `ByteSlice` (byte_slice.rs:37-52) as
//! written — see the SAFETY comment on the impl. Everything else is safe code
//! calling zerocopy's safe public API.
//!
//! `Ref::<Inline, u16>::from_bytes` validates alignment at `source`'s pre-move
//! address (ref.rs:314), then moves `source` into `Ref.0` (ref.rs:319).
//! `Ref::read` later does `ptr::read::<u16>` on the post-move address
//! (ref.rs:769) without re-checking. Because `align_of::<Inline>() == 1`, we
//! can move the `Ref` to an odd address → misaligned `ptr::read` → UB.

use core::ops::Deref;
use zerocopy::{ByteSlice, Ref};

/// A byte-slice type whose referent is its own inline storage.
/// `align_of::<Inline>() == 1`.
struct Inline([u8; 2]);

impl Deref for Inline {
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        &self.0[..]
    }
}

// SAFETY (per the documented contract at byte_slice.rs:37-52):
// "given `B: ByteSlice` and `b: B`, two calls, each to either `b.deref()` or
// `b.deref_mut()`, must return a byte slice with the same address and length.
// This must hold even if the two calls are separated by an arbitrary sequence
// of calls to methods on `ByteSlice`, `ByteSliceMut`, `IntoByteSlice`, or
// `IntoByteSliceMut`, or on their super-traits."
//
// For any fixed binding `b: Inline`, `b.deref()` returns `&b.0[..]`. None of
// the enumerated operations relocate `b`, so the returned address and length
// are identical across any such sequence. The carve-out clause ("does not need
// to hold if separated by any method calls, field accesses, or field
// modifications other than those from these traits") is not triggered. Moves
// of `b` are neither in the stability-preserving list nor the carve-out list;
// after a move, `b` no longer exists, so the "two calls to `b.deref()`" clause
// is vacuously satisfied.
unsafe impl ByteSlice for Inline {}

/// Force a `Ref<Inline, u16>` (which itself has alignment 1) to live at an odd
/// address: `Holder` is 8-aligned via the ZST array, and `r` sits at offset 1.
#[repr(C)]
struct Holder {
    _align: [u64; 0],
    _pad: u8,
    r: Ref<Inline, u16>,
}

/// Try `from_bytes` at recursion depth `d`. Under Miri, each stack frame's
/// `source` parameter gets a fresh allocation; varying depth varies its
/// concrete address, so eventually it lands 2-aligned and the runtime
/// alignment check inside `from_bytes` passes.
#[inline(never)]
fn attempt(d: usize) -> Option<Ref<Inline, u16>> {
    if d == 0 {
        Ref::<Inline, u16>::from_bytes(Inline([0xAB, 0xCD])).ok()
    } else {
        attempt(d - 1)
    }
}

#[test]
fn poc() {
    // `Ref<Inline, u16>` is align-1, so we can place it at an odd offset.
    assert_eq!(core::mem::align_of::<Ref<Inline, u16>>(), 1);
    assert_eq!(core::mem::align_of::<Holder>(), 8);

    // Step 1: obtain a `Ref` by finding a stack depth at which the align-1
    // `source` parameter inside `from_bytes` happens to be 2-aligned.
    let mut found = None;
    for d in 0..512 {
        if let Some(r) = attempt(d) {
            eprintln!("from_bytes succeeded at recursion depth {d}");
            found = Some(r);
            break;
        }
    }
    let r = found.expect(
        "from_bytes never succeeded across 512 stack depths — the align-1 \
         `source` local inside from_bytes was never 2-aligned. Try a different \
         `-Zmiri-seed`. The documentation gap exists regardless.",
    );

    // Step 2: move the `Ref` to a guaranteed-odd address.
    let h = Box::new(Holder { _align: [], _pad: 0, r });
    let inner_addr = Ref::bytes(&h.r).as_ptr() as usize;
    eprintln!(
        "post-move Inline storage at {inner_addr:#x} (2-aligned: {})",
        inner_addr % 2 == 0
    );

    // Step 3: safe zerocopy API call that assumes post-move alignment.
    // `Ref::read` at ref.rs:769 performs
    //     ptr::read(b.deref().as_ptr().cast::<u16>())
    // on the post-move address — a misaligned load. Miri reports UB here.
    let v: u16 = Ref::read(&h.r);
    eprintln!("read: {v:#06x}");
}
output.log
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.06s
     Running tests/poc.rs (/tmp/cargo-target/miri/aarch64-unknown-linux-gnu/debug/deps/poc-6cf15f38e3822cc3)

running 1 test
test poc ... from_bytes succeeded at recursion depth 1
post-move Inline storage at 0x11f731 (2-aligned: false)
error: Undefined Behavior: accessing memory based on pointer with alignment 1, but alignment 2 is required
   --> src/ref.rs:769:18
    |
769 |         unsafe { ptr::read(b.deref().as_ptr().cast::<T>()) }
    |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here
    |
    = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
    = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
    = note: this is on thread `poc`
    = note: stack backtrace:
            0: zerocopy::r#ref::<impl zerocopy::Ref<Inline, u16>>::read
                at src/ref.rs:769:18: 769:59
            1: poc
                at tests/poc.rs:103:18: 103:33
            2: poc::{closure#0}
                at tests/poc.rs:70:9: 70:9

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace

error: aborting due to 1 previous error
fix.patch
diff --git a/zerocopy/src/byte_slice.rs b/zerocopy/src/byte_slice.rs
index 2c5ea3a5e..2cadc3030 100644
--- a/zerocopy/src/byte_slice.rs
+++ b/zerocopy/src/byte_slice.rs
@@ -49,6 +49,13 @@ use crate::Ref;
 /// Note that this also implies that, given `b: B`, the address and length
 /// cannot be modified via objects other than `b`, either on the same thread or
 /// on another thread.
+///
+/// Additionally, the address and length returned by `deref()`/`deref_mut()`
+/// must not depend on the address of `b` itself: given `b: B` and `b2: B`
+/// produced by moving `b`, `b2.deref()` must return a byte slice with the same
+/// address and length that `b.deref()` returned before the move. In other
+/// words, `B` must semantically hold a *reference to* a byte slice rather than
+/// inline byte storage.
 pub unsafe trait ByteSlice: Deref<Target = [u8]> + Sized {}
 
 /// A mutable reference to a byte slice.

Suggested Fix

Update the # Safety documentation for pub unsafe trait ByteSlice in zerocopy/src/byte_slice.rs:37-52 to explicitly require move-stability—i.e., that the address and length of the slice returned by deref() / deref_mut() are preserved across moves of b (and therefore cannot point to inline storage within Self).

Ngôn ngữ chính
Rust
Star
2.6k
Fork
194
Merge trung bình
18 giờ 15 phút
Pull request đã merge (30 ngày)
14

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của google/zerocopy

Tất cả issue của google/zerocopy

Issue tương tự

Thêm issue về Rust

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.