Skip to content

Potential Integer Overflow in cpSpaceAddCachedArbiter #300

@mpap10

Description

@mpap10

We are researchers from the University of Athens, working on cross-language analysis of Python packages with C/C++ native extensions.

Problem

We found an issue in the pymunk package. The function cpSpaceAddCachedArbiter() [1] does not check arb->count [2] before copying them.
If arb->count is large, multiplying it by the size of the contact structure [3] can overflow, producing a smaller value. This causes memcpy() [3] to write past the allocated memory, which can lead to crashes or segmentation faults.

Steps to Reproduce

Open a terminal and run the following Python script:

import pymunk, sys

ffi = pymunk._chipmunk.ffi
lib = pymunk._chipmunk.lib

space = pymunk.Space()
arb = ffi.new("cpArbiter*")
arb.contacts = ffi.new("struct cpContact[]", 1)

count = 1000
for _ in range(10):
    print(count); sys.stdout.flush()
    arb.count = count
    lib.cpSpaceAddCachedArbiter(space._space, arb)
    count *= 2

You should observe an immediate crash:

1000
Segmentation fault (core dumped)

Potential Fix

  • Validate the contact count to prevent an integer overflow when multiplying by the size of the contact structure.
  • Ensure the total size does not overflow and fits within the allocated buffer before memcpy call.

References

[1]

void cpSpaceAddCachedArbiter(cpSpace *space, cpArbiter *arb)

[2]
int numContacts = arb->count;

[3]
memcpy(arb->contacts, contacts, numContacts * sizeof(struct cpContact));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions