Which Python function should be avoided when evaluating user-provided input to prevent code execution?

Get ready for your WGU ITEC2034 D385 Software Security and Testing Test. Study with multiple choice questions that include hints and explanations. Boost your confidence for your exam day!

Multiple Choice

Which Python function should be avoided when evaluating user-provided input to prevent code execution?

Explanation:
The risk comes from a function that executes the string you supply as Python code. The eval function takes a string and runs it as code, with access to the current globals and builtins. If a user provides input designed to do something harmful—like importing modules, reading or writing files, or running system commands—eval will execute it, potentially compromising your system or data. That’s why eval is avoided when handling user-provided input. Safer approaches include ast.literal_eval, which only evaluates Python literals (strings, numbers, tuples, lists, dicts, booleans, None) and prevents arbitrary code execution, or json.loads for parsing JSON data. If you need to parse expressions, use a restricted parser or a sandboxed evaluation environment rather than evaluating the input directly. Other familiar functions like print, len, or sum don’t execute code from input; they perform defined operations on data, so they aren’t a mechanism for evaluating user-provided expressions, though they aren’t substitutes for proper input parsing.

The risk comes from a function that executes the string you supply as Python code. The eval function takes a string and runs it as code, with access to the current globals and builtins. If a user provides input designed to do something harmful—like importing modules, reading or writing files, or running system commands—eval will execute it, potentially compromising your system or data. That’s why eval is avoided when handling user-provided input.

Safer approaches include ast.literal_eval, which only evaluates Python literals (strings, numbers, tuples, lists, dicts, booleans, None) and prevents arbitrary code execution, or json.loads for parsing JSON data. If you need to parse expressions, use a restricted parser or a sandboxed evaluation environment rather than evaluating the input directly. Other familiar functions like print, len, or sum don’t execute code from input; they perform defined operations on data, so they aren’t a mechanism for evaluating user-provided expressions, though they aren’t substitutes for proper input parsing.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy