flowtop: add options for display ipv4,ipv6
[netsniff-ng.git] / src / flowtop.c
blobedcd7404252c4ad85d17320bb0fde4ce38403dba
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2011 - 2012 Daniel Borkmann.
5 * Copyright 2011 Emmanuel Roullit.
6 * Subject to the GPL, version 2.
8 * A tiny tool to provide top-like netfilter connection tracking information.
10 * The Dark Lord has Nine. But we have One, mightier than they: the White
11 * Rider. He has passed through the fire and the abyss, and they shall
12 * fear him. We will go where he leads.
14 * -- The Lord of the Rings, Aragorn,
15 * Chapter 'The White Rider'.
18 #define _LGPL_SOURCE
19 #include <stdio.h>
20 #include <stdint.h>
21 #include <stdlib.h>
22 #include <signal.h>
23 #include <getopt.h>
24 #include <pthread.h>
25 #include <signal.h>
26 #include <netdb.h>
27 #include <ctype.h>
28 #include <libnetfilter_conntrack/libnetfilter_conntrack.h>
29 #include <libnetfilter_conntrack/libnetfilter_conntrack_tcp.h>
30 #include <libnetfilter_conntrack/libnetfilter_conntrack_dccp.h>
31 #include <libnetfilter_conntrack/libnetfilter_conntrack_sctp.h>
32 #include <GeoIP.h>
33 #include <GeoIPCity.h>
34 #include <netinet/in.h>
35 #include <curses.h>
36 #include <dirent.h>
37 #include <sys/stat.h>
38 #include <urcu.h>
39 #include <libgen.h>
41 #include "die.h"
42 #include "xmalloc.h"
43 #include "xio.h"
44 #include "xutils.h"
45 #include "built_in.h"
46 #include "locking.h"
47 #include "dissector_eth.h"
48 #include "pkt_buff.h"
50 struct geo_ip_db {
51 GeoIP *gi4, *gi6;
52 char *path4, *path6;
55 struct flow_entry {
56 uint32_t flow_id, use, status;
57 uint8_t l3_proto, l4_proto;
58 uint32_t ip4_src_addr, ip4_dst_addr;
59 uint32_t ip6_src_addr[4], ip6_dst_addr[4];
60 uint16_t port_src, port_dst;
61 uint8_t tcp_state, tcp_flags;
62 uint64_t counter_pkts, counter_bytes;
63 uint64_t timestamp_start, timestamp_stop;
64 char country_src[128], country_dst[128];
65 char city_src[128], city_dst[128];
66 char rev_dns_src[256], rev_dns_dst[256];
67 int first, procnum, inode;
68 char cmdline[256];
69 struct flow_entry *next;
72 struct flow_list {
73 struct flow_entry *head;
74 struct spinlock lock;
77 #ifndef ATTR_TIMESTAMP_START
78 # define ATTR_TIMESTAMP_START 63
79 #endif
80 #ifndef ATTR_TIMESTAMP_STOP
81 # define ATTR_TIMESTAMP_STOP 64
82 #endif
84 #define SCROLL_MAX 1000
86 #define INCLUDE_IPV4 (1 << 0)
87 #define INCLUDE_IPV6 (1 << 1)
88 #define INCLUDE_UDP (1 << 2)
89 #define INCLUDE_TCP (1 << 3)
90 #define INCLUDE_DCCP (1 << 4)
91 #define INCLUDE_ICMP (1 << 5)
92 #define INCLUDE_SCTP (1 << 6)
94 volatile sig_atomic_t sigint = 0;
96 static int what = INCLUDE_IPV4 | INCLUDE_IPV6 | INCLUDE_TCP, show_src = 0;
98 struct geo_ip_db geo_country, geo_city;
100 static struct flow_list flow_list;
102 static const char *short_options = "vhTULKsOPDIS46";
103 static const struct option long_options[] = {
104 {"ipv4", no_argument, NULL, '4'},
105 {"ipv6", no_argument, NULL, '6'},
106 {"tcp", no_argument, NULL, 'T'},
107 {"udp", no_argument, NULL, 'U'},
108 {"dccp", no_argument, NULL, 'D'},
109 {"icmp", no_argument, NULL, 'I'},
110 {"sctp", no_argument, NULL, 'S'},
111 {"show-src", no_argument, NULL, 's'},
112 {"city-db4", required_argument, NULL, 'L'},
113 {"country-db4", required_argument, NULL, 'K'},
114 {"city-db6", required_argument, NULL, 'O'},
115 {"country-db6", required_argument, NULL, 'P'},
116 {"version", no_argument, NULL, 'v'},
117 {"help", no_argument, NULL, 'h'},
118 {NULL, 0, NULL, 0}
121 static const char *const l3proto2str[AF_MAX] = {
122 [AF_INET] = "ipv4",
123 [AF_INET6] = "ipv6",
126 static const char *const l4proto2str[IPPROTO_MAX] = {
127 [IPPROTO_TCP] = "tcp",
128 [IPPROTO_UDP] = "udp",
129 [IPPROTO_UDPLITE] = "udplite",
130 [IPPROTO_ICMP] = "icmp",
131 [IPPROTO_ICMPV6] = "icmpv6",
132 [IPPROTO_SCTP] = "sctp",
133 [IPPROTO_GRE] = "gre",
134 [IPPROTO_DCCP] = "dccp",
135 [IPPROTO_IGMP] = "igmp",
136 [IPPROTO_IPIP] = "ipip",
137 [IPPROTO_EGP] = "egp",
138 [IPPROTO_PUP] = "pup",
139 [IPPROTO_IDP] = "idp",
140 [IPPROTO_RSVP] = "rsvp",
141 [IPPROTO_IPV6] = "ip6tun",
142 [IPPROTO_ESP] = "esp",
143 [IPPROTO_AH] = "ah",
144 [IPPROTO_PIM] = "pim",
145 [IPPROTO_COMP] = "comp",
148 static const char *const tcp_state2str[TCP_CONNTRACK_MAX] = {
149 [TCP_CONNTRACK_NONE] = "NOSTATE",
150 [TCP_CONNTRACK_SYN_SENT] = "SYN_SENT",
151 [TCP_CONNTRACK_SYN_RECV] = "SYN_RECV",
152 [TCP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
153 [TCP_CONNTRACK_FIN_WAIT] = "FIN_WAIT",
154 [TCP_CONNTRACK_CLOSE_WAIT] = "CLOSE_WAIT",
155 [TCP_CONNTRACK_LAST_ACK] = "LAST_ACK",
156 [TCP_CONNTRACK_TIME_WAIT] = "TIME_WAIT",
157 [TCP_CONNTRACK_CLOSE] = "CLOSE",
158 [TCP_CONNTRACK_SYN_SENT2] = "SYN_SENT2",
161 static const uint8_t tcp_states[] = {
162 TCP_CONNTRACK_SYN_SENT,
163 TCP_CONNTRACK_SYN_RECV,
164 TCP_CONNTRACK_ESTABLISHED,
165 TCP_CONNTRACK_FIN_WAIT,
166 TCP_CONNTRACK_CLOSE_WAIT,
167 TCP_CONNTRACK_LAST_ACK,
168 TCP_CONNTRACK_TIME_WAIT,
169 TCP_CONNTRACK_CLOSE,
170 TCP_CONNTRACK_SYN_SENT2,
171 TCP_CONNTRACK_NONE,
174 static const char *const dccp_state2str[DCCP_CONNTRACK_MAX] = {
175 [DCCP_CONNTRACK_NONE] = "NOSTATE",
176 [DCCP_CONNTRACK_REQUEST] = "REQUEST",
177 [DCCP_CONNTRACK_RESPOND] = "RESPOND",
178 [DCCP_CONNTRACK_PARTOPEN] = "PARTOPEN",
179 [DCCP_CONNTRACK_OPEN] = "OPEN",
180 [DCCP_CONNTRACK_CLOSEREQ] = "CLOSEREQ",
181 [DCCP_CONNTRACK_CLOSING] = "CLOSING",
182 [DCCP_CONNTRACK_TIMEWAIT] = "TIMEWAIT",
183 [DCCP_CONNTRACK_IGNORE] = "IGNORE",
184 [DCCP_CONNTRACK_INVALID] = "INVALID",
187 static const uint8_t dccp_states[] = {
188 DCCP_CONNTRACK_NONE,
189 DCCP_CONNTRACK_REQUEST,
190 DCCP_CONNTRACK_RESPOND,
191 DCCP_CONNTRACK_PARTOPEN,
192 DCCP_CONNTRACK_OPEN,
193 DCCP_CONNTRACK_CLOSEREQ,
194 DCCP_CONNTRACK_CLOSING,
195 DCCP_CONNTRACK_TIMEWAIT,
196 DCCP_CONNTRACK_IGNORE,
197 DCCP_CONNTRACK_INVALID,
200 static const char *const sctp_state2str[SCTP_CONNTRACK_MAX] = {
201 [SCTP_CONNTRACK_NONE] = "NOSTATE",
202 [SCTP_CONNTRACK_CLOSED] = "CLOSED",
203 [SCTP_CONNTRACK_COOKIE_WAIT] = "COOKIE_WAIT",
204 [SCTP_CONNTRACK_COOKIE_ECHOED] = "COOKIE_ECHOED",
205 [SCTP_CONNTRACK_ESTABLISHED] = "ESTABLISHED",
206 [SCTP_CONNTRACK_SHUTDOWN_SENT] = "SHUTDOWN_SENT",
207 [SCTP_CONNTRACK_SHUTDOWN_RECD] = "SHUTDOWN_RECD",
208 [SCTP_CONNTRACK_SHUTDOWN_ACK_SENT] = "SHUTDOWN_ACK_SENT",
211 static const uint8_t sctp_states[] = {
212 SCTP_CONNTRACK_NONE,
213 SCTP_CONNTRACK_CLOSED,
214 SCTP_CONNTRACK_COOKIE_WAIT,
215 SCTP_CONNTRACK_COOKIE_ECHOED,
216 SCTP_CONNTRACK_ESTABLISHED,
217 SCTP_CONNTRACK_SHUTDOWN_SENT,
218 SCTP_CONNTRACK_SHUTDOWN_RECD,
219 SCTP_CONNTRACK_SHUTDOWN_ACK_SENT,
222 static const struct nfct_filter_ipv4 filter_ipv4 = {
223 .addr = __constant_htonl(INADDR_LOOPBACK),
224 .mask = 0xffffffff,
227 static const struct nfct_filter_ipv6 filter_ipv6 = {
228 .addr = { 0x0, 0x0, 0x0, 0x1 },
229 .mask = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
232 static void signal_handler(int number)
234 switch (number) {
235 case SIGINT:
236 sigint = 1;
237 break;
238 case SIGHUP:
239 default:
240 break;
244 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct);
245 static void flow_entry_get_extended(struct flow_entry *n);
247 static void help(void)
249 printf("\nflowtop %s, top-like netfilter TCP/UDP flow tracking\n",
250 VERSION_STRING);
251 puts("http://www.netsniff-ng.org\n\n"
252 "Usage: flowtop [options]\n"
253 "Options:\n"
254 " -4|--ipv4 Show only IPv4 flows (default)\n"
255 " -6|--ipv6 Show only IPv6 flows (default)\n"
256 " -T|--tcp Show only TCP flows (default)\n"
257 " -U|--udp Show only UDP flows\n"
258 " -D|--dccp Show only DCCP flows\n"
259 " -I|--icmp Show only ICMP/ICMPv6 flows\n"
260 " -S|--sctp Show only SCTP flows\n"
261 " -s|--show-src Also show source, not only dest\n"
262 " --city-db4 <path> Specifiy path for geoip4 city database\n"
263 " --country-db4 <path> Specifiy path for geoip4 country database\n"
264 " --city-db6 <path> Specifiy path for geoip6 city database\n"
265 " --country-db6 <path> Specifiy path for geoip6 country database\n"
266 " -v|--version Print version\n"
267 " -h|--help Print this help\n\n"
268 "Examples:\n"
269 " flowtop\n"
270 " flowtop -46UTDISs\n\n"
271 "Note:\n"
272 " If netfilter is not running, you can activate it with i.e.:\n"
273 " iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT\n"
274 " iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT\n\n"
275 "Please report bugs to <bugs@netsniff-ng.org>\n"
276 "Copyright (C) 2011-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
277 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n"
278 "License: GNU GPL version 2.0\n"
279 "This is free software: you are free to change and redistribute it.\n"
280 "There is NO WARRANTY, to the extent permitted by law.\n");
281 die();
284 static void version(void)
286 printf("\nflowtop %s, top-like netfilter TCP/UDP flow tracking\n",
287 VERSION_STRING);
288 puts("http://www.netsniff-ng.org\n\n"
289 "Please report bugs to <bugs@netsniff-ng.org>\n"
290 "Copyright (C) 2011-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
291 "Copyright (C) 2011-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n"
292 "License: GNU GPL version 2.0\n"
293 "This is free software: you are free to change and redistribute it.\n"
294 "There is NO WARRANTY, to the extent permitted by law.\n");
295 die();
298 static inline struct flow_entry *flow_entry_xalloc(void)
300 struct flow_entry *n;
302 n = xzmalloc(sizeof(*n));
303 n->first = 1;
305 return n;
308 static inline void flow_entry_xfree(struct flow_entry *n)
310 xfree(n);
313 static inline void flow_list_init(struct flow_list *fl)
315 fl->head = NULL;
316 spinlock_init(&fl->lock);
319 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
321 struct flow_entry *n = flow_entry_xalloc();
323 rcu_assign_pointer(n->next, fl->head);
324 rcu_assign_pointer(fl->head, n);
326 flow_entry_from_ct(n, ct);
327 flow_entry_get_extended(n);
330 static struct flow_entry *flow_list_find_id(struct flow_list *fl,
331 uint32_t id)
333 struct flow_entry *n = rcu_dereference(fl->head);
335 while (n != NULL) {
336 if (n->flow_id == id)
337 return n;
339 n = rcu_dereference(n->next);
342 return NULL;
345 static struct flow_entry *flow_list_find_prev_id(struct flow_list *fl,
346 uint32_t id)
348 struct flow_entry *n = rcu_dereference(fl->head), *tmp;
350 if (n->flow_id == id)
351 return NULL;
353 while ((tmp = rcu_dereference(n->next)) != NULL) {
354 if (tmp->flow_id == id)
355 return n;
357 n = tmp;
360 return NULL;
363 static void flow_list_update_entry(struct flow_list *fl,
364 struct nf_conntrack *ct)
366 int do_ext = 0;
367 struct flow_entry *n;
369 n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
370 if (n == NULL) {
371 n = flow_entry_xalloc();
373 rcu_assign_pointer(n->next, fl->head);
374 rcu_assign_pointer(fl->head, n);
376 do_ext = 1;
379 flow_entry_from_ct(n, ct);
380 if (do_ext)
381 flow_entry_get_extended(n);
384 static void flow_list_destroy_entry(struct flow_list *fl,
385 struct nf_conntrack *ct)
387 struct flow_entry *n1, *n2;
388 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
390 n1 = flow_list_find_id(fl, id);
391 if (n1) {
392 n2 = flow_list_find_prev_id(fl, id);
393 if (n2) {
394 rcu_assign_pointer(n2->next, n1->next);
395 rcu_assign_pointer(n1->next, NULL);
397 flow_entry_xfree(n1);
398 } else {
399 flow_entry_xfree(fl->head);
401 rcu_assign_pointer(fl->head, NULL);
406 static void flow_list_destroy(struct flow_list *fl)
408 struct flow_entry *n;
410 while (fl->head != NULL) {
411 n = rcu_dereference(fl->head->next);
412 rcu_assign_pointer(fl->head->next, NULL);
414 flow_entry_xfree(fl->head);
415 rcu_assign_pointer(fl->head, n);
418 synchronize_rcu();
419 spinlock_destroy(&fl->lock);
422 static int walk_process(char *process, struct flow_entry *n)
424 int ret;
425 DIR *dir;
426 struct dirent *ent;
427 char path[1024];
429 if (snprintf(path, sizeof(path), "/proc/%s/fd", process) == -1)
430 panic("giant process name! %s\n", process);
432 dir = opendir(path);
433 if (!dir)
434 return 0;
436 while ((ent = readdir(dir))) {
437 struct stat statbuf;
439 if (snprintf(path, sizeof(path), "/proc/%s/fd/%s",
440 process, ent->d_name) < 0)
441 continue;
443 if (stat(path, &statbuf) < 0)
444 continue;
446 if (S_ISSOCK(statbuf.st_mode) && n->inode == statbuf.st_ino) {
447 memset(n->cmdline, 0, sizeof(n->cmdline));
449 snprintf(path, sizeof(path), "/proc/%s/exe", process);
451 ret = readlink(path, n->cmdline,
452 sizeof(n->cmdline) - 1);
453 if (ret < 0)
454 panic("readlink error: %s\n", strerror(errno));
456 n->procnum = atoi(process);
457 return 1;
461 closedir(dir);
462 return 0;
465 static void walk_processes(struct flow_entry *n)
467 int ret;
468 DIR *dir;
469 struct dirent *ent;
471 /* n->inode must be set */
472 if (n->inode <= 0) {
473 memset(n->cmdline, 0, sizeof(n->cmdline));
474 return;
477 dir = opendir("/proc");
478 if (!dir)
479 panic("Cannot open /proc!\n");
481 while ((ent = readdir(dir))) {
482 if (strspn(ent->d_name, "0123456789") == strlen(ent->d_name)) {
483 ret = walk_process(ent->d_name, n);
484 if (ret > 0)
485 break;
489 closedir(dir);
492 static int get_port_inode(uint16_t port, int proto, int is_ip6)
494 int ret = -ENOENT;
495 char path[128], buff[1024];
496 FILE *proc;
498 memset(path, 0, sizeof(path));
499 snprintf(path, sizeof(path), "/proc/net/%s%s",
500 l4proto2str[proto], is_ip6 ? "6" : "");
502 proc = fopen(path, "r");
503 if (!proc)
504 return -EIO;
506 memset(buff, 0, sizeof(buff));
508 while (fgets(buff, sizeof(buff), proc) != NULL) {
509 int inode = 0;
510 unsigned int lport = 0;
512 buff[sizeof(buff) - 1] = 0;
513 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
514 "%*X %*u %*u %u", &lport, &inode) == 2) {
515 if ((uint16_t) lport == port) {
516 ret = inode;
517 break;
521 memset(buff, 0, sizeof(buff));
524 fclose(proc);
525 return ret;
528 #define CP_NFCT(elem, attr, x) \
529 do { n->elem = nfct_get_attr_u##x(ct,(attr)); } while (0)
530 #define CP_NFCT_BUFF(elem, attr) do { \
531 const uint8_t *buff = nfct_get_attr(ct,(attr)); \
532 if (buff != NULL) \
533 memcpy(n->elem, buff, sizeof(n->elem)); \
534 } while (0)
536 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
538 CP_NFCT(l3_proto, ATTR_ORIG_L3PROTO, 8);
539 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
540 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
541 CP_NFCT(ip4_dst_addr, ATTR_ORIG_IPV4_DST, 32);
542 CP_NFCT(port_src, ATTR_ORIG_PORT_SRC, 16);
543 CP_NFCT(port_dst, ATTR_ORIG_PORT_DST, 16);
544 CP_NFCT(status, ATTR_STATUS, 32);
545 CP_NFCT(tcp_state, ATTR_TCP_STATE, 8);
546 CP_NFCT(tcp_flags, ATTR_TCP_FLAGS_ORIG, 8);
547 CP_NFCT(counter_pkts, ATTR_ORIG_COUNTER_PACKETS, 64);
548 CP_NFCT(counter_bytes, ATTR_ORIG_COUNTER_BYTES, 64);
549 CP_NFCT(timestamp_start, ATTR_TIMESTAMP_START, 64);
550 CP_NFCT(timestamp_stop, ATTR_TIMESTAMP_STOP, 64);
551 CP_NFCT(flow_id, ATTR_ID, 32);
552 CP_NFCT(use, ATTR_USE, 32);
554 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
555 CP_NFCT_BUFF(ip6_dst_addr, ATTR_ORIG_IPV6_DST);
557 n->port_src = ntohs(n->port_src);
558 n->port_dst = ntohs(n->port_dst);
560 n->ip4_src_addr = ntohl(n->ip4_src_addr);
561 n->ip4_dst_addr = ntohl(n->ip4_dst_addr);
563 if (n->first) {
564 n->inode = get_port_inode(n->port_src, n->l4_proto,
565 n->l3_proto == AF_INET6);
566 if (n->inode > 0)
567 walk_processes(n);
570 n->first = 0;
573 enum flow_entry_direction {
574 flow_entry_src,
575 flow_entry_dst,
578 static inline int flow_entry_get_extended_is_dns(struct flow_entry *n)
580 /* We don't want to analyze / display DNS itself, since we
581 * use it to resolve reverse dns.
583 return n->port_src == 53 || n->port_dst == 53;
586 #define SELFLD(dir,src_member,dst_member) \
587 (((dir) == flow_entry_src) ? n->src_member : n->dst_member)
589 static struct sockaddr_in *
590 flow_entry_get_sain4_obj(struct flow_entry *n, enum flow_entry_direction dir,
591 struct sockaddr_in *sa)
593 memset(sa, 0, sizeof(*sa));
594 sa->sin_family = PF_INET;
595 sa->sin_addr.s_addr = htonl(SELFLD(dir, ip4_src_addr, ip4_dst_addr));
597 return sa;
600 static struct sockaddr_in6 *
601 flow_entry_get_sain6_obj(struct flow_entry *n, enum flow_entry_direction dir,
602 struct sockaddr_in6 *sa)
604 memset(sa, 0, sizeof(*sa));
605 sa->sin6_family = PF_INET6;
607 memcpy(&sa->sin6_addr, SELFLD(dir, ip6_src_addr, ip6_dst_addr),
608 sizeof(SELFLD(dir, ip6_src_addr, ip6_dst_addr)));
610 return sa;
613 static void
614 flow_entry_geo_city_lookup_generic(struct flow_entry *n,
615 enum flow_entry_direction dir)
617 GeoIPRecord *gir = NULL;
618 struct sockaddr_in sa4;
619 struct sockaddr_in6 sa6;
620 inline const char *make_na(const char *p) { return p ? : "N/A"; }
621 const char *city = NULL;
623 switch (n->l3_proto) {
624 default:
625 bug();
627 case AF_INET:
628 flow_entry_get_sain4_obj(n, dir, &sa4);
629 gir = GeoIP_record_by_ipnum(geo_city.gi4,
630 ntohl(sa4.sin_addr.s_addr));
631 break;
633 case AF_INET6:
634 flow_entry_get_sain6_obj(n, dir, &sa6);
635 gir = GeoIP_record_by_ipnum_v6(geo_city.gi6, sa6.sin6_addr);
636 break;
639 city = make_na(gir != NULL ? gir->city : city);
641 bug_on(sizeof(n->city_src) != sizeof(n->city_dst));
642 memcpy(SELFLD(dir, city_src, city_dst), city,
643 min(sizeof(n->city_src), strlen(city)));
646 static void
647 flow_entry_geo_country_lookup_generic(struct flow_entry *n,
648 enum flow_entry_direction dir)
650 struct sockaddr_in sa4;
651 struct sockaddr_in6 sa6;
652 inline const char *make_na(const char *p) { return p ? : "N/A"; }
653 const char *country = NULL;
655 switch (n->l3_proto) {
656 default:
657 bug();
659 case AF_INET:
660 flow_entry_get_sain4_obj(n, dir, &sa4);
661 country = GeoIP_country_name_by_ipnum(geo_country.gi4,
662 ntohl(sa4.sin_addr.s_addr));
663 break;
665 case AF_INET6:
666 flow_entry_get_sain6_obj(n, dir, &sa6);
667 country = GeoIP_country_name_by_ipnum_v6(geo_country.gi6,
668 sa6.sin6_addr);
669 break;
672 country = make_na(country);
674 bug_on(sizeof(n->country_src) != sizeof(n->country_dst));
675 memcpy(SELFLD(dir, country_src, country_dst), country,
676 min(sizeof(n->country_src), strlen(country)));
679 static void flow_entry_get_extended_geo(struct flow_entry *n,
680 enum flow_entry_direction dir)
682 flow_entry_geo_city_lookup_generic(n, dir);
683 flow_entry_geo_country_lookup_generic(n, dir);
686 static void flow_entry_get_extended_revdns(struct flow_entry *n,
687 enum flow_entry_direction dir)
689 size_t sa_len;
690 struct sockaddr_in sa4;
691 struct sockaddr_in6 sa6;
692 struct sockaddr *sa;
693 struct hostent *hent;
695 switch (n->l3_proto) {
696 default:
697 bug();
699 case AF_INET:
700 flow_entry_get_sain4_obj(n, dir, &sa4);
701 sa = (struct sockaddr *) &sa4;
702 sa_len = sizeof(sa4);
703 hent = gethostbyaddr(&sa4.sin_addr, sizeof(sa4.sin_addr),
704 AF_INET);
705 break;
707 case AF_INET6:
708 flow_entry_get_sain6_obj(n, dir, &sa6);
709 sa = (struct sockaddr *) &sa6;
710 sa_len = sizeof(sa6);
711 hent = gethostbyaddr(&sa6.sin6_addr, sizeof(sa6.sin6_addr),
712 AF_INET6);
713 break;
716 bug_on(sizeof(n->rev_dns_src) != sizeof(n->rev_dns_dst));
717 getnameinfo(sa, sa_len, SELFLD(dir, rev_dns_src, rev_dns_dst),
718 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
720 if (hent) {
721 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
722 memcpy(SELFLD(dir, rev_dns_src, rev_dns_dst),
723 hent->h_name, min(sizeof(n->rev_dns_src),
724 strlen(hent->h_name)));
728 static void flow_entry_get_extended(struct flow_entry *n)
730 if (n->flow_id == 0 || flow_entry_get_extended_is_dns(n))
731 return;
733 flow_entry_get_extended_revdns(n, flow_entry_src);
734 flow_entry_get_extended_geo(n, flow_entry_src);
736 flow_entry_get_extended_revdns(n, flow_entry_dst);
737 flow_entry_get_extended_geo(n, flow_entry_dst);
740 static uint16_t presenter_get_port(uint16_t src, uint16_t dst, int tcp)
742 if (src < dst && src < 1024) {
743 return src;
744 } else if (dst < src && dst < 1024) {
745 return dst;
746 } else {
747 const char *tmp1, *tmp2;
748 if (tcp) {
749 tmp1 = lookup_port_tcp(src);
750 tmp2 = lookup_port_tcp(dst);
751 } else {
752 tmp1 = lookup_port_udp(src);
753 tmp2 = lookup_port_udp(dst);
755 if (tmp1 && !tmp2) {
756 return src;
757 } else if (!tmp1 && tmp2) {
758 return dst;
759 } else {
760 if (src < dst)
761 return src;
762 else
763 return dst;
768 static void presenter_screen_init(WINDOW **screen)
770 (*screen) = initscr();
771 noecho();
772 cbreak();
773 keypad(stdscr, TRUE);
774 nodelay(*screen, TRUE);
775 refresh();
776 wrefresh(*screen);
779 static void presenter_screen_do_line(WINDOW *screen, struct flow_entry *n,
780 unsigned int *line)
782 char tmp[128];
783 uint16_t port;
785 mvwprintw(screen, *line, 2, "");
787 /* PID, application name */
788 if (n->procnum > 0) {
789 slprintf(tmp, sizeof(tmp), "%u/%s", n->procnum,
790 basename(n->cmdline));
792 printw("[");
793 attron(COLOR_PAIR(3));
794 printw("%s", tmp);
795 attroff(COLOR_PAIR(3));
796 printw("]:");
799 /* L3 protocol, L4 protocol, TCP state */
800 printw("%s:%s", l3proto2str[n->l3_proto], l4proto2str[n->l4_proto]);
801 printw("[");
802 attron(COLOR_PAIR(3));
803 printw("%s", tcp_state2str[n->tcp_state]);
804 attroff(COLOR_PAIR(3));
805 printw("]:");
807 /* Guess application port */
808 attron(A_BOLD);
809 if (n->tcp_state != TCP_CONNTRACK_NONE) {
810 port = presenter_get_port(n->port_src, n->port_dst, 1);
811 printw("%s ->", lookup_port_tcp(port));
812 } else {
813 port = presenter_get_port(n->port_src, n->port_dst, 0);
814 printw("%s ->", lookup_port_udp(port));
816 attroff(A_BOLD);
818 #if 0
819 /* Number packets, bytes */
820 printw("(%upkts/%ubytes) ->", n->counter_pkts, n->counter_bytes);
821 #endif
823 /* Show source information: reverse DNS, port, country, city */
824 if (show_src) {
825 attron(COLOR_PAIR(1));
826 mvwprintw(screen, ++(*line), 8, "src: %s", n->rev_dns_src);
827 attroff(COLOR_PAIR(1));
829 printw(":%u (", n->port_src);
831 attron(COLOR_PAIR(4));
832 printw("%s", n->country_src);
833 attroff(COLOR_PAIR(4));
835 printw(", %s) => ", n->city_src);
838 /* Show dest information: reverse DNS, port, country, city */
839 attron(COLOR_PAIR(2));
840 mvwprintw(screen, ++(*line), 8, "dst: %s", n->rev_dns_dst);
841 attroff(COLOR_PAIR(2));
843 printw(":%u (", n->port_dst);
845 attron(COLOR_PAIR(4));
846 printw("%s", n->country_dst);
847 attroff(COLOR_PAIR(4));
849 printw(", %s)", n->city_dst);
852 static void presenter_screen_update(WINDOW *screen, struct flow_list *fl,
853 int skip_lines)
855 int i, maxy;
856 unsigned int line = 3;
857 struct flow_entry *n;
859 curs_set(0);
861 maxy = getmaxy(screen);
863 start_color();
864 init_pair(1, COLOR_RED, COLOR_BLACK);
865 init_pair(2, COLOR_BLUE, COLOR_BLACK);
866 init_pair(3, COLOR_YELLOW, COLOR_BLACK);
867 init_pair(4, COLOR_GREEN, COLOR_BLACK);
869 wclear(screen);
870 clear();
872 mvwprintw(screen, 1, 2, "Kernel netfilter TCP/UDP "
873 "flow statistics, [+%d]", skip_lines);
875 rcu_read_lock();
877 if (rcu_dereference(fl->head) == NULL)
878 mvwprintw(screen, line, 2, "(No active sessions! "
879 "Is netfilter running?)");
881 maxy -= 6;
882 /* Yes, that's lame :-P */
883 for (i = 0; i < sizeof(tcp_states); i++) {
884 n = rcu_dereference(fl->head);
885 while (n && maxy > 0) {
886 if (n->tcp_state != tcp_states[i] ||
887 (i != TCP_CONNTRACK_NONE &&
888 n->tcp_state == TCP_CONNTRACK_NONE) ||
889 /* Filter out DNS */
890 presenter_get_port(n->port_src,
891 n->port_dst, 0) == 53) {
892 n = rcu_dereference(n->next);
893 continue;
895 if (skip_lines > 0) {
896 n = rcu_dereference(n->next);
897 skip_lines--;
898 continue;
901 presenter_screen_do_line(screen, n, &line);
903 line++;
904 maxy -= (2 + 1 * show_src);
905 n = rcu_dereference(n->next);
909 rcu_read_unlock();
911 wrefresh(screen);
912 refresh();
915 static inline void presenter_screen_end(void)
917 endwin();
920 static void presenter(void)
922 int skip_lines = 0;
923 WINDOW *screen = NULL;
925 dissector_init_ethernet(0);
926 presenter_screen_init(&screen);
928 rcu_register_thread();
929 while (!sigint) {
930 switch (getch()) {
931 case 'q':
932 sigint = 1;
933 break;
934 case KEY_UP:
935 case 'u':
936 case 'k':
937 skip_lines--;
938 if (skip_lines < 0)
939 skip_lines = 0;
940 break;
941 case KEY_DOWN:
942 case 'd':
943 case 'j':
944 skip_lines++;
945 if (skip_lines > SCROLL_MAX)
946 skip_lines = SCROLL_MAX;
947 break;
948 default:
949 fflush(stdin);
950 break;
953 presenter_screen_update(screen, &flow_list, skip_lines);
954 usleep(100000);
956 rcu_unregister_thread();
958 presenter_screen_end();
959 dissector_cleanup_ethernet();
962 static int collector_cb(enum nf_conntrack_msg_type type,
963 struct nf_conntrack *ct, void *data)
965 if (sigint)
966 return NFCT_CB_STOP;
968 synchronize_rcu();
969 spinlock_lock(&flow_list.lock);
971 switch (type) {
972 case NFCT_T_NEW:
973 flow_list_new_entry(&flow_list, ct);
974 break;
975 case NFCT_T_UPDATE:
976 flow_list_update_entry(&flow_list, ct);
977 break;
978 case NFCT_T_DESTROY:
979 flow_list_destroy_entry(&flow_list, ct);
980 break;
981 default:
982 break;
985 spinlock_unlock(&flow_list.lock);
987 return NFCT_CB_CONTINUE;
990 static inline GeoIP *collector_geoip_open(const char *path, int type)
992 if (path != NULL)
993 return GeoIP_open(path, GEOIP_MMAP_CACHE);
994 else
995 return GeoIP_open_type(type, GEOIP_MMAP_CACHE);
998 static void collector_load_geoip(void)
1000 geo_country.gi4 = collector_geoip_open(geo_country.path4,
1001 GEOIP_COUNTRY_EDITION);
1002 if (geo_country.gi4 == NULL)
1003 panic("Cannot open GeoIP4 country database!\n");
1005 geo_country.gi6 = collector_geoip_open(geo_country.path6,
1006 GEOIP_COUNTRY_EDITION_V6);
1007 if (geo_country.gi6 == NULL)
1008 panic("Cannot open GeoIP6 country database!\n");
1010 geo_city.gi4 = collector_geoip_open(geo_city.path4,
1011 GEOIP_CITY_EDITION_REV1);
1012 if (geo_city.gi4 == NULL)
1013 panic("Cannot open GeoIP4 city database!\n");
1015 geo_city.gi6 = collector_geoip_open(geo_city.path6,
1016 GEOIP_CITY_EDITION_REV1_V6);
1017 if (geo_city.gi6 == NULL)
1018 panic("Cannot open GeoIP6 city database!\n");
1020 GeoIP_set_charset(geo_country.gi4, GEOIP_CHARSET_UTF8);
1021 GeoIP_set_charset(geo_country.gi6, GEOIP_CHARSET_UTF8);
1023 GeoIP_set_charset(geo_city.gi4, GEOIP_CHARSET_UTF8);
1024 GeoIP_set_charset(geo_city.gi6, GEOIP_CHARSET_UTF8);
1027 static void collector_destroy_geoip(void)
1029 GeoIP_delete(geo_country.gi4);
1030 GeoIP_delete(geo_country.gi6);
1032 GeoIP_delete(geo_city.gi4);
1033 GeoIP_delete(geo_city.gi6);
1036 static void *collector(void *null)
1038 int ret;
1039 struct nfct_handle *handle;
1040 struct nfct_filter *filter;
1042 handle = nfct_open(CONNTRACK, NFCT_ALL_CT_GROUPS);
1043 if (!handle)
1044 panic("Cannot create a nfct handle!\n");
1046 filter = nfct_filter_create();
1047 if (!filter)
1048 panic("Cannot create a nfct filter!\n");
1050 if (what & INCLUDE_UDP)
1051 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
1052 if (what & INCLUDE_TCP)
1053 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
1054 if (what & INCLUDE_DCCP)
1055 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_DCCP);
1056 if (what & INCLUDE_SCTP)
1057 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_SCTP);
1058 if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
1059 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMP);
1060 if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
1061 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMPV6);
1062 if (what & INCLUDE_IPV4) {
1063 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4,
1064 NFCT_FILTER_LOGIC_NEGATIVE);
1065 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
1067 if (what & INCLUDE_IPV6) {
1068 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6,
1069 NFCT_FILTER_LOGIC_NEGATIVE);
1070 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
1073 ret = nfct_filter_attach(nfct_fd(handle), filter);
1074 if (ret < 0)
1075 panic("Cannot attach filter to handle!\n");
1077 nfct_callback_register(handle, NFCT_T_ALL, collector_cb, NULL);
1079 collector_load_geoip();
1081 flow_list_init(&flow_list);
1083 rcu_register_thread();
1084 while (!sigint)
1085 nfct_catch(handle);
1086 rcu_unregister_thread();
1088 flow_list_destroy(&flow_list);
1090 collector_destroy_geoip();
1092 nfct_filter_destroy(filter);
1093 nfct_close(handle);
1095 pthread_exit(0);
1098 int main(int argc, char **argv)
1100 pthread_t tid;
1101 int ret, c, opt_index, what_cmd = 0;
1103 memset(&geo_country, 0, sizeof(geo_country));
1104 memset(&geo_city, 0, sizeof(geo_city));
1106 while ((c = getopt_long(argc, argv, short_options, long_options,
1107 &opt_index)) != EOF) {
1108 switch (c) {
1109 case '4':
1110 what_cmd |= INCLUDE_IPV4;
1111 break;
1112 case '6':
1113 what_cmd |= INCLUDE_IPV6;
1114 break;
1115 case 'T':
1116 what_cmd |= INCLUDE_TCP;
1117 break;
1118 case 'U':
1119 what_cmd |= INCLUDE_UDP;
1120 break;
1121 case 'D':
1122 what_cmd |= INCLUDE_DCCP;
1123 break;
1124 case 'I':
1125 what_cmd |= INCLUDE_ICMP;
1126 break;
1127 case 'S':
1128 what_cmd |= INCLUDE_SCTP;
1129 break;
1130 case 's':
1131 show_src = 1;
1132 break;
1133 case 'L':
1134 geo_city.path4 = xstrdup(optarg);
1135 break;
1136 case 'K':
1137 geo_country.path4 = xstrdup(optarg);
1138 break;
1139 case 'O':
1140 geo_city.path6 = xstrdup(optarg);
1141 break;
1142 case 'P':
1143 geo_country.path6 = xstrdup(optarg);
1144 break;
1145 case 'h':
1146 help();
1147 break;
1148 case 'v':
1149 version();
1150 break;
1151 case '?':
1152 switch (optopt) {
1153 case 'L':
1154 case 'K':
1155 case 'O':
1156 case 'P':
1157 panic("Option -%c requires an argument!\n",
1158 optopt);
1159 default:
1160 if (isprint(optopt))
1161 whine("Unknown option character "
1162 "`0x%X\'!\n", optopt);
1163 die();
1165 default:
1166 break;
1170 if (what_cmd > 0)
1171 what = what_cmd;
1173 rcu_init();
1175 register_signal(SIGINT, signal_handler);
1176 register_signal(SIGHUP, signal_handler);
1178 ret = pthread_create(&tid, NULL, collector, NULL);
1179 if (ret < 0)
1180 panic("Cannot create phthread!\n");
1182 presenter();
1184 free(geo_country.path4);
1185 free(geo_country.path6);
1187 free(geo_city.path4);
1188 free(geo_city.path6);
1190 return 0;