An unsupervised and hierarchical intrusion detection system for software-defined wireless sensor networks

Wireless sensor networks are considered as the foundation of the Internet of Things. Inherent problems in wireless sensor networks such as power consumption, lack of flexibility, and disability in development and programming have led to serious challenges in these networks. Software-defined networking (SDN) is flexible with development and programming capabilities that decouple the control and data planes. The combination of wireless sensor networks and software-defined networks has created the idea of software-defined wireless sensor networks (SDWSNs). Security is considered as one of the most fundamental issues in any network. Due to their combinatorial nature, the software-defined wireless sensor networks faced a variety of security challenges for both wireless sensor networks and software-defined networks. This paper proposes a novel architecture with an unsupervised intrusion detection algorithm using a hierarchical approach to improve the security of integrated software-defined wireless sensor networks. In the proposed architecture, the sensors are not fully dependent on the SDWSN controller; instead, they run the appropriate intrusion detection algorithm module locally at the layer. The data analysis results in different zones, produced by clustering based on entropy and cumulative point similarity as criteria, are sent to the SDWSN controller, and decisions are made after the final check of data normality or abnormality. To examine the effectiveness of the proposed architecture and algorithm, the sensors were simulated on Cooja, WSN-DS and NSL-KDD standardized datasets. The results show that the proposed method is able to detect the abnormal traffic up to 97%.


Introduction
The evolution of the Internet of Things (IoT) idea has highlighted the role of the wireless sensor networks even more than before, leading to more studies being conducted on this subject. Applications of this network are not limited to the Internet of Things and can even be extended to the intelligence for various services such as agriculture, administration, forestry, and military services [6]. The inherent problems with these types of networks which is related to processing and memory resources, bandwidth and energy make the development of wireless sensor networks more difficult. Furthermore, the lack of flexibility and the programmability as well as the management complexity have made wireless sensor networks less effective in the Internet of Things [8,11,25]. As an efficient and supportive network, software-defined networks have been combined with a wireless sensor networks to cover some of their weaknesses, resulting in an innovation called software-defined wireless sensor networks (SDWSNs) [18]. Extensive studies have been conducted on combining wireless sensor networks and software-defined networks to improve the efficiency of this integrated network in smartification and the Internet of Things [20]. In software-defined networking, the data plane is decoupled from the control plane in the equipment. The data plane equipment is commonly referred to as a switch, which is controlled by the SDN controller in a centralized or distributed manner [10]. Such separation of planes has provided certain capabilities such as integrated management of heterogeneous equipment, centralized programming, and improved reliability [10].
The most important component of a software-defined network is the SDN controller, which is responsible for processing and communicating with the higherlevel application software for decision-making on network traffic. The communication between the SDN controller and the switches is done through a secure and encrypted channel. The communication between the SDN controller and the application software takes place via an application programming interfaces (APIs). Generally, the responsibilities of the SDN controller include routing, security and protection decisions, resource access control, load distribution, and intrusion detection.
In order to achieve the highest level of software-defined network performance on heterogeneous equipment, the OpenFlow protocol has been employed to establish communication between the SDN controller and the switches. This protocol is flow-based and updates the flow table in the switches. In the switch flow table, there are a number of flow matching parameters to examine incoming packets and match them against flow parameters, counters, and interactions (switch responses to incoming packets based on the SDN controller decisions) [8]. In a centrally designed software-defined network, there are two areas of serious security threats [8]: the threat of centralized SDN controller, and the threat of control of the entire network by software, which that may be the result of malfunctioning or encryption errors. In SDWSN, frequent traditional attacks, such as penetration into a management station to gain control over this integrated network, are also possible. DDOS attacks, information theft, information interception, and spoofing 1 3 affect network performance and quality. Since the SDN controller operates in a centralized or distributed manner, the intrusions related to the OS layer and the control plane encryption are also concerns of the integrated software-defined wireless sensor network. At the data plane (switches), we face the threat of spoofing and malicious traffic. Malicious users and faulty sensors generate malicious network traffic that decrease the efficiency and lifetime of the network depending on the type and volume of the malicious traffic generated [1]. Sensor infiltration has also added to the security problems of the integrated network. Various sensors with different architectures and different brands and the heterogeneity in the wireless sensor network cause weaknesses in the overall network security [8]. Wireless sensor networks, as one of the components of SDWSNs, face serious security threats. Intrusion detection systems are widely used as a security backup solution in various computer networks, to protect networks by identifying attack types, attacker profiles, targets, and attack layers [37]. The intrusion detection systems are categorized into two categories based on the detection methodology and facing attacks, namely anomaly-based and misuse-based. There are some sub-techniques of categories under each of the mentioned methods for specific purposes such as anomaly-based IDS with machine learning, statistical model, or deep learning [35]. In the first category, intrusion detection is carried out by modeling the normal behavior of the network. The normal practices of network services are stored over time as normal behavior profiles in the system and are reported as abnormal behavior by observing the traffic when behaving outside of the stored standard profile. This high-performance method is particularly applicable to unknown attacks. In the second methodology, the behavior of previously known attacks is stored as a profile and pattern in the system. For example, the pattern of more than three attempts to log in within five minutes is stored in the intrusion detection system as a Brute Force attack. The advantage of this methodology lies in the accuracy and speed of intrusion detection based on previously stored knowledge. However, this method has proven to be ineffective in detecting new attacks [23]. Anomaly-based IDS can play a significant role in SDWSN security. In the sensor layer of SDWSN, we are faced with the lack of online traffic analysis tools and it might be put the network in danger. Blackhole, Sinkhole, and MITM node attacks can occur because of this weakness. By using the ability to detect new and unknown attacks in the anomaly-based IDS and the distributability of this system, allows security to be implemented in a distributed manner across different layers of the SDWSN.

Problem Statement
Security is just as important as the architecture of the SDWSN network infrastructure, and it remains one of the core issues open to research [8]. Although the combination of SDN and WSN leads to increased efficiency, improved management, and the development of wireless sensor networks; it seems that emerging security challenges need to be addressed seriously, and appropriate solutions must be offered. IDS as a comprehensive solution in attack detection can play an important role in covering SDWSN security challenges. These problems motivate us to investigate a generalized architecture combined with IDS for SDWSN. The proposed architecture utilizes an appropriate anomaly-based detection algorithm compatible with the limitation of WSN.

Contribution
The current paper presents an architecture with an anomaly-based intrusion detection system to detect malicious network traffic. SDWSN is the new idea to combine wireless sensor networks and software-defined networks. Due to the need to provide security in SDWSN, the proposed security architecture carries out data classification at different levels of the SDWSN. It works in a non-parametric and unsupervised manner and reports the results to the upper layer. Then, the control plane will decide whether the traffic is abnormal or not. In the generalized architecture with a security approach, the sensors do not have complete process dependence on the controller plane. The local intrusion detection module is implemented in them. This module is responsible for reporting the results of the processing to the controller plane. This improves the speed and the accuracy of attack detection at the controller plane. The main contributions of this paper are as follows.
-Proposes a suitable anomaly-based detection algorithm for sensor networks.
-Presents Distribute intrusion detection algorithm on controller and sensors layers. -Presents a non-parametric data classification at different layers of SDWSN architecture.
Experimental results show that the proposed security architecture to protect the SDWSNs against abnormal traffics has acceptable performance and can detect up to 97% of the anomalies. Moreover, the energy consumption in executing the intrusion detection algorithm over the sensors does not impose much energy consumption overhead compared to the normal sensor-to-sensor process. The structure of this paper is as follows: Introduction and necessary definitions are presented in Sec. 1. Section 2 consists of an overview of previous studies on this area. Section 3 describes the proposed method and security architecture for SDWSN. Results of the tests and outcome of the simulations are analyzed in Sect. 4. Finally, conclusion is made in Sect. 5.

Related works
The inherent problems of the wireless sensor networks along with their complicated management and development constraints have led to the use of SDN networking capabilities in WSNs. To implement this integrated network, various architectures have been proposed by researchers. In this section, security-based wireless sensor network architectures are discussed. In general, the architecture with a security approach to integrating wireless sensor networks into software-defined networks should address the following considerations: -Hardware level in which sensors are the main infrastructure of this integrated network. Sensors consist of hardware and software components, including radio transmitters, sensing modules, power supplies, and the hardware addresses [16]. -The control plane which has various responsibilities including information flow constraints, access control and protection of the network, communication with application software modules and hardware modules, network topology control, ensuring the quality of service, and integrated management of the network. The responsibilities of this module increase with the growth of demands and the advent of new needs [9]. The control plane can operate in a centralized or a distributed manner.
In [15,24], the sink is considered as the control plane, which consists of five layers: physical, media access, network operating system (NOS), middleware, and application. The middleware in this proposed architecture includes a centralized controller, flow management, topology control, and security. In order to protect the network, the controller must constantly monitor the status of the sensors and receives information about the sensors' energy levels, the distance of the sensors from the base station, the neighbor list of each sensor, and the response time through monitoring massages. The tasks of the application layer are the location and mobility control of the sensor. In [32], a centralized and decentralized intrusion detection algorithm for WS-SDN based on the CP (Change Point) theory is presented. The IDS algorithm is suitable for DOS attacks, and the method monitors the control packet overheads and the data packets delivery rate of the network. If the application detects a change in the statistical properties of any of these metrics, the network is considered under attack. In their distributed method, every node is in charge of detecting a change in its own metrics. They used IT-SDN for simulation and testing. They achieved 96% detection rate in the centralized and 89% detection rate in the distributed method. In [8], a general architecture for a SDWSN is outlined. This architecture was proposed to focus on the analysis of the design and implementation requirements of the network that is impractical and simulated. However, it provides researchers with a comprehensive and realistic overview of the basic requirements for deploying a SDWSN architecture. In the comprehensive architecture [8], similar to the softwaredefined network, three general layers are considered, and for each layer, the general modules are analyzed with the existing protocols and standards. In this method, the specific requirements of the architecture were not considered in detail. Nevertheless, the distribution of the required modules in each layer gives an idea of designing of efficient architecture. Another architecture is presented in [3], which has capable of developing security for the integrated SDWSN. The core is responsible for controlling and coordinating all other components. The main focus of this approach is the reduction of energy consumption, but also software architecture capabilities and security capabilities are also observed. Neighbor control discovery, identification protocols and reduced routing overheads cover the primary security requirements as a potential feature of this architecture. On the other hand, its implementation on the IPv6 protocol stack supports network layer security capabilities. In [7,17,27], the DDOS detection method was based on machine learning techniques and all of them obtained a detection rate over 90%; however, none of these researches considered resource constraints. The main reason is that these require a lot of traffic for monitoring and learning. Bhunia and Gurusamy [7] and Ravi and Shalinie [27] proposed an attacker identification mechanism where Jia et al. [17] presented the attack types detection algorithm. A secure architecture with sensor admission capability and symmetric key in the entire network is presented in [36]. Cryptography and security algorithms were modified with integrated software-defined network protocols, and the framework templates were modified to conform to physical layer sensor network standards. In this architecture, the sensors are not fully dependent on the control plane, and they run the RELIC module (a C library for elliptic curve arithmetic) [5].
A Key Generation Center (KGC) is responsible for generating symmetric cryptographic keys based on the iSMQV key agreement protocol [34]. Then, to establish a secure connection, the sensor sends the authentication request to the control plane. The control plane executes the detection and identification modules of the sensor and responds to requests. Upon delivery of the control plane response to the sensor, the password delivery packet is sent by the sensor to the KGC, and the KGC queries the sensor for identity information from the control plane. After confirmation by the control plane, the password is sent to the sensor. Communication between the control plane and the sensors takes place via the encrypted channel using the key generated in the KGC. This method is designed to secure the connection between the sensor and the control plane and is able to detect network attacks. On the other hand, due to the heavy and repetitive process of authentication, encryption, and decryption, it imposes significant processing overload and memory on the sensor and control plane. In the reviewed studies, the security in the SDWSN has been considered as a significant issue, also some researchers discuss it, and it colorblue remains a challenge for this integrated network [18]. For instance, in [26,31], layered architectures for integrating wireless sensor networks and software-defined networks have been proposed, but security concerns have not been addressed. In the current paper, security is considered in conjunction with an approach to intrusion detection as the main idea of the proposed architecture. In [21], a software-defined security framework for wireless sensor networks is proposed. This framework combines intrusion prevention with a collaborative anomaly detection system. In the data plane, to provide lightweight intrusion prevention, an IPS-based authentication process is designed. A smart monitoring system for intrusion detection system in the control plane is exploited. In [38], a software-defined mission-critical wireless sensor network (MC-SDWSN) is proposed. MC-SDWSN can solve the existing challenging issues in traditional WSN such as resource utilization, data processing, system compatibility, and strict latency requirement. The architecture is based on the idea of SDN architecture, which combines hierarchical cloud and edge computing technologies. Our proposed architecture with intrusion detection algorithm is able to detect malicious attacks at different layers of the sensor networks. In the proposed method, to increase the accuracy of the intrusion detection, the sensors have an independent security module. They analyze the collected information and send their analysis and diagnostic reports to the controller. Finally, at the controller, the security decision module will report the normality or abnormality of the traffic based on the local analysis and the analysis received from the sensors. The proposed architecture is an efficient solution for protecting SDWSNs with an intrusion detection approach.

Proposed SDWSN architecture
The proposed method is a generalized architecture with a specialized and efficient approach to intrusion detection implemented in an integrated manner on the controller and SDN sensors. A network attack usually results in abnormal behavior. A network attack usually results in abnormal behavior. Identifying abnormal behavior requires data classification and calculating the density and distance of each data point from the observations collected by the sensors. This is carried out via zoning and comparing with the entropy of the cumulative points which has a threshold value derived from the given statistical specifications. The modules used in the proposed architecture were developed with a general focus on SDWSN services and with a particular focus on the anomaly detection module.  The proposed architecture operates in an integrated manner on the controller and the sensors. In this architecture, the sensors are not colorbluefully dependent on the controller to extend the lifetime of the network and to improve the accuracy of the intrusion detection algorithm. In addition to the controller, a part of the intrusion detection algorithm is implemented locally on each sensor. The proposed intrusion detection algorithm can be executed in centralized and distributed manners. The knowledge of the system topology and the sensor distribution as independent modules is stored in the controller. The intrusion detection algorithm is implemented as a layer in the proposed architecture, and then, the result is reported to upper layer. Finally, the controller will decide whether or not the traffic is abnormal upon receiving the results of the calculations from each layer. Figure 2 depicts different modules of the proposed architecture. As depicted in Fig. 2, the proposed architecture consists of application, controller, and sensor layers. The controller layer contains: Sensor Neighbors Watchdog (SNW), Received Signal Strength Indicator (RSSI), routing and forwarding, and intrusion detection module. The sensor layer includes: Neighbor discovery, sensor routing, RSSI send and receive modules and sensor intrusion detection module. Figure 3 shows the timing diagram of the proposed anomaly detection system. When a packet arrives, the sensing element (hardware) checks the flow  status of the flows that packet belongs. If the packet is not in the blacklist flows, the intrusion detection system examines it and decides to mark it as suspicious or normal traffic. If the intrusion detection algorithm decides to mark the packet as suspicious, it updates the flow table and checks the suspicious fields. Then, the routing and forwarding module is called and the suspicious packets are sent by the default route, the packets are sent to the controller and delivered to the intrusion detection module within the controller. This module finally clears the status of the delivered packets as normal or abnormal. Forwarding module drops the abnormal packets or sending back the normal packets to the sensor to be forwarded as normal traffic.

Controller module
The controller is the most important element in the SDWSN network that is responsible for the infrastructure and the provision of services. In the proposed architecture, the controller consists of the following modules based on the general network services and the specific intrusion detection service.

Sensor neighbors watchdog (SNW)
This module is responsible for collecting neighbor information stored in each sensor. Information is validated based on each node's distance from its neighbors.   If the reported distance of a neighbor exceeds the range of the sensor coverage, the controller sends the disconnection packet to the sensor, and the communication between the sensor and the neighbor is disconnected. In the proposed architecture, this process is considered in the application layer, which sends the commands to the sensors by the ID component for each sensor (a random number).

Received signal strength indicator (RSSI)
This module is responsible for calculating the location of the sensors and the coverage range of each sensor. The main criterion is to estimate the distance from the transmitter to the receiver using the power of the received signal, knowledge of the transmitter power and the loss model. We use the Log-Normal Shadowing model as loss model [40] in the proposed architecture which is presented in Eq. (1) where P(d) is the received signal power loss (in dBm), and d is the distance between the transmitter and the receiver. d 0 is the reference distance usually 1 m. P(d 0 ) is the path loss (in dBm) at the reference distance. n is the path loss exponent. And X 0 is a zero mean Gaussian random variable that reflects the random variation of the path loss. This calculation, which is assembled and computed at the beginning of the network configuration (at the time of the initial configuration, is not considered a strike), is stored in an array. After detecting anomalies in the network, the controller sends the attack packet to the sensor. This module waits for the sensor to fully execute the attack packet and forwards the attack packet to the rest of the sensors involved with the malfunction and then reported back to the controller by the sensors to rearrange the arrays after the attack has been reported and resolved.

Routing and forwarding
In general, sensor packets are routed through a default route on the sensors to the controller. If any of the default route sensors are switched off, the controller updates the new route on the sensors. The controller is responsible for providing the most optimal route as the default route on the sensors based on the distribution of the sensors and the topology of the network. Neighboring sensors help route each sensor packet to the controller. This module has a significant dependency on the intrusion detection module. If the controller detects a sensor-level anomaly and intends to disconnect the sensor in the network, by sending a special packet containing the malicious sensor ID, it notifies the sensors of the malicious sensor node and updates the packet-sending path. It also set a timer (descending with a default value of 120 s) as age and updates the sensor flow table with the blacklist malicious node id and blacklist timer (age).

Intrusion detection module
This module performs its layer-by-layer calculations based on the information received from the sensors, including the result of calculating data anomalies at the sensor level, and ultimately decides on the data from a security perspective. In order to increase reliability, reduce computation, and extend the lifetime of the sensor network, a list of data behaviors is stored in this module for faster detection and decision-making in subsequent computations. A full explanation of the process is given in Sect. 3.4. If a flow is known as abnormal traffic, this module updates the sensor flow table and sets the blacklist flow field.

Sensors modules
In general, the sensors in the SDWSN architecture are completely dependent on the controller and receive commands from it for all their processes. However, in the proposed architecture, the following modules are considered locally on the sensors to increase the accuracy of intrusion detection and to extend the network lifetime. Considering the sub-modules (functions) designed in the proposed architecture, in addition to the public services of the SDWSNs, the sensors execute the traffic analysis process with an intrusion detection approach in their layer.

Neighbor discovery
At the beginning of the network configuration, the sensors store the initial neighbor information as valid data (before an attack occurs). If the sensor detects a change in the number of neighbors or the level of normal neighbor behavior (based on the intrusion detection parameters) during the lifetime of the network, the module is responsible for generating a report packet and sending the new information to the controller promptly.

Sensor routing
This module is responsible for routing and forwarding the packets at the sensor level. The sensor-level routing module is updated by receiving routing information from the controller routing module. In control-dependent delivery, all other sensors transmit the information collected by one sensor to the controller. For the critical packets such as suspected packets (when the suspicious status in the flow table is true), a default route is set by the controller on each sensor. All other sensors forward the packet to the controller on each sensor's default route. This module is also responsible for disconnecting the sensor from the malicious sensor reported by the controller, which not only disconnects its communication with the malicious node, but also instructs normal neighbors to disconnect the malicious sensor.

3
An unsupervised and hierarchical intrusion detection system…

RSSI receive and send module
This module is responsible for controlling the sensor's communication with its neighbors. Upon receiving of the attack packet from the controller, it analyzes the packet destination sensor and, if the packet destination is the sensor itself (based on the identifier assigned to each sensor), it sends the packet to the sensors which the controller has identified as abnormal. If the attack-packet destination was not the receiving sensor, this module is responsible for the delivery depending on the sensor layout routing module. The neighbors table is rebuilt on each sensor.

Sensor intrusion detection module
In each sensor, a controller-independent intrusion detection module is designed based on the proposed intrusion detection algorithm, which performs the initial calculations and reports them to upper layer. The distribution of the intrusion detection algorithm on the sensor layer and the controller improves the accuracy of the detection and the lifetime of the sensor network. If this module is suspected for traffic, it updates the flow table and set the suspicious status to true. The proposed algorithm is described in more detail in the next section.

Proposed intrusion detection algorithm
When a packet arrives, the sensor checks the flow table for blacklist flow status. If the packet was not a part of the blacklist flow traffic, the intrusion detection algorithm would run. The proposed intrusion detection algorithm is an algorithm with non-parametric and unsupervised segmentation, which uses the similarity of cumulative points and entropy. This algorithm is implemented in layers, and in each layer, the available information from the same layer is analyzed without any prior assumptions. A controller with an intrusion detection module is responsible for the final decision on network anomalies. Moreover, the sensors accelerate security computations by an on-level anomaly computing module and improve the accuracy of detection in the network.

Data plane granularity
The vector X = [X 1 , X 2 , ..., X i , ..., X n ] shows a set of observations, where each observation consists of m items including X i = (X i1 , X i2 , ..., X im ) , then the closeness criterion among two data points is calculated in the following Arakn and Ahmadi [4]. In this calculation, the exponential function is used for normalization based on Eq. (2). The Euclidean distance (D ij ) among X i and X j is calculated from Eq. (3) and has a value in [0, ∞] . Therefore, this distance is normalized based on Eq. (2), to be mapped in the range [0, 1].
To calculate the closeness, the value of can be achieved by replacing S ij with 0.5 and D ij with the average distance of all the given data point pairs in Eq. (2). Therefore, is obtained using Eq. (4) based on the available data distributed in the data set. The component D in these equations is the average distance of all the given pairs of data points in the data set. Fig. 4 shows a sample chart of closeness calculated on a sensor node, and Fig. 5 presents a sample entropy chart of the data points on a sensor node.

Accumulative point calculation (ACCPCALC)
Based on the above explanation, the cumulative point similarity, which is used as a new criterion to distinguish the normal points from the abnormal ones in the intrusion detection algorithm, is calculated from Eq. (5) for each data point X i .
To calculate the entropy value ( e ij is the entropy value between two data points) between two data points X i and X j , Eq. (6) is used.
In addition, the entropy value of the cumulative points for each observation is determined as follows:

Data classification
To classify the data points, the proposed algorithm calculates the sum of the entropy of the summation points and the sum of the similarities of the cumulative points for each time window ΔT at each node for each data point using Eqs. (5)-(7). As stated above, it can be assumed that the points (here the points refer to the results of the calculations we have performed on the collected data. The sums of the entropy of the cumulative points and the sum of the similarities of the cumulative points are effective for us as the center of the regions. These are the same computational results as previously described) located in the heart of dense and sparse areas, have a small value, and the points located in dense, compressed areas have large values. This criterion can represent the density of points around a data point and their position relative to the size of the dataset. Assuming that most of the points in the dataset are normal points, it can be concluded that the abnormal data points are similar to low cumulative points and high cumulative entropy points, and the normal data points are similar to high cumulative points and low cumulative point entropies. By dividing the sum of the similarities of the cumulative points by the sum of the entropy of the cumulative points, the criterion for the classification of similar data points is obtained. We will show this criterion for each data point X i with R i . The set of R i = (R 1 , R 2 , ..., R i , ...R n ) is calculated for every data point X i ∈ X as follows: R i is a small value for points in an isolated area (abnormal data points) and a large value for dense areas (normal points). The classification algorithm works as follows: Initially, the smallest value of R i is selected, and points whose distance from it is about a standard deviation will all be grouped together and removed from the dataset. Perform this recursion for all parts of the dataset. As a result, the data space is divided into areas for the detection of abnormal and normal points. To minimize the impact of noise and outliers and to improve data mapping in certain areas, the outliers are first removed. A data point X i ∈ X is a point out of the dataset if the calculated S i for that point is less than five percent of the mean of the S i of the whole node. At the end of each ΔT time window, each sensor node performs anomaly detection to determine the status of each region after segmenting the data space into the desired area. In order to improve the accuracy of the detection, abnormal behavior can be performed at the sensor and controller levels.

Data plane anomaly detection (DPAD)
To detect the sensor-level anomalies, first, the mean of S is and e is of the resulted areas is calculated. The ratio of these two values is separately calculated for each area. E = {E 1 , E 2 , ..., E i , ..., E k } is the set of resulting areas in a node, and K is the number of available areas for that node. For each area, the number of areas which are, respectively, called Ē e i , and Ē s i is calculated and the set R is obtained in each node as follows: To detect abnormal behavior in an area following steps must be done: An unsupervised and hierarchical intrusion detection system… -If all the calculated values of the set R from Eq. (10) are less than 1, the abnormality behavior is not there in the set. If some regions have R i values larger than 1, and some regions have R i values less than 1, the region with R i becomes greater than 1, they are probably abnormal and the next step must be checked.
-The mean of Ē s i of the regions is calculated and if this value of a region is as much smaller than the mean value, the region is recognized as abnormal.

Control plane anomaly detection (CPAD)
In order to detect anomalies in the controller, after segmenting the data and identifying abnormal areas in the sensors, information about the mean local data of each area and the local data that have been recognized as abnormal are sent to the controller. At this level, the R i values are averaged, and any area whose R i is less than a standard deviation smaller than the mean is reported susceptible to malformations and condition 2 in Sect. 3.4.4 will be implemented. If an area in the previous level is detected as a normal area and the new level is identified as an abnormal area, the controller requests the sensor to send all data points to that area. Accordingly, anomaly detection at each level of the network is evaluated with different levels of accuracy.

Simulation and experimental results
To evaluate the efficiency and simulation, the Contiki operating system and the Cooja simulator were used. Tmote Sky sensors were simulated. The Radio interface cc2420 protocol was used for communication. The RPL routing protocol (Routing Protocol for Low-Power and Lossy Networks) on the IPv6 platform was also considered a third layer service. Each layer of the proposed architecture has a traffic anomaly detection module, which based on the descriptions provided in Sect. 3.4, identifies the normal traffic layers from the anomalous traffic and reports to the higher layer. In the data modules, in addition to the modules described in Sect. 3.3, all sensors are equipped with standard modules such as data aggregation, flow table, and SDN-enabled. In the controller module, the modules described in Sect. 3.2 and the standard SDWSN modules, along with the specialized IDS decision-maker module, are designed to detect malfunctions.

Topology
To implement the simulation, a topology of 10, 50, and 100 sensors with random distribution was used (Figs. 6, 7, 8); node 1 is the controller in each topology. The rest of the sensors are simulated by Tmote Sky. To run the controller, a virtual machine corresponding to the HP G9 DL-380 server with an E5-Xeon proces-sor2600 v4 with 8-cores and 16 GB of memory was used on the Xen 7.0.2 hypervisor. OpenDayLight controller with karaf 0.8 is installed on this virtual machine.

Dataset
WSN-DS [2] and NSL-KDD [12] standard datasets were used to evaluate the accuracy of the intrusion detection algorithm. These datasets are presented as a fully standardized and validated datasets containing various types of different categories for intrusion detection. We used bi-directional flows of transferred packets between nodes. The raw traffic is analyzed first. Then, the procedure extracts features from the pcap files using the CICFlowmeter software. The CIC-Flowmeter is an open-source software that converts pcap to CSV. WSN-DS with 374,661 records and 19 features contains different types of Denial of Service attacks including Blackhole, Grayhole, Flooding, and Scheduling attacks. NSL-KDD contains records of internet traffic and 43 features per record. This dataset exists 4 different types of attacks: Denial of Service (DoS), Probe, User to Root, and Remote to Local. The features of NSL-KDD can be divided down into four types: Categorical (2, 3, 4, 42), Binary (7,12,14,20,21,22), Discrete (8,9,15,(23)(24)(25)(26)(27)(28)(29)(30)(31)(32)(33)(34)(35)(36)(37)(38)(39)(40)(41)43), and Continuous (1,5,6,10,11,13,16,17,18,19). In the simulation, we labeled each dataset instance using predefined criteria for each dataset. Non-numeric features are converted to numeric fields, and NaN values are padded with 0. The redundant instances that created during the conversion process were removed from all datasets and accelerated calculations via the normalized columns feature within (−1, 1) . At the switch level, the routing information of header is examined to detect and classify common attacks, including hello flood, sinkhole flood and wormhole attack. However, some of the information examined is unreliable and contains noises that may lead to the wrong classification of the  Table 1.
Consider the features listed in Table 1 and conduct more detailed testing to correlate them with each of the attacks mentioned. The results of this test are shown in Table 2. Following the selection of significant features for each attack, the duplicated data are removed from the packet.

Evaluation of intrusion detection rate and classification method
The accuracy of the proposed algorithm was evaluated based on the correct intrusion detection rate and is shown in Fig. 9. Different simulations were performed on the topology with 10, 50, and 100 sensors. The detection rate by the proposed algorithm for suspicious and malicious activities reached 97%. The attacker detection rate in encapsulated packets also achieved 89%. The intrusion detection rate generally depends on the packet delivery to the sensor. In order to verify the ability of the proposed architecture, the performance of classifying attacks was evaluated. To determine the best intrusion detection algorithm, the performance of the proposed algorithm and other algorithms (SVM [14], Naïve Bayes [29],   and Logistic [30]) were evaluated by WEKA (Waikato Environment for Knowledge Analysis) tools. In this specific case, three common WSN and IoT attacks (hello flood, sinkhole flood, and wormhole attack) are configured, combined, and tested.
Using the WEKA workbench, the true positive rate (TP), the false positive rate (FP), the mean absolute error (MAE), the root mean squared error (RMSE), and accuracy are calculated based on equations (10)(11)(12)(13). In addition, the terminology of TP and FP is given in Table 2.
The combination of the attacks is examined, and the performance of tested algorithms results is summarized in Tables 3, 4 and 5.  To evaluate the proposed IDS, two well-known WSN IDS mitigation approaches are tested, namely SVELTE [39] and Pongle's IDS [33]. These methods were designed to detect routing attacks like sinkhole and wormhole, but both of them have serious problems with new anomaly attacks. The TP rate and energy of each approach are compared to the proposed method.
We also tested our method against the methods presented in [22,32] to prove that the proposed generalized architecture reliably detects unknown attacks. Fig. 10 shows the comparison of the true positive rate between the proposed method and prior well-known intrusion detection systems. According to the results, the proposed IDS achieved an overall of 97% of TP rate. Pongle's IDS shows a weakness in detecting combination attacks but SVELTE achieved 80% in total. IDS in [22] that used SVM as the classification algorithm obtained 88% and IDS in [32] achieved 95% detection rate in total.
As explained in Algorithm 1, the IDS module waits for suspicious activity recognition and then requests for a report on the packet parameters. The algorithm then extracts the node details from the packet and stores them in an AttackerGuess vector. Finally, the controller checks the counter and decides whether to mark the node as an attacker or a as normal node.

Power consumption evaluation
Generally, SDWSN network sensors are powered by batteries, and the issue of power consumption is one of the most important factors for wireless sensor networks. For this reason, the power consumption of the proposed algorithm and its overhead were calculated by Powertrace in Contiki. General information from the Tmote Sky sensor was used in this calculation, as shown in Table 7. In energy calculations, a potential difference of 3 volts is considered. Low Power Mode (LPM) means that the Micro-Controller Unit (MCU) is idle when the radio transmitter is off. Processing time is the time the MCU is active and the radio transmitter is off. In contrast, the time when both MCU and the radio transmitter are active is called transmit time. Equation (15) used to calculate energy consumption is as follows [13,28]: The average power is calculated using the consumed energy based on Eq. (16) [28]. In Fig. 11, the overhead of the intrusion detection system is shown for one hour in the different number of sensors (first column). The effective intrusion detection rate is shown in the second column of each section, which is obtained by the difference in power consumption between the normal system time and the intrusion detection time. The amount of energy required to detect intrusions is shown in the third column. This column is derived from the difference in the energy consumption during the time of the attack and its non-detection by the intrusion detection system and the time of the attack and its detection by the intrusion detection system. The last column shows the overload of energy consumption in the event of an attack for one hour. In all the simulated topologies, the attack starts at the 5th minute. In Fig. 12, a comparison of energy overhead for each IDS on a Tmote Sky node running for 1 h has been shown. The lowest energy consumption belongs to SVELTE with 11,560 mW, but the proposed IDS supports 97% rate of TP with 11,614 mW energy consumption. On the other hand, the proposed IDS system increases the energy consumption by about 0.004% compared to the SVELTE which is negligible in relation to the accuracy of the proposed IDS system. Data packet delay results were obtained while executing the proposed architecture with and without the IDS module running is shown in Fig. 13. The results show that the packet transmission process delay of the IDS module is acceptable. In Fig. 14 a comparison of data packet delay result between different intrusion detection systems and the proposed IDS on combined datasets on different topologies has been shown.

Conclusion
Security should be considered as one of the most important challenges in any network design. Software-defined networking is a new paradigm that has influenced other networking areas. Therefore, the software-defined wireless sensor networks (SDWSN) have been proposed to overcome the limitations of wireless sensor networks. The integrated SDWSN has inherited its parents' security challenges, and as a result of this integration, several new security concerns have been added. In this paper, an architecture for SDWSN security with a layered, non-parametric approach to intrusion detection was presented. The proposed architecture has high detection performance due to the security modules implemented in the sensors which acts as a layer. The predicted intrusion detection system in this architecture uses the anomaly methodology, which is capable of detecting new and unplanned attacks. Due to the limited resources in the sensors, the proposed algorithm is considered as a solution for intrusion detection in the proposed architecture with high accuracy.