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

时间:2017-05-26 15:40:39

标签: python python-2.7 input

我一直在尝试使用python 2.7的input()函数,并试图找到利用它的方法。我知道它本身很容易受到攻击,因为你可以输入python表达式,然后对其进行评估。我的问题是,如果你把它作为一个字符串,即:

str(input())

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

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

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

5 个答案:

答案 0 :(得分:11)

  

有没有办法利用input()并输出“RIGHT password”?

是的:

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>

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

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>

“好吧,好吧,在一个真实的应用程序中,我不会使用random.randint来确定密码。给我看一个条件inp == "hunter2":通过的示例”

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

“这不算数,因为你读了这个文件。给我举个例子,你不从源代码中提取密码”

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>

答案 1 :(得分:2)

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="table_div"></div>必须先处理字符串,然后才能返回input的值,将返回转换为字符串。所以不,&#34;铸造&#34;不安全。

答案 2 :(得分:1)

要回答您的具体示例:字符串[random.seed(1), random.randint(0, 100), random.seed(1)][1]将始终生成&#34; RIGHT密码&#34;。它的工作原理是强制生成的随机数为已经看过的随机数。

答案 3 :(得分:0)

尝试输入&#34;退出()&#34;作为字符串内容,它将杀死解释器。施展到str并没有改变任何东西。

答案 4 :(得分:0)

没有。你误会了。

您所做的就是将input()中运行代码的结果转换为字符串。无论是否将返回值强制转换为字符串,Python仍将在input()中运行代码。将input()的结果转换为字符串对其漏洞没有帮助:

>>> str(input('enter> ')) # Python will still run the code.
enter> 1 + 10 * 5
'51' 
>>>