Skip to content

Instantly share code, notes, and snippets.

@skahwah
Created January 15, 2021 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save skahwah/36c50539a10a3e117a563bf6dd936ff9 to your computer and use it in GitHub Desktop.
Save skahwah/36c50539a10a3e117a563bf6dd936ff9 to your computer and use it in GitHub Desktop.
WSL Portforwarding
# Stick this in your ps profile c:/Users/you/Documents/WindowsPowerShell/profile.ps1
function wsl-add-port-forward {
param ($param1)
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){
echo "This function needs to be run as Administrator"
break
}
$remoteport = bash.exe -c "ip -4 addr show eth0 | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -v .255"
$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if( $found ){
$remoteport = $matches[0];
echo "[+] Found WSL instance at $remoteport"
} else{
echo "[!] IP address of WSL 2 cannot be found. Check the interface name in the remoteport variable.";
break
}
#The ports you want to forward separated by comma
$ports=@($param1);
$addr='0.0.0.0';
$ports_a = $ports -join ",";
# Adding inbound and outbound exception rules
iex "[void](New-NetFireWallRule -DisplayName 'WSL Port Forward' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP)";
iex "[void](New-NetFireWallRule -DisplayName 'WSL Port Forward' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP)";
for( $i = 0; $i -lt $ports.length; $i++ ){
$port = $ports[$i];
iex "[void](netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr)";
iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport";
}
echo "[+] Ports $param1 have been forwarded to WSL instance at $remoteport"
}
function wsl-delete-port-forward {
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){
echo "This function needs to be run as Administrator"
break
}
iex "Remove-NetFireWallRule -DisplayName 'WSL Port Forward' ";
iex "netsh interface portproxy reset" ;
echo "[+] Forwarded ports have been deleted"
}
function wsl-list-port-forward {
iex "netsh interface portproxy show v4tov4";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment