On Mon, Sep 18, 2017 at 8:47 PM, Jason A. Donenfeld <ja...@zx2c4.com> wrote: > The best I've come up with is, in a sleep loop, writing to the tun > device's fd something with a NULL or invalid payload. If the interface > is down, the kernel returns -EIO. If the interface is up, the kernel > returns -EINVAL. This seems to be a reliable distinguisher, but is a > pretty insane way of doing it. And sleep loops are somewhat different > from events too.
Specifically, I'm referring to the horrific hack exemplified in the attached .c file, in case anybody is curious about the details of what I'd rather not use.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/syscall.h> #include <linux/if.h> #include <linux/if_tun.h> int main(int argc, char *argv[]) { /* If IFF_NO_PI is specified, this still sort of works but it * bumps the device error counters, which we don't want, so * it's best not to use this trick with IFF_NO_PI. */ struct ifreq ifr = { .ifr_flags = IFF_TUN }; int tun, sock, ret; tun = open("/dev/net/tun", O_RDWR); if (tun < 0) { perror("[-] open(/dev/net/tun)"); return 1; } sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { perror("[-] socket(AF_INET, SOCK_DGRAM)"); return 1; } ret = ioctl(tun, TUNSETIFF, &ifr); if (ret < 0) { perror("[-] ioctl(TUNSETIFF)"); return 1; } if (write(tun, NULL, 0) >= 0 || errno != EIO) perror("[-] write(if:down, NULL, 0) did not return -EIO"); else fprintf(stderr, "[+] write(if:down, NULL, 0) returned -EIO: test successful\n"); ifr.ifr_flags = IFF_UP; ret = ioctl(sock, SIOCSIFFLAGS, &ifr); if (ret < 0) { perror("[-] ioctl(SIOCSIFFLAGS)"); return 1; } if (write(tun, NULL, 0) >= 0 || errno != EINVAL) perror("[-] write(if:up, NULL, 0) did not return -EINVAL"); else fprintf(stderr, "[+] write(if:up, NULL, 0) returned -EINVAL: test successful\n"); return 0; }