├── model ├── s ├── RAN_renew.h5 └── random_forest_renew.py ├── mirai ├── loader.dbg ├── mirai.arm7 ├── mirai_80.arm7 ├── mirai_r.arm7 ├── mirai_ssh.arm7 ├── mirai_loader_me.arm7 └── mirai_loader_scan.arm7 ├── module ├── RAN_scan.h5 ├── RAN_attack.h5 ├── RAN_in_out.h5 ├── RAN_in_out_2.h5 ├── module │ ├── RAN_scan.h5 │ ├── RAN_attack.h5 │ ├── __pycache__ │ │ ├── client.cpython-39.pyc │ │ ├── ids_ap.cpython-39.pyc │ │ └── model_check.cpython-39.pyc │ ├── final.py │ ├── client.py │ ├── model_check.py │ └── ids_ap.py ├── __pycache__ │ ├── client.cpython-39.pyc │ ├── ids_ap.cpython-39.pyc │ └── model_check.cpython-39.pyc ├── final.py ├── client.py ├── model_check.py └── ids_ap.py ├── README.md └── model_renew ├── final_pcap.py ├── get_user.py ├── model_check.py ├── client.py ├── final.py ├── h0neyp0t-firebase-adminsdk-wrhlp-cd02b8d173.json └── ids_ap.py /model/s: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /mirai/loader.dbg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/mirai/loader.dbg -------------------------------------------------------------------------------- /mirai/mirai.arm7: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/mirai/mirai.arm7 -------------------------------------------------------------------------------- /mirai/mirai_80.arm7: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/mirai/mirai_80.arm7 -------------------------------------------------------------------------------- /mirai/mirai_r.arm7: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/mirai/mirai_r.arm7 -------------------------------------------------------------------------------- /model/RAN_renew.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/model/RAN_renew.h5 -------------------------------------------------------------------------------- /module/RAN_scan.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/module/RAN_scan.h5 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # H0neyP0t 2 | Development of Botnet Detection Module for Traffic-Based IoT Devices Using Deep Learning 3 | -------------------------------------------------------------------------------- /mirai/mirai_ssh.arm7: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/mirai/mirai_ssh.arm7 -------------------------------------------------------------------------------- /module/RAN_attack.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/module/RAN_attack.h5 -------------------------------------------------------------------------------- /module/RAN_in_out.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/module/RAN_in_out.h5 -------------------------------------------------------------------------------- /module/RAN_in_out_2.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/module/RAN_in_out_2.h5 -------------------------------------------------------------------------------- /mirai/mirai_loader_me.arm7: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/mirai/mirai_loader_me.arm7 -------------------------------------------------------------------------------- /module/module/RAN_scan.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/module/module/RAN_scan.h5 -------------------------------------------------------------------------------- /mirai/mirai_loader_scan.arm7: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/mirai/mirai_loader_scan.arm7 -------------------------------------------------------------------------------- /module/module/RAN_attack.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/module/module/RAN_attack.h5 -------------------------------------------------------------------------------- /module/__pycache__/client.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/module/__pycache__/client.cpython-39.pyc -------------------------------------------------------------------------------- /module/__pycache__/ids_ap.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/module/__pycache__/ids_ap.cpython-39.pyc -------------------------------------------------------------------------------- /module/__pycache__/model_check.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/module/__pycache__/model_check.cpython-39.pyc -------------------------------------------------------------------------------- /module/module/__pycache__/client.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/module/module/__pycache__/client.cpython-39.pyc -------------------------------------------------------------------------------- /module/module/__pycache__/ids_ap.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/module/module/__pycache__/ids_ap.cpython-39.pyc -------------------------------------------------------------------------------- /module/module/__pycache__/model_check.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wja0/IoT-Botnet-Attack-Detection-Module/HEAD/module/module/__pycache__/model_check.cpython-39.pyc -------------------------------------------------------------------------------- /module/final.py: -------------------------------------------------------------------------------- 1 | import ids_ap as ids 2 | import model_check as mdc 3 | import client as srv 4 | import os 5 | from requests import get 6 | #import requests 7 | 8 | if __name__ == "__main__": 9 | host_ip = get("https://api.ipify.org").text 10 | attack = False 11 | c_socket = srv.connection_server() 12 | scan_model, atk_model = mdc.model_init() 13 | 14 | while(True): 15 | traffic_df = ids.scan_data() 16 | 17 | if os.fork() == 0: 18 | #err = srv.check_server(c_socket) 19 | 20 | 21 | #if err: 22 | # print("Can't connect to secure server!") 23 | 24 | attack, bad_traffic = mdc.check_attack(traffic_df, scan_model, atk_model, host_ip) 25 | 26 | if attack: 27 | #infrom_usr() 28 | srv.send_to_server(c_socket, bad_traffic) 29 | 30 | exit(0)#child process down 31 | 32 | print("restart scan data") 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /module/module/final.py: -------------------------------------------------------------------------------- 1 | import ids_ap as ids 2 | import model_check as mdc 3 | import client as srv 4 | import os 5 | from requests import get 6 | #import requests 7 | 8 | if __name__ == "__main__": 9 | host_ip = get("https://api.ipify.org").text 10 | attack = False 11 | c_socket = srv.connection_server() 12 | scan_model, atk_model = mdc.model_init() 13 | 14 | while(True): 15 | traffic_df = ids.scan_data() 16 | 17 | if os.fork() == 0: 18 | #err = srv.check_server(c_socket) 19 | 20 | 21 | #if err: 22 | # print("Can't connect to secure server!") 23 | 24 | attack, bad_traffic = mdc.check_attack(traffic_df, scan_model, atk_model, host_ip) 25 | 26 | if attack: 27 | #infrom_usr() 28 | srv.send_to_server(c_socket, bad_traffic) 29 | 30 | exit(0)#child process down 31 | 32 | print("restart scan data") 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /model_renew/final_pcap.py: -------------------------------------------------------------------------------- 1 | import ids_ap_pcap as ids 2 | import model_check as mdc 3 | import client as srv 4 | import os 5 | import get_user as gusr 6 | from requests import get 7 | #import requests 8 | 9 | if __name__ == "__main__": 10 | #host_ip = get("https://api.ipify.org").text 11 | host_ip = '210.117.181.96' 12 | attack = False 13 | c_socket = srv.connection_server() 14 | final_model = mdc.model_init() 15 | 16 | while(True): 17 | traffic_df = ids.scan_data() 18 | print(traffic_df) 19 | if os.fork() == 0: 20 | #err = srv.check_server(c_socket) 21 | 22 | #if err: 23 | # print("Can't connect to secure server!") 24 | 25 | attack, bad_traffic = mdc.check_attack(traffic_df, final_model, host_ip) 26 | 27 | if attack == True: 28 | gusr.inform_user() 29 | srv.send_to_server(c_socket, bad_traffic) 30 | 31 | exit(0)#child process down 32 | 33 | print("restart scan data") 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /model_renew/get_user.py: -------------------------------------------------------------------------------- 1 | import firebase_admin 2 | from firebase_admin import credentials 3 | from firebase_admin import db 4 | from firebase_admin import auth 5 | from pyfcm import FCMNotification 6 | 7 | APIKEY = "AAAA7aJLMSQ:APA91bGNf83X0OmIatkt_Fs1xVWiLM8OzWRu38v_aipfkpIcLEufg5a_FIhD5EFX8SX75tas7M42kD_KE_WN7W5rWFSr98uPnqlEzdEob5b3pr8UI6-Ae7p3FCTDO7y6ajfjN_f1W_Bz" 8 | push_service = FCMNotification(APIKEY) 9 | 10 | def sendMessage(title, body,TOKEN): 11 | data_message = { 12 | "body" : body, 13 | "title": title 14 | } 15 | result = push_service.single_device_data_message(registration_id=TOKEN, data_message=data_message) 16 | print(result) 17 | 18 | 19 | 20 | 21 | 22 | def inform_user(): 23 | # bring uid 24 | cred = credentials.Certificate('h0neyp0t-firebase-adminsdk-wrhlp-cd02b8d173.json') 25 | firebase_admin.initialize_app(cred, {'databaseURL': 'https://h0neyp0t-default-rtdb.firebaseio.com/'}) 26 | 27 | page = auth.list_users() 28 | SELECTED_USER = 'b@gmail.com' 29 | while page: 30 | for user in page.users: 31 | if user.email == SELECTED_USER : 32 | UID = user.uid 33 | print("User's UID: ", UID) 34 | page = page.get_next_page() 35 | 36 | # bring APIKEY 37 | ref = db.reference('USER/{}/TOKEN'.format(UID)) 38 | TOKEN = ref.get() 39 | 40 | sendMessage("공격 위험 감지", "IoT 기기의 해킹이 의심됩니다! 전원을 껐다 켜주세요!!",TOKEN) 41 | -------------------------------------------------------------------------------- /model_renew/model_check.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pandas as pd 3 | import ids_ap as ids 4 | from sklearn.model_selection import train_test_split 5 | import time 6 | import numpy as np 7 | import joblib 8 | from collections import Counter 9 | import xgboost as xgb 10 | #import tensorflow as tf 11 | str_attack = ['Normal', 'Scan IN', 'Scan OUT'] 12 | 13 | def model_init(): 14 | final_model = joblib.load('./RAN_in_out_2.h5') 15 | 16 | return final_model 17 | 18 | 19 | def check_attack(x_traffic, final_model, host_ip): 20 | x_traffic = x_traffic.drop(['ip', 'mac','t_port', 'd_port'], axis = 1) 21 | y_traffic = final_model.predict(x_traffic) 22 | cnt = 0 23 | result = x_traffic 24 | result['attack'] = y_traffic 25 | 26 | for i in y_traffic: 27 | if i == 1 or i == 2: 28 | cnt = cnt + 1 29 | 30 | 31 | attack = True 32 | if cnt > 50: 33 | attack = True 34 | 35 | #print('Attack 0: '+str(len(result.loc[result['attack']==0]))) 36 | #print('Attack 1: '+str(len(result.loc[result['attack']==1]))) 37 | #print('Attack 2: '+str(len(result.loc[result['attack']==2]))) 38 | #print('Attack 3: '+str(len(result.loc[result['attack']==3]))) 39 | 40 | print("[*]Finish Botnet Attack Detection") 41 | for i in range(3): 42 | print('Attack %d (%s): %d' % (i,str_attack[i],len(result.loc[result['attack']== i ]))) 43 | 44 | return attack, result 45 | 46 | 47 | -------------------------------------------------------------------------------- /model_renew/client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import pandas as pd 3 | 4 | def connection_server(): 5 | #domain = 'cncloader.shop' 6 | #ip = socket.gethostbyname_ex(domain) 7 | HOST = '210.117.181.86' 8 | #HOST = '210.117.181.86' 9 | PORT = 20226 10 | #PORT = 20226 11 | 12 | c_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 13 | c_socket.connect((HOST, PORT)) 14 | 15 | return c_socket 16 | 17 | def check_connetion(c_socket): 18 | msg = 'hello'; 19 | data = msg.encode(); 20 | length = len(data); 21 | c_socket.sendall(length.to_bytes(4, byteorder="little")); 22 | c_socket.sendall(data); 23 | data = c_socket.recv(4); 24 | length = int.from_bytes(data, "little"); 25 | data = c_socket.recv(length); 26 | msg = data.decode(); 27 | 28 | if err : #err check plz 29 | for i in range(0,10): 30 | err = check_server(c_socket) 31 | if not err: 32 | break 33 | 34 | print('Received from : ', msg); 35 | 36 | return False #check error plz 37 | 38 | def send_to_server(c_socket, df): 39 | print(df) 40 | bad_traffic = pd.DataFrame(df) 41 | bad_traffic = bad_traffic.to_string().encode() 42 | length = len(bad_traffic); 43 | c_socket.sendall(length.to_bytes(4, byteorder="little")); 44 | c_socket.sendall(bad_traffic) 45 | 46 | def send_to_server_no_scan(c_socket): 47 | no_scan = "no scan" 48 | no_scan = no_scan.encode() 49 | length = len(no_scan); 50 | c_socket.sendall(length.to_bytes(4, byteorder="little")); 51 | c_socket.sendall(no_scan) 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /module/client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import pandas as pd 3 | 4 | def connection_server(): 5 | domain = 'cncbotnet.shop' 6 | #ip = socket.gethostbyname_ex(domain) 7 | HOST = '210.117.181.86' 8 | PORT = 20226 9 | 10 | c_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 | c_socket.connect((HOST, PORT)) 12 | 13 | return c_socket 14 | 15 | def check_connetion(c_socket): 16 | msg = 'hello'; 17 | data = msg.encode(); 18 | length = len(data); 19 | c_socket.sendall(length.to_bytes(4, byteorder="little")); 20 | c_socket.sendall(data); 21 | data = c_socket.recv(4); 22 | length = int.from_bytes(data, "little"); 23 | data = c_socket.recv(length); 24 | msg = data.decode(); 25 | 26 | if err : #err check plz 27 | for i in range(0,10): 28 | err = check_server(c_socket) 29 | if not err: 30 | break 31 | 32 | print('Received from : ', msg); 33 | 34 | return False #check error plz 35 | 36 | def send_to_server(c_socket, df): 37 | bad_traffic = pd.DataFrame(df) 38 | bad_traffic = bad_traffic.to_string().encode() 39 | length = len(bad_traffic); 40 | c_socket.sendall(length.to_bytes(4, byteorder="little")); 41 | c_socket.sendall(bad_traffic) 42 | 43 | 44 | #for i in range(1,10): 45 | # msg = 'hello'; 46 | # data = msg.encode(); 47 | # length = len(data); 48 | # client_socket.sendall(length.to_bytes(4, byteorder="little")); 49 | # client_socket.sendall(data); 50 | # data = client_socket.recv(4); 51 | # length = int.from_bytes(data, "little"); 52 | # data = client_socket.recv(length); 53 | # msg = data.decode(); 54 | # print('Received from : ', msg); 55 | 56 | #client_socket.close(); 57 | -------------------------------------------------------------------------------- /module/module/client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import pandas as pd 3 | 4 | def connection_server(): 5 | domain = 'cncbotnet.shop' 6 | #ip = socket.gethostbyname_ex(domain) 7 | HOST = '210.117.181.86' 8 | PORT = 20226 9 | 10 | c_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 | c_socket.connect((HOST, PORT)) 12 | 13 | return c_socket 14 | 15 | def check_connetion(c_socket): 16 | msg = 'hello'; 17 | data = msg.encode(); 18 | length = len(data); 19 | c_socket.sendall(length.to_bytes(4, byteorder="little")); 20 | c_socket.sendall(data); 21 | data = c_socket.recv(4); 22 | length = int.from_bytes(data, "little"); 23 | data = c_socket.recv(length); 24 | msg = data.decode(); 25 | 26 | if err : #err check plz 27 | for i in range(0,10): 28 | err = check_server(c_socket) 29 | if not err: 30 | break 31 | 32 | print('Received from : ', msg); 33 | 34 | return False #check error plz 35 | 36 | def send_to_server(c_socket, df): 37 | bad_traffic = pd.DataFrame(df) 38 | bad_traffic = bad_traffic.to_string().encode() 39 | length = len(bad_traffic); 40 | c_socket.sendall(length.to_bytes(4, byteorder="little")); 41 | c_socket.sendall(bad_traffic) 42 | 43 | 44 | #for i in range(1,10): 45 | # msg = 'hello'; 46 | # data = msg.encode(); 47 | # length = len(data); 48 | # client_socket.sendall(length.to_bytes(4, byteorder="little")); 49 | # client_socket.sendall(data); 50 | # data = client_socket.recv(4); 51 | # length = int.from_bytes(data, "little"); 52 | # data = client_socket.recv(length); 53 | # msg = data.decode(); 54 | # print('Received from : ', msg); 55 | 56 | #client_socket.close(); 57 | -------------------------------------------------------------------------------- /model_renew/final.py: -------------------------------------------------------------------------------- 1 | import ids_ap as ids 2 | import model_check as mdc 3 | import client as srv 4 | import os 5 | import get_user as gusr 6 | from requests import get 7 | #import requests 8 | 9 | if __name__ == "__main__": 10 | #host_ip = get("https://api.ipify.org").text 11 | print("Select type of traffic (0: exit, 1: Network, 2: pcap)") 12 | in_chk = True 13 | while(in_chk): 14 | type_traffic = input() 15 | if type_traffic == '0': 16 | print("Exit proccess") 17 | exit(0) 18 | elif type_traffic == '1': 19 | print("Scan this network!") 20 | in_chk = False 21 | elif type_traffic == '2': 22 | print("Read pcap!") 23 | in_chk = False 24 | else: 25 | print("Please select in (0: exit, 1: Network, 2: pcap)") 26 | 27 | 28 | host_ip = '210.117.181.96' 29 | attack = False 30 | c_socket = srv.connection_server() 31 | final_model = mdc.model_init() 32 | 33 | while(True): 34 | traffic_df = ids.scan_data(type_traffic) 35 | 36 | #if os.fork() == 0: 37 | if True: 38 | #err = srv.check_server(c_socket) 39 | 40 | #if err: 41 | # print("Can't connect to secure server!") 42 | 43 | attack, bad_traffic = mdc.check_attack(traffic_df, final_model, host_ip) 44 | 45 | if attack == True: 46 | gusr.inform_user() 47 | srv.send_to_server(c_socket, bad_traffic) 48 | else : 49 | srv.send_to_server_no_scan(c_socket) 50 | exit(0)#child process down 51 | 52 | print("restart scan data") 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /model_renew/h0neyp0t-firebase-adminsdk-wrhlp-cd02b8d173.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "service_account", 3 | "project_id": "h0neyp0t", 4 | "private_key_id": "cd02b8d173af96a26fd97cf39b47d64b1e21cbcb", 5 | "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDUDc5xVzImesNc\njxod2dweMuxnCrh9Kaijxm5LEtRZ8McHIjyKAtOeLtGyY91LFudrftRDsXXBoaKS\noK68dfkKmmEaKyfTtyh7m+KsiN97fyR6fTFi1bSK+FyzFnrqYGkjEM61qCIHnFso\nk4iTTvL8M/J9ewnweJuCqGa0gvO5cvaF5dDct279DLDi7wiH3R/m/UKmTbwG6+CC\ncUnJi5cXP/3J5IurW4m5gQ+qva2E/UXsB1jvdkl77uft1Dg3KNgxcUYGZeFtrw5Q\nZxj4mHFMfrJIhJ8nIv9xGmrWEGc0+TYNIxAE54i11U2hI76OeartHbha4MVKL/oM\nJ0XYTyQpAgMBAAECggEADgGIxy0D36LFezxAdK71E6bivROU3T9+fK1t5NYuNxqT\ngBcfedt3RWrA6FAhnQS67aYHjckPhrs5qlxOmPK51kdyw8W3RbaX8pd4lf4cX2Ml\nx6leilv50XasuMTIAumx8rejekAhWfCr3LbnPcOTLQaerPG5gFaW/umcjwOvPBUL\nB6wqMMmEtBYclqcXhgB0vPJM86QmxYN7oEbwWApuu0PvZWJFzqjlhC7RK0vmHlSL\nxJI5jQhFjfSSwIF2fAUTnQkvwjulD3EG/Wy0rMWz5sYPTXC9Dq9g/qbjTEO3mzdU\nIrOq9dQidrzo28zdEMEEC6wCkj5BLVabsYWMggmo4QKBgQDrY36av73iOjbE9Ntv\npF3OFpfAQD2ZyrxX8kxlkbYi89E8x/ymW0TNFOUL1eeEQV93v0983wbnN5XZfD40\n8kTeqs1NlRidLDz8Yfk+xMLRlZrouT1PVgjPuKBOyOuAr2DWd6VRC8wme6O+G9Dd\nJ/yUFvj3hXo0Bq3FwscQ9qagvQKBgQDmnzzLwvDJqOxa6VMkq/w4YSaW+6m3msut\nFjPCGF1QKMtygkzMTOSdWlk5cgxKLBQexsKdsfBawy1earaFXp943mW1Iq4aFVJO\nRHobuMKenygwVhFEasNjDYczzBGg1qQzTjf65IAucohS9VAl8n1HSodswpWjYoLQ\nQKDdfwB13QKBgGufFeeS+zJQA3KRsTKeJ/VuBvvzYzbJpstfEObvdCMO7v+nQDCf\nUhmiEAcVScECUq/hXGpvXiyhEXZag+aZTjuwRCXQoWxbKZcLBHZaZ+iDSkxVRV7c\nqzKt6z2aR3KSvOfR1Ff12OVPalIlTZ2QBr9+sV4aPQFEfHcK0xFCdHTRAoGBANeX\nsSwDFzpOEnaCfNlhdi32lC69IVGlAhbTFJu0Tzdqi5aGvOiYUXfQSGztcxO71StY\nQANPnxQaNcV4GRzg8k/6CDanLv7vQ7wrQ8O6myXSP63AJ/A/plxo/yWq9ifXwDS+\nQJLpHfNN2qdC8SQoZnlI8QT5ew38P7ITWM73tSR5AoGAIgNo/xvY8y1eldgddHGs\n6N3T+zgkcPq4ICbZPSuAG6IdILYOT6MZzUXuIA6QkP6DcBZUUK6omoR6EZpL0j1a\nR5ZBEe08rjXHX85ccgca8BefZ/RcR7155vaxqPdIkuUQJGAoAlNBcabvsYCLx6g0\n4Ea48RrRqma4Y8YIH/j7JYo=\n-----END PRIVATE KEY-----\n", 6 | "client_email": "firebase-adminsdk-wrhlp@h0neyp0t.iam.gserviceaccount.com", 7 | "client_id": "111452640632827408160", 8 | "auth_uri": "https://accounts.google.com/o/oauth2/auth", 9 | "token_uri": "https://oauth2.googleapis.com/token", 10 | "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", 11 | "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-wrhlp%40h0neyp0t.iam.gserviceaccount.com" 12 | } 13 | -------------------------------------------------------------------------------- /module/model_check.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pandas as pd 3 | from sklearn.model_selection import train_test_split 4 | import time 5 | import numpy as np 6 | import joblib 7 | from collections import Counter 8 | 9 | def model_init(): 10 | scan_model = joblib.load('./RAN_scan.h5') 11 | atk_model = joblib.load('./RAN_attack.h5') 12 | 13 | return scan_model, atk_model 14 | 15 | 16 | def check_attack(x_traffic, scan_model, atk_model, host_ip): 17 | chk_traffic = x_traffic 18 | x_traffic = x_traffic.drop(['saddr', 'daddr', 'src_mac', 'dst_mac'], axis = 1) 19 | 20 | y_scan_traffic = scan_model.predict(x_traffic) 21 | y_atk_traffic = atk_model.predict(x_traffic) 22 | ip_cnt = Counter() 23 | ten_point_ip = [] 24 | result = [] 25 | 26 | ip_cnt, atk_list = collection_atk_ip(chk_traffic, y_scan_traffic, y_atk_traffic, ip_cnt, host_ip) 27 | 28 | for (col_ip), ip_score in ip_cnt.most_common(): 29 | if ip_score > 0: # if ip_score is more than 10 point, we consider this traffic is attack. 30 | ten_point_ip.append(col_ip) 31 | 32 | #atk_list = pd.DataFrame(atk_list) 33 | 34 | 35 | for i in atk_list: #Is this optimization? 36 | if ''.join(i[0]) == host_ip: 37 | tmp = ''.join(i[1]) 38 | else: 39 | tmp = ''.join(i[0]) 40 | 41 | for j in ten_point_ip: 42 | if ''.join(j) == tmp: 43 | result.append(i) 44 | break 45 | #for i in atk_list: #Is this optimization? 46 | # if atk_list.iat[i,0] == host_ip: 47 | # tmp = atk_list.iat[i,1] 48 | # else: 49 | # tmp = atk_list.iat[i,0] 50 | # 51 | # for j in ten_point_ip: 52 | # if ''.join(j) == tmp: 53 | # result.append(atk_list.loc[i]) 54 | # break 55 | 56 | #print(result) 57 | attack = False 58 | 59 | if len(result) != 0: 60 | attack = True 61 | 62 | return attack, result 63 | 64 | 65 | 66 | 67 | 68 | def collection_atk_ip(chk_traffic, y_scan_traffic, y_atk_traffic, ip_cnt, host_ip): 69 | atk_list = [] 70 | 71 | for i in range(0, len(chk_traffic)): 72 | score = y_scan_traffic[i] + y_atk_traffic[i] # if scan and atk are 1, score is 2 point. and if just one of them is 1, socre is 1 point. 73 | 74 | if score > 0 : 75 | #if chl_traffic[i]['src_ip'] == host_ip: # collect ip of bad traffics. and mark a score. 76 | if chk_traffic.iat[i, 0] == host_ip: 77 | #ip_cnt.update(chk_traffic[i]['dst_ip']:score) 78 | ip_cnt.update({tuple(chk_traffic.iat[i,1]):score}) 79 | else: 80 | ip_cnt.update({tuple(chk_traffic.iat[i,0]):score}) 81 | 82 | atk_list.append(chk_traffic.loc[i]) # new only attack data frame :) 83 | 84 | return ip_cnt, atk_list 85 | -------------------------------------------------------------------------------- /module/module/model_check.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pandas as pd 3 | from sklearn.model_selection import train_test_split 4 | import time 5 | import numpy as np 6 | import joblib 7 | from collections import Counter 8 | 9 | def model_init(): 10 | scan_model = joblib.load('./RAN_scan.h5') 11 | atk_model = joblib.load('./RAN_attack.h5') 12 | 13 | return scan_model, atk_model 14 | 15 | 16 | def check_attack(x_traffic, scan_model, atk_model, host_ip): 17 | chk_traffic = x_traffic 18 | x_traffic = x_traffic.drop(['saddr', 'daddr', 'src_mac', 'dst_mac', 'sport', 'dport'], axis = 1) 19 | 20 | y_scan_traffic = scan_model.predict(x_traffic) 21 | y_atk_traffic = atk_model.predict(x_traffic) 22 | ip_cnt = Counter() 23 | ten_point_ip = [] 24 | result = [] 25 | 26 | ip_cnt, atk_list = collection_atk_ip(chk_traffic, y_scan_traffic, y_atk_traffic, ip_cnt, host_ip) 27 | 28 | for (col_ip), ip_score in ip_cnt.most_common(): 29 | if ip_score > 0: # if ip_score is more than 10 point, we consider this traffic is attack. 30 | ten_point_ip.append(col_ip) 31 | 32 | #atk_list = pd.DataFrame(atk_list) 33 | 34 | 35 | for i in atk_list: #Is this optimization? 36 | if ''.join(i[0]) == host_ip: 37 | tmp = ''.join(i[1]) 38 | else: 39 | tmp = ''.join(i[0]) 40 | 41 | for j in ten_point_ip: 42 | if ''.join(j) == tmp: 43 | result.append(i) 44 | break 45 | #for i in atk_list: #Is this optimization? 46 | # if atk_list.iat[i,0] == host_ip: 47 | # tmp = atk_list.iat[i,1] 48 | # else: 49 | # tmp = atk_list.iat[i,0] 50 | # 51 | # for j in ten_point_ip: 52 | # if ''.join(j) == tmp: 53 | # result.append(atk_list.loc[i]) 54 | # break 55 | 56 | #print(result) 57 | attack = False 58 | 59 | if len(result) != 0: 60 | attack = True 61 | 62 | return attack, result 63 | 64 | 65 | 66 | 67 | 68 | def collection_atk_ip(chk_traffic, y_scan_traffic, y_atk_traffic, ip_cnt, host_ip): 69 | atk_list = [] 70 | 71 | for i in range(0, len(chk_traffic)): 72 | score = y_scan_traffic[i] + y_atk_traffic[i] # if scan and atk are 1, score is 2 point. and if just one of them is 1, socre is 1 point. 73 | 74 | if score > 0 : 75 | #if chl_traffic[i]['src_ip'] == host_ip: # collect ip of bad traffics. and mark a score. 76 | if chk_traffic.iat[i, 0] == host_ip: 77 | #ip_cnt.update(chk_traffic[i]['dst_ip']:score) 78 | ip_cnt.update({tuple(chk_traffic.iat[i,1]):score}) 79 | else: 80 | ip_cnt.update({tuple(chk_traffic.iat[i,0]):score}) 81 | 82 | atk_list.append(chk_traffic.loc[i]) # new only attack data frame :) 83 | 84 | return ip_cnt, atk_list 85 | -------------------------------------------------------------------------------- /model/random_forest_renew.py: -------------------------------------------------------------------------------- 1 | import os 2 | from tkinter import Image 3 | 4 | import mglearn 5 | import pandas as pd 6 | import pydotplus as pydotplus 7 | from sklearn.metrics import roc_curve, accuracy_score, precision_score, recall_score, f1_score, plot_confusion_matrix, auc 8 | from sklearn.ensemble import RandomForestClassifier 9 | import matplotlib.pyplot as plt 10 | import time 11 | import seaborn as sns 12 | import gc 13 | import joblib 14 | from sklearn.model_selection import train_test_split 15 | from sklearn.tree import export_graphviz 16 | 17 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 18 | PATH = os.path.join("C:/Users/KIM_GANG_MIN/Desktop/DataSet") 19 | 20 | def load_data(path, filename): 21 | csv_path = os.path.join(path, filename) 22 | return pd.read_csv(csv_path,low_memory=False) 23 | 24 | 25 | time_1 = time.time() 26 | train_df = load_data(PATH, "total_traffic.csv") 27 | #train_df['attack'] = textToInt(train_df, 'category') 28 | time_2 = time.time() 29 | time_interval = time_2 - time_1 30 | print("데이터 불러오기 & 데이터 셔플 시간: " + str(time_interval)) 31 | 32 | 33 | time_1 = time.time() 34 | x = pd.get_dummies(train_df.drop(['ip','mac','t_port','d_port', 'attack'], axis=1)) 35 | print(x.columns) 36 | y = train_df['attack'] 37 | 38 | x_train, x_test, y_train, y_test = train_test_split(x, y, test_size =0.3) 39 | time_2 = time.time() 40 | time_interval = time_2 - time_1 41 | print("데이터 전처리 시간: " + str(time_interval)) 42 | print("x_train data length: " + str(len(x_train))+"\ny_train data length: " + str(len(y_train))+"\nx_test data length: " + str(len(x_test))+"\ny_test data length: " + str(len(y_test))) 43 | 44 | del train_df 45 | gc.collect() 46 | 47 | 48 | print("------랜덤 포레스트 시작------") 49 | rf_clf = RandomForestClassifier(random_state=40) 50 | 51 | time_1 = time.time() 52 | rf_clf.fit(x_train, y_train) 53 | time_2 = time.time() 54 | time_interval = time_2 - time_1 55 | print("교육 시간: " + str(time_interval)) 56 | 57 | time_1 = time.time() 58 | pred = rf_clf.predict(x_test) 59 | train_acc = rf_clf.score(x_train, y_train) 60 | test_acc = rf_clf.score(x_test, y_test) 61 | time_2 = time.time() 62 | time_interval = time_2 - time_1 63 | print("모델 평가 시간: " + str(time_interval)) 64 | 65 | print(f"Accuracy: {accuracy_score(y_test, pred):.3f}") # 정확도 66 | print(f"Precision: {precision_score(y_test, pred,average='micro'):.3f}") # 정밀도 67 | print(f"Recall: {recall_score(y_test, pred,average='micro'):.3f}") # 재현율 68 | print(f"F1-score: {f1_score(y_test, pred,average='micro'):.3f}") # F1 스코어 69 | 70 | 71 | 72 | joblib.dump(rf_clf, 'C:/Users/KIM_GANG_MIN/Desktop/DataSet/Model/RAN_renew.h5') 73 | 74 | time_1 = time.time() 75 | ftr_importances_values = rf_clf.feature_importances_ 76 | ftr_importances = pd.Series(ftr_importances_values, index = x_train.columns) 77 | ftr_top20 = ftr_importances.sort_values(ascending=False)[:15] 78 | time_2 = time.time() 79 | time_interval = time_2 - time_1 80 | print("중요 피처 시각화 시간: " + str(time_interval)) 81 | 82 | plt.figure(1, figsize=(8,6)) 83 | plt.title('Top 20 Feature Importances') 84 | sns.barplot(x=ftr_top20, y=ftr_top20.index) 85 | plt.figure(2, figsize=(8,6)) 86 | for i in y_test: 87 | if i != 0: 88 | i = 1 89 | 90 | for i in pred: 91 | if i!= 0: 92 | i=1 93 | fpr, tpr, thresholds = roc_curve(y_test, pred) 94 | plt.plot(fpr, tpr, '--', label="Logistic Regression") 95 | plt.plot([0,1], [0,1], 'k--') 96 | plt.plot([fpr],[tpr],'r-',ms=10) 97 | plt.show() 98 | 99 | -------------------------------------------------------------------------------- /module/ids_ap.py: -------------------------------------------------------------------------------- 1 | from scapy.all import * 2 | from collections import Counter 3 | import pandas as pd 4 | import csv 5 | from dataclasses import dataclass 6 | from requests import get 7 | @dataclass 8 | class Time_cls: 9 | src_ip:str = '-1.-1.-1.-1' 10 | dst_ip:str = '-1.-1.-1.-1' 11 | sport:str = '-1' 12 | dport:str = '-1' 13 | s_time:float = 0 14 | l_time:float = 0 15 | 16 | protocols={6:'tcp', 17:'udp', 47:'gre'} 17 | time_check = [] 18 | traffic = Counter() 19 | src_traffic = Counter() 20 | dst_traffic = Counter() 21 | 22 | 23 | 24 | def traffic_monitor_callback(pkt): 25 | if IP in pkt: 26 | proto = pkt[IP].proto #protocol 27 | src_ip = pkt[IP].src #saddr 28 | dst_ip = pkt[IP].dst #daddr 29 | host_ip = get("https://api.ipify.org").text 30 | 31 | time = pkt[IP].time # time_atr 32 | length = pkt[IP].len #length 33 | src_mac = pkt[0][0].src #smac 34 | dst_mac = pkt[0][0].dst #dmac 35 | sport = str(0) 36 | dport = str(0) 37 | flag = 0 38 | flags = 0 39 | dns = 0 40 | 41 | if proto ==1: 42 | proto = 5 #icmp 43 | elif proto == 2: 44 | proto = 4 #igmp 45 | elif proto == 6: 46 | sport = str(pkt[TCP].sport) 47 | dport = str(pkt[TCP].dport) 48 | proto = 0 #tcp 49 | flag = pkt[TCP].flags 50 | 51 | elif proto == 17: 52 | try: 53 | sport = str(pkt[UDP].sport) 54 | except: 55 | sport = str(0) 56 | 57 | try: 58 | dport = str(pkt[UDP].dport) 59 | except: 60 | sport = str(0) 61 | proto = 1 #udp 62 | 63 | elif proto == 47: 64 | flag = pkt[GRE].flags 65 | proto = 2 #gre 66 | elif proto == 89: 67 | proto = 3 # ospfigp 68 | 69 | src_traffic.update({tuple(src_ip)}) # get conn_p_src_ip 70 | dst_traffic.update({tuple(dst_ip)}) # get conn_p_dst_ip 71 | check_time(src_ip, dst_ip, dport, time) # get time and datarate 72 | flags = flag_to_int(flag) 73 | 74 | traffic.update({tuple(map(str, (src_ip, dst_ip, proto, src_mac, dst_mac, sport, dport, flags, dns))): length}) 75 | print(src_ip," ", dst_ip, " ",proto, " ",src_mac, " ",dst_mac, " ",sport, " ",dport, " ",flags, " ",dns) 76 | 77 | def flag_to_int(flag): 78 | flags = 0 79 | if 'U' in str(flag): 80 | flags += 32 81 | if 'A' in str(flag): 82 | flags += 16 83 | if 'P' in str(flag): 84 | flags += 8 85 | if 'R' in str(flag): 86 | flags += 4 87 | if 'S' in str(flag): 88 | flags += 2 89 | if 'F' in str(flag): 90 | flags += 1 91 | return flags 92 | 93 | def add_n_in(df, scan_time): 94 | time = 1 95 | for(h1, h2, proto, src_mac, dst_mac, sport, dport, flag,dns), total in traffic.most_common(): # except broadcast 96 | if src_mac == 'ff:ff:ff:ff:ff:ff' : 97 | continue 98 | elif dst_mac == 'ff:ff:ff:ff:ff:ff': 99 | continue 100 | 101 | for (src_h), num_s in src_traffic.most_common(): # save conn_p_src_ip in tuple 102 | if ''.join(src_h) == h1: 103 | temp_s = num_s 104 | break 105 | 106 | for (dst_h), num_s in dst_traffic.most_common(): # save conn_p_dst_ip in tuple 107 | if ''.join(dst_h) == h2: 108 | temp_d = num_s 109 | break 110 | 111 | for i in time_check: # save tine in tuple 112 | if(i.src_ip == h1) and (i.dst_ip == h2) and (i.dport == dport): 113 | if i.s_time == i.l_time: 114 | time = 1 115 | else : 116 | time = i.l_time - i.s_time 117 | break 118 | 119 | data = pd.DataFrame({'saddr': [h1], 'daddr' : [h2], 'proto' : [proto], 'src_mac' : [src_mac], 'dst_mac' : [dst_mac], 'sport' : [sport], 'dport':[dport], 'flag':[flag], 'N_IN_Conn_P_SrcIP':[temp_s], 'N_IN_Conn_P_DstIP':[temp_d], 'length' :[total] , 'time' : [time], 'datarate' : [total/time], 'dns':[dns]}) 120 | df = pd.concat([df,data], ignore_index=True) 121 | return df 122 | 123 | def init_traffic(): 124 | global traffic 125 | global src_traffic 126 | global dst_traffic 127 | traffic = Counter() 128 | src_traffic = Counter() 129 | dst_traffic = Counter() 130 | tmp = Time_cls() 131 | time_check.append(tmp) 132 | 133 | def do_sniff(scan_time): 134 | df = pd.DataFrame(columns=['saddr', 'daddr', 'proto', 'src_mac', 'dst_mac', 'sport', 'dport', 'flag', 'N_IN_Conn_P_SrcIP', 'N_IN_Conn_P_DstIP', 'length', 'time', 'datarate','dns']) 135 | sniff(iface="br0",prn=traffic_monitor_callback, timeout = scan_time, store=False) 136 | df = add_n_in(df, scan_time) 137 | 138 | return df 139 | 140 | def write_csv(df, PATH): 141 | df.to_csv(PATH, index=False) 142 | 143 | def check_time(src_ip, dst_ip, dport, n_time): 144 | for i in time_check: 145 | if (i.src_ip == src_ip) and (i.dst_ip == dst_ip) and (i.dport == dport): 146 | i.l_time = n_time 147 | return 0 148 | temp = Time_cls() 149 | temp.src_ip = src_ip 150 | temp.dst_ip = dst_ip 151 | temp.dport = dport 152 | temp.s_time = n_time 153 | temp.l_time = n_time 154 | time_check.append(temp) 155 | 156 | return 0 157 | 158 | def scan_data(): 159 | init_traffic() 160 | sc_time_one = 60 161 | df = do_sniff(sc_time_one) 162 | return df 163 | 164 | -------------------------------------------------------------------------------- /module/module/ids_ap.py: -------------------------------------------------------------------------------- 1 | from scapy.all import * 2 | from collections import Counter 3 | import pandas as pd 4 | import csv 5 | from dataclasses import dataclass 6 | from requests import get 7 | @dataclass 8 | class Time_cls: 9 | src_ip:str = '-1.-1.-1.-1' 10 | dst_ip:str = '-1.-1.-1.-1' 11 | sport:str = '-1' 12 | dport:str = '-1' 13 | s_time:float = 0 14 | l_time:float = 0 15 | 16 | protocols={6:'tcp', 17:'udp', 47:'gre'} 17 | time_check = [] 18 | traffic = Counter() 19 | src_traffic = Counter() 20 | dst_traffic = Counter() 21 | 22 | 23 | 24 | def traffic_monitor_callback(pkt): 25 | if IP in pkt: 26 | proto = pkt[IP].proto #protocol 27 | 28 | 29 | src_ip = pkt[IP].src #saddr 30 | dst_ip = pkt[IP].dst #daddr 31 | host_ip = get("https://api.ipify.org").text 32 | 33 | #if str(src_ip) not in host_ip: 34 | #return 35 | # if str(dst_ip) not in host_ip: 36 | # if str(src_ip) not in '192.168.0.': 37 | # return 38 | 39 | time = pkt[IP].time # time_atr 40 | length = pkt[IP].len #length 41 | src_mac = pkt[0][0].src #smac 42 | dst_mac = pkt[0][0].dst #dmac 43 | sport = str(0) 44 | dport = str(0) 45 | flag = 0 46 | flags = 0 47 | dns = 0 48 | 49 | if proto ==1: 50 | proto = 5 #icmp 51 | elif proto == 2: 52 | proto = 4 #igmp 53 | elif proto == 6: 54 | sport = str(pkt[TCP].sport) 55 | dport = str(pkt[TCP].dport) 56 | proto = 0 #tcp 57 | flag = pkt[TCP].flags 58 | 59 | elif proto == 17: 60 | try: 61 | sport = str(pkt[UDP].sport) 62 | except: 63 | sport = str(0) 64 | 65 | try: 66 | dport = str(pkt[UDP].dport) 67 | except: 68 | sport = str(0) 69 | proto = 1 #udp 70 | 71 | elif proto == 47: 72 | flag = pkt[GRE].flags 73 | proto = 2 #gre 74 | elif proto == 89: 75 | proto = 3 # ospfigp 76 | 77 | src_traffic.update({tuple(src_ip)}) # get conn_p_src_ip 78 | dst_traffic.update({tuple(dst_ip)}) # get conn_p_dst_ip 79 | check_time(src_ip, dst_ip, dport, time) # get time and datarate 80 | flags = flag_to_int(flag) 81 | 82 | traffic.update({tuple(map(str, (src_ip, dst_ip, proto, src_mac, dst_mac, sport, dport, flags, dns))): length}) 83 | print(src_ip," ", dst_ip, " ",proto, " ",src_mac, " ",dst_mac, " ",sport, " ",dport, " ",flags, " ",dns) 84 | 85 | def flag_to_int(flag): 86 | flags = 0 87 | if 'U' in str(flag): 88 | flags += 32 89 | if 'A' in str(flag): 90 | flags += 16 91 | if 'P' in str(flag): 92 | flags += 8 93 | if 'R' in str(flag): 94 | flags += 4 95 | if 'S' in str(flag): 96 | flags += 2 97 | if 'F' in str(flag): 98 | flags += 1 99 | return flags 100 | 101 | def add_n_in(df, scan_time): 102 | time = 1 103 | for(h1, h2, proto, src_mac, dst_mac, sport, dport, flag,dns), total in traffic.most_common(): # except broadcast 104 | if src_mac == 'ff:ff:ff:ff:ff:ff' : 105 | continue 106 | elif dst_mac == 'ff:ff:ff:ff:ff:ff': 107 | continue 108 | 109 | for (src_h), num_s in src_traffic.most_common(): # save conn_p_src_ip in tuple 110 | if ''.join(src_h) == h1: 111 | temp_s = num_s 112 | break 113 | 114 | for (dst_h), num_s in dst_traffic.most_common(): # save conn_p_dst_ip in tuple 115 | if ''.join(dst_h) == h2: 116 | temp_d = num_s 117 | break 118 | 119 | for i in time_check: # save tine in tuple 120 | if(i.src_ip == h1) and (i.dst_ip == h2) and (i.dport == dport): 121 | if i.s_time == i.l_time: 122 | time = 1 123 | else : 124 | time = i.l_time - i.s_time 125 | break 126 | 127 | data = pd.DataFrame({'saddr': [h1], 'daddr' : [h2], 'proto' : [proto], 'src_mac' : [src_mac], 'dst_mac' : [dst_mac], 'sport' : [sport], 'dport':[dport], 'flag':[flag], 'N_IN_Conn_P_SrcIP':[temp_s], 'N_IN_Conn_P_DstIP':[temp_d], 'length' :[total] , 'time' : [time], 'datarate' : [total/time], 'dns':[dns]}) 128 | df = pd.concat([df,data], ignore_index=True) 129 | return df 130 | 131 | def init_traffic(): 132 | global traffic 133 | global src_traffic 134 | global dst_traffic 135 | traffic = Counter() 136 | src_traffic = Counter() 137 | dst_traffic = Counter() 138 | tmp = Time_cls() 139 | time_check.append(tmp) 140 | 141 | def do_sniff(scan_time): 142 | df = pd.DataFrame(columns=['saddr', 'daddr', 'proto', 'src_mac', 'dst_mac', 'sport', 'dport', 'flag', 'N_IN_Conn_P_SrcIP', 'N_IN_Conn_P_DstIP', 'length', 'time', 'datarate','dns']) 143 | sniff(iface="br0",prn=traffic_monitor_callback, timeout = scan_time, store=False) 144 | df = add_n_in(df, scan_time) 145 | 146 | return df 147 | 148 | def write_csv(df, PATH): 149 | df.to_csv(PATH, index=False) 150 | 151 | def check_time(src_ip, dst_ip, dport, n_time): 152 | for i in time_check: 153 | if (i.src_ip == src_ip) and (i.dst_ip == dst_ip) and (i.dport == dport): 154 | i.l_time = n_time 155 | return 0 156 | temp = Time_cls() 157 | temp.src_ip = src_ip 158 | temp.dst_ip = dst_ip 159 | temp.dport = dport 160 | temp.s_time = n_time 161 | temp.l_time = n_time 162 | time_check.append(temp) 163 | 164 | return 0 165 | 166 | def scan_data(): 167 | init_traffic() 168 | sc_time_one = 60 169 | df = do_sniff(sc_time_one) 170 | return df 171 | 172 | -------------------------------------------------------------------------------- /model_renew/ids_ap.py: -------------------------------------------------------------------------------- 1 | from scapy.all import * 2 | from collections import Counter 3 | import pandas as pd 4 | import csv 5 | from dataclasses import dataclass 6 | from requests import get 7 | 8 | 9 | class Traffic_info: 10 | ip:str = '' 11 | mac:str = '' 12 | t_port:int = -1 #transfer port, just check 13 | d_port:int = -1 #dynamic port, just check 14 | weak_port:int = -1 15 | proto:str = '' 16 | length:int = 0 17 | flag:int = -1 18 | total_length:int= 0 19 | time:float = 1 20 | datarate:float = 1 21 | cnt:int = 0 22 | s_time:float = 0 23 | l_time:float = 0 24 | 25 | def __init__(self, ip, mac, t_port, d_port, proto, weak_port, length, flag, total_length,s_time, l_time): 26 | self.ip = ip 27 | self.mac = mac 28 | self.t_port = t_port 29 | self.d_port = d_port 30 | self.weak_port = weak_port 31 | self.proto = proto 32 | self.length = length 33 | self.flag = flag 34 | self.total_length = total_length 35 | self.s_time = s_time 36 | self.l_time = l_time 37 | self.time = 1 38 | self.datarate= 1 39 | self.cnt = 1 40 | 41 | def getNetInfo(self): 42 | return self.ip, self.mac, self.t_port,self.d_port, self.proto, self.length, self.flag 43 | 44 | def getAllInfo(self): 45 | return self.ip, self.mac, self.t_port,self.d_port, self.proto, self.weak_port, self.length, self.flag, self.total_length, self.time, self.datarate, self.cnt 46 | 47 | def setCount(self): 48 | self.cnt = self.cnt + 1 49 | 50 | def setTotalLength(self, length): 51 | self.total_length = self.total_length + length 52 | 53 | def setLastTime(self, l_time): 54 | self.l_time = l_time 55 | 56 | def setTimeValue(self): 57 | self.time = self.l_time - self.s_time 58 | self.datarate = self.total_length / self.time 59 | 60 | 61 | 62 | weak_ports = [22, 23, 2323, 80, 81, 5555, 7574, 8080, 8443, 37215, 49152, 52869] 63 | protocols={6:'tcp', 17:'udp'} 64 | time_check = [] 65 | traffic = Counter() 66 | src_traffic = Counter() 67 | dst_traffic = Counter() 68 | cnt_traffic = [] 69 | 70 | 71 | 72 | def traffic_monitor_callback(pkt): 73 | if IP in pkt: 74 | proto = pkt[IP].proto #protocol 75 | src_ip = pkt[IP].src #saddr 76 | dst_ip = pkt[IP].dst #daddr 77 | host_ip = '192.168.2.5' 78 | #host_ip = get("https://api.ipify.org").text 79 | 80 | if proto not in protocols: 81 | return 82 | 83 | # if str(src_ip) not in host_ip or str(dst_ip) not in '210.117.181.86': 84 | # if str(src_ip) not in '210.117.181.86' or str(dst_ip) not in host_ip: 85 | # return 86 | 87 | #if str(src_ip) not in host_ip: 88 | # if str(dst_ip) not in host_ip: 89 | # return 90 | 91 | 92 | 93 | time = pkt[IP].time # time_atr 94 | length = pkt[IP].len #length 95 | src_mac = pkt[0][0].src #smac 96 | dst_mac = pkt[0][0].dst #dmac 97 | sport = 0 98 | dport = 0 99 | flags = 0 100 | 101 | if proto == 6: 102 | try: 103 | sport = pkt[TCP].sport 104 | dport = pkt[TCP].dport 105 | except: 106 | sport = 0 107 | dport = 0 108 | 109 | #proto = 'tcp' #tcp 110 | proto = 1 111 | flags = flag_to_int(pkt[TCP].flags) 112 | 113 | elif proto == 17: 114 | try: 115 | sport = pkt[UDP].sport 116 | dport = pkt[UDP].dport 117 | except: 118 | sport = 0 119 | dport = 0 120 | 121 | #proto = 'udp' 122 | proto=0 123 | 124 | if (sport in weak_ports) or (dport in weak_ports): 125 | weak_port = 1 126 | else : 127 | weak_port = 0 128 | 129 | #if weak_port == 0 : 130 | # return 131 | 132 | if str(src_ip) in host_ip: 133 | check_traffic_cls(dst_ip, dst_mac, dport, sport, proto, weak_port, flags, length, time) 134 | else : 135 | check_traffic_cls(src_ip, src_mac, sport, dport, proto, weak_port, flags, length, time) 136 | 137 | print(src_ip," ", dst_ip, " ",proto, " ",src_mac, " ",dst_mac, " ",sport, " ",dport, " ",flags, " ", length) 138 | 139 | def check_traffic_cls(ip, mac, t_port, d_port, proto, weak_port, flags, length,time): 140 | exist = 0 141 | for i in cnt_traffic: 142 | (tmp_ip, tmp_mac, tmp_t_port, tmp_d_port, tmp_proto, tmp_length, tmp_flag) = i.getNetInfo() 143 | if (tmp_ip, tmp_mac, tmp_t_port, tmp_d_port, tmp_proto,tmp_length, tmp_flag) == (ip, mac, t_port, d_port, proto, length, flags): 144 | exist = 1 145 | i.setCount() 146 | i.setTotalLength(length) 147 | i.setLastTime(time) 148 | break 149 | 150 | if exist == 0: 151 | total_length = length 152 | s_time = time 153 | l_time = time + 1 # Preventing division by zero 154 | tmp_traffic_cls = Traffic_info(ip, mac, t_port, d_port, proto, weak_port, length, flags, total_length, s_time, l_time) 155 | cnt_traffic.append(tmp_traffic_cls) 156 | 157 | 158 | 159 | def flag_to_int(flag): 160 | flags = 0 161 | if 'U' in str(flag): 162 | flags += 32 163 | if 'A' in str(flag): 164 | flags += 16 165 | if 'P' in str(flag): 166 | flags += 8 167 | if 'R' in str(flag): 168 | flags += 4 169 | if 'S' in str(flag): 170 | flags += 2 171 | if 'F' in str(flag): 172 | flags += 1 173 | return flags 174 | 175 | def add_n_in(df): 176 | for i in cnt_traffic: 177 | i.setTimeValue() 178 | tmp_ip, tmp_mac, tmp_t_port, tmp_d_port, tmp_proto, tmp_weak_port, tmp_length, tmp_flag, tmp_total_length, tmp_time, tmp_datarate, tmp_cnt = i.getAllInfo() 179 | 180 | if tmp_mac == 'ff:ff:ff:ff:ff:ff' : # except broadcast 181 | continue 182 | 183 | data = pd.DataFrame({'ip':[tmp_ip], 'mac':[tmp_mac], 't_port':[tmp_t_port], 'd_port':[tmp_d_port], 'weak_port':[tmp_weak_port], 'proto':[tmp_proto], 'length':[tmp_length],'flag':[tmp_flag], 'total_length':[tmp_total_length], 'time':[tmp_time],'datarate':[tmp_datarate], 'cnt':[tmp_cnt]}) 184 | #print(tmp_ip,' ',tmp_mac, ' ',tmp_t_port, ' ' ,tmp_proto, ' ',tmp_weak_port, ' ',tmp_length,'',tmp_flag, ' ',tmp_total_length, ' ',tmp_time, ' ',tmp_datarate, ' ',tmp_cnt) 185 | df = pd.concat([df,data], ignore_index=True) 186 | return df 187 | 188 | def init_traffic(): 189 | global cnt_traffic 190 | cnt_traffic = [] 191 | 192 | def do_sniff(scan_time): 193 | df = pd.DataFrame(columns=['ip', 'mac', 't_port', 'd_port', 'weak_port', 'proto', 'length', 'flag', 'total_length', 'time','datarate', 'cnt']) 194 | sniff(iface="br0",prn=traffic_monitor_callback, timeout = scan_time, store=False) 195 | df = add_n_in(df) 196 | 197 | return df 198 | 199 | def read_pp(pkt_pcap): 200 | df = pd.DataFrame(columns=['ip', 'mac', 't_port', 'd_port', 'weak_port', 'proto', 'length', 'flag', 'total_length', 'time','datarate', 'cnt']) 201 | for i in pkt_pcap: 202 | traffic_monitor_callback(i) 203 | df = add_n_in(df) 204 | 205 | return df 206 | 207 | def write_csv(df, PATH): 208 | df.to_csv(PATH, index=False) 209 | 210 | 211 | 212 | def scan_data(type_traffic): 213 | init_traffic() 214 | 215 | if type_traffic == '1': 216 | sc_time_one = 600 217 | df = do_sniff(sc_time_one) 218 | 219 | elif type_traffic == '2': 220 | print("Input pcap file path (input 0 is exit)") 221 | pcap_path = input() 222 | 223 | if pcap_path == '0': 224 | exit(0) 225 | 226 | pkt_pcap = rdpcap(pcap_path) 227 | df = read_pp(pkt_pcap) 228 | 229 | return df 230 | 231 | 232 | 233 | 234 | --------------------------------------------------------------------------------