5

I am developing an app in C for Android. I want to add a new tun interface and use the file descriptor to access the device. The way I am doing it is the same as described here: https://backreference.org/2010/03/26/tuntap-interface-tutorial/

However, I am getting Operation not permitted on ioctl() call. My device is rooted, I granted superuser rights to my app, set SELinux policy to permissive. But still, Android does not allow me to access /dev/net/tun. I created it by creating symbolic link from /dev/tun. I also didn't forget to set chmod 666 on /dev/tun. Calling open("/dev/net/tun", O_RDWR | O_NONBLOCK) returns a valid file descriptor, and I set the ifreq struct correctly. It is exactly ioctl() call that returns an error that is Operation not permitted.

Furthermore, if I separate the code and cross-compile it, and then push it to device via adb and run it - everything works. But if I do it as a part of my application, the Operation is not permitted.

Any advise on how to allow this system call inside application? Any tips on why it fails would be also appreciated.

Code:

int create_virtual_nic(char *device) {

  struct ifreq ifr;
  int fd_tunnel = -1;
  int err = -1;

  fd_tunnel = open("/dev/net/tun", O_RDWR | O_NONBLOCK);
  if(fd_tunnel < 0) {
    fprintf(stderr, "Could not open TUN device!\n");
    return fd_tunnel;
  }

  memset(&ifr, 0, sizeof(ifr));

  ifr.ifr_flags = IFF_TUN | IFF_NO_PI;

  if (*device) {
    strncpy(ifr.ifr_name, device, IFNAMSIZ);
  }

  // ERROR IS HERE
  err = ioctl(fd_tunnel, TUNSETIFF, (void*) &ifr);

  if(err < 0 ) {
     close(fd_tunnel);
     perror("ioctl()");
     fprintf(stderr, "Device '%s' taken or not running as root!\n", device);
     exit(EXIT_FAILURE);
  } else {
        fprintf(stdout, "Succesfullt ioctl() on %d\n", err);
  }

  fprintf(stdout, "Created interface '%s'...\n", device);

  return fd_tunnel;
}
pavshr
  • 51
  • 5
  • Did you solve this? My guess is that you were blocked by access controls that are hard coded in the driver. While regular read and write access to the device files is controlled by the standard filesystem level access control rules, drivers sometimes further restrict access to the ioctls, normally by checking for root. – Roger Dahl Aug 15 '20 at 21:27

0 Answers0