-
Notifications
You must be signed in to change notification settings - Fork 4
/
rcs_client_demo.py
1322 lines (1124 loc) · 65.8 KB
/
rcs_client_demo.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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import ssl
import sys
import uuid
import time
import socket
import logging
import hashlib
import secrets
import datetime
import requests
import sslkeylog
from argparse import ArgumentParser
from colorlog import ColoredFormatter
import rcs_client_constants as CONST
sslkeylog.set_keylog("sslkeylog-rcs-tls.txt")
# log.basicConfig(stream=sys.stderr, level=CONST.LOG_LEVEL, format=CONST.LOG_FMT)
logging.root.setLevel(CONST.LOG_LEVEL)
formatter = ColoredFormatter(CONST.LOG_FMT)
stream = logging.StreamHandler()
stream.setLevel(CONST.LOG_LEVEL)
stream.setFormatter(formatter)
log = logging.getLogger('pythonConfig')
log.setLevel(CONST.LOG_LEVEL)
log.addHandler(stream)
class Utils():
def __init__(self):
pass
@staticmethod
def get_ip_address(ip = "8.8.8.8", port = 80):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((ip, port))
return s.getsockname()[0]
@staticmethod
def get_ip_address_from_socket(sock):
return sock.getsockname()[0]
@staticmethod
def find_1st_occurrence(re_pattern, text):
textObj = re.search(re_pattern, text)
if textObj:
return textObj.group(1)
else:
return ""
@staticmethod
def find_all_occurrence(re_pattern, text):
return re.findall(re_pattern, text)
@staticmethod
def calc_sip_digest_auth(username, realm, password, uri, nonce):
str1 = hashlib.md5("{}:{}:{}".format(username, realm, password).encode('utf-8')).hexdigest()
str2 = hashlib.md5("REGISTER:{}".format(uri).encode('utf-8')).hexdigest()
return hashlib.md5("{}:{}:{}".format(str1,nonce,str2).encode('utf-8')).hexdigest()
@staticmethod
def get_utc_time(time_datetime):
return time_datetime.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
@staticmethod
def time_since_1900_sec():
epoch_time_sec = 2208988800
return int(time.time()) + epoch_time_sec
class ArgumentsException(Exception):
pass
class Arguments():
def __init__(self):
self.parser = ArgumentParser()
self.add_arguments()
self.parse_args()
self.validate()
def parse_args(self):
# Parse the supplied arguments and map each one to an attribute on
# the Argument object.
for k, v in self.parser.parse_args().__dict__.items():
setattr(self, k, v)
def validate(self):
if not self.sim_mode:
if self.realm == CONST.SIM_RCS_REALM:
log.warning("No SIP realm provided, using default Fi RCS realm.")
self.realm = CONST.FI_RCS_REALM
try:
assert re.match(CONST.REGEX_MSISDN, str(self.username)) is not None
except AssertionError as ae:
log.warning("No username provided or illegal format in the username provided.")
log.warning("Using default username instead.")
self.username = CONST.DEMO_USERNAME
if not self.password:
raise ArgumentsException("In non-sim mode, please specify the user's password with '-p'")
else:
try:
assert re.match(CONST.REGEX_SIP_PASSWORD, str(self.password)) is not None
except AssertionError as ae:
raise ArgumentsException("Illegal character or wrong length in the password provided!")
try:
assert re.match(CONST.REGEX_MSISDN, str(self.receiver)) is not None
except AssertionError as ae:
log.warning("No receiver provided or illegal format in the receiver provided.")
log.warning("Using default reciver's MSISDN instead.")
self.receiver = CONST.DEMO_RECEIVER
else:
if not self.password:
log.warning("No password provided, using default demo password.")
self.password = CONST.DEMO_SIP_PWD
else:
try:
assert re.match(CONST.REGEX_SIP_PASSWORD, str(self.password)) is not None
except AssertionError as ae:
log.warning("Illegal character or wrong format in the password provided!")
log.warning("Using default demo password: {pwd}".format(pwd = CONST.DEMO_SIP_PWD))
self.password = CONST.DEMO_SIP_PWD
def add_arguments(self):
self.parser.add_argument('-u',
'--username',
dest='username',
default=CONST.DEMO_USERNAME,
# action='store_true',
help='Username (in MSISDN format) for SIP')
self.parser.add_argument('-p',
'--pwd',
dest='password',
default=None,
# action='store_true',
help='Auth Password for SIP')
self.parser.add_argument('-P',
'--port',
dest='port',
default=CONST.FI_RCS_PORT,
help='TCP port to use on SIP connection')
self.parser.add_argument('-r',
'--receiver',
dest='receiver',
default=CONST.DEMO_RECEIVER,
# action='store_true',
help='Receiver number (in MSISDN format) for SIP conversation')
self.parser.add_argument('-s',
'--realm',
dest='realm',
default=CONST.SIM_RCS_REALM,
# action='store_true',
help='SIP realm to register on')
self.parser.add_argument('-t',
'--transport',
dest='trans_proto',
default="tls",
# action='store_true',
help='Transport protocol to use for SIP')
self.parser.add_argument('--imei',
dest='imei',
default=CONST.DEMO_IMEI,
# action='store_true',
help='IMEI of the device')
self.parser.add_argument('--sim',
dest='sim_mode',
action='store_true',
default=False,
help='Use simulation mode (use pre-recorded responses instead of communicating with real server)')
class MsrpSession():
def __init__(self, to_path, from_path):
self.to_path = to_path
self.from_path = from_path
self.msrp_sess_id = ""
self.imdn_msg_id = ""
self.failure_report = "yes"
self.success_report = "no"
self.content_type = "message/cpim"
def init_send(self):
self.msrp_sess_id = secrets.token_hex(16)[:16]
self.imdn_msg_id = secrets.token_urlsafe(24)[:24]
msrp_msg = "MSRP " + self.msrp_sess_id + " SEND\r\n" \
+ "To-Path: {to_path}\r\n".format(to_path = self.to_path) \
+ "From-Path: {from_path}\r\n".format(from_path = self.from_path) \
+ "Message-ID: {message_id}\r\n".format(message_id = self.imdn_msg_id) \
+ "Failure-Report: {failure_report}\r\n".format(failure_report = self.failure_report) \
+ "Success-Report: {success_report}\r\n".format(success_report = self.success_report) \
+ "Byte-Range: 1-0/0\r\n" \
+ "-------{msrp_sess_id}$\r\n".format(msrp_sess_id = self.msrp_sess_id)
return msrp_msg
def send(self, imdn_msg_id, imdn_msg_len):
self.msrp_sess_id = secrets.token_hex(16)[:16]
# self.imdn_msg_id = secrets.token_urlsafe(24)[:24]
msrp_msg = "MSRP " + self.msrp_sess_id + " SEND\r\n" \
+ "To-Path: {to_path}\r\n".format(to_path = self.to_path) \
+ "From-Path: {from_path}\r\n".format(from_path = self.from_path) \
+ "Message-ID: {message_id}\r\n".format(message_id = imdn_msg_id) \
+ "Failure-Report: {failure_report}\r\n".format(failure_report = self.failure_report) \
+ "Success-Report: {success_report}\r\n".format(success_report = self.success_report) \
+ "Byte-Range: 1-{byte_range}/{byte_range}\r\n".format(byte_range = imdn_msg_len) \
+ "Content-Type: {content_type}\r\n".format(content_type = self.content_type) \
+ "\r\n"
return (msrp_msg, self.msrp_sess_id)
def ok(self, msrp_id):
msrp_msg = "MSRP " + msrp_id + " 200 OK\r\n" \
+ "To-Path: {to_path}\r\n".format(to_path = self.to_path) \
+ "From-Path: {from_path}\r\n".format(from_path = self.from_path) \
+ "-------:{msrp_id}$\r\n".format(message_id = msrp_id)
return msrp_msg
class SipHeaders():
def __init__(self, ip, username, receiver, p_cscf_addr, imei, port=20000, sip_ver=2, transport="tls", max_forwards=70, branch_prefix="z9hG4bK", user_agent=CONST.DEMO_RCS_UA):
self._ip = ip
self._port = port
self._username = username
self._receiver = receiver
self._p_cscf_addr = p_cscf_addr
self._imei = imei
self._user_agent = user_agent
self._max_forwards = max_forwards
# [TODO] Zengwen: the tag and branch are actually somehow correlated
# Needs further update
# the RFC 3261 says: "The combination of the To tag, From tag,
# and Call-ID completely defines a peer-to-peer SIP relationship
# between Alice and Bob and is referred to as a dialog.""
self._branch_prefix = branch_prefix
# self._supported = supported
self._authorization = "Digest"
self._allow_methods = "INVITE, ACK, BYE, CANCEL, NOTIFY, OPTIONS, MESSAGE"
self._p_access_network_info = "IEEE-802.11;i-wlan-node-id=000000000000"
self._expires = 600000
self._q = 0.5
if transport.lower() == "tls" or transport.lower() == "tcp" or transport.lower() == "udp":
self._transport = transport.upper()
else:
self._transport = "TCP"
if sip_ver == 2:
self._sip_ver = "2.0"
else:
self._sip_ver = "1.0"
def _build_sip_flags(self, capability="simple-im|chat|geopush|fthttp|chatbot"):
'''
Refer to GSMA RCC.07 v10.0. pp.33 of 398.
Should check pp.54 for more service tags
'''
self._rcs_iari_flag_prefix = "+g.3gpp.iari-ref"
self._rcs_icsi_flag_prefix = "+g.3gpp.icsi-ref"
self._rcs_callcomposer_flag = "+g.gsma.callcomposer"
self._rcs_ipcall_flag = "+g.gsma.rcs.ipcall"
self._rcs_chatbot_version_flag = "+g.gsma.rcs.botversion=\"#=0.92,#=1\""
self._rcs_cpm_ext_support_flag = "+g.gsma.rcs.cpmext"
self._rcs_chat_oma_simple_im_flag = "+g.oma.sip-im"
# self._rcs_flag_weight_flag = "expires=600000;q=0.5"
self._rcs_icsi_tag_standalone_messaging = "urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.msg,urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.largemsg,urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.deferred"
self._rcs_icsi_tag_chat_oma_cpm = "urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.session"
self._rcs_icsi_tag_callcomposer = "urn%3Aurn-7%3A3gpp-service.ims.icsi.gsma.callcomposer"
self._rcs_icsi_tag_postcall = "urn%3Aurn-7%3A3gpp-service.ims.icsi.gsma.callunanswered"
self._rcs_icsi_tag_sharedmap = "urn%3Aurn-7%3A3gpp-service.ims.icsi.gsma.sharedmap"
self._rcs_icsi_tag_sharedsketch = "urn%3Aurn-7%3A3gpp-service.ims.icsi.gsma.sharedsketch"
self._rcs_icsi_tag_ipcall = "urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel"
self._rcs_iari_tag_chat_oma_simple_im = "urn%3Aurn-7%3A3gpp-application.ims.iari.rcse.im"
self._rcs_iari_tag_ft = "urn%3Aurn-7%3A3gpp-application.ims.iari.rcse.ft"
self._rcs_iari_tag_joyn_intmsg = "urn%3Aurn-7%3A3gpp-application.ims.iari.joyn.intmsg"
self._rcs_iari_tag_fthttp = "urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.fthttp"
self._rcs_iari_tag_ftsms = "urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.ftsms"
self._rcs_iari_tag_geopush = "urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.geopush"
self._rcs_iari_tag_geosms = "urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.geosms"
self._rcs_iari_tag_chatbot = "urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.chatbot"
self._rcs_iari_tag_chatbot_standalone_msg = "urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.chatbot.sa"
self._rcs_iari_tag_plugin_support = "urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.plugin"
if capability == "simple-im|chat|geopush|fthttp|chatbot":
return "{};{}=\"{},{},{},{}\";{}".format(
self._rcs_chat_oma_simple_im_flag,
self._rcs_iari_flag_prefix,
self._rcs_iari_tag_chat_oma_simple_im,
self._rcs_iari_tag_geopush,
self._rcs_iari_tag_fthttp,
self._rcs_iari_tag_chatbot,
self._rcs_chatbot_version_flag
)
else: # used in capability definition in OPTIONS header
return "{};{}=\"{},{},{},{},{},{}\";{}".format(
self._rcs_chat_oma_simple_im_flag,
self._rcs_iari_flag_prefix,
self._rcs_iari_tag_chat_oma_simple_im,
self._rcs_iari_tag_ft,
self._rcs_iari_tag_geopush,
self._rcs_iari_tag_joyn_intmsg,
self._rcs_iari_tag_fthttp,
self._rcs_iari_tag_chatbot,
self._rcs_chatbot_version_flag
)
def set_call_id(self, call_id):
return "Call-Id: {id}\r\n".format(id = call_id)
def set_c_seq(self, c_seq, method):
return "CSeq: {c_seq} {method}\r\n".format(c_seq = c_seq, method = method)
def set_from(self, tag = uuid.uuid4()):
return "From: <tel:{username}>;tag={tag}\r\n".format(username = self._username, tag = tag)
def set_to(self, receiver, tag = ""):
return "To: <tel:{to}>{tag}\r\n".format(to = receiver, tag = tag)
def set_via(self, branch = secrets.token_urlsafe(10)[:10], options=";keep;server-keep;rport"):
return "Via: SIP/{sip_ver}/{transport} {ip}:{port};branch={branch_prefix}{branch}{options}\r\n".format(
sip_ver = self._sip_ver,
transport = self._transport,
ip = self._ip,
port = self._port,
branch_prefix = self._branch_prefix,
branch = branch,
options = options
)
def set_max_forwards(self):
return "Max-Forwards: {max_forwards}\r\n".format(max_forwards = self._max_forwards)
def set_accept_contact(self, capability="customized"):
return "Accept-Contact: *;{feature_tags};explicit\r\n".format(feature_tags = self._build_sip_flags(capability))
def set_accept_contact_invite(self, accept_contact):
return "Accept-Contact: *;{accept_contact}\r\n".format(accept_contact = accept_contact)
def set_contact(self, capability="simple-im|chat|geopush|fthttp|chatbot"):
self._sip_instance_tag = "+sip.instance=\"<urn:gsma:imei:{imei}>\"".format(imei = self._imei)
return "Contact: <sip:{username}@{ip}:{port};transport={transport}>;{identity};{feature_tags};expires={expires};q={q}\r\n".format(
username = self._username,
ip = self._ip,
port = self._port,
transport = self._transport.lower(),
identity = self._sip_instance_tag,
feature_tags = self._build_sip_flags(capability),
expires = self._expires,
q = self._q
)
def set_contact_options(self, capability="customized"):
self._sip_instance_tag = "+sip.instance=\"<urn:gsma:imei:{imei}>\"".format(imei = self._imei)
return "Contact: <sip:{username}@{ip}:{port};transport={transport}>;{identity};{feature_tags}\r\n".format(
username = self._username,
ip = self._ip,
port = self._port,
transport = self._transport.lower(),
identity = self._sip_instance_tag,
feature_tags = self._build_sip_flags(capability)
)
def set_contact_invite(self, feature_tags=";+g.oma.sip-im"):
self._sip_instance_tag = "+sip.instance=\"<urn:gsma:imei:{imei}>\"".format(imei = self._imei)
return "Contact: <sip:{username}@{ip}:{port};transport={transport}>;{identity}{feature_tags}\r\n".format(
username = self._username,
ip = self._ip,
port = self._port,
transport = self._transport.lower(),
identity = self._sip_instance_tag,
feature_tags = feature_tags
)
def set_accept(self):
return "Accept: application/sdp\r\n"
def set_supported(self, supported):
return "Supported: {supported}\r\n".format(supported = supported)
def set_session_expires(self, field):
return "Session-Expires: {val}\r\n".format(val = field)
def set_content_type(self, c_type):
return "Content-Type: {val}\r\n".format(val = c_type)
def set_contribution_id(self, contrib_id):
return "Contribution-ID: {val}\r\n".format(val = contrib_id)
def set_route(self, route_lst):
return "Route: <{route}>\r\n".format(route = ">,<".join(route_lst))
def set_p_preferred_identity(self):
return "P-Preferred-Identity: tel:{username}\r\n".format(username = self._username)
def set_user_agent(self):
return "User-Agent: {user_agent}\r\n".format(user_agent = self._user_agent)
def set_allow(self):
return "Allow: {allow_methods}\r\n".format(allow_methods = self._allow_methods)
def set_authorization(self, nonce, response):
return "Authorization: {authorization} username=\"{username}\",uri=\"sip:{p_cscf_addr}\",algorithm=MD5,realm=\"{p_cscf_addr}\",nonce=\"{nonce}\",response=\"{response}\"\r\n".format(
authorization = self._authorization,
username = self._username,
p_cscf_addr = self._p_cscf_addr,
nonce = nonce,
response = response)
def set_x_google_event_id(self):
return "X-Google-Event-Id: {x_google_event_id}\r\n".format(x_google_event_id = uuid.uuid4())
def set_p_access_network_info(self):
return "P-Access-Network-Info: {p_access_network_info}\r\n".format(p_access_network_info = self._p_access_network_info)
def set_content_length(self, len=0):
return "Content-Length: {content_len}\r\n".format(content_len=len)
class SipMessages():
def __init__(self, username, password, realm, ip, receiver, p_cscf_addr, imei):
self.username = username
self.password = password
self.receiver = receiver
self.realm = realm
self.uri = "sip:{}".format(self.realm)
self.ip = ip
self.headers = SipHeaders(ip, username, receiver, p_cscf_addr, imei)
self.status_code = 0
self.status_code_hldr = { '200' : self.status_hdlr_200,
'401' : self.status_hdlr_401,
'403' : self.status_hdlr_403,
'480' : self.status_hdlr_480,
'511' : self.status_hdlr_511,
'default' : self.status_hdlr_default}
self.nonce = ""
self.response = ""
self.received_ip = ""
self.rport = -1
self.server_nonce = False
self.path = ""
self.path_tag = ""
self.p_associated_uri = ""
self.route_lst = []
self.call_id = ""
self.contact_ack_route = ""
self.record_route_lst = []
self.to_tag = ""
self.from_tag = ""
self.delivered = False
self.displayed = False
self.needs_ok = False
self.msrp_srv_ip = ""
self.msrp_to_path = ""
self.msrp_from_path = ""
self.msrp_session_ready = False
self.ack_content_type = ""
def register(self, seq, call_id):
reg_str = "REGISTER sip:{realm} SIP/2.0\r\n".format(realm = self.realm)
reg_msg = reg_str + self.headers.set_call_id(call_id) \
+ self.headers.set_c_seq(seq, "REGISTER") \
+ self.headers.set_from("{tag}".format(tag = secrets.token_urlsafe(10)[:10] if seq == 1 else self.from_tag)) \
+ self.headers.set_to(self.username) \
+ self.headers.set_via(secrets.token_urlsafe(10)[:10]) \
+ self.headers.set_max_forwards() \
+ self.headers.set_contact() \
+ self.headers.set_supported("path,gruu") \
+ self.headers.set_p_preferred_identity() \
+ self.headers.set_user_agent() \
+ self.headers.set_allow() \
+ self.headers.set_authorization(self.nonce, self.response) \
+ self.headers.set_x_google_event_id() \
+ self.headers.set_p_access_network_info() \
+ self.headers.set_content_length(0) \
+ "\r\n"
return reg_msg
def options(self, seq, call_id):
options_str = "OPTIONS tel:{receiver} SIP/2.0\r\n".format(receiver = self.receiver)
options_msg = options_str + self.headers.set_call_id(call_id) \
+ self.headers.set_c_seq(seq, "OPTIONS") \
+ self.headers.set_from(secrets.token_urlsafe(10)[:10]) \
+ self.headers.set_to(self.receiver) \
+ self.headers.set_via(secrets.token_urlsafe(10)[:10], "") \
+ self.headers.set_max_forwards() \
+ self.headers.set_accept_contact() \
+ self.headers.set_contact_options() \
+ self.headers.set_accept() \
+ self.headers.set_route(self.route_lst) \
+ self.headers.set_p_preferred_identity() \
+ self.headers.set_user_agent() \
+ self.headers.set_allow() \
+ self.headers.set_x_google_event_id() \
+ self.headers.set_p_access_network_info() \
+ self.headers.set_content_length(0) \
+ "\r\n"
return options_msg
def invite(self, seq, call_id, my_ip, msg = "Hello", content_type = "text"):
boundary = secrets.token_urlsafe(11)[:11]
contrib_id = secrets.token_hex(32)[:32]
invite_body = self.compose_invite_body(my_ip, msg, boundary, content_type)
invite_str = "INVITE tel:{receiver} SIP/2.0\r\n".format(receiver = self.receiver)
invite_msg = invite_str + self.headers.set_call_id(call_id) \
+ self.headers.set_c_seq(seq, "INVITE") \
+ self.headers.set_from(secrets.token_urlsafe(10)[:10]) \
+ self.headers.set_to(self.receiver) \
+ self.headers.set_via(secrets.token_urlsafe(10)[:10], ";keep") \
+ self.headers.set_max_forwards() \
+ self.headers.set_contact_invite() \
+ self.headers.set_route(self.route_lst) \
+ self.headers.set_p_preferred_identity() \
+ self.headers.set_user_agent() \
+ self.headers.set_allow() \
+ self.headers.set_supported("timer") \
+ self.headers.set_session_expires("1800;refresher=uac") \
+ self.headers.set_content_type("multipart/mixed;boundary={}".format(boundary)) \
+ self.headers.set_contribution_id(contrib_id) \
+ self.headers.set_accept_contact_invite("+g.oma.sip-im") \
+ self.headers.set_x_google_event_id() \
+ self.headers.set_p_access_network_info() \
+ self.headers.set_content_length(len(invite_body)) \
+ "\r\n" \
+ "{invite_body}\r\n".format(invite_body = invite_body)
# log.debug("Composed INVITE message is:\n\n{}\n".format(invite_msg))
return invite_msg
def ok(self, seq, method):
ok_str = "SIP/2.0 200 OK \r\n".format(receiver = self.receiver)
ok_msg = ok_str + self.headers.set_via(self.from_tag, ";rport={rport};received={recv_ip}".format(rport = self.rport, recv_ip = self.received_ip)) \
+ self.headers.set_contact_invite() \
+ self.headers.set_to(self.receiver, ";{}".format(secrets.token_urlsafe(16)[:16])) \
+ self.headers.set_from(self.from_tag) \
+ self.headers.set_call_id(self.call_id) \
+ self.headers.set_c_seq(seq, method) \
+ self.headers.set_p_asserted_identity("") \
+ self.headers.set_x_google_event_id() \
+ self.headers.set_content_length(0)
# log.debug("Composed OK message is:\n\n{}\n".format(ok_msg))
return ok_msg
def ack(self, seq):
ack_str = "ACK {contact_ack_route} SIP/2.0\r\n".format(contact_ack_route = self.contact_ack_route)
ack_msg = ack_str + self.headers.set_call_id(self.call_id) \
+ self.headers.set_c_seq(seq, "ACK") \
+ self.headers.set_from(self.from_tag) \
+ self.headers.set_to(self.receiver, ";tag={}".format(self.to_tag)) \
+ self.headers.set_via(secrets.token_urlsafe(10)[:10], "") \
+ self.headers.set_max_forwards() \
+ self.headers.set_route(self.record_route_lst) \
+ self.headers.set_contact_invite("") \
+ self.headers.set_user_agent() \
+ self.headers.set_allow() \
+ self.headers.set_x_google_event_id() \
+ self.headers.set_content_length(0)
# log.debug("Composed ACK message is:\n\n{}\n".format(ack_msg))
return ack_msg
def compose_invite_body(self, my_ip, msg, boundary="bS5DQx0W7AA", content_type = "text"):
return "--{boundary}\r\n".format(boundary = boundary) \
+ "{sdp_msg}\r\n".format(sdp_msg = self.compose_sdp_msg(my_ip)) \
+ "--{boundary}\r\n".format(boundary = boundary) \
+ "{cpim_msg}\r\n".format(cpim_msg = self.compose_cpim_msg(msg, content_type)) \
+ "--{boundary}--\r\n".format(boundary = boundary)
def compose_rcs_body(self, rcs_type, content):
if rcs_type == "text":
return content
else:
return ""
def compose_rcs_msg(self, content_type, content):
rcs_body = self.compose_rcs_body(content_type, content)
if content_type == "text":
rcs_msg = "Content-Length: {length}\r\n".format(length = len(rcs_body)) \
+ "Content-Type: text/plain; charset=utf-8\r\n" \
+ "\r\n" \
+ rcs_body
elif content_type == "ft_http":
rcs_msg = "Content-Length: {length}\r\n".format(length = len(content)) \
+ "Content-Type: application/vnd.gsma.rcs-ft-http+xml; charset=utf-8\r\n" \
+ "\r\n" \
+ content
elif content_type == "geoloc_push":
rcs_msg = "Content-Length: {length}\r\n".format(length = len(content)) \
+ "Content-Type: application/vnd.gsma.rcspushlocation+xml; charset=utf-8\r\n" \
+ "\r\n" \
+ content
else:
rcs_msg = "Content-Length: {length}\r\n".format(length = 12) \
+ "Content-Type: text/plain; charset=utf-8\r\n" \
+ "\r\n" \
+ "Hello World!"
# log.debug("Composed RCS message is:\n\n{}\n".format(rcs_msg))
return rcs_msg
def compose_rcs_ft_body(self, data_url, filename, file_type, file_size, has_thumbnail = True, tb_url = "https://cdn4.iconfinder.com/data/icons/new-google-logo-2015/400/new-google-favicon-512.png", tb_file_type = "image/png", tb_file_size = 17908):
rcs_ft_xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" \
+ "<file xmlns=\"urn:gsma:params:xml:ns:rcs:rcs:fthttp\">" \
+ "<file-info type=\"thumbnail\">" \
+ "<file-size>{tb_file_size}</file-size>".format(tb_file_size = tb_file_size) \
+ "<content-type>{tb_file_type}</content-type>".format(tb_file_type = tb_file_type) \
+ "<data url=\"{tb_url}\" until=\"{tb_until}\"></data>".format(tb_url = tb_url, tb_until = Utils.get_utc_time(datetime.datetime.utcnow() + datetime.timedelta(days=180))) \
+ "</file-info>" \
+ "<file-info type=\"file\">" \
+ "<file-size>{file_size}</file-size>".format(file_size = file_size) \
+ "<file-name>{filename}</file-name>".format(filename = filename) \
+ "<content-type>image/jpeg</content-type>" \
+ "<data url=\"{data_url}\" branded-url=\"{data_url}\" until=\"{data_until}\"></data>".format(data_url = data_url, data_until = Utils.get_utc_time(datetime.datetime.utcnow() + datetime.timedelta(days=180))) \
+ "</file-info>" \
+ "</file>"
# log.debug("Composed RCS FT HTTP message is:\n\n{}\n".format(rcs_ft_xml))
return rcs_ft_xml
def compose_rcs_geolocation_push_body(self):
rcs_geo_xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" \
+ "<rcsenvelope entity=\"tel:{username}\" ".format(username = self.username) \
+ "xmlns=\"urn:gsma:params:xml:ns:rcs:rcs:geolocation\" " \
+ "xmlns:rpid=\"urn:ietf:params:xml:ns:pidf:rpid\" " \
+ "xmlns:gml=\"http://www.opengis.net/gml\" " \
+ "xmlns:gp=\"urn:ietf:params:xml:ns:pidf:geopriv10\" " \
+ "xmlns:gs=\"http://www.opengis.net/pidflo/1.0\" " \
+ "xmlns:dm=\"urn:ietf:params:xml:ns:pidf:data-model\">" \
+ "<rcspushlocation id=\"IgIQx0WCBA\" label=\"https://www.google.com/maps/place/Samueli+School+Samueli+School%2C+520+Portola+Plaza%2C+Los+Angeles%2C+CA+90095%2C+USA/\"> " \
+ "<gp:geopriv>" \
+ "<gp:location-info>" \
+ "<gs:Circle srsName=\"urn:ogc:def:crs:EPSG::4326\">" \
+ "<gml:pos>34.069820017616955 -118.44278275966646</gml:pos>" \
+ "<gs:radius uom=\"urn:ogc:def:uom:EPSG::9001\">0.0</gs:radius>" \
+ "</gs:Circle>" \
+ "</gp:location-info>" \
+ "<gp:usage-rules>" \
+ "<gp:retention-expiry>2019-09-14T17:29:35</gp:retention-expiry>" \
+ "</gp:usage-rules>" \
+ "</gp:geopriv>" \
+ "<timestamp>2019-09-14T12:29:35</timestamp>" \
+ "</rcspushlocation>" \
+ "</rcsenvelope>"
# log.debug("Composed RCS GEO PUSH message is:\n\n{}\n".format(rcs_geo_xml))
return rcs_geo_xml
def compose_imdn_msg(self, content = "Ok", content_type = "text"):
imdn_msg_id = secrets.token_urlsafe(24)[:24]
rcs_msg = self.compose_rcs_msg(content_type, content)
imdn_msg = "NS: imdn <urn:ietf:params:imdn>\r\n" \
+ "imdn.Disposition-Notification: positive-delivery, display\r\n" \
+ "imdn.Message-ID: {msg_id}\r\n".format(msg_id = imdn_msg_id) \
+ "To: <sip:[email protected]>\r\n" \
+ "From: <sip:[email protected]>\r\n" \
+ "DateTime: {time}\r\n".format(time = Utils.get_utc_time(datetime.datetime.utcnow())) \
+ "\r\n" \
+ rcs_msg
# log.debug("Composed IMDN message is:\n\n{}\n".format(imdn_msg))
return (imdn_msg, imdn_msg_id)
def compose_cpim_msg(self, msg, content_type = "text"):
imdn_msg, _ = self.compose_imdn_msg(msg, content_type)
cpim_msg = "Content-Type: message/cpim\r\n" \
+ "Content-Length: {length}\r\n".format(length = len(imdn_msg)) \
+ "\r\n" \
+ imdn_msg
# log.debug("Composed CPIM message is:\n\n{}\n".format(cpim_msg))
return cpim_msg
def compose_sdp_body(self, my_ip):
msrp_to_path_token = secrets.token_hex(32)[:32]
sdp_body = "v=0\r\n" \
+ "o={username} {time} {time} IN IP4 {ip}\r\n".format(username = self.username, time = Utils.time_since_1900_sec(), ip = my_ip) \
+ "s=-\r\n" \
+ "c=IN IP4 {ip}\r\n".format(ip = my_ip) \
+ "t=0 0\r\n" \
+ "m=message 9 TCP/TLS/MSRP *\r\n" \
+ "a=path:msrps://{ip}:9/{token};tcp\r\n".format(ip = my_ip, token = msrp_to_path_token) \
+ "a=fingerprint:SHA-1 {fingerprint}\r\n".format(fingerprint = "76:7C:2B:DA:26:8F:CB:25:D6:98:C3:EE:09:66:88:84:C7:BB:82:38") \
+ "a=connection:new\r\n" \
+ "a=setup:active\r\n" \
+ "a=accept-types:{accept_types}\r\n".format(accept_types = "message/cpim application/im-iscomposing+xml") \
+ "a=accept-wrapped-types:{accept_wrapped_types}\r\n".format(accept_wrapped_types = "text/plain application/vnd.gsma.rcs-ft-http+xml message/imdn+xml application/vnd.gsma.rcspushlocation+xml") \
+ "a=sendrecv\r\n"
self.msrp_from_path = "msrps://{ip}:9/{token};tcp".format(ip = my_ip, token = msrp_to_path_token)
return sdp_body
def compose_sdp_msg(self, my_ip):
sdp_body = self.compose_sdp_body(my_ip)
sdp_msg = self.headers.set_content_type("application/sdp") \
+ self.headers.set_content_length(len(sdp_body)) \
+ "\r\n" \
+ sdp_body
# log.debug("Composed SDP message is:\n\n{}\n".format(sdp_msg))
return sdp_msg
def calculate_response(self):
self.response = Utils.calc_sip_digest_auth(self.username, self.realm, self.password, self.uri, self.nonce)
# Some resource maybe worth looking at: https://github.com/racker/python-twisted-core/blob/master/twisted/protocols/sip.py
def message_parser(self, message):
msg_split = message.split("\r\n\r\n")
msg_header = msg_split[0]
if len(msg_split) > 1:
msg_body = msg_split[1:]
log.debug("Split message header:\n\n{}\n".format(msg_header))
log.debug("Split message body:\n\n{}\n".format(msg_body))
msg_header_lst = msg_header.split("\r\n")
log.debug("Found {} lines in total in the message header received.".format(len(msg_header_lst)))
log.debug("First line in message header:\n{}".format(msg_header_lst[0]))
if (msg_header_lst[0].startswith("SIP/")):
try:
# status_code = msg_header_lst[0].split(" ")[1]
# print(msg_header_lst)
# print("trying parser for {}".format(status_code))
# print(self.status_code_hldr[str(status_code)])
self.status_code_hldr[msg_header_lst[0].split(" ")[1]](msg_header_lst) # handle 200, 401, 511 SIP response
except Exception as e:
log.error("Received a response not in defined handlers!")
log.error(e)
self.status_code_hldr['default'](msg_header_lst) # handle other cases
elif (msg_header_lst[0].startswith("MESSAGE")):
if "status><delivered" in message:
self.delivered = True
log.warning("Received message deliver notification")
elif "status><displayed" in message:
self.displayed = True
log.warning("Received message display notification")
elif (msg_header_lst[0].startswith("OPTIONS")):
self.needs_ok = True
log.warning("Received message display notification")
if msg_body != "":
msg_body_lst = msg_body[0].split("\r\n")
self.sip_msg_body_hdlr(msg_body_lst)
def sip_msg_body_hdlr(self, msg_body_lst):
if self.ack_content_type == "sdp":
for l in msg_body_lst:
if l.startswith("c="):
self.msrp_srv_ip = Utils.find_1st_occurrence(r".*\s(.*)$", l)
log.debug("msrp_srv_ip:\n{}\n".format(self.msrp_srv_ip))
elif l.startswith("a=path:"):
self.msrp_to_path = l[7:]
log.debug("msrp_to_path:\n{}\n".format(self.msrp_to_path))
self.ack_content_type == ""
if self.msrp_srv_ip != "" and self.msrp_to_path != "":
self.msrp_session_ready = True
def status_hdlr_200(self, msg_header_lst):
log.debug("Entering status_hdlr_200()")
self.status_code = 200
for l in msg_header_lst:
if l.startswith("Via"):
self.header_parser_via(l)
elif l.startswith("Path"):
self.header_parser_path(l)
elif l.startswith("Service-Route"):
self.header_parser_service_route(l)
elif l.startswith("Record-Route"):
self.header_parser_record_route(l)
elif l.startswith("Contact"):
self.header_parser_contact(l)
elif l.startswith("To"):
self.header_parser_to(l)
elif l.startswith("From"):
self.header_parser_from(l)
elif l.startswith("Call-ID"):
self.header_parser_call_id(l)
elif l.startswith("Contact"):
self.header_parser_contact(l)
elif l.startswith("CSeq"):
self.header_parser_c_seq(l)
elif l.startswith("Content-Type"):
self.header_parser_content_type(l)
elif l.startswith("P-Associated-URI"):
self.header_parser_p_associated_uri(l)
elif l.startswith("X-Google-Event-Id"):
self.header_parser_x_google_event_id(l)
elif l.startswith("Content-Length"):
self.header_parser_content_length(l)
def status_hdlr_401(self, msg_header_lst):
log.debug("Entering status_hdlr_401()")
self.status_code = 401
for l in msg_header_lst:
if l.startswith("Via"):
self.header_parser_via(l)
elif l.startswith("To"):
self.header_parser_to(l)
elif l.startswith("From"):
self.header_parser_from(l)
elif l.startswith("Call-ID"):
self.header_parser_call_id(l)
elif l.startswith("CSeq"):
self.header_parser_c_seq(l)
elif l.startswith("WWW-Authenticate"):
self.header_parser_www_auth(l)
elif l.startswith("X-Google-Event-Id"):
self.header_parser_x_google_event_id(l)
elif l.startswith("Content-Length"):
self.header_parser_content_length(l)
def status_hdlr_403(self, msg_header_lst):
log.debug("Entering status_hdlr_403()")
self.status_code = 403
for l in msg_header_lst:
if l.startswith("Via"):
self.header_parser_via(l)
elif l.startswith("To"):
self.header_parser_to(l)
elif l.startswith("From"):
self.header_parser_from(l)
elif l.startswith("Call-ID"):
self.header_parser_call_id(l)
elif l.startswith("CSeq"):
self.header_parser_c_seq(l)
elif l.startswith("P-Charging-Vector"):
self.header_parser_p_charging_vector(l)
elif l.startswith("X-Google-Event-Id"):
self.header_parser_x_google_event_id(l)
elif l.startswith("Content-Length"):
self.header_parser_content_length(l)
def status_hdlr_480(self, msg_header_lst):
log.debug("Entering status_hdlr_480()")
self.status_code = 480
for l in msg_header_lst:
if l.startswith("Via"):
self.header_parser_via(l)
elif l.startswith("To"):
self.header_parser_to(l)
elif l.startswith("From"):
self.header_parser_from(l)
elif l.startswith("Call-ID"):
self.header_parser_call_id(l)
elif l.startswith("CSeq"):
self.header_parser_c_seq(l)
elif l.startswith("P-Asserted-Identity"):
self.header_parser_p_associated_identity(l)
elif l.startswith("X-Google-Event-Id"):
self.header_parser_x_google_event_id(l)
elif l.startswith("Content-Length"):
self.header_parser_content_length(l)
def status_hdlr_511(self, msg_header_lst):
log.debug("Entering status_hdlr_511()")
self.status_code = 511
pass
def status_hdlr_default(self, msg_header_lst):
log.debug("Entering status_hdlr_default()")
self.status_code = self.status_code = msg_header_lst[0].split(" ")[1]
def header_parser_via(self, message):
self.rport = Utils.find_1st_occurrence(r"rport=(\d+);", message)
self.received_ip = Utils.find_1st_occurrence(r"received=(.*)$", message)
log.debug(self.rport)
log.debug(self.received_ip)
def header_parser_path(self, message):
self.path = Utils.find_1st_occurrence(r"<(.*)>", message)
self.path_tag = Utils.find_1st_occurrence(r";(.*)>", message)
self.route_lst.append("{path};transport={transport}".format(path = self.path, transport = "tls"))
log.debug(self.path)
log.debug(self.path_tag)
log.debug(self.route_lst)
def header_parser_record_route(self, message):
# log.debug("Processing found record route:\n\n{}\n".format(message))
self.record_route_lst.append(Utils.find_1st_occurrence(r"<(.*)>", message))
log.debug(self.record_route_lst)
def header_parser_service_route(self, message):
# log.debug("Processing found service route:\n\n{}\n".format(message))
self.route_lst.append(Utils.find_1st_occurrence(r"<(.*)>", message))
log.debug(self.route_lst)
def header_parser_contact(self, message):
log.debug("Accepted contact info at server: {}\n".format(message))
def header_parser_to(self, message):
self.to_tag = Utils.find_1st_occurrence(r"tag=(.*)$", message)
def header_parser_from(self, message):
self.from_tag = Utils.find_1st_occurrence(r"tag=(.*)$", message)
def header_parser_call_id(self, message):
self.call_id = Utils.find_1st_occurrence(r"Call-ID:\s(.*?)$", message)
log.debug(self.call_id)
def header_parser_contact(self, message):
self.contact_ack_route = Utils.find_1st_occurrence(r"<(.*?)>", message)
log.debug(self.contact_ack_route)
def header_parser_c_seq(self, message):
pass
def header_parser_content_type(self, message):
self.ack_content_type = Utils.find_1st_occurrence(r"/(.*?)$", message)
log.debug(self.ack_content_type)
def header_parser_p_associated_uri(self, message):
self.p_associated_uri = Utils.find_1st_occurrence(r"^<(.*)>", message)
log.debug(self.p_associated_uri)
def header_parser_p_associated_identity(self, message):
pass
def header_parser_www_auth(self, message):
self.nonce = Utils.find_1st_occurrence(r"nonce=\"(.*?)\",", message)
log.debug(self.nonce)
self.server_nonce = True
def header_parser_p_charging_vector(self, message):
self.info(Utils.find_1st_occurrence(r"P-Charging-Vector:\s(.*?)$", message))
def header_parser_x_google_event_id(self, message):
pass
def header_parser_content_length(self, message):
pass
def main(args):
log.info("========================================================================")
log.info("| Connecting to RCS ACS server ... |")
log.info("========================================================================\n")
try:
# CREATE SOCKET
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
# WRAP SOCKET
wrappedSocket = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLS, ciphers="ALL") # ssl_version=ssl.PROTOCOL_TLSv1_2
# CONNECT AND PRINT REPLY
try:
wrappedSocket.connect((args.realm, args.port))
log.info("========================================================================")
log.info("| Connected to RCS ACS server at {} |".format(args.realm))
log.info("========================================================================\n")
except:
log.info("========================================================================")
log.info("| Error: Cannot connect to given RCS ACS server! |")
log.info("========================================================================\n")
# Regardless of what happened, try to gracefully close down the socket.
# CLOSE SOCKET CONNECTION
wrappedSocket.close()
exit(-1)
log.info("========================================================================")
log.info("| Preparing SIP Messages ... |")
log.info("========================================================================\n")
my_ip = Utils.get_ip_address_from_socket(wrappedSocket)
rcs_messages = SipMessages(args.username, args.password, args.realm, my_ip, args.receiver, args.realm, args.imei)
# Step 1. Send a SIP REGISTER message and get 401 Unauthorized response
log.info("========================================================================")
log.info("| Sending a SIP REGISTER message and |")
log.info("| expecting a 401 Unauthorized response |")
log.info("========================================================================\n")
# google_fi_register_1_req = rcs_messages.register(1, "23099613-21b1-4565-902f-0001f4b4b99d", "", "")
reg_call_id = uuid.uuid4()
google_fi_register_1_req = rcs_messages.register(1, reg_call_id)
log.info("Sending:\n\n{}\n".format(google_fi_register_1_req))
if not args.sim_mode:
# send message (encoded into bytes) through socket
wrappedSocket.send(google_fi_register_1_req.encode())
rcs_messages.status_code = 0
# receive server's response
google_fi_register_1_resp = wrappedSocket.recv(65535)
log.info("Received:\n\n{}\n".format(google_fi_register_1_resp.decode()))
else:
google_fi_register_1_resp = CONST.GOOGLE_FI_REGISTER_1_RESP.encode()