forked from voipmonitor/sniffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sniff.cpp
5273 lines (4874 loc) · 173 KB
/
sniff.cpp
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
/* Martin Vit [email protected]
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2.
*/
/*
This unit reads and parse packets from network interface or file
and insert them into Call class.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <time.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <net/ethernet.h>
#include <iomanip>
#include "voipmonitor.h"
#ifdef FREEBSD
#include <machine/endian.h>
#else
#include <malloc.h>
#include <endian.h>
#endif
#include <sys/times.h>
#include <sys/param.h>
#include <sys/signal.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <syslog.h>
#include <semaphore.h>
#include <sstream>
#include <pcap.h>
//#include <pcap/sll.h>
#define int_ntoa(x) inet_ntoa(*((struct in_addr *)&x))
//#define HAS_NIDS 1
#ifdef HAS_NIDS
#include <nids.h>
#endif
#include "flags.h"
#include "codecs.h"
#include "calltable.h"
#include "sniff.h"
#include "voipmonitor.h"
#include "filter_mysql.h"
#include "hash.h"
#include "rtp.h"
#include "rtcp.h"
#include "md5.h"
#include "tools.h"
#include "mirrorip.h"
#include "ipaccount.h"
#include "sql_db.h"
#include "rtp.h"
#include "skinny.h"
#include "tcpreassembly.h"
#include "ip_frag.h"
#include "regcache.h"
#include "manager.h"
#include "fraud.h"
#include "send_call_info.h"
extern MirrorIP *mirrorip;
#define MAXLIVEFILTERS 10
using namespace std;
#ifndef MAX
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#endif
#ifndef MIN
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#endif
#ifdef MUTEX_THREAD
queue<pcap_packet*> readpacket_thread_queue;
extern pthread_mutex_t readpacket_thread_queue_lock;
#endif
unsigned int duplicate_counter = 0;
extern struct pcap_stat pcapstat;
int pcapstatresCount = 0;
volatile unsigned int glob_last_packet_time;
Calltable *calltable;
extern volatile int calls_counter;
extern int opt_saveSIP; // save SIP packets to pcap file?
extern int opt_saveRTP; // save RTP packets to pcap file?
extern int opt_saveRTCP; // save RTCP packets to pcap file?
extern int opt_saveRAW;
extern int opt_saveWAV;
extern int opt_saveGRAPH;
extern int opt_packetbuffered; // Make .pcap files writing ‘‘packet-buffered’’
extern int opt_rtcp; // Make .pcap files writing ‘‘packet-buffered’’
extern int verbosity;
extern int verbosityE;
extern int opt_rtp_firstleg;
extern int opt_sip_register;
extern int opt_norecord_header;
extern int opt_enable_http;
extern int opt_enable_webrtc;
extern int opt_enable_ssl;
extern int opt_convert_dlt_sll_to_en10;
extern char *sipportmatrix;
extern char *httpportmatrix;
extern char *webrtcportmatrix;
extern pcap_t *global_pcap_handle;
extern pcap_t *global_pcap_handle_dead_EN10MB;
extern rtp_read_thread *rtp_threads;
extern int opt_norecord_dtmf;
extern int opt_onlyRTPheader;
extern int opt_sipoverlap;
extern int readend;
extern int opt_dup_check;
extern int opt_dup_check_ipheader;
extern char opt_match_header[128];
extern char opt_callidmerge_header[128];
extern char opt_callidmerge_secret[128];
extern int opt_domainport;
extern int opt_mirrorip;
extern int opt_mirrorall;
extern int opt_mirroronly;
extern char opt_scanpcapdir[2048];
extern int opt_ipaccount;
extern int opt_cdrproxy;
extern IPfilter *ipfilter;
extern IPfilter *ipfilter_reload;
extern volatile int ipfilter_reload_do;
extern TELNUMfilter *telnumfilter;
extern TELNUMfilter *telnumfilter_reload;
extern volatile int telnumfilter_reload_do;
extern DOMAINfilter *domainfilter;
extern DOMAINfilter *domainfilter_reload;
extern volatile int domainfilter_reload_do;
extern SIP_HEADERfilter *sipheaderfilter;
extern SIP_HEADERfilter *sipheaderfilter_reload;
extern volatile int sipheaderfilter_reload_do;
extern int rtp_threaded;
extern int opt_rtpnosip;
extern char opt_cachedir[1024];
extern int opt_savewav_force;
extern int opt_saveudptl;
extern nat_aliases_t nat_aliases;
extern int opt_enable_preprocess_packet;
extern unsigned int opt_preprocess_packets_qring_length;
extern unsigned int opt_preprocess_packets_qring_usleep;
extern unsigned int opt_process_rtp_packets_qring_length;
extern unsigned int opt_process_rtp_packets_qring_usleep;
extern unsigned int rtp_qring_usleep;
extern int opt_pcapdump;
extern int opt_id_sensor;
extern int opt_destination_number_mode;
extern int opt_update_dstnum_onanswer;
extern MySqlStore *sqlStore;
int global_pcap_dlink;
extern int opt_udpfrag;
extern int global_livesniffer;
extern int opt_pcap_split;
extern int opt_newdir;
extern int opt_callslimit;
extern int opt_skiprtpdata;
extern char opt_silencedmtfseq[16];
extern int opt_skinny;
extern int opt_read_from_file;
extern int opt_saverfc2833;
extern livesnifferfilter_use_siptypes_s livesnifferfilterUseSipTypes;
extern int opt_skipdefault;
extern TcpReassembly *tcpReassemblyHttp;
extern TcpReassembly *tcpReassemblyWebrtc;
extern TcpReassembly *tcpReassemblySsl;
extern char ifname[1024];
extern int opt_sdp_reverse_ipport;
extern int opt_fork;
extern regcache *regfailedcache;
extern ManagerClientThreads ClientThreads;
extern int opt_register_timeout;
extern int opt_nocdr;
extern int opt_enable_fraud;
extern int pcap_drop_flag;
extern int opt_hide_message_content;
extern int opt_remotepartyid;
extern int opt_remotepartypriority;
extern int opt_ppreferredidentity;
extern int opt_passertedidentity;
extern char cloud_host[256];
extern SocketSimpleBufferWrite *sipSendSocket;
extern int opt_sip_send_before_packetbuffer;
extern PreProcessPacket *preProcessPacket;
extern ProcessRtpPacket *processRtpPacketHash;
extern ProcessRtpPacket *processRtpPacketDistribute[MAX_PROCESS_RTP_PACKET_THREADS];
extern int opt_enable_process_rtp_packet;
extern CustomHeaders *custom_headers_cdr;
extern CustomHeaders *custom_headers_message;
extern bool _save_sip_history;
extern bool _save_sip_history_request_types[1000];
extern bool _save_sip_history_all_requests;
extern bool _save_sip_history_all_responses;extern int absolute_timeout;
unsigned int glob_ssl_calls = 0;
char * gettag(const void *ptr, unsigned long len, const char *tag, unsigned long *gettaglen, unsigned long *limitLen = NULL,
ParsePacket *parsePacket = NULL);
static void logPacketSipMethodCall(u_int64_t packet_number, int sip_method, int lastSIPresponseNum, pcap_pkthdr *header,
unsigned int saddr, int source, unsigned int daddr, int dest,
Call *call, const char *descr = NULL);
#define logPacketSipMethodCall_enable ((opt_read_from_file && verbosity > 2) || verbosityE > 1 || sverb.sip_packets)
typedef struct pcap_hdr_s {
u_int32_t magic_number; /* magic number */
u_int16_t version_major; /* major version number */
u_int16_t version_minor; /* minor version number */
int32_t thiszone; /* GMT to local correction */
u_int32_t sigfigs; /* accuracy of timestamps */
u_int32_t snaplen; /* max length of captured packets, in octets */
u_int32_t network; /* data link type */
} pcap_hdr_t;
typedef struct pcaprec_hdr_s {
u_int32_t ts_sec; /* timestamp seconds */
u_int32_t ts_usec; /* timestamp microseconds */
u_int32_t incl_len; /* number of octets of packet saved in file */
u_int32_t orig_len; /* actual length of packet */
} pcaprec_hdr_t;
TcpReassemblySip tcpReassemblySip;
ipfrag_data_s ipfrag_data;
u_int64_t counter_calls;
u_int64_t counter_sip_packets[2];
u_int64_t counter_sip_register_packets;
u_int64_t counter_sip_message_packets;
u_int64_t counter_rtp_packets;
u_int64_t counter_all_packets;
u_int64_t process_rtp_counter;
u_int64_t read_rtp_counter;
extern struct queue_state *qs_readpacket_thread_queue;
map<unsigned int, livesnifferfilter_t*> usersniffer;
volatile int usersniffer_sync;
#define ENABLE_CONVERT_DLT_SLL_TO_EN10(dlt) (dlt == DLT_LINUX_SLL && opt_convert_dlt_sll_to_en10 && global_pcap_handle_dead_EN10MB)
#include "sniff_inline.h"
static unsigned long process_packet__last_cleanup = 0;
static unsigned long process_packet__last_filter_reload = 0;
static unsigned long process_packet__last_destroy_calls = 0;
static unsigned long preprocess_packet__last_cleanup = 0;
// return IP from nat_aliases[ip] or 0 if not found
in_addr_t match_nat_aliases(in_addr_t ip) {
nat_aliases_t::iterator iter;
iter = nat_aliases.find(ip);
if(iter == nat_aliases.end()) {
// not found
return 0;
} else {
return iter->second;
}
}
inline void save_packet_sql(Call *call, struct pcap_pkthdr *header, const u_char *packet, unsigned int saddr, int source, unsigned int daddr, int dest, int istcp, char *data, int datalen, int uid, int dlt, int sensor_id) {
//save packet
stringstream query;
// pcap file header
pcap_hdr_t pcaphdr; // 24bytes
pcaphdr.magic_number = 0xa1b2c3d4;
pcaphdr.version_major = 2;
pcaphdr.version_minor = 4;
pcaphdr.thiszone = 0;
pcaphdr.sigfigs = 0;
pcaphdr.snaplen = 3200;
pcaphdr.network = ENABLE_CONVERT_DLT_SLL_TO_EN10(dlt) ? DLT_EN10MB : dlt;
// packet header
pcaprec_hdr_t pcaph;
pcaph.ts_sec = header->ts.tv_sec; /* timestamp seconds */
pcaph.ts_usec = header->ts.tv_usec; /* timestamp microseconds */
pcaph.incl_len = header->caplen; /* number of octets of packet saved in file */
pcaph.orig_len = header->caplen; /* actual length of packet */
// copy data to mpacket buffer
char mpacket[10512];
char *ptr = mpacket;
memcpy(ptr, &pcaphdr, sizeof(pcaphdr)); // pcap header
ptr += sizeof(pcaphdr);
memcpy(ptr, &pcaph, sizeof(pcaph)); // packet header
ptr += sizeof(pcaph);
unsigned int len = MIN(10000, header->caplen);
memcpy(ptr, packet, len);
len += sizeof(pcaph) + sizeof(pcaphdr);
//construct description and call-id
char description[1024] = "";
char callidstr[1024] = "";
if(datalen) {
void *memptr = memmem(data, datalen, "\r\n", 2);
if(memptr) {
memcpy(description, data, (char *)memptr - (char*)data);
description[(char*)memptr - (char*)data] = '\0';
} else {
strcpy(description, "error in description\n");
}
if(!call) {
unsigned long l;
char *s = gettag(data, datalen, "\nCall-ID:", &l);
if(l > 0 && l < 1024) {
memcpy(callidstr, s, MIN(l, 1024));
callidstr[MIN(l, 1023)] = '\0';
}
}
}
// construct query and push it to mysqlquery queue
int id_sensor = sensor_id > 0 ? sensor_id : 0;
query << "INSERT INTO livepacket_" << uid <<
" SET sipcallerip = '" << saddr <<
"', sipcalledip = '" << daddr <<
"', id_sensor = " << id_sensor <<
", sport = " << source <<
", dport = " << dest <<
", istcp = " << istcp <<
", created_at = " << sqlEscapeStringBorder(sqlDateTimeString(header->ts.tv_sec).c_str()) <<
", microseconds = " << header->ts.tv_usec <<
", callid = " << sqlEscapeStringBorder(call ? call->call_id : callidstr) <<
", description = " << sqlEscapeStringBorder(description) <<
", data = ";
if(cloud_host[0]) {
query << "concat('#', from_base64('" << base64_encode((unsigned char*)mpacket, len) << "'), '#')";
} else {
query << "'#" << _sqlEscapeString(mpacket, len, "mysql") << "#'";
}
sqlStore->query_lock(query.str().c_str(), STORE_PROC_ID_SAVE_PACKET_SQL);
return;
}
/*
stores SIP messags to sql.livepacket based on user filters
*/
int get_sip_peername(char *data, int data_len, const char *tag, char *peername, unsigned int peername_len);
inline void save_live_packet(Call *call, struct pcap_pkthdr *header, const u_char *packet, unsigned int saddr, int source, unsigned int daddr, int dest, int istcp, char *data, int datalen, unsigned char sip_type,
int dlt, int sensor_id) {
if(!global_livesniffer) {
return;
}
// check saddr and daddr filters
daddr = htonl(daddr);
saddr = htonl(saddr);
while(__sync_lock_test_and_set(&usersniffer_sync, 1));
map<unsigned int, livesnifferfilter_t*>::iterator usersnifferIT;
char caller[1024] = "", called[1024] = "";
if(call) {
strncpy(caller, call->caller, sizeof(caller));
caller[sizeof(caller) - 1] = 0;
strncpy(called, call->called, sizeof(called));
called[sizeof(called) - 1] = 0;
} else {
bool needcaller = false;
bool needcalled = false;
for(usersnifferIT = usersniffer.begin(); usersnifferIT != usersniffer.end(); usersnifferIT++) {
if(!usersnifferIT->second->state.all_all && !usersnifferIT->second->state.all_num) {
for(int i = 0; i < MAXLIVEFILTERS; i++) {
if(!usersnifferIT->second->state.all_srcnum && usersnifferIT->second->lv_srcnum[i][0]) {
needcaller = true;
}
if(!usersnifferIT->second->state.all_dstnum && usersnifferIT->second->lv_dstnum[i][0]) {
needcalled = true;
}
if(!usersnifferIT->second->state.all_bothnum && usersnifferIT->second->lv_bothnum[i][0]) {
needcaller = true;
needcalled = true;
}
}
}
}
int res;
if(needcaller) {
res = get_sip_peername(data,datalen,"\nFrom:", caller, sizeof(caller));
if(res) {
// try compact header
get_sip_peername(data,datalen,"\nf:", caller, sizeof(caller));
}
}
if(needcalled) {
res = get_sip_peername(data,datalen,"\nTo:", called, sizeof(called));
if(res) {
// try compact header
get_sip_peername(data,datalen,"\nt:", called, sizeof(called));
}
}
}
for(usersnifferIT = usersniffer.begin(); usersnifferIT != usersniffer.end(); usersnifferIT++) {
livesnifferfilter_t *filter = usersnifferIT->second;
bool save = filter->state.all_all;
if(!save) {
bool okAddr = filter->state.all_addr;
if(!okAddr) {
for(int i = 0; i < MAXLIVEFILTERS && !okAddr; i++) {
if((filter->state.all_saddr || (filter->lv_saddr[i] &&
saddr == filter->lv_saddr[i])) &&
(filter->state.all_daddr || (filter->lv_daddr[i] &&
daddr == filter->lv_daddr[i])) &&
(filter->state.all_bothaddr || (filter->lv_bothaddr[i] &&
(saddr == filter->lv_bothaddr[i] ||
daddr == filter->lv_bothaddr[i])))) {
okAddr = true;
}
}
}
bool okNum = filter->state.all_num;
if(!okNum) {
for(int i = 0; i < MAXLIVEFILTERS && !okNum; i++) {
if((filter->state.all_srcnum || (filter->lv_srcnum[i][0] &&
memmem(caller, strlen(caller), filter->lv_srcnum[i], strlen(filter->lv_srcnum[i])))) &&
(filter->state.all_dstnum || (filter->lv_dstnum[i][0] &&
memmem(called, strlen(called), filter->lv_dstnum[i], strlen(filter->lv_dstnum[i])))) &&
(filter->state.all_bothnum || (filter->lv_bothnum[i][0] &&
(memmem(caller, strlen(caller), filter->lv_bothnum[i], strlen(filter->lv_bothnum[i])) ||
memmem(called, strlen(called), filter->lv_bothnum[i], strlen(filter->lv_bothnum[i])))))) {
okNum = true;
}
}
}
bool okSipType = filter->state.all_siptypes;
if(!okSipType) {
for(int i = 0; i < MAXLIVEFILTERS && !okSipType; i++) {
if(filter->lv_siptypes[i] == sip_type) {
okSipType = true;
}
}
}
if(okAddr && okNum && okSipType) {
save = true;
}
}
if(save) {
save_packet_sql(call, header, packet, saddr, source, daddr, dest, istcp, data, datalen, usersnifferIT->first,
dlt, sensor_id);
}
}
__sync_lock_release(&usersniffer_sync);
}
/*
save packet into file
type - 1 is SIP, 2 is RTP, 3 is RTCP
*/
void save_packet(Call *call, struct pcap_pkthdr *header, const u_char *packet,
unsigned int saddr, int source, unsigned int daddr, int dest,
int istcp, iphdr2 *header_ip, char *data, unsigned int datalen, unsigned int dataoffset, int type,
int forceSip, int dlt, int sensor_id) {
bool allocPacket = false;
bool allocHeader = false;
if(ENABLE_CONVERT_DLT_SLL_TO_EN10(dlt)) {
const u_char *packet_orig = packet;
pcap_pkthdr *header_orig = header;
packet = (const u_char*) new FILE_LINE u_char[header_orig->caplen];
memcpy((u_char*)packet, (u_char*)packet_orig, 14);
memset((u_char*)packet, 0, 6);
((ether_header*)packet)->ether_type = ((sll_header*)packet_orig)->sll_protocol;
memcpy((u_char*)packet + 14, (u_char*)packet_orig + 16, header_orig->caplen - 16);
header = new FILE_LINE pcap_pkthdr;
memcpy(header, header_orig, sizeof(pcap_pkthdr));
header->caplen -= 2;
header->len -= 2;
allocPacket = true;
allocHeader = true;
}
unsigned int limitCapLen = 65535;
if(dataoffset > 0 && dataoffset < 100 &&
((call->type == MESSAGE && opt_hide_message_content) ||
(istcp && header->caplen > limitCapLen))) {
unsigned long l;
char *s = gettag(data, datalen, "\nContent-Length:", &l);
if(l && l < datalen) {
long int contentLength = atol(s);
if(contentLength > 0) {
if(istcp &&
header->caplen > limitCapLen &&
(u_char*)header_ip > packet &&
(u_char*)header_ip - packet < 100) {
u_int32_t diffLen = header->caplen - limitCapLen;
header->caplen -= diffLen;
header->len -= diffLen;
header_ip->tot_len = htons(ntohs(header_ip->tot_len) - diffLen);
contentLength -= diffLen;
while(*s == ' ') {
++s;
}
char contLengthStr[10];
sprintf(contLengthStr, "%u", (unsigned int)contentLength);
char *pointToModifyContLength = (char*)packet + dataoffset + (s - data);
strncpy(pointToModifyContLength, contLengthStr, strlen(contLengthStr));
char *pointToEndModifyContLength = pointToModifyContLength + strlen(contLengthStr);
while(*pointToEndModifyContLength != '\r') {
*pointToEndModifyContLength = ' ';
++pointToEndModifyContLength;
}
}
if(call->type == MESSAGE && opt_hide_message_content) {
char *endHeaderSepPos = (char*)memmem(data, datalen, "\r\n\r\n", 4);
if(endHeaderSepPos) {
const u_char *packet_orig = packet;
packet = (const u_char*) new FILE_LINE u_char[header->caplen];
memcpy((u_char*)packet, packet_orig, header->caplen);
u_char *message = (u_char*)packet + dataoffset + (endHeaderSepPos - data) + 4;
memset((u_char*)message, 'x', min(contentLength, (long int)(header->caplen - (message - packet))));
allocPacket = true;
}
}
}
}
}
// check if it should be stored to mysql
if(type == TYPE_SIP and global_livesniffer and (sipportmatrix[source] || sipportmatrix[dest] || forceSip)) {
save_live_packet(call, header, packet, saddr, source, daddr, dest, istcp, data, datalen, call->type,
dlt, sensor_id);
}
if(opt_newdir and opt_pcap_split) {
switch(type) {
case TYPE_SKINNY:
case TYPE_SIP:
if(call->getPcapSip()->isOpen()){
call->set_last_packet_time(header->ts.tv_sec);
if(type == TYPE_SIP) {
call->getPcapSip()->dump(header, packet, dlt, false, (u_char*)data, datalen, saddr, daddr, source, dest, istcp);
} else {
call->getPcapSip()->dump(header, packet, dlt);
}
}
break;
case TYPE_RTP:
case TYPE_RTCP:
if(call->getPcapRtp()->isOpen()){
call->set_last_packet_time(header->ts.tv_sec);
call->getPcapRtp()->dump(header, packet, dlt);
} else {
char pcapFilePath_spool_relative[1024];
snprintf(pcapFilePath_spool_relative , 1023, "%s/%s/%s.pcap", call->dirname().c_str(), opt_newdir ? "RTP" : "", call->get_fbasename_safe());
pcapFilePath_spool_relative[1023] = 0;
char str2[1024];
if(opt_cachedir[0] != '\0') {
snprintf(str2, 1023, "%s/%s", opt_cachedir, pcapFilePath_spool_relative);
} else {
strcpy(str2, pcapFilePath_spool_relative);
}
if(call->getPcapRtp()->open(str2, pcapFilePath_spool_relative, call->useHandle, call->useDlt)) {
if(verbosity > 3) syslog(LOG_NOTICE,"pcap_filename: [%s]\n", str2);
call->set_last_packet_time(header->ts.tv_sec);
call->getPcapRtp()->dump(header, packet, dlt);
}
}
break;
}
} else {
if (call->getPcap()->isOpen()){
call->set_last_packet_time(header->ts.tv_sec);
if(type == TYPE_SIP) {
call->getPcap()->dump(header, packet, dlt, false, (u_char*)data, datalen, saddr, daddr, source, dest, istcp);
} else {
call->getPcap()->dump(header, packet, dlt);
}
}
}
if(allocPacket) {
delete [] packet;
}
if(allocHeader) {
delete header;
}
}
inline void save_sip_packet(Call *call, struct pcap_pkthdr *header, const u_char *packet,
unsigned int saddr, int source, unsigned int daddr, int dest,
int istcp, iphdr2 *header_ip, char *data, unsigned int sipDatalen, unsigned int dataoffset, int type,
unsigned int datalen, unsigned int sipOffset,
int forceSip, int dlt, int sensor_id) {
if(istcp &&
sipDatalen && (sipDatalen < datalen || sipOffset) &&
(unsigned)datalen + sipOffset < header->caplen) {
bpf_u_int32 oldcaplen = header->caplen;
bpf_u_int32 oldlen = header->len;
u_int16_t oldHeaderIpLen = header_ip->tot_len;
unsigned long datalenWithSipOffset = datalen + sipOffset;
unsigned long diffLen = sipOffset + (datalen - sipDatalen);
unsigned long newPacketLen = oldcaplen - diffLen;
header->caplen -= diffLen;
header->len -= diffLen;
header_ip->tot_len = htons(ntohs(header_ip->tot_len) - diffLen);
u_char *newPacket = new FILE_LINE u_char[newPacketLen];
memcpy(newPacket, packet, oldcaplen - datalenWithSipOffset);
memcpy(newPacket + (oldcaplen - datalenWithSipOffset), data, sipDatalen);
iphdr2 *newHeaderIp = header_ip;
if((u_char*)header_ip > packet && (u_char*)header_ip - packet < 100) {
newHeaderIp = (iphdr2*)(newPacket + ((u_char*)header_ip - packet));
}
save_packet(call, header, newPacket, saddr, source, daddr, dest, istcp, newHeaderIp, data, sipDatalen, dataoffset, TYPE_SIP,
forceSip, dlt, sensor_id);
delete [] newPacket;
header->caplen = oldcaplen;
header->len = oldlen;
header_ip->tot_len = oldHeaderIpLen;
} else {
save_packet(call, header, packet, saddr, source, daddr, dest, istcp, header_ip, data, sipDatalen, dataoffset, TYPE_SIP,
forceSip, dlt, sensor_id);
}
}
ParsePacket _parse_packet_global;
ParsePacket *_parse_packet_process_packet;
int check_sip20(char *data, unsigned long len){
if(len < 11) {
return 0;
}
ParsePacket *parsePacket = NULL;
if(_parse_packet_process_packet && _parse_packet_process_packet->getParseData() == data) {
parsePacket = _parse_packet_process_packet;
} else if(_parse_packet_global.getParseData() == data) {
parsePacket = &_parse_packet_global;
}
if(parsePacket) {
return(parsePacket->isSip());
}
int ok;
char a = data[9];
data[9] = '\0';
//List of SIP request methods
//RFC 3261
if(strcasestr(data, "SIP/2.0")) {
ok = 1;
} else if(strcasestr(data, "INVITE")) {
ok = 1;
} else if(strcasestr(data, "ACK")) {
ok = 1;
} else if(strcasestr(data, "BYE")) {
ok = 1;
} else if(strcasestr(data, "CANCEL")) {
ok = 1;
} else if(strcasestr(data, "OPTIONS")) {
ok = 1;
} else if(strcasestr(data, "REGISTER")) {
ok = 1;
//RFC 3262
} else if(strcasestr(data, "PRACK")) {
ok = 1;
} else if(strcasestr(data, "SUBSCRIBE")) {
ok = 1;
} else if(strcasestr(data, "NOTIFY")) {
ok = 1;
} else if(strcasestr(data, "PUBLISH")) {
ok = 1;
} else if(strcasestr(data, "INFO")) {
ok = 1;
} else if(strcasestr(data, "REFER")) {
ok = 1;
} else if(strcasestr(data, "MESSAGE")) {
ok = 1;
} else if(strcasestr(data, "UPDATE")) {
ok = 1;
} else {
ok = 0;
}
data[9] = a;
return ok;
}
/* get SIP tag from memory pointed to *ptr length of len */
char * gettag(const void *ptr, unsigned long len, const char *tag, unsigned long *gettaglen, unsigned long *limitLen,
ParsePacket *parsePacket) {
bool test_pp = false;
const char *rc_pp = NULL;
long l_pp;
char _tag[1024];
if(!parsePacket) {
if(_parse_packet_process_packet && _parse_packet_process_packet->getParseData() == ptr) {
parsePacket = _parse_packet_process_packet;
} else if(_parse_packet_global.getParseData() == ptr) {
parsePacket = &_parse_packet_global;
}
}
if(parsePacket) {
rc_pp = parsePacket->getContentData(tag, &l_pp);
if((!rc_pp || l_pp <= 0) && tag[0] != '\n') {
_tag[0] = '\n';
strcpy(_tag + 1, tag);
rc_pp = parsePacket->getContentData(_tag, &l_pp);
}
if(!test_pp) {
if(rc_pp && l_pp > 0) {
*gettaglen = l_pp;
return((char*)rc_pp);
} else {
*gettaglen = 0;
return(NULL);
}
}
}
unsigned long register r, l, tl;
char *rc = NULL;
char *tmp;
char tmp2;
tmp = (char*)ptr;
bool positionOK = true;
unsigned long _limitLen = 0;
if(len <= 0) {
*gettaglen = 0;
return NULL;
}
// put '\0' at the end of the packet so it can be used with string functions. then restore the character
tmp2 = tmp[len - 1];
tmp[len - 1] = '\0';
tl = strlen(tag);
//r = (unsigned long)memmem(ptr, len, tag, tl); memmem cannot be used because SIP headers are case insensitive
r = (unsigned long)strcasestr(tmp, tag);
if(r == 0){
// tag did not match
l = 0;
} else {
//check if position ok
if(limitLen && *limitLen > 0) {
_limitLen = *limitLen;
} else {
const char *contentLengthString = "Content-Length: ";
char *contentLengthPos = strcasestr(tmp, contentLengthString);
if(contentLengthPos) {
int contentLength = atoi(contentLengthPos + strlen(contentLengthString));
if(contentLength >= 0) {
const char *endHeaderSepString = "\r\n\r\n";
char *endHeaderSepPos = (char*)memmem(tmp, len, endHeaderSepString, strlen(endHeaderSepString));
if(endHeaderSepPos) {
_limitLen = (endHeaderSepPos - tmp) + strlen(endHeaderSepString) + contentLength;
if(limitLen) {
*limitLen = _limitLen;
}
}
}
}
}
if(_limitLen &&
(unsigned long)(_limitLen + tmp) < r) {
positionOK = false;
}
if(positionOK || verbosity > 0) {
//tag matches move r pointer behind the tag name
r += tl;
tmp[len - 1] = tmp2;
l = (unsigned long)memmem((void *)r, len - (r - (unsigned long)ptr), "\r", 1);
if (l > 0){
// remove trailing \r\n and set l to length of the tag
l -= r;
} else {
// trailing \r not found try to find \n
l = (unsigned long)memmem((void *)r, len - (r - (unsigned long)ptr), "\n", 1);
if (l > 0){
// remove trailing \r\n and set l to length of the tag
l -= r;
} else {
// trailing \r not found try to find \n
l = 0;
}
}
} else {
l = 0;
}
}
tmp[len - 1] = tmp2;
// left trim spacees
if(l > 0) {
rc = (char*)r;
if (rc) {
while (((char *)ptr + len) > rc && rc[0] == ' '){
rc++;
l--;
}
}
}
if(!positionOK) {
if(verbosity > 2 && l > 0) {
char tagc[101];
strncpy(tagc, rc, min(l, 100ul));
tagc[min(l, 100ul)] = 0;
syslog(LOG_NOTICE, "bad tag position - tag: %s, content: %s\n", tag, tagc);
}
*gettaglen = 0;
} else {
*gettaglen = l;
}
if(test_pp && rc && l) {
if(_parse_packet_global.getParseData() == ptr) {
//cout << "." << flush;
string content = string(rc_pp, l_pp);
string content2 = string(rc, l);
while(content2.length() && content2[content2.length() - 1] == ' ') {
content2.resize(content2.length() - 1);
}
if(content != content2) {
cout << "GETTAG ERR " << tag << " :: " << content << " // " << string(rc, l) << endl;
//cout << (char*)ptr << endl << endl << endl << endl;
}
} else {
cout << "GETTAG --- " << tag << " :: " << string(rc, l) << endl;
}
}
return rc;
}
int get_sip_peercnam(char *data, int data_len, const char *tag, char *peername, unsigned int peername_len){
unsigned long r, r2, peername_tag_len;
char *peername_tag = gettag(data, data_len, tag, &peername_tag_len);
if(!peername_tag_len) {
goto fail_exit;
}
/* three types of URI
1) "A. G. Bell" <sip:[email protected]> ;tag=a48s
2) Anonymous <sip:[email protected]>;tag=hyh8
3) sip:[email protected];tag=887s
*/
if ((r = (unsigned long)memmem(peername_tag, peername_tag_len, "\"", 1)) == 0){
// try without ""
if ((r = (unsigned long)memmem(peername_tag, peername_tag_len, "<", 1)) == 0){
goto fail_exit;
} else {
// found case 2) Anonymous <sip:[email protected]>;tag=hyh8
r = (unsigned long)peername_tag;
}
} else {
// found case 1) "A. G. Bell" <sip:[email protected]> ;tag=a48s
r += 1;
}
if ((r2 = (unsigned long)memmem(peername_tag, peername_tag_len, "\" <", 3)) == 0){
// try without space ' '
if ((r2 = (unsigned long)memmem(peername_tag, peername_tag_len, "\"<", 2)) == 0){
// try without quotes
if ((r2 = (unsigned long)memmem(peername_tag, peername_tag_len, " <", 2)) == 0){
goto fail_exit;
}
}
}
if (r2 <= r || ((r2 - r) > (unsigned long)peername_len) ){
goto fail_exit;
}
memcpy(peername, (void*)r, MIN(r2 - r, peername_len));
peername[MIN(r2 - r, peername_len - 1)] = '\0';
return 0;
fail_exit:
strcpy(peername, "");
return 1;
}
int get_sip_peername(char *data, int data_len, const char *tag, char *peername, unsigned int peername_len){
unsigned long r, r2, peername_tag_len;
char *peername_tag = gettag(data, data_len, tag, &peername_tag_len);
if(!peername_tag_len) {
goto fail_exit;
}
if ((r = (unsigned long)memmem(peername_tag, peername_tag_len, "sip:", 4)) == 0){
if ((r = (unsigned long)memmem(peername_tag, peername_tag_len, "sips:", 4)) == 0){
goto fail_exit;
} else {
r += 5;
}
} else {
r += 4;
}
if ((r2 = (unsigned long)memmem((char*)r, peername_tag_len, "@", 1)) == 0){
goto fail_exit;
}
if (r2 <= r || ((r2 - r) > (unsigned long)peername_len) ){
goto fail_exit;
}
memcpy(peername, (void*)r, MIN(r2 - r, peername_len));
peername[MIN(r2 - r, peername_len - 1)] = '\0';
return 0;
fail_exit:
strcpy(peername, "");
return 1;
}
int get_sip_domain(char *data, int data_len, const char *tag, char *domain, unsigned int domain_len){
unsigned long r, r2, peername_tag_len;
char *peername_tag = gettag(data, data_len, tag, &peername_tag_len);
char *c;
if(!peername_tag_len) {
goto fail_exit;
}
if ((r = (unsigned long)memmem(peername_tag, peername_tag_len, "sip:", 4)) == 0){
if ((r = (unsigned long)memmem(peername_tag, peername_tag_len, "sips:", 4)) == 0){
goto fail_exit;
} else {
r += 4;
}
} else {
r += 4;
}
if ((r = (unsigned long)memmem((char*)r, peername_tag_len, "@", 1)) == 0){
goto fail_exit;
}
r += 1;
if ((r2 = (unsigned long)memmem(peername_tag, peername_tag_len, ">", 1)) == 0){
if ((r2 = (unsigned long)memmem(peername_tag, peername_tag_len + 1, "\r", 1)) == 0){
goto fail_exit;
}
}
if (r2 <= r || ((r2 - r) > (unsigned long)domain_len) ){
goto fail_exit;
}
memcpy(domain, (void*)r, MIN(r2 - r, domain_len));
domain[MIN(r2 - r, domain_len - 1)] = '\0';
// strip :port
if(!opt_domainport) {
c = strchr(domain, ':');
if(c != NULL)
*c = '\0';
}
// check if there is ; in the string (for example sip:<123@domain;user=phone>
c = strchr(domain, ';');
if(c != NULL)
*c = '\0';
return 0;
fail_exit:
strcpy(domain, "");
return 1;
}
int get_sip_branch(char *data, int data_len, const char *tag, char *branch, unsigned int branch_len){
unsigned long branch_tag_len;
char *branch_tag = gettag(data, data_len, tag, &branch_tag_len);
char *branchBegin = (char*)memmem(branch_tag, branch_tag_len, "branch=", 7);
char *branchEnd;
if(!branchBegin) {
goto fail_exit;
}
branchBegin += 7;
branchEnd = (char*)memmem(branchBegin, branch_tag_len - (branchBegin - branch_tag), ";", 1);
if(!branchEnd) {
branchEnd = branchBegin + branch_tag_len - (branchBegin - branch_tag);
}
if(branchEnd <= branchBegin || ((branchEnd - branchBegin) > branch_len)) {
goto fail_exit;
}
memcpy(branch, branchBegin, MIN(branchEnd - branchBegin, branch_len));
branch[MIN(branchEnd - branchBegin, branch_len - 1)] = '\0';
return 0;
fail_exit:
strcpy(branch, "");