Virus living exclusively in PLC
This article does not have the nature of “attribution” of authorship. Only a translation and some own thoughts on this subject.
Authors: Ralf Spenneberg, Maik Brüggemann, Hendrik Schwartke
Source: OpenSource Security Ralf Spenneberg
Modern industrial processes are controlled by programmable logic controllers (PLCs). Many PLCs sold today have Ethernet ports on board and can communicate via IP. Based on Siemens SIMATIC S7-1200, we will demonstrate the virus. This vulnerability does not require any additional PCs for distribution. The worm lives and works only in the PLC. It scans the network for new targets (PLCs), attacks them and reproduces itself on the found targets. The main, main program running on the affected PLC is not modified. The affected device begins to scan the network in search of a new target. We will analyze the effect of the virus on the target and possible methods to reduce the negative consequences.
1. Introduction
IT systems are critical components in modern industrial processes. These processes would not have been possible without modern communication networks. Unfortunately, with the use of IT systems and communication networks in industrial systems, the user is subjected to attacks that have long been known in IT. These hacker attacks can harm industrial systems in many ways. They can lead to large financial losses, but at the same time they can have a negative impact on the life and health of others. The effectiveness of these attacks was demonstrated by Stuxnet.. Siemens PLCs have been modified to prevent Iran from enriching nuclear fuel. The virus spread through the PC station, exploiting MS Windows vulnerabilities. The PLC software was modified so that the centrifuges used in the process were destroyed. The worm needed a computer to spread and attack the PLC through a PC. This article will demonstrate a virus / worm that spreads only through PLC. No PC or server required. The worm can be brought into the station through an already compromised PLC. The virus spreads to the following PLCs by copying itself and thereby infecting the remaining PLCs, working simultaneously with the user program.
The experiments were carried out on Siemens SIMATIC S7-1200v3. The virus was written in the programming language ST.
2. Related research areas
2015, BlackHat, USA 2015 - demonstrated a mailbox running on a PLC .
They implemented an intermediate server using the communication capabilities of the PLC. We use similar capabilities to implement the protocol used to spread the virus program. Using this protocol, the worm can spread directly from the PLC to another PLC. The worm does not require further support from the system. Instead of using the already well-known Simatic S7-300, we used the new S7-1200v3 in our work.
3. A bit about PLC architecture
The controller architecture is simple. It is based on a central processing unit (CPU) and additional expansion modules for digital and analog I / O. The CPU is responsible for starting and managing the PLC operating system and runs the user program. Also, the CPU is responsible for communication (switching) with additional devices and controls the process.
The process image stores the status of all inputs / outputs. The user program starts in cycles. The process status is updated by the CPU at the beginning and at the end of each cycle. The cycle is limited by cycle time. If the limit is reached, the PLC stops the user program and gives an error.

The user program consists of Program Organization Units (POUs). They contain instructions for monitoring and controlling the PLC. The program for Siemens SIMATIC S7-1200 consists of:
- Organization Blocks - Organization Block (OB) - Where the user program is entered.
- Data Block (DB) - Data block - global memory.
- Function (FC) - functions
- Function Block - functions with stored local memory.
This article also uses the TCON and TDISCON system functions. Using these functions, you can initialize or terminate a TCP connection with an arbitrary system. Data can be sent and received using the TRCV and TSEND commands.
4. Computer worms
Computer worms have been known since 1988 and are a well-known type of malware. Each virus attack can be described by the following phases:
- determination of a possible target
- distribution to the target
- use of the target
- execution of malicious code
On the PLC, the worm must perform the same functions. The article demonstrates the implementation of each of the necessary steps.
5. Virus implementation for Siemens SIMATIC S7-1200
5.1 Architecture
Like any other worm, the virus was written with some features. During the development, specific limitations and conditions of the PLC were taken into account. The condition of not violating the maximum cycle time must be met. The virus should interrupt its execution for several milliseconds. Execution can be continued during the following cycles. At the beginning of each cycle, the virus code was called again. This allowed us not to violate the maximum cycle time.
The phased execution of the code is shown in the image below. The execution of the virus began with the initialization of the connection with a possible purpose. First of all, after the connection, the virus checked whether the target was already infected. If no infection was detected, then the virus stops the user program for the purpose in order to allow the transfer of its own code.
After copying, and directly launching the infected PLC, the worm continues to search for the next possible target.

5.2 Search and target definition
The virus starts scanning to find possible targets. Siemens SIMATIC PLCs can be recognized on port 102 of the TCP protocol. This port can be closed using an external firewall. No other service uses this port. S7-1200 initializes a TCP connection using TCON. The use of this command is shown in Listing 3, line 4. The IP address and port are written in line 9.
As soon as the unit is called up, the PLC will try to establish a connection. This happens asynchronously. In the following cycles, the connection status is confirmed. Return value DONE (line 5) - indicates whether a connection has been established. If TRUE, the infection continues. If the IP address and port are unavailable, no error is displayed. Each cycle increases the counter by 1.

If after 200 cycles the connection has not been established, the worm executes the following code. Although no connection has been established, the TDISCON block is called to clear the line for the next connection. In line 13, the IP address is incremented. Thus, all 24 subnets are scanned for an open port 102 / TCP.

5.3. Infection
During the infection phase, the worm copies itself to the attacked PLC. Typically, the software is downloaded to the controller using the Siemens TIA-Portal software. The worm mimics under TIA-Portal and implements the proprietary Siemens protocol. For the analysis of the protocol and its subsequent implementation, we used Wireshark.
5.3.1. Transmission Protocol Description
In this article, the protocol will be called S7CommPlus. This is a binary protocol that uses the TPKT and ISO8073 protocols. Both of these protocols use port 102 / TCP.
Main features of S7CommPlus:
- PLC control
- Start / Stop PLC
- Reading and writing variables
- Transfer of the program (loading / unloading)
- Debugging
- Providing Debug Information
- Accident Notification
5.3.2. The code
Each message used by S7CommPlus has the same structure. The picture №5 shows the first message to the connection. TIA Portal sends this message to initiate the connection. Let us explain the general structure. The first 2 highlighted fields are TPKT and ISO8073 protocols. Their contents are described in the relevant documentation. The next byte 0x72 represents the beginning of the message from S7CommPlus. The version number differs between different protocol options. Field length does not take into account frame boundaries. If there is no frame boundary, subsequent data is transmitted in additional messages. After the length of the field, the cell type is passed. The subtype further defines the messages. The sequence number is incremented by 1 for each message. Additional data is transmitted in the form of attribute blocks (attribute blocks).

5.3.3. Attribute Blocks (Attribute Blocks)
Data is generated according to the following block attributes. Picture 6 shows the first attributes of the previous picture. Each attribute begins with byte 0xA3. This block contains a string. A string begins with its length and contains a value.

5.3.4 Value Encoding
In attribute blocks, values are encoded in a special way. The value may have a variable length. The first bits of each byte are moved to the beginning of the next byte. Figure 7 explains the decoding of the attribute identifier and field length from the previous example. If the value is stored inside the attribute block, then encoding is not applied.

5.3.5. Anti-snooze mechanism
S7CommPlus protocol defines anti-replay. To do this, the PLC sends a random value of 25 bytes in the response message. The value is defined between 0x06 and 0x7f. The anti-retry byte is calculated using the following formula.

All further messages sent by TIAPortal must use anti-retry bytes in their 24 bytes. Grayed out attribute blocks should also be displayed.

5.3.6. Program transfer
A special message is used to transmit the program. (Picture 10). Each message carries one POU. The block number indicates the location in the PLC memory.

Several attribute blocks make up the message header. In addition to the actual bytecode, meta-information is recorded in S7. This meta information determines the required memory (necessary), the block creation date, the block number, the language used, the source code and the functions are protected. TIA Portal may use this information to verify the code.
5.3.7. Identify Required Messages
During the transfer of the user program, some messages are exchanged that are not required for the process.
These inappropriate messages increase the memory required for the virus, so you can skip them. Figure 11 shows the necessary messages for a successful injection.
Transfer started. In order to avoid re-infection, the virus checks the target and tries to download a copy of itself. Downloading additional code is only possible after the PLC is stopped. When the program is loaded, the PLC starts again.

5.3.8. General implementation
Based on the analysis of the protocol, the program transmission can be recorded, changed and sent again to the PLC. All necessary messages are known.
To store commands in a virus, we use a static global data unit (DB). Additional DBs are used to store temporary variables and as a transmit / receive data buffer. The constant block given stores all messages necessary for an infection. This block cannot be generated using TIA Portla and must be written manually.

6. The launch of the virus
The transmitted code is added to the user program already running on the PLC. Additional OBs and required DBs are added. The user program code is original and not corrected. The OB block is automatically detected by the PLC and executed.
habrastorage.org/files/7d7/479/d4c/7d7479d4c7ba4fbdbde958ed124016ca.png
7. Performing malicious functions
During the functioning of the virus, we implement various functions to demonstrate the possibility of the influence of the virus.
7.1. Command & Control Server
(Server management and control)
Our worm will try to connect to the C&C server. The communication protocol is TCP. Through the C&C server, you can organize the execution of various functions.
7.2. Socks4 proxy
After the worm connects to the C&C server, connections to additional clients in the PLC network can be initiated using the built-in Socks4 proxy.
7.3. Service Failure
Operation (PLC code execution) may be stopped due to violation of the cycle time. The worm executes (implements) an infinite loop that starts the error state in the PLC (DoS attack).
7.4 Manipulation of output signals
The worm can control the output of the PLC. When using the POKE system function, various variables within the process can be changed.
8. Detection of the virus. Counteraction. Resources for the Worm
8.1 Virus Detection
8.1.1. TIA Portal
TIA Portal can verify the user program in the PLC and can detect changes as well as adding various functions (POU elements). (Picture 14). Red highlighted area of functions that are used by the virus. The analysis of these functions is not possible, because the TIA Portal only parses the XML code. In addition, through the use of TIA Portala errors, the worm can cause an application crash, crashing.
8.1.2. PLC stop
For infection, the PLC must stop for approximately 10 seconds. The user program will not be executed at this time. Interruption can be seen and logged in to the PLC.
8.1.3. Network traffic
The worm generates unusual network traffic. Many suspicious packets are sent during the phases of network scanning and target infection.
8.2 Counteraction
8.2.1. PLC restart
Since the virus is in the memory of the PLC and is part of the user program, the worm will remain in the device as a result of restart or power outage.
8.2.2. Reset to factory settings
Through TIA Portal, you can return to the factory settings, which will lead to the complete deletion of data from the PLC, including the worm.
8.2.3. Download program
The worm is written to the OB9999 block, when overwriting this block, the worm will be deleted.
8.3. Resources for the Worm
8.3.1 runtime
The maximum cycle time is hard-coded in the settings. By default, the limit is 150 ms. The worm must not violate this limit. We measured the PLC cycle time without any user program - it is 0 ms. Then we infected S7 with our worm and measured the cycle time again. The maximum measured cycle time is 7ms. This is 4.7% of the allowable limit.
8.3.2. Memory
The worm requires 38.5 KB of RAM for storage. 9 KB (23.3%) is required to execute malicious code. Additionally, 216.6 KB of flash memory is required. The table displays the available memory in various models.

9. Protection features
PLC S7-1200v3 offers 3 different protection functions. We will analyze each of them and evaluate whether they protect the PLC from the injection of the virus. The analysis is based on TIA Portl V11, Update 5 and S7-1200v3 with firmware 3.0.2
9.1. Knowhow Protection
Knowhow protection protects the user program from unauthorized access, without a valid password, unauthorized access and modification of program blocks is impossible. Knowhow protection is implemented using attribute blocks. These blocks are written to the PLC during program loading. The blocks are shown in Figure 15. The stored password hash generated from password P is calculated using the following formula:

TIA Portal evaluates the block attribute. If the flag is set, the TIA Portal prohibits reading and writing information to the corresponding blocks without the correct password. PLC source code is encrypted using AES128-CBC. This prevents access to the code. Figure 16 shows the encrypted source code.

9.1.1. Method Vulnerability
Lack of integrity check. The block can be read and modified despite knowhow protection. Protection is implemented by TIA Portala, not PLC. When using independently written tools for reading and writing blocks on the PLC, any access is provided. Even the knowhow protection flag can be reset as a result of access using TIAPortal. AES-key can be retrieved or retrieved. The key for the encryption name can be obtained from the password hash. The password hash can be read using self-written software. The key is calculated using the following formula:

* fixed by the manufacturer SSA-833048
Conclusion: This protection does not help against the virus.
9.2 Copy protection
Copy protection prevents duplication of the user program on the second PLC. The serial number of the target PLC is stored in the user program to prevent the user program from loading through the TIA Portal to another PLC. The serial number is stored in a separate attribute block.
9.2.1. Method Vulnerability
Attribute block integrity is not protected. A stored serial number can be changed, moved, or deleted. The PLC does not check the serial number itself. Verification is only possible with the TIA Portal.
* fixed by the manufacturer SSA-833048
Conclusion: This protection does not help against the virus.
9.3. Access protection
Access protection prevents access to the PLC using the S7CommPlus protocol without a password. 3 different levels of protection are available. The table shows various levels of protection:

Authentication uses a mechanism - a response to a request.
Conclusion: Access protection can protect the PLC from virus attacks. Write protection prevents any code change in the PLC. Using a request response mechanism is relatively safe. If the password used is not known, the worm cannot infect the PLC. By default, access protection is disabled.
10. Conclusion
In this paper, we demonstrate the capabilities of a worm for a PLC. Such a virus poses a new threat in industrial networks. Traditionally, such networks are well protected from outside attacks. With the introduction of already infected worms, PLC makes other devices not only the target of the attack, but also the source of the attack. Infected PLCs may be distributed by distributors, or infection may occur during transport. The worm can spread inside the controller and does not require any standard PCs or servers. Thus, it cannot be detected by antivirus. Moreover, the operator has very few opportunities to detect malicious code in the PLC.
From the author of the translation
Как известно, на каждую хитрую гайку, найдется свой болт с резьбой. Лично автор считает, что проблема безопасности промышленной автоматизации слегка раздута, по причине отсутствие единой унифицированной среды для выполнения вредоносного кода на различных ПЛК разных производителей. Ориентация на Siemens, Allen-Bradley, Honeywell, B&R и т.п. производителей ставит задачу написания вируса под строго определённое устройство.
В целом, принцип распространения вируса внутри сети состоящей из контроллеров, базовых/инженерных станций и панелей управления — заслуживает отдельного внимания. К тому же, пример StuxNet'а вроде и показал миру возможную ситуацию развития событий. Как и зачем была реализована атака — вряд ли узнаем. Но все так любят приводить его в пример…
В современных реалиях боthe greatest threat is lack of care in the performance of work and subsequent maintenance. The profession "Automated Process Control Programmer", "Automated Control System Programmer Programmer", etc. is also becoming very widespread. leading to a growing number of low-skilled personnel.
So while we are scared by the future industrial Skynet, we must remain attentive to the executable code.