Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cause Python 3.5 to crash?

We are using embedded cpython as a scripting language in our app. We are modifying our sys.path at startup to make sure that we don't execute code from outside our app, but a user with a sitecustomize.py in their PYTHONPATH is causing code to execute before we have a chance to fix sys.path, and we believe their code has a hard crash (not an exception, which site.py will catch and handle gracefully).

I believe the correct fix is to simply clear the PYTHONPATH variable from the environment before we initialize python, but I can't test it properly because I can't recreate the problem.

The simplest way I've found is using ctypes to write to memory, such as:

import ctypes
p = (ctypes.c_char).from_address(0)
while True:
  p[0] = 0
  p = p + 1

But in Python 3.5, it doesn't allow me to write to c_char types, giving the error "TypeError: 'c_char' object does not support item assignment".

I've tried a few of the methods available in https://wiki.python.org/moin/CrashingPython to no avail.

Is there a reliable way to crash python 3.5 from pure Python code?

like image 994
alvion Avatar asked Mar 02 '17 00:03

alvion


People also ask

How do I make Python crash my computer?

To shut down the computer/PC/laptop by using a Python script, you have to use the os. system() function with the code “ shutdown /s /t 1 ” .

Can you crash Python?

While a lot of effort has gone into making it difficult or impossible to crash the Python interpreter in normal usage, there are lots fairly easy ways to crash the interpreter.


3 Answers

Here is a simple way to crash python:

def crash():
    try:
        crash()
    except:
        crash()

crash()
like image 178
Nehemiah Britt Avatar answered Oct 20 '22 04:10

Nehemiah Britt


There are plenty of ways through ctypes. For example, a corrected version of your code:

p = ctypes.pointer(ctypes.c_char.from_address(5))
p[0] = b'x'

If you don't want to use ctypes, you could trigger a C stack overflow in the dict.__repr__ implementation:

x = {}
for i in range(1000000):
    x = {1: x}
repr(x)

This might get patched in a future Python release, but for now, it should produce a hard crash.

There are also ways to do it by constructing your own bytecode objects, since Python does almost nothing to make sure that the bytecode it's executing makes sense.

like image 36
user2357112 supports Monica Avatar answered Oct 20 '22 03:10

user2357112 supports Monica


Simply put 0 / 0 on the line of code you want to trigger the crash. You will get a ZeroDivisionError

I think this is the easiest way to force a crash

like image 31
Rodrigo Santos Avatar answered Oct 20 '22 04:10

Rodrigo Santos