Skip to main content

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

TablePurpose
global_code_patternsVendor-managed detection patterns
org_code_analysis_configPer-org configuration
org_pattern_overrideCustomer pattern overrides
org_custom_patternsCustomer-defined patterns
code_pattern_audit_logDetection audit trail

Supported Languages

Language Detection

LanguageDetection MethodFile Extensions
SQLKeywords (SELECT, INSERT, etc.).sql
PythonSyntax (def, class, import).py
Shell/BashShebang, commands.sh, .bash
JavaScriptSyntax (function, const, =>).js, .ts
GoSyntax (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 IDCWEMITREDescriptionSeverity
SQL-INJ-001CWE-89T1190SQL Injection (UNION)Critical
SQL-INJ-002CWE-89T1190SQL Injection (Comment)Critical
SQL-INJ-003CWE-89T1190SQL Injection (OR 1=1)Critical
SQL-DDL-001CWE-564T1485DROP TABLECritical
SQL-DDL-002CWE-564T1485TRUNCATE TABLEHigh
SQL-PRIV-001CWE-269T1078GRANT ALLHigh

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 IDCWEMITREDescriptionSeverity
PY-EXEC-001CWE-95T1203eval() usageCritical
PY-EXEC-002CWE-95T1203exec() usageCritical
PY-CMD-001CWE-78T1059os.system()Critical
PY-CMD-002CWE-78T1059subprocess.call(shell=True)Critical
PY-DESER-001CWE-502T1203pickle.loads()High
PY-PATH-001CWE-22T1083Path 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 IDCWEMITREDescriptionSeverity
SH-CMD-001CWE-78T1059Command substitutionHigh
SH-CMD-002CWE-78T1059Backtick executionHigh
SH-PRIV-001CWE-269T1548sudo without passwordHigh
SH-NET-001CWE-918T1071Curl to external URLMedium

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 IDCWEMITREDescriptionSeverity
JS-EXEC-001CWE-95T1059eval() usageCritical
JS-DOM-001CWE-79T1189innerHTML assignmentHigh
JS-XSS-001CWE-79T1189document.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 IDCWEMITREDescriptionSeverity
GO-CMD-001CWE-78T1059exec.Command with shellHigh
GO-BUF-001CWE-119T1203Unsafe pointerHigh

CWE Mapping

Complete CWE Coverage

CWE IDNameLanguagesPatterns
CWE-22Path TraversalPython, ShellPY-PATH-001, SH-PATH-001
CWE-77Command InjectionAllMultiple
CWE-78OS Command InjectionPython, Shell, GoPY-CMD-, SH-CMD-, GO-CMD-*
CWE-79Cross-Site ScriptingJavaScriptJS-DOM-001, JS-XSS-001
CWE-89SQL InjectionSQLSQL-INJ-*
CWE-94Code InjectionJavaScriptJS-EXEC-001
CWE-95Eval InjectionPython, JSPY-EXEC-, JS-EXEC-
CWE-119Buffer OverflowGoGO-BUF-001
CWE-269Improper PrivilegeSQL, ShellSQL-PRIV-, SH-PRIV-
CWE-502DeserializationPythonPY-DESER-001
CWE-564SQL Injection (Hibernate)SQLSQL-DDL-*
CWE-918Server-Side Request ForgeryShellSH-NET-001

MITRE ATT&CK Mapping

Technique Coverage

TechniqueNamePatterns
T1059Command and Scripting InterpreterPY-CMD-, SH-CMD-, GO-CMD-, JS-EXEC-
T1071Application Layer ProtocolSH-NET-001
T1078Valid AccountsSQL-PRIV-001
T1083File and Directory DiscoveryPY-PATH-001
T1189Drive-by CompromiseJS-DOM-001, JS-XSS-001
T1190Exploit Public-Facing ApplicationSQL-INJ-*
T1203Exploitation for Client ExecutionPY-EXEC-, PY-DESER-, GO-BUF-*
T1485Data DestructionSQL-DDL-*
T1548Abuse Elevation Control MechanismSH-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

SeverityRisk ScoreBlock by Default
Critical95Yes
High80Yes (if threshold <= 80)
Medium60No
Low40No
Info20No

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

ScenarioResponse
Pattern loading failsBLOCK all code execution
Analysis timeoutBLOCK code
Language detection failsAnalyze as "any" language (apply all patterns)
Config unavailableUse strictest defaults
Database unavailableUse cached patterns, BLOCK on cache miss

Compliance Mapping

FrameworkControlImplementation
SOC 2CC6.1Code input validation
SOC 2CC7.1Real-time vulnerability detection
PCI-DSSReq 6.5Address common coding vulnerabilities
PCI-DSSReq 6.5.1Injection flaws
HIPAA164.312(e)Technical safeguards
NIST 800-53SI-10Information input validation
OWASP ASVSV5Validation, 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