29,99 €
Web attacks and exploits pose an ongoing threat to the interconnected world. This comprehensive book explores the latest challenges in web application security, providing you with an in-depth understanding of hackers' methods and the practical knowledge and skills needed to effectively understand web attacks.
The book starts by emphasizing the importance of mindset and toolset in conducting successful web attacks. You’ll then explore the methodologies and frameworks used in these attacks, and learn how to configure the environment using interception proxies, automate tasks with Bash and Python, and set up a research lab. As you advance through the book, you’ll discover how to attack the SAML authentication layer; attack front-facing web applications by learning WordPress and SQL injection, and exploit vulnerabilities in IoT devices, such as command injection, by going through three CTFs and learning about the discovery of seven CVEs. Each chapter analyzes confirmed cases of exploitation mapped with MITRE ATT&CK. You’ll also analyze attacks on Electron JavaScript-based applications, such as XSS and RCE, and the security challenges of auditing and exploiting Ethereum smart contracts written in Solidity. Finally, you’ll find out how to disclose vulnerabilities.
By the end of this book, you’ll have enhanced your ability to find and exploit web vulnerabilities.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 357
Veröffentlichungsjahr: 2023
Discover the mindset, techniques, and tools to perform modern web attacks and exploitation
Simone Onofri
Donato Onofri
BIRMINGHAM—MUMBAI
Copyright © 2023 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Pavan Ramchandani
Publishing Product Manager: Prachi Sawant
Book Project Manager: Aryaa Joshi
Senior Content Development Editor: Adrija Mitra
Technical Editor: Nithik Cheruvakodan
Copy Editor: Safis Editing
Proofreader: Safis Editing
Indexer: Rekha Nair
Production Designer: Jyoti Chauhan
DevRel Marketing Coordinator: Marylou De Mello
First published: August 2023
Production reference: 1270723
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul's Square
Birmingham
B3 1RB, UK.
ISBN 978-1-80181-629-8
www.packtpub.com
Many thanks to our amazing partners, Manuela and Giulia, for always supporting us, encouraging us, and being there when we needed them the most.
Furthermore, to our family, including the newest addition to our tribe. May this book inspire you to explore, experiment, and follow your passions!
– Simone and Donato
The internet has become integral to our daily lives in today’s interconnected world. From online banking and shopping to social networking and communication, the web has transformed how we live, work, and interact. However, this digital revolution has also brought new challenges and risks, with cyber threats lurking everywhere.
Web application security, therefore, plays a vital role in ensuring the integrity, confidentiality, and availability of information transmitted over the internet. It encompasses a range of practices, technologies, and measures designed to protect web applications and IoT devices from unauthorized access, exploitation, and manipulation.
How do we prepare for the next era of web attacks and exploitation? I am honored to present Attacking and Exploiting Modern Web Applications, a groundbreaking book by Simone Onofri and Donato Onofri.
With their extensive knowledge and expertise in cybersecurity, they have crafted an excellent guide that sheds light on the art of exploiting web vulnerabilities.
With over two decades of combined experience, Donato and Simone are pioneers in web security, renowned for their dedication to research and innovation. Their expertise and passion for empowering others to defend themselves against cyber threats make them the perfect guides through the intricate world of web exploitation.
In Attacking and Exploiting Modern Web Applications, the authors take readers on a captivating journey that begins with exploring the hacker’s mindset. They emphasize that hacking is not just about technical skills but also about a particular mindset – a mindset driven by curiosity, problem-solving, and a deep understanding of how systems can be manipulated.
Beyond delving into the mindset, Attacking and Exploiting Modern Web Applications offers an array of real-life case studies that demonstrate the practical application of the concepts discussed throughout the book. These case studies showcase how vulnerabilities can be exploited in actual web applications. By analyzing these real-world examples, readers will understand how to perform a test and the importance of proactive defense measures.
The book stands out as a valuable resource for both beginners and experienced professionals in the field of cybersecurity. It offers a unique blend of the hacker mindset, real-world case studies, and technical expertise, ensuring readers are well equipped to tackle the challenges posed by web security exploits.
Attacking and Exploiting Modern Web Applications is not just a book; it is a testament to the importance of continuous learning and collaboration and the relentless pursuit of secure digital environments. I wholeheartedly endorse this book as an invaluable resource for those seeking to enhance their knowledge and skills in web security.
While the subject matter may be inherently challenging, Simone and Donato have successfully balanced technical depth and accessibility. Their ability to communicate complex concepts clearly and concisely ensures that readers of all skill levels can benefit from the knowledge shared within these pages.
Join us on this extraordinary journey as we uncover the secrets of advanced web attacks. Together, let us enhance our understanding of web security exploits and work toward a safer and more resilient digital future.
Matteo Meucci
CEO, IMQ Minded Security, and OWASP Testing Guide Lead
Simone Onofri is a cybersecurity director with over two decades of experience in Red and Blue Teaming, vulnerability research, and product management. He has been an instructor at the Joint Intelligence and EW Training Centre and is associated with global companies such as Hewlett-Packard Enterprise. Simone has discovered various vulnerabilities and holds key certifications such as GXPN, GREM, GWAPT, OSCP, and OPSA. An active participant in organizations such as OWASP and ISECOM, he regularly speaks at major conferences, including TEDx. Simone is committed to inspiring and educating industry professionals and enthusiasts through his work, with a mission to create a positive influence.
Donato Onofri is a seasoned Red Team engineer. He has over a decade of experience in activities including reverse engineering, Red Teaming, threat research, and penetration testing. Passionate about both the offensive and defensive sides of cybersecurity, Donato has worked with industry leaders such as CrowdStrike and Hewlett-Packard Enterprise and as an advisor and engineer for governments and financial institutions. His research delves into state-of-the-art security techniques, malware analysis, and internals. He holds the GREM, GXPN, OSCP, OSCE, and OSWE certifications, and his expertise is underscored by multiple recognitions for vulnerability discovery.
We sincerely thank Neha Sharma, Prachi Sawant, Aryaa Joshi, and Adrija Mitra at Packt for their infinite patience.
We also thank Matteo Meucci of IMQ Minded Security, Luca “beinux”, Antonio Parata, Gerardo Di Giacomo, Sanket Agarwal of QuillAcademy, Giancluca Varisco, and Pascal Ackerman for their invaluable technical insights.
A special acknowledgment goes to Donato’s colleagues at CrowdStrike, and Simone's colleagues too, for their supportive work environment, which afforded them the time to contribute to this book.
Lastly, we sincerely appreciate our families’ unwavering support while writing this book. Your patience and encouragement have been integral to this journey.
Our heartfelt thanks to all.
Saeed Dehqan is currently a project leader working with OWASP and an instructor at Hakin9.org e-learning. At OWASP, he is a security researcher and project leader. He has extensive experience in security areas such as network security, secure coding, threat hunting, and applied deep learning for threat analysis. He has six years of experience in research and works in the software engineering and cybersecurity fields for some companies. He was also a mentor at Google Summer of Code 2021 and 2022 for students who actively conducted research on applying NLP to cyber-threat hunting. He is passionate about natural language processing and uses it for cybersecurity purposes.
I’d like to thank Bell, Neda, and Negar.
Antonio Parata has worked in computer security since 2001, with 13 years specifically dedicated to web application security.
Antonio is currently a CrowdStrike employee with a focus on malware analysis and reverse engineering. In the past, he collaborated with OWASP and is one of the OWASP Testing Guide v2 co-authors. He is a Phrack author, having written an article on .NET instrumentation via MSIL bytecode injection. Antonio is a passionate developer with a focus on low-level development and the creation of offensive tools.
Antonio has a master’s degree in computer science from Politecnico di Milano.
Gerardo Di Giacomo is an information security professional and aficionado, with over 20 years of industry experience. He is currently the information security lead at Aptos Labs, focused on securing the Aptos web3 stack and ecosystem. After spending several years as a consultant for private companies and government organizations, Gerardo helped secure some popular products, including Microsoft’s Windows, Office, Azure, and the Surface lineup, Meta’s WhatsApp, Signal Messenger, and Stripe’s product offering. Outside of work, Gerardo actively contributes to the growth of the security community, most recently by supporting the RomHack security conference and the editorial project Guerre di Rete.
Ameya Khankar is a highly regarded and trusted business technology and cybersecurity professional focusing on the areas of technology risk, enterprise transformations, and digital governance. He advises large global enterprises in the US and globally as an expert on enterprise technology risks with a deep focus on strategies for strengthening their cybersecurity posture. He has advised a $4-billion organization in the past in defining their business transformation enterprise security strategy. He has also advised a $9-billion organization in meeting complex digital transformation and cybersecurity regulatory requirements.
Why is there a need for another book on web attacks and exploitation? More than two decades have passed since Jeff “Rain Forest Puppy” Forristal first discussed the then-unknown SQL injection in the well-known Phrack e-zine in 1998.
The web plays a significant role in our daily lives and business operations. It has progressed from static web pages to the era of user-generated content known as Web 2.0, and now we have Web 3.0, a decentralized web that operates on blockchain technology.
Having been involved in web application security from its infancy, we find it fascinating to assess the current state of attacks and exploitation of web vulnerabilities. As suggested by the OWASP TOP 10, the nature of these vulnerabilities remains relatively consistent, although their specific characteristics evolve. Examining how Advanced Persistent Threats (APTs) often use web attacks for initial access and persistence is interesting – mapping them using MITRE ATT&CK.
This book will provide an in-depth understanding of hackers’ methods for web attacks and exploitation, analyzing some Capture the Flags (CTFs) we created and several Common Vulnerabilities and Exposures (CVEs) we discovered.
The first part helps you understand the methodologies and frameworks, how to configure your research lab, and how to automate tasks with Bash and Python.
The second and third parts will guide you through practical examples using dynamic analysis, analyzing source code, reversing binaries, debugging, and instrumenting. In each chapter, you will find a brief introduction to the basics of each specific technology, the vulnerability, and the risk. Then, we’ll provide step-by-step instructions to discover and exploit the vulnerabilities.
In the second part, you’ll get an overview of evergreen vulnerabilities in authentication with a use case on SAML, SQL injection and Cross-Site Scripting (XSS) on WordPress, and Command Injection and Path Traversal on Internet of Things (IoT) devices, and then we’ll focus on analyzing source code and reversing binaries.
In the third part, you will see vulnerabilities in newer contexts, turning an XSS into a Remote Code Execution (RCE), analyzing Electron JavaScript applications and, exploiting the famous Reentrancy when auditing an Ethereum smart contract written in Solidity.
After reading this book, you will have improved your skills in identifying and taking advantage of web vulnerabilities and comprehending the consequences of disclosure.
This book is aimed at anyone who must ensure their organization’s security. It’s for penetration testers and red teamers who want to deepen their knowledge of the current security challenges for web applications, Developers and DevOps Engineers who want to get into the mindset of an attacker, and Security Managers and Chief Information Security Officers (CISOs) who want to truly understand the impact and risk of the Web, IoT, and smart contracts from an attacker’s point of view.
How to read this book
We recommend reading the various chapters in order if you are a beginner.
If you are familiar with web attacks and exploitation or prefer to go straight to the practical exercises, you can directly read Parts 2 and 3 and skim Part 1.
If you’re a security manager or CISO, the book can help you understand an attacker’s mindset, but you can focus on the sections devoted to you.
If you’re interested in a specific topic instead, each scenario is self-consistent, so you can go straight to the part you’re interested in.
Chapter 1, Mindset and Methodologies, offers an overview of the mindset and guiding principles for attacks, the learning process, the skill set, techniques for exploitation, and the methodologies that can be used to attack web applications.
Chapter 2, Toolset for Web Attacks and Exploitation, explains the tools available to attack web applications such as operating systems, browsers, interception proxies, Bash, and Python by playing a CTF.
Chapter 3, Attacking the Authentication Layer – a SAML Use Case, contains the first scenario we will analyze, again through a CTF exercise, where we will learn to exploit authentication systems, specifically SAML, through Burp.
Chapter 4, Attacking Internet-Facing Web Applications – SQL Injection and Cross-Site Scripting (XSS) on WordPress, explores another scenario where we will find two CVEs together. We will find a SQL injection by reading the source code for a WordPress plugin and exploiting it first by hand with Burp and then with Python. We will also find an XSS.
Chapter 5, Attacking IoT Devices – Command Injection and Path Traversal, examines a scenario where we will analyze an IoT device, starting from the firmware, emulate it, and find four CVEs relating to command injections, bypassing some security features. We will also reverse-engineer together some of the binaries present in the device.
Chapter 6, Attacking Electron JavaScript Applications – from Cross-Site Scripting (XSS) to Remote Command Execution (RCE), delves into a scenario where we will analyze an Electron JavaScript application we use daily, figuring out how to instrument and debug it. We will find a CVE related to an XSS, which we will then turn into an RCE.
Chapter 7, Attacking Ethereum Smart Contracts – Reentrancy, Weak Sources of Randomness, and Business Logic, provides the last scenario. It’s structured as a CTF exercise, where we will analyze smart contracts on Ethereum, revert them, and exploit several business logic vulnerabilities and the famous reentrancy by writing an attacking contract with Solidity and Foundry.
Chapter 8, Continuing the Journey of Vulnerability Discovery, concludes by reflecting on what we learned in the previous chapters. There’s not so much about specific vulnerabilities and, in general, more about the methods used. We will also mention the vulnerability disclosure dilemma from the researcher and CISO perspectives.
To get the most out of this book, you should be interested in web application security and vulnerability research. We also suggest having a good knowledge of web technologies and related protocols and a basic understanding of reverse engineering.
Software/hardware covered in the book
Operating system requirements
Burp
The host system can be Windows, macOS, or Linux, with enough power to run two or three Linux-based containers.
Python
Bash
Having physical GL.iNet devices such as the Mango or the Shadow is preferable for recreating the scenario in Chapter 5.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors in copying and pasting code.
We suggest that you not only read the book but also recreate the scenarios included in it by trying them out locally, either by following the directions in the book or by finding solutions on your own.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Attacking-and-Exploiting-Modern-Web-Applications. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “We found two headers containing the specific PHP (X-Powered-By) and Apache (Server) versions.”
A block of code is set as follows:
SELECT id, wpid, room, timestamp, UNIX_TIMESTAMP(timestamp) AS unix_timestamp, alias, status, message FROM $Shoutbox_messages_table_name.' WHERE room IN ("'.$rooms.'") AND timestamp > FROM_UNIXTIME('.esc_sql($_POST['last_timestamp']).') ORDER BY unix_timestamp ASCWhen we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
function esc_sql( $data ) { global $wpdb; return $wpdb->_escape( $data ); }Any command-line input or output is written as follows:
$ curl -kis http://localhost | grep generator <meta name="generator" content="WordPress 6.1.1" />Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Select and right-click on that image from the menu, and click Inspect to see precisely the resulting code.”
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at customercare@packtpub.com and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packtpub.com with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Once you’ve read Attacking and Exploiting Modern Web Applications, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781801816298
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyAs a quote incorrectly attributed to Abraham Lincoln but coming from a wise and anonymous lumberjack teaches us, “If I had five minutes to chop down a tree, I’d spend the first three sharpening my axe”.
This leads us to the point that preparation is critical.
So, we will focus on sharpening our tools before performing our attacks. Of course, given the essence of our work, we will only know later what we will need when faced with an unknown vulnerability. The essential tool to have ready is our mind, plus a set of technological tools always at hand.
This part has the following chapters:
Chapter 1, Mindset and MethodologiesChapter 2, Toolset for Web Attacks and Exploitation“Novices often view exploitation as some sort of magic process, but no magic is involved – only creativity, cleverness, and a lot of dedication. In other words, it is an art.”
Enrico Perla and Massimo Oldani [1]
Welcome to the first chapter, where we will begin our journey by understanding the right approach, mindset, and methodologies for attacking and exploiting modern web applications.
As we read in the epigraph, taken from the book A Guide to Kernel Exploitation, written by a dear friend, exploitation is considered an art, which makes it difficult to systematize. While our discussion focuses on web applications rather than the Linux kernel, it is essential to clarify what we mean by attacking web applications and exploiting their vulnerabilities.
In the first part of this chapter, we will clarify these concepts and learn about the approach, the steps of an attack, the testing techniques, the mindset, and the competencies we need to have.
In the second part, we will learn about the existing methodologies and how to combine them to use them effectively in real-world scenarios.
In this chapter, we’re going to cover the following main topics:
Approach and mindsetMethodologies and frameworks for attacking web applicationsWe can define web attacks as activities that “targets vulnerabilities in websites to gain unauthorized access, obtain confidential information, introduce malicious content, or alter the website’s content” [2]. This includes the preparatory steps necessary for successful attacks in the context of web applications, such as information gathering, context-related risk analysis (threat modeling), and vulnerability discovery and analysis.
We will usually encounter these activities whether we are penetration testers, code reviewers, security researchers, or bug hunters. Even if we are red teamers and work primarily on networks and operating systems, we can find web applications during Initial Access [3], as well as when playing Capture the Flag (CTF) exercises, trying to solve web challenges.
Understanding these types of attacks can prove beneficial for various roles:
Developers: Gaining an “attacker’s” perspective can assist in writing more secure code. This efficient approach is commonly incorporated into the security awareness courses we teach.Forensic Analysts and Incident Responders: They might need to analyze incidents involving applications or web servers. Knowledge about these attacks can provide a comprehensive understanding of what happened.Security Managers and Chief Information Security Officers: They may need to assess and manage risks related to web applications. This understanding can be instrumental in forming strategic security measures.Now that we know what web attacks are, let’s look at how to approach them when dealing with an application.
What is exploitation?
Let’s solve the exploitation definition we discussed in the epigraph, so we’re all on the same page.
It all begins with a bug – an issue in the code, design, or configuration that generates a malfunction, incorrect results, a crash, or an abnormal termination.
We are particularly interested in bugs that have security implications (security bugs), which can potentially be used to compromise an application or one of its components.
Unfortunately, or fortunately, not all security bugs are potentially exploitable; when they are, they are called vulnerabilities.
So, an exploit is a code or a procedure that allows you to take advantage of one or more vulnerabilities, and exploitation is the term used to describe this process.
Discovering and exploiting vulnerabilities can be likened to a problem-solving exercise.
Consider this example – we were hired to conduct a Web Application Penetration Test (WAPT) on one web application accessible online: https://onofri.org/security/. We started from scratch – no credentials or inside information about the target. Thus, we interacted with a user-friendly web application that reciprocated our requests with HTML code, JavaScript, CSS, and images. What’s our next move?
If this was our first time engaging in such an activity or our first encounter with this target type, we could have considered two distinct approaches. The first, a more academic approach, involves studying all relevant theoretical concepts before proceeding to the practical stage. The second, a decided tinkerer approach, encourages hands-on experience.
However, there is a third way to balance these two extremes. As the Latins once stated, “In medio stat virtus” (“virtue stands in the middle”):
Acquire a foundational understanding of theoretical concepts. This doesn’t involve becoming an expert but providing context and aiding navigation in specific situations. This foundational understanding can be bifurcated into two parts – understanding the technology itself and knowing about potential vulnerabilities and attacks that might be employed.Dive into hands-on practice. This involves exploring our needs through trial and error, observing an application’s responses to our requests, and modifying the application to understand its workings better. In this process, we loop back to theoretical concepts as and when required. This iterative approach allows for both practical and theoretical growth.Following the various steps, let’s see how we use this approach when attacking a web application.
The approach in the book
This book embodies this approach through its structure – the initial part serves as a primer, while the following two provide practical, scenario-based examples.
Moreover, every scenario-centric chapter commences with a theoretical discussion before transitioning into the practical aspect.
When we launch a web attack, we rely on a process that involves preparatory steps such as information gathering, threat modeling, vulnerability discovery, and vulnerability analysis. Then, we have the actual attack, which – if successful – leads to exploitation. These steps are based on the technical sections of the Penetration Testing Executing Standard (PTES) [4].
If we start without having any information about the target, the first thing we do is to understand the technology that underpins the application. There are several methods. Examining the HTML code returned from https://onofri.org/security is the most straightforward and least invasive. We can do this from any web browser, such as Firefox, by pressing Ctrl + U on Windows and Linux or Cmd + Uon macOS.
We will find two particularly interesting lines from the HTML code associated with the meta tag named generator. As name suggests, this tag typically contains information about the software used to generate the page:
<meta name="generator" content="WordPress 6.2.2"/>The code remains quite clear, even if we do not know HTML. We can now infer that WordPress version 6.2.2 powers the website.
Our next step is to visit the WordPress site for further investigation. First, we will check whether the installed version is the latest and whether any known vulnerabilities are associated.
To become more familiar with WordPress, as open source software with publicly available code, we will download it and examine its file structure and contents. We can read the PHP (a recursive acronym for PHP: Hypertext Preprocessor) code and understand the structure – some foundational files – named WordPress Core – and a wide range of pluginsand themes.
The source code gives us a significant advantage because it allows us to find vulnerabilities through static analysis by reviewing the code instead of relying solely on dynamic methods, such as sending queries. It also allows us to recreate the target application in our lab environment for analysis. This controlled environment allows us to modify the application, enhancing our understanding in a more “hybrid” fashion.
As Core allows additional plugins and themes, our next step should be identifying which ones are installed. Let’s understand the installed theme.
The file structure shows the themes inside the wp-content/themes directory. We then examine the HTML code again for this information. We can find it easily:
<script src='https://onofri.org/security/wp-content/themes/astra/assets/js/minified/frontend.min.js?ver=4.1.5' id='astra-theme-js-js'></script>We’ve determined that the active theme is astra. We know the theme but not the version. However, we can download it to determine when to read the version. From the theme directory, we find the following file list:
404.php, admin, archive.php, assets, changelog.txt, comments.php, footer.php,functions.php, header.php, inc, index.php, languages, page.php, readme.txt,screenshot.jpg, search.php, searchform.php, sidebar.php, single.php, style.css,template-parts, theme.json, toolset-config.json, wpml-config.xmlTake readme.txt, for example, which contains extensive metadata. Unfortunately, we get blocked when we try to access it via https://onofri.org/security/wp-content/themes/astra/readme.txt.
Undaunted, we look for an alternative and find that changelog.txt contains the version information and is accessible via https://onofri.org/security/wp-content/themes/astra/changelog.txt. We can get the installed version from here by looking for the latest entry:
v4.1.5 - Fix: Offcanvas Menu - Transparent empty canvas visible on expanding offcanvas toggle button. - Fix: Custom Layouts - Block editor core blocks custom spacing incorrectly applies to custom layout blocks in editor.In addition, our familiarity with WordPress allows us to identify the login page address (https://onofri.org/security/wp-login.php) and potentially perform actions such as user enumeration or password discovery.
This is an example of our strategy when targeting a web application. Given the target scope of https://onofri.org/security, we can discover numerous other elements.
Now that we know the version of WordPress, the theme, and its version, we can proceed by enumerating the installed plugins.
This can be done passively by examining the generated code or more actively (and somewhat aggressively) by creating a list of all available plugins (or the most commonly installed ones) and checking for the presence of files in the target path.
In the same way, we can consider a wordlist of common files such as phpinfo.php, info.php, or test.php.
Once we understand our target, we will prepare our potential avenues of attack. To determine the most effective types of attacks, we need to understand the context and related risks. This practice is called threat modeling. We can be specific about the capabilities and the technology used and match them to our goals, such as the following:
If a SQL database is used, we might try SQL injection to gain database access (see an example in Chapter 4).If there are functions that send commands to the operating system, we can attempt command injections to execute arbitrary commands (see an example in Chapter 5).If a login page is available, we might try to access the admin panel or impersonate other users to have more control over the application (see an example in Chapter 3).If we can display input strings under our control, we can look for cross-site scripting (XSS) to execute arbitrary JavaScript on a user’s browser (see examples in Chapter 4 and Chapter 6).Alternatively, we can use a relatively simple method, prompt lists, or checklists in risk management. These lists can guide us on what risks and attacks to consider. We can use the Open Worldwide Application Security Project (OWASP) or the Web Security Testing Guide (WSTG) [5] (formerly the OWASP Testing Guide), which provides a massive list of attacks organized into different categories.
Although these lists are massive, they are partial. For example, on OWASP Italy Day 2012, with a friend, we presented a study on semantic web-related vulnerabilities. We explained the SPARQL Protocol and RDF Query Language (SPARQL) language and how to do SPARQL Injections [6]. we also found a SQL injection inside the SPARQL endpoint. Despite this, SPARQL injection is not currently listed in the testing guide.
Armed with enough information about the target and a defined threat model, we can begin discovering vulnerabilities, analyzing them, and attempting to exploit them. This step typically varies in the amount of time it takes. We will focus on this particular aspect, as well as exploitation, in our book.
Let’s go ahead and continue with our example.
We will check whether WordPress, its plugins, and its themes are up to date with the latest version or whether known vulnerabilities are present. It went wrong for us this time.
However, we discovered a test page inadvertently exposed in our search for vulnerable pages. Its guessable name, test.php, tipped us off.
When we visit the page at https://onofri.org/security/test.php, we find a form to enter text input. By inputting the text hello there, we find it within the response exactly as we wrote it or, as we say in the jargon, “reflected”.
We can also see the effect by directly typing the text into the URL, using + instead of a space: https://onofri.org/security/test.php?param=hello+there.
Let’s look at the source code:
<p id=echoed> hello there </p>If we can execute arbitrary JavaScript code (e.g., an alert appears), we have found XSS. Since we are looking for XSS, let’s first see whether we can insert arbitrary HTML code. Let’s try the b tag, which makes the text bold – <b>hello there</b>.
We can also write it directly into the URL (the browser can automatically substitute the space with a +): https://onofri.org/security/test.php?param=<b>hello+there</b>.
Let's look at the source code again:
<p id=echoed> <b>hello there</b> </p>Well, we are almost there! Let’s add some JavaScript code. To perform the classic XSS attack, we need to include the code alert(1) within the script tag - <script>alert(1)</script>. This will trigger a pop-up alert with the number 1.
We can also write it directly in the URL: https://onofri.org/security/test.php?param=<script>alert(1)</script>.
This time, things are not going the way we hoped. The answer says, Not Acceptable!. Let’s look at the code:
<head><title>Not Acceptable!</title></head><body><h1>Not Acceptable!</h1><p>An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.</p></body></html>Mod_Security replied to us. We can go and look up what it is. According to its official GitHub [7], it’s an opn source Web Application Firewall (WAF). So, we have a defense system that needs to be bypassed.
Is it possible? Impossible? Easy? Difficult? If it’s the first time we have encountered it, we can’t know, and also it depends on how it’s configured and the rules applied.
The important thing is to take heart and proceed. Of course, bypasses can require time.
Let’s think rationally. We can assume that the script tag triggers Mod_Security. We can try another vector with a different tag, one of our favorites – <img src=x onerror=alert(1)>. This vector retrieves a non-existing image, x, specifying it in the src attribute, and triggers an alert when the loading error is triggered via the onerror attribute.
We are cautious and see first whether it likes the img tag (in this case, the browser changed the space to %20 – the corresponding hexadecimal ASCII code): https://onofri.org/security/test.php?param=<img%20src=x>.
Let’s look at the code:
<p id=echoed> <img src=x> </p>It returns the image code, so it likes this. Let’s proceed with the full vector: https://onofri.org/security/test.php?param=<img%20src=x%20onerror=alert(1)> .
Unfortunately, it didn’t work. Mod_Security blocked us again:
<head><title>Not Acceptable!</title></head><body><h1>Not Acceptable!</h1><p>An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.</p></body></html>To exploit this, we need to be creative.
We can search the internet for the various known bypasses and randomly throw them at the server, or we can be more surgical and study how Mod_Security and the two rules work. The rules that are often applied are those of the OWASP coreruleset.
Reading the XSS-specific configuration file [8], we find that the img tag is filtered:
[…] h1|head|hr|html|i|iframe|ilayer|img|input|ins|isindex|kdb […]But the video tag, defined in HTML5, is missing.
So let’s try the modified vector – <video src=x onerror=alert(1)>: https://onofri.org/security/test.php?param=<video%20src=x%20onerror=alert(1)>
Figure 1.1 – An alert from XSS
We then notice an alert message in our browser. We exploited XSS. You can try it in your browser, assuming that this will be allowed after the book’s publication. But, in general, it’s just like a cat-and-mouse game:
<p id=echoed> <video src=x onerror=alert(1)> </p>Of course, it’s not the only bypass that exists. To find a different one with ease, just read the code, study which tags can trigger JavaScript in the various versions of HTML, and try.
We exploited XSS by executing arbitrary JavaScript code, which often suffices in a web application penetration test. If we want to go further, we can weaponize XSS to steal the cookies of the WordPress admin.
Imagine what happens next. Let’s suppose, through some clever social engineering, we send a link to an administrator and then hijack their session.
Once we gain access to the WordPress admin panel, we can check whether the feature that allows direct editing of plugins or uploading custom plugins via the web interface is enabled.
This allows us to execute arbitrary PHP code on the server, which enables us to perform various actions. For example, we could load a custom web shell or use an existing one, such as those available on GitHub [9].
Even though we can execute system commands directly on the server via PHP, we are likely operating as a limited user. Therefore, we can gather more information to identify configuration issues or check whether there’s any outdated software running as root.
Alternatively, if we’ve stayed stealthy enough, we can patiently wait for an exploit related to the specific version we’re using to surface and then switch to root access, a strategy we’ve used successfully many times before.
In this brief web application penetration test example, we’ve navigated through various process steps to plan and execute an attack on a web application, combining theory and practice. We’ve also applied various testing techniques by interacting with the application and reading the code. We’ve realized that we need a set of skills, the basics of which help us right away and the others learn as we encounter them. Finally, we’ve realized that we need a resilient mindset that doesn’t shy away from challenges, pushes us to dig deeper when necessary, and spurs us to use our creativity to find new solutions.
We will explore these aspects in the following sections.
Our example highlights that, initially, we interacted with the application. However, when the source code became available, we utilized it to gain an advantage compared to a more holistic approach. These techniques are also specified in Appendix C of NIST SP 800-115 [10], a technical guide with a similar process to PTES but enhanced with a more high-level vision.
When doing static analysis, we analyze the source code of the application. We must either have the source code or analyze the disassembled/decompiled code to do this.
The analysis is performed without executing the code, which remains static.
In this case, it is necessary to know the language in which the software is written, the peculiar bugs, and how to recognize them by reading.
In the case of web applications, codes usually are interpreted, so you need to know how to read server-side languages such as Python, PHP, Ruby, and C#. In other cases, you have bytecode, as with Java classes – for example, we usually try to disassemble or decompile it.
It is also helpful to know client-side programming/markup languages such as HTML, JavaScript (now used server-side), and CSS, which can be helpful in some complex attacks.
To use this approach, we must have many programming language skills or quickly recognize those we need to learn better.
Tausende von E-Books und Hörbücher
Ihre Zahl wächst ständig und Sie haben eine Fixpreisgarantie.
Sie haben über uns geschrieben: