Notes about TUN/TAP Interface。内容主要转载自:TUN/TAP Interface

Concept

From the Linux kernel documentation:

TUN/TAP provides packet reception and transmission for user space programs. It can be seen as a simple Point-to-Point or Ethernet device, which, instead of receiving packets from physical media, receives them from user space program and instead of sending packets via physical media writes them to the user space program.

In other words, TUN/TAP interfaces are virtual interfaces that does not have physical devices associated. A user space program can attach to a TUN/TAP interface and handle the traffic sent to the interface.

Difference

There are two types of virtual network interfaces managed by /dev/net/tun:

  • TUN interfaces transport IP packets (layer 3);
  • TAP interfaces transport Ethernet frames (layer 2).

A TUN interface is a virtual IP Point-to-Point interface(L3) and a TAP interface is a virtual Ethernet interface(L2). That means the user program can only read/write IP packets from/to a TUN interface and Ethernet frames from/to a TAP interface.

Use Cases

The typical use case of a TUN interface is IP tunneling. For example, OpenVPN receives packets from a TUN interface such as tun0 and encrypts it before sending to the real ethernet interface eth0. Then the OpenVPN client on the peer receives the packet from eth0 and decrypts it before sending it to tun0. In other words, OpenVPN works as a proxy between tun0 and eth0 and creates a encrypted UDP connection over the internet between two hosts.

The typical use case of a TAP interface is virtual networking. For example, in Linux Bridge Part 1, we’ve seen that when we create a VM in the KVM with bridged network, it creates a TAP interface like vnet0 and adds it to the Linux bridge. In this case, KVM is the userspace program which reads from and writes to the TAP interfaces. When VM0 sends a packet to its eth0, KVM sends it to TAP interface vnet0 so that the bridge will forward it to vnet1. Then KVM receives it and sends it to VM1’s eth0.

Managing TUN/TAP interfaces

ip tuntap can be used to manage TUN/TAP interfaces. For example:

1
2
3
4
5
6
7
$ ip tuntap help
Usage: ip tuntap { add | del | show | list | lst | help } [ dev PHYS_DEV ]
[ mode { tun | tap } ] [ user USER ] [ group GROUP ]
[ one_queue ] [ pi ] [ vnet_hdr ] [ multi_queue ]

Where: USER := { STRING | NUMBER }
GROUP := { STRING | NUMBER }

文章推荐

精读Linux 虚拟网络设备之 TUN/TAP 设备,会收获颇丰。




参考资料:

  1. TUN/TAP Interface
  2. TUN/TAP interface (on Linux)
  3. Linux 虚拟网络设备之 TUN/TAP 设备
  4. kernel document Universal TUN/TAP device driver
  5. Tun/Tap interface tutorial
  6. man netdevice