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