wsl2-firewall-rules.ps1 1.2 KB

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