-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsip.py
765 lines (641 loc) · 24.7 KB
/
sip.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
################################################################################
#
# Stand-alone VoIP honeypot client (preparation for Dionaea integration)
# Copyright (c) 2010 Tobias Wulff (twu200 at gmail)
#
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
################################################################################
#
# Parts of the SIP response codes and a lot of SIP message parsing are taken
# from the Twisted Core: http://twistedmatrix.com/trac/wiki/TwistedProjects
#
################################################################################
import logging
import time
import random
import hashlib
from connection import connection
from sdp import parseSdpMessage, SdpParsingError
from config import g_config
# Shortcut to sip config
g_sipconfig = g_config['modules']['python']['sip']
# Setup logging mechanism
logger = logging.getLogger('sip')
logger.setLevel(logging.DEBUG)
logConsole = logging.StreamHandler()
logConsole.setLevel(logging.DEBUG)
logConsole.setFormatter(logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
logger.addHandler(logConsole)
TRYING = '100'
RINGING = '180'
CALL_FWD = '181'
QUEUED = '182'
PROGRESS = '183'
OK = '200'
ACCEPTED = '202'
MULTI_CHOICES = '300'
MOVED_PERMANENTLY = '301'
MOVED_TEMPORARILY = '302'
SEE_OTHER = '303'
USE_PROXY = '305'
ALT_SERVICE = '380'
BAD_REQUEST = '400'
UNAUTHORIZED = '401'
PAYMENT_REQUIRED = '402'
FORBIDDEN = '403'
NOT_FOUND = '404'
NOT_ALLOWED = '405'
NOT_ACCEPTABLE = '406'
PROXY_AUTH_REQUIRED = '407'
REQUEST_TIMEOUT = '408'
CONFLICT = '409'
GONE = '410'
LENGTH_REQUIRED = '411'
ENTITY_TOO_LARGE = '413'
URI_TOO_LARGE = '414'
UNSUPPORTED_MEDIA = '415'
UNSUPPORTED_URI = '416'
BAD_EXTENSION = '420'
EXTENSION_REQUIRED = '421'
INTERVAL_TOO_BRIEF = '423'
NOT_AVAILABLE = '480'
NO_TRANSACTION = '481'
LOOP = '482'
TOO_MANY_HOPS = '483'
ADDRESS_INCOMPLETE = '484'
AMBIGUOUS = '485'
BUSY_HERE = '486'
CANCELLED = '487'
NOT_ACCEPTABLE_HERE = '488'
REQUEST_PENDING = '491'
UNDECIPHERABLE = '493'
INTERNAL_ERROR = '500'
NOT_IMPLEMENTED = '501'
BAD_GATEWAY = '502'
UNAVAILABLE = '503'
GATEWAY_TIMEOUT = '504'
SIP_VERSION_NOT_SUPPORTED = '505'
MESSAGE_TOO_LARGE = '513'
BUSY_EVERYWHERE = '600'
DECLINE = '603'
DOES_NOT_EXIST = '604'
NOT_ACCEPTABLE_6xx = '606'
# SIP Responses from SIP Demystified by Gonzalo Camarillo
RESPONSE = {
# 1xx
TRYING: '100 Trying',
RINGING: '180 Ringing',
CALL_FWD: '181 Call is being forwarded',
QUEUED: '182 Queued',
PROGRESS: '183 Session progress',
# 2xx
OK: '200 OK',
ACCEPTED: '202 Accepted',
# 3xx
MULTI_CHOICES: '300 Multiple choices',
MOVED_PERMANENTLY: '301 Moved permanently',
MOVED_TEMPORARILY: '302 Moved temporarily',
SEE_OTHER: '303 See other',
USE_PROXY: '305 Use proxy',
ALT_SERVICE: '380 Alternative service',
# 4xx
BAD_REQUEST: '400 Bad request',
UNAUTHORIZED: '401 Unauthorized',
PAYMENT_REQUIRED: '402 Payment required',
FORBIDDEN: '403 Forbidden',
NOT_FOUND: '404 Not found',
NOT_ALLOWED: '405 Method not allowed',
NOT_ACCEPTABLE: '406 Not acceptable',
PROXY_AUTH_REQUIRED: '407 Proxy authentication required',
REQUEST_TIMEOUT: '408 Request time-out',
CONFLICT: '409 Conflict',
GONE: '410 Gone',
LENGTH_REQUIRED: '411 Length required',
ENTITY_TOO_LARGE: '413 Request entity too large',
URI_TOO_LARGE: '414 Request-URI too large',
UNSUPPORTED_MEDIA: '415 Unsupported media type',
UNSUPPORTED_URI: '416 Unsupported URI scheme',
BAD_EXTENSION: '420 Bad extension',
EXTENSION_REQUIRED: '421 Extension required',
INTERVAL_TOO_BRIEF: '423 Interval too brief',
NOT_AVAILABLE: '480 Temporarily not available',
NO_TRANSACTION: '481 Call leg/transaction does not exist',
LOOP: '482 Loop detected',
TOO_MANY_HOPS: '483 Too many hops',
ADDRESS_INCOMPLETE: '484 Address incomplete',
AMBIGUOUS: '485 Ambiguous',
BUSY_HERE: '486 Busy here',
CANCELLED: '487 Request cancelled',
NOT_ACCEPTABLE_HERE: '488 Not acceptable here',
REQUEST_PENDING: '491 Request pending',
UNDECIPHERABLE: '493 Undecipherable',
# 5xx
INTERNAL_ERROR: '500 Internal server error',
NOT_IMPLEMENTED: '501 Not implemented',
BAD_GATEWAY: '502 Bad gateway',
UNAVAILABLE: '503 Service unavailable',
GATEWAY_TIMEOUT: '504 Gateway time-out',
SIP_VERSION_NOT_SUPPORTED: '505 SIP version not supported',
MESSAGE_TOO_LARGE: '513 Message too large',
# 6xx
BUSY_EVERYWHERE: '600 Busy everywhere',
DECLINE: '603 Decline',
DOES_NOT_EXIST: '604 Does not exist anywhere',
NOT_ACCEPTABLE_6xx: '606 Not acceptable'
}
# SIP headers have short forms
shortHeaders = {"call-id": "i",
"contact": "m",
"content-encoding": "e",
"content-length": "l",
"content-type": "c",
"from": "f",
"subject": "s",
"to": "t",
"via": "v",
"cseq": "cseq",
"accept": "accept",
"user-agent": "user-agent",
"max-forwards": "max-forwards",
"www-authentication": "www-authentication",
"authorization": "authorization"
}
longHeaders = {}
for k, v in shortHeaders.items():
longHeaders[v] = k
del k, v
class SipParsingError(Exception):
"""Exception class for errors occuring during SIP message parsing"""
def parseSipMessage(msg):
"""Parses a SIP message (string), returns a tupel (type, firstLine, header,
body)"""
# Sanitize input: remove superfluous leading and trailing newlines and
# spaces
msg = msg.strip("\n\r\t ")
# Split request/status line plus headers and body: we don't care about the
# body in the SIP parser
parts = msg.split("\n\n", 1)
if len(parts) < 1:
logger.error("Message too short")
raise SipParsingError("Message too short")
msg = parts[0]
# Python way of doing a ? b : c
body = len(parts) == 2 and parts[1] or ""
# Normalize line feed and carriage return to \n
msg = msg.replace("\n\r", "\n")
# Split lines into a list, each item containing one line
lines = msg.split('\n')
# Get message type (first word, smallest possible one is "ACK" or "BYE")
sep = lines[0].find(' ')
if sep < 3:
raise SipParsingError("Malformed request or status line")
msgType = lines[0][:sep]
firstLine = lines[0][sep+1:]
# Done with first line: delete from list of lines
del lines[0]
# Parse header
headers = {}
for i in range(len(lines)):
# Take first line and remove from list of lines
line = lines.pop(0)
# Strip each line of leading and trailing whitespaces
line = line.strip("\n\r\t ")
# Break on empty line (end of headers)
if len(line.strip(' ')) == 0:
break
# Parse header lines
sep = line.find(':')
if sep < 1:
raise SipParsingError("Malformed header line (no ':')")
# Get header identifier (word before the ':')
identifier = line[:sep]
identifier = identifier.lower()
# Check for valid header
if identifier not in shortHeaders.keys() and \
identifier not in longHeaders.keys():
raise SipParsingError("Unknown header type: {}".format(identifier))
# Get long header identifier if necessary
if identifier in longHeaders.keys():
identifier = longHeaders[identifier]
# Get header value (line after ':')
value = line[sep+1:].strip(' ')
# The Via header can occur multiple times
if identifier == "via":
if identifier not in headers:
headers["via"] = [value]
else:
headers["via"].append(value)
# Assign any other header value directly to the header key
else:
headers[identifier] = value
# Return message type, header dictionary, and body string
return (msgType, firstLine, headers, body)
class RtpUdpStream(connection):
"""RTP stream that can send data and writes the whole conversation to a
file"""
def __init__(self, address, port):
connection.__init__(self, 'udp')
# Bind to free random port for incoming RTP traffic
self.bind(('',0))
self.__localport = self.getsockname()[1]
# The address and port of the remote host
self.__address = address
self.__port = port
# Send byte buffer
self.__sendBuffer = b''
# Create a stream dump file with date and time and random ID in case of
# flooding attacks
dumpDateTime = time.strftime("%Y%m%d_%H:%M:%S")
dumpId = random.randint(1000, 9999)
streamDumpFile = "stream_{0}_{1}.rtpdump".format(dumpDateTime, dumpId)
# Catch IO errors
try:
self.__streamDump = open(streamDumpFile, "wb")
except IOError as e:
logger.error("Could not open stream dump file: {}".format(e))
self.__streamDump = None
logger.debug("Created RTP channel :{} <-> :{}".format(
self.__localport, self.__port))
def writable(self):
return len(self.__sendBuffer) > 0
def handle_close(self):
self.close()
def handle_read(self):
# Don't have to get address and port because they're already known since
# __init__
logger.debug("Incoming RTP data ...")
data, _ = self.recvfrom(1024)
# Write data to disk
# TODO: Make sure this cannot cause DoS
if self.__streamDump:
self.__streamDump.write(data)
def handle_write(self):
# Because of the writable function, handle_write will only be called if
# there is data in the send buffer
bytesSent = self.send(self.__sendBuffer)
# Write the sent part of the buffer to the stream dump file
# TODO: separate inbound and outbound traffic?
if self.__streamDump:
self.__streamDump.write(self.__sendBuffer[:bytesSend])
# Shift sending window for next send or handle_write operation
self.__sendBuffer = self.__sendBuffer[bytesSend:]
def send(self, msg):
# Append to send buffer, handle_write will take care of socket operation
self.__sendBuffer += msg.encode('utf-8')
def close(self):
if self.__streamDump:
self.__streamDump.close()
connection.close(self)
class SipSession(object):
"""Usually, a new SipSession instance is created when the SIP server
receives an INVITE message"""
NO_SESSION, SESSION_SETUP, ACTIVE_SESSION, SESSION_TEARDOWN = range(4)
sipConnection = None
def __init__(self, conInfo, rtpPort, inviteHeaders):
if not SipSession.sipConnection:
logger.error("SIP connection class variable not set")
# Store incoming information of the remote host
self.__inviteHeaders = inviteHeaders
self.__state = SipSession.SESSION_SETUP
self.__remoteAddress = conInfo[0]
self.__remoteSipPort = conInfo[1]
self.__remoteRtpPort = rtpPort
# Generate static values for SIP messages
global g_sipconfig
self.__sipTo = inviteHeaders['from']
self.__sipFrom = "{0} <sip:{0}@{1}>".format(g_sipconfig['user'],
g_sipconfig['ip'])
self.__sipVia = "SIP/2.0/UDP {}:{}".format(g_sipconfig['ip'],
g_sipconfig['port'])
# Create RTP stream instance and pass address and port of listening
# remote RTP host
self.__rtpStream = RtpUdpStream(self.__remoteAddress,
self.__remoteRtpPort)
# Send 180 Ringing to make honeypot appear more human-like
# TODO: Delay between 180 and 200
msgLines = []
msgLines.append("SIP/2.0 " + RESPONSE[RINGING])
msgLines.append("Via: " + self.__sipVia)
msgLines.append("Max-Forwards: 70")
msgLines.append("To: " + self.__sipTo)
msgLines.append("From: " + self.__sipFrom)
msgLines.append("Call-ID: {}".format(self.__inviteHeaders['call-id']))
msgLines.append("CSeq: 1 INVITE")
msgLines.append("Contact: " + self.__sipFrom)
msgLines.append("User-Agent: " + g_sipconfig['useragent'])
SipSession.sipConnection.send('\n'.join(msgLines))
# Send our RTP port to the remote host as a 200 OK response to the
# remote host's INVITE request
logger.debug("getsockname: {}".format(self.__rtpStream.getsockname()))
localRtpPort = self.__rtpStream.getsockname()[1]
msgLines = []
msgLines.append("SIP/2.0 " + RESPONSE[OK])
msgLines.append("Via: " + self.__sipVia)
msgLines.append("Max-Forwards: 70")
msgLines.append("To: " + self.__sipTo)
msgLines.append("From: " + self.__sipFrom)
msgLines.append("Call-ID: {}".format(self.__inviteHeaders['call-id']))
msgLines.append("CSeq: 1 INVITE")
msgLines.append("Contact: " + self.__sipFrom)
msgLines.append("User-Agent: " + g_sipconfig['useragent'])
msgLines.append("Content-Type: application/sdp")
msgLines.append("\nv=0")
msgLines.append("o=... 0 0 IN IP4 localhost")
msgLines.append("t=0 0")
msgLines.append("m=audio {} RTP/AVP 0".format(localRtpPort))
SipSession.sipConnection.send('\n'.join(msgLines))
def handle_ACK(self, headers, body):
if self.__state == SipSession.SESSION_SETUP:
logger.debug(
"Waiting for ACK after INVITE -> got ACK -> active session")
logger.info("Connection accepted (session {})".format(
self.__inviteHeaders['call-id']))
# Set current state to active (ready for multimedia stream)
self.__state = SipSession.ACTIVE_SESSION
def handle_BYE(self, headers, body):
global g_sipconfig
# Only close down RTP stream if session is active
if self.__state == SipSession.ACTIVE_SESSION:
self.__rtpStream.close()
# A BYE ends the session immediately
self.__state = SipSession.NO_SESSION
# Send OK response to other client
msgLines = []
msgLines.append("SIP/2.0 200 OK")
msgLines.append("Via: " + self.__sipVia)
msgLines.append("Max-Forwards: 70")
msgLines.append("To: " + self.__sipTo)
msgLines.append("From: " + self.__sipFrom)
msgLines.append("Call-ID: {}".format(self.__inviteHeaders['call-id']))
msgLines.append("CSeq: 1 BYE")
msgLines.append("Contact: " + self.__sipFrom)
msgLines.append("User-Agent: " + g_sipconfig['useragent'])
SipSession.sipConnection.send('\n'.join(msgLines))
class Sip(connection):
"""Only UDP connections are supported at the moment"""
def __init__(self):
connection.__init__(self, 'udp')
# Set SIP connection in session class variable
SipSession.sipConnection = self
# Dictionary with SIP sessions (key is call-id)
self.__sessions = {}
def send(self, s):
logger.debug("sending to ({}:{})".format(
self.__remoteAddress, self.__remoteSipPort))
self.sendto(s.encode('utf-8'),
(self.__remoteAddress, self.__remoteSipPort))
def handle_read(self):
"""Callback for handling incoming SIP traffic"""
# TODO: Handle long messages
data, conInfo = self.recvfrom(1024)
self.__remoteAddress = conInfo[0]
self.__remoteSipPort = conInfo[1]
# Get byte data and decode to string
data = data.decode("utf-8")
# Parse SIP message
try:
msgType, firstLine, headers, body = parseSipMessage(data)
except SipParsingError as e:
logger.error(e)
return
if msgType == 'INVITE':
self.sip_INVITE(firstLine, headers, body)
elif msgType == 'ACK':
self.sip_ACK(firstLine, headers, body)
elif msgType == 'OPTIONS':
self.sip_OPTIONS(firstLine, headers, body)
elif msgType == 'BYE':
self.sip_BYE(firstLine, headers, body)
elif msgType == 'CANCEL':
self.sip_CANCEL(firstLine, headers, body)
elif msgType == 'REGISTER':
self.sip_REGISTER(firstLine, headers, body)
elif msgType == 'SIP/2.0':
self.sip_RESPONSE(firstLine, headers, body)
elif msgType == 'Error':
logger.error("Error on parsing SIP message")
else:
logger.error("Error: unknown header")
# SIP message type handlers
def sip_INVITE(self, requestLine, headers, body):
global g_sipconfig
# Print SIP header
logger.info("Received INVITE")
for k, v in headers.items():
logger.info("SIP header {}: {}".format(k, v))
if self.__checkForMissingHeaders(headers, ["accept", "content-type"]):
return
# Check authentication
if g_sipconfig['use_authentication']:
r = self.__challengeINVITE(headers)
if not r: return
# Header has to define Content-Type: application/sdp if body contains
# SDP message. Also, Accept has to be set to sdp so that we can send
# back a SDP response.
if headers["content-type"] != "application/sdp":
logger.error("INVITE without SDP message: exit")
return
if headers["accept"] != "application/sdp":
logger.error("INVITE without SDP message: exit")
return
# Check for SDP body
if not body:
logger.error("INVITE without SDP message: exit")
return
# Parse SDP part of session invite
try:
sessionDescription, mediaDescriptions = parseSdpMessage(body)
except SdpParsingError as e:
logger.error(e)
return
# Check for all necessary fields
sdpSessionOwnerParts = sessionDescription['o'].split(' ')
if len(sdpSessionOwnerParts) < 6:
logger.error("SDP session owner field to short: exit")
return
logger.debug("Parsed SDP message:")
logger.debug(sessionDescription)
logger.debug(mediaDescriptions)
# Get RTP port from SDP media description
if len(mediaDescriptions) < 1:
logger.error("SDP message has to include a media description: exit")
return
mediaDescriptionParts = mediaDescriptions[0]['m'].split(' ')
if mediaDescriptionParts[0] != 'audio':
logger.error("SDP media description has to be of audio type: exit")
return
rtpPort = mediaDescriptionParts[1]
# Read Call-ID field and create new SipSession instance on first INVITE
# request received (remote host might send more than one because of time
# outs or because he wants to flood the honeypot)
callId = headers["call-id"]
if callId in self.__sessions:
logger.info("SIP session with Call-ID {} already exists".format(
callId))
return
# Establish a new SIP session
newSession = SipSession((self.__remoteAddress, self.__remoteSipPort),
rtpPort, headers)
# Store session object in sessions dictionary
self.__sessions[callId] = newSession
def sip_ACK(self, requestLine, headers, body):
logger.info("Received ACK")
if self.__checkForMissingHeaders(headers):
return
# Get SIP session for given Call-ID
try:
s = self.__sessions[headers["call-id"]]
except KeyError:
logger.error("Given Call-ID does not belong to a session: exit")
return
# Handle incoming ACKs depending on current state
s.handle_ACK(headers, body)
def sip_OPTIONS(self, requestLine, headers, body):
logger.info("Received OPTIONS")
# Construct OPTIONS response
global g_sipconfig
msgLines = []
msgLines.append("SIP/2.0 " + RESPONSE[OK])
msgLines.append("Via: SIP/2.0/UDP {}:{}".format(g_sipconfig['ip'],
g_sipconfig['port']))
msgLines.append("To: " + headers['from'])
msgLines.append("From: {0} <sip:{0}@{1}>".format(g_sipconfig['user'],
g_sipconfig['ip']))
msgLines.append("Call-ID: " + headers['call-id'])
msgLines.append("CSeq: " + headers['cseq'])
msgLines.append("Contact: {0} <sip:{0}@{1}>".format(g_sipconfig['user'],
g_sipconfig['ip']))
msgLines.append("Allow: INVITE, ACK, CANCEL, OPTIONS, BYE")
msgLines.append("Accept: application/sdp")
msgLines.append("Accept-Language: en")
self.send('\n'.join(msgLines))
def sip_BYE(self, requestLine, headers, body):
logger.info("Received BYE")
if self.__checkForMissingHeaders(headers):
return
# Get SIP session for given Call-ID
try:
s = self.__sessions[headers["call-id"]]
except KeyError:
logger.error("Given Call-ID does not belong to a session: exit")
return
# Handle incoming BYE request depending on current state
s.handle_BYE(headers, body)
def sip_CANCEL(self, requestLine, headers, body):
logger.info("Received CANCEL")
# Check mandatory headers
if self.__checkForMissingHeaders(headers):
return
# Get Call-Id and check if there's already a SipSession
callId = headers['call-id']
# Get CSeq to find out which request to cancel
cseq = headers['cseq'].split(' ')
cseqNumber = cseq[0]
cseqMethod = cseq[1]
if cseqMethod == "INVITE" or cseqMethod == "ACK":
# Find SipSession and delete it
if callId not in self.__sessions:
logger.info(
"CANCEL request does not match any existing SIP session")
return
# No RTP connection has been made yet so deleting the session
# instance is sufficient
del self.__session[callId]
# Construct CANCEL response
global g_sipconfig
msgLines = []
msgLines.append("SIP/2.0 " + RESPONSE[OK])
msgLines.append("Via: SIP/2.0/UDP {}:{}".format(g_sipconfig['ip'],
g_sipconfig['port']))
msgLines.append("To: " + headers['from'])
msgLines.append("From: {0} <sip:{0}@{1}>".format(g_sipconfig['user'],
g_sipconfig['ip']))
msgLines.append("Call-ID: " + headers['call-id'])
msgLines.append("CSeq: " + headers['cseq'])
msgLines.append("Contact: {0} <sip:{0}@{1}>".format(g_sipconfig['user'],
g_sipconfig['ip']))
self.send('\n'.join(msgLines))
def sip_REGISTER(self, requestLine, headers, body):
logger.info("Received REGISTER")
def sip_RESPONSE(self, statusLine, headers, body):
logger.info("Received a response")
def __checkForMissingHeaders(self, headers, mandatoryHeaders=[]):
"""
Check for specific missing headers given as a list in the second
argument are present as keys in the dictionary of headers.
If list of mandatory headers is omitted, a set of common standard
headers is used: To, From, Call-ID, CSeq, and Contact.
"""
if not mandatoryHeaders:
mandatoryHeaders = ["to", "from", "call-id", "cseq", "contact"]
headerMissing = False
for m in mandatoryHeaders:
if m not in headers:
logger.warning("Mandatory header {} not in message".format(m))
headerMissing = True
return headerMissing
def __challengeINVITE(self, headers):
global g_sipconfig
def hash(s):
return hashlib.md5(s.encode('utf-8')).hexdigest()
nonce = hash("{}".format(time.time()))
if "authorization" not in headers:
# Send 401 Unauthorized response
msgLines = []
msgLines.append('SIP/2.0 ' + RESPONSE[UNAUTHORIZED])
msgLines.append("Via: SIP/2.0/UDP {}:{}".format(
g_sipconfig['ip'], g_sipconfig['port']))
msgLines.append("To: " + headers['from'])
msgLines.append("From: {0} <sip:{0}@{1}>".format(
g_sipconfig['user'], g_sipconfig['ip']))
msgLines.append("Call-ID: " + headers['call-id'])
msgLines.append("CSeq: " + headers['cseq'])
msgLines.append("Contact: {0} <sip:{0}@{1}>".format(
g_sipconfig['user'], g_sipconfig['ip']))
msgLines.append('WWW-Authenticate: Digest ' + \
'realm="{}@{}",'.format(g_sipconfig['user'],
g_sipconfig['ip']) + \
'nonce="{}",'.format(nonce) + \
'opaque="{}"'.format('1234567890'))
self.send('\n'.join(msgLines))
else:
# Check against config file
authMethod, authLine = headers['authorization'].split(' ', 1)
if authMethod != 'Digest':
logger.error("Authorization is not Digest")
return
# Get Authorization header parts (a="a", b="b", c="c", ...) and put
# them in a dictionary for easy lookup
authLineParts = [x.strip(' \t\r\n') for x in authLine.split(',')]
authLineDict = {}
for x in authLineParts:
parts = x.split('=')
authLineDict[parts[0]] = parts[1].strip(' \n\r\t"\'')
# The calculation of the expected response is taken from
# Sipvicious (c) Sandro Gaucci
# TODO: compare config values to values in Authorization header
realm = "{}@{}".format(g_sipconfig['user'], g_sipconfig['ip'])
uri = "sip:" + realm
a1 = hash("{}:{}:{}".format(
g_sipconfig['user'], realm, g_sipconfig['secret']))
a2 = hash("INVITE:{}".format(uri))
expected = hash("{}:{}:{}".format(a1, nonce, a2))
if expected != authLineDict['response']:
logger.error("Authorization failed")
return
return expected, authLineDict['response']