{"title":"Import Hijacking via sys.path Manipulation","language":"Python","severity":"Critical","cwe":"CWE-427","source_lines":[4],"flow_lines":[4,5,6,7,8],"sink_lines":[8],"vulnerable_code":"import sys\nimport os\n\ndef load_cloud_provider_sdk(provider_name, config_dir):\n    sdk_path = os.path.join(config_dir, provider_name, 'sdk')\n    if os.path.exists(sdk_path):\n        sys.path.insert(0, sdk_path)\n    import boto3\n    s3_client = boto3.client('s3', aws_access_key_id=os.getenv('AWS_KEY'))\n    return s3_client\n\ncloud_client = load_cloud_provider_sdk('aws', '/var/app/user_configs')","explanation":"The code constructs a path from user-controlled input (config_dir parameter) and inserts it at the beginning of sys.path, allowing an attacker to inject malicious Python modules. When 'import boto3' executes after sys.path manipulation, Python will load a malicious boto3 module from the attacker-controlled directory, which can then steal AWS credentials or perform arbitrary actions.","remediation":"The fix removes the sys.path manipulation entirely, eliminating the ability for user-controlled directories to inject malicious modules. The boto3 import now only resolves from the standard Python path (site-packages), ensuring only the legitimate AWS SDK is loaded. The config_dir parameter was removed since dynamically adding untrusted paths to the module search path is inherently unsafe.","secure_code":"import sys\nimport os\nimport importlib\n\ndef load_cloud_provider_sdk(provider_name):\n    \"\"\"Loads AWS SDK using only the standard installed package.\n    \n    Does not manipulate sys.path or load modules from user-controlled directories.\n    \"\"\"\n    # Import boto3 directly from the standard installed location\n    # without any sys.path manipulation\n    import boto3\n    s3_client = boto3.client('s3', aws_access_key_id=os.getenv('AWS_KEY'))\n    return s3_client\n\ncloud_client = load_cloud_provider_sdk('aws')"}