Python input() 函式的漏洞
在本文中,我們將學習 input 函式在 2.x 或更早版本中如何表現出不良行為。在 2.x 版本中,raw_input() 函式可以替代 input() 函式。在 3.x 或更高版本中,這兩個函式的所有理想特性和功能都合併到了 input() 函式中。
首先,讓我們看看 Python 2.x 中用於獲取輸入的內建函式的輸入型別。
示例
# Input Given : String
str1 = raw_input("Output of raw_input() function: ")
print type(str1)
str2 = input("Output of input() function: ")
print type(str2)
# Input Given : Float
str3 = raw_input("Output of raw_input() function: ")
print type(str3)
str4 = input("Output of input() function: ")
print type(str4)
# Input Given : Integer
str5 = raw_input("Output of raw_input() function: ")
print type(str5)
str6 = input("Output of input() function: ")
print type(str6)輸出
Output of raw_input() function: Output of input() function: Output of raw_input() function: Output of input() function: Output of raw_input() function: Output of input() function:
說明 − 從輸出中可以很明顯地看出,raw_input 函式會將輸入顯式轉換為字串型別,而不管提供的輸入型別是什麼。相反,input 函式會保留與輸入期間提供的相同的資料型別。
現在,在看到上面的例子之後,您可能想知道,如果 input 函式保留資料型別,那麼它為什麼會有漏洞?讓我們用一個例子來澄清這一點 −
示例 1:現在讓我們使用 random 模組做一個擲骰子游戲。
示例
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說明 − 如果使用者提供整數輸入,則根據條件表示式將相應地計算期望輸出。
如果使用者提供字串輸入,即與我們使用 random 模組儲存骰子生成的隨機整數的變數名相同,則也會計算輸出。但這不一定是我們想要計算的期望輸出。實際上,當輸入為字串時,它應該引發錯誤,指出輸入型別錯誤。它直接將變數名視為使用者直接輸入的數字,表示式產生 True 布林值,遊戲結束。相反,如果我使用 raw_input(),則不會遇到此問題。
如果我們儲存登入憑據、使用者詳細資訊和帳戶密碼,此漏洞可能會非常危險。
示例 2:現在讓我們建立一個要求輸入 PIN 碼並與儲存值進行比較的系統。
示例
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() 來克服。
從以上兩個示例可以清楚地看出,input 函式使程式容易受到直接變數攻擊。
結論
在本文中,我們瞭解了在 Python 2.x 中使用 input() 函式時遇到的所有問題和漏洞。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP