Deep Analysis of Snake
Meet Snake keylogger
Snake, also known as the 404 Keylogger and Snake Keylogger, is a . NET-based info-stealing malware that was first discovered in late 2020, commonly spread via phishing scams, and remains a major threat in 2024.
The name ‘Snake’ comes from strings in its log files and code. Threat actors use the snake’s builder to select features and create new attacks. This means the capabilities of different versions can vary.
Snake has evolved from basic keystroke logging to include advanced data capture capabilities. Over time, it has improved its stealth and persistence techniques. Recent campaigns have increasingly targeted critical infrastructure and used legitimate services to mask malicious activities.
Technical in Points
-
Snake operates in multiple stages, where each stage decrypts and loads the next payload. This staged approach involves using.NET assemblies and dynamic analysis to reveal the core payload.
-
Host Profiling: Snake will gather information about the infected host; it collects the following information: the PC name, date and time, client IP address, country name, country code, region name, region code, city, time zone, latitude, and longitude, which are put in the header of the collected stolen information.
-
Snake makes use of timers to execute specific tasks at regular intervals, such as repeatedly capturing keystrokes, screenshots, and clipboard contents, as well as scheduling data exfiltration to remote command-and-control servers to avoid detection.
-
Snake steals sensitive data from applications installed on infected systems, including email clients and browsers, capturing credentials and other information. It also targets FTP clients such as FileZilla and communication apps like Discord.
-
Configuration Extraction: Snake comes with embedded configuration; in this variant, the configuration is Base64 encoded and encrypted using DES with a hard-coded key. These configurations contain the host, port, username, and password, which determine the set-up used for its server to exfiltrate the gathered information.
-
Snake sends stolen data to its server using various methods, including SMTP, FTP, and Telegram, in plain text or encrypted using the DES algorithm.
Sample Basic Information
The sample is identified as a PE32 executable (GUI) Mono/.Net assembly designed for the x86 architecture. It was created on July 25, 2082, at 14:24:59 UTC, and according to Virus Total, it first appeared in the wild on June 11, 2024, at 18:32:45 UTC.
Unpacking
Stage 1
Packed .NET samples usually hide a further-stage payload that is unpacked in memory at runtime and loaded as byte reflection without writing it to disk.
In Snake, when the main entry point is called, it creates a form (Form1). The form’s constructor then loads and creates a type from the decrypted payload.
The process starts with Activator.CreateInstance
, which dynamically creates an instance of a type during program execution.
The type is determined through DefaultJsonNameTable.Anterne
, which then starts loading the second stage assembly or module using AppDomain.CurrentDomain.Load
. This assembly/module is decrypted from an embedded resource (Resources.Example) using a simple XOR encryption method with the hard-coded key YPrALKXmrr.
To extract the binary after unpacking, we can do a dynamic analysis session by stepping through the code and breakpoint at the line where the module is loaded and saving it to disk; however, we could keep working with the dynamic session until we get our final payload.
Stage 2
By analyzing the interesting function BMfMTiULrwrQOTDiGxUMZ()
, we see that it uses reflection to load an assembly and invoke a method from it dynamically.
The encrypted data (Resources.AQipUvwTwkLZyiCs) is retrieved using a ResourceManager (Resources.ResourceManager) and decrypted using AES encryption with the ECB mode and a SHA-256 hashed key to get the assembly to load.
Then,the type (class) and method to be invoked are decrypted using the same technique.
The decryption method uses the AES encryption algorithm (RijndaelManaged
). It initializes with a predefined salt for key derivation and uses Rfc2898DeriveBytes to derive the encryption key and IV from a provided password.
After loading the assembly and getting the method, the malware runs it with specific parameters. These parameters are: a PE file fetched from ‘Resources.Scrivens’, decrypted using the previously mentioned AES decryption method, as the first parameter, and the file path of the application’s executable as the second parameter.
Stage 3
This DLL is more obfuscated than the previous stages, and it dynamically decrypts using a simple XOR and loads APIs.
By looking into the code, this stage uses process hollowing to inject the main Snake payload into a newly created child process and execute it to evade detection.
First, the file path passed as the first argument is used to start a new process in suspended mode and hollows out the memory using ZwUnmapViewOfSection()
and then allocates it again using VirtualAllocEx()
with RWX permissions.
Next, it writes the final stage executable that is passed as the first argument of the previous stage to the allocated memory region using two calls to WriteProcessMemory()
.
Finally, it’s making the necessary modifications; the thread context is updated using SetThreadContext
and the suspended thread is resumed with ResumeThread
, allowing the new process to run with the injected malicious code.
By dumping the data injected into the process, we can extract the final Snake payload and start examining the malware’s exact behavior.
Anti Analysis
Code Obfuscation
Snake’s final payload uses obfuscation tools like Deep Sea Obfuscator and Ben-Mhenni-Protector to make its code quite challenging to understand. The names of classes and functions are scrambled, making the code difficult to analyze.
To better understand the code, we can use the tool de4dot to de-obfuscate the payload file. This made the code easier to read, allowing us to analyze it more effectively.
Date check
Snake checks the current date it runs on to ensure that if a specified date has passed, then the executable will schedule its deletion to avoid detection or analysis.
Detect Analysis Environment
Snake uses specific IP addresses to check for monitoring or analysis. If these IPs are detected, the malware alters its behavior to avoid detection. If the environment is considered clean, the malware sends the collected data to its server.
Checking Processes
Snake loops through running processes on the system and compares their executable names against a list of processes that are generally associated with antivirus software, firewalls, network monitoring tools, and other security-related applications and malware analysis tools, and terminates any running processes whose names match any of those listed.
full processes list
Expand to see more
zlclient
egui
bdagent
wireshark
olydbg
anubisnpfmsg
avastui
_Avp32
vsmon
mbam
keyscrambler
_Avpcc
_Avpm
Ackwin32
Outpost
Anti-Trojan
ANTIVIR
Apvxdwin
ATRACK
Autodown
Avconsol
Ave32
Avgctrl
Avkserv
Avnt
Avp
Avp32
Avpcc
Avpdos32
Avpm
Avptc32
Avpupd
Avsched32
AVSYNMGR
Avwin95
Avwupd32
Blackd
Blackice
Cfiadmin
Cfiaudit
Cfinet
Cfinet32
Claw95
Claw95cf
Cleaner
Cleaner3
Defwatch
Dvp95
Dvp95_0
Ecengine
Esafe
Espwatch
F-Agnt95
Findviru
Fprot
F-Prot
F-Prot95
Fp-Win
Frw
F-Stopw
Iamapp
Iamserv
Ibmasn
Ibmavsp
Icload95
Icloadnt
Icmon
Icsupp95
Icsuppnt
Iface
Iomon98
Jedi
Lockdown2000
Lookout
Luall
MCAFEE
Moolive
Mpftray
N32scanw
NAVAPSVC
NAVAPW32
NAVLU32
Navnt
NAVRUNR
Navw32
Navwnt
NeoWatch
NISSERV
Nisum
Nmain
Normist
NORTON
Nupgrade
Nvc95
Outpost
Padmin
Pavcl
Pavsched
Pavw
PCCIOMON
PCCMAIN
Pccwin98
Pcfwallicon
Persfw
POP3TRAP
PVIEW95
Rav7
Rav7win
Rescue
Safeweb
Scan32
Scan95
Scanpm
Scrscan
Serv95
Smc
SMCSERVICE
Snort
Sphinx
Sweep95
SYMPROXYSVC
Tbscan
Tca
Tds2-98
Tds2-Nt
TermiNET
Vet95
Vettray
Vscan40
Vsecomr
Vshwin32
Vsstat
Webscanx
WEBTRAP
Wfindv32
Zonealarm
LOCKDOWN2000
RESCUE32
LUCOMSERVER
avgcc
avgamsvr
avgupsvc
avgw
avgcc32
avgserv
avgserv9
avgserv9schedapp
avgemc
ashwebsv
ashdisp
ashmaisv
ashserv
aswUpdSv
symwsc
norton
Norton Auto-Protect
norton_av
nortonav
ccsetmgr
ccevtmgr
avadmin
avcenter
avgnt
avguard
avnotify
avscan
guardgui
nod32krn
nod32kui
clamscan
clamTray
clamWin
freshclam
oladdin
sigtool
w9xpopen
Wclose
cmgrdian
alogserv
mcshield
vshwin32
avconsol
vsstat
avsynmgr
avcmd
avconfig
licmgr
sched
preupd
MsMpEng
MSASCui
Avira.Systray
Main Snake Functionality
Host Profiling
Snake builds a detailed profile of the infected system; it gathers important details from infected machines, starting with basic information like the machine’s name and current date/time. Also, it retrieves sensitive geolocation data such as the machine’s public IP address, country name/code, region name/code, city name, time zone, and precise latitude and longitude coordinates.
KeyLogging
Snake performs keylogging and employs a timer to periodically send this data to its server.
In programming, timers run a specific piece of code at regular intervals. In .NET, the System.Windows.Forms.Timer
class is often used in Windows Forms applications to trigger events at set intervals.
Timers allow asynchronous execution, enabling actions to happen independently of the main program’s flow.
Snake’s keylogger runs continuously in the background by using the SetWindowsHookExA
API to set up a Windows hook _hook)
. This hook monitors keyboard events and integrates itself into the keyboard hook chain. The hook is associated with the callback method _hookCallback
, which handles keyboard events. Whenever a key is pressed, this callback function is triggered. It records the keystroke and then forwards the call to the next hook in the chain.
It also regularly monitors and logs the title of the active window in the foreground using APIs like GetForegroundWindow()
and GetWindowText()
. By recording the active window’s title alongside keystrokes, the keylogger gains valuable context about where and when the keystrokes occur. This is important for improving the information captured by the keylogger and helping the attacker understand what apps or windows are in use when the user types.
Screenshot
Snake periodically captures screenshots of the user’s screen, which may capture sensitive information such as documents or login credentials, saving them initially as “Screenshot.jpg” in a folder “SnakeKeylogger” within the user’s Documents directory. The captured images are stored until they are sent to the attacker before they are deleted from the system. This process is triggered by a timer set to run every 100 milliseconds.
Clipboard
Snake uses a timer to capture and process clipboard contents. It retrieves text from the clipboard using Class2.Class1_0.Clipboard. GetText()
checks if the text is already stored in a global variable before adding it, to ensure that each unique clipboard entry is logged only once. Periodically, another timer sends the collected clipboard data to its server. This capability allows Snake to capture sensitive information, such as passwords or credit card numbers, that users have copied.
Steal Email Clients credentials
Snake retrieves Outlook email credentials from Microsoft Outlook profiles stored in the Windows Registry and gets values associated with various email protocols such as IMAP, POP3, HTTP, and SMTP. If these values are found, it decrypts the passwords using a helper method and retrieves the associated email addresses and email information.
With a similar method, Snake targets Foxmail to extract stored credentials by retrieving the Foxmail installation path from the registry and constructing the path to the storage directory where account information is stored. It loops through the directories within Storage, looking for Account.rec0
files that contain account credentials (e-mail and password).
Path | Description |
---|---|
SOFTWARE\Microsoft\Office\15.0\Outlook\Profiles\Outlook\9375CFF0413111d3B88A00104B2A6676 |
Outlook profile registry (Office 15.0) |
SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook\9375CFF0413111d3B88A00104B2A6676 |
Outlook profile registry (Windows NT) |
SOFTWARE\Microsoft\Windows Messaging Subsystem\Profiles\9375CFF0413111d3B88A00104B2A6676 |
Messaging profiles (Windows) |
SOFTWARE\Microsoft\Office\16.0\Outlook\Profiles\Outlook\9375CFF0413111d3B88A00104B2A6676 |
Outlook profile registry (Office ) |
SOFTWARE\Classes\Foxmail.url.mailto\Shell\open\command |
Foxmail registry |
\\Accounts\\Account.rec0 |
Account data file path |
The extracted information is then formatted and appended to the stolen info global variable to be sent to the attacker.
Steal Browsers Credentials
Browsers store saved login credentials in encrypted files. Snake has a predefined list of common browsers and checks for their existence on the system. It can access these storage locations to extract these credentials and send them to the attacker.
Chromium-based browsers
Chromium-based browsers, such as Chrome, use SQLite databases to store saved login credentials in a file called ‘Login Data’ in the user’s profile directory.
Snake scans the system for browser profiles and accesses the SQLite databases used by these browsers, then parses the ‘logins’ table within the SQLite database, iterating through each row to retrieve the website URL (origin_url), the username (username_value), and the encrypted password (password_value). Depending on the encryption version, it tries to decrypt passwords. Both the username and decrypted password are formatted into a string and appended to the stolen info global variable to be sent to the attacker.
The full list of browsers :
Expand to see more
Google Chrome
Chrome Canary
BraveSoftware (Brave-Browser)
360Browser
Chromium
KinzaFalkon
CoolNovo
QIPSurf
BlackHawk
7Star
Citrio
Coowon
CocCoc
Uran
Orbitum
Slimjet
Iridium
Vivaldi
Iron
Ghost
Cent
Xvast
Chedot
SuperBird
Opera
360Secure
Comodo
Torch
UCBrowser
Blisk
EpicPrivacyBrowser
Yandex
Nichrome
Amigo
Kometa
Xpom
Elements
SalamWeb
Sputnik (browser/extension)
Liebao7 (Liebao Browser)
AVASTSoftware (Avast Browser)
Gecko-based browsers
Gecko-based browsers use JSON files to store saved login credentials in ‘logins.json’.
Snake scans directories to find profiles of Gecko-based browsers, such as Firefox. Then, it accesses the logins.json file within each profile directory, which stores encrypted login credentials, including usernames and passwords.
It decrypts these credentials using cryptographic libraries (mozglue.dll and nss3.dll), which are dynamically loaded from the installation directories of Mozilla Firefox and related browsers. Once loaded, these libraries enable Snake to initialize the NSS (Network Security Services) library, creating the necessary cryptographic contexts that decrypt and extract usernames and passwords.
The decrypted information is formatted into strings and appended to the stolen info global variable to be sent to the attacker.
The full list of Gecko-based browsers is :
- Mozilla Firefox
- SeaMonkey
- IceDragon
- Cyberfox
- Pale Moon
- Waterfox
- icecat
Steal FTP clients credentials
The FileZilla software program is a free-to-use (open source) FTP utility, allowing a user to transfer files from a local computer to a remote computer.
FileZilla is targeted by Snake to get the saved configurations of previously accessed servers.By parsing the recentservers.xml
file located in the user’s AppData directory, it tries to retrieve stored server details such as hostnames, usernames, encrypted passwords, and ports. It uses XML parsing techniques to extract these elements and decrypt the Base64-encoded password.
Obtain discord tokens
Discord uses a token-based authentication system. Each user session is identified by a token that is stored locally. By accessing the leveldb files, Snake can extract these tokens and use them to mimic the user, gaining access to their account without needing their password. This can lead to unauthorized access to personal messages, servers, and other sensitive information.
The code checks if the leveldb
directory exists. If found, it iterates through its files to locate .ldb
files containing the substring “oken” (part of “token”). It then extracts the token by splitting the text around the “oken” substring and reassembling the parts to separate the token. Finally, it logs the result to be sent to the attacker.
Stealing Wi-Fi Credentials:
Snake extracts Wi-Fi profile information and passwords using netsh
commands. It starts by fetching a list of Wi-Fi profiles on the system.
Then it parses each profile to retrieve its name and clear-text password. This information is logged and sent to the attacker.
By gathering Wi-Fi credentials, Snake can secretly connect to networks, monitor traffic for sensitive data, and get access to activities like botnet operations or data theft.
Snake’s data exfiltration Functionality
Configuration Extraction
Snake contains an embedded DES-encrypted configuration within its binary.
Snake malware uses embedded DES in ECB mode encryption with a hard-coded key. It first decodes the data using Base64 encoding. For decryption, it hashes the key using MD5 and uses only the first 8 bytes of the hashed key as the final key to decrypt the data.
We can use CyberChef to simulate the decryption process statically. First, the key will be MD5 hashed = {6fc98cd68a1aab8b24c517549e658115}, and the first 8 bytes are used to decrypt the data.
These configurations determine the setup used by the sample for its server.
- the host set to ‘valleycountysar[.]org’ .
- port:’26’.
- username : ‘rightlut@valleycountysar[.]org’ .
- password ‘fY,FLoadtsiF’ .
Data Exfiltration
Malware needs to connect to servers to exfiltrate stolen data.
Snake can transmit gathered information in plaintext or DES-encrypted format to its server through several communication methods, including SMTP, FTP, or even sending it to a specific Telegram bot.
SMTP
Snake uses SMTP (Simple Mail Transfer Protocol) in two different approaches for data exfiltration.
The first approach creates an email (a mail message) with the following configurations: sender, recipient, subject (including PC name and a tracking identifier), and a body containing stolen information. This email is sent using an SmtpClient configuration: host, port, and authentication credentials (username and password).
The second approach is to create an email (MailMessage2) with similar sender and recipient details. But instead of adding data directly, it attaches files containing stolen information. This method also uses an SmtpClient2 configured similarly to the first way.
FTP
The FTP request is configured with credentials (user name and password) to authenticate access to the FTP server and a dynamic method to create an FtpWebRequest
. It builds a filename by combining the machine name with a random string and adding a.txt extension that helps uniquely identify the data.
Telegram
Snake uses Telegram’s bot API as a C2 channel by creating and communicating with a bot hosted on Telegram servers. It starts by creating a message containing stolen information, which is URL-encoded, and sends via HTTPS POST requests to a remote endpoint (Class6.string_1 + "/_send_.php?L"
) where the encoded message is directed for transmission.
Persistence
Snake adds a startup entry to the Windows Registry, ensuring that the malware runs automatically on the system boot.
Conclusion
Analyzing Snake revealed its true purpose as a sophisticated keylogger and data stealer that targets sensitive data from various applications like browers, email clients, FTP clients, and messaging apps, demonstrating its broad data theft capabilities.
YARA Rule
rule detect_unpacked_snake
{
meta:
description = "A rule for detecting unpacked snake samples"
author = "Mohamed Ezzat (@ZW01f)"
hash1 = "e81ff60c955d9f232d4812a68ef4335f204be923d6aa75c5d309e8fe76eed1ed"
hash2 = "fc20db86eea0db054491e5739e93153c5548ed933e0df6a139582e0b8569e737"
hash3 = "461bcd6658a32970b9bd12d978229b8d3c8c1f4bdf00688db287b2b7ce6c880e"
strings:
$mz = {4D 5A} //PE File
$s0 = "YFGGCVyufgtwfyuTGFWTVFAUYVF" ascii wide
$s1 = "Snake Keylogger Stub New" ascii wide
$s2 = "\\SnakeKeylogger" wide
$s3 = "Open Network" ascii wide
$s4 = "- Clipboard Logs ID -" ascii wide
$s5 = "| Snake Tracker" wide
$s6 = "/C choice /C Y /N /D Y /T 3 & Del \"" ascii wide
$s7 = "wlan show profile" ascii wide
$p1 = {1D 8D ?? 00 00 01 25 16 72 ?? ?? 00 70 A2 25 17 09 A2 25 18 72 ?? ?? 00 70 A2 25 19 11 04 A2 25 1A 72 ?? ?? 00 70 A2 25 1B 11 05 A2 25 1C 72 ?? ?? 00 70 A2 28 ?? 00 00 0A 13 0D} // pattern used in sending info
condition:
($mz at 0) and (all of ($p*)) and (5 of ($s*)) and filesize < 500KB
}
IoCs
Stage | Hash |
---|---|
Stage 1 | faebc09f47203bbe599ac368f12622f38255e957d1435e6763c80bf2ebd988bf |
Stage 2 | 8a520450581de3e9987f53c54723fdf9d4af32571769c49af7c18d985ef52fb0 |
Stage 3 | 45c7b64a55dca23ee1239649e03a7c361813dbcfc2a0817b0d8e94c907d6ed4b |
Main payload | 68df92cd19e5587a799a54bc21ddd95a27223faf972c6a914c818c99d3332a84 |
URL | hxxp://103[.]130[.]147[.]85 |
URL | valleycountysar[.]org |
Email / UserName | rightlut@valleycountysar[.]org |
Password | fY,FLoadtsiF |