Senior LevelPython
Why is yaml.load() in PyYAML vulnerable to arbitrary code execution, and why must you strictly enforce yaml.safe_load()?
❓ Interview Prompt: Explain PyYAML security, `yaml.load()`, `!!python/object/apply` tags, Remote Code Execution (RCE), and `yaml.safe_load()`.
PyYAML RCE Vulnerability:
Legacy 'yaml.load(data, Loader=yaml.Loader)' supports custom Python object tags ('!!python/object/apply:os.system ["whoami"]'), executing arbitrary shell commands during YAML parsing!
Security Requirement:
Always strictly enforce 'yaml.safe_load(data)' or 'Loader=yaml.SafeLoader', restricting parsing to standard scalar types, lists, and dicts!
Code Implementation Example
python
import yaml
untrusted_yaml = '''
!!python/object/apply:os.system
- echo "Malicious RCE Payload Executed!"
'''
# SAFE: Restricts parsing to standard data structures safely!
data = yaml.safe_load(untrusted_yaml)
# Raises ConstructorError instead of executing RCE!💡Parsing YAML safely using yaml.safe_load().
🎯 Interview Key Takeaway
Always use yaml.safe_load() to parse YAML input and prevent arbitrary remote code execution.
#PyYAML#safe_load#RCE#Security#Senior
Back to all Python Questions→