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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
|
/*
* netsniff-ng - the packet sniffing beast
* Copyright 2011 - 2013 Daniel Borkmann.
* Copyright 2011 Emmanuel Roullit.
* Subject to the GPL, version 2.
*/
#define _LGPL_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <signal.h>
#include <getopt.h>
#include <pthread.h>
#include <signal.h>
#include <netdb.h>
#include <ctype.h>
#include <netinet/in.h>
#include <curses.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/fsuid.h>
#include <urcu.h>
#include <libgen.h>
#include <inttypes.h>
#include <poll.h>
#include <fcntl.h>
#include "die.h"
#include "xmalloc.h"
#include "conntrack.h"
#include "config.h"
#include "str.h"
#include "sig.h"
#include "lookup.h"
#include "geoip.h"
#include "built_in.h"
#include "locking.h"
#include "pkt_buff.h"
#include "screen.h"
struct flow_entry {
uint32_t flow_id, use, status;
uint8_t l3_proto, l4_proto;
uint32_t ip4_src_addr, ip4_dst_addr;
uint32_t ip6_src_addr[4], ip6_dst_addr[4];
uint16_t port_src, port_dst;
uint8_t tcp_state, tcp_flags, sctp_state, dccp_state;
uint64_t counter_pkts, counter_bytes;
uint64_t timestamp_start, timestamp_stop;
char country_src[128], country_dst[128];
char city_src[128], city_dst[128];
char rev_dns_src[256], rev_dns_dst[256];
char cmdline[256];
struct flow_entry *next;
int inode;
unsigned int procnum;
bool is_visible;
struct nf_conntrack *ct;
};
struct flow_list {
struct flow_entry *head;
struct spinlock lock;
};
#ifndef ATTR_TIMESTAMP_START
# define ATTR_TIMESTAMP_START 63
#endif
#ifndef ATTR_TIMESTAMP_STOP
# define ATTR_TIMESTAMP_STOP 64
#endif
#define SCROLL_MAX 1000
#define INCLUDE_IPV4 (1 << 0)
#define INCLUDE_IPV6 (1 << 1)
#define INCLUDE_UDP (1 << 2)
#define INCLUDE_TCP (1 << 3)
#define INCLUDE_DCCP (1 << 4)
#define INCLUDE_ICMP (1 << 5)
#define INCLUDE_SCTP (1 << 6)
static volatile sig_atomic_t sigint = 0;
static int what = INCLUDE_IPV4 | INCLUDE_IPV6 | INCLUDE_TCP, show_src = 0;
static struct flow_list flow_list;
static struct condlock collector_ready;
static int nfct_acct_val = -1;
static const char *short_options = "vhTUsDIS46u";
static const struct option long_options[] = {
{"ipv4", no_argument, NULL, '4'},
{"ipv6", no_argument, NULL, '6'},
{"tcp", no_argument, NULL, 'T'},
{"udp", no_argument, NULL, 'U'},
{"dccp", no_argument, NULL, 'D'},
{"icmp", no_argument, NULL, 'I'},
{"sctp", no_argument, NULL, 'S'},
{"show-src", no_argument, NULL, 's'},
{"update", no_argument, NULL, 'u'},
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0}
};
static const char *copyright = "Please report bugs to <bugs@netsniff-ng.org>\n"
"Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
"Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
"Swiss federal institute of technology (ETH Zurich)\n"
"License: GNU GPL version 2.0\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.";
static const char *const l3proto2str[AF_MAX] = {
[AF_INET] = "ipv4",
[AF_INET6] = "ipv6",
};
static const char *const l4proto2str[IPPROTO_MAX] = {
[IPPROTO_TCP] = "tcp",
[IPPROTO_UDP] = "udp",
[IPPROTO_UDPLITE] = "udplite",
[IPPROTO_ICMP] = "icmp",
[IPPROTO_ICMPV6] = "icmpv6",
[IPPROTO_SCTP] = "sctp",
[IPPROTO_GRE] = "gre",
[IPPROTO_DCCP] = "dccp",
[IPPROTO_IGMP] = "igmp",
[IPPROTO_IPIP] = "ipip",
[IPPROTO_EGP] = "egp",
[IPPROTO_PUP] = "pup",
[IPPROTO_IDP] = "idp",
[IPPROTO_RSVP] = "rsvp",
[IPPROTO_IPV6] = "ip6tun",
[IPPROTO_ESP] = "esp",
[IPPROTO_AH] = "ah",
[IPPROTO_PIM] = "pim",
[IPPROTO_COMP] = "comp",
};
static const char *const tcp_state2str[TCP_CONNTRACK_MAX] = {
[TCP_CONNTRACK_NONE] = "NOSTATE",
[TCP_CONNTRACK_SYN_SENT] = "SYN_SENT",
[TCP_CONNTRACK_SYN_RECV] = "SYN_RECV",
[TCP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
[TCP_CONNTRACK_FIN_WAIT] = "FIN_WAIT",
[TCP_CONNTRACK_CLOSE_WAIT] = "CLOSE_WAIT",
[TCP_CONNTRACK_LAST_ACK] = "LAST_ACK",
[TCP_CONNTRACK_TIME_WAIT] = "TIME_WAIT",
[TCP_CONNTRACK_CLOSE] = "CLOSE",
[TCP_CONNTRACK_SYN_SENT2] = "SYN_SENT2",
};
static const bool tcp_states_show[TCP_CONNTRACK_MAX] = {
[TCP_CONNTRACK_SYN_SENT] = true,
[TCP_CONNTRACK_SYN_RECV] = true,
[TCP_CONNTRACK_ESTABLISHED] = true,
[TCP_CONNTRACK_FIN_WAIT] = true,
[TCP_CONNTRACK_CLOSE_WAIT] = true,
[TCP_CONNTRACK_LAST_ACK] = true,
[TCP_CONNTRACK_TIME_WAIT] = true,
[TCP_CONNTRACK_CLOSE] = true,
[TCP_CONNTRACK_SYN_SENT2] = true,
[TCP_CONNTRACK_NONE] = true,
};
static const char *const dccp_state2str[DCCP_CONNTRACK_MAX] = {
[DCCP_CONNTRACK_NONE] = "NOSTATE",
[DCCP_CONNTRACK_REQUEST] = "REQUEST",
[DCCP_CONNTRACK_RESPOND] = "RESPOND",
[DCCP_CONNTRACK_PARTOPEN] = "PARTOPEN",
[DCCP_CONNTRACK_OPEN] = "OPEN",
[DCCP_CONNTRACK_CLOSEREQ] = "CLOSEREQ",
[DCCP_CONNTRACK_CLOSING] = "CLOSING",
[DCCP_CONNTRACK_TIMEWAIT] = "TIMEWAIT",
[DCCP_CONNTRACK_IGNORE] = "IGNORE",
[DCCP_CONNTRACK_INVALID] = "INVALID",
};
static const uint8_t dccp_states_show[DCCP_CONNTRACK_MAX] = {
[DCCP_CONNTRACK_NONE] = true,
[DCCP_CONNTRACK_REQUEST] = true,
[DCCP_CONNTRACK_RESPOND] = true,
[DCCP_CONNTRACK_PARTOPEN] = true,
[DCCP_CONNTRACK_OPEN] = true,
[DCCP_CONNTRACK_CLOSEREQ] = true,
[DCCP_CONNTRACK_CLOSING] = true,
[DCCP_CONNTRACK_TIMEWAIT] = true,
[DCCP_CONNTRACK_IGNORE] = true,
[DCCP_CONNTRACK_INVALID] = true,
};
static const char *const sctp_state2str[SCTP_CONNTRACK_MAX] = {
[SCTP_CONNTRACK_NONE] = "NOSTATE",
[SCTP_CONNTRACK_CLOSED] = "CLOSED",
[SCTP_CONNTRACK_COOKIE_WAIT] = "COOKIE_WAIT",
[SCTP_CONNTRACK_COOKIE_ECHOED] = "COOKIE_ECHOED",
[SCTP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
[SCTP_CONNTRACK_SHUTDOWN_SENT] = "SHUTDOWN_SENT",
[SCTP_CONNTRACK_SHUTDOWN_RECD] = "SHUTDOWN_RECD",
[SCTP_CONNTRACK_SHUTDOWN_ACK_SENT] = "SHUTDOWN_ACK_SENT",
};
static const uint8_t sctp_states_show[SCTP_CONNTRACK_MAX] = {
[SCTP_CONNTRACK_NONE] = true,
[SCTP_CONNTRACK_CLOSED] = true,
[SCTP_CONNTRACK_COOKIE_WAIT] = true,
[SCTP_CONNTRACK_COOKIE_ECHOED] = true,
[SCTP_CONNTRACK_ESTABLISHED] = true,
[SCTP_CONNTRACK_SHUTDOWN_SENT] = true,
[SCTP_CONNTRACK_SHUTDOWN_RECD] = true,
[SCTP_CONNTRACK_SHUTDOWN_ACK_SENT] = true,
};
static const struct nfct_filter_ipv4 filter_ipv4 = {
.addr = __constant_htonl(INADDR_LOOPBACK),
.mask = 0xffffffff,
};
static const struct nfct_filter_ipv6 filter_ipv6 = {
.addr = { 0x0, 0x0, 0x0, 0x1 },
.mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
};
#define SYS_PATH "/proc/sys/"
static int sysctl_set_int(char *file, int value)
{
char path[PATH_MAX];
char str[64];
ssize_t ret;
int fd;
path[0] = '\0';
strcat(path, SYS_PATH);
strncat(path, file, PATH_MAX - sizeof(SYS_PATH) - 1);
fd = open(path, O_WRONLY);
if (unlikely(fd < 0))
return -1;
ret = snprintf(str, 63, "%d", value);
if (ret < 0) {
close(fd);
return -1;
}
ret = write(fd, str, strlen(str));
close(fd);
return ret <= 0 ? -1 : 0;
}
static int sysctl_get_int(char *file, int *value)
{
char path[PATH_MAX];
char str[64];
ssize_t ret;
int fd;
path[0] = '\0';
strcat(path, SYS_PATH);
strncat(path, file, PATH_MAX - sizeof(SYS_PATH) - 1);
fd = open(path, O_RDONLY);
if (fd < 0)
return -1;
ret = read(fd, str, sizeof(str));
if (ret > 0) {
*value = atoi(str);
ret = 0;
} else {
ret = -1;
}
close(fd);
return ret;
}
static void signal_handler(int number)
{
switch (number) {
case SIGINT:
case SIGQUIT:
case SIGTERM:
sigint = 1;
break;
case SIGHUP:
default:
break;
}
}
static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct);
static void flow_entry_get_extended(struct flow_entry *n);
static void help(void)
{
printf("flowtop %s, top-like netfilter TCP/UDP/SCTP/.. flow tracking\n",
VERSION_STRING);
puts("http://www.netsniff-ng.org\n\n"
"Usage: flowtop [options]\n"
"Options:\n"
" -4|--ipv4 Show only IPv4 flows (default)\n"
" -6|--ipv6 Show only IPv6 flows (default)\n"
" -T|--tcp Show only TCP flows (default)\n"
" -U|--udp Show only UDP flows\n"
" -D|--dccp Show only DCCP flows\n"
" -I|--icmp Show only ICMP/ICMPv6 flows\n"
" -S|--sctp Show only SCTP flows\n"
" -s|--show-src Also show source, not only dest\n"
" -u|--update Update GeoIP databases\n"
" -v|--version Print version and exit\n"
" -h|--help Print this help and exit\n\n"
"Examples:\n"
" flowtop\n"
" flowtop -46UTDISs\n\n"
"Note:\n"
" If netfilter is not running, you can activate it with e.g.:\n"
" iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT\n"
" iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT\n");
puts(copyright);
die();
}
static void version(void)
{
printf("flowtop %s, Git id: %s\n", VERSION_LONG, GITVERSION);
puts("top-like netfilter TCP/UDP/SCTP/.. flow tracking\n"
"http://www.netsniff-ng.org\n");
puts(copyright);
die();
}
static inline struct flow_entry *flow_entry_xalloc(void)
{
return xzmalloc(sizeof(struct flow_entry));
}
static inline void flow_entry_xfree(struct flow_entry *n)
{
if (n->ct)
nfct_destroy(n->ct);
xfree(n);
}
static inline void flow_list_init(struct flow_list *fl)
{
fl->head = NULL;
spinlock_init(&fl->lock);
}
static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
{
struct flow_entry *n = flow_entry_xalloc();
n->ct = nfct_clone(ct);
flow_entry_from_ct(n, ct);
flow_entry_get_extended(n);
rcu_assign_pointer(n->next, fl->head);
rcu_assign_pointer(fl->head, n);
}
static struct flow_entry *flow_list_find_id(struct flow_list *fl,
uint32_t id)
{
struct flow_entry *n = rcu_dereference(fl->head);
while (n != NULL) {
if (n->flow_id == id)
return n;
n = rcu_dereference(n->next);
}
return NULL;
}
static struct flow_entry *flow_list_find_prev_id(struct flow_list *fl,
uint32_t id)
{
struct flow_entry *n = rcu_dereference(fl->head), *tmp;
if (n->flow_id == id)
return NULL;
while ((tmp = rcu_dereference(n->next)) != NULL) {
if (tmp->flow_id == id)
return n;
n = tmp;
}
return NULL;
}
static void flow_list_update_entry(struct flow_list *fl,
struct nf_conntrack *ct)
{
struct flow_entry *n;
n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
if (n == NULL) {
flow_list_new_entry(fl, ct);
return;
}
flow_entry_from_ct(n, ct);
}
static void flow_list_destroy_entry(struct flow_list *fl,
struct nf_conntrack *ct)
{
struct flow_entry *n1, *n2;
uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
n1 = flow_list_find_id(fl, id);
if (n1) {
n2 = flow_list_find_prev_id(fl, id);
if (n2) {
rcu_assign_pointer(n2->next, n1->next);
n1->next = NULL;
flow_entry_xfree(n1);
} else {
struct flow_entry *next = fl->head->next;
flow_entry_xfree(fl->head);
fl->head = next;
}
}
}
static void flow_list_destroy(struct flow_list *fl)
{
struct flow_entry *n;
while (fl->head != NULL) {
n = rcu_dereference(fl->head->next);
fl->head->next = NULL;
flow_entry_xfree(fl->head);
rcu_assign_pointer(fl->head, n);
}
synchronize_rcu();
spinlock_destroy(&fl->lock);
}
static int walk_process(unsigned int pid, struct flow_entry *n)
{
int ret;
DIR *dir;
struct dirent *ent;
char path[1024];
if (snprintf(path, sizeof(path), "/proc/%u/fd", pid) == -1)
panic("giant process name! %u\n", pid);
dir = opendir(path);
if (!dir)
return 0;
while ((ent = readdir(dir))) {
struct stat statbuf;
if (snprintf(path, sizeof(path), "/proc/%u/fd/%s",
pid, ent->d_name) < 0)
continue;
if (stat(path, &statbuf) < 0)
continue;
if (S_ISSOCK(statbuf.st_mode) && (ino_t) n->inode == statbuf.st_ino) {
memset(n->cmdline, 0, sizeof(n->cmdline));
snprintf(path, sizeof(path), "/proc/%u/exe", pid);
ret = readlink(path, n->cmdline,
sizeof(n->cmdline) - 1);
if (ret < 0)
panic("readlink error: %s\n", strerror(errno));
n->procnum = pid;
closedir(dir);
return 1;
}
}
closedir(dir);
return 0;
}
static void walk_processes(struct flow_entry *n)
{
int ret;
DIR *dir;
struct dirent *ent;
/* n->inode must be set */
if (n->inode <= 0) {
memset(n->cmdline, 0, sizeof(n->cmdline));
return;
}
dir = opendir("/proc");
if (!dir)
panic("Cannot open /proc: %s\n", strerror(errno));
while ((ent = readdir(dir))) {
const char *name = ent->d_name;
char *end;
unsigned int pid = strtoul(name, &end, 10);
/* not a PID */
if (pid == 0 && end == name)
continue;
ret = walk_process(pid, n);
if (ret > 0)
break;
}
closedir(dir);
}
static int get_port_inode(uint16_t port, int proto, int is_ip6)
{
int ret = -ENOENT;
char path[128], buff[1024];
FILE *proc;
memset(path, 0, sizeof(path));
snprintf(path, sizeof(path), "/proc/net/%s%s",
l4proto2str[proto], is_ip6 ? "6" : "");
proc = fopen(path, "r");
if (!proc)
return -EIO;
memset(buff, 0, sizeof(buff));
while (fgets(buff, sizeof(buff), proc) != NULL) {
int inode = 0;
unsigned int lport = 0;
buff[sizeof(buff) - 1] = 0;
if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
"%*X %*u %*u %u", &lport, &inode) == 2) {
if ((uint16_t) lport == port) {
ret = inode;
break;
}
}
memset(buff, 0, sizeof(buff));
}
fclose(proc);
return ret;
}
#define CP_NFCT(elem, attr, x) \
do { n->elem = nfct_get_attr_u##x(ct,(attr)); } while (0)
#define CP_NFCT_BUFF(elem, attr) do { \
const uint8_t *buff = nfct_get_attr(ct,(attr)); \
if (buff != NULL) \
memcpy(n->elem, buff, sizeof(n->elem)); \
} while (0)
static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
{
CP_NFCT(l3_proto, ATTR_ORIG_L3PROTO, 8);
CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
CP_NFCT(ip4_dst_addr, ATTR_ORIG_IPV4_DST, 32);
CP_NFCT(port_src, ATTR_ORIG_PORT_SRC, 16);
CP_NFCT(port_dst, ATTR_ORIG_PORT_DST, 16);
CP_NFCT(status, ATTR_STATUS, 32);
CP_NFCT(tcp_state, ATTR_TCP_STATE, 8);
CP_NFCT(tcp_flags, ATTR_TCP_FLAGS_ORIG, 8);
CP_NFCT(sctp_state, ATTR_SCTP_STATE, 8);
CP_NFCT(dccp_state, ATTR_DCCP_STATE, 8);
CP_NFCT(counter_pkts, ATTR_ORIG_COUNTER_PACKETS, 64);
CP_NFCT(counter_bytes, ATTR_ORIG_COUNTER_BYTES, 64);
CP_NFCT(timestamp_start, ATTR_TIMESTAMP_START, 64);
CP_NFCT(timestamp_stop, ATTR_TIMESTAMP_STOP, 64);
CP_NFCT(flow_id, ATTR_ID, 32);
CP_NFCT(use, ATTR_USE, 32);
CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
CP_NFCT_BUFF(ip6_dst_addr, ATTR_ORIG_IPV6_DST);
n->port_src = ntohs(n->port_src);
n->port_dst = ntohs(n->port_dst);
n->ip4_src_addr = ntohl(n->ip4_src_addr);
n->ip4_dst_addr = ntohl(n->ip4_dst_addr);
}
enum flow_entry_direction {
flow_entry_src,
flow_entry_dst,
};
static inline int flow_entry_get_extended_is_dns(struct flow_entry *n)
{
/* We don't want to analyze / display DNS itself, since we
* use it to resolve reverse dns.
*/
return n->port_src == 53 || n->port_dst == 53;
}
#define SELFLD(dir,src_member,dst_member) \
(((dir) == flow_entry_src) ? n->src_member : n->dst_member)
static void flow_entry_get_sain4_obj(struct flow_entry *n,
enum flow_entry_direction dir,
struct sockaddr_in *sa)
{
memset(sa, 0, sizeof(*sa));
sa->sin_family = PF_INET;
sa->sin_addr.s_addr = htonl(SELFLD(dir, ip4_src_addr, ip4_dst_addr));
}
static void flow_entry_get_sain6_obj(struct flow_entry *n,
enum flow_entry_direction dir,
struct sockaddr_in6 *sa)
{
memset(sa, 0, sizeof(*sa));
sa->sin6_family = PF_INET6;
memcpy(&sa->sin6_addr, SELFLD(dir, ip6_src_addr, ip6_dst_addr),
sizeof(sa->sin6_addr));
}
static void
flow_entry_geo_city_lookup_generic(struct flow_entry *n,
enum flow_entry_direction dir)
{
struct sockaddr_in sa4;
struct sockaddr_in6 sa6;
const char *city = NULL;
switch (n->l3_proto) {
default:
bug();
case AF_INET:
flow_entry_get_sain4_obj(n, dir, &sa4);
city = geoip4_city_name(&sa4);
break;
case AF_INET6:
flow_entry_get_sain6_obj(n, dir, &sa6);
city = geoip6_city_name(&sa6);
break;
}
bug_on(sizeof(n->city_src) != sizeof(n->city_dst));
if (city) {
memcpy(SELFLD(dir, city_src, city_dst), city,
min(sizeof(n->city_src), strlen(city)));
} else {
memset(SELFLD(dir, city_src, city_dst), 0,
sizeof(n->city_src));
}
}
static void
flow_entry_geo_country_lookup_generic(struct flow_entry *n,
enum flow_entry_direction dir)
{
struct sockaddr_in sa4;
struct sockaddr_in6 sa6;
const char *country = NULL;
switch (n->l3_proto) {
default:
bug();
case AF_INET:
flow_entry_get_sain4_obj(n, dir, &sa4);
country = geoip4_country_name(&sa4);
break;
case AF_INET6:
flow_entry_get_sain6_obj(n, dir, &sa6);
country = geoip6_country_name(&sa6);
break;
}
bug_on(sizeof(n->country_src) != sizeof(n->country_dst));
if (country) {
memcpy(SELFLD(dir, country_src, country_dst), country,
min(sizeof(n->country_src), strlen(country)));
} else {
memset(SELFLD(dir, country_src, country_dst), 0,
sizeof(n->country_src));
}
}
static void flow_entry_get_extended_geo(struct flow_entry *n,
enum flow_entry_direction dir)
{
flow_entry_geo_city_lookup_generic(n, dir);
flow_entry_geo_country_lookup_generic(n, dir);
}
static void flow_entry_get_extended_revdns(struct flow_entry *n,
enum flow_entry_direction dir)
{
size_t sa_len;
struct sockaddr_in sa4;
struct sockaddr_in6 sa6;
struct sockaddr *sa;
struct hostent *hent;
switch (n->l3_proto) {
default:
bug();
case AF_INET:
flow_entry_get_sain4_obj(n, dir, &sa4);
sa = (struct sockaddr *) &sa4;
sa_len = sizeof(sa4);
hent = gethostbyaddr(&sa4.sin_addr, sizeof(sa4.sin_addr), AF_INET);
break;
case AF_INET6:
flow_entry_get_sain6_obj(n, dir, &sa6);
sa = (struct sockaddr *) &sa6;
sa_len = sizeof(sa6);
hent = gethostbyaddr(&sa6.sin6_addr, sizeof(sa6.sin6_addr), AF_INET6);
break;
}
bug_on(sizeof(n->rev_dns_src) != sizeof(n->rev_dns_dst));
getnameinfo(sa, sa_len, SELFLD(dir, rev_dns_src, rev_dns_dst),
sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
if (hent) {
memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
memcpy(SELFLD(dir, rev_dns_src, rev_dns_dst),
hent->h_name, min(sizeof(n->rev_dns_src),
strlen(hent->h_name)));
}
}
static void flow_entry_get_extended(struct flow_entry *n)
{
if (n->flow_id == 0 || flow_entry_get_extended_is_dns(n))
return;
flow_entry_get_extended_revdns(n, flow_entry_src);
flow_entry_get_extended_geo(n, flow_entry_src);
flow_entry_get_extended_revdns(n, flow_entry_dst);
flow_entry_get_extended_geo(n, flow_entry_dst);
/* Lookup application */
n->inode = get_port_inode(n->port_src, n->l4_proto,
n->l3_proto == AF_INET6);
if (n->inode > 0)
walk_processes(n);
}
static uint16_t presenter_get_port(uint16_t src, uint16_t dst, int tcp)
{
if (src < dst && src < 1024) {
return src;
} else if (dst < src && dst < 1024) {
return dst;
} else {
const char *tmp1, *tmp2;
if (tcp) {
tmp1 = lookup_port_tcp(src);
tmp2 = lookup_port_tcp(dst);
} else {
tmp1 = lookup_port_udp(src);
tmp2 = lookup_port_udp(dst);
}
if (tmp1 && !tmp2) {
return src;
} else if (!tmp1 && tmp2) {
return dst;
} else {
if (src < dst)
return src;
else
return dst;
}
}
}
static void presenter_screen_do_line(WINDOW *screen, struct flow_entry *n,
unsigned int *line)
{
char tmp[128], *pname = NULL;
uint16_t port;
mvwprintw(screen, *line, 2, "");
/* PID, application name */
if (n->procnum > 0) {
slprintf(tmp, sizeof(tmp), "%s(%d)", basename(n->cmdline),
n->procnum);
printw("[");
attron(COLOR_PAIR(3));
printw("%s", tmp);
attroff(COLOR_PAIR(3));
printw("]:");
}
/* L3 protocol, L4 protocol, states */
printw("%s:%s", l3proto2str[n->l3_proto], l4proto2str[n->l4_proto]);
printw("[");
attron(COLOR_PAIR(3));
switch (n->l4_proto) {
case IPPROTO_TCP:
printw("%s", tcp_state2str[n->tcp_state]);
break;
case IPPROTO_SCTP:
printw("%s", sctp_state2str[n->sctp_state]);
break;
case IPPROTO_DCCP:
printw("%s", dccp_state2str[n->dccp_state]);
break;
case IPPROTO_UDP:
case IPPROTO_UDPLITE:
case IPPROTO_ICMP:
case IPPROTO_ICMPV6:
printw("NOSTATE");
break;
}
attroff(COLOR_PAIR(3));
printw("]");
/* Guess application port */
switch (n->l4_proto) {
case IPPROTO_TCP:
port = presenter_get_port(n->port_src, n->port_dst, 1);
pname = lookup_port_tcp(port);
break;
case IPPROTO_UDP:
case IPPROTO_UDPLITE:
port = presenter_get_port(n->port_src, n->port_dst, 0);
pname = lookup_port_udp(port);
break;
}
if (pname) {
attron(A_BOLD);
printw(":%s", pname);
attroff(A_BOLD);
}
printw(" ->");
/* Number packets, bytes */
if (n->counter_pkts > 0 && n->counter_bytes > 0)
printw(" (%"PRIu64" pkts, %"PRIu64" bytes) ->",
n->counter_pkts, n->counter_bytes);
/* Show source information: reverse DNS, port, country, city */
if (show_src) {
attron(COLOR_PAIR(1));
mvwprintw(screen, ++(*line), 8, "src: %s", n->rev_dns_src);
attroff(COLOR_PAIR(1));
printw(":%"PRIu16, n->port_src);
if (n->country_src[0]) {
printw(" (");
attron(COLOR_PAIR(4));
printw("%s", n->country_src);
attroff(COLOR_PAIR(4));
if (n->city_src[0])
printw(", %s", n->city_src);
printw(")");
}
printw(" => ");
}
/* Show dest information: reverse DNS, port, country, city */
attron(COLOR_PAIR(2));
mvwprintw(screen, ++(*line), 8, "dst: %s", n->rev_dns_dst);
attroff(COLOR_PAIR(2));
printw(":%"PRIu16, n->port_dst);
if (n->country_dst[0]) {
printw(" (");
attron(COLOR_PAIR(4));
printw("%s", n->country_dst);
attroff(COLOR_PAIR(4));
if (n->city_dst[0])
printw(", %s", n->city_dst);
printw(")");
}
}
static inline int presenter_flow_wrong_state(struct flow_entry *n)
{
int ret = 1;
switch (n->l4_proto) {
case IPPROTO_TCP:
if (tcp_states_show[n->tcp_state])
ret = 0;
break;
case IPPROTO_SCTP:
if (sctp_states_show[n->sctp_state])
ret = 0;
break;
case IPPROTO_DCCP:
if (dccp_states_show[n->dccp_state])
ret = 0;
break;
case IPPROTO_UDP:
case IPPROTO_UDPLITE:
case IPPROTO_ICMP:
case IPPROTO_ICMPV6:
ret = 0;
break;
}
return ret;
}
static void presenter_screen_update(WINDOW *screen, struct flow_list *fl,
int skip_lines)
{
int maxy;
unsigned int line = 3;
struct flow_entry *n;
curs_set(0);
maxy = getmaxy(screen);
maxy -= 6;
start_color();
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_BLUE, COLOR_BLACK);
init_pair(3, COLOR_YELLOW, COLOR_BLACK);
init_pair(4, COLOR_GREEN, COLOR_BLACK);
wclear(screen);
clear();
mvwprintw(screen, 1, 2, "Kernel netfilter flows for %s%s%s%s%s%s"
"[+%d]", what & INCLUDE_TCP ? "TCP, " : "" ,
what & INCLUDE_UDP ? "UDP, " : "",
what & INCLUDE_SCTP ? "SCTP, " : "",
what & INCLUDE_DCCP ? "DCCP, " : "",
what & INCLUDE_ICMP && what & INCLUDE_IPV4 ? "ICMP, " : "",
what & INCLUDE_ICMP && what & INCLUDE_IPV6 ? "ICMP6, " : "",
skip_lines);
rcu_read_lock();
n = rcu_dereference(fl->head);
if (!n)
mvwprintw(screen, line, 2, "(No active sessions! "
"Is netfilter running?)");
for (; n; n = rcu_dereference(n->next)) {
if (maxy <= 0)
goto skip;
if (presenter_get_port(n->port_src, n->port_dst, 0) == 53)
goto skip;
if (presenter_flow_wrong_state(n))
goto skip;
if (skip_lines > 0) {
skip_lines--;
goto skip;
}
presenter_screen_do_line(screen, n, &line);
line++;
maxy -= (2 + 1 * show_src);
n->is_visible = true;
continue;
skip:
n->is_visible = false;
continue;
}
rcu_read_unlock();
wrefresh(screen);
refresh();
}
static void presenter(void)
{
int skip_lines = 0;
WINDOW *screen;
condlock_wait(&collector_ready);
lookup_init_ports(PORTS_TCP);
lookup_init_ports(PORTS_UDP);
screen = screen_init(false);
rcu_register_thread();
while (!sigint) {
switch (getch()) {
case 'q':
sigint = 1;
break;
case KEY_UP:
case 'u':
case 'k':
skip_lines--;
if (skip_lines < 0)
skip_lines = 0;
break;
case KEY_DOWN:
case 'd':
case 'j':
skip_lines++;
if (skip_lines > SCROLL_MAX)
skip_lines = SCROLL_MAX;
break;
default:
fflush(stdin);
break;
}
presenter_screen_update(screen, &flow_list, skip_lines);
usleep(200000);
}
rcu_unregister_thread();
screen_end();
lookup_cleanup_ports(PORTS_UDP);
lookup_cleanup_ports(PORTS_TCP);
}
static int collector_cb(enum nf_conntrack_msg_type type,
struct nf_conntrack *ct, void *data __maybe_unused)
{
if (sigint)
return NFCT_CB_STOP;
synchronize_rcu();
spinlock_lock(&flow_list.lock);
switch (type) {
case NFCT_T_NEW:
flow_list_new_entry(&flow_list, ct);
break;
case NFCT_T_UPDATE:
flow_list_update_entry(&flow_list, ct);
break;
case NFCT_T_DESTROY:
flow_list_destroy_entry(&flow_list, ct);
break;
default:
break;
}
spinlock_unlock(&flow_list.lock);
return NFCT_CB_CONTINUE;
}
static inline void collector_flush(struct nfct_handle *handle, uint8_t family)
{
nfct_query(handle, NFCT_Q_FLUSH, &family);
}
static void restore_sysctl(void *value)
{
int int_val = *(int *)value;
if (int_val == 0)
sysctl_set_int("net/netfilter/nf_conntrack_acct", int_val);
}
static void on_panic_handler(void *arg)
{
restore_sysctl(arg);
screen_end();
}
static void conntrack_acct_enable(void)
{
/* We can still work w/o traffic accounting so just warn about error */
if (sysctl_get_int("net/netfilter/nf_conntrack_acct", &nfct_acct_val)) {
fprintf(stderr, "Can't read net/netfilter/nf_conntrack_acct: %s\n",
strerror(errno));
}
if (nfct_acct_val == 1)
return;
if (sysctl_set_int("net/netfilter/nf_conntrack_acct", 1)) {
fprintf(stderr, "Can't write net/netfilter/nf_conntrack_acct: %s\n",
strerror(errno));
}
}
static int dump_cb(enum nf_conntrack_msg_type type,
struct nf_conntrack *ct, void *data __maybe_unused)
{
struct flow_entry *n;
if (type != NFCT_T_UPDATE)
return NFCT_CB_CONTINUE;
if (sigint)
return NFCT_CB_STOP;
n = flow_list_find_id(&flow_list, nfct_get_attr_u32(ct, ATTR_ID));
if (!n)
return NFCT_CB_CONTINUE;
flow_entry_from_ct(n, ct);
return NFCT_CB_CONTINUE;
}
static void collector_refresh_flows(struct nfct_handle *handle)
{
struct flow_entry *n;
n = rcu_dereference(flow_list.head);
for (; n; n = rcu_dereference(n->next)) {
if (!n->is_visible)
continue;
nfct_query(handle, NFCT_Q_GET, n->ct);
}
}
static void *collector(void *null __maybe_unused)
{
struct nfct_handle *ct_event;
struct nfct_handle *ct_dump;
struct nfct_filter *filter;
struct pollfd poll_fd[1];
int ret;
ct_event = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_NEW |
NF_NETLINK_CONNTRACK_UPDATE |
NF_NETLINK_CONNTRACK_DESTROY);
if (!ct_event)
panic("Cannot create a nfct handle: %s\n", strerror(errno));
collector_flush(ct_event, AF_INET);
collector_flush(ct_event, AF_INET6);
filter = nfct_filter_create();
if (!filter)
panic("Cannot create a nfct filter: %s\n", strerror(errno));
ret = nfct_filter_attach(nfct_fd(ct_event), filter);
if (ret < 0)
panic("Cannot attach filter to handle: %s\n", strerror(errno));
if (what & INCLUDE_UDP) {
nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDPLITE);
}
if (what & INCLUDE_TCP)
nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
if (what & INCLUDE_DCCP)
nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_DCCP);
if (what & INCLUDE_SCTP)
nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_SCTP);
if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMP);
if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMPV6);
if (what & INCLUDE_IPV4) {
nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4, NFCT_FILTER_LOGIC_NEGATIVE);
nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
}
if (what & INCLUDE_IPV6) {
nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6, NFCT_FILTER_LOGIC_NEGATIVE);
nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
}
ret = nfct_filter_attach(nfct_fd(ct_event), filter);
if (ret < 0)
panic("Cannot attach filter to handle: %s\n", strerror(errno));
nfct_filter_destroy(filter);
nfct_callback_register(ct_event, NFCT_T_ALL, collector_cb, NULL);
flow_list_init(&flow_list);
ct_dump = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_UPDATE);
if (!ct_dump)
panic("Cannot create a nfct handle: %s\n", strerror(errno));
nfct_callback_register(ct_dump, NFCT_T_ALL, dump_cb, NULL);
poll_fd[0].fd = nfct_fd(ct_event);
poll_fd[0].events = POLLIN;
if (fcntl(nfct_fd(ct_event), F_SETFL, O_NONBLOCK) == -1)
panic("Cannot set non-blocking socket: fcntl(): %s\n",
strerror(errno));
if (fcntl(nfct_fd(ct_dump), F_SETFL, O_NONBLOCK) == -1)
panic("Cannot set non-blocking socket: fcntl(): %s\n",
strerror(errno));
condlock_signal(&collector_ready);
rcu_register_thread();
while (!sigint && ret >= 0) {
int status;
usleep(300000);
collector_refresh_flows(ct_dump);
status = poll(poll_fd, 1, 0);
if (status < 0) {
if (errno == EAGAIN || errno == EINTR)
continue;
panic("Error while polling: %s\n", strerror(errno));
} else if (status == 0) {
continue;
}
if (poll_fd[0].revents & POLLIN)
nfct_catch(ct_event);
}
rcu_unregister_thread();
flow_list_destroy(&flow_list);
nfct_close(ct_event);
nfct_close(ct_dump);
pthread_exit(NULL);
}
int main(int argc, char **argv)
{
pthread_t tid;
int ret, c, opt_index, what_cmd = 0;
setfsuid(getuid());
setfsgid(getgid());
while ((c = getopt_long(argc, argv, short_options, long_options,
&opt_index)) != EOF) {
switch (c) {
case '4':
what_cmd |= INCLUDE_IPV4;
break;
case '6':
what_cmd |= INCLUDE_IPV6;
break;
case 'T':
what_cmd |= INCLUDE_TCP;
break;
case 'U':
what_cmd |= INCLUDE_UDP;
break;
case 'D':
what_cmd |= INCLUDE_DCCP;
break;
case 'I':
what_cmd |= INCLUDE_ICMP;
break;
case 'S':
what_cmd |= INCLUDE_SCTP;
break;
case 's':
show_src = 1;
break;
case 'u':
update_geoip();
die();
break;
case 'h':
help();
break;
case 'v':
version();
break;
default:
break;
}
}
if (what_cmd > 0)
what = what_cmd;
rcu_init();
register_signal(SIGINT, signal_handler);
register_signal(SIGQUIT, signal_handler);
register_signal(SIGTERM, signal_handler);
register_signal(SIGHUP, signal_handler);
panic_handler_add(on_panic_handler, &nfct_acct_val);
conntrack_acct_enable();
init_geoip(1);
condlock_init(&collector_ready);
ret = pthread_create(&tid, NULL, collector, NULL);
if (ret < 0)
panic("Cannot create phthread!\n");
presenter();
condlock_destroy(&collector_ready);
destroy_geoip();
restore_sysctl(&nfct_acct_val);
return 0;
}
|