Positive Research Center

Syndikovat obsah
Positive Researchhttp://www.blogger.com/profile/12273696227623127095noreply@blogger.comBlogger22113
Aktualizace: 59 min 1 sek zpět

Low-level Hacking NCR ATM

10 Srpen, 2018 - 15:00

Image credit: Sascha Kohlmann, CC BY-SA 2.0
Many of the systems that power the modern world are supposed to be beyond the reach of mere mortals. Developers naively assume that these systems will never give up their secrets to attackers and eagle-eyed researchers.

ATMs are a perfect case in point. Thefts with malware of the likes of Cutlet Maker, as well as unpublicized incidents when unknown attackers plugged in their laptop to an ATM and stole cash without leaving any system logs behind, confirm what the security community has long known. There is no such thing as a hack-proof system, merely one that has not been sufficiently tested.

Getting startedEven now, many people think that the only way to rob an ATM involves the brutest of brute force: pulling up in a pickup, attaching a hook, and pushing hard on the gas pedal, before savaging the ATM with a circular saw, crowbar, and welding kit.

But there is another way.

After a brief search on eBay, I obtained the board for a NCR USB S1 Dispenser with firmware. I had two objectives:

  • Bypass the encryption used for commands (such as "dispense banknotes") that are sent by the ATM computer via USB to the dispenser.
  • Bypass the requirement for physical access to the safe in order to complete authentication (which must be performed by toggling the bottom cassette in the safe), which is needed for generating the encryption keys for the commands mentioned above.


FirmwareThe firmware is an ELF file for the NXP ColdFire processor (the Motorola 68040, my favorite CPU!) running on VxWorks v5.5.1.


There are two main sections of interest in the ELF file, .text and .data:

  • The first contains code that loops continuously most of the time (we'll call it the "main firmware") when the dispenser is connected to the system in the upper part of the ATM.
  • The second contains a zlib-compressed bootloader (locally named "USB Secure Bootloader"), which is responsible for uploading firmware and running the main code.

And best of all (for researchers, anyway), is that the debug symbols in the ELF file were all there and easily searchable.

Inner workings of the main firmwareWe can divide the code into four main levels, from top to bottom in the hierarchy:

  1. USB Receive Thread, which accepts USB packets and distributes them to the different services.
  2. Services are the main units of execution. Each service has a particular role and corresponding tasks (classes).
  3. Classes, here, are tasks that can be performed by a particular service using controllers.
  4. Controllers are the workers that validate tasks, perform tasks, and generate result packets.


There was a lot of firmware code, so I decided to start by finding all possible services and only then trying to figure out where tasks are transferred.

Here are the services I found that were responsible for the actions of interest:

1) DispTranService (Dispenser Transaction Service): Handles encrypted commands, generates bundle of banknotes, authenticates, and much more. Sure, the interesting stuff.


2) securityService: After authentication, a session key is generated on the dispenser. When requested by the ATM computer, the session key is sent to it in encrypted form. This key is then used to encrypt all commands designated important by the vendor, such as dispensing cash and banknotes bundle forming.


But then another service, UsbDownloadService, caught my eye. The job of this service is, when the dispenser is connected to the computer and the firmware version on the dispenser doesn't match the version on the computer, switch to the bootloader in order to upload the firmware needed to work (which is stored in the folder with the vendor's software on the computer) with the OS. This service can also give us information about the current firmware version.


Physical authenticationPhysical authentication is in fact implemented extremely well, with the mission of protecting the ATM from unauthorized USB commands. The ATM safe with cash must be open in order to perform either of the following actions:

  • Remove and insert the lower cassette.
  • Toggle the switch on the dispenser main board.


But this all is required only if the access level is set to the maximum. There are a total of three access levels: USB (0), logical (1), and physical (2). The first two are used by firmware developers for debugging and testing. The vendor, of course, strongly urges selecting the third one by default.

The vulnerabilityHere I will describe a critical vulnerability (now fixed by the vendor) that with physical access to the service zone of the ATM but not to the safe zone (such as through a hole drilled in the ATM front panel), allowed the dispenser execute any command – even if the command is "give me cash now!"


I found that UsbDownloadService accepts commands that don't require encryption. That sounds tempting, but shouldn't Secure Bootloader prevent any further mischief, as its name implies?

Spoiler: …it doesn't!

We need to go deeper As mentioned already, the .data section contains compressed bootloader code that didn't initially catch my attention or that of my colleagues.


As long as the bootloader remained a secret, there was no way to answer the question: "How does the software on the computer upload the dispenser’s firmware?" The main firmware did not reveal any clues.


So the bootloader is unpacked and loaded into the IDA at offset 0x100000, from where investigation can start… except there are no debug symbols there!

But after comparing the main firmware with the bootloader code and reading the controller datasheet, I started to get a better idea of what was happening.


Although the process of firmware uploading seemed to be secure, in reality it was not. The trick was just to upload the firmware in the right way :)

Fully understanding this process took a lot of time and dedication (details can be learned from "Blackbox is dead – Long live Blackbox!" at Black Hat USA 2018 in Las Vegas). These efforts included re-soldering NVRAM and copying the backup to it in order to unbrick the controller… and other easy-peasy stuff like that.

Thank you to my colleague Alexey for his patience!

Here is the method for uploading firmware to the dispenser:

1) Generate an RSA key pair and upload the public key to the controller.


2) Write .data and .text from the ELF in sequence to their physical addresses, taken from the section headers:


3) Calculate the SHA-1 checksum for the newly written data, encrypt that value with the private key, and send the result to the controller.


4) Calculate and send the sum of all firmware words that have been written.


At which point, if everything has been calculated and written correctly, the main firmware will boot without a hitch.

Only one restriction was found for the firmware writing process: the version of the "new" firmware cannot be less than the version of the current firmware. But there's nothing to stop you from tinkering with the firmware number in the data that you write yourself.

So my special firmware with anti-security "secret sauce" was uploaded and run successfully!

By now I had a good knowledge of the main firmware, commands used to dispense cash, and more. All that remained was to send (unencrypted) commands, which the dispenser would eagerly obey.


Cash dispensingThis successful result was a worthy intellectual (although not monetary) reward for all the travails of research, such as bricking a real ATM (oops!). My curiosity almost inspired me to try repeating this trick with another major ATM vendor.


Ultimately, a very real ATM began to whirr and spit out very not-real dummy bills (vendors' shiny equivalent of Hollywood prop money). No magic was necessary: just a laptop, brainpower, and a USB cord.

Conclusions"Security through obscurity" is no security at all. Merely keeping code or firmware proprietary will not stop an attacker from finding a way in and taking advantage of vulnerabilities. Curiosity and an initial financial outlay are all that is required.

Just as development is best handled by developers, security should be the job of security professionals. The most productive approach for vendors is to work closely with dedicated security companies, which have teams possessing the necessary experience and qualifications to assess flaws and ensure a proper level of protection on a case-by-case basis.

PostscriptumThe vendor has confirmed the vulnerability (which was also found in the S2 model) and declared it fixed as of the February 2018 patch.

CVE listings:

  • CVE-2017-17668 (NCR S1 Dispenser)
  • CVE-2018-5717 (NCR S2 Dispenser)

AcknowledgementsBefore I had even set to work on the firmware, Dmitry Sklyarov and Mikhail Tsvetkov had already discovered a lot about it (even without having a dispenser board). Their findings were of enormous assistance! And as concerns everything hardware-related, Alexey Stennikov's help was absolutely invaluable.

Author: Vladimir Kononovich, Positive Technologies

Pegasus: analysis of network behavior

30 Červenec, 2018 - 13:19
Source code for Pegasus, a banking Trojan, was recently published online. Although the Carbanak cybercrime gang was referenced in the archive name, researchers at Minerva Labs have shown that Pegasus actually is the handiwork of a different group known as Buhtrap (Ratopak). The archive contains an overview of the Trojan, its source code, description Russian banking procedures, and information on employees at a number of Russian banks.

The architecture of the Pegasus source code is rather interesting. Functionality is split among multiple modules, which are combined into a single binpack at compile time. During compilation, executables are signed with a certificate from the file tric.pfx, which is missing from the archive.

The network behavior of Pegasus is no less curious. After infection, Pegasus tries to spread within the domain and can act as a proxy to move data among systems, with the help of pipes and Mailslot transport. We focused on the unique aspects of the malware's network behavior and quickly added detection signatures to PT Network Attack Discovery. Thanks to this, all users of PT NAD can quickly detect this Trojan and its modifications on their own networks. In this article, I will describe how Pegasus spreads on a network and how copies of Pegasus communicate with each other.

Basic structureOnce on a victim computer, the initial module (InstallerExe) uses process hollowing to inject code into svchost.exe. After the main modules initialize, Pegasus launches several parallel processes:

  1. Domain Replication: Gathers information about the network and tries to spread Pegasus to other Windows systems.
  2. Mailslot Listener: Listens for Mailslot broadcasts, which are used by Pegasus to send stolen credentials. The slot name is generated at compile time.
  3. Pipe Server Listener: Listens to the Windows Pipe with a name derived from the name of the computer. These pipes are used mainly to discover and communicate with other copies of Pegasus on the same network.
  4. Logon Passwords: Tries once every few minutes to dump credentials from memory with the help of a Mimikatz-based module.
  5. Network Connectivity: Responsible for interfacing with the C&C 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 ReplicationThis module is responsible for lateral movement on Windows networks. Movement consists of two steps:

  1. Discovering other machines on the domain.
  2. Trying to replicate Pegasus to those machines.


Discovery of other machines on the domain relies on use of two API calls: NetServerEnum, which requires the Browser service to work, and WNetOpenEnum/WNetEnumResource. All machines discovered on the domain are verified to determine whether they are already infected. Pegasus polls the generated pipe name more than 20 consecutive times once every 200 milliseconds. (We flagged this strange behavior as one of the indicators of Pegasus presence.) If Pegasus does not detect any signs of infection, it proceeds to the next step: replication.

With the help of credentials found on the host, Pegasus tries to log in to the target over the SMB protocol to IPC$ and ADMIN$ shares. If IPC$ is accessible but ADMIN$ is not, Pegasus concludes that the account does not have sufficient rights and marks the credentials as invalid. After obtaining access to the ADMIN$ share, which is an alias for the %windir% folder, the malware tries to determine the machine architecture in order to pick the suitable module to apply.

This process of architecture determination is based on the headers of PE files on the machine in question. Pegasus attempts to read the first 4 kilobytes of notepad.exe in the %windir% folder. One subtle drawback of this method is that on Windows Server 2012, notepad.exe is located at the path %windir%\System32.

Location of notepad.exe on Windows 7:

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

Location of notepad.exe on Windows Server 2012:

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

If notepad.exe is not found, Pegasus cannot infect the server, even if it has credentials for an account with the necessary rights. So the simple absence of Notepad in %windir% can stop Pegasus from spreading on Windows Server 2012. Using regedit.exe would have been a more surefire way of accomplishing this task.

After determining the architecture of the target server, Pegasus downloads a small (~10 kilobytes) Remote Service Exe (RSE) dropper. The dropper's purpose is to download binpack, which contains the payload modules, via a pipe in cleartext and hand off control to the Shellcode module. The name of the dropper is generated pseudorandomly and consists of 8 to 15 hexadecimal characters. The pseudorandom generator uses the name of the target machine as a seed and ensures that the name will be identical across restarts, in order to avoid littering %windir% with multiple copies.


After a check of the dropper’s integrity and making sure that the dropper has not been deleted by antivirus protection, an attempt is made to run the dropper via the Windows Management Instrumentation (WMI) mechanism. Service Control Manager (SCM) can also be used, but the malware prefers the first method because SCM leaves more traces in Windows logs. Code suggests plans by the creators of Pegasus to implement other replication methods: WSH Remote, PowerShell Remoting, and Task Scheduler. A module for running commands via RDP was under development as well.

As mentioned already, once launched the dropper successfully checks and starts listening to a pipe before handing off control to the payload that arrives.


Since Pegasus code is injected via process hollowing into the svchost.exe process, the victim disk will not retain any copy of the initial module InstallerExe (if infection started with the machine in question) or of the RSE dropper (in the case of replication). If the dropper is still accessible at a known path, Pegasus deletes it as follows:

  1. Overwrites the file contents with random data.
  2. Overwrites the file again, this time with empty data (zeroes).
  3. Renames the file.
  4. Deletes the file.

If infection is successful, Domain Replication begins again.
MailslotWhen Pegasus obtains credentials from another copy of Pegasus or from the mod_LogonPasswords module, the malware starts broadcasting the credentials on the domain. Broadcasting is performed using the Mailslot mechanism, which is based on SMB and allows sending one-way broadcasts of small portions of data to systems on the domain. The slot names are randomly generated. In order for all infected machines on the domain to send and receive data with the same slot name, the pseudorandom name generator is initialized from the variable TARGET_BUILDCHAIN_HASH, which is set in the configuration during build.

Since Mailslot imposes an upper limit on packet size, only one set of credentials is broadcast at a time. Among all available domain credentials, the set of credentials broadcast longest ago (=all other credentials have been broadcasted more recently at least once) is chosen.

Mailslot data is not sent in cleartext, but instead wrapped in three layers of XOR encryption, the keys for which are transmitted together with the data. The first layer is NetMessageEnvelope with an SHA1 integrity check, which is used for all data sent on the local network. The key is contained in 4 bytes in the beginning of the packet, and shifts 5 bits to the right per cycle. Inside is an XOR-encrypted data structure with fields for credentials and their date of addition. The beginning of the structure contains an 8-byte key, but no shifting is applied. After decoding the structure of the credentials, all that remains is to deserialize individual fields from ENC_BUFFER structures such as computer name, domain name, username, and password. These fields are encrypted with an 8-byte key with shifts. A sample Mailslot packet and script for decrypting it are available: script, PCAP.

In the release version of the malware, Mailslot messages are sent at an interval between 20 seconds and 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

Besides providing credentials, Mailslot messages also announce Internet access and help to find other infected computers that have such access. NetMessageEnvelope indicates the type of message inside. Pipes make it possible for Internet-connected computers to communicate with computers that are not connected to the Internet.

PipesPegasus uses pipes for two-way communication and sending large amounts of data. Although the name of each pipe is generated by a pseudorandom generator, it also depends on the machine name and build, which allows the Pegasus client and server to use the same name.

During one-way communication (such as when sending binpack during replication to another computer), data is sent unencrypted. At the beginning of binpack is the structure SHELLCODE_CONTEXT, which is 561 bytes long.


Two-way communication—say, when proxying data between a Pegasus copy with Internet access and a C&C server—makes use of the same NetMessageEnvelope structure with XOR encryption as we already saw with Mailslot. This is possible because the structure enables differentiating different message types based on the id field.

When data is being proxied, a query for data is sent (PMI_SEND_QUERY), the query ID is received, and the status of the query can be checked by its ID (PMI_CHECK_STATUS_QUERY). In most cases, the payload will be yet another Envelope structure, which adds features and another layer of encryption.

These pipes can do more than just help infected machines to communicate. The module mod_KBRI_hd injects cmd.exe processes with code that intercepts MoveFileExW calls and analyzes all copied data, since this is a part of the bank payment mechanism. If the copied file contains payment data of interest to the attackers, a notification is sent to the C&C server. The mod_KBRI module, injected into cmd.exe, communicates with Pegasus on an infected machine via a pipe whose name is not generated, but rather hard-coded:

\.\pipe\pg0F9EC0DB75F67E1DBEFB3AFA2

Module functionality also includes the ability to replace payment information on the fly using a template. Example search patterns are shown in the screenshot.


C&C trafficData exchange with the C&C server is handled by a separate stream that, every few minutes, checks the queue of data chunks from internal processes or other copies of Pegasus and sends them to the server

During initialization of the mod_NetworkConnectivity module, the presence of a network connection is tested in several steps:

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

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

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

3) Testing of HTTPS connections with one of the following addresses:

  • https://safebrowsing.google.com
  • https://aus3.mozilla.org
  • https://addons.mozilla.org
  • https://fhr.data.mozilla.com
  • https://versioncheck-bg.addons.mozilla.org
  • https://services.addons.mozilla.org

Only if all these checks are passed does Pegasus consider an external network to be accessible, after which it announces this fact on the domain via a Mailslot message. For stealth, Pegasus communicates with the C&C server only during working hours (9:00 a.m. to 7:00 p.m. local time).

Data chunks, wrapped in an envelope with checksum, are sent with DES encryption in CRYPT_MODE_CBC/PKCS5_PADDING mode. The encryption key is derived entirely from a variable that is set at compile time, meaning that we can decrypt traffic between Pegasus and the C&C server so long as we know the value of BUILDCHAIN_HASH. In the source code in the archive in question, this variable was equal to 0x7393c9a643eb4a76. A sample packet and script for decrypting the server check-in are available for download: GitHub, PCAP.

This content (in the INNER_ENVELOPE structure) is sent to the C&C server during check-in or together with other data. The beginning of it contains 28 bytes of envelope with a field for the length and SHA1 checksum.


When proxied via pipes between machines, the same data is sent, but wrapped in the NetMessageEnvelope we have already discussed, plus the checksum and XOR encryption.

The C&C operator can send execution commands to Pegasus copies. Messages with commands or other data, such as EID_CREDENTIALS_LIST, can contain their own layers of encryption for fields, as we already saw with broadcasting of stolen credentials.

DetectionOur attention focused on how to detect Pegasus activity on networks. After carefully studying source code and running the malware in a test environment, we were able to create a list of network anomalies and artifacts that clearly indicate the presence of this sophisticated threat.

It would be fair to call Pegasus versatile: it actively uses the SMB protocol to send messages and communicate with other copies. The methods used for replication and C&C interaction are also distinct. Pegasus copies establish a peer-to-peer network on the domain, building a path to the Internet and communicating with C&C servers by means of traffic proxying. Certificate signing of executables and use of Microsoft and Mozilla sites for verifying connection access complicate attempts to detect Pegasus activity and discover infected hosts.

The Pegasus source code is relatively well structured and commented, making it likely that other threat actors will copy or "borrow" code for their own malware.

Many of the mechanisms for remotely running commands and searching for credentials remain unimplemented. Among the developers' unrealized plans was the ability to modify shellcode on the fly during process injection.

We have developed several signatures for PT NAD and the Suricata IDS suitable for detecting Pegasus-specific activity at various stages, within the very first seconds of presence. Public signatures for Suricata are available from our company on GitHub and Twitter, and will automatically be added to Suricata if you use the suricata-update mechanism.

You can view detections with Pegasus signatures in the following screenshot. This view is taken from PT Network Attack Discovery, our product for incident detection and forensic investigation:


In addition, here are some useful indicators of compromise (IoC):

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

Author: Kirill Shipulin, @attackdetection team, Twitter | Telegram