Linux create tun device

Виртуальный сетевой интерфейс в linux. TAP vs TUN

Читатели, не нуждающиеся в теоретическом изложении концепции виртуальных сетевый интерфейсов Linux, могут сразу перейти к настройке по ссылкам:

Создавать сетевые интерфейсы в linux нам позволяют различные модули ядра. Но там, где для реальных железных сетевых карт эти модули ядра, или как их еще называют — драйверы, обеспечивают прием данных от стека TCP/IP и их формирование уже в виде электрического сигнала на сетевой карте, драйверы виртуальных сетевых интерфейсов (loopback) могут лишь, приняв эти данные, отдать их какому-нибудь приложению для дальнейшей обработки. Такая функциональность может быть востребована, если на вашем сервере установлены программы, использующие стек TCP/IP для обмена данными и, понятно, не нуждающиеся в выводе этих данных в реальную сеть. Пример: веб-сайт на drupal связывается с базой данных, установленной на этом же сервере:

Другим распростаренным примером использования виртуальных сетевых интерфейсов (loopback) в linux может быть их использование для целей построения виртуальных частных сетей — VPN. Вы наверняка слышали о таких технологиях как OpenVPN, GRE, WireGuard и т.д. Каждый из этих демонов создает виртуальный сетевой интерфейс который служит для прозрачной маршрутизации данных между узлами, находящимися на удалении друг от друга и не имеющих возможности прямого взаимодействия. Рассмотрим общую сетевую топологию на примере OpenVPN:

От используемого драйвера зависит тип интерфейса, его скорость, допустимый размер MTU и т. д. Совсем даже не обязательно, что загружать драйвер в ядро вам придется самостоятельно. Скорее всего, создавая интерфейс нужного типа, система сама подберет и загрузит требуемый драйвер. Вам лишь останется сконфигурировать уже работающий loopback интерфейс. В данной статье мы рассмотрим 3 возможных на конец 2016 года типа виртуальных интерфейсов в linux: tun, tap и dummy. Отличие интерфейсов tun и tap заключается в том, что tap старается больше походить на реальный сетевой интерфейс, а именно он позволяет себе принимать и отправлять ARP запросы, обладает MAC адресом и может являться одним из интерфейсов сетевого моста, так как он обладает полной поддержкой ethernet — протокола канального уровня (уровень 2). Интерфейс tun этой поддержки лишен, поэтому он может принимать и отправлять только IP пакеты и никак не ethernet кадры. Он не обладает MAC-адресом и не может быть добавлен в бридж. Зато он более легкий и быстрый за счет отсутствия дополнительной инкапсуляции и прекрасно подходит для тестирования сетевого стека или построения виртуальных частных сетей (VPN). Виртуальный интерфейс типа dummy очень похож на tap, разница лишь в том, что он реализуется другим модулем ядра.

Создаем виртуальный интерфейс в linux вручную

Создавать и удалять интерфейсы, назначать IP и MAC адреса, изменять MTU и многое другое нам помогает утилита ip. Пользоваться ip удобно и легко, но помните, что произведенные изменения будут потеряны после перезагрузки компьютера. Используйте ip в целях тестирования.

Создаем интерфейс типа tun

ip tuntap add dev tun0 mode tun
ip address add 192.168.99.1/30 dev tun0
ip address show tun0
2: tun0:

mtu 1500 qdisc noop state DOWN group default qlen 500
link/none
inet 192.168.99.1/30 scope global tun0
valid_lft forever preferred_lft forever

Читайте также:  Как изменить букву диска с установленной windows

Как видим у нас теперь есть виртуальный интерфейс с именем «tun0», у него есть IP-адрес, и ни слова о MAC-адресе — всё, как мы и рассчитывали. Его уже можно пинговать, и на нем уже можно запускать слушающие сервисы. Но что будет, если мы попытаемся добавить этот интерфейс в бридж?

ip link set dev tun0 master br0
RTNETLINK answers: Invalid argument

Команда ip логичным образом выдала ошибку — нет никакого смысла добавлять в бридж интерфейс, не обладающий поддержкой ethernet.

Создаем интерфейс типа tap

ip tuntap add dev tap0 mode tap
ip address add 192.168.99.5/30 dev tap0
ip address show tap0
3: tap0:
mtu 1500 qdisc noop state DOWN group default qlen 1000
link/ether d6:1c:67:cd:6f:80 brd ff:ff:ff:ff:ff:ff
inet 192.168.99.5/30 scope global tap0
valid_lft forever preferred_lft forever

У нас теперь появился новый виртуальный интерфейс с именем «tap0», у него есть как IP-адрес, так и MAC-адреса. Его также можно пинговать, и на нем также можно запускать слушающие сервисы. Команда, добавляющая интерфейс в бридж уже не выдаст ошибку, потому что это интерфейс, обладающий поддержкой ethernet:

ip link set dev tap0 master br0

Создаем интерфейс типа dummy

ip link add dev dum0 type dummy
ip address add 192.168.99.9/30 dev dum0
ip address show dum0
4: dum0:
mtu 1500 qdisc noop master br0 state DOWN group default qlen 1000
link/ether 1a:37:3b:0f:da:be brd ff:ff:ff:ff:ff:ff
inet 192.168.99.9/30 scope global dum0
valid_lft forever preferred_lft forever

Вы наверняка заметили, что команда для добавления интерфейса изменилась. Ничего необычного. Так написана утилита «ip». Ну и конечно, виртуальный интерфейс типа dummy можно легко добавить в бридж:

ip link set dev dum0 master br0

Создаем виртуальный интерфейс в linux с помощью systemd-networkd

В systemd-networkd за создание интерфейсов отвечают одни конфигурационные файлы, имеющие суффикс «.netdev», а за их настройку другие, имеющие суффикс «.network». Соответственно нам понадобиться в /etc/systemd/network создать по паре конфигурационных файлов для каждого из исследуемых типов интерфейсов

Создаем интерфейс типа tun

Создадим соответственно файлы tun0.netdev с содержимым:

[NetDev]
Name=tun0
Kind=tun

Создаем интерфейс типа tap

Создадим соответственно файлы tap0.netdev с содержимым:

[NetDev]
Name=tap0
Kind=tap

Создаем интерфейс типа dummy

Создадим соответственно файлы dum0.netdev с содержимым:

[NetDev]
Name=dum0
Kind=dummy

Стоит отметить, что если вы планируете маршрутизировать траффик через виртуальные интерфейсы ( а, используя их для цели создания виртуальных частных сетей (VPN), вы точно этого хотите), то в конфигурационный файл в секии «Network» следует добавить диррективу «IPForward=yes».

Источник

Creating tap/tun devices with IP tuntap and tunctl as detailed in Linux network tools

This article was first published in my public number.CloudDeveloper(ID: cloud_dev)Focus on dry goods sharing. There are a lot of books and videos in the number. Backstage reply「1024」You can get it. Welcome your attention. Two-dimensional code can be scanned at the end.

In the previous article, we have introduced the basic principles of tap/tun, and this article will show you how to use tools. tunctl and ip tuntap To create and use tap/tun devices.

tunctl

install

First of all centos Installation in Environment tunctl 。

ubuntu yes apt-get install uml-utilities 。

man tunctl See tunctl The manual is used as follows:

  • – The u parameter specifies the user name, indicating that the interface is only controlled by the user, and that what happens to the interface does not affect the interface of the system.
  • – G Specifies a set of users
  • – t specifies the tap / Tun device name to create.
  • – B Simple Print Created Interface Name
  • – n Create Tun devices
  • – P creates a tap device, which is created by default
  • – F tun-clone-device specifies the file name corresponding to the Tun device by default /dev/net/tun Some systems are /dev/misc/net/tun 。
  • – D interfacename deletes the specified interface
Читайте также:  Как полностью удалить matlab windows

Common usage:

Create tap interface by default:

The above is equivalent to tunctl -p

For users user Create a tap interface:

Create Tun interface:

Configure IP for the interface and enable:

Add routing to the interface:

ip tuntap

install

Command line input ip help See ip Is the command supported? tuntap Tools, if supported, will be displayed tuntap Options:

Upgrade or download the latest if not supported iproute2 Toolkit, or use the one described above tunctl Tools.

input ip tuntap help View the Detailed Use Commands:

Common usage:

Create tap/tun devices:

Delete tap/tun devices:

PS: user and group Parameters and tunctl The – U and – G parameters are the same.

We recommend using the above two tools. ip tuntap One is because iproute2 More complete updates have gradually replaced some of the older tools. Another reason is that tunctl In some Debian Class is not fully supported on the system.

summary

tunctl and ip tuntap Common usage.

More recommended ip tuntap Tools.

My Public NumberCloudDeveloper(ID: cloud_dev)There are a lot of books and videos in the number. Backstage reply「1024」You can get it. The content you share includes but is not limited to cloud computing virtualization, container, OpenStack, K8S, fog computing, network, tools, SDN, OVS, DPDK, Linux, Go, Python, C/C++ programming technology and so on. Welcome your attention.

Источник

Universal TUN/TAP device driverВ¶

1. DescriptionВ¶

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 order to use the driver a program has to open /dev/net/tun and issue a corresponding ioctl() to register a network device with the kernel. A network device will appear as tunXX or tapXX, depending on the options chosen. When the program closes the file descriptor, the network device and all corresponding routes will disappear.

Depending on the type of device chosen the userspace program has to read/write IP packets (with tun) or ethernet frames (with tap). Which one is being used depends on the flags given with the ioctl().

The package from http://vtun.sourceforge.net/tun contains two simple examples for how to use tun and tap devices. Both programs work like a bridge between two network interfaces. br_select.c — bridge based on select system call. br_sigio.c — bridge based on async io and SIGIO signal. However, the best example is VTun http://vtun.sourceforge.net :))

2. ConfigurationВ¶

Create device node:

There’s no harm in allowing the device to be accessible by non-root users, since CAP_NET_ADMIN is required for creating network devices or for connecting to network devices which aren’t owned by the user in question. If you want to create persistent devices and give ownership of them to unprivileged users, then you need the /dev/net/tun device to be usable by those users.

Driver module autoloading

Make sure that “Kernel module loader” — module auto-loading support is enabled in your kernel. The kernel should load it on first access.

insert the module by hand:

If you do it the latter way, you have to load the module every time you need it, if you do it the other way it will be automatically loaded when /dev/net/tun is being opened.

Читайте также:  Unary operator expected linux

3. Program interfaceВ¶

3.1 Network device allocationВ¶

char *dev should be the name of the device with a format string (e.g. “tun%d”), but (as far as I can see) this can be any valid network device name. Note that the character pointer becomes overwritten with the real device name (e.g. “tun0”):

3.2 Frame formatВ¶

If flag IFF_NO_PI is not set each frame format is:

3.3 Multiqueue tuntap interfaceВ¶

From version 3.8, Linux supports multiqueue tuntap which can uses multiple file descriptors (queues) to parallelize packets sending or receiving. The device allocation is the same as before, and if user wants to create multiple queues, TUNSETIFF with the same device name must be called many times with IFF_MULTI_QUEUE flag.

char *dev should be the name of the device, queues is the number of queues to be created, fds is used to store and return the file descriptors (queues) created to the caller. Each file descriptor were served as the interface of a queue which could be accessed by userspace.

A new ioctl(TUNSETQUEUE) were introduced to enable or disable a queue. When calling it with IFF_DETACH_QUEUE flag, the queue were disabled. And when calling it with IFF_ATTACH_QUEUE flag, the queue were enabled. The queue were enabled by default after it was created through TUNSETIFF.

fd is the file descriptor (queue) that we want to enable or disable, when enable is true we enable it, otherwise we disable it:

Universal TUN/TAP device driver Frequently Asked QuestionВ¶

What platforms are supported by TUN/TAP driver ?

Currently driver has been written for 3 Unices:

Linux kernels 2.2.x, 2.4.x

FreeBSD 3.x, 4.x, 5.x

Solaris 2.6, 7.0, 8.0

What is TUN/TAP driver used for?

As mentioned above, main purpose of TUN/TAP driver is tunneling. It is used by VTun (http://vtun.sourceforge.net).

Another interesting application using TUN/TAP is pipsecd (http://perso.enst.fr/

beyssac/pipsec/), a userspace IPSec implementation that can use complete kernel routing (unlike FreeS/WAN).

How does Virtual network device actually work ?

Virtual network device can be viewed as a simple Point-to-Point or Ethernet device, which instead of receiving packets from a physical media, receives them from user space program and instead of sending packets via physical media sends them to the user space program.

Let’s say that you configured IPv6 on the tap0, then whenever the kernel sends an IPv6 packet to tap0, it is passed to the application (VTun for example). The application encrypts, compresses and sends it to the other side over TCP or UDP. The application on the other side decompresses and decrypts the data received and writes the packet to the TAP device, the kernel handles the packet like it came from real physical device.

What is the difference between TUN driver and TAP driver?

TUN works with IP frames. TAP works with Ethernet frames.

This means that you have to read/write IP packets when you are using tun and ethernet frames when using tap.

What is the difference between BPF and TUN/TAP driver?

BPF is an advanced packet filter. It can be attached to existing network interface. It does not provide a virtual network interface. A TUN/TAP driver does provide a virtual network interface and it is possible to attach BPF to this interface.

Does TAP driver support kernel Ethernet bridging?

Yes. Linux and FreeBSD drivers support Ethernet bridging.

Источник

Оцените статью