Linux – How to find out which process keeps tunnel interface(tun) up

linuxnetwork-interfacetext processing

If I create a tun interface with ip tuntap add mode tun command and force it administratively up with ip link set dev tun1 up command, then the interface itself is always "physically" down:

root@A58:~# ip link show dev tun1
46: tun1: <NO-CARRIER,POINTOPOINT,MULTICAST,NOARP,UP> mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT qlen 500
    link/none 
root@A58:~# 

This makes sense as there are no applications connected to this interface. However, I also have tun0 in my system which is "physically" up:

root@A58:~# ip link show dev tun0
45: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN mode DEFAULT qlen 100
    link/none 
root@A58:~# 

Is there a way to find out which process is connected to this tun0 interface? I had no luck with ps -ef | grep tun0 or lsof | grep tun0.

Best Answer

It doesn't looks like the kernel exposes this information. Therefore, short of kernel debugging, I don't think you can know this. The best you can do is list all processes that have tun or tap devices open like this:

lsof /dev/net/tun

So that will narrow it down, but in the case where there are multiple active tun interfaces on the system, it doesn't tell you which process is managing which tunnel.

When a process wants to create a tun interface, it opens /dev/net/tun no matter which tun interface it intends to use. Then, it either lets the kernel dynamically assign a new tun interface name (like tun0, tun1, tun2 etc...) or it sets a chosen name. This is done with an ioctl call with code TUNSETIFF. So unless you get to trace that ioctl call, there isn't really a way to tell what name got assigned.

Related Question