├── requirements.txt
├── .gitignore
├── sipcheck.service
├── whitelist.txt
├── sipcheck.conf.sample
├── README.md
├── sipcheck.py
└── LICENSE.txt
/requirements.txt:
--------------------------------------------------------------------------------
1 | panoramisk==1.3
2 | configparser==4.0.2
3 | pygtail==0.11.1
4 | asyncio==0.4.1
5 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | #python specific
2 | *.pyc
3 | build/*
4 | dist/*
5 | MANIFEST
6 | sipcheck.conf
7 |
8 | ## generic files to ignore
9 | *~
10 | *.lock
11 | *.DS_Store
12 | *.swp
13 | *.conf
14 | *.db
15 | tmp/
16 | *.egg-info/
17 |
--------------------------------------------------------------------------------
/sipcheck.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=SIPCheck
3 |
4 | [Service]
5 | ExecStart=/opt/sipcheck/sipcheck.py
6 | WorkingDirectory=/opt/sipcheck
7 | Restart=always
8 | RestartSec=10
9 | StandardOutput=syslog
10 | StandardError=syslog
11 | SyslogIdentifier=sipcheck
12 |
13 | [Install]
14 | WantedBy=multi-user.target
15 |
--------------------------------------------------------------------------------
/whitelist.txt:
--------------------------------------------------------------------------------
1 | # This list should include the IP addresses (only IP addresses, not hostnames) that we don't want banned.
2 | # Important note: If one of this IP addresses already is into the firewall, sipcheck will delete these rule to unban this IP.
3 | # Recommended for servers, providers, friends, testing, etc.
4 | 31.211.185.235
5 | 213.98.65.123
6 | 10.10.10.10
7 | 10.10.12.12
8 |
--------------------------------------------------------------------------------
/sipcheck.conf.sample:
--------------------------------------------------------------------------------
1 | ###################################################################
2 | ## Config file sample
3 | ##
4 | ## Please, create a copy of this file called `sipcheck.conf` and
5 | ## modify as your own configuration.
6 | ###################################################################
7 |
8 | [manager]
9 | # IP or hostname where is the Asterisk (generally localhost)
10 | host = 127.0.0.1
11 | port = 5038
12 | username = mngrUser
13 | password = mngrP4ssW0rd
14 |
15 | [log]
16 | # Asterisk log messages
17 | asterisklog = /var/log/asterisk/messages
18 |
19 | # One of this possible values: DEBUG, INFO, WARNING, ERROR, CRITICAL
20 | level = INFO
21 |
22 | # Filename where
23 | file = /var/log/sipcheck.log
24 |
25 | [attacker]
26 | # Maximun number of wrong passwords before to insert into the blacklist
27 | maxNumTries = 5
28 |
29 | # Maximum number of INVITES without auth allowed before to consider it an attack
30 | maxNumInvites = 4
31 |
32 | # Time in seconds that one IP address will be holded into the blacklist ()
33 | BLExpireTime = 86400
34 |
35 | # Time in seconds that one IP address will be retained as a friend to trust
36 | WLExpireTime = 21600
37 |
38 | # Time in seconds that one IP address will be holded as a suspected of attack
39 | TLExpireTime = 3600
40 |
41 | # Chain of IPTables that will be used to DROP or ACCEPT the attackers or friends addresses.
42 | iptablesChain = INPUT
43 |
44 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
SIPCheck v.3.0
2 |
3 | ## Introduction
4 |
5 | SIPCheck is a tool that watch the authentication of users of Asterisk and bans automatically if some user (or bot) try to register o make calls using wrong passwords.
6 |
7 | Unlike Fail2Ban, SIPCheck manage, not just the attacker, also the clients that you have trust so if you have SIP users that has demostrated that they are trusted, it will don't ban although we receive wrong password, because it would means that lots of SIP clients behind of this IP could be banned too.
8 |
9 | For this reason, we have redesign from scratch this application with several features respect of older versions.
10 |
11 | - **Easier**: Easy of installing, configure and execute.
12 | - **Resources**: Oriented to great systems with a lot number of simoultaneous calls, avoiding access to log files and parsing of lots of real time information.
13 | - **Persistent**: Don't worry if you have to restart the application or the system, SIPCheck keep the attackers into the firewall when it start again.
14 | - **Confidable**: New system of expire time will keep the IPTable clean of old attackers avoiding unending and uncontrollable lists.
15 | - **Control**: Using the small config file `sipcheck.conf`, you can control the number of tries before to ban the access, the time that attackers will be on the firewall and the time that suspected users will be under watch.
16 |
17 | ## Requirements
18 |
19 | SIP Check requires been executed in the same system where Asterisk run. (it could run in other system but the firewall will be used in the same system where it run).
20 | SIPCheck needs **root privileges** to be able to insert and remove rules into the firewall.
21 |
22 | ### Python 3
23 | SIPCheck 3 works using Python 3 and the libraries defined in `requirements.txt`
24 |
25 | ### Asterisk manager account
26 | `/etc/asterisk/manager.conf` must have some manager user like this (change user and password variables):
27 |
28 | You have create a new user of [Asterisk Manager Interface](https://wiki.asterisk.org/wiki/display/AST/The+Asterisk+Manager+TCP+IP+API).
29 | ```ini
30 | [CHANGETHISUSER]
31 | secret = CHANGETHISPASSWORD
32 | deny = 0.0.0.0/0.0.0.0
33 | permit = 127.0.0.1/255.255.255.255
34 | read = security
35 | write = system
36 | ```
37 |
38 | Once created/modified this user, you have to reload manager configuration:
39 | ```bash
40 | asterisk -rx 'manager reload'
41 | ```
42 |
43 | ## How to Install
44 |
45 | ```bash
46 | # Download github repository
47 | git clone https://github.com/sinologicnet/sipcheck.git /opt/sipcheck
48 | cd /opt/sipcheck
49 |
50 | # Update repositories
51 | apt-get update
52 |
53 | # Install PIP for Python3
54 | apt-get install python3-pip
55 |
56 | # Install the libraries required
57 | pip3 install -r requirements.txt
58 |
59 | # Copy the sample of configuration file into a official configuration file
60 | cp sipcheck.conf.sample sipcheck.conf
61 |
62 | # Edit this file to configure SIPCheck
63 | nano sipcheck.conf
64 |
65 | # Make executable sipcheck.py
66 | chmod 777 sipcheck.py
67 |
68 | # Insert the script into systemd
69 | cp /opt/sipcheck/sipcheck.service /etc/systemd/system/
70 | systemctl enable sipcheck
71 |
72 | # Start the application
73 | systemctl start sipcheck
74 |
75 | # Check if everything is working fine
76 | tail -f /var/log/sipcheck.log
77 | ```
78 |
79 | ## Real example of how it works...
80 | ```log
81 | 2020-03-14 19:25:51,309 INFO: -----------------------------------------------------
82 | 2020-03-14 19:25:51,309 INFO: Starting SIPCheck 3 ...
83 | 2020-03-14 19:25:51,309 INFO: + Added 185.53.88.49,1584140431 into blacklist again from the time: 1584140431
84 | 2020-03-14 19:25:51,309 INFO: BL: Detected attack from IP: '185.53.88.49' (Banning address)
85 | 2020-03-14 19:25:51,312 INFO: + Added 195.154.28.205,1584140431 into blacklist again from the time: 1584140431
86 | 2020-03-14 19:25:51,312 INFO: BL: Detected attack from IP: '195.154.28.205' (Banning address)
87 | 2020-03-14 19:25:51,313 INFO: + Added 92.246.85.154,1584140431 into blacklist again from the time: 1584140431
88 | 2020-03-14 19:25:51,313 INFO: BL: Detected attack from IP: '92.246.85.154' (Banning address)
89 | 2020-03-14 19:25:51,315 INFO: + Added 113.141.67.163,1584140431 into blacklist again from the time: 1584140431
90 | 2020-03-14 19:25:51,315 INFO: BL: Detected attack from IP: '113.141.67.163' (Banning address)
91 | 2020-03-14 19:25:51,317 INFO: + Added 192.227.132.19,1584140431 into blacklist again from the time: 1584140431
92 | 2020-03-14 19:25:51,317 INFO: BL: Detected attack from IP: '192.227.132.19' (Banning address)
93 | 2020-03-14 19:25:51,319 INFO: + Added 45.143.220.240,1584140431 into blacklist again from the time: 1584140431
94 | 2020-03-14 19:25:51,319 INFO: BL: Detected attack from IP: '45.143.220.240' (Banning address)
95 | 2020-03-14 19:25:51,321 INFO: + Added 45.143.221.59,1584200178 into blacklist again from the time: 1584200178
96 | 2020-03-14 19:25:51,321 INFO: BL: Detected attack from IP: '45.143.221.59' (Banning address)
97 | 2020-03-14 19:25:51,322 INFO: + Added 192.3.140.204,1584200178 into blacklist again from the time: 1584200178
98 | 2020-03-14 19:25:51,322 INFO: BL: Detected attack from IP: '192.3.140.204' (Banning address)
99 | 2020-03-14 19:25:51,324 INFO: + Added 185.221.135.138,1584200178 into blacklist again from the time: 1584200178
100 | 2020-03-14 19:25:51,324 INFO: BL: Detected attack from IP: '185.221.135.138' (Banning address)
101 | 2020-03-14 19:25:51,326 INFO: + Added 45.143.220.25,1584200178 into blacklist again from the time: 1584200178
102 | 2020-03-14 19:25:51,326 INFO: BL: Detected attack from IP: '45.143.220.25' (Banning address)
103 | 2020-03-14 19:25:51,331 INFO: + Added 10.10.10.10 into whitelist during one year
104 | 2020-03-14 19:25:51,332 INFO: + Added 10.10.12.12 into whitelist during one year
105 | 2020-03-14 19:25:51,341 INFO: protocol version: '5.0.0'
106 | 2020-03-14 19:25:51,342 INFO: Sending awaiting actions
107 | 2020-03-14 19:47:09,842 WARNING: Received anonymous INVITE from IP 91.212.38.210
108 | 2020-03-14 20:47:14,776 INFO: TL: Expired time for 91.212.38.210
109 | 2020-03-14 21:14:17,786 WARNING: Received wrong password for user Administrator from IP 45.234.152.38
110 | 2020-03-14 21:50:28,963 WARNING: Received wrong password for user administrator from IP 45.234.152.38
111 | 2020-03-14 22:07:02,806 WARNING: Received wrong password for user 10 from IP 45.234.152.38
112 | 2020-03-14 22:14:18,490 INFO: TL: Expired time for 45.234.152.38
113 | 2020-03-14 22:24:22,969 WARNING: Received anonymous INVITE from IP 45.143.220.220
114 | 2020-03-14 22:43:22,100 WARNING: Received wrong password for user 11 from IP 45.234.152.38
115 | 2020-03-14 23:19:42,874 WARNING: Received wrong password for user 100 from IP 45.234.152.38
116 | 2020-03-14 23:24:26,489 INFO: TL: Expired time for 45.143.220.220
117 | 2020-03-14 23:27:28,488 WARNING: Received anonymous INVITE from IP 45.143.220.214
118 | ```
119 |
--------------------------------------------------------------------------------
/sipcheck.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | '''
5 | sipCheck v.3.0
6 | ---------------------------
7 | This application connects into the Asterisk Manager Interface (v11 or newer) and reads the Security Events received when some user try send
8 | INVITE or REGISTER and when it happens SIPCheck classify the IP address into 'friends' or, if the user continues sending wrong passwords,
9 | into 'attackers'.
10 |
11 | SIPCheck counts the number of failed tries per IP Address so, if this address is not into a white list, and the tries are exceeded the limits
12 | automatically will be baned during some time.
13 |
14 | The new purpous of this application is ban attackers and automatically clean the IP past some time to avoid the firewall be bigger and bigger
15 |
16 | If some IP address auth correctly, it is consider a "friend who trust" and it will be classified into white list to avoid be banned although
17 | some SIP client send wrong passwords. (maybe this SIP users belongs a company with some phones and one of them are badly configured).
18 |
19 | You can find more information at:
20 | https://github.com/sinologicnet/sipcheck
21 |
22 | If you have questions or suggestions, you can use this page:
23 | https://github.com/sinologicnet/sipcheck/issues
24 |
25 | Authors:
26 | Elio Rojano, Sergio Cotelo, Javier Vidal, Tomás Sahagún
27 |
28 | Thanks to:
29 | Jose Luis Verdeguer (testing)
30 | Aitor Martin (fix and corrections)
31 |
32 | Email:
33 | sipcheck@sinologic.net
34 |
35 | '''
36 |
37 | import time
38 | import io
39 | import os
40 | import re
41 | import sys
42 | import socket
43 | import logging
44 | import asyncio
45 | import configparser
46 | from pygtail import Pygtail
47 | from panoramisk import Manager
48 | from threading import Thread
49 | from threading import RLock
50 |
51 | lock = RLock()
52 |
53 | # We parser the config file
54 | config = configparser.ConfigParser()
55 | dir = os.path.dirname(os.path.abspath(__file__))
56 | config.read(dir+'/sipcheck.conf')
57 |
58 | if ('manager' in config):
59 | managerHost = config['manager']['host']
60 | managerPort = int(config['manager']['port'])
61 | managerUser = config['manager']['username']
62 | managerPass = config['manager']['password']
63 | else:
64 | managerHost = "127.0.0.1"
65 | managerPort = 5038
66 | managerUser = "manageruser"
67 | managerPass = "SuPeR@p4ssw0rd123"
68 |
69 | if ('log' in config):
70 | logLevel = config['log']['level']
71 | logFile = config['log']['file']
72 | else:
73 | logLevel = "DEBUG"
74 | logFile = "/var/log/sipcheck.log"
75 |
76 | if ('attacker' in config):
77 | maxNumTries = int(config['attacker']['maxNumTries'])
78 | maxNumInvitesWithoutAuth = int(config['attacker']['maxNumInvites'])
79 | BLExpireTime = int(config['attacker']['BLExpireTime'])
80 | WLExpireTime = int(config['attacker']['WLExpireTime'])
81 | TLExpireTime = int(config['attacker']['TLExpireTime'])
82 | iptablesChain = config['attacker']['iptablesChain']
83 | else:
84 | maxNumTries = 5
85 | BLExpireTime = 86400
86 | WLExpireTime = 21600
87 | TLExpireTime = 3600
88 | iptablesChain = "INPUT"
89 |
90 |
91 | # We connect into a Asterisk Manager (Asterisk 11 or newer with Security permissions to read)
92 | manager = Manager(loop=asyncio.get_event_loop(), host=managerHost, port=managerPort, username=managerUser, secret=managerPass)
93 |
94 | # Set the logging system to dump everything we do
95 | logging.basicConfig(filename=logFile,level=logging.DEBUG,format='%(asctime)s %(levelname)s: %(message)s')
96 | Log = logging.getLogger()
97 | level = logging.getLevelName(logLevel)
98 | Log.setLevel(level)
99 |
100 | logging.debug("Configured Blacklist expire time: "+str(BLExpireTime))
101 | logging.debug("Configured Whitelist expire time: "+str(WLExpireTime))
102 | logging.debug("Configured Templist expire time: "+str(TLExpireTime))
103 |
104 | # We set the lists where we storage the addresses.
105 | templist={} # Suspected addresses
106 | whitelist={} # Trusted addresses
107 | blacklist={} # Attackers addresses
108 | invitelist={} # Invite control
109 |
110 | ## Function that counts the tries and insert the address into the suspected list.
111 | def templist_counter(ip,score=1.0):
112 | if (ip not in whitelist) and (ip not in blacklist):
113 | if (ip in templist):
114 | templist[ip]['intentos']=templist[ip]['intentos']+score
115 | else:
116 | templist[ip]={'intentos':score,'time':int(time.time())}
117 | output=templist[ip]['intentos']
118 | elif (ip in whitelist):
119 | if (score < 1):
120 | logging.warning("Detected INVITE from "+ip+" but this address is whitelisted.")
121 | else:
122 | logging.warning("Detected wrong password for "+ip+" but this address is whitelisted.")
123 | output=0
124 | else: # It shouldn't happen
125 | logging.warning("Detected suspected behaviour for "+ip+" but this address is blacklisted.")
126 | output=0
127 |
128 | return output
129 |
130 |
131 | ## Function that counts the tries and insert the address into the suspected list.
132 | def invitelist_counter(ip,score=1.0):
133 | if (ip not in whitelist) and (ip not in blacklist):
134 | if (ip in invitelist):
135 | invitelist[ip]['veces']=invitelist[ip]['veces']+score
136 | else:
137 | invitelist[ip]={'veces':score,'time':int(time.time())}
138 | output=invitelist[ip]['veces']
139 | else: # It shouldn't happen
140 | output=0
141 |
142 | return output
143 |
144 |
145 | ## Function that insert the rule to drop everything from the ip into the iptables
146 | def ban(ip):
147 | if (not isbanned(ip)):
148 | logging.info("Banned IP: "+ip)
149 | os.popen("iptables -A "+iptablesChain+" -s "+ip+" -j DROP")
150 |
151 |
152 | ## Function that delete the rule to drop everything from the ip into the iptables
153 | def unban(ip):
154 | if (isbanned(ip)):
155 | logging.info("Unbaned IP: "+ip)
156 | os.popen("iptables -D "+iptablesChain+" -s "+ip+" -j DROP")
157 |
158 |
159 | ## Returns if an IP Address is the iptables list
160 | def isbanned(ip):
161 | salidaIptables=os.popen("iptables -L "+iptablesChain+" -n").read().replace(" ","#").replace("\n","")
162 | out=False
163 | if ("#"+ip+"#" in salidaIptables): # we uses '#' to sure that we don't confuse with pieces of others ip addresses
164 | out=True
165 | return out
166 |
167 |
168 | def create_blackfile():
169 | f = open("/tmp/blacklist.dat", "w")
170 | f.write("# This file is generated automatically by SIPCheck 3, so please, dont modify it\n\n")
171 | for t in blacklist:
172 | f.write(t+","+str(blacklist[t])+"\n")
173 | f.close()
174 |
175 |
176 | ## Function that add an IP address into a whitelist (and remove from list of suspected)
177 | def insert_to_whitelist(ip,hastacuando=time.time()):
178 | if ip not in [y for x in whitelist for y in x.split()]:
179 | whitelist[ip]=int(hastacuando) # Insert into the whitelist
180 | if (ip in templist): # Extract from suspected list (to save memory)
181 | templist.pop(ip, None)
182 | if (ip in invitelist):
183 | invitelist.pop(ip, None)
184 | # note: I know that we should haven't this ip address into the blacklist, but if it happen, we remove too. ;)
185 | if (ip in blacklist):
186 | blacklist.pop(ip, None)
187 |
188 |
189 | ## Function that add an IP address into a blacklist (and remove from list of suspected)
190 | def insert_to_blacklist(ip,cuando=time.time()):
191 | if ip not in [y for x in blacklist for y in x.split()]:
192 | logging.info("BL: Detected attack from IP: '"+ip+"' (Banning address)")
193 | blacklist[ip]=int(cuando); # Insert the address and the time into the blacklist
194 | ban(ip)
195 | create_blackfile()
196 | if (ip in templist): # Remove from suspected list (to save memory)
197 | templist.pop(ip, None)
198 | if (ip in invitelist):
199 | invitelist.pop(ip, None)
200 |
201 |
202 | ## Function that is executed when an 'invalidPassword' is received
203 | def invalidPassword(evento):
204 | logging.warning("Received wrong password for user "+evento['AccountID']+" from IP "+evento["RemoteAddress"])
205 | # We check if the IP address is in the whitelist
206 | # If it isn't into the whitelist, we increment the counter until the number of tries will be greater that the 'maxNumTries' constant
207 | num = templist_counter(evento['RemoteAddress'],1.0)
208 | if (num > maxNumTries):
209 | insert_to_blacklist(evento['RemoteAddress'])
210 |
211 | def inviteWithoutAuth(evento):
212 | logging.warning("Received anonymous INVITE from IP "+evento["RemoteAddress"])
213 | # We check if the IP address is in the whitelist
214 | # If it isn't into the whitelist, we increment the counter until the number of tries will be greater that the 'maxNumTries' constant
215 | num = templist_counter(evento['RemoteAddress'],1.0)
216 | if (num > maxNumTries):
217 | insert_to_blacklist(evento['RemoteAddress'])
218 |
219 | ## Function that is executed when a 'ChallengeSent' is received
220 | def inviteSend(evento):
221 | logging.debug("Received invite user "+evento['AccountID']+" from IP "+evento["RemoteAddress"])
222 | # We check if the IP address is in the whitelist
223 | # If it isn't into the whitelist, we increment the counter until the number of tries will be greater that the 'maxNumTries' constant
224 | num = invitelist_counter(evento['RemoteAddress'],1.0)
225 | if (num > maxNumInvitesWithoutAuth):
226 | insert_to_blacklist(evento['RemoteAddress'])
227 |
228 |
229 | ## Function that is executed when a 'successfulAuth' is received
230 | def successfulAuth(evento):
231 | logging.debug("Received right password for user "+evento['AccountID']+" from IP "+evento["RemoteAddress"])
232 | # We insert the IP address into the whitelist
233 | insert_to_whitelist(evento['RemoteAddress'])
234 |
235 |
236 | ## Function to filter the string with IPv4 IP address from the manager object and returns just the IP address.
237 | def getIP(stringip):
238 | ## We get the string "IPV4/UDP/X.X.X.X/5062" and we need only "X.X.X.X"
239 | paramsIP=stringip.strip().split("/")
240 | salida=""
241 | if (len(paramsIP) > 3):
242 | salida=paramsIP[2]
243 | return salida
244 |
245 |
246 | ## Returns if a string is a valid IP address
247 | def isValidIP(address):
248 | try:
249 | socket.inet_pton(socket.AF_INET, address)
250 | except AttributeError:
251 | try:
252 | socket.inet_aton(address)
253 | except socket.error:
254 | return False
255 | return address.count('.') == 3
256 | except socket.error:
257 | return False
258 | return True
259 |
260 |
261 | ## Function that go through the lists checking the time when the addresses was inserted and if this time is greater than the Expiretime configured, it removes the addresses of these lists.
262 | def expireRecord():
263 | now=int(time.time())
264 | # We search the elements with the time expired.
265 | listaABorrar=[]
266 | for t in blacklist:
267 | if (now - blacklist[t] > BLExpireTime):
268 | logging.info("BL: Expired time for "+t)
269 | listaABorrar.append(t)
270 |
271 | # ... and we remove the elements found
272 | for t1 in listaABorrar:
273 | blacklist.pop(t1, None)
274 | unban(t1) # Lo extraemos del firewall
275 | create_blackfile() # We update the blacklist file with actual records
276 |
277 | # We search the elements with the time expired.
278 | listaABorrar=[]
279 | for t in whitelist:
280 | if (now - whitelist[t] > WLExpireTime):
281 | logging.info("WL: Expired time for "+t)
282 | listaABorrar.append(t)
283 | # ... and we remove the elements found
284 | for t1 in listaABorrar:
285 | whitelist.pop(t1, None)
286 |
287 | # We search the elements with the time expired.
288 | listaABorrar=[]
289 | for t in templist:
290 | if (now - templist[t]['time'] > TLExpireTime):
291 | logging.info("TL: Expired time for "+t)
292 | listaABorrar.append(t)
293 | # ... and we remove the elements found
294 | for t1 in listaABorrar:
295 | templist.pop(t1, None)
296 |
297 | # Uncomment this block to see updately the content of the lists (only for development)
298 | if (logLevel == "DEBUG"):
299 | print("-----------| "+time.strftime('%y-%m-%d %T')+" |---------------")
300 | print("blacklist "+str(blacklist))
301 | print("whitelist "+str(whitelist))
302 | print("templist "+str(templist))
303 | print("invitelist "+str(invitelist))
304 |
305 |
306 | ## Function that execute "expireRecord" function each 5 seconds
307 | def expire():
308 | while True:
309 | #logging.debug("Executing expire process...")
310 | expireRecord() # We process the lists to remove the expired records
311 | time.sleep(5)
312 |
313 |
314 | ## It register the manager event that warning when the user send a right authentication
315 | @manager.register_event('SuccessfulAuth')
316 | def callback(manager, message):
317 | message['RemoteAddress']=getIP(message.RemoteAddress.replace('"',''))
318 | if (message['RemoteAddress'] != "127.0.0.1"):
319 | logging.debug(message)
320 | successfulAuth(message)
321 |
322 |
323 | ## It register the manager event that warning when the user send a wrong authentication
324 | @manager.register_event('InvalidPassword')
325 | def callback(manager, message):
326 | message['RemoteAddress']=getIP(message.RemoteAddress.replace('"',''))
327 | logging.debug(message)
328 | invalidPassword(message)
329 |
330 |
331 | '''
332 | ## It register the manager event that warning when the user send a wrong authentication
333 | @manager.register_event('ChallengeSent')
334 | def callback(manager, message):
335 | message['RemoteAddress']=getIP(message.RemoteAddress.replace('"',''))
336 | logging.debug(message)
337 | inviteSend(message)
338 | '''
339 |
340 |
341 | ## Function that insert the addresses located in whitelist.txt file, into the whitelist without expiretime.
342 | def load_whitelist_file():
343 | dir = os.path.dirname(os.path.abspath(__file__))
344 | wlfile = dir+"/whitelist.txt"
345 | logging.debug("Reading "+wlfile+" to insert IP address into Whitelist table...")
346 | if (os.path.exists(wlfile)):
347 | with io.open(wlfile) as fp:
348 | line = fp.readline()
349 | cnt = 1
350 | while line:
351 | content = line.strip()
352 | if (content != "") and (content[0] != "#") and (isValidIP(content)):
353 | logging.info("+ Added "+content+" into whitelist during one year")
354 | insert_to_whitelist(content,time.time()+(60*60*24*365))
355 | unban(content) # If this address has been banned sometime, we try to remove this ban
356 | line = fp.readline()
357 | cnt += 1
358 |
359 |
360 | ## Function that insert the addresses located in blacklist.txt file, into the blacklist (and ban them again if they wasn't on the iptables).
361 | # If the time when they was banned is greater than BLExpireTime, the thread of ExpireTime will remove this address again.
362 | def load_blacklist_file():
363 | blfile="/tmp/blacklist.dat"
364 | logging.debug("Reading "+blfile+" to insert IP address into Blacklist table...")
365 | if (os.path.exists(blfile)):
366 | with io.open(blfile) as fp:
367 | line = fp.readline()
368 | cnt = 1
369 | while line:
370 | content = line.strip()
371 | if (content != "") and (content[0] != "#"):
372 | registro = content.split(",")
373 | if (len(registro) == 2) and (isValidIP(registro[0])):
374 | if (content not in whitelist):
375 | logging.info("+ Added "+content+" into blacklist again from the time: "+str(registro[1]))
376 | insert_to_blacklist(registro[0],registro[1])
377 | line = fp.readline()
378 | cnt += 1
379 |
380 |
381 | ## System to parse the Asterisk message file searching INVITES without Authentication or trials of calls annoying.
382 | def tailLogFile(filename):
383 | while True:
384 | for line in Pygtail(filename, offset_file="/tmp/sipcheck.tmp", read_from_end=True):
385 | yield line
386 | time.sleep(1.0)
387 |
388 | def parseLog():
389 | if (config['log']['asterisklog']):
390 | filename=config['log']['asterisklog']
391 | else:
392 | filename="/var/log/asterisk/messages"
393 |
394 | if (config['log']['level'] == "DEBUG"):
395 | logging.info("Checking %s ..." % filename)
396 |
397 | if (os.path.isfile(filename)):
398 | generator = tailLogFile(filename)
399 | for line in generator:
400 | analizeLog(line)
401 | else:
402 | logging.error("!! Asterisk logfile %s not found. Please, check this file in sipcheck.conf" % filename)
403 |
404 | def analizeLog(line):
405 | # Maybe there are some future patters to detect others attacks
406 | termsToSearch=[
407 | "rejected because extension not found in context 'public'"
408 | ]
409 | for term in termsToSearch:
410 | if (term in line):
411 | detectedAttack=True
412 | try:
413 | IP = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', line).group()
414 | except:
415 | IP = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', line)
416 | if (IP):
417 | if (logLevel == "DEBUG"):
418 | print("Detected anonymous attack from %s" % str(IP))
419 |
420 | event={'RemoteAddress':str(IP)}
421 | inviteWithoutAuth(event)
422 |
423 |
424 | ## Main function
425 | def main():
426 | logging.info('-----------------------------------------------------')
427 | logging.info('Starting SIPCheck 3 ...')
428 | load_blacklist_file()
429 | load_whitelist_file()
430 | manager.connect()
431 | try:
432 | # We create an asyncronous thread that check the expiretime of the lists
433 | Thread(name='expireRecord', target = expire).start()
434 | # Thread for parsing Asterisk message log file
435 | Thread(name='parseLog', target = parseLog).start()
436 | # Run the manager loop
437 | manager.loop.run_forever()
438 | except KeyboardInterrupt:
439 | manager.loop.close()
440 |
441 |
442 | if __name__ == '__main__':
443 | main()
444 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 |
294 | Copyright (C)
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | , 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------