Runtime Security
🔥 Vibe Prompt
"Set up runtime protection: RASP, WAF, anomaly detection, and security monitoring."
RASP (Runtime Application Self-Protection)
# Simple RASP implementation
import os, sys
class RASP:
def __init__(self):
self.blocked_funcs = {
'os.system': ['cmd', 'exec'],
'subprocess.call': ['shell'],
'eval': [],
'exec': []
}
def protect(self, func_name, args):
if func_name in self.blocked_funcs:
log.warning(f"RASP blocked: {func_name}({args})")
raise SecurityException(f"Blocked: {func_name}")
def start(self):
# Monkey-patch dangerous functions
import builtins
original_eval = builtins.eval
def safe_eval(*args, **kwargs):
self.protect('eval', args)
return original_eval(*args, **kwargs)
builtins.eval = safe_eval
# Use it in app
if __name__ == '__main__':
rasp = RASP()
rasp.start()
# Now eval() is protected:
# eval("os.system('rm -rf /')") # Would be blocked!
ModSecurity WAF
# Nginx + ModSecurity
server {
location / {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
}
}
# modsec/main.conf
SecRuleEngine On
SecRequestBodyAccess On
# OWASP CRS (Core Rule Set)
Include /etc/nginx/modsec/crs-setup.conf
Include /etc/nginx/modsec/activated_rules/*.conf
# Custom rules
SecRule REQUEST_URI "@contains /admin" "id:1000,deny,msg:'Admin access blocked'"
SecRule ARGS "@detectSQLi" "id:1001,deny,msg:'SQLi detected'"
WAF vs RASP
| Aspect | WAF | RASP | |--------|-----|------| | Location | Before app (network) | Inside app (runtime) | | Visibility | HTTP only | Full app context | | Bypass | Possible | Hard to bypass | | Performance | Low overhead | Some overhead | | Deployment | Reverse proxy | Code instrumentation | | False positives | Common | Rare (context-aware) |
Anomaly Detection
import numpy as np
from collections import deque
class AnomalyDetector:
def __init__(self, window=100, threshold=3):
self.window = deque(maxlen=window)
self.threshold = threshold
def add_metric(self, value):
self.window.append(value)
if len(self.window) < 30: # Need baseline
return False
mean = np.mean(self.window)
std = np.std(self.window)
z_score = abs(value - mean) / (std + 0.001)
if z_score > self.threshold:
return True # Anomaly detected!
return False
# Usage
detector = AnomalyDetector()
for req in traffic_stream:
if detector.add_metric(req.latency):
alert(f"Anomalous latency: {req.latency}ms")
if detector.add_metric(req.error_rate):
alert(f"Anomalous error rate: {req.error_rate}")
Security Monitoring Stack
App → Prometheus (metrics) → Grafana (dashboard)
App → Loki (logs) → Grafana (log analysis)
App → Sentry (error tracking) → Alerting
WAF → CloudWatch → Security Hub
RASP → Custom metrics → Slack alerts
Key metrics to monitor:
- 4xx/5xx error rates (spikes)
- Authentication failure rate
- SQL query anomaly (sudden change)
- API parameter sizes (large = attack)
- Response time degradation
Best Practices
| Layer | Protection | |-------|-----------| | Network | WAF (ModSecurity, Cloudflare) | | Application | RASP (self-protection) | | Runtime | Anomaly detection | | Monitoring | Prometheus + Loki + Grafana | | Response | Automated playbooks |
Best Practices
- Use WAF for known attack patterns
- Use RASP for unknown attacks (zero-day)
- Monitor all security events centrally
- Set up automated response for critical events
- Regularly test protections (bypass attempts)
- Keep WAF/RASP rules updated
為什麼執行時期安全是最後一道防線?
前面三章(SAST、DAST、SCA)都是在「上線前」發現問題。但現實是:
- 零日漏洞(Zero-day)沒有修補程式,上線前掃不到
- 配置漂移(Configuration Drift):上線時是安全的,運行三個月後被人手動改了設定
- 內部威脅:有合法權限的人做了不該做的事
- 供應鏈攻擊:依賴的套件被植入後門(如 SolarWinds、Log4j)
執行時期安全就是針對這些「上線後才出現的威脅」提供保護。
常見的執行時期威脅
| 威脅 | 範例 | 偵測方式 |
|:----:|:----:|:--------:|
| 異常行程執行 | 容器中突然跑起了 minerd(加密貨幣挖礦) | Falco 規則偵測 |
| 反向 Shell | 攻擊者取得 Shell 後與外部 C2 伺服器通訊 | 網路流量分析 |
| 權限提升 | 一般使用者嘗試執行 sudo 或存取 /etc/shadow | Auditd 或 Falco |
| 橫向移動 | 從被攻破的 Pod 掃描內部網路 | 微隔離 (Micro-segmentation) |
| 資料外洩 | 大量資料透過 API 被讀取 | 異常 API 流量偵測 |
Falco 規則範例
# 偵測容器中執行 Shell
- rule: Terminal shell in container
desc: 偵測有人在容器內開啟了互動式 Shell
condition: >
spawned_process and container
and proc.name in (bash, zsh, sh, ash)
and not proc.name in (docker-entrypoint)
output: >
Shell started in container
(user=%user.name, container=%container.name, shell=%proc.name)
priority: WARNING
# 偵測加密貨幣挖礦
- rule: Crypto miner download
desc: 偵測從已知挖礦池下載檔案
condition: >
outbound and fd.sport in (3333, 3334, 4444, 5555, 7777)
output: >
Potential crypto miner communication
(connection=%fd.name)
priority: CRITICAL
下一章預告:完整的 DevSecOps Pipeline
你已經學會了 SAST、DAST、SCA 和執行時期安全。下一章 完整 DevSecOps Pipeline 將這四個安全階段整合成一條自動化的安全流水線——從 Commit 開始,到 Production 運行,全程自動化安全檢查。