Como Criar um Servidor WireGuard para Acesso Remoto

Se você precisa de um túnel seguro para acessar redes remotamente, o WireGuard é uma das melhores opções. Ele é rápido, seguro e fácil de configurar. Neste post, vou mostrar como criar um servidor WireGuard e conectar clientes a ele.


1. Instalando o WireGuard

Debian/Ubuntu

apt update && apt install wireguard -y

CentOS/RHEL

yum install epel-release -y
yum install wireguard-tools -y

Arch Linux

pacman -S wireguard-tools

2. Gerando as Chaves do Servidor

WireGuard usa criptografia baseada em chave pública/privada. Vamos gerar as chaves:

wg genkey | tee server_private.key | wg pubkey > server_public.key

Agora, verifique as chaves:

cat server_private.key  # Chave privada do servidor
cat server_public.key   # Chave pública do servidor

3. Configurando o Servidor WireGuard

Edite o arquivo de configuração:

nano /etc/wireguard/wg0.conf

Adicione:

[Interface]
Address = 10.0.0.1/24
PrivateKey = <CHAVE_PRIVADA_DO_SERVIDOR>
ListenPort = 51820

# Para permitir acesso a toda a rede
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

Substitua <CHAVE_PRIVADA_DO_SERVIDOR> pela chave gerada.


4. Habilitando o Encaminhamento de Pacotes

Para permitir que os clientes se comuniquem com outras redes, ative o encaminhamento:

echo 'net.ipv4.ip_forward=1' >> /etc/sysctl.conf
sysctl -p

5. Iniciando e Ativando o WireGuard

systemctl enable wg-quick@wg0 --now

Para verificar se está rodando:

wg show

6. Configurando um Cliente WireGuard

Agora, configure um cliente para se conectar ao servidor.

Gerando as chaves do cliente:

wg genkey | tee client_private.key | wg pubkey > client_public.key

Adicionando o Cliente ao Servidor:

Edite /etc/wireguard/wg0.conf e adicione:

[Peer]
PublicKey = <CHAVE_PÚBLICA_DO_CLIENTE>
AllowedIPs = 10.0.0.2/32

Reinicie o WireGuard:

systemctl restart wg-quick@wg0

Configurando o Cliente:

Crie um arquivo wg-client.conf no cliente:

[Interface]
PrivateKey = <CHAVE_PRIVADA_DO_CLIENTE>
Address = 10.0.0.2/24

[Peer]
PublicKey = <CHAVE_PÚBLICA_DO_SERVIDOR>
Endpoint = <IP_DO_SERVIDOR>:51820
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25

Para iniciar o cliente:

wg-quick up wg-client

Agora, você pode acessar o servidor pelo IP 10.0.0.1 e utilizar o túnel WireGuard para comunicação segura.


Conclusão

Com essa configuração, você terá um servidor WireGuard pronto para conectar clientes de qualquer lugar, garantindo um acesso remoto seguro e rápido. Se precisar expandir a configuração para múltiplos clientes, basta adicionar mais [Peer] no wg0.conf.

Rolar para cima