Code Analysis
Overview
ASCEND's Code Analysis Service detects dangerous patterns in AI-generated or AI-processed code using database-driven pattern matching with full CWE (Common Weakness Enumeration) and MITRE ATT&CK technique mapping. The service supports multiple programming languages and provides detailed findings for security remediation.
Why It Matters
AI systems that generate or process code introduce significant security risks:
- SQL Injection: AI-generated queries may be vulnerable to injection
- Command Injection: Shell commands may execute arbitrary code
- Code Execution: Dynamic code evaluation (eval, exec) is dangerous
- Path Traversal: File operations may access unauthorized directories
- Deserialization: Untrusted data deserialization enables code execution
Architecture
Analysis Pipeline
+------------------+ +------------------+ +------------------+
| Action Request | | Code Extraction | | Language |
| with Code | | | | Detection |
+--------+---------+ +--------+---------+ +--------+---------+
| | |
| Parameters contain | |
| query/code/script | |
+----------------------->| |
| | |
| | Extract code from |
| | known parameter names |
| | |
| +----------------------->|
| | |
| | | Detect language
| | | from action type
| | | or patterns
| | |
+--------+---------+ +--------+---------+ +--------+---------+
| Pattern Match |<----+ Load Effective |<----+ Language |
| | | Patterns | | Detected |
+--------+---------+ +------------------+ +------------------+
|
| Match against
| global + custom
| patterns
|
+--------+---------+
| Risk Score |
| Calculation |
+--------+---------+
|
| Apply org config
| severity scores
|
+--------+---------+
| Block Decision |
| (if enforce) |
+------------------+
Database Tables
| Table | Purpose |
|---|---|
global_code_patterns | Vendor-managed detection patterns |
org_code_analysis_config | Per-org configuration |
org_pattern_override | Customer pattern overrides |
org_custom_patterns | Customer-defined patterns |
code_pattern_audit_log | Detection audit trail |
Supported Languages
Language Detection
| Language | Detection Method | File Extensions |
|---|---|---|
| SQL | Keywords (SELECT, INSERT, etc.) | .sql |
| Python | Syntax (def, class, import) | .py |
| Shell/Bash | Shebang, commands | .sh, .bash |
| JavaScript | Syntax (function, const, =>) | .js, .ts |
| Go | Syntax (func, package) | .go |
Language Detection Patterns
LANGUAGE_PATTERNS = {
"sql": [
r"\b(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|GRANT|TRUNCATE)\b",
r"\bFROM\s+\w+",
r"\bWHERE\b",
],
"python": [
r"\bdef\s+\w+\s*\(",
r"\bclass\s+\w+",
r"\bimport\s+\w+",
],
"shell": [
r"^\s*(#!.*sh|#!/)",
r"\b(echo|cat|grep|rm|cp|mv|ls)\b",
r"\|\s*\w+",
],
"javascript": [
r"\bfunction\s+\w+\s*\(",
r"\bconst\s+\w+\s*=",
r"=>\s*{",
],
}
Detection Patterns
SQL Patterns
| Pattern ID | CWE | MITRE | Description | Severity |
|---|---|---|---|---|
| SQL-INJ-001 | CWE-89 | T1190 | SQL Injection (UNION) | Critical |
| SQL-INJ-002 | CWE-89 | T1190 | SQL Injection (Comment) | Critical |
| SQL-INJ-003 | CWE-89 | T1190 | SQL Injection (OR 1=1) | Critical |
| SQL-DDL-001 | CWE-564 | T1485 | DROP TABLE | Critical |
| SQL-DDL-002 | CWE-564 | T1485 | TRUNCATE TABLE | High |
| SQL-PRIV-001 | CWE-269 | T1078 | GRANT ALL | High |
SQL Injection Examples
-- SQL-INJ-001: UNION-based injection
SELECT * FROM users WHERE id = 1 UNION SELECT password FROM credentials
-- SQL-INJ-002: Comment-based injection
SELECT * FROM users WHERE name = 'admin'--' AND password = 'x'
-- SQL-INJ-003: Always-true condition
SELECT * FROM users WHERE id = 1 OR 1=1
-- SQL-DDL-001: Destructive DDL
DROP TABLE users;
-- SQL-DDL-002: Data wipe
TRUNCATE TABLE audit_logs;
Python Patterns
| Pattern ID | CWE | MITRE | Description | Severity |
|---|---|---|---|---|
| PY-EXEC-001 | CWE-95 | T1203 | eval() usage | Critical |
| PY-EXEC-002 | CWE-95 | T1203 | exec() usage | Critical |
| PY-CMD-001 | CWE-78 | T1059 | os.system() | Critical |
| PY-CMD-002 | CWE-78 | T1059 | subprocess.call(shell=True) | Critical |
| PY-DESER-001 | CWE-502 | T1203 | pickle.loads() | High |
| PY-PATH-001 | CWE-22 | T1083 | Path traversal (../) | High |
Python Vulnerability Examples
# PY-EXEC-001: Dynamic code execution
user_code = request.get('code')
result = eval(user_code) # CRITICAL: Code injection
# PY-CMD-001: Shell command injection
filename = request.get('filename')
os.system(f'cat {filename}') # CRITICAL: Command injection
# PY-CMD-002: Shell injection via subprocess
subprocess.call(user_command, shell=True) # CRITICAL
# PY-DESER-001: Insecure deserialization
data = pickle.loads(untrusted_data) # HIGH: Code execution
# PY-PATH-001: Path traversal
open(f'/data/{user_path}') # HIGH if user_path = '../../../etc/passwd'
Shell Patterns
| Pattern ID | CWE | MITRE | Description | Severity |
|---|---|---|---|---|
| SH-CMD-001 | CWE-78 | T1059 | Command substitution | High |
| SH-CMD-002 | CWE-78 | T1059 | Backtick execution | High |
| SH-PRIV-001 | CWE-269 | T1548 | sudo without password | High |
| SH-NET-001 | CWE-918 | T1071 | Curl to external URL | Medium |
Shell Vulnerability Examples
# SH-CMD-001: Command substitution injection
FILENAME=$(user_input)
cat $FILENAME # If user_input = "; rm -rf /"
# SH-CMD-002: Backtick execution
result=`$user_command` # HIGH: Arbitrary command
# SH-PRIV-001: Privilege escalation
sudo -n rm -rf / # HIGH: Sudo without password prompt
JavaScript Patterns
| Pattern ID | CWE | MITRE | Description | Severity |
|---|---|---|---|---|
| JS-EXEC-001 | CWE-95 | T1059 | eval() usage | Critical |
| JS-DOM-001 | CWE-79 | T1189 | innerHTML assignment | High |
| JS-XSS-001 | CWE-79 | T1189 | document.write() | High |
JavaScript Vulnerability Examples
// JS-EXEC-001: Dynamic code execution
const result = eval(userInput); // CRITICAL: Code injection
// JS-DOM-001: DOM-based XSS
element.innerHTML = userContent; // HIGH: XSS if not sanitized
// JS-XSS-001: Document manipulation
document.write(userData); // HIGH: XSS
Go Patterns
| Pattern ID | CWE | MITRE | Description | Severity |
|---|---|---|---|---|
| GO-CMD-001 | CWE-78 | T1059 | exec.Command with shell | High |
| GO-BUF-001 | CWE-119 | T1203 | Unsafe pointer | High |
CWE Mapping
Complete CWE Coverage
| CWE ID | Name | Languages | Patterns |
|---|---|---|---|
| CWE-22 | Path Traversal | Python, Shell | PY-PATH-001, SH-PATH-001 |
| CWE-77 | Command Injection | All | Multiple |
| CWE-78 | OS Command Injection | Python, Shell, Go | PY-CMD-, SH-CMD-, GO-CMD-* |
| CWE-79 | Cross-Site Scripting | JavaScript | JS-DOM-001, JS-XSS-001 |
| CWE-89 | SQL Injection | SQL | SQL-INJ-* |
| CWE-94 | Code Injection | JavaScript | JS-EXEC-001 |
| CWE-95 | Eval Injection | Python, JS | PY-EXEC-, JS-EXEC- |
| CWE-119 | Buffer Overflow | Go | GO-BUF-001 |
| CWE-269 | Improper Privilege | SQL, Shell | SQL-PRIV-, SH-PRIV- |
| CWE-502 | Deserialization | Python | PY-DESER-001 |
| CWE-564 | SQL Injection (Hibernate) | SQL | SQL-DDL-* |
| CWE-918 | Server-Side Request Forgery | Shell | SH-NET-001 |
MITRE ATT&CK Mapping
Technique Coverage
| Technique | Name | Patterns |
|---|---|---|
| T1059 | Command and Scripting Interpreter | PY-CMD-, SH-CMD-, GO-CMD-, JS-EXEC- |
| T1071 | Application Layer Protocol | SH-NET-001 |
| T1078 | Valid Accounts | SQL-PRIV-001 |
| T1083 | File and Directory Discovery | PY-PATH-001 |
| T1189 | Drive-by Compromise | JS-DOM-001, JS-XSS-001 |
| T1190 | Exploit Public-Facing Application | SQL-INJ-* |
| T1203 | Exploitation for Client Execution | PY-EXEC-, PY-DESER-, GO-BUF-* |
| T1485 | Data Destruction | SQL-DDL-* |
| T1548 | Abuse Elevation Control Mechanism | SH-PRIV-001 |
Risk Scoring
Score Calculation
def calculate_risk_score(finding: CodeFinding, config: OrgConfig) -> int:
"""Calculate risk score for a code finding."""
# Priority 1: Organization override
if finding.risk_score_override is not None:
return finding.risk_score_override
# Priority 2: CVSS base score conversion
if finding.cvss_base_score:
# Convert CVSS (0-10) to risk score (0-100)
return int(finding.cvss_base_score * 10)
# Priority 3: Organization severity mapping
return config.get_severity_score(finding.severity)
Default Severity Scores
| Severity | Risk Score | Block by Default |
|---|---|---|
| Critical | 95 | Yes |
| High | 80 | Yes (if threshold <= 80) |
| Medium | 60 | No |
| Low | 40 | No |
| Info | 20 | No |
Agent-Specific Thresholds
Each registered agent can have a custom risk threshold:
def get_effective_threshold(config: OrgConfig, agent_id: str) -> int:
"""Get block threshold considering agent-specific limits."""
org_threshold = config.block_threshold
if agent_id:
agent = db.query(RegisteredAgent).filter(
RegisteredAgent.agent_id == agent_id
).first()
if agent and agent.max_risk_threshold:
# Use the more restrictive threshold
return min(org_threshold, agent.max_risk_threshold)
return org_threshold
Configuration
Environment Variables
# Enable/disable code analysis
CODE_ANALYSIS_ENABLED=true
# Mode: enforce (block dangerous code), monitor (log only), off
CODE_ANALYSIS_MODE=enforce
# Risk score threshold for blocking
CODE_ANALYSIS_BLOCK_THRESHOLD=80
Organization-Level Configuration
{
"org_code_analysis_config": {
"enabled": true,
"mode": "enforce",
"block_threshold": 80,
"languages_enabled": ["sql", "python", "shell", "javascript", "go"],
"categories_enabled": [
"injection",
"execution",
"privilege_escalation",
"data_destruction",
"path_traversal",
"deserialization"
],
"severity_scores": {
"critical": 95,
"high": 80,
"medium": 60,
"low": 40,
"info": 20
},
"disabled_patterns": [],
"custom_patterns_enabled": true
}
}
Custom Patterns
Organizations can add custom detection patterns:
{
"org_custom_patterns": [
{
"pattern_id": "CUSTOM-SQL-001",
"language": "sql",
"category": "data_access",
"severity": "high",
"pattern_type": "regex",
"pattern_value": "SELECT\\s+\\*\\s+FROM\\s+(customers|payments|credit_cards)",
"pattern_flags": "IGNORECASE",
"description": "Access to sensitive financial tables",
"recommendation": "Use column-specific queries with proper authorization",
"cwe_ids": ["CWE-200"],
"mitre_techniques": ["T1213"],
"cvss_base_score": 7.5
}
]
}
Pattern Overrides
Organizations can override vendor patterns:
{
"org_pattern_override": [
{
"pattern_id": "SQL-DDL-002",
"is_disabled": false,
"severity_override": "critical",
"risk_score_override": 100
}
]
}
Fail-Secure Behavior
| Scenario | Response |
|---|---|
| Pattern loading fails | BLOCK all code execution |
| Analysis timeout | BLOCK code |
| Language detection fails | Analyze as "any" language (apply all patterns) |
| Config unavailable | Use strictest defaults |
| Database unavailable | Use cached patterns, BLOCK on cache miss |
Compliance Mapping
| Framework | Control | Implementation |
|---|---|---|
| SOC 2 | CC6.1 | Code input validation |
| SOC 2 | CC7.1 | Real-time vulnerability detection |
| PCI-DSS | Req 6.5 | Address common coding vulnerabilities |
| PCI-DSS | Req 6.5.1 | Injection flaws |
| HIPAA | 164.312(e) | Technical safeguards |
| NIST 800-53 | SI-10 | Information input validation |
| OWASP ASVS | V5 | Validation, sanitization, encoding |
Verification
Test SQL Injection Detection
curl -X POST https://api.ascend.io/v1/actions/evaluate \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "test-agent",
"action_type": "execute_sql",
"parameters": {
"query": "SELECT * FROM users WHERE id = 1 OR 1=1"
}
}'
# Expected response
{
"decision": "DENY",
"reason": "Critical code pattern detected: SQL-INJ-003",
"risk_score": 95,
"code_analysis": {
"analyzed": true,
"language": "sql",
"findings": [
{
"pattern_id": "SQL-INJ-003",
"severity": "critical",
"category": "injection",
"cwe_ids": ["CWE-89"],
"mitre_techniques": ["T1190"],
"matched_text": "1 OR 1=1",
"line_number": 1,
"recommendation": "Use parameterized queries"
}
]
}
}
Test Python Code Analysis
curl -X POST https://api.ascend.io/v1/actions/evaluate \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "test-agent",
"action_type": "execute_python",
"parameters": {
"code": "import os\nos.system(user_input)"
}
}'
# Expected response
{
"decision": "DENY",
"reason": "Critical code pattern detected: PY-CMD-001",
"risk_score": 95,
"code_analysis": {
"analyzed": true,
"language": "python",
"findings": [
{
"pattern_id": "PY-CMD-001",
"severity": "critical",
"category": "execution",
"cwe_ids": ["CWE-78"],
"mitre_techniques": ["T1059"],
"matched_text": "os.system(user_input)",
"line_number": 2,
"recommendation": "Use subprocess with shell=False and input validation"
}
]
}
}
Get Code Analysis Statistics
curl -X GET https://api.ascend.io/v1/security/code-analysis/stats \
-H "Authorization: Bearer $TOKEN"
# Response
{
"total_patterns": 45,
"global_patterns": 40,
"custom_patterns": 5,
"patterns_by_language": {
"sql": 12,
"python": 15,
"shell": 8,
"javascript": 7,
"go": 3
},
"patterns_by_severity": {
"critical": 18,
"high": 15,
"medium": 8,
"low": 4
}
}
Next Steps
- Compliance Overview - Framework mapping
- SOC 2 Mapping - SOC 2 Type II controls
- Security Architecture - 12-layer defense