`ApplyOptions` and `StashApplyOptions` store their own address as the callback payload, so moving them after registering a callback is a use-after-free (safe code)

Abierto
#1,367 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
68/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Área
devtools

Línea de trabajo

Start with src/apply.rs and src/stash.rs, where callback payloads are registered and raw() is called before the FFI operations. Compare the pointer setup with CheckoutBuilder::configure in src/build.rs, which refreshes its payload immediately before use. The change is done when moving the options no longer leaves a stale address in raw.payload or raw_opts.progress_payload, and both apply and stash callback variants pass under AddressSanitizer.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

ApplyOptions::hunk_callback and delta_callback (src/apply.rs:120-144) set
self.raw.payload = self as *mut _ when the callback is registered, and
StashApplyOptions::progress_cb (src/stash.rs:128-136) does the same with
raw_opts.progress_payload. Neither raw() (apply.rs:151, stash.rs:139) refreshes that pointer.
If the options value is moved between registering the callback and calling Repository::apply,
apply_to_tree, stash_apply or stash_pop, libgit2 passes the old address to the trampoline
(hunk_cb_c, delta_cb_c, stash_apply_progress_cb), which dereferences it as &mut ApplyOptions
/ &mut StashApplyOptions. Returning the options from a helper function is enough:

#![forbid(unsafe_code)]
use git2::{ApplyLocation, ApplyOptions, Repository, Signature, StashApplyOptions};
use std::path::Path;

fn apply_options<'a>() -> ApplyOptions<'a> {
    let mut opts = Box::new(ApplyOptions::new());
    opts.hunk_callback(|_| true); // raw.payload = address of *opts
    *opts // moved out; the box is freed, the payload still points into it
}

fn stash_options<'a>() -> StashApplyOptions<'a> {
    let mut opts = Box::new(StashApplyOptions::new());
    opts.progress_cb(|_| true); // raw_opts.progress_payload = address of *opts
    *opts
}

fn main() {
    let dir = std::env::temp_dir().join(format!("git2-options-moved-{}", std::process::id()));
    let mut repo = Repository::init(&dir).unwrap();
    std::fs::write(dir.join("f"), "one\n").unwrap();
    let mut index = repo.index().unwrap();
    index.add_path(Path::new("f")).unwrap();
    index.write().unwrap();
    let tree = index.write_tree().unwrap();
    std::fs::write(dir.join("f"), "two\n").unwrap();

    if std::env::args().nth(1).as_deref() == Some("stash") {
        let sig = Signature::now("a", "[email protected]").unwrap();
        repo.commit(Some("HEAD"), &sig, &sig, "c", &repo.find_tree(tree).unwrap(), &[]).unwrap();
        repo.stash_save(&sig, "wip", None).unwrap();
        repo.stash_pop(0, Some(&mut stash_options())).unwrap();
    } else {
        let diff = repo.diff_index_to_workdir(None, None).unwrap();
        repo.apply(&diff, ApplyLocation::Index, Some(&mut apply_options())).unwrap();
    }
    let _ = std::fs::remove_dir_all(&dir);
}

Run against git2-rs b9d59b6 (main, git2 0.21.0) with the vendored libgit2 1.9.7, under
AddressSanitizer, with no argument (trimmed):

ERROR: AddressSanitizer: heap-use-after-free
READ of size 8 at 0x7864115f9b60 thread T0
    #0 git2::apply::hunk_cb_c::{closure#0} src/apply.rs:74:30
    #7 apply_hunk libgit2/src/libgit2/apply.c:199:11
    #12 git_apply libgit2/src/libgit2/apply.c:862:15
    #13 <git2::repo::Repository>::apply src/call.rs:13:39
    #14 repro_apply_options_move::main src/main.rs:34:14
0x7864115f9b60 is located 0 bytes inside of 72-byte region
freed by thread T0 here:
    #4 repro_apply_options_move::apply_options src/main.rs:9:1

With stash the read is in stash_apply_progress_cb (src/stash.rs:201), called from
git_stash_apply (stash.c:1061). Without a sanitizer the default variant segfaults.

Possible fix

Set the payload in raw(), which takes &mut self immediately before the FFI call, instead of in
the setters; CheckoutBuilder::configure already does this (src/build.rs:592, :596). With that
change both variants above run clean. It is not a breaking change.

Found by Crustify, an
experimental UB/soundness auditing agent developed at UC Berkeley and running
on Claude Opus 4.5, then manually reviewed and independently reproduced.

Lenguaje dominante
Rust
Estrellas
2.1k
Forks
470
Merge medio
2 d 17 h
PR fusionados (30 d)
18

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de rust-lang/git2-rs

Todos los issues de rust-lang/git2-rs

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.