Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Using the input() is always a security concern. Input is seldom properly handled from a defense security perspective.

When using input with incorrect or no validation and sanitizing the risk for remote code execution (RCE) and other serious attacks is present.

From a security perspective: The fundamental security concern lies not in use of the input() function itself, but in how you process use the data it receives.

Security concerns

Common security concerns with the use of input() in Python are:

Preventive measures

Some simple rules for handling User Input:

  1. Always Validate Input:

    • Whitelist Validation: Define what constitutes valid input (e.g., only digits, specific characters, certain length) and reject anything that doesn’t match. This is generally more secure than trying to blacklist bad input.

    • Regular Expressions: Use re module for complex pattern matching.

    • Type Conversion and Error Handling: If you expect a number, try to convert the input to int or float and handle ValueError gracefully.

  2. Sanitize Input: Remove or escape potentially dangerous characters from the input.

    • For HTML output, use libraries like html (built-in) or Bleach to escape HTML entities.

    • For database queries, use parameterized queries (prepared statements) provided by your database driver/ORM. Never concatenate user input directly into SQL strings.

    • For shell commands, avoid shell=True in subprocess whenever possible, and pass arguments as a list of strings. Validate and sanitize each argument.

  3. Limit Input Size: Restrict the maximum length of user input to prevent buffer overflows or excessive memory usage.

  4. Practice security testing:: Always run fuzzers on user input statements.

These functions are extremely dangerous as they execute arbitrary Python code that can be supplied from user input using the input statement.

  1. Principle of Least Privilege: Your application should only have the minimum permissions necessary to perform its function.

  2. Secure Error Handling: Don’t display raw error messages to users. Log them for internal review and provide generic, user-friendly error messages instead.

Discussion

Validating and sanitising user-supplied input is never simple. Always follow simple but proven Security by Design principles.

More information