Openvpn не работает dns
I set up an OpenVPN server at a remote cloud server, and config all routes to the dnsmasq that resides at the same OpenVPN server. I then downloaded all ca, and client keys in my local laptop. Once the laptop is connected to remote OpenVPN server, I would use DNS server at the OpenVPN server, and then all network connection would through the OpenVPN server.
The client.conf is
I checked the server and everything is still there. When I moved the laptop back to the home, it works again.
The client's console:
Updated VPN server.conf:
and /etc/sysctl.conf: net.ipv4.ip_forward=1
I also configured the IP forward rules at the server side.
@OrganicMarble All web sites could not be displayed. Try to ping "www.google.com", but reports unknown host finally..
Did you add the push lines in your server.conf? push "dhcp-option DNS 208.67.222.222" push "dhcp-option DNS 208.67.220.220"
Are you pushing DNS to the client with a directive like push "dhcp-option DNS 208.67.222.222" ? Do you have a directive like push "redirect-gateway def1 bypass-dhcp" ?
@OrganicMarble Yes, I push DNS to clients, and let all traffics go through the VPN. I post my server.conf, which has push "redirect-gateway def1 bypass-dhcp" . In my home, I can connect to the server and everything is OK. But when my laptop is moved to the university office, all host names can not be resolved.
Testing DNS resolution from a client system
We are going to assume that you have a DNS server configured in the Admin UI of the Access Server, under VPN Settings. We are assuming you are not using the DNS Resolution Zones or the DNS Default Suffix fields. With this setting, all DNS request should be going from the OpenVPN client, through the OpenVPN Access Server, and then to the specified DNS server. In our example we are pushing the Google Public DNS server 8.8.8.8, and our test results will reflect this in the sample outputs as well.
Install your OpenVPN client program on your chosen client system. In our example we will be using a Windows 10 Professional client system with the OpenVPN Connect Client installed, and connected to the OpenVPN Access Server. Next open a console session or an SSH session to the OpenVPN Access Server, and obtain root privileges. We will be using the tool tcpdump to monitor activity on port 53 TCP and UDP, the default port where DNS queries are handled. We will be flushing the local DNS resolver cache on the client side, and then resolve a number of domains simply by pinging them by name. In our test situation, there are only a handful of clients connected, and the activity of DNS queries is very low, so we can monitor it easily. If you are testing on a production system and the tcpdump command gives too much output, you can append a grep filter by IP address, to filter queries coming only from your specific VPN client's IP address, to make reading and locating the DNS query results easier.
On the Access Server run these commands:
With TCPdump installed, now run it with these parameters:
Or, if you want to filter it by the IP address of your VPN client (adjust as needed):
With this running in the background, go to your VPN client's operating system, and open a command prompt. On Windows for example you can run the cmd program to open an old style DOS prompt. With that open, use the following commands to wipe the local DNS resolver cache, so it won't pull results from its own local memory, and then do an actual query.
Wipe local DNS resolver cache on Windows:
Resolve some domain names:
Each of these should yield results that look somewhat like this:
On the OpenVPN Access Server you should be seeing results that look somewhat like this:
2 Answers 2
uncomment the lines (which already exist in your server.conf file at line 111) by removing the semi colon (;):
in your server.conf file.
At home, your DNS was probably supplied by your router.
Do you mean to append the two provided configurations to the server.conf? Can you help explain why it is OK in my home, while unknown host error when moving to the office? Thanks
Your /etc/resolv.conf file defines where your computer should look to resolve hostnames into IP addresses. The basic problem is that /etc/resolv.conf doesn't get updated when you run openvpn by default.
Here's what you need to do to fix the problem.
1.) Append the following onto your server.conf file on your OpenVPN server machine (typically located at /etc/openvpn/server.conf ) to have the server to the client where to look to convert hostnames to IP addresses.
2.) Install resolvconf on your client machine and link the standard resolv.conf to resolvconf 's version with the following commands to have a function capable of modifying resolv.conf
3.) Append the following to the bottom of your client.ovpn file to run resolvconf whenver the OpenVPN server is connected to or disconnected from.
4.) Whenever you run openvpn you'll have to do so with the -script-security 2 flag to allow openvpn to run resolvconf . Here is an example call
Companies often run their own DNS server that they use to resolve DNS names to private IP addresses, to make accessing systems easier for users. It is for example easier to tell a user to start their Remote Desktop client program and to connect to server1 instead of having to tell them to connect to 192.168.70.243. To learn what DNS is, see this article. OpenVPN Access Server supports pushing an instruction to a connecting OpenVPN client to use a specific DNS server. Actually it supports pushing 2 DNS servers, in case the first one fails to respond. This can be configured in the Admin UI under VPN Settings. The Access Server also supports sending additional instructions for DNS Resolution Zones, which functions like a type of split-DNS where only queries for a specific DNS zone are sent to the VPN server, and DNS Default Suffix, which provides a hint to Windows to 'autocomplete' a partial hostname to a Fully Qualified Domain Name, or FQDN.
Unfortunately, not every operating system behaves the same in regards to DNS. Some systems will try all DNS servers at once, and accept the response from the first to respond. Others will be able to do split-DNS, and others will not. This can lead to certain problems. The guide below provides a way of checking to see if the DNS query you are doing from your OpenVPN client device, is actually making it through the VPN tunnel to the OpenVPN Access Server. And from there, of course, to the target DNS server. This information is valuable in determining whether or not the problem is at the client end, or at the server end.
Split-DNS when using DNS Resolution Zones
Split-DNS is the principle of resolving only certain zones (domains) through a DNS server pushed by the VPN server, and the rest through your already present local DNS servers. In Access Server there is a field in the Admin UI, under VPN Settings, called DNS Resolution Zones. If you enter a single domain or a list of (comma-separated) domains here, then the clients will receive an instruction to only resolve those domains through the DNS server pushed by the VPN server, and resolve the rest through the client's local DNS server.
Please note that not all OpenVPN clients out there support this and there are some differences in behavior between versions of OpenVPN as well. The best results can be achieved by using OpenVPN Connect v3 client software.
When you use split-DNS, you will not see the DNS server that is being pushed in your ipconfig or ifconfig output. The DNS server will not get implemented at the network interface configuration level. Instead, it will be implemented in the DNS system in a DNS resolution policy table. On mac OS for example this can be queried using the scutil command line utility and on Windows this can be queried using netsh to query the resolution policy table in the OS. Such a table is simply a list of domains, and which DNS servers they should be resolved through. Below we will show example output of how split-DNS and normal DNS resolution looks like through a VPN tunnel. Some superfluous data has been removed from these example outputs.
Commands to see network configuration and DNS resolution policy on Windows:
Commands to see network configuration and DNS resolution policy on mac OS:
Example output on Windows when split-DNS is currently in use:
Example output on Windows when split-DNS is not used:
In the above output, you can see that split-DNS is not being used because the DNS server is assigned to the network interface adapter itself, and there is only one top level zone for DNS resolution (the dot means all zones). This means that this configuration is not using split-DNS and therefore all DNS queries get redirected to the server at 1.2.3.4.
Troubleshooting
Below are a number of common problems you can see that we try to explain here and where to look for a solution.
Specifically the item NXDomain here is important. It means that this DNS server does not know the name we are trying to resolve. Another DNS might still know the name. but this one doesn't. In the example above however we have purposefully selected a name that does not exist (or at least it didn't when we ran the test - it is possible of course someone may register the name in the future) to be sure we see the error. If you are encountering this problem you may want to try to use the nslookup program on a computer with direct access to the DNS server, and use it to query the specific DNS server directly, to confirm that it does know the domain.
If you see a result like this, repeated a few times:
Then what you may notice here is that you do see a query arriving from the VPN client, pass through the Access Server, and go out to the Internet, but there is no reply. Usually this means that this DNS server is unreachable, or is not a DNS server at all. In the example I have chosen IP address 1.2.3.4 which I know for a fact is not a DNS server. Obviously the query will be repeated a few times but will ultimately fail. The obvious solution here is to choose a DNS server that works, or, to make sure that there is no firewall standing in the way, blocking the queries from the VPN clients to the DNS server. In some cases, when routing is used to give VPN clients access to servers on the private network behind the Access Server, it is a matter of a missing route. In such a case that packets from VPN clients make it to the target DNS server just fine, but it is not able to respond because it is receiving packets from a subnet it does not know how to respond to. That can be solved by implementing static routes for direct VPN client communication, or switching to giving access using NAT instead. In other cases we've seen, especially on Windows Server platforms, the built-in Windows Firewall could be blocking queries coming from a subnet outside of the local network. In such a case an adjustment to the firewall is necessary to allow the DNS server to receive the query and respond to it.
Могу приложить конфиги сервера и клиента.
Скажи спасибо systemd, который всё делает через жопу и сует свои поганые шупальца куда не просят, и иди его настраивать.
А поподробнее можно? Или ссылку
В твоей вселенной гугл не изобрели еще?
openvpn dns systemd
Не, пока вы тут его сравнивали с землей, мне было странно, но когда он отказывался запускать мой postges в режиме восстановления, я стал его недолюбливать.
Удалил openresolv, поставил openvpn-systemd-resolved. Сейчас в конце конфигурации записано следующее:
DNS leak test показывает моего провайдера. А если его закомментировать, а прописанные DNS раскомментировать, то показывает и DNS провайдера и OpenDNS одновременно. Но мне нужно чтобы DNS брался не из конфигурации клиента и шёл через провайдера, а брался из конфигурации сервера и через него же и шёл. Я надеюсь, смог донести суть, я не мастер объяснений. Если это важно: openvpn запускаю через
Подключай клиент не через NetworkManager, а отдельно сервисом openvpn, это он (NM) сливает DNS, недавно кучу времени убил.
mephistopheles ★★ ( 30.05.18 18:22:58 )
Последнее исправление: mephistopheles 30.05.18 18:23:49 (всего исправлений: 1)
Вот пример моего конфига клиента /etc/openvpn/client.conf:
Предварительно конечно же нужно поставить сам openvpn.
Кстати, NM выпиливать не обязательно, основное соединение может устанавливаться через него.
dpkg -l | grep resolvconf
если не стоит, ставишь пакет. Добавляешь в конфиг клиента:
При подкл. должно запушиться на те днс адреса, которые прописаны в конф. сервера. После подкл. смотришь, что на кл. в /etc/resolv.conf. Там должны быть твои opendns адреса.
Я уже пробовал и 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 на уровне роутера? » :)
Да это ты не понимаешь чего хочешь.
DNS запросы идут через VPN на сервер, а от туда на выбранный мною DNS.
Они и так идут через туннель, в случае opendns. А так, поднимай unbound, dnsmasq, etc . И пушь этот локальный адрес. Он пропишется на клиенте. Да и мозгоеб, закрой уже тему.
Я хз, как это делать, иначе не лез бы на форумы.И DNS-запросы не идут через тунель.
Появилась проблема, подключение openVPN перестал резольвить имена через внешние днс.
шлюз 192.168.1.1 он же dhcp сервер.
впн сервер где то на другом полушарии, к которому доступа нет.
днс сервер х.х.х.х, который тоже черт знает где.
lan - addr:192.168.1.30 gw:192.168.1.1 dns:x.x.x.x
tun0 - addr:z.z.z.22 peer:z.z.z.21
без впн все работает, как только подключается впн имена перестаю резольвится.
Вот что говорит tcpdump на момент dns-запроса
При этом трасса к 8.8.8.8 успешно прокладывается через tun0. Если поднять днс на шлюзе и выдавать его вместо x.x.x.x, то все работает.
Не помогает(что странно):
Как не прибегая к костылям вернуть работоспособность впн? Спасибо!
Логично, что проблема в
Либо пусть сервере уберут
либо руками после установления соединения удаляйте выданный дефолтный маршрут и добавляйте роут на подсеть вручную.
Как вариант - можно увеличить метрику до 700 у выданного дефолтного маршрута
так впн и должен быть роутом по умолчанию.
там две записи 0.0.0.0/1 default via tun0 и 128.0.0.0/1 default via tun0, что грубо говоря является 0.0.0.0/0 default via tun0.
а третья 0.0.0.0/0 default via wlp3s0 c метрикой 600.
Кстати, это тоже пробовал - не помогает.
Вру, помогает. Но все же костыль, не? Или это особенность ovpn такая?
Да нет, норм решение раз работает.
Так и есть. Исторически под онтопиком ovpn не устанавливает dns сервера полученные с сервера. Поэтому всегда это решалось скриптами. На эту тему «немало копий было сломано» что мол «оффтопику больше внимания чем родной системе». Но и аргументация исторически так же понятна, не трогать /etc/resolv.conf (это сейчас расплодилось всяких NM) поясню вот прописали вы в resolv.conf свой локальный днс 1.1.1.1 стартанули ovpn он поменял на полученный 2.2.2.2 после этого «бамс» и ребут, не важно по какой причине, например электрики, в результате после ребута resolv.conf останется от ovpn т.е. не правильный. На текущий момент при учете большого разнообразия в дистрах в части «откуда что берем» с точки зрения создателей ovpn я бы даже и не смотрел в сторону какой-то доп. автоматизации, есть скрипты ими и пользуйтесь.
Здравствуйте! У меня проблема по настройке сервера, проблема заключается в том что от клиента по openvpn не пингуются машины за сервером по ИМЕНИ, по IP все нормально работает и пингуется, прошу сразу прощения, я не особо бум бум что нужно предоставить по информации, все не выкладываю что бы не было помойки, скажите что нужно выложить я выложу, заранее спасибо, уже все перепробовал, немогу понять в чем дело.
ДНС значит не доступен. Не резольвятся хосты.
eth0 - смотрит на модем 192.168.100.245
eth1 - локальная сеть за сервером, 192.168.1.99
tap0 - интерфейс openVPN
установлен bind, в resolv.conf - nameserver 192.168.1.99
Что не так не соображу. повторю вопрос почему клиент из 10.10.10.0/24 не пингует сеть за сервером в сторону 192.168.1.0/24 по именам, по IP пингует. я не скажу что я совсем дерево, но я дерево))) ибо настройки по мануалам делал.
Какие днс сервера пушатся клиенту?
Да конечно извините, сглупил не выложил vpn конфиги
Конфиг клиента в ccd
Насчет ссылки на вики, непонял половину, это получается скрипт для resolv? с английским проблемы, но половину понял, но не понял что делает и смысл его, можете дать комментарии?
нужно смотреть какие днс на клиенте, openvpn их может пушить, но что будет происходить на клиенте не знает никто. вообще это чисто проблема со стороны клиента, оттуда ее и надо дебажить. nslookup хотя бы пробовали запускать на клиентах? что при этом в логах ДНС сервера видно?
в логах ничего нет, точнее скорее всего у меня они не включены, что то найти не могу, на клиенте пишутся адреса на адаптере которые я укажу, в качестве адресов я указывал адрес openvpn сервера а так же интерфейса на который dns сервер настраивал, но толку не было, хотя в свойствах адаптера они были прописаны в качестве основного и вторичного DNS. nslookup, пробовал что то такое, но не разобрался в том что выдает, сегодня еще раз попробую вечером скажу результат.
nslookup показал что:
Server: UnKnown
Address: 10.10.10.1
Включить логи на клиенте и показать их нам (момент подключения клиента к серверу), особенно строчку про пуш днс.
Да конечно вот логи клиента, они ведутся:
Эээ, а ты сам ничего такого в этом логе не замечаешь?
Видел ошибку Warning ругался на gateway и что инициализация в конце закончена с ошибками, я так думаю это на то что шлюз не присвоился, или я ошибаюсь? я как бы это во внимание не брал про шлюз.
а так ничего не заметил более.
Я немного о другом скажу, но все таки закинь в конфиг клиента:
Это проблему с днс вряд ли решит, но лишним не будет.
Тьфу, у тебя там керио? Отключай его и проверяй без него. 99% что проблема в нем.
где керио? на клиенте? установлен но не запущен
где керио? на клиенте? установлен но не запущен
конечно я понимаю может быть наглостью, но я могу дать доступ по tamviewer, ибо я реально уже голову сломал, уже месяц бьюсь с этим, я просто понимаю как тяжело через форум смотреть и анализировать проблему не видя всего и того что нужно
ICQ 233930692, буду очень рад помощи
Извини, мне не до этого сейчас, да и я навскидку не скажу, где проблема в твоей конфигурации.
P.S. как то странно ты керио удалил, раз его интерфейс в системе остался.
xtraeft ★★☆☆ ( 08.09.14 20:00:00 )
Последнее исправление: xtraeft 08.09.14 20:00:47 (всего исправлений: 1)
погуглил немного, похоже в каких-то случая (где используется static key, хз что это, но вроде как сабж не попадает туда) есть бага с назначением DNS на клиенте. чтобы проверить днс можно вручную прописать в свойствах подключения свой днс сервер и проверить как работает.
я совсем запутался, не пингуется или не резолвится или непонятно что происходит. включи логи в бинде посмотри что он пишет.
это значит что DNS на сервере работает? правильно?
Да и еще если прописываю на винде у клиента в Hosts адрес и имя, то потом по vpn я могу найти машину по имени, ребята чувствую мы близко к разгадке))) я пока что в тупике))) есть идеи?)))
Берём совочек и начинаем с dig hostname . Потом смотрим man dig и указываем дигу руками днс-сервер для запроса. Сравниваем два выхлопа, думаем, отписываемся на ЛОР.
Ну, это всё, если openvpn-клиент на линуксе.
dhameoelin ★★★★★ ( 09.09.14 20:53:12 )
Последнее исправление: dhameoelin 09.09.14 20:53:45 (всего исправлений: 1)
Читайте также: