Claude Skills Security Best Practices
Security is critical when Skills execute real code. Follow these practices to protect your systems.
Key Security Principles
1. Input Validation
Always validate and sanitize inputs:
python1def process_file(filepath): 2 # Validate file exists 3 if not os.path.exists(filepath): 4 raise ValueError("File not found") 5 6 # Check file type 7 allowed_extensions = ['.pdf', '.docx', '.txt'] 8 if not any(filepath.endswith(ext) for ext in allowed_extensions): 9 raise ValueError("Invalid file type") 10 11 # Check file size 12 if os.path.getsize(filepath) > 10 * 1024 * 1024: # 10MB 13 raise ValueError("File too large")1def process_file(filepath): 2 # Validate file exists 3 if not os.path.exists(filepath): 4 raise ValueError("File not found") 5 6 # Check file type 7 allowed_extensions = ['.pdf', '.docx', '.txt'] 8 if not any(filepath.endswith(ext) for ext in allowed_extensions): 9 raise ValueError("Invalid file type") 10 11 # Check file size 12 if os.path.getsize(filepath) > 10 * 1024 * 1024: # 10MB 13 raise ValueError("File too large")
2. Sandboxing
Run untrusted code in isolated environments:
python1import subprocess 2 3def run_sandboxed(script_path): 4 result = subprocess.run( 5 ['docker', 'run', '--rm', '-v', f'{script_path}:/app', 'python:3.9', 'python', '/app/script.py'], 6 capture_output=True, 7 timeout=30 8 ) 9 return result.stdout1import subprocess 2 3def run_sandboxed(script_path): 4 result = subprocess.run( 5 ['docker', 'run', '--rm', '-v', f'{script_path}:/app', 'python:3.9', 'python', '/app/script.py'], 6 capture_output=True, 7 timeout=30 8 ) 9 return result.stdout
3. Secrets Management
Never hardcode sensitive data:
python1import os 2 3# ✅ Good: Use environment variables 4API_KEY = os.getenv('API_KEY') 5 6# ❌ Bad: Hardcoded secrets 7# API_KEY = "sk-1234567890abcdef"1import os 2 3# ✅ Good: Use environment variables 4API_KEY = os.getenv('API_KEY') 5 6# ❌ Bad: Hardcoded secrets 7# API_KEY = "sk-1234567890abcdef"
4. Principle of Least Privilege
Request minimum permissions:
markdown## Required Permissions - File read: /data/input/ - File write: /data/output/ - Network: None## Required Permissions - File read: /data/input/ - File write: /data/output/ - Network: None
5. Code Review
Audit Skills before deployment:
bash# Check for dangerous patterns grep -r "eval(" skill/ grep -r "exec(" skill/ grep -r "subprocess.call" skill/# Check for dangerous patterns grep -r "eval(" skill/ grep -r "exec(" skill/ grep -r "subprocess.call" skill/
Common Vulnerabilities
Path Traversal
python1# ❌ Vulnerable 2def read_file(filename): 3 return open(filename).read() 4# Attack: read_file("../../etc/passwd") 5 6# ✅ Secure 7import os 8def read_file(filename): 9 base_dir = "/safe/directory" 10 filepath = os.path.join(base_dir, filename) 11 if not filepath.startswith(base_dir): 12 raise ValueError("Invalid path") 13 return open(filepath).read()1# ❌ Vulnerable 2def read_file(filename): 3 return open(filename).read() 4# Attack: read_file("../../etc/passwd") 5 6# ✅ Secure 7import os 8def read_file(filename): 9 base_dir = "/safe/directory" 10 filepath = os.path.join(base_dir, filename) 11 if not filepath.startswith(base_dir): 12 raise ValueError("Invalid path") 13 return open(filepath).read()
Command Injection
python# ❌ Vulnerable os.system(f"convert {filename} output.pdf") # ✅ Secure subprocess.run(['convert', filename, 'output.pdf'], check=True)# ❌ Vulnerable os.system(f"convert {filename} output.pdf") # ✅ Secure subprocess.run(['convert', filename, 'output.pdf'], check=True)
Arbitrary Code Execution
python1# ❌ Dangerous 2eval(user_input) 3exec(user_code) 4 5# ✅ Use safe alternatives 6import ast 7ast.literal_eval(user_input) # Only for literals1# ❌ Dangerous 2eval(user_input) 3exec(user_code) 4 5# ✅ Use safe alternatives 6import ast 7ast.literal_eval(user_input) # Only for literals
Security Checklist
- [ ] All inputs validated
- [ ] File paths sanitized
- [ ] Commands use subprocess with list args
- [ ] No hardcoded secrets
- [ ] Timeouts on all operations
- [ ] Error messages don't leak sensitive info
- [ ] Dependencies from trusted sources
- [ ] Regular security audits
Monitoring
Log security-relevant events:
pythonimport logging logging.info(f"Skill executed: {skill_name} by {user_id}") logging.warning(f"Invalid input attempt: {input_data}") logging.error(f"Security violation: {error_details}")import logging logging.info(f"Skill executed: {skill_name} by {user_id}") logging.warning(f"Invalid input attempt: {input_data}") logging.error(f"Security violation: {error_details}")
Resources
Reading Time: 4 minutes
Author: ClaudeSkills Team