- OpenVPN и DNS
- Connecting to Access Server with Linux
- Client software choice
- Linux Packages Discussed
- OpenVPN 3 Linux Client
- OpenVPN open source OpenVPN CLI program
- Ubuntu network management program
- OpenVPN не меняет DNS на клиенте
- Внимательнее
- Re: Внимательнее
- Вы совершенно не поняли сути проблемы.
- Re: Вы совершенно не поняли сути проблемы.
OpenVPN и DNS
Есть опенвпн сервер который используется для серфинга и защиты, то есть я подлючаюсь к мену и весь трафик гоняю через него. Все работает нормально. Конфиг:
http://pastebin.com/1nqcAg2v
Когда подключается клиент явно видно что ему пушиться все нужные параметры:
Fri Mar 22 19:18:10 2013 us=202541 PUSH: Received control message: ‘.. dhcp-option DNS 8.8.8.8,dhcp-option DNS 8.8.4.4 . ‘
То есть если я правильно понимаю весь трафик должен ходить через впн туннель, даже DNS. Но wireshark я вижу:
http://i.picresize.com/Ini
*.100 — адрес моей машины.
*.20.1 — адрес роутера.
То есть трафик ДНС идет не через туннель. Подскажите как это можно исправить?
Не юзал,но м.б. что то наподобие:
push route 8.8.8.8 255.255.255.255
У тебя реврайтится гейтвей? Если да, то все верно ходит.
Если это дамп трафика на клиенте, то там DNS-запрос идёт на локальный DNS-сервер (видимо 8.8.8.8 не прописался в /etc/resolv.conf), а потом уже этот DNS-cервере передаёт запрос на маршрутизатор.
Вам нужно не DNS-трафик отправлять в тунель, а смотреть, почему ваш клиент не принял dhcp-опции и не поменял настройки своего DNS. То есть почему трафик идёт к 10.19.20.1, а не к 8.8.8.8. И, ЕМНИП, все обычные программы, запущенные до изменнения resolv.conf не перечитывают его.
OpenVPN-клиент на линуксе не меняет DNS. Только если через обертки, типа нетворкменеджера, или скриптом подключения.
Под виндой и андроидом все нормально.
ну ходит же через него.
cat /etc/resolv.conf покажи.
И еще traceroute 8.8.8.8 тоже. Интересуют первые 2-3 хопа.
При включенном впне конечно же.
Да это дамп на клиенте, vpn поднимается сразу после загрузки. То есть дам я уже снимал уже после часа работы.
Под виндой и андроидом все нормально работает, ну нет обращения «за» DNS к локальному маршрутизатору.
Попробовал запустить впн ручками, resolv.conf не изменился.
В логах все ок. Может покажите куда можно еще покапать?
cat /etc/resolv.conf
———
nameserver 127.0.1.1
search lan
———
А что у тебя висит на 127.0.0.1? Dnsmasq какой-нибудь?
Судя по пасте, трафик у тебя ходит на 8.8.8.8 через впн, все ок.
И судя по днс 127.0.1.1 у тебя стоит на локлхосте кеширующий днс, в конфиге которого написано юзать днс сервер твоего роутера/провайдера.
Есть два варинта:
1) Выкинуть локальный днс сервер
2) Ставить впн скриптами новый днс насильно, линукс по дефолту его не подсасывает.
А до этого как запускали, через network-manager?
А так, вам ответили, что под линуксом openvpn клиент не меняет resolv.conf. Можно использовать скрипты, допустим http://www.subvs.co.uk/openvpn_resolvconf или те, что идут в дистрибутиве openvpn, например в RHEL в каталоге /usr/share/doc/openvpn-2.2.0/contrib/pull-resolv-conf
Ну и отдельный вопрос, нужно ли вам менять resolv.conf или лучше менять настройки вашего локального dns-сервера, который слушает на 127.0.0.1. Тогда нужен другой скрипт. В принципе, можно написать тупой скрипт, который не парсит опции dhcp, а при поднятии интерфейса просто меняет конфигурацию dns-сервера, прописывая там 8.8.8.8.
А что у тебя висит на 127.0.0.1? Dnsmasq какой-нибудь?
Есть два варинта:
1) Выкинуть локальный днс сервер
Выкинул локальный (пакет dnsmasq-base1).
Бутнул свою тачку, resolv.conf:
nameserver 10.19.20.1 #уже явно указан маршрутизатор
search lan
Что еще можно посмотреть/попробовать? (Да, я не совсем компетентен в данном вопросе, потому и спрашиваю такие нубские вопросы)
Не совсем корректно выразился. Обычно у меня впн поднимается после того как подыматься eth*.
Когда «попробовал запустить впн ручками», я остановил текущее впн соединение, и просто заново его запустил.
За скрипы спасибо, но это не совсем удобно так как я всегда тягаю только один .ovpn кофниг файл.
Основная задача этого всего защитить себя, что бы например админ на моей работе(или где-то еще) не знал какие я сайты посещаю. С трафиком то понятно, если дампы снимут то особо ничего не сделаю. А вот то факт что днс идет через основной маршрутизатор сети меня пугает, так как админ может легко узнать какие сайты я посещаю, потому мне подойдет почти любое решение, со скриптом, впринцепе, нормально но просто не особо хотеться таскать с собой еще скрипт (хоть он и тривиальный будет).
Может подобная задача может решится средствами openvpn?(up,down скрипты не учитывать).
так, вам ответили, что под линуксом openvpn клиент не меняет resolv.conf.
просто в чем тогда смысл в конфиге сервера
—
push «dhcp-option DNS 8.8.8.8»
push «dhcp-option DNS 8.8.4.4»
—
Почитал OpenVPN cookbook, там тоже говориться об этой проблеме, я так понял up,down скрипты самое быстрое и просторе решение проблемы. Спасибо!
Ну можно ещё придумать некий хак с помощью iptables. Примерно такой:
1. В /etc/resolv.conf пишем ДНСы гугля.
2. В iptables пихаем правило:
iptables -t nat -I OUTPUT -d 8.8.8.8 -o eth0 -p udp —dport 53 -j DNAT —to-destination 10.19.20.1
и второе аналогичное правило для 8.8.4.4
Как я понял, openvpn не умеет запускать в качестве up скрипта команду с произвольными аргрументами, а так бы можно было добавлять/удалять правило iptables и таскать с собой только конфиг.
Касательно того, что openvpn клиент не понимает dhcp-опции, ИМХО, недоработка разработчиков. Конечно, пихать это в бинарник не нужно, но сделать так, чтобы типовые скрипты лежали в известном бинарнику месте (указываемом при компиляции) и вызывались простыми опциями конфига стоило бы. Вот, например, в openswan идёт скрипт «_updown» и куча других скриптов и они идут все как исполняемые файлы, а не как обычные файлы в каталоге с документацией.
Источник
Connecting to Access Server with Linux
Client software choice
Connecting to OpenVPN Access Server from Linux requires a client program. It will capture the traffic you wish to send through the OpenVPN tunnel, encrypting it and passing it to the OpenVPN server. And of course, the reverse, to decrypt the return traffic.
Linux Packages Discussed
OpenVPN Access Server | openvpn-as |
OpenVPN 3 Linux Client | openvpn3 |
OpenVPN open source | openvpn |
OpenVPN 3 Linux Client
The OpenVPN 3 Linux project is a new client built on top of the OpenVPN 3 Core Library. This client is the official OpenVPN Linux Client program. You can find an overview of the features, frequently asked questions, and instructions on installing the openvpn3 package on our OpenVPN 3 for Linux site.
After following the instructions there to install the client, you’ll need a connection profile. This is a file generated by your OpenVPN Access Server installation for your specific user account. It contains the required certificates and connection settings. Go to the Client web interface of your Access Server (the main address, not the /admin portion). Log in with your user credentials. You will be shown a list of files available to download. Pick the user-locked profile or the auto-login profile, and you will be sent a client.ovpn file. Save this file to your Linux operating system.
Once you’ve moved the file to your Linux system, you can import it.
You can start a new VPN session:
You can manage a running VPN session:
And so on. More details can be found here: OpenVPN3Linux.
OpenVPN open source OpenVPN CLI program
The open source project client program can also connect to the Access Server. The package is available in most distributions and is known simply as openvpn. It supports the option to connect to multiple OpenVPN servers simultaneously, and it comes with a service component that can automatically and silently start any auto-login profiles it finds in the /etc/openvpn folder, even before a user has logged in. This service component can be set to automatically start at boot time with the tools available in your Linux distribution if supported. On Ubuntu and Debian, when you install the openvpn package, it is automatically configured to start at boot time.
To install the OpenVPN client on Linux, it is possible in many cases to just use the version that is in the software repository for the Linux distribution itself. If you run into any connectivity problems when using outdated software, it may be due to a possible lack of support for higher TLS versions in older versions of OpenVPN. Follow the instructions found on the open source openvpn community wiki if you wish to install the OpenVPN client on your Linux system.
After installing, you will need a connection profile. This is a file generated by your OpenVPN Access Server installation for your specific user account. It contains the required certificates and connection settings. Go to the Client web interface of your Access Server (the main address, not the /admin portion). Log in with your user credentials. You will be shown a list of files available to you for download. Pick the user-locked profile or the auto-login profile, and you will be sent a client.ovpn file. Save this file to your Linux operating system somewhere. OpenVPN Access Server supports server-locked, user-locked, and auto-login profiles, but the OpenVPN command line client is only able to connect with user-locked or auto-login connection profiles.
We are assuming you are going to start the connection through either the command line as a root user, or via the service daemon. If you want unprivileged users to be able to make a connection, take a look at the community wiki for more information on how to implement that. Here we are going to focus on the simplest implementation; run the connection as root user directly, or via the service daemon.
Start a connection with an auto-login profile manually:
Start a connection with a user-locked profile manually:
If you use Google Authenticator or another extra factor authentication, add the auth-retry parameter:
To start an auto-login connection via the service daemon, place client.ovpn in /etc/openvpn/ and rename the file. It must end with .conf as file extension. Ensure the service daemon is enabled to run after a reboot, and then simply reboot the system. The auto-login type profile will be picked up automatically and the connection will start itself. You can verify this by checking the output of the ifconfig command; you should see a tun0 network adapter in the list.
One major feature that is missing with the command line client is the ability to automatically implement DNS servers that are pushed by the VPN server. It is possible, but it requires you to install a DNS management program such as resolvconf or openresolv, and it may or may not clash with existing network management software in your OS. The idea here, however, is that you use a script that runs when the connection goes up, and when it goes down, that uses resolvconf or openresolv to implement the DNS servers for you. The reason why this client is not able to manage it completely by itself is mainly because in an operating system like Windows, Macintosh, Android, or iOS, there is already an established single method of handling DNS management. It is therefore easy for us to create a software client for those operating systems that already knows how to handle DNS. But Linux is available in so many variations and also supports different programs and methods of implementing DNS servers, and so it was only reasonable to leave built-in DNS support out of the OpenVPN program and instead to provide, where possible, a script that handles DNS implementation. Such a script could even be written by yourself to do whatever tasks are necessary to implement the DNS servers in your unique situation.
Fortunately on Ubuntu and Debian, for example, there is the /etc/openvpn/update-resolv-conf script that comes with the openvpn package that handles DNS implementation for these operating systems. You need only to activate the use of these by following the instructions:
Open your client.ovpn file in a text editor:
At the very bottom simply add these lines:
The first line enables the use of external scripts to handle the DNS implementation tasks. The up and down lines are there to implement DNS servers pushed by the VPN server when the connection goes up, and afterwards to undo it, when the connection goes down.
Ubuntu network management program
There is also the option of connecting through the GUI using the openvpn extension for the Gnome network manager plugin. But this is currently a bit tricky to set up. There is for example the incorrect assumption that all VPNs will be able to redirect Internet traffic, and older versions might not understand the .ovpn file format, requiring you to split up the certificate embedded in it into separate file. And you would likely have to dig into the options to ensure that a default Internet traffic route going through the VPN server is not always enabled by default, especially for servers where you only give access to some internal resources, and not the entire Internet. However the advantage of using the GUI component is that you can start/stop the connection from the desktop environment on Linux.
Источник
OpenVPN не меняет DNS на клиенте
В конфиге сервера (Lubuntu 16.04) прописано:
push «redirect-gateway def1 bypass-dhcp»
push «dhcp-option DNS 208.67.222.222»
push «dhcp-option DNS 208.67.220.220»
На клиенте (Ubuntu 18.04) УТЕЧКА DNS УСТРАНЕНА (DNS теперь не идёт через моего провайдера при конекте к VPN), но при подключении к серверу, DNS меняется не на OpenDNS (те, что в конфиге сервера), а на DNS провайдера сервера. При подключении с Android всё ок, https://www.dnsleaktest.com показывает сервера OpenDNS.
Могу приложить конфиги сервера и клиента.
Скажи спасибо systemd, который всё делает через жопу и сует свои поганые шупальца куда не просят, и иди его настраивать.
А поподробнее можно? Или ссылку
В твоей вселенной гугл не изобрели еще?
openvpn dns systemd
Читай новости украины. Гугла в России блокирует розкомнадзор. Недоступен, короче, гугл во вселенной России.
Не, пока вы тут его сравнивали с землей, мне было странно, но когда он отказывался запускать мой postges в режиме восстановления, я стал его недолюбливать.
Удалил openresolv, поставил openvpn-systemd-resolved. Сейчас в конце конфигурации записано следующее:
Подключай клиент не через NetworkManager, а отдельно сервисом openvpn, это он (NM) сливает DNS, недавно кучу времени убил.
Вот пример моего конфига клиента /etc/openvpn/client.conf:
Предварительно конечно же нужно поставить сам openvpn.
Кстати, NM выпиливать не обязательно, основное соединение может устанавливаться через него.
Внимательнее
Я же в сообщении выше написал, что запускаю через команду в терминале.
Re: Внимательнее
dpkg -l | grep resolvconf
если не стоит, ставишь пакет. Добавляешь в конфиг клиента:
Вы совершенно не поняли сути проблемы.
Я уже пробовал и resolvconf и openresolv. Сейчас у меня стоит openvpn-systemd-resolved. Они все работаю примерно одинаково. И мне нужно НЕ чтобы OpenDNS прописывались в /etc/resolv.conf, а чтобы чапросы шли через VPN тунель на сервер, а от туда на OpenDNS. Если DNS запросы будут идти через моего провайдера, я потеряю половину смысла от личного VPN-сервера.
OpenVPN не меняет DNS на клиенте
push «dhcp-option DNS 208.67.222.222»
push «dhcp-option DNS 208.67.220.220»
И мне нужно НЕ чтобы OpenDNS прописывались в /etc/resolv.conf
Вы уж определитесь что вам нужно.
В последнем ответе я изложил хотелку: DNS запросы идут через VPN на сервер, а от туда на выбранный мною DNS.
А можно прописать в DNS на клиенте адрес сервера и «научить» сервер перенаправлять запросы на нужный мне DNS? Если да, то как это реализовать
Точнее не внешний адрес сервера, а внутренний, который используется для VPN тунеля
На сервере поставить dnsmasq и его адрес прописать клиенту.
Только не понятно зачем вам это.
Так мне же надо, чтобы запросы не шли через моего провайдера.
И мне нужно НЕ чтобы OpenDNS прописывались в /etc/resolv.conf
Это кто написал?
Есть еще один вектор атаки. Практически везде на линуксах, в роутерах и т.д. используется dnsmasq — кеширующий dns сервер. У каждого резолва есть TTL несколько минут, если dns’ы гугла отдают ip по геопривязки, то в принципе они могут задетектить, что даже если ip из страны Х, то запрос пришел на сервер для станы Y (потому что dnsmasq вернул закешированный адрес).
Перепутал, хотел ответить в теме «Утечка DNS на уровне роутера? » 🙂
Re: Вы совершенно не поняли сути проблемы.
Да это ты не понимаешь чего хочешь.
DNS запросы идут через VPN на сервер, а от туда на выбранный мною DNS.
Они и так идут через туннель, в случае opendns. А так, поднимай unbound, dnsmasq, etc . И пушь этот локальный адрес. Он пропишется на клиенте. Да и мозгоеб, закрой уже тему.
Я хз, как это делать, иначе не лез бы на форумы.И DNS-запросы не идут через тунель.
Источник