Skip to content

Instantly share code, notes, and snippets.

@shigenobuokamoto
Last active April 23, 2024 12:35
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shigenobuokamoto/b565d468541fc8be7d7d76a0434496a0 to your computer and use it in GitHub Desktop.
Save shigenobuokamoto/b565d468541fc8be7d7d76a0434496a0 to your computer and use it in GitHub Desktop.
/etc/systemd/system/network-mirrored.service
[Unit]
Wants=network-pre.target
Before=network-pre.target shutdown.target
[Service]
User=root
ExecStart=/bin/sh -ec '\
[ -x /usr/bin/wslinfo ] && [ "$(/usr/bin/wslinfo --networking-mode)" = "mirrored" ] || exit 0;\
echo "\
add chain ip nat WSLPREROUTING { type nat hook prerouting priority dstnat - 1; policy accept; };\
insert rule ip nat WSLPREROUTING iif loopback0 ip daddr 127.0.0.1 counter dnat to 127.0.0.1 comment mirrored;\
"|nft -f -\
'
ExecStop=/bin/sh -ec '\
[ -x /usr/bin/wslinfo ] && [ "$(/usr/bin/wslinfo --networking-mode)" = "mirrored" ] || exit 0;\
for chain in "ip nat WSLPREROUTING";\
do\
handle=$(nft -a list chain $chain | sed -En "s/^.*comment \\"mirrored\\" # handle ([0-9]+)$/\\1/p");\
for n in $handle; do echo "delete rule $chain handle $n"; done;\
done|nft -f -\
'
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
@shigenobuokamoto
Copy link
Author

shigenobuokamoto commented Dec 15, 2023

you can try it.

$ sudo systemctl --now enable network-mirrored

@shigenobuokamoto
Copy link
Author

revision 8:
delete IPv6 routing filter
- natively supported in wsl 2.2.2

@Adam-Jin
Copy link

I saw your description in the issue "adding this action breaks the prerouting hook and disables any Docker rules set in the PREROUTING chain". Can you explain why? The dnat of 127.0.0.1 to 127.0.0.1 seems redundant. thx

@shigenobuokamoto
Copy link
Author

@Adam-Jin
as you said, it is redundant.
nothing changes with this DNAT, except that it can terminate the prerouting hook.
PREROUTING is not processed by applying DNAT first.

@shigenobuokamoto
Copy link
Author

this is the reason why PERROUTING (Docker's rules) is handled poorly in mirrored networking.
microsoft/WSL#10494 (comment)

explanation about systemd service can be found here.
microsoft/WSL#10494 (comment)

@Adam-Jin
Copy link

thx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment