Force Wireguard DNS Zone Override

From RoseWiki
Jump to navigation Jump to search

Sometimes you may have a situation in which you require a machine using a Wireguard tunnel to always use a specific DNS server to resolve specific zones. One case where we needed this was an Active Directory DNS zone that also matched a publicly available DNS zone. The publicly available records resolved to one end of a NAT'd IP range, but the AD DNS zone had records pointing to the other side. When connecting locally in the network, this was fine, but some Windows clients were resolving through the LAN's DNS regardless of the search domain set in the Wireguard config.

To fix this we can leverage the power of the Name Resolution Policy Table.

You could simply fix this by executing this command:

Add-DnsClientNrptRule -Comment 'NameOfVPNTunnel' -Namespace '.dnszone.com' -NameServers 203.0.113.0

This works, but the problem is that this rule will always be active. If you know for sure that the device's network situation will never change, this is fine, but if it's a mobile workstation that may be repurposed you should avoid this if possible. We can tell Wireguard to dynamically create and remove these rules using the PostUp and PostDown hooks in the Wireguard config. The problem is that these are disabled by default due to the potential room for abuse. The solution is to enable these using a registry edit:

Set-ItemProperty -Path HKLM:\SOFTWARE\Wireguard -Name DangerousScriptExecution -Type DWord -Value 1

If this results in "The operation was completed successfully" we can now add these lines to our wireguard config:

PostUp = powershell.exe -Command "& { Add-DnsClientNrptRule -Comment 'NameOfVPNTunnel' -Namespace '.dnszone.com' -NameServers 203.0.113.0 }"
PostDown = powershell.exe -Command "& { Get-DnsClientNrptRule | where Comment -eq 'NameOfVPNTunnel' | foreach { Remove-DnsClientNrptRule -Name $_.Name -Force } }"