Design and implementation of simple network early warning system

The course design of this course in intrusion prevention technology and application hopes to help your course design or project

1, Topic content

1.1 Problem Description:

Based on network sniffing, a simple network early warning system is designed and implemented to decode / decode and detect the characteristics of the captured packets.

1.2 requirements:

The following functions are completed by interactive working mode under text interface or graphical interface:

1.2.1 interface:

Configurable and display system operation results.

1.2.2 function design:

Grab the communication data of the local machine in the network, including protocol type, source and destination address, port, packet size, etc.
Support application layer protocol analysis, including at least three protocols: HTTP, FTP and SMTP.
Support SSL/TLS.
Support feature detection based on MAC address, IP address, protocol type, port and application layer protocol features.
Support real-time statistical analysis and real-time alarm according to the detection results.

2, Experimental environment

Programming language: This program is designed in C# language
Operating system: Windows10
Compiler: Microsoft Visual Studio 2019

3, Scheme design

3.1 overall function flow chart design

3.2. Packet capture function

WinPcap is used to capture and filter the underlying packets on the windows operating platform. WinPcap is an architecture of BPF model and Libpcap function library for network packet capture and network state analysis on Windows platform. This architecture is composed of a core packet filtering driver, a low-level dynamic connection library Packet.dll and a high-level system independent function library Libpcap. C# function library SharpPcap and PacketDotNet use encapsulated WinPcap to capture packets. It provides many function interfaces based on packet packet.

3.3 application layer protocol analysis

Using the captured transport layer data packet, analyze its corresponding port number. Then judge the protocol type according to the specific port number, and further analyze the field value through the protocol message format of each application layer. Through the encapsulated packet function interface of the library function, the packet content of different application layer protocol types can be analyzed.

3.4,TLS/SSL

Since Packet.Net and SharpPcap do not have HTTPS packet parsing, they can only design their own packet content parsing for TLS or SSL. The default HTTPS port number is 443. Through the analysis of the port, we can know whether the data packet is HTTPS, and the analysis of the data field format, we can analyze the information of HTTPS data packet, such as content type, protocol version, data length and so on

3.5 characteristic detection of network attack

This program detects the syn-flood attack and NTP reflection amplification attack learned in the intrusion detection experiment course. In the program used to test the attack in this experiment, the source ip address of the data packet after SYN Flood attack is random and uncertain, while the source ip address of the data packet after NTP reflection attack is determined, that is, NTP server.

3.5.1. SYN Flood attack feature detection

SYN Flood judges whether the Tcp protocol flag bit corresponding to the captured packet is syn and whether the destination address is the local IP, and then whether the proportion in the currently captured datagram buffer array reaches more than 70%.
Secondly, since the packet buffer is read every 50ms, there are certain requirements for the number of packets received within 50ms when measuring the attack in advance, that is, if there are few packets read within 50ms, they will not be identified as an attack.
The flow chart is designed as follows:

3.5.2 feature detection of Ntp amplification reflection attack

The Ntp amplification reflection attack is determined by analyzing whether the source port number corresponding to the UDP protocol in the packet is 123, whether the source IP address of the packet is consistent (both are the IP address of the Ntp Server), and whether the target address of the packet is local. If more than 70% of the current packet buffer array meets the conditions, it is judged that the host has been attacked by Ntp amplification reflection attack. Like SYN Flood, if the number of packets currently read is low, it will not be identified as an attack.
The flow chart is designed as follows:

3.6 real time statistical analysis

It is realized by calling the multithreaded delegate function of DataGridView window and design update and reading data packets in WinForm. DataGridView is a window control in WinForm that displays data in tabular form and provides a function interface for real-time display. Usually, this function is used in conjunction with threads. In this program, a packet array buffer is designed. The thread reading the data buffer is updated every 50ms. Each time it is read, the protocol content and number of each packet are counted from the current buffer, and the read statistical information is displayed in the DataGrid table in real time through the function interface Invoke provided in WinForm.

4, System implementation

4.1. Packet capture function

The SharpPcap Library of C# provides a CaptureDeviceList class, which is used to get local existing network adapters. After instantiating one of its objects, one of its Instance parameters can be invoked to the network adapter device.
Before capturing a data packet, you need to select the data acquisition mode. device provides Promiscuous and Normal modes. The former is a hybrid mode. It can accept all data streams passing through it. It will accept the data packet regardless of whether the destination address of the data stream is it or not, The latter general mode is to accept only packets whose destination address is it and not network packets with other addresses.
Define a buffer linked list with the type of packet RawPacket. When the listening event is enabled, the captured packets are stored in the packet buffer. Because the operation is asynchronous, when the current thread performs operations on the packet buffer, other threads cannot access it. Release the thread after updating the buffer array, and the update cycle is set to 50ms.
The Packet format stored in each buffer linked list is Packet. Call the Packet object as the parameter of the parsing function and create the object of each network layer protocol. For example, the object of the data link layer is Ethernet, the object of the network layer is Ipv4, and the object of the transport layer is UDP. If the new object of each level created according to the Packet object is not null, it indicates that the captured Packet is the protocol of the corresponding level. Each time the Packet buffer is updated, the link layer of each Packet in the buffer is parsed through the function interface of the link layer provided in the library function, and the source mac address and destination mac address are parsed. Secondly, the protocol, IP address and version information of the network layer are parsed according to the data Packet. Then analyze its transport layer information, including TCP or UDP and port information.
The node tree control is provided in the C#WinForm form form. The captured packet level information is displayed through the node number. Using this control, the effect similar to that of analyzing the content of each level of the packet in Wireshark software can be realized.

4.2. Application layer protocol analysis

Distinguish the application layer protocol from the data packet of the transport layer. First judge the port of the transport layer, for example, the port number of HTTP is 80, the port number of SMTP is 25, and the port number of FTP is 21 or 20. After analyzing which application layer protocol it belongs to, it is parsed according to the byte array content of the captured packet. Through the function provided in the library function, the parameter is the corresponding byte array, and the return value is the node tree node. Finally, the resolved node object is added as a child node to the node parent class in the form for display.

4.3,TLS/SSL

Since the library function in this program does not provide HTTPS parsing function, I simply parse it according to the byte array of the packet. Analyze the value of the port number in the transport layer object of the packet. If it is 443, it is judged that it is HTTPS protocol. Analyze the corresponding content according to the field value at a specific position in the packet byte array. The first byte in the data carrier of HTTPS byte array represents the Content Type, which is the HandShake layer. 20 represents Change Cipher Spec, 21 represents Alert warning protocol, 22 represents HandShake handshake protocol, and 23 represents Application Data protocol. The second and third bytes in the data carrier represent the protocol version information. For example, the 0303 field represents the protocol version as TLSv1.20301 represents TLSv1.0, etc. The fourth byte and the fifth byte in the data carrier represent the length of the data segment. The contents of the following fields are detailed packaging information, including certificates and secret keys.

4.4 characteristic detection of network attack

It is realized by analyzing the packet buffer updated in the packet capturing process. Because the packet buffer is updated in real time, the detection of the buffer is also real-time.

4.4.1 feature detection of SYN Flood Attack

Define an int array whose length is the length of the current packet buffer and is used to store the number of TCP message contents in the current packet array marked syn. Then define a string array to store the destination address in the buffer packet. If the TCP flag bit in the packet buffer is syn and the proportion of the destination ip address to the local machine reaches more than 70%, it is judged that it is attacked and pop-up prompt is made by using the MessageBox space in WinForm.

4.4.2 feature detection of Ntp amplification reflection attack

Define an int array to store whether the source port corresponding to UDP in the packet buffer array is 123. Define two string arrays, one for storing the destination IP address of the packet and the other for storing the source address. Find the value with the largest proportion in the source address array to judge whether it is the address of the NTP server. As mentioned above, the source address in the data packet sent by the Syn attack program tested by this program is random, while in the NTP attack program, because the machine accesses the NTP server once, the NTP server sends the corresponding data packet dozens of times, so the source address in the NTP attack tested in this program is the address of the fixed NTP server. By judging that in the packet buffer, the destination address satisfying the sending is the local machine, the source address is the source address with the most repeated times in the buffer, and the port number corresponding to UDP is 123. If the proportion reaches more than 70%, a pop-up window will prompt that an NTP attack has been received.

4.5 realization of real-time statistics

Define a delegate function whose parameter type is packet, which is used to display it in DataGridView table in real time. When the thread that updates the packet buffer runs each time, it executes the predefined delegate function for display with the specified packet chain table by owning the basic window handle of the control, and generates the corresponding string according to the packet and index serial number to display in the window list. The DataGridView function of C# provides the interface of ADD function. The parameter of the function is used to display the data array of every row in the form. After parsing the packets, the information is packaged into an array and the ADD function of the DataGridView control is added to the new row.

5, Program demonstration

5.1. Bag capturing demonstration

Select the network adapter, where the wireless network is selected

Select scan mode

The SharpPcap library provides functions for filtering rules. Filtering can be realized by entering rules

Click the start button to execute packet capture. The result is shown in the figure below, including information at all levels and packet content

Detailed information of each level can be expanded in the node tree at the lower left corner:

The contents of transport layer UDP are as follows:

5.2 application layer protocol analysis demonstration

5.2.1,FTP

The captured FTP packets are as follows

5.2.2,SMTP

SMTP packets can be captured by entering telnet smtp.qq.com 25 in the CMD console. Because the port number of SMTP is 25, the content displayed after setting the filter rules in the filter is analyzed as follows:

5.2.3,HTTP

After normal access to the web page, you can capture the Http packet, and its parsing content is as follows

5.3 TLS/SSL demonstration

5.4 network attack

The program used to test the attack in this experiment is two files used in the experimental course of intrusion detection DOS attack

5.4.1 SYN Flood attack and early warning demonstration

Use pre prepared SYN Flood attack software in cmd consoleThe data packets after SYN Flood attack and pop-up prompt can be captured in the program as follows:

5.4.2 Ntp amplification reflection attack and early warning demonstration

Start ntp attack in CMD

The captured data packets and warning prompts are as follows:

5.5 real time statistical demonstration

This program implements a monitoring window for real-time statistics of the corresponding number of packet protocol types, as follows:

6, Summary

In this experiment, a major difficulty is that in order to realize the real-time display of captured data packets, it is necessary to use the relevant knowledge of multi-threaded calls and delegate functions. Because they are not very skilled in their operation in advance, they spend a lot of time in this place. Finally, they write it themselves after deeply understanding the relevant examples.
Secondly, there is an error in the understanding of the functions to be realized by SSL and TLS. In this experiment, TLS and SSL should analyze their signatures and encrypted contents, while I only realized the analysis of specific field values. In the aspect of early warning function, I did not consider the judgment of analyzing port, flag bit and other information in advance, but only considered the IP address and proportion. As a result, although the early warning system can detect the corresponding attack at the beginning, the false alarm rate is very high, which is reflected in that I will be prompted to receive the attack when I browse the web page normally, After the judgment of port number and flag bit is added later, the false alarm rate is greatly reduced.
In the implementation of the early warning system, only two attacks are considered, and less aspects are considered. After the teacher reminds me, I understand that the source host IP address reflected by NTP can be forged, so the related functions need to be improved. This program only detects the characteristics of SYN Flood and NTP amplification reflection attacks. In addition, the characteristics of other attacks are not considered.

7, Partial code display

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using SharpPcap;
using SharpPcap.LibPcap;//Reference SharpPcap
using SharpPcap.WinPcap;
using SharpPcap.AirPcap;
using System.Net.NetworkInformation;
using PacketDotNet;
using System.Management;
using System.Net;
using System.Net.Sockets;

namespace MySniffer
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            pktInfo = new PacketInfo(this.treeView1);
            IpAddress = GetLocalIP();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            loadDevice();//Load network card when loading form
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        public void DetecetSynFlood(List<RawCapture> bufferList)
        {
            try
            {
                if (StartMessageBox == false)
                {
                    if (bufferList.Count < 30)
                    {
                        return;
                    }
                    int N = bufferList.Count;
                    string[] DestPortArr = new string[N];
                   int[] SourceSYN = new int[N];
                    for (int i = 0; i < N; i++)
                    {
                            Packet pp = Packet.ParsePacket(bufferList[i].LinkLayerType,
                          bufferList[i].Data);
                            IpPacket ipp = IpPacket.GetEncapsulated(pp);
                            if(ipp!=null)
                            {
                                DestPortArr[i] = ipp.DestinationAddress.ToString();
                            }
                            TcpPacket tp = TcpPacket.GetEncapsulated(pp);
                            
                            if (tp!=null)
                            {
                                bool tempbool = tp.Syn;
                                SourceSYN[i] = (tempbool == true ? 1 : 0);
                            }                  
                    }
                    int temp2 = 0;
                    for (int i = 0; i < N; i++)
                    {
                        if ((DestPortArr[i] == IpAddress)&& SourceSYN[i]==1)
                        {
                            temp2++;
                        }
                    }
                    double y = ((double)(temp2)) / ((double)(N));
                    if (y >= 0.7)
                    {
                        DialogResult answer;
                        answer = MessageBox.Show
                            ("Detected SYN FLOOD attack");
                        if (answer == DialogResult.OK)
                        {
                            StartMessageBox = false;
                        }
                        else
                        {
                            StartMessageBox = true;
                        }
                    }
                }

            }
            catch (Exception)
            {

            }
            
          
        }
        public void DetecetNtpReply(List<RawCapture> bufferList)
        {
            if (StartMessageBox == false)
            {
                if (bufferList.Count < 5)
                {
                    return;
                }
                int N = bufferList.Count;
                string[] DestPortArr = new string[N];
                string[] SourcePortArr = new string[N];
                int[] SourcePort = new int[N];
                for (int i = 0; i < N; i++)
                {
                    Packet pp = Packet.ParsePacket(bufferList[i].LinkLayerType,
                         bufferList[i].Data);
                    IpPacket ip = IpPacket.GetEncapsulated(pp);
                    if(ip!=null)
                    {
                        DestPortArr[i]=ip.DestinationAddress.ToString();
                    }
                    UdpPacket up = UdpPacket.GetEncapsulated(pp);
                    if (up != null)
                    {
                        string temps =up.SourcePort.ToString();
                        SourcePort[i] = (temps == "123" ? 1 : 0);
                    }
                }
                var d = from n in SourcePortArr
                        group n by n into g
                        select new { Key = g.Key, Count = g.Count() };
                //Find the most frequent occurrence
                var max = d.Max(a => a.Count);
                int temp2 = 0;
                //Find elements based on maximum number of times
                var maxItems = from m in d where m.Count == max select m.Key;
                string Source = maxItems.First();
                for (int i = 0; i < N; i++)
                {
                    if ((SourcePortArr[i] == Source) && (DestPortArr[i] == IpAddress)
                        &&(SourcePort[i]==1))
                    {
                        temp2++;
                    }
                }
                double y = ((double)(temp2)) / ((double)(N));

                if (y >= 0.7)
                {
                    DialogResult answer;
                    answer = MessageBox.Show
                        ("Detected NTP Reflection amplification attack");
                    if (answer == DialogResult.OK)
                    {
                        StartMessageBox = false;
                    }
                    else
                    {
                        StartMessageBox = true;
                    }
                }
            }


        }
        string IpAddress = "";//Get native IP address
        ICaptureDevice device;// Define device
        bool StartMessageBox = false;
        List<RawCapture> packetList = new List<RawCapture>();//List of captured data
        List<RawCapture> bufferList;//Cache list
        Thread AnalyzerThread;//Thread analyzing data
        Thread MonitorThread;//Monitoring thread
        object threadLock = new object();//Thread locking
        object MonitorLock = new object();//Monitoring thread locking
        bool isStartAnalyzer;//Flag indicating whether to start the analysis thread
        DeviceMode devMode = DeviceMode.Promiscuous;//Data acquisition mode, the default is hybrid mode
        int readTimeOut = 50;//Set the time delay for reading
        delegate void DataGridRowsShowHandler(RawCapture packet);
        public static string GetLocalIP()
        {
            /* var address = NetworkInterface
            .GetAllNetworkInterfaces()
            .Where(i => i.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
            .SelectMany(i => i.GetIPProperties().UnicastAddresses)
            .Where(a => a.Address.AddressFamily == AddressFamily.InterNetwork)
            .Select(a => a.Address.ToString())
            .ToList().Last();
             return address.ToString();*/
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }

        //Define delegate functions to display captured packets in real time
        DataBuilder rowsBulider = new DataBuilder();
        PacketInfo pktInfo;//Class for analyzing packets
        uint packetIndex = 0;
        private MonitorForm monitorform;
        int[][] DataCache = new int[4][];
        private void loadDevice()// Method of obtaining network card
        {
            comDeviceList.ComboBox.DisplayMember = "Text";
            comDeviceList.ComboBox.ValueMember = "Value";
            CaptureDeviceList deviceLst = CaptureDeviceList.Instance;
            //Get host network card information
            foreach (ICaptureDevice dev in deviceLst)
            {
                // AirPcap devices cannot disable local capture
                if (dev is AirPcapDevice)
                {
                    Console.WriteLine(dev.ToString());
                }
                else if (dev is WinPcapDevice)
                {
                    ClsComboboxItem clsCbxItem = new ClsComboboxItem();
                    clsCbxItem.Text = ((WinPcapDevice)dev).Interface.FriendlyName
                        + "  " + dev.Description.Split('\'')[1];
                    clsCbxItem.Value = dev;
                    comDeviceList.ComboBox.Items.Add(clsCbxItem);
                }
                else if (dev is LibPcapLiveDevice)
                {
                    Console.WriteLine(dev.ToString());
                }
            }
        }
        //Select network card
        private void comDeviceList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {

                device = CaptureDeviceList.Instance[comDeviceList.SelectedIndex];
            }
            catch(Exception)
            {

            }
           
        }
        private void UIConfig(bool isStart)
        {
            //Set the selectability of UI interface buttons
            comDeviceList.Enabled = !isStart;
            comFilter.Enabled = !isStart;
            btnStart.Enabled = !isStart;
            btnStop.Enabled = isStart;
            btnOpen.Enabled = !isStart;
            btnSave.Enabled = !isStart;
            checkBox1.Enabled = !isStart;
        }
        public void Clear()
        {
            //clear list 
            if (packetList != null)
            {
                packetList.Clear();
            }
            if (bufferList != null)
            {
                bufferList.Clear();
            }
            dataGridPacket.Rows.Clear();
            treeView1.Nodes.Clear();
            richTextBox1.Text = "";
            packetIndex = 0;
        }
       private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            //Set the changed data collection mode
            if(checkBox1.SelectedItem =="promiscuous mode ")
            {
                devMode = DeviceMode.Promiscuous;
            }
            else if(checkBox1.SelectedItem == "Normal mode")
            {
                devMode = DeviceMode.Normal;
            }
            else
            {
                devMode = DeviceMode.Promiscuous;
            }
            //Hybrid mode: it can accept all data streams passing through it,
            //Whether the destination address of the data stream is it or not, it will accept the packet

            //Normal mode: only accept packets whose destination address is it, and do not accept network packets with other addresses
        }
        /// <summary>
        ///Start network card
        /// </summary>
        private void Start()
        {
            if (device == null || device.Started)
                return;
            bufferList = new List<RawCapture>();
            DataCache=InitArr(DataCache);
            //Construct cache list
            Clear();//Clean up the original data
            isStartAnalyzer = true;//Start parsing flag position true
            StartAnalyzer();//Start analysis thread

            try
            {
                device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
                //Hybrid mode is used by default, with timeout of 50ms
                device.Open(devMode, readTimeOut);
                //The function to turn on the device is called through the selected mode and the selected delay per captured packet
                device.Filter = comFilter.Text;
                //Set filtering rules
                device.StartCapture();
                //Call the function that starts capturing the packet
                UIConfig(true);
                 //Set the selectability of UI controls
            }
            catch (Exception ex)
            {
                //Accident handling
                MessageBox.Show(ex.Message);
                UIConfig(false);
            }

        }
        /// <summary>
        ///Start analysis
        /// </summary>
        private void StartAnalyzer()
        {
            AnalyzerThread = new Thread(new ThreadStart(analysrThreadMethod));
            //Construct thread for analyzing data
            AnalyzerThread.IsBackground = true;
            //Thread set to run in the background
            AnalyzerThread.Start();
            //Parsing thread starts execution
      

        }
        public void StartMonitor()
        {
            MonitorThread = new Thread(new ThreadStart(MonitorMethod));
            MonitorThread.IsBackground = true;
            MonitorThread.Start();
        }

        /// <summary>
        ///Stop
        /// </summary>
        private void Stop()
        {
            try
            {
                if (device != null && device.Started)
                {
                    //If the current network adapter exists and is working, pause it
                    device.StopCapture();
                    device.Close();
                }
                isStartAnalyzer = false;
                //Will resolve flag position false
                if (AnalyzerThread !=null && AnalyzerThread.IsAlive)
                {
                    AnalyzerThread.Abort();
                    //If the current parsing process exists and is working, the thread is forcibly terminated
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);//Exception handling
            }
            UIConfig(false);
        }

        void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            lock (threadLock)
            {
                bufferList.Add(e.Packet);
            }
            //If the event threadLock is not locked, lock it. Otherwise, wait until the event is released.
            //After lock, other threads cannot perform this operation or call this event while adding packets to the packet buffer linked list
            //After execution, the event is released, and the operation of adding a function can be accessed by other threads.
        }
        //Data analysis thread
        private void analysrThreadMethod()
        {
            while (isStartAnalyzer)
            {
                //As long as the flag bit that starts parsing is true, parsing will continue
                bool isShoudSleep = true;
                //Set thread sleep flag bit
                lock (threadLock)
                {
                    if (bufferList.Count != 0)
                        isShoudSleep = false;
                    //When there is no data in the thread buffer, the sleep flag is set to false
                }
                if (isShoudSleep)
                {
                    Thread.Sleep(200);
                    //If the sleep flag is set to true, the current thread will sleep for 200ms
                }
                else
                {
                    //If the thread is active at this time, that is, the packet cache contains data, the packet is added to the linked list
                    List<RawCapture> tmpPacketList;
                    lock (threadLock) //get data
                    {
                        tmpPacketList = bufferList;
                        DetecetSynFlood(bufferList);
                        DetecetNtpReply(bufferList);
                        //Save the data of the current packet cache to the total packet chain table
                        bufferList = new List<RawCapture>();
                        packetList.AddRange(tmpPacketList);
                    }
                    //Add each packet in the temporary buffer as an argument to the parameter list of the display function
                    foreach (var i in tmpPacketList)
                    {
                        this.Invoke(new DataGridRowsShowHandler(ShowDataRows), i);
                        //Call the delegate to realize the real-time display in the interface            
                    }
                }
            }
        }
        public void MonitorMethod()
        {
            while (isStartAnalyzer)
            {
                bool isShoudSleep = true;
                lock (MonitorLock)
                {
                    if (bufferList.Count != 0)
                        isShoudSleep = false;
                    //When there is no data in the thread buffer, the sleep flag is set to false
                }
                if (isShoudSleep)
                {
                    Thread.Sleep(200);
                    //If the sleep flag is set to true, the current thread will sleep for 200ms
                }
                else
                {
                    monitorform.UpdateDatagrid(DataCache);
                }
            }
        }
        public int[][] InitArr(int[][] arr)
        {
            int[] Eth = new int[7];
            int[] Net = new int[6];
            int[] Tra = new int[2];
            int[] APP = new int[8];
            InitArr(Eth);
            InitArr(Net);
            InitArr(Tra);
            InitArr(APP);
            arr = new int[][] { Eth, Net, Tra, APP };
            return arr;
        }
        public void InitArr(int[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = 0;
            }
        }
        //Functions displayed in the DataGrid list according to packets
        private void ShowDataRows(RawCapture packet)
        {
            try
            {
                //The corresponding string is generated according to the packet and index serial number and displayed in the window list
                string[] Row_Arr = rowsBulider.Row(packet, ++packetIndex);
                int[][] data = rowsBulider.Monitor(packet);
                AddData(DataCache,data);
                dataGridPacket.Rows.Add(Row_Arr);
                //Load DataGridRows and add them to the list;
            }
            catch (Exception ex)
            {
                MessageBox.Show("load DataGridRows fail");//Handling of abnormal conditions 
            }
        }
        private void AddData(int[][] Data1,int[][]Data)
        {
            for(int i=0;i<Data1.Length;i++)
            {
                for(int j=0;j<Data1[i].Length;j++)
                {
                    Data1[i][j]+= Data[i][j];
                }
            }
        }
        private void btnStart_Click(object sender, EventArgs e)
        {
            Start();//Click the start button to execute the start function
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            Stop();//Click the stop button to execute the stop function
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Stop();//The stop function is also called when the program is closed
        }

        private void dataGridPacket_CellMouseDown
            (object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1)
                return;
            if (e.Button == MouseButtons.Right)//Right click to select
            {
                dataGridPacket.Rows[e.RowIndex].Selected = true;
            }
            selectDataGridRow(e.RowIndex);
        }
        /// <summary>
        ///Select a row
        /// </summary>
        ///< param name = "index" > index value of selected data row < / param >
        private void selectDataGridRow(int index)
        {
            if (index < 0 || index > dataGridPacket.Rows.Count)
                return;
            //Get packet location
            int i = Convert.ToInt32(dataGridPacket.Rows[index].Cells[0].Value.ToString());
            //Contents of cells in the first column: the label of the captured packet
            if (i > packetList.Count)
                return;
            RawCapture rawPacket = packetList[i - 1];
            //The index value is set to the packet to be read according to the selected sequence number
            treeView1.Nodes.Clear();
            //Clear the protocol tree under the current window page
            pktInfo.GetProtcolTree(rawPacket);
            richTextBox1.Text = HexConvert.ConvertToHexText(rawPacket.Data);
            //The contents of the packet and the corresponding ASCL code value are displayed in the lower right corner of the window in hexadecimal
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "Pcap file|*.pcap";
            // pcap file is a common datagram storage format
            if (sd.ShowDialog() == DialogResult.OK)
            {
                var offDev = new SharpPcap.LibPcap.CaptureFileWriterDevice(sd.FileName);
                foreach (var i in packetList)
                {
                    offDev.Write(i);
                }
                //Store the data in the packet chain table in the specified path in PAP file format
                MessageBox.Show("File saved successfully", "Tips", 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        //Open file
        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog od = new OpenFileDialog();
            od.Filter = "pcap file|*.pcap";
            if (od.ShowDialog() == DialogResult.OK)
            {
                //clear list 
                Clear();
                ICaptureDevice offDev = new SharpPcap.LibPcap.
                    CaptureFileReaderDevice(od.FileName);
                //Network adapter read from pap file
                RawCapture tempPacket;
                offDev.Open();
                while ((tempPacket = offDev.GetNextPacket()) != null)
                {
                    packetList.Add(tempPacket);
                    ShowDataRows(tempPacket);
                    //Read packet information from pap file
                }
                offDev.Close();
            }
        }

        private void comFilter_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            Clear();
            //empty
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }

        private void comDeviceList_Click(object sender, EventArgs e)
        {

        }

        private void toolStripTextBox1_Click(object sender, EventArgs e)
        {

        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(monitorform==null||monitorform.isclosed==true)
            {
                monitorform = new MonitorForm(DataCache);
                monitorform.Show();
                monitorform.UpdateDatagrid(DataCache);
                StartMonitor();
            }
            else
            {
                monitorform.UpdateDatagrid(DataCache);
                StartMonitor();
            }
           
        }

        private void checkBox1_Click(object sender, EventArgs e)
        {

        }

        private void dataGridPacket_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}

Keywords: C# Cyber Security Information Security

Added by Karpathos on Mon, 13 Sep 2021 06:25:06 +0300