- Коммутатор (Switch)
- Настройка UCI, swconfig
- Предположим
- Настройка
- Коммутатор
- VLAN: настройка коммутатора
- VLAN: interface/network config
- Extending the router ports with a managed switch with VLANs
- Prerequired knowledge
- Explanation of the need
- Configuring a managed switch with VLANs
- Notes
- Configuration
- Configuring an OpenWrt router
- With programmable switch
- Without programmable switch
- Conclusion
- Practical applications for productive work
- How to configure the managed switch with VLAN allowed
- Reserving and grouping ports in rows or ‘nibbles’
- Assigning VLANS
- Example configuration
- Switch documentation
- UCI config, swconfig style
- Known problems
- Assumptions
- The configuration
- The Switch
- VLAN: switch config
- VLAN: interface/network config
- Examples
- Example on the asus wl500gp v2 , openwrt 10.03, every physical port
- Example vmware linux guest, openwrt x86 generic 12.09 combined, 2virtualized intel e1000
- Собираем свой OpenWRT на роутер Tp-Link TL-WR741ND v.4.25 c vlan, openvpn, ротацией провайдеров и блэкджеком
- 1) Подготовка устройства
- 2) Сбор прошивки
- 3) Настройка vlan:
- 4) mwan3 или крутая выручалочка админа
- 5) Офисная дружба или openvpn
- Заключение:
Коммутатор (Switch)
: Эта страница предполагает что вы знаете “что это ? ” и “зачем это надо?”.
Если вы хотите изменить настройки подключения портов, нужно настроить коммутатор вашего роутера(читаем network.interfaces)
Настройка UCI, swconfig
Предположим
Настройка
Коммутатор
В файле /etc/config/network
VLAN: настройка коммутатора
В файле /etc/config/network
Заметки
В документе, который описывает стандарт 801.2q, говорится, что значения VID 0 и 4095 не могут использоваться для теггированного трафика, так как эти значения зарезервированы: VID 0 ‘родной’ vlan по умолчанию — оставляя диапазон из 4094 доступных значений, хотя VID 1 обычно зарезервирован для управления сетью (например, как у Dell 2708). Это означает, что vlan0 можно использовать как VLAN внутри или между устройствами, но им нельзя тегировать пакеты.
The config sections
VLAN: interface/network config
Конечно же, если у вас на eth0 лишь свитч на пять портов (и никаких других интерфейсов), вы можете сделать интерфейс wan в eth0.1 и lan eth0.0 соответственно совпадающей с switch , switch_vlan и switch_port разделами.
- Last modified: 2018/02/17 18:16
- by 174.255.195.53
Self-registration in the wiki has been disabled.
If you want to contribute to the OpenWrt wiki, please post HERE in the forum or ask on IRC for access.
Except where otherwise noted, content on this wiki is licensed under the following license:
CC Attribution-Share Alike 4.0 International
Источник
Extending the router ports with a managed switch with VLANs
Prerequired knowledge
See Switch documentation and Network documentation.
This article may contain network configuration that is version dependent post 2021-06
More Information
Explanation of the need
You have a powerful machine running OpenWrt. Powerful here means: a device able to process the amount of network packets created by your activities by a big margin. Like you create a flow of 50 Mbit and your device is able to process until 800 Mbit.
You can extend the Ethernet ports of the device using a managed switch (and it means that you have a bit of money/resources and you are in a homeoffice or small office scenario).
Configuring a managed switch with VLANs
The technology that enables an OpenWrt based device to be extended in terms of ports is VLAN .
Notes
A tagged port, with VID Y, accepts only packets tagged with the VID Y in input, while let packets tagged with VID Y going out to the port. Note that one port could be untagged only once, while can be tagged with several VID.
With a brief schema you have:
Configuration
So, imagine to have a 16 ports switch, we want to extend our router with 8 ports. We choose the first 8.
So the ports 9-16 of the switch will retain the VID 1, and be untagged, with the VID 1 used also for management.
Then we create the VID 100 to assign it to trunks or hybrid ports (a trunk is a port that is assigned to all the VLAN IDs, and hybrid port is a port assigned to some VIDs).
This because we want that the packets coming from the port 1 to the port 7 can pass through the port 8, and the tagged packets coming from the port 8 can pass through the ports 1 to 7, without tag (because other devices could not recognize the tag or reject the packet if tagged).
Configuring an OpenWrt router
Now we want to make use of this. For example, let’s say that we connect to the port 1 of the switch the modem for the wan connection ‘wan’, and on the port 2 the modem for the wan connection ‘wan2’.
With programmable switch
On a TP-Link TL-WDR3600 we have something like this:
Without programmable switch
On a routerOS metarouter or a x86 device with have something similar to this.
Conclusion
In this way you have your extended router with way more ports, overcoming the limits of the table of hardware that actually does not offer any device with more than 5 gigabit ports easy to install (the Mikrotik ones are a bit complicated to install).
The limits to take care of are: how much traffic will pass through a port, normally for SOHO even combining multiple WANs it should not exceed 200-300 Mbit, and the processing power of the device itself (that will be under stress already for checking the vlan tag) with OpenWrt (that sometimes cannot use hardware acceleration),
But this could enable the usage of very powerful devices with just 2 ports, for example.
Practical applications for productive work
How to configure the managed switch with VLAN allowed
Reserving and grouping ports in rows or ‘nibbles’
So the idea is to reserve some ports in a managed switch with VLANs to configure them as extension for a OpenWrt based gateway. A point that should not be underestimated is how to choose and reserve ports for specific roles. For now we can decide to divide the role of the ports in two main groups: external connection and internal connections. This because if we do not reserve enough ports, in case of small expansion of the network needs, we end up on a switch that has a minefield (and no clear structure) of VLANs. Furthermore consider that we are going to use one gigabit port as connection to the router, therefore we expect that the traffic on every port is way less than one gigabit, else we have congestion. In our case the traffic generated between logical networks is less than 50 Mbit on average, even if a gigabit port has to channel several logical networks it will be enough. Of course the solution is not extremely scalable but for small networks (the ones covered by us), it is way enough.
The same applies for internal connections. We should see the port on the switch as ‘managed ports’ by the router (through VLANs), so even internal network ports should be defined. For internal networks the number of assigned port should be a bit ‘expansion proof’ since internal necessities can arise and we want to have a standard that does not change every moment.
The internal logical network that is likely that could be covered are: voip, lan, lan2 (another company or an old network), wifi. So mostly 4. We can put a bit of margin, because creating an internal need is way more cheap than creating another contract for wan connection, so let’s extend to 7, so we have 8 port used (one has to go to the router).
Now it is about grouping. Mostly we will use switches with 16 ports until 48, and those normally have 2 rows of Ethernet ports. One way is to use rows, one way is to use nibbles (that are rectangular grouping). We will see later how to use nibbles, because using a row of N contiguous ports it is the simpler way.
Assigning VLANS
With a 24 port switch like an hp 1810-24 j9803A we can use 12 ports like this (note that we assign the logical network numbers following the numbers of the device for easy of maintenance. This is one of the small factor in our ‘parametric standard’):
port 1 — wan1 PVID 101 | port 3 — wan3 PVID 103 | port 5 — lan1 PVID 201 | port 7 — lan3 PVID 203 | port 9 — lan5 PVID 205 | port 11 — lan7 PVID 207 |
port 2 — wan2 PVID 102 | port 4 to the wan ‘collector’ port on the router PVID 100 tagged VID 101,102,103 | port 6 — lan2 PVID 202 | port 8 — lan4 PVID 204 | port 10 — lan6 PVID 206 | port 12 to the LAN ‘collector’ port on the router PVID 200 tagged VID 201,202,203,204,205,206,207 |
You can see the rectangular grouping called also ‘nibble’. An advantage of not using ‘trunk’ ports over ‘hybrid’ is that we separated neatly the groupings and we do not risk that a port is sending data also to an unwanted port.
Example configuration
An example of configuration to use part of the managed switch configuration.
- Last modified: 2021/07/23 14:52
- by someothertime
Self-registration in the wiki has been disabled.
If you want to contribute to the OpenWrt wiki, please post HERE in the forum or ask on IRC for access.
Except where otherwise noted, content on this wiki is licensed under the following license:
CC Attribution-Share Alike 4.0 International
Источник
Switch documentation
: This page is very outdated and incomplete, from the era of kernel 2.6 or 3 and early UCI-driven configuration. If your device has multiple interfaces, the default configuration of VLANs will likely be very different than that described here.
This article may contain network configuration that is version dependent post 2021-06
More Information
: This page assumes you know what this is and why you want it. (see switch_configuration).
If you want to change how these ports are connected to each other you need to configure the switch of your device (see also network.interfaces)
UCI config, swconfig style
Known problems
Assumptions
Some of the assumptions, does not see to add up with the provided diagram. Someone familiar with the matter, should either fix them or add a better explanation.
The configuration
The Switch
VLAN: switch config
Notes
The relevant standards document is 801.2q which says that VID values 0 and 4095 may not be used for tagging packets as they denote reserved values — VID 0 is the default ‘native’ vlan — leaving 4094 valid values in between, although VID 1 is often reserved for network management (see Dell 2708 for example). This means vlan0 can be used as a VLAN within or between devices, but you cannot tag packets with it.
The config sections
VLAN: interface/network config
Of course, if you only had a five port switch on eth0 (and no other interfaces), you might make the wan interface eth0.1 and the lan eth0.0 with appropriately matching switch , switch_vlan and switch_port sections.
Examples
Example on the asus wl500gp v2 , openwrt 10.03, every physical port
Example vmware linux guest, openwrt x86 generic 12.09 combined, 2virtualized intel e1000
More research on vlan on x86 devices has to be done to collect more information on the wiki.
The majority of x86 devices do not have any programmable switch, but it does not seem to be a problem. The syntax used on devices with programmable switches seems completely not necessary.
For example we want to create two ‘virtual interfaces’ associated to the same physical interface, eth1 . To do this, we do the following in /etc/config/network
According to what the contributors of this section have read online, so far seems that the packet will be tagged by default, because they are associated to one physical ports that at most will have one PVID (port vlan id) but more than one virtual interfaces. Therefore, having multiple virtual interfaces, the packets must be tagged else it won’t make sense, they won’t be able to reach the interfaces or to go out.
The tests seems to confirm that because (using a vmware switch and portgroups) to let two openwrt x86 vmware guests reach each other the portgroups had to be configured with the trunk vlan id (that is: vlan id 4095, According to white papers: VMware Virtual Networking Concepts and VMware ESX Server 3 802.1Q VLAN Solutions).
Side note: if different virtual interfaces related to different vlan are in the same logical network, there will be conflict in terms of metrics, in that case bridging the interfaces could be a solution (has to be tested).
- Last modified: 2021/08/02 19:51
- by vgaetera
Self-registration in the wiki has been disabled.
If you want to contribute to the OpenWrt wiki, please post HERE in the forum or ask on IRC for access.
Except where otherwise noted, content on this wiki is licensed under the following license:
CC Attribution-Share Alike 4.0 International
Источник
Собираем свой OpenWRT на роутер Tp-Link TL-WR741ND v.4.25 c vlan, openvpn, ротацией провайдеров и блэкджеком
В данной статье я хотел бы поделиться опытом сборки собственной прошивки openwrt, с выбором нужных пакетов, а также настройкой отказоустойчивого доступа в интернет с мгновенной ротацией каналов и одновременной их работой, складыванием скорости провайдеров и как следствием, настройкой всем любимых vlan-ов.
Выбор пал на роутер Tp-Link TL-WR741ND v.4.25 (цена 1150 рублей), который я выбрал по следующим характеристикам:
1) Низкая цена
2) Достаточное количество памяти для заявленных требований
3) Возможность запиливания USB (для истинных ценителей поковырять железку)
4) Поддержка OpenWrt Barrier breaker
5) Поддержка vlan-ов
6) Поразительная живучесть (роутер невозможно убить неверной прошивкой, функция восстановления прошивки по tftpd работает как часы, и не раз выручала во время неудачных экспериментов). О методах восстановления напишу в конце статьи.
Стандартная прошивка для данного роутера от OpenWrt не устраивала. Причиной тому были лишние пакеты, которые занимали место в драгоценной памяти данного малыша.
Было решено выпилить: ppp, поддержку ipv6, opkg (ставить же не будем больше ничего).
Добавить: openvpn-polarssl (меньше занимает места), luci-mwan3 (очень понравилась визуальная настройки и индикация работы каналов)
Итак, начнем:
1) Подготовка устройства
Для начала, обновим наше устройство до последней версии стандартной прошивки tp-link. Смысла описывать подробно данное действо я не вижу, все достаточно понятно и просто.
2) Сбор прошивки
Нам понадобится многоядерный процессор для комфортного создания своей прошивки (я собирал на i7). Но и Core2Duo сойдет, разве что подольше собираться будет. OS подойдет Ubuntu 15 x86_64.
Установка необходимых пакетов:
Все дальнейшие команды сборки делаются от обычного пользователя, не от рута!
Идем в «магазин» за исходниками. Я выбрал OpenWrt Bariier Breaker за удобство в настройке и отличную стабильность на предыдущем роутере (TP-LINK Archer C7).
В домашней папке у нас появится папка wrt, где мы и будем производить сборку.
Скачаем исходники дополнительных пакетов (типа Luci):
Выполним настройку платформы
Появится псевдографическое меню, где нас интересуют пункты Target System, Subtarget и Target Profile:
Вся навигация свободится к выбору нужного пункта (стрелками) и нажатием enter, выбор компонента — также enter, выход из меню — стрелки вправо-влево — Exit. Не забудьте сохранить конфиг.
Применяем стандартные параметры для профиля:
Модифицируем набор пакетов:
Удалил:
opkg из (base system)
убрал опцию сборки с поддержкой ipv6 (Global build settings)
ppp (Network).
Добавил:
Luci
luci-app-mwan3 (Luci-Applications)
openvpn-polarssl (Network-vpn).
Не забудьте сохранить конфигурацию!
Параметр -j5 указывает на количество ядер +1 поток для быстрой сборки, а V=s — на вывод подробностей (если будут ошибки).
Процесс займет долгое время, 10-15 минут на i7 процессоре, после чего в директории /home/user/wrt/bin/ar71xx появятся наши прошивки для различных версий роутера. Если не появились — смотрим в логи сборки — наверняка, вы превысили размер прошивки и увидите строку: «firmware is too big». Придется делать make clean, make distclean и начинать все заново. (с шага ./scripts/feeds update -a )
openwrt-ar71xx-generic-tl-wr741nd-v4-squashfs-factory.bin — «заводская» прошивка.
Перекидываем её на компьютер с подключенным по ethernet-у роутером (например, через ftp или winscp).
Заходим по адресу: 192.168.0.1 и прошиваем новоиспеченной прошивкой, ждем перезагрузки, затем заходим по адресу: 192.168.1.1
root без пароля (его назначим при первом входе — вверху будет висеть желтый баннер с предупреждением и ссылкой на смену пароля).
Ну наконец-то, самое сложное позади, теперь у нас современная прошивка и НАШ набор программ.
3) Настройка vlan:
Происходит в меню роутера: network — switch
Тут не обошлось без непоняток — нумерация портов в роутере и в конфигурации vlan не совпадает. На скриншоте я постарался объяснить как они изменены. Порт WAN в роутере не участвует в vlan-функционале.
Tagged — тэгированный трафик, сюда направляются пакеты от каждого vlan (101, 102, 103), которые затем распределяются по интерфейсам wan (основной провайдер), wan2 (резервный провайдер), eth0.103 (vlan для локальной сети).
Untagged — нетэгированный режим порта (точка входа ethernet-кабеля от нужного провайдера). Тут важно не запутаться в проводах: что куда идет. Я подписал сзади роутера нужные названия, чтобы в будущем не было путаницы (провайдер№1 101, провайдер№2 102, локалка 103).
Проще говоря, мы впускаем через 3 порта 3 разных сети, которые затем внутри устройства распределяются по полочкам.
После изменений нажмите Save, но не Apply! Мы ведь не хотим остаться без сети во время настройки?
Теперь, нужно создать нужные интерфейсы в Network — Interfaces:
Удалим wan6 интерфейс (мы не используем ipv6 в данном случае).
Изменим wan интерфейс для первого провайдера, укажем нужные данные для подключения (например, провайдер дает инет по dhcp), и укажем какой vlan использовать для этого интерфейса. Вот тут-то и идет сопоставление vlan: провод: интерфейс.
Для второго провайдера wan2 укажем eth0.102.
Для Lan укажем объединить интерфейсы в bridge eth0 и eth0.103:
В настройках интерфейсов wan и wan2 укажите метрику устройств (обязательно для работы mwan3):
Теперь смело можно жать на Save&Apply и проверить введенные настройки.
4) mwan3 или крутая выручалочка админа
Трудно недооценить данный пакет, ведь пользователи смогут получать сумму скорости двух интернет-каналов, интернет в офисе будет всегда, ведь маловероятно, что упадут оба канала.
Для админа пройдет головная боль по временному отключению какого-либо из каналов, и не нужно городить костыльные скрипты по переключению. Я забыл о проблемах в офисе с интернетом и не переживаю когда падает один из них (мне приходят sms по данным событиям).
Я точно знаю, что OpenVPN через 30 секунд переключится на резервный канал (слава параметру multihome), связь с главным офисом в г.Москва восстановится и некоторые пользователи и начальники не заметят данный инцидент.
Зайдем в network — load balancing — configuration:
И включим wan2 в работу:
Далее, настроим правила работы каналов:
1) Balanced — Каналы складываются, скорость увеличивается, есть отказоустойчивость (переключение). Рекомендую.
2) wan_only — только провайдер№1
3) wan2_only — только провайдер№2
Остальные rules можно удалить или оставить другое правило.
Подробно я останавливаться на mwan3 не буду — скажу только, что есть возможность пускать трафик до определенного ресурса через один из каналов, если есть привязка на данном ресурсе по IP.
5) Офисная дружба или openvpn
Отлично, интернет настроили, теперь нужно соединить 2 офиса вместе.
Будет заходить по статическому ключу. Генерацию ключа можно произвести на клиентской стороне:
Ключ нужно поместить в /etc/openvpn/keys/ (сервер, клиент).
OpenVPN на роутере у нас уже установлен и мы начнем править конфиг. Для этого зайдем на TP-Link по ssh.
В шапке конфига изменяем:
Cохраняем, выходим. Тут мы включили кастомный конфиг в /etc/openvpn/openvpn.conf — лично для меня это как-то привычнее.
Далее, сам конфиг:
На роутере у нас серверная сторона openvpn. Приводим конфиг к виду:
Примерный конфиг выглядит так:
Сохраняем конфиг, применяем:
Смотрим ifconfig, логи и радуемся надежному каналу.
Заключение:
Конечно же, вы не один раз убьете свой роутер неудачной прошивкой, позарившись на удаление нужных компонентов base system.
Но ничего страшного!
Самый простой способ реанимировать роутер — это fail safe в openwrt:
1) Назначьте сетевому адаптеру на компьютере IP адрес 192.168.1.2
2) Маска 255.255.255.0
3) Кабель ethernet — в порт LAN1
4) Выключите роутер
5) Включите и дождитесь пока загорится значок шестеренки
6) Зажмите на 1-2 секунды кнопку роутера QSS — шестеренка заморгает очень быстро
7) Запустите телнет-клиент и подсоединитесь по адресу 192.168.1.1
8) Залейте в tmp роутера дефолтную прошифку для вашей модели, например, через мини-веб-сервер tinyweb
9) Выполните:
Роутер скушает прошивку и перезагрузится.
Шеф, всё пропало!
Да, именно так я подумал, когда убил роутер еще тяжелее. Шестеренка не горела, а роутер циклически ребутался без остановки.
Воспользуемся замечательной функцией в прошивке tp-link-а — загрузка прошивки через tftp:
1) Назначьте сетевому адаптеру на компьютере IP адрес 192.168.0.66
2) Маска 255.255.255.0
3) Кабель ethernet — в порт LAN1
4) Запустите tftp сервер с дефолтной прошивкой в папке под названием «wr741ndv4_tp_recovery.bin» (нужно переименовать файл прошивки)
4) Выключите роутер
5) Возьмите острый и тонкий предмет (ручка)
6) Возьмите роутер в руки, поверните его к лицу портами, ручку держите в свободной руке
7) Включите роутер и тут же зажмите QSS пальцем одной руки+reset ручкой в другой руке. Потренируйтесь и это получится.
8) Удерживайте зажатыми эти 2 кнопки 4-8 секунд, пока в tftp клиенте не пойдет загрузка прошивки в роутер. А она пойдет, не беспокойтесь.
Как только прошивка загрузилась (2-3 сек), отпустите кнопки. Выдохните, роутер спасен.
Источник