Skip to contentSkip to conversation

Problem using "WireGuardSetConfiguration" for Wireguard-NT with heap allocated configuration

DISCUSSION Lukas Lüdke 2 participants 2 messages Aug 13, 2021

lore
Share & tools
lore
#0 lore raw

Hello,

I am trying to implement a custom wireguard client using the provided wireguard.dll/wireguard.h in c++.
I tried to modify the example from here:
https://git.zx2c4.com/wireguard-nt/tree/example/example.c
It works, when I specify a struct with one interface (WIREGUARD_INTERFACE) and one or more peers + allowed ips (WIREGUARD_PEER, WIREGUARD_ALLOWED_IP) and then use "WireGuardSetConfiguration" to the the configuration on the adapter, like it the example.
But when I try to use a buffer allocated on the heap, containing the interface and the peers + allowed_ips, I always get error 0x57 from "WireGuardSetConfiguration".
It seems to work, when I only create the buffer and memcpy a WIREGUARD_INTERFACE object into the buffer, but if I create a larger buffer and also memcpy the WIREGUARD_PEER object into it, set the Flags and set the PeersCount, I get the error.
like in the following example it does not work:

unsigned char* buffer = (unsigned char *)malloc(sizeof(WIREGUARD_INTERFACE) + sizeof(WIREGUARD_PEER)); /*new_interface is the interface from the example.c file*/ new_interface.PeersCount = 1;
memcpy(buffer, &new_interface, sizeof(WIREGUARD_INTERFACE)); unsigned char* buffer2 = (buffer + sizeof(WIREGUARD_INTERFACE)); /*peer is a created peer, which does work, if I use it in a struct*/ memcpy(buffer2, &peer, sizeof(WIREGUARD_PEER));
if (!WireGuardSetConfiguration(Adapter, (WIREGUARD_INTERFACE *)&(buffer), sizeof(struct t))) {
    LastError = LogError(L"Failed to set configuration", GetLastError()); return cleanupAdapter(Adapter, WireGuard, LastError);
}

Does anyone has an idea, how I can implement this correctly, so that I can dynamically add/remove the peers and I am not forced to create a struct with fixed peer count?

Best Regards,
Lukas

#1 lore raw

Hi Lukas,

This appears to be a C pointer snafu, with this line in the code you sent:

Quoted 1 line

if (!WireGuardSetConfiguration(Adapter, (WIREGUARD_INTERFACE*)&(buffer), sizeof(struct t))) {

The issue is that buffer is already a pointer to the malloc'd memory, so passing &buffer is actually the address of the pointer that points to the memory you want. The reason why the example.c code passes "&thing" and not "thing" is because thing is on the stack. But in your case, buffer is on the heap, so it's already a pointer. The second thing that stands out is sizeof(struct t) might not be what you want. Instead try providing as length the same length that you passed to the malloc call -- sizeof(iface)+sizeof(peer).

Hope that helps.

Jason