Настройка dnsmasq и resolvconf
Если используете Network Manager, то настройте dnsmasq.
Скопируйте конфиг:
В /etc/dnsmasq.conf пропишите:
Это не рекомендуется делять. Можно задать глобально DNS. Для этого создайте файл /etc/dnsmasq.d/dns
Но лучше всегда задавать DNS параметры через менеджер подключений, такие как wicd или network manager. Чтобы он через resolvconf обновлял DNS сервера.
Если вы хотите прописать свои хосты в системе, вы можете использовать файл /etc/hosts или создать новый файл в папке /etc/dnsmasq.d/examle.domain со следующим содержанием:
Данный файл говорит dnsmasq резолвить домен .examle, учитывая wildcard запросы.
Также dnsmasq переодически будет проверять файл /var/run/dnsmasq/resolv.conf на наличие новых записей. Wicd и Network Manager будут помещать туда DNS сервера при подключении.
Настройка для домашней сети
Теперь самое интересное — настройка. Этот процесс задокументирован для Arch Wiki, и Gentoo Wiki, но всех деталей там естественно нет.
Программа обычно ставится в директорию , и наша задача — правильно настроить конфигурационный файл , и привязать его к автозапуску беспроводного сетевого интерфейса.
Начнем с . Если вы подключаетесь из дома к WPA/WPA2, то скорее всего используете пароль для WiFi соединения, что соответствует режиму . Мы не будет рассматривать варианты с WEP шифрованием, так как оно ненамного лучше открытой сети.
Возьмем типовой конфиг из документации. Например такой.
Первая строка необходима, без программа даже не запустится. GROUP=wheel нужно для того, чтобы запускать из под обычного пользователя в графическом интерфейсе wpa_gui, но это не наш путь. Поэтому меняем на рутовый .
Каждой сети в файле настроек должен соответствовать блок . Покопавшись в исходниках, обнаружил нашел годное писание переменной в файле , а в мануале и руководстве пользователя ее описание очень скудное.
Остальные опции взяты из руководства конфиг файла.
- — The Basic Service Set Identifier (BSSID), физический адрес точки доступа.
- — Протоколы аутентификации.
- — Для WPA2 укажите CCMP, а для WPA — TKIP.
- — WPA/WPA2.
- — Хэш пароля PreShared Key.
Создаем хэш пароля для :
Все готово, чтобы создать конфиг сети. Итоговый файл должен выглядеть как-то так.
Верные значения для , , и можно определить, сканируя беспроводную сеть.
Команда из набора устарела, вместо нее сейчас .
NetworkManager
For the average desktop user, the easiest way to configure your network is to install the GUI frontend for NetworkManager that corresponds to your desktop. NetworkManager itself is a frontend for different network backends (wpa_supplicant by default) that abstracts away the configuration and simplifies it. Your wireless interface should not be referenced within Debian’s /etc/network/interfaces file.
NetworkManager Frontends
NetworkManager on GNOME
As of GNOME 3, integration with NetworkManager is baked into GNOME Shell, and will appear in the settings and as an icon in the top-right of your screen as long as it’s running.
Open the «Networks» section of your settings, select your network in the list, enter the password as prompted, and you should be ready to surf the web.
The network-manager-gnome package still exists and provides a systray applet for other desktops, but will not make any difference with GNOME 3.
See the NetworkManager page for frequently asked questions, documentation and support references.
NetworkManager on KDE Plasma
The KDE Plasma task should bring in plasma-nm during system installation without any extra steps being required, and its usage should be intuitive. If you aren’t sure how to use it though, or if you installed the desktop manually and might not have brought it in, the following will likely be useful.
-
Ensure your user account is a member of the netdev group.
-
Install the plasma-nm package.
- Restart your Plasma session (most easily by logging out and logging back in).
- A new applet (with a traditional «no Wi-Fi signal» icon) will appear in the system tray. Click this icon.
- Neighboring wireless networks with a broadcasted SSID should be listed:
- Click on the desired network’s name.
- If the network uses WPA encryption with a password (aka passphrase/pre-shared key), you will be prompted to enter it. After providing, click the «Connect» button.
- The wireless network connection will be activated.
If the desired network is not listed (e.g. SSID not broadcast/hidden):
- Click «Connect to Other Wireless Network…».
- Enter the network’s name in «Name (ESSID)».
- Tick «Use Encryption» if in use on the network.
- Select the encryption method used (usually «WPA Personal»).
- Enter the passphrase/pre-shared key at «Password».
- Select «WPA 1» or «WPA 2» for the protocol version, as used by the network.
- Click the «Connect» button to activate the wireless network connection.
See the NetworkManager page for frequently asked questions, documentation and support references.
NetworkManager on a generic desktop/headless session
If there is no GUI frontend available, the «nmcli» and «nmtui» commands are available as CLI and TUI frontends respectively for NetworkManager.
Troubleshooting & Tips for NetworkManager
WiFi can scan, but not connect using NetworkManager (Debian 9 Stretch)
If you find that your wireless network device can scan, but will not complete connecting, try turning off MAC address randomization.
Write inside /etc/NetworkManager/NetworkManager.conf:
wifi.scan-rand-mac-address=no
After doing this, restart NetworkManager with service NetworkManager restart
Setting up a WiFi hotspot
In recent years, NetworkManager is sophisticated enough to set up a WiFi hotspot that «just works» (i.e. sets up a local private net, with DHCP and IP forwarding). In some desktops, such as KDE Plasma, a button to create a hotspot is visible in the network applet if two separate wireless network interfaces are present. Alternatively, it can be created manually with a command similar to:
nmcli dev wifi hotspot ifname wlp4s0 ssid test password "test1234"
Source: https://unix.stackexchange.com/a/384513
Changing the backend
It’s possible to replace wpa_supplicant with IWD in NetworkManager in Debian 10 and newer, though Debian 11 is recommended for the best experience as there are known issues with the old version of IWD present in Debian 10. For more information on how to switch, see NetworkManager/iwd.
Редактирование /etc/wpa_supplicant/wpa_supplicant.conf
Для большинства ваших сетей потребуется всего одна запись в wpa_supplicant.conf, которая выглядит следующим образом:
network={ ssid="MYNETWORKSSID" scan_ssid=1 key_mgmt=WPA-PSK psk="MYNETWORKPSK" }
Очевидно, что вы замените MYNETWORKSSI и MYNETWORKPS своими значениями. Пароль для вашей зашифрованной сети должен быть кодирован в шестнадцатиричную строку.
Чтобы получить эти значения, воспользуемся утилитой: wpa_passphrase ( wpa_passphrase , ssid — имя нашей точки доступа, passphrase — пароль). Например:
~$ wpa_passphrase mynetworkssid mypassword network={ ssid="mynetworkssid" #psk="mypassword" psk=28202e0efd235b16f2bbad175758143c856d2bf8a112c878b57e25b8a7f60765 }
последняя строка (psk) содержит hex-код, который требуется для связи с сетью.
Примечание: в прмере выше используется парольная фраза, а хеш код не задан. Подобный подход работает в CentOS 5. В CentOS 6 необходимо также задать и hex-код.
Краткое описание руководства
В данном руководстве объясняется, как подключить компьютер к сети при помощи конфигурационных файлов и консольных утилит. Основная цель — рассказать о различных способах подключения к интернету без использования GUI (графического интерфейса). Руководство не затрагивает таких тем, как настройка сетевых фильтров или, например, собственных точек доступа Wi-Fi. Подразумевается, что существует некий, предоставленный провайдером, способ подключения к интернету, для использования которого и необходимо выполнить приведенные ниже действия.
В руководстве приведены примеры редактирования конфигурационных файлов с помощью текстовых редакторов «nano» и «gedit»
Обратите внимание на то, что первый редактор запускается в терминале и может быть использован как при запуске Ubuntu с графическим интерфейсом, так и без него, а «gedit» можно использовать только при включенной графической среде
Генерация пароля (ключа) wpa-psk на ubuntu
В терминале нам нужно ввести данную команду
wpa_passphrase troyan 1237876535
где troyan — это название wi-fi сети, а 1237876535 это пароль от вашей wi-fi сетиПосле того как вы это сделаете консоль вам выдаст примерно такой результат:
network={ ssid="troyan" #psk="9261745831" psk=73625469f53a89c6d0728a4c15766b519d80dcce742a3169657cec8a2a62848c }
Запомним эти данные, перед генерацией wpa-psk ключа убедитесь что вы правильно прописали ваш не зашифрованный пароль который сгенерировался в ключ ( иногда многие бьются часами над проблемой с подключением из-за опечатки в пароле ).
Подключение к Wi-Fi
В терминале прописываем
sudo nano /etc/network/interfaces
# interfaces(5) file used by ifup(8) and ifdown(8) auto lo iface lo inet loopback # Все что ниже этих настоек меняем на эти: # если у вас другой идентификатор сетевой карты замените на свой auto wlp13s0 # если у вас другой идентификатор сетевой карты замените на свой iface wlp13s0 inet dhcp # название сети замените на свое wpa-ssid troyan # ключ wpa-psk - замените на тот что сгенерировали wpa-psk 73625469f53a89c6d0728a4c15766b519d80dcce742a3169657cec8a2a62848c
Все что выделено красным рекомендовано заменить на свое значение. В большинстве своем идентефикатор сетевой карты wi-fi совпадает с моим возможно менять не понадобится. Будьте внимательны. Теперь перезагрузим сеть
sudo /etc/init.d/networking restart
Если все сделали без ошибок то все заработает. Проверено на 6 ноутбуках данная конфигурация работает железно. Какие либо другие данные в конфигурацию вносить необязательно.
OVERVIEW
Wireless networks do not require physical access to the network equipment
in the same way as wired networks. This makes it easier for unauthorized
users to passively monitor a network and capture all transmitted frames.
In addition, unauthorized use of the network is much easier. In many cases,
this can happen even without user’s explicit knowledge since the wireless
LAN adapter may have been configured to automatically join any available
network.
Link-layer encryption can be used to provide a layer of security for
wireless networks. The original wireless LAN standard, IEEE 802.11,
included a simple encryption mechanism, WEP. However, that proved to
be flawed in many areas and network protected with WEP cannot be consider
secure. IEEE 802.1X authentication and frequently changed dynamic WEP keys
can be used to improve the network security, but even that has inherited
security issues due to the use of WEP for encryption. Wi-Fi Protected
Access and IEEE 802.11i amendment to the wireless LAN standard introduce
a much improvement mechanism for securing wireless networks. IEEE 802.11i
enabled networks that are using CCMP (encryption mechanism based on strong
cryptographic algorithm AES) can finally be called secure used for
applications which require efficient protection against unauthorized
access.
wpa_supplicant is an implementation of
the WPA Supplicant component, i.e., the part that runs in the
client stations. It implements WPA key negotiation with a WPA
Authenticator and EAP authentication with Authentication
Server. In addition, it controls the roaming and IEEE 802.11
authentication/association of the wireless LAN driver.
wpa_supplicant is designed to be a
«daemon» program that runs in the background and acts as the
backend component controlling the wireless
connection. wpa_supplicant supports separate
frontend programs and an example text-based frontend,
wpa_cli, is included with
wpa_supplicant.
Before wpa_supplicant can do its work, the network interface
must be available. That means that the physical device must be
present and enabled, and the driver for the device must be
loaded. The daemon will exit immediately if the device is not already
available.
After wpa_supplicant has configured the
network device, higher level configuration such as DHCP may
proceed. There are a variety of ways to integrate wpa_supplicant
into a machine’s networking scripts, a few of which are described
in sections below.
The following steps are used when associating with an AP
using WPA:
- •
-
wpa_supplicant requests the kernel
driver to scan neighboring BSSes - •
-
wpa_supplicant selects a BSS based on
its configuration - •
-
wpa_supplicant requests the kernel
driver to associate with the chosen BSS - •
-
If WPA-EAP: integrated IEEE 802.1X Supplicant
completes EAP authentication with the
authentication server (proxied by the Authenticator in the
AP) - •
-
If WPA-EAP: master key is received from the IEEE 802.1X
Supplicant - •
-
If WPA-PSK: wpa_supplicant uses PSK
as the master session key - •
-
wpa_supplicant completes WPA 4-Way
Handshake and Group Key Handshake with the Authenticator
(AP) - •
-
wpa_supplicant configures encryption
keys for unicast and broadcast - •
- normal data packets can be transmitted and received
AVAILABLE DRIVERS
A summary of available driver backends is below. Support for each
of the driver backends is chosen at wpa_supplicant compile time. For a
list of supported driver backends that may be used with the -D option on
your system, refer to the help output of wpa_supplicant
(wpa_supplicant -h).
- nl80211
-
Uses the modern Linux nl80211/cfg80211 netlink-based
interface (most new drivers). - wext
-
Uses the legacy Linux wireless extensions ioctl-based
interface (older hardware/drivers). - wired
- wpa_supplicant wired Ethernet driver
- roboswitch
- wpa_supplicant Broadcom switch driver
- bsd
- BSD 802.11 support (Atheros, etc.).
- ndis
- Windows NDIS driver.
Troubleshooting
In case it does not work as expected try some of the following and analyze the output.
Run wpa_supplicant in debug mode
Be sure to stop any running instance of the supplicant:
Something like the following options can be used for debugging (click «Expand» to view the output below):
wpa_supplicant v2.2 random: Trying to read entropy from /dev/random Successfully initialized wpa_supplicant Initializing interface 'wlp8s0' conf '/etc/wpa_supplicant/wpa_supplicant.conf' driver 'nl80211' ctrl_interface '/var/run/wpa_supplicant' bridge 'N/A' Configuration file '/etc/wpa_supplicant/wpa_supplicant.conf' -> '/etc/wpa_supplicant/wpa_supplicant.conf' Reading configuration file '/etc/wpa_supplicant/wpa_supplicant.conf' ctrl_interface='DIR=/var/run/wpa_supplicant GROUP=wheel' update_config=1 Line: 6 - start of a new network block
FILE for usage with the
modules_wlan0="wpa_supplicant" wpa_supplicant_wlan0="-Dnl80211 -d -f /var/log/wpa_supplicant.log" config_wlan0="dhcp"
Now, within one terminal issue a tail command to monitor output and restart the net.wlan0 device in another:
Usage
Using wpa_cli
Wpa_supplicant also has a command-line user interface. Typing wpa_cli starts its interactive mode with tab-completion. Typing at this prompt will list the commands available (click «Expand» to view the output for the wpa_cli command below):
wpa_cli v2.5 Copyright (c) 2004-2015, Jouni Malinen <[email protected]> and contributors This software may be distributed under the terms of the BSD license. See README for more details. Selected interface 'wlan0' Interactive mode > scan OK > scan_results bssid / frequency / signal level / flags / ssid 01:23:45:67:89:ab 2437 0 hotel-free-wifi > add_network 0 > set_network 0 ssid "hotel-free-wifi" OK > set_network 0 psk "password" OK > enable_network 0 OK <3>CTRL-EVENT-SCAN-RESULTS <3>WPS-AP-AVAILABLE <3>Trying to associate with 01:23:45:67:89:ab (SSID='hotel-free-wifi' freq=2437 MHz) <3>Associated with 01:23:45:67:89:ab <3>WPA: Key negotiation completed with 01:23:45:67:89:ab <3>CTRL-EVENT-CONNECTED - Connection to 01:23:45:67:89:ab completed > save_config OK > quit
More details on how to connect can be found in the Arch Linux wiki.
Using wpa_passphrase
wpa_supplicant includes a tool to quickly write a network block from the command line for pre-shared key (WPA-PSK aka password) networks, wpa_passphrase.
The SSID is required. If omitted, the passphrase can be entered when prompted.
The resulting output can then be copied or piped to /etc/wpa_supplicant/wpa_supplicant.conf.
Editing manually
Of course, the configuration file /etc/wpa_supplicant/wpa_supplicant.conf could also be edited manually. However this can be very laborious if the computer needs to connect to many different access points.
Examples can be found in man 5 wpa_supplicant.conf and /usr/share/doc/wpa_supplicant-2.4-r3/wpa_supplicant.conf.bz2.
WPA2 with wpa_supplicant
Connecting to any wireless access point serving YourSSID
FILE
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=wheel #ap_scan=0 #update_config=1 network={ ssid="YourSSID" psk="your-secret-key" scan_ssid=1 proto=RSN key_mgmt=WPA-PSK group=CCMP TKIP pairwise=CCMP TKIP priority=5 }
Using bssid to specify which access point it should connect to using its MAC address, in case there are repeaters in place. Remember to use wpa_passphrase <ssid> to generate the psk
FILE
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=wheel ap_scan=1 network={ bssid=00:50:17:31:1a:11 ssid="YourSSID" psk="your-secret-key" scan_ssid=1 proto=RSN key_mgmt=WPA-PSK group=CCMP TKIP pairwise=CCMP TKIP priority=5 }
Демон роуминга и wpa_action
Будучи запущенным roaming daemon, в дальнейшем контролируется с помощью ifupdown. Таким образом: wpa_cli вызывает ifup, когда wpa_supplicant успешно ассоциируется с точкой доступа, и вызывает ifdown, когда соединение потеряно или разорвано. Пока roaming daemon остается активным, вместо ifupdown используйте /sbin/wpa_action для его остановки и перезагрузки. Например, чтобы остановить romaing daemon на устройстве ‘eth1’:
wpa_action eth1 stop
Для внесения новых дополнительных деталей конфигурации нет необходимости останавливать roaming daemon . Отредактируйте wpa_supplicant.conf для внесения необходимых дополнений и, опционально, /etc/network/interfaces для указания новой сети (с пометкой ‘id_str’) и просто перезапустите демона:
wpa_action eth1 reload
Troubleshooting
In case it does not work as expected try some of the following and analyze the output.
Run wpa_supplicant in debug mode
Be sure to stop any running instance of the supplicant:
Something like the following options can be used for debugging (click «Expand» to view the output below):
wpa_supplicant v2.2 random: Trying to read entropy from /dev/random Successfully initialized wpa_supplicant Initializing interface 'wlp8s0' conf '/etc/wpa_supplicant/wpa_supplicant.conf' driver 'nl80211' ctrl_interface '/var/run/wpa_supplicant' bridge 'N/A' Configuration file '/etc/wpa_supplicant/wpa_supplicant.conf' -> '/etc/wpa_supplicant/wpa_supplicant.conf' Reading configuration file '/etc/wpa_supplicant/wpa_supplicant.conf' ctrl_interface='DIR=/var/run/wpa_supplicant GROUP=wheel' update_config=1 Line: 6 - start of a new network block
FILE for usage with the
modules_wlan0="wpa_supplicant" wpa_supplicant_wlan0="-Dnl80211 -d -f /var/log/wpa_supplicant.log" config_wlan0="dhcp"
Now, within one terminal issue a tail command to monitor output and restart the net.wlan0 device in another:
Hardware
You can use sudo iwconfig to check that you have your wireless device working. Most of the time this should be the case, but sometimes the drivers (kernel modules) fight, and the wrong one wins—for example, Prism 2 cards supported by hostap may instead end up using the orinoco driver, which won’t work properly. Add incorrect modules to /etc/modprobe.d/blacklist.
Comments
This was my case in Kubuntu, but should also apply to ubuntu. Once I had ndiswrapper setup, and after much detective work on filtering through the various pages on wifi in linux(ie using wext, wpa_supplicant, etc), I was able to connect to my router using wpa. I ignored the section on editing the /etc/network/interfaces to just use kwlan(Not knetworkmanager) to handle my wpa needs. There all one needs to do is set it to use wext, scan, enter password, and it just works. So maybe next time it should be made easier with having ndiswrapper(or the other driver solutions) and wpa_supplicant pre-installed. And maybe a much more non-veteran linux user howto.
sudo apt-get install network-manager-gnome
look for a new icon in the upper left — click it — you should see a list of ESSID’s (wireless network names)
Some WLAN routers, such as the FRITZ!Box WLAN 3170, allow WPA network keys of up to 60 characters, including alpha-numeric and special characters. WPA network keys including alphabetical and special characters can cause problems. The solution to such problems is to set the WPA network key to maximal 10 numbers on the WLAN router.
Feisty — Using just the /etc/network/interfaces file, with ndiswrapper and SSID broadcast
I got mine working(RaLink Rt2500). Run lspci and if you have «Network controller: RaLink RT2500 802.11g Cardbus/mini-PCI» then this should work for you.
2. Verify that you’re not using the default driver(serialmonkey) and that you’re using ndiswrapper. Just type dmesg |grep rt2500 and you should get something like:
ndiswrapper: driver rt2500 (Ralink Technology, Inc.,10/20/2005, 3.01.00.0000) loaded wlan0: ethernet device 00:13:d3:75:d4:a8 using serialized NDIS driver: rt2500, version: 0x20001, NDIS version: 0x501, vendor: 'IEEE 802.11g Wireless Card.', 1814:0201.5.conf
Step 3 won’t work if you don’t get through step 2. I had to blacklist the serialmonkey driver and then add ndiswrapper to /etc/modules before I could proceed.
3. Find out your router settings. I just ran iwlist scan and got the following:
Cell 01 - Address: 00:14:BF:0F:XX:XX ESSID:"myEssid" Protocol:IEEE 802.11g Mode:Managed Frequency:2.417 GHz (Channel 2) Quality:100/100 Signal level:-29 dBm Noise level:-96 dBm Encryption key:on Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s 24 Mb/s; 36 Mb/s; 54 Mb/s; 6 Mb/s; 9 Mb/s 12 Mb/s; 48 Mb/s Extra:bcn_int=100 Extra:atim=0 IE: IEEE 802.11i/WPA2 Version 1 Group Cipher : TKIP Pairwise Ciphers (2) : CCMP TKIP Authentication Suites (1) : PSK IE: WPA Version 1 Group Cipher : TKIP Pairwise Ciphers (2) : CCMP TKIP Authentication Suites (1) : PSK
4. Modify /etc/network/interfaces as follows, using the info from iwlist scan above:
iface ra0 inet dhcp wpa-driver wext wpa-ssid your-ssid wpa-ap-scan 1 wpa-proto RSN WPA wpa-pairwise CCMP TKIP wpa-group CCMP TKIP wpa-key-mgmt WPA-PSK wpa-psk your-wpa-psk
You may need to remove other things aded by network manager and you may need to disable the wireless in network manager as well for this to work.
Troubleshooting intermittent disconnects
This can be caused by Network Manager. Apparently when Network Manager scans for APs, wpa_supplicant will disconnect. Disabling Network Manager allows WPA to work, but you loose the NM function of automatic connections.
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:
$ wpa_passphrase MYSSID passphrase
network={ ssid="MYSSID" #psk="passphrase" psk=59e0d07fa4c7741797a4e394f38a5c321e3bed51d54ad5fcbd3f84bc7415d73d }
This means that wpa_supplicant can be associated with wpa_passphrase and started with:
# wpa_supplicant -B -i interface -c <(wpa_passphrase MYSSID passphrase)
Note: Because of the process substitution, you cannot run this command with sudo and must use a root shell, see for more explanations. Just pre-pending sudo will lead to the following error:
Successfully initialized wpa_supplicant Failed to open config file '/dev/fd/63', error: No such file or directory Failed to read or parse configuration '/dev/fd/63'
Tip:
- Use quotes, if the input contains spaces. For example: .
- To discover your wireless network interface name, see .
- Some unusually complex passphrases may require input from a file, e.g. , or here strings, e.g. .
- Alternatively, when using special characters in the passphrase, rather than escaping them, simply invoke without specifying the passphrase. It will then prompt for it to be entered in the standard input where users can paste it even if it contains special characters.
Finally, you should obtain an IP address, see .
QUICK START
First, make a configuration file, e.g.
/etc/wpa_supplicant.conf, that describes the networks
you are interested in. See wpa_supplicant.conf(5)
for details.
Once the configuration is ready, you can test whether the
configuration works by running wpa_supplicant
with following command to start it on foreground with debugging
enabled:
-
wpa_supplicant -iwlan0 -c/etc/wpa_supplicant.conf -d
Assuming everything goes fine, you can start using following
command to start wpa_supplicant on background
without debugging:
-
wpa_supplicant -iwlan0 -c/etc/wpa_supplicant.conf -B
Please note that if you included more than one driver
interface in the build time configuration (.config), you may need
to specify which interface to use by including -D<driver
name> option on the command line.