This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: `compile` returns the first line of file on termination
Type: security Stage: resolved
Components: Versions: Python 3.9, Python 3.8, Python 3.7, Python 3.6, Python 3.5, Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: christian.heimes, iso, xtreak
Priority: normal Keywords:

Created on 2019-12-06 09:29 by iso, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg357906 - (view) Author: Koh (iso) Date: 2019-12-06 09:29
By specifying a filename in the compile function and then improperly terminating it, we are able to return the first line of any file.

>> compile('yield', '/etc/passwd', 'exec')
File "/etc/passwd", line 1
    root:x:0:0:root:/root:/bin/bash
    ^
SyntaxError: 'yield' outside function

Is this intended behavior? I have been able to use it to escape sandboxes.
msg357907 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2019-12-06 10:22
It's not necessarily the first line. The code is executed with the context of the given file. Hence the corresponding line number of error from traceback with respect to file is printed.

$ cat /tmp/passwd
line 1
line 2
line 3
line 4

$ python3 -c 'compile("\n\n\nyield", "/tmp/passwd", "exec")'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/tmp/passwd", line 4
    line 4
    ^
SyntaxError: 'yield' outside function
msg357908 - (view) Author: Christian Heimes (christian.heimes) * (Python committer) Date: 2019-12-06 10:26
Yes, that is expected behavior.

 Python is not designed for sandboxing and doesn't support sandboxing. *If* Python would support sandboxing, then compile() would be one of the first functions to go, because it allows an attacker to construct custom executable code.
History
Date User Action Args
2022-04-11 14:59:24adminsetgithub: 83166
2019-12-06 10:33:42serhiy.storchakasetstatus: open -> closed
resolution: not a bug
stage: resolved
2019-12-06 10:26:13christian.heimessetnosy: + christian.heimes
messages: + msg357908
2019-12-06 10:22:08xtreaksetnosy: + xtreak
messages: + msg357907
2019-12-06 09:29:05isocreate