Wifi hotspot with linux

Software access point

A software access point, also called virtual router or virtual Wi-Fi, enables a computer to turn its wireless interface into a Wi-Fi access point. It saves the trouble of getting a separate wireless router.

Contents

Requirements

Wi-Fi device must support AP mode

You need a nl80211 compatible wireless device, which supports the AP operating mode. This can be verified by running the iw list command, under the Supported interface modes block there should be AP listed:

Wireless client and software AP with a single Wi-Fi device

Creating a software AP is independent from your own network connection (Ethernet, wireless, . ). Many wireless devices even support simultaneous operation both as AP and as wireless «client» at the same time. Using that capability you can create a software AP acting as a «wireless repeater» for an existing network, using a single wireless device. The capability is listed in the following section in the output of iw list :

The constraint #channels means that your software AP must operate on the same channel as your Wi-Fi client connection; see the channel setting in hostapd.conf below.

If you want to use the capability/feature, perhaps because an Ethernet connection is not available, you need to create two separate virtual interfaces for using it. Virtual interfaces for a physical device wlan0 can be created as follows: The virtual interfaces with unique MAC address are created for the network connection ( wlan0_sta ) itself and for the software AP/hostapd «wireless repeater»:

Random MAC address can be generated using macchanger.

Configuration

Setting up an access point consists of two main parts:

  1. Setting up the Wi-Fi link layer, so that wireless clients can associate to your computer’s software access point and exchange IP packets with it.
  2. Setting up the network configuration on your computer, so that it properly relays IP packets between its own internet connection and the wireless clients.

The actual Wi-Fi link is established via the hostapd package, which has WPA2 support.

Adjust the options in hostapd configuration file if necessary. Especially, change the ssid and the wpa_passphrase . See hostapd Linux documentation page for more information.

For automatically starting hostapd on boot, enable the hostapd.service .

If you are starting hostapd on boot, make sure the wireless network interface is brought up first, otherwise it will fail. To ensure your wireless interface is ready, edit the unit configuration file and state that it is bound to and should start after your network interface:

Also make sure that the interface is not managed by other network managers. If you are using NetworkManager, see NetworkManager#Ignore specific devices.

Network configuration

There are two basic ways for implementing this:

  1. bridge: creates a network bridge on your computer, wireless clients will appear to access the same network interface and the same subnet that is used by your computer.
  2. NAT: with IP forwarding/masquerading and DHCP service, wireless clients will use a dedicated subnet, data from/to that subnet is NAT-ted. This is similar to a normal Wi-Fi router which is connected to the internet.
Читайте также:  Windows doctor как он работает

The bridge approach is simpler, but it requires that any service that is needed by the wireless clients, in particular DHCP, is available on the computer’s external interface. This means it will not work if the external modem which assigns IP addresses, supplies the same one to different clients.

The NAT approach is more versatile, as it clearly separates Wi-Fi clients from your computer and it is completely transparent to the outside world. It will work with any kind of network connection, and (if needed) traffic policies can be introduced using the usual iptables approach.

It is possible to combine these two approaches: for example having a bridge that contains both an ethernet device and the wireless device with a static ip, offering DHCP and setting NAT configured to relay the traffic to an additional network device connected to the WAN.

Bridge setup

You need to create a network bridge and add your network interface (e.g. eth0 ) to it. You should not add the wireless device (e.g. wlan0 ) to the bridge; hostapd will add it on its own.

NAT setup

In that article, the device connected to the LAN is net0 . That device would be in this case your wireless device (e.g. wlan0 ).

Tools

linux-wifi-hotspot

The linux-wifi-hotspot AUR package provides a script that can create either a bridged or a NATed access point for internet sharing. It combines hostapd, dnsmasq and iptables for the good functioning of the access point. Includes both command line and gui. The basic syntax to create a NATed virtual network is the following:

Alternatively, the template configuration provided in /etc/create_ap.conf can be adapted to ones need and the script run with:

To use the GUI, run in terminal:

Enable/start the create_ap.service to run the script at boot time with the configuration specified in /etc/create_ap.conf .

RADIUS

See [1] for instructions to run a FreeRADIUS server for WPA2 Enterprise.

This article or section needs expansion.

Troubleshooting

WLAN is very slow

Frequent causes for a lower than expected throughput include

  • An improper choice of operation mode with a hw_mode lower than the one supported can limit the router artificially. Check that a modern operating mode is selected.
  • A crowded or otherwise noise afflicted channel can severely degrade performance especially in densely populated areas. Try changing to a different channel or even switch frequencies.
  • The availability of too little entropy can lead to poor performance. Consider installing haveged.

NetworkManager is interfering

hostapd may not work, if the device is managed by NetworkManager. You can mask the device using MAC:

Or interface name:

Cannot start AP mode in 5Ghz band

Apparently with the special country code 00 (global), all usable frequencies in the 5Ghz band will have the no-ir (no-initiating-radiation) flag set, which will prevent hostapd from using them. You will need to have crda installed and have your country code set to make frequencies allowed in your country available for hostapd.

Источник

Беспроводная точка доступа, используя Linux

Самый первый шаг, конечно же:

Мда, в исходниках уже есть 2.0. Такой он, Debian stable. Но на самом деле это нам не особо помешает — версия 1.0 у меня работает достаточно стабильно.

Настройка:

Отредактировать файл /etc/default/hostapd.conf. В нём раскомментировать строку вида Это путь к файлу конфигурации демона hostapd.
Затем идем дальше — редактировать /etc/hostapd/hostapd.conf. Предоставлю содержимое моего файла конфигурации. Предупреждаю, парсер конфигурационных опций у этого демона очень чувствителен и ругается даже на пустые строки с пробелом. На комментарии не ругается.

Читайте также:  Php mail on linux

Сетевой интерфейс беспроводной карты
Драйвер сетевой карты — обычно для hostapd отлично работает nl80211, не вижу смысла менять, да и говорят, что он работает в большинстве случаев.
Название точки доступа, т.н. SSID
Режим работы сетевой карты — 801.11b/g/n. На самом деле — там всегда должно оставаться g, даже если карта способна на n, для настройки режима n придётся кое-что поменять, смотрите дальше:

Беспроводной канал — от 1 до 13. Для лучшей производительности рекомендуются 1, 6 или 11 канал.
Версия WPA
Пароль беспроводной точки
Дополнительные настройки WPA2:
Следующая опция устанавливает блокировку MAC-адресов. Пока не знаю, как это настроить, да и штука довольно бесполезная, но все говорят, что без блокировки эту опцию нужно выставить в ноль — что я и сделал:

Конфиг автоматически проверяется перед запуском, так что — смело пробуйте запустить hostapd. Команды управления:
Напомню — также в Debian можно использовать команды вида service hostapd start, что легче в написании.

Пару шагов для устойчивости:
  • Нельзя забывать, что для шифрования WPA/WPA2 пароль должен быть не короче 8 символов. Если поменять пароль на лету, используя SSH сессию через беспроводной канал, можно внезапно отрезать себя от сервера — hostapd не захочет запускаться и единственное средство связи с сервером будет потеряно. Работает — не трогай, ну а если трогаешь — трогай осторожно.
  • В случае многопользовательской системы советую поставить права чтения файлов вида 700, чтобы простые пользователи не могли узнать пароль для точки доступа — если вас это волнует, конечно.

Что ещё могу сказать? С мобильными устройствами проблем нет, с ноутбуком под Windows 7 — крайне редко (примерно раз-два в месяц) не получается подключиться к точке. Лечится командой service hostapd restart, велика вероятность, что в новых релизах эта проблема убрана — есть версия hostapd 2.0.0, но компилировать и ставить её я пока что не пытался.

Пока всё. К точке можно попробовать подключиться, но… Для успешного подключения к точке доступа нужен DHCP сервер, без него к точке полноценно не подключишься — те же операционные системы не дадут этого сделать, поскольку без получения адреса само подключение не имеет особого смысла. Вот его и настроим!

Когда я только начинал учиться настраивать сервера под свои нужды, первое, на что я тогда я наткнулся — это пакет isc-dhcp-server, его я и планировал предложить, и статья уже была готова, но… Я нашёл dnsmasq, и моя жизнь изменилась в лучшую сторону. Dnsmasq — это и кэширующий DNS, и DHCP сервер со своим набором различных фич. Как только я заглянул в его конфиг, мое зрение улучшилось, все мысли в мозгу внезапно стали упорядоченными и я достиг просветления. Реально, конфиг очень простой и понятный. Но пока подготавливаем площадку для работы dnsmasq. Что же делать?

1) Придумать, как будут выглядеть адреса в нашей локальной сети. Я выбрал адреса типа 192.168.51.x.

2) Настроить сетевой интерфейс, на котором будет работать dnsmasq. На самом деле — очень важный шаг, который пропускают многие в своих мануалах по настройке DHCP-серверов. Дело в том, что компьютеру, на котором работает DHCP-сервер, необходимо прописать статический адрес — кто выдаст адрес DHCP-серверу, если он сам не может запуститься без адреса, а адрес себе он выдать не может, потому что не запущен?
Итак, открываем для редактирования файл /etc/network/interfaces и добавляем туда абзац вида:
Сохраняем и перезапускаем наш сетевой интерфейс, на котором настроен DHCP:
Проверяем состояние, сверяем настройки с теми, что должны быть:

Читайте также:  Windows 10 anahtar kodu

3) Нужно удалить любые DNS и DHCP серверы, чтобы dnsmasq мог спокойно запуститься — иначе выдаёт ошибку. У меня были установлены bind9 и isc-dhcp-server, пришлось избавиться от них. Если работаем по SSH из сети, в которой раньше адреса раздавал покойный DHCP-сервер, не перезагружаемся — выдавать адреса уже некому.

4) Нужно создать условия для работы сервера — создать пользователя для того, чтобы под ним запускать dnsmasq, прописать в системных настройках DNS-сервера, к которым dnsmasq будет обращаться и ещё пару мелочей.
Прописываем DNS сервера Гугла. Правда, первой строчкой у нас будет localhost. Это сделано для того, чтобы остальные системные приложения на нашем же сервере, когда им надо получить адрес от DNS-сервера, обращались сначала к dnsmasq, а не к Гуглу. Ну а dnsmasq достаточно умён, чтобы игнорировать эту строчку:

Нужно защитить это файл от перезаписи при каждом запуске системы. Перезаписывает его dhclient, если что. Честно говоря, блокировка от записи — лишь один из способов того, как не допустить перезапись =) Есть и другие, но этот самый простой:

Что же, если вы по каким-либо причинам считаете блокирование файла неверным путём или также хотите использовать DNS, которые столь настойчиво предлагает dhclient? Тогда, как советует merlin-vrn, нужно использовать программу resolvconf.

Если пакет resolvconf ещё не установлен, устанавливаем. Единственное, что нужно для того, чтобы прописать статический адрес DNS для системы — отредактировать /etc/resolvconf/resolv.conf.d/base, вписав туда всё, что мы бы вписали в /etc/resolv.conf:

service resolvconf reload — готово!

Добавляем группу и пользователя:

5) Ставим Dnsmasq, он запускается и готов к работе, но мы его отключаем — ещё не настроен, нечего ему тут делать:

6) Чистим оригинальный файл от стандартного конфига:
Ну а теперь мы готовы настраивать. Скажу сразу — у dnsmasq много разных опций, которые я при написании статьи подробно описывал в комментариях… Пока не понял, что топик раздулся до неприличных и нечитаемых размеров, как будто недостаточно того, что статья и так переполнена текстом и отформатирована, как кусок незнамо чего. Поэтому — я оставлю конфиг с самыми важными без длинных комментариев и всяких дополнительных опций, а конфиг с дополнительными опциями будет под спойлером.

Источник

Wifi hotspot with linux

Linux Wifi Hotspot

  • UI improvements
  • Fallback to same channel when same wifi interface does not support for multiple channels
  • Show the connected devices
  • Add MAC filter
  • Share your wifi like in Windows — Use wifi and enable hotspot at the same time.
  • Share access point from any network interface
  • MAC filter
  • Includes Both command line and gui.
  • Support both 2.4GHz and 5GHz (Need to be compatible with your wifi adapter). Ex: You have connected to the 5GHz network and share a connection with 2.4GHz.
  • Select Channel.
  • Hide SSID
  • Show the connected devices

Command line help and documentation

If you only need the command-line without GUI run make install-cli-only as root user.

Sometimes there are troubles with 5Ghz bands due to some vendor restrictions. If you cannot start hotspot while you are connected to 5Ghz band, Unselect Auto and select 2.4Ghz in frequency selection.

If any problems with RealTeK Wifi Adapters see this

Download the debian package from latest release

Источник

Оцените статью