On the afternoon of 11 October 2026 I ran a script against my OPNsense router’s API from Windows PowerShell 5.1, the PowerShell that comes with Windows. It stopped before it wrote a single line of its own log. The script’s first call to the router comes after that line, so, as far as I can tell, nothing reached the router.
That was version 2.0. Version 2.4 finished the job at 15:06, 37 minutes after I saved version 2.0. Each version had passed its tests in Claude’s sandbox first. Those tests ran in the wrong place: against a mock router instead of the real one, and under PowerShell 7 instead of Windows PowerShell 5.1. The mock passed all three versions that then failed on the router. Whether the PowerShell difference played a part in failure 1 I do not know. It played none in failure 2, and it broke my test harness later. Three runs failed, each for a different reason. None of them left a change switched on.
I did this with Claude. I set the rules the script had to follow, created the API key and deleted it afterwards, and ran every version on my own PC against my own router. Claude wrote the script, the mock router it was tested against, and each fix. It tested them under PowerShell 7, the only PowerShell its sandbox had.
The script, a mock router and a test harness are at the end of this page, under the MIT licence. The script makes a router refuse three common ways around its DNS blocklist: DNS over HTTPS, DNS over TLS or QUIC, and plain DNS sent to another server. This page records the runs and what I would change, and a panel near the end walks through running the script on your own router.
New to the command line? How to read the boxes
PS> means: type this in PowerShell on Windows (Start menu → type powershell → Enter). Do not type the PS> itself.
Each line that starts with PS> is one command. Click that PS> to copy just that line, paste it, press Enter, and wait for it to finish before the next. A box with a Copy button at the top holds one command (or one file), so copy it whole. A dashed box shows what you should see back, or code to read; you do not type it.
What the script does
The script applies a DNS fix on an OPNsense 26.7 router. My router’s blocklist only filters devices that ask the router; phones, browsers and some devices ask other servers. The fix involves four objects:
- an alias,
DoH_IPs, that downloads a public list of DNS-over-HTTPS server addresses kept by the Hagezi project (1,434 of them that day); - Rule A, which rejects LAN traffic to those addresses on port 443;
- Rule B, which rejects LAN traffic to any address on port 853, used by DNS over TLS and DNS over QUIC;
- a NAT redirect that sends any port 53 query aimed past the router back to the router.
On my router the alias and the redirect rule already existed, and the redirect was switched off. The script cleans the alias, creates the two rules if they are missing, and switches the redirect on. It does not create the redirect rule. The rules cover IPv4 and the LAN interface only; the limits are listed in the step-by-step panel near the end.
I could have clicked these four objects into place. I scripted it because I wanted the change in a form I could check without changing anything, run again, and switch off in one command.
The rules it runs under
- Three modes.
Checkreads and reports.Applymakes the change.Rollbackswitches the two rules and the redirect off and deletes nothing. A command without-ModerunsCheck. - Version guard. The script first asks the router what it runs, and stops unless the answer is the 26.7 series.
- Backup next. Before it reads or changes any configuration, every run downloads the router’s full configuration into a new file. It refuses to overwrite an existing one.
- Test each change. The alias first, then both rules, then the redirect. In version 2.3 a failed test undid everything the run had changed. From version 2.4, if only the redirect fails, only the redirect is switched off, and the rules that passed stay.
- No secret in the script. The API key lives in a separate file.
Thirty-seven minutes
| Started | Version | Mode | What happened | Left on the router |
|---|---|---|---|---|
| after 14:29 | 2.0 | not logged | Stopped before its first log line | Nothing |
| 14:43 | 2.1 | Check | Read-only report, complete | Nothing |
| 14:51 | 2.2 | Apply | Stopped on its own guard before any save | Nothing |
| 14:56 | 2.3 | Apply | Rules worked; redirect test failed; undone | Two rules, disabled |
| 15:04 | 2.4 | Apply | Finished at 15:06, every test passed | The fix |
Version 2.0 wrote no log, so its time is the minute I saved the file. The other times are from the script’s own logs.
The order of operations limited the damage. The script checks the version, backs up, and reads before it writes. Failure 1 stopped before any call to the router. Failure 2 stopped before any save, on a guard written for a different problem. Failure 3 happened after changes were made, and that version’s undo switched them off.
Failure 1: a cause I got wrong
Version 2.0 took its working folder from a parameter default:
[string]$WorkDir = $PSScriptRoot$PSScriptRoot is the folder the script sits in. The script uses it to build the path for its logs folder, which it creates before it reads the key or calls the router.
Version 2.1 changed three things. It worked out the folder in the script body, it stopped if that folder did not exist, and it wrapped two counts so that an empty DNS answer counts as zero. Only the folder changes come before the first log line. On the day, Claude and I concluded that Windows PowerShell 5.1 had left $PSScriptRoot empty, and the first drafts of this post said so.
The test kit for this post checked that, and the conclusion was wrong. On my PC, Windows PowerShell 5.1, started with -File as I start the script, put the folder into $PSScriptRoot in a parameter default. So did PowerShell 7.4.6. I did not test every way of starting a script, so I cannot rule out that some leave it empty. I did not record how I started version 2.0 that afternoon, or the error it showed, so I do not know what stopped it. What the evidence supports is narrower: version 2.0 stopped before its first log line, and so, as far as the evidence shows, before any call to the router. A comment in the published script says the folder can be empty under Windows PowerShell 5.1. That comment repeats my first conclusion; I left the tested file as it was.
The change in version 2.1 stays. It costs nothing and it works whichever way the script is started:
if ([string]::IsNullOrWhiteSpace($WorkDir)) {
if ($MyInvocation.MyCommand.Path) { $WorkDir = Split-Path -Parent $MyInvocation.MyCommand.Path }
else { $WorkDir = (Get-Location).Path }
}Version 2.1’s Check run at 14:43 completed.
Failure 2: a mock without the router’s quirks
To check the alias’s type, version 2.2 called the router’s alias/get_item endpoint. The run log at 14:51:
14:51:46 Problem: Existing alias DoH_IPs is type '', not urltable. Fix or delete it in the GUI, then rerun.
14:51:46 Nothing to undo.
...
14:51:47 STOP: Apply did not complete; changes from this run were undone.The alias’s type was not empty. The router’s reply contains entries whose name is an empty string ("":). JSON allows that. PowerShell cannot make an object property with an empty name. Microsoft’s documentation for ConvertFrom-Json says so (the PowerShell 7.4 reference), and offers the -AsHashtable switch for such replies. Windows PowerShell 5.1 does not have that switch. Invoke-RestMethod raised no error. It returned the reply as plain text, and the script read the type from that text as nothing.
This was not a difference between PowerShell versions. The test kit gives the script a reply with an empty key. Under PowerShell 7.4.6, and on my PC under Windows PowerShell 5.1, Invoke-RestMethod returned it as text, with no error. Version 2.2 passed against the mock because the mock’s reply had no empty keys. The router’s reply had them.
The guard that stopped the run was written for a different problem: an existing alias of the wrong type. It stopped this run because an empty type is not urltable. Without it, the run would have saved the new URL and then, on undo, written an empty string into the alias.
The Check run at 14:43 had not caught this. Check read the alias through alias/search_item. Only Apply called get_item.
Version 2.3 makes two changes. The router’s search_item and search_rule endpoints already return the type and contents, and their replies parsed, so the script reads only through them. And every API call now goes through one helper that refuses a reply it could not parse:
$r = Invoke-RestMethod @p
if ($r -is [string]) {
$t = $r.TrimStart()
if ($t.StartsWith('{') -or $t.StartsWith('[')) { throw "Router reply to $Path could not be read as JSON by this PowerShell; stopping." }
}Failure 3: a redirect tested too soon
Version 2.3 got further. It cleaned the alias, added both rules and tested them. Then it switched the NAT redirect on and tested it five seconds later:
14:57:16 Rules A and B verified: DoH and DoT refused, normal HTTPS works.
14:57:17 NAT rule enabled and applied. Verifying...
14:57:22 Problem: 8.8.8.8 still returns real ad addresses; the redirect is not taking effect.
14:57:22 Undoing changes made in this run...The test sends two queries to 8.8.8.8: one for example.com and one for an ad domain. The firewall log showed one of the two redirected. The ad domain came back with real addresses, so it was the one not redirected. Thirteen seconds before switching the redirect on, the script’s opening check had sent that same name to 8.8.8.8, to show the bypass was open.
I have two explanations, and I tested neither. The firewall keeps a state entry for each connection it has seen, and applies a redirect only to new connections. If the second query for the ad domain left my PC from the same source port as the first, it matched the old entry and went out to Google. Or something on my PC answered the repeated question from memory, and the query never left the PC.
This router’s UDP state timeouts, read from Firewall → Diagnostics → Statistics, are 60 seconds for udp.first and udp.multiple and 30 seconds for udp.single. Version 2.4 waits 70 seconds before testing, and the test passed:
15:05:08 NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
15:06:18 NAT redirect verified: queries to 8.8.8.8 are answered by your router.The wait outlasts the firewall’s state entries. Whether it also outlasts an answer remembered on the PC depends on how long that answer is kept, which I did not measure. So the result does not tell the two explanations apart. A test with a name not queried earlier, with the firewall’s state table open, would.
The undo in version 2.3 switched the redirect off, disabled the two new rules and restored the alias’s contents. It did not delete the rules, and it left the alias’s refresh interval at one day. The backup taken after the undo is 4,788 bytes larger than the one before the run. Version 2.4 began by finding the two rules:
15:04:56 Rule A: present, enabled=0, sort_order=400000.0000100
15:04:56 Rule B: present, enabled=0, sort_order=400000.0000200So “undone” meant “nothing left switched on”, not “the router as it was”. Version 2.4 switched the two existing rules on instead of adding new copies, because it looks rules up by description before creating them.
What the mock missed, and a second round of tests
Claude had run each version against its mock before I ran it against the router. By the record of that session, each version ran once normally and once with a forced failure, to check the undo. Versions 2.0 to 2.3 passed against the mock. Against the router, three of the four failed. The mock never ran under Windows PowerShell 5.1, and its replies did not carry the router’s empty keys.
The script at the end of this page is version 2.5.1, not 2.4. Before publishing, I had Claude review the script again, and version 2.5 fixes what that review found: messages that could describe the router’s state wrongly, stops that were not written to the log, an undo that did not restore the alias’s enabled flag, and runs that could start on a router without the redirect rule or the LAN allow-all rule. It also refuses a router address that does not start with https://, except one on the PC itself, which the test kit uses. Version 2.4 is the one that ran on my router. Version 2.5.1, which differs from 2.5 in its header comments only, has run only against the mock.
The second round of tests used a new mock, built to misbehave the way a router can, including a reply with an empty key. A harness ran a copy of the script against it once for each of 30 cases. Under PowerShell 7.4.6, all 30 passed.
The first run under Windows PowerShell 5.1 on my PC failed two cases. The script’s logs showed it had done the right thing; the harness had not. When a PowerShell function returns a list with one item, the caller gets the item itself. PowerShell 7 lets you count and index that item as if it were a list. Windows PowerShell 5.1 does not, for this kind of object. The harness had run only under PowerShell 7. With that fixed, all 30 cases passed under Windows PowerShell 5.1 too, on the published version of the script.
To check the harness itself, Claude broke the script ten ways, for example by removing the undo, the JSON check or the HTTPS check. Each break made at least one case fail. That check ran under PowerShell 7.4.6 against version 2.5, with an earlier version of the harness.
What I would take to the next script
- Test on the PowerShell that will run the script, and run the tests there too. The harness passed under PowerShell 7 and failed its first run under 5.1.
- Build the mock’s replies from real ones. A reply saved from the router’s
get_itemwould have caught failure 2 before the router saw the script. - Make the read-only mode make every read the write mode will make. Here,
CheckandApplyread the alias through different endpoints. - Treat a string from
Invoke-RestMethodas a failure when you expected an object. It does not always raise an error. - After switching on a redirect, wait longer than the firewall’s state timeout, and test with a name you have not queried before.
- If the undo disables instead of deleting, make the next run look for what the last one left.
- Break the script on purpose to check that the tests can fail.
- Keep the API key out of the script and delete it when the work is done. I used the
rootuser’s key. A user with only the privileges the script needs would be better; I have not tried that.
Run it on your own router, step by step
Before you start. You need:
- a Windows PC on the same network as the router. You type in two places: PowerShell on the PC, and the router’s web page in a browser;
- OPNsense 26.7. The script stops on any other series, because its API paths were read from that series’ own pages;
- the DNS blocklist switched on, under Services → Unbound DNS → Blocklist (the OPNsense documentation names that page), and your devices asking the router for DNS;
- a Destination NAT rule that sends DNS queries (port 53) aimed anywhere but the router back to the router, already made, with the description “Redirect non-local DNS to Local”. The script switches it on. It does not build it. The script does not create this rule, this panel does not cover making one, and without it Apply stops. A community how-to on the OPNsense forum shows one way;
- a LAN rule called “Default allow LAN to any rule”, which OPNsense creates by default. The script checks that its two new rules sit above it.
Version 2.5.1, the script in this panel, has run only against the mock router in the test kit. Version 2.4 is the one that ran on my router.
Allow about 20 minutes; the change itself takes about two. The first change to the router is the API key in step 3. The Check run in step 5 changes nothing on it. Apply in step 6 changes it. Step 8 switches the fix off and shows how to restore the whole configuration. Every run saves a backup of the router’s configuration on the PC before it reads the configuration.
Read the limits next. If one describes your network, the script does not suit it, so do not go on.
Limits
- IPv4 only. Rules A and B are created for IPv4, and every test uses an IPv4 address. If your LAN has IPv6, DoH and DoT over IPv6 are neither blocked nor tested. (Interfaces → LAN shows an IPv6 Configuration Type; None means no IPv6.)
- LAN interface only. Other interfaces and VLANs are not covered.
- Every LAN host. A Pi-hole or AdGuard Home on the LAN that uses DoH or DoT upstream loses its upstream. If it sends plain DNS to a public server, your redirect rule may catch that too, depending on how the rule is built.
- Devices that insist on encrypted DNS. A device set to use only an encrypted DNS provider, for example a phone with Private DNS set to a hostname, may lose name lookups on this network once the rules refuse its route. Change that setting on the device.
- The redirect rule must exist in Firewall → NAT → Destination NAT, with the description “Redirect non-local DNS to Local” or whatever you set in
$NatDesc. It is not created or checked for how it is built. - The alias is overwritten with the Hagezi URL. The old contents are written to the log.
- The test domain in
$AdTestDomainmust be blocked by your router’s blocklist, answered as 0.0.0.0 or with no address, or the redirect test fails. - A LAN you trust. The script’s certificate check accepts any certificate presented for the router’s address, so a device on the LAN posing as the router would receive the key. Run it only on a network you control.
- The wait in
$NatWaitSecondsshould be longer than your router’s UDP state timeouts. - Rollback switches the two rules and the redirect rule off, even if the redirect was on before you first ran
Apply. It does not restore the alias.
Open PowerShell and make a folder. Open the Start menu, type
powershelland press Enter. A window titled Windows PowerShell opens, and its prompt starts withPS. If the prompt has noPS, you are in Command Prompt: close it and open PowerShell instead, because the commands below work only in PowerShell. Click inside the window. Use the two lines below one at a time: click the PS> to copy a line, paste it (Ctrl + V, or right-click), and press Enter.New-Item -ItemType Directory -Path "$env:USERPROFILE\opnsense-dns" Set-Location "$env:USERPROFILE\opnsense-dns"The first line makes a folder called
opnsense-dnsinside your user folder and prints a short listing; the second moves PowerShell into it, and the prompt then ends withopnsense-dns>. Each takes under a second. If the first line says the folder exists, go on. Keep this window open, and keep the folder out of OneDrive, Dropbox and shared locations: the backups saved here hold the router’s whole configuration.Save the script. Scroll to The script, the mock router and the test harness at the end of this page, open opnsense-dns-bypass.ps1 (version 2.5.1), read it, and click Copy. It is 491 lines. It will use your router’s key, so read it before you run it. Windows marks files a browser downloads as coming from the internet; a file written by the command below has no such mark, so
Unblock-Fileis not needed. The command replaces a file of the same name in this folder. In the PowerShell window:Get-Clipboard -Raw | Set-Content -Encoding Ascii .\opnsense-dns-bypass.ps1Get-Clipboardreads what you copied andSet-Contentwrites it to a file; the script is plain ASCII, so that encoding is safe. It takes under a second and prints nothing. Check that all of it arrived:(Get-Content .\opnsense-dns-bypass.ps1).Count491A different number suggests the copy was cut short or changed. Go back to the page, click Copy again and repeat the first command.
Create an API key on the router. In a web browser, type
https://and the address you use for the router’s settings page (for examplehttps://192.168.1.1), and press Enter. The browser may warn that the connection is not private, because the router signs its own certificate. Choose the option that continues to the address (in Chrome: Advanced, then Proceed). Log in with your own router login. Then:- In the menu on the left, click System, then Access, then Users.
- Click the pencil (edit) icon at the end of the row of the administrator you log in as.
- Find the API keys section in the user’s settings (the OPNsense documentation calls it the ApiKeys tab) and use the button in its grid that creates a key.
- The browser downloads a small text file within a few seconds. It has a
key=line and asecret=line. The documentation says the secret is generated only once; if the file is lost, make a new key.
A key acts as the user it belongs to. I used the root user’s key and deleted it afterwards; the root key gives full control of the router. A user limited to the firewall, NAT and backup pages would hold less power, but the script downloads the router’s whole configuration, so that user can still read the password hashes and private keys in it. I have not tried a limited user. If your menu looks different, the OPNsense documentation on local users describes the same step. Do not paste the key file anywhere: the secret in it gives control of the router.
Put the key file in the folder. Back in PowerShell, list the newest text files in your Downloads folder:
Get-ChildItem "$env:USERPROFILE\Downloads" -Filter *.txt | Sort-Object LastWriteTime -Descending | Select-Object -First 3 Name, LastWriteTimeName LastWriteTime ---- ------------- example_apikey.txt <date and time>If the list is empty, your browser saved the file somewhere else: press Ctrl + J in the browser to see where. Now move the file into the folder under the name the script expects. Replace
<file-name>, angle brackets included, with the name from the list:Move-Item -LiteralPath "$env:USERPROFILE\Downloads\<file-name>" -Destination .\apikey.txtIt takes under a second and prints nothing. It will not overwrite an
apikey.txtalready in the folder; if it refuses for that reason, an earlier key file is there. Remove that key on the router (step 8 shows where), runRemove-Item .\apikey.txt, and repeat this step. If it reports an error about the path, the path may still hold<file-name>, or the name may differ from the one in the list. Now check the key file has its two lines. This prints only the word before each=, never the values:Get-Content .\apikey.txt | ForEach-Object { ($_ -split '=')[0] }key secretIf you see other words, this is probably not the key file. Download a new key (step 3).
Run Check. It only reads. First tell PowerShell your router’s address. Click the PS> to copy the line, paste it, and do not press Enter yet. Replace
<router-ip-address>, angle brackets included, with the numbers of the address from step 3 (for example192.168.1.1), and leavehttps://as it is. Move the cursor with the arrow keys, because a mouse click does not move it in PowerShell; Backspace deletes. Then press Enter. The script stops if the angle brackets are still there.$RouterUrl = 'https://<router-ip-address>'This remembers the address for this window only. If you close the window, repeat it.
Now run the script.
powershell -ExecutionPolicy Bypass -Filestarts a fresh Windows PowerShell 5.1 that runs the file.-ExecutionPolicy Bypasson the command line lasts for that one run, and Microsoft’s documentation on execution policies says it is not stored. It does not override a Group Policy set by an employer. Without-Modethe script runsCheck.powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrlIt takes 10 to 60 seconds and changes nothing on the router. It saves a backup of the router’s configuration in the
router-backupsfolder insideopnsense-dns, a log inlogs, and runs five live tests. The lines that matter:HH:MM:SS Router reports: OPNsense series 26.7, amd64 HH:MM:SS Backup (before) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Check-before-<timestamp>.xml (NNN,NNN bytes) ... HH:MM:SS Router resolves example.com : True (want True) HH:MM:SS Router blocks the ad domain (blocklist) : True (want True) HH:MM:SS Bypass DoH 1.1.1.1:443 reachable : True (want False after Apply) HH:MM:SS Bypass DoT 9.9.9.9:853 reachable : True (want False after Apply) HH:MM:SS Bypass 8.8.8.8 gives real ad IPs : True (want False after Apply) HH:MM:SS Check mode: nothing was changed on the router. HH:MM:SS Log file: C:\Users\<you>\opnsense-dns\logs\run-Check-<timestamp>.logBoth “want True” lines must be True. If “Router blocks the ad domain” is False, your blocklist does not block the test domain and the redirect test in step 6 would fail. Set
$AdTestDomainnear the top of the script to a domain your blocklist blocks, or switch the blocklist on. If a yellow line startsApply would stop:, it names a missing rule: the redirect rule or the LAN allow-all rule. Fix that on the router before step 6.If something went wrong. The script prints a red line (most contain the word STOP) and changes nothing on the router. What the line says, and what it means:
- Set -Router to your router’s address: the angle brackets are still in the address from this step.
- Missing an argument for parameter ‘Router’: probably the address line above was not run in this window. Run it again.
- -Router must start with https://: the address begins with
http://. Usehttps://. - STOP: Key file not found:
apikey.txtis not in theopnsense-dnsfolder. Redo step 4. - STOP: Cannot reach the router API with this key: the address is wrong, the key was removed, or the PC is not on the router’s network. Open the address in the browser to test it.
- STOP: Script was built for OPNsense 26.7: your router runs another series, and the script’s API paths were read from 26.7. Stop here.
- PowerShell says running scripts is disabled: a policy on your PC blocks scripts, and the command-line option cannot override it. Stop here.
Run Apply. This changes the router. It overwrites the alias
DoH_IPswith the Hagezi list address (the old contents go to the log), adds the two reject rules if they are missing, and switches the redirect rule on. Devices on your network that talk to a DNS-over-HTTPS or DNS-over-TLS server directly lose that route; that is the purpose. Run the same command with-Mode Applyadded:powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode ApplyIt takes about two minutes, and up to four if the alias has to download its list first. One line says
Waiting 70 s for older DNS states to expire before testing...; wait for it and do not close the window. The last lines should read:HH:MM:SS Bypass DoH 1.1.1.1:443 reachable : False (want False after Apply) HH:MM:SS Bypass DoT 9.9.9.9:853 reachable : False (want False after Apply) HH:MM:SS Bypass 8.8.8.8 gives real ad IPs : False (want False after Apply) HH:MM:SS Backup (after) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Apply-after-<timestamp>.xml (NNN,NNN bytes) HH:MM:SS Apply finished. Expected: router tests True, all three bypass tests False. HH:MM:SS Log file: C:\Users\<you>\opnsense-dns\logs\run-Apply-<timestamp>.logIf something went wrong. Apply did not complete; changes from this run were undone: a test failed, and the script switched off what it had changed. Rules it added stay, switched off. It saved a backup of the result. Read the line that starts Problem: for the reason. If any line says UNDO STEP FAILED, restore the “before” backup as step 8 describes. Apply PARTLY finished (in yellow): the alias and the two rules are in place and tested, and the redirect did not pass; the line says whether the redirect was left on or off. To switch the fix off, use step 8.
Check that it worked. Run the Check command from step 5 again:
powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrlNow the three
Bypasslines readFalseand the twoRouterlines readTrue. In the router’s web page you can also look at Firewall → Rules (choose LAN in the interface selector), where the two rules Reject DoH to known resolvers (A) and Reject DoT/DoQ 853 from LAN (B) now appear, and at Firewall → NAT → Destination NAT, where Redirect non-local DNS to Local is enabled.Switch it off, restore if you need to, and remove the key. To switch the fix off, run the command with
-Mode Rollback:powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode RollbackIt takes under a minute. It disables the two rules and the redirect and deletes nothing. The alias stays as Apply left it. If the redirect was on before you started, it is now off: switch it back on in Firewall → NAT → Destination NAT.
To put the whole configuration back as it was before Apply, restore the backup on the router: go to System → Configuration → Backups, choose the file named
config-Apply-before-<timestamp>.xmlfrom therouter-backupsfolder, and restore it. Each Apply run saves one such file; the earliest holds the configuration from before your first Apply. That also undoes any other change made on the router since.When you have finished with the script, whether you keep the fix or not, remove the key. On the router go to System → Access → Users, click the pencil on the same user, and remove the key in the API keys section (the ApiKeys tab). Then delete the key file from the PC:
Remove-Item .\apikey.txtThis deletes the file at once, with no recycle bin. When you no longer need the backups, delete the
router-backupsfolder too: it holds password hashes and private keys.
Security notes. The script sends the key with every request. It does not print or log the secret, and the test kit checks that in each of its 30 cases. Its certificate check accepts any certificate presented for the router’s address, so a device on the LAN posing as the router would receive the key. I deleted my key on 13 October 2026, two days after the run, and the router’s configuration history records the deletion.
The backups are the router’s whole configuration: password hashes, and the private keys of its certificates and VPN tunnels. Keep that folder private, and do not attach a backup to a forum post.
Deep dive: the script’s other checks
- The backup must look like a backup. After downloading, the script checks the file is at least 50,000 bytes and has
<opnsense>in its first three lines. - A failed save is caught. A reply carrying
validationscounts as a failed save, as it does in the router’s own web pages; so does aresultoffailed. Alias and redirect changes are read back. Rule changes are checked by the rules’ presence and order, and by live connection tests. - Rule order. After adding Rules A and B, the script stops if either sorts after “Default allow LAN to any rule”, because a rule below the allow-all rule would never match.
- The alias must fill. It polls the alias every 5 seconds for up to 90 seconds and stops unless it holds at least 500 addresses.
- Normal browsing must still work. Before declaring the rules good, it opens a connection to
www.google.com:443. - A partial result says so. If only the redirect stage fails, the run ends
Apply PARTLY finished, says what state it left the redirect in, and exits with code 2.
Deep dive: accepting a bad certificate only for the router’s address
The router’s web interface uses a self-signed certificate. PowerShell 7 has -SkipCertificateCheck, which the script uses there. Windows PowerShell 5.1 has no such switch. A common workaround is a callback that accepts every certificate for the whole session. The script’s callback accepts a failed certificate check only when the request’s host is the router’s address:
public static bool Check(object sender, X509Certificate c, X509Chain ch, SslPolicyErrors e) {
if (e == SslPolicyErrors.None) return true;
HttpWebRequest r = sender as HttpWebRequest;
return r != null && r.RequestUri.Host == Host;
}This narrows the exception. It does not pin the certificate: any certificate presented for that address passes. Checking the certificate’s thumbprint would close that gap. The script also sets TLS 1.2 for 5.1.
Deep dive: a precaution, not a failure: Expect: 100-continue
Check mode sends only GET requests. Apply sends POSTs. Windows PowerShell 5.1 runs on the .NET Framework, where ServicePointManager.Expect100Continue is true by default and adds an Expect: 100-continue header to POST requests that carry a body (Microsoft’s documentation). Version 2.2 switches the header off before the first request:
[Net.ServicePointManager]::Expect100Continue = $falseI did not test whether the router’s web server would have objected to the header.
Deep dive: the finished run, line by line
The log of the 15:04 run. The router’s address and the name of one of its interfaces are replaced with placeholders in angle brackets; the local folder and the PowerShell build number are removed, and the digits in the byte counts are grouped in threes. The opening tests show all three ways around the blocklist open; the closing tests show them shut, for the three IPv4 addresses tested.
15:04:49 Mode: Apply Router: https://<router-ip-address> PowerShell 5.1
15:04:55 Router reports: OPNsense series 26.7, amd64
15:04:55 Backup (before) saved: ...\config-Apply-before-20261011-150449.xml (404,269 bytes)
15:04:56 Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[__<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
15:04:56 Rule A: present, enabled=0, sort_order=400000.0000100
15:04:56 Rule B: present, enabled=0, sort_order=400000.0000200
15:04:56 'Default allow LAN to any rule': sort_order=400000.1000023
15:04:56 NAT 'Redirect non-local DNS to Local': disabled=1
15:04:56 Router resolves example.com : True (want True)
15:04:56 Router blocks the ad domain (blocklist) : True (want True)
15:04:56 Bypass DoH 1.1.1.1:443 reachable : True (want False after Apply)
15:04:56 Bypass DoT 9.9.9.9:853 reachable : True (want False after Apply)
15:04:56 Bypass 8.8.8.8 gives real ad IPs : True (want False after Apply)
15:04:56 Alias DoH_IPs set to the URL only (was: __<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt).
15:04:58 Alias DoH_IPs holds 1434 addresses.
15:04:58 Rule 'Reject DoH to known resolvers (A)' enabled.
15:04:58 Rule 'Reject DoT/DoQ 853 from LAN (B)' enabled.
15:04:58 Firewall rules applied. Verifying...
15:05:08 Rules A and B verified: DoH and DoT refused, normal HTTPS works.
15:05:08 NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
15:06:18 NAT redirect verified: queries to 8.8.8.8 are answered by your router.
15:06:19 Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
15:06:19 Rule A: present, enabled=1, sort_order=400000.0000100
15:06:19 Rule B: present, enabled=1, sort_order=400000.0000200
15:06:19 'Default allow LAN to any rule': sort_order=400000.1000023
15:06:19 NAT 'Redirect non-local DNS to Local': disabled=0
15:06:23 Router resolves example.com : True (want True)
15:06:23 Router blocks the ad domain (blocklist) : True (want True)
15:06:23 Bypass DoH 1.1.1.1:443 reachable : False (want False after Apply)
15:06:23 Bypass DoT 9.9.9.9:853 reachable : False (want False after Apply)
15:06:23 Bypass 8.8.8.8 gives real ad IPs : False (want False after Apply)
15:06:23 Backup (after) saved: ...\config-Apply-after-20261011-150449.xml (404,254 bytes)
15:06:23 Apply finished. Expected: router tests True, all three bypass tests False.The alias held one entry I had not put there on purpose: the network of one of the router’s interfaces, ahead of the URL. The run printed the old contents before replacing them, so they can be restored from the log.
Deep dive: what the test kit checks, and what it cannot
The mock answers the script’s API paths, keeps the router’s state in memory, records every call, and can be set to misbehave: a wrong version, a bad API key, a small backup, a backup that fails after changes, an alias of the wrong type, a reply with an empty key, a save the router rejects, an alias that does not fill, rules that sort below the allow-all rule, DoH still reachable, normal HTTPS broken, a missing redirect rule or allow rule, a redirect that does not take effect, and a redirect that was already on. It also plays the states my router went through: the alias with a stray entry, the two rules left disabled by version 2.3, and everything already applied. Its reply with an empty key is written by hand, after the router’s get_item reply, and served on the endpoint the script reads.
The harness runs the script once per case, as a separate process, and checks the exit code, the log, the backup files, every call the mock received, and the mock router’s state at the end. In every case it checks that neither the secret nor the encoded key appears in the output or the log, that nothing was deleted, and that a stop after the log is opened is written to the log.
The harness tests a copy of the script, not the script itself. In the copy, the two network tests ask the mock instead of the internet, and every wait is cut to a millisecond; before any case runs, the harness checks that each of those patterns matched the expected number of times. The copy talks to the mock over plain HTTP on the PC; the script accepts plain HTTP only for an address on the PC itself.
So the kit does not test: the certificate check and TLS; the real network tests; failure 3, because the mock has no state table and the waits are cut; replies from a real router, apart from the one hand-written empty-key reply; the script’s refusal to overwrite a backup; the fallback for the work folder, because every case names one; or an undo step that itself fails.
The ten deliberate breaks and the cases each one made fail are listed with the kit at the end of the page.
Deep dive: OPNsense 26.7 API notes
- The script’s header records that each configuration path was taken from the router’s own web pages on the day:
alias/search_item,alias/add_item,alias/set_item,alias/reconfigure,filter/search_rule,filter/add_rule,filter/set_rule,filter/apply,d_nat/search_rule,d_nat/set_rule,d_nat/apply,alias_util/listandcore/backup/download/this. It also callscore/firmware/infofor the version andcore/firmware/statusas a reachability check. - The search endpoints answer a GET with
?rowCount=-1¤t=1and return every row, with the fields the script needs. alias/get_itemreturns option lists with empty-named keys, which PowerShell cannot turn into object properties.GET /api/core/backup/download/thisreturns the full configuration as XML.- POST bodies are JSON with
Content-Type: application/json. Rule changes take effect after the matchingapply; alias changes afterreconfigure.
Glossary
- Windows PowerShell 5.1: the PowerShell that comes with Windows, built on the .NET Framework. Started as
powershell. - PowerShell 7: the newer PowerShell, installed separately, built on modern .NET. Started as
pwsh. - REST API: a set of web addresses a program calls to read or change settings; OPNsense’s replies are JSON.
- JSON: a text format for structured data.
- Mock: a stand-in for a real system, used for testing; here, a small web server that answers like the router.
- Test harness: a script that runs another script in many set situations and checks the results.
- API key: a key and secret that let a script act as a router user without a password.
- Alias (URL table): an OPNsense list of addresses that the router downloads from a web address and refreshes.
- NAT redirect: a rule that changes where matching traffic goes; here it sends stray DNS queries to the router.
- State table: the firewall’s list of connections it has already seen. Later packets of a known connection follow the decision made for the first.
- DoH, DoT: DNS over HTTPS (port 443) and DNS over TLS (port 853), two ways for a device to look up names without asking the router.
Expect: 100-continue: an HTTP header that asks the server to approve a request before its body is sent.
Script हर test में पास हुई, ग़लत जगह पर
11 अक्टूबर 2026 की दोपहर मैंने अपने OPNsense router की API पर एक script चलाई, Windows PowerShell 5.1 से, यानी वह PowerShell जो Windows के साथ आता है। Script अपने log की पहली line लिखने से पहले ही रुक गई। Router को script की पहली call उस line के बाद आती है, इसलिए, जहाँ तक मैं बता सकता हूँ, router तक कुछ नहीं पहुँचा।
वह वर्ज़न 2.0 था। वर्ज़न 2.4 ने काम 15:06 पर पूरा किया, वर्ज़न 2.0 save करने के 37 मिनट बाद। हर वर्ज़न पहले Claude के sandbox में अपने tests पास कर चुका था। वे tests ग़लत जगह पर चले थे: असली router की जगह एक mock router पर, और Windows PowerShell 5.1 की जगह PowerShell 7 पर। Mock ने उन तीनों वर्ज़नों को पास किया जो बाद में router पर fail हुए। PowerShell के फ़र्क़ की failure 1 में कोई भूमिका थी या नहीं, मुझे नहीं पता। Failure 2 में उसकी कोई भूमिका नहीं थी, और बाद में उसकी वजह से मेरा test harness fail हुआ। तीन runs fail हुए, हर एक अलग वजह से। किसी ने भी कोई बदलाव चालू नहीं छोड़ा।
यह काम मैंने Claude के साथ किया। Script को किन नियमों पर चलना है, यह मैंने तय किया, API key बनाई और बाद में delete की, और हर वर्ज़न अपने PC से अपने router पर चलाया। Script, जिस mock router पर उसे test किया गया, और हर fix, Claude ने लिखे। उसने इन्हें PowerShell 7 पर test किया, जो उसके sandbox में मौजूद अकेला PowerShell था।
Script, एक mock router और एक test harness इस पेज के आख़िर में हैं, MIT licence के तहत। Script router से उसकी DNS blocklist को bypass करने के तीन आम तरीक़े बंद करवाती है: DNS over HTTPS, DNS over TLS या QUIC, और किसी दूसरे server को भेजा गया सादा DNS। यह पेज runs का record और मैं क्या बदलूँगा, यह बताता है, और आख़िर के पास एक panel आपके अपने router पर script चलाने के चरण समझाता है।
Command line आपके लिए नई है? Boxes को कैसे पढ़ें
PS> का मतलब है: इसे Windows में PowerShell में type करें (Start menu → powershell type करें → Enter)। PS> को ख़ुद type न करें।
जिस भी line की शुरुआत PS> से होती है, वह एक command है। सिर्फ़ उस line को copy करने के लिए उसके PS> पर click करें, उसे paste करें, Enter दबाएँ, और अगली command से पहले उसके पूरा होने का इंतज़ार करें। ऊपर Copy button वाला box एक command (या एक file) रखता है, इसलिए उसे पूरा copy करें। टूटी (dashed) रेखा वाला box दिखाता है कि जवाब में आपको क्या दिखना चाहिए, या पढ़ने के लिए code; उसे आप type नहीं करते।
Script क्या करती है
Script एक OPNsense 26.7 router पर DNS का एक fix लगाती है। मेरे router की blocklist सिर्फ़ उन devices को filter करती है जो router से पूछते हैं; फ़ोन, browsers और कुछ devices दूसरे servers से पूछते हैं। इस fix में चार objects हैं:
- एक alias,
DoH_IPs, जो Hagezi project की रखी DNS-over-HTTPS servers के पतों की एक public list download करता है (उस दिन 1,434 पते); - Rule A, जो उन पतों पर port 443 की LAN traffic को reject करता है;
- Rule B, जो किसी भी पते पर port 853 की LAN traffic को reject करता है, जिसे DNS over TLS और DNS over QUIC इस्तेमाल करते हैं;
- एक NAT redirect, जो router को छोड़कर कहीं और जाने वाली port 53 की हर query को वापस router पर भेजता है।
मेरे router पर alias और redirect rule पहले से मौजूद थे, और redirect बंद था। Script alias को साफ़ करती है, दोनों rules न हों तो बनाती है, और redirect को चालू करती है। वह redirect rule नहीं बनाती। Rules सिर्फ़ IPv4 और LAN interface को cover करते हैं; सीमाएँ आख़िर के पास step-by-step panel में दी गई हैं।
ये चार objects मैं click करके भी लगा सकता था। Script इसलिए लिखी क्योंकि मुझे यह बदलाव ऐसे रूप में चाहिए था जिसे मैं कुछ बदले बिना जाँच सकूँ, दोबारा चला सकूँ, और एक command से बंद कर सकूँ।
किन नियमों पर चलती है
- तीन modes।
Checkपढ़ता है और report देता है।Applyबदलाव करता है।Rollbackदोनों rules और redirect को बंद करता है और कुछ delete नहीं करता।-Modeके बिना commandCheckचलाती है। - वर्ज़न की जाँच। Script पहले router से पूछती है कि उस पर क्या चल रहा है, और जवाब 26.7 series न हो तो रुक जाती है।
- उसके बाद backup। कोई भी configuration पढ़ने या बदलने से पहले, हर run router की पूरी configuration एक नई file में download करता है। वह किसी मौजूदा file को overwrite करने से मना करता है।
- हर बदलाव का test। पहले alias, फिर दोनों rules, फिर redirect। वर्ज़न 2.3 में एक fail हुआ test उस run के सारे बदलाव undo कर देता था। वर्ज़न 2.4 से, अगर सिर्फ़ redirect fail हो, तो सिर्फ़ redirect बंद होता है, और जो rules पास हुए वे बने रहते हैं।
- Script में कोई secret नहीं। API key एक अलग file में रहती है।
सैंतीस मिनट
| शुरू | वर्ज़न | Mode | क्या हुआ | Router पर क्या बचा |
|---|---|---|---|---|
| 14:29 के बाद | 2.0 | log नहीं हुआ | अपनी पहली log line से पहले रुकी | कुछ नहीं |
| 14:43 | 2.1 | Check | सिर्फ़ पढ़ने वाली report, पूरी | कुछ नहीं |
| 14:51 | 2.2 | Apply | किसी save से पहले अपनी ही सुरक्षा-जाँच पर रुकी | कुछ नहीं |
| 14:56 | 2.3 | Apply | Rules चले; redirect test fail; undo हुआ | दो rules, बंद |
| 15:04 | 2.4 | Apply | 15:06 पर पूरी, हर test पास | Fix |
वर्ज़न 2.0 ने कोई log नहीं लिखा, इसलिए उसका समय वह मिनट है जब मैंने file save की। बाक़ी समय script के अपने logs से हैं।
कामों के क्रम ने नुक़सान सीमित रखा। Script वर्ज़न जाँचती है, backup लेती है, और लिखने से पहले पढ़ती है। Failure 1 router को कोई भी call जाने से पहले रुका। Failure 2 किसी भी save से पहले रुका, एक ऐसी जाँच पर जो किसी दूसरी समस्या के लिए लिखी गई थी। Failure 3 बदलाव होने के बाद हुआ, और उस वर्ज़न के undo ने उन्हें बंद कर दिया।
Failure 1: एक वजह जो मैंने ग़लत समझी
वर्ज़न 2.0 अपना working folder एक parameter default से लेता था:
[string]$WorkDir = $PSScriptRoot$PSScriptRoot वह folder है जिसमें script रखी है। Script इससे अपने logs folder का path बनाती है, जिसे वह key पढ़ने या router को call करने से पहले बनाती है।
वर्ज़न 2.1 ने तीन चीज़ें बदलीं। उसने folder script के body में तय किया, वह folder मौजूद न होने पर रुकने लगी, और दो गिनतियों को wrap किया ताकि DNS का ख़ाली जवाब शून्य गिना जाए। इनमें से सिर्फ़ folder वाले बदलाव पहली log line से पहले आते हैं। उस दिन Claude और मैंने यह नतीजा निकाला कि Windows PowerShell 5.1 ने $PSScriptRoot ख़ाली छोड़ दिया था, और इस post के पहले drafts में यही लिखा था।
इस post के test kit ने इसकी जाँच की, और वह नतीजा ग़लत निकला। मेरे PC पर Windows PowerShell 5.1 ने, -File के साथ शुरू करने पर, जैसे मैं script शुरू करता हूँ, parameter default में $PSScriptRoot में folder डाल दिया। PowerShell 7.4.6 ने भी। मैंने script शुरू करने के हर तरीक़े को test नहीं किया, इसलिए मैं इस संभावना को ख़ारिज नहीं कर सकता कि कुछ तरीक़ों में वह ख़ाली रहता है। उस दोपहर मैंने वर्ज़न 2.0 को कैसे शुरू किया, या उसने कौन-सा error दिखाया, यह मैंने दर्ज नहीं किया, इसलिए मुझे नहीं पता कि उसे किस चीज़ ने रोका। सबूत इससे कम बात का समर्थन करते हैं: वर्ज़न 2.0 अपनी पहली log line से पहले रुका, और इसलिए, जहाँ तक सबूत दिखाते हैं, router को कोई भी call जाने से पहले रुका। प्रकाशित script की एक comment कहती है कि Windows PowerShell 5.1 में folder ख़ाली हो सकता है। वह comment मेरे पहले नतीजे को दोहराती है; मैंने test की हुई file को वैसा ही रहने दिया।
वर्ज़न 2.1 का बदलाव बना रहता है। इसकी कोई क़ीमत नहीं है और script किसी भी तरह शुरू हो, यह काम करता है:
if ([string]::IsNullOrWhiteSpace($WorkDir)) {
if ($MyInvocation.MyCommand.Path) { $WorkDir = Split-Path -Parent $MyInvocation.MyCommand.Path }
else { $WorkDir = (Get-Location).Path }
}वर्ज़न 2.1 का Check run 14:43 पर पूरा हुआ।
Failure 2: router की ख़ासियतों के बिना एक mock
Alias का type जाँचने के लिए वर्ज़न 2.2 ने router का alias/get_item endpoint call किया। 14:51 का run log:
14:51:46 Problem: Existing alias DoH_IPs is type '', not urltable. Fix or delete it in the GUI, then rerun.
14:51:46 Nothing to undo.
...
14:51:47 STOP: Apply did not complete; changes from this run were undone.Alias का type ख़ाली नहीं था। Router के जवाब में ऐसी entries हैं जिनका नाम एक ख़ाली string है ("":)। JSON इसकी इजाज़त देता है। PowerShell ख़ाली नाम वाली object property नहीं बना सकता। ConvertFrom-Json के लिए Microsoft के दस्तावेज़ यही कहते हैं (PowerShell 7.4 का reference), और ऐसे जवाबों के लिए -AsHashtable switch देते हैं। Windows PowerShell 5.1 में यह switch नहीं है। Invoke-RestMethod ने कोई error नहीं दिया। उसने जवाब सादे text के रूप में लौटाया, और script को उस text से type ख़ाली मिला।
यह PowerShell वर्ज़नों का फ़र्क़ नहीं था। Test kit script को ख़ाली key वाला एक जवाब देता है। PowerShell 7.4.6 पर, और मेरे PC पर Windows PowerShell 5.1 में, Invoke-RestMethod ने उसे text के रूप में लौटाया, बिना किसी error के। वर्ज़न 2.2 mock पर इसलिए पास हुआ क्योंकि mock के जवाब में कोई ख़ाली key नहीं थी। Router के जवाब में थीं।
जिस सुरक्षा-जाँच ने run रोका वह एक दूसरी समस्या के लिए लिखी गई थी: ग़लत type का पहले से मौजूद alias। उसने यह run इसलिए रोका क्योंकि ख़ाली type urltable नहीं है। उसके बिना, run नया URL save कर देता और फिर undo पर alias में एक ख़ाली string लिख देता।
14:43 के Check run ने यह नहीं पकड़ा था। Check alias को alias/search_item से पढ़ता था। सिर्फ़ Apply ने get_item call किया।
वर्ज़न 2.3 दो बदलाव करता है। Router के search_item और search_rule endpoints पहले से type और contents लौटाते हैं, और उनके जवाब parse हो गए थे, इसलिए script सिर्फ़ उन्हीं से पढ़ती है। और अब हर API call एक helper से होकर जाती है जो ऐसा जवाब मानने से मना करता है जिसे वह parse न कर सके:
$r = Invoke-RestMethod @p
if ($r -is [string]) {
$t = $r.TrimStart()
if ($t.StartsWith('{') -or $t.StartsWith('[')) { throw "Router reply to $Path could not be read as JSON by this PowerShell; stopping." }
}Failure 3: बहुत जल्दी test किया गया redirect
वर्ज़न 2.3 आगे पहुँचा। उसने alias साफ़ किया, दोनों rules जोड़े और उन्हें test किया। फिर उसने NAT redirect चालू किया और पाँच सेकंड बाद उसे test किया:
14:57:16 Rules A and B verified: DoH and DoT refused, normal HTTPS works.
14:57:17 NAT rule enabled and applied. Verifying...
14:57:22 Problem: 8.8.8.8 still returns real ad addresses; the redirect is not taking effect.
14:57:22 Undoing changes made in this run...Test 8.8.8.8 को दो queries भेजता है: एक example.com के लिए और एक किसी ad domain के लिए। Firewall के log में दोनों में से एक redirect हुई दिखी। Ad domain असली पतों के साथ लौटा, इसलिए redirect न होने वाली query वही थी। Redirect चालू करने से तेरह सेकंड पहले, script की शुरुआती जाँच ने यही नाम 8.8.8.8 को भेजा था, यह दिखाने के लिए कि bypass खुला है।
मेरे पास दो व्याख्याएँ हैं, और मैंने किसी को test नहीं किया। Firewall हर उस connection की state entry रखता है जो वह देख चुका है, और redirect सिर्फ़ नए connections पर लागू करता है। अगर ad domain की दूसरी query मेरे PC से उसी source port से निकली जिससे पहली, तो वह पुरानी entry से match हुई और Google तक चली गई। या मेरे PC पर किसी चीज़ ने दोहराए गए सवाल का जवाब याद से दे दिया, और query PC से बाहर निकली ही नहीं।
इस router के UDP state timeouts, जो Firewall → Diagnostics → Statistics से पढ़े, udp.first और udp.multiple के लिए 60 सेकंड और udp.single के लिए 30 सेकंड हैं। वर्ज़न 2.4 test करने से पहले 70 सेकंड रुकता है, और test पास हुआ:
15:05:08 NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
15:06:18 NAT redirect verified: queries to 8.8.8.8 are answered by your router.यह इंतज़ार firewall की state entries से लंबा है। क्या यह PC पर याद रखे गए जवाब से भी लंबा है, यह इस पर निर्भर है कि वह जवाब कितनी देर रखा जाता है, जो मैंने नहीं मापा। इसलिए यह नतीजा दोनों व्याख्याओं में फ़र्क़ नहीं करता। पहले न पूछे गए किसी नाम के साथ, firewall की state table खोलकर किया गया test यह फ़र्क़ कर सकेगा।
वर्ज़न 2.3 के undo ने redirect बंद किया, दोनों नए rules disable किए और alias के contents वापस रखे। उसने rules delete नहीं किए, और alias का refresh interval एक दिन पर छोड़ दिया। Undo के बाद लिया गया backup run से पहले वाले backup से 4,788 bytes बड़ा है। वर्ज़न 2.4 ने शुरुआत में ही उन दोनों rules को ढूँढ लिया:
15:04:56 Rule A: present, enabled=0, sort_order=400000.0000100
15:04:56 Rule B: present, enabled=0, sort_order=400000.0000200तो “undo हुआ” का मतलब था “कुछ भी चालू नहीं बचा”, न कि “router जैसा था वैसा”। वर्ज़न 2.4 ने नई copies जोड़ने की जगह दोनों मौजूदा rules चालू किए, क्योंकि वह rules बनाने से पहले उन्हें description से ढूँढता है।
Mock से क्या छूटा, और tests का दूसरा दौर
मेरे router पर चलाने से पहले Claude हर वर्ज़न अपने mock पर चला चुका था। उस session के record के अनुसार, हर वर्ज़न एक बार सामान्य रूप से चला और एक बार ज़बरदस्ती कराई गई failure के साथ, undo जाँचने के लिए। वर्ज़न 2.0 से 2.3 mock पर पास हुए। Router पर चार में से तीन fail हुए। Mock कभी Windows PowerShell 5.1 पर नहीं चला, और उसके जवाबों में router की ख़ाली keys नहीं थीं।
इस पेज के आख़िर में दी गई script वर्ज़न 2.5.1 है, 2.4 नहीं। Publish करने से पहले मैंने Claude से script का फिर review कराया, और वर्ज़न 2.5 उस review में मिली चीज़ें ठीक करता है: ऐसे messages जो router की state को ग़लत बता सकते थे, ऐसे stops जो log में नहीं लिखे जाते थे, एक undo जो alias का enabled flag वापस नहीं रखता था, और ऐसे runs जो redirect rule या LAN allow-all rule के बिना वाले router पर शुरू हो सकते थे। यह ऐसे router पते को भी मना करता है जो https:// से शुरू न हो, सिवाय PC पर ही मौजूद पते के, जिसे test kit इस्तेमाल करता है। मेरे router पर वर्ज़न 2.4 चला था। वर्ज़न 2.5.1, जो 2.5 से सिर्फ़ अपनी header comments में अलग है, सिर्फ़ mock पर चला है।
Tests के दूसरे दौर में एक नया mock इस्तेमाल हुआ, जो उसी तरह गड़बड़ करने के लिए बनाया गया था जैसे कोई router कर सकता है, ख़ाली key वाले जवाब समेत। एक harness ने script की एक copy उस पर 30 cases में से हर एक के लिए एक बार चलाई। PowerShell 7.4.6 पर सभी 30 पास हुए।
मेरे PC पर Windows PowerShell 5.1 के तहत पहले run में दो cases fail हुए। Script के logs दिखाते थे कि उसने सही काम किया था; harness ने नहीं। जब कोई PowerShell function एक item वाली list लौटाता है, तो call करने वाले को वह item ही मिलता है। PowerShell 7 आपको उस item को list की तरह गिनने और index करने देता है। Windows PowerShell 5.1 इस तरह के object के लिए ऐसा नहीं करता। Harness सिर्फ़ PowerShell 7 पर चला था। यह ठीक करने के बाद, script के publish किए गए वर्ज़न पर Windows PowerShell 5.1 में भी सभी 30 cases पास हुए।
ख़ुद harness को जाँचने के लिए Claude ने script को दस तरह से तोड़ा, जैसे undo, JSON की जाँच या HTTPS की जाँच हटाकर। हर बिगाड़ से कम से कम एक case fail हुआ। यह जाँच PowerShell 7.4.6 पर, वर्ज़न 2.5 के विरुद्ध, harness के एक पहले वर्ज़न के साथ चली थी।
अगली script के लिए मैं क्या साथ ले जाऊँगा
- उसी PowerShell पर test करें जिस पर script चलेगी, और tests भी वहीं चलाएँ। मेरा harness PowerShell 7 पर पास हुआ और 5.1 पर अपने पहले run में fail हुआ।
- Mock के जवाब असली जवाबों से बनाएँ। Router के
get_itemसे save किया गया एक जवाब failure 2 को router तक script पहुँचने से पहले पकड़ लेता। - सिर्फ़ पढ़ने वाला mode वे सारे reads करे जो लिखने वाला mode करेगा। यहाँ
CheckऔरApplyalias को अलग-अलग endpoints से पढ़ते थे। - जब आप object की उम्मीद कर रहे हों, तो
Invoke-RestMethodसे मिली string को failure मानें। वह हमेशा error नहीं देता। - Redirect चालू करने के बाद firewall के state timeout से ज़्यादा इंतज़ार करें, और ऐसे नाम से test करें जो आपने पहले query न किया हो।
- अगर undo delete करने की जगह disable करता है, तो अगला run वह ढूँढे जो पिछला छोड़ गया।
- Script को जान-बूझकर तोड़ें, यह जाँचने के लिए कि tests fail हो सकते हैं।
- API key को script से बाहर रखें और काम पूरा होने पर उसे delete करें। मैंने
rootuser की key इस्तेमाल की। सिर्फ़ उतने privileges वाला user बेहतर होगा जितने script को चाहिए; यह मैंने आज़माया नहीं है।
अपने router पर चरण-दर-चरण चलाएँ
शुरू करने से पहले। आपको चाहिए:
- एक Windows PC, जो router वाले ही network पर हो। आप दो जगह type करेंगे: PC पर PowerShell में, और browser में router के web page पर;
- OPNsense 26.7। Script किसी दूसरी series पर रुक जाती है, क्योंकि उसके API paths उसी series के अपने pages से पढ़े गए थे;
- DNS blocklist चालू, Services → Unbound DNS → Blocklist में (OPNsense के दस्तावेज़ उस page का नाम देते हैं), और आपके devices DNS के लिए router से पूछते हों;
- एक Destination NAT rule जो router को छोड़कर कहीं और जाने वाली DNS queries (port 53) को वापस router पर भेजता है, पहले से बना हुआ, description “Redirect non-local DNS to Local” के साथ। Script उसे चालू करती है। वह उसे बनाती नहीं है। Script यह rule नहीं बनाती, यह panel भी इसे बनाना नहीं बताता, और इसके बिना Apply रुक जाता है। OPNsense forum पर एक community how-to एक तरीक़ा दिखाता है;
- एक LAN rule जिसका नाम “Default allow LAN to any rule” है, जिसे OPNsense default रूप से बनाता है। Script जाँचती है कि उसके दो नए rules उसके ऊपर बैठते हैं।
वर्ज़न 2.5.1, यानी इस panel की script, सिर्फ़ test kit के mock router पर चली है। मेरे router पर वर्ज़न 2.4 चला था।
लगभग 20 मिनट रखें; बदलाव ख़ुद लगभग दो मिनट लेता है। Router में पहला बदलाव step 3 की API key है। Step 5 का Check run उसमें कुछ नहीं बदलता। Step 6 का Apply बदलता है। Step 8 fix को बंद करता है और पूरी configuration restore करना दिखाता है। हर run router की configuration पढ़ने से पहले उसका backup PC पर save करता है।
पहले सीमाएँ पढ़ें। अगर उनमें से कोई आपके network का वर्णन करती है, तो script आपके लिए ठीक नहीं है, इसलिए आगे न बढ़ें।
सीमाएँ
- सिर्फ़ IPv4। Rules A और B IPv4 के लिए बनते हैं, और हर test एक IPv4 पता इस्तेमाल करता है। अगर आपके LAN पर IPv6 है, तो IPv6 पर DoH और DoT न block होते हैं, न test। (Interfaces → LAN में एक IPv6 Configuration Type दिखता है; None का मतलब IPv6 नहीं है।)
- सिर्फ़ LAN interface। दूसरे interfaces और VLANs cover नहीं होते।
- LAN का हर host। LAN पर कोई Pi-hole या AdGuard Home जो upstream के लिए DoH या DoT इस्तेमाल करता है, अपना upstream खो देता है। अगर वह किसी public server को सादा DNS भेजता है, तो आपका redirect rule उसे भी पकड़ सकता है, यह इस पर निर्भर है कि rule कैसे बना है।
- जो devices encrypted DNS पर ही अड़े रहते हैं। जो device सिर्फ़ किसी encrypted DNS provider के लिए set है, जैसे Private DNS में hostname वाला फ़ोन, उसका DNS lookup इस network पर बंद हो सकता है, जब rules उसका रास्ता refuse कर दें। वह setting device पर बदलें।
- Redirect rule मौजूद होना चाहिए Firewall → NAT → Destination NAT में, description “Redirect non-local DNS to Local” के साथ, या जो भी आप
$NatDescमें रखें। वह बनाया नहीं जाता, और यह जाँचा नहीं जाता कि वह कैसे बना है। - Alias overwrite होता है Hagezi URL से। पुराने contents log में लिखे जाते हैं।
- Test domain जो
$AdTestDomainमें है, आपके router की blocklist से block होना चाहिए, यानी उसका जवाब 0.0.0.0 या बिना किसी पते का हो, वरना redirect test fail होता है। - भरोसे का LAN। Script की certificate जाँच router के पते के लिए पेश किया गया कोई भी certificate मान लेती है, इसलिए LAN पर router होने का दिखावा करने वाले device को key मिल जाएगी। इसे सिर्फ़ ऐसे network पर चलाएँ जो आपके नियंत्रण में हो।
- इंतज़ार जो
$NatWaitSecondsमें है, आपके router के UDP state timeouts से लंबा होना चाहिए। - Rollback दोनों rules और redirect rule को बंद कर देता है, भले ही redirect आपके पहली बार
Applyचलाने से पहले चालू रहा हो। वह alias को restore नहीं करता।
PowerShell खोलें और एक folder बनाएँ। Start menu खोलें,
powershelltype करें और Enter दबाएँ। Windows PowerShell नाम की एक window खुलती है, और उसका promptPSसे शुरू होता है। अगर prompt मेंPSनहीं है, तो आप Command Prompt में हैं: उसे बंद करें और उसकी जगह PowerShell खोलें, क्योंकि नीचे के commands सिर्फ़ PowerShell में चलते हैं। Window के अंदर click करें। नीचे की दो lines एक-एक करके इस्तेमाल करें: एक line copy करने के लिए PS> पर click करें, उसे paste करें (Ctrl + V, या right-click), और Enter दबाएँ।New-Item -ItemType Directory -Path "$env:USERPROFILE\opnsense-dns" Set-Location "$env:USERPROFILE\opnsense-dns"पहली line आपके user folder के अंदर
opnsense-dnsनाम का folder बनाती है और एक छोटी listing print करती है; दूसरी PowerShell को उसके अंदर ले जाती है, और तब promptopnsense-dns>पर ख़त्म होता है। हर एक एक सेकंड से कम लेती है। अगर पहली line कहे कि folder पहले से है, तो आगे बढ़ें। यह window खुली रखें, और folder को OneDrive, Dropbox और shared जगहों से बाहर रखें: यहाँ save होने वाले backups में router की पूरी configuration होती है।Script save करें। इस page के आख़िर में The script, the mock router and the test harness तक scroll करें, opnsense-dns-bypass.ps1 (version 2.5.1) खोलें, उसे पढ़ें, और Copy पर click करें। वह 491 lines की है। वह आपके router की key इस्तेमाल करेगी, इसलिए चलाने से पहले उसे पढ़ें। Browser से download की गई files पर Windows निशान लगाता है कि वे internet से आई हैं; नीचे के command से लिखी गई file पर ऐसा कोई निशान नहीं होता, इसलिए
Unblock-Fileकी ज़रूरत नहीं है। Command इस folder में उसी नाम की file को replace कर देता है। PowerShell की window में:Get-Clipboard -Raw | Set-Content -Encoding Ascii .\opnsense-dns-bypass.ps1Get-Clipboardवह पढ़ता है जो आपने copy किया औरSet-Contentउसे file में लिखता है; script सादी ASCII है, इसलिए वह encoding सुरक्षित है। यह एक सेकंड से कम लेता है और कुछ print नहीं करता। जाँचें कि सब कुछ पहुँच गया:(Get-Content .\opnsense-dns-bypass.ps1).Count491अलग संख्या का मतलब हो सकता है कि copy बीच में कट गई या बदल गई। Page पर वापस जाएँ, दोबारा Copy पर click करें और पहला command दोहराएँ।
Router पर एक API key बनाएँ। Web browser में
https://type करें और वह पता जो आप router के settings page के लिए इस्तेमाल करते हैं (जैसेhttps://192.168.1.1), और Enter दबाएँ। Browser चेतावनी दे सकता है कि connection private नहीं है, क्योंकि router अपना certificate ख़ुद sign करता है। वह विकल्प चुनें जो उस पते तक जारी रखता है (Chrome में: Advanced, फिर Proceed)। अपने router के login से log in करें। फिर:- बाईं ओर के menu में System पर click करें, फिर Access, फिर Users।
- जिस administrator के रूप में आप log in करते हैं, उसकी row के आख़िर में pencil (edit) icon पर click करें।
- User की settings में API keys वाला section ढूँढें (OPNsense के दस्तावेज़ उसे ApiKeys tab कहते हैं) और उसके grid में key बनाने वाले button का इस्तेमाल करें।
- Browser कुछ सेकंड के भीतर एक छोटी text file download करता है। उसमें एक
key=line और एकsecret=line होती है। दस्तावेज़ कहते हैं कि secret सिर्फ़ एक बार बनता है; file खो जाए तो नई key बनाएँ।
Key उसी user की तरह काम करती है जिसकी वह है। मैंने root user की key इस्तेमाल की और बाद में उसे delete कर दिया; root key router का पूरा नियंत्रण देती है। सिर्फ़ firewall, NAT और backup pages तक सीमित user के पास कम अधिकार होगा, पर script router की पूरी configuration download करती है, इसलिए वह user भी उसमें के password hashes और private keys पढ़ सकता है। मैंने सीमित user आज़माया नहीं है। अगर आपका menu अलग दिखता है, तो local users पर OPNsense के दस्तावेज़ यही step बताते हैं। Key file को कहीं paste न करें: उसमें का secret router का नियंत्रण देता है।
Key file को folder में रखें। PowerShell में वापस आकर, अपने Downloads folder की सबसे नई text files की list निकालें:
Get-ChildItem "$env:USERPROFILE\Downloads" -Filter *.txt | Sort-Object LastWriteTime -Descending | Select-Object -First 3 Name, LastWriteTimeName LastWriteTime ---- ------------- example_apikey.txt <date and time>अगर list ख़ाली है, तो आपके browser ने file कहीं और save की है: browser में Ctrl + J दबाकर देखें कि कहाँ। अब file को उस नाम से folder में ले जाएँ जो script उम्मीद करती है।
<file-name>को, angle brackets समेत, list के नाम से बदलें:Move-Item -LiteralPath "$env:USERPROFILE\Downloads\<file-name>" -Destination .\apikey.txtयह एक सेकंड से कम लेता है और कुछ print नहीं करता। यह folder में पहले से मौजूद
apikey.txtको overwrite नहीं करेगा; अगर वह इसी कारण मना करे, तो वहाँ पहले की कोई key file है। उस key को router पर हटाएँ (step 8 बताता है कहाँ),Remove-Item .\apikey.txtचलाएँ, और यह step दोहराएँ। अगर वह path के बारे में error बताए, तो हो सकता है path में अब भी<file-name>हो, या नाम list के नाम से अलग हो। अब जाँचें कि key file में उसकी दो lines हैं। यह हर=से पहले का सिर्फ़ शब्द print करता है, मान कभी नहीं:Get-Content .\apikey.txt | ForEach-Object { ($_ -split '=')[0] }key secretअगर आपको दूसरे शब्द दिखें, तो शायद यह key file नहीं है। नई key download करें (step 3)।
Check चलाएँ। यह सिर्फ़ पढ़ता है। पहले PowerShell को अपने router का पता बताएँ। Line copy करने के लिए PS> पर click करें, उसे paste करें, और अभी Enter न दबाएँ।
<router-ip-address>को, angle brackets समेत, step 3 के पते की संख्याओं से बदलें (जैसे192.168.1.1), औरhttps://को वैसा ही रहने दें। Cursor को arrow keys से हिलाएँ, क्योंकि PowerShell में mouse click से cursor नहीं हिलता; Backspace मिटाता है। फिर Enter दबाएँ। अगर angle brackets अब भी वहाँ हैं तो script रुक जाती है।$RouterUrl = 'https://<router-ip-address>'यह पता सिर्फ़ इस window के लिए याद रखा जाता है। Window बंद करें तो इसे दोहराएँ।
अब script चलाएँ।
powershell -ExecutionPolicy Bypass -Fileएक नया Windows PowerShell 5.1 शुरू करता है जो file चलाता है। Command line पर दिया गया-ExecutionPolicy Bypassसिर्फ़ उसी एक run के लिए रहता है, और execution policies पर Microsoft के दस्तावेज़ कहते हैं कि वह store नहीं होता। यह किसी employer की लगाई Group Policy को override नहीं करता।-Modeके बिना scriptCheckचलाती है।powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrlयह 10 से 60 सेकंड लेता है और router पर कुछ नहीं बदलता। यह router की configuration का backup
router-backupsfolder में, जोopnsense-dnsके अंदर है, एक loglogsमें save करता है, और पाँच live tests चलाता है। ज़रूरी lines:HH:MM:SS Router reports: OPNsense series 26.7, amd64 HH:MM:SS Backup (before) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Check-before-<timestamp>.xml (NNN,NNN bytes) ... HH:MM:SS Router resolves example.com : True (want True) HH:MM:SS Router blocks the ad domain (blocklist) : True (want True) HH:MM:SS Bypass DoH 1.1.1.1:443 reachable : True (want False after Apply) HH:MM:SS Bypass DoT 9.9.9.9:853 reachable : True (want False after Apply) HH:MM:SS Bypass 8.8.8.8 gives real ad IPs : True (want False after Apply) HH:MM:SS Check mode: nothing was changed on the router. HH:MM:SS Log file: C:\Users\<you>\opnsense-dns\logs\run-Check-<timestamp>.logदोनों “want True” lines True होनी चाहिए। अगर “Router blocks the ad domain” False है, तो आपकी blocklist test domain को block नहीं करती और step 6 का redirect test fail होगा। Script के ऊपरी हिस्से में
$AdTestDomainको ऐसे domain पर set करें जिसे आपकी blocklist block करती है, या blocklist चालू करें। अगर कोई पीली lineApply would stop:से शुरू होती है, तो वह किसी ग़ायब rule का नाम बताती है: redirect rule या LAN allow-all rule। Step 6 से पहले उसे router पर ठीक करें।अगर कुछ गड़बड़ हुई। Script एक लाल line print करती है (ज़्यादातर में शब्द STOP होता है) और router पर कुछ नहीं बदलती। Line क्या कहती है, और उसका मतलब क्या है:
- Set -Router to your router’s address: इस step के पते में angle brackets अब भी हैं।
- Missing an argument for parameter ‘Router’: शायद ऊपर की पते वाली line इस window में चलाई नहीं गई। उसे फिर चलाएँ।
- -Router must start with https://: पता
http://से शुरू होता है।https://इस्तेमाल करें। - STOP: Key file not found:
apikey.txtopnsense-dnsfolder में नहीं है। Step 4 फिर करें। - STOP: Cannot reach the router API with this key: पता ग़लत है, key हटा दी गई थी, या PC router के network पर नहीं है। पते को browser में खोलकर जाँचें।
- STOP: Script was built for OPNsense 26.7: आपका router दूसरी series पर है, और script के API paths 26.7 से पढ़े गए थे। यहीं रुक जाएँ।
- PowerShell कहता है कि scripts चलाना बंद है: आपके PC की एक policy scripts को रोकती है, और command-line option उसे override नहीं कर सकता। यहीं रुक जाएँ।
Apply चलाएँ। यह router को बदलता है। यह alias
DoH_IPsको Hagezi list के पते से overwrite करता है (पुराने contents log में जाते हैं), दो reject rules जोड़ता है अगर वे न हों, और redirect rule को चालू करता है। आपके network के जो devices किसी DNS-over-HTTPS या DNS-over-TLS server से सीधे बात करते हैं, वे वह रास्ता खो देते हैं; यही मक़सद है। वही command चलाएँ,-Mode Applyजोड़कर:powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Applyयह लगभग दो मिनट लेता है, और चार तक, अगर alias को पहले अपनी list download करनी पड़े। एक line कहती है
Waiting 70 s for older DNS states to expire before testing...; उसका इंतज़ार करें और window बंद न करें। आख़िरी lines ऐसी होनी चाहिए:HH:MM:SS Bypass DoH 1.1.1.1:443 reachable : False (want False after Apply) HH:MM:SS Bypass DoT 9.9.9.9:853 reachable : False (want False after Apply) HH:MM:SS Bypass 8.8.8.8 gives real ad IPs : False (want False after Apply) HH:MM:SS Backup (after) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Apply-after-<timestamp>.xml (NNN,NNN bytes) HH:MM:SS Apply finished. Expected: router tests True, all three bypass tests False. HH:MM:SS Log file: C:\Users\<you>\opnsense-dns\logs\run-Apply-<timestamp>.logअगर कुछ गड़बड़ हुई। Apply did not complete; changes from this run were undone: कोई test fail हुआ, और script ने जो बदला था उसे बंद कर दिया। जो rules उसने जोड़े वे बंद हालत में रहते हैं। उसने नतीजे का backup save किया। कारण के लिए वह line पढ़ें जो Problem: से शुरू होती है। अगर कोई line UNDO STEP FAILED कहे, तो “before” backup को restore करें, जैसा step 8 बताता है। Apply PARTLY finished (पीले में): alias और दोनों rules लग चुके हैं और test हो चुके हैं, और redirect पास नहीं हुआ; line बताती है कि redirect चालू छोड़ा गया या बंद। Fix को बंद करने के लिए step 8 इस्तेमाल करें।
जाँचें कि काम हुआ। Step 5 का Check command फिर चलाएँ:
powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrlअब तीनों
BypasslinesFalseदिखाती हैं और दोनोंRouterlinesTrue। Router के web page में आप Firewall → Rules भी देख सकते हैं (interface selector में LAN चुनें), जहाँ दोनों rules Reject DoH to known resolvers (A) और Reject DoT/DoQ 853 from LAN (B) अब दिखते हैं, और Firewall → NAT → Destination NAT में, जहाँ Redirect non-local DNS to Local चालू है।इसे बंद करें, ज़रूरत हो तो restore करें, और key हटाएँ। Fix को बंद करने के लिए command को
-Mode Rollbackके साथ चलाएँ:powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Rollbackयह एक मिनट से कम लेता है। यह दोनों rules और redirect को disable करता है और कुछ delete नहीं करता। Alias वैसा ही रहता है जैसा Apply ने छोड़ा। अगर redirect आपके शुरू करने से पहले चालू था, तो वह अब बंद है: उसे Firewall → NAT → Destination NAT में फिर चालू करें।
पूरी configuration को Apply से पहले जैसी थी वैसी वापस लाने के लिए, router पर backup restore करें: System → Configuration → Backups पर जाएँ,
config-Apply-before-<timestamp>.xmlनाम की file चुनें, जोrouter-backupsfolder में है, और उसे restore करें। हर Apply run ऐसी एक file save करता है; सबसे पुरानी में आपके पहले Apply से पहले की configuration है। इससे router पर उसके बाद किया गया कोई भी दूसरा बदलाव भी undo हो जाता है।जब script का काम पूरा हो जाए, चाहे fix रखें या नहीं, key हटा दें। Router पर System → Access → Users पर जाएँ, उसी user पर pencil पर click करें, और API keys वाले section में key हटा दें (ApiKeys tab)। फिर key file को PC से delete करें:
Remove-Item .\apikey.txtयह file को तुरंत delete कर देता है, recycle bin के बिना। जब आपको backups की ज़रूरत न रहे, तो
router-backupsfolder भी delete करें: उसमें password hashes और private keys हैं।
सुरक्षा संबंधी नोट। Script हर request के साथ key भेजती है। वह secret को print या log नहीं करती, और test kit अपने 30 cases में से हर एक में यह जाँचता है। उसकी certificate जाँच router के पते के लिए पेश किया गया कोई भी certificate मान लेती है, इसलिए LAN पर router होने का दिखावा करने वाले device को key मिल जाएगी। मैंने अपनी key 13 अक्टूबर 2026 को delete की, run के दो दिन बाद, और router की configuration का history इस deletion को दर्ज करता है।
Backups router की पूरी configuration हैं: password hashes, और उसके certificates और VPN tunnels की private keys। उस folder को निजी रखें, और किसी forum post के साथ backup attach न करें।
विस्तार से: script की दूसरी जाँचें
- Backup, backup जैसा दिखना चाहिए। Download के बाद script जाँचती है कि file कम से कम 50,000 bytes की है और उसकी पहली तीन lines में
<opnsense>है। - Fail हुआ save पकड़ा जाता है।
validationsवाला जवाब fail हुआ save गिना जाता है, जैसा router के अपने web pages में होता है;resultकाfailedहोना भी। Alias और redirect के बदलाव वापस पढ़े जाते हैं। Rule के बदलाव rules की मौजूदगी और क्रम से, और live connection tests से जाँचे जाते हैं। - Rule का क्रम। Rules A और B जोड़ने के बाद, अगर दोनों में से कोई “Default allow LAN to any rule” के बाद sort होता है तो script रुक जाती है, क्योंकि allow-all rule के नीचे का rule कभी match नहीं होगा।
- Alias भरना चाहिए। यह alias को हर 5 सेकंड पर, 90 सेकंड तक poll करती है और जब तक उसमें कम से कम 500 पते न हों, रुक जाती है।
- सामान्य browsing चलती रहनी चाहिए। Rules को ठीक घोषित करने से पहले, यह
www.google.com:443से एक connection खोलती है। - अधूरा नतीजा अधूरा ही बताया जाता है। अगर सिर्फ़ redirect वाला चरण fail होता है, तो run
Apply PARTLY finishedपर ख़त्म होता है, बताता है कि redirect को किस state में छोड़ा, और code 2 के साथ exit करता है।
विस्तार से: ख़राब certificate सिर्फ़ router के पते के लिए मानना
Router का web interface एक self-signed certificate इस्तेमाल करता है। PowerShell 7 में -SkipCertificateCheck है, जिसे script वहाँ इस्तेमाल करती है। Windows PowerShell 5.1 में ऐसा कोई switch नहीं है। एक आम workaround एक callback है जो पूरे session के लिए हर certificate मान लेता है। Script का callback fail हुई certificate जाँच को सिर्फ़ तब मानता है जब request का host router का पता हो:
public static bool Check(object sender, X509Certificate c, X509Chain ch, SslPolicyErrors e) {
if (e == SslPolicyErrors.None) return true;
HttpWebRequest r = sender as HttpWebRequest;
return r != null && r.RequestUri.Host == Host;
}यह छूट को सीमित करता है। यह certificate को pin नहीं करता: उस पते के लिए पेश किया गया कोई भी certificate पास हो जाता है। Certificate का thumbprint जाँचने से यह कमी बंद हो जाएगी। Script 5.1 के लिए TLS 1.2 भी set करती है।
विस्तार से: एक एहतियात, failure नहीं: Expect: 100-continue
Check mode सिर्फ़ GET requests भेजता है। Apply POSTs भेजता है। Windows PowerShell 5.1 .NET Framework पर चलता है, जहाँ ServicePointManager.Expect100Continue default रूप से true होता है और body वाली POST requests में एक Expect: 100-continue header जोड़ता है (Microsoft के दस्तावेज़)। वर्ज़न 2.2 पहली request से पहले यह header बंद कर देता है:
[Net.ServicePointManager]::Expect100Continue = $falseमैंने test नहीं किया कि router का web server इस header पर आपत्ति करता या नहीं।
विस्तार से: पूरा हुआ run, line दर line
15:04 वाले run का log। Router का पता और उसके एक interface का नाम angle brackets में placeholders से बदले गए हैं; local folder और PowerShell का build number हटाए गए हैं, और bytes की गिनती के अंक तीन-तीन के समूहों में रखे गए हैं। शुरुआती tests blocklist से बचने के तीनों रास्ते खुले दिखाते हैं; आख़िरी tests उन्हें बंद दिखाते हैं, test किए गए तीन IPv4 पतों के लिए।
15:04:49 Mode: Apply Router: https://<router-ip-address> PowerShell 5.1
15:04:55 Router reports: OPNsense series 26.7, amd64
15:04:55 Backup (before) saved: ...\config-Apply-before-20261011-150449.xml (404,269 bytes)
15:04:56 Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[__<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
15:04:56 Rule A: present, enabled=0, sort_order=400000.0000100
15:04:56 Rule B: present, enabled=0, sort_order=400000.0000200
15:04:56 'Default allow LAN to any rule': sort_order=400000.1000023
15:04:56 NAT 'Redirect non-local DNS to Local': disabled=1
15:04:56 Router resolves example.com : True (want True)
15:04:56 Router blocks the ad domain (blocklist) : True (want True)
15:04:56 Bypass DoH 1.1.1.1:443 reachable : True (want False after Apply)
15:04:56 Bypass DoT 9.9.9.9:853 reachable : True (want False after Apply)
15:04:56 Bypass 8.8.8.8 gives real ad IPs : True (want False after Apply)
15:04:56 Alias DoH_IPs set to the URL only (was: __<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt).
15:04:58 Alias DoH_IPs holds 1434 addresses.
15:04:58 Rule 'Reject DoH to known resolvers (A)' enabled.
15:04:58 Rule 'Reject DoT/DoQ 853 from LAN (B)' enabled.
15:04:58 Firewall rules applied. Verifying...
15:05:08 Rules A and B verified: DoH and DoT refused, normal HTTPS works.
15:05:08 NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
15:06:18 NAT redirect verified: queries to 8.8.8.8 are answered by your router.
15:06:19 Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
15:06:19 Rule A: present, enabled=1, sort_order=400000.0000100
15:06:19 Rule B: present, enabled=1, sort_order=400000.0000200
15:06:19 'Default allow LAN to any rule': sort_order=400000.1000023
15:06:19 NAT 'Redirect non-local DNS to Local': disabled=0
15:06:23 Router resolves example.com : True (want True)
15:06:23 Router blocks the ad domain (blocklist) : True (want True)
15:06:23 Bypass DoH 1.1.1.1:443 reachable : False (want False after Apply)
15:06:23 Bypass DoT 9.9.9.9:853 reachable : False (want False after Apply)
15:06:23 Bypass 8.8.8.8 gives real ad IPs : False (want False after Apply)
15:06:23 Backup (after) saved: ...\config-Apply-after-20261011-150449.xml (404,254 bytes)
15:06:23 Apply finished. Expected: router tests True, all three bypass tests False.Alias में एक entry थी जो मैंने जान-बूझकर नहीं डाली थी: router के एक interface का network, URL से पहले। Run ने बदलने से पहले पुराने contents print किए, इसलिए उन्हें log से वापस लाया जा सकता है।
विस्तार से: test kit क्या जाँचता है, और क्या नहीं जाँच सकता
Mock script के API paths का जवाब देता है, router की state memory में रखता है, हर call दर्ज करता है, और गड़बड़ करने के लिए set किया जा सकता है: ग़लत वर्ज़न, ख़राब API key, छोटा backup, बदलावों के बाद fail होने वाला backup, ग़लत type का alias, ख़ाली key वाला जवाब, ऐसा save जिसे router reject करे, ऐसा alias जो न भरे, allow-all rule के नीचे sort होने वाले rules, DoH का फिर भी पहुँच में होना, सामान्य HTTPS का टूटना, redirect rule या allow rule का न होना, ऐसा redirect जो असर न करे, और ऐसा redirect जो पहले से चालू था। यह उन states को भी दोहराता है जिनसे मेरा router गुज़रा: एक भटकी हुई entry वाला alias, वर्ज़न 2.3 के disable छोड़े गए दो rules, और सब कुछ पहले से लागू (applied)। इसका ख़ाली key वाला जवाब हाथ से लिखा गया है, router के get_item जवाब के आधार पर, और उस endpoint पर दिया जाता है जिसे script पढ़ती है।
Harness script को हर case के लिए एक बार, अलग process के रूप में चलाता है, और exit code, log, backup files, mock को मिली हर call, और आख़िर में mock router की state जाँचता है। हर case में यह जाँचता है कि न secret और न encoded key output या log में दिखे, कि कुछ भी delete न हुआ हो, और कि log खुलने के बाद का कोई भी stop log में लिखा जाए।
Harness script की एक copy को test करता है, ख़ुद script को नहीं। Copy में दोनों network tests internet की जगह mock से पूछते हैं, और हर इंतज़ार एक millisecond कर दिया जाता है; कोई भी case चलने से पहले harness जाँचता है कि इनमें से हर pattern उम्मीद जितनी बार match हुआ। Copy PC पर सादे HTTP से mock से बात करती है; script सादा HTTP सिर्फ़ PC पर ही मौजूद पते के लिए मानती है।
तो kit ये चीज़ें test नहीं करता: certificate जाँच और TLS; असली network tests; failure 3, क्योंकि mock में कोई state table नहीं है और इंतज़ार छोटे कर दिए गए हैं; असली router के जवाब, हाथ से लिखे एक ख़ाली key वाले जवाब के सिवा; script का backup overwrite करने से मना करना; work folder का fallback, क्योंकि हर case एक folder का नाम देता है; या ऐसा undo step जो ख़ुद fail हो जाए।
script में जान-बूझकर किए गए दस बिगाड़ और हर एक से fail हुए cases, पेज के आख़िर में kit के साथ दिए गए हैं।
विस्तार से: OPNsense 26.7 API पर टिप्पणियाँ
- Script का header दर्ज करता है कि हर configuration path उस दिन router के अपने web pages से लिया गया था:
alias/search_item,alias/add_item,alias/set_item,alias/reconfigure,filter/search_rule,filter/add_rule,filter/set_rule,filter/apply,d_nat/search_rule,d_nat/set_rule,d_nat/apply,alias_util/listऔरcore/backup/download/this। यह वर्ज़न के लिएcore/firmware/infoऔर पहुँच की जाँच के लिएcore/firmware/statusभी call करती है। - Search endpoints
?rowCount=-1¤t=1वाली GET का जवाब देते हैं और हर row लौटाते हैं, उन fields के साथ जो script को चाहिए। alias/get_itemख़ाली नाम वाली keys के साथ option lists लौटाता है, जिन्हें PowerShell object properties में नहीं बदल सकता।GET /api/core/backup/download/thisपूरी configuration XML के रूप में लौटाता है।- POST bodies
Content-Type: application/jsonके साथ JSON होती हैं। Rule के बदलाव मेल खातेapplyके बाद असर करते हैं; alias के बदलावreconfigureके बाद।
शब्दावली
- Windows PowerShell 5.1: वह PowerShell जो Windows के साथ आता है, .NET Framework पर बना।
powershellसे शुरू होता है। - PowerShell 7: नया PowerShell, अलग से install होता है, आधुनिक .NET पर बना।
pwshसे शुरू होता है। - REST API: web पतों का एक set जिसे कोई program settings पढ़ने या बदलने के लिए call करता है; OPNsense के जवाब JSON में होते हैं।
- JSON: structured data के लिए एक text format।
- Mock: किसी असली system की जगह खड़ा किया गया नक़ली system, testing के लिए; यहाँ, एक छोटा web server जो router की तरह जवाब देता है।
- Test harness: एक script जो किसी दूसरी script को कई तय स्थितियों में चलाती है और नतीजे जाँचती है।
- API key: एक key और secret जो script को बिना password के router user की तरह काम करने देते हैं।
- Alias (URL table): पतों की एक OPNsense list जिसे router एक web पते से download करता है और refresh करता है।
- NAT redirect: एक rule जो match होने वाली traffic की मंज़िल बदलता है; यहाँ यह भटकी DNS queries को router पर भेजता है।
- State table: firewall की वह list जिसमें उन connections का हिसाब रहता है जिन्हें वह पहले देख चुका है। किसी जाने-पहचाने connection के बाद के packets पहले packet के लिए लिए गए फ़ैसले के हिसाब से चलते हैं।
- DoH, DoT: DNS over HTTPS (port 443) और DNS over TLS (port 853), किसी device के लिए router से पूछे बिना नामों का पता लगाने (DNS lookup) के दो तरीक़े।
Expect: 100-continue: एक HTTP header जो server से कहता है कि request की body भेजे जाने से पहले उसे मंज़ूरी दे।
ప్రతి టెస్ట్లోనూ పాసైంది, తప్పు చోట
11 అక్టోబర్ 2026 మధ్యాహ్నం నా OPNsense router API మీద Windows PowerShell 5.1 నుంచి ఒక script నడిపాను. ఇది Windows తో పాటు వచ్చే PowerShell. script తన log లో ఒక్క లైన్ కూడా రాయకముందే ఆగిపోయింది. router కి script చేసే మొదటి call ఆ లైన్ తర్వాత వస్తుంది. కాబట్టి, నాకు తెలిసినంతవరకు, router వరకు ఏదీ చేరలేదు.
అది వెర్షన్ 2.0. వెర్షన్ 2.4 పనిని 15:06 కి పూర్తి చేసింది, నేను వెర్షన్ 2.0 ని save చేసిన 37 నిమిషాల తర్వాత. ప్రతి వెర్షన్ ముందుగా Claude sandbox లో తన టెస్ట్లను పాసైంది. ఆ టెస్ట్లు తప్పు చోట నడిచాయి: నిజమైన router కి బదులు ఒక mock router మీద, Windows PowerShell 5.1 కి బదులు PowerShell 7 కింద. తర్వాత router మీద ఫెయిల్ అయిన మూడు వెర్షన్లనూ mock పాస్ చేసింది. వైఫల్యం 1 లో PowerShell తేడా పాత్ర పోషించిందో లేదో నాకు తెలియదు. వైఫల్యం 2 లో అది ఏ పాత్రా పోషించలేదు, తర్వాత నా test harness ని ఫెయిల్ చేసింది. మూడు రన్లు ఫెయిల్ అయ్యాయి, ఒక్కొక్కటి వేరే కారణంతో. వాటిలో ఏదీ ఏ మార్పునూ on లో వదిలిపెట్టలేదు.
ఈ పని Claude తో కలిసి చేశాను. script పాటించాల్సిన rules నేను నిర్ణయించాను, API key సృష్టించాను, తర్వాత దాన్ని delete చేశాను, ప్రతి వెర్షన్నీ నా సొంత PC లో, నా సొంత router మీద నడిపాను. script, దాన్ని టెస్ట్ చేసిన mock router, ప్రతి fix Claude రాసింది. వాటిని PowerShell 7 కింద టెస్ట్ చేసింది. దాని sandbox లో ఉన్న PowerShell అదొక్కటే.
script, ఒక mock router, ఒక test harness ఈ పేజీ చివర MIT licence కింద ఉన్నాయి. router తన DNS blocklist ని తప్పించుకునే మూడు సాధారణ మార్గాలను నిరాకరించేలా script చేస్తుంది: DNS over HTTPS, DNS over TLS లేదా QUIC, వేరే server కి పంపే plain DNS. ఈ పేజీ రన్లను, నేను ఏం మారుస్తానో నమోదు చేస్తుంది; చివర దగ్గర ఉన్న ఒక panel మీ సొంత router మీద script ని ఎలా నడపాలో step by step చెబుతుంది.
command line కి కొత్తవారా? boxes ని ఎలా చదవాలి
PS> అంటే: దీన్ని Windows లోని PowerShell లో టైప్ చేయండి (Start menu → powershell అని టైప్ చేయండి → Enter). PS> ని మాత్రం టైప్ చేయవద్దు.
PS> తో మొదలయ్యే ప్రతి లైన్ ఒక command. ఆ PS> మీద click చేస్తే ఆ లైన్ మాత్రమే copy అవుతుంది; దాన్ని paste చేసి, Enter నొక్కి, అది పూర్తయ్యే వరకు ఆగి, ఆ తర్వాతే తర్వాతి దాన్ని చేయండి. పైన Copy button ఉన్న box లో ఒక command (లేదా ఒక file) ఉంటుంది, కాబట్టి దాన్ని పూర్తిగా copy చేయండి. చుక్కల గీతల (dashed) box మీరు తిరిగి చూడాల్సినదాన్ని, లేదా చదవాల్సిన code ని చూపుతుంది; దాన్ని టైప్ చేయరు.
ఈ script ఏం చేస్తుంది
ఈ script ఒక OPNsense 26.7 router మీద ఒక DNS fix ని అమలు చేస్తుంది. నా router blocklist, router ని అడిగే devices ని మాత్రమే filter చేస్తుంది; phones, browsers, కొన్ని devices వేరే servers ని అడుగుతాయి. ఈ fix లో నాలుగు objects ఉంటాయి:
DoH_IPsఅనే alias. ఇది Hagezi project నిర్వహించే DNS-over-HTTPS server అడ్రసుల public జాబితాను download చేస్తుంది (ఆ రోజు అందులో 1,434 అడ్రసులు);- Rule A. ఆ అడ్రసులకు port 443 మీద వెళ్లే LAN traffic ని reject చేస్తుంది;
- Rule B. ఏ అడ్రసుకైనా port 853 మీద వెళ్లే LAN traffic ని reject చేస్తుంది. DNS over TLS, DNS over QUIC ఈ port వాడతాయి;
- ఒక NAT redirect. router ని దాటి వెళ్లే ఏ port 53 query నైనా తిరిగి router కే పంపుతుంది.
నా router లో alias, redirect rule ముందే ఉన్నాయి; redirect off లో ఉంది. script alias ని శుభ్రం చేస్తుంది, రెండు rules లేకపోతే సృష్టిస్తుంది, redirect ని on చేస్తుంది. redirect rule ని అది సృష్టించదు. rules IPv4 ని, LAN interface ని మాత్రమే cover చేస్తాయి; పరిమితులు చివర దగ్గర ఉన్న step-by-step panel లో ఉన్నాయి.
ఈ నాలుగు objects ని click చేసి పెట్టడం నాకు సాధ్యమే. అయినా script రాశాను, ఎందుకంటే ఈ మార్పు ఒక రూపంలో ఉండాలనుకున్నాను: ఏదీ మార్చకుండా చెక్ చేయగలిగేలా, మళ్లీ నడపగలిగేలా, ఒక్క command తో off చేయగలిగేలా.
అది పాటించే rules
- మూడు modes.
Checkచదివి report ఇస్తుంది.Applyమార్పు చేస్తుంది.Rollbackరెండు rules నీ redirect నీ off చేస్తుంది, దేన్నీ delete చేయదు.-Modeలేని commandCheckనడుపుతుంది. - వెర్షన్ guard. script ముందుగా router ఏం నడుపుతోందో అడుగుతుంది. జవాబు 26.7 series కాకపోతే ఆగిపోతుంది.
- వెర్షన్ guard తర్వాత backup. ఏ configuration ని చదవడానికి గానీ మార్చడానికి గానీ ముందే, ప్రతి రన్ router పూర్తి configuration ని ఒక కొత్త file లోకి download చేస్తుంది. ఉన్న file ని overwrite చేయడానికి నిరాకరిస్తుంది.
- ప్రతి మార్పునూ టెస్ట్ చేయండి. ముందు alias, తర్వాత రెండు rules, తర్వాత redirect. వెర్షన్ 2.3 లో ఒక టెస్ట్ ఫెయిల్ అయితే ఆ రన్ చేసిన మార్పులన్నీ undo అయ్యేవి. వెర్షన్ 2.4 నుంచి, redirect ఒక్కటే ఫెయిల్ అయితే redirect ఒక్కటే off అవుతుంది; పాసైన rules అలాగే ఉంటాయి.
- script లో secret ఉండదు. API key వేరే file లో ఉంటుంది.
ముప్పై ఏడు నిమిషాలు
| మొదలైన సమయం | వెర్షన్ | Mode | ఏం జరిగింది | router మీద మిగిలింది |
|---|---|---|---|---|
| 14:29 తర్వాత | 2.0 | log కాలేదు | మొదటి log లైన్ కంటే ముందే ఆగింది | ఏమీ లేదు |
| 14:43 | 2.1 | Check | read-only report, పూర్తైంది | ఏమీ లేదు |
| 14:51 | 2.2 | Apply | ఏ save కంటే ముందే తన సొంత guard వల్ల ఆగింది | ఏమీ లేదు |
| 14:56 | 2.3 | Apply | rules పనిచేశాయి; redirect టెస్ట్ ఫెయిల్; undo అయింది | రెండు rules, disabled |
| 15:04 | 2.4 | Apply | 15:06 కి పూర్తైంది, ప్రతి టెస్ట్ పాసైంది | fix |
వెర్షన్ 2.0 log రాయలేదు, కాబట్టి దాని సమయం నేను file ని save చేసిన నిమిషం. మిగతా సమయాలు script సొంత logs నుంచి.
పనుల క్రమం నష్టాన్ని పరిమితం చేసింది. script వెర్షన్ చెక్ చేస్తుంది, backup తీసుకుంటుంది, రాసే ముందు చదువుతుంది. వైఫల్యం 1 router కి ఏ call కంటే ముందే ఆగింది. వైఫల్యం 2 ఏ save కంటే ముందే ఆగింది, వేరే సమస్య కోసం రాసిన guard వల్ల. వైఫల్యం 3 మార్పులు జరిగిన తర్వాత వచ్చింది; ఆ వెర్షన్ undo వాటిని off చేసింది.
వైఫల్యం 1: నేను తప్పుగా గుర్తించిన కారణం
వెర్షన్ 2.0 తన working folder ని ఒక parameter default నుంచి తీసుకుంది:
[string]$WorkDir = $PSScriptRoot$PSScriptRoot అంటే script ఉన్న folder. script దాన్ని తన logs folder path కట్టడానికి వాడుతుంది. ఆ folder ని key చదవడానికి, router ని call చేయడానికి ముందే సృష్టిస్తుంది.
వెర్షన్ 2.1 మూడు విషయాలు మార్చింది. folder ని script body లో లెక్కించింది. ఆ folder లేకపోతే ఆగింది. ఖాళీ DNS జవాబు సున్నాగా లెక్కకు వచ్చేలా రెండు counts ని wrap చేసింది. వీటిలో folder మార్పులు మాత్రమే మొదటి log లైన్ కంటే ముందు వస్తాయి. ఆ రోజు Windows PowerShell 5.1 $PSScriptRoot ని ఖాళీగా వదిలిందనే నిర్ధారణకు Claude, నేను వచ్చాం. ఈ post మొదటి drafts కూడా అదే చెప్పాయి.
ఈ post కోసం తయారు చేసిన test kit దాన్ని చెక్ చేసింది, ఆ నిర్ధారణ తప్పు. నా PC లో, నేను script ని మొదలుపెట్టే విధంగానే -File తో మొదలుపెట్టిన Windows PowerShell 5.1, parameter default లో $PSScriptRoot లోకి folder ని పెట్టింది. PowerShell 7.4.6 కూడా అలాగే చేసింది. script ని మొదలుపెట్టే పద్ధతుల్లో కొన్నింటినే టెస్ట్ చేశాను, కాబట్టి కొన్ని పద్ధతుల్లో అది ఖాళీగా ఉండే అవకాశాన్ని కొట్టిపారేయలేను. ఆ మధ్యాహ్నం వెర్షన్ 2.0 ని ఎలా మొదలుపెట్టానో, అది చూపిన error ఏమిటో నేను record చేయలేదు, కాబట్టి దాన్ని ఏది ఆపిందో నాకు తెలియదు. ఆధారాలు సమర్థించేది ఇంతకంటే పరిమితమైనది: వెర్షన్ 2.0 తన మొదటి log లైన్ కంటే ముందే ఆగింది, కాబట్టి, ఆధారాలు చూపినంతవరకు, router కి ఏ call కంటే ముందే. ప్రచురించిన script లోని ఒక comment, Windows PowerShell 5.1 కింద ఆ folder ఖాళీగా ఉండవచ్చని చెబుతుంది. ఆ comment నా మొదటి నిర్ధారణనే పునరావృతం చేస్తుంది; టెస్ట్ చేసిన file ని నేను అలాగే వదిలేశాను.
వెర్షన్ 2.1 లోని మార్పు అలాగే ఉంటుంది. దానికి ఖర్చు ఏమీ లేదు. script ని ఏ విధంగా మొదలుపెట్టినా అది పనిచేస్తుంది:
if ([string]::IsNullOrWhiteSpace($WorkDir)) {
if ($MyInvocation.MyCommand.Path) { $WorkDir = Split-Path -Parent $MyInvocation.MyCommand.Path }
else { $WorkDir = (Get-Location).Path }
}వెర్షన్ 2.1 యొక్క Check రన్ 14:43 కి పూర్తైంది.
వైఫల్యం 2: router విచిత్రాలు లేని mock
alias type చెక్ చేయడానికి వెర్షన్ 2.2 router alias/get_item endpoint ని call చేసింది. 14:51 నాటి run log:
14:51:46 Problem: Existing alias DoH_IPs is type '', not urltable. Fix or delete it in the GUI, then rerun.
14:51:46 Nothing to undo.
...
14:51:47 STOP: Apply did not complete; changes from this run were undone.alias type ఖాళీ కాదు. router జవాబులో పేరు ఖాళీ string గా ఉన్న entries ఉన్నాయి ("":). JSON దీన్ని అనుమతిస్తుంది. ఖాళీ పేరుతో object property ని PowerShell తయారు చేయలేదు. ConvertFrom-Json గురించి Microsoft documentation ఇదే చెబుతుంది (PowerShell 7.4 reference), అలాంటి జవాబుల కోసం -AsHashtable switch ని సూచిస్తుంది. Windows PowerShell 5.1 లో ఆ switch లేదు. Invoke-RestMethod ఏ error నూ ఇవ్వలేదు. జవాబును plain text గా తిరిగి ఇచ్చింది, script ఆ text నుంచి type ని ఏమీ లేనిదిగా చదివింది.
ఇది PowerShell వెర్షన్ల మధ్య తేడా కాదు. test kit script కి ఖాళీ key ఉన్న జవాబును ఇస్తుంది. PowerShell 7.4.6 కింద, నా PC లో Windows PowerShell 5.1 కింద కూడా, Invoke-RestMethod దాన్ని text గా, error లేకుండా తిరిగి ఇచ్చింది. వెర్షన్ 2.2 mock మీద పాసైంది, ఎందుకంటే mock జవాబులో ఖాళీ keys లేవు. router జవాబులో ఉన్నాయి.
రన్ని ఆపిన guard వేరే సమస్య కోసం రాసినది: తప్పు type తో ముందే ఉన్న alias. ఖాళీ type urltable కాదు కాబట్టి అది ఈ రన్ని ఆపింది. అది లేకపోతే రన్ కొత్త URL ని save చేసి ఉండేది, తర్వాత undo లో alias లోకి ఖాళీ string రాసి ఉండేది.
14:43 Check రన్ దీన్ని పట్టుకోలేదు. Check alias ని alias/search_item ద్వారా చదివింది. Apply మాత్రమే get_item ని call చేసింది.
వెర్షన్ 2.3 రెండు మార్పులు చేస్తుంది. router search_item, search_rule endpoints ఇప్పటికే type నీ contents నీ ఇస్తాయి, వాటి జవాబులు parse అయ్యాయి. కాబట్టి script వాటి ద్వారా మాత్రమే చదువుతుంది. ఇంకా, ప్రతి API call ఇప్పుడు ఒకే helper ద్వారా వెళ్తుంది. parse చేయలేని జవాబును ఆ helper తిరస్కరిస్తుంది:
$r = Invoke-RestMethod @p
if ($r -is [string]) {
$t = $r.TrimStart()
if ($t.StartsWith('{') -or $t.StartsWith('[')) { throw "Router reply to $Path could not be read as JSON by this PowerShell; stopping." }
}వైఫల్యం 3: మరీ త్వరగా టెస్ట్ చేసిన redirect
వెర్షన్ 2.3 ఇంకా ముందుకు వెళ్లింది. alias ని శుభ్రం చేసింది, రెండు rules జోడించి టెస్ట్ చేసింది. తర్వాత NAT redirect ని on చేసి, ఐదు సెకన్ల తర్వాత దాన్ని టెస్ట్ చేసింది:
14:57:16 Rules A and B verified: DoH and DoT refused, normal HTTPS works.
14:57:17 NAT rule enabled and applied. Verifying...
14:57:22 Problem: 8.8.8.8 still returns real ad addresses; the redirect is not taking effect.
14:57:22 Undoing changes made in this run...టెస్ట్ 8.8.8.8 కి రెండు queries పంపుతుంది: ఒకటి example.com కోసం, ఒకటి ఒక ad domain కోసం. firewall log లో రెండింటిలో ఒకటి redirect అయినట్లు కనిపించింది. ad domain నిజమైన అడ్రసులతో తిరిగి వచ్చింది, కాబట్టి redirect కానిది అదే. redirect ని on చేయడానికి పదమూడు సెకన్ల ముందు, bypass తెరిచి ఉందని చూపడానికి script ప్రారంభ చెక్ అదే పేరును 8.8.8.8 కి పంపింది.
నా దగ్గర రెండు వివరణలు ఉన్నాయి, రెండింటినీ నేను టెస్ట్ చేయలేదు. firewall తాను చూసిన ప్రతి connection కీ ఒక state entry ఉంచుకుంటుంది, redirect ని కొత్త connections కి మాత్రమే వర్తింపజేస్తుంది. ad domain కోసం రెండో query మొదటిదాని source port నుంచే నా PC ని వదిలి ఉంటే, అది పాత entry తో match అయి Google కి వెళ్లి ఉంటుంది. లేదా నా PC లో ఏదో ఒకటి మళ్లీ అడిగిన ప్రశ్నకు cache నుంచి జవాబిచ్చి ఉంటుంది; అప్పుడు query PC ని వదిలి వెళ్లనే లేదు.
ఈ router లోని UDP state timeouts, Firewall → Diagnostics → Statistics నుంచి చదివినవి: udp.first, udp.multiple కి 60 సెకన్లు, udp.single కి 30 సెకన్లు. వెర్షన్ 2.4 టెస్ట్ చేసే ముందు 70 సెకన్లు ఆగుతుంది, టెస్ట్ పాసైంది:
15:05:08 NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
15:06:18 NAT redirect verified: queries to 8.8.8.8 are answered by your router.ఈ ఆగే సమయం firewall state entries కంటే ఎక్కువ సేపు ఉంటుంది. PC లో గుర్తుంచుకున్న జవాబు కంటే కూడా ఎక్కువ సేపు ఉంటుందా అన్నది ఆ జవాబును ఎంత సేపు ఉంచుకుంటారనే దానిపై ఆధారపడుతుంది; అది నేను కొలవలేదు. కాబట్టి ఈ ఫలితం రెండు వివరణల మధ్య తేడాను చెప్పదు. ఇంతకు ముందు query చేయని పేరుతో, firewall state table తెరిచి పెట్టి చేసే టెస్ట్ తేడాను చెప్పగలదు.
వెర్షన్ 2.3 లోని undo redirect ని off చేసింది, రెండు కొత్త rules ని disable చేసింది, alias contents ని పునరుద్ధరించింది. rules ని delete చేయలేదు, alias refresh interval ని ఒక రోజుగానే వదిలేసింది. undo తర్వాత తీసిన backup రన్ ముందు తీసినదాని కంటే 4,788 bytes పెద్దది. వెర్షన్ 2.4 మొదట ఆ రెండు rules ని కనుగొంది:
15:04:56 Rule A: present, enabled=0, sort_order=400000.0000100
15:04:56 Rule B: present, enabled=0, sort_order=400000.0000200కాబట్టి “undone” అంటే “on లో ఏదీ మిగల్లేదు” అని, “router ముందున్నట్లే ఉంది” అని కాదు. వెర్షన్ 2.4 కొత్త copies జోడించకుండా, ఉన్న రెండు rules నే on చేసింది, ఎందుకంటే అది rules ని సృష్టించే ముందు description తో వెతుకుతుంది.
mock పట్టుకోనివి, రెండో రౌండ్ టెస్ట్లు
నేను router మీద నడపక ముందే Claude ప్రతి వెర్షన్నీ తన mock మీద నడిపింది. ఆ session record ప్రకారం, undo ని చెక్ చేయడానికి ప్రతి వెర్షన్ ఒకసారి మామూలుగా, ఒకసారి బలవంతంగా కలిగించిన failure తో నడిచింది. వెర్షన్లు 2.0 నుంచి 2.3 వరకు mock మీద పాసయ్యాయి. router మీద, ఆ నాలుగింటిలో మూడు ఫెయిల్ అయ్యాయి. mock ఎప్పుడూ Windows PowerShell 5.1 కింద నడవలేదు, దాని జవాబుల్లో router జవాబుల్లోని ఖాళీ keys లేవు.
ఈ పేజీ చివర ఉన్న script వెర్షన్ 2.5.1, 2.4 కాదు. publish చేసే ముందు Claude తో script ని మళ్లీ review చేయించాను. ఆ review కనుగొన్నవాటిని వెర్షన్ 2.5 సరిచేస్తుంది: router స్థితిని తప్పుగా వర్ణించగల messages, log లో రాయని stops, alias enabled flag ని పునరుద్ధరించని undo, redirect rule గానీ LAN allow-all rule గానీ లేని router మీద మొదలవగల runs. https:// తో మొదలుకాని router అడ్రసును కూడా అది తిరస్కరిస్తుంది, PC మీదే ఉన్న అడ్రసు తప్ప; test kit దాన్ని వాడుతుంది. నా router మీద నడిచింది వెర్షన్ 2.4. వెర్షన్ 2.5.1, వెర్షన్ 2.5 కి header comments లో మాత్రమే భిన్నంగా ఉంటుంది; అది mock మీద మాత్రమే నడిచింది.
రెండో రౌండ్ టెస్ట్లు ఒక కొత్త mock ని వాడాయి. router తప్పుగా ప్రవర్తించగల విధంగానే అది తప్పుగా ప్రవర్తించేలా తయారైంది, ఖాళీ key ఉన్న జవాబుతో సహా. ఒక harness 30 cases లో ప్రతిదానికీ ఒకసారి script copy ని దానిపై నడిపింది. PowerShell 7.4.6 కింద 30 అన్నీ పాసయ్యాయి.
నా PC లో Windows PowerShell 5.1 కింద మొదటి రన్లో రెండు cases ఫెయిల్ అయ్యాయి. script logs ప్రకారం script సరైన పనే చేసింది; harness చేయలేదు. ఒక PowerShell function ఒకే item ఉన్న list ని return చేస్తే, caller కి ఆ item నేరుగా వస్తుంది. PowerShell 7 ఆ item ని list లాగే count చేయడానికి, index చేయడానికి అనుమతిస్తుంది. ఈ రకమైన object కి Windows PowerShell 5.1 అనుమతించదు. harness PowerShell 7 కింద మాత్రమే నడిచింది. అది సరిచేశాక, publish చేసిన script వెర్షన్పై Windows PowerShell 5.1 కింద కూడా 30 cases అన్నీ పాసయ్యాయి.
harness నే చెక్ చేయడానికి, Claude script ని పది రకాలుగా పాడుచేసింది, ఉదాహరణకు undo ని, JSON చెక్ని లేదా HTTPS చెక్ని తీసేయడం. ప్రతి పాడుచేత కనీసం ఒక case ని ఫెయిల్ చేసింది. ఆ చెక్ PowerShell 7.4.6 కింద, వెర్షన్ 2.5 మీద, harness యొక్క ఒక పాత వెర్షన్తో నడిచింది.
తర్వాతి script కి నేను తీసుకెళ్లేవి
- script ని నడపబోయే PowerShell మీదే టెస్ట్ చేయండి, టెస్ట్లను కూడా అక్కడే నడపండి. నా harness PowerShell 7 కింద పాసైంది, 5.1 కింద మొదటి రన్లో ఫెయిల్ అయింది.
- mock జవాబులను నిజమైన జవాబుల నుంచి కట్టండి. router
get_itemనుంచి save చేసిన ఒక జవాబు ఉండి ఉంటే, router script ని చూడక ముందే వైఫల్యం 2 పట్టుబడేది. - write mode చేసే ప్రతి read నీ read-only mode కూడా చేసేలా చూడండి. ఇక్కడ
Check,Applyalias ని వేర్వేరు endpoints ద్వారా చదివాయి. - object ఆశించినప్పుడు
Invoke-RestMethodనుంచి string వస్తే దాన్ని failure గా చూడండి. అది ప్రతిసారీ error ఇవ్వదు. - redirect ని on చేశాక, firewall state timeout కంటే ఎక్కువ సేపు ఆగండి. ఇంతకు ముందు query చేయని పేరుతో టెస్ట్ చేయండి.
- undo delete చేయకుండా disable చేస్తే, గత రన్ వదిలినవాటి కోసం తర్వాతి రన్ వెతికేలా చేయండి.
- టెస్ట్లు ఫెయిల్ కాగలవని చెక్ చేయడానికి script ని కావాలని పాడుచేయండి.
- API key ని script బయట ఉంచండి, పని అయ్యాక దాన్ని delete చేయండి. నేను
rootuser key వాడాను. script కి కావాల్సిన privileges మాత్రమే ఉన్న user మంచిది; అది నేను ప్రయత్నించలేదు.
మీ router మీద దశల వారీగా నడపండి
మొదలుపెట్టే ముందు. మీకు ఇవి కావాలి:
- router ఉన్న network లోనే ఉన్న ఒక Windows PC. మీరు రెండు చోట్ల type చేస్తారు: PC లో PowerShell, browser లో router web page;
- OPNsense 26.7. ఇతర series లో script ఆగిపోతుంది, ఎందుకంటే దాని API paths ఆ series సొంత pages నుంచి తీసుకున్నవి;
- DNS blocklist on లో, Services → Unbound DNS → Blocklist కింద (OPNsense documentation ఆ page పేరు చెబుతుంది), మీ devices DNS కోసం router నే అడుగుతూ ఉండాలి;
- port 53 మీద router కాకుండా ఇంకెక్కడికైనా వెళ్లే DNS queries ని తిరిగి router కే పంపే Destination NAT rule, ముందే సృష్టించినది, “Redirect non-local DNS to Local” అనే description తో. script దాన్ని on చేస్తుంది. సృష్టించదు. ఈ rule ని script సృష్టించదు, ఒకటి సృష్టించడం ఈ panel లో లేదు, అది లేకపోతే Apply ఆగిపోతుంది. OPNsense forum లోని ఒక community how-to ఒక పద్ధతి చూపిస్తుంది;
- “Default allow LAN to any rule” అనే LAN rule, OPNsense దాన్ని default గా సృష్టిస్తుంది. దాని పైన తన రెండు కొత్త rules ఉన్నాయో లేదో script చెక్ చేస్తుంది.
వెర్షన్ 2.5.1, ఈ panel లోని script, test kit లోని mock router మీద మాత్రమే నడిచింది. నా router మీద నడిచింది వెర్షన్ 2.4.
సుమారు 20 నిమిషాలు కేటాయించండి; మార్పుకే సుమారు రెండు నిమిషాలు పడుతుంది. router కి చేసే మొదటి మార్పు 3వ దశలోని API key. 5వ దశలోని Check రన్ దానిపై ఏదీ మార్చదు. 6వ దశలోని Apply మారుస్తుంది. 8వ దశ fix ని off చేయడాన్ని, మొత్తం configuration ను ఎలా restore చేయాలో చూపిస్తుంది. ప్రతి రన్, configuration ను చదివే ముందు router configuration backup ను PC లో save చేస్తుంది.
ఇప్పుడు పరిమితులు చదవండి. వాటిలో ఒకటి మీ network ని వర్ణిస్తే, script మీకు సరిపోదు, కాబట్టి ముందుకు వెళ్లకండి.
పరిమితులు
- IPv4 మాత్రమే. Rules A, B ను script IPv4 కోసమే సృష్టిస్తుంది, ప్రతి టెస్ట్ IPv4 అడ్రసు వాడుతుంది. మీ LAN లో IPv6 ఉంటే, IPv6 మీద DoH, DoT block కావు, టెస్ట్ కూడా కావు. (Interfaces → LAN లో IPv6 Configuration Type కనిపిస్తుంది; None అంటే IPv6 లేదు.)
- LAN interface మాత్రమే. ఇతర interfaces, VLANs cover కావు.
- LAN లో ప్రతి host. upstream కోసం DoH లేదా DoT వాడే LAN లోని Pi-hole లేదా AdGuard Home తన upstream ని కోల్పోతుంది. అది plain DNS ని ఒక public server కి పంపితే, మీ redirect rule ఎలా కట్టబడిందో దాన్ని బట్టి, ఆ rule దాన్ని కూడా పట్టుకోవచ్చు.
- encrypted DNS నే కోరే devices. encrypted DNS provider ని మాత్రమే వాడేలా set చేసిన device, ఉదాహరణకు Private DNS ని ఒక hostname కి set చేసిన phone, rules దాని దారిని తిరస్కరించాక ఈ network లో పేర్లను వెతకలేకపోవచ్చు. ఆ setting ని device మీద మార్చండి.
- redirect rule ముందే ఉండాలి Firewall → NAT → Destination NAT లో, “Redirect non-local DNS to Local” description తో, లేదా మీరు
$NatDescలో పెట్టిన దానితో. script దాన్ని సృష్టించదు, అది ఎలా కట్టబడిందో చెక్ చేయదు. - alias overwrite అవుతుంది Hagezi URL తో. పాత contents ను script log లో రాస్తుంది.
- టెస్ట్ domain
$AdTestDomainలోది. మీ router blocklist దాన్ని block చేసి, 0.0.0.0 గా లేదా అడ్రసు లేకుండా జవాబివ్వాలి; లేకపోతే redirect టెస్ట్ ఫెయిల్ అవుతుంది. - మీరు నమ్మే LAN. script certificate చెక్ router అడ్రసు కోసం చూపిన ఏ certificate నైనా అంగీకరిస్తుంది, కాబట్టి LAN లో router లా నటించే device కి key అందుతుంది. మీరు నియంత్రించే network లోనే నడపండి.
- ఆగే సమయం
$NatWaitSecondsలోది. ఇది మీ router UDP state timeouts కంటే ఎక్కువ ఉండాలి. - Rollback రెండు rules నీ redirect rule నీ off చేస్తుంది, మీరు మొదటిసారి
Applyనడపక ముందే redirect on లో ఉన్నా. alias ని పునరుద్ధరించదు.
PowerShell తెరిచి ఒక folder సృష్టించండి. Start menu తెరిచి,
powershellఅని type చేసి Enter నొక్కండి. Windows PowerShell అనే title తో ఒక window తెరుచుకుంటుంది, దాని promptPSతో మొదలవుతుంది. prompt లోPSలేకపోతే మీరు Command Prompt లో ఉన్నారు: దాన్ని మూసి బదులుగా PowerShell తెరవండి, ఎందుకంటే కింది commands PowerShell లో మాత్రమే పనిచేస్తాయి. window లోపల click చేయండి. కింది రెండు లైన్లను ఒక్కొక్కటిగా వాడండి: లైన్ను copy చేయడానికి PS> మీద click చేయండి, paste చేయండి (Ctrl + V, లేదా right-click), Enter నొక్కండి.New-Item -ItemType Directory -Path "$env:USERPROFILE\opnsense-dns" Set-Location "$env:USERPROFILE\opnsense-dns"మొదటి లైన్ మీ user folder లోపల
opnsense-dnsఅనే folder ను సృష్టించి, చిన్న listing ను print చేస్తుంది; రెండోది PowerShell ని అందులోకి తీసుకెళ్తుంది, తర్వాత promptopnsense-dns>తో ముగుస్తుంది. ఒక్కొక్కటి ఒక సెకను కంటే తక్కువ పడుతుంది. మొదటి లైన్ folder ఉందని చెబితే, ముందుకు వెళ్లండి. ఈ window ని తెరిచి ఉంచండి, ఈ folder ని OneDrive, Dropbox, shared locations బయట ఉంచండి: ఇక్కడ save అయ్యే backups లో router మొత్తం configuration ఉంటుంది.script ని save చేయండి. ఈ page చివర ఉన్న The script, the mock router and the test harness దగ్గరికి scroll చేసి, opnsense-dns-bypass.ps1 (version 2.5.1) ను తెరిచి, చదివి, Copy మీద click చేయండి. అది 491 లైన్లు. ఇది మీ router key ని వాడుతుంది, కాబట్టి నడపక ముందు చదవండి. browser download చేసిన files ని Windows internet నుంచి వచ్చినవిగా గుర్తు పెడుతుంది; కింది command రాసిన file కి ఆ గుర్తు ఉండదు, కాబట్టి
Unblock-Fileఅవసరం లేదు. ఈ command ఈ folder లో అదే పేరున్న file ను భర్తీ చేస్తుంది. PowerShell window లో:Get-Clipboard -Raw | Set-Content -Encoding Ascii .\opnsense-dns-bypass.ps1Get-Clipboardమీరు copy చేసినదాన్ని చదువుతుంది,Set-Contentదాన్ని ఒక file లో రాస్తుంది; script plain ASCII, కాబట్టి ఆ encoding సురక్షితం. ఇది ఒక సెకను కంటే తక్కువ పడుతుంది, ఏదీ print చేయదు. అంతా వచ్చిందో చెక్ చేయండి:(Get-Content .\opnsense-dns-bypass.ps1).Count491వేరే సంఖ్య వస్తే, copy మధ్యలోనే ఆగిపోయిందని లేదా మారిందని అనిపిస్తుంది. page కి తిరిగి వెళ్లి, Copy మీద మళ్లీ click చేసి, మొదటి command ను మళ్లీ నడపండి.
router మీద API key సృష్టించండి. web browser లో
https://అని, మీరు router settings page కోసం వాడే అడ్రసును (ఉదాహరణకుhttps://192.168.1.1) type చేసి Enter నొక్కండి. router తన certificate ని తానే sign చేస్తుంది కాబట్టి, connection private కాదని browser హెచ్చరించవచ్చు. ఆ అడ్రసుకు కొనసాగించే ఎంపికను ఎంచుకోండి (Chrome లో: Advanced, తర్వాత Proceed). మీ సొంత router login తో log in అవండి. తర్వాత:- ఎడమవైపు menu లో System మీద, తర్వాత Access మీద, తర్వాత Users మీద click చేయండి.
- మీరు log in అయ్యే administrator వరుస చివర ఉన్న పెన్సిల్ (edit) icon మీద click చేయండి.
- user settings లో API keys section ను కనుక్కోండి (OPNsense documentation దాన్ని ApiKeys tab అంటుంది), దాని grid లో key ను సృష్టించే button ను వాడండి.
- కొన్ని సెకన్లలో browser ఒక చిన్న text file ను download చేస్తుంది. అందులో
key=లైన్,secret=లైన్ ఉంటాయి. secret ఒక్కసారి మాత్రమే generate అవుతుందని documentation చెబుతుంది; file పోతే కొత్త key సృష్టించండి.
key తన user లాగే పనిచేస్తుంది. నేను root user key వాడి, తర్వాత దాన్ని delete చేశాను; root key router మీద పూర్తి నియంత్రణ ఇస్తుంది. firewall, NAT, backup pages కి మాత్రమే పరిమితమైన user కి తక్కువ అధికారం ఉంటుంది, కానీ script router మొత్తం configuration ను download చేస్తుంది, కాబట్టి ఆ user కూడా అందులోని password hashes, private keys ను చదవగలడు. పరిమిత user ను నేను ప్రయత్నించలేదు. మీ menu వేరేగా కనిపిస్తే, local users మీద OPNsense documentation అదే దశను వివరిస్తుంది. key file ను ఎక్కడా paste చేయకండి: అందులోని secret router మీద నియంత్రణ ఇస్తుంది.
key file ను folder లో పెట్టండి. PowerShell కి తిరిగి వచ్చి, మీ Downloads folder లోని కొత్త text files జాబితా చూడండి:
Get-ChildItem "$env:USERPROFILE\Downloads" -Filter *.txt | Sort-Object LastWriteTime -Descending | Select-Object -First 3 Name, LastWriteTimeName LastWriteTime ---- ------------- example_apikey.txt <date and time>జాబితా ఖాళీగా ఉంటే, browser ఆ file ను వేరే చోట save చేసింది: ఎక్కడ save అయిందో చూడటానికి browser లో Ctrl + J నొక్కండి. ఇప్పుడు ఆ file ను script ఆశించే పేరుతో folder లోకి తరలించండి.
<file-name>ను, angle brackets తో సహా, జాబితాలోని పేరుతో మార్చండి:Move-Item -LiteralPath "$env:USERPROFILE\Downloads\<file-name>" -Destination .\apikey.txtఇది ఒక సెకను కంటే తక్కువ పడుతుంది, ఏదీ print చేయదు. folder లో ముందే ఉన్న
apikey.txtను ఇది overwrite చేయదు; ఆ కారణంతో నిరాకరిస్తే, ఇంతకు ముందటి key file అక్కడ ఉంది. ఆ key ను router మీద తీసేసి (ఆ key ఎక్కడ ఉందో 8వ దశ చూపిస్తుంది),Remove-Item .\apikey.txtనడిపి, ఈ దశను మళ్లీ చేయండి. path గురించి error వస్తే, path లో ఇంకా<file-name>ఉండి ఉండవచ్చు, లేదా పేరు జాబితాలోని పేరుతో సరిపోకపోవచ్చు. ఇప్పుడు key file లో రెండు లైన్లు ఉన్నాయో చెక్ చేయండి. ఇది ప్రతి=కి ముందున్న పదాన్ని మాత్రమే print చేస్తుంది, విలువలను ఎప్పుడూ కాదు:Get-Content .\apikey.txt | ForEach-Object { ($_ -split '=')[0] }key secretవేరే పదాలు కనిపిస్తే, ఇది బహుశా key file కాదు. కొత్త key ను download చేయండి (3వ దశ).
Check నడపండి. ఇది చదువుతుంది మాత్రమే. ముందు PowerShell కి మీ router అడ్రసు చెప్పండి. లైన్ను copy చేయడానికి PS> మీద click చేసి, paste చేయండి, ఇంకా Enter నొక్కకండి.
<router-ip-address>ను, angle brackets తో సహా, 3వ దశలోని అడ్రసు సంఖ్యలతో మార్చండి (ఉదాహరణకు192.168.1.1),https://ను అలాగే ఉంచండి. cursor ను arrow keys తో కదిలించండి, ఎందుకంటే PowerShell లో mouse click cursor ను కదిలించదు; Backspace తీసేస్తుంది. తర్వాత Enter నొక్కండి. angle brackets ఇంకా ఉంటే script ఆగిపోతుంది.$RouterUrl = 'https://<router-ip-address>'ఇది అడ్రసును ఈ window కి మాత్రమే గుర్తుంచుకుంటుంది. window ను మూసేస్తే, దీన్ని మళ్లీ చేయండి.
ఇప్పుడు script ను నడపండి.
powershell -ExecutionPolicy Bypass -Fileఆ file ను నడిపే కొత్త Windows PowerShell 5.1 ను మొదలుపెడుతుంది. command line మీది-ExecutionPolicy Bypassఆ ఒక్క రన్ కి మాత్రమే ఉంటుంది, execution policies మీద Microsoft documentation అది store కాదని చెబుతుంది. మీ సంస్థ set చేసిన Group Policy ని అది override చేయదు.-Modeలేకుండా scriptCheckనడుపుతుంది.powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrlఇది 10 నుంచి 60 సెకన్లు పడుతుంది, router మీద ఏదీ మార్చదు. router configuration backup ను
router-backupsfolder లో (అదిopnsense-dnsలోపల ఉంటుంది), log నుlogsలో save చేసి, ఐదు live టెస్ట్లు నడుపుతుంది. ముఖ్యమైన లైన్లు:HH:MM:SS Router reports: OPNsense series 26.7, amd64 HH:MM:SS Backup (before) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Check-before-<timestamp>.xml (NNN,NNN bytes) ... HH:MM:SS Router resolves example.com : True (want True) HH:MM:SS Router blocks the ad domain (blocklist) : True (want True) HH:MM:SS Bypass DoH 1.1.1.1:443 reachable : True (want False after Apply) HH:MM:SS Bypass DoT 9.9.9.9:853 reachable : True (want False after Apply) HH:MM:SS Bypass 8.8.8.8 gives real ad IPs : True (want False after Apply) HH:MM:SS Check mode: nothing was changed on the router. HH:MM:SS Log file: C:\Users\<you>\opnsense-dns\logs\run-Check-<timestamp>.logరెండు “want True” లైన్లూ True అయి ఉండాలి. “Router blocks the ad domain” False అయితే, మీ blocklist టెస్ట్ domain ను block చేయడం లేదు, 6వ దశలోని redirect టెస్ట్ ఫెయిల్ అవుతుంది. script పైభాగంలోని
$AdTestDomainను మీ blocklist block చేసే domain కి set చేయండి, లేదా blocklist ను on చేయండి. పసుపు లైన్Apply would stop:తో మొదలైతే, అది లేని rule ను చెబుతుంది: redirect rule లేదా LAN allow-all rule. 6వ దశకు ముందు router మీద దాన్ని సరిచేయండి.ఏదైనా తప్పు జరిగితే. script ఎరుపు లైన్ print చేస్తుంది (చాలావాటిలో STOP అనే పదం ఉంటుంది), router మీద ఏదీ మార్చదు. లైన్ ఏం చెబుతుంది, దాని అర్థం ఏమిటి:
- Set -Router to your router’s address: ఈ దశలోని అడ్రసులో angle brackets ఇంకా ఉన్నాయి.
- Missing an argument for parameter ‘Router’: బహుశా పై అడ్రసు లైన్ను ఈ window లో నడపలేదు. దాన్ని మళ్లీ నడపండి.
- -Router must start with https://: అడ్రసు
http://తో మొదలవుతోంది.https://వాడండి. - STOP: Key file not found:
apikey.txtopnsense-dnsfolder లో లేదు. 4వ దశను మళ్లీ చేయండి. - STOP: Cannot reach the router API with this key: అడ్రసు తప్పు, key ను తీసేశారు, లేదా PC router network లో లేదు. చెక్ చేయడానికి browser లో అడ్రసును తెరవండి.
- STOP: Script was built for OPNsense 26.7: మీ router వేరే series నడుపుతోంది, script API paths 26.7 నుంచి తీసుకున్నవి. ఇక్కడే ఆగండి.
- scripts నడపడం disabled అని PowerShell చెబుతుంది: మీ PC లోని policy scripts ను block చేస్తోంది, command-line option దాన్ని override చేయలేదు. ఇక్కడే ఆగండి.
Apply నడపండి. ఇది router ను మారుస్తుంది. ఇది
DoH_IPsalias ను Hagezi list అడ్రసుతో overwrite చేస్తుంది (పాత contents log కి వెళ్తాయి), రెండు reject rules లేకపోతే జోడిస్తుంది, redirect rule ను on చేస్తుంది. DNS-over-HTTPS లేదా DNS-over-TLS server తో నేరుగా మాట్లాడే మీ network లోని devices ఆ దారిని కోల్పోతాయి; అదే ఉద్దేశం. అదే command ను-Mode Applyజోడించి నడపండి:powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Applyఇది సుమారు రెండు నిమిషాలు పడుతుంది, alias ముందుగా తన list ను download చేయాల్సి వస్తే నాలుగు నిమిషాల వరకు. ఒక లైన్
Waiting 70 s for older DNS states to expire before testing...అని ఉంటుంది; దాని కోసం ఆగండి, window ను మూసేయకండి. చివరి లైన్లు ఇలా ఉండాలి:HH:MM:SS Bypass DoH 1.1.1.1:443 reachable : False (want False after Apply) HH:MM:SS Bypass DoT 9.9.9.9:853 reachable : False (want False after Apply) HH:MM:SS Bypass 8.8.8.8 gives real ad IPs : False (want False after Apply) HH:MM:SS Backup (after) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Apply-after-<timestamp>.xml (NNN,NNN bytes) HH:MM:SS Apply finished. Expected: router tests True, all three bypass tests False. HH:MM:SS Log file: C:\Users\<you>\opnsense-dns\logs\run-Apply-<timestamp>.logఏదైనా తప్పు జరిగితే. Apply did not complete; changes from this run were undone: ఒక టెస్ట్ ఫెయిల్ అయింది, script తాను మార్చినదాన్ని off చేసింది. అది జోడించిన rules off స్థితిలో అలాగే ఉంటాయి. ఫలితం యొక్క backup ను save చేసింది. కారణం కోసం Problem: తో మొదలయ్యే లైన్ చదవండి. ఏ లైన్ అయినా UNDO STEP FAILED అంటే, 8వ దశ వివరించినట్లు “before” backup ను restore చేయండి. Apply PARTLY finished (పసుపు రంగులో): alias, రెండు rules అమల్లో ఉన్నాయి, టెస్ట్ అయ్యాయి, redirect పాసవ్వలేదు; redirect ను on లో వదిలిందో off లో వదిలిందో లైన్ చెబుతుంది. fix ను off చేయడానికి 8వ దశ వాడండి.
అది పనిచేసిందో చెక్ చేయండి. 5వ దశలోని Check command ను మళ్లీ నడపండి:
powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrlఇప్పుడు మూడు
Bypassలైన్లుFalse, రెండుRouterలైన్లుTrueఅని చూపిస్తాయి. router web page లో Firewall → Rules (interface selector లో LAN ఎంచుకోండి) చూడవచ్చు; అక్కడ Reject DoH to known resolvers (A), Reject DoT/DoQ 853 from LAN (B) అనే రెండు rules ఇప్పుడు కనిపిస్తాయి. Firewall → NAT → Destination NAT లో Redirect non-local DNS to Local enabled గా ఉంటుంది.దాన్ని off చేయండి, అవసరమైతే restore చేయండి, key ను తీసేయండి. fix ను off చేయడానికి command ను
-Mode Rollbackతో నడపండి:powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Rollbackఇది ఒక నిమిషం కంటే తక్కువ పడుతుంది. రెండు rules నీ redirect నీ disable చేస్తుంది, దేన్నీ delete చేయదు. alias Apply వదిలినట్లే ఉంటుంది. మీరు మొదలుపెట్టే ముందే redirect on లో ఉంటే, ఇప్పుడు అది off: Firewall → NAT → Destination NAT లో దాన్ని మళ్లీ on చేయండి.
మొత్తం configuration ను Apply కి ముందున్నట్లు తిరిగి పెట్టడానికి, router మీద backup ను restore చేయండి: System → Configuration → Backups కి వెళ్లి,
config-Apply-before-<timestamp>.xmlఅనే file నుrouter-backupsfolder నుంచి ఎంచుకుని restore చేయండి. ప్రతి Apply రన్ ఇలాంటి ఒక file ను save చేస్తుంది; అన్నిటికంటే పాతది మీ మొదటి Apply కి ముందున్న configuration ను కలిగి ఉంటుంది. అది అప్పటి నుంచి router మీద చేసిన ఇతర మార్పులనూ undo చేస్తుంది.script తో పని అయ్యాక, fix ను ఉంచుకున్నా లేకపోయినా, key ను తీసేయండి. router మీద System → Access → Users కి వెళ్లి, అదే user మీద పెన్సిల్ click చేసి, API keys section లో key ను తీసేయండి (ApiKeys tab). తర్వాత key file ను PC నుంచి delete చేయండి:
Remove-Item .\apikey.txtఇది file ను వెంటనే delete చేస్తుంది, recycle bin ఉండదు. backups అవసరం లేనప్పుడు
router-backupsfolder ను కూడా delete చేయండి: అందులో password hashes, private keys ఉన్నాయి.
భద్రతా గమనికలు. script ప్రతి request తో key ను పంపుతుంది. secret ను print చేయదు, log చేయదు, test kit తన 30 cases లో ప్రతిదానిలో అది చెక్ చేస్తుంది. దాని certificate చెక్ router అడ్రసు కోసం చూపిన ఏ certificate నైనా అంగీకరిస్తుంది, కాబట్టి LAN లో router లా నటించే device కి key అందుతుంది. నా key ను 13 అక్టోబర్ 2026 న, రన్ తర్వాత రెండు రోజులకు delete చేశాను, router configuration history ఆ deletion ను record చేస్తుంది.
backups అంటే router మొత్తం configuration: password hashes, దాని certificates, VPN tunnels private keys. ఆ folder ను private గా ఉంచండి, forum post కి backup ను attach చేయకండి.
లోతుగా: script చేసే ఇతర చెక్లు
- backup, backup లాగే కనిపించాలి. download చేశాక, file కనీసం 50,000 bytes ఉందో, మొదటి మూడు లైన్లలో
<opnsense>ఉందో script చెక్ చేస్తుంది. - ఫెయిల్ అయిన save పట్టుబడుతుంది.
validationsఉన్న జవాబు ఫెయిల్ అయిన save గా లెక్క, router సొంత web pages లో లాగే;resultవిలువfailedఅయినా అంతే. alias, redirect మార్పులను తిరిగి చదువుతుంది. rule మార్పులను rules ఉనికి, క్రమం ద్వారా, live connection టెస్ట్ల ద్వారా చెక్ చేస్తుంది. - Rule క్రమం. Rules A, B జోడించాక, వాటిలో ఏదైనా “Default allow LAN to any rule” తర్వాత sort అయితే script ఆగుతుంది. ఎందుకంటే allow-all rule కింద ఉన్న rule ఎప్పుడూ match కాదు.
- alias నిండాలి. ప్రతి 5 సెకన్లకు, 90 సెకన్ల వరకు alias ని poll చేస్తుంది. కనీసం 500 అడ్రసులు లేకపోతే ఆగుతుంది.
- మామూలు browsing పనిచేస్తూనే ఉండాలి. rules బాగున్నాయని ప్రకటించే ముందు,
www.google.com:443కి ఒక connection తెరుస్తుంది. - పాక్షిక ఫలితం ఆ మాటే చెబుతుంది. redirect దశ ఒక్కటే ఫెయిల్ అయితే, రన్
Apply PARTLY finishedతో ముగుస్తుంది, redirect ని ఏ స్థితిలో వదిలిందో చెబుతుంది, code 2 తో exit అవుతుంది.
లోతుగా: router అడ్రసుకు మాత్రమే చెడ్డ certificate ని అంగీకరించడం
router web interface ఒక self-signed certificate వాడుతుంది. PowerShell 7 లో -SkipCertificateCheck ఉంది; అక్కడ script దాన్ని వాడుతుంది. Windows PowerShell 5.1 లో అలాంటి switch లేదు. సాధారణంగా వాడే workaround, మొత్తం session కి ప్రతి certificate నీ అంగీకరించే callback. script callback, request host router అడ్రసు అయినప్పుడు మాత్రమే ఫెయిల్ అయిన certificate చెక్ని అంగీకరిస్తుంది:
public static bool Check(object sender, X509Certificate c, X509Chain ch, SslPolicyErrors e) {
if (e == SslPolicyErrors.None) return true;
HttpWebRequest r = sender as HttpWebRequest;
return r != null && r.RequestUri.Host == Host;
}ఇది మినహాయింపును పరిమితం చేస్తుంది. certificate ని pin చేయదు: ఆ అడ్రసు కోసం చూపిన ఏ certificate అయినా పాసవుతుంది. certificate thumbprint ని చెక్ చేస్తే ఆ లోపం మూసుకుంటుంది. 5.1 కోసం script TLS 1.2 ని కూడా set చేస్తుంది.
లోతుగా: వైఫల్యం కాదు, ముందు జాగ్రత్త: Expect: 100-continue
Check mode GET requests మాత్రమే పంపుతుంది. Apply POSTs పంపుతుంది. Windows PowerShell 5.1 .NET Framework మీద నడుస్తుంది. అక్కడ ServicePointManager.Expect100Continue default గా true. body ఉన్న POST requests కి అది Expect: 100-continue header జోడిస్తుంది (Microsoft documentation). వెర్షన్ 2.2 మొదటి request కంటే ముందే ఆ header ని off చేస్తుంది:
[Net.ServicePointManager]::Expect100Continue = $falserouter web server ఆ header కి అభ్యంతరం చెప్పి ఉండేదా అని నేను టెస్ట్ చేయలేదు.
లోతుగా: పూర్తైన రన్, లైన్ వారీగా
15:04 రన్ log. router అడ్రసు, దాని interfaces లో ఒకదాని పేరు స్థానంలో angle brackets లో placeholders పెట్టాను; local folder, PowerShell build number తీసేశాను, byte counts లోని అంకెలను మూడేసి చొప్పున group చేశాను. ప్రారంభ టెస్ట్లు blocklist ని దాటే మూడు దారులూ తెరిచి ఉన్నాయని చూపుతాయి. ముగింపు టెస్ట్లు, టెస్ట్ చేసిన మూడు IPv4 అడ్రసుల వరకు, అవి మూసుకున్నాయని చూపుతాయి.
15:04:49 Mode: Apply Router: https://<router-ip-address> PowerShell 5.1
15:04:55 Router reports: OPNsense series 26.7, amd64
15:04:55 Backup (before) saved: ...\config-Apply-before-20261011-150449.xml (404,269 bytes)
15:04:56 Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[__<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
15:04:56 Rule A: present, enabled=0, sort_order=400000.0000100
15:04:56 Rule B: present, enabled=0, sort_order=400000.0000200
15:04:56 'Default allow LAN to any rule': sort_order=400000.1000023
15:04:56 NAT 'Redirect non-local DNS to Local': disabled=1
15:04:56 Router resolves example.com : True (want True)
15:04:56 Router blocks the ad domain (blocklist) : True (want True)
15:04:56 Bypass DoH 1.1.1.1:443 reachable : True (want False after Apply)
15:04:56 Bypass DoT 9.9.9.9:853 reachable : True (want False after Apply)
15:04:56 Bypass 8.8.8.8 gives real ad IPs : True (want False after Apply)
15:04:56 Alias DoH_IPs set to the URL only (was: __<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt).
15:04:58 Alias DoH_IPs holds 1434 addresses.
15:04:58 Rule 'Reject DoH to known resolvers (A)' enabled.
15:04:58 Rule 'Reject DoT/DoQ 853 from LAN (B)' enabled.
15:04:58 Firewall rules applied. Verifying...
15:05:08 Rules A and B verified: DoH and DoT refused, normal HTTPS works.
15:05:08 NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
15:06:18 NAT redirect verified: queries to 8.8.8.8 are answered by your router.
15:06:19 Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
15:06:19 Rule A: present, enabled=1, sort_order=400000.0000100
15:06:19 Rule B: present, enabled=1, sort_order=400000.0000200
15:06:19 'Default allow LAN to any rule': sort_order=400000.1000023
15:06:19 NAT 'Redirect non-local DNS to Local': disabled=0
15:06:23 Router resolves example.com : True (want True)
15:06:23 Router blocks the ad domain (blocklist) : True (want True)
15:06:23 Bypass DoH 1.1.1.1:443 reachable : False (want False after Apply)
15:06:23 Bypass DoT 9.9.9.9:853 reachable : False (want False after Apply)
15:06:23 Bypass 8.8.8.8 gives real ad IPs : False (want False after Apply)
15:06:23 Backup (after) saved: ...\config-Apply-after-20261011-150449.xml (404,254 bytes)
15:06:23 Apply finished. Expected: router tests True, all three bypass tests False.alias లో నేను కావాలని పెట్టని ఒక entry ఉంది: URL కంటే ముందు, router interfaces లో ఒకదాని network. రన్ పాత contents ని మార్చే ముందు print చేసింది, కాబట్టి వాటిని log నుంచి పునరుద్ధరించవచ్చు.
లోతుగా: test kit ఏం చెక్ చేస్తుంది, ఏం చెక్ చేయలేదు
mock script API paths కి జవాబిస్తుంది, router స్థితిని memory లో ఉంచుకుంటుంది, తనకు వచ్చిన ప్రతి call నీ record చేస్తుంది. దాన్ని తప్పుగా ప్రవర్తించేలా set చేయవచ్చు: తప్పు వెర్షన్, చెడ్డ API key, చిన్న backup, మార్పుల తర్వాత ఫెయిల్ అయ్యే backup, తప్పు type ఉన్న alias, ఖాళీ key ఉన్న జవాబు, router తిరస్కరించే save, నిండని alias, allow-all rule కింద sort అయ్యే rules, ఇంకా చేరగలిగే DoH, పాడైన మామూలు HTTPS, లేని redirect rule లేదా allow rule, ప్రభావం చూపని redirect, ముందే on లో ఉన్న redirect. నా router గడిచిన స్థితులను కూడా ఇది అనుకరిస్తుంది: అదనపు entry ఉన్న alias, వెర్షన్ 2.3 disable చేసి వదిలిన రెండు rules, అన్నీ ముందే apply అయిన స్థితి. ఖాళీ key ఉన్న దాని జవాబు router get_item జవాబు ఆధారంగా చేతితో రాసినది. script చదివే endpoint మీదే అది serve అవుతుంది.
harness ప్రతి case కీ script ని ఒకసారి, వేరే process గా నడుపుతుంది. exit code, log, backup files, mock కి వచ్చిన ప్రతి call, చివర్లో mock router స్థితి చెక్ చేస్తుంది. ప్రతి case లో ఇవి చెక్ చేస్తుంది: secret గానీ encoded key గానీ output లో, log లో కనిపించలేదని; ఏదీ delete కాలేదని; log తెరిచిన తర్వాత జరిగే stop log లో రాయబడిందని.
harness script నే కాదు, దాని copy ని టెస్ట్ చేస్తుంది. copy లో, రెండు network టెస్ట్లు internet ని కాకుండా mock ని అడుగుతాయి. ప్రతి ఆగే సమయాన్ని ఒక millisecond కి తగ్గిస్తారు. ఏ case నడవక ముందే, ఆ patterns లో ప్రతిదీ ఆశించిన సంఖ్యలో match అయిందని harness చెక్ చేస్తుంది. copy PC మీద plain HTTP ద్వారా mock తో మాట్లాడుతుంది; script plain HTTP ని PC మీదే ఉన్న అడ్రసుకు మాత్రమే అంగీకరిస్తుంది.
కాబట్టి kit టెస్ట్ చేయనివి: certificate చెక్, TLS; నిజమైన network టెస్ట్లు; వైఫల్యం 3, ఎందుకంటే mock కి state table లేదు, ఆగే సమయాలు తగ్గించబడ్డాయి; నిజమైన router నుంచి జవాబులు, చేతితో రాసిన ఒక ఖాళీ-key జవాబు తప్ప; backup ని overwrite చేయడానికి script నిరాకరించడం; work folder fallback, ఎందుకంటే ప్రతి case ఒక folder పేరు ఇస్తుంది; లేదా తానే ఫెయిల్ అయ్యే undo దశ.
కావాలని చేసిన పది పాడుచేతలు, ఒక్కొక్కటి ఫెయిల్ చేసిన cases, పేజీ చివర kit తో పాటు జాబితాగా ఉన్నాయి.
లోతుగా: OPNsense 26.7 API గమనికలు
- script header ప్రకారం, ప్రతి configuration path ఆ రోజు router సొంత web pages నుంచి తీసుకున్నది:
alias/search_item,alias/add_item,alias/set_item,alias/reconfigure,filter/search_rule,filter/add_rule,filter/set_rule,filter/apply,d_nat/search_rule,d_nat/set_rule,d_nat/apply,alias_util/list,core/backup/download/this. వెర్షన్ కోసంcore/firmware/infoని, reachability చెక్ గాcore/firmware/statusని కూడా call చేస్తుంది. - search endpoints
?rowCount=-1¤t=1తో GET కి జవాబిస్తాయి. ప్రతి row నీ, script కి కావాల్సిన fields తో తిరిగి ఇస్తాయి. alias/get_itemఖాళీ పేరున్న keys తో option lists ఇస్తుంది. వాటిని PowerShell object properties గా మార్చలేదు.GET /api/core/backup/download/thisపూర్తి configuration ని XML గా ఇస్తుంది.- POST bodies
Content-Type: application/jsonతో JSON. Rule మార్పులు సరిపోయేapplyతర్వాత అమల్లోకి వస్తాయి; alias మార్పులుreconfigureతర్వాత.
పదకోశం
- Windows PowerShell 5.1: Windows తో పాటు వచ్చే PowerShell, .NET Framework మీద కట్టినది.
powershellగా మొదలవుతుంది. - PowerShell 7: కొత్త PowerShell, విడిగా install చేసేది, modern .NET మీద కట్టినది.
pwshగా మొదలవుతుంది. - REST API: settings చదవడానికి లేదా మార్చడానికి ఒక program call చేసే web అడ్రసుల సమితి; OPNsense జవాబులు JSON.
- JSON: structured data కోసం ఒక text format.
- Mock: టెస్టింగ్ కోసం నిజమైన system స్థానంలో వాడేది; ఇక్కడ, router లా జవాబిచ్చే ఒక చిన్న web server.
- Test harness: మరొక script ని నిర్ణయించిన అనేక పరిస్థితుల్లో నడిపి ఫలితాలు చెక్ చేసే script.
- API key: password లేకుండా ఒక script router user లా పనిచేయడానికి అనుమతించే key, secret.
- Alias (URL table): router ఒక web అడ్రసు నుంచి download చేసి refresh చేసే అడ్రసుల OPNsense జాబితా.
- NAT redirect: match అయిన traffic ఎక్కడికి వెళ్లాలో మార్చే rule; ఇక్కడ దారి తప్పిన DNS queries ని router కి పంపుతుంది.
- State table: firewall ఇప్పటికే చూసిన connections జాబితా. తెలిసిన connection తర్వాతి packets మొదటిదానికి తీసుకున్న నిర్ణయాన్నే పాటిస్తాయి.
- DoH, DoT: DNS over HTTPS (port 443), DNS over TLS (port 853). router ని అడగకుండా ఒక device పేర్లను వెతకడానికి రెండు దారులు.
Expect: 100-continue: request body పంపే ముందు దాన్ని ఆమోదించమని server ని అడిగే HTTP header.
ผ่านทุกการทดสอบ ในที่ที่ผิด
บ่ายวันที่ 11 ตุลาคม 2026 ผมรัน script ตัวหนึ่งกับ API ของ router OPNsense ของผม จาก Windows PowerShell 5.1 ซึ่งเป็น PowerShell ที่มากับ Windows มันหยุดก่อนจะเขียน log ของตัวเองได้แม้แต่บรรทัดเดียว การเรียก router ครั้งแรกของ script อยู่หลังบรรทัดนั้น จึงเท่าที่ผมดูออก ไม่มีอะไรไปถึง router
นั่นคือเวอร์ชัน 2.0 เวอร์ชัน 2.4 ทำงานเสร็จเมื่อ 15:06 คือ 37 นาทีหลังจากผมบันทึกเวอร์ชัน 2.0 ทุกเวอร์ชันผ่านการทดสอบใน sandbox ของ Claude ก่อน แต่การทดสอบเหล่านั้นทำในที่ที่ผิด คือรันกับ mock router แทน router ตัวจริง และรันบน PowerShell 7 แทน Windows PowerShell 5.1 เวอร์ชันทั้งสามที่ต่อมาล้มเหลวบน router ผ่านการทดสอบกับ mock ความต่างของ PowerShell มีส่วนในความล้มเหลวครั้งที่ 1 หรือไม่ ผมไม่รู้ ในครั้งที่ 2 ไม่มีส่วน และภายหลังมันทำให้ test harness ของผมพัง มีสามครั้งที่รันแล้วล้มเหลว แต่ละครั้งด้วยสาเหตุต่างกัน ไม่มีครั้งไหนทิ้งการเปลี่ยนแปลงที่เปิดใช้งานค้างไว้
ผมทำงานนี้ร่วมกับ Claude ผมเป็นคนกำหนดกฎที่ script ต้องทำตาม สร้าง API key และลบมันทิ้งหลังเสร็จงาน และรันทุกเวอร์ชันบน PC ของผมเองกับ router ของผมเอง Claude เขียน script, mock router ที่ใช้ทดสอบ และการแก้ไขแต่ละครั้ง Claude ทดสอบทั้งหมดบน PowerShell 7 ซึ่งเป็น PowerShell ตัวเดียวที่ sandbox ของมันมี
script, mock router และ test harness อยู่ท้ายหน้านี้ ภายใต้สัญญาอนุญาต MIT script นี้ทำให้ router ปฏิเสธสามวิธีทั่วไปที่ใช้เลี่ยง blocklist ของ DNS คือ DNS over HTTPS, DNS over TLS หรือ QUIC และ DNS ธรรมดาที่ส่งไปยัง server อื่น หน้านี้บันทึกการรันและสิ่งที่ผมจะเปลี่ยน และแผงใกล้ท้ายหน้าแสดงขั้นตอนการรัน script บน router ของคุณเอง ทีละขั้น
ไม่คุ้นกับ command line? วิธีอ่านกล่องคำสั่ง
PS> หมายถึง: พิมพ์คำสั่งนี้ใน PowerShell บน Windows (เมนู Start → พิมพ์ powershell → Enter) อย่าพิมพ์ PS> เอง
แต่ละบรรทัดที่ขึ้นต้นด้วย PS> คือหนึ่งคำสั่ง คลิกที่ PS> เพื่อคัดลอกเฉพาะบรรทัดนั้น วางลงไป กด Enter และรอให้ทำงานเสร็จก่อนจะไปคำสั่งถัดไป กล่องที่มีปุ่ม Copy อยู่ด้านบนใส่หนึ่งคำสั่ง (หรือหนึ่งไฟล์) จึงให้คัดลอกทั้งกล่อง กล่องเส้นประแสดงสิ่งที่คุณควรเห็นตอบกลับมา หรือโค้ดไว้อ่าน คุณไม่ต้องพิมพ์
สิ่งที่ script ทำ
script นี้ใช้แก้ปัญหา DNS บน router OPNsense 26.7 blocklist ของ router ผมกรองได้เฉพาะอุปกรณ์ที่ถาม router ส่วนโทรศัพท์ เบราว์เซอร์ และอุปกรณ์บางตัวไปถาม server อื่น การแก้นี้เกี่ยวกับ object สี่ตัว:
- alias ชื่อ
DoH_IPsที่ดาวน์โหลดรายการสาธารณะของ address ของ server DNS-over-HTTPS ซึ่งโปรเจกต์ Hagezi ดูแลไว้ (วันนั้นมี 1,434 รายการ); - Rule A ซึ่ง reject ทราฟฟิกจาก LAN ที่ไปยัง address เหล่านั้นบน port 443;
- Rule B ซึ่ง reject ทราฟฟิกจาก LAN ที่ไปยัง address ใดก็ได้บน port 853 ซึ่ง DNS over TLS และ DNS over QUIC ใช้;
- NAT redirect ที่ส่ง query ทุกตัวบน port 53 ที่ส่งไปยัง server อื่นโดยไม่ผ่าน router กลับมาที่ router
บน router ของผม alias และ rule redirect มีอยู่แล้ว และ redirect ถูกปิดไว้ script จะทำความสะอาด alias สร้าง rule สองตัวถ้ายังไม่มี และเปิด redirect มันไม่สร้าง rule redirect rule เหล่านี้ครอบคลุมเฉพาะ IPv4 และ interface LAN ข้อจำกัดต่าง ๆ อยู่ในแผงขั้นตอนใกล้ท้ายหน้า
ผมคลิกสร้าง object ทั้งสี่นี้เองก็ได้ แต่ผมเขียน script เพราะอยากได้การเปลี่ยนแปลงในรูปที่ตรวจสอบได้โดยไม่เปลี่ยนอะไร รันซ้ำได้ และปิดได้ด้วยคำสั่งเดียว
กฎที่ script ต้องทำตาม
- สามโหมด
Checkอ่านและรายงานApplyทำการเปลี่ยนแปลงRollbackปิด rule สองตัวและ redirect โดยไม่ลบอะไร คำสั่งที่ไม่ระบุ-ModeจะรันCheck - ตรวจเวอร์ชัน script ถาม router ก่อนว่ารันอะไรอยู่ และหยุดถ้าคำตอบไม่ใช่ซีรีส์ 26.7
- backup เป็นลำดับถัดไป ก่อนจะอ่านหรือเปลี่ยน configuration ใด ๆ ทุกการรันจะดาวน์โหลด configuration ทั้งหมดของ router ลงไฟล์ใหม่ และไม่ยอมเขียนทับไฟล์ที่มีอยู่แล้ว
- ทดสอบทุกการเปลี่ยนแปลง alias ก่อน แล้วตามด้วย rule ทั้งสอง แล้วจึง redirect ในเวอร์ชัน 2.3 ถ้าการทดสอบล้มเหลว จะ undo ทุกอย่างที่การรันนั้นเปลี่ยนไป ตั้งแต่เวอร์ชัน 2.4 ถ้าล้มเหลวเฉพาะ redirect ก็จะปิดเฉพาะ redirect ส่วน rule ที่ผ่านแล้วยังอยู่
- ไม่มีความลับใน script API key เก็บอยู่ในไฟล์แยก
สามสิบเจ็ดนาที
| เริ่ม | เวอร์ชัน | โหมด | เกิดอะไรขึ้น | สิ่งที่เหลืออยู่บน router |
|---|---|---|---|---|
| หลัง 14:29 | 2.0 | ไม่ได้บันทึกใน log | หยุดก่อน log บรรทัดแรก | ไม่มี |
| 14:43 | 2.1 | Check | รายงานแบบอ่านอย่างเดียว ครบถ้วน | ไม่มี |
| 14:51 | 2.2 | Apply | หยุดเพราะ guard ของตัวเองก่อนการ save ใด ๆ | ไม่มี |
| 14:56 | 2.3 | Apply | rule ใช้ได้; การทดสอบ redirect ล้มเหลว; undo แล้ว | rule สองตัว ถูกปิดไว้ |
| 15:04 | 2.4 | Apply | เสร็จเมื่อ 15:06 ผ่านทุกการทดสอบ | การแก้ไขนี้ |
เวอร์ชัน 2.0 ไม่ได้เขียน log เวลาของมันจึงเป็นนาทีที่ผมบันทึกไฟล์ เวลาอื่น ๆ มาจาก log ของ script เอง
ลำดับการทำงานช่วยจำกัดความเสียหาย script ตรวจเวอร์ชัน ทำ backup และอ่านก่อนเขียน ความล้มเหลวครั้งที่ 1 หยุดก่อนเรียก router ใด ๆ ความล้มเหลวครั้งที่ 2 หยุดก่อนการ save ใด ๆ ด้วย guard ที่เขียนไว้สำหรับปัญหาอื่น ความล้มเหลวครั้งที่ 3 เกิดหลังจากมีการเปลี่ยนแปลงแล้ว และ undo ของเวอร์ชันนั้นปิดการเปลี่ยนแปลงเหล่านั้น
ความล้มเหลวครั้งที่ 1: สาเหตุที่ผมเข้าใจผิด
เวอร์ชัน 2.0 เอาโฟลเดอร์ทำงานมาจากค่า default ของ parameter:
[string]$WorkDir = $PSScriptRoot$PSScriptRoot คือโฟลเดอร์ที่ script อยู่ script ใช้มันสร้าง path ของโฟลเดอร์ logs ซึ่ง script สร้างขึ้นก่อนจะอ่าน key หรือเรียก router
เวอร์ชัน 2.1 เปลี่ยนสามอย่าง มันหาโฟลเดอร์ในตัว script เอง หยุดถ้าโฟลเดอร์นั้นไม่มีอยู่ และครอบการนับสองจุดไว้เพื่อให้คำตอบ DNS ที่ว่างเปล่านับเป็นศูนย์ มีเพียงการเปลี่ยนเรื่องโฟลเดอร์ที่อยู่ก่อน log บรรทัดแรก ในวันนั้น Claude กับผมสรุปว่า Windows PowerShell 5.1 ปล่อยให้ $PSScriptRoot ว่าง และร่างแรก ๆ ของโพสต์นี้ก็เขียนไว้อย่างนั้น
ชุดทดสอบของโพสต์นี้ตรวจเรื่องนั้น และข้อสรุปนั้นผิด บน PC ของผม Windows PowerShell 5.1 ที่เริ่มด้วย -File แบบที่ผมเริ่ม script ใส่โฟลเดอร์ลงใน $PSScriptRoot ในค่า default ของ parameter เช่นเดียวกับ PowerShell 7.4.6 ผมไม่ได้ทดสอบทุกวิธีที่ใช้เริ่ม script จึงตัดความเป็นไปได้ไม่ได้ว่าบางวิธีทำให้มันว่าง ผมไม่ได้บันทึกว่าบ่ายวันนั้นผมเริ่มเวอร์ชัน 2.0 อย่างไร หรือ error ที่มันแสดง ผมจึงไม่รู้ว่าอะไรทำให้มันหยุด สิ่งที่หลักฐานรองรับแคบกว่านั้น: เวอร์ชัน 2.0 หยุดก่อน log บรรทัดแรก ดังนั้น เท่าที่หลักฐานแสดง จึงหยุดก่อนการเรียก router ใด ๆ คอมเมนต์ใน script ที่เผยแพร่บอกว่าโฟลเดอร์นี้อาจว่างบน Windows PowerShell 5.1 คอมเมนต์นั้นตรงกับข้อสรุปแรกของผม ผมปล่อยไฟล์ที่ผ่านการทดสอบแล้วไว้ตามเดิม
การเปลี่ยนในเวอร์ชัน 2.1 ยังคงไว้ มันไม่มีต้นทุนอะไร และใช้ได้ไม่ว่าจะเริ่ม script ด้วยวิธีไหน:
if ([string]::IsNullOrWhiteSpace($WorkDir)) {
if ($MyInvocation.MyCommand.Path) { $WorkDir = Split-Path -Parent $MyInvocation.MyCommand.Path }
else { $WorkDir = (Get-Location).Path }
}การรัน Check ของเวอร์ชัน 2.1 เมื่อ 14:43 ทำงานจนจบ
ความล้มเหลวครั้งที่ 2: mock ที่ไม่มีพฤติกรรมเฉพาะตัวของ router
เพื่อตรวจชนิดของ alias เวอร์ชัน 2.2 เรียก endpoint alias/get_item ของ router log ของการรันเมื่อ 14:51:
14:51:46 Problem: Existing alias DoH_IPs is type '', not urltable. Fix or delete it in the GUI, then rerun.
14:51:46 Nothing to undo.
...
14:51:47 STOP: Apply did not complete; changes from this run were undone.ชนิดของ alias ไม่ได้ว่าง คำตอบของ router มีรายการที่ชื่อเป็นสตริงว่าง ("":) JSON อนุญาตให้ทำเช่นนั้นได้ แต่ PowerShell สร้าง property ของ object ที่มีชื่อว่างไม่ได้ เอกสารของ Microsoft สำหรับ ConvertFrom-Json บอกไว้อย่างนั้น (เอกสารอ้างอิง PowerShell 7.4) และเสนอ switch -AsHashtable สำหรับคำตอบแบบนี้ Windows PowerShell 5.1 ไม่มี switch นั้น Invoke-RestMethod ไม่แจ้ง error ใด ๆ มันคืนคำตอบมาเป็นข้อความธรรมดา และ script อ่านชนิดจากข้อความนั้นออกมาเป็นค่าว่าง
นี่ไม่ใช่ความต่างระหว่างเวอร์ชันของ PowerShell ชุดทดสอบป้อนคำตอบที่มี key ว่างให้ script บน PowerShell 7.4.6 และบน PC ของผมบน Windows PowerShell 5.1 Invoke-RestMethod คืนค่าเป็นข้อความโดยไม่มี error เวอร์ชัน 2.2 ผ่านการทดสอบกับ mock เพราะคำตอบของ mock ไม่มี key ว่าง แต่คำตอบของ router มี
guard ที่หยุดการรันนี้เขียนไว้สำหรับปัญหาอื่น คือ alias ที่มีอยู่แล้วแต่เป็นชนิดผิด มันหยุดการรันนี้เพราะชนิดที่ว่างไม่ใช่ urltable ถ้าไม่มี guard นี้ การรันจะ save URL ใหม่ แล้วตอน undo ก็จะเขียนสตริงว่างลงใน alias
การรัน Check เมื่อ 14:43 ไม่ได้จับปัญหานี้ Check อ่าน alias ผ่าน alias/search_item มีแค่ Apply ที่เรียก get_item
เวอร์ชัน 2.3 เปลี่ยนสองอย่าง endpoint search_item และ search_rule ของ router คืนชนิดและเนื้อหาอยู่แล้ว และคำตอบของมัน parse ได้ script จึงอ่านผ่าน endpoint เหล่านี้เท่านั้น และทุกการเรียก API ตอนนี้ผ่าน helper ตัวเดียวที่ปฏิเสธคำตอบที่มัน parse ไม่ได้:
$r = Invoke-RestMethod @p
if ($r -is [string]) {
$t = $r.TrimStart()
if ($t.StartsWith('{') -or $t.StartsWith('[')) { throw "Router reply to $Path could not be read as JSON by this PowerShell; stopping." }
}ความล้มเหลวครั้งที่ 3: redirect ที่ทดสอบเร็วเกินไป
เวอร์ชัน 2.3 ไปได้ไกลกว่า มันทำความสะอาด alias เพิ่ม rule ทั้งสองและทดสอบ จากนั้นเปิด NAT redirect และทดสอบห้าวินาทีต่อมา:
14:57:16 Rules A and B verified: DoH and DoT refused, normal HTTPS works.
14:57:17 NAT rule enabled and applied. Verifying...
14:57:22 Problem: 8.8.8.8 still returns real ad addresses; the redirect is not taking effect.
14:57:22 Undoing changes made in this run...การทดสอบส่ง query สองตัวไปที่ 8.8.8.8: ตัวหนึ่งสำหรับ example.com และอีกตัวสำหรับโดเมนโฆษณา log ของ firewall แสดงว่ามีหนึ่งในสองตัวถูก redirect โดเมนโฆษณาได้ address จริงกลับมา ตัวที่ไม่ถูก redirect จึงเป็นตัวนั้น สิบสามวินาทีก่อนเปิด redirect การตรวจตอนเริ่มของ script ได้ส่งชื่อเดียวกันนั้นไปที่ 8.8.8.8 เพื่อแสดงว่าทางเลี่ยงยังเปิดอยู่
ผมมีคำอธิบายสองแบบ และไม่ได้ทดสอบเลยสักแบบ firewall เก็บ state entry ไว้สำหรับแต่ละ connection ที่มันเคยเห็น และใช้ redirect กับ connection ใหม่เท่านั้น ถ้า query ครั้งที่สองของโดเมนโฆษณาออกจาก PC ของผมจาก source port เดียวกับครั้งแรก มันจะตรงกับ entry เดิมและออกไปถึง Google หรือมีบางอย่างบน PC ของผมตอบคำถามซ้ำนั้นจากแคช และ query ไม่เคยออกจาก PC เลย
timeout ของ UDP state บน router นี้ ซึ่งอ่านจาก Firewall → Diagnostics → Statistics คือ 60 วินาทีสำหรับ udp.first และ udp.multiple และ 30 วินาทีสำหรับ udp.single เวอร์ชัน 2.4 รอ 70 วินาทีก่อนทดสอบ และการทดสอบผ่าน:
15:05:08 NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
15:06:18 NAT redirect verified: queries to 8.8.8.8 are answered by your router.การรอนี้นานกว่า state entry ของ firewall แต่จะนานกว่าคำตอบที่ PC จำไว้หรือไม่ ขึ้นกับว่าคำตอบนั้นถูกเก็บไว้นานแค่ไหน ซึ่งผมไม่ได้วัด ผลลัพธ์นี้จึงแยกคำอธิบายทั้งสองแบบออกจากกันไม่ได้ การทดสอบด้วยชื่อที่ไม่เคย query มาก่อน โดยเปิด state table ของ firewall ดูไปด้วย จะแยกได้
undo ในเวอร์ชัน 2.3 ปิด redirect ปิด rule ใหม่ทั้งสองตัว และคืนเนื้อหาของ alias มันไม่ได้ลบ rule และปล่อยให้ช่วงเวลา refresh ของ alias เป็นหนึ่งวัน backup ที่ทำหลัง undo ใหญ่กว่า backup ก่อนการรัน 4,788 ไบต์ เวอร์ชัน 2.4 เริ่มต้นด้วยการพบ rule ทั้งสองตัว:
15:04:56 Rule A: present, enabled=0, sort_order=400000.0000100
15:04:56 Rule B: present, enabled=0, sort_order=400000.0000200ดังนั้น “undo แล้ว” หมายถึง “ไม่มีอะไรเหลือที่เปิดใช้งานอยู่” ไม่ใช่ “router กลับเป็นเหมือนเดิม” เวอร์ชัน 2.4 เปิด rule สองตัวที่มีอยู่แล้วแทนที่จะเพิ่มสำเนาใหม่ เพราะมันค้นหา rule จากคำอธิบายก่อนจะสร้าง
สิ่งที่ mock พลาด และการทดสอบรอบที่สอง
Claude รันแต่ละเวอร์ชันกับ mock ก่อนที่ผมจะรันกับ router ตามบันทึกของ session นั้น แต่ละเวอร์ชันรันครั้งหนึ่งแบบปกติ และอีกครั้งแบบบังคับให้ล้มเหลว เพื่อตรวจ undo เวอร์ชัน 2.0 ถึง 2.3 ผ่านการทดสอบกับ mock แต่เมื่อรันกับ router สามในสี่เวอร์ชันล้มเหลว mock ไม่เคยรันบน Windows PowerShell 5.1 และคำตอบของมันไม่มี key ว่างแบบที่ router มี
script ท้ายหน้านี้คือเวอร์ชัน 2.5.1 ไม่ใช่ 2.4 ก่อนเผยแพร่ ผมให้ Claude รีวิว script อีกครั้ง และเวอร์ชัน 2.5 แก้สิ่งที่รีวิวนั้นพบ: ข้อความที่อาจบรรยายสถานะของ router ผิด, การหยุดที่ไม่ได้เขียนลง log, undo ที่ไม่ได้คืนค่า enabled ของ alias และการรันที่อาจเริ่มได้บน router ที่ไม่มี rule redirect หรือ rule allow-all ของ LAN มันยังปฏิเสธ address ของ router ที่ไม่ได้ขึ้นต้นด้วย https:// ยกเว้น address บน PC เครื่องที่รัน script เอง ซึ่งชุดทดสอบใช้ เวอร์ชัน 2.4 คือตัวที่รันบน router ของผม เวอร์ชัน 2.5.1 ซึ่งต่างจาก 2.5 เฉพาะคอมเมนต์ส่วนหัว รันกับ mock เท่านั้น
การทดสอบรอบที่สองใช้ mock ตัวใหม่ ที่สร้างให้ทำตัวผิดปกติแบบที่ router อาจทำได้ รวมถึงคำตอบที่มี key ว่าง harness รันสำเนาของ script กับ mock นี้ครั้งละหนึ่งกรณี รวม 30 กรณี บน PowerShell 7.4.6 ผ่านทั้ง 30 กรณี
การรันครั้งแรกบน Windows PowerShell 5.1 บน PC ของผมล้มเหลวสองกรณี log ของ script แสดงว่า script ทำถูกแล้ว แต่ harness ทำไม่ถูก เมื่อ function ของ PowerShell คืน list ที่มีสมาชิกตัวเดียว ผู้เรียกจะได้ตัวสมาชิกนั้นเอง PowerShell 7 ให้นับและ index สมาชิกนั้นได้เหมือนเป็น list แต่ Windows PowerShell 5.1 ไม่ให้ สำหรับ object ชนิดนี้ harness เคยรันบน PowerShell 7 เท่านั้น เมื่อแก้ตรงนั้นแล้ว ทั้ง 30 กรณีผ่านบน Windows PowerShell 5.1 ด้วย กับ script เวอร์ชันที่เผยแพร่
เพื่อตรวจ harness เอง Claude ทำให้ script พังสิบแบบ เช่น เอา undo, การตรวจ JSON หรือการตรวจ HTTPS ออก การทำพังแต่ละแบบทำให้อย่างน้อยหนึ่งกรณีล้มเหลว การตรวจนั้นรันบน PowerShell 7.4.6 กับเวอร์ชัน 2.5 โดยใช้ harness รุ่นก่อนหน้า
สิ่งที่ผมจะนำไปใช้กับ script ตัวต่อไป
- ทดสอบบน PowerShell ที่จะใช้รัน script และรันการทดสอบบนตัวนั้นด้วย (harness ผ่านบน PowerShell 7 และล้มเหลวในการรันครั้งแรกบน 5.1)
- สร้างคำตอบของ mock จากคำตอบจริง คำตอบที่ save มาจาก
get_itemของ router จะจับความล้มเหลวครั้งที่ 2 ได้ก่อนที่ router จะเห็น script - ทำให้โหมดอ่านอย่างเดียวอ่านทุกอย่างที่โหมดเขียนจะอ่าน ในกรณีนี้
CheckและApplyอ่าน alias ผ่าน endpoint ต่างกัน - ถือว่าสตริงจาก
Invoke-RestMethodคือความล้มเหลว เมื่อคุณคาดว่าจะได้ object มันไม่ได้แจ้ง error เสมอไป - หลังเปิด redirect ให้รอนานกว่า state timeout ของ firewall และทดสอบด้วยชื่อที่ยังไม่เคย query มาก่อน
- ถ้า undo ใช้วิธีปิดแทนการลบ ให้การรันครั้งถัดไปมองหาสิ่งที่ครั้งก่อนทิ้งไว้
- ทำให้ script พังโดยตั้งใจ เพื่อตรวจว่าการทดสอบล้มเหลวได้
- เก็บ API key ไว้นอก script และลบมันเมื่องานเสร็จ ผมใช้ key ของ user
rootการใช้ user ที่มีเฉพาะสิทธิ์ที่ script ต้องใช้จะดีกว่า ผมไม่ได้ลอง
วิธีรันกับ router ของคุณเอง ทีละขั้น
ก่อนเริ่ม คุณต้องมี:
- PC Windows ที่อยู่ในเครือข่ายเดียวกับ router คุณพิมพ์ในสองที่ คือ PowerShell บน PC และหน้าเว็บของ router ในเบราว์เซอร์;
- OPNsense 26.7 script จะหยุดถ้าเป็นซีรีส์อื่น เพราะ path ของ API อ่านมาจากหน้าเว็บของซีรีส์นั้นเอง;
- DNS blocklist ที่เปิดอยู่ ใน Services → Unbound DNS → Blocklist (เอกสารของ OPNsense ระบุหน้านั้น) และอุปกรณ์ของคุณถาม router เรื่อง DNS;
- rule Destination NAT ที่ส่ง query DNS (port 53) ซึ่งเล็งไปที่ใดก็ได้ที่ไม่ใช่ router กลับมาที่ router สร้างไว้แล้ว โดยมีคำอธิบาย “Redirect non-local DNS to Local” script เปิดมัน แต่ไม่ได้สร้าง script ไม่สร้าง rule นี้ แผงนี้ไม่ครอบคลุมการสร้าง rule นี้ และถ้าไม่มี Apply จะหยุด วิธีทำจากชุมชนในฟอรัม OPNsense แสดงวิธีหนึ่ง;
- rule LAN ชื่อ “Default allow LAN to any rule” ซึ่ง OPNsense สร้างให้โดย default script ตรวจว่า rule ใหม่สองตัวของมันอยู่เหนือ rule นี้
เวอร์ชัน 2.5.1 ซึ่งเป็น script ในแผงนี้ รันกับ mock router ในชุดทดสอบเท่านั้น เวอร์ชัน 2.4 คือตัวที่รันบน router ของผม
ใช้เวลาราว 20 นาที ตัวการเปลี่ยนเองใช้ราวสองนาที การเปลี่ยนแปลงแรกบน router คือ API key ในขั้น 3 การรัน Check ในขั้น 5 ไม่เปลี่ยนอะไรบน router Apply ในขั้น 6 เปลี่ยนค่าบน router ขั้น 8 ปิดการแก้ไขและแสดงวิธีกู้คืน configuration ทั้งหมด ทุกการรันจะบันทึก backup ของ configuration ของ router ลงบน PC ก่อนอ่าน configuration
อ่านข้อจำกัดต่อไป ถ้าข้อใดตรงกับเครือข่ายของคุณ script ไม่เหมาะกับเครือข่ายนั้น อย่าทำต่อ
ข้อจำกัด
- IPv4 เท่านั้น Rule A และ B สร้างสำหรับ IPv4 และทุกการทดสอบใช้ address IPv4 ถ้า LAN ของคุณมี IPv6 DoH และ DoT ผ่าน IPv6 จะไม่ถูกบล็อกและไม่ถูกทดสอบ (Interfaces → LAN แสดง IPv6 Configuration Type; None หมายถึงไม่มี IPv6)
- interface LAN เท่านั้น interface อื่นและ VLAN ไม่ครอบคลุม
- ทุก host ใน LAN Pi-hole หรือ AdGuard Home ใน LAN ที่ใช้ DoH หรือ DoT เป็น upstream จะเสีย upstream ไป ถ้ามันส่ง DNS ธรรมดาไปที่ server สาธารณะ rule redirect ของคุณอาจจับสิ่งนั้นด้วย ขึ้นกับว่า rule สร้างไว้อย่างไร
- อุปกรณ์ที่บังคับใช้ DNS แบบเข้ารหัสเท่านั้น อุปกรณ์ที่ตั้งให้ใช้เฉพาะผู้ให้บริการ DNS แบบเข้ารหัส เช่น โทรศัพท์ที่ตั้ง Private DNS เป็น hostname อาจค้นหาชื่อบนเครือข่ายนี้ไม่ได้ เมื่อ rule ปฏิเสธเส้นทางของมัน ให้เปลี่ยนค่านั้นบนอุปกรณ์
- rule redirect ต้องมีอยู่แล้ว ใน Firewall → NAT → Destination NAT โดยมีคำอธิบาย “Redirect non-local DNS to Local” หรือค่าที่คุณตั้งใน
$NatDescscript ไม่ได้สร้างมัน และไม่ได้ตรวจว่ามันสร้างไว้อย่างไร - alias จะถูกเขียนทับ ด้วย URL ของ Hagezi เนื้อหาเดิมจะถูกเขียนลง log
- โดเมนทดสอบ ใน
$AdTestDomainต้องถูก blocklist ของ router บล็อก โดยตอบเป็น 0.0.0.0 หรือไม่มี address ไม่เช่นนั้นการทดสอบ redirect จะล้มเหลว - LAN ที่คุณเชื่อถือ การตรวจ certificate ของ script ยอมรับ certificate ใดก็ได้ที่แสดงสำหรับ address ของ router ดังนั้นอุปกรณ์ใน LAN ที่ปลอมตัวเป็น router จะได้ key ไป รันเฉพาะบนเครือข่ายที่คุณควบคุม
- เวลารอ ใน
$NatWaitSecondsควรนานกว่า UDP state timeout ของ router คุณ - Rollback ปิด rule สองตัวและ rule redirect แม้ว่า redirect จะเปิดอยู่ก่อนที่คุณจะรัน
Applyครั้งแรก มันไม่คืนค่า alias
เปิด PowerShell และสร้างโฟลเดอร์ เปิดเมนู Start พิมพ์
powershellแล้วกด Enter หน้าต่างชื่อ Windows PowerShell จะเปิดขึ้น และ prompt ของมันขึ้นต้นด้วยPSถ้า prompt ไม่มีPSแสดงว่าคุณอยู่ใน Command Prompt ให้ปิดแล้วเปิด PowerShell แทน เพราะคำสั่งด้านล่างใช้ได้เฉพาะใน PowerShell คลิกในหน้าต่าง ใช้สองบรรทัดด้านล่างทีละบรรทัด: คลิก PS> เพื่อคัดลอกบรรทัดนั้น วางมัน (Ctrl + V หรือคลิกขวา) แล้วกด EnterNew-Item -ItemType Directory -Path "$env:USERPROFILE\opnsense-dns" Set-Location "$env:USERPROFILE\opnsense-dns"บรรทัดแรกสร้างโฟลเดอร์ชื่อ
opnsense-dnsในโฟลเดอร์ผู้ใช้ของคุณและแสดงรายการสั้น ๆ; บรรทัดที่สองย้าย PowerShell เข้าไปในโฟลเดอร์นั้น และ prompt จะลงท้ายด้วยopnsense-dns>แต่ละบรรทัดใช้เวลาไม่ถึงหนึ่งวินาที ถ้าบรรทัดแรกบอกว่ามีโฟลเดอร์อยู่แล้ว ให้ทำต่อ เปิดหน้าต่างนี้ไว้ และเก็บโฟลเดอร์ให้อยู่นอก OneDrive, Dropbox และที่เก็บที่แชร์ร่วม: backup ที่บันทึกที่นี่มี configuration ทั้งหมดของ routerบันทึก script เลื่อนไปที่ The script, the mock router and the test harness ท้ายหน้านี้ เปิด opnsense-dns-bypass.ps1 (version 2.5.1) อ่านมัน แล้วคลิก Copy มันยาว 491 บรรทัด มันจะใช้ key ของ router คุณ จึงอ่านก่อนรัน Windows ทำเครื่องหมายไฟล์ที่เบราว์เซอร์ดาวน์โหลดว่ามาจากอินเทอร์เน็ต ไฟล์ที่เขียนด้วยคำสั่งด้านล่างไม่มีเครื่องหมายนั้น จึงไม่ต้องใช้
Unblock-Fileคำสั่งนี้เขียนทับไฟล์ชื่อเดียวกันในโฟลเดอร์นี้ ในหน้าต่าง PowerShell:Get-Clipboard -Raw | Set-Content -Encoding Ascii .\opnsense-dns-bypass.ps1Get-Clipboardอ่านสิ่งที่คุณคัดลอก และSet-Contentเขียนลงไฟล์ ตัว script เป็น ASCII ล้วน encoding นี้จึงปลอดภัย ใช้เวลาไม่ถึงหนึ่งวินาทีและไม่พิมพ์อะไร ตรวจว่าทั้งหมดมาครบ:(Get-Content .\opnsense-dns-bypass.ps1).Count491ตัวเลขที่ต่างออกไปบ่งว่าการคัดลอกถูกตัดหรือถูกเปลี่ยน กลับไปที่หน้านั้น คลิก Copy อีกครั้ง แล้วทำคำสั่งแรกซ้ำ
สร้าง API key บน router ในเว็บเบราว์เซอร์ พิมพ์
https://ตามด้วย address ที่คุณใช้เปิดหน้า settings ของ router (เช่นhttps://192.168.1.1) แล้วกด Enter เบราว์เซอร์อาจเตือนว่าการเชื่อมต่อไม่เป็นส่วนตัว เพราะ router เซ็น certificate เอง เลือกตัวเลือกที่ไปต่อยัง address นั้น (ใน Chrome: Advanced แล้ว Proceed) ล็อกอินด้วย login ของคุณเองบน router จากนั้น:- ในเมนูทางซ้าย คลิก System แล้ว Access แล้ว Users
- คลิกไอคอนดินสอ (edit) ที่ท้ายแถวของผู้ดูแลที่คุณล็อกอินเป็น
- หาส่วน API keys ในการตั้งค่าของ user (เอกสารของ OPNsense เรียกว่าแท็บ ApiKeys) และใช้ปุ่มในตารางของมันที่สร้าง key
- เบราว์เซอร์จะดาวน์โหลดไฟล์ข้อความขนาดเล็กภายในไม่กี่วินาที ไฟล์มีบรรทัด
key=และบรรทัดsecret=เอกสารบอกว่า secret ถูกสร้างเพียงครั้งเดียว ถ้าไฟล์หาย ให้สร้าง key ใหม่
key ทำงานในฐานะ user ที่เป็นเจ้าของมัน ผมใช้ key ของ user root และลบทิ้งหลังจากนั้น key ของ root ให้สิทธิ์ควบคุม router เต็มที่ user ที่จำกัดเฉพาะหน้า firewall, NAT และ backup จะมีสิทธิ์น้อยกว่า แต่ script ดาวน์โหลด configuration ทั้งหมดของ router user นั้นจึงยังอ่าน hash ของรหัสผ่านและ private key ใน configuration ได้ ผมไม่ได้ลอง user ที่จำกัดสิทธิ์ ถ้าเมนูของคุณหน้าตาต่างออกไป เอกสารของ OPNsense เรื่อง local user อธิบายขั้นเดียวกัน อย่านำเนื้อหาในไฟล์ key ไปวางที่ใด: secret ในไฟล์ให้สิทธิ์ควบคุม router
ใส่ไฟล์ key ในโฟลเดอร์ กลับมาที่ PowerShell แสดงรายการไฟล์ข้อความใหม่ล่าสุดในโฟลเดอร์ Downloads ของคุณ:
Get-ChildItem "$env:USERPROFILE\Downloads" -Filter *.txt | Sort-Object LastWriteTime -Descending | Select-Object -First 3 Name, LastWriteTimeName LastWriteTime ---- ------------- example_apikey.txt <date and time>ถ้ารายการว่าง เบราว์เซอร์บันทึกไฟล์ไว้ที่อื่น: กด Ctrl + J ในเบราว์เซอร์เพื่อดูว่าอยู่ที่ไหน ตอนนี้ย้ายไฟล์เข้าโฟลเดอร์ภายใต้ชื่อที่ script คาดไว้ แทน
<file-name>รวมวงเล็บมุม ด้วยชื่อจากรายการ:Move-Item -LiteralPath "$env:USERPROFILE\Downloads\<file-name>" -Destination .\apikey.txtใช้เวลาไม่ถึงหนึ่งวินาทีและไม่พิมพ์อะไร มันจะไม่เขียนทับ
apikey.txtที่มีอยู่แล้วในโฟลเดอร์ ถ้ามันปฏิเสธด้วยเหตุนั้น แสดงว่ามีไฟล์ key เก่าอยู่ที่นั่น ลบ key นั้นบน router (ขั้น 8 บอกว่าอยู่ที่ไหน) รันRemove-Item .\apikey.txtและทำขั้นนี้ซ้ำ ถ้ามันรายงาน error เรื่อง path แสดงว่า path อาจยังมี<file-name>อยู่ หรือชื่ออาจไม่ตรงกับชื่อในรายการ ตอนนี้ตรวจว่าไฟล์ key มีสองบรรทัด คำสั่งนี้พิมพ์เฉพาะคำก่อนเครื่องหมาย=แต่ละตัว ไม่พิมพ์ค่า:Get-Content .\apikey.txt | ForEach-Object { ($_ -split '=')[0] }key secretถ้าคุณเห็นคำอื่น ไฟล์นี้น่าจะไม่ใช่ไฟล์ key ดาวน์โหลด key ใหม่ (ขั้น 3)
รัน Check — คำสั่งนี้อ่านอย่างเดียว ก่อนอื่นบอก PowerShell ว่า address ของ router คืออะไร คลิก PS> เพื่อคัดลอกบรรทัด วางมัน และอย่าเพิ่งกด Enter แทน
<router-ip-address>รวมวงเล็บมุม ด้วยตัวเลขของ address จากขั้น 3 (เช่น192.168.1.1) และปล่อยhttps://ไว้ตามเดิม ขยับ cursor ด้วยปุ่มลูกศร เพราะการคลิกเมาส์ไม่ย้าย cursor ใน PowerShell; Backspace ลบตัวอักษร จากนั้นกด Enter ถ้ายังมีวงเล็บมุมอยู่ script จะหยุด$RouterUrl = 'https://<router-ip-address>'ค่านี้จำ address ไว้เฉพาะหน้าต่างนี้ ถ้าปิดหน้าต่าง ให้ทำซ้ำ
ตอนนี้รัน script
powershell -ExecutionPolicy Bypass -Fileเริ่ม Windows PowerShell 5.1 ตัวใหม่ที่รันไฟล์นั้น-ExecutionPolicy Bypassบน command line มีผลเฉพาะการรันครั้งนั้น และ เอกสารของ Microsoft เรื่อง execution policy บอกว่าค่านี้ไม่ถูกเก็บไว้ มันไม่ override Group Policy ที่นายจ้างตั้งไว้ ถ้าไม่มี-Modescript จะรันCheckpowershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrlใช้เวลา 10 ถึง 60 วินาทีและไม่เปลี่ยนอะไรบน router มันบันทึก backup ของ configuration ของ router ไว้ในโฟลเดอร์
router-backupsภายในopnsense-dnsบันทึก log ในlogsและรันการทดสอบจริงห้าตัว บรรทัดที่สำคัญ:HH:MM:SS Router reports: OPNsense series 26.7, amd64 HH:MM:SS Backup (before) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Check-before-<timestamp>.xml (NNN,NNN bytes) ... HH:MM:SS Router resolves example.com : True (want True) HH:MM:SS Router blocks the ad domain (blocklist) : True (want True) HH:MM:SS Bypass DoH 1.1.1.1:443 reachable : True (want False after Apply) HH:MM:SS Bypass DoT 9.9.9.9:853 reachable : True (want False after Apply) HH:MM:SS Bypass 8.8.8.8 gives real ad IPs : True (want False after Apply) HH:MM:SS Check mode: nothing was changed on the router. HH:MM:SS Log file: C:\Users\<you>\opnsense-dns\logs\run-Check-<timestamp>.logบรรทัด “want True” ทั้งสองต้องเป็น True ถ้า “Router blocks the ad domain” เป็น False แสดงว่า blocklist ของคุณไม่บล็อกโดเมนทดสอบ และการทดสอบ redirect ในขั้น 6 จะล้มเหลว ตั้ง
$AdTestDomainใกล้ต้น script เป็นโดเมนที่ blocklist ของคุณบล็อก หรือเปิด blocklist ถ้าบรรทัดสีเหลืองขึ้นต้นด้วยApply would stop:มันระบุ rule ที่ขาด: rule redirect หรือ rule allow-all ของ LAN แก้บน router ก่อนขั้น 6ถ้าเกิดปัญหา script พิมพ์บรรทัดสีแดง (ส่วนใหญ่มีคำว่า STOP) และไม่เปลี่ยนอะไรบน router บรรทัดนั้นบอกอะไร และหมายความว่าอย่างไร:
- Set -Router to your router’s address: วงเล็บมุมยังอยู่ใน address จากขั้นนี้
- Missing an argument for parameter ‘Router’: น่าจะไม่ได้รันบรรทัด address ข้างบนในหน้าต่างนี้ รันอีกครั้ง
- -Router must start with https://: address ขึ้นต้นด้วย
http://ใช้https:// - STOP: Key file not found:
apikey.txtไม่อยู่ในโฟลเดอร์opnsense-dnsทำขั้น 4 ใหม่ - STOP: Cannot reach the router API with this key: address ผิด key ถูกลบแล้ว หรือ PC ไม่ได้อยู่ในเครือข่ายของ router เปิด address ในเบราว์เซอร์เพื่อทดสอบ
- STOP: Script was built for OPNsense 26.7: router ของคุณรันซีรีส์อื่น และ path API ของ script อ่านมาจาก 26.7 หยุดที่นี่
- PowerShell บอกว่าการรัน script ถูกปิด: นโยบายบน PC ของคุณบล็อก script และตัวเลือกบน command line override ไม่ได้ หยุดที่นี่
รัน Apply — คำสั่งนี้เปลี่ยนค่าบน router มันเขียนทับ alias
DoH_IPsด้วย address ของรายการ Hagezi (เนื้อหาเดิมไปอยู่ใน log) เพิ่ม rule reject สองตัวถ้ายังไม่มี และเปิด rule redirect อุปกรณ์ในเครือข่ายของคุณที่คุยกับ server DNS-over-HTTPS หรือ DNS-over-TLS โดยตรงจะเสียเส้นทางนั้น นั่นคือจุดประสงค์ รันคำสั่งเดิมโดยเพิ่ม-Mode Apply:powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Applyใช้เวลาราวสองนาที และนานสุดสี่นาทีถ้า alias ต้องดาวน์โหลดรายการก่อน มีหนึ่งบรรทัดที่เขียนว่า
Waiting 70 s for older DNS states to expire before testing...; รอมันและอย่าปิดหน้าต่าง บรรทัดสุดท้ายควรเป็น:HH:MM:SS Bypass DoH 1.1.1.1:443 reachable : False (want False after Apply) HH:MM:SS Bypass DoT 9.9.9.9:853 reachable : False (want False after Apply) HH:MM:SS Bypass 8.8.8.8 gives real ad IPs : False (want False after Apply) HH:MM:SS Backup (after) saved: C:\Users\<you>\opnsense-dns\router-backups\config-Apply-after-<timestamp>.xml (NNN,NNN bytes) HH:MM:SS Apply finished. Expected: router tests True, all three bypass tests False. HH:MM:SS Log file: C:\Users\<you>\opnsense-dns\logs\run-Apply-<timestamp>.logถ้าเกิดปัญหา Apply did not complete; changes from this run were undone: การทดสอบล้มเหลว และ script ปิดสิ่งที่มันเปลี่ยน rule ที่มันเพิ่มยังอยู่ แต่ถูกปิดไว้ มันบันทึก backup ของผลลัพธ์ อ่านบรรทัดที่ขึ้นต้นด้วย Problem: เพื่อดูเหตุผล ถ้าบรรทัดใดมี UNDO STEP FAILED ให้กู้คืน backup “before” ตามที่ขั้น 8 อธิบาย Apply PARTLY finished (สีเหลือง): alias และ rule สองตัวอยู่ครบและผ่านการทดสอบ และ redirect ไม่ผ่าน บรรทัดนั้นบอกว่า redirect ถูกทิ้งไว้เปิดหรือปิด ถ้าต้องการปิดการแก้ไข ใช้ขั้น 8
ตรวจว่าได้ผล รันคำสั่ง Check จากขั้น 5 อีกครั้ง:
powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrlตอนนี้สามบรรทัด
Bypassเป็นFalseและสองบรรทัดRouterเป็นTrueในหน้าเว็บของ router คุณยังดู Firewall → Rules ได้ (เลือก LAN ในตัวเลือก interface) ซึ่ง rule สองตัว Reject DoH to known resolvers (A) และ Reject DoT/DoQ 853 from LAN (B) ปรากฏอยู่ และดู Firewall → NAT → Destination NAT ซึ่ง Redirect non-local DNS to Local เปิดใช้งานอยู่ปิดการแก้ไข กู้คืนถ้าจำเป็น และลบ key ถ้าต้องการปิดการแก้ไข รันคำสั่งโดยใช้
-Mode Rollback:powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Rollbackใช้เวลาไม่ถึงหนึ่งนาที มันปิด rule สองตัวและ redirect และไม่ลบอะไร alias ยังอยู่ตามที่ Apply ทิ้งไว้ ถ้า redirect เปิดอยู่ก่อนที่คุณเริ่ม ตอนนี้มันปิดอยู่: เปิดกลับใน Firewall → NAT → Destination NAT
ถ้าต้องการคืน configuration ทั้งหมดให้เป็นเหมือนก่อน Apply ให้กู้คืน backup บน router: ไปที่ System → Configuration → Backups เลือกไฟล์ชื่อ
config-Apply-before-<timestamp>.xmlจากโฟลเดอร์router-backupsแล้วกู้คืน การรัน Apply แต่ละครั้งบันทึกไฟล์แบบนี้หนึ่งไฟล์ ไฟล์แรกสุดเก็บ configuration จากก่อน Apply ครั้งแรกของคุณ การกู้คืนนี้จะย้อนการเปลี่ยนแปลงอื่นทุกอย่างที่ทำบน router หลังจากนั้นด้วยเมื่อใช้ script เสร็จ ไม่ว่าจะเก็บการแก้ไขไว้หรือไม่ ให้ลบ key บน router ไปที่ System → Access → Users คลิกดินสอที่ user เดิม และลบ key ในส่วน API keys (แท็บ ApiKeys) จากนั้นลบไฟล์ key จาก PC:
Remove-Item .\apikey.txtคำสั่งนี้ลบไฟล์ทันที ไม่ผ่านถังรีไซเคิล เมื่อไม่ต้องใช้ backup อีกแล้ว ให้ลบโฟลเดอร์
router-backupsด้วย: มี hash ของรหัสผ่านและ private key อยู่
หมายเหตุด้านความปลอดภัย script ส่ง key ไปกับทุก request มันไม่พิมพ์หรือเขียน secret ลง log และชุดทดสอบตรวจเรื่องนั้นในทั้ง 30 กรณี การตรวจ certificate ของมันยอมรับ certificate ใดก็ได้ที่แสดงสำหรับ address ของ router ดังนั้นอุปกรณ์ใน LAN ที่ปลอมตัวเป็น router จะได้ key ไป ผมลบ key ของผมเมื่อ 13 ตุลาคม 2026 สองวันหลังการรัน และประวัติ configuration ของ router บันทึกการลบนั้นไว้
backup คือ configuration ทั้งหมดของ router: hash ของรหัสผ่าน และ private key ของ certificate และ VPN tunnel ต่าง ๆ เก็บโฟลเดอร์นั้นไว้เป็นส่วนตัว และอย่าแนบ backup ไปกับโพสต์ในฟอรัม
เจาะลึก: การตรวจอื่น ๆ ของ script
- backup ต้องดูเหมือน backup หลังดาวน์โหลด script ตรวจว่าไฟล์มีขนาดอย่างน้อย 50,000 ไบต์ และมี
<opnsense>ในสามบรรทัดแรก - การ save ที่ล้มเหลวจะถูกจับได้ คำตอบที่มี
validationsนับเป็นการ save ที่ล้มเหลว เหมือนที่หน้าเว็บของ router เองทำresultที่เป็นfailedก็เช่นกัน การเปลี่ยน alias และ redirect จะถูกอ่านกลับมาตรวจ การเปลี่ยน rule ตรวจจากการมีอยู่และลำดับของ rule และจากการทดสอบ connection จริง - ลำดับ rule หลังเพิ่ม Rule A และ B script จะหยุดถ้า rule ตัวใดเรียงอยู่หลัง “Default allow LAN to any rule” เพราะ rule ที่อยู่ใต้ rule allow-all จะไม่มีวัน match
- alias ต้องมีข้อมูลเข้ามา script ตรวจ alias ทุก 5 วินาที นานสูงสุด 90 วินาที และหยุดถ้า alias มี address ไม่ถึง 500 รายการ
- การท่องเว็บปกติต้องยังใช้ได้ ก่อนจะสรุปว่า rule ใช้ได้ script เปิด connection ไปที่
www.google.com:443 - ผลที่สำเร็จบางส่วนจะบอกว่าเป็นเช่นนั้น ถ้าล้มเหลวเฉพาะขั้น redirect การรันจะจบด้วย
Apply PARTLY finishedบอกว่าทิ้ง redirect ไว้ในสถานะใด และออกด้วย exit code 2
เจาะลึก: ยอมรับ certificate ที่ไม่ผ่านการตรวจ เฉพาะ address ของ router
หน้าเว็บของ router ใช้ certificate แบบ self-signed PowerShell 7 มี -SkipCertificateCheck ซึ่ง script ใช้ในกรณีนั้น Windows PowerShell 5.1 ไม่มี switch นี้ วิธีแก้ที่ใช้กันทั่วไปคือ callback ที่ยอมรับทุก certificate ตลอดทั้ง session callback ของ script ยอมรับการตรวจ certificate ที่ล้มเหลวเฉพาะเมื่อ host ของ request เป็น address ของ router:
public static bool Check(object sender, X509Certificate c, X509Chain ch, SslPolicyErrors e) {
if (e == SslPolicyErrors.None) return true;
HttpWebRequest r = sender as HttpWebRequest;
return r != null && r.RequestUri.Host == Host;
}วิธีนี้ทำให้ข้อยกเว้นแคบลง แต่ไม่ได้ pin certificate: certificate ใดก็ตามที่แสดงสำหรับ address นั้นจะผ่าน การตรวจ thumbprint ของ certificate จะปิดช่องว่างนั้นได้ script ยังตั้ง TLS 1.2 สำหรับ 5.1 ด้วย
เจาะลึก: มาตรการป้องกันไว้ก่อน ไม่ใช่ความล้มเหลว: Expect: 100-continue
โหมด Check ส่งเฉพาะ request แบบ GET ส่วน Apply ส่ง POST Windows PowerShell 5.1 รันบน .NET Framework ซึ่ง ServicePointManager.Expect100Continue เป็น true โดย default และเพิ่ม header Expect: 100-continue ให้ request แบบ POST ที่มี body (เอกสารของ Microsoft) เวอร์ชัน 2.2 ปิด header นี้ก่อน request แรก:
[Net.ServicePointManager]::Expect100Continue = $falseผมไม่ได้ทดสอบว่า web server ของ router จะมีปัญหากับ header นี้หรือไม่
เจาะลึก: การรันที่สำเร็จ ทีละบรรทัด
log ของการรันเมื่อ 15:04 address ของ router และชื่อของ interface หนึ่งของมันถูกแทนด้วย placeholder ในวงเล็บมุม โฟลเดอร์ในเครื่องและหมายเลข build ของ PowerShell ถูกตัดออก และตัวเลขในจำนวนไบต์ถูกจัดกลุ่มทีละสามหลัก การทดสอบตอนเริ่มแสดงว่าทางเลี่ยง blocklist ทั้งสามทางเปิดอยู่ การทดสอบตอนจบแสดงว่าทั้งสามทางปิดแล้ว สำหรับ address IPv4 สามตัวที่ทดสอบ
15:04:49 Mode: Apply Router: https://<router-ip-address> PowerShell 5.1
15:04:55 Router reports: OPNsense series 26.7, amd64
15:04:55 Backup (before) saved: ...\config-Apply-before-20261011-150449.xml (404,269 bytes)
15:04:56 Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[__<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
15:04:56 Rule A: present, enabled=0, sort_order=400000.0000100
15:04:56 Rule B: present, enabled=0, sort_order=400000.0000200
15:04:56 'Default allow LAN to any rule': sort_order=400000.1000023
15:04:56 NAT 'Redirect non-local DNS to Local': disabled=1
15:04:56 Router resolves example.com : True (want True)
15:04:56 Router blocks the ad domain (blocklist) : True (want True)
15:04:56 Bypass DoH 1.1.1.1:443 reachable : True (want False after Apply)
15:04:56 Bypass DoT 9.9.9.9:853 reachable : True (want False after Apply)
15:04:56 Bypass 8.8.8.8 gives real ad IPs : True (want False after Apply)
15:04:56 Alias DoH_IPs set to the URL only (was: __<interface>_network | https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt).
15:04:58 Alias DoH_IPs holds 1434 addresses.
15:04:58 Rule 'Reject DoH to known resolvers (A)' enabled.
15:04:58 Rule 'Reject DoT/DoQ 853 from LAN (B)' enabled.
15:04:58 Firewall rules applied. Verifying...
15:05:08 Rules A and B verified: DoH and DoT refused, normal HTTPS works.
15:05:08 NAT rule enabled and applied. Waiting 70 s for older DNS states to expire before testing...
15:06:18 NAT redirect verified: queries to 8.8.8.8 are answered by your router.
15:06:19 Alias DoH_IPs: present, enabled=1, entries loaded=1434, content=[https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt]
15:06:19 Rule A: present, enabled=1, sort_order=400000.0000100
15:06:19 Rule B: present, enabled=1, sort_order=400000.0000200
15:06:19 'Default allow LAN to any rule': sort_order=400000.1000023
15:06:19 NAT 'Redirect non-local DNS to Local': disabled=0
15:06:23 Router resolves example.com : True (want True)
15:06:23 Router blocks the ad domain (blocklist) : True (want True)
15:06:23 Bypass DoH 1.1.1.1:443 reachable : False (want False after Apply)
15:06:23 Bypass DoT 9.9.9.9:853 reachable : False (want False after Apply)
15:06:23 Bypass 8.8.8.8 gives real ad IPs : False (want False after Apply)
15:06:23 Backup (after) saved: ...\config-Apply-after-20261011-150449.xml (404,254 bytes)
15:06:23 Apply finished. Expected: router tests True, all three bypass tests False.alias มีรายการหนึ่งที่ผมไม่ได้ตั้งใจใส่ไว้: network ของ interface หนึ่งของ router อยู่ก่อน URL การรันพิมพ์เนื้อหาเดิมออกมาก่อนแทนที่ จึงคืนค่าได้จาก log
เจาะลึก: ชุดทดสอบตรวจอะไร และตรวจอะไรไม่ได้
mock ตอบ path API ที่ script ใช้ เก็บสถานะของ router ไว้ในหน่วยความจำ บันทึกทุกการเรียก และตั้งให้ทำตัวผิดปกติได้: เวอร์ชันผิด, API key ไม่ถูกต้อง, backup ขนาดเล็ก, backup ที่ล้มเหลวหลังมีการเปลี่ยนแปลง, alias ชนิดผิด, คำตอบที่มี key ว่าง, การ save ที่ router ปฏิเสธ, alias ที่ไม่มีข้อมูลเข้ามา, rule ที่เรียงอยู่ใต้ rule allow-all, DoH ที่ยังเข้าถึงได้, HTTPS ปกติใช้ไม่ได้, rule redirect หรือ rule allow-all ที่ไม่มีอยู่, redirect ที่ไม่มีผล และ redirect ที่เปิดอยู่แล้ว มันยังจำลองสถานะที่ router ของผมผ่านมา: alias ที่มีรายการแปลกปลอม, rule สองตัวที่เวอร์ชัน 2.3 ปิดทิ้งไว้ และสถานะที่ apply ทุกอย่างแล้ว คำตอบที่มี key ว่างของมันเขียนด้วยมือ ตามแบบคำตอบ get_item ของ router และตอบบน endpoint ที่ script อ่าน
harness รัน script ครั้งละหนึ่งกรณี เป็น process แยก และตรวจ exit code, log, ไฟล์ backup, ทุกการเรียกที่ mock ได้รับ และสถานะของ mock router ตอนจบ ในทุกกรณี มันตรวจว่าทั้ง secret และ key ที่ encode แล้วไม่ปรากฏใน output หรือ log ว่าไม่มีอะไรถูกลบ และว่าการหยุดหลังเปิด log แล้วถูกเขียนลง log
harness ทดสอบสำเนาของ script ไม่ใช่ตัว script เอง ในสำเนานั้น การทดสอบเครือข่ายสองตัวจะถาม mock แทนอินเทอร์เน็ต และทุกการรอถูกตัดเหลือหนึ่งมิลลิวินาที ก่อนรันกรณีใด ๆ harness ตรวจว่าแต่ละ pattern เหล่านั้น match ตามจำนวนครั้งที่คาดไว้ สำเนานั้นคุยกับ mock ผ่าน HTTP ธรรมดาบน PC ส่วน script ยอมรับ HTTP ธรรมดาเฉพาะ address บน PC เครื่องนั้นเองเท่านั้น
ดังนั้นชุดทดสอบไม่ได้ทดสอบ: การตรวจ certificate และ TLS; การทดสอบเครือข่ายจริง; ความล้มเหลวครั้งที่ 3 เพราะ mock ไม่มี state table และการรอถูกตัดสั้น; คำตอบจาก router จริง ยกเว้นคำตอบ key ว่างที่เขียนด้วยมือหนึ่งตัว; การที่ script ไม่ยอมเขียนทับ backup; ทางสำรองสำหรับโฟลเดอร์ทำงาน เพราะทุกกรณีระบุโฟลเดอร์ไว้; หรือขั้น undo ที่ตัวมันเองล้มเหลว
การทำพังโดยตั้งใจสิบแบบ และกรณีที่แต่ละแบบทำให้ล้มเหลว อยู่ในรายการพร้อมชุดทดสอบท้ายหน้า
เจาะลึก: บันทึกเกี่ยวกับ API ของ OPNsense 26.7
- header ของ script บันทึกว่า path ของ configuration แต่ละตัวนำมาจากหน้าเว็บของ router เองในวันนั้น:
alias/search_item,alias/add_item,alias/set_item,alias/reconfigure,filter/search_rule,filter/add_rule,filter/set_rule,filter/apply,d_nat/search_rule,d_nat/set_rule,d_nat/apply,alias_util/listและcore/backup/download/thisมันยังเรียกcore/firmware/infoเพื่อดูเวอร์ชัน และcore/firmware/statusเพื่อตรวจว่าเข้าถึง router ได้ - endpoint สำหรับค้นหาตอบ GET ที่มี
?rowCount=-1¤t=1และคืนทุกแถว พร้อม field ที่ script ต้องใช้ alias/get_itemคืนรายการตัวเลือกที่มี key ชื่อว่าง ซึ่ง PowerShell แปลงเป็น property ของ object ไม่ได้GET /api/core/backup/download/thisคืน configuration ทั้งหมดเป็น XML- body ของ POST เป็น JSON พร้อม
Content-Type: application/jsonการเปลี่ยน rule มีผลหลังapplyที่คู่กัน การเปลี่ยน alias มีผลหลังreconfigure
อภิธานศัพท์
- Windows PowerShell 5.1: PowerShell ที่มากับ Windows สร้างบน .NET Framework เรียกใช้ด้วย
powershell - PowerShell 7: PowerShell รุ่นใหม่ ติดตั้งแยก สร้างบน .NET รุ่นใหม่ เรียกใช้ด้วย
pwsh - REST API: ชุดของ web address ที่โปรแกรมเรียกเพื่ออ่านหรือเปลี่ยนค่าตั้ง คำตอบของ OPNsense เป็น JSON
- JSON: รูปแบบข้อความสำหรับข้อมูลที่มีโครงสร้าง
- Mock: ตัวแทนของระบบจริงที่ใช้ทดสอบ ในที่นี้คือ web server ขนาดเล็กที่ตอบเหมือน router
- Test harness: script ที่รัน script อีกตัวในสถานการณ์ที่กำหนดไว้หลายแบบ และตรวจผลลัพธ์
- API key: key และ secret ที่ให้ script ทำงานในฐานะ user ของ router โดยไม่ต้องใช้รหัสผ่าน
- Alias (URL table): รายการ address ของ OPNsense ที่ router ดาวน์โหลดจาก web address และ refresh
- NAT redirect: rule ที่เปลี่ยนปลายทางของทราฟฟิกที่ match ในที่นี้ใช้ส่ง query DNS ที่ส่งไปยัง server อื่นกลับมาที่ router
- State table: รายการ connection ที่ firewall เคยเห็นแล้ว packet ถัดไปของ connection ที่รู้จักจะทำตามการตัดสินใจที่ทำไว้กับ packet แรก
- DoH, DoT: DNS over HTTPS (port 443) และ DNS over TLS (port 853) สองวิธีที่อุปกรณ์ใช้ค้นหาชื่อโดยไม่ต้องถาม router
Expect: 100-continue: header ของ HTTP ที่ขอให้ server อนุมัติ request ก่อนส่ง body
The script, the mock router and the test harness
opnsense-dns-bypass.ps1 (version 2.5.1)
<#
opnsense-dns-bypass.ps1 (version 2.5.1, 28/10/2026)
Prepared by Vivek Sanghi with Claude (Anthropic).
Copyright (c) 2026 Vivek Sanghi. MIT licence: see the end of this header.
Built for: OPNsense 26.7 series (amd64). Version 2.4 of this script ran against the author's router
on 11/10/2026. Version 2.5.1 has been tested only against the mock router published with it.
Changes from 2.4:
- the router address is a placeholder you must replace; https is required (plain http is
accepted only for an address on this PC, as the test kit uses)
- Apply stops before changing anything if the NAT rule or the LAN allow rule is not found
- an undo of the alias restores its enabled flag as well as its contents
- messages corrected: the NAT stage says what state it left the redirect in, a failed backup
says whether changes had been made, and every stop after the log file is opened is
written to the log (the checks on -Router and the work folder stop earlier, on screen only)
- the test domain and the NAT wait are settings near the top
- this header: usage, scope and limits, firmware paths, licence
Every API path used here was taken from the router's own web pages on that date:
Aliases page : alias/search_item, alias/add_item, alias/set_item, alias/reconfigure
Rules page : filter/search_rule, filter/add_rule, filter/set_rule, filter/apply
get_item/get_rule are NOT used: their replies contain empty JSON keys ("":), which PowerShell
cannot turn into object properties, so Invoke-RestMethod returns raw text. Checked 11/10/2026.
Destination NAT : d_nat/search_rule, d_nat/set_rule, d_nat/apply
Diagnostics : alias_util/list ; Backups: core/backup/download/this
Also used, not listed in 2.4's header: core/firmware/info (version check), core/firmware/status (reachability).
The script stops before changing anything if the router reports a different OPNsense series.
What it does (Apply):
1. Alias DoH_IPs : URL table, Hagezi DoH IP list, refresh daily (created, or cleaned to the URL only)
2. Rule A : LAN in, reject TCP/UDP to DoH_IPs port 443
3. Rule B : LAN in, reject TCP/UDP to any port 853
4. NAT : "Redirect non-local DNS to Local" (port 53) switched ON (the rule must already exist)
Scope and limits (read before running):
- IPv4 only. Rules A and B are created for IPv4 (ipprotocol inet) and every test uses an IPv4
address. If your LAN has IPv6, DoH and DoT over IPv6 are neither blocked nor tested.
- LAN interface only (interface 'lan'). Other interfaces and VLANs are not covered.
- Rules A and B apply to every host on the LAN. A Pi-hole or AdGuard Home on the LAN that uses
DoH or DoT upstream loses its upstream.
- The NAT rule must already exist (Firewall > NAT > Destination NAT) with the description in
$NatDesc. The script only switches it on or off; it does not create it or check how it is built.
- The alias named in $AliasName is overwritten with the Hagezi URL; its old contents are logged.
- $AdTestDomain must be blocked by your router's DNS blocklist and answered as 0.0.0.0.
- Rollback switches the NAT rule off even if it was on before you first ran Apply.
- The API key acts as an OPNsense user. A root user's key gives full control of the router, to
the script and to anyone who obtains the key. The certificate check accepts any certificate
presented for the router's address, so a LAN device posing as the router would receive the key.
Modes:
-Mode Check (default) Backup, then READ-ONLY report and live tests.
-Mode Apply Backup, check that the NAT rule and the LAN allow rule exist, make the changes and
verify them; on a failure it undoes what this run changed. If only the NAT stage
fails, only the NAT change is undone and it exits with code 2.
-Mode Rollback Backup, then DISABLE rules A and B and the NAT rule. Nothing is deleted.
Files written on this PC (never overwritten):
<WorkDir>\router-backups\config-<mode>-<before|after>-<timestamp>.xml
<WorkDir>\logs\run-<mode>-<timestamp>.log
The API secret is read from -KeyFile and is never printed or logged.
Usage (Windows PowerShell 5.1):
powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router https://<router-ip-address>
Add -Mode Apply or -Mode Rollback to change the router; without -Mode it only checks.
MIT licence
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#>
[CmdletBinding()]
param(
[ValidateSet('Check','Apply','Rollback')]
[string]$Mode = 'Check',
[Parameter(Mandatory = $true)]
[string]$KeyFile,
[string]$Router = 'https://<router-ip-address>',
[string]$WorkDir = $PSScriptRoot
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version 1
$LogFile = $null
# $PSScriptRoot in a param() default can be empty under Windows PowerShell 5.1, so resolve the folder here.
if ([string]::IsNullOrWhiteSpace($WorkDir)) {
if ($MyInvocation.MyCommand.Path) { $WorkDir = Split-Path -Parent $MyInvocation.MyCommand.Path }
else { $WorkDir = (Get-Location).Path }
}
if (-not (Test-Path -LiteralPath $WorkDir -PathType Container)) { Write-Host "Work folder not found: $WorkDir" -ForegroundColor Red; exit 1 }
if ($Router -match '[<>]') { Write-Host "Set -Router to your router's address, for example -Router https://192.168.1.1 . Nothing was done." -ForegroundColor Red; exit 1 }
try { $RouterUri = [Uri]$Router } catch { Write-Host "-Router is not a valid address: $Router . Nothing was done." -ForegroundColor Red; exit 1 }
if ($RouterUri.Scheme -ne 'https' -and -not $RouterUri.IsLoopback) { Write-Host "-Router must start with https:// because the API key goes with every request. Nothing was done." -ForegroundColor Red; exit 1 }
# ---------- fixed settings ----------
$ExpectedSeries = '26.7'
$AliasName = 'DoH_IPs'
$AliasUrl = 'https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt'
$AliasDesc = 'Hagezi DoH resolver IPs'
$DescA = 'Reject DoH to known resolvers (A)'
$DescB = 'Reject DoT/DoQ 853 from LAN (B)'
$NatDesc = 'Redirect non-local DNS to Local'
$AllowLan = 'Default allow LAN to any rule'
$AdTestDomain = 'googleads.g.doubleclick.net' # must be blocked by your router's blocklist (answered as 0.0.0.0)
$NatWaitSeconds = 70 # longer than the router's udp.first / udp.multiple timeouts (Firewall > Diagnostics > Statistics)
$MinAliasIPs = 500
$RuleDefs = @(
@{ description = $DescA; destination_net = $AliasName; destination_port = '443' },
@{ description = $DescB; destination_net = 'any'; destination_port = '853' }
)
# ---------- logging ----------
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$logDir = Join-Path $WorkDir 'logs'
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
$LogFile = Join-Path $logDir ("run-{0}-{1}.log" -f $Mode, $stamp)
function Log([string]$msg, [string]$color = 'Gray') {
$line = '{0} {1}' -f (Get-Date -Format 'HH:mm:ss'), $msg
Write-Host $line -ForegroundColor $color
if ($LogFile) { Add-Content -Path $LogFile -Value $line }
}
function Fail([string]$msg) { Log "STOP: $msg" 'Red'; Log "Log file: $LogFile" 'Red'; exit 1 }
# Any error that no try/catch below handles is written to the log before the script stops.
trap { Log "STOP: $($_.Exception.Message)" 'Red'; Log "Log file: $LogFile" 'Red'; exit 1 }
# ---------- API key ----------
if (-not (Test-Path -LiteralPath $KeyFile)) { Fail "Key file not found: $KeyFile" }
$kv = @{}
foreach ($l in Get-Content -LiteralPath $KeyFile) {
if ($l -match '^\s*(key|secret)\s*=\s*(\S+)\s*$') { $kv[$Matches[1]] = $Matches[2] }
}
if (-not $kv.ContainsKey('key') -or -not $kv.ContainsKey('secret')) { Fail "Key file must contain lines key=... and secret=..." }
$Auth = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($kv['key'] + ':' + $kv['secret']))
$kv = $null
# ---------- TLS: accept the router's self-signed certificate, for the router's address only ----------
$IsPS7 = $PSVersionTable.PSVersion.Major -ge 6
if (-not $IsPS7) {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Windows PowerShell 5.1 adds 'Expect: 100-continue' to POSTs; switch it off so the router's web server gets a plain request.
[Net.ServicePointManager]::Expect100Continue = $false
if (-not ('RouterCertTrust' -as [type])) {
Add-Type -TypeDefinition @"
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public static class RouterCertTrust {
public static string Host;
public static bool Check(object sender, X509Certificate c, X509Chain ch, SslPolicyErrors e) {
if (e == SslPolicyErrors.None) return true;
HttpWebRequest r = sender as HttpWebRequest;
return r != null && r.RequestUri.Host == Host;
}
public static void Enable(string host) {
Host = host;
ServicePointManager.ServerCertificateValidationCallback = Check;
}
}
"@
}
[RouterCertTrust]::Enable(([Uri]$Router).Host)
}
# ---------- API helper ----------
function Api([string]$Method, [string]$Path, $Body = $null) {
$p = @{ Uri = $Router + $Path; Method = $Method; Headers = @{ Authorization = $Auth }; TimeoutSec = 60 }
if ($Method -eq 'POST') {
if ($null -eq $Body) { $p.Body = '{}' } else { $p.Body = ($Body | ConvertTo-Json -Depth 10 -Compress) }
$p.ContentType = 'application/json'
}
if ($IsPS7) { $p.SkipCertificateCheck = $true }
$r = Invoke-RestMethod @p
if ($r -is [string]) {
$t = $r.TrimStart()
if ($t.StartsWith('{') -or $t.StartsWith('[')) { throw "Router reply to $Path could not be read as JSON by this PowerShell; stopping." }
}
return $r
}
function Assert-Saved($resp, [string]$what) {
# The router's own GUI (opnsense_ui.js) treats a reply carrying 'validations' as a failure.
# A reply with result 'failed' is also a failure. Every save is additionally verified by reading state back.
$names = @()
if ($resp) { $names = @($resp.PSObject.Properties.Name) }
$bad = (-not $resp) -or ($names -contains 'validations') -or (($names -contains 'result') -and "$($resp.result)" -eq 'failed')
if ($bad) { throw "$what was not saved. Router replied: $($resp | ConvertTo-Json -Compress -Depth 6)" }
}
# ---------- live tests from this PC ----------
function Test-Tcp([string]$TargetHost, [int]$Port, [int]$Ms = 4000) {
$c = New-Object Net.Sockets.TcpClient
try {
$t = $c.ConnectAsync($TargetHost, $Port)
if ($t.Wait($Ms)) { return $c.Connected } else { return $false }
} catch { return $false } finally { $c.Dispose() }
}
function Get-ARecords([string]$Name, [string]$Server) {
try {
$a = Resolve-DnsName -Name $Name -Server $Server -Type A -DnsOnly -QuickTimeout -ErrorAction Stop
return @($a | Where-Object { $_.Type -eq 'A' } | ForEach-Object { $_.IPAddress })
} catch { return @() }
}
function Test-Leaks([string]$Server) {
# $true if $Server hands out a real address for $AdTestDomain, which your blocklist blocks
$ips = Get-ARecords $AdTestDomain $Server
return (@($ips | Where-Object { $_ -ne '0.0.0.0' }).Count -gt 0)
}
function Show-Tests {
$routerHost = ([Uri]$Router).Host
$r = [ordered]@{
RouterResolves = (@(Get-ARecords 'example.com' $routerHost).Count -gt 0)
RouterBlocks = (-not (Test-Leaks $routerHost))
DoH443Open = (Test-Tcp '1.1.1.1' 443)
DoT853Open = (Test-Tcp '9.9.9.9' 853)
Google53Leaks = (Test-Leaks '8.8.8.8')
}
Log ("Router resolves example.com : {0} (want True)" -f $r.RouterResolves)
Log ("Router blocks the ad domain (blocklist) : {0} (want True)" -f $r.RouterBlocks)
Log ("Bypass DoH 1.1.1.1:443 reachable : {0} (want False after Apply)" -f $r.DoH443Open)
Log ("Bypass DoT 9.9.9.9:853 reachable : {0} (want False after Apply)" -f $r.DoT853Open)
Log ("Bypass 8.8.8.8 gives real ad IPs : {0} (want False after Apply)" -f $r.Google53Leaks)
return $r
}
# ---------- router state ----------
function Get-State {
$aliases = Api GET '/api/firewall/alias/search_item?rowCount=-1¤t=1'
$alias = @($aliases.rows | Where-Object { $_.name -eq $AliasName }) | Select-Object -First 1
$rules = Api GET '/api/firewall/filter/search_rule?rowCount=-1¤t=1'
$mvc = @($rules.rows | Where-Object { -not (($_.PSObject.Properties.Name -contains 'legacy') -and $_.legacy) })
$ruleA = @($mvc | Where-Object { $_.description -eq $DescA }) | Select-Object -First 1
$ruleB = @($mvc | Where-Object { $_.description -eq $DescB }) | Select-Object -First 1
$allow = @($rules.rows | Where-Object { $_.description -eq $AllowLan }) | Select-Object -First 1
$nats = Api GET '/api/firewall/d_nat/search_rule?rowCount=-1¤t=1'
$nat = @($nats.rows | Where-Object { $_.descr -eq $NatDesc }) | Select-Object -First 1
$count = 0
if ($alias) { try { $count = [int](Api GET "/api/firewall/alias_util/list/$AliasName").total } catch { $count = 0 } }
return [pscustomobject]@{ Alias = $alias; AliasCount = $count; RuleA = $ruleA; RuleB = $ruleB; Allow = $allow; Nat = $nat }
}
function Show-State($s) {
if ($s.Alias) {
$c = ("$($s.Alias.content)" -replace "`r?`n", ' | ')
Log ("Alias {0}: present, enabled={1}, entries loaded={2}, content=[{3}]" -f $AliasName, $s.Alias.enabled, $s.AliasCount, $c)
} else { Log ("Alias {0}: not present" -f $AliasName) }
foreach ($pair in @(@('Rule A', $s.RuleA), @('Rule B', $s.RuleB))) {
$r = $pair[1]
if ($r) { Log ("{0}: present, enabled={1}, sort_order={2}" -f $pair[0], $r.enabled, $r.sort_order) }
else { Log ("{0}: not present" -f $pair[0]) }
}
if ($s.Allow) { Log ("'{0}': sort_order={1}" -f $AllowLan, $s.Allow.sort_order) }
if ($s.Nat) { Log ("NAT '{0}': disabled={1}" -f $NatDesc, $s.Nat.disabled) }
else { Log ("NAT '{0}': NOT FOUND" -f $NatDesc) 'Yellow' }
}
# ---------- backup ----------
function Save-Backup([string]$when) {
$dir = Join-Path $WorkDir 'router-backups'
New-Item -ItemType Directory -Force -Path $dir | Out-Null
$file = Join-Path $dir ("config-{0}-{1}-{2}.xml" -f $Mode, $when, $stamp)
if (Test-Path -LiteralPath $file) { Fail "Backup file already exists, refusing to overwrite: $file" }
$p = @{ Uri = "$Router/api/core/backup/download/this"; Method = 'GET'; Headers = @{ Authorization = $Auth }; OutFile = $file; UseBasicParsing = $true; TimeoutSec = 60 }
if ($IsPS7) { $p.SkipCertificateCheck = $true }
Invoke-WebRequest @p | Out-Null
$size = (Get-Item -LiteralPath $file).Length
$head = (Get-Content -LiteralPath $file -TotalCount 3) -join ' '
if ($size -lt 50000 -or $head -notmatch '<opnsense>') {
if ($when -eq 'before') { Fail "Backup looks wrong ($size bytes): $file. Nothing changed on the router." }
Fail "Backup ($when) looks wrong ($size bytes): $file. The changes logged above were made; check the router."
}
Log ("Backup ({0}) saved: {1} ({2:N0} bytes)" -f $when, $file, $size) 'Green'
}
# ================= START =================
Log "Mode: $Mode Router: $Router PowerShell $($PSVersionTable.PSVersion)"
try { $info = Api GET '/api/core/firmware/info' } catch { Fail "Cannot reach the router API with this key: $($_.Exception.Message)" }
$series = "$($info.product.product_series)"
Log ("Router reports: {0} series {1}, {2}" -f $info.product.product_name, $series, $info.product.product_arch)
if ($series -ne $ExpectedSeries) { Fail "Script was built for OPNsense $ExpectedSeries; router reports $series. Nothing changed. Check the API paths against your router's own web pages before changing ExpectedSeries." }
# Backup next (after the version check), in every mode, before any configuration is read or changed.
Save-Backup 'before'
$state = Get-State
Show-State $state
$tests = Show-Tests
# Apply needs both of these before it changes anything; Check reports them.
$problems = @()
if (-not $state.Nat) { $problems += "NAT rule '$NatDesc' not found. Create it in Firewall > NAT > Destination NAT, or set `$NatDesc to its description." }
if (-not $state.Allow) { $problems += "Rule '$AllowLan' not found, so rule order cannot be checked. Set `$AllowLan to the description of your LAN allow-all rule." }
if ($Mode -eq 'Check') {
foreach ($p in $problems) { Log "Apply would stop: $p" 'Yellow' }
Log 'Check mode: nothing was changed on the router.' 'Green'; Log "Log file: $LogFile"; exit 0
}
if ($Mode -eq 'Apply' -and $problems.Count -gt 0) { Fail (($problems -join ' ') + ' Nothing changed.') }
# ---------- undo bookkeeping ----------
$Undo = New-Object System.Collections.ArrayList
function Invoke-Undo {
if ($Undo.Count -eq 0) { Log 'Nothing to undo.'; return }
Log 'Undoing changes made in this run...' 'Yellow'
for ($i = $Undo.Count - 1; $i -ge 0; $i--) {
$u = $Undo[$i]
try {
switch ($u.kind) {
'rule' { $null = Api POST "/api/firewall/filter/set_rule/$($u.uuid)" @{ rule = @{ enabled = '0' } }; $null = Api POST '/api/firewall/filter/apply'; Log " rule $($u.uuid) disabled" 'Yellow' }
'nat' { $null = Api POST "/api/firewall/d_nat/set_rule/$($u.uuid)" @{ rule = @{ disabled = '1' } }; $null = Api POST '/api/firewall/d_nat/apply'; Log ' NAT rule switched back off' 'Yellow' }
'aliascontent' { $null = Api POST "/api/firewall/alias/set_item/$($u.uuid)" @{ alias = @{ content = $u.old; enabled = $u.oldEnabled } }; $null = Api POST '/api/firewall/alias/reconfigure'; Log ' alias content and enabled flag restored (refresh interval left at 1 day)' 'Yellow' }
'aliasnew' { $null = Api POST "/api/firewall/alias/set_item/$($u.uuid)" @{ alias = @{ enabled = '0' } }; $null = Api POST '/api/firewall/alias/reconfigure'; Log ' new alias disabled' 'Yellow' }
}
} catch { Log " UNDO STEP FAILED ($($u.kind)): $($_.Exception.Message). Restore the 'before' backup from System > Configuration > Backups." 'Red' }
}
}
# ================= ROLLBACK =================
if ($Mode -eq 'Rollback') {
try {
$changed = $false
foreach ($r in @($state.RuleA, $state.RuleB)) {
if ($r -and "$($r.enabled)" -eq '1') {
Assert-Saved (Api POST "/api/firewall/filter/set_rule/$($r.uuid)" @{ rule = @{ enabled = '0' } }) "Disable rule '$($r.description)'"
Log "Disabled rule '$($r.description)'" 'Yellow'; $changed = $true
}
}
if ($changed) { $null = Api POST '/api/firewall/filter/apply'; Log 'Firewall rules applied.' }
if ($state.Nat -and "$($state.Nat.disabled)" -ne '1') {
Assert-Saved (Api POST "/api/firewall/d_nat/set_rule/$($state.Nat.uuid)" @{ rule = @{ disabled = '1' } }) 'Disable NAT rule'
$null = Api POST '/api/firewall/d_nat/apply'
Log "Disabled NAT rule '$NatDesc' and applied." 'Yellow'
}
} catch { Fail "Rollback error: $($_.Exception.Message)" }
Start-Sleep -Seconds 3
Show-State (Get-State); $null = Show-Tests
Save-Backup 'after'
Log 'Rollback finished.' 'Green'; Log "Log file: $LogFile"; exit 0
}
# ================= APPLY =================
if (-not $tests.RouterResolves) { Fail 'The router itself is not resolving example.com. Fix that first; nothing changed.' }
try {
# ---- 1. Alias ----
if (-not $state.Alias) {
$body = @{ alias = @{ enabled = '1'; name = $AliasName; type = 'urltable'; updatefreq = '1'; content = $AliasUrl; description = $AliasDesc } }
$r = Api POST '/api/firewall/alias/add_item' $body
Assert-Saved $r "Alias $AliasName"
$newId = "$($r.uuid)"
if (-not $newId) { $newId = "$((@((Api GET '/api/firewall/alias/search_item?rowCount=-1¤t=1').rows | Where-Object { $_.name -eq $AliasName }) | Select-Object -First 1).uuid)" }
[void]$Undo.Add(@{ kind = 'aliasnew'; uuid = $newId })
Log "Alias $AliasName created." 'Green'
} else {
$uuid = "$($state.Alias.uuid)"
$oldContent = ("$($state.Alias.content)" -replace "`r`n", "`n").Trim()
if ("$($state.Alias.type)" -ne 'urltable') { throw "Existing alias $AliasName is type '$($state.Alias.type)', not urltable. Fix or delete it in the GUI, then rerun." }
if ($oldContent -ne $AliasUrl -or "$($state.Alias.enabled)" -ne '1') {
Assert-Saved (Api POST "/api/firewall/alias/set_item/$uuid" @{ alias = @{ enabled = '1'; content = $AliasUrl; updatefreq = '1' } }) "Clean alias $AliasName"
[void]$Undo.Add(@{ kind = 'aliascontent'; uuid = $uuid; old = $oldContent; oldEnabled = "$($state.Alias.enabled)" })
Log ("Alias {0} set to the URL only (was: {1})." -f $AliasName, ($oldContent -replace "`r?`n", ' | ')) 'Green'
} else { Log "Alias $AliasName already correct." }
}
$null = Api POST '/api/firewall/alias/reconfigure'
$nowRow = @((Api GET '/api/firewall/alias/search_item?rowCount=-1¤t=1').rows | Where-Object { $_.name -eq $AliasName }) | Select-Object -First 1
if (-not $nowRow) { throw "Alias $AliasName not found after saving." }
$nowContent = ("$($nowRow.content)" -replace "`r`n", "`n").Trim()
if ($nowContent -ne $AliasUrl) { throw "Alias $AliasName content reads back as [$($nowContent -replace "`r?`n", ' | ')], not the URL alone." }
$count = 0
for ($i = 0; $i -lt 18; $i++) {
try { $count = [int](Api GET "/api/firewall/alias_util/list/$AliasName").total } catch { $count = 0 }
if ($count -ge $MinAliasIPs) { break }
Start-Sleep -Seconds 5
}
if ($count -lt $MinAliasIPs) { throw "Alias $AliasName loaded only $count entries after 90 s." }
Log "Alias $AliasName holds $count addresses." 'Green'
# ---- 2. Rules A and B ----
$current = @{ $DescA = $state.RuleA; $DescB = $state.RuleB }
foreach ($d in $RuleDefs) {
$existing = $current[$d.description]
if (-not $existing) {
$body = @{ rule = @{
enabled = '1'; action = 'reject'; quick = '1'; interface = 'lan'; direction = 'in'
ipprotocol = 'inet'; protocol = 'TCP/UDP'; source_net = 'any'
destination_net = $d.destination_net; destination_port = $d.destination_port
log = '1'; description = $d.description } }
$r = Api POST '/api/firewall/filter/add_rule' $body
Assert-Saved $r "Rule '$($d.description)'"
$newId = "$($r.uuid)"
if (-not $newId) { $newId = "$((@((Api GET '/api/firewall/filter/search_rule?rowCount=-1¤t=1').rows | Where-Object { $_.description -eq $d.description }) | Select-Object -First 1).uuid)" }
if (-not $newId) { throw "Rule '$($d.description)' saved but its id could not be found; stopping before apply." }
[void]$Undo.Add(@{ kind = 'rule'; uuid = $newId })
Log "Rule '$($d.description)' added." 'Green'
} elseif ("$($existing.enabled)" -ne '1') {
Assert-Saved (Api POST "/api/firewall/filter/set_rule/$($existing.uuid)" @{ rule = @{ enabled = '1' } }) "Enable rule '$($d.description)'"
[void]$Undo.Add(@{ kind = 'rule'; uuid = $existing.uuid })
Log "Rule '$($d.description)' enabled." 'Green'
} else { Log "Rule '$($d.description)' already present and enabled." }
}
$null = Api POST '/api/firewall/filter/apply'
Log 'Firewall rules applied. Verifying...' 'Cyan'
Start-Sleep -Seconds 5
$after = Get-State
foreach ($r in @($after.RuleA, $after.RuleB)) {
if (-not $r) { throw 'A rule is missing after apply.' }
if (-not $after.Allow) { throw "Rule '$AllowLan' not found after apply." }
if ([double]"$($r.sort_order)" -ge [double]"$($after.Allow.sort_order)") {
throw ("'{0}' sorts after '{1}' ({2} vs {3}) and would never match." -f $r.description, $AllowLan, $r.sort_order, $after.Allow.sort_order)
}
}
try { $null = Api GET '/api/core/firmware/status' } catch { throw 'Router API not reachable after apply.' }
if (-not (Test-Tcp 'www.google.com' 443)) { throw 'Ordinary HTTPS to www.google.com failed after apply.' }
if (Test-Tcp '1.1.1.1' 443) { throw 'DoH to 1.1.1.1:443 is still reachable.' }
if (Test-Tcp '9.9.9.9' 853) { throw 'DoT to 9.9.9.9:853 is still reachable.' }
Log 'Rules A and B verified: DoH and DoT refused, normal HTTPS works.' 'Green'
}
catch {
Log "Problem: $($_.Exception.Message)" 'Red'
Invoke-Undo
Show-State (Get-State)
Save-Backup 'after-undo'
Fail 'Apply did not complete; changes from this run were undone.'
}
# ---- 3. NAT rule (separate stage: if it fails, only the NAT change is undone; alias and rules A/B stay) ----
$natUndoFrom = $Undo.Count
$natOk = $true
$nat = $null
$natWaited = $false
$natEnd = ''
try {
$nat = (Get-State).Nat
if (-not $nat) { throw "NAT rule '$NatDesc' not found." }
if ("$($nat.disabled)" -eq '1') {
Assert-Saved (Api POST "/api/firewall/d_nat/set_rule/$($nat.uuid)" @{ rule = @{ disabled = '0' } }) 'Enable NAT rule'
[void]$Undo.Add(@{ kind = 'nat'; uuid = $nat.uuid })
$null = Api POST '/api/firewall/d_nat/apply'
$chk = @($((Api GET '/api/firewall/d_nat/search_rule?rowCount=-1¤t=1').rows) | Where-Object { $_.uuid -eq $nat.uuid }) | Select-Object -First 1
if ("$($chk.disabled)" -ne '0') { throw "Router still shows the NAT rule disabled (disabled=$($chk.disabled))." }
# A redirect applies only to NEW connections. A DNS query that matches a state opened before the
# redirect (this script's own test query, or a device that keeps reusing one source port) still goes
# to 8.8.8.8 until that state expires. The author's router reported udp.first/udp.multiple = 60s, udp.single = 30s
# (Firewall > Diagnostics > Statistics, read 11/10/2026). Wait them out with no queries to 8.8.8.8.
Log ("NAT rule enabled and applied. Waiting {0} s for older DNS states to expire before testing..." -f $NatWaitSeconds) 'Cyan'
Start-Sleep -Seconds $NatWaitSeconds
$natWaited = $true
} else { Log 'NAT rule already enabled. Testing it...' }
if (@(Get-ARecords 'example.com' '8.8.8.8').Count -eq 0) { throw 'example.com no longer resolves through 8.8.8.8 after the redirect.' }
$waitNote = ''
if ($natWaited) { $waitNote = " after $NatWaitSeconds s" }
if (Test-Leaks '8.8.8.8') { throw "8.8.8.8 still returns real ad addresses$waitNote; the redirect is not taking effect." }
Log 'NAT redirect verified: queries to 8.8.8.8 are answered by your router.' 'Green'
}
catch {
$natOk = $false
Log "Problem (NAT stage): $($_.Exception.Message)" 'Red'
if ($Undo.Count -gt $natUndoFrom) {
$u = $Undo[$Undo.Count - 1]
try {
$null = Api POST "/api/firewall/d_nat/set_rule/$($u.uuid)" @{ rule = @{ disabled = '1' } }
$null = Api POST '/api/firewall/d_nat/apply'
Log ' NAT rule switched back off. Alias and rules A/B are kept: they passed their checks.' 'Yellow'
$natEnd = 'This run switched it on and has switched it off again.'
} catch {
Log " UNDO OF NAT FAILED: $($_.Exception.Message). Switch it off in Firewall > NAT > Destination NAT." 'Red'
$natEnd = 'This run switched it on and could not switch it off again: switch it off in Firewall > NAT > Destination NAT.'
}
} elseif ($nat -and "$($nat.disabled)" -ne '1') {
$natEnd = 'It was already on before this run and is left on: check it in Firewall > NAT > Destination NAT.'
} else {
$natEnd = 'It is still off.'
}
}
Show-State (Get-State)
$null = Show-Tests
Save-Backup 'after'
if ($natOk) {
Log 'Apply finished. Expected: router tests True, all three bypass tests False.' 'Green'
Log "Log file: $LogFile"
} else {
Log ('Apply PARTLY finished: alias and rules A/B are in place and verified; the NAT redirect did not pass. ' + $natEnd) 'Yellow'
Log "Log file: $LogFile"
exit 2
}
mock-opnsense.ps1
<#
mock-opnsense.ps1 (v2) - a stand-in for the OPNsense 26.7 API, for testing opnsense-dns-bypass.ps1
Prepared by Vivek Sanghi with Claude (Anthropic). Copyright (c) 2026 Vivek Sanghi. MIT licence (see opnsense-dns-bypass.ps1).
Runs on Windows PowerShell 5.1 and PowerShell 7. Listens on 127.0.0.1 only. Writes no files.
It answers the API paths the script uses, keeps the router's state in memory, and records every call.
Test-only paths (not part of OPNsense):
POST /__test/reset {"scenario":"name"} start a scenario with fresh state
GET /__test/state the current state
GET /__test/calls every call received since the last reset
GET /__test/tcp?h=host&p=port mocked "can this PC reach host:port?"
GET /__test/dns?n=name&s=server mocked DNS answer from that server
GET /__test/ping liveness
POST /__test/stop stop the mock
#>
param([int]$Port = 18443)
$ErrorActionPreference = 'Stop'
$Url = 'https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt'
$DescA = 'Reject DoH to known resolvers (A)'
$DescB = 'Reject DoT/DoQ 853 from LAN (B)'
$GoodAuth = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes('testkey:testsecret'))
$AdReal = '142.250.183.2'
$ExampleIp = '93.184.215.14'
function New-State([string]$scenario) {
$s = @{
scenario = $scenario; series = '26.7'; nextId = 1
alias = @{ uuid = 'alias-1'; name = 'DoH_IPs'; type = 'urltable'; content = "__lan_network`n$Url"; enabled = '1'; loaded = 1434 }
rules = New-Object System.Collections.ArrayList
allow = @{ uuid = 'allow-1'; description = 'Default allow LAN to any rule'; sort_order = '400000.1000023'; enabled = '1' }
nat = @{ uuid = 'nat-1'; descr = 'Redirect non-local DNS to Local'; disabled = '1' }
natLive = $false
backups = 0
calls = New-Object System.Collections.ArrayList
}
switch ($scenario) {
'version-mismatch' { $s.series = '26.1' }
'alias-wrong-type' { $s.alias.type = 'host' }
'fresh-alias' { $s.alias = $null }
'fresh-alias-doh-open' { $s.alias = $null }
'nat-missing' { $s.nat = $null }
'allow-missing' { $s.allow = $null }
'nat-already-on-ineffective' { $s.nat.disabled = '0'; $s.natLive = $true }
'alias-disabled-doh-open' { $s.alias.enabled = '0' }
'already-applied' {
$s.alias.content = $Url
[void]$s.rules.Add(@{ uuid = 'rule-a'; description = $DescA; enabled = '1'; live = '1'; sort_order = '400000.0000100' })
[void]$s.rules.Add(@{ uuid = 'rule-b'; description = $DescB; enabled = '1'; live = '1'; sort_order = '400000.0000200' })
$s.nat.disabled = '0'; $s.natLive = $true
}
'left-disabled' {
# what version 2.3's undo left on the real router: both rules present, disabled
[void]$s.rules.Add(@{ uuid = 'rule-a'; description = $DescA; enabled = '0'; live = '0'; sort_order = '400000.0000100' })
[void]$s.rules.Add(@{ uuid = 'rule-b'; description = $DescB; enabled = '0'; live = '0'; sort_order = '400000.0000200' })
}
}
return $s
}
$S = New-State 'default'
function Find-Rule([string]$desc) { foreach ($r in $S.rules) { if ($r.description -eq $desc) { return $r } }; return $null }
function Find-RuleById([string]$id) { foreach ($r in $S.rules) { if ($r.uuid -eq $id) { return $r } }; return $null }
function Json($o) { return (ConvertTo-Json -InputObject $o -Depth 10 -Compress) }
function Saved($extra) { $o = @{ result = 'saved' }; if ($extra) { foreach ($k in $extra.Keys) { $o[$k] = $extra[$k] } }; return (Json $o) }
function Invalid([string]$field) { return (Json @{ result = 'failed'; validations = @{ $field = 'Mock validation error.' } }) }
function Get-Query([string]$q) {
$h = @{}
foreach ($pair in ($q -split '&')) {
if ($pair -match '^([^=]+)=(.*)$') { $h[$Matches[1]] = [Uri]::UnescapeDataString($Matches[2]) }
}
return $h
}
function Alias-Row {
$a = $S.alias
return @{ uuid = $a.uuid; name = $a.name; type = $a.type; content = $a.content; enabled = $a.enabled; description = 'mock' }
}
function Handle([string]$method, [string]$path, [string]$query, [string]$body, [string]$auth) {
# returns @(status, contentType, body)
if ($path -like '/__test/*') {
switch ("$method $path") {
'GET /__test/ping' { return @(200, 'application/json', '{"ok":true}') }
'POST /__test/reset' {
$sc = 'default'
if ($body) { $j = ConvertFrom-Json $body; if ($j.scenario) { $sc = "$($j.scenario)" } }
$script:S = New-State $sc
return @(200, 'application/json', (Json @{ ok = $true; scenario = $sc }))
}
'GET /__test/state' {
$o = @{ scenario = $S.scenario; alias = $S.alias; rules = @($S.rules); nat = $S.nat; natLive = $S.natLive }
return @(200, 'application/json', (Json $o))
}
'GET /__test/calls' { return @(200, 'application/json', (Json @{ calls = @($S.calls) })) }
'GET /__test/tcp' {
$q = Get-Query $query; $hostPort = "$($q.h):$($q.p)"
$ruleA = Find-Rule $DescA; $ruleB = Find-Rule $DescB
$aliasOk = ($S.alias -ne $null) -and ($S.alias.loaded -ge 500) -and ($S.alias.enabled -eq '1')
$open = $true
switch ($hostPort) {
'1.1.1.1:443' { if ($ruleA -and $ruleA.live -eq '1' -and $aliasOk -and $S.scenario -notlike '*doh-open*') { $open = $false } }
'9.9.9.9:853' { if ($ruleB -and $ruleB.live -eq '1') { $open = $false } }
'www.google.com:443' { if ($S.scenario -eq 'https-broken' -and $ruleA -and $ruleA.live -eq '1') { $open = $false } }
}
return @(200, 'application/json', (Json @{ open = $open }))
}
'GET /__test/dns' {
$q = Get-Query $query; $ips = @()
$isAd = ($q.n -eq 'googleads.g.doubleclick.net')
if ($q.s -eq '8.8.8.8') {
$redirected = $S.natLive -and ($S.scenario -notlike '*ineffective*')
if ($isAd) { if ($redirected) { $ips = @('0.0.0.0') } else { $ips = @($AdReal) } }
elseif ($q.n -eq 'example.com') { $ips = @($ExampleIp) }
} else {
# the router itself
if ($isAd) { $ips = @('0.0.0.0') } elseif ($q.n -eq 'example.com') { $ips = @($ExampleIp) }
}
return @(200, 'application/json', (Json @{ ips = $ips }))
}
'POST /__test/stop' { $script:Running = $false; return @(200, 'application/json', '{"ok":true}') }
}
return @(404, 'application/json', '{"error":"unknown test path"}')
}
[void]$S.calls.Add(@{ method = $method; path = $path; body = $body })
if ($auth -ne $GoodAuth) { return @(401, 'application/json', '{"status":401,"message":"Authentication Failed"}') }
switch -Regex ("$method $path") {
'^GET /api/core/firmware/info$' {
return @(200, 'application/json', (Json @{ product = @{ product_name = 'OPNsense'; product_series = $S.series; product_arch = 'amd64' } }))
}
'^GET /api/core/firmware/status$' { return @(200, 'application/json', '{"status":"ok"}') }
'^GET /api/core/backup/download/this$' {
$S.backups++
if ($S.scenario -eq 'small-backup' -or ($S.scenario -eq 'small-backup-after' -and $S.backups -gt 1)) { return @(200, 'application/xml', '<?xml version="1.0"?><error/>') }
$pad = 'x' * 60000
return @(200, 'application/xml', "<?xml version=`"1.0`"?>`n<opnsense>`n<!-- mock $pad -->`n</opnsense>`n")
}
'^GET /api/firewall/alias/search_item$' {
if ($S.scenario -eq 'empty-key-reply') {
# a reply carrying an empty JSON key, as alias/get_item does on a real router
return @(200, 'application/json', '{"rows":[{"uuid":"alias-1","name":"DoH_IPs","type":{"":{"value":"","selected":0},"urltable":{"value":"URL Table","selected":1}},"content":"x","enabled":"1"}],"total":1}')
}
$rows = @(); if ($S.alias) { $rows = @(Alias-Row) }
return @(200, 'application/json', (Json @{ rows = $rows; total = $rows.Count }))
}
'^GET /api/firewall/alias_util/list/DoH_IPs$' {
$n = 0; if ($S.alias) { $n = $S.alias.loaded }
return @(200, 'application/json', (Json @{ total = $n; rows = @() }))
}
'^POST /api/firewall/alias/add_item$' {
if ($S.scenario -eq 'alias-validation') { return @(200, 'application/json', (Invalid 'alias.name')) }
$j = (ConvertFrom-Json $body).alias
$S.alias = @{ uuid = 'alias-new'; name = "$($j.name)"; type = "$($j.type)"; content = "$($j.content)"; enabled = "$($j.enabled)"; loaded = 0 }
return @(200, 'application/json', (Saved @{ uuid = 'alias-new' }))
}
'^POST /api/firewall/alias/set_item/(.+)$' {
if ($S.scenario -eq 'alias-validation') { return @(200, 'application/json', (Invalid 'alias.content')) }
$j = (ConvertFrom-Json $body).alias
foreach ($p in $j.PSObject.Properties) { if ($p.Name -ne 'updatefreq') { $S.alias[$p.Name] = "$($p.Value)" } }
return @(200, 'application/json', (Saved $null))
}
'^POST /api/firewall/alias/reconfigure$' {
if ($S.alias) {
$ok = ($S.alias.enabled -eq '1') -and (("$($S.alias.content)" -replace "`r", '').Trim() -eq $Url)
if ($ok) { if ($S.scenario -eq 'alias-not-filling') { $S.alias.loaded = 12 } else { $S.alias.loaded = 1434 } }
}
return @(200, 'application/json', '{"status":"ok"}')
}
'^GET /api/firewall/filter/search_rule$' {
$rows = @()
foreach ($r in $S.rules) { $rows += @{ uuid = $r.uuid; description = $r.description; enabled = $r.enabled; sort_order = $r.sort_order } }
if ($S.allow) { $rows += @{ uuid = $S.allow.uuid; description = $S.allow.description; enabled = '1'; sort_order = $S.allow.sort_order } }
return @(200, 'application/json', (Json @{ rows = $rows; total = $rows.Count }))
}
'^POST /api/firewall/filter/add_rule$' {
$j = (ConvertFrom-Json $body).rule
if ($S.scenario -eq 'rule-validation' -and "$($j.description)" -eq $DescB) { return @(200, 'application/json', (Invalid 'rule.destination_port')) }
$S.nextId++
$id = "rule-new-$($S.nextId)"
$base = '400000.00001'; if ($S.scenario -eq 'rule-order') { $base = '500000.00001' }
[void]$S.rules.Add(@{ uuid = $id; description = "$($j.description)"; enabled = "$($j.enabled)"; live = '0'; sort_order = ('{0}{1:00}' -f $base, $S.rules.Count) })
return @(200, 'application/json', (Saved @{ uuid = $id }))
}
'^POST /api/firewall/filter/set_rule/(.+)$' {
$r = Find-RuleById $Matches[1]
if (-not $r) { return @(200, 'application/json', (Invalid 'rule.uuid')) }
$j = (ConvertFrom-Json $body).rule
if ($j.PSObject.Properties.Name -contains 'enabled') { $r.enabled = "$($j.enabled)" }
return @(200, 'application/json', (Saved $null))
}
'^POST /api/firewall/filter/apply$' {
foreach ($r in $S.rules) { $r.live = $r.enabled }
return @(200, 'application/json', '{"status":"OK"}')
}
'^GET /api/firewall/d_nat/search_rule$' {
$rows = @(); if ($S.nat) { $rows = @(@{ uuid = $S.nat.uuid; descr = $S.nat.descr; disabled = $S.nat.disabled }) }
return @(200, 'application/json', (Json @{ rows = $rows; total = $rows.Count }))
}
'^POST /api/firewall/d_nat/set_rule/(.+)$' {
if (-not $S.nat -or $Matches[1] -ne $S.nat.uuid) { return @(200, 'application/json', (Invalid 'rule.uuid')) }
$j = (ConvertFrom-Json $body).rule
if ($S.scenario -eq 'nat-validation' -and "$($j.disabled)" -eq '0') { return @(200, 'application/json', (Invalid 'rule.target')) }
if ($j.PSObject.Properties.Name -contains 'disabled') { $S.nat.disabled = "$($j.disabled)" }
return @(200, 'application/json', (Saved $null))
}
'^POST /api/firewall/d_nat/apply$' {
$S.natLive = ($S.nat -ne $null) -and ($S.nat.disabled -eq '0')
return @(200, 'application/json', '{"status":"OK"}')
}
}
return @(404, 'application/json', '{"errorMessage":"Endpoint not found"}')
}
# ---------- minimal HTTP/1.1 server on 127.0.0.1 ----------
$listener = New-Object System.Net.Sockets.TcpListener([Net.IPAddress]::Loopback, $Port)
$listener.Start()
Write-Host "mock-opnsense listening on http://127.0.0.1:$Port"
$script:Running = $true
$enc = New-Object System.Text.UTF8Encoding($false)
while ($script:Running) {
$client = $listener.AcceptTcpClient()
try {
$stream = $client.GetStream()
$reader = New-Object System.IO.StreamReader($stream, $enc, $false, 65536, $true)
$first = $reader.ReadLine()
if (-not $first) { continue }
$parts = $first -split ' '
$method = $parts[0]; $target = $parts[1]
$headers = @{}
while ($true) {
$line = $reader.ReadLine()
if ([string]::IsNullOrEmpty($line)) { break }
$i = $line.IndexOf(':')
if ($i -gt 0) { $headers[$line.Substring(0, $i).Trim().ToLowerInvariant()] = $line.Substring($i + 1).Trim() }
}
if ($headers.ContainsKey('expect') -and $headers['expect'] -match '100-continue') {
$c = $enc.GetBytes("HTTP/1.1 100 Continue`r`n`r`n"); $stream.Write($c, 0, $c.Length); $stream.Flush()
}
$body = ''
if ($headers.ContainsKey('content-length')) {
$len = [int]$headers['content-length']
if ($len -gt 0) { $buf = New-Object char[] $len; $got = 0; while ($got -lt $len) { $n = $reader.Read($buf, $got, $len - $got); if ($n -le 0) { break }; $got += $n }; $body = New-Object System.String -ArgumentList $buf, 0, $got }
}
$path = $target; $query = ''
$q = $target.IndexOf('?'); if ($q -ge 0) { $path = $target.Substring(0, $q); $query = $target.Substring($q + 1) }
$auth = ''; if ($headers.ContainsKey('authorization')) { $auth = $headers['authorization'] }
try { $res = Handle $method $path $query $body $auth }
catch { $res = @(500, 'application/json', (ConvertTo-Json -InputObject @{ mockError = "$($_.Exception.Message)" } -Compress)) }
$status = $res[0]
$reason = @{ 200 = 'OK'; 401 = 'Unauthorized'; 404 = 'Not Found'; 500 = 'Internal Server Error' }[$status]
$bytes = $enc.GetBytes([string]$res[2])
$head = "HTTP/1.1 $status $reason`r`nContent-Type: $($res[1]); charset=utf-8`r`nContent-Length: $($bytes.Length)`r`nConnection: close`r`n`r`n"
$hb = $enc.GetBytes($head)
$stream.Write($hb, 0, $hb.Length); $stream.Write($bytes, 0, $bytes.Length); $stream.Flush()
} catch {
Write-Host "mock: request failed: $($_.Exception.Message)"
} finally {
$client.Close()
}
}
$listener.Stop()
Write-Host 'mock-opnsense stopped'
Test-OpnsenseScript.ps1
<#
Test-OpnsenseScript.ps1 (v4) - runs opnsense-dns-bypass.ps1 against mock-opnsense.ps1, one case per failure path
Prepared by Vivek Sanghi with Claude (Anthropic). Copyright (c) 2026 Vivek Sanghi. MIT licence (see opnsense-dns-bypass.ps1).
Runs on Windows PowerShell 5.1 and PowerShell 7.
What it touches:
- reads the script under test; never changes it
- writes a test copy and one folder per case under .\test-run-<timestamp>\ (next to this file)
- starts mock-opnsense.ps1 on 127.0.0.1:<Port> and stops it at the end
- contacts nothing else: the test copy's two network-test functions ask the mock instead of the internet,
and every run points -Router at the mock. No real router, no real API key.
The test copy differs from the script in exactly three ways, each checked before any case runs:
Test-Tcp and Get-ARecords ask the mock; every Start-Sleep is cut to 1 ms.
#>
param(
[string]$ScriptPath = '',
[string]$MockPath = '',
[int]$Port = 18443
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version 1
# Work out this file's folder in the body, not in param(): the article's failure 1.
$Here = ''
if ($MyInvocation.MyCommand.Path) { $Here = Split-Path -Parent $MyInvocation.MyCommand.Path }
if (-not $Here) { $Here = (Get-Location).Path }
if (-not $ScriptPath) { $ScriptPath = Join-Path $Here 'opnsense-dns-bypass.ps1' }
if (-not $MockPath) { $MockPath = Join-Path $Here 'mock-opnsense.ps1' }
if (-not (Test-Path -LiteralPath $MockPath)) { Write-Host "Mock not found: $MockPath" -ForegroundColor Red; exit 1 }
$Exe = (Get-Process -Id $PID).Path
$Base = "http://127.0.0.1:$Port"
$Url = 'https://cdn.jsdelivr.net/gh/hagezi/dns-blocklists@latest/ips/doh.txt'
$DescA = 'Reject DoH to known resolvers (A)'
$DescB = 'Reject DoT/DoQ 853 from LAN (B)'
foreach ($n in 'NO_PROXY', 'no_proxy') { [Environment]::SetEnvironmentVariable($n, '127.0.0.1,localhost') }
if ($PSVersionTable.PSVersion.Major -lt 6) { [Net.ServicePointManager]::Expect100Continue = $false }
if (-not (Test-Path -LiteralPath $ScriptPath)) { Write-Host "Script not found: $ScriptPath" -ForegroundColor Red; exit 1 }
$hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $ScriptPath).Hash.ToLowerInvariant()
Write-Host "PowerShell $($PSVersionTable.PSVersion) ($($PSVersionTable.PSEdition))"
Write-Host "Script under test: $ScriptPath"
Write-Host "SHA-256: $hash"
# ---------- test copy ----------
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$Run = Join-Path $Here "test-run-$stamp"
New-Item -ItemType Directory -Path $Run | Out-Null
$text = [IO.File]::ReadAllText($ScriptPath)
function Swap([string]$t, [string]$pattern, [string]$new, [int]$want, [string]$what) {
$m = [regex]::Matches($t, $pattern)
if ($m.Count -ne $want) { throw "Test copy: expected $want match(es) for $what, found $($m.Count). Has the script changed?" }
foreach ($x in @($m | Sort-Object Index -Descending)) { $t = $t.Remove($x.Index, $x.Length).Insert($x.Index, $new) }
return $t
}
$tcp = @'
function Test-Tcp([string]$TargetHost, [int]$Port, [int]$Ms = 4000) {
return [bool](Invoke-RestMethod -Uri ("$Router/__test/tcp?h={0}&p={1}" -f [Uri]::EscapeDataString($TargetHost), $Port) -TimeoutSec 10).open
}
'@
$dns = @'
function Get-ARecords([string]$Name, [string]$Server) {
return @((Invoke-RestMethod -Uri ("$Router/__test/dns?n={0}&s={1}" -f [Uri]::EscapeDataString($Name), [Uri]::EscapeDataString($Server)) -TimeoutSec 10).ips)
}
'@
$text = Swap $text '(?s)function Test-Tcp\(.*?\r?\n\}\r?\n' $tcp 1 'function Test-Tcp'
$text = Swap $text '(?s)function Get-ARecords\(.*?\r?\n\}\r?\n' $dns 1 'function Get-ARecords'
$text = Swap $text 'Start-Sleep -Seconds (\d+|\$\w+)' 'Start-Sleep -Milliseconds 1' 4 'Start-Sleep'
$Copy = Join-Path $Run 'script-under-test.ps1'
[IO.File]::WriteAllText($Copy, $text, (New-Object Text.UTF8Encoding($false)))
# Evidence, not a pass/fail case: what this PowerShell puts in $PSScriptRoot when it is a parameter default.
$probe = Join-Path $Run 'probe-psscriptroot.ps1'
[IO.File]::WriteAllText($probe, 'param([string]$WorkDir = $PSScriptRoot)' + "`n" + '"[" + $WorkDir + "]"' + "`n")
$probeOut = "$(& $Exe -NoProfile -ExecutionPolicy Bypass -File $probe)"
$Evidence = "Evidence: `$PSScriptRoot as a parameter default, run with -File, gave $probeOut (empty brackets = empty)"
Write-Host $Evidence
$GoodKey = Join-Path $Run 'key-good.txt'; [IO.File]::WriteAllText($GoodKey, "key=testkey`nsecret=testsecret`n")
$BadKey = Join-Path $Run 'key-bad.txt'; [IO.File]::WriteAllText($BadKey, "key=testkey`nsecret=wrongsecret`n")
# ---------- mock ----------
function Q([string]$a) { return '"' + $a + '"' }
$mockOut = Join-Path $Run 'mock-output.txt'
$mockArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Q $MockPath), '-Port', $Port)
$mock = Start-Process -FilePath $Exe -ArgumentList $mockArgs -PassThru -NoNewWindow -RedirectStandardOutput $mockOut -RedirectStandardError (Join-Path $Run 'mock-errors.txt')
$up = $false
for ($i = 0; $i -lt 60; $i++) { try { $null = Invoke-RestMethod "$Base/__test/ping" -TimeoutSec 2; $up = $true; break } catch { Start-Sleep -Milliseconds 500 } }
if (-not $up) { Write-Host "The mock did not start. See $mockOut" -ForegroundColor Red; if (-not $mock.HasExited) { Stop-Process -Id $mock.Id -Force }; exit 1 }
Write-Host "Mock: $MockPath (SHA-256 $((Get-FileHash -Algorithm SHA256 -LiteralPath $MockPath).Hash.ToLowerInvariant()))"
$Secret64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes('testkey:testsecret'))
function Reset([string]$scenario) { $null = Invoke-RestMethod -Method POST -Uri "$Base/__test/reset" -Body (ConvertTo-Json @{ scenario = $scenario }) -ContentType 'application/json' }
function State { return Invoke-RestMethod "$Base/__test/state" }
function Calls { return @((Invoke-RestMethod "$Base/__test/calls").calls) }
function Rule($st, [string]$desc) { return @(@($st.rules) | Where-Object { $_.description -eq $desc }) }
# ---------- cases ----------
$Results = New-Object System.Collections.ArrayList
function Run-Case {
param([string]$Name, [string]$Scenario, [string]$Mode = 'Apply', [int[]]$Exit, [scriptblock]$Check, [switch]$NoRouter, [string]$Key = $GoodKey, [string]$ModeRaw = '', [string]$RouterArg = '')
Reset $Scenario
$dir = Join-Path $Run $Name; New-Item -ItemType Directory -Path $dir | Out-Null
$a = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', (Q $Copy), '-KeyFile', (Q $Key), '-WorkDir', (Q $dir))
if ($RouterArg) { $a += @('-Router', $RouterArg) } elseif (-not $NoRouter) { $a += @('-Router', $Base) }
if ($ModeRaw) { $a += @('-Mode', $ModeRaw) } else { $a += @('-Mode', $Mode) }
$out = Join-Path $dir 'console.txt'; $err = Join-Path $dir 'console-errors.txt'
$p = Start-Process -FilePath $Exe -ArgumentList $a -PassThru -Wait -NoNewWindow -RedirectStandardOutput $out -RedirectStandardError $err
$code = $p.ExitCode
$console = ((Get-Content -LiteralPath $out -Raw -ErrorAction SilentlyContinue) + (Get-Content -LiteralPath $err -Raw -ErrorAction SilentlyContinue))
$logs = @(Get-ChildItem -LiteralPath (Join-Path $dir 'logs') -Filter '*.log' -ErrorAction SilentlyContinue)
$log = ''; if ($logs.Count -gt 0) { $log = Get-Content -LiteralPath $logs[0].FullName -Raw }
$backups = @(Get-ChildItem -LiteralPath (Join-Path $dir 'router-backups') -Filter '*.xml' -ErrorAction SilentlyContinue | ForEach-Object { $_.Name })
$calls = Calls; $posts = @($calls | Where-Object { $_.method -eq 'POST' })
$st = State
$script:fails = New-Object System.Collections.ArrayList
function Want([bool]$ok, [string]$msg) { if (-not $ok) { [void]$script:fails.Add($msg) } }
Want ($Exit -contains $code) "exit code $code, wanted $($Exit -join ' or ')"
Want (-not (($console + $log) -match 'testsecret|wrongsecret')) 'the API secret appeared in the output or log'
Want (-not (($console + $log).Contains($Secret64))) 'the encoded API key appeared in the output or log'
if ($code -ne 0 -and $log) { Want ($log -match 'STOP: |PARTLY finished') 'the run stopped without saying so in the log' }
Want (@($posts | Where-Object { $_.path -match 'del' }).Count -eq 0) 'a delete call was made'
$ctx = @{ code = $code; console = $console; log = $log; all = ($console + "`n" + $log); backups = $backups; calls = $calls; posts = $posts; state = $st; dir = $dir }
& $Check $ctx
$status = 'PASS'; if ($script:fails.Count -gt 0) { $status = 'FAIL' }
[void]$Results.Add([pscustomobject]@{ Case = $Name; Result = $status; Exit = $code; Posts = $posts.Count; Notes = ($script:fails -join '; ') })
$colour = 'Green'; if ($status -eq 'FAIL') { $colour = 'Red' }
Write-Host ("{0,-24} {1} exit={2} POSTs={3} {4}" -f $Name, $status, $code, $posts.Count, ($script:fails -join '; ')) -ForegroundColor $colour
}
try {
Write-Host ''
Run-Case 'placeholder-router' 'default' -Mode Check -NoRouter -Exit 1 -Check { param($c)
Want ($c.calls.Count -eq 0) 'the mock received calls'
Want (-not (Test-Path -LiteralPath (Join-Path $c.dir 'logs'))) 'a logs folder was created'
Want ($c.console -match 'Set -Router') 'no "Set -Router" message' }
Run-Case 'bad-mode' 'default' -ModeRaw 'Aply' -Exit 1 -Check { param($c)
Want ($c.calls.Count -eq 0) 'the mock received calls' }
Run-Case 'bad-key' 'default' -Mode Check -Key $BadKey -Exit 1 -Check { param($c)
Want ($c.posts.Count -eq 0) 'POSTs were sent'
Want ($c.backups.Count -eq 0) 'a backup was written'
Want ($c.log -match 'Cannot reach the router API') 'no "Cannot reach the router API" message' }
Run-Case 'version-mismatch' 'version-mismatch' -Exit 1 -Check { param($c)
Want ($c.posts.Count -eq 0) 'POSTs were sent'
Want ($c.backups.Count -eq 0) 'a backup was written'
Want ($c.log -match 'built for OPNsense 26\.7; router reports 26\.1') 'no version message' }
Run-Case 'small-backup' 'small-backup' -Exit 1 -Check { param($c)
Want ($c.posts.Count -eq 0) 'POSTs were sent'
Want ($c.log -match 'Backup looks wrong') 'no "Backup looks wrong" message' }
Run-Case 'check' 'default' -Mode Check -Exit 0 -Check { param($c)
Want ($c.posts.Count -eq 0) 'Check sent POSTs'
Want (@($c.backups | Where-Object { $_ -like 'config-Check-before-*.xml' }).Count -eq 1) 'no Check backup'
Want ($c.log -match 'Check mode: nothing was changed') 'no Check message'
Want (@([regex]::Matches($c.log, 'want False after Apply\)')).Count -eq 3) 'not three bypass tests' }
Run-Case 'empty-key-reply' 'empty-key-reply' -Exit 1 -Check { param($c)
Want ($c.posts.Count -eq 0) 'POSTs were sent'
Want ($c.log -match 'STOP: .*could not be read as JSON') 'the JSON guard stop is not in the log' }
Run-Case 'http-router' 'default' -Mode Check -RouterArg 'http://192.0.2.1' -Exit 1 -Check { param($c)
Want ($c.calls.Count -eq 0) 'the mock received calls'
Want ($c.console -match 'must start with https://') 'no https message' }
Run-Case 'check-nat-missing' 'nat-missing' -Mode Check -Exit 0 -Check { param($c)
Want ($c.posts.Count -eq 0) 'Check sent POSTs'
Want ($c.log -match "Apply would stop: NAT rule 'Redirect non-local DNS to Local' not found") 'no "Apply would stop" warning' }
Run-Case 'allow-missing' 'allow-missing' -Exit 1 -Check { param($c)
Want ($c.posts.Count -eq 0) 'POSTs were sent'
Want ($c.log -match "Rule 'Default allow LAN to any rule' not found, so rule order cannot be checked") 'no allow-rule message'
Want ($c.log -match 'Nothing changed\.') 'no "Nothing changed"' }
Run-Case 'small-backup-after' 'small-backup-after' -Exit 1 -Check { param($c)
Want ($c.log -match 'The changes logged above were made') 'no "changes were made" message'
Want (-not ($c.log -match 'Nothing changed on the router')) 'claims nothing changed after changes' }
Run-Case 'alias-undo-enabled' 'alias-disabled-doh-open' -Exit 1 -Check { param($c)
Want ("$($c.state.alias.enabled)" -eq '0') 'alias enabled flag not restored'
Want ("$($c.state.alias.content)" -eq "__lan_network`n$Url") 'alias content not restored'
Want ($c.log -match 'alias content and enabled flag restored') 'no restore message' }
Run-Case 'alias-wrong-type' 'alias-wrong-type' -Exit 1 -Check { param($c)
Want ($c.posts.Count -eq 0) 'POSTs were sent'
Want ($c.log -match "is type 'host', not urltable") 'no type message'
Want ($c.log -match 'Nothing to undo') 'no "Nothing to undo"'
Want (@($c.backups | Where-Object { $_ -like '*after-undo*' }).Count -eq 1) 'no after-undo backup' }
Run-Case 'alias-validation' 'alias-validation' -Exit 1 -Check { param($c)
Want ($c.log -match 'was not saved') 'no "was not saved" message'
Want ($c.log -match 'Nothing to undo') 'no "Nothing to undo"'
Want ("$($c.state.alias.content)" -eq "__lan_network`n$Url") 'alias content changed' }
Run-Case 'alias-not-filling' 'alias-not-filling' -Exit 1 -Check { param($c)
Want ($c.log -match 'loaded only 12 entries') 'no "loaded only" message'
Want ($c.log -match 'alias content and enabled flag restored') 'alias not restored'
Want ("$($c.state.alias.content)" -eq "__lan_network`n$Url") 'alias content not back to the original' }
Run-Case 'rule-validation' 'rule-validation' -Exit 1 -Check { param($c)
Want ($c.log -match "Rule 'Reject DoT/DoQ 853 from LAN \(B\)' was not saved") 'no rule B message'
$ra = @(Rule $c.state $DescA)
Want ($ra.Count -eq 1 -and "$($ra[0].enabled)" -eq '0') 'rule A not disabled by the undo'
Want (@(Rule $c.state $DescB).Count -eq 0) 'rule B exists'
Want ("$($c.state.alias.content)" -eq "__lan_network`n$Url") 'alias not restored'
Want ("$($c.state.nat.disabled)" -eq '1') 'NAT touched' }
Run-Case 'rule-order' 'rule-order' -Exit 1 -Check { param($c)
Want ($c.log -match 'would never match') 'no rule-order message'
Want (@(@($c.state.rules) | Where-Object { "$($_.enabled)" -ne '0' }).Count -eq 0) 'a rule left enabled'
Want ("$($c.state.alias.content)" -eq "__lan_network`n$Url") 'alias not restored' }
Run-Case 'doh-still-open' 'doh-open' -Exit 1 -Check { param($c)
Want ($c.log -match 'DoH to 1\.1\.1\.1:443 is still reachable') 'no DoH message'
Want (@(@($c.state.rules) | Where-Object { "$($_.enabled)" -ne '0' }).Count -eq 0) 'a rule left enabled'
Want ("$($c.state.nat.disabled)" -eq '1') 'NAT touched' }
Run-Case 'https-broken' 'https-broken' -Exit 1 -Check { param($c)
Want ($c.log -match 'Ordinary HTTPS to www\.google\.com failed') 'no HTTPS message'
Want (@(@($c.state.rules) | Where-Object { "$($_.enabled)" -ne '0' }).Count -eq 0) 'a rule left enabled' }
Run-Case 'fresh-alias' 'fresh-alias' -Exit 0 -Check { param($c)
Want (@($c.posts | Where-Object { $_.path -eq '/api/firewall/alias/add_item' }).Count -eq 1) 'alias not created once'
Want ("$($c.state.alias.content)" -eq $Url) 'alias content wrong'
Want ($c.log -match 'Apply finished') 'no "Apply finished"' }
Run-Case 'fresh-alias-fails' 'fresh-alias-doh-open' -Exit 1 -Check { param($c)
Want ($c.log -match 'new alias disabled') 'new alias not disabled'
Want ("$($c.state.alias.enabled)" -eq '0') 'alias still enabled' }
Run-Case 'apply' 'default' -Exit 0 -Check { param($c)
Want ("$($c.state.alias.content)" -eq $Url) 'alias content not cleaned'
Want ($c.log -match 'Alias DoH_IPs set to the URL only \(was: __lan_network \|') 'old alias content not logged'
$ra = @(Rule $c.state $DescA); $rb = @(Rule $c.state $DescB)
Want ($ra.Count -eq 1 -and "$($ra[0].enabled)" -eq '1') 'rule A not enabled'
Want ($rb.Count -eq 1 -and "$($rb[0].enabled)" -eq '1') 'rule B not enabled'
Want ("$($c.state.nat.disabled)" -eq '0') 'NAT not enabled'
Want ($c.log -match 'Waiting 70 s') 'no 70 s wait message'
Want ($c.log -match 'Apply finished') 'no "Apply finished"'
Want (@($c.backups | Where-Object { $_ -like 'config-Apply-before-*' }).Count -eq 1 -and @($c.backups | Where-Object { $_ -like 'config-Apply-after-*' }).Count -eq 1) 'backups not before + after' }
Run-Case 'leftover-rules' 'left-disabled' -Exit 0 -Check { param($c)
Want (@($c.posts | Where-Object { $_.path -eq '/api/firewall/filter/add_rule' }).Count -eq 0) 'rules added again'
Want (@($c.state.rules).Count -eq 2) 'duplicate rules'
Want ($c.log -match "Rule 'Reject DoH to known resolvers \(A\)' enabled\.") 'rule A not re-enabled' }
Run-Case 'already-applied' 'already-applied' -Exit 0 -Check { param($c)
Want (@($c.posts | Where-Object { $_.path -like '/api/firewall/filter/add_rule' -or $_.path -like '/api/firewall/filter/set_rule/*' -or $_.path -like '/api/firewall/d_nat/set_rule/*' -or $_.path -like '/api/firewall/alias/set_item/*' }).Count -eq 0) 'something was re-saved'
Want ($c.log -match 'already present and enabled') 'no "already present" message'
Want ($c.log -match 'NAT rule already enabled') 'no "NAT already enabled" message' }
Run-Case 'nat-missing' 'nat-missing' -Exit 1 -Check { param($c)
Want ($c.posts.Count -eq 0) 'POSTs were sent before the missing NAT rule was reported'
Want ($c.log -match "NAT rule 'Redirect non-local DNS to Local' not found\. Create it in Firewall > NAT > Destination NAT") 'no NAT-missing message' }
Run-Case 'nat-ineffective' 'nat-ineffective' -Exit 2 -Check { param($c)
Want ($c.log -match 'still returns real ad addresses after 70 s') 'no redirect message'
Want ("$($c.state.nat.disabled)" -eq '1') 'NAT left on'
Want ($c.log -match 'NAT rule switched back off') 'no switch-off message'
Want ($c.log -match 'This run switched it on and has switched it off again') 'PARTLY message does not say what happened to NAT'
Want (@(@($c.state.rules) | Where-Object { "$($_.enabled)" -eq '1' }).Count -eq 2) 'rules not kept' }
Run-Case 'nat-validation' 'nat-validation' -Exit 2 -Check { param($c)
Want ($c.log -match 'Enable NAT rule was not saved') 'no NAT save message'
Want ("$($c.state.nat.disabled)" -eq '1') 'NAT changed'
Want ($c.log -match 'did not pass\. It is still off\.') 'PARTLY message wrong for a NAT rule that never switched on'
Want (@(@($c.state.rules) | Where-Object { "$($_.enabled)" -eq '1' }).Count -eq 2) 'rules not kept' }
Run-Case 'nat-already-on' 'nat-already-on-ineffective' -Exit 2 -Check { param($c)
Want ("$($c.state.nat.disabled)" -eq '0') 'NAT rule that was on before was switched off'
Want (-not ($c.log -match 'after 70 s')) 'claims a 70 s wait that did not happen'
Want ($c.log -match 'It was already on before this run and is left on') 'PARTLY message does not say NAT was left on' }
Run-Case 'rollback' 'already-applied' -Mode Rollback -Exit 0 -Check { param($c)
Want (@($c.state.rules).Count -eq 2) 'rules deleted'
Want (@(@($c.state.rules) | Where-Object { "$($_.enabled)" -ne '0' }).Count -eq 0) 'a rule left enabled'
Want ("$($c.state.nat.disabled)" -eq '1') 'NAT left on'
Want ($c.log -match 'Rollback finished') 'no "Rollback finished"'
Want (@($c.backups | Where-Object { $_ -like 'config-Rollback-after-*' }).Count -eq 1) 'no after backup' }
Run-Case 'rollback-nothing-to-do' 'default' -Mode Rollback -Exit 0 -Check { param($c)
Want (@($c.posts | Where-Object { $_.path -like '*set_rule*' }).Count -eq 0) 'something was changed'
Want ($c.log -match 'Rollback finished') 'no "Rollback finished"' }
} finally {
# ---------- always stop the mock ----------
try { $null = Invoke-RestMethod -Method POST -Uri "$Base/__test/stop" -TimeoutSec 5 } catch { }
Start-Sleep -Milliseconds 500
if (-not $mock.HasExited) { Stop-Process -Id $mock.Id -Force -ErrorAction SilentlyContinue }
}
$failed = @($Results | Where-Object { $_.Result -eq 'FAIL' }).Count
$summary = "{0} cases, {1} passed, {2} failed. PowerShell {3}. Script SHA-256 {4}" -f $Results.Count, ($Results.Count - $failed), $failed, $PSVersionTable.PSVersion, $hash
$Results | Format-Table -AutoSize | Out-String -Width 200 | Set-Content -LiteralPath (Join-Path $Run 'results.txt')
Add-Content -LiteralPath (Join-Path $Run 'results.txt') -Value $summary
Add-Content -LiteralPath (Join-Path $Run 'results.txt') -Value $Evidence
Write-Host ''
if ($failed -eq 0) { Write-Host $summary -ForegroundColor Green } else { Write-Host $summary -ForegroundColor Red }
Write-Host "Details: $Run"
if ($failed -gt 0) { exit 1 } else { exit 0 }
Mutation check results
Mutation check of opnsense-dns-bypass.v2.5.ps1 (SHA-256 df017f33269979e9...; 2.5.1 differs only in header comments) with Test-OpnsenseScript.v3.ps1 and mock-opnsense.v2.ps1
PowerShell 7.4.6, 28/10/2026. Each line: a deliberately broken copy of the script, and the cases that then failed.
no-undo 9 failed: alias-undo-enabled alias-wrong-type alias-validation alias-not-filling rule-validation rule-order doh-still-open https-broken fresh-alias-fails
no-exit2 3 failed: nat-ineffective nat-validation nat-already-on
no-json-guard 1 failed: empty-key-reply
no-router-guard 1 failed: placeholder-router
no-order-check 1 failed: rule-order
no-https-guard 1 failed: http-router
no-preflight 2 failed: allow-missing nat-missing
no-trap 1 failed: empty-key-reply
old-undo-content-only 1 failed: alias-undo-enabled
old-backup-message 1 failed: small-backup-after
Unbroken script: 30 cases, 30 passed.










