Reputation: 31
I'm trying to set up a new wireguard client and create a new VPN tunnel with the server (10.6.0.1) programmatically by using this single file C library https://git.zx2c4.com/wireguard-tools/tree/contrib/embeddable-wg-library wirguard.h. Following is my code. However it seems that the tunnel is not properly established.
#include <libmnl/libmnl.h>
#include "/home/WG/wireguard.h"
#define SERVER_IP "10.6.0.1"
#define ENDPOINT_IP "192.168.30.209"
#define SERVER_PORT 51820
#define CLIENT_PRIVATE_KEY "private_key_goes_here"
#define CLIENT_PUBLIC_KEY " public key goes here "
#define SERVER_PUBLIC_KEY " public key goes here "
#define CLIENT_IP "10.6.0.2" /* Client-side IP address for the WireGuard tunnel*/
#define BUFFER_SIZE 1036
int main() {
wg_peer new_peer = {
.flags = WGPEER_HAS_PUBLIC_KEY | WGPEER_REPLACE_ALLOWEDIPS
};
wg_device new_device = {
.name = "wg",
.listen_port = 51820,
.flags = WGDEVICE_HAS_PRIVATE_KEY | WGDEVICE_HAS_LISTEN_PORT,
.first_peer = &new_peer,
.last_peer = &new_peer
};
// Convert base64 strings to binary keys using wg_key_from_base64
wg_key private_key;
wg_key public_key;
wg_key server_public_key;
if (wg_key_from_base64(private_key, CLIENT_PRIVATE_KEY) < 0) {
perror("Invalid private key");
exit(1);
}
if (wg_key_from_base64(public_key, CLIENT_PUBLIC_KEY) < 0) {
perror("Invalid public key");
exit(1);
}
if (wg_key_from_base64(server_public_key, SERVER_PUBLIC_KEY) < 0) {
perror("Invalid server public key");
exit(1);
}
// Set the public key of the server
memcpy(new_peer.public_key, server_public_key, sizeof(wg_key));
// Set the endpoint address and port of the server
new_peer.endpoint.addr.sa_family = AF_INET;
if (inet_aton(ENDPOINT_IP, &new_peer.endpoint.addr4.sin_addr) == 0) {
perror("Invalid server IP address");
return 1;
}
new_peer.endpoint.addr4.sin_port = htons(SERVER_PORT);
if (wg_add_device(new_device.name) < 0) {
perror("Unable to add device");
exit(1);
}
if (wg_set_device(&new_device) < 0) {
perror("Unable to set device");
exit(1);
}
sleep(3);
Free the allocated memory before exiting
free(new_device->name);
free(new_device);
free(peer);
return 0;
}
This is the output for: sudo wg
interface: wg listening port: 51820
peer:
endpoint: 192.168.30.209:51820
allowed ips: (none)
In wireshark, it lists down the wg interface somewhere in the bottom. When I try to select and listen to the port, it says the “wg device is not up”. for ifconfig its not showing the wg interface.
Any mistakes I have made ? I think it’s because the CLIENT_IP address has not been applied properly. I’m struggling with this. Any suggestions?
Upvotes: 2
Views: 1058