eval: this is very powerful, but also very dangerous if you accept lines to evaluate from untrusted input. Suppose the string being evaluated is "os.system ('rm -rf /')"? This will really start deleting all files on your computer.
ast.literal_eval: Safely parsing an expression node or string containing a Python literal or container mapping. The provided string or node can only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dictations, sets, booleans, None, bytes, and sets.
Syntax:
eval(expression, globals=None, locals=None) import ast ast.literal_eval(node_or_string)
Example:
# python 2.x - doesn't accept operators in string format import ast ast.literal_eval('[1, 2, 3]') # output: [1, 2, 3] ast.literal_eval('1+1') # output: ValueError: malformed string # python 3.0 -3.6 import ast ast.literal_eval("1+1") # output : 2 ast.literal_eval("{'a': 2, 'b': 3, 3:'xyz'}") # output : {'a': 2, 'b': 3, 3:'xyz'} # type dictionary ast.literal_eval("",{}) # output : Syntax Error required only one parameter ast.literal_eval("__import__('os').system('rm -rf /')") # output : error eval("__import__('os').system('rm -rf /')") # output : start deleting all the files on your computer. # restricting using global and local variables eval("__import__('os').system('rm -rf /')",{'__builtins__':{}},{}) # output : Error due to blocked imports by passing '__builtins__':{} in global # But still eval is not safe. we can access and break the code as given below s = """ (lambda fc=( lambda n: [ c for c in ().__class__.__bases__[0].__subclasses__() if c.__name__ == n ][0] ): fc("function")( fc("code")( 0,0,0,0,"KABOOM",(),(),(),"","",0,"" ),{} )() )() """ eval(s, {'__builtins__':{}})
In the above code ().__class__.__bases__[0] just an object. Now we have created all the subclasses , here our main goal of enter code here is to find one class from it named n .
We need a code object and a function object from the created instances of subclasses. This is an alternative way from CPython to access the subclasses of the object and connect the system.
In python 3.7, ast.literal_eval () has now become more strict. Addition and subtraction of arbitrary numbers are no longer allowed. link