Wireguard ubuntu нет интернета

Wireguard VPN can’t access internet and LAN

I have a server running Ubuntu 20.04 and wireguard 1.0.20200513-1~20.04.2. I installed the wireguard app on my phone (Android Samsung S20+) and disabled WIFI and connected to 4G. When the VPN is active I can access the server and nothing else on my home network (192.168.1.X) or the internet. The server has a 10.0.0.1 (VPN) and 192.168.1.171 (LAN) interface. The phone gets a 10.0.0.2 interface. I’m guessing I need to setup a route. Server firewall (ufw status) is inactive. Any help would be much appreciated. /etc/wireguard/wg0.conf

[Interface] Address = 10.0.0.1/24 Address = ::1/64 SaveConfig = true ListenPort = 51820 PrivateKey = [Peer] PublicKey = AllowedIPs = 10.0.0.2/32, Endpoint = :8598 
Cellphone config [Interface] PrivateKey = Address = 10.0.0.2/24 DNS = 1.1.1.1, 1.0.0.1 [Peer] PublicKey = AllowedIPs = 10.0.0.0/24, 192.168.1.0/24 Endpoint = :51820 
net.ipv4.ip_forward=1 net.ipv6.conf.all.forwarding=1 
Destination Gateway Genmask Flags Metric Ref Use Iface 0.0.0.0 192.168.1.1 0.0.0.0 UG 100 0 0 enp2s0 10.0.0.0 0.0.0.0 255.255.255.0 U 0 0 0 wg0 169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 enp2s0 192.168.1.0 0.0.0.0 255.255.255.0 U 100 0 0 enp2s0 
ip route get from 10.0.0.2 iif wg0 192.168.1.1 192.168.1.1 from 10.0.0.2 dev enp2s0 cache iif wg0 
[Interface] Address = 10.0.0.1/24 SaveConfig = true PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o enp2s0 -j MASQUERADE PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o enp2s0 -j MASQUERADE ListenPort = 51820 PrivateKey = [Peer] PublicKey = AllowedIPs = 10.0.0.2/32 

Источник

Wireguard VPN, no Internet access

I’m trying out Wireguard VPN, and although I believe that I’ve finally got it to connect, I have no Internet access, and can’t ping various sites on the Internet. I took a Wireguard .conf file provided by my VPN vendor, renamed it, and copied it to /etc/wireguard/wg0.conf.

[Interface] PrivateKey = redacted ListenPort = 51820 Address = redacted/32 DNS = 10.100.0.1 [Peer] PublicKey = redacted PresharedKey = redacted AllowedIPs = 0.0.0.0/0 Endpoint = redacted:51820 PersistentKeepalive = 25 

If I do sudo wg-quick up wg0 it appears to connect, but I have no Internet access. $ sudo wg-quick up wg0

[#] ip link add wg0 type wireguard [#] wg setconf wg0 /dev/fd/63 [#] ip -4 address add redacted/32 dev wg0 [#] ip link set mtu 1420 up dev wg0 [#] resolvconf -a tun.wg0 -m 0 -x [#] wg set wg0 fwmark 51820 [#] ip -4 route add 0.0.0.0/0 dev wg0 table 51820 [#] ip -4 rule add not fwmark 51820 table 51820 [#] ip -4 rule add table main suppress_prefixlength 0 [#] sysctl -q net.ipv4.conf.all.src_valid_mark=1 [#] iptables-restore -n 
interface: wg0 public key: redacted private key: (hidden) listening port: 51820 fwmark: 0xca6c peer: redacted preshared key: (hidden) endpoint: redacted:51820 allowed ips: 0.0.0.0/0 transfer: 0 B received, 2.89 KiB sent persistent keepalive: every 25 seconds 

I’ve tried disabling the firewall with no luck. I’ve tried sysctl -w net.ipv4.ip_forward=1 with no luck. Any ideas why no Internet?

Читайте также:  Интернет банкинг белагропромбанк зарегистрироваться мобильная

2 Answers 2

I have success troubleshooting Wireguard links by analizing the main points of the configuration:

  1. Are the wireguard endpoints restarted so they both recognize the other side keys, and didn’t generate error messages?
  2. Is the VPN network range different from all the ranges present in the endpoints so the VPN could have its own separate net?
  3. Are the local firewalls allowing ingress of traffic thru the UDP ports used in each node?
  4. Does each node have a unique IP address in the VPN range?
  5. Do the masks of the VPN IP address/range allow for visibility of the required nodes?
  6. If DNS address is configured, is the server reachable and responding directly or thru VPN allowed ranges?
  7. Is the endpoint declared in the peer accesible directly by it?
  8. The routes created in the peer by its Allowed IPs line are referring to ranges present in the other side of the link?
  9. The firewall rules added by wg-quick allow traffic thru/from the VPN and local/remote IP ranges?
  10. Is the kernel ip_forward variable enabled?
  11. Is NAT at egress traffic required?

Directly: Not using the VPN.

VPN range: The IP range selected for the peer Address line and mask of all nodes.

Each of the questions require different rules/tecniques to test/solve, but is required some knowledge of IP addressing and access to network tools like ping , nmap or nslookup/dig and the corresponding operating system commands to ask for network current status of interface addresses, routes and firewall. Some actions could be:

  1. Check the /var/log/syslog for error messages and that the wg interface is defined and have the configured IP address.

2,4,5,8. Calculate IP address intervals for all ranges/masks involved and draw a diagram indicating how are they interconnected and how traffic will flow between them. Check for inconsistencies.

3,9. Check the current firewall used (iptables, ufw, nftables, etc.) and the rules currently applied.

  1. Use dig , nslookup or host to check DNS resolution ( man each command to increase verbosity if necessary).
  2. The Endpoint line has to use a public IP address, or one directly accesible without using the VPN.

Last, 11.(Had to add the «Last» word to avoid auto renumbering of «11» to «8») If the remote hosts (besides the remote peer node) that we want to have access to do not have routes for our local IP address/range thru the VPN/peer node, then we need NAT translation in the peer.

For example, if we need to route all traffic thru the VPN, the remote peer node has to NAT all traffic directed to internet from the VPN so the remote hosts like Google/Facebook respond directly to the peer, and so the data could be rerouted correctly to us.

Источник

Wireguard handshake works but no internet access

First off: this is not a duplicate. I’ve tried everything except OpenVPN or IPSec. I’m receiving a handshake between the client and server, and SSH and Ping work between clients, but I cannot access the global internet or even have access to the server’s public IP. My config is just the usual, keys, endpoints, I followed the Linode guide exactly. My client is openSUSE but my server is ubuntu, which I’m assuming is the chokepoint.

Читайте также:  Подключение интернета орион телеком

2 Answers 2

This is exactly the situation I had. Does your server have a public IP or is it behind a NAT? If it’s behind a NAT, the PostUp and PostDown iptables commands from the Linode guide don’t apply.

Try adding the following to your server configuration file, changing eth0 to whatever your computer calls it:

PreUp = iptables -t nat -A POSTROUTING -j MASQUERADE -o eth0 PreDown = iptables -t nat -D POSTROUTING -j MASQUERADE -o eth0 

Example configuration

Here’s an example configuration where the router is at 10.0.1.1 (normal network) and 10.0.0.x is the new WireGuard network, with the server being configured for 10.0.0.1 and the client for 10.0.0.2. The port used is 51820 and the default network interface is eth0. All traffic is routed through WireGuard, but it does not stay within the WireGuard subnet. The client has access to the server’s local network (10.0.1.x) and the general internet. Don’t forget to forward the 51820 port from your router to your server and to enable ipv4 forwarding on the server ( # sysctl -w net.ipv4.ip_forward=1 )

Server configuration

[Interface] Address = 10.0.0.1/24 PrivateKey = YOUR_SEVER_PRIVATE_KEY ListenPort = 51820 PreUp = iptables --table nat --append POSTROUTING --jump MASQUERADE --out-interface eth0 PreDown = iptables --table nat --delete POSTROUTING --jump MASQUERADE --out-interface eth0 [Peer] PublicKey = YOUR_CLIENT_PUBLIC_KEY AllowedIPs = 10.0.0.2/32 

Client configuration

[Interface] Address = 10.0.0.2/24 DNS = 10.0.1.1 PrivateKey = YOUR_CLIENT_PRIVATE_KEY ListenPort = 51820 [Peer] PublicKey = YOUR_SERVER_PUBLIC_KEY AllowedIPs = 0.0.0.0/0, ::/0 Endpoint = YOUR.DYNAMIC_DNS.COM:51820 

Источник

Проблема настройки своего VPN через WireGuard на VDS: подключается, но нет интернета

Велик соблазн написать «наконец-то нормальный» мануал для настройке wireguard. Но в итоге такой мануал станет очередным, который не решает все проблемы пользователя при настройке. Поэтому данная запись носит цель подсветить возможные проблемы, с которыми может столкнуться рядовой пользователь при настройке базового vpn через wireguard на типовом vds.

Использовал данный мануал по настройке:

Вполне возможно, что статья будет добавлять или в итоге в комментариях окажется больше полезной информации нежели в самом посте.

  • базовый VDS в DIgitalOcean за $4: 512 MB Memory / 10 GB Disk / SGP1 — Ubuntu 22.10 x64
  • регион Сингапур. Скорее всего не лучший вариант, но точно рабочий. Изначально пробовал другие регионы, но в процессе поиска проблем менял сервера. Встречал комменты, что для некоторых регионов не «заводилось». Пример замера скорости в конце статьи.

Примечание: при регистрации Digital Ocean предоставил пробный период с «$200.00 (expires in 59 days)». При этом DO сделал списание (и сразу возврат) тестовой суммы в $5 при регистрации. Если есть подходящая карта, то скорее всего есть рабочий вариант завести новый аккаунт и раскатать wireguard еще раз на два месяца. При необходимости повторить.

Читайте также:  Обновил драйвера нет интернета

Пробовал настраивать VDS по нескольким инструкциям. Вцелом, они однотипны и по каждой из них была проблема на финальном шаге — подключаюсь в WireGuard через клиент, но интернета нет. Скорее всего если есть проблема, то она будет воспроизводиться именно на этом шаге.

Полагаю, что вы прошли инструкцию и понимаете о чем идет речь дальше.

Проверьте еще раз файлы конфигураций. При минимальной настройке файлов получается два:

  • первый файл wg0.conf располагается на самом VDS и задает настройки для wireguard
  • второй, к примеру, mac.conf в моем случае, в котором задаются настройки клиента

Пример моего файла wg0.conf

[Interface] Address = 10.0.0.1/24 PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE ListenPort = 51830 PrivateKey = [Peer] PublicKey = AllowedIPs = 10.0.0.2/32

Пройдемся по основным полям:

  1. PrivateKey & PublicKey. В процессе настройке можно вполне легко перепутать данные для вставки в поля PrivateKey и PublicKey при вставке в файлы конфигураций. Проверьте еще раз, что в этой части все правильно.
  2. ListenPort. У меня указан 51830, но вроде как 51820 согласно другим инструкциям тоже должен работать. Проблем тут быть не должно.
  3. AllowedIPs. По сути данное значение должно совпадать с указанным в файле настроек клиента.
  4. ⚡⚡⚡ PostUp & PostDown. Молния. Даже три. В инструкции указана такая строчка:

PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

Данные команды выполняются при старте/останове wireguard сервера. Здесь нас интересуют значения %i и eth0.

Так понял значение %i является шаблоном для сетевого интерфейса, вместо которого в итоге подставляется конкретное значение. В моем случаем указал хардкодом ‘wg0’. Без этого у меня не работало.

Также вместо eth0 иногда требуется указать ваше значение сетевого интерфейса. Для просмотра сетевых интерфейсов можно использовать команду ifconfig -a в терминале VDS. В моем случае eth0, но может быть ens3 или другое значение. Если здесь указан неправильный интерфейс, то при просмотре статуса через команду systemctl status [email protected] видел ошибку в консоли. В моем случае правка относительно инструкции не понадобилась.

Пример моего файла mac.conf (файл клиента)

[Interface] PrivateKey = Address = 10.0.0.2/32 # должно совпадать с указанным в wg0.cong в для настойки [Peer] DNS = 1.1.1.1 # сами задаем DNS, можно 8.8.8.8 или любой другой [Peer] PublicKey = Endpoint = :51830 # проверяем порт AllowedIPs = 0.0.0.0/0 # пропускаем весь трафик через wireguard PersistentKeepalive = 20

Основные момент прокомментировал по файлу.

Клиент настраивал на MacOS. Приложение WireGuard можно скачать из AppStore. Приложение в итоге рабочее, но не отличается многословностью в случае ошибок. Даже в кривыми конфигами подключается и горит зеленым. что появились строки — получено данных, отправлено данных, последнее рукопожатие. Пример скрина с удачно запущенным wireguard:

Источник

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