The Wayback Machine - http://web.archive.org/web/20240908133200/https://www.geeksforgeeks.org/vulnerability-input-function-python-2-x/
Open In App

Vulnerability in input() function – Python 2.x

Last Updated : 29 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This article aims to explain and explore the vulnerability in the input() function in Python 2.x. In Python 3, the raw_input() function was erased, and its functionality was transferred to a new built-in function known as input().

Different Ways to Input Data in Python 2.x

There are two common methods to receive input in Python 2.x:

  1. input() function: This function takes the value and type of the input you enter as it is without modifying any type.
  2. raw_input() function: This function explicitly converts the input you give to type string,

Let us use the following program to determine the difference between the two: 

Python




# Python 2.x program to show differences between
# input() and rawinput()function 
  
s1 = raw_input("Enter input to test raw_input() function: ")
print type(s1)
  
s2 = raw_input("Enter input to test raw_input() function: ")
print type(s2)
  
s3 = raw_input("Enter input to test raw_input() function: ")
print type(s3)
  
# 3 inputs using input() function, 
  
s4 = input("Enter input to test input() function: ")
print type(s4)
  
s5 = input("Enter input to test input() function: ")
print type(s5)
  
s6 = input("Enter input to test input() function: ")
print type(s6)


Input:

Hello
456
[1,2,3]
45
"goodbye"
[1,2,3]

Output:

Enter input to test raw_input() function: <type 'str'>
Enter input to test raw_input() function: <type 'str'>
Enter input to test raw_input() function: <type 'str'>
Enter input to test input() function: <type 'int'>
Enter input to test input() function: <type 'str'>
Enter input to test input() function: <type 'list'>

Note: While giving string input in the input() function, we have to enclose to value in double-quotes. This is not required in raw_input()

Vulnerability in input() Method

The vulnerability in input() method lies in the fact that the variable accessing the value of input can be accessed by anyone just by using the name of the variable or method. Below are some vulnerability in input() method:

  • Variable name as input parameter: 
  • Function name as parameter

Variable Name as Input Parameter

The variable having the value of input variable is able to access the value of the input variable directly. 

Python3




# Python 3 to demonstrate difference in input() function
  
import random
secret_number = random.randint(1,500)
print ("Pick a number between 1 to 500")
while True:
    res = input("Guess the number: ")
    if res==secret_number:
        print ("You win")
        break
    else:
        print ("You lose")
        continue


Python




# Python 2.x program to show Vulnerabilities
# in input() function using a variable 
  
import random
secret_number = random.randint(1,500)
print "Pick a number between 1 to 500"
while True:
    res = input("Guess the number: ")
    if res==secret_number:
        print "You win"
        break
    else:
        print "You lose"
        continue


Input1:

15

Output1:

Pick a number between 1 to 500
Guess the number: You lose
Guess the number:

Input2:

secret_number

Output2:

Pick a number between 1 to 500
Guess the number: You win

As it can be seen, in the second case the variable “secret_number” can be directly given as input and the answer is always “You won”. It evaluates the variable as if a number was directly entered, which means it returns a True Boolean always. Using raw_input, would not be possible as it disallows reading the variable directly.

Python 3 shows different results. If  “secret_number” is given as input,  answer is ‘You lose’.

Function Name as Parameter

The vulnerability lies here as we can even provide the name of a function as input and access values that are otherwise not meant to be accessed. In this set of input/output, we can see that when we use raw_input, we necessarily have to input the correct number. However while using the input() function, we can even provide the name of a function or variable, and the interpreter will evaluate that. Here for example, the input for input() function has been given as the name of a function ‘secretfunction()’. The interpreter evaluates this function call and returns the secret number that we wish to find and hence our if the condition evaluates to be true, even though we did not enter the secret number.

Python




# Python 2.x program to demonstrate input() function
# vulnerability by passing function name as parameter
secret_value = 500
  
# function that returns the secret value
def secretfunction():
    return secret_value
  
# using raw_input() to enter the number
input1 = raw_input("Raw_input(): Guess secret number: ")
  
# input1 will be explicitly converted to a string
if input1 == secret_value:
    print "You guessed correct"
else:
    print "wrong answer"
      
# using input() to enter the number
input2 = input("Input(): Guess the secret number: ")
  
#input2 is evaluated as it is entered
if input2 == secret_value:
    print "You guessed correct"
else:
    print "wrong answer"


Input1:

400
secretfunction()

Output1:

Raw_input(): Guess secret number: wrong answer
Input(): Guess the secret number: You guessed correct

As explained in the first point, in this example also we were able to simply enter the variable name ‘secret_number’ in the input for ‘input()’ function and we were able to gain access to the secret value. However, while trying to call secretfunction() in the input for the raw_input() function, it gives us false as the interpreter converts our argument to a string, and doesn’t evaluate it as a function call.

Input2:

secretfunction()
secret_value

Output2:

Raw_input(): Guess secret number: wrong answer
Input(): Guess the secret number: You guessed correct

Preventing Input Vulnerabilities

It is always better to use raw_input() in python 2.x and then explicitly convert the input to whatever type we require. For example, if we wish to take the input of an integer, we can do the following

n = int(raw_input())

This prevents the malicious calling or evaluation of functions. 



Similar Reads

Vulnerability in str.format() in Python
Prerequisites: Python - format() function str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting. It seems quite a cool thing. But the vulnerability comes when our Python app uses str.format in t
2 min read
Meltdown Security Vulnerability
What is Meltdown security vulnerability? Meltdown, also known as Rogue Data Cache Load, is a security vulnerability that affects microprocessors of the types Intel x86, IBM Power, and ARM, by allowing some malicious processes to read memory, even without authorization. Exploiting race condition, this vulnerability allows a process to bypass the nor
5 min read
Command Injection Vulnerability and Mitigation
Command injection is basically injection of operating system commands to be executed through a web-app. The purpose of the command injection attack is to inject and execute commands specified by the attacker in the vulnerable application. In situation like this, the application, which executes unwanted system commands, is like a pseudo system shell
3 min read
Format String Vulnerability and Prevention with Example
A format string is an ASCII string that contains text and format parameters. Example: // A statement with format stringprintf("my name is : %s\n", "Akash");// Output// My name is : Akash There are several format strings that specify output in C and many other programming languages but our focus is on C. Format string vulnerabilities are a class of
3 min read
Race Condition Vulnerability
Race condition occurs when multiple threads read and write the same variable i.e. they have access to some shared data and they try to change it at the same time. In such a scenario threads are “racing” each other to access/change the data. This is a major security vulnerability. What is Race Condition?A race condition is a situation that may occur
10 min read
Python 3 - input() function
In Python, we use the input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function converts it into a string. Python input() Function SyntaxSyntax: input(prompt) Parameter: Prompt: (optional) The string that is written to standard output
3 min read
Python input() Function
Python input() function is used to take user input. By default, it returns the user input in form of a string. input() Function Syntax:  input(prompt)prompt [optional]: any string value to display as input message Ex: input("What is your name? ") Returns: Return a string value as input by the user. By default input() function helps in taking user i
4 min read
How to Compute the Heaviside Step Function for Each Element in Input in PyTorch?
In this article, we are going to cover how to compute the Heaviside step function for each element in input in PyTorch using Python. We can compute this with the help of torch.heaviside() method. torch.heaviside() method The torch.heaviside() method is used to compute the Heaviside step function for each element. This method accepts input and value
2 min read
Generate two output strings depending upon occurrence of character in input string in Python
Given an input string str[], generate two output strings. One of which consists of that character that occurs only once in the input string and the second consists of multi-time occurring characters. Output strings must be sorted. Examples: Input : str = "geeksforgeeks" Output : String with characters occurring once: "for". String with characters o
4 min read
Python | Find all close matches of input string from a list
We are given a list of pattern strings and a single input string. We need to find all possible close good enough matches of input string into list of pattern strings. Examples: Input : patterns = ['ape', 'apple', 'peach', 'puppy'], input = 'appel' Output : ['apple', 'ape'] We can solve this problem in python quickly using in built function difflib.
2 min read
Taking input from console in Python
What is Console in Python? Console (also called Shell) is basically a command line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error free then it runs the command and gives required output otherwise shows the error message. A Python Console looks like this. Here we write a command and to execute
2 min read
Get a list as input from user in Python
We often encounter a situation when we need to take a number/string as input from the user. In this article, we will see how to get input a list from the user using Python. Example: Input : n = 4, ele = 1 2 3 4Output : [1, 2, 3, 4]Input : n = 6, ele = 3 4 1 7 9 6Output : [3, 4, 1, 7, 9, 6]Get a list as input from user in Python using Loop C/C++ Cod
2 min read
Compute the square root of negative input with emath in Python
In this article, we will cover how to compute the square root of negative inputs with emath in Python using NumPy. Example:Input: [-3,-4] Output: [0.+1.73205081j 0.+2.j ] Explanation: Square root of a negative input.NumPy.emath.sqrt method: The np.emath.sqrt() method from the NumPy library calculates the square root of complex inputs. A complex val
2 min read
Python | Accepting Script Input
A lot of people use Python as a replacement for shell scripts, using it to automate common system tasks, such as manipulating files, configuring systems, and so forth. This article aims to describe accepting Script Input via Redirection, Pipes, or Input Files. Problem - To have a script to be able to accept input using whatever mechanism is easiest
2 min read
PyQt5 Input Dialog | Python
PyQt5 provides a class named QInputDialog which is used to take input from the user. In most of the application, there comes a situation where some data is required to be entered by the user and hence input dialog is needed. Input can be of type String or Text, Integer, Double and item.Used methods: These methods return tuple having two elements -
2 min read
Difference between input() and raw_input() functions in Python
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input ( prompt )raw_input ( prompt )input() function Pytho
4 min read
Take input from stdin in Python
In this article, we will read How to take input from stdin in Python. There are a number of ways in which we can take input from stdin in Python. sys.stdininput()fileinput.input()Read Input From stdin in Python using sys.stdin First we need to import sys module. sys.stdin can be used to get input from the command line directly. It used is for stand
2 min read
Python VLC MediaPlayer – Enabling Keyboard Input
In this article, we will see how we can enable keyboard input handling the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. By
2 min read
Python VLC MediaPlayer – Enabling Mouse Input Handling
In this article we will see how we can enable mouse input handling the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. By input
2 min read
Replace infinity with large finite numbers and fill NaN for complex input values using NumPy in Python
In this article, we will cover how to fill Nan for complex input values and infinity values with large finite numbers in Python using NumPy. Example: Input: [complex(np.nan,np.inf)] Output: [1000.+1.79769313e+308j] Explanation: Replace Nan with complex values and infinity values with large finite. numpy.nan_to_num method The numpy.nan_to_num method
3 min read
Python Arcade - Handling Keyboard Input
In this article, we will discuss how to handle keyboard inputs in Python arcade module. In Arcade, you can easily check which keyboard button is pressed and perform tasks according to that. For this, we are going to use these functions: on_key_press()on_key_release() Syntax: on_key_press(symbol,modifiers)on_key_release (symbol, modifiers) Parameter
4 min read
Using a Class with Input in Python
In this article, we will see how to take input using class in Python. Using a Class with Input in Python It is to be noted that while using class in Python, the __init__() method is mandatory to be called for declaring the class data members, without which we cannot declare the instance variable (data members) for the object of the class. A variabl
2 min read
Python NumPy - Replace NaN with zero and fill positive infinity for complex input values
In this article, we will see how to replace NaN with zero and fill positive infinity for complex input values in Python. Numpy package provides us with the numpy.nan_to_num() method to replace NaN with zero and fill positive infinity for complex input values in Python. This method substitutes a nan value with a number and replaces positive infinity
4 min read
Return the result of the power to which the negative input value is raised with scimath in Python
In this article, we will discuss how to Return the result of the power to which the negative input value is raised with scimath in Python and NumPy. Example Input: [-1,-2,-3] Output: [1.-0.j 4.-0.j 9.-0.j] Explanation: It return x to the power p, (x**p), If x contains negative values, the output is converted to the complex domain. NumPy.lib.scimath
3 min read
Return the result of the power to which the input value is raised with scimath in Python
This article will discuss how to Return the result of the power to which the input value is raised with sci math in Python using NumPy. Example Input: [1,2,3] Output: [1 4 9] Explanation: It returns x to the power p, (x**p).NumPy.lib.scimath.power method The lib.scimath.power() method from the NumPy package is used to return the power to which the
2 min read
Python NumPy - Return real parts if input is complex with all imaginary parts close to zero
In this article, we will discuss how to return real parts if the input is complex with all imaginary parts close to zero in Python. The numpy np.real_if_close() method is used to return the real parts if the input is a complex number with all imaginary parts close to zero. “Close to zero” is defined as tol * (machine epsilon of the type for a). syn
2 min read
Take input from user and store in .txt file in Python
In this article, we will see how to take input from users and store it in a .txt file in Python. To do this we will use python open() function to open any file and store data in the file, we put all the code in Python try-except block. Let's see the implementation below. Stepwise Implementation Step 1: First, we will take the data from the user and
2 min read
How to set an input time limit in Python?
In this article, we will explain how to set an input time limit in Python. It is one of the easiest programming languages which is not only dynamically typed but also garbage collected. Here we will look at different methods to set an input time limit. Below are the methods we will use in this article. Methods to Set an Input Time Limit in PythonUs
6 min read
How to Take Only a Single Character as an Input in Python
Through this article, you will learn how to accept only one character as input from the user in Python. Prompting the user again and again for a single character To accept only a single character from the user input: Run a while loop to iterate until and unless the user inputs a single character.If the user inputs a single character, then break out
3 min read
Save user input to a Excel File in Python
In this article, we will learn how to store user input in an excel sheet using Python, What is Excel? Excel is a spreadsheet in a computer application that is designed to add, display, analyze, organize, and manipulate data arranged in rows and columns. It is the most popular application for accounting, analytics, data presentation, etc. Methods us
4 min read
Practice Tags :