Как обнаружить модульный стример rat csharp

  • HiSolutions successfully identified distinctive patterns within the CSHARP-STREAMER malware, aiding in the identification of specific malware samples.
  • We confirmed the modular structure of CSHARP-STREAMER. This customization could be driven by their business model, which might involve payment for specific features, or as a strategy to minimize the chances of detection and analysis.
  • The usage of the RAT has massively increased in Q3 2023.
  • HiSolutions is able to share extra detection rules to support the detection of components of the deployment kit.

Prevalence and Initial Analysis

We can confirm the usage of the RAT’s TCP relay functionality. Using this feature, the threat actors were able to move from one network to another more carefully protected network.

Как обнаружить модульный стример rat csharp

The usage of the TCP function leaves some traces, providing opportunities for forensic investigation: This leads to visible traces in Windows Eventlogs in the form of EventID 2004 and the creation of a distinct firewall rule by "C:\\Windows\System32\netsh.exe": "Inbound TCP Port 6667". This behaviour (creation of firewall rule via netsh) is already covered by a publicly available SIGMA-rule, written by Michel de Crevoisier. The threat actors used the feature not on a large scale, but only in situations, where they had to close a gap between different parts of the affected organizations network.

  • ADUtils
  • ExecuteAssembly
  • Filetree
  • HttpServer
  • Keylogger
  • LineParser
  • PsExec
  • Relay
  • RunAs
  • Sendfile
  • Sget
  • SmbLogin
  • Wget
  • Spawn

Evolution of Malware

The analysis of samples shows that there are two main different configurations of CSHARP-STREAMER used in the wild, one with the MegaUpload-Client and one without. While we couldn’t identify samples from the year 2022, we are confident that CSHARP-STREAMER was also in active use during this timeperiod.

Как обнаружить модульный стример rat csharp

The observed uptick of the RATs usage in August 2023 also marks the beginning of Metaencryptor‘s publishing of victims (12 in August, 1 in September, 2 in November, 1 in December) and LostTrusts trove of 53 victims in August.


Detection and Response

Thus, we can provide a Yara-Rule, helping with the identification of known samples. Please note, that in cases known to us, the sample was loaded only in memory, not on disk.

Additionally detection mechanisms involve:

  • PowershellScriptBlock-Logging
  • The creation of firewall-rules by netsh.exe
  • Multiple static strings which can be found in memory
  • The use of CSHARP-STREAMER‘s user agent „websocket-sharp/1.0
  • Specific Web-Requests (see headers below)

Yara Rule

rule CSHARP_STREAMER {
   meta:
      description = "Detects decrypted csharp_streamer"
      author = "HiSolutions AG"
      reference = "https://malpedia.caad.fkie.fraunhofer.de/details/win.csharpstreamer"
      sharing = "TLP:CLEAR"
      date = "2023-12-18"
      score = 100
   strings:
              $y1 = "csharp_streamer.Properties"
              $y2 = "csharp_streamer.Utils"
              $y3 = "csharp_streamer.ms17_10"
              $y4 = "csharp-streamer"
              $z1 = "iphlpapi.dll" ascii wide
              $z2 = "\\<title\\b[^>]*\\>\\s*(?<Title>[\\s\\S]*?)\\</title\\>" ascii wide
              $z3 = "MagicConstants.kSessionTerminate = ByteString.CopyFrom" ascii wide
              $z4 = "StartRalay"
              $d1 = "csharp-streamer.pdb"
   condition:
              uint16(0) == 0x5a4d and (3 of ($y*) or all of ($z*) or $d1)
}

SIGMA Rule

title: Potential csharp_streamer Powershell-Loader
id: 77bdea07-634c-49ad-96d3-03736882b914
status: test
description: Detects Powershell-Loader as seen with csharp_streamer.
references:
    - none
author: HiSolutions AG
date: 2023/12/18
tags:
    - tlp.white
    - attack.t1562.001
    - attack.t1059.001
logsource:
    product: windows
    category: ps_script
    definition: 'Requirements: Script Block Logging must be enabled'
detection:
    ps_script:
        EventID: 4104
        Channel:
            - Microsoft-Windows-PowerShell/Operational
            - PowerShellCore/Operational
    selection:
        ScriptBlockText|contains:
            - '[WinApi]::VirtualProtect($funcAddr, [uint32]$patch.Length, 0x40, [ref] $out)'
            - '$wc = New-Object System.Net.WebClient; $wc.Proxy = [System.Net.GlobalProxySelection]::GetEmptyWebProxy();'
            - '$string = xor "$rawData" "decrypt" "'
            - 'if($metInfo.GetParameters().Length -eq 0) # If Assembly - VB, update params'
            - '-UseBasicParsing -UserAgent "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)" ).Content'
            - '$amsiDll = [WinApi]::LoadLibrary("ams"+"i.dll")'
            - '$funcAddr = [WinApi]::GetProcAddress($amsiDll, "Ams"+"iScanB"+"uffer")'
    condition: ps_script and selection
falsepositives:
    - Unknown
level: high
ruletype: Sigma

Malware related MITRE ATT&CK Techniques

IDTechniqueUsage
T1016System Network Configuration DiscoveryThe malware enumerates the network configuration of infected hosts.
T1018Remote System DiscoveryThe malware queries LDAP to discover additional systems.
T1021.002Remote Services: SMB/Windows Admin SharesThe malware uses an PsExec-implementation to support lateral movement.
T1046Network Service DiscoveryThe malware implements port-scanning-capabilities and contains descriptions for multiple ports.
T1056.001Input Capture: KeyloggingThe malware offers keylogging functionality
T1083File and Directory DiscoveryThe malware can create filetrees on infected systems. It also contains an extensivedictionary of strings to classify found files (e.g. network architecture, finance, passwords).
T1090.001Proxy: Internal ProxyThe malware has dedicated port-relaying capabilities
T1095Non-Application Layer ProtocolThe malware supports C2-communication via ICMP.
T1110.001Brute Force: Password GuessingThe malware has an integrated function that supports bruteforcing credentials for smb-access.
T1113Screen CaptureThe malware can capture screenshots.
T1134.001Access Token Manipulation: Token Impersonation/TheftThe malware supports token impersonation.
T1134.002Access Token Manipulation: Create Process with TokenThe malware offers the ability to launch processes in different contexts.
T1562.001Impair Defenses: Disable or Modify ToolsThe malware patches the in-memory amsi.dll before executiong PowerShell-Commands
T1567Exfiltration Over Web ServiceThe malware allows data exfiltration via https.
T1567.002Exfiltration Over Web Service: Exfiltration to Cloud StorageThe malware allows direct file exfiltration to Mega.io.
T1620Reflective Code LoadingThe malware allows to execute Code from URLs, remote and local files directly in memory.
TTP related to CSHARP-Streamer Malware

Threat Actor (TA) related MITRE ATT&CK Techniques

IDTechniqueUsage
T1018Remote System DiscoveryThe TA queries the AD-Environment for computers via a Powershell-Script using “adsisearcher[1].
T1021.002Remote Service (SMB/Windows Admin Shares)The TA uses „PSExec[2] to execute commands on remote systems via a Powershell-Script.
T1033System Owner / User DiscoveryThe TA queries the AD-Environment and uses LDAP for User-Discovery via a Powershell-Script using „adsisearcher“.
T1046Network Service DiscoveryThe TA queries the AD-Environment for SPNs via a Powershell-Script.
T1082System Information DiscoveryThe TA queries the AD-Environment for the operating system and system version via a Powershell-Script.
T1083File and Directory DiscoveryThe TA lists files in multiple directories and searches actively for KeePass-Configuration-Files.
T1087.001Account Discovery (Local)The TA uses “net user” to enumerate local users on each computer via a Powershell-Script.
T1087.002Account Discovery (Domain)The TA uses “net user” and “adsisearcher” to enumerate domain users on each computer via a Powershell-Script.
T1087.003Account Discovery (Mail)The TA uses “adsisearcher” to enumerate mail users on each computer via a Powershell-Script.
T1217Browser Information DiscoveryThe TA uses NirSoft’s “Browser History View”[3] to view the History of Internet Explorer, Firefox, Chrome and Safari via a Powershell-Script.
T1482Domain Trust DiscoveryThe TA queries the AD-Environment for all trust-relationships via a Powershell-Script.
T1485Data DestructionThe TA uses “format” to format secondary partitions via „PSExec“.
T1486Data Encrypt for ImpactThe TA encrypts virtual machines on the hypervisor-level. Local files are encrypted through the use of ransomware deployed via „PSExec“.
T1497.001Virtualization/Sandbox Evasion (Systemchecks)The TA checks the host environment via the bios serialnumber and manufacturer of the computer via a Powershell-Script.
T1518Software DiscoveryThe TA lists all .lnk files in the Windows\Start Menu Folder and analyzes the Windows\Prefetch Folder for executed and installed Applications via a Powershell-Script.
T1558.003Steal or Forge Kerberos-Tickets (Kerberoasting)The TA uses „PowerView“[4] from the „PowerSploit“-Framework to aquire Tickets and converts them for later usage via a Powershell-Script.
T1569.002System Services (Service Execution)The TA uses „PSExec“ to execute commands on remote systems via a Powershell-Script.
T1614System Location DiscoveryThe TA queries the AD-Environment for department and physical delivery location of computers via a Powershell-Script.
T1619Cloud Storage Object DiscoveryThe TA lists all Files in the main folderpath of „OneDrive“ and „Dropbox“ and their first subdirectory-level via a Powershell-Script.
TTP related to MetaEncryptor threat actor using CSHARP-Streamer

Understanding PowerShell

Before we delve into the ways in which hackers leverage PowerShell, let’s first gain a basic understanding of what It is and how it has evolved over time. PowerShell is a command-line shell and scripting language built on Microsoft’s .NET framework. It was first introduced in 2006 and has undergone several significant updates and advancements.

:/>  Получить данные о настройке операционной системы и установке программного обеспечения, используя функциональность базовой платы wmi win32

What is PowerShell?

The Evolution of PowerShell

Over the years, PowerShell has evolved from a simple command-line shell to a full-fledged scripting language. Microsoft has introduced new features and enhancements with each new version, making PowerShell even more powerful and flexible.

The Attraction of PowerShell for Hackers

There are several reasons why hackers are increasingly turning to PowerShell as their weapon of choice:

The Versatility of PowerShell

PowerShell’s versatility is one of the main reasons it has become a favorite tool for hackers. Its rich set of cmdlets (commandlets) and its ability to interact with other Windows components and APIs make it suitable for various malicious activities.

With its extensive capabilities, PowerShell provides hackers with a powerful toolkit to carry out their nefarious activities. Whether reconnaissance, exploitation, or maintaining control over compromised systems, PowerShell offers a wide range of options to achieve their malicious objectives.

PowerShell’s Accessibility and Ubiquity

Another factor contributing to PowerShell’s popularity among hackers is its accessibility and ubiquity. PowerShell has been an integral part of Windows operating systems since Windows 7, making it readily available on most Windows-based systems.

This widespread adoption makes it easier for hackers to leverage PowerShell for their malicious activities, as they can assume that their targets will have PowerShell installed by default.

PowerShell’s integration with the Windows ecosystem allows hackers to seamlessly blend their activities with legitimate system processes, making it harder for security measures to detect and mitigate their actions. By exploiting PowerShell’s trusted status within the operating system, hackers can evade detection and maintain persistence within compromised networks.

PowerShell’s ubiquity extends beyond Windows systems. With the introduction of PowerShell Core, a cross-platform version of PowerShell, hackers can now target Windows, Linux, and macOS systems, broadening their reach and potential impact.

Common PowerShell Exploits in Cyber Attacks

Now that we understand why hackers are drawn to PowerShell, let’s take a closer look at some of the common ways in which they exploit this powerful tool:

Section Image

Scripting Attacks with PowerShell

By leveraging PowerShell’s flexibility and capabilities, hackers can create sophisticated scripts that bypass traditional security measures and remain undetected by antivirus software. These scripts can be designed to evade detection using obfuscation techniques, making it even more challenging for security professionals to identify and mitigate the threat.

Remote Access Trojans (RATs) and PowerShell

The combination of PowerShell and Remote Access Trojans (RATs) has become a potent weapon for hackers. RATs are malicious programs that provide attackers remote access and control over a compromised system. By leveraging PowerShell, hackers can execute RATs stealthily and remotely, allowing them to maintain persistent access to the compromised system.

Let’s consider a scenario where an attacker gains access to a corporate network through a phishing attack. Once inside, they can use PowerShell to deploy a RAT that establishes a backdoor, granting them unrestricted access to the network. From there, the attacker can move laterally, escalate privileges, and exfiltrate sensitive data without arousing suspicion.

For example, the notorious banking Trojan, TrickBot, has been known to use PowerShell to download additional payloads and establish command-and-control channels with its operators. This combination of PowerShell and RATs enables attackers to operate discreetly, making it difficult for security teams to detect and respond to the threat in a timely manner.

As cybercriminals evolve tactics, organizations must stay vigilant and implement robust security measures to protect against PowerShell exploits. Regular security awareness training, strong access controls, and up-to-date threat intelligence can help organizations defend against these sophisticated attacks.

Detecting and Preventing PowerShell Attacks

As PowerShell continues to be exploited by hackers, it is crucial for organizations to implement effective measures to detect and prevent these attacks. Here are some strategies that can help:

Signs of a PowerShell Attack

Identifying the signs of a PowerShell attack is the first step in detecting and mitigating the damage caused by such an attack. Some common indicators include unusual PowerShell process activity, suspicious PowerShell scripts or commands being executed, and the presence of unauthorized PowerShell modules or plugins.

Best Practices for Preventing PowerShell Exploits

Restrict PowerShell execution to authorized users and systems.

Implement strong access controls and regularly review permissions.

Strong access controls are essential to prevent unauthorized access to PowerShell. Regularly reviewing permissions ensures that only the necessary individuals have access, reducing the chances of a malicious actor gaining control over PowerShell and using it as a tool for their nefarious activities.

Keep PowerShell and other software up-to-date with the latest security patches.

Regularly updating PowerShell and other software with the latest security patches is crucial in preventing exploitation. Hackers often take advantage of known vulnerabilities in outdated software, so staying up-to-date with patches ensures these vulnerabilities are addressed and closed off, making it harder for attackers to gain a foothold.

Enable PowerShell logging and monitoring to detect suspicious activities.

Enabling PowerShell logging and monitoring allows organizations to monitor PowerShell activities closely and detect suspicious behavior. Organizations can quickly identify potential attacks and take appropriate action to mitigate the damage by analyzing logs and monitoring for unusual patterns or commands.

:/>  Нет дежурного питания на блоке питания компьютера

Regularly conduct security awareness training to educate employees about the risks of PowerShell attacks.

Employee education and awareness play a crucial role in preventing PowerShell attacks. Regular security awareness training sessions can help employees understand the risks associated with PowerShell and teach them how to identify and report suspicious activities. By empowering employees with knowledge, organizations can create a strong human firewall against potential attacks.

The Future of PowerShell and Cybersecurity

As the battle between hackers and cybersecurity professionals continues to escalate, the future of PowerShell and its role in cyber attacks remains uncertain. However, there are ongoing efforts to enhance the security of PowerShell and mitigate its exploitation by malicious actors.

Advancements in PowerShell Security

Constrained Language Mode is a powerful security feature that restricts the functionality of PowerShell to prevent the execution of potentially dangerous commands. By enforcing strict language constraints, attackers find it much more difficult to leverage PowerShell for malicious purposes. This feature has proven effective in reducing the attack surface and minimizing the impact of PowerShell-based cyber attacks.

The Ongoing Battle Against PowerShell Exploits

While advancements in PowerShell security are promising, it’s important to acknowledge that hackers constantly evolve their techniques to bypass security measures. Organizations must stay vigilant and continuously update their defenses to counter emerging PowerShell exploits and other evolving threats.

Real-world examples, such as the highly publicized NotPetya ransomware attack in 2017, underscore the need for robust security measures and proactive threat detection. NotPetya, which exploited vulnerabilities in PowerShell, caused widespread disruption and financial losses. This incident served as a wake-up call for organizations worldwide, highlighting the urgent need to strengthen their defenses against PowerShell-based attacks.

Conclusion

As the cybersecurity landscape continues to evolve, it is clear that PowerShell will remain a significant tool in the arsenal of both attackers and defenders. The future of PowerShell and its role in cyber attacks will depend on the collective efforts of cybersecurity professionals, developers, and organizations to stay ahead of emerging threats. Continued collaboration and knowledge sharing will be crucial in shaping the future of PowerShell and ensuring a safer computing environment for all.

21 сентября Центр кибербезопасности F.A.C.C.T. зафиксировал кибератаку c использованием фейкового сайта компании КриптоПро, разработчика средств криптографической защиты. Угроза была нейтрализована решением F.A.C.C.T. Managed XDR.

Злоумышленники поместили на фишинговом ресурсе ссылку на архив с трояном DarkWatchman под видом криптографической утилиты для создания электронной подписи. Сам вредоносный сайт они активно продвигали в поисковиках, чтобы он был на верхних строках выдачи. При этом доменное имя фишинговой страницы никак не напоминало официальный сайт компании КриптоПро.

DarkWatchman RAT — это троян удаленного доступа, написанный на JavaScript. Используется для скрытого удаленного доступа к зараженному компьютеру, на котором троян может выполнять различные команды: загрузку других вредоносных программ, шпионаж и дальнейшее распространение по сети. DarkWatchman был замечен в кампаниях финансово мотивированной группы Hive0117, активной в феврале 2022 года. Троян использовался в качестве разведывательного инструмента на первоначальной стадии атаки.

Последнее время троян DarkWatchman часто фигурирует в различных инцидентах.  В июле мы уже писали, как RAT распространялся через рассылку.

Хронология обнаружения атаки

В процессе мониторинга кибератак специалисты Центра кибербезопасности F.A.C.C.T. с помощью системы Managed XDR обнаружили и своевременно остановили инцидент у одного из клиентов компании, связанный с загрузкой вредоносного файла на рабочее устройство. Модулем динамического анализа MDP вредоносная программа была атрибутирована к семейству DarkWatchman.

Инцидент обнаружен и своевременно остановлен

Рис. 1 Инцидент обнаружен и своевременно остановлен

На компьютер пользователя была предпринята попытка загрузить архив CSP.rar. Архив содержал два файла, readme.txt с описанием легитимной программы КриптоПро CSP, а также исполняемый файл CSPSetup.exe, являющийся бэкдором DarkWatchman.

Как обнаружить модульный стример rat csharp

Рис 2. Содержимое архива CSP.rar

Отчет об инциденте Darkwatchman

Рис.3 Отчет об инциденте

Детали инцидента darkwatchman

Рис 4. Детали инцидента

Индикаторы позволили убедиться в безошибочности вынесенного вердикта, а также дали возможность отследить все действия и изменения, произведенные пойманным экземпляром вредоноса.

Аналитики Центра кибербезопасности F.A.C.C.T. установили источник загрузки — фишинговый сайт, мимикрирующий под компанию КриптоПро, разработчика средств криптографической защиты.

Фишинговый сайт криптопро

Рис.5 Фишинговый сайт

  • На самом сайте располагалась кнопка для загрузки и пароль от архива.
  • Кнопка вела на ссылку, созданную с помощью сервиса сокращателя u[.]to.
  • Загрузка архива происходила с сервиса Discord.
  • Пароль от архива был указан на сайте приманке.

Хотя инструмент активно применялся финансово мотивированной группой киберпреступников, само вредоносное ПО DarkWatchman обладает функционалом трояна удаленного доступа (RAT) и используется в первую очередь для шпионажа, позволяя атакующим получать скрытый контроль над скомпрометированной системой и похищать конфиденциальные данные.

Решение КриптоПро CSP широко используется для криптографической защиты информации в различных организациях.

Поскольку без средств криптографической защиты нельзя использовать электронную цифровую подпись, софт на основе СКЗИ (криптографических технологий) востребован практически у всех ведущих частных компаний и госорганизаций. Атакующие, вероятно, пытались скомпрометировать компьютеры тех сотрудников, которые искали утилиту для сдачи налоговой отчётности и работы с ДБО — дистанционное банковское обслуживание.

SEO — злоупотребление

Во время исследования фишинговый сайт был первым в списке выдачи поисковой системы.

Фейковый сайт в поисковой выдаче

Рис.6 Фейковый сайт в поисковой выдаче

Примечательно, что злоумышленники не использовали покупку контекстной рекламы для размещения своего сайта в топе выдачи. Использование сервиса от поисковика при создании сайта позволило атакующим эффективно применить классическое seo-продвижение, тем самым занять верхнюю позицию по целевому поисковому запросу.

Техника размещения вредоносного сайта в топе поисковой выдачи SEO poisoning — является довольно популярной и эффективной, когда речь идет о широком охвате целевой аудитории. Часто применяется в традиционных финансовых фишинговых веб-атаках, а также в распространении ВПО.

Сайт был заблокирован командой CERT-F.A.C.C.T.. Тем не менее, опасность сохраняется, так как злоумышленники могут активировать копии вредоносного ресурса.

Технические детали

RarSFX

Защищенный паролем архив CSP.rar (пароль: 123) содержит файлы: CSPSetup.exe (самораспаковывающийся архив RarSFX), readme.txt (текстовый файл, содержащий информацию о дистрибутиве «КриптоПро CSP»).

RarSFX файл CSPSetup.exe содержит: DarkWatchman (обфусцированный JS файл 41779253.js), C# кейлоггер в закодированном виде (файл 108788037) и множество мусорных файлов. Пример содержимого RarSFX файла:

Содержимое самораспаковывающегося архива CSPSetup.exe.

Рис.7 Содержимое самораспаковывающегося архива CSPSetup.exe

RarSFX файл CSPSetup.exe содержит в комментариях следующую команду:

Silent=2
Overwrite=1
Path=%TMP%
Setup=wscript.exe 41779253.js 40 "%sfxname%"

При выполнении процесса wscript.exe отображается диалоговое окно с текстом «Unexpected end of file.» Чтобы DarkWatchman продолжил работу, пользователю необходимо нажать «OK».

Диалоговое окно Windows.

Рис.8 Диалоговое окно Windows

DarkWatchman

DarkWatchman представляет собой троян удаленного доступа (RAT). DarkWatchman написан на JavaScript и распространяется в паре с простым C# кейлоггером.

Функциональные возможности DarkWatchman:

Команды с C2 сервера передаются в виде HTTP статус-кода. Список команд DarkWatchman:

:/>  Не запускаются приложения Windows 10: ничего не происходит при открытии, как исправить
Код командыОписание команды
820Загрузка и выполнение EXE-файла, используя WMI
821Загрузка DLL и вызов функции, указанной в аргументе команды
822Выполнение команды в интерпретаторе командной строки cmd.exe
823Загрузка и выполнение команд WMI
824Загрузка и выполнение JS кода через порождение wscript.exe
825Загрузка и выполнение JS через вызов функции eval() (без порождения нового процесса)
826Загрузка и выполнение Powershell скрипта
827Завершение работы кейлоггера и DarkWatchman
828Деинсталляция с зараженного хоста
829Выгрузка файла на C2
830Установка таймаута запросов к С2
831Установка нового С2 URL
832Загрузка и запуск обновленного DarkWatchman
833Загрузка и обновление кейлоггера
834Установка DarkWatchman в автозагрузку
835Загрузка и выполнение EXE-файла

Кейлоггер

DarkWatchman считывает содержимое файла 108788037, затем декодирует и расшифровывает содержимое с помощью операции XOR.

 Фрагмент кода DarkWatchman: чтение и расшифровка содержимого

Рис. 9 Фрагмент кода DarkWatchman: чтение и расшифровка содержимого файла 108788037

Фрагмент кода DarkWatchman: алгоритм XOR

Рис.10 Фрагмент кода DarkWatchman: алгоритм XOR

Расположение кейлоггера в реестре ОС

Рис. 11 Расположение кейлоггера в реестре ОС

Фрагмент декомпилированного кода кейлоггера

Рис. 12 Фрагмент декомпилированного кода кейлоггера

Выводы

Как мы ранее писали RAT (Remote Access Trojan) сегодня один из самых активно распространяемых киберпреступниками типов вредоносного ПО. Это связано с относительной простотой разработки, обеспечивающей большое количество предложений на рынке, а также широкими возможностями для использования вредоноса. В этом году киберпреступники довольно активно распространяют DarkWatchman RAT – этот троян рассылали по российским компаниям под видом зашифрованного архива с итогами фейкового тендера от Минобороны или лже-повесток от военных комиссариатов. В случае, который мы описали в блоге, они использовали фишинговый сайт, который копировал ресурс разработчика криптографической защиты. Чтобы скомпрометировать инфраструктуру и учетную запись в подходящей организации злоумышленники придумывают, пробуют все новые изощренные сценарии, которых мы еще увидим немало.

Рекомендации

  • Организации в случае реальной заинтересованности в обеспечении защиты от современных кибератак должны либо вкладывать в развитие собственной экспертизы мониторинга и реагирования, либо обратиться к специалистам из этой области. Сегодня для этих целей существуют управляемые сервисы, позволяющие компаниям полностью отдать мониторинг угроз и реагирование на них профессионалам.
  • Для защиты инфраструктуры от подобных угроз организациям необходим комплексный подход к безопасности, который может обеспечить, к примеру, F.A.C.C.T. Managed XDR — комплекс высокотехнологичных решений для продвинутого обнаружения, реагирования и защиты от сложных и неизвестных киберугроз.
  • В современных атаках киберпреступники применяют различные вектора, но социальная инженерия остается одним из самых популярных. Поэтому необходимо уделять особое внимание повышению уровня цифровой грамотности сотрудников и их навыков обнаружения потенциальных угроз.

Если ваша компания подверглась кибератаке, важно как можно скорее обратиться к экспертам по реагированию на инциденты.

Матрица MITRE ATT&CK

ТактикаТехникаПроцедура
Resource Development (TA0042)SEO Poisoning (T1608.006)Злоумышленники продвигают в поисковой системе подконтрольные им сайты, с которых осуществляется распространение DarkWatchman.
Initial Access (TA0001)Phishing (T1566)Злоумышленники используют фишинговый сайт, мимикрирующий под  компанию КриптоПро.
Execution (TA0002)User Execution: Malicious File (T1204.002)Злоумышленники при распространении DarkWatchman используют защищенный паролем архив. В архиве предоставляется  информация о дистрибутиве.
Command and Scripting Interpreter: JavaScript (T1059.007)DarkWatchman выполняет JavaScript код, полученный от C2.
Command and Scripting Interpreter: PowerShell (T1059.001)DarkWatchman выполняет PowerShell команды, полученные от C2.
Command and Scripting Interpreter: Windows Command Shell (T1059.003)DarkWatchman выполняет команды, полученные от C2, в интерпретаторе командной строки.
Inter-Process Communication: Component Object Model (T1559.001)DarkWatchman использует COM-объекты для работы с файлами, создания отложенных задач, исполнения команд (cmd, PowerShell), взаимодействия с реестром ОС.
Windows Management Instrumentation (T1047)DarkWatchman выполняет WMI команды.
Scheduled Task/Job: Scheduled Task (T1053.005)DarkWatchman создает отложенные задачи в планировщике задач.
Persistence (TA0003)Scheduled Task/Job: Scheduled Task (T1053.005)
Privilege Escalation (TA0004)Scheduled Task/Job: Scheduled Task (T1053.005)
Defense Evasion (TA0005)Deobfuscate/Decode Files or Information (T1140)DarkWatchman считывает содержимое файла 108788037, затем декодирует и расшифровывает содержимое с помощью операции XOR.
Masquerading (T1036)Файл CSPSetup.exe мимикрирует под официальный установщик «КриптоПро CSP».
Modify Registry (T1112)DarkWatchman использует ключ реестра HKCU\Software\Microsoft\Windows\DWM для хранения кейлоггера, перехваченных данных и конфигурационных параметров.
Obfuscated Files or Information: Compile After Delivery (T1027.004)Компиляция кейлоггера с помощью csc.exe в ходе выполнения сценария PowerShell.
Obfuscated Files or Information: Command Obfuscation (T1027.010)Кейлоггер запускается с помощью закодированной в Base64 команды.
Obfuscated Files or Information: Fileless Storage (T1027.011)Расшифрованное содержимое кейлоггера (файл:108788037) записывается в параметр ключа реестра.
Indicator Removal: Clear Windows Event Logs (T1070.001)DarkWatchman осуществляет очистку журналов событий Windows с помощью команды: ‘cmd.exe /c for /F «tokens=*» %1 in(\’wevtutil.exe el\’)DO wevtutil.exe cl «%1″‘.
Indicator Removal: File Deletion (T1070.004)DarkWatchman удалянет RarSFX файл CSPSetup.exe и файлы из каталога %TEMP%: 41779253.js, 108788037.
Indicator Removal: Clear Persistence (T1070.009)DarkWatchman получает информацию от C2 и производит деинсталляцию с зараженного хоста.
Discovery (TA0007)System Information Discovery (T1082)DarkWatchman собирает информации о версии атакованной ОС.
System Owner/User Discovery (T1033)DarkWatchman собирает информации о названии компьютера и имени пользователя.
System Time Discovery (T1124)DarkWatchman собирает информацию о часовом поясе.
System Location Discovery: System Language Discovery (T1614.001)DarkWatchman собирает информацию о языке системы.
Account Discovery: Local Account (T1087.001)DarkWatchman собирает информацию о роли пользователя.
Account Discovery: Domain Account (T1087.002)DarkWatchman собирает информацию о том, является ли хост частью домена.
Software Discovery: Security Software Discovery (T1518.001)DarkWatchman собирает информацию об антивирусном ПО.
Process Discovery (T1057)DarkWatchman осуществляет остановку процессов для очистки истории браузеров (Google Chrome, Yandex Browser, Mozilla Firefox).
Browser Information Discovery (T1217)DarkWatchman чистит историю браузеров.
Application Window Discovery (T1010)Кейлоггер осуществляет сбор данных об окнах запущенных процессов.
File and Directory Discovery (T1083)DarkWatchman осуществляет сбор данных о файлах и папках на хосте.
Peripheral Device Discovery (T1120)Кейлоггер осуществляет сбор данных подписанных драйверах PnP для устройств чтения смарт-карт.
Query Registry (T1012)DarkWatchman обращается к ключам реестра для сбора информации об ОС, например, для получения GUID зараженного хоста.
Collection (TA0009)Input Capture: Keylogging (T1056.001)DarkWatchman использует функционал кейлоггера для записи нажатия клавиш, данных буфера обмена и информации смарт-карт.
Data Staged: Local Data Staging (T1074.001)DarkWatchman размещает локальные данные в реестре Windows. Записывает расшифрованное содержимое кейлоггера в реестр системы.
Data from Local System (T1005)DarkWatchman отправляет собранную информацию о системе и загружает файлы с зараженного хоста на C2 сервер.
Command and Control (TA0011)Application Layer Protocol: Web Protocols (T1071.001)DarkWatchman получает информацию от C2 в виде HTTP статус-кода.
Data Encoding: Standard Encoding (T1132.001)Собранную информацию с зараженного хоста (телеметрию) DarkWatchman кодирует в виде HEX-строки.
Dynamic Resolution: Domain Generation Algorithms (T1568.002)DarkWatchman использует алгоритм генерации доменных имен (Domain Generation Algorithm – DGA).
Fallback Channels (T1008)DarkWatchman может использовать дополнительные 100 доменов, сгенерированных с помощью собственного алгоритма генерации доменных имен.
Exfiltration (TA0010)Exfiltration Over C2 Channel (T1041)DarkWatchman отправляет собранную информацию о системе и загружает файлы с зараженного хоста на C2 сервер.
Impact (TA0040)Inhibit System Recovery (T1490)DarkWatchman удаляет теневые копии с помощью vssadmin.exe.

YARA-правила

rule darkwatchman_rarsfx
{ meta: author = "Dmitry Kupin" company = "F.A.C.C.T." description = "Detects DarkWatchman RarSFX samples" sample = "5f7527bdb49d1f6a440aad9296888f8884818bea3b6af7d85da1ee5bde7f2574" sample = "d439a3ce7353ef96cf3556abba1e5da77eac21fdba09d6a4aad42d1fc88c1e3c" // old sample from Cyble blog date = "2023-09-27" strings: $rar = { 52 61 72 21 } // Rar! $setup_0 = "Setup=wscript.exe" fullword ascii $setup_1 = "Setup=cmd.exe" fullword ascii $sfxname = "%sfxname%" fullword ascii $r_cmnd0 = /Overwrite=(1|2)\r\nPath=.{4,15}\r\nSetup=wscript\.exe .{4,15}\.js [0-9]{1,4} \"%sfxname%\"/ $r_cmnd1 = /Overwrite=(1|2)\r\nPath=.{4,15}\r\nSetup=cmd\.exe \/c \(start \/MIN powershell\.exe -NonI -W Hidden -Exec Bypass Add-MpPreference -ExclusionPath "%SYSTEMDRIVE%"\) & \(start \/MIN wscript\.exe \/E:jscript .{4,15} [0-9]{1,4} \"%sfxname%\"/ condition: $rar and $sfxname and (any of ($setup_*) or any of ($r_*))
}
rule darkwatchman_js
{ meta: author = "Dmitry Kupin" company = "F.A.C.C.T." description = "Detects DarkWatchman obfuscated JavaScript samples" sample = "ae4c56ae10c6569f33638a6ed1da035731c4f6089bdaa80fa87cc5b09e78a57f" date = "2023-09-27" strings: $s0 = ");\x0D\x0A}\x0D\x0Areturn String.fromCharCode[String.fromCharCode(" ascii $s1 = ");\x0D\x0A}\x0D\x0Acatch(e)\x0D\x0A{\x0D\x0A}\x0D\x0A" ascii condition: uint16be(0) == 0x0D0A and filesize < 70KB and $s0 and $s1 in (filesize-30..filesize)
}
rule darkwatchman_keylogger
{ meta: author = "Dmitry Kupin" company = "F.A.C.C.T." description = "Detects DarkWatchman keylogger samples" sample = "f583dac65dc542063a9270f0e5e40c841f67779e133c72b9333b74a1d640627b" date = "2023-09-27" strings: // '=Software\Microsoft\Windows\DWM %HKEY_CURRENT_USER\' $h0 = { 3D 53 00 6F 00 66 00 74 00 77 00 61 00 72 00 65 00 5C 00 4D 00 69 00 63 00 72 00 6F 00 73 00 6F 00 66 00 74 00 5C 00 57 00 69 00 6E 00 64 00 6F 00 77 00 73 00 5C 00 44 00 57 00 4D 00 00 25 48 00 4B 00 45 00 59 00 5F 00 43 00 55 00 52 00 52 00 45 00 4E 00 54 00 5F 00 55 00 53 00 45 00 52 00 5C 00 } // '[<<] [del] :: Clipboard' $h1 = { 5B 00 AB 00 5D 00 01 0B 5B 00 64 00 65 00 6C 00 5D 00 00 1B 20 00 3A 00 3A 00 20 00 43 00 6C 00 69 00 70 00 62 00 6F 00 61 00 72 00 64 00 } condition: uint16(0) == 0x5A4D and uint32(uint32(0x3C)) == 0x00004550 and filesize < 11KB and any of them
}

Индикаторы компрометации

  • d0e352ba8198a9791bc21df9d40da653c8d267364fdd652cf534645bccd2c579 — CSP.rar
  • 5f7527bdb49d1f6a440aad9296888f8884818bea3b6af7d85da1ee5bde7f2574 — CSPSetup.exe
  • ae4c56ae10c6569f33638a6ed1da035731c4f6089bdaa80fa87cc5b09e78a57f — 41779253.js
  • 65c22eca2a518748606c6c02fd84986991a23595d555bf9a8f8ff2ebb7e8613c — 108788037
  • f583dac65dc542063a9270f0e5e40c841f67779e133c72b9333b74a1d640627b — C# keylogger
  • %LOCALAPPDATA%\[0-9a-f]{8}0.js (<%UID% + «0»>, например, ba8c3a320.js)
  • %TEMP%\bayspsyc.r14
  • %TEMP%\bgai224f.4pu
  • %TEMP%\bixdpgxb.o1o
  • %TEMP%\emcqzedg.epk
  • %TEMP%\isirzhga.vf2
  • %Windows%\system32\wbem\wmiprvse.exe -secured -Embedding (родительский процесс: svchost.exe)
  • wscript.exe %LOCALAPPDATA%\[0-9a-f]{8}0.js [0-9]{1,4} (родительский процесс: WmiPrvSE.exe), например: wscript.exe %LOCALAPPDATA%\ba8c3a320.js 40 (родительский процесс: WmiPrvSE.exe)
  • powershell.exe -NoP -NonI -W Hidden -Exec Bypass -enc <закодированный Base64 кейлоггер> (родительский процесс: WmiPrvSE.exe)
  • Шаблон: [HKCU\Software\Microsoft\Windows\DWM] «[0-9a-f]{8}[01aszphcbrtjvd]{1}»
  • [HKCU\Software\Microsoft\Windows\DWM] <%UID% + [01aszphcbrtjvd]{1}>, например, %UID% — ba8c3a32:
    • [HKCU\Software\Microsoft\Windows\DWM] «ba8c3a320» = 1
    • [HKCU\Software\Microsoft\Windows\DWM] «ba8c3a321» = <закодированный Base64 кейлоггер>
    • [HKCU\Software\Microsoft\Windows\DWM] «ba8c3a32a» = <информация об активных окнах и перехваченные вводимые данные с клавиатуры>
    • [HKCU\Software\Microsoft\Windows\DWM] «ba8c3a32d»
  • Мьютекс процесса powershell.exe: <%UID% + m>, например, %UID% — ba8c3a32, тогда имя мьютекса имеет вид: ba8c3a32m.
  • Переменная среды с именем «__UID_ENV_VAR__», содержащая значение %UID%, например, ba8c3a32.
  • Запланированная задача с именем %GUID%, например, ba8c3a32-f8d9-07cc-f8d9-ba8c3a32f8d0, которая выполняет команду: wscript.exe %LOCALAPPDATA%\[0-9a-f]{8}0.js [0-9]{1,4}, например: wscript.exe %LOCALAPPDATA%\ba8c3a320.js 40.
  • hxxps://u[.]to/98yNHg
  • hxxps://cdn.discordapp[.]com/attachments/1071280949523927053/1088019667878154250/CSP.rar
  • Шаблон: hxxp://[0-9a-f]{8}.(cyou|shop|icu)/index.php, например, hxxp://ec311447[.]cyou/index.php

Время на прочтение

Вводная.

В начале апреля в организации в Российской Федерации (и не только) пришли письма от неизвестного отправителя. В содержимом письма, кроме пожелания хорошего дня и просьбой ответить «скорее», находился RAR архив, а внутри архива *.bat файл.

Как обнаружить модульный стример rat csharp

После проверки содержимого в песочнице были предоставлены некоторые артефакты, указывая, что в письме явно содержится что-то подозрительное, но определить наверняка, вредонос это или нет СЗИ не удалось.

Зато были указаны некоторые составляющие bat файла: обфусцированные строки PowerShell.

Как обнаружить модульный стример rat csharp

Этого было достаточно чтобы начать анализ содержимого, найти IoC’и, и посмотреть на наличие таковых в трафике от организации.

Анализ вложения.

Как уже было отмечено, в архиве находился bat-файл.

Внутри обфусцированные функции и зашифрованные payloads, но об этом по порядку.

Содержимое bat-файла часть 1 (пейлоад отредактирован)
Содержимое bat-файла часть 1 (пейлоад отредактирован)
Содержимое bat-файла часть 2 (обфусцированный PowerShell).
Содержимое bat-файла часть 2 (обфусцированный PowerShell).