2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2009, 2010 Daniel Borkmann.
5 * Copyright 2009, 2010 Emmanuel Roullit.
6 * Copyright 2010 Marek Polacek.
7 * Subject to the GPL, version 2.
21 #include <arpa/inet.h>
29 #include <sys/socket.h>
30 #include <sys/ioctl.h>
31 #include <sys/resource.h>
32 #include <sys/epoll.h>
33 #include <sys/syscall.h>
34 #include <asm/unistd.h>
37 #include <linux/socket.h>
38 #include <linux/types.h>
40 #include <linux/if_ether.h>
41 #include <linux/if_packet.h>
42 #include <linux/sockios.h>
43 #include <netinet/tcp.h>
44 #include <netinet/udp.h>
52 #define IOPRIO_CLASS_SHIFT 13
62 ioprio_who_process
= 1,
67 static const char *const to_prio
[] = {
68 "none", "realtime", "best-effort", "idle",
71 static const char *const sock_mem
[] = {
72 "/proc/sys/net/core/rmem_max",
73 "/proc/sys/net/core/rmem_default",
74 "/proc/sys/net/core/wmem_max",
75 "/proc/sys/net/core/wmem_default",
82 if (unlikely(af
!= AF_INET
&& af
!= AF_INET6
)) {
83 whine("Wrong AF socket type! Falling back to AF_INET\n");
87 sock
= socket(af
, SOCK_DGRAM
, 0);
88 if (unlikely(sock
< 0))
89 panic("Creation AF socket failed!\n");
96 int sock
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
97 if (unlikely(sock
< 0))
98 panic("Creation of PF socket failed!\n");
103 void set_sock_prio(int fd
, int prio
)
106 setsockopt(fd
, SOL_SOCKET
, SO_PRIORITY
, &val
, sizeof(val
));
109 void set_udp_cork(int fd
)
112 setsockopt(fd
, IPPROTO_UDP
, UDP_CORK
, &state
, sizeof(state
));
115 void set_udp_uncork(int fd
)
118 setsockopt(fd
, IPPROTO_UDP
, UDP_CORK
, &state
, sizeof(state
));
121 void set_tcp_cork(int fd
)
124 setsockopt(fd
, IPPROTO_TCP
, TCP_CORK
, &state
, sizeof(state
));
127 void set_tcp_uncork(int fd
)
130 setsockopt(fd
, IPPROTO_TCP
, TCP_CORK
, &state
, sizeof(state
));
133 void set_sock_cork(int fd
, int udp
)
141 void set_sock_uncork(int fd
, int udp
)
149 int set_nonblocking(int fd
)
151 int ret
= fcntl(fd
, F_SETFL
, fcntl(fd
, F_GETFD
, 0) | O_NONBLOCK
);
152 if (unlikely(ret
< 0))
153 panic("Cannot fcntl!\n");
158 int set_nonblocking_sloppy(int fd
)
160 return fcntl(fd
, F_SETFL
, fcntl(fd
, F_GETFD
, 0) | O_NONBLOCK
);
163 void set_socket_keepalive(int fd
)
166 setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, &one
, sizeof(one
));
169 void set_tcp_nodelay(int fd
)
172 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, &one
, sizeof(one
));
175 int set_ipv6_only(int fd
)
178 return setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &one
, sizeof(one
));
181 int set_reuseaddr(int fd
)
185 ret
= setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &one
, sizeof (one
));
186 if (unlikely(ret
< 0))
187 panic("Cannot reuse addr!\n");
192 void set_mtu_disc_dont(int fd
)
194 int mtu
= IP_PMTUDISC_DONT
;
195 setsockopt(fd
, SOL_IP
, IP_MTU_DISCOVER
, &mtu
, sizeof(mtu
));
198 void set_epoll_descriptor(int fd_epoll
, int action
, int fd_toadd
, int events
)
201 struct epoll_event ev
;
203 memset(&ev
, 0, sizeof(ev
));
205 ev
.data
.fd
= fd_toadd
;
207 ret
= epoll_ctl(fd_epoll
, action
, fd_toadd
, &ev
);
209 panic("Cannot add socket for epoll!\n");
212 int set_epoll_descriptor2(int fd_epoll
, int action
, int fd_toadd
, int events
)
214 struct epoll_event ev
;
216 memset(&ev
, 0, sizeof(ev
));
218 ev
.data
.fd
= fd_toadd
;
220 return epoll_ctl(fd_epoll
, action
, fd_toadd
, &ev
);
223 u32
wireless_bitrate(const char *ifname
)
225 int sock
, ret
, rate_in_mbit
;
228 sock
= af_socket(AF_INET
);
230 memset(&iwr
, 0, sizeof(iwr
));
231 strlcpy(iwr
.ifr_name
, ifname
, IFNAMSIZ
);
233 ret
= ioctl(sock
, SIOCGIWRATE
, &iwr
);
235 rate_in_mbit
= iwr
.u
.bitrate
.value
/ 1000000;
244 int adjust_dbm_level(int in_dbm
, int dbm_val
)
249 return dbm_val
- 0x100;
252 int get_system_socket_mem(int which
)
256 const char *file
= sock_mem
[which
];
259 fd
= open(file
, O_RDONLY
);
263 ret
= read(fd
, buff
, sizeof(buff
));
271 void set_system_socket_mem(int which
, int val
)
274 const char *file
= sock_mem
[which
];
278 fd
= open(file
, O_WRONLY
);
282 memset(buff
, 0, sizeof(buff
));
283 slprintf(buff
, sizeof(buff
), "%d", val
);
285 ret
= write(fd
, buff
, strlen(buff
));
291 int wireless_sigqual(const char *ifname
, struct iw_statistics
*stats
)
296 sock
= af_socket(AF_INET
);
298 memset(&iwr
, 0, sizeof(iwr
));
299 strlcpy(iwr
.ifr_name
, ifname
, IFNAMSIZ
);
301 iwr
.u
.data
.pointer
= (caddr_t
) stats
;
302 iwr
.u
.data
.length
= sizeof(*stats
);
303 iwr
.u
.data
.flags
= 1;
305 ret
= ioctl(sock
, SIOCGIWSTATS
, &iwr
);
312 int wireless_rangemax_sigqual(const char *ifname
)
314 int ret
, sock
, sigqual
;
316 struct iw_range iwrange
;
318 sock
= af_socket(AF_INET
);
320 memset(&iwrange
, 0, sizeof(iwrange
));
322 memset(&iwr
, 0, sizeof(iwr
));
323 strlcpy(iwr
.ifr_name
, ifname
, IFNAMSIZ
);
325 iwr
.u
.data
.pointer
= (caddr_t
) &iwrange
;
326 iwr
.u
.data
.length
= sizeof(iwrange
);
327 iwr
.u
.data
.flags
= 0;
329 ret
= ioctl(sock
, SIOCGIWRANGE
, &iwr
);
331 sigqual
= iwrange
.max_qual
.qual
;
340 u32
ethtool_bitrate(const char *ifname
)
342 int ret
, sock
, bitrate
;
344 struct ethtool_cmd ecmd
;
346 sock
= af_socket(AF_INET
);
348 memset(&ecmd
, 0, sizeof(ecmd
));
350 memset(&ifr
, 0, sizeof(ifr
));
351 strlcpy(ifr
.ifr_name
, ifname
, IFNAMSIZ
);
353 ecmd
.cmd
= ETHTOOL_GSET
;
354 ifr
.ifr_data
= (char *) &ecmd
;
356 ret
= ioctl(sock
, SIOCETHTOOL
, &ifr
);
362 switch (ecmd
.speed
) {
368 bitrate
= ecmd
.speed
;
380 int ethtool_link(const char *ifname
)
384 struct ethtool_value ecmd
;
386 sock
= af_socket(AF_INET
);
388 memset(&ecmd
, 0, sizeof(ecmd
));
390 memset(&ifr
, 0, sizeof(ifr
));
391 strlcpy(ifr
.ifr_name
, ifname
, IFNAMSIZ
);
393 ecmd
.cmd
= ETHTOOL_GLINK
;
394 ifr
.ifr_data
= (char *) &ecmd
;
396 ret
= ioctl(sock
, SIOCETHTOOL
, &ifr
);
406 int ethtool_drvinf(const char *ifname
, struct ethtool_drvinfo
*drvinf
)
411 sock
= af_socket(AF_INET
);
413 memset(drvinf
, 0, sizeof(*drvinf
));
415 memset(&ifr
, 0, sizeof(ifr
));
416 strlcpy(ifr
.ifr_name
, ifname
, IFNAMSIZ
);
418 drvinf
->cmd
= ETHTOOL_GDRVINFO
;
419 ifr
.ifr_data
= (char *) drvinf
;
421 ret
= ioctl(sock
, SIOCETHTOOL
, &ifr
);
428 u32
device_bitrate(const char *ifname
)
430 u32 speed_c
, speed_w
;
432 speed_c
= ethtool_bitrate(ifname
);
433 speed_w
= wireless_bitrate(ifname
);
435 return (speed_c
== 0 ? speed_w
: speed_c
);
438 int device_ifindex(const char *ifname
)
440 int ret
, sock
, index
;
443 if (!strncmp("any", ifname
, strlen("any")))
446 sock
= af_socket(AF_INET
);
448 memset(&ifr
, 0, sizeof(ifr
));
449 strlcpy(ifr
.ifr_name
, ifname
, IFNAMSIZ
);
451 ret
= ioctl(sock
, SIOCGIFINDEX
, &ifr
);
453 index
= ifr
.ifr_ifindex
;
462 static int __device_address6(const char *ifname
, struct sockaddr_storage
*ss
)
464 int ret
, family
, found
= -EINVAL
;
465 struct ifaddrs
*ifaddr
, *ifa
;
467 ret
= getifaddrs(&ifaddr
);
469 panic("Cannot get device addresses for IPv6!\n");
471 for (ifa
= ifaddr
; ifa
!= NULL
; ifa
= ifa
->ifa_next
) {
472 family
= ifa
->ifa_addr
->sa_family
;
473 if (family
!= AF_INET6
)
475 if (strcmp(ifa
->ifa_name
, ifname
))
478 memcpy(ss
, ifa
->ifa_addr
, sizeof(*ss
));
487 int device_address(const char *ifname
, int af
, struct sockaddr_storage
*ss
)
494 if (!strncmp("any", ifname
, strlen("any")))
497 return __device_address6(ifname
, ss
);
499 sock
= af_socket(af
);
501 memset(&ifr
, 0, sizeof(ifr
));
502 strlcpy(ifr
.ifr_name
, ifname
, IFNAMSIZ
);
504 ifr
.ifr_addr
.sa_family
= af
;
506 ret
= ioctl(sock
, SIOCGIFADDR
, &ifr
);
508 memcpy(ss
, &ifr
.ifr_addr
, sizeof(ifr
.ifr_addr
));
515 int device_mtu(const char *ifname
)
520 sock
= af_socket(AF_INET
);
522 memset(&ifr
, 0, sizeof(ifr
));
523 strlcpy(ifr
.ifr_name
, ifname
, IFNAMSIZ
);
525 ret
= ioctl(sock
, SIOCGIFMTU
, &ifr
);
536 short device_get_flags(const char *ifname
)
538 /* Really, it's short! Look at struct ifreq */
543 sock
= af_socket(AF_INET
);
545 memset(&ifr
, 0, sizeof(ifr
));
546 strlcpy(ifr
.ifr_name
, ifname
, IFNAMSIZ
);
548 ret
= ioctl(sock
, SIOCGIFFLAGS
, &ifr
);
550 flags
= ifr
.ifr_flags
;
559 void device_set_flags(const char *ifname
, const short flags
)
564 sock
= af_socket(AF_INET
);
566 memset(&ifr
, 0, sizeof(ifr
));
567 strlcpy(ifr
.ifr_name
, ifname
, IFNAMSIZ
);
569 ifr
.ifr_flags
= flags
;
571 ret
= ioctl(sock
, SIOCSIFFLAGS
, &ifr
);
573 panic("Cannot set NIC flags!\n");
578 int device_irq_number(const char *ifname
)
581 * Since fetching IRQ numbers from SIOCGIFMAP is deprecated and not
582 * supported anymore, we need to grab them from procfs
590 if (!strncmp("lo", ifname
, strlen("lo")))
593 fp
= fopen("/proc/interrupts", "r");
595 whine("Cannot open /proc/interrupts!\n");
599 memset(buff
, 0, sizeof(buff
));
600 while (fgets(buff
, sizeof(buff
), fp
) != NULL
) {
601 buff
[sizeof(buff
) - 1] = 0;
603 if (strstr(buff
, ifname
) == NULL
)
607 while (*buffp
!= ':')
612 memset(buff
, 0, sizeof(buff
));
620 * Try sysfs as fallback. Probably wireless devices will be found
621 * here. We return silently if it fails ...
623 slprintf(sysname
, sizeof(sysname
), "/sys/class/net/%s/device/irq",
626 fp
= fopen(sysname
, "r");
630 memset(buff
, 0, sizeof(buff
));
631 if(fgets(buff
, sizeof(buff
), fp
) != NULL
) {
632 buff
[sizeof(buff
) - 1] = 0;
641 int device_bind_irq_to_cpu(int irq
, int cpu
)
648 /* Note: first CPU begins with CPU 0 */
649 if (irq
< 0 || cpu
< 0)
652 memset(file
, 0, sizeof(file
));
653 memset(buff
, 0, sizeof(buff
));
655 /* smp_affinity starts counting with CPU 1, 2, ... */
657 sprintf(file
, "/proc/irq/%d/smp_affinity", irq
);
659 fp
= fopen(file
, "w");
661 whine("Cannot open file %s!\n", file
);
665 sprintf(buff
, "%d", cpu
);
666 ret
= fwrite(buff
, sizeof(buff
), 1, fp
);
669 return (ret
> 0 ? 0 : ret
);
672 void sock_print_net_stats(int sock
, unsigned long skipped
)
675 struct tpacket_stats kstats
;
677 socklen_t slen
= sizeof(kstats
);
679 memset(&kstats
, 0, sizeof(kstats
));
681 ret
= getsockopt(sock
, SOL_PACKET
, PACKET_STATISTICS
, &kstats
, &slen
);
683 uint64_t packets
= kstats
.tp_packets
;
684 uint64_t drops
= kstats
.tp_drops
;
686 printf("\r%12ld frames incoming\n", packets
);
687 printf("\r%12ld frames passed filter\n",
688 packets
- drops
- skipped
);
689 printf("\r%12ld frames failed filter (out of space)\n",
691 if (kstats
.tp_packets
> 0)
692 printf("\r%12.4f%\% frame droprate\n",
693 1.f
* drops
/ packets
* 100.f
);
697 void register_signal(int signal
, void (*handler
)(int))
700 struct sigaction saction
;
702 sigfillset(&block_mask
);
704 saction
.sa_handler
= handler
;
705 saction
.sa_mask
= block_mask
;
706 saction
.sa_flags
= SA_RESTART
;
707 sigaction(signal
, &saction
, NULL
);
710 void register_signal_f(int signal
, void (*handler
)(int), int flags
)
713 struct sigaction saction
;
715 sigfillset(&block_mask
);
717 saction
.sa_handler
= handler
;
718 saction
.sa_mask
= block_mask
;
719 saction
.sa_flags
= flags
;
720 sigaction(signal
, &saction
, NULL
);
723 int get_tty_size(void)
726 struct ttysize ts
= {0};
727 return (ioctl(0, TIOCGSIZE
, &ts
) == 0 ?
728 ts
.ts_cols
: DEFAULT_TTY_SIZE
);
729 #elif defined(TIOCGWINSZ)
731 return (ioctl(0, TIOCGWINSZ
, &ts
) == 0 ?
732 ts
.ws_col
: DEFAULT_TTY_SIZE
);
734 return DEFAULT_TTY_SIZE
;
738 short enter_promiscuous_mode(char *ifname
)
742 if (!strncmp("any", ifname
, strlen("any")))
745 ifflags
= device_get_flags(ifname
);
746 device_set_flags(ifname
, ifflags
| IFF_PROMISC
);
751 void leave_promiscuous_mode(char *ifname
, short oldflags
)
753 if (!strncmp("any", ifname
, strlen("any")))
756 device_set_flags(ifname
, oldflags
);
759 int device_up(char *ifname
)
763 if (!strncmp("any", ifname
, strlen("any")))
766 return (device_get_flags(ifname
) & IFF_UP
) == IFF_UP
;
769 int device_running(char *ifname
)
773 if (!strncmp("any", ifname
, strlen("any")))
776 return (device_get_flags(ifname
) & IFF_RUNNING
) == IFF_RUNNING
;
779 int device_up_and_running(char *ifname
)
783 if (!strncmp("any", ifname
, strlen("any")))
786 return (device_get_flags(ifname
) & (IFF_UP
| IFF_RUNNING
)) ==
787 (IFF_UP
| IFF_RUNNING
);
790 int poll_error_maybe_die(int sock
, struct pollfd
*pfd
)
792 if ((pfd
->revents
& (POLLHUP
| POLLRDHUP
| POLLERR
| POLLNVAL
)) == 0)
793 return POLL_NEXT_PKT
;
794 if (pfd
->revents
& (POLLHUP
| POLLRDHUP
))
795 panic("Hangup on socket occured!\n");
796 if (pfd
->revents
& POLLERR
) {
800 if (recv(sock
, &tmp
, sizeof(tmp
), MSG_PEEK
) >= 0)
801 return POLL_NEXT_PKT
;
802 if (errno
== ENETDOWN
)
803 panic("Interface went down!\n");
805 return POLL_MOVE_OUT
;
807 if (pfd
->revents
& POLLNVAL
) {
808 whine("Invalid polling request on socket!\n");
810 return POLL_MOVE_OUT
;
813 return POLL_NEXT_PKT
;
816 static inline char *next_token(char *q
, int sep
)
821 * glibc defines this as a macro and gcc throws a false
822 * positive ``logical ‘&&’ with non-zero constant will
823 * always evaluate as true'' in older versions. See:
824 * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=36513
831 int set_cpu_affinity(char *str
, int inverted
)
835 cpu_set_t cpu_bitmask
;
839 cpus
= get_number_cpus();
841 CPU_ZERO(&cpu_bitmask
);
843 for (i
= 0; inverted
&& i
< cpus
; ++i
)
844 CPU_SET(i
, &cpu_bitmask
);
846 while (p
= q
, q
= next_token(q
, ','), p
) {
847 unsigned int a
; /* Beginning of range */
848 unsigned int b
; /* End of range */
849 unsigned int s
; /* Stride */
852 if (sscanf(p
, "%u", &a
) < 1)
858 c1
= next_token(p
, '-');
859 c2
= next_token(p
, ',');
861 if (c1
!= NULL
&& (c2
== NULL
|| c1
< c2
)) {
862 if (sscanf(c1
, "%u", &b
) < 1)
865 c1
= next_token(c1
, ':');
867 if (c1
!= NULL
&& (c2
== NULL
|| c1
< c2
))
868 if (sscanf(c1
, "%u", &s
) < 1)
877 CPU_CLR(a
, &cpu_bitmask
);
879 CPU_SET(a
, &cpu_bitmask
);
884 ret
= sched_setaffinity(getpid(), sizeof(cpu_bitmask
),
887 panic("Can't set this cpu affinity!\n");
892 int set_proc_prio(int priority
)
895 * setpriority() is clever, even if you put a nice value which
896 * is out of range it corrects it to the closest valid nice value
898 int ret
= setpriority(PRIO_PROCESS
, getpid(), priority
);
900 panic("Can't set nice val to %i!\n", priority
);
905 int set_sched_status(int policy
, int priority
)
907 int ret
, min_prio
, max_prio
;
908 struct sched_param sp
;
910 max_prio
= sched_get_priority_max(policy
);
911 min_prio
= sched_get_priority_min(policy
);
913 if (max_prio
== -1 || min_prio
== -1)
914 whine("Cannot determine scheduler prio limits!\n");
915 else if (priority
< min_prio
)
917 else if (priority
> max_prio
)
920 memset(&sp
, 0, sizeof(sp
));
921 sp
.sched_priority
= priority
;
923 ret
= sched_setscheduler(getpid(), policy
, &sp
);
925 whine("Cannot set scheduler policy!\n");
929 ret
= sched_setparam(getpid(), &sp
);
931 whine("Cannot set scheduler prio!\n");
938 static inline int ioprio_set(int which
, int who
, int ioprio
)
940 return syscall(SYS_ioprio_set
, which
, who
, ioprio
);
943 static inline int ioprio_get(int which
, int who
)
945 return syscall(SYS_ioprio_get
, which
, who
);
948 static void ioprio_setpid(pid_t pid
, int ioprio
, int ioclass
)
950 int ret
= ioprio_set(ioprio_who_process
, pid
,
951 ioprio
| ioclass
<< IOPRIO_CLASS_SHIFT
);
953 panic("Failed to set io prio for pid!\n");
956 void ioprio_print(void)
958 int ioprio
= ioprio_get(ioprio_who_process
, getpid());
960 panic("Failed to fetch io prio for pid!\n");
962 int ioclass
= ioprio
>> IOPRIO_CLASS_SHIFT
;
963 if (ioclass
!= ioprio_class_idle
) {
965 printf("%s: prio %d\n", to_prio
[ioclass
], ioprio
);
967 printf("%s\n", to_prio
[ioclass
]);
971 void set_ioprio_rt(void)
973 ioprio_setpid(getpid(), 4, ioprio_class_rt
);
976 void set_ioprio_be(void)
978 ioprio_setpid(getpid(), 4, ioprio_class_be
);
981 int set_timeout(struct timeval
*timeval
, unsigned int msec
)
987 timeval
->tv_usec
= 0;
990 timeval
->tv_usec
= msec
* 1000;
994 timeval
->tv_sec
= (long) (msec
/ 1000);
995 timeval
->tv_usec
= (long) ((msec
- (timeval
->tv_sec
* 1000)) * 1000);
1000 size_t strlcpy(char *dest
, const char *src
, size_t size
)
1002 size_t ret
= strlen(src
);
1005 size_t len
= (ret
>= size
) ? size
- 1 : ret
;
1007 memcpy(dest
, src
, len
);
1014 int slprintf(char *dst
, size_t size
, const char *fmt
, ...)
1021 ret
= vsnprintf(dst
, size
, fmt
, ap
);
1022 dst
[size
- 1] = '\0';
1029 noinline
void *xmemset(void *s
, int c
, size_t n
)
1034 for (i
= 0; i
< n
; ++i
)
1035 ptr
[i
] = (uint8_t) c
;
1040 char *getuint(char *in
, uint32_t *out
)
1043 char *endptr
= NULL
;
1045 while (*in
&& (isdigit(*in
) || isxdigit(*in
) || *in
== 'x'))
1048 panic("Syntax error!\n");
1052 *out
= strtoul(pt
, &endptr
, 0);
1053 if ((endptr
!= NULL
&& *endptr
!= '\0') || errno
!= 0) {
1054 panic("Syntax error!\n");
1061 char *strtrim_right(register char *p
, register char c
)
1079 char *strtrim_left(register char *p
, register char c
)
1084 while (*p
&& len
--) {