param ( $vpnName = "Verdnatura", $allUsers = $true ) # Advanced configuration $vpnHost = "vpn.verdnatura.es" $vpnSuffix = "verdnatura.es" $vpnSplit = $true $vpnNetworks = @("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16") $vpnCaUrl = "https://cdn.verdnatura.es/public/verdnatura.der" $caHash = "028a316a3072f402c10fd7699cb061c93cc5cb15" # Scripting $restorePowerShellPolicy = $false $ErrorActionPreference = "Inquire" if ($allUsers) { $caPath = "LocalMachine\Root" } else { $caPath = "CurrentUser\Root" } $caLocation = "Cert:\$caPath" $hasCa = Get-ChildItem $caLocation | Where-Object {$_.Thumbprint -eq $caHash} if (!$hasCa) { Echo "Downloading and installing CA certificate." $caFile = "$env:TEMP\$caHash.der" Invoke-WebRequest $vpnCaUrl ` -OutFile $caFile Import-Certificate ` -FilePath $caFile ` -CertStoreLocation $caLocation ` | Out-Null Remove-Item $caFile } Echo "Creating the VPN connection." try { $args = @{ Name = $vpnName Force = $true ErrorAction = "Stop" AllUserConnection = $allUsers } Remove-VpnConnection @args } catch { if ($_.Exception.StatusCode -eq 1) { throw "Connection '$vpnName' is open, close it before running the script." } elseif ($_.Exception.StatusCode -ne 6) { throw } } $args = @{ Name = $vpnName ServerAddress = $vpnHost TunnelType = "Ikev2" EncryptionLevel = "Required" AuthenticationMethod = "Eap" DnsSuffix = $vpnSuffix RememberCredential = $true AllUserConnection = $allUsers } Add-VpnConnection @args $rasphoneRelPath = "Microsoft\Network\Connections\Pbk\rasphone.pbk" if ($allUsers) { $rasphonePath = "$env:ProgramData\$rasphoneRelPath" } else { $rasphonePath = "$env:AppData\$rasphoneRelPath" } $rasphone = Get-Content $rasphonePath -Raw $regex = "^([\s\S]*\[${vpnName}\][\s\S]*IpInterfaceMetric=)(\d+)([\s\S]*)$" $match = [Regex]::Match($rasphone, $regex) $rasphone = $match.Groups[1].Value + '1' + $match.Groups[3].Value $rasphone | Set-Content $rasphonePath New-ItemProperty ` -Path "HKLM:\SYSTEM\CurrentControlSet\Services\RasMan\Parameters" ` -Name "NegotiateDH2048_AES256" ` -PropertyType DWord ` -Value 1 ` -ErrorAction SilentlyContinue ` | Out-Null if ($vpnSplit) { Echo "Enabling split tunneling." $args = @{ Name = $vpnName SplitTunneling = $true AllUserConnection = $allUsers } Set-VpnConnection @args Echo "Adding routes for VPN networks." foreach ($vnNetwork in $vpnNetworks) { Echo " - $vnNetwork" $args = @{ ConnectionName = $vpnName DestinationPrefix = $vnNetwork RouteMetric = 5 AllUserConnection = $allUsers } Add-VpnConnectionRoute @args } } if ($restorePowerShellPolicy) { Echo "Restoring PowerShell default policy." Set-ExecutionPolicy ` -ExecutionPolicy Undefined ` -Scope LocalMachine } Echo "Connection created successfully."