Перейти к содержимому

Wmm mode openwrt что это

  • автор:

Wmm mode openwrt что это

Wireless Mesh is the buzzword for the 2020s. In the effort to have wall-to-wall Wifi coverage, SOHO (Small Office/Home Office) router vendors, have carved out a new, more expensive, market niche. If one router is good, then three routers must be better (and more profitable).

In this article, we’ll delve into the technology of Wireless Mesh, and the benefits, and downsides if using a Wireless Mesh, instead of the common traditional single SOHO Wireless Router.

What is Wireless Mesh

Wireless Mesh is a group of routers acting together to provide broader wireless coverage, while creating a non-looping paths through the network. The IEEE (The Institute of Electrical and Electronics Engineers) which brought you Ethernet (802.3) and Wifi (802.11), created an ammendment to the Wifi Standard for wireless mesh called 802.11s in 2012.

There are many commercial offerrings for Wireless Mesh network on the market today. Many extend, or implement proprietary aspects of of mesh networking, which creates vendor lock-in.

Fortunately, OpenWrt, the open-source router software, implements the 802.11s standard, and it is possible to create a multi-node wireless mesh with a variety of router vendor’s products.

Wireless Mesh using OpenWrt & 802.11s

Below is a diagram of a simple 3 node wireless mesh network. The Mesh Portal connects the wireless mesh network to the wired network. The left-most router acts as a Layer 3 (network layer) boundary for the mesh network, providing RA (Router Advertisements), and NAT64/DNS64 services.

Wireless Mesh

The wireless mesh network is a single L2 domain, all attached devices will be in the same subnet (or IPv6 prefix).

In this mesh network, all nodes are on the same 5 Ghz channel, while the 2.4 Ghz access APs can be on different channels, but share the same SSID to allow wireless devices to easily roam from one mesh node to the next.

Two of the nodes, Waialae-nui and Iao, also server as regular Access Points (AP) allowing wireless nodes to connect to the mesh network.

Looking at 802.11s loop prevention

In order to prevent looping in mesh networks, 802.11s uses Path Discovery using Path Requests (PREQ) and Path Reply (PREP) messages.

Node A looking for a path to Node H. It will flood PREQ messages to all nodes using the ethernet broadcast MAC address. Node H will receive the PREQ message from Nodes F & J, but F will have a lower hop-count, thus the path back to Node A will be via Node F. Node H will send the PREP message back to Node A via the F-D-A path, which Node A will record, noting that the best path from A to H is along the path of A-D-F-H. The use of PREQ and PREP messages remove the possibility of looping in a Mesh network.

Wireless Mesh Path Discovery

PCAP of PREQ & PREP messages

Mesh Networking Addressing, the Air Bridge

A mesh network can be thought of as a giant distributed ethernet bridge forwarding ethernet frames from wired and wireless interfaces across the 802.11s mesh network. In order to transport entire ethernet frames (and their IP payloads) across the wireless mesh, an additional mesh control header is appended after 802.11 header. The Mesh Control Header contain the additional MAC address fields of original source and destination.

In the diagram below, you can see the original sender STA 1 and destination, STA 7 are preserved in Mesh Control Header (as addr 5 & 6) as the packet traverses the mesh network.

Wireless Mesh Path Addressing

PCAP of the Six Addresses used to create the Air Bridge

Determining if your OpenWrt router supports 802.11s

The OpenWrt router must be running version 19.07.x, as wireless mesh is not supported in earlier releases.

802.11s wireless mesh must be supported at the hardware level. In order to determine if your OpenWrt router has this support run the following command:

In the above example of dual band router, the * mesh point indicates that it does support 802.11s mesh. The < AP, mesh point >indicates that mesh and AP functionality are simultaneously supported on the same radio.

Configuring OpenWrt for 802.11s Mesh

In order to configure wireless mesh, where all nodes run on the same channel, it is good to scout the area you wish to cover with the wireless mesh network to determine a relatively empty channel. 5 Ghz is the better choice as it has more available non-overlapping channels (9 20 Mhz channels, vs 3 20 Mhz channels on 2.4 Ghz). You may choose to use 40 Mhz channels on the 5 Ghz band, but that reduces the available channels to four. There are the DFS channels (16 20 Mhz, or 8 40 Mhz), but they are not recommended for Wireless Mesh, as nodes will become unavailable, as they move out of the DFS band.

5 Ghz Band

Once you have selected a single channel to be used by your mesh, the following must be done for each of the mesh nodes in your network.

  1. Install a wpad which supports mesh
  2. Add /etc/config/wireless with a mesh interface
  3. And configure mesh channel in /etc/config/wireless
  4. Run the wifi command to reload the wireless config

Before configuring the OpenWrt router for 802.11s, one must remove the default wpad (WPA daemon) and install one that supports mesh networking. Ensure you do this while attached to the router via a wired connection, as you are likely to lose your wireless connection.

Then add this stanza to the /etc/config/wireless file:

Change mymesh and mysecret to match your naming and password needs. They must be the same for all mesh nodes

And change the channel of the 5 Ghz Radio to your mesh channel in /etc/config/wireless

Run the wifi command to cause OpenWrt to reload the wireless configuration.

Clearly, you will need to run through these steps for each node in your wireless mesh.

Managing the Mesh Nodes

802.11s only provides Layer 2 connectivity between the nodes. In order to be able to manage the nodes the router must be put into dumb AP mode, and assigned a static IP address

In order to not lose connectivity while configuring the router, assign a static IP address to the the LAN interface. Since this is to be an IPv6-only network, assign a static IPv6 address in the same prefix as your IPv6-only network.

Edit the /etc/config/network file, adding ip6gw and ip6addr to the LAN interface. Normally IPv6 gateway addresses are link-local addresses, but that requires interface scope. In this case, it is easier to point back to the NAT64 router’s Global Address (GUA) on LAN interface as the gateway.

For an IPv6-only network, it is OK to leave the IPv4 static address, as it won’t be used, and maybe helpful, to recover the node on your workbench.

To place the router into dumb AP mode, one must disable the DHCPv4 server, and disable IPv6 RA and DHCPv6 services.

Edit /etc/config/dhcp file to disable DHCPv4, and comment out the following lines for RA and DHCPv6 servers on the LAN interface.

Ensure that you are connected to the router via the static IPv6 address (it is a good time to put that address in your local DNS server), and restart networking on the router for the changes to take effect.

Admiring your 802.11s mesh network

In the default OpenWrt configuration, the LAN ports, and the Wireless Radios (2.4 & 5 Ghz) are bridge together. This means by default, the wireless mesh will be bridged to the LAN ports of each router, making it easy to manage by plugging into any LAN port with your laptop.

Since you have already assigned DNS names to the static IPv6 addresses of each node, it is easy to ssh to a node and see if your mesh network is up and running. In this example I’ll ssh to the mesh portal node kahaluu.

The iw command will display that status of paths as well as of each peer. The Paths command is a shorter output. Make sure you use the correct wireless interface (wlan0 or wlan1).

Since this is Layer 2-based, you will only see MAC addresses of each node. It is probably a good time to make a note of each nodes MAC address. The key fields of this output are the Destination Address, Next Hope, and Metric columns. Because this is only a 3 node mesh, the Destination Address and Next Hop will almost always be the same. To see the mesh in action, run the wifi command on another node, while running the MPath on the original node, not that initially, the connectivity will be via the third node, before reverting to a direct connection.

Watching a mesh node reattach
Dumping information about the peer nodes

Using the iw command it is possible to view quite a bit of information about the peer nodes.

Key information here is Signal strength, bitrate, and mesh parameters.

Configuring APs on your mesh network

Now that you have your mesh nodes all configured, and peering setup, you still need to configure some (or all) of the Nodes in AP mode. This will allow wireless devices, such as laptops, cell phones, IoT devices, to communicate across your new mesh network.

You have a choice, you can configure an AP on the 5 Ghz interface if your initial HW check displayed < AP, mesh point >. If not, then you will must use the 2.4 Ghz interface as an AP.

Configuring an AP

Configuring an AP on a node is the same as you would configure an AP on a non-mesh network router. It is easier to do via the *LuCI Web Interface, but it can also be done via the CLI.

Edit the /etc/config/wireless file, which should be default already have an AP configuration stanza

Update the key with your preferred wireless password, and the SSID with the name of the AP.

Run the wifi command to reload the wireless config

Roaming from AP to AP with 802.11r

In order to enable roaming as you wander around your mesh network, you must use the same key and ssid for all of the APs on the mesh network.

If you want to add 802.11r support (for faster roaming handoff) add the following options to your AP configuration stanza. The mobility domain (4 hex digits) must be the same for each AP that allows roaming.

Or use the LuCI web interface and just check the box Wireless Mesh 802.11r

And add a four hex digit mobility domain when the box appears. Wireless Mesh 802.11r

Using your Wireless Mesh Network

Now that the mesh network is up and running, and APs have been configured and enabled, it is time to use the wireless mesh network.

Configure your wireless device to use the shared AP SSID (holoholo in this example).

The NAT64/DNS64 router (kapalua) will provide the IPv6-only addressing across the mesh network and your wireless device will obtain a SLAAC and/or DHCPv6 address.

Once your wireless device has an IPv6 address, the world is at your finger tips.

1. Hands On — Examining Wireless Mesh at work

Download the following packet captures, and open in Wireshark to answer the questions below:

Discuss the following:

  • What is the Destination Address of a PREQ message (frame 1)? of a PREP message (frame 2)?
  • In the ICMPv6 packet (frame 73), what are the Original sender/receiver MAC addresses stored?
  • What is Manufacturer of the original sender (MAC address) in frame 73 ?

extra credit: Why are there only 4 MAC addresses in the 802.11 header for a Router Advertisement (frame 100)?

Downside to using Wireless Mesh

All of those wireless hops come at an additional cost of higher latency and lower throughput. Since each wireless hop must store and forward each packet, there is additional latency added. And if you chose to use 5 Ghz APs, then each AP must share the same access channel as the mesh channel, adding additional latency.

Latency & Throughput

Use ping to measure latency across the mesh network.

Compared to a wired connection, where the latency is about 1 ms.

Throughput

Transferring a 251 MB video file from RAM disk to RAM disk, using scp on a Raspberry Pi 3B+. All times measured by scp .

Rate Time Comment
7.4MB/ 00:33 Wired with Powerline adapters
20.6MB/s 00:12 Wired GigE on same network
2.6MB/s 01:35 Mesh with 1 hop — same channel
4.0MB/s 01:03 Mesh with 1 hop — 2.4 Ghz access, 5 Ghz Mesh
17.8MB/s 00:14 Direct connect to 802.11n bridged
11.8MB/s 00:21 Direct connect to 802.11ac routered

The 3B+ Pi although equipped with a GigE interface, is throughput limited to 200 Mbit, but that is enough for this testing.

As it can be seen, a traditional router (non-mesh) has much better throughput. And bridged Wifi is faster than routed Wifi (in the traditional router scenarios).

802.11r Fast Roaming Performance

How fast is Fast Roaming (802.11r)? Walking between two APs, noted an extra long ping when the switch happens.

Without 802.11r enabled, I noted that my test the wireless device (a Chromebook) would not switch APs, even though the Chromebook was right next to another AP until it was put to sleep and reawakened.

IPv6 Support

Since 802.11s wireless mesh, is a layer 2 protocol, it is possible to configure an IPv6-only network on top of the mesh network.

Wireless Mesh

Router Advertisements are sent into the mesh network normally, as one would expect. Neighbour discovery (NDP) which also uses multicast works correctly.

Of course, one doesn’t need to run an IPv6-only network as part of a wireless mesh network, but many issues can be flushed out by running IPv6-only.

Conclusion: A matter of size

Looking at the Commercial Wireless Mesh Products online, the prices range from about $200-$1000. All of them make claims of covering 400-600 m 2 (4000 to 6000 square feet). That is a really large house, or you just want to give your horses Wifi in the barn.

Perhaps only a distant room or office requires a stronger wireless signal. OpenWrt supports Wireless Distribution System (WDS), which is much easier to configure, can easily extend your wireless coverage.

Wireless mesh has its place in large area loop-free distribution of wireless networking. However, most SOHO (Small Office/Home Office) environments will not require the broad area coverage that 802.11s provides.

Прошивка OpenWRT для роутеров

Данная статья может быть полезна продвинутым пользователям, которые хотят улучшить работу своего домашнего роутера, а также системным администраторам предприятий, перед которым стоит задача повысить надежность и безопасность удаленной работы сотрудников.

Как вы скорее всего знаете, ваш роутер – это маленький компьютер и него есть программное обеспечение, так называемая “прошивка” или “firmware”. Прошивку разрабатывает производитель роутера, однако существуют также альтернативные решения – проекты с открытым исходным кодом: OpenWRT, DD-WRT, Tomato.

Что нам даёт использование OpenWRT?

Обновления (безопасность и новые фишки) выпускаются в разы чаще и поддержка сохраняется в разы дольше, чем у большинства производителей. Особенно актуально это стало в условиях карантина. Уязвимая “прошивка” роутера – одна из наиболее частых причин инцидентов при удаленной работе.

“Родные” прошивки бывают нестабильными, особенно у дешевых роутеров. Так многие модели TP-Link зависали после нескольких дней беспрерывной работы.

Вы привыкаете к одному интерфейсу пользователя и при последующей смене/апгрейде роутера, даже от другого производителя, чувствуете себя “как дома”.

Вам не обязательно покупать дорогой роутер для реализации продвинутых “фишек”, таких как IPv6, родительский контроль, блокировка рекламы, VPN, гостевой WiFi, DNS шифрование, динамический DNS (DDNS) и т. д.

Есть активное сообщество, которое поможет оперативнее, чем даже поддержка крупного производителя, да и многое уже описано.

Преимущества открытого решения на базе Linux: возможность подключаться через SSH, автоматизировать настройку и управлять роутером с помощью скриптов, настройки хранятся в текстовых файлах (автоматизация, контроль версий), можно использовать роутер для других задач (умный дом, SFTP/Web сервер, закачка торрентов и т.п.).

Подробнее эти и другие причины описаны на сайте проекта.

Базовая настройка OpenWRT

Данная статья поможет вам настроить базовые функции OpenWRT, благодаря чему вы сможете быстро и безболезненно перейти на это решение. Вот перечень этих функций:

Установить пароль пользователя root.

Ограничить доступ по SSH только для интерфейса LAN.

Настроить PPPoE подключение по WAN.

Добавить гостевой WiFi (без доступа в локальную сеть).

Настроить динамический DNS NoIP.

Настроить переадресацию портов (port forwarding).

Сохранить конфигурацию в архивный файл.

Пункты 6 и 7 нужны, например, для того, чтобы подключаться из Интернета к домашнему компьютеру по SSH или SFTP (например, для синхронизация файлов с ноутбуком), а также для прямого подключения по Anydesk, которое работает быстрее, чем обычное.

Процесс “перепрошивки” на OpenWRT зависит от модели вашего роутера. Следует найти его в списке поддерживаемых устройств и следовать приведенным там рекомендациям.

Настройки можно делать с помощью SSH-подключения и скриптов, однако мы рассмотрим веб-интерфейс (который называется LuCI) как более наглядный и устойчивый к изменениям вариант.

1. Установить пароль пользователя root

2. Ограничить доступ по SSH только для интерфейса LAN

После этого шага имеет смысл сделать Logout и залогиниться снова, чтобы убрать предупреждение в верхней части экрана.

3. Настроить PPPoE подключение по WAN

Нажать кнопку “Edit” в строке “WAN”.

4. Настроить WiFi

4.1 Нажать на кнопку “Edit” под “radio0 802.11nac”.

Перейти на вкладку Wireless Security.

4.2 Нажать на кнопку “Edit” под “radio1 802.11bgn”.

Перейти на вкладку Wireless Security.

Нажать кнопки “Enable” (слева от “Edit”) на обоих подключениях.

5. Добавить гостевой WiFi

Взято отсюда, плюс ужато и обновлено под новый интерфейс.

Делаем для 2.4 ГГц, но аналогично можно сделать и для 5ГГц.

5.1.1 Нажать кнопку “Add” в “radio1 802.11bgn”.

5.1.2 Перейти на вкладку Wireless Security.

5.2.1 Нажать на кнопку “Edit” в интерфейсе “GUEST”.

5.2.2 Перейти на вкладку “Firewall settings”.

5.2.3 Перейти на вкладку “DHCP server”.

5.3.1 Нажать на кнопку “Edit” в зоне “guest”.

5.3.2 Перейти на вкладку Traffic rules.

Нажать на кнопку “Add” внизу.

Нажать на кнопку “Add” внизу.

6. Настроить динамический DNS NoIP

Нажать кнопку “Update lists…”

Набрать “ddns” в поле “Filter”.

Установить пакеты “ddns-scripts”, “ddns-scripts-noip”, “luci-app-ddns”.

Сделать Logout и потом залогиниться снова.

6.2.1 Нажать кнопку “Edit” в строке “myddns_ipv4”.

6.2.2 Нажать кнопку “Reload” в строке “myddns_ipv4”.

6.2.3 Нажать кнопку “Delete” в строке “myddns_ipv6” — если вам достаточно IPv4.

7. Настроить переадресацию портов (port forwarding)

Нажать кнопку “Add” внизу:

Нажать кнопку “Add” внизу:

8. Сохранить конфигурацию в архивный файл.

Нажать на кнопку “Generate archive”.

Сохранить скачанный файл в надежном месте.

В этом же пункте меню можно загружать обновления прошивки – кнопка “Flash image…”.

Заключение

Таким образом, мы рассмотрели недорогие в применении меры повышения безопасности и стабильности работы домашних роутеров с помощью прошивки OpenWRT. В то же время, следует заметить, что ни одна разовая мера безопасности, включая внедрение дорогого оборудования и программного обеспечения, не даст гарантий отсутствия инцидентов безопасности. Если вам нужен действительно высокий уровень защищённости, то необходим комплексный системный подход, начиная с аудита вашей ИТ-инфраструктуры, в том числе, домашнего окружения.

OpenWRT. Настройка сети

Маршрутизатор мы перепрошили в прошлой статье, а теперь давайте рассмотрим, что из себя представляет сама OpenWRT.

В качестве командной оболочки, ввиду предположительно малого количества встроенной памяти, используется ash (вместо привычного многим bash). Ash имеет 24 встроенные команды, 10 опций командной строки, и является одной из самых маленьких оболочек для Unix.

В качестве пакетного менеджера, для загрузки и установки пакетов из репозитория OpenWRT, используется легковесный opkg (форк ipkg), вместо привычных apt-get, pacman, yum и т. д.

О команднах opkg можно почитать здесь: http://wiki.openwrt.org/doc/techref/opkg

В качестве редактора по умолчанию, используется vi, который довольно непривычен для начинающих (например, для выхода нужно ввести :q! , для выхода с сохранением :wq ). Прежде чем работать с vi, ознакомьтесь с данной статьей:

Если вам привычней работать с более простым nano — установите его, он не так много весит. Для начала обновим список пакетов:

И установим nano:

# opkg install nano

Работать с OpenWRT, как вы уже догадались, можно через командную оболочку, подключаясь по ssh, или же через веб-интерфейс LuCI — второй гораздо проще и интуитивно понятней, отлично подходит повседневной работы, но не имеет всей гибкости, достигаемой правкой конфига.

Настройка Wi-Fi

По умолчанию, в OpenWRT отключает Wi-Fi передатчик, так что подключим и настроим, для начала, его.

Перейдите на вкладку Network → Wi-Fi.

openwrt 6

На вкладке «scan» доступны все найденные в области доступа сети. Таким образом, марщрутизатор на OpenWRT можно использовать как клиент, подключающийся к другой сети, и раздающий трафик на ваши устройства (в базовой прошивке TP-Link такой функции нет).

На вкладке «Add» — создадим собственную сеть:

openwrt 7

Channel — канал по умолчанию. Если вкратце: на частоте 2.4GHz, имеется 11 каналов, и если, к примеру, ваш сосед замет 1-й канал, то работая на первом канале, вы получите куда худшее качество связи, чем при работе на 6-м. Полностью непересекающихся каналов только три — 1/6/11. Лучше выбрать режим auto — тогда роутер будет анализировать качество связи на каждом канале, и сам выбирать оптимальный вариант.

Transmit Power — мощность передатчика. Для такого бюджетного роутера, как у нас, рекомендуется понизить её с 27dBm до, хотя-бы, 24-25dBm, в особенности при обслуживании большого количества Wi-Fi клиентов, иначе он будет перегреваться и может периодически зависать.

ESSID — имя вашей сети.

Mode — режим работы (в большинстве случаев вам нужен Access Point, если же вы организуете mesh-сеть или большую домашнуюю Wi-Fi сеть из нескольких взаимных устройств, то вы и так знаете, какой режим вам нужен).

WMM — протокол QoS для обеспечения лучшего качества передачи мультимедийных файлов (распознавая трафик, в режиме WMM маршрутизатор будет присваивать файлам потокового видео/голоса высокий приоритет, что повысит их качество).

В Advanced Settings вы можете выбрать протокол, в котором работает ваш передатчик, а также ширину канала. Современные устройства работают на 802.11n, те что постарее — на b/g, так что выбирайте 802.11g+n, и ширину канала 40MHz.

На вкладке Wireless Security вы найдете настройки шифрования. Желательно выбрать WPA-PSK/WPA2-PSK Mixed Mode, а во вкладке Key — ваш пароль от сети.

Вот и все базовые настройки — жмите «Save & Apply» и в вашем доме вновь заработает Wi-Fi.

В OpenWRT есть собственная централизованная система для управления всеми элементами системы, также она имеет свой, довольно простой синтаксис. То есть вместо привычных конфигов Linux, используются файлы конфига UCI, в целом похожие на конфиги в вашем Linux. Стоит разобраться с UCI, и работать с OpenWRT станет гораздо легче.

Файлы конфигурации UCI лежат в /etc/config:

openwrt 8

Для примера, настроим беспроводную сеть, конфиг которой лежит в файле wireless:

rm -f /etc/config/wireless

wifi detect > /etc/config/wireless

rm -f — удаляет имеющийся файл с настройкой.

Wifi detect — определяет информацию по железу (все авто-детектируемые опции файла wireless) и создает такой же файл, какой был у нас изначально, до настойки в веб.

openwrt 9

На примере этого файла, рассмотрим синтаксис uci.

config wifi-device radio0

option type mac80211

option channel 11

option macaddr b0:f3:c1:7e:4e:30

config — обозначает начало секции.

Wifi-device — тип объясняющий uci что что именно мы редактируем.

radio0 — имя, или идентификатор (то, какое именно устройство/интерфейс мы редактируем)

option — тип настроек, в данном случае опция. Также может быть list — составные настройки, в которые могут быть включены опции с множественными значениями

type/channel/macaddr — всё это типы настройки, которые входят в блок опций wi-fi-device.

Опции могут быть заключены в кавычки, двойные и одинарные (заключающая кавычка должна быть такой же, как и начинающая). И даже должны быть заключены, если в имени опции имеется пробел.

Теперь редактирует сам файл wireless:

Первый блок настроек отвечает за физическую составляющую, такую как mac-адрес, канал и его ширину, используемый стандарт и т. д. Все они детектируются автоматически, и большинство из них, кроме mac-адреса, можно поменять.

Option channel 11 — используемый канал. Допустимые значения — от 0 до 11, или «auto» (желательно) для автоматического определения канала.

Option hwmode 11ng — используемый стандарт, оставим без изменений. Допустимые значения: 11b, 11g, 11a и 11ng.

option htmode HT20 — ширина канала. В особо зашумленных сетях (в многоквартирном доме, например) не рекомендуется использовать широкий канал, но если ваша сеть единственная в округе, то можете сменить на HT40 — канал шириной 40MHz. Для стандартов 802.11ac (не в нашем случае) допустмы значения VHT80 / VHT160.

option disabled 1 — по умолчанию радиопередатчик заблокирован. Смените значение на 0, или просто удалите строку, чтобы его разблокировать.

Добавим также строку:

option txpower 25 — txpower принимает как аргумент численное значение равное мощности вашего передатчика в dBm.

Блок config ‘wifi-iface’ — задает настройки интерфейса, такие как режим работы, имя устройства и пароль:

option device radio0 — указывает, для какого устройства мы настраиваем интерфейс.

option mode ap — задает режим работы. Допустимые значения: ap — точка доступа / sta — клиент / adhoc / wds / monitor / mesh)

option ssid OpenWrt — задает имя (SSID) сети. Смените на желаемое (не забывая про кавычки)

option encryption none — настройки шифрования, по умолчанию отключены. Допустимые значения — wep для WEP, psk для WPA-PSK, или psk2 для WPA2-PSK. Желательно выбрать psk2.

option key ‘пароль’ — в режиме WPA2-PSK, задает пароль для сети.

Вот мы и настроили сеть также, как и настроили её ранее в веб-интерфейсе. Теперь, сохраните файл и примените настройки:

uci get wireless

И перезагрузить демон настройки сети:

/etc/init.d/network restart

После, беспроводная сеть вновь должна заработать.

Надеемся, на этом примере вы поняли базовые принциапы работы с UCI и настройки путем правки конфига. Выше, перечислены далеко не все функции, но многие из них специфичны и требуют особых драйверов. Больше о настройке файла wireless и полный список опций:

Wi-Fi /etc/config/wireless

The wireless radio UCI configuration is located in /etc/config/wireless. If the device has Ethernet ports, the wireless is turned OFF by default.

Sections

A typical wireless config file contains at least a pair of:

Wi-Fi devices

The wifi-device refer to physical radio devices present on the system. The options present in this section describe properties common across all wireless interfaces on this radio device, such as channel or antenna selection.

A minimal wifi-device declaration may look like the example below. Note that identifiers and options may vary for different chipset types or drivers.

The possible options for device sections are listed in the table below. Note that not all options are used for all chipset/driver types, refer to the comments for further details.

Common options

Name Type Required Default Description
type string yes (autodetected) The type is determined on firstboot during the initial radio device detection — it is usually not required to change it. Used values are broadcom on brcm47xx, or mac80211 for all other platforms
phy string no/yes (autodetected) Specifies the radio phy associated to this section. If present, it is usually autodetected and should not be changed.
macaddr MAC address yes/no (autodetected) Specifies the radio adapter associated to this section, it is not used to change the device mac but to identify the underlying interface.
disabled boolean no 0 Disables the radio adapter if set to 1. Removing this option or setting it to 0 will enable the adapter
channel integer or “auto” yes auto Specifies the wireless channel. “auto” defaults to the lowest available channel, or utilizes the ACS algorithm depending on hardware/driver support.
channels list no (regulatory domain specific) Use specific channels, when channel is in “auto” mode. This option allows hostapd to select one of the provided channels when a channel should be automatically selected. Channels can be provided as range using hyphen ('-') or individual channels can be specified by space (' ') separated values.
hwmode string no (driver default) Specifies the hardware mode, possible values are 11b for 2.4 GHz (used for legacy 802.11b only), 11g for 2.4 GHz (used for 802.11b, 802.11g and 802.11n) and 11a for 5 GHz (used for 802.11a, 802.11n and 802.11ac). Note that 11ng, 11na, 11n and 11ac are invalid options, this setting should largely be seen as controlling the frequency band. (DEPRECATED since 21.02.2, replaced with band)
band string no (driver default) Specifies the band, possible values are 2g for 2.4 GHz , 5g for 5 GHz , 6g for 6 GHz and 60g for 60 GHz . (NEW since 21.02.2, replaces hwmode)
htmode string no (driver default) Specifies the high throughput mode, used to control 802.11n (HT), 802.11ac (VHT) and 802.11ax (HE). The channel width used for these depends on this configuration. See this section for details. Possible values are: HT20, HT40-, HT40+, HT40, or VHT20, VHT40, VHT80, VHT160, NOHT disables 11n and 11ac, HE20, HE40, HE80, HE160
chanbw integer no 20 Specifies a narrow channel width in MHz , possible values are: 5, 10, 20
ht_capab string no (driver default) Specifies the available capabilities of the radio. The values are autodetected. See here for options (check vs. the version of hostapd installed on your router using the “refs” link)
txpower integer no (driver default) Specifies the maximum desired transmission power in dBm. The actual txpower used depends on regulatory requirements.
diversity boolean no 1 Enables or disables the automatic antenna selection by the driver
rxantenna integer no (driver default) Specifies the antenna for receiving, the value may be driver specific, usually it is 1 for the first and 2 for the second antenna. Specifying 0 enables automatic selection by the driver if supported. This option has no effect if diversity is enabled
txantenna integer no (driver default) Specifies the antenna for transmitting, values are identical to rxantenna
country varies no (driver default) Specifies the country code, affects the available channels and transmission powers. For types mac80211 and broadcom a two letter country code is used (EN or DE). The madwifi driver expects a numeric code.
country_ie boolean no 1 if country is set, otherwise 0 Enables IEEE 802.11d country IE (information element) advertisement in beacon and probe response frames. This IE contains the country code and channel/power map. Requires country.
distance string no (driver default) Distance between the ap and the furthest client in meters.
beacon_int integer no 100 (hostapd default) Set the beacon interval. This is the time interval between beacon frames, measured in units of 1.024 ms. hostapd permits this to be set between 15 and 65535. This option only has an effect on ap and adhoc wifi-ifaces
legacy_rates boolean no 1 in 19.07, 0 in 21.02 0 = Disallow legacy 802.11b data rates, 1 = Allow legacy 802.11b data rates. Legacy or badly behaving devices may require legacy 802.11b rates to interoperate. Airtime efficiency may be significantly reduced where these are used. It is recommended to not allow 802.11b rates where possible. The basic_rate and supported_rates options overrides this option.
require_mode string no none Sets the minimum client capability level mode that connecting clients must support to be allowed to connect. Overrides and sets legacy_rates to 0 to disable legacy 802.11b data rates. Supported values: n = 802.11n, ac = 802.11ac
cell_density integer no 0, supported in 21.02 Configures data rates based on the coverage cell density. Normal configures basic rates to 6, 12, 24 Mbps if legacy_rates is 0, else to 5.5, 11 Mbps. High configures basic rates to 12, 24 Mbps if legacy_rates is 0, else to the 11 Mbps rate. Very High configures 24 Mbps as the basic rate. Supported rates lower than the minimum basic rate are not offered. The basic_rate and supported_rates options overrides this option. 0 = Disabled, 1 = Normal, 2 = High, 3 = Very High
basic_rate list no (hostapd/driver default) Set the basic data rates. Each basic_rate is measured in kb/s. This option only has an effect on ap and adhoc wifi-ifaces. It is recommended to use the cell_density option instead.
supported_rates list no (hostapd/driver default) Set the supported data rates. Each supported rate is measured in kb/s. This option only has an effect on ap and adhoc wifi-ifaces. This must be a superset of the rates set in basic_rate. The minimum basic rate should also be the minimum supported rate. It is recommended to use the cell_density option instead.
log_level integer no 2 Set the log_level. Supported levels are: 0 = Verbose Debugging, 1 = Debugging, 2 = Informational Messages, 3 = Notification, 4 = Warning
hostapd_options list no none Pass any custom options to hostapd-*.conf . Values passed as-is. For example, used when setting vendor-specific informational element to make Windows clients detect Wi-Fi as metered connection

MAC80211 options

Name Type Required Default Description
path string no (none) Alternative to phy used to identify the device based paths in /sys/devices
htmode string no (driver default) Specifies the channel width in 802.11n and 802.11ac mode, possible values are:
HT20 (single 20MHz channel),
HT40- (2x 20MHz channels, primary/control channel is upper, secondary channel is below),
HT40+ (2x 20MHz channels, primary/control channel is lower, secondary channel is above),
HT40 (2x 20Mz channels, auto selection of upper or lower secondary channel on versions 14.07 and above),
NONE (disables 802.11n rates and enforce the usage of legacy 802.11 b/g/a rates)
VHT20 / VHT40 / VHT80 / VHT160 (channel width in 802.11ac, extra channels are picked according to the specification)
HE20 / HE40 / HE80 / HE160 (channel width in 802.11ax)
See also: Why can't I use HT40+ with channel 11?
See HT (high throughput) capabilities below for options to customize high-throughput modes
chanbw integer no 20 Specifies a narrow channel width, possible values are: 5 (5MHz channel), 10 (10MHz channel) or 20 (20MHz channel).
Only supported by the ath9k/ath5k driver (since Attitude Adjustment)
noscan boolean no 0 Do not scan for overlapping BSSs in HT40+/- mode.
Turning this on will violate regulatory requirements!
beacon_int integer no 100 (hostapd default) Set the beacon interval. This is the time interval between beacon frames, measured in units of 1.024 ms. hostapd permits this to be set between 15 and 65535. This option only has an effect on ap and adhoc wifi-ifaces.
basic_rate list no (hostapd/driver default) Set the supported basic rates. Each basic_rate is measured in kb/s. This option only has an effect on ap and adhoc wifi-ifaces.
supported_rates list no (hostapd/driver default) Set the supported rates. Each supported_rates is measured in kb/s. This option only has an effect on ap wifi-ifaces.
ht_coex integer no 0 Disable honoring 40 MHz intolerance in coexistence flags of stations (since Chaos Calmer)
frag integer no (none) Fragmentation threshold
rts integer no (driver default) Override the RTS/CTS threshold
antenna_gain integer no 0 Reduction in antenna gain from regulatory maximum in dBi

Broadcom options

The options below are only used by the proprietary Broadcom driver (type broadcom).

Name Type Required Default Description
frameburst boolean no 0 Enables Broadcom frame bursting (Xpress Technology) if supported
maxassoc integer no (driver default) Limits the maximum allowed number of associated clients
slottime integer no (driver default) Slot time in milliseconds

Ubiquiti Nanostation options

The options below are only used by the Ubiquiti Nanostation family of devices.

Name Type Required Default Description
antenna string no (driver default) Specifies the antenna, possible values are vertical for internal vertical polarization, horizontal for internal horizontal polarization or external to use the external antenna connector

Wi-Fi interfaces

A complete wireless configuration contains at least one wifi-iface section per adapter to define a wireless network on top of the hardware. Some drivers support multiple wireless networks per device:

A minimal example for a wifi-iface declaration is given below.

Common Options

The common configuration options for wifi-iface sections are listed below.

Name Type Required Default Description
ifname string no (driver default) Specifies a custom name for the Wi-Fi interface, which is otherwise automatically named. Maximum length: 15 characters. Note: DSA support does not effect wireless configuration and ifname continues to be valid here. (See Network Basics for more info)
device string yes (first device id) Specifies the used wireless adapter, must refer to one of the defined wifi-device sections
network string yes lan Specifies the network interface to attach the wireless to.
mode string yes ap Specifies the operation mode of the wireless network interface controller. Possible values are ap, sta, adhoc, monitor, mesh. NB: for wds mode, use option wds 1 with either option mode 'ap ' or option mode 'sta '.
disabled boolean no 0 When set to 1, wireless network is disabled.
ssid string yes OpenWrt The broadcasted SSID of the wireless network and for for managed mode the SSID of the network you’re connecting to
bssid BSSID address no (driver default) Override the BSSID of the network, only applicable in adhoc or sta mode. In wds mode specifies the BSSID of another AP to create WDS with.
mesh_id Mesh ID no none The Mesh ID as defined in IEEE 802.11s. If set, the wireless interface will join this mesh network when brought up. If not, it is necessary to invoke iw <iface> mesh join <mesh_id> to join a mesh after the interface is brought up.
hidden boolean no 0 Disables the broadcasting of beacon frames if set to 1 and, in doing so, hides the ESSID. Where the ESSID is hidden, clients may fail to roam and airtime efficiency may be significantly reduced.
isolate boolean no 0 Isolates wireless clients from each other, only applicable in ap mode. See this post for details.
doth boolean no 0 Enables 802.11h support.
wmm boolean no 1 Enables WMM. Where Wi-Fi Multimedia (WMM) Mode QoS is disabled, clients may be limited to 802.11a/802.11g rates. Required for 802.11n/802.11ac/802.11ax.
encryption string no none Wireless encryption method. Possible values are listed in the encryption values table, right after this table.
key integer or string no (none) In any WPA-PSK mode, this is a string that specifies the pre-shared passphrase from which the pre-shared key will be derived. The clear text key has to be 8-63 characters long. If a 64-character hexadecimal string is supplied, it will be used directly as the pre-shared key instead. In WEP mode, this can be an integer specifying which key index to use (key1, key2, key3, or key4.) Alternatively, it can be a string specifying a passphrase or key directly, as in key1. In any WPA-Enterprise AP mode, this option has a different interpretation.
key1 string no (none) WEP passphrase or key #1 (selected by the index in key). This string is treated as a passphrase from which the WEP key will be derived. If a 10- or 26-character hexadecimal string is supplied, it will be used directly as the WEP key instead.
key2 string no (none) WEP passphrase or key #2 (selected by the index in key), as in key1.
key3 string no (none) WEP passphrase or key #3 (selected by the index in key), as in key1.
key4 string no (none) WEP passphrase or key #4 (selected by the index in key), as in key1.
macfilter string no disable Specifies the mac filter policy, disable to disable the filter, allow to treat it as whitelist or deny to treat it as blacklist.
maclist list of MAC addresses no (none) List of MAC addresses (divided by spaces) to put into the mac filter.
iapp_interface string no (none) Specifies a network interface to be used for 802.11f (IAPP) — only enabled when defined.
rsn_preauth boolean no 0 Allow preauthentication for WPA2-EAP networks (and advertise it in WLAN beacons). Only works if the specified network interface is a bridge.
ieee80211w integer no 0 Enables MFP (802.11w) support (0 = disabled, 1 = optional, 2 = required). Requires the 'full' version of wpad/hostapd and support from the Wi-Fi driver
ieee80211w_max_timeout integer no (hostapd default) Specifies the 802.11w Association SA Query maximum timeout.
ieee80211w_retry_timeout integer no (hostapd default) Specifies the 802.11w Association SA Query retry timeout.
maxassoc integer no (hostapd/driver default) Specifies the maximum number of clients to connect.
macaddr mac address no (hostapd/driver default) Overrides the MAC address used for the Wi-Fi interface. Warning: if the MAC address specified is a multicast address, this override will fail silently. To avoid this problem, ensure that the mac address specified is a valid unicast mac address.
dtim_period integer no 2 (hostapd default) Set the DTIM (delivery traffic information message) period. There will be one DTIM per this many beacon frames. This may be set between 1 and 255. This option only has an effect on ap wifi-ifaces.
short_preamble boolean no 1 Set optional use of short preamble
max_listen_int integer no 65535 (hostapd default) Set the maximum allowed STA (client) listen interval. Association will be refused if a STA attempts to associate with a listen interval greater than this value. This option only has an effect on ap wifi-ifaces.
mcast_rate integer no (driver default) Sets the fixed multicast rate, measured in kb/s. Only supported in adhoc and mesh modes
wds boolean no 0 This sets 4-address mode
owe_transition_ssid string no none Opportunistic Wireless Encryption (OWE) Transition SSID (only for OPEN and OWE networks)
owe_transition_bssid BSSID address no none Opportunistic Wireless Encryption (OWE) Transition BSSID (only for OPEN and OWE networks)
sae_pwe integer no 0 (hostapd default) Sets the SAE mechanism for PWE derivation (0 = hunting-and-pecking only, 1 = hash-to-element only, 2 = both hunting-and-pecking and hash-to-element)
ocv integer no 0 (hostapd/wpa_supplicant default) Configuration option for Operating Channel Validation. When operating as an access point the following options are available: 0 = disabled, 1 = enabled, 2 = enabled in workaround mode — Allow STA that claims OCV capability to connect even if the STA doesn't send OCI or negotiate PMF.

Encryption Modes

Besides the encryption mode, the encryption option also specifies the group and peer ciphers to use. To override the cipher, the value of encryption must be given in the form mode+cipher. See the listing below for possible combinations.

To use the WPA3 modes as access point, it is required to install the hostapd-openssl package.

To use the WPA3 modes as station (client), it is required to install the wpa-supplicant-openssl package.

To support both access point and station modes with WPA3, it is possible to install the wpad-openssl package.

Value Type Ciphers Supported since
none no authentication none
sae WPA3 Personal (SAE) CCMP 19.07
sae-mixed WPA2/WPA3 Personal (PSK/SAE) mixed mode CCMP 19.07
psk2+tkip+ccmp WPA2 Personal (PSK) TKIP, CCMP
psk2+tkip+aes WPA2 Personal (PSK) TKIP, CCMP
psk2+tkip WPA2 Personal (PSK) TKIP
psk2+ccmp WPA2 Personal (PSK) CCMP
psk2+aes WPA2 Personal (PSK) CCMP
psk2 WPA2 Personal (PSK) CCMP
psk+tkip+ccmp WPA Personal (PSK) TKIP, CCMP
psk+tkip+aes WPA Personal (PSK) TKIP, CCMP
psk+tkip WPA Personal (PSK) TKIP
psk+ccmp WPA Personal (PSK) CCMP
psk+aes WPA Personal (PSK) CCMP
psk WPA Personal (PSK) CCMP
psk-mixed+tkip+ccmp WPA/WPA2 Personal (PSK) mixed mode TKIP, CCMP
psk-mixed+tkip+aes WPA/WPA2 Personal (PSK) mixed mode TKIP, CCMP
psk-mixed+tkip WPA/WPA2 Personal (PSK) mixed mode TKIP
psk-mixed+ccmp WPA/WPA2 Personal (PSK) mixed mode CCMP
psk-mixed+aes WPA/WPA2 Personal (PSK) mixed mode CCMP
psk-mixed WPA/WPA2 Personal (PSK) mixed mode CCMP
wep defaults to “open system” authentication aka wep+open RC4
wep+open “open system” authentication RC4
wep+shared “shared key” authentication RC4
wpa3 WPA3 Enterprise CCMP 19.07
wpa3-mixed WPA3/WPA2 Enterprise CCMP 19.07
wpa2+tkip+ccmp WPA2 Enterprise TKIP, CCMP
wpa2+tkip+aes WPA2 Enterprise TKIP, CCMP
wpa2+ccmp WPA2 Enterprise CCMP
wpa2+aes' WPA2 Enterprise CCMP
wpa2 WPA2 Enterprise CCMP
wpa2+tkip WPA2 Enterprise TKIP
wpa+tkip+ccmp WPA Enterprise TKIP, CCMP
wpa+tkip+aes WPA Enterprise TKIP, AES
wpa+ccmp WPA Enterprise CCMP
wpa+aes WPA Enterprise CCMP
wpa+tkip WPA Enterprise TKIP
wpa WPA Enterprise CCMP
wpa-mixed+tkip+ccmp WPA/WPA2 Enterprise mixed mode TKIP, CCMP
wpa-mixed+tkip+aes WPA/WPA2 Enterprise mixed mode TKIP, CCMP
wpa-mixed+tkip WPA/WPA2 Enterprise mixed mode TKIP
wpa-mixed+ccmp WPA/WPA2 Enterprise mixed mode CCMP
wpa-mixed+aes WPA/WPA2 Enterprise mixed mode CCMP
wpa-mixed WPA/WPA2 Enterprise mixed mode CCMP
owe Opportunistic Wireless Encryption (OWE) CCMP 19.07

WPA Enterprise (Access Point)

Listing of Access Point options for WPA Enterprise.

Name Default Description
server (none) RADIUS server to handle client authentication
port 1812 RADIUS port
key (none) Shared RADIUS secret
wpa_group_rekey 600 WPA Group Cipher rekeying interval in seconds
auth_server (none) RADIUS authentication server to handle client authentication
auth_port 1812 RADIUS authentication port
auth_secret (none) Shared authentication RADIUS secret
auth_cache 0 Disable or enable PMKSA and Opportunistic Key Caching
acct_server (none) RADIUS accounting server to handle client authentication
acct_port 1813 RADIUS accounting port
acct_secret (none) Shared accounting RADIUS secret
nasid (none) NAS ID for RADIUS authentication requests
ownip (none) NAS IP Address for RADIUS authentication requests
dae_client (none) Dynamic Authorization Extension client. This client can send “Disconnect-Request” or “CoA-Request” packets to forcibly disconnect a client or change connection parameters.
dae_port 3799 Port the Dynamic Authorization Extension server listens on.
dae_secret (none) Shared DAE secret.
dynamic_vlan 0 Dynamic VLAN assignment
vlan_naming 1 VLAN Naming
vlan_tagged_interface (none) VLAN Tagged Interface
vlan_bridge (none) VLAN Bridge Naming Scheme — added in https://dev.openwrt.org/changeset/43473/
radius_client_addr (none) Source-IP for RADIUS requests.

WPA Enterprise (Client)

Listing of Client related options for WPA Enterprise.

Name Default Description
eap_type (none) Defines the EAP protocol, possible values are tls for EAP-TLS and peap or ttls for EAP-PEAP
auth MSCHAPV2 “auth=PAP”/PAP/MSCHAPV2 — Defines the phase 2 (inner) authentication method, only applicable if eap_type is peap or ttls
identity (none) EAP identity to send during authentication
password (none) Password to send during EAP authentication
ca_cert (none) Specifies the path the CA certificate used for authentication
client_cert (none) Specifies the client certificate used for the authentication
priv_key (none) Specifies the path to the private key file used for authentication, only applicable if eap_type is set to tls
priv_key_pwd (none) Password to unlock the private key file, only works in conjunction with priv_key

When using WPA Enterprise type PEAP with Active Directory Servers, the “auth” option must be set to “auth=MSCHAPV2” or “auth=PAP”.

WPA key reinstallation attack workaround

Name Default Description
wpa_disable_eapol_key_retries 0 Workaround for key reinstallation attacks (requires LEDE 17.01.4 or higher)

Complete description copied from upstream hostapd.conf example:

Note that this workaround can't prevent attacks against Tunneled Direct-Link Setup (TDLS). You may also want to add the option tdls_prohibit=1 in order to make such an attack more complicated:

Name Default Description
tdls_prohibit 0 Prohibit the use of TDLS on the network (complicates key reinstallation attacks against TDLS) (requires hostapd/wpad 2016-12-19-ad02e79d-7 or higher)

WPS options

Listing of Wi-Fi Protected Setup related options.

Support for WPS is provided by packages wpad and hostapd-utils. Default package wpad-mini is not enough.

WPS is possible only when encryption PSK/PSK2 is selected.

Name Type Required Default Description
wps_config list no (none) List of configuration methods. Currentlly supported methods are: push_button.
wps_device_name string no LEDE AP User-friendly description of device; up to 32 octets encoded in UTF-8.
wps_device_type string no 6-0050F204-1 Primary device type. Examples: 1-0050F204-1 (Computer / PC), 1-0050F204-2 (Computer / Server), 5-0050F204-1 (Storage / NAS), 6-0050F204-1 (Network Infrastructure / AP )
wps_label boolean no 0 Enable label configuration method.
wps_manufacturer string no lede-project.org The manufacturer of the device (up to 64 ASCII characters).
wps_pushbutton boolean no 0 Enable push-button configuration method.
wps_pin string no none The PIN to use with WPS-PIN (only in external registrar mode?)

Minimal steps needed to get WPS running:

After rebooting, instead of pushing the WPS button, you can manually initiate the WPS process (which is safer than using the button if it doubles as a reset button):

When using WPS-PIN:

After rebooting, the WPS PIN needs to be given to hostapd each time a station tries to connect. The PIN may NOT be used multiple times, as an active attacker can recover half of it during each try. The “any” keyword can be replaced by the specific stations EUUID, as printed in hostapd log.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *