Skip to content

Instantly share code, notes, and snippets.

@jaysonsantos
Last active March 12, 2021 14:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaysonsantos/1c174baba69fdc67336e06fa806ce3e5 to your computer and use it in GitHub Desktop.
Save jaysonsantos/1c174baba69fdc67336e06fa806ce3e5 to your computer and use it in GitHub Desktop.
Use openvpn inside WSL2 and be able to route traffic from windows through linux
# On linux side you need iptables
# On windows side you need sudo which can be installed with scoop
$CidrBlocks = "10.0.0.0/16", "10.1.0.0/16", "10.70.0.0/16", "10.3.0.0/16"
$WslIP = "$(wsl -- ip addr show dev eth0 | Select-String -Pattern 'inet ')"
$WslIP = $WslIP.Split(' ').Where{ $_.Length }[1].Split('/')[0]
function BuildIptablesRoute {
param (
[Parameter(Mandatory = $true)]
[String]
$CidrBlock
)
return "iptables --table nat --append POSTROUTING --destination '$CidrBlock' -j MASQUERADE"
}
function BuildWindowsRoute {
param (
[Parameter(Mandatory = $true)]
[String]
$CidrBlock,
[Parameter(Mandatory = $true)]
[String]
$GatewayIp
)
$Ip, $NetmaskBits = $CidrBlock.Split("/")
$Netmask = NetmaskBitsToString -NetmaskBits $NetmaskBits
return "route add $Ip mask $Netmask $GatewayIp"
}
function NetmaskBitsToString {
param (
[Parameter(Mandatory = $true)]
[ValidateRange(0, 32)]
[UInt32]
$NetmaskBits
)
$Mask = ([System.Math]::Pow(2, (32 - $NetmaskBits)) - 1) -bxor [System.UInt32]::MaxValue
$Bytes = 3..0 | ForEach-Object { $Mask -shr $_ * 8 -band [System.Byte]::MaxValue }
return $Bytes | Join-String -Separator "."
}
Write-Output "Setting up linux side with", $CidrBlocks
$IptablesRules = (
$CidrBlocks |
ForEach-Object { BuildIptablesRoute -CidrBlock $_ } |
Join-String -Separator " && "
)
Write-Output "Type the sudo password for your user on linux"
wsl -- sudo bash -exc "${IptablesRules}"
Write-Output "Adding routes on windows side"
$WindowsRoutes = (
$CidrBlocks |
ForEach-Object { BuildWindowsRoute -CidrBlock $_ -GatewayIp $WslIP } |
Join-String -Separator "; "
)
sudo powershell -Command "Set-PSDebug -Trace 1 ; $WindowsRoutes"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment