- Беспроводная сеть в Linux
- Сети с Wireless-Tools для Linux
- Использование команды iwconfig для конфигурации пакета wireless-tools
- Сохранение конфигурации wireless-tools
- Fedora / RedHat
- Debian / Ubuntu
- Конфигурирование схемы шифрования WEP
- Генерация ключа WEP
- Конфигурирование ключа WEP для Fedora / RedHat
- Конфигурирование ключа WEP для Debian / Ubuntu
- Шифрование WPA
- Установка суппликанта шифрования WPA
- Файл wpa_supplicant.conf
- Дальнейшие шаги по шифрованию WPA — Fedora / RedHat
- Дальнейшие шаги по шифрованию WPA — Debian / Ubuntu
- wpa_supplicant
- Contents
- Installation
- Overview
- Connecting with wpa_cli
- Connecting with wpa_passphrase
- Advanced usage
- Configuration
- Connection
- Manual
- At boot (systemd)
- wpa_cli action script
- Roaming
- Troubleshooting
- nl80211 driver not supported on some hardware
- Problem with mounted network shares (cifs) and shutdown
- Password-related problems
- Problems with eduroam and other MSCHAPv2 connections
- Connections to pure WPA3-SAE access points
- Connections to mixed WPA2-PSK/WPA3-SAE access points
Беспроводная сеть в Linux
Оригинал: «Linux Wireless Networking»
Автор: Петер Харрисон (Peter Harrison)
Перевод: Н.Ромоданов
Дата перевода: 10.09.2009 г.
Сети с Wireless-Tools для Linux
Пакет Wireless Tools для Linux, установленный по умолчанию, вероятно, наиболее соответствует требования стандарта 802.11a/b.
Использование команды iwconfig для конфигурации пакета wireless-tools
После того, как ваша сетевая плата, совместимая с Linux, будет установлена физически, вам потребуется сконфигурировать IP платы и выполнить настройки беспроводной сети прежде, чем можно будет использовать пакет Wireless Tools.
Вы можете сконфигурировать IP вашей сетевой платы также, как если бы это было обычное Ethernet устройство. После выполнения команды ifup сетевая плата станет активной, но не будет работать должным образом, поскольку еще не были сконфигурированы настройки беспроводной сети.
Наиболее часто используемая команда в пакете Wireless Tools – iwconfig, которую Вы можете использовать для конфигурирования большинства параметров беспроводной сети, в том числе задания SSID и выбора режима работы. Выбор режима работы Managed означает, что в сети имеется беспроводная точка доступа WAP, а Ad-hoc указывает, что ее нет.
Например, если беспроводная сетевая плата имеет имя eth0, а ESSID вашей сети – homenet, то команды будут следующими:
Теперь ваша сетевая плата должна стать полностью функциональной. Вам нужно будет запускать эти команды iwconfig всякий раз, когда Вы используете команду ifup. Однако, возникает проблема – не забывать это делать. В следующем разделе будет показано, как сделать изменения, внесенные командой iwconfig, постоянными.
Сохранение конфигурации wireless-tools
После того, как Вы проверили свою конфигурацию ad-hoc, вам потребуется сохранить сделанные изменения. Способы сохранение изменений слегка варьируются в зависимости от используемого дистрибутива.
Fedora / RedHat
Конфигурация беспроводной сети в Fedora / RedHat потребует внесения нескольких дополнительных строк в конфигурационные файлы вашей сетевой платы.
1. Сконфигурируйте файл /etc/sysconfig/network-scripts/ifcfg-eth0 обычным образом, как если это была обычная сетевая плата Ethernet.
Прим. пер.: DHCP Version — вариант для динамически распределяемых ip адресов; Fixed IP Version – вариант с фиксированными ip адресами.
2. Для того, чтобы указать, что сетевая плата беспроводная, в конце добавьте приведенные ниже инструкции: укажите используемый ESSID (в нашем случае homenet) и в качестве режима работы выберите Managed (точка доступа WAP присутствует на сети) или Ad-hoc (точки доступа нет). «Managed» является наиболее вероятным вариантом в случае, если в вашей сети имеется беспроводный маршрутизатор или точка доступа.
Если Вы используете беспроводный маршрутизатор и сетевую плату стандарта 802.11g, то можно указать максимальную скорость, равную 54Мбит/сек – максимальной скорости передачи данных, обеспечиваемую этим протоколом. Если нет, то по умолчанию будет использоваться скорость, равная 11 Мбит/сек – максимальная скорость более медленных протоколов. Сетевая плата автоматически использует тип протокола с точкой доступа WAP. Вам нужно просто указать максимальную скорость.
Эти команды нужны только в главном интерфейсном файле. Они не нужны для IP алиасов. При использовании команд ifup и ifdown ваша беспроводная сетевая плата должна функционировать точно также, как и обычная сетевая плата Ethernet.
Debian / Ubuntu
Конфигурация в системах Debian / Ubuntu требует добавления в файл /etc/network/interfaces правильного параметра wireless-essid.
В этом примере интерфейс eth1 использует для идентификатора ESSID значение homenet, тогда как интерфейс eth0 использует для идентификатора ESSID значение jamrock.
Конфигурирование схемы шифрования WEP
В Linux поддерживаются обе схемы шифрования WEP и WPA. Ниже рассказывается, как Вы можете сконфигурировать их на своей системе.
Генерация ключа WEP
Для шифрования WEP требуется ключ шифрования, который Вы можете выбрать самостоятельно или можете сгенерировать случайным образом с помощью команды dd так, как это показано ниже:
По умолчанию WEP для Linux использует 40 битовый ключ, форматированный в шестнадцатеричной нотации, т.е. посредством цифр от 0 до 9 и букв от A до F. Следовательно, в приведенном выше примере требуется задать количество байтов равным 5, и в результате будет сгенерировано в два раза больше (десять) шестнадцатеричных символов. В таблице 13.1 показано число байтов, требуемое для генерации ключей различной длины, и соответствующее число шестнадцатеричных символов, которые должны быть в ключе.
Таблица 13-1 Соотношение числа байтов и длин ключа WEP
Длина ключа (биты) | Количество байт | Количество шестнадцатеричных символов |
---|---|---|
40 | 5 | 10 |
64 | 8 | 16 |
104 | 13 | 26 |
128 | 16 | 32 |
152 | 19 | 28 |
232 | 29 | 58 |
256 | 32 | 64 |
Если Вы решили сделать свой собственный ключ, то используйте правильное количество шестнадцатеричных цифр.
Конфигурирование ключа WEP для Fedora / RedHat
С помощью команды iwconfig ваш ключ WEP может быть временно добавлен в конфигурацию вашей сетевой платы. Убедитесь в том, что среди символов ключа нет запятых или иных нешестнадцатеричных символов. Всего должно быть десять символов:
Те же самые правила (отсутствие запятых или других нешестнадцатеричных символов среди десяти символов ключа) применяются, когда для шифрования используется файл /etc/sysconfig/network-scripts :
Замечание: Использование файлов ключей в директории /etc/sysconfig/network-scripts поддерживается только в новых версиях Fedora . Формат файла тот же самый, как и в старых вариантах конфигурационных фалов интерфейса. Помните, в конфигурационном файле интерфейса не поддерживается использование инструкции KEY.
Конфигурирование ключа WEP для Debian / Ubuntu
Конфигурация в системах Debian / Ubuntu требует добавления в файл /etc/network/interfaces правильного параметра wireless-essid.
В этом примере указывается, что должны использоваться значение нашего ключа WEP, равное 967136deac, и ESSID, равный homenet, и они будут использоваться сразу, как только будет активирован беспроводный интерфейс eth1.
Шифрование WPA
В Linux шифрование WPA основывается на демоне- суппликанте, который от имени операционной системы запрашивает проверку подлинности доступа, а также выполняет шифрование данных. Он запускается независимо от демона сети и, поэтому, для шифрования WPA сетевые интерфейсы вообще не конфигурируются.
blockqoute>Прим.перев.: Слово «supplicant» переводится как «проситель». Подходящего компьютерного термина для перевода я не нашел, поэтому оставляю название в виде транслитерации английского термина. Домашняя страница проекта WPA Supplicant — http://hostap.epitest.fi/wpa_supplicant/ blockqoute>
Установка суппликанта шифрования WPA
Установка проста. Установите пакет RPM wpa_supplicant или пакет DEB wpasupplicant. Если вам нужно вспомнить, как это делается, смотрите Главу 6 «Установка программного обеспечения Linux» , где это подробно описано.
Файл wpa_supplicant.conf
Основным конфигурационным файлом суппликанта WPA является файл /etc/wpa_supplicant/wpa_supplicant.conf. Его конфигурирование хорошо задокументировано, с примерами, в страницах man.
Замечание: В Debian / Ubuntu файл может не создаваться во время установки и вам следует его создать вручную следующим образом:
В этой главе мы сфокусируемся только на простом методе шифрования PSK WPA, другие методы выходят за рамки рассмотрения настоящее книги.
В этом примере мы установим идентификатор SSID равным homenet и будем использовать WPA-PSK шифрование с ключом шифрования «ketchup_and_mustard».
Если Вы обеспокоены, что люди могут прочитать ваш файл wpa_supplicant.conf, то зашифруйте ключ PSK с помощью команды wpa_passphrase, которая сгенерирует пример конфигурации. Она потребует в качестве аргументов идентификатор SSID и незашифрованный ключ. В этом примере мы видим, что незашифрованную строку psk=»ketchup_and_mustard» можно заменить зашифрованным эквивалентом, в котором не используются кавычки.
Замечание: Единственное место, где должен быть определен ключ шифрования, это конфигурационный файл WPA.
Дальнейшие шаги по шифрованию WPA — Fedora / RedHat
Суппликант WPA также использует файл /etc/sysconfig/wpa_supplicant, в котором определяется, какие интерфейсы должны контролироваться и какие для этого драйвера должны использоваться.
В этом примере WPA следует применять к интерфейсу eth0 и по умолчанию использовать драйвер «wext».
Здесь мы видим, что WPA сконфигурирован для wlan0, создаваемого с помощью драйвера ndiswrapper.
Дальнейшую подсказку, касающуюся файла wpa_supplicant, можно получить из страниц man.
После того, как Вы завершили редактирование конфигурационных файлов, нужно сразу стартовать демон суппликанта WPA с тем, чтобы настройки стали активными. Не забудьте с помощью команды chkconfig сделать эту активацию постоянной.
Наконец сконфигурируйте свою сетевую плату также, как и для беспроводной сети, но без идентификатора SSID и ключа шифрования, поскольку эта информация будет подаваться через суппликант WPA.
При решении любых проблем, с которыми Вы можете встретиться, пожалуйста, обращайтесь в раздел по устранению проблем, имеющийся в настоящей главе.
Дальнейшие шаги по шифрованию WPA — Debian / Ubuntu
Суппликант WPA можно вызвать из командной строки. В системах Debian / Ubuntu нужно модифицировать файл /etc/network/interfaces и включить в него параметр pre-up, за которым будет следовать допустимый набор команд суппликанта WPA. В данном примере с помощью опции «-c» дается ссылка на файл /etc/wpa_supplicant/wpa_supplicant.conf, а нужный интерфейс определяется с помощью опции «-i». Затем используется параметр post-down, в котором определяются команды, останавливающие работу демона суппликанта WPA при остановке интерфейса eth1.
При решении любых проблем, с которыми Вы можете встретиться, пожалуйста, обращайтесь в раздел по устранению проблем, имеющийся в настоящей главе.
Источник
wpa_supplicant
wpa_supplicant is a cross-platform supplicant with support for WEP, WPA, WPA2 and WPA3 (IEEE 802.11i). It is suitable for desktops, laptops and embedded systems. It is the IEEE 802.1X/WPA component that is used in the client stations. It implements key negotiation with a WPA authenticator and it controls the roaming and IEEE 802.11 authentication/association of the wireless driver.
Contents
Installation
Install the wpa_supplicant package, which includes the main program wpa_supplicant, the passphrase tool wpa_passphrase, and the text front-end wpa_cli.
Optionally, also install the official wpa_supplicant_gui AUR which provides wpa_gui, a graphical front-end for wpa_supplicant, or wpa-cute AUR which is a fork from an earlier version of wpa_gui with a couple of fixes and improvements.
Overview
The first step to connect to an encrypted wireless network is having wpa_supplicant obtain authentication from a WPA authenticator. In order to do this, wpa_supplicant must be configured so that it will be able to submit the correct credentials to the authenticator.
Once you are authenticated you need to assign an IP address, see Network configuration#IP addresses.
Connecting with wpa_cli
This connection method allows scanning for available networks, making use of wpa_cli, a command line tool which can be used to configure wpa_supplicant. See wpa_cli(8) for details.
In order to use wpa_cli, a control interface must be specified for wpa_supplicant, and it must be given the rights to update the configuration. Do this by creating a minimal configuration file:
Now start wpa_supplicant with:
At this point run:
This will present an interactive prompt ( > ), which has tab completion and descriptions of completed commands.
Use the scan and scan_results commands to see the available networks:
To associate with MYSSID , add the network, set the credentials and enable it:
If the SSID does not have password authentication, you must explicitly configure the network as keyless by replacing the command set_network 0 psk «passphrase» with set_network 0 key_mgmt NONE .
Finally save this network in the configuration file and quit wpa_cli:
Once association is complete, you must obtain an IP address, for example, using dhcpcd.
Connecting with wpa_passphrase
This connection method allows quickly connecting to a network whose SSID is already known, making use of wpa_passphrase, a command line tool which generates the minimal configuration needed by wpa_supplicant. For example:
This means that wpa_supplicant can be associated with wpa_passphrase and started with:
Finally, you should obtain an IP address, see Network configuration#IP addresses.
Advanced usage
For networks of varying complexity, possibly employing extensive use of EAP, it will be useful to maintain a customised configuration file. For an overview of the configuration with examples, refer to wpa_supplicant.conf(5) ; for details on all the supported configuration parameters, refer to the example file /usr/share/doc/wpa_supplicant/wpa_supplicant.conf .[1]
Configuration
As explained in #Connecting with wpa_passphrase, a basic configuration file can be generated with:
This will only create a network section. A configuration file with also the ability of #Connecting with wpa_cli and some other common options may look like:
If security is not a concern, the passphrase can also be defined in clear text in the network section by enclosing it in quotes:
If the network does not have a passphrase, e.g. a public Wi-Fi:
To connect to a WPA-Enterprise network, see #802.1x/radius.
Further network blocks may be added manually, or using wpa_cli as illustrated in #Connecting with wpa_cli. In order to use wpa_cli, a control interface must be set with the ctrl_interface option. Setting ctrl_interface_group=wheel allows users belonging to such group to execute wpa_cli. This setting can be used to enable users without root access (or equivalent via sudo etc) to connect to wireless networks. Also add update_config=1 so that changes made with wpa_cli to example.conf can be saved. Note that any user that is a member of the ctrl_interface_group group will be able to make changes to the file if this is turned on.
fast_reauth=1 and ap_scan=1 are the wpa_supplicant options active globally at the time of writing. Whether you need them, or other global options too for that matter, depends on the type of network to connect to. If you need other global options, simply copy them over to the file from /usr/share/doc/wpa_supplicant/wpa_supplicant.conf .
Alternatively, wpa_cli set can be used to see options’ status or set new ones. Multiple network blocks may be appended to this configuration: the supplicant will handle association to and roaming between all of them. The strongest signal defined with a network block usually is connected to by default, one may define priority= to influence behaviour. For example to auto-connect to any unsecured network as a fallback with the lowest priority:
Once you have finished the configuration file, you can optionally use it as a system-wide or per-interface default configuration by naming it according to the paths listed in #At boot (systemd). This also applies if you use additional network manager tools, which may rely on the paths (for example Dhcpcd#10-wpa_supplicant).
Connection
Manual
First start wpa_supplicant command, whose most commonly used arguments are:
- -B — Fork into background.
- -c filename — Path to configuration file.
- -i interface — Interface to listen on.
- -D driver — Optionally specify the driver to be used. For a list of supported drivers see the output of wpa_supplicant -h .
- nl80211 is the current standard, but not all wireless chip’s modules support it.
- wext is currently deprecated, but still widely supported.
See wpa_supplicant(8) for the full argument list. For example:
followed by a method to obtain an ip address manually as indicated in the #Overview, for example:
At boot (systemd)
The wpa_supplicant package provides multiple systemd service files:
- wpa_supplicant.service — uses D-Bus, recommended for NetworkManager users.
- wpa_supplicant@interface.service — accepts the interface name as an argument and starts the wpa_supplicant daemon for this interface. It reads a /etc/wpa_supplicant/wpa_supplicant-interface.conf configuration file. Useful when using systemd-networkd.
- wpa_supplicant-nl80211@interface.service — also interface specific, but explicitly forces the nl80211 driver (see below). The configuration file path is /etc/wpa_supplicant/wpa_supplicant-nl80211-interface.conf .
- wpa_supplicant-wired@interface.service — also interface specific, uses the wired driver. The configuration file path is /etc/wpa_supplicant/wpa_supplicant-wired-interface.conf .
To enable wireless at boot, enable an instance of one of the above services on a particular wireless interface. For example, enable the wpa_supplicant@interface systemd unit.
Now choose and enable an instance of a service to obtain an ip address for the particular interface as indicated in the #Overview. For example, enable the dhcpcd@interface systemd unit.
802.1x/radius
To connect a wired adapter using 802.1x/radius you will need to specify some configurations and enable the necessary service for the adapter. This is useful for headless servers using networkd.
Replace adapter with the wired adapter you wish to connect, and adapt the settings to match your 802.1x/radius requirements.
Since this file is storing a plaintext password, chown it to root:root and chmod it to 600 .
To use the hash instead of the plaintext password, you can use the hash keyword:
To hash your password:
After invoking the command above, provide your plain password and then press Ctrl+d .
Before running the wpa_supplicant-wired@adapter.service service, make sure to set the device down:
wpa_cli action script
wpa_cli can run in daemon mode and execute a specified script based on events from wpa_supplicant. Two events are supported: CONNECTED and DISCONNECTED . Some environment variables are available to the script, see wpa_cli(8) for details.
The following example will use desktop notifications to notify the user about the events:
Remember to make the script executable, then use the -a flag to pass the script path to wpa_cli:
Roaming
When connected to a wireless network with multiple access points, wpa_supplicant is typically responsible for roaming between access points. Choosing a new access point requires wpa_supplicant to perform a scan of available networks, which causes a brief interruption in connectivity to the current access point while the wireless radio scans other frequencies. After a scan, if wpa_supplicant detects a closer access point (BSSID) in the current network (SSID), in terms of signal strength (RSSI), it will re-associate to the closer access point.
The default configuration of wpa_supplicant has relatively timid roaming: it will rescan only when the association to the current access point is lost. This means that, if a client moves far away from its current access point, but not far enough to completely lose signal, the client will keep using the weak signal instead of roaming to a closer access point.
To make wpa_supplicant more aggressive about roaming, set the bgscan parameter in the configuration file, such as:
The above example will cause wpa_supplicant to scan every 30 seconds when the signal is weak (below -70), and every 3600 seconds otherwise. bgscan can be specified either in specific network blocks or globally for all networks.
Troubleshooting
nl80211 driver not supported on some hardware
On some (especially old) hardware, wpa_supplicant may fail with the following error:
This indicates that the standard nl80211 driver does not support the given hardware. The deprecated wext driver might still support the device:
If the command works to connect, and the user wishes to use systemd to manage the wireless connection, it is necessary to edit the wpa_supplicant@.service unit provided by the package and modify the ExecStart line accordingly:
Problem with mounted network shares (cifs) and shutdown
When you use wireless to connect to network shares you might have the problem that the shutdown takes a very long time. That is because systemd runs against a 3 minute timeout. The reason is that WPA supplicant is shut down too early, i.e. before systemd tries to unmount the share(s). A bug report suggests a work-around by editing the wpa_supplicant@.service as follows:
Password-related problems
wpa_supplicant may not work properly if directly passed via stdin particularly long or complex passphrases which include special characters. This may lead to errors such as failed 4-way WPA handshake, PSK may be wrong when launching wpa_supplicant .
In order to solve this try using here strings wpa_passphrase or passing a file to the -c flag instead:
In some instances it was found that storing the passphrase cleartext in the psk key of the wpa_supplicant.conf network block gave positive results (see [2]). However, this approach is rather insecure. Using wpa_cli to create this file instead of manually writing it gives the best results most of the time and therefore is the recommended way to proceed.
Problems with eduroam and other MSCHAPv2 connections
Ensure that your config uses
with a capital «v» (see FS#51358). You could even omit this setting entirely, since MSCHAPV2 is the default.
Connections to pure WPA3-SAE access points
Make sure to define the following within the network block of the config to enable connections to pure WPA3 access points:
Connections to mixed WPA2-PSK/WPA3-SAE access points
Mixed WPA2-PSK/WPA3-SAE access points will require an alternative setting for key_mgmt as shown below:
Источник