DoSDetection.py 1.9 KB
import pyshark as pyshark
import os
import subprocess
import CountingBloom as CBF
import threading
import time
import schedule



def LiveSniffer(net_interface, cbf):
    capture = pyshark.LiveCapture(interface=net_interface, bpf_filter= 'dst 192.168.219.110 && tcp') # 캡쳐 프로세스 생성
    capture.set_debug()
    for packet in capture.sniff_continuously():
        PktFiltering(packet, cbf)


def PktFiltering(pkt, filter): # 패킷의 src IP address를 기반으로 flooding 공격 탐지(packet per second)
    print(pkt.ip.src, " to ", pkt.ip.dst)
    count = filter.insert_to_cbf(pkt.ip.src) # 해시결과들 중 최소값 리턴
    print(count)
    if count > 10: # cbf에 10 이상의 값이 매핑되어 있을 때 (threshold)
        print("Anomal packet flow detected. source IP: ", pkt.ip.src, ", Suspicious Alert")
        

def CntDecrement(c_bf):
    for k in range (len(c_bf)):
        if c_bf[k]: 
            c_bf[k] -= 1
        else:
            continue
    print("Dec all completed.")



def main():
    print("capturing start")

    try:
        capture = pyshark.LiveCapture(interface='wlp2s0', bpf_filter='tcp', display_filter= 'ip.dst == 192.168.219.100') # 캡쳐 프로세스 생성
        #capture.set_debug()
        filter = CBF.Counting_bloom_filter(20, 0.001) 
        # CBF 초기화, 홈 IoT 환경에서는 최대 20개 정도의 노드로부터 정보를 송수신한다고 판단, 0.001은 hash miss 비율
        # false-positive 비율을 낮추기 위해서 
        print("CB-Filter Length: ", filter.length)
        schedule.every(0.1).seconds.do(CntDecrement, filter.c_bf)  # 0.1초마다 필터 내 1이상의 모든 값을 1씩 감소
        for packet in capture.sniff_continuously():
            PktFiltering(packet, filter)
            schedule.run_pending()

    except KeyboardInterrupt:
        print("\nPressed Ctrl+C: End Capturing")


if __name__ == "__main__":
    main()