2.3.4 Sanitize Sensitive Data
Sanitize Sensitive Data
import html
import re
def sanitize_input(user_input):
# Prevent XSS — escape HTML entities
sanitized = html.escape(user_input)
# Remove potential SQL injection patterns
sanitized = re.sub(r"['\";--]", "", sanitized)
# Trim whitespace
sanitized = sanitized.strip()
return sanitized
Common Attack Vectors
| Attack | Mô tả | Prevention |
|---|
| SQL Injection | Inject SQL qua input | Parameterized queries, input validation |
| XSS | Inject script qua input | HTML escape, Content-Security-Policy |
| Command Injection | Inject OS commands | Avoid shell execution, whitelist input |
| Path Traversal | Access files ngoài scope | Validate paths, chroot |
Parameterized Queries (Prevent SQL Injection)
# BAD — SQL Injection vulnerable
query = f"SELECT * FROM users WHERE id = '{user_input}'"
# GOOD — Parameterized query
cursor.execute("SELECT * FROM users WHERE id = %s", (user_input,))
API Gateway Request Validation
# SAM template — request validation
MyApi:
Type: AWS::Serverless::Api
Properties:
Models:
CreateOrderModel:
type: object
required:
- productId
- quantity
properties:
productId:
type: string
pattern: "^[a-zA-Z0-9-]+$"
quantity:
type: integer
minimum: 1
maximum: 100
- Validate request body, query parameters, headers
- Reject invalid requests trước khi đến Lambda
- Giảm unnecessary Lambda invocations
AWS WAF (Web Application Firewall)
WAF bảo vệ web applications khỏi common exploits.
Deployment Points
| Service | WAF Support |
|---|
| CloudFront | ✅ (global) |
| API Gateway (REST) | ✅ (regional) |
| ALB | ✅ (regional) |
| AppSync | ✅ (regional) |
| API Gateway (HTTP) | ❌ |
Rule Types
| Rule | Mô tả |
|---|
| Managed Rules | AWS và marketplace rules (SQL injection, XSS, bad bots) |
| Rate-based | Block IPs exceeding request threshold |
| IP Set | Allow/block specific IP ranges |
| Geo Match | Block/allow by country |
| Size Constraint | Limit request body size |
| Regex Pattern | Match custom patterns |
Common Managed Rule Groups
| Rule Group | Protection |
|---|
| AWSManagedRulesCommonRuleSet | General web exploits |
| AWSManagedRulesSQLiRuleSet | SQL injection |
| AWSManagedRulesKnownBadInputsRuleSet | Known bad patterns |
| AWSManagedRulesBotControlRuleSet | Bot traffic |
WAF + API Gateway Example
# CloudFormation
WebACL:
Type: AWS::WAFv2::WebACL
Properties:
DefaultAction:
Allow: {}
Rules:
- Name: RateLimit
Priority: 1
Action:
Block: {}
Statement:
RateBasedStatement:
Limit: 2000
AggregateKeyType: IP
- WAF logs → S3, CloudWatch Logs, Kinesis Data Firehose
- Web ACL capacity units (WCU) limit per ACL
Exam Tip: API Gateway request validation = first line of defense. WAF cho SQL injection/XSS protection. Parameterized queries cho database. Validate + sanitize tại mọi layer.