Analysis of the behavior of the Pegasus Trojan in the network

    The source code of the Pegasus banking Trojan was recently published . Despite the mention of the Carbanak group in the name of the archive, researchers from Minerva Labs denied the Trojan’s involvement in this group and proved their involvement in the Buhtrap (Ratopak) group . Inside the archive is a brief description of the work of the Trojan, its source codes, a description of the bank payment system and data from employees of many Russian banks.

    The architecture of the source code of this malware is quite interesting. The functionality is divided into modules assembled into a single binpack at compile time. The compilation process also includes the signature of executable files with a certificate from the tric.pfx file that is not in the archive.

    No less curious is the Pegasus network activity, which, after infection, tries to spread within the domain and is able to proxy the data between the machines using the Mailslot pipes and transport. We focused on exploring the Trojan’s network activity and quickly added detections for Pegasus to the PT Network Attack Discovery product . This will allow all its users to timely detect the activity of this trojan and its modifications in its network. In this article I will give a detailed description of the mechanisms of distribution over the network and the interaction between copies of Pegasus.



    Intro


    Once on the machine, the main module InstallerExe injects the code into svchost.exe using the Process Hollowing technique and, after initializing the main modules, Pegasus starts several parallel processes:

    1. Domain Replication - is engaged in intelligence within the network and attempts to spread to other Windows machines.
    2. Mailslot Listener listens to broadcast mailslot messages with which Pegasus sends out acquired accounts. The slot name is generated at compile time.
    3. Pipe Server Listener listens to Windows Pipe with the name generated on behalf of the machine. These pipes are mainly used to detect other copies of Pegasus on the network and their interaction.
    4. Logon Passwords periodically every few minutes trying to dump account data module from Mimikatz.
    5. Network Connectivity is responsible for communicating with the CnC server and periodically exchanging messages.

    // start transports which links data with our CB-manager
    	pwInitPipeServerAsync(dcmGetServerCallback());
    	mwInitMailslotServer(dcmGetServerCallback());
    ...
    	// start broadcasting creds to other machines
    	cmStartupNetworkBroadcaster();
    

    Domain Replication


    One of the subsystems in Pegasus is responsible for the horizontal distribution (Lateral Movement) in the Windows network. Distribution is divided into two important stages:

    1. Detection of neighboring machines.
    2. Attempt to replicate on the machine.

    Detection of neighboring machines in the domain is carried out through two API calls:

    NetServerEnum, which requires the Browser service to work and WNetOpenEnum / WNetEnumResource calls.
    All machines found in the domain are checked if they are already infected. Pegasus queries the generated name of the pipe once every 200 milliseconds more than 20 times in a row. We have used this abnormal behavior as one of the indicators of Pegasus activity in the domain. Having found no signs of infection, the malware proceeds to the next step - an attempt to replicate.

    Replication occurs as follows. Using the found accounts (US) on the host, Pegasus attempts to authenticate on the machine using the SMB protocol to the IPC $ and ADMIN $ balls, and if there is access to IPC $, but there is no access to ADMIN $, then Pegasus concludes that account is not enough and must be marked as invalid. Having gained access to the ADMIN $ balloon, which is an alias for the% windir% folder, the malware tries to determine the architecture of the machine in order to use the appropriate module in the future.

    The architecture definition algorithm is based on the headers of the PE files on the remote machine. As such a file, Pegasus tries to read the first 4 kilobytes of notepad.exe from the% windir% folder. The obvious lack of such a method is that on Windows Server 2012, the notebook is located along the path% windir% \ System32.

    Location notepad.exe on windows 7:

    C:\Users\Administrator>where notepad.exe
    C:\Windows\System32\notepad.exe
    C:\Windows\notepad.exe
    

    On Windows Server 2012:

    C:\Users\Administrator>where notepad.exe
    C:\Windows\System32\notepad.exe
    

    Not finding notepad.exe, Pegasus cannot infect the server, even with account information with the necessary permissions. The mere absence of a notebook in% windir% can stop the distribution of Pegasus on Windows Server 2012. Using regedit.exe in this regard is more reliable.

    After successfully determining the architecture of the target server, Pegasus downloads a small RSE (Remote Service Exe) dropper with a size of about 10 kilobytes, the task of which is to load the binpack from Pegasus modules through the pipe in open form and transfer control to the Shellcode module. A dropper name is composed in a pseudo-random manner and consists of a string of hexadecimal characters 8 to 15 characters long. The pseudo-random generator is initialized depending on the name of the target machine and will be the same between runs to avoid possible garbage% windir% with previous copies of the dropper.



    The dropper is checked for integrity and possible removal by the antivirus, after which it is launched by one of two implemented mechanisms - SCM or WMI, and in the first place Pegasus attempts to launch RSE via the WMI mechanism, and only then with the help of Service Control Manager (SCM). This is done for the reason that SCM leaves more traces in the Windows logs. The plans of the creators of Pegasus were other methods of distribution - Wsh Remote, Powershell remoting, Task Scheduler, and a module for executing commands via RDP was under development.

    As mentioned above, after a successful launch, the dropper checks and opens the listening pipe and transfers control to the incoming payload.



    Since the Pegasus code is injected by the Process Hollowing method into the svchost.exe process, neither the original InstallerExe module in the case of the initial infection, nor the RSE dropper in the distribution case should remain on the disk. If the dropper is still available along a known path, Pegasus deletes it in its own way:

    1. overwriting the file contents with random data;
    2. overwriting with empty data (zeros);
    3. rename file;
    4. delete the file.



    After successful infection, the Domain Replication distribution process begins again.

    Mailslot works


    After Pegasus has access to account data either from another copy of Pegasus, or from the mod_LogonPasswords module, it will start broadcasting KM data by domain. Mailing is done using the SMB-based Mailslot mechanism, which allows for unidirectional broadcasting of a small portion of data across a domain. Distribution occurs on a randomly generated slot name and, so that all infected machines in the domain can send and receive data using a single name, the pseudo-random generator for names is initialized from the TARGET_BUILDCHAIN_HASH variable specified in the config when building.

    Since the Mailslot mechanism imposes a limit on the maximum packet size, only one UZ is distributed at a time according to the principle of the last distribution time: among all the existing UZ by the domain, the one whose date of the last distribution is the oldest is sent.

    The data in Mailslot ah is not transmitted in the clear, but wrapped with three layers of XOR encryption, with the keys being transmitted along with the data. The first data layer is the envelope NetMessageEnvelope with data integrity checking algorithm SHA1, used for all data transmitted over the local network. The 4 bytes of data at the beginning of a packet are a key that changes by bit shifts by 5 bits to the right per cycle. Inside the envelope contains the XOR coded data structure with the fields of the ultrasound directly and the date of their addition. The 8 byte key is also located at the beginning of the structure, but is applied without shifts. After decoding the structure of the KM, all that remains is to deserialize the individual fields from the ENC_BUFFER structures such as the computer name, the domain name, the user name, and his password. These fields are encrypted using an 8 byte key with offsets.the script , the PCAP .

    Mailslot mailing period in the release version ranges from 20 seconds to 11 minutes.

    // some random wait before making next step
    		DbgPrint("going to sleep");
    #ifdef _DEBUG
    		// debug - 2-5 s
    		Sleep(rg.rgGetRnd(&rg, 2000, 5000));
    #else
    		// release - 20 - 650 s
    		//Sleep(rg.rgGetRnd(&rg, 2000, 65000) * 10);
    		Sleep(rg.rgGetRnd(&rg, 2000, 15000));
    #endif

    In addition to sharing accounts, the Mailslot mechanism is used to search for an infected machine with Internet access and announce Internet access. The envelope NetMessageEnvelope stores the type of message sent. The data exchange between the machine without access and the machine with Internet access is carried out through the pipes.

    Pipe works


    For two-way communication or transfer of large amounts of data, copies of Pegasus use pipes as a channel of communication. The name of the pipe, though also generated by a pseudo-random generator, depends on the name of the machine and the build, and thus allows the client and server parts to use the same name.

    With one-way communication, for example, transferring binpack during replication to another machine, the data is not encrypted and transmitted in the clear. Binpack starts with a SHELLCODE_CONTEXT structure with a length of 561 bytes.



    During a two-way transfer, for example, data proxying between a copy of Pegasus without Internet access and a CnC server, the same NetMessageEnvelope structure with XOR encryption is used, as in the case of Mailslot, since It allows you to distinguish between different types of messages in the id field.

    Architecturally, data proxying is performed through a request to transfer a portion of data (PMI_SEND_QUERY), receive the request id in response, and poll the task status by id (PMI_CHECK_STATUS_QUERY). As a rule, a different Envelope structure is added as a load, adding different functionality and another layer of encryption.

    In addition, work with the pipe does not end with the interaction between infected machines. The mod_KBRI_hd module injects cmd.exe code into the processes that intercepts MoveFileExW calls and analyzes all copied data, since this is part of the payment mechanism. If the file being copied contains data interesting to the attackers - payment data, a notification about this is sent to the CnC server. Communication between the mod_KBRI module injected into cmd.exe and a copy of Pegasus is carried out inside the infected machine through a pipe whose name is not generated, but is strictly specified in the source code:

    \.\pipe\pg0F9EC0DB75F67E1DBEFB3AFA2

    The functionality of the module also includes the substitution of account data on the fly by a template. An example of patterns for search in the screenshot.

    Cnc traffic


    A separate stream is responsible for direct data exchange with the CnC server, which every few minutes checks a queue of data chunks from internal processes or from other copies of the malware and sends them to the server.

    During the initialization of the mod_NetworkConnectivity module, it conducts a multi-step test of the network connection:

    1) Detection of proxy server settings and an attempt to connect to www.google.com :

    • In the registry \\ Software \\ Microsoft \\ Windows \\ CurrentVersion \\ Internet Settings.
    • Via WPAD (call WinHttpGetProxyForUrl).
    • Through the proxy server configuration for the current user (call WinHttpGetIEProxyConfigForCurrentUser).

    2) Checking the connection with Microsoft update servers and the returned data ( authrootseq.txt , authrootstl.cab , rootsupd.exe )

    3) Testing HTTPS connections with one of 6i addresses:


    Only after passing through all the checks, Pegasus believes that it has the necessary access to the external network and can announce it over the Mailslot domain as a message. And Pegasus can be masked and communicate with the CnC server only during business hours - from 9 to 19 and local time.

    Pegasus sends chunks of data wrapped in an envelope with a hash sum calculation encrypted using DES encryption in CRYPT_MODE_CBC / PKCS5_PADDING mode. The encryption key depends only on the variable at compile time, and in this way we can decrypt the traffic between the malware and the server knowing only its BUILDCHAIN_HASH. In the source code inside the archive, this variable had the value 0x7393c9a643eb4a76. The script for decrypting the bounce (Check-in) to the server and an example of such a package can be found here: the script ,PCAP .

    Such content (structure INNER_ENVELOPE) it sends to the CnC server during the Check-in, or with some data. First, there are 28 bytes of an envelope with a length field and a SHA1 sum.



    The same data is transmitted between the machines during proxying through the pipe, but wrapped inside the NetMessageEnvelope envelope known to us with a hash sum and XOR encryption.

    The CnC operator can send commands to execute on a copy of Pegasus and messages with commands or other data, for example EID_CREDENTIALS_LIST can contain their own field encryption layers, as we have already seen in the case of broadcast accounts.

    Detection


    First of all, we were interested in detecting Pegasus activity on the network and, after carefully studying the source codes and running it in the test environment, we found those network anomalies and artifacts that clearly indicate the presence of this complex malware on the network. Pegasus can really be called versatile - it actively uses the SMB protocol for sending messages and establishing communication with other copies, extends to other machines and communicates with the CnC server in its own particular way. By establishing a peer-to-peer network in the domain, copies of Pegasus pave the way to the external network and communicate with the CnC server, proxying traffic through each other. Using certificates to sign executable files and accessing Microsoft and Mozilla resources during connection testing makes it difficult to detect its activity and detection on the host.

    The Pegasus source code project is quite well structured and described, so in the near future we can expect the borrowing of parts of its code by other malicious programs and the appearance of modifications.

    Many of the mechanisms for remote execution of commands and search for these accounts remained unfulfilled, the developers were also going to add the ability to change the shellcode during the implementation process on the fly. And this is not all their ideas.

    We have developed several signatures for PT NAD and IDS Suricata, which allow identifying Pegasus-specific network activity at different stages, starting from the very first seconds of its activity. Find open signatures for Suricata IDS on our github and Twitter., they will automatically go to your Suricata if you use the suricata-update update mechanism.

    How the signatures on the activity of Pegasus work can be seen in the screenshot below. This is our new product, PT Network Attack Discovery , which detects incidents and assists in their investigation: In addition, the following compromise indicators (IC) can be used for detection:





    MAILSLOT \ 46CA075C165CBB2786 
    pipe \ pg0F9EC0DB75F67E1DBEFB3AFA2
    hxxp: //denwer/pegasus/index.php
    hxxp: //mp3.ucrazy.org/music/index.php
    hxxp: //support.zakon-auto.net/tuning/index.asp
    hxxp: //video.tnt-online.info/tnt-comedy-tv/stream.php

    Posted by : Kirill Shipulin from @attackdetection, Twitter | Telegram

    Also popular now: