flowtop: show first name, then pid
[netsniff-ng.git] / src / flowtop.c
blobc865633a4b71984a5941f8289f094a97ee949bfe
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 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 e.g.:\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 return xzmalloc(sizeof(struct flow_entry));
303 static inline void flow_entry_xfree(struct flow_entry *n)
305 xfree(n);
308 static inline void flow_list_init(struct flow_list *fl)
310 fl->head = NULL;
311 spinlock_init(&fl->lock);
314 static void flow_list_new_entry(struct flow_list *fl, struct nf_conntrack *ct)
316 struct flow_entry *n = flow_entry_xalloc();
318 flow_entry_from_ct(n, ct);
319 flow_entry_get_extended(n);
321 rcu_assign_pointer(n->next, fl->head);
322 rcu_assign_pointer(fl->head, n);
325 static struct flow_entry *flow_list_find_id(struct flow_list *fl,
326 uint32_t id)
328 struct flow_entry *n = rcu_dereference(fl->head);
330 while (n != NULL) {
331 if (n->flow_id == id)
332 return n;
334 n = rcu_dereference(n->next);
337 return NULL;
340 static struct flow_entry *flow_list_find_prev_id(struct flow_list *fl,
341 uint32_t id)
343 struct flow_entry *n = rcu_dereference(fl->head), *tmp;
345 if (n->flow_id == id)
346 return NULL;
348 while ((tmp = rcu_dereference(n->next)) != NULL) {
349 if (tmp->flow_id == id)
350 return n;
352 n = tmp;
355 return NULL;
358 static void flow_list_update_entry(struct flow_list *fl,
359 struct nf_conntrack *ct)
361 int do_ext = 0;
362 struct flow_entry *n;
364 n = flow_list_find_id(fl, nfct_get_attr_u32(ct, ATTR_ID));
365 if (n == NULL) {
366 n = flow_entry_xalloc();
367 do_ext = 1;
370 flow_entry_from_ct(n, ct);
371 if (do_ext) {
372 flow_entry_get_extended(n);
374 rcu_assign_pointer(n->next, fl->head);
375 rcu_assign_pointer(fl->head, n);
379 static void flow_list_destroy_entry(struct flow_list *fl,
380 struct nf_conntrack *ct)
382 struct flow_entry *n1, *n2;
383 uint32_t id = nfct_get_attr_u32(ct, ATTR_ID);
385 n1 = flow_list_find_id(fl, id);
386 if (n1) {
387 n2 = flow_list_find_prev_id(fl, id);
388 if (n2) {
389 rcu_assign_pointer(n2->next, n1->next);
390 rcu_assign_pointer(n1->next, NULL);
392 flow_entry_xfree(n1);
393 } else {
394 flow_entry_xfree(fl->head);
396 rcu_assign_pointer(fl->head, NULL);
401 static void flow_list_destroy(struct flow_list *fl)
403 struct flow_entry *n;
405 while (fl->head != NULL) {
406 n = rcu_dereference(fl->head->next);
407 rcu_assign_pointer(fl->head->next, NULL);
409 flow_entry_xfree(fl->head);
410 rcu_assign_pointer(fl->head, n);
413 synchronize_rcu();
414 spinlock_destroy(&fl->lock);
417 static int walk_process(char *process, struct flow_entry *n)
419 int ret;
420 DIR *dir;
421 struct dirent *ent;
422 char path[1024];
424 if (snprintf(path, sizeof(path), "/proc/%s/fd", process) == -1)
425 panic("giant process name! %s\n", process);
427 dir = opendir(path);
428 if (!dir)
429 return 0;
431 while ((ent = readdir(dir))) {
432 struct stat statbuf;
434 if (snprintf(path, sizeof(path), "/proc/%s/fd/%s",
435 process, ent->d_name) < 0)
436 continue;
438 if (stat(path, &statbuf) < 0)
439 continue;
441 if (S_ISSOCK(statbuf.st_mode) && n->inode == statbuf.st_ino) {
442 memset(n->cmdline, 0, sizeof(n->cmdline));
444 snprintf(path, sizeof(path), "/proc/%s/exe", process);
446 ret = readlink(path, n->cmdline,
447 sizeof(n->cmdline) - 1);
448 if (ret < 0)
449 panic("readlink error: %s\n", strerror(errno));
451 n->procnum = atoi(process);
452 return 1;
456 closedir(dir);
457 return 0;
460 static void walk_processes(struct flow_entry *n)
462 int ret;
463 DIR *dir;
464 struct dirent *ent;
466 /* n->inode must be set */
467 if (n->inode <= 0) {
468 memset(n->cmdline, 0, sizeof(n->cmdline));
469 return;
472 dir = opendir("/proc");
473 if (!dir)
474 panic("Cannot open /proc!\n");
476 while ((ent = readdir(dir))) {
477 if (strspn(ent->d_name, "0123456789") == strlen(ent->d_name)) {
478 ret = walk_process(ent->d_name, n);
479 if (ret > 0)
480 break;
484 closedir(dir);
487 static int get_port_inode(uint16_t port, int proto, int is_ip6)
489 int ret = -ENOENT;
490 char path[128], buff[1024];
491 FILE *proc;
493 memset(path, 0, sizeof(path));
494 snprintf(path, sizeof(path), "/proc/net/%s%s",
495 l4proto2str[proto], is_ip6 ? "6" : "");
497 proc = fopen(path, "r");
498 if (!proc)
499 return -EIO;
501 memset(buff, 0, sizeof(buff));
503 while (fgets(buff, sizeof(buff), proc) != NULL) {
504 int inode = 0;
505 unsigned int lport = 0;
507 buff[sizeof(buff) - 1] = 0;
508 if (sscanf(buff, "%*u: %*X:%X %*X:%*X %*X %*X:%*X %*X:%*X "
509 "%*X %*u %*u %u", &lport, &inode) == 2) {
510 if ((uint16_t) lport == port) {
511 ret = inode;
512 break;
516 memset(buff, 0, sizeof(buff));
519 fclose(proc);
520 return ret;
523 #define CP_NFCT(elem, attr, x) \
524 do { n->elem = nfct_get_attr_u##x(ct,(attr)); } while (0)
525 #define CP_NFCT_BUFF(elem, attr) do { \
526 const uint8_t *buff = nfct_get_attr(ct,(attr)); \
527 if (buff != NULL) \
528 memcpy(n->elem, buff, sizeof(n->elem)); \
529 } while (0)
531 static void flow_entry_from_ct(struct flow_entry *n, struct nf_conntrack *ct)
533 CP_NFCT(l3_proto, ATTR_ORIG_L3PROTO, 8);
534 CP_NFCT(l4_proto, ATTR_ORIG_L4PROTO, 8);
535 CP_NFCT(ip4_src_addr, ATTR_ORIG_IPV4_SRC, 32);
536 CP_NFCT(ip4_dst_addr, ATTR_ORIG_IPV4_DST, 32);
537 CP_NFCT(port_src, ATTR_ORIG_PORT_SRC, 16);
538 CP_NFCT(port_dst, ATTR_ORIG_PORT_DST, 16);
539 CP_NFCT(status, ATTR_STATUS, 32);
540 CP_NFCT(tcp_state, ATTR_TCP_STATE, 8);
541 CP_NFCT(tcp_flags, ATTR_TCP_FLAGS_ORIG, 8);
542 CP_NFCT(counter_pkts, ATTR_ORIG_COUNTER_PACKETS, 64);
543 CP_NFCT(counter_bytes, ATTR_ORIG_COUNTER_BYTES, 64);
544 CP_NFCT(timestamp_start, ATTR_TIMESTAMP_START, 64);
545 CP_NFCT(timestamp_stop, ATTR_TIMESTAMP_STOP, 64);
546 CP_NFCT(flow_id, ATTR_ID, 32);
547 CP_NFCT(use, ATTR_USE, 32);
549 CP_NFCT_BUFF(ip6_src_addr, ATTR_ORIG_IPV6_SRC);
550 CP_NFCT_BUFF(ip6_dst_addr, ATTR_ORIG_IPV6_DST);
552 n->port_src = ntohs(n->port_src);
553 n->port_dst = ntohs(n->port_dst);
555 n->ip4_src_addr = ntohl(n->ip4_src_addr);
556 n->ip4_dst_addr = ntohl(n->ip4_dst_addr);
559 enum flow_entry_direction {
560 flow_entry_src,
561 flow_entry_dst,
564 static inline int flow_entry_get_extended_is_dns(struct flow_entry *n)
566 /* We don't want to analyze / display DNS itself, since we
567 * use it to resolve reverse dns.
569 return n->port_src == 53 || n->port_dst == 53;
572 #define SELFLD(dir,src_member,dst_member) \
573 (((dir) == flow_entry_src) ? n->src_member : n->dst_member)
575 static struct sockaddr_in *
576 flow_entry_get_sain4_obj(struct flow_entry *n, enum flow_entry_direction dir,
577 struct sockaddr_in *sa)
579 memset(sa, 0, sizeof(*sa));
580 sa->sin_family = PF_INET;
581 sa->sin_addr.s_addr = htonl(SELFLD(dir, ip4_src_addr, ip4_dst_addr));
583 return sa;
586 static struct sockaddr_in6 *
587 flow_entry_get_sain6_obj(struct flow_entry *n, enum flow_entry_direction dir,
588 struct sockaddr_in6 *sa)
590 memset(sa, 0, sizeof(*sa));
591 sa->sin6_family = PF_INET6;
593 memcpy(&sa->sin6_addr, SELFLD(dir, ip6_src_addr, ip6_dst_addr),
594 sizeof(SELFLD(dir, ip6_src_addr, ip6_dst_addr)));
596 return sa;
599 static void
600 flow_entry_geo_city_lookup_generic(struct flow_entry *n,
601 enum flow_entry_direction dir)
603 GeoIPRecord *gir = NULL;
604 struct sockaddr_in sa4;
605 struct sockaddr_in6 sa6;
606 inline const char *make_na(const char *p) { return p ? : "N/A"; }
607 const char *city = NULL;
609 switch (n->l3_proto) {
610 default:
611 bug();
613 case AF_INET:
614 flow_entry_get_sain4_obj(n, dir, &sa4);
615 gir = GeoIP_record_by_ipnum(geo_city.gi4,
616 ntohl(sa4.sin_addr.s_addr));
617 break;
619 case AF_INET6:
620 flow_entry_get_sain6_obj(n, dir, &sa6);
621 gir = GeoIP_record_by_ipnum_v6(geo_city.gi6, sa6.sin6_addr);
622 break;
625 city = make_na(gir != NULL ? gir->city : city);
627 bug_on(sizeof(n->city_src) != sizeof(n->city_dst));
628 memcpy(SELFLD(dir, city_src, city_dst), city,
629 min(sizeof(n->city_src), strlen(city)));
632 static void
633 flow_entry_geo_country_lookup_generic(struct flow_entry *n,
634 enum flow_entry_direction dir)
636 struct sockaddr_in sa4;
637 struct sockaddr_in6 sa6;
638 inline const char *make_na(const char *p) { return p ? : "N/A"; }
639 const char *country = NULL;
641 switch (n->l3_proto) {
642 default:
643 bug();
645 case AF_INET:
646 flow_entry_get_sain4_obj(n, dir, &sa4);
647 country = GeoIP_country_name_by_ipnum(geo_country.gi4,
648 ntohl(sa4.sin_addr.s_addr));
649 break;
651 case AF_INET6:
652 flow_entry_get_sain6_obj(n, dir, &sa6);
653 country = GeoIP_country_name_by_ipnum_v6(geo_country.gi6,
654 sa6.sin6_addr);
655 break;
658 country = make_na(country);
660 bug_on(sizeof(n->country_src) != sizeof(n->country_dst));
661 memcpy(SELFLD(dir, country_src, country_dst), country,
662 min(sizeof(n->country_src), strlen(country)));
665 static void flow_entry_get_extended_geo(struct flow_entry *n,
666 enum flow_entry_direction dir)
668 flow_entry_geo_city_lookup_generic(n, dir);
669 flow_entry_geo_country_lookup_generic(n, dir);
672 static void flow_entry_get_extended_revdns(struct flow_entry *n,
673 enum flow_entry_direction dir)
675 size_t sa_len;
676 struct sockaddr_in sa4;
677 struct sockaddr_in6 sa6;
678 struct sockaddr *sa;
679 struct hostent *hent;
681 switch (n->l3_proto) {
682 default:
683 bug();
685 case AF_INET:
686 flow_entry_get_sain4_obj(n, dir, &sa4);
687 sa = (struct sockaddr *) &sa4;
688 sa_len = sizeof(sa4);
689 hent = gethostbyaddr(&sa4.sin_addr, sizeof(sa4.sin_addr),
690 AF_INET);
691 break;
693 case AF_INET6:
694 flow_entry_get_sain6_obj(n, dir, &sa6);
695 sa = (struct sockaddr *) &sa6;
696 sa_len = sizeof(sa6);
697 hent = gethostbyaddr(&sa6.sin6_addr, sizeof(sa6.sin6_addr),
698 AF_INET6);
699 break;
702 bug_on(sizeof(n->rev_dns_src) != sizeof(n->rev_dns_dst));
703 getnameinfo(sa, sa_len, SELFLD(dir, rev_dns_src, rev_dns_dst),
704 sizeof(n->rev_dns_src), NULL, 0, NI_NUMERICHOST);
706 if (hent) {
707 memset(n->rev_dns_dst, 0, sizeof(n->rev_dns_dst));
708 memcpy(SELFLD(dir, rev_dns_src, rev_dns_dst),
709 hent->h_name, min(sizeof(n->rev_dns_src),
710 strlen(hent->h_name)));
714 static void flow_entry_get_extended(struct flow_entry *n)
716 if (n->flow_id == 0 || flow_entry_get_extended_is_dns(n))
717 return;
719 flow_entry_get_extended_revdns(n, flow_entry_src);
720 flow_entry_get_extended_geo(n, flow_entry_src);
722 flow_entry_get_extended_revdns(n, flow_entry_dst);
723 flow_entry_get_extended_geo(n, flow_entry_dst);
725 n->inode = get_port_inode(n->port_src, n->l4_proto,
726 n->l3_proto == AF_INET6);
727 if (n->inode > 0)
728 walk_processes(n);
731 static uint16_t presenter_get_port(uint16_t src, uint16_t dst, int tcp)
733 if (src < dst && src < 1024) {
734 return src;
735 } else if (dst < src && dst < 1024) {
736 return dst;
737 } else {
738 const char *tmp1, *tmp2;
739 if (tcp) {
740 tmp1 = lookup_port_tcp(src);
741 tmp2 = lookup_port_tcp(dst);
742 } else {
743 tmp1 = lookup_port_udp(src);
744 tmp2 = lookup_port_udp(dst);
746 if (tmp1 && !tmp2) {
747 return src;
748 } else if (!tmp1 && tmp2) {
749 return dst;
750 } else {
751 if (src < dst)
752 return src;
753 else
754 return dst;
759 static void presenter_screen_init(WINDOW **screen)
761 (*screen) = initscr();
762 noecho();
763 cbreak();
764 keypad(stdscr, TRUE);
765 nodelay(*screen, TRUE);
766 refresh();
767 wrefresh(*screen);
770 static void presenter_screen_do_line(WINDOW *screen, struct flow_entry *n,
771 unsigned int *line)
773 char tmp[128];
774 uint16_t port;
776 mvwprintw(screen, *line, 2, "");
778 /* PID, application name */
779 if (n->procnum > 0) {
780 slprintf(tmp, sizeof(tmp), "%s(%u)", basename(n->cmdline),
781 n->procnum);
783 printw("[");
784 attron(COLOR_PAIR(3));
785 printw("%s", tmp);
786 attroff(COLOR_PAIR(3));
787 printw("]:");
790 /* L3 protocol, L4 protocol, TCP state */
791 printw("%s:%s", l3proto2str[n->l3_proto], l4proto2str[n->l4_proto]);
792 printw("[");
793 attron(COLOR_PAIR(3));
794 printw("%s", tcp_state2str[n->tcp_state]);
795 attroff(COLOR_PAIR(3));
796 printw("]:");
798 /* Guess application port */
799 attron(A_BOLD);
800 if (n->tcp_state != TCP_CONNTRACK_NONE) {
801 port = presenter_get_port(n->port_src, n->port_dst, 1);
802 printw("%s ->", lookup_port_tcp(port));
803 } else {
804 port = presenter_get_port(n->port_src, n->port_dst, 0);
805 printw("%s ->", lookup_port_udp(port));
807 attroff(A_BOLD);
809 #if 0
810 /* Number packets, bytes */
811 printw("(%upkts/%ubytes) ->", n->counter_pkts, n->counter_bytes);
812 #endif
814 /* Show source information: reverse DNS, port, country, city */
815 if (show_src) {
816 attron(COLOR_PAIR(1));
817 mvwprintw(screen, ++(*line), 8, "src: %s", n->rev_dns_src);
818 attroff(COLOR_PAIR(1));
820 printw(":%u (", n->port_src);
822 attron(COLOR_PAIR(4));
823 printw("%s", n->country_src);
824 attroff(COLOR_PAIR(4));
826 printw(", %s) => ", n->city_src);
829 /* Show dest information: reverse DNS, port, country, city */
830 attron(COLOR_PAIR(2));
831 mvwprintw(screen, ++(*line), 8, "dst: %s", n->rev_dns_dst);
832 attroff(COLOR_PAIR(2));
834 printw(":%u (", n->port_dst);
836 attron(COLOR_PAIR(4));
837 printw("%s", n->country_dst);
838 attroff(COLOR_PAIR(4));
840 printw(", %s)", n->city_dst);
843 static void presenter_screen_update(WINDOW *screen, struct flow_list *fl,
844 int skip_lines)
846 int i, maxy;
847 unsigned int line = 3;
848 struct flow_entry *n;
850 curs_set(0);
852 maxy = getmaxy(screen);
854 start_color();
855 init_pair(1, COLOR_RED, COLOR_BLACK);
856 init_pair(2, COLOR_BLUE, COLOR_BLACK);
857 init_pair(3, COLOR_YELLOW, COLOR_BLACK);
858 init_pair(4, COLOR_GREEN, COLOR_BLACK);
860 wclear(screen);
861 clear();
863 mvwprintw(screen, 1, 2, "Kernel netfilter TCP/UDP "
864 "flow statistics, [+%d]", skip_lines);
866 rcu_read_lock();
868 if (rcu_dereference(fl->head) == NULL)
869 mvwprintw(screen, line, 2, "(No active sessions! "
870 "Is netfilter running?)");
872 maxy -= 6;
873 /* Yes, that's lame :-P */
874 for (i = 0; i < sizeof(tcp_states); i++) {
875 n = rcu_dereference(fl->head);
876 while (n && maxy > 0) {
877 if (n->tcp_state != tcp_states[i] ||
878 (i != TCP_CONNTRACK_NONE &&
879 n->tcp_state == TCP_CONNTRACK_NONE) ||
880 /* Filter out DNS */
881 presenter_get_port(n->port_src,
882 n->port_dst, 0) == 53) {
883 n = rcu_dereference(n->next);
884 continue;
886 if (skip_lines > 0) {
887 n = rcu_dereference(n->next);
888 skip_lines--;
889 continue;
892 presenter_screen_do_line(screen, n, &line);
894 line++;
895 maxy -= (2 + 1 * show_src);
896 n = rcu_dereference(n->next);
900 rcu_read_unlock();
902 wrefresh(screen);
903 refresh();
906 static inline void presenter_screen_end(void)
908 endwin();
911 static void presenter(void)
913 int skip_lines = 0;
914 WINDOW *screen = NULL;
916 dissector_init_ethernet(0);
917 presenter_screen_init(&screen);
919 rcu_register_thread();
920 while (!sigint) {
921 switch (getch()) {
922 case 'q':
923 sigint = 1;
924 break;
925 case KEY_UP:
926 case 'u':
927 case 'k':
928 skip_lines--;
929 if (skip_lines < 0)
930 skip_lines = 0;
931 break;
932 case KEY_DOWN:
933 case 'd':
934 case 'j':
935 skip_lines++;
936 if (skip_lines > SCROLL_MAX)
937 skip_lines = SCROLL_MAX;
938 break;
939 default:
940 fflush(stdin);
941 break;
944 presenter_screen_update(screen, &flow_list, skip_lines);
945 usleep(100000);
947 rcu_unregister_thread();
949 presenter_screen_end();
950 dissector_cleanup_ethernet();
953 static int collector_cb(enum nf_conntrack_msg_type type,
954 struct nf_conntrack *ct, void *data)
956 if (sigint)
957 return NFCT_CB_STOP;
959 synchronize_rcu();
960 spinlock_lock(&flow_list.lock);
962 switch (type) {
963 case NFCT_T_NEW:
964 flow_list_new_entry(&flow_list, ct);
965 break;
966 case NFCT_T_UPDATE:
967 flow_list_update_entry(&flow_list, ct);
968 break;
969 case NFCT_T_DESTROY:
970 flow_list_destroy_entry(&flow_list, ct);
971 break;
972 default:
973 break;
976 spinlock_unlock(&flow_list.lock);
978 return NFCT_CB_CONTINUE;
981 static inline GeoIP *collector_geoip_open(const char *path, int type)
983 if (path != NULL)
984 return GeoIP_open(path, GEOIP_MMAP_CACHE);
985 else
986 return GeoIP_open_type(type, GEOIP_MMAP_CACHE);
989 static void collector_load_geoip(void)
991 geo_country.gi4 = collector_geoip_open(geo_country.path4,
992 GEOIP_COUNTRY_EDITION);
993 if (geo_country.gi4 == NULL)
994 panic("Cannot open GeoIP4 country database!\n");
996 geo_country.gi6 = collector_geoip_open(geo_country.path6,
997 GEOIP_COUNTRY_EDITION_V6);
998 if (geo_country.gi6 == NULL)
999 panic("Cannot open GeoIP6 country database!\n");
1001 geo_city.gi4 = collector_geoip_open(geo_city.path4,
1002 GEOIP_CITY_EDITION_REV1);
1003 if (geo_city.gi4 == NULL)
1004 panic("Cannot open GeoIP4 city database!\n");
1006 geo_city.gi6 = collector_geoip_open(geo_city.path6,
1007 GEOIP_CITY_EDITION_REV1_V6);
1008 if (geo_city.gi6 == NULL)
1009 panic("Cannot open GeoIP6 city database!\n");
1011 GeoIP_set_charset(geo_country.gi4, GEOIP_CHARSET_UTF8);
1012 GeoIP_set_charset(geo_country.gi6, GEOIP_CHARSET_UTF8);
1014 GeoIP_set_charset(geo_city.gi4, GEOIP_CHARSET_UTF8);
1015 GeoIP_set_charset(geo_city.gi6, GEOIP_CHARSET_UTF8);
1018 static void collector_destroy_geoip(void)
1020 GeoIP_delete(geo_country.gi4);
1021 GeoIP_delete(geo_country.gi6);
1023 GeoIP_delete(geo_city.gi4);
1024 GeoIP_delete(geo_city.gi6);
1027 static void inline collector_flush(struct nfct_handle *handle, uint8_t family)
1029 nfct_query(handle, NFCT_Q_FLUSH, &family);
1032 static void *collector(void *null)
1034 int ret;
1035 struct nfct_handle *handle;
1036 struct nfct_filter *filter;
1038 handle = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_NEW |
1039 NF_NETLINK_CONNTRACK_UPDATE |
1040 NF_NETLINK_CONNTRACK_DESTROY);
1041 if (!handle)
1042 panic("Cannot create a nfct handle!\n");
1044 collector_flush(handle, AF_INET);
1045 collector_flush(handle, AF_INET6);
1047 filter = nfct_filter_create();
1048 if (!filter)
1049 panic("Cannot create a nfct filter!\n");
1051 if (what & INCLUDE_UDP)
1052 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_UDP);
1053 if (what & INCLUDE_TCP)
1054 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_TCP);
1055 if (what & INCLUDE_DCCP)
1056 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_DCCP);
1057 if (what & INCLUDE_SCTP)
1058 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_SCTP);
1059 if (what & INCLUDE_ICMP && what & INCLUDE_IPV4)
1060 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMP);
1061 if (what & INCLUDE_ICMP && what & INCLUDE_IPV6)
1062 nfct_filter_add_attr_u32(filter, NFCT_FILTER_L4PROTO, IPPROTO_ICMPV6);
1063 if (what & INCLUDE_IPV4) {
1064 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV4,
1065 NFCT_FILTER_LOGIC_NEGATIVE);
1066 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &filter_ipv4);
1068 if (what & INCLUDE_IPV6) {
1069 nfct_filter_set_logic(filter, NFCT_FILTER_SRC_IPV6,
1070 NFCT_FILTER_LOGIC_NEGATIVE);
1071 nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV6, &filter_ipv6);
1074 ret = nfct_filter_attach(nfct_fd(handle), filter);
1075 if (ret < 0)
1076 panic("Cannot attach filter to handle!\n");
1078 nfct_callback_register(handle, NFCT_T_ALL, collector_cb, NULL);
1080 collector_load_geoip();
1082 flow_list_init(&flow_list);
1084 rcu_register_thread();
1085 while (!sigint)
1086 nfct_catch(handle);
1087 rcu_unregister_thread();
1089 flow_list_destroy(&flow_list);
1091 collector_destroy_geoip();
1093 nfct_filter_destroy(filter);
1094 nfct_close(handle);
1096 pthread_exit(0);
1099 int main(int argc, char **argv)
1101 pthread_t tid;
1102 int ret, c, opt_index, what_cmd = 0;
1104 memset(&geo_country, 0, sizeof(geo_country));
1105 memset(&geo_city, 0, sizeof(geo_city));
1107 while ((c = getopt_long(argc, argv, short_options, long_options,
1108 &opt_index)) != EOF) {
1109 switch (c) {
1110 case '4':
1111 what_cmd |= INCLUDE_IPV4;
1112 break;
1113 case '6':
1114 what_cmd |= INCLUDE_IPV6;
1115 break;
1116 case 'T':
1117 what_cmd |= INCLUDE_TCP;
1118 break;
1119 case 'U':
1120 what_cmd |= INCLUDE_UDP;
1121 break;
1122 case 'D':
1123 what_cmd |= INCLUDE_DCCP;
1124 break;
1125 case 'I':
1126 what_cmd |= INCLUDE_ICMP;
1127 break;
1128 case 'S':
1129 what_cmd |= INCLUDE_SCTP;
1130 break;
1131 case 's':
1132 show_src = 1;
1133 break;
1134 case 'L':
1135 geo_city.path4 = xstrdup(optarg);
1136 break;
1137 case 'K':
1138 geo_country.path4 = xstrdup(optarg);
1139 break;
1140 case 'O':
1141 geo_city.path6 = xstrdup(optarg);
1142 break;
1143 case 'P':
1144 geo_country.path6 = xstrdup(optarg);
1145 break;
1146 case 'h':
1147 help();
1148 break;
1149 case 'v':
1150 version();
1151 break;
1152 case '?':
1153 switch (optopt) {
1154 case 'L':
1155 case 'K':
1156 case 'O':
1157 case 'P':
1158 panic("Option -%c requires an argument!\n",
1159 optopt);
1160 default:
1161 if (isprint(optopt))
1162 whine("Unknown option character "
1163 "`0x%X\'!\n", optopt);
1164 die();
1166 default:
1167 break;
1171 if (what_cmd > 0)
1172 what = what_cmd;
1174 rcu_init();
1176 register_signal(SIGINT, signal_handler);
1177 register_signal(SIGHUP, signal_handler);
1179 ret = pthread_create(&tid, NULL, collector, NULL);
1180 if (ret < 0)
1181 panic("Cannot create phthread!\n");
1183 presenter();
1185 free(geo_country.path4);
1186 free(geo_country.path6);
1188 free(geo_city.path4);
1189 free(geo_city.path6);
1191 return 0;