Настройка wireguard oracle cloud
I have Wireguard VPN set up in Oracle Cloud VM (Ubuntu 18.04). Wireguard client (Windows) connects, but there is no internet. 0 bytes received, hundreds sent every other second.
Here are the things I've done and tried:
- Created and updated/upgraded Ubuntu VM
- Executed Angristan's scripts.
- Added the port number assigned by Angristan's script in Ingress Rules (firewall)
- Tried to check/uncheck "Skip source/destination check" in VNIC setup
- Tried to set MTU size to 1360 (the default for wg0 was 8920) and added it in client config
- (Update) Tried to open the firewall another way "sudo ufw allow 54321/upd", I have no idea why I should do this, but still no result.
One thing I didn't understand in the process is why "net.ipv4.ip_forward=1" is still commented out inside "/etc/sysctl.conf" file after executing Angristan's script. Isn't it supposed to be enabled? Anyway, I tried to manually enable it in the file, still no internet.
I'm not good with Linux, Wireguard and networking stuff, so I'm hoping to get some help here on how to troubleshoot this issue.
The text was updated successfully, but these errors were encountered:
2. Installing and Configuring algo:
a. Connecting to VM(default username for ubuntu VMs is “ubuntu” in oracle)
b. Updating packages repos
(if you list sudo permissions via sudo -l, you can see )
b. Downloading algo vpn
b. Installing python3-virtualenv and other dependencies:
if dependencies get installed properly we should be in a virtual environment.
c. Add more users by editing config.cfg
d. Run the algo binary to start the installation:
[Cloud prompt]
What provider would you like to use?
12 [Install to existing Ubuntu 18.04 or 20.04 server (for more advanced users)]
[Cellular On Demand prompt]
Do you want macOS/iOS clients to enable “Connect On Demand” when connected to cellular networks?
[Wi-Fi On Demand prompt]
Do you want macOS/iOS clients to enable “Connect On Demand” when connected to Wi-Fi?
[Retain the PKI prompt]
Do you want to retain the keys (PKI)? (required to add users in the future, but less secure)
[DNS adblocking prompt]
Do you want to enable DNS ad blocking on this VPN server?
Enter the IP address of your server: (or use localhost for local installation):
Enter the public IP address or domain name of your server: (IMPORTANT! This is used to verify the certificate)
At last we get something like this:
e. Copying config files and qr codes.(We will be using them to connect to vpn)
Testing the WireGuard Tunnel
On the client, use the ping command to check communications with the WireGuard server, for example:
Likewise, the wg command indicates whether a connection to the WireGuard tunnel is established, as shown in the following example:
The handshake and transfer output show the traffic in the tunneled connection.
If communications between the server and the client cannot be established, check if the firewall might be blocking access to the ports that have been set up for WireGuard. You might need to open the ports to link both server and client. For example, you would type the following commands on the server:
rayMomoko commented May 8, 2021 •
@hosseinmarvi Hi, not necessarily all, I did it for those being added to Chain FORWARD only.
If adding the rules by append (to the bottom), the transit traffic would be rejected by the prebuilt rule on Oracle VM which is at the top. (Basically the table lookup is from the top to the bottom)
I also added the port ACCEPT iptables rule to the wg0.conf (I am using udp port 60000).
Here's part of my wg0.conf and how my iptables eventually looks like.
Hope it can give you some help.
FireMasterK commented Mar 24, 2021
Oracle cloud has a firewall that has to be configured in their portal.
Once you allow it, you should be able to use it just fine.
I'm able to run it fine on Ubuntu 20.04.
1. Creating a VM compute instance
a. Login to your oracle cloud account and Click Create VM instance option.
b. In the next screen you will be prompted with various configuration options for your instance. First we can change the name of our VM(not required) and select compartment in which you want to create the instance.
c. Then we may select other os images(not required)
This completely depends upon user preference. Here I have chosen ubuntu 20.04 image.
Then click Select Image option.
d. Setting ssh keys for access to VM: Scroll down and there you will find a option to upload/create ssh keys. Now here you can generate a key-pair then upload that pub key or you can upload your previously created pub key. That’s what we have done here. I have uploaded 3 ssh pub key files which allows me to connect to the VM via 3 different computers. You can create your ssh key pair using ssh-keygen command and your pub key will be available at ~/.ssh/id_rsa.pub. You can then upload this file. Please note if your keys are lost or changed you will not be able to access the machine(as password authentication is disabled by default, but can be enabled though via making modifications in ssh_config)
e. We don’t need to alter other settings scroll down and click Create button and wait for 30 seconds. Your vm will start and will be in running state.
hosseinmarvi commented May 8, 2021 •
Sorry I don't have enough knowledge about networking and I might need a bit more help.
@rayMomoko Do you mean replacing every -A flag with -I in wg0.conf ? Because I tried to do that and it didn't help.
@FireMasterK Would you please explain where and how I can configure firewall settings?
Доступ к Majordomo через бесплатный VPS на базе Oracle Cloud и Wireguard
Задался целью организовать удаленный доступ к серверу УД, чтоб можно было занимается настройкой УД с работы, ну и с телефона в случае чего зайти.
Создал экземпляр виртуальной машины Ubuntu 20.04. Установил там Wireguard - имеется следующая конфигурация на wg0.conf:
До самой Raspberry Pi еще дело не дошло. Сейчас хотя бы добиться нормального подключения к серверу со всех клиентов, чтоб был интернет, ping между всем клиентами, попасть в локальную сеть.
Почему-то SSH работает. С сайта сканера портов по общедоступному IP вижу открытый 22-й порт TCP, а вот 51820 закрыт. Wireguard по идеи работает, wg show показывает информацию о сервисе, но трафик не бегает и клиенты при подключении не получают данные.
На сервере тут /etc/sysctl.conf раскомментировал net.ipv4.ip_forward=1, сюда /proc/sys/net/ipv4/ip_forward добавил 1.
Думаю, что нужно больше ковыряться в веб-морде самого Oracle Cloud, хотя и тут вроде разрешил все входящие соединения.
Тут есть общедоступный IP-адрес, по которому получаю доступ к виртуальной. машине.
Есть основной виртуальный адаптер с частным IP-адресом 10.0.0.3. Подсеть subnet со следующими параметрами:
Блок CIDR: 10.0.0.0/24
Тип подсети: Региональная
Доступ к подсети: Общедоступная подсеть
Есть еще тут таблица маршрутизации по умолчанию, где у меня есть правила для входящего и исходящего трафика с назначением\источником: 0.0.0.0/0, со всеми IP протоколами и разрешением трафика для всех портов.
В правилах маршрутизации есть еще разные варианты типа адресата, кроме Интернет-шлюз, которые мне не совсем понятны, хоть и читал документацию.
Еще обнаружил возможность резервирования общедоступных IP-адресов, но по сути у меня есть такой для виртуально машины, по которому собственной и подключаюсь через SSH.
В общем если есть идеи, то подскажите куда копать и где может быть затык. Для начала нужно увидеть сканером открытый порт, а далее уже проверять правильно ли настроен WG и т.д.
Под спойлером 7 скриншотов с веб-интерфейса Oracle и терминал виртуальной машины для наглядности, хотел максимально подробно описать ситуацию.
rmspro commented Mar 25, 2021
@FireMasterK I have opened ports for Wireguard by adding ingress rules. Is there anything else to be done to configure the firewall on the Oracle side? By the way, I've also tried it with Ubuntu 20.04, same issue.
3. Adding Security list(ingress firewall rules):
or we can use netstat to see what processes are listening on which ports:
b. After knowing to which ports we need to allow connections, we need to create new security list to our vcn which our VPN-SERVER is currently using:
i) To do that we just click on the vcn id shown in the instance details.
ii) Then in next screen we choose Security Lists option and then choose Create Security List option.
iii) Add rules according to the below image. In subnet field we need to choose 0.0.0.0/0 and in source port range we choose all.
iv) Save the list and then we need to add the lit to our current subnet: For that choose subnet option and click on subnet id. It will open subnet settings.
v) Here we need to choose add security list option and choose our newly created security list named Algo. After these settings we should be able to connect to our VPN.
WireGuard is a cross-platform technology that enables you to create a VPN setup that is simple, fast, but secure through its implementation of the latest cryptography.
WireGuard is supported beginning with Unbreakable Enterprise Kernel Release 6 Update 3. Ensure that your system is upgraded to this release before proceeding to the steps in this chapter. For more information, see the Unbreakable Enterprise Kernel: Release Notes for Unbreakable Enterprise Kernel Release 6 Update 3.
hosseinmarvi commented May 9, 2021 •
@rayMomoko Thanks for your great help. It worked for me on a freshly installed Ubuntu 20.04.
I should also mention that having OpenVPN installed before WireGuard was another reason that I couldn't solve the issue with this workaround.
Для маршрутизации всего вашего трафика через шифрованный тоннель мы предлагаем использовать VPN WireGuard. Сейчас это один из самых передовых протоколов. Он реализован для многих платформ, включая Linux, macOS, Windows, Android и iOS, а скоро должен появиться во FreeBSD и в OpenBSD. В качестве транспортного протокола используется UDP, что даёт низкие накладные расходы на передачу данных. В качестве алгоритма симметричного шифрования используется ChaCha20, который эффективно работает на множестве процессоров даже без аппаратного ускорения. Реализация очень компактная (для Linux это 5500 строк кода), включена в официальный код ядра Linux, а значит прошла хорошее рецензирование, поэтому не должна иметь проблем с безопасностью.
Судя по всему, блокировка пока осуществляется по IP-адресам серверов конкретных известных поставщиков услуг VPN или по протоколу, но далеко не на всех портах. Это нас пока не волнует, поскольку мы будем настраивать собственный сервер и сможем указать альтернативный порт. Данное решение может оказаться временным, но тогда философия WireGuard тоже сыграет нам на руку, потому что мы сможем пробросить трафик в другой, уже более скрытный тоннель, например TCP, Tor или Shadowsocks с опциональной обфускацией. Гибкость такого подхода позволит нам выбрать решение в зависимости от ситуации. Мы постараемся предоставить соответствующие инструкции позже, а пока перейдём к настройке сервера WireGuard.
Для следования инструкциям в данной статье вам понадобится любой сервер за пределами России с операционной системой Ubuntu 21.04 или подобной и статическим внешним IP-адресом. Можно купить виртуальный сервер, например на DigitalOcean (партнёрская ссылка).
Также необходимо владеть навыками работы в консольном текстовом редакторе. Можно использовать Vim или Emacs, но они требуют изучения. Самым простым вариантом для новичков будет Nano. Устанавливается командой sudo apt install nano . Вызывается командой sudo nano , которой можно дополнительно передать имя файла: sudo nano /foo/bar . Далее можно разобраться по подсказкам в нижней части экрана. Они означают сочетания клавиши Ctrl с другими клавишами.
Все дальнейшие команды необходимо исполнять не просто от имени суперпользователя, а в его окружении. Если вы не вошли от его имени по SSH (а мы рекомендуем отключать такую возможность, о чём подробнее будет сказано в конце статьи), то выполните команду sudo su .
Применим новую конфигурацию:
Установим WireGuard и другие нужные пакеты:
Далее мы создадим файлы ключей и конфигурации. В целях безопасности необходимо ограничить доступ к ним только для суперпользователя, поэтому установим маску текущей сессии командной оболочки:
Сгенерируем ключи для сервера и пары клиентов (в дальнейшем мы будем подключать к VPN домашний компьютер и смартфон):
Выведем на экран сгенерированные ключи:
После окончания настройки сервера и клиентов или сейчас, если вы не собираетесь очищать экран, эти файлы можно удалить:
Теперь нужно выбрать порт и подсети IPv4 и IPv6. Мы будем использовать порт 37581 и подсети 10.73.105.0/24 и fd41:ce44:b4c9:44ca::/64 . Вы можете использовать их же или выбрать любой другой порт (от 1 до 65535, кроме 22, поскольку он используется для SSH) и любые подсети из 10.0.0.0/8 и fd00::/8 (если знаете, как их рассчитывать). Вопрос выбора порта особенно интересен, так как есть информация о блокировках WireGuard по порту, но мы не столкнулись ни с какими проблемами такого рода. На всякий случай рекомендуем не использовать стандартный порт 51820 .
Создадим файл /etc/wireguard/wg0.conf . Ключи нужно заменить на те, что мы сгенерировали. Название интерфейса eth0 у вас может отличаться, узнать его можно командой sudo ifconfig :
Теперь включим и запустим сервис:
Проверить работу сервера можно командой sudo wg show . На экране должна появиться следующая информация (ключи будут отличаться):
Здесь мы рассмотрим настройку WireGuard на настольном компьютере под управлением операционной системы Ubuntu 20.04 или подобной. Если вы используете другую операционную систему, то воспользуйтесь инструкциями из Интернета.
Повторим команды, которые мы уже использовали на сервере:
Теперь с помощью консольного текстового редактора создадим файл /etc/wireguard/wg0.conf . Ключи, опять же, нужно заменить на те, что мы сгенерировали. IP-адрес 164.90.178.225 замените на адрес вашего сервера:
Если вы использовали графический текстовый редактор, то файл нужно защитить явно:
Теперь включим и запустим сервис:
Проверить работу сервера можно командой sudo wg show . На экране должна появиться следующая информация (ключи и порт будут отличаться):
Узнать свой IP-адрес можно следующей командой:
Он должен совпадать с IP-адресом вашего сервера.
Если на вашем сервере настроен IPv6, то у вас он тоже будет работать, даже если ваш поставщик услуг Интернета не поддерживает его:
Для смартфонов под управлением операционной системы Android существует официальное приложение от оригинального разработчика WireGuard, доступное в Google Play Store и, конечно, для самостоятельной компиляции из исходного кода.
Интерфейс настройки повторяет структуру уже созданного нами ранее файла конфигурации для настольного компьютера, но мы всё-таки приведём пример заполнения полей. Опять же, нужно заменить ключи, IP-адрес и порт сервера на те, которые вы сгенерировали.
В секции “Interface”:
- Name: любое название
- Private key: SI+uObmWkwTXykuGk0E2LdClUvAmwkjRJA/XBo7//m4=
- Public key: QmmAJIv5U5eMynOHz6/b4zqtuEURhhaKxV+QVmHcRWQ= (должен появиться автоматически)
- Addresses: 10.73.105.3/32, fd41:ce44:b4c9:44ca::3/128
- DNS servers: 1.1.1.1
В секции “Peer” (нужно нажать кнопку “ADD PEER”):
- Public key: /Rv/4+vo9pGPRAL5EOAk/LkEy7nXdvKH4ZX5UkS78yA=
- Endpoint: 164.90.178.225:37581
- Allowed IPs: 0.0.0.0/0, ::/0
Также вы можете сгенерировать QR-код с вашей конфигурацией, который удобно считывать с помощью приложения WireGuard для смартфона. Для этого создайте где угодно файл конфигурации wg0.conf аналогичный тому, который мы создавали для настольного компьютера:
Теперь установить программу для генерации QR-кодов и запустите её:
Считайте этот QR-код с помощью приложения WireGuard для смартфона. Не забудьте после этого удалить файл конфигурации, так как он содержит ваш приватный ключ:
Теперь ваш VPN должен работать. Однако мы совсем не рассматривали вопросы безопасности.
Категорически важно обновить пакеты на вашем сервере и делать это регулярно (хотя бы раз в неделю):
Столь же важно включить аутентификацию в SSH по ключу вместо пароля или использовать очень длинный пароль (минимум 32 большие и маленькие цифры и буквы), а также сменить стандартный порт 22 на какой-нибудь другой (строка Port 22 в файле /etc/ssh/sshd_confg и команда sudo systemctl restart ssh.service для перезапуска).
Стоит запретить вход по SSH от имени суперпользователя. Для этого нужно создать другого пользователя, установить для него пароль и ключи SSH и раскомментировать в файле /etc/ssh/sshd_config строку PermitRootLogin no . Этот пользователь, хотя и будет иметь возможность исполнять команды от имени суперпользователя, должен требовать для этого ввод пароля. Таким образом, защита важных файлов будет состоять и из ключа, и из пароля.
Обычной практикой является использование сетевого экрана. В данном случае мы не видим в этом серьёзной необходимости, но всё-таки рекомендуем настроить его. Можно воспользоваться сетевым экраном вашего поставщика услуг VPS и самой операционной системы. Необходимо открыть порты SSH и WireGuard и запретить всё остальное. Следующие команды сохранят настройки и применят их даже после перезагрузки:
Проверить работу сетевого экрана можно командой sudo ufw status verbose .
В большинстве других случаев также рекомендуются такие практики, как настройка Fail2ban для предотвращения множественных попыток подключения по SSH или включение доступа по SSH только после простукивания портов (англ. port knocking), настройка мониторинга и сбора журналов. Однако это выходит за рамки данной статьи.
Есть три основные опасности, которые может представлять для вас незащищённый сервер VPN в случае его взлома:
Мы не считаем эти опасности очень критичными. При следовании советам из данной статьи они менее вероятны, чем, например, взлом домашнего маршрутизатора (англ. router), за безопасностью которых редко кто следит, насмотря на риски. Так что мы считаем, что если вы смогли выполнить указанные здесь инструкции, то вы вполне можете пользоваться собственным сервером VPN и не беспокоиться. Однако мы всё-таки надеемся, что вы не остановитесь на прочтении данного материала и подробнее изучите работу сетей и операционных систем. Хотя бы потому, что в современных условиях это может вам пригодиться, чтобы просто не потерять доступ в Интернет.
umairakhtar123 commented Mar 20, 2021
I am also facing the issue in setting up the Wireguard VPN on Oracle Cloud VM.
I followed the instruction and created the VPS and their clients but not working for me here are the details:
peer:
preshared key: (hidden)
allowed ips: 10.66.66.2/32, fd42:42:42::2/128
peer:
preshared key: (hidden)
allowed ips: 10.66.66.3/32, fd42:42:42::3/128
This is the Desktop client conf:
[Interface]
PrivateKey =
Address = 10.66.66.2/32, fd42:42:42::2/128
DNS = 94.140.14.14, 94.140.15.15
[Peer]
PublicKey =
PresharedKey =
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = 10.0.0.3:64399
Do you think it has something to do with the Firewall?
rayMomoko commented Apr 28, 2021 •
The script works perfectly for me like 6 months ago but not work for my new instances on Oracle cloud VM recently.
Allowing the udp port on Oracle dashboard is not the only work to make it works.
After adding the accept rule for udp port into iptables, you will see your client device start receiving and sending data with the VM.
But your client is still not able to access Internet.
It seems there is a prebuilt FORWARD rule on Oracle VM blocking the traffic.
The generated config /etc/wireguard/wg0.conf is using "-A" to append the rules to the bottom of FORWARD chain, you may modify it using "-I" instead so it will add the rules to the top, and after it, run "sudo wg-quick down/up wg0" for resetting the iptables.
It should work then. At least it works for me.
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT udp -- anywhere anywhere udp dpt:(port num) state NEW,ESTABLISHED
Chain FORWARD (policy ACCEPT)
target prot opt source destination
ACCEPT all -- anywhere anywhere
ACCEPT all -- anywhere anywhere
REJECT all -- anywhere anywhere reject-with icmp-host-prohibited
Configuring WireGuard
For simplicity, the following sections describe how to deploy WireGuard by using two hosts as examples. One host functions as the VPN server while the other is a client.
To use WireGuard, you need the following requirements:
IP addresses of both hosts. Use the ip addr sh command to obtain this information. For the procedures that follow, the IP addressess of the server and client are 10.0.0.1 and 10.0.0.2, respectively
Private IP addresses to be assigned to the WireGuard interfaces of both hosts. For the procedures that follow, the private IP addresses of the server and client are 192.168.2.1 and 192.168.2.2, respectively.
Name of the WireGuard interface. For the procedures that follow, the Wireguard interface name of both server and client is wg0 .
Console connections to the client.
Edit the /etc/sysctl.conf file with the following changes:
Run the sysctl command to reread the /etc/sysctl.conf file.
You can disregard the error messages that might appear about the command not being able to perform stat .
Create a directory where you can store the WireGuard key pair, for example:
In the directory you just created, generate a WireGuard cryptographic key pair.
You can specify any preferred names for the files to contain the server's private and public keys.
Obtain the server's private and public keys and store them in a temporary storage.
Create a directory where you can store the WireGuard key pair, for example:
In the directory you just created, generate a WireGuard cryptographic key pair.
You can specify any preferred names for the files to contain the client's private and public keys.
Obtain the client's private and public keys and store them in a temporary storage.
Edit the /etc/wireguard/wg0.conf file to contain the following:
Edit the /etc/wireguard/wg0.conf file to contain the following:
In the PostUp and PostDown lines of the example, the server's interface name is eno1 . Ensure that you specify the correct interface name of your server for those same lines. To display the server's IP interface, run the ip addr sh command.
Enabling the WireGuard Tunnel
Start the tunnel on the server.
Check the status of the tunnel in the server.
On a separate terminal window, log in to the client by using a console connection.
From this point on, all network traffic will be routed through the tunnel. If you are currently logged in to the client through SSH and then issue the command to start the tunnel, that connection becomes lost. You can only reconnect to the client through a console connection.
Start the tunnel on the client.
Check the status of the client.
You can use other commands to check the tunnel information, such as ip addr sh and ip link , for example:
umairakhtar123 commented Mar 20, 2021
I am also facing the issue in setting up the Wireguard VPN on Oracle Cloud VM.
I followed the instruction and created the VPS and their clients but not working for me here are the details:
peer:
preshared key: (hidden)
allowed ips: 10.66.66.2/32, fd42:42:42::2/128
peer:
preshared key: (hidden)
allowed ips: 10.66.66.3/32, fd42:42:42::3/128
This is the Desktop client conf:
[Interface]
PrivateKey =
Address = 10.66.66.2/32, fd42:42:42::2/128
DNS = 94.140.14.14, 94.140.15.15
[Peer]
PublicKey =
PresharedKey =
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = 10.0.0.3:64399
Do you think it has something to do with the Firewall?
Shutting Down the WireGuard Tunnel
To shut down the WireGuard tunnel, type the following command on both server and client.
After shutting down, you can optionally check the status of the tunnels by using one of the commands that were provided previously: wg , ip addr , or ip link .
Installing WireGuard
To configure a VPN with WireGuard, download the package with the following command:
You must install WireGuard on the server and all of its clients.
Читайте также: