AYakovenko368689 (Community Member) asked a question.

CWE-73 vulnerability in Python code

Can not fix "CWE-73: External Control of File Name or Path" vulnerability in the following Python code:

 

```

import os

 

 

def load_json_data(json_file_path: str) -> dict:

  if not json_file_path.endswith('.json'):

    raise ValueError('The file should be in json format')

 

  # Ensure the file is in the project directory to prevent external file path traversal.

  abs_path = os.path.abspath(os.path.join(PROJECT_ROOT, json_file_path))

  if not abs_path.startswith(PROJECT_ROOT):

    raise ValueError(f'The file path is outside the project directory: {json_file_path}')

 

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

    json_data = json.load(f)

  return json_data

 

```

 

Can please anyone take a look and tell how to fix it?

 


  • AYakovenko368689 (Community Member)

    This code has CWE-73 vulnerability as well:

     

    ```

    import os

    import re

     

     

    from pathlib import Path

     

    PROJECT_ROOT = Path(__file__).parent.absolute()

     

     

    def load_json_data(json_file_path: str) -> dict:

      if not re.match(r'^[A-Za-z0-9]+\.json$', json_file_path):

        raise ValueError('Illegal file name')

     

      # Ensure the file is in the project directory to prevent external file path traversal.

      file_path = os.path.abspath(os.path.join(PROJECT_ROOT, json_file_path))

      if not file_path.startswith(str(PROJECT_ROOT)):

        raise ValueError(f'The file path is outside the project directory: {json_file_path}')

     

      with open(file_path, 'r') as f:

        json_data = json.load(f)

      return json_data

     

    ```

    Expand Post
  • Hello,

     

    I realize this question has been raised over 2 years ago at this time, but just in case this information helps other active Veracode users out when running into similar Python CWE-73 flaws that are still being reported by the Veracode static analysis engine even after attempting similar fix solutions.

     

    In the Python code provided above, this code does seem to be following a Veracode recommended strategy of applying a canonical path validation check to ensure the target filename for the open() call is located under the expected base project directory location. Here, the code is relying on the os.path.abspath() method to normalize the incoming filename and then check that it starts with base directory in PROJECT_ROOT.

     

    To improve this canonical path verification, Veracode recommends replacing the os.path.abspath() method with os.path.realpath() instead. While both functions do the job of converting the incoming filename to an absolute path while normalizing the "." and ".." patterns commonly used for path traversal attacks, realpath() is preferred over abspath() as it also supports resolving and normalizing any symbolic links encountered in the incoming filename, while abspath() does not.

     

    That said, even when this code is rewritten to use the replacement method suggested, the Veracode static analysis engine will not be able to evaluate and recognize a bespoke canonical path check during static analysis. This is because the engine does not actually execute the Python code submitted for scanning which would be the only reliable way to validate and confirm the canonical path check only accepts filenames under the expected base folder. Remember that Veracode static engine is analyzing a generated model graph representation of the code here and is tracing this model to identify tainted data paths to report on CWEs statically without any code execution. So, the information about this validation will not be visible as part of the model analyzed.

     

    So, after adding this proper canonical path validation check, Veracode recommends entering a "Mitigate by Design" mitigation proposal for the reported CWE-73 flaw(s) in the Veracode Platform that has this canonical path check showing up as part of the flaw's data path. The mitigation proposal submitted should then document and describe how the canonical path validation check behaves to demonstrate how it addresses the risk here

     

    To learn more about entering a mitigation proposal to resolve flaws the Veracode static engine identifies, please refer to https://docs.veracode.com/r/improve_mitigation and https://docs.veracode.com/r/Video_Mitigate_Static_Analysis_findings . Developers will need to contact and work with their organization's application security team members responsible for your Veracode usage and administration to apply and complete this process.

     

    For more information about how Veracode static analysis engine reports on CWE-73 and strategies to fix this CWE that the engine can recognize on a re-scan attempt versus strategies that require entering and approving a mitigation proposal to resolve, please refer to Veracode's Community guide on this CWE at https://community.veracode.com/s/article/how-do-i-fix-cwe-73-external-control-of-file-name-or-path-in-java. Note the code examples here are in Java and .NET, however these recommendations can easily be adopted across other languages.

     

    Best Regards,

    Andrew

    Expand Post

Topics (1)

No articles found
Loading

Ask the Community

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