One simple way I can think of is to sanitize user input using a blacklist which contains the commands you do not want to allow, such as the ones you have mentioned. OWASP provides very good explanation about White/Black lists HERE

Answer from Hummus_Ful on Stack Exchange
🌐
GitHub
github.com › 3ls3if › Cybersecurity-Notes › blob › main › real-world-and-and-ctf › scripts-and-systems › python2-input-vulnerability.md
Cybersecurity-Notes/real-world-and-and-ctf/scripts-and-systems/python2-input-vulnerability.md at main · 3ls3if/Cybersecurity-Notes
If an attacker enters malicious code instead of expected input, the interpreter will execute it without any restrictions, potentially allowing the attacker to run arbitrary commands on the system. # Python 2 vulnerable code user_input = input("Enter your name: ") print("Hello, " + user_input + "!")
Author   3ls3if
Discussions

Demo of how input() is security probem in Python 2.7 (4min)
Demo of how writing insecure code is a security problem. More on reddit.com
🌐 r/Python
60
84
March 14, 2018
Be Careful with Python's New-Style String Format
I think the problem is not the new-style string format, every input or output must be sanitized if you want keep it safe. If somebody has access to execute a script you already are vulnerable. It's one more thing to escape :/ This CTF questions show how to access python base class easily https://hexplo.it/escaping-the-csawctf-python-sandbox/ More on reddit.com
🌐 r/Python
32
87
December 29, 2016
🌐
CTFtime.org
ctftime.org › writeup › 27723
CTFtime.org / Cyber Apocalypse 2021 / Input as a Service / Writeup
Maurus Traceback (most recent call ... > The vulnerability in input() method lies in the fact that the variable accessing > the value of input can be accessed by anyone just by using the name of variable or method...
🌐
CyberChef
sevenlayers.com › index.php › 215-abusing-python-input
Abusing Python Input
But if you recall from above, it's evaluating the input so if instead we feed it something like this: It evaluates the expression. In order to abuse this behavior, we can use __import__ to import a module and ultimately, we want it to eval the following: ... We catch a shell. Now let's point it to our victim: ... We catch our shell from the victim. If we wanted to fix our Python script, we'd use raw_input instead of input:
🌐
GitHub
github.com › adeptex › CTF › blob › master › fstring-injection.md
CTF/fstring-injection.md at master · adeptex/CTF
Looks like a Python f-string. So this pwn challenge is about Python injection. According to the docs, {} evalues input before supplying it to the f-string. The vulnerability can be confirmed by creating a key eval('print(1234)') with {} as value:
Author   adeptex
🌐
Medium
medium.com › @GallegoDor › python-exploitation-1-input-ac10d3f4491f
Python Exploitation #1: Input(). This weeks topic 22/2/15: Input() | by Dor Rondel | Medium
June 21, 2015 - The main purpose of these articles, is to prevent security issues by informing readers who might’ve not been aware of these vulnerabilities prior to reading the article. Another motive would be promoting CTF (Capture the Flag) cybersecurity competitions. For the time being, I’ll try releasing these on a weekly basis. With that said, lets get started! Before we dive in, a quick notice. For those of you who are using Python version 3.x, this does NOT apply to you. For those who don’t know, in Python 3, the raw_input() function was erased, and it’s functionality was transferred to a new built-in function known as input().
🌐
Reddit
reddit.com › r/python › demo of how input() is security probem in python 2.7 (4min)
r/Python on Reddit: Demo of how input() is security probem in Python 2.7 (4min)
March 14, 2018 - input() in python 2 is a fun code injection example for CTFs and stuff, but it's not exactly a security problem unless you use it remotely.
Find elsewhere
🌐
GitHub
github.com › ctfs › write-ups-2013 › tree › master › pico-ctf-2013 › python-eval-2
write-ups-2013/pico-ctf-2013/python-eval-2 at master · ctfs/write-ups-2013
Guess it!" print "Rules: You should input your guesses as 5 digits separated by commas." print " I will respond by marking the correct digits with a 2, marking" print " digits in the wrong place with a 1, and marking wrong digits 0." while True: guess = input('guess> ') if len(guess) != 5: print "You must guess a 5-digit code!" continue printpegs(guess) right = map(lambda x,y: (x == y) + (x in mm_code), guess, mm_code) printpegs(right) if guess == mm_code: print "You got it right!" exit(0) This script defines a 'guess' variable with the vulnerable input function.
Author   ctfs
🌐
Gitbooks
reboare.gitbooks.io › booj-security › content › os-agnostic › python.html
Python · booj.security
Further Reading https://blog.nelhage.com/2011/03/exploiting-pickle/ https://sensepost.com/blog/2010/playing-with-python-pickle-#1/ https://dan.lousqui.fr/explaining-and-exploiting-deserialization-vulnerability-with-python-en.html · These are a collection of CTF writeups that may prove helpful if you find yourself against a Python Jail or environment.
🌐
Blogger
anthonyvoza.blogspot.com › 2018 › 10 › rootme-ctf-app-security-python-input.html
Myself is a Bad Boy: RootMe - CTF App Security - Python - input()
October 9, 2018 - If passwd has been defined before the input() statement, I could set as input int(passwd) and in this way, the if statement would be always true. In our case, we need to read the .passwd. To do this, start the program by setuid-wrapper, then we can exploit the vulnerability by inserting __import__("os").system('cat .passwd').
🌐
Blogger
intx0x80.blogspot.com › 2017 › 05 › python-input-vulnerability_25.html
python input vulnerability
May 25, 2017 - input vulnerability it'not stop here but they have ability to read value like you system connect to database can when user enter password it will compare it with password store in database
🌐
GeeksforGeeks
geeksforgeeks.org › vulnerability-input-function-python-2-x
Vulnerability in input() function – Python 2.x - GeeksforGeeks
March 29, 2024 - If "secret_number" is given as input, answer is 'You lose'. The vulnerability lies here as we can even provide the name of a function as input and access values that are otherwise not meant to be accessed.
🌐
Greg Scharf
blog.gregscharf.com › 2023 › 04 › 11 › code-injections
Code Injections :: Greg Scharf — Development & Security
April 11, 2023 - A common CTF example is a calculator embedded in a web app that takes user input and then sends that input directly to eval() as an argument. Here is OWASP’s summary of this vulnerability along with a basic PHP code injection example. A good way to understand how code injection through the Python eval() method works is by doing this yourself in the Python CLI.
🌐
CTFtime.org
ctftime.org › writeup › 9684
CTFtime.org / HITB-XCTF GSEC CTF 2018 Quals / Baby FS / Writeup
### easy\_block (sasdf) #### Vulnerability * We have a service to compute mac for any plaintext. ```python # must be delete! elif choice[0] == 'c': un = input('your username:>>') un = bytes(un, 'ISO-8859-1') print(sha256(mac_key + un).digest().hex()) ``` * Unpad function doesn't check for valid padding that can trim more than 16 bytes.
🌐
Blogger
intx0x80.blogspot.com › 2017 › 06 › backdoor-ctf-evil.html
backdoor CTF evil
June 20, 2017 - ok that flow now time to identify weakness ,input in last python version it act like eval(raw_input) as we know eval it function evaluates a string of text which is passed as its parameter, accepting possible second argument for the global values to use during evaluation. through this we can read super_secret_code by type it in prompt it will read variable and save it in guess and use it in if statement . ... SECURECODE: 1 : OSWE Prep SECURECODE: 1 it's OSWE Like machine which need to do some code reviwing and detect vulnerabilities and chained together to gain final target which remote code execution (RCE).
🌐
StackHawk
stackhawk.com › stackhawk, inc. › vulnerabilities and remediation › preventing command injection in python: a guide to security
Preventing Command Injection in Python: A Guide to Security
January 13, 2025 - Like other injection attacks, unsanitized user input makes command injection possible. And this is irrespective of the programming language used. We say this because even code written in Python, which has a reputation as a secure programming language, can fall prey to injection attacks.
🌐
Wapiflapi
wapiflapi.github.io › 2013 › 04 › 22 › plaidctf-pyjail-story-of-pythons-escape.html
A python's escape from PlaidCTF jail · wapiflapi
It clears the dictionary python uses to find its builtins and we can’t use them anymore except if we already have a reference to the builtin we need somewhere else. There is one protection left, but it doesn’t try to limit what we can do, it only tries to make it harder by filtering out ...
🌐
GitHub
github.com › saurav3199 › CTF-writeups › blob › master › HSCTF6 › README.md
CTF-writeups/HSCTF6/README.md at master · saurav3199/CTF-writeups
March 28, 2021 - So, yeah the vulnerability is here, Great!!! streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999 Welcome to JSON info! Please enter your JSON: !!python/object/apply:os.system ["cat flag.txt"] hsctf{JS0N_or_Y4ML} Type int is unsupported Please use a valid JSON array or object Thank you for using JSON info!
Author   saurav3199