GNU/Linux >> Linux Esercitazione >  >> Panels >> OpenVPN

Come configurare WireGuard su Ubuntu 22.04

Introduzione

WireGuard è una rete privata virtuale (VPN) leggera che supporta connessioni IPv4 e IPv6. Una VPN ti consente di attraversare reti non affidabili come se fossi su una rete privata. Ti dà la libertà di accedere a Internet in modo sicuro dal tuo smartphone o laptop quando sei connesso a una rete non affidabile, come il Wi-Fi di un hotel o di un bar.

La crittografia di WireGuard si basa su chiavi pubbliche e private per consentire ai peer di stabilire un tunnel crittografato tra loro. Ogni versione di WireGuard utilizza una specifica suite di crittografia crittografica per garantire semplicità, sicurezza e compatibilità con i peer.

In confronto, altri software VPN come OpenVPN e IPSec utilizzano Transport Layer Security (TLS) e certificati per autenticare e stabilire tunnel crittografati tra i sistemi. Diverse versioni di TLS includono il supporto per centinaia di suite crittografiche e algoritmi diversi e, sebbene ciò consenta una grande flessibilità per supportare client diversi, rende anche la configurazione di una VPN che utilizza TLS più dispendiosa in termini di tempo, complessa e soggetta a errori.

In questo tutorial, configurerai WireGuard su un server Ubuntu 22.04, quindi configurerai un'altra macchina per connettersi ad esso come peer utilizzando connessioni IPv4 e IPv6 (comunemente chiamate dual stack connessione). Imparerai anche come instradare il traffico Internet del peer attraverso il server WireGuard in una configurazione gateway, oltre a utilizzare la VPN per un tunnel peer-to-peer crittografato.

Ai fini di questo tutorial, configureremo un altro sistema Ubuntu 22.04 come peer (indicato anche come client) per WireGuard Server. I tutorial successivi di questa serie spiegheranno come installare ed eseguire WireGuard su sistemi e dispositivi Windows, macOS, Android e iOS.

Nota: Se prevedi di configurare WireGuard su un Droplet DigitalOcean, tieni presente che noi, come molti provider di hosting, addebitiamo i sovraccarichi di larghezza di banda. Per questo motivo, fai attenzione a quanto traffico sta gestendo il tuo server. Vedi questa pagina per maggiori informazioni.

Prerequisiti

Per seguire questo tutorial, avrai bisogno di:

  • Un server Ubuntu 22.04 con un utente sudo non root e un firewall abilitato. Per configurarlo, puoi seguire il nostro tutorial Configurazione iniziale del server con Ubuntu 22.04. Lo chiameremo Server WireGuard in questa guida.
  • Avrai bisogno di una macchina client che utilizzerai per connetterti al tuo WireGuard Server. In questo tutorial faremo riferimento a questa macchina come WireGuard Peer . Ai fini di questo tutorial, ti consigliamo di utilizzare la tua macchina locale come WireGuard Peer, ma puoi utilizzare server remoti o telefoni cellulari come client se preferisci. Se stai utilizzando un sistema remoto, assicurati di seguire tutte le sezioni facoltative più avanti in questo tutorial o potresti escluderti dal sistema.
  • Per utilizzare WireGuard con IPv6, dovrai anche assicurarti che il tuo server sia configurato per supportare quel tipo di traffico. Se desideri abilitare il supporto IPv6 con WireGuard e stai utilizzando un Droplet DigitalOcean, fai riferimento a questa pagina della documentazione Come abilitare IPv6 sui droplet. Puoi aggiungere il supporto IPv6 quando crei un Droplet o in seguito utilizzando le istruzioni in quella pagina.

Fase 1:installazione di WireGuard e generazione di una coppia di chiavi

Il primo passo in questo tutorial è installare WireGuard sul tuo server. Per iniziare, aggiorna l'indice del pacchetto del tuo server WireGuard e installa WireGuard utilizzando i seguenti comandi. Potrebbe esserti richiesto di fornire la password del tuo utente sudo se è la prima volta che utilizzi sudo in questa sessione:

  1. sudo apt update
  2. sudo apt install wireguard

Ora che WireGuard è installato, il passaggio successivo consiste nel generare una coppia di chiavi privata e pubblica per il server. Utilizzerai il wg genkey integrato e wg pubkey comandi per creare le chiavi, quindi aggiungere la chiave privata al file di configurazione di WireGuard.

Dovrai anche cambiare i permessi sulla chiave che hai appena creato usando il chmod comando, poiché per impostazione predefinita il file è leggibile da qualsiasi utente sul tuo server.

Crea la chiave privata per WireGuard e modifica i suoi permessi usando i seguenti comandi:

  1. wg genkey | sudo tee /etc/wireguard/private.key
  2. sudo chmod go= /etc/wireguard/private.key

Il sudo chmod go=... Il comando rimuove tutte le autorizzazioni sul file per utenti e gruppi diversi dall'utente root per garantire che solo lui possa accedere alla chiave privata.

Dovresti ricevere una singola riga di base64 output codificato, che è la chiave privata. Una copia dell'output è anche memorizzata in /etc/wireguard/private.key file per riferimento futuro tramite il tee parte del comando. Prendi nota con attenzione della chiave privata che viene emessa poiché dovrai aggiungerla al file di configurazione di WireGuard più avanti in questa sezione.

Il passaggio successivo consiste nel creare la chiave pubblica corrispondente, che deriva dalla chiave privata. Utilizzare il comando seguente per creare il file della chiave pubblica:

  1. sudo cat /etc/wireguard/private.key | wg pubkey | sudo tee /etc/wireguard/public.key

Questo comando è composto da tre singoli comandi che sono concatenati insieme usando il | Operatore (tubo):

  • sudo cat /etc/wireguard/private.key :questo comando legge il file della chiave privata e lo invia al flusso di output standard.
  • wg pubkey :il secondo comando prende l'output del primo comando come input standard e lo elabora per generare una chiave pubblica.
  • sudo tee /etc/wireguard/public.key :il comando finale prende l'output del comando di generazione della chiave pubblica e lo reindirizza nel file denominato /etc/wireguard/public.key .

Quando esegui il comando riceverai di nuovo una singola riga di base64 output codificato, che è la chiave pubblica del server WireGuard. Copialo da qualche parte come riferimento, poiché dovrai distribuire la chiave pubblica a qualsiasi peer che si connette al server.

Passaggio 2:scelta degli indirizzi IPv4 e IPv6

Nella sezione precedente hai installato WireGuard e generato una coppia di chiavi che verrà utilizzata per crittografare il traffico da e verso il server. In questa sezione creerai un file di configurazione per il server e configurerai WireGuard per l'avvio automatico al riavvio del server. Definirai anche indirizzi IPv4 e IPv6 privati ​​da utilizzare con il tuo WireGuard Server e peer.

Se prevedi di utilizzare entrambi gli indirizzi IPv4 e IPv6, segui entrambe queste sezioni. In caso contrario, segui le istruzioni nella sezione appropriata per le esigenze di rete della tua VPN.

Fase 2(a) — Scelta di un intervallo IPv4

Se stai utilizzando il tuo server WireGuard con peer IPv4, il server necessita di un intervallo di indirizzi IPv4 privati ​​da utilizzare per i client e per la sua interfaccia tunnel. Puoi scegliere qualsiasi intervallo di indirizzi IP dai seguenti blocchi di indirizzi riservati (se desideri saperne di più su come vengono assegnati questi blocchi, visita la specifica RFC 1918):

  • 10.0.0.0 a 10.255.255.255 (prefisso 10/8)
  • 172.16.0.0 a 172.31.255.255 (prefisso 172.16/12)
  • 192.168.0.0 a 192.168.255.255 (prefisso 192.168/16)

Ai fini di questo tutorial useremo 10.8.0.0/24 come blocco di indirizzi IP dal primo intervallo di IP riservati. Questo intervallo consentirà fino a 255 diverse connessioni peer e generalmente non dovrebbe avere indirizzi sovrapposti o in conflitto con altri intervalli di IP privati. Sentiti libero di scegliere un intervallo di indirizzi che funzioni con la tua configurazione di rete se questo intervallo di esempio non è compatibile con le tue reti.

Il server WireGuard utilizzerà un singolo indirizzo IP dall'intervallo per il suo indirizzo IPv4 del tunnel privato. Useremo 10.8.0.1/24 qui, ma qualsiasi indirizzo nell'intervallo 10.8.0.1 a 10.8.0.255 può essere utilizzato. Prendi nota dell'indirizzo IP che scegli se utilizzi qualcosa di diverso da 10.8.0.1/24 . Aggiungerai questo indirizzo IPv4 al file di configurazione che definisci nel Passaggio 3 — Creazione di una configurazione del server WireGuard.

Passaggio 2(b):scelta di un intervallo IPv6

Se si utilizza WireGuard con IPv6, sarà necessario generare un prefisso di indirizzo unicast IPv6 locale univoco basato sull'algoritmo in RFC 4193. Gli indirizzi utilizzati con WireGuard saranno associati a un'interfaccia tunnel virtuale. Dovrai completare alcuni passaggi per generare un prefisso IPv6 casuale e univoco all'interno del fd00::/8 riservato blocco di indirizzi IPv6 privati.

Secondo la RFC, il modo consigliato per ottenere un prefisso IPv6 univoco è combinare l'ora del giorno con un valore identificativo univoco da un sistema come un numero di serie o un ID dispositivo. Tali valori vengono quindi sottoposti a hash e troncati risultando in un insieme di bit che possono essere utilizzati come indirizzo univoco all'interno del fd00::/8 privato riservato blocco di IP.

Per iniziare a generare un intervallo IPv6 per il tuo server WireGuard, raccogli un timestamp a 64 bit utilizzando la date utility con il seguente comando:

  1. date +%s%N

Riceverai un numero come il seguente, che è il numero di secondi (il %s nella date comando) e nanosecondi (il %N ) dal 1970-01-01 00:00:00 UTC combinati insieme:

Output1650301699497770167

Registrare il valore da qualche parte per utilizzarlo più avanti in questa sezione. Quindi, copia il machine-id valore per il tuo server da /var/lib/dbus/machine-id file. Questo identificatore è univoco per il tuo sistema e non dovrebbe cambiare finché il server esiste.

  1. cat /var/lib/dbus/machine-id

Riceverai un output come il seguente:

/var/lib/dbus/machine-id610cef4946ed46da8f71dba9d66c67fb

Ora devi combinare il timestamp con il machine-id ed eseguire l'hashing del valore risultante utilizzando l'algoritmo SHA-1. Il comando utilizzerà il seguente formato:

printf <timestamp><machine-id> | sha1sum

Esegui il comando sostituendo i valori di timestamp e identità macchina:

  1. printf 1650301699497770167610cef4946ed46da8f71dba9d66c67fb | sha1sum

Riceverai un valore hash come il seguente:

Output442adea1488d96388dae9ab816045b24609a6c18  -

Nota che l'output di sha1sum il comando è in esadecimale, quindi l'output utilizza due caratteri per rappresentare un singolo byte di dati. Ad esempio 4f e 26 nell'output di esempio sono i primi due byte dei dati hash.

L'algoritmo nell'RFC richiede solo i 40 bit o 5 byte meno significativi dell'output hash. Usa il cut comando per stampare gli ultimi 5 byte codificati esadecimali dall'hash:

  1. printf 442adea1488d96388dae9ab816045b24609a6c18 | cut -c 31-

Il -c argomento dice il cut comando per selezionare solo un set di caratteri specificato. Il 31- argomento dice cut per stampare tutti i caratteri dalla posizione 31 alla fine della riga di input.

Dovresti ricevere un output come il seguente:

Output24609a6c18

In questo output di esempio, l'insieme di byte è:24 60 9a 6c 18 .

Ora puoi costruire il tuo prefisso di rete IPv6 univoco aggiungendo i 5 byte che hai generato con fd prefisso, separando ogni 2 byte con un : due punti per la leggibilità. Poiché ogni sottorete nel tuo prefisso univoco può contenere un totale di 18.446.744.073.709.551.616 possibili indirizzi IPv6, puoi limitare la sottorete a una dimensione standard di /64 per semplicità.

Utilizzando i byte precedentemente generati con il /64 subnet size il prefisso risultante sarà il seguente:

Unique Local IPv6 Address Prefixfd24:609a:6c18::/64

Questo fd24:609a:6c18::/64 range è ciò che utilizzerai per assegnare singoli indirizzi IP alle interfacce del tunnel WireGuard sul server e sui peer. Per allocare un IP per il server, aggiungi un 1 dopo il :: finale caratteri. L'indirizzo risultante sarà fd24:609a:6c18::1/64 . I peer possono utilizzare qualsiasi IP nell'intervallo, ma in genere incrementerai il valore di uno ogni volta che aggiungi un peer, ad es. fd24:609a:6c18::2/64 . Prendere nota dell'IP e procedere con la configurazione del WireGuard Server nella sezione successiva di questo tutorial.

Fase 3 — Creazione di una configurazione del server WireGuard

Prima di creare la configurazione del tuo WireGuard Server, avrai bisogno delle seguenti informazioni:

  1. Assicurati di avere la chiave privata disponibile dal passaggio 1:installazione di WireGuard e generazione di una coppia di chiavi.

  2. Se stai utilizzando WireGuard con IPv4, avrai bisogno dell'indirizzo IP che hai scelto per il server nel passaggio 2(a) — Scelta di un intervallo IPv4, che in questo esempio è 10.8.0.1/24 .

  3. Se stai utilizzando WireGuard con IPv6, avrai bisogno dell'indirizzo IP per il server che hai generato nel Passaggio 2(b) — Scelta di un intervallo IPv6. In questo esempio l'IP è fd24:609a:6c18::1/64 .

Una volta che hai la chiave privata e gli indirizzi IP richiesti, crea un nuovo file di configurazione usando nano o il tuo editor preferito eseguendo il comando seguente:

  1. sudo nano /etc/wireguard/wg0.conf

Aggiungi le seguenti righe al file, sostituendo la tua chiave privata al posto di base64_encoded_private_key_goes_here evidenziata valore e gli indirizzi IP su Address linea. Puoi anche modificare il ListenPort riga se desideri che WireGuard sia disponibile su una porta diversa:

/etc/wireguard/wg0.conf[Interface]
PrivateKey = base64_encoded_private_key_goes_here
Address = 10.8.0.1/24, fd24:609a:6c18::1/64
ListenPort = 51820
SaveConfig = true

Il SaveConfig assicura che quando un'interfaccia WireGuard viene arrestata, tutte le modifiche verranno salvate nel file di configurazione.

Salva e chiudi il /etc/wireguard/wg0.conf file. Se stai usando nano , puoi farlo con CTRL+X , quindi Y e ENTER per confermare. Ora hai una configurazione del server iniziale su cui puoi basarti a seconda di come prevedi di utilizzare il tuo server VPN WireGuard.

Fase 4:regolazione della configurazione di rete del server WireGuard

Se stai usando WireGuard per connettere un peer al WireGuard Server per accedere ai servizi sul solo server , non è necessario completare questa sezione. Se desideri instradare il traffico Internet del tuo peer WireGuard attraverso il server WireGuard, dovrai configurare l'inoltro IP seguendo questa sezione del tutorial.

Per configurare l'inoltro, apri /etc/sysctl.conf file utilizzando nano o il tuo editor preferito:

  1. sudo nano /etc/sysctl.conf

Se stai usando IPv4 con WireGuard, aggiungi la seguente riga in fondo al file:

/etc/sysctl.conf
net.ipv4.ip_forward=1

Se stai usando IPv6 con WireGuard, aggiungi questa riga in fondo al file:

/etc/sysctl.conf
net.ipv6.conf.all.forwarding=1

Se utilizzi sia IPv4 che IPv6, assicurati di includere entrambe le righe. Salva e chiudi il file quando hai finito.

Per leggere il file e caricare i nuovi valori per la sessione del terminale corrente, eseguire:

  1. sudo sysctl -p
Outputnet.ipv6.conf.all.forwarding = 1
net.ipv4.ip_forward = 1

Ora il tuo WireGuard Server sarà in grado di inoltrare il traffico in entrata dal dispositivo ethernet VPN virtuale ad altri sul server e da lì a Internet pubblico. L'utilizzo di questa configurazione ti consentirà di instradare tutto il traffico web dal tuo peer WireGuard tramite l'indirizzo IP del tuo server e l'indirizzo IP pubblico del tuo cliente sarà effettivamente nascosto.

Tuttavia, prima che il traffico possa essere instradato correttamente tramite il tuo server, dovrai configurare alcune regole del firewall. Queste regole assicureranno che il traffico da e verso il tuo WireGuard Server e Peer fluisca correttamente.

Passaggio 5:configurazione del firewall del server WireGuard

In questa sezione modificherai la configurazione del server WireGuard per aggiungere regole firewall che assicureranno che il traffico da e verso il server e i client sia instradato correttamente. Come per la sezione precedente, salta questo passaggio se stai utilizzando la tua VPN WireGuard solo per una connessione da macchina a macchina per accedere a risorse limitate alla tua VPN.

Per consentire il traffico VPN WireGuard attraverso il firewall del server, dovrai abilitare il masquerading, che è un concetto iptables che fornisce la traduzione dinamica degli indirizzi di rete (NAT) al volo per instradare correttamente le connessioni client.

Per prima cosa trova l'interfaccia di rete pubblica del tuo WireGuard Server usando il ip route sottocomando:

  1. ip route list default

L'interfaccia pubblica è la stringa trovata all'interno dell'output di questo comando che segue la parola "dev". Ad esempio, questo risultato mostra l'interfaccia denominata eth0 , che viene evidenziato di seguito:

Outputdefault via 203.0.113.1 dev eth0 proto static

Prendi nota del nome del tuo dispositivo poiché lo aggiungerai a iptables regole nel passaggio successivo.

Per aggiungere regole firewall al tuo WireGuard Server, apri il /etc/wireguard/wg0.conf file con nano o di nuovo il tuo editor preferito.

  1. sudo nano /etc/wireguard/wg0.conf

In fondo al file dopo SaveConfig = true riga, incolla le seguenti righe:

/etc/wireguard/wg0.conf. . .
PostUp = ufw route allow in on wg0 out on eth0
PostUp = iptables -t nat -I POSTROUTING -o eth0 -j MASQUERADE
PostUp = ip6tables -t nat -I POSTROUTING -o eth0 -j MASQUERADE
PreDown = ufw route delete allow in on wg0 out on eth0
PreDown = iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
PreDown = ip6tables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

Il PostUp le linee verranno eseguite quando WireGuard Server avvia il tunnel VPN virtuale. Nell'esempio qui, verranno aggiunti tre ufw e iptables regole:

  • ufw route allow in on wg0 out on eth0 - Questa regola consentirà di inoltrare il traffico IPv4 e IPv6 che arriva su wg0 Interfaccia VPN per eth0 interfaccia di rete sul server. Funziona in combinazione con net.ipv4.ip_forward e net.ipv6.conf.all.forwarding sysctl che hai configurato nella sezione precedente.
  • iptables -t nat -I POSTROUTING -o eth0 -j MASQUERADE - Questa regola configura il masquerading e riscrive il traffico IPv4 che arriva su wg0 Interfaccia VPN per far sembrare che provenga direttamente dall'indirizzo IPv4 pubblico del server WireGuard.
  • ip6tables -t nat -I POSTROUTING -o eth0 -j MASQUERADE - Questa regola configura il masquerading e riscrive il traffico IPv6 che arriva su wg0 Interfaccia VPN per far sembrare che provenga direttamente dall'indirizzo IPv6 pubblico del server WireGuard.

Il PreDown le regole vengono eseguite quando WireGuard Server interrompe il tunnel VPN virtuale. Queste regole sono l'inverso del PostUp regole e funzione per annullare le regole di inoltro e mascheramento per l'interfaccia VPN quando la VPN viene interrotta.

In entrambi i casi, modifica la configurazione per includere o escludere le regole IPv4 e IPv6 appropriate per la tua VPN. Ad esempio, se stai usando solo IPv4, puoi escludere le righe con ip6tables comandi.

Al contrario, se stai usando solo IPv6, modifica la configurazione per includere solo ip6tables comandi. Il ufw linee dovrebbero esistere per qualsiasi combinazione di reti IPv4 e IPv6. Salva e chiudi il file quando hai finito.

L'ultima parte della configurazione del firewall sul server WireGuard consiste nel consentire il traffico da e verso la porta UDP WireGuard stessa. Se non hai cambiato la porta nel /etc/wireguard/wg0.conf del server file, la porta che aprirai è 51820 . Se hai scelto una porta diversa durante la modifica della configurazione assicurati di sostituirla nel seguente comando UFW.

Nel caso in cui ti sei dimenticato di aprire la porta SSH dopo aver seguito il tutorial dei prerequisiti, aggiungilo anche qui:

  1. sudo ufw allow 51820/udp
  2. sudo ufw allow OpenSSH

Nota :Se stai utilizzando un firewall diverso o hai personalizzato la tua configurazione UFW, potrebbe essere necessario aggiungere regole firewall aggiuntive. Ad esempio, se decidi di incanalare tutto il traffico di rete sulla connessione VPN, dovrai assicurarti che la porta 53 il traffico è consentito per le richieste DNS e le porte come 80 e 443 rispettivamente per il traffico HTTP e HTTPS. Se ci sono altri protocolli che stai utilizzando tramite la VPN, dovrai aggiungere regole anche per loro.

Dopo aver aggiunto queste regole, disabilita e riattiva UFW per riavviarlo e caricare le modifiche da tutti i file che hai modificato:

  1. sudo ufw disable
  2. sudo ufw enable

Puoi confermare che le regole sono in vigore eseguendo ufw status comando. Eseguilo e dovresti ricevere un output come il seguente:

  1. sudo ufw status
OutputStatus: active

To                         Action      From
--                         ------      ----
51280/udp                  ALLOW       Anywhere                  
22/tcp                     ALLOW       Anywhere                  
51280/udp (v6)             ALLOW       Anywhere (v6)             
22/tcp (v6)                ALLOW       Anywhere (v6)

Il tuo WireGuard Server è ora configurato per gestire correttamente il traffico della VPN, incluso l'inoltro e il mascheramento per i peer. Con le regole del firewall in atto, puoi avviare il servizio WireGuard stesso per ascoltare le connessioni peer.

Passaggio 6:avvio del server WireGuard

WireGuard può essere configurato per essere eseguito come systemd servizio utilizzando il suo wg-quick integrato sceneggiatura. Mentre potresti usare manualmente il wg comando per creare il tunnel ogni volta che si desidera utilizzare la VPN, farlo è un processo manuale che diventa ripetitivo e soggetto a errori. Invece, puoi usare systemctl per gestire il tunnel con l'ausilio del wg-quick copione.

Usando un systemd servizio significa che puoi configurare WireGuard per l'avvio all'avvio in modo da poterti connettere alla tua VPN in qualsiasi momento finché il server è in esecuzione. Per fare ciò, abilita il wg-quick servizio per il wg0 tunnel che hai definito aggiungendolo a systemctl :

  1. sudo systemctl enable [email protected]

Si noti che il comando specifica il nome del tunnel wg0 nome del dispositivo come parte del nome del servizio. Questo nome corrisponde a /etc/wireguard/wg0.conf file di configurazione. Questo approccio alla denominazione significa che puoi creare tutti i tunnel VPN separati che desideri utilizzando il tuo server.

Ad esempio, potresti avere un dispositivo tunnel e il nome di prod e il suo file di configurazione sarebbe /etc/wireguard/prod.conf . Ciascuna configurazione del tunnel può contenere diverse impostazioni del firewall IPv4, IPv6 e client. In questo modo puoi supportare più connessioni peer differenti, ognuna con i propri indirizzi IP e regole di routing univoci.

Ora avvia il servizio:

  1. sudo systemctl start [email protected]

Verifica che il servizio WireGuard sia attivo con il comando seguente. Dovresti vedere active (running) nell'output:

  1. sudo systemctl status [email protected]
Output● [email protected] - WireGuard via wg-quick(8) for wg0
     Loaded: loaded (/lib/systemd/system/[email protected]; enabled; vendor preset: enabled)
     Active: active (exited) since Mon 2022-04-18 17:22:13 UTC; 2s ago
       Docs: man:wg-quick(8)
             man:wg(8)
             https://www.wireguard.com/
             https://www.wireguard.com/quickstart/
             https://git.zx2c4.com/wireguard-tools/about/src/man/wg-quick.8
             https://git.zx2c4.com/wireguard-tools/about/src/man/wg.8
    Process: 98834 ExecStart=/usr/bin/wg-quick up wg0 (code=exited, status=0/SUCCESS)
   Main PID: 98834 (code=exited, status=0/SUCCESS)
        CPU: 193ms

Apr 18 17:22:13 thats-my-jam wg-quick[98834]: [#] wg setconf wg0 /dev/fd/63
Apr 18 17:22:13 thats-my-jam wg-quick[98834]: [#] ip -4 address add 10.8.0.1/24 dev wg0
Apr 18 17:22:13 thats-my-jam wg-quick[98834]: [#] ip -6 address add fd24:609a:6c18::1/64 dev wg0
Apr 18 17:22:13 thats-my-jam wg-quick[98834]: [#] ip link set mtu 1420 up dev wg0
Apr 18 17:22:13 thats-my-jam wg-quick[98834]: [#] ufw route allow in on wg0 out on ens3
Apr 18 17:22:13 thats-my-jam wg-quick[98890]: Rule added
Apr 18 17:22:13 thats-my-jam wg-quick[98890]: Rule added (v6)
Apr 18 17:22:13 thats-my-jam wg-quick[98834]: [#] iptables -t nat -I POSTROUTING -o ens3 -j MASQUERADE
Apr 18 17:22:13 thats-my-jam wg-quick[98834]: [#] ip6tables -t nat -I POSTROUTING -o ens3 -j MASQUERADE
Apr 18 17:22:13 thats-my-jam systemd[1]: Finished WireGuard via wg-quick(8) for wg0.

L'output mostra il ip comandi utilizzati per creare il wg0 virtuale dispositivo e assegnargli gli indirizzi IPv4 e IPv6 aggiunti al file di configurazione. Puoi utilizzare queste regole per risolvere i problemi del tunnel o con il wg comando stesso se desideri provare a configurare manualmente l'interfaccia VPN.

Con il server configurato e in esecuzione, il passaggio successivo consiste nel configurare la macchina client come WireGuard Peer e connettersi al WireGuard Server.

Passaggio 7:configurazione di un peer WireGuard

La configurazione di un peer WireGuard è simile alla configurazione del server WireGuard. Una volta installato il software client, genererai una coppia di chiavi pubblica e privata, deciderai uno o più indirizzi IP per il peer, definirai un file di configurazione per il peer e quindi avvierai il tunnel usando il wg-quick copione.

Puoi aggiungere tutti i peer che desideri alla tua VPN generando una coppia di chiavi e una configurazione utilizzando i passaggi seguenti. Se aggiungi più peer alla VPN, assicurati di tenere traccia dei loro indirizzi IP privati ​​per evitare collisioni.

Per configurare WireGuard Peer, assicurati di aver installato il pacchetto WireGuard utilizzando il seguente apt comandi. Sulla corsa peer WireGuard:

  1. sudo apt update
  2. sudo apt install wireguard

Creazione della coppia di chiavi del peer WireGuard

Successivamente, dovrai generare la coppia di chiavi sul peer utilizzando gli stessi passaggi che hai utilizzato sul server. Dal tuo computer locale o server remoto che fungerà da peer, procedi e crea la chiave privata per il peer utilizzando i seguenti comandi:

  1. wg genkey | sudo tee /etc/wireguard/private.key
  2. sudo chmod go= /etc/wireguard/private.key

Anche in questo caso riceverai una singola riga di base64 output codificato, che è la chiave privata. Una copia dell'output è anche memorizzata in /etc/wireguard/private.key . Prendi nota con attenzione della chiave privata che viene emessa poiché dovrai aggiungerla al file di configurazione di WireGuard più avanti in questa sezione.

Quindi usa il comando seguente per creare il file della chiave pubblica:

  1. sudo cat /etc/wireguard/private.key | wg pubkey | sudo tee /etc/wireguard/public.key

Riceverai di nuovo una singola riga di base64 output codificato, che è la chiave pubblica per il tuo peer WireGuard. Copialo da qualche parte come riferimento, poiché dovrai distribuire la chiave pubblica al server WireGuard per stabilire una connessione crittografata.

Creazione del file di configurazione del peer WireGuard

Ora che hai una coppia di chiavi, puoi creare un file di configurazione per il peer che contiene tutte le informazioni necessarie per stabilire una connessione al server WireGuard.

Avrai bisogno di alcune informazioni per il file di configurazione:

  • Il base64 chiave privata codificata che hai generato sul peer.

  • Gli intervalli di indirizzi IPv4 e IPv6 definiti sul server WireGuard.

  • Il base64 chiave pubblica codificata dal server WireGuard.

  • L'indirizzo IP pubblico e il numero di porta del server WireGuard. Di solito questo sarà l'indirizzo IPv4, ma se il tuo server ha un indirizzo IPv6 e la tua macchina client ha una connessione IPv6 a Internet puoi usarlo invece di IPv4.

Con tutte queste informazioni a portata di mano, apri un nuovo /etc/wireguard/wg0.conf file sulla macchina WireGuard Peer utilizzando nano o il tuo editor preferito:

  1. sudo nano /etc/wireguard/wg0.conf

Aggiungi le seguenti righe al file, sostituendo i vari dati nelle sezioni evidenziate come richiesto:

/etc/wireguard/wg0.conf[Interface]
PrivateKey = base64_encoded_peer_private_key_goes_here
Address = 10.8.0.2/24
Address = fd24:609a:6c18::2/64

[Peer]
PublicKey = U9uE2kb/nrrzsEU58GD3pKFU3TLYDMCbetIsnV8eeFE=
AllowedIPs = 10.8.0.0/24, fd24:609a:6c18::/64
Endpoint = 203.0.113.1:51820

Notice how the first Address line uses an IPv4 address from the 10.8.0.0/24 subnet that you chose earlier. This IP address can be anything in the subnet as long as it is different from the server’s IP. Incrementing addresses by 1 each time you add a peer is generally the easiest way to allocate IPs.

Likewise, notice how the second Address line uses an IPv6 address from the subnet that you generated earlier, and increments the server’s address by one. Again, any IP in the range is valid if you decide to use a different address.

The other notable part of the file is the last AllowedIPs line. These two IPv4 and IPv6 ranges instruct the peer to only send traffic over the VPN if the destination system has an IP address in either range. Using the AllowedIPs directive, you can restrict the VPN on the peer to only connect to other peers and services on the VPN, or you can configure the setting to tunnel all traffic over the VPN and use the WireGuard Server as a gateway.

If you are only using IPv4, then omit the trailing fd24:609a:6c18::/64 range (including the , comma). Conversely, if you are only using IPv6, then only include the fd24:609a:6c18::/64 prefix and leave out the 10.8.0.0/24 IPv4 range.

In both cases, if you would like to send all your peer’s traffic over the VPN and use the WireGuard Server as a gateway for all traffic, then you can use 0.0.0.0/0 , which represents the entire IPv4 address space, and ::/0 for the entire IPv6 address space.

(Optional) Configuring a Peer to Route All Traffic Over the Tunnel

If you have opted to route all of the peer’s traffic over the tunnel using the 0.0.0.0/0 or ::/0 routes and the peer is a remote system, then you will need to complete the steps in this section. If your peer is a local system then it is best to skip this section.

For remote peers that you access via SSH or some other protocol using a public IP address, you will need to add some extra rules to the peer’s wg0.conf file. These rules will ensure that you can still connect to the system from outside of the tunnel when it is connected. Otherwise, when the tunnel is established, all traffic that would normally be handled on the public network interface will not be routed correctly to bypass the wg0 tunnel interface, leading to an inaccessible remote system.

First, you’ll need to determine the IP address that the system uses as its default gateway. Run the following ip route comando:

  1. ip route list table main default

You will receive output like the following:

Outputdefault via 203.0.113.1 dev eth0 proto static

Note the gateway’s highlighted IP address 203.0.113.1 for later use, and device eth0 . Your device name may be different. If so, substitute it in place of eth0 in the following commands.

Next find the public IP for the system by examining the device with the ip address show comando:

  1. ip -brief address show eth0

You will receive output like the following:

Outputeth0             UP             203.0.113.5/20 10.20.30.40/16 2604:a880:400:d1::3d3:6001/64 fe80::68d5:beff:feff:974c/64

In this example output, the highlighted 203.0.113.5 IP (without the trailing /20 ) is the public address that is assigned to the eth0 device that you’ll need to add to the WireGuard configuration.

Now open the WireGuard Peer’s /etc/wireguard/wg0.conf file with nano or your preferred editor.

  1. sudo nano /etc/wireguard/wg0.conf

Before the [Peer] line, add the following 4 lines:

PostUp = ip rule add table 200 from 203.0.113.5
PostUp = ip route add table 200 default via 203.0.113.1
PreDown = ip rule delete table 200 from 203.0.113.5
PreDown = ip route delete table 200 default via 203.0.113.1

[Peer]
. . .

These lines will create a custom routing rule, and add a custom route to ensure that public traffic to the system uses the default gateway.

  • PostUp = ip rule add table 200 from 203.0.113.5 - This command creates a rule that checks for any routing entries in the table numbered 200 when the IP matches the system’s public 203.0.113.5 address.
  • PostUp = ip route add table 200 default via 203.0.113.1 - This command ensures that any traffic being processed by the 200 table will use the 203.0.113.1 gateway for routing, instead of the WireGuard interface.

The PreDown lines remove the custom rule and route when the tunnel is shutdown.

Note:The table number 200 is arbitrary when constructing these rules. You can use a value between 2 and 252, or you can use a custom name by adding a label to the /etc/iproute2/rt_tables file and then referring to the name instead of the numeric value.

For more information about how routing tables work in Linux visit the Routing Tables Section of the Guide to IP Layer Network Administration with Linux.

If you are routing all the peer’s traffic over the VPN, ensure that you have configured the correct sysctl and iptables rules on the WireGuard Server in Step 4 — Adjusting the WireGuard Server’s Network Configuration and Step 5 — Configuring the WireGuard Server’s Firewall.

(Optional) Configuring the WireGuard Peer’s DNS Resolvers

If you are using the WireGuard Server as a VPN gateway for all your peer’s traffic, you will need to add a line to the [Interface] section that specifies DNS resolvers. If you do not add this setting, then your DNS requests may not be secured by the VPN, or they might be revealed to your Internet Service Provider or other third parties.

If you are only using WireGuard to access resources on the VPN network or in a peer-to-peer configuration then you can skip this section.

To add DNS resolvers to your peer’s configuration, first determine which DNS servers your WireGuard Server is using. Run the following command on the WireGuard Server , substituting in your ethernet device name in place of eth0 if it is different from this example:

  1. resolvectl dns eth0

You should receive output like the following:

OutputLink 2 (eth0): 67.207.67.2 67.207.67.3 2001:4860:4860::8844 2001:4860:4860::8888

The IP addresses that are output are the DNS resolvers that the server is using. You can choose to use any or all of them, or only IPv4 or IPv6 depending on your needs. Make a note of the resolvers that you will use.

Next you will need to add your chosen resolvers to the WireGuard Peer’s configuration file. Back on the WireGuard Peer , open /etc/wireguard/wg0.conf file using nano or your preferred editor:

  1. sudo nano /etc/wireguard/wg0.conf

Before the [Peer] line, add the following:

DNS = 67.207.67.2 2001:4860:4860::8844

[Peer]
. . .

Again, depending on your preference or requirements for IPv4 and IPv6, you can edit the list according to your needs.

Once you are connected to the VPN in the following step, you can check that you are sending DNS queries over the VPN by using a site like DNS leak test.com.

You can also check that your peer is using the configured resolvers with the resolvectl dns command like you ran on the server. You should receive output like the following, showing the DNS resolvers that you configured for the VPN tunnel:

OutputGlobal: 67.207.67.2 67.207.67.3
. . .

With all of these DNS resolver settings in place, you are now ready to add the peer’s public key to the server, and then start the WireGuard tunnel on the peer.

Step 8 — Adding the Peer’s Public Key to the WireGuard Server

Before connecting the peer to the server, it is important to add the peer’s public key to the WireGuard Server. This step ensures that you will be able to connect to and route traffic over the VPN. Without completing this step the WireGuard server will not allow the peer to send or receive any traffic over the tunnel.

Ensure that you have a copy of the base64 encoded public key for the WireGuard Peer by running:

  1. sudo cat /etc/wireguard/public.key
OutputPeURxj4Q75RaVhBKkRTpNsBPiPSGb5oQijgJsTa29hg=

Now log into the WireGuard server, and run the following command:

  1. sudo wg set wg0 peer PeURxj4Q75RaVhBKkRTpNsBPiPSGb5oQijgJsTa29hg= allowed-ips 10.8.0.2,fd24:609a:6c18::2

Note that the allowed-ips portion of the command takes a comma separated list of IPv4 and IPv6 addresses. You can specify individual IPs if you would like to restrict the IP address that a peer can assign itself, or a range like in the example if your peers can use any IP address in the VPN range. Also note that no two peers can have the same allowed-ips setting.

If you would like to update the allowed-ips for an existing peer, you can run the same command again, but change the IP addresses. Multiple IP addresses are supported. For example, to change the WireGuard Peer that you just added to add an IP like 10.8.0.100 to the existing 10.8.0.2 and fd24:609a:6c18::2 IPs, you would run the following:

  1. sudo wg set wg0 peer PeURxj4Q75RaVhBKkRTpNsBPiPSGb5oQijgJsTa29hg= allowed-ips 10.8.0.2,10.8.0.100,fd24:609a:6c18::2

Once you have run the command to add the peer, check the status of the tunnel on the server using the wg comando:

  1. sudo wg
Outputinterface: wg0
 public key: U9uE2kb/nrrzsEU58GD3pKFU3TLYDMCbetIsnV8eeFE=
 private key: (hidden)
 listening port: 51820

peer: PeURxj4Q75RaVhBKkRTpNsBPiPSGb5oQijgJsTa29hg=
 allowed ips: 10.8.0.2/32, fd24:609a:6c18::/128

Notice how the peer line shows the WireGuard Peer’s public key, and the IP addresses, or ranges of addresses that it is allowed to use to assign itself an IP.

Now that you have defined the peer’s connection parameters on the server, the next step is to start the tunnel on the peer.

Step 9 — Connecting the WireGuard Peer to the Tunnel

Now that your server and peer are both configured to support your choice of IPv4, IPv6, packet forwarding, and DNS resolution, it is time to connect the peer to the VPN tunnel.

Since you may only want the VPN to be on for certain use cases, we’ll use the wg-quick command to establish the connection manually. If you would like to automate starting the tunnel like you did on the server, follow those steps in Step 6 — Starting the WireGuard Server section instead of using the wq-quick comando.

In case you are routing all traffic through the VPN and have set up DNS forwarding, you’ll need to install the resolvconf utility on the WireGuard Peer before you start the tunnel. Run the following command to set this up:

  1. sudo apt install resolvconf

To start the tunnel, run the following on the WireGuard Peer:

  1. sudo wg-quick up wg0

You will receive output like the following:

Output[#] ip link add wg0 type wireguard
[#] wg setconf wg0 /dev/fd/63
[#] ip -4 address add 10.8.0.2/24 dev wg0
[#] ip -6 address add fd24:609a:6c18::2/64 dev wg0
[#] ip link set mtu 1420 up dev wg0
[#] resolvconf -a tun.wg0 -m 0 -x

Notice the highlighted IPv4 and IPv6 addresses that you assigned to the peer.

If you set the AllowedIPs on the peer to 0.0.0.0/0 and ::/0 (or to use ranges other than the ones that you chose for the VPN), then your output will resemble the following:

Output[#] ip link add wg0 type wireguard
[#] wg setconf wg0 /dev/fd/63
[#] ip -4 address add 10.8.0.2/24 dev wg0
[#] ip -6 address add fd24:609a:6c18::2/64 dev wg0
[#] ip link set mtu 1420 up dev wg0
[#] resolvconf -a tun.wg0 -m 0 -x
[#] wg set wg0 fwmark 51820
[#] ip -6 route add ::/0 dev wg0 table 51820
[#] ip -6 rule add not fwmark 51820 table 51820
[#] ip -6 rule add table main suppress_prefixlength 0
[#] ip6tables-restore -n
[#] 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

In this example, notice the highlighted routes that the command added, which correspond to the AllowedIPs in the peer configuration.

You can check the status of the tunnel on the peer using the wg comando:

  1. sudo wg
Outputinterface: wg0
 public key: PeURxj4Q75RaVhBKkRTpNsBPiPSGb5oQijgJsTa29hg=
 private key: (hidden)
 listening port: 49338
 fwmark: 0xca6c

peer: U9uE2kb/nrrzsEU58GD3pKFU3TLYDMCbetIsnV8eeFE=
 endpoint: 203.0.113.1:51820
 allowed ips: 10.8.0.0/24, fd24:609a:6c18::/64
 latest handshake: 1 second ago
 transfer: 6.50 KiB received, 15.41 KiB sent

You can also check the status on the server again, and you will receive similar output.

Verify that your peer is using the VPN by using the ip route and ip -6 route comandi. If you are using the VPN as a gateway for all your Internet traffic, check which interface will be used for traffic destined to CloudFlare’s 1.1.1.1 and 2606:4700:4700::1111 DNS resolvers.

If you are only using WireGuard to access resources on the VPN, substitute a valid IPv4 or IPv6 address like the gateway itself into these commands. For example 10.8.0.1 or fd24:609a:6c18::1 .

  1. ip route get 1.1.1.1
Output1.1.1.1 dev wg0 table 51820 src 10.8.0.2 uid 1000
   cache

Notice the wg0 device is used and the IPv4 address 10.8.0.2 that you assigned to the peer. Likewise, if you are using IPv6, run the following:

  1. ip -6 route get 2606:4700:4700::1111
Output2606:4700:4700::1111 from :: dev wg0 table 51820 src fd24:609a:6c18::2 metric 1024 pref medium

Again note the wg0 interface, and the IPv6 address fd24:609a:6c18::2 that you assigned to the peer.

If your peer has a browser installed, you can also visit ipleak.net and ipv6-test.com to confirm that your peer is routing its traffic over the VPN.

Once you are ready to disconnect from the VPN on the peer, use the wg-quick comando:

  1. sudo wg-quick down wg0

You will receive output like the following indicating that the VPN tunnel is shut down:

Output[#] ip link delete dev wg0
[#] resolvconf -d tun.wg0 -f

If you set the AllowedIPs on the peer to 0.0.0.0/0 and ::/0 (or to use ranges other than the ones that you chose for the VPN), then your output will resemble the following:

Output[#] ip rule delete table 200 from 203.0.113.5
[#] ip route delete table 200 default via 203.0.113.1
[#] ip -4 rule delete table 51820
[#] ip -4 rule delete table main suppress_prefixlength 0
[#] ip -6 rule delete table 51820
[#] ip -6 rule delete table main suppress_prefixlength 0
[#] ip link delete dev wg0
[#] resolvconf -d tun.wg0 -f
[#] iptables-restore -n
[#] ip6tables-restore -n

To reconnect to the VPN, run the wg-quick up wg0 command again on the peer. If you would like to completely remove a peer’s configuration from the WireGuard Server, you can run the following command, being sure to substitute the correct public key for the peer that you want to remove:

  1. sudo wg set wg0 peer PeURxj4Q75RaVhBKkRTpNsBPiPSGb5oQijgJsTa29hg= remove

Typically you will only need to remove a peer configuration if the peer no longer exists, or if its encryption keys are compromised or changed. Otherwise it is better to leave the configuration in place so that the peer can reconnect to the VPN without requiring that you add its key and allowed-ips each time.

Conclusion

In this tutorial you installed the WireGuard package and tools on both the server and client Ubuntu 22.04 systems. You set up firewall rules for WireGuard, and configured kernel settings to allow packet forwarding using the sysctl command on the server. You learned how to generate private and public WireGuard encryption keys, and how to configure the server and peer (or peers) to connect to each other.

If your network uses IPv6, you also learned how to generate a unique local address range to use with peer connections. Finally, you learned how to limit which traffic should go over the VPN by restricting the network prefixes that the peer can use, as well as how to use the WireGuard Server as a VPN gateway to handle all Internet traffic for peers.

If you would like to learn more about WireGuard, including how to configure more advanced tunnels, or use WireGuard with containers, visit the official WireGuard documentation.


OpenVPN
  1. Come configurare un server LAMP Ubuntu/Debian

  2. Come configurare WireGuard VPN su Ubuntu (una guida passo passo)

  3. Come configurare server e client NFS su Ubuntu 20.04

  4. Ubuntu:come impostare un IP statico in Ubuntu?

  5. Come configurare un server TeamSpeak su Ubuntu 16.04

Come configurare CUPS Print Server su Ubuntu 20.04

Come configurare e configurare un server OpenVPN su Ubuntu 22.04

Come configurare il server di posta elettronica con Plesk su Ubuntu 20.04

Come configurare il server Prosody XMPP su Ubuntu 20.04

Come configurare il server Prosody XMPP su Ubuntu 18.04

Come configurare il server proxy Shadowsocks-libev su Ubuntu