Install WireGuard:
Ensure that WireGuard is installed on both your host and virtual machine. You can install it using your package manager:
# On Ubuntu/Debian
sudo apt-get install wireguard-tools
# On CentOS/Fedora
sudo dnf install wireguard-tools
Code:
**Generate Key Pairs:**
You need to generate key pairs for both the host and the virtual machine. Run the following commands on both machines:
wg genkey | tee privatekey | wg pubkey > publickey
This will generate a private key and its corresponding public key. Make sure to keep the private key secure.
Configure the Host:
Create a WireGuard configuration file on your host machine. Let's assume the name is
wg0-host.conf
. You can use a text editor to create this file:
sudo nano /etc/wireguard/wg0-host.conf
Code:
Here's a sample configuration file:
[Interface]
Address = 10.0.0.1/24
PrivateKey = <Host Private Key>
ListenPort = 51820
[Peer]
PublicKey = <Virtual Machine Public Key>
AllowedIPs = 10.0.0.2/32
Endpoint = <Virtual Machine's Public IP>:51820
Replace
<Host Private Key>
and
<Virtual Machine Public Key>
with the keys generated in step 2.
Configure the Virtual Machine:
Create a WireGuard configuration file on your virtual machine. Let's assume the name is
wg0-vm.conf
. You can use a text editor to create this file:
sudo nano /etc/wireguard/wg0-vm.conf
Code:
Here's a sample configuration file:
[Interface]
Address = 10.0.0.2/24
PrivateKey = <Virtual Machine Private Key>
ListenPort = 51820
[Peer]
PublicKey = <Host Public Key>
AllowedIPs = 10.0.0.1/32
Endpoint = <Host's Public IP>:51820
Replace
<Virtual Machine Private Key>
and
<Host Public Key>
with the keys generated in step 2.
Enable and Start WireGuard:
On both the host and virtual machine, enable and start the WireGuard service:
sudo systemctl enable wg-quick@wg0-host # On the host
sudo systemctl start wg-quick@wg0-host
sudo systemctl enable wg-quick@wg0-vm # On the virtual machine
sudo systemctl start wg-quick@wg0-vm
```
IP Forwarding and Firewall Rules:
You might need to enable IP forwarding on the host machine, depending on your network configuration. Also, ensure that your firewall settings allow traffic through the WireGuard interface.
Test the Connection:
You should now be able to connect to your virtual machine from the host and vice versa using the assigned IP addresses in the WireGuard configuration.