PRam374509 (Community Member) asked a question.

How to fix CWE 73 in python script

Hi all,

I'm getting the file path as user input in code. The base directory of the input file path is ​also not known.

I tried to use the below solutions for fixing the CWE 73 flaw.

1. Using os.path.normpath() method

​2. Using os.path.abspath()

​3. Using regex match

​But none of the above methods helped out in fixing the flaw.

​Please could you help me out in fixing this and provide a sample python solution snippet please.

Thanks in advance!!!​


  • Hi @PRam374509 (Community Member)​ ,

     

    Veracode Static Analysis picks up flaws of category CWE-73 when it identifies that the file path or the filename is constructed using untrusted data (data from configuration files, database, user input, http requests etc).

     

    The general remediation is to hardcode the filename/filepath within the code, if applicable, so that it cannot be manipulated or tampered with . This would automatically close the flaw on the Veracode Platform. If hardcoding is not possible, as in your case, please implement custom validation to verify the following, using a combination of Regex and whitelist validation:

     

    1. Check the Filename - if it conforms to the expected pattern of characters
    2. Check the File extension - using a hardcoded list of expected file extensions
    3. Check the absolute path of the File - check if the absolute path of the file starts with the expected path

     

    For such cases of custom input validation, a mitigation by design is required to be raised on the Veracode Platform. To raise a mitigation, please refer https://docs.veracode.com/r/Propose_Mitigating_Factors_for_a_Flaw

     

    Reference: https://community.veracode.com/s/article/how-do-i-fix-cwe-73-external-control-of-file-name-or-path-in-java

     

    Thanks,

    Sounderya

     

     

    Expand Post
  • VWashington710631 (Community Member)

    There are several solutions for it:

    Validate with a whitelist but use the input from the entry point As we mentioned at Use a list of hardcoded values. Validate with a simple regular expression whitelist Canonicalise the input and validate the path I used the first and second solutions and work fine.

     

    More info at: https://community.veracode.com/s/article/how-do-i-fix-cwe-73-external-control-of-file-name-or-path-in-java/CUIMS App

    Expand Post
  • RMahakud579859 (Community Member)

    hey i tried all but it didn't work.

     

    def is_valid_filepath(filepath: str) -> bool:

    # A filepath whitelist that allows alphanumeric characters, periods, underscores, hyphens, and slashes.

    return re.match(r'^(/?[\w\.-]+)+$', filepath) is not None

     

    Expand Post
  • CSmith195682 (Community Member)

    CWE-73, also known as "External Control of File Name or Path," refers to vulnerabilities where an attacker can influence the file or resource that is accessed or controlled by the application. To fix CWE-73 in a Python script, follow these general guidelines:

     

    1. Input Validation: Always validate and sanitize any input that affects file paths or names. Ensure that user input cannot contain characters that could be used to traverse directories or execute commands.

     

    2. Use Absolute Paths: Whenever possible, use absolute paths instead of relative paths. This ensures that the file is accessed from the expected location in the file system.

     

    3. Avoid User Input for File Paths: Minimize the use of user-provided input for file paths or names. If user input is necessary, consider limiting it to a predefined set of options or employing a file picker dialog in GUI applications.

     

    4. Use Safe APIs: Prefer using safer APIs provided by Python's standard library or third-party libraries for file operations. For example, use `os.path.join()` instead of concatenating paths manually, and use `os.path.abspath()` to convert relative paths to absolute paths.

     

    5. Set Permissions Appropriately: Ensure that files and directories are created with appropriate permissions to prevent unauthorized access or modification.

     

    6. Consider File System Permissions: Be mindful of file system permissions and access controls. Ensure that sensitive files are not accessible to unauthorized users.

     

    Here's an example of how you might mitigate CWE-73 in a Python script:

     

    ```python

    import os

     

    def process_file(file_name):

      # Validate file name to prevent directory traversal

      if not file_name.endswith('.txt'):

        print("Invalid file name.")

        return

     

      # Construct absolute path

      base_dir = '/path/to/files'

      abs_path = os.path.abspath(os.path.join(base_dir, file_name))

     

      # Check if the file exists and is within the expected directory

      if not abs_path.startswith(base_dir):

        print("Invalid file path.")

        return

     

      # Proceed with processing the file

      try:

        with open(abs_path, 'r') as file:

          # Do something with the file

          pass

      except FileNotFoundError:

        print("File not found.")

      except IOError:

        print("Error accessing the file.")

      except Exception as e:

        print("An unexpected error occurred:", e)

     

    # Example usage

    file_name = input("Enter file name: ")

    process_file(file_name)

    ```

     

    In this example:

     

    - The input file name is validated to ensure it ends with '.txt' to prevent arbitrary file execution.

    - The absolute path is constructed using `os.path.abspath()` to avoid directory traversal.

    - The absolute path is checked to ensure it's within the expected directory.

    - Error handling is implemented to gracefully handle exceptions during file processing.

    Expand Post

Topics (4)

No articles found
Loading

Ask the Community

Get answers, share a use case, discuss your favorite features, or get input from the community.