I’ve been trying to find a way to script or automate the creation of a new Windows VPN connection that uses L2TP/IPSEC with a pre shared key and automatically uses the current user’s credentials, but it seems there is no way to do this using the CMAK, netsh, various powershell scripts, or GPO Preferences as none of them include all of the options we needed to set. So I have come up with a .NET app for doing this and am posting the code here in case it helps anyone else out.
The image below highlights the settings that we were struggling to configure via any kind of script or automated process.
The MS CMAK tool lets you specify a pre shared key but does not let you enable the “Automatically use current windows credentials” option (there is an extra line you can add to the config file manually that supposedly enables this but it simply does not seem to work). This powershell script does not let you specify a pre shared key, and neither does the Server 2008 GPO Preferences option that lets you create VPN connection.
So I decided to try and write my own command line application in VB.NET that would create the VPN connection with all of the required settings. As there is no method for creating VPN connections in the .NET Framework, we need to use the native RAS Windows APIs. Anyone following this blog will know I’m no stranger to calling Windows APIs from .NET (see my Windows API Library) but I found a .NET library that already contains all of the RAS APIs here: http://dotras.codeplex.com/ so I decided to just use that rather than spending hours getting the API definitions worked out myself. So thanks to the author of the DotRas library (and yes I have made a donation to say thank you properly!) for saving me some time and headaches 🙂
After adding a reference to the DotRas library mentioned above, it was just a case of writing the following code to configure the VPN the way I wanted:
As you can see, I have made this a command line application that accepts 3 arguments. The first is the name for the new VPN connection, the second is the destination IP address or host name, and the third is the pre shared key. So now in our SCCM task sequence for building laptops we can simply call this app like so:
VpnSetup.exe “Our VPN” vpn.company.com PreSharedKeyHere
Also note that this will need to be run “As Administrator” so I set the application to always require full admin rights so that you get a UAC prompt to elevate whenever you run it (to avoid access denied errors).
If anyone else is in need of a similar thing then let me know and I will see if I can make this available on my website and make it a bit more flexible (at the moment it is hard coded to only use L2TP with a pre shared key and use the current user’s logon credentials, you might not want that). Will have to check with the author of the DotRas library to see if this is OK as well.