`TryFromBytes` derive emits `ProjectField` over-claiming `Shared` aliasing on enum fields

未关闭
#3,757 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
45/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
rust
领域
security, tooling

调研方向

Start in zerocopy/zerocopy-derive/src/derive/try_from_bytes.rs at the emitted ProjectField implementation, then read the ProjectField contract in zerocopy/src/lib.rs and the Shared invariant in zerocopy/src/pointer/invariant.rs. Use the enum example and Miri outputs in the issue to validate the behavior. Done means Shared projections no longer over-claim aliasing for overlapping enum fields while supported projections still work.

由索引模型根据 Issue 内容生成。

描述

Agent-discovered bug, and agent-authored writeup.

Summary

The TryFromBytes derive macro for data-carrying enums unconditionally emits an unsafe impl ProjectField for every field of every variant that is generic over the full Aliasing lattice, including Shared, with type Error = Infallible;.

When an enum contains multiple variants with mismatched UnsafeCell coverage at overlapping byte offsets (e.g., Cell<u8> in one variant and u8 in another at the same byte offset), instantiating this projection under the Shared aliasing mode violates the safety contract of ProjectField.

Projecting a Shared pointer to the non-UnsafeCell field (u8) yields a Ptr whose Shared invariant asserts that the referent bytes cannot be concurrently mutated. Meanwhile, a concurrent projection from a copy of the same Shared enum pointer to the Cell<u8> field yields a Ptr whose Shared invariant permits interior mutation. Safe Rust code can thus materialize coexisting &u8 and &Cell<u8> references to the exact same byte offset; mutating through the Cell while the &u8 is live triggers Undefined Behavior under both Stacked Borrows and Tree Borrows.

Affected Files
  • zerocopy/zerocopy-derive/src/derive/try_from_bytes.rs
  • zerocopy/src/lib.rs
  • zerocopy/src/pointer/ptr.rs

Detailed Execution Flow

  1. Overlapping enum with mismatched interior mutability:
    #[derive(TryFromBytes, IntoBytes, KnownLayout)]
    #[repr(u8)]
    enum E {
        A(core::cell::Cell<u8>),
        B(u8),
    }
    
    Both variants store their payload at byte offset 1.
  2. Derive macro emits ProjectField:
    In zerocopy/zerocopy-derive/src/derive/try_from_bytes.rs:272-294, TryFromBytes emits an unsafe impl<Aliasing, Alignment> ProjectField<..., (Aliasing, Alignment, Initialized), ...> for E for every field of every variant, declaring type Error = Infallible; and type Invariants = (Aliasing, Alignment, Initialized);.
  3. Safety contract violation:
    The safety contract of ProjectField (zerocopy/src/lib.rs:1266-1271) requires that the projected pointer's invariants are supported by the source pointer. The Shared aliasing invariant (zerocopy/src/pointer/invariant.rs:115-125) states that memory must not be mutated except via UnsafeCells. A Ptr<'_, E, (Shared, ...)> permits mutation at byte 1 because variant A contains an UnsafeCell, whereas the projected Ptr<'_, u8, (Shared, ...)> for variant B asserts no UnsafeCell coverage at byte 1.
  4. Reaching Ptr<'_, E, (Shared, Aligned, Initialized)> from safe code:
    • Ptr::from_mut(&mut buf[..]) produces Ptr<'_, [u8], (Exclusive, Aligned, Valid)>.
    • .try_cast_into::<E, BecauseExclusive>(CastType::Prefix, None) produces Ptr<'_, E, (Exclusive, Aligned, Initialized)> (satisfying E: Read<Exclusive, BecauseExclusive>).
    • .reborrow_shared() degrades aliasing to Ptr<'_, E, (Shared, Aligned, Initialized)>, which is Copy.
  5. Concurrent projections to both variants:
    • Projecting variant B's field 0 yields Ptr<'_, u8, (Shared, Aligned, Initialized)>, which upgrades via .recall_validity::<Valid, BecauseImmutable>().as_ref() to ru8: &u8.
    • Projecting variant A's field 0 from the copied Ptr yields Ptr<'_, Cell<u8>, (Shared, Aligned, Initialized)>, which upgrades via .recall_validity::<Valid, (BecauseMutationCompatible, BecauseInvariantsEq)>().as_ref() to rcell: &Cell<u8>.
    • Calling rcell.set(42) while ru8 is live and subsequently reading *ru8 violates Rust's aliasing rules.

Proof of Concept & Attachments

poc.rs
//! Safe-code witness for the derive-emitted enum-variant `ProjectField` impl
//! that is generic over `Aliasing` (including `Shared`) with `Error = Infallible`.
//!
//! Route to `Ptr<E, (Shared, Aligned, Initialized)>` without `E: FromBytes`:
//!   `&mut [u8]` -> `Ptr<[u8], (Exclusive,_,Valid)>`
//!     -> `.try_cast_into::<E, BecauseExclusive>()`         (E: Read<Exclusive,_>)
//!     -> `Ptr<E, (Exclusive, Aligned, Initialized)>`
//!     -> `.reborrow_shared()`
//!     -> `Ptr<E, (Shared, Aligned, Initialized)>`          (Copy)
//!
//! From there, project both variant `A`'s `Cell<u8>` field and variant `B`'s
//! `u8` field via the derive-emitted `ProjectField` impls, then materialize
//! `&Cell<u8>` and `&u8` at the same byte. Writing through the `Cell` while
//! `&u8` is live is UB (Stacked/Tree Borrows).
//!
//! No `unsafe` appears in this file.

#![allow(dead_code)]

use core::cell::Cell;
use zerocopy::pointer::invariant::Valid;
use zerocopy::pointer::transmute::BecauseInvariantsEq;
use zerocopy::pointer::BecauseMutationCompatible;
use zerocopy::{BecauseExclusive, BecauseImmutable, CastType, Ptr};
use zerocopy_derive::{IntoBytes, KnownLayout, TryFromBytes};

#[derive(TryFromBytes, IntoBytes, KnownLayout)]
#[repr(u8)]
enum E {
    A(Cell<u8>),
    B(u8),
}

#[test]
fn poc() {
    // discriminant = 0 (variant A), payload = 1
    let mut buf: [u8; 2] = [0, 1];

    // Ptr<[u8], (Exclusive, Aligned, Valid)>
    let bytes = Ptr::from_mut(&mut buf[..]);
    // Ptr<E, (Exclusive, Aligned, Initialized)>
    let (mut pe, _rem) = bytes
        .try_cast_into::<E, BecauseExclusive>(CastType::Prefix, None)
        .map_err(drop)
        .unwrap();
    // Ptr<E, (Shared, Aligned, Initialized)> — Copy at Shared aliasing
    let ps = pe.reborrow_shared();

    // ----- Project variant B, field 0 → &u8 ------------------------------
    // Uses the derive-emitted
    //   unsafe impl<Aliasing, Alignment>
    //     ProjectField<(), (Aliasing, Alignment, Initialized), ident_id!(B), ident_id!(0)>
    //     for E { type Error = Infallible; type Invariants = (Aliasing, Alignment, Initialized); }
    // instantiated at Aliasing = Shared. This impl over-claims: the output
    // Ptr<u8, (Shared, _, Initialized)> forbids all mutation of its referent,
    // but the input Ptr<E, (Shared, _, Initialized)> permits mutation via
    // variant A's UnsafeCell at the same byte.
    let pb = ps.project::<(), { zerocopy::ident_id!(B) }, 0>();
    let pb = match pb {
        Ok(x) => x,
        Err(never) => match never {},
    };
    // u8: Immutable + FromBytes ⇒ recall_validity::<Valid, BecauseImmutable> is available
    let ru8: &u8 = pb.recall_validity::<Valid, BecauseImmutable>().as_ref();

    // ----- Project variant A, field 0 → &Cell<u8> ------------------------
    // Same derive-emitted ProjectField impl shape, for variant A.
    let pa = ps.project::<(), { zerocopy::ident_id!(A) }, 0>();
    let pa = match pa {
        Ok(x) => x,
        Err(never) => match never {},
    };
    // Cell<u8>: FromBytes + IntoBytes + InvariantsEq<Cell<u8>>
    let rcell: &Cell<u8> = pa
        .recall_validity::<Valid, (BecauseMutationCompatible, BecauseInvariantsEq)>()
        .as_ref();

    // ----- UB: write through Cell while &u8 (SharedReadOnly) is live -----
    let before = *ru8;
    rcell.set(42);
    let after = *ru8;
    assert_eq!((before, after), (1, 42));
}
output.log (Miri Stacked Borrows)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 10.09s
     Running tests/poc.rs (/tmp/cargo-target/miri/aarch64-unknown-linux-gnu/debug/deps/poc-29210f9c7ea96872)

running 1 test
test poc ... error: Undefined Behavior: attempting a read access using <126065> at alloc41173[0x1], but that tag does not exist in the borrow stack for this location
  --> tests/poc.rs:81:17
   |
81 |     let after = *ru8;
   |                 ^^^^ this error occurs as part of an access at alloc41173[0x1..0x2]
   |
   = help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental
   = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information
help: <126065> was created by a SharedReadOnly retag at offsets [0x1..0x2]
  --> tests/poc.rs:64:20
   |
64 |     let ru8: &u8 = pb.recall_validity::<Valid, BecauseImmutable>().as_ref();
   |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: <126065> was later invalidated at offsets [0x1..0x2] by a Unique retag
  --> tests/poc.rs:80:5
   |
80 |     rcell.set(42);
   |     ^^^^^^^^^^^^^
   = note: this is on thread `poc`
   = note: stack backtrace:
           0: poc
               at tests/poc.rs:81:17: 81:21
           1: poc::{closure#0}
               at tests/poc.rs:35:9: 35:9

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

error: aborting due to 1 previous error
output-tree-borrows.log (Miri Tree Borrows)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
     Running tests/poc.rs (/tmp/cargo-target/miri/aarch64-unknown-linux-gnu/debug/deps/poc-29210f9c7ea96872)

running 1 test
test poc ... error: Undefined Behavior: read access through <123842> at alloc41173[0x1] is forbidden
  --> tests/poc.rs:81:17
   |
81 |     let after = *ru8;
   |                 ^^^^ Undefined Behavior occurred here
   |
   = help: this indicates a potential bug in the program: it performed an invalid operation, but the Tree Borrows rules it violated are still experimental
   = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/tree-borrows.md for further information
   = help: the accessed tag <123842> has state Disabled which forbids this child read access
help: the accessed tag <123842> was created here, in the initial state Frozen
  --> tests/poc.rs:64:20
   |
64 |     let ru8: &u8 = pb.recall_validity::<Valid, BecauseImmutable>().as_ref();
   |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: the accessed tag <123842> later transitioned to Disabled due to a foreign write access at offsets [0x1..0x2]
  --> tests/poc.rs:80:5
   |
80 |     rcell.set(42);
   |     ^^^^^^^^^^^^^
   = help: this transition corresponds to a loss of read permissions
   = note: this is on thread `poc`
   = note: stack backtrace:
           0: poc
               at tests/poc.rs:81:17: 81:21
           1: poc::{closure#0}
               at tests/poc.rs:35:9: 35: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/zerocopy-derive/src/derive/try_from_bytes.rs b/zerocopy/zerocopy-derive/src/derive/try_from_bytes.rs
index 8a7741f39..5c2514af7 100644
--- a/zerocopy/zerocopy-derive/src/derive/try_from_bytes.rs
+++ b/zerocopy/zerocopy-derive/src/derive/try_from_bytes.rs
@@ -279,17 +279,21 @@ pub(crate) fn derive_is_bit_valid(
                     // here; we use `()`.
                     field: field.clone(),
                     field_id: parse_quote!({ #zerocopy_crate::ident_id!(#ident) }),
-                    invariants: parse_quote!((Aliasing, Alignment, #zerocopy_crate::invariant::Initialized)),
+                    // Restricting to `Exclusive` because at `Shared`
+                    // the projected field's `UnsafeCell` coverage may not match
+                    // the enum's (variants can overlap with mismatched
+                    // interior-mutability), so the `Shared` invariant on the
+                    // output `Ptr` would over-claim immutability.
+                    invariants: parse_quote!((#zerocopy_crate::invariant::Exclusive, Alignment, #zerocopy_crate::invariant::Initialized)),
                 },
                 FieldBounds::None,
             )
             .param_extras(vec![
-                parse_quote!(Aliasing: #zerocopy_crate::invariant::Aliasing),
                 parse_quote!(Alignment: #zerocopy_crate::invariant::Alignment),
             ])
             .inner_extras(quote! {
                 type Error = #zerocopy_crate::util::macro_util::core_reexport::convert::Infallible;
-                type Invariants = (Aliasing, Alignment, #zerocopy_crate::invariant::Initialized);
+                type Invariants = (#zerocopy_crate::invariant::Exclusive, Alignment, #zerocopy_crate::invariant::Initialized);
             })
             .build();

Suggested Fix

Modify zerocopy/zerocopy-derive/src/derive/try_from_bytes.rs to restrict the generated ProjectField implementation for enum fields to #zerocopy_crate::invariant::Exclusive instead of making it generic over Aliasing.

主要语言
Rust
星标
2.6k
派生
194
平均合并
18 小时 15 分钟
30 天内合并 PR
14

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

google/zerocopy 的其他 Issue

查看 google/zerocopy 的全部 Issue

相似的 Issue

更多 Rust Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。