Skip to content

PyClassGuardMap has wrong variance for mutable maps #6072

Description

@davidhewitt

Definition of PyClassGuardMap is

pub struct PyClassGuardMap<'a, U: ?Sized, const MUT: bool> {
    ptr: NonNull<U>,
    checker: &'a dyn PyClassBorrowChecker,
}

the NonNull<U> is covariant over U, but &mut U is invariant.

This allows e.g. the following #[pyclass] to be vulnerable:

#[pyclass]
struct Victim {
    s: &'static str,
}

when mapping Victim::s by a PyClassGuardMut::map, it is then possible to overwrite the mapped &'static str with a short-lived &str due to the covariance.

cc @Icxolu - I took a look at fixing this. We probably want to add a PhantomData<&mut U> field to make the PyClassGuardMap<U, true> invariant. I think it'll be hard to do it internally to the PyClassGuardMap struct conditional on the const MUT, I wonder if we need to split out a separate PyClassGuardMutMap type?

(Credit to Codex security scanning for this discovery.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions