Skip to content

Function mmap resizes without checking for valid fd

ebranca edited this page Jun 19, 2014 · 1 revision

Classification

  • Affected Components : builtin, mmap

  • Operating System : Linux

  • Python Versions : 2.6.x, 2.7.x, 3.1.x, 3.2.x

  • Reproducible : Yes

Source code

import mmap

m = mmap.mmap(-1, 10)
m[:] = "0123456789"
x = m[:]

print(repr(x))
# '0123456789'

m.resize(20)
y = m[:]
print(repr(y))

Steps to Produce/Reproduce

To reproduce the problem copy the source code in a file and execute the script using the following command syntax:

$ python -OOBRtt test.py

Alternatively you can open python in interactive mode:

$ python -OOBRtt <press enter>

Then copy the lines of code into the interpreter.

Description

The source code generates an error by design:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    m.resize(20)
mmap.error: [Errno 9] Bad file descriptor

In python seemes that file mapping object, the function mmap.resize() resizes the underlying file too.

But for anonymous mapping object the same mmap call does not resize the memory region itself.

Also to note that on linux/unix mmap has a problem as does not checks for situations in which the file descriptor is invalid.

From the unix [documentation][01] we know:

open() returns a file descriptor, a small, non negative integer

and also:

open() and creat() return the new file descriptor, or -1 if an error occurred

Meaning that in unix/linux the file descriptor has to be a small, non negative number.

Python mmap can use the function ftruncate() that does not check for the validity of the number provided as file descriptor and fails for fd == -1.

Workaround

We are not aware on any easy solution other than trying to avoid using 'mmap' for cases like the one examined.

Secure Implementation

WORK IN PROGRESS

References

[open(2)][01] [01]:http://linux.die.net/man/2/open

[open(3)][02] [02]:http://linux.die.net/man/3/open

[Opening and Closing files][03] [03]:http://www.gnu.org/software/libc/manual/html_node/Opening-and-Closing-Files.html

[Python bug 2733][04] [04]:http://bugs.python.org/issue2733

[Python bug 12562][05] [05]:http://bugs.python.org/issue12562?

  • Home
  • [Security Concerns](Security Concerns)
Clone this wiki locally