input() 函数中的 Python 漏洞

pythonserver side programmingprogramming更新于 2025/10/26 3:24:17

在本文中,我们将了解 input 函数在 2.x 或更早版本中如何以不良方式运行。在 2.x 版本中,raw_input() 函数可替代 input() 函数。在较新的 3.x 或更高版本中,所有理想的功能 &两个函数的功能都合并到了 input() 函数中。

首先我们来看看 Python 2.x 中用于输入的内置函数的输入类型。

示例

# 输入:字符串
str1 = raw_input("raw_input() 函数的输出:")
print type(str1)
str2 = input("input() 函数的输出:")
print type(str2)
# 输入:浮点数
str3 = raw_input("raw_input() 函数的输出:")
print type(str3)
str4 = input("input() 函数的输出:")
print type(str4)
# 输入:整数
str5 = raw_input("raw_input() 函数的输出: ")
print type(str5)
str6 = input("Input() 函数的输出:")
print type(str6)

输出

raw_input() 函数的输出:
input() 函数的输出:
raw_input() 函数的输出:
input() 函数的输出:
raw_input() 函数的输出:
input() 函数的输出:

解释 − 从输出中可以明显看出,raw_input 函数明确将输入转换为字符串类型,而不管提供的输入类型如何。相反,输入函数保留与输入期间提供的相同的数据类型。

现在,在看到上面的例子后,您可能想知道,如果输入函数保留数据类型,那么为什么它容易受到攻击?让我们用一个例子来解释一下 −

图 1:现在让我们使用随机模块制作一个骰子游戏。

示例

import random as rd
number = random.randint(1,6)
print ("Pick a number between 1 to 6")
while True:
   user_input = input("Guess the number: ")
   if user_input==number:
      print ("You guessed it right.")
      break
   else:
      print ("OOPS! try it next time.")
      continue

解释 − 如果用户提供整数输入,则将根据条件表达式相应地计算所需的输出。

如果用户提供字符串输入,即与我们存储使用随机模块由骰子生成的随机整数的变量名相同,则也会计算输出。但这一定不是我们想要计算的期望输出。实际上,当输入字符串时,它必须引发错误,表示输入类型错误。它将变量名视为用户直接输入的数字,表达式产生 True 布尔值,游戏结束。相反,如果我改用 raw_input(),则不会遇到这样的问题。

如果我们存储登录凭据、用户详细信息和帐户密码,此漏洞可能会造成致命影响。

图 1:现在让我们制作一个系统,要求输入密码并与存储的值进行比较。

示例

stored_value = 7863
def return_function():
   return stored_value
inp = input()
if inp == stored_value:
   print "You Entered Correctly"
else:
   print "Oops! It's Incorrect"

解释

正如我们在前面的插图中所讨论的那样,如果提供的输入是整数类型,则该函数正常工作。但无论如何,只要用户提供的输入与函数的返回值相同,条件就会变为 True 并产生输出。

在处理关键和机密信息(如 PIN 码和密码)时,使用这种方法非常危险。可以使用 Python 2.x 中提供的 raw_input() 来克服这个问题。

从以上两个插图中,可以清楚地看出,输入函数使程序准备好进行直接变量攻击。

结论

在本文中,我们了解了在 Python 2.x 中使用 input() 函数时遇到的所有问题和漏洞。


相关文章


有用资源