9

I'd like to programmatically create a new Network Profile (in addtion to those listed under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Profiles). Then I'd like to programmatically assign a particular network adapter to it (e.g., vEthernet (WSL)), and set the profile to Private network mode to follow the firewall rules, similar to what we can do for Wi-Fi networks. Is there a Windows or PowerShell API to help with that?

Eventually, the goal is to access Windows network from WSL2 Linux without tweaking the Windows Firewall settings manually.

More context for the question, including some things I've tried so far.

Currently, my solution is to call New-NetFirewallRule -DisplayName "WSL" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" manually each time I need access the Windows host network from WSL2.

3

1 Answer 1

2

Personally, I would avoid P/Invoke if possible - it's usually the most fiddly approach.

I suggest using netsh and parsing the text. Netsh is using the Win32 API under the hood, so that changes your problem from P/Invoke to regex (which I think is usually an easier tool to use).

This may be a useful pointer for the netsh invocation. The salient bits:

netsh lan show profiles
netsh lan export profile folder=PATH_TO_FOLDER interface="INTERFACE_NAME"
netsh lan add profile filename="PATH_AND_FILENAME.xml" interface="INTERFACE_NAME"

IIUC, you don't need a new profile every time, you only need to define that once. From my knowledge of WSL, you get a new IP on every boot, so the issue is assigning that to the one profile that you have created for the task.

If that's correct, then I would export a profile to XML for an existing profile, edit it once manually, then automate applying that XML when you see the WSL adapter.

Not sure if you want to do this interactively, but for full automation, the approach that pops into my mind is to attach a task to the relevant event in Event Viewer. On my box, I didn't spot any obvious event sources for WSL, but the Hyper-V-VmSwitch source looks promising. Here's a sample event:

Log Name:      System
Source:        Microsoft-Windows-Hyper-V-VmSwitch
Date:          02/08/2021 09:59:40
Event ID:      264
Task Category: None
Level:         Information
Keywords:      (128)
User:          SYSTEM
Computer:      ******************
Description:
Port D76B3365-5A23-4960-B044-066E05FF3F2D (Friendly Name: A7DB3628-B2A6-4605-AAED-229DB96E064E) successfully created on switch 5EE23C35-0881-4967-A447-FF22139BE1F4 (Friendly Name: WSL).

I've elided over a lot for brevity, but happy to answer follow-up questions.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.