wsl2-firewall-rules.ps1 1.0 KB

12345678910111213141516171819202122232425262728293031
  1. // Copyright (c) 2021 Bryan C. Roessler
  2. //
  3. // This software is released under the MIT License.
  4. // https://opensource.org/licenses/MIT
  5. # Get the WSL2 IP address (randomized on init)
  6. $remoteport = bash.exe -c "ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1"
  7. # All the ports you want to forward separated by comma
  8. $ports=@(22);
  9. $ports_a = $ports -join ",";
  10. # Listening address
  11. $addr='0.0.0.0';
  12. # Remove existing rules
  13. iex "Remove-NetFireWallRule -DisplayName 'WSL2 Services' ";
  14. # Add Inbound/Outbound exception rules
  15. iex "New-NetFireWallRule -DisplayName 'WSL Services' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
  16. iex "New-NetFireWallRule -DisplayName 'WSL Services' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP";
  17. for( $i = 0; $i -lt $ports.length; $i++ ){
  18. $port = $ports[$i];
  19. iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr";
  20. iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport";
  21. }