├── requirements.txt ├── .gitignore ├── README.md ├── LICENSE └── sip-dd.py /requirements.txt: -------------------------------------------------------------------------------- 1 | python3 2 | python-iptables==0.13.0 3 | scapy==2.4.0 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SIP-Based DDoS Defense Tool 2 | 3 | * Architecture : Melih Tas 4 | * Code: Sumer Cip 5 | 6 | SIP-DD is a defense tool developed against SIP-based DoS/DDoS attacks. In the current state, SIP-DD comprises 3 main modules namely with Statistics, Inspection and Action. 7 | 8 | Originally it was developed to be used in academic work to help developing novel defense approaches and then as an idea to convert it to a fully functional application level SIP-based DDoS mitigation tool. 9 | 10 | It has been used in an academic journal paper titled "Novel SIP-based DDoS Attacks and Effective Defense Strategies" published in Computers & Security 63 (2016) 29-44 by Elsevier, Science Direct http://sciencedirect.com/science/article/pii/S0167404816300980. 11 | 12 | SIP-DD uses pcap library which keeps a queue at the kernel level and allows to examine the asynchronous data, and it does detection after the actual traffic copy is received. Calculation method takes interval approximately 4-5 seconds considering the performance. SIP-DD also does multi-threading rate control. 13 | 14 | Statistics Module collects a window of traffic periodically (hourly, daily, weekly, monthly) and for each of them, it creates a sample traffic pattern especially considering network and SIP packet specifications. This sample is named normal traffic pattern. The sampled network traffic is used as the input for the learning and calculation mechanism to obtain statistics for generating the dynamic thresholds employed by the action module in the defense mechanism. According to threshold calculation, there should be initial inbound and outbound traffic values defined. Measuring the bandwidth usages and packets per seconds for a time period, the learning mechanism calculates the attack traffic threshold. 15 | 16 | When the current traffic rate reaches the attack traffic threshold, the Inspection Module becomes active and compares the normal traffic pattern to the suspected attack traffic pattern. Inspecting the SIP specifications that include the headers and tags in SIP messages such as Call-ID, from tag, branch tag, etc. running the following attack-specific detection rules, the mechanism aims to identify how much of the suspicious traffic is auto-generated and should be dropped/blocked in Action module of the defense mechanism. 17 | 18 | * Rule 1: Incoming SIP connections/requests per second from a single source IP address. 19 | * Rule 2: Incoming SIP connections/requests per second to a single destination IP address. 20 | * Rule 3: Incoming SIP connections, including retransmission, from a single source IP address. 21 | * Rule 4: Incoming SIP connections, including retransmission, to a single destination IP address. 22 | 23 | Current features: 24 | 25 | * Multi-threading rate control 26 | * Write live traffic to Pcap files (hourly, weekly, monthly, daily) (appending is supported) 27 | * If app closed/opened, writing PCAP files and sniffing resumes from where it was (all edge/limit counters make their calculations with respect to these absences) 28 | * Calculate all limit/edge values defined in the spec. 29 | * Calculate rule counters defined in the spec. 30 | 31 | Future feaures: 32 | 33 | * If there is an attack, SIP-DD will catch the IP address, print it to the console, send email alarms, active blocking mechanism and check if it is an retransmission attack. 34 | * Attack scenario based rules 35 | 36 | Usage: 37 | 38 | install requirements.txt python3 sip_dd.py -d -t -v (VERBOSE logging on) -f 39 | 40 | If no bpf filter given, default is 'udp port 5060' 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /sip-dd.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import argparse 4 | import calendar 5 | import datetime 6 | import threading 7 | import pickle 8 | from datetime import timedelta 9 | from collections import defaultdict, Counter 10 | from scapy.all import * 11 | 12 | MAX_UDP_SIP_PACKET_SIZE = 64 # kb 13 | RATE_CALCULATE_INTERVAL = 1 # sec - smaller is more accurate but slower 14 | 15 | def _get_dump_file_names(): 16 | """Calculate the filenames that the PCAP data to be written from the now(DateTime) 17 | hourly/13:00-14:00_28.Nov.2017.pcap 18 | daily/28.Nov.2017.pcap 19 | weekly/21-28_Nov.2017 20 | monthly/Nov.2017 21 | """ 22 | now = datetime.now() 23 | 24 | abbr_month_name = calendar.month_name[now.month][:3] 25 | start_day_of_week = (now - timedelta(days=now.weekday())).day 26 | end_day_of_week = (now - timedelta(days=now.weekday()) + \ 27 | timedelta(days=7)).day 28 | 29 | hfn = 'hourly/%d:00-%d:00_%d.%s.%d' % (now.hour, now.hour+1, now.day, 30 | abbr_month_name, now.year) 31 | dfn = 'daily/%d.%s.%d' % (now.day, abbr_month_name, now.year) 32 | wfn = 'weekly/%d-%d_%s.%d' % (start_day_of_week, end_day_of_week, abbr_month_name, 33 | now.year) 34 | mfn = 'monthly/%s.%d' % (abbr_month_name, now.year) 35 | 36 | return [('hourly', hfn), ('daily', dfn), ('weekly', wfn), ('monthly', mfn)] 37 | 38 | # TODO: Write a mock way to simulate traffic from a pcap file(for testing) 39 | 40 | class SipDDSniffer(object): 41 | """ 42 | XXX 43 | 44 | Note: I don't care too much about thread-safety since data intensive stuff happens 45 | on files, only simple conf./status is passed between threads. 46 | """ 47 | 48 | def __init__(self, args): 49 | self.args = args 50 | self.in_packet_rate_limit=self.args.inbound_traffic_rate_in_kbps/MAX_UDP_SIP_PACKET_SIZE 51 | 52 | self.total_len_in_bytes = 0 53 | self.current_rate_in_kpbs = 0 # kbps 54 | self.counters = {} 55 | self.rates = {} 56 | 57 | def _load_rates(self): 58 | for period, file_name in _get_dump_file_names(): 59 | try: 60 | with open(file_name + '.rates', 'rb') as f: 61 | self.rates[period] = pickle.load(f) 62 | except FileNotFoundError: 63 | self.rates[period] = {'total_sum':0, 'sample_count': 0, 'max': 0} 64 | 65 | def current_edge(self, period): 66 | return self.current_rate_in_kpbs 67 | 68 | def normal_edge(self, period): 69 | return self.rates[period]['total_sum'] / self.rates[period]['sample_count'] 70 | 71 | def attack_edge(self, period): 72 | return self.rates[period]['max'] 73 | 74 | def suspect_edge(self, period): 75 | return (self.attack_edge(period) + self.normal_edge(period)) / 2 76 | 77 | def current_limit(self, period): 78 | return (self.current_edge(period) / MAX_UDP_SIP_PACKET_SIZE) 79 | 80 | def normal_limit(self, period): 81 | return (self.normal_edge(period) / MAX_UDP_SIP_PACKET_SIZE) 82 | 83 | def suspect_limit(self, period): 84 | return (self.suspect_edge(period) / MAX_UDP_SIP_PACKET_SIZE) 85 | 86 | def attack_limit(self, period): 87 | return (self.attack_edge(period) / MAX_UDP_SIP_PACKET_SIZE) 88 | 89 | def _calc_rate(self): 90 | PACKET_DROP_INTERVAL = 5*60 # secs 91 | prev_tot_len = self.total_len_in_bytes 92 | while(True): 93 | self.current_rate_in_kpbs = \ 94 | (self.total_len_in_bytes-prev_tot_len) / 1024 / RATE_CALCULATE_INTERVAL 95 | prev_tot_len = self.total_len_in_bytes 96 | 97 | # save rates 98 | for period, file_name in _get_dump_file_names(): 99 | self.rates[period]['total_sum'] += self.current_rate_in_kpbs 100 | self.rates[period]['sample_count'] += 1 101 | self.rates[period]['max'] = max(self.rates[period]['max'], self.current_rate_in_kpbs) 102 | with open(file_name + '.rates', 'wb') as f: 103 | pickle.dump(self.rates[period], f) 104 | 105 | if self.current_edge(period) > self.suspect_edge(period) or \ 106 | self.current_limit(period) > self.suspect_limit(period): 107 | 108 | # traverse all counters and check if any of them exceeds the suspect limit 109 | for rule_no, counter in self.counters['rules'].items(): 110 | for ip, v in counter.items(): 111 | if v > self.suspect_limit(period): 112 | print('Rule %d is activated. There may be an attack' 113 | ' from %s.' % (rule_no, ip)) 114 | # TODO: Send email 115 | if v > self.attack_limit(period): 116 | print('There was an attack from %s. SIP packets are being' 117 | ' blocked for %d mins.' % (ip, PACKET_DROP_INTERVAL//60)) 118 | # TODO: Send email 119 | # TODO: Drop packets 120 | # current SIP traffic is more than %95 of SIP packet rate limit 121 | if v >= ((95*self.in_packet_rate_limit) // 100): 122 | print('There was an attack from %s.(in_packet_rate saturated.) SIP packets are being' 123 | ' blocked for %d mins.' % (ip, PACKET_DROP_INTERVAL//60)) 124 | # TODO: Send email 125 | # TODO: Drop packets 126 | 127 | # counters hold the rule related data 128 | self.counters = {'rules': {1: Counter(), 2: Counter(),}} 129 | 130 | time.sleep(RATE_CALCULATE_INTERVAL) 131 | 132 | def _on_pkt_recv(self, pkt): 133 | try: 134 | print("packet received...") 135 | for _, file_name in _get_dump_file_names(): 136 | wrpcap(file_name + '.pcap', pkt, append=True) 137 | 138 | self.total_len_in_bytes += pkt.len 139 | 140 | try: 141 | # TODO: For lab purpose we will use the IP address in From header in the Application Layer. 142 | src_ip = pkt[IP].src 143 | dst_ip = pkt[IP].dst 144 | sip_data = pkt[Raw].load.decode('utf-8') 145 | 146 | # TODO: I am sure there is a better alternative to extract CSeq 147 | # value from a sip msg but this simply works. 148 | cseq = None 149 | sip_data_splitted = sip_data.split() 150 | for i, a in enumerate(sip_data_splitted): 151 | if a == b'CSeq:': 152 | cseq = sip_data_splitted[i+1] 153 | break 154 | if cseq is None: 155 | raise Exception("CSeq not found.") 156 | except IndexError: 157 | return 158 | 159 | # Rule-1 160 | if any(x in sip_data for x in ['INVITE sip', 'REGISTER sip']): 161 | self.counters['rules'][1][src_ip] += 1 162 | 163 | # Rule-2 164 | if any(x in sip_data for x in ['INVITE sip', 'REGISTER sip']): 165 | self.counters['rules'][2][dst_ip] += 1 166 | 167 | except Exception as e: 168 | import traceback; traceback.print_exc() 169 | 170 | def _sniff(self): 171 | sniff(iface=self.args.dev_name, prn=self._on_pkt_recv, 172 | filter=self.args.bpf_filter, store=0) 173 | 174 | def start(self): 175 | self._load_rates() 176 | 177 | self._rate_calculator_thread = threading.Thread(target=self._calc_rate, args=()) 178 | self._rate_calculator_thread.start() 179 | 180 | self._sniffer_thread = threading.Thread(target=self._sniff, args=()) 181 | self._sniffer_thread.start() 182 | 183 | def main(): 184 | parser = argparse.ArgumentParser(description='SIP DoS Defense Tool') 185 | parser.add_argument('--dev_name', '-d', type=str, required=True) 186 | parser.add_argument('--verbose', '-v', action='store_true') 187 | parser.add_argument('--bpf_filter', '-f', type=str, default='udp port 5060') 188 | parser.add_argument('--inbound_traffic_rate_in_kbps', '-t', type=int, required=True) 189 | 190 | args = parser.parse_args() 191 | 192 | # ensure save output dirs are in place 193 | for d in ['daily', 'hourly', 'weekly', 'monthly']: 194 | if not os.path.exists(d): 195 | os.makedirs(d) 196 | 197 | # start our sniffer 198 | sniffer = SipDDSniffer(args) 199 | sniffer.start() 200 | 201 | if __name__ == "__main__": 202 | main() 203 | 204 | """ 205 | a=rdpcap(_get_dump_file_names()[3]+'.pcap') 206 | for p in a: 207 | if IP in p: # can be IPv6 208 | print(p[IP].src) 209 | print(p[UDP]) 210 | #if Raw in p: 211 | print(p[Raw].load) 212 | #p.show() 213 | #print(dir(p)) 214 | #print(p[IP].src) 215 | #print(p[UDP]) 216 | """ 217 | --------------------------------------------------------------------------------