Rejected mjs_delete on a foreign element corrupts both specifications and causes use-after-free
Intro
Hi!
I found a failed-mutation atomicity problem in mjs_delete: asking one specification to delete an element owned by another returns an error, but transfers the element into the wrong specification's detached ownership list before validating ownership.
My setup
- MuJoCo source build from
mainat1fb91483f045c6aaf5207323e2372614043a64fc - C API, double precision
- Ubuntu 24.04.5 LTS, x86_64
- GCC 13.3.0 normal and AddressSanitizer builds
What's happening? What did you expect?
I expected mjs_delete(wrong, foreign) to return -1 without changing either specification. It does return -1 with Error: element is not in this model, but mjCModel::operator-= has already appended the foreign pointer to wrong's detached_ list and reset its tree lists. Destroying wrong frees the object still owned and indexed by the original spec. Compiling the owner then reads freed memory.
foreign_delete_result=-1
wrong_error=Error: element is not in this model
wrong_spec_deleted
ERROR: AddressSanitizer: heap-use-after-free
READ in mjCModel::ProcessList_ ... src/user/user_model.cc:4560Relevant source:
- https://github.com/google-deepmind/mujoco/blob/1fb91483f045c6aaf5207323e2372614043a64fc/src/user/user_model.cc#L694-L712
- https://github.com/google-deepmind/mujoco/blob/1fb91483f045c6aaf5207323e2372614043a64fc/src/user/user_model.cc#L4553-L4568
Steps for reproduction
- Check out the commit above and make a normal or ASan build.
- Compile
poc/reproducer.ccusing the command inpoc/README.md. - Run it. The normal build crashes while compiling the owner; ASan identifies the freed specification element.
Reproduction package:
foreign-spec-delete-ownership-corruption-poc.zip
Minimal model for reproduction
The reproducer creates two empty specifications and adds one site programmatically; no model asset is required.
Code required for reproduction
See poc/reproducer.cc. I also prepared a patch that performs the ownership check before changing body/plugin ownership, detached_, or tree lists. The focused regression passes.
Confirmations
- I searched the latest documentation thoroughly before posting.
- I searched previous Issues and Discussions, I am certain this has not been raised before.
Source: google-deepmind/mujoco