diff --git a/_labs/example_highlighting_guide.md b/_labs/example_highlighting_guide.md index 86a5b1a..37ddb07 100644 --- a/_labs/example_highlighting_guide.md +++ b/_labs/example_highlighting_guide.md @@ -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 diff --git a/_labs/software_and_malware_analysis/3_c_and_asm.md b/_labs/software_and_malware_analysis/3_c_and_asm.md index 079a7d9..69d2512 100644 --- a/_labs/software_and_malware_analysis/3_c_and_asm.md +++ b/_labs/software_and_malware_analysis/3_c_and_asm.md @@ -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: | diff --git a/_labs/web_security/1_intro_web_security.md b/_labs/web_security/1_intro_web_security.md new file mode 100644 index 0000000..5a0484d --- /dev/null +++ b/_labs/web_security/1_intro_web_security.md @@ -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 + + +

Here's a web page!

+Hello! + +``` + +> Tip: Make sure you have an empty line where the headers finish, before the . + +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 + +The time is: + +``` + +==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 + + + +``` + +> 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 diff --git a/_labs/web_security/2_sessions_and_cookies.md b/_labs/web_security/2_sessions_and_cookies.md new file mode 100644 index 0000000..10d9b7e --- /dev/null +++ b/_labs/web_security/2_sessions_and_cookies.md @@ -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 + + + + + + +``` + +==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 + + + + + + + +``` + +==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 diff --git a/_labs/web_security/3_xss.md b/_labs/web_security/3_xss.md new file mode 100644 index 0000000..d6161d9 --- /dev/null +++ b/_labs/web_security/3_xss.md @@ -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 + + + +Hello, ! + + +``` + +==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== `` + +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== + +`` + +> 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 `#is', '', $_REQUEST['name']); +session_start(); +?> + + +Hello, ! + + +``` + +==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== + +``` + +``` + +> 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:== + +* `` +* `click me` + +> 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 + + + +Hello, ! + + +``` + +==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:== + +* `` + +* `` + +* `click me` + +> 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 | +| :---- | +| \alert('XSS')\ | +| \ | +| \ | +| \