WebSocket Connection to WireGuard
In some countries (e.g. Egypt) or some hotels, VPN connections are blocked and the only possibility is to tunnel them through WebSocket. In this article, I will focus on that.
Setting Up Nginx#
If you have an existing HTTPS server (e.g. nginx, Kubernetes, Traefik), you can put an HTTPS SNI proxy before your server. This will divide traffic between the WebSocket tunnel and your existing webserver-no need to change web certificates.
Firstly, we will install and configure Nginx.
/etc/nginx/nginx.conf
#
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 1024;
}
stream {
resolver 8.8.8.8;
map $ssl_preread_server_name $selected_upstream {
YOUR.WIREGUARD.WEBSITE.COM 127.0.0.1:10443;
default 127.0.0.1:8443; # YOUR EXISTING HTTPS WEBSERVER ADDRESS
}
}
server {
listen 443; # PORT WE WILL LISTEN ON
proxy_pass $selected_upstream;
ssl_preread on;
}
Installing WSTunnel#
Later we will install WSTunnel.
You can download it from https://github.com/erebe/wstunnel/releases and copy it to /usr/bin/
.
/etc/systemd/system/wstunnel.service
#
[Unit]
Description=WebSocket tunnel for WireGuard
After=network.target
[Service]
Type=simple
User=nobody
ExecStart=/usr/bin/wstunnel server wss://0.0.0.0:10443 --restrict-to 127.0.0.1:51820
Restart=no
[Install]
WantedBy=multi-user.target
This service will forward traffic to port 51820 on localhost where WireGuard is running.
Client Configuration#
To run the client on Windows, I have the following Python script in shell:startup
which runs the service in the background.
tunnel.pyw
#
import subprocess
DETACHED_PROCESS = 8
subprocess.Popen("C:\Windows\wstunnel.exe client wss://yourwebsite.com/ -L udp://51820:127.0.0.1:51820"
, creationflags=DETACHED_PROCESS, close_fds=True)
I run this script on every login to Windows, and then set up the WireGuard tunnel pointing to localhost:51820. If you want to route all traffic, you have to disallow the IP of yourwebsite.com from WireGuard. You can use the following calculator:
WireGuard Disallowed IPs#
https://www.procustodibus.com/blog/2021/03/wireguard-allowedips-calculator/