Skip to content

Double free from safe code when dropping a cloned Handle #32

Description

@Ollie-Pearce

Handle derives Clone, which bitwise-copies its pointer field. The Drop implementation for Handle frees the pointee unconditionally, so cloning an instance of Handle and dropping both copies causes a double-free.

#[derive(Clone)]
pub struct Handle {
    handle: *mut pcap_sys::pcap_t,
    live_capture: bool,
    interrupted: std::sync::Arc<std::sync::Mutex<bool>>,
}

impl Drop for Handle {
    fn drop(&mut self) {
        self.close();
    }
}

Reproducing:

use pcap_async::Handle;

#[test]
fn handle_double_free() {
    let foo = Handle::dead(0, 0).unwrap();
    let bar: Handle = (*foo).clone();

    drop(bar); // pcap_close(handle)
    drop(foo); // SAME pcap_t, closed again
}

You can run the above test with valgrind and see an Invalid read error.

cargo test --test repro --no-run
valgrind --leak-check=no ./target/debug/deps/repro-<HASH>

Fix:

  • Drop #[derive(Clone)] on Handle.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions