R – Virtual Network Connection

network-programmingnetwork-protocolsnetworking

I can see that lot's of programs like openvpn and Teamviewer for their VPN Connection creat a virtual network connection on windows. I want to create one for myself for testing purposes.

Is it possible to create one programmatically or so?

Best Answer

It sounds like you're looking for the Tap-Win32 driver. It's the driver OpenVPN on Windows uses to create the virtual interface you are seeing, and in fact part of the OpenVPN package. This subsystem is also available on many *nixes.

The interface to this TAP driver is roughly the same on all OSes. You open a special file, and write raw Ethernet frames to this file. The driver then inserts these frames into the virtual interface. Conversely, any packets that are transmitted on the virtual interface, can be read from the special file as raw Ethernet frames.

Most implementations also have a TUN mode, which operates at layer 3 instead of layer 2. So you will be reading raw IP, IPv6, etc. packets instead of Ethernet frames.

I have no experience with this on Windows, so I'm going by quick skimming of source code here. OpenVPN goes through most of these steps in tun.c function open_tun. You'll find multiple definitions of this function, but they're #ifdef'd for different OSes (so search for CreateFile). The basic way this seems to operate on Windows is:

  1. Before any application operating a TAP interface is started, one or more virtual interfaces are pre-created (by the installer?). These interfaces start out disconnected.
  2. Your application starts and does a special CreateFile call on "\\.\Global\GUID.tap". Where GUID is replaced by the GUID that describes the specific virtual interface. Virtual interfaces can be iterated in the registry key which is defined as ADAPTER_KEY in "tap-win32\common.h" in the OpenVPN source code.
  3. Your application may perform some DeviceIoControl calls. OpenVPN uses this a bunch of times to get the driver version, get MTU, set TUN mode, and other misc things.
  4. At this point, the interface is probably showing up as connected in Windows, and you might even be reading DHCP requests you're receiving from Windows itself already. OpenVPN goes through a large amount of hoopla to configure the interface using other parts of Windows networking APIs, but this is not specific to the TAP driver.

So while the API is really just a special file and thus fairly simple, there's a lot to actually managing the interface. But if you're just in it for testing, this may well be enough. You can then manually configure your test interface in Windows.