- VLAN в Linux
- Материал из Xgu.ru
- [править] Настройка VLAN в Linux
- [править] Настройка VLAN с помощью средств IPRoute2
- [править] Аппаратная поддержка 802.1q
- [править] Настройка VLAN при загрузке в Debian GNU/Linux
- [править] Настройка VLAN при загрузке в CentOS
- [править] Настройка VLAN при загрузке в Gentoo
- [править] QinQ-инкапсуляция в Linux
- What is vlan tagging in linux
- Contents
- Instant Configuration
- Create the VLAN device
- Add an IP
- Turning down the device
- Removing the device
- Persistent Configuration
- systemd-networkd
- Single interface
- Single interface with multiple VLANs each with its own gateway
- Bonded interface
- netctl
- Setting bridge IP
- Troubleshooting
- udev renames the virtual devices
- VLANs
- Linux VLAN support
- Hardware Support
- Ventana
- Laguna
- OpenWrt VLAN support (swconfig)
- Linux Distributed Switch Architecture
- GW16083 Ethernet Expansion Mezzanine
VLAN в Linux
Материал из Xgu.ru
[править] Настройка VLAN в Linux
Ниже описывает процедура поднятия тегированного интерфейса на Linux-системе. Может применяться, например, в тех случаях, когда нужно маршрутизировать трафик между несколькими VLAN’ами или обеспечить присутствие сервера в нескольких VLAN’ах одновременно.
Необходима поддержка 802.1Q ядром Linux.
Если модуль не найден, необходимо переконфигурировать ядро, включив поддержку модуля, а потом пересобрать модули ядра.
Модуль включается в Network options / 802.1Q VLAN Support.
Говорим, какие VID будем пропускать. Для этого используем программу vconfig (пакет vlan в Debian) В результате будут созданы виртуальные интерфейсы с именами, содержащими VLAN ID.
Следует учесть, что трафик нижележащего интерфейса (eth0, в данном случае) будет отсылаться без тега (untagged в терминологии cisco). Добавление дополнительных вланов никак не скажется на его работе.
Имена интерфейсов могут отличаться (список возможным имён и от чего это зависит см. в man:vconfig).
Далее, назначаем каждому интерфейсу свой IP-адрес.
Если маршрут по умолчанию смотрит в один из VLAN’ов, нужно его задать:
Лучше сразу запретить пересылку трафика между интерфейсами (forwarding). Если пересылку разрешить, весь трафик между VLANами может пересылаться через эту систему. Если для этого она и настраивалась, пересылку разрешайте, но помните, что вы можете ограничить прохождение трафика и регулировать его другим способом.
Для управления прохождением трафика между VLAN’ами можно использовать стандартные механизмы ядра Linux, такие как маршрутизация, iptables и QoS.
Просматривать информацию о VLAN-подыинтерфейсах в Linux можно через /proc:
[править] Настройка VLAN с помощью средств IPRoute2
В последних версиях пакета iproute появились средства, позволяющие управлять влан-интерфейсами.
На формат имени влан-интерфейса не накладывается особых ограничений. Допускается использование символов национального алфавита. При включенной опции reorder-header кадры, проходящие через интерфейс-влан, не содержат тегов. По умолчанию включена. При отключенной опции, в кадрах сохраняется тег. Это нужно учесть, если вы, например, используете фильтры tc типа u32 с указанием смещений. Опция loose-binding отвечает за синхронизацию состояния влан-интерфейса с нижележащим интерфейсом. По-умолчанию, отключена, и при переключении нижележащего интерфейса в состояние down состояние влан-интерфейса так же меняется на down. При включении, состояние влан-интерфейса не зависит от состояния нижележащего интерфейса. Опция gvrp отвечает за то, распространять ли информацию о данном влане по протоколу gvrp. Для поддержки этой опции должна быть поддержка данной возможности со стороны ядра. Опции ingress-qos-map и egress-qos-map задают трансляцию между полем приоритета заголовка 802.1q и приоритетом структуры skb (данное поле используется в системе управления трафиком). Следует учитывать, что поле приоритета влан-заголовка имеет размер 3 бита и может принимать значения от 0 до 7. Размер же поля приоритета структуры skb составляет 32 бита.
Для просмотра информации о влан-интерфейсе в команде ip link show необходимо задать ключ -d[etails].
Для изменения параметров влан-интерфейса используется команда ip link set, с обязательным указанием type vlan.
[править] Аппаратная поддержка 802.1q
Многие сетевые контроллеры производства intel и broadcom имеют аппаратную поддержку 802.1q, которая снижает загрузку ЦПУ. При снятии дампа трафика с нижележащего интерфейса при аппаратной акселерации в дампе не будет упоминаний о тэгах 802.1q, информация о них хранится непосредственно в структурах, ассоциированных с пакетом.
Для управления аппаратной обработкой вланов сетевым адаптером используется утилита ethtool:
[править] Настройка VLAN при загрузке в Debian GNU/Linux
Для того чтобы информация о созданных VLAN’ах сохранилась после перезагрузки, необходимо добавить её в файл /etc/network/interfaces. Например:
[править] Настройка VLAN при загрузке в CentOS
Для того чтобы информация о созданных VLAN’ах сохранилась после перезагрузки, необходимо создать файлы с описанием подинтерфейсов VLAN. Например, для создания подинтерфейса eth0.10 необходимо создать файл /etc/sysconfig/network-scripts/ifcfg-eth0.10, содержимое которого будет похожим на традиционное содержимое файлов network-scripts/ifcfg-*:
Вариант 2, необходимо создать файл /etc/sysconfig/network-scripts/ifcfg-vlan1, содержимое которого будет похожим на традиционное содержимое файлов network-scripts/ifcfg-*:
[править] Настройка VLAN при загрузке в Gentoo
Ниже приведен пример части файла /etc/conf.d/net, отвечающей за настройку VLAN. В данном примере настраивается 2 vlan-интерфейса на интерфейсе eth0, создание и удаление данных интерфейсах происходит в скрипте /etc/init.d/net.eth0:
[править] QinQ-инкапсуляция в Linux
Q-in-Q инкапсуляция позволяет создавать дважды тегированный трафик. Для каждого уровня вложенности создаётся свой собственный интерфейс.
Источник
What is vlan tagging in linux
Virtual LANs give you the ability to sub-divide a LAN. Linux can accept VLAN tagged traffic and presents each VLAN ID as a different network interface (eg: eth0.100 for VLAN ID 100 )
This article explains how to configure a VLAN using iproute2 and systemd-networkd or netctl.
Contents
Instant Configuration
Previously, Arch Linux used the vconfig command to setup VLANs. This command was superseded by the ip command. Make sure you have iproute2 installed.
In the following examples, let us assume the interface is eth0 , the assigned name is eth0.100 and the vlan id is 100 .
Create the VLAN device
Add the VLAN with the following command:
Run ip link to confirm that it has been created.
This interface behaves like a normal interface. All traffic routed to it will go through the master interface (in this example, eth0 ) but with a VLAN tag. Only VLAN-aware devices can accept them if configured correctly, else the traffic is dropped.
Using a name like eth0.100 is just convention and not enforced; you can alternatively use eth0_100 or something descriptive like IPTV . To see the VLAN ID on an interface, in case you used an unconventional name:
The -d flag shows full details of an interface:
Add an IP
Now add an IPv4 address to the just created VLAN link, and activate the link:
Turning down the device
To cleanly shut down the setting before you remove the link, you can do:
Removing the device
Removing a VLAN interface is significantly less convoluted
Persistent Configuration
systemd-networkd
Single interface
Use the following configuration files (Remember that systemd config files are case sensitive!):
You will have to have associated .network files for each .netdev to handle addressing and routing. For example, to set the eno1.100 interface with a static IP and the eno1.200 interface with DHCP (but ignoring the supplied default route), use:
Then enable systemd-networkd.service . See systemd-networkd for details.
Single interface with multiple VLANs each with its own gateway
Each vlan gets its own routing table and a RoutingPolicyRule that specifies which source ip addresses this routing applies to.
Checks
Use ip route list table . E.g.:
Bonded interface
Similar to above, you are just going to stack more of the concepts in place. You will want to ensure that you have got a bond set up in your switch and also make sure its a trunk with tagged vlans corresponding to what you create below. Convention would be to create a bond interface with the name bond0 , however there is a known issue where the bonding module, when loaded, creates a bond device of the name bond0 which systemd then refuses to configure (as systemd tries to respectfully leave alone any device it did not create).
For the purposes of this write up, we are going to use bondname and you can make the choice yourself.
First, we create the bond device:
Now create a .network directive that references the vlans and interface carriers. In this case we will use the convention for a dual port fiber module:
We are using the vlan naming convention here, you can use something else but realize that this is a named reference so you will have to have a corresponding set of files with the same name.
We will now set up the physical network interfaces:
At this time you could reboot, and likely should, because the bonded interface is created at boot time. Restarting systemd-networkd will consume changes from these files typically, but device creation seems to occur at startup.
We will now set up the VLANs. You should be aware that having multiple VLANs can result in a situation where your machine has multiple default routes, so you will need to specify a Destination directive in the network directives to ensure that only one VLAN is being used for a default route. In this case we will use the VLAN with an ID of 10 as our default route.
Now create the associated network directive to set an address:
We will create a similar pair of files for the VLAN with an ID of 20:
And again for the VLAN with an ID of 30:
Note that the Destination on vlan10 is set to 0.0.0.0/0 , which will match all outbound, becoming the default route.
netctl
You can use netctl for this purpose, see the self-explanatory example profiles in <
Setting bridge IP
Sometimes you might want to configure the bridge ip on which docker operates, for example when the default ip clashes with other ip addresses in the network. Docker has a straight forward way of setting the bip (bridge IP) via the /etc/docker/daemon.json . When this file does not exist yet you can create it.
Troubleshooting
udev renames the virtual devices
An annoyance is that udev may try to rename virtual devices as they are added, thus ignoring the name configured for them (in this case eth0.100 ).
For instance, if the following commands are issued:
This could generate the following output:
udev has ignored the configured virtual interface name eth0.100 and autonamed it rename1.
The solution is to edit /etc/udev/rules.d/network_persistent.rules and append DRIVERS==»?*» to the end of the physical interface’s configuration line.
For example, for the interface aa:bb:cc:dd:ee:ff (eth0):
A reboot should mean that VLANs configure correctly with the names assigned to them.
Источник
VLANs
IEEE 802.1Q IEEE 802.1Q is the networking standard that supports Virtual LANs (VLANs) on an Ethernet network (Layer 3 networking).
The advantages of a VLAN are:
- increased switching efficiency
- network segmentation
- security
- trunks
- ability to sub-divide a LAN for security purposes
In order to use VLAN’s you need:
- a switch that supports IEEE 802.1Q
- a NIC (Network Interface Card) that supports 802.1Q (Not all network drivers support VLAN)
- 802.1Q support in the kernel (8021q module, CONFIG_VLAN_8021Q)
VLANs work by applying a tag to each frame (which increases the header size by 4 bytes). The tag contains an ‘ID’ and a ‘prority’. The priority can be used for a quality of service (QoS) scheme known IEEE 802.1p.
Only portions of a network which are VLAN-aware (802.1Q compliant) can include VLAN tags — traffic on other segments (802.1D conformant) will not contain tags. When a frame enters the VLAN-aware portion a tag is added to denote the VLAN info (membership etc).
In general, you add a VLAN tag to a network port (on a managed switch, for example), and that switch port will drop all packets that don’t have the specified VLAN ID, while allowing those with the appropriate VLAN ID to continue on.
Here is an image showcasing a potential use case for VLANs:
Generally speaking, VLAN tagging is done on a switch basis, though you can also use Linux to listen to VLAN tagged packets on interface devices.
Linux VLAN support
The Linux network layer supports VLAN if built with CONFIG_VLAN_8021Q. To create a VLAN you need to slave it off a physical interface port. Note that the physical interface will still accept ‘un-tagged’ traffic, but only traffic matching the VLAN ID will be presented to the virtual interface.
The Linux ip utility from the ip-route2 package allows the manipulation of the network stack on the Layer 3 network layer.
- use ip link add to create VLAN ID 5 slaved off physical interface eth0:
- adds a ‘link’ object to the eth0 nic with a name of eth0.5 (the name can be anything but it is convention to use the
. )
- eth0.1@eth0 is using the IEEE 802.1Q standard with VLAN id 42.
See ip(8) or here for more info
Alternatively the Linux vconfig (which is a bit older and deprecated) can be used as well.
- create VLAN ID 5 slaved off physical interface eth0:
See vconfig(8) for more info
Hardware Support
Many Gateworks products have ethernet MAC’s or switch devices that support VLAN tagging.
Ventana
All on-board NIC’s on Ventana boards support 802.1Q VLAN Tagging:
- Freescale FEC (eth0 on most boards)
- Marvell Sky2 (eth1 on GW54xx/GW53xx)
- Intel i210 (igb driver) (eth0 and eth1 on GW5520 and MAC on GW16083)
The Ventana GW16083 Ethernet Expansion Mezzanine supports VLAN tagging in the OpenWrt BSP via swconfig as well as DSA support.
Laguna
The on-board NIC’s on Laguna boards support 802.1Q VLAN Tagging.
OpenWrt VLAN support (swconfig)
OpenWrt has its own light-weight application and kernel driver that configures ’embedded switches’ and supports per-port management including VLAN configuration. Being light-weight it does not represent each port as a network interface and thus you can not sun higher level protocols such as STP, LLDP, etc on a per-port basis (for that, see #dsa below).
Please see our OpenWrt swconfig page for more details.
Linux Distributed Switch Architecture
The Linux Distributed Switch Architecture (DSA) is a framework for Ethernet Switch chips present on Embedded boards. When supported each external port of the switch is available as a Network Interface Card (NIC) such that higher level protocols can act at the port level.
In other words each physical port on the switch becomes a network interface in Linux and this allows protocols such as STP, LLDP, etc to run at a port level.
GW16083 Ethernet Expansion Mezzanine
The GW16083 Ethernet Expansion Mezzanine has DSA support in the latest Gateworks Yocto and OpenWrt BSPs.
Note that while the MV88E6176 switch can tag/untag frames automatically according to VLAN configuration which does not require the CPU port to be ‘up’, if you need to do any other protocol level networking packets must enter the CPU and thus the cpu port needs to be ‘up’. Typically the GW16083 PCI NIC routing to the CPU interface is the 2nd network interface (eth1).
For example, a GW54xx + GW16083:
- Notice how we use grep -H DRIVER=igb /sys/class/net/*/device/uevent to show which NIC belongs to the Intel I210 on the GW16083. Note that on a GW552x you will see three NIC’s all using igb.
- Notice how until the Intel I210 on the GW16083 is brought up the lan1 — lan6 NIC’s are not present
- The lan numbering matches the silkscreen. Please refer to the following table:
Connector | Silkscreen | DSA Name |
---|---|---|
J7 | Ethernet1 | lan1 |
J8 | Ethernet2 | lan2 |
J9 | Ethernet3 | lan3 |
J10 | Ethernet4 | lan4 |
J3/J4 | Ethernet5 | lan5 |
J2/J4 | Ethernet6 | lan6 |
- Note that on OpenWrt by default the 2nd NIC on a GW552x/GW53xx/GW54xx is configured as the wan interface and brought up with dhcp running on it. If you want to use dhcp you will want to run it on a port interface instead (ie lan1 through lan6)
- On boards with a single on-board NIC (ie GW51xx/GW52xx) you will need to bring eth1 up manually before you can see lan1 — lan6 (or configure it to come up via OpenWrt’s network configuration)
Источник