# Import Hijacking via sys.path Manipulation

Language: Python
Severity: Critical
CWE: CWE-427

## Source
4

## Flow
4-5-6-7-8

## Sink
8

## Vulnerable Code
```python
import sys
import os

def load_cloud_provider_sdk(provider_name, config_dir):
    sdk_path = os.path.join(config_dir, provider_name, 'sdk')
    if os.path.exists(sdk_path):
        sys.path.insert(0, sdk_path)
    import boto3
    s3_client = boto3.client('s3', aws_access_key_id=os.getenv('AWS_KEY'))
    return s3_client

cloud_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
```python
import sys
import os
import importlib

def load_cloud_provider_sdk(provider_name):
    """Loads AWS SDK using only the standard installed package.
    
    Does not manipulate sys.path or load modules from user-controlled directories.
    """
    # Import boto3 directly from the standard installed location
    # without any sys.path manipulation
    import boto3
    s3_client = boto3.client('s3', aws_access_key_id=os.getenv('AWS_KEY'))
    return s3_client

cloud_client = load_cloud_provider_sdk('aws')
```
