0
# Application Security
1
2
Application security monitoring provides comprehensive protection against web application attacks, vulnerabilities, and suspicious behavior through Interactive Application Security Testing (IAST), runtime security monitoring, and AI/LLM-specific security features. This enables real-time threat detection, vulnerability identification, and security policy enforcement.
3
4
## Capabilities
5
6
### Security Configuration
7
8
Enable and configure application security features through environment variables and programmatic settings.
9
10
```python { .api }
11
# Environment variable constants
12
APPSEC_ENV: str = "DD_APPSEC_ENABLED"
13
IAST_ENV: str = "DD_IAST_ENABLED"
14
```
15
16
Usage examples:
17
18
```python
19
import os
20
from ddtrace.constants import APPSEC_ENV, IAST_ENV
21
22
# Enable Application Security Monitoring
23
os.environ[APPSEC_ENV] = "true"
24
25
# Enable Interactive Application Security Testing
26
os.environ[IAST_ENV] = "true"
27
28
# Start your application with security monitoring enabled
29
# Security features are automatically activated when ddtrace is imported
30
import ddtrace
31
```
32
33
### Interactive Application Security Testing (IAST)
34
35
IAST provides runtime vulnerability detection by analyzing application behavior during execution, identifying security weaknesses such as SQL injection, XSS, path traversal, and other OWASP Top 10 vulnerabilities.
36
37
Configuration and usage:
38
39
```python
40
import os
41
from ddtrace.constants import IAST_ENV
42
43
# Enable IAST
44
os.environ[IAST_ENV] = "true"
45
46
# IAST automatically analyzes:
47
# - SQL queries for injection vulnerabilities
48
# - File operations for path traversal
49
# - Template rendering for XSS
50
# - Deserialization for unsafe operations
51
# - LDAP queries for injection attacks
52
# - NoSQL operations for injection vulnerabilities
53
54
# Example vulnerable code that IAST would detect:
55
def vulnerable_query(user_input):
56
# IAST detects SQL injection vulnerability
57
query = f"SELECT * FROM users WHERE name = '{user_input}'"
58
return execute_sql(query)
59
60
def vulnerable_file_access(filename):
61
# IAST detects path traversal vulnerability
62
return open(f"/app/files/{filename}", 'r')
63
```
64
65
### Runtime Application Self-Protection (RASP)
66
67
Runtime monitoring and protection against active attacks and suspicious behavior patterns.
68
69
```python
70
import os
71
from ddtrace.constants import APPSEC_ENV
72
73
# Enable runtime protection
74
os.environ[APPSEC_ENV] = "true"
75
76
# RASP automatically monitors and can block:
77
# - Suspicious request patterns
78
# - Known attack signatures
79
# - Abnormal application behavior
80
# - Malicious payloads in requests
81
82
# Example: Automatic detection of attack patterns
83
def process_request(request_data):
84
# RASP monitors this function for:
85
# - SQL injection attempts in request_data
86
# - XSS payloads in input parameters
87
# - Command injection patterns
88
# - Suspicious file access patterns
89
return handle_user_request(request_data)
90
```
91
92
### AI/LLM Security Monitoring
93
94
Specialized security monitoring for AI and Large Language Model applications, detecting prompt injection, data leakage, and model abuse.
95
96
```python
97
# AI Guard automatically monitors AI/LLM operations when enabled
98
import os
99
from ddtrace.constants import APPSEC_ENV
100
101
os.environ[APPSEC_ENV] = "true"
102
103
# Example: OpenAI integration with automatic security monitoring
104
from openai import OpenAI
105
106
client = OpenAI()
107
108
def secure_chat_completion(user_prompt):
109
# ddtrace automatically monitors for:
110
# - Prompt injection attempts
111
# - Data exfiltration patterns
112
# - Jailbreak attempts
113
# - Sensitive data in prompts/responses
114
115
response = client.chat.completions.create(
116
model="gpt-3.5-turbo",
117
messages=[{"role": "user", "content": user_prompt}]
118
)
119
120
return response.choices[0].message.content
121
122
# Usage with automatic security monitoring
123
result = secure_chat_completion("Tell me about your training data")
124
```
125
126
### Security Event Detection
127
128
Automatic detection and reporting of security events and violations.
129
130
Security events are automatically captured and reported when suspicious activity is detected:
131
132
```python
133
# Security events are automatically generated for:
134
# - Blocked attack attempts
135
# - Vulnerability detections
136
# - Policy violations
137
# - Suspicious behavior patterns
138
139
# Events include context such as:
140
# - Attack type and severity
141
# - Request details and payload
142
# - User session information
143
# - Application response actions
144
145
# Example of operations that generate security events:
146
def handle_login(username, password):
147
# Monitors for credential stuffing, brute force
148
return authenticate_user(username, password)
149
150
def process_upload(file_data):
151
# Monitors for malicious file uploads, directory traversal
152
return save_uploaded_file(file_data)
153
154
def execute_search(search_query):
155
# Monitors for injection attacks, data exfiltration
156
return search_database(search_query)
157
```
158
159
### Security Policy Configuration
160
161
Configure security policies and response actions for different types of threats.
162
163
```python
164
# Security policies are configured through environment variables
165
import os
166
167
# Configure security sensitivity levels
168
os.environ["DD_APPSEC_RULES"] = "strict" # strict, standard, permissive
169
170
# Configure response actions
171
os.environ["DD_APPSEC_AUTOMATED_USER_EVENTS_TRACKING"] = "enabled"
172
173
# Configure custom rules and exceptions
174
os.environ["DD_APPSEC_OBFUSCATION_PARAMETER_KEY_REGEXP"] = "password|token|secret"
175
os.environ["DD_APPSEC_OBFUSCATION_PARAMETER_VALUE_REGEXP"] = "pass|pwd|token"
176
177
# Rate limiting configuration
178
os.environ["DD_APPSEC_TRACE_RATE_LIMIT"] = "100" # traces per second
179
180
# WAF (Web Application Firewall) configuration
181
os.environ["DD_APPSEC_WAF_TIMEOUT"] = "5000" # microseconds
182
```
183
184
### Framework Integration
185
186
Application security automatically integrates with popular Python web frameworks to provide comprehensive protection.
187
188
#### Django Integration
189
190
```python
191
# Django integration is automatic when AppSec is enabled
192
import os
193
from ddtrace.constants import APPSEC_ENV
194
195
os.environ[APPSEC_ENV] = "true"
196
197
# In Django settings.py
198
INSTALLED_APPS = [
199
# ... other apps
200
'ddtrace.contrib.django',
201
]
202
203
# Security monitoring covers:
204
# - Django ORM queries
205
# - Template rendering
206
# - File uploads
207
# - Authentication flows
208
# - Admin interface access
209
```
210
211
#### Flask Integration
212
213
```python
214
import os
215
from flask import Flask
216
from ddtrace.constants import APPSEC_ENV
217
218
os.environ[APPSEC_ENV] = "true"
219
220
app = Flask(__name__)
221
222
# Flask routes are automatically monitored for:
223
# - Request parameter injection
224
# - File upload vulnerabilities
225
# - Template injection
226
# - Authentication bypasses
227
228
@app.route('/user/<user_id>')
229
def get_user(user_id):
230
# Automatically monitored for path traversal
231
return load_user_data(user_id)
232
233
@app.route('/search')
234
def search():
235
query = request.args.get('q')
236
# Automatically monitored for injection attacks
237
return search_database(query)
238
```
239
240
#### FastAPI Integration
241
242
```python
243
import os
244
from fastapi import FastAPI
245
from ddtrace.constants import APPSEC_ENV
246
247
os.environ[APPSEC_ENV] = "true"
248
249
app = FastAPI()
250
251
# FastAPI endpoints are automatically monitored
252
@app.post("/upload")
253
async def upload_file(file: bytes):
254
# Monitored for malicious file uploads
255
return process_uploaded_file(file)
256
257
@app.get("/data/{item_id}")
258
async def get_item(item_id: str):
259
# Monitored for injection and traversal attacks
260
return fetch_item_data(item_id)
261
```
262
263
### Vulnerability Reporting
264
265
Detected vulnerabilities and security events are automatically reported to Datadog with detailed context.
266
267
```python
268
# Vulnerability reports include:
269
# - Vulnerability type (SQL injection, XSS, etc.)
270
# - Severity level (critical, high, medium, low)
271
# - Affected code location and stack trace
272
# - Request details and attack payload
273
# - Remediation suggestions
274
275
# Example vulnerability detection:
276
def unsafe_sql_query(user_input):
277
# This would generate a vulnerability report:
278
# Type: SQL Injection
279
# Severity: High
280
# Location: Line 123, function unsafe_sql_query
281
# Payload: "'; DROP TABLE users; --"
282
# Suggestion: Use parameterized queries
283
284
query = f"SELECT * FROM products WHERE name = '{user_input}'"
285
return execute_query(query)
286
```
287
288
### Security Headers and Response Modification
289
290
Automatic enhancement of HTTP responses with security headers and protection mechanisms.
291
292
```python
293
# When AppSec is enabled, responses are automatically enhanced with:
294
# - Content Security Policy headers
295
# - X-Frame-Options headers
296
# - X-Content-Type-Options headers
297
# - Security event correlation headers
298
299
# Example of automatic response enhancement:
300
@app.route('/sensitive-data')
301
def get_sensitive_data():
302
data = fetch_sensitive_information()
303
304
# Response automatically includes:
305
# X-Content-Type-Options: nosniff
306
# X-Frame-Options: DENY
307
# Content-Security-Policy: default-src 'self'
308
# DD-Trace-ID: correlation header for security events
309
310
return jsonify(data)
311
```
312
313
### Custom Security Rules
314
315
Define custom security rules and detection patterns for application-specific threats.
316
317
```python
318
# Custom security rules can be configured through environment variables
319
import os
320
321
# Define custom attack patterns
322
os.environ["DD_APPSEC_RULES_FILE"] = "/path/to/custom-rules.json"
323
324
# Custom rule example (in JSON file):
325
# {
326
# "rules": [
327
# {
328
# "id": "custom-rule-001",
329
# "name": "API Key Exposure",
330
# "pattern": "sk-[a-zA-Z0-9]{48}",
331
# "severity": "high",
332
# "action": "block"
333
# }
334
# ]
335
# }
336
337
def process_api_request(request_data):
338
# Custom rules are automatically applied to monitor for:
339
# - API key exposure in logs/responses
340
# - Custom business logic vulnerabilities
341
# - Domain-specific attack patterns
342
return handle_request(request_data)
343
```
344
345
## Security Event Analysis
346
347
Security events and vulnerabilities detected by ddtrace AppSec appear in the Datadog Security platform with:
348
349
- **Attack Timeline**: Chronological view of security events
350
- **Vulnerability Assessment**: IAST-detected code vulnerabilities
351
- **Threat Intelligence**: Attack attribution and threat actor information
352
- **Risk Scoring**: Business impact assessment for detected threats
353
- **Remediation Guidance**: Code fix recommendations and security best practices
354
355
## Best Practices
356
357
### Production Deployment
358
359
```python
360
import os
361
from ddtrace.constants import APPSEC_ENV, IAST_ENV
362
363
# Production security configuration
364
os.environ[APPSEC_ENV] = "true" # Enable runtime protection
365
os.environ[IAST_ENV] = "false" # Disable IAST in production (use in staging)
366
367
# Configure appropriate sensitivity for production
368
os.environ["DD_APPSEC_RULES"] = "standard" # Balanced detection/performance
369
os.environ["DD_APPSEC_TRACE_RATE_LIMIT"] = "100" # Rate limit security traces
370
```
371
372
### Development and Testing
373
374
```python
375
import os
376
from ddtrace.constants import APPSEC_ENV, IAST_ENV
377
378
# Development/staging security configuration
379
os.environ[APPSEC_ENV] = "true" # Enable runtime monitoring
380
os.environ[IAST_ENV] = "true" # Enable vulnerability detection
381
382
# More verbose detection in development
383
os.environ["DD_APPSEC_RULES"] = "strict"
384
os.environ["DD_APPSEC_TRACE_RATE_LIMIT"] = "1000"
385
```
386
387
### Security Testing Integration
388
389
```python
390
# Integration with security testing frameworks
391
import unittest
392
from ddtrace.constants import APPSEC_ENV
393
394
class SecurityTestCase(unittest.TestCase):
395
def setUp(self):
396
os.environ[APPSEC_ENV] = "true"
397
398
def test_sql_injection_protection(self):
399
# Test that SQL injection attempts are detected
400
malicious_input = "'; DROP TABLE users; --"
401
result = search_users(malicious_input)
402
# Verify security event was generated
403
404
def test_xss_protection(self):
405
# Test that XSS payloads are detected
406
xss_payload = "<script>alert('xss')</script>"
407
result = render_user_content(xss_payload)
408
# Verify XSS attempt was blocked/detected
409
```