User Tools

Site Tools


docu:csheet:net:relays:vpn_wireguard_vps

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
docu:csheet:net:relays:vpn_wireguard_vps [2023/06/30 00:14] admindocu:csheet:net:relays:vpn_wireguard_vps [2023/06/30 01:02] (current) admin
Line 2: Line 2:
  
 \\ \\
-In this tutorial you will learn how to connect your local network (mainlyPC) with a computer in other place (in this case a VPS on some cloud server). This wayyou can forward traffic IN and OUT to your local network from the internet, and keep the original IPs at the endwhile having another computer as a firewall or gateway.+En este tutorial aprenderás a conectar tu red local (principalmenteun PC) con una computadora en otro lugar (en este caso un VPS o algún servidor Cloud). Asípodremos enrutar tráfico de ENTRADA y SALIDA a tu red local desde internet, y preservar las IPs originales de la conexiónteniendo el servidor VPN como firewall gateway.
  
-\\ First of allmake sure your both VPS and local PC has ip_forward enabledYou might need to run this on every system start, as (maybe?it is not saved upon rebootYou can do so on cron, systemd, or directly on /etc/network/interfaces on a "post-up" statement.+Usaremos "VPS" para referirnos a la computadora con IP pública y que actuará como servidor VPN Wireguard, y "localpc" como computadora de nuestra infraestructura local, que solo tiene conexión a internet (incluso con CG NAT) y que se conectará como cliente a nuestro servidor "VPS" usando también la VPN Wireguard. 
 + 
 +\\ 
 +Lo primero de todoasegurate de que ambos VPS y localpc tienen habilitado el IP forwardingQuizás necesites ejecutar esto en cada inicio del sistema (quizás, no estoy seguro). Puedes hacerlo con cron, systemd o directamente en /etc/network/interfaces con un "post-up" en la interfaz que quieras.
 <code bash> <code bash>
 echo 1 > /proc/sys/net/ipv4/ip_forward echo 1 > /proc/sys/net/ipv4/ip_forward
Line 10: Line 13:
  
 \\ \\
-Secondinstall Wireguard on your both computers (both the VPS and local PC):+Segundoinstala Wireguard en tus dos computadoras (el VPS y el localpc):
 <code bash> <code bash>
 apt install wireguard wireguard-dkms apt install wireguard wireguard-dkms
  
-on some newer distros, just the following should work:+en algunas distros más nuevasbasta con ejecutar esto:
 apt install wireguard apt install wireguard
 </code> </code>
  
 \\ \\
-Create your Wireguard public/private keys on both computers (files are not neededjust their contentwe will remove them later).+Crea tus claves public/private en tus dos computadoras (los archivos en sí que generen no nos sirvensolo su contenido como textoluego los borraremos).
 <code bash> <code bash>
 cd /etc/wireguard/ cd /etc/wireguard/
Line 25: Line 28:
 </code> </code>
  
-Then, configure your server (the VPS) on **/etc/wireguard/<yoursrv>.conf** +Ahora configuraremos el Wireguard en el VPS. Editaremos el archivo **/etc/wireguard/<yoursrv>.conf**. Ten en cuenta que <yoursrv> va sin "<" ">" y "yoursrv" será el nombre de la interfaz de red que genere Wireguard. En todo el tutorial usaré "<>" para enmarcar valores variables.
-Please mind that <yoursrv> goes without "<" and ">" and will be the name of your Wireguard network interface created.+
 <code> <code>
 [Interface] [Interface]
-The address your wireguard interface will have+La direccción IP que tendrá la interfaz de Wireguard
 Address = 10.5.0.1/32 Address = 10.5.0.1/32
  
-We use 443 (UDP) to evade traffic limiting on our residential internet providersas QUIC (for example, YouTube) uses this port and they can't afford limiting or monitoring large amount of traffic on this port.+Usamos el 443 (UDP) para evadir la limitación de tráfico de los proveedores de internet residencialporque por ejemplo QUIC (usado por YouTube) hace que sea muy pesado el monitoreo de grandes cantidades de tráfico en ese puerto y protocolo.
 ListenPort = 443 ListenPort = 443
  
-PrivateKey = <copy the text from "private.key" file created before, the one of the VPS> +PrivateKey = <copia el contenido de "private.key" del VPS> 
-The next line is not needed (it is commented), is just a way to save the PublicKey in a place you can inspect later for further configurations+La siguiente línea no hace nada (está comentada), es solo una forma de guardar la PublicKey para poder utilizarla más tarde en otras configuraciones
-#PublicKey = <copy the text from "public.key" file created before, the one of the VPS>+#PublicKey = <copia el contenido de "public.key" del VPS>
  
-Nextwe add some series of "PostUp" commands that will be executed (obviouslyafter putting up the interface+Lo siguienteañadiremos una serie de comandos "PostUp" que se ejecutarán (evidentementedespués de levantar la interfaz
-Maybe not needed.+Quizás no sea necesario.
 PostUp = ifconfig yoursrv broadcast 10.5.0.255 up PostUp = ifconfig yoursrv broadcast 10.5.0.255 up
  
-Add the route needed for VPN clients. (Maybe not neededas i think wireguard already knows how to route to this clients either).+Añade la ruta que especifica por donde llegar a los clientes VPN. (Quizás no sea necesario tampocoporque creo que Wireguard mediante el kernel es capaz de enrutar el tráfico igualmente sin que aparezca en las rutas del sistema cuando escribes "ip route" por ejemplo).
 PostUp = ip route add 10.5.0.0/24       dev yoursrv PostUp = ip route add 10.5.0.0/24       dev yoursrv
  
-Totally optional other routes can be added this way+(totalmente opcional) otras rutas por ejemplo se añadirían así. En este caso enrutamos unas redes locales muy comunes por el otro punto de nuestra VPN punto a punto, que en este caso sería "localpc"
 #PostUp = ip route add 10/8              via 10.5.0.2 #PostUp = ip route add 10/8              via 10.5.0.2
 #PostUp = ip route add 192.168/16        via 10.5.0.2 #PostUp = ip route add 192.168/16        via 10.5.0.2
  
-Optionalmaybe useless as your server may already set MTU to 1420 by default +Opcionalquizás inutil porque creo que los servidores Wireguard suelen poner 1420 de MTU por defectoaunque a veces ponen otro valorSupongo que quizás se pone un valor óptimo automático según unos factores que desconozco.
-#  Keep in mind there is a reason (i don't know) Wireguard uses 1420 as MTU, so make sure your applications work correctly if using 1500 MTU (the default on most *nix systems)If not, make sure wherever your application is, the source network interface has 1420 as MTU also.+
 #PostUp = ifconfig yoursrv mtu 1420 #PostUp = ifconfig yoursrv mtu 1420
  
  
-peer configuration (server side) for your VPN client: localpc+configuración del par VPN para nuestro cliente: localpc
 [Peer] [Peer]
-PublicKey = <copy the text from "public.key" file created before, the one of the localpc> +PublicKey = <copia el contenido de "public.key" del localpc> 
-This setting specifies which IPs are allowed to pass to the gateway+Esta conf especifica qué IPs son permitidas para pasar por esta interfaz (en ambas direcciones, supongo). 
 +#  Ponemos la IP del peer y luego 0.0.0.0/0 entendiendo que pasará todo tipo de IPs por esta interfaz.
 AllowedIPs = 10.5.0.2/32, 0.0.0.0/0 AllowedIPs = 10.5.0.2/32, 0.0.0.0/0
 PersistentKeepalive = 5 PersistentKeepalive = 5
 </code> </code>
  
-Nowon the localpc, edit the file **/etc/wireguard/<whatever>.conf** and add this content:+Ahoraen el "localpc"modifica el archivo **/etc/wireguard/<whatever>.conf** y añade este contenido:
 <code> <code>
 [Interface] [Interface]
-This will be the IP of your localpc wireguard interface+Esta será la IP de la interfaz wireguard en tu localpc
 Address = 10.5.0.2/32 Address = 10.5.0.2/32
  
-PrivateKey = <copy the text from "private.key" file created before, the one of the localpc> +PrivateKey = <copia el contenido de "private.key" del localpc> 
-The next line is not needed (it is commented)is just a way to save the PublicKey in a place you can inspect later for further configurations+Como he dicho en la anterior configuración del VPSponemos esta siguiente línea comentada para tener este valor disponible por si necesitamos configurar otra cosa en adelante
-#PublicKey = <copy the text from "public.key" file created before, the one of the localpc>+#PublicKey = <copia el contenido de "public.key" del localpc>
  
 [Peer] [Peer]
-Which IPs are allowed to pass on the interface+Qué IPs son permitidas para pasar por la interfaz (también se usa para enrutar todo el tráfico de salida por esta interfaz). Es extraño Wireguard, no me preguntes como funciona, no lo sé xD
 AllowedIPs = 10.5.0.0/24, 0.0.0.0/0 AllowedIPs = 10.5.0.0/24, 0.0.0.0/0
-PublicKey = <copy the text from "public.key" file created before, the one of the VPS> +PublicKey = <copia el contenido de "public.key" del VPS> 
-EndPoint = <IP_of_the_VPS>:443 # remember: 443/udp, and it must be reachable+EndPoint = <IP_publica_VPS>:443 # recuerda: 443/udp, y debe ser alcanzable por tu localpc
 PersistentKeepalive = 30 PersistentKeepalive = 30
 </code> </code>
  
 \\ \\
-Thenremove the "public.key" and "private.key" files on both computers:+Luegoborra los archivos "public.key" "private.key" en ambas computadoras:
 <code bash> <code bash>
 cd /etc/wireguard/ cd /etc/wireguard/
Line 89: Line 91:
  
 \\ \\
-Finallyget both interfaces up with the wg-quick command or using systemd if you have it.+Casi para terminarlevanta las dos interfaces desde ambas computadoras usando wg-quick o en su defecto systemd si tienes.
 <code bash> <code bash>
-on the VPS: +en el VPS: 
-wg-quick up yoursrv # the manual way +wg-quick up yoursrv # la forma manual (tienes que programar autoejecución en el startup) 
-systemctl enable wg-quick@yoursrv; systemctl start wg-quick@yoursrv # the systemd way+systemctl enable wg-quick@yoursrv; systemctl start wg-quick@yoursrv # la forma systemd (ya se autoejecuta en el startup)
  
-on the localpc: +en el localpc: 
-wg-quick up whatever # the manual way +wg-quick up whatever # la forma manual (tienes que programar autoejecución en el startup) 
-systemctl enable wg-quick@whatever; systemctl start wg-quick@whatever # the systemd way +systemctl enable wg-quick@whatever; systemctl start wg-quick@whatever # la forma systemd (ya se autoejecuta en el startup)
- +
-# mind we used "yoursrv" interface name on the VPS and "whatever" on localpc just to differentiate and prove that we can use different names and it does not affect the way it will work. You can also use the same name for both.+
 </code> </code>
 +Fijate que hemos usado el nombre de interfaz "yoursrv" en el VPS y "whatever" en el localpc para diferenciar y demostrar que podemos usar nombres distintos para las interfaces y no afectarán para nada en su funcionamiento, aunque si usas los mismos nombres funcionará igualmente. Es más, quizás sea más recomendado, para no liarse, pero esto es para que se entienda.
  
 \\ \\
-If everything is OKyou should be able to ping your VPS from localpc with:+Si todo está biendeberías poder hacer ping a tu VPS desde el localpc con:
 <code bash> <code bash>
 ping 10.5.0.1 ping 10.5.0.1
  
-Check the wireguard status on any host by using:+Comprueba el estado de wireguard en cualquier nodo que tenga wireguard configurado.
 wg wg
 </code> </code>
  
 \\ \\
-To end with this tutorialyou need this final steps too: +Y finalmentepara terminar, necesitamos enrutar tráfico para que funcione. Vamos a hacer un ejemplo con enrutamiento de HTTP (que es lo más comúnpero esto se usaría igual para cada servicio que queramos enrutar nuestra IP interna. Para elloejecutaremos estos comandos de iptables (debemos tenerlo instalado):
-In order to route some traffic (say, for example webto localpcyou must write some iptables rules. In our example, we could do it like this. This rules (except otherwise mentionedare executed on the VPS.+
 <code bash> <code bash>
-route the IN traffic on ports 80,443 TCP to your localpc VPN IP. (You could also use another internal network IP if you add corresponding routes on Wireguard configuration). +ejecutar en "VPS": enruta el tráfico de ENTRADA a la IP pública del VPSen los puertos TCP 80 y 443, al destino 10.5.0.2 (que en este ejemplo sería la IP de localpc en la VPN). 
-iptables -t nat -A PREROUTING -d <public_ip_of_VPS> -p tcp -m multiport --dports 80,443 -j DNAT --to-destination 10.5.0.2+iptables -t nat -A PREROUTING -d <ip_public_del_VPS> -p tcp -m multiport --dports 80,443 -j DNAT --to-destination 10.5.0.2 
 + 
 +# ejecutar en "VPS": enmascara (cambia la IP) del tráfico en la SALIDA cuando el tráfico (establecido o nuevo) sale de localpc a internet por la VPN, ya que si salimos con una IP interna (de la VPN), el siguiente gateway no sabría como enrutar de vuelta, y menos todavía la IP de destino final (que es otra IP en internet). 
 +iptables -t nat -A POSTROUTING -s 10.5.0.2/32 -o <nombre_interfaz_VPS_ip_publica> -j MASQUERADE
  
-# Masquerade IP of the VPN localpc when going OUT of the public (internet facing) interface. 
-iptables -t nat -A POSTROUTING -s 10.5.0.2/32 -o <interface_name_of_public_ip_of_VPS> -j MASQUERADE 
  
-At the localpc, run this command (this is a "hack" to fix MTU problems on some applications, as Wireguard uses 1420 MTU and the internet normally uses 1500):+ejecutar en "localpc": este comando es un "hack" que permite solucionar el problema de disconcordancias de MTU en ciertas aplicaciones TCP que pueden no funcionar correctamente. Esto evita tener que cambiar el MTU de cada interfaz de red donde tengamos aplicaciones que puedan no funcionar. Fuente: https://tldp.org/HOWTO/Adv-Routing-HOWTO/lartc.cookbook.mtu-mss.html
 iptables -A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu iptables -A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
  
-Optionallyif you use a DROP policy on your FORWARD iptables filter, you must also add this+ejecutar en "VPS": OpcionalmenteSOLO si tenemos una política DROP en nuestro filter de iptables "FORWARD"debes añadir esto
-iptables -A FORWARD -i <interface_name_of_public_ip_of_VPS> -d 10.5.0.2 -p tcp -m multiport --dports 80,443 -j ACCEPT +iptables -A FORWARD -i <nombre_interfaz_VPS_ip_publica> -d 10.5.0.2/32 -p tcp -m multiport --dports 80,443 -j ACCEPT 
-iptables -A FORWARD -i <yoursrv> -o <interface_name_of_public_ip_of_VPS> -j ACCEPT+iptables -A FORWARD -i <yoursrv> -o <nombre_interfaz_VPS_ip_publica> -j ACCEPT
 </code> </code>
  
 \\ \\
-With all of thisyou should now be able to get internet traffic into your localpc with the original IPs!+Con todo estodeberías por fin recibir tráfico en tu localpc con las IPs originales y sobre todo sabiendo que pasamos por una IP públic fija que no depende de infraestructuras complicadas de DDNS y que además nos supone una posible protección extra ante ataques DDoS o similares, ya que se podría cortar el tráfico y evitar la caída de más nodos de nuestra red.
docu/csheet/net/relays/vpn_wireguard_vps.1688084056.txt.gz · Last modified: 2023/06/30 00:14 by admin