Tag: debugging

  • It passed every test, in the wrong place

    It passed every test, in the wrong place

    10 min read

    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

    1. Three modes. Check reads and reports. Apply makes the change. Rollback switches the two rules and the redirect off and deletes nothing. A command without -Mode runs Check.
    2. Version guard. The script first asks the router what it runs, and stops unless the answer is the 26.7 series.
    3. 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.
    4. 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.
    5. 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.0000200

    So “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

    1. 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.
    2. Build the mock’s replies from real ones. A reply saved from the router’s get_item would have caught failure 2 before the router saw the script.
    3. Make the read-only mode make every read the write mode will make. Here, Check and Apply read the alias through different endpoints.
    4. Treat a string from Invoke-RestMethod as a failure when you expected an object. It does not always raise an error.
    5. After switching on a redirect, wait longer than the firewall’s state timeout, and test with a name you have not queried before.
    6. If the undo disables instead of deleting, make the next run look for what the last one left.
    7. Break the script on purpose to check that the tests can fail.
    8. Keep the API key out of the script and delete it when the work is done. I used the root user’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 $AdTestDomain must 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 $NatWaitSeconds should 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.
    1. Open PowerShell and make a folder. Open the Start menu, type powershell and press Enter. A window titled Windows PowerShell opens, and its prompt starts with PS. If the prompt has no PS, 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-dns inside your user folder and prints a short listing; the second moves PowerShell into it, and the prompt then ends with opnsense-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.

    2. 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-File is 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.ps1

      Get-Clipboard reads what you copied and Set-Content writes 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).Count
      491

      A different number suggests the copy was cut short or changed. Go back to the page, click Copy again and repeat the first command.

    3. 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 example https://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:

      1. In the menu on the left, click System, then Access, then Users.
      2. Click the pencil (edit) icon at the end of the row of the administrator you log in as.
      3. 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.
      4. The browser downloads a small text file within a few seconds. It has a key= line and a secret= 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.

    4. 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, LastWriteTime
      Name                  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.txt

      It takes under a second and prints nothing. It will not overwrite an apikey.txt already 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), run Remove-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
      secret

      If you see other words, this is probably not the key file. Download a new key (step 3).

    5. 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 example 192.168.1.1), and leave https:// 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 -File starts a fresh Windows PowerShell 5.1 that runs the file. -ExecutionPolicy Bypass on 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 -Mode the script runs Check.

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      It takes 10 to 60 seconds and changes nothing on the router. It saves a backup of the router’s configuration in the router-backups folder inside opnsense-dns, a log in logs, 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>.log

      Both “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 $AdTestDomain near the top of the script to a domain your blocklist blocks, or switch the blocklist on. If a yellow line starts Apply 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://. Use https://.
      • STOP: Key file not found: apikey.txt is not in the opnsense-dns folder. 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.
    6. Run Apply. This changes the router. It overwrites the alias DoH_IPs with 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 Apply added:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl -Mode Apply

      It 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>.log

      If 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.

    7. Check that it worked. Run the Check command from step 5 again:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      Now the three Bypass lines read False and the two Router lines read True. 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.

    8. 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 Rollback

      It 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>.xml from the router-backups folder, 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.txt

      This deletes the file at once, with no recycle bin. When you no longer need the backups, delete the router-backups folder 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 validations counts as a failed save, as it does in the router’s own web pages; so does a result of failed. 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 = $false

    I 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/list and core/backup/download/this. It also calls core/firmware/info for the version and core/firmware/status as a reachability check.
    • The search endpoints answer a GET with ?rowCount=-1&current=1 and return every row, with the fields the script needs.
    • alias/get_item returns option lists with empty-named keys, which PowerShell cannot turn into object properties.
    • GET /api/core/backup/download/this returns the full configuration as XML.
    • POST bodies are JSON with Content-Type: application/json. Rule changes take effect after the matching apply; alias changes after reconfigure.
    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 में पास हुई, ग़लत जगह पर

    10 मिनट में पढ़ें · अंग्रेज़ी मूल से अनूदित। Code, commands और तकनीकी नाम अंग्रेज़ी में रखे गए हैं।

    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 से बंद कर सकूँ।

    किन नियमों पर चलती है

    1. तीन modes। Check पढ़ता है और report देता है। Apply बदलाव करता है। Rollback दोनों rules और redirect को बंद करता है और कुछ delete नहीं करता। -Mode के बिना command Check चलाती है।
    2. वर्ज़न की जाँच। Script पहले router से पूछती है कि उस पर क्या चल रहा है, और जवाब 26.7 series न हो तो रुक जाती है।
    3. उसके बाद backup। कोई भी configuration पढ़ने या बदलने से पहले, हर run router की पूरी configuration एक नई file में download करता है। वह किसी मौजूदा file को overwrite करने से मना करता है।
    4. हर बदलाव का test। पहले alias, फिर दोनों rules, फिर redirect। वर्ज़न 2.3 में एक fail हुआ test उस run के सारे बदलाव undo कर देता था। वर्ज़न 2.4 से, अगर सिर्फ़ redirect fail हो, तो सिर्फ़ redirect बंद होता है, और जो rules पास हुए वे बने रहते हैं।
    5. 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 के लिए मैं क्या साथ ले जाऊँगा

    1. उसी PowerShell पर test करें जिस पर script चलेगी, और tests भी वहीं चलाएँ। मेरा harness PowerShell 7 पर पास हुआ और 5.1 पर अपने पहले run में fail हुआ।
    2. Mock के जवाब असली जवाबों से बनाएँ। Router के get_item से save किया गया एक जवाब failure 2 को router तक script पहुँचने से पहले पकड़ लेता।
    3. सिर्फ़ पढ़ने वाला mode वे सारे reads करे जो लिखने वाला mode करेगा। यहाँ Check और Apply alias को अलग-अलग endpoints से पढ़ते थे।
    4. जब आप object की उम्मीद कर रहे हों, तो Invoke-RestMethod से मिली string को failure मानें। वह हमेशा error नहीं देता।
    5. Redirect चालू करने के बाद firewall के state timeout से ज़्यादा इंतज़ार करें, और ऐसे नाम से test करें जो आपने पहले query न किया हो।
    6. अगर undo delete करने की जगह disable करता है, तो अगला run वह ढूँढे जो पिछला छोड़ गया।
    7. Script को जान-बूझकर तोड़ें, यह जाँचने के लिए कि tests fail हो सकते हैं।
    8. API key को script से बाहर रखें और काम पूरा होने पर उसे delete करें। मैंने root user की 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 नहीं करता।
    1. PowerShell खोलें और एक folder बनाएँ। Start menu खोलें, powershell type करें और Enter दबाएँ। Windows PowerShell नाम की एक window खुलती है, और उसका prompt PS से शुरू होता है। अगर 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 को उसके अंदर ले जाती है, और तब prompt opnsense-dns> पर ख़त्म होता है। हर एक एक सेकंड से कम लेती है। अगर पहली line कहे कि folder पहले से है, तो आगे बढ़ें। यह window खुली रखें, और folder को OneDrive, Dropbox और shared जगहों से बाहर रखें: यहाँ save होने वाले backups में router की पूरी configuration होती है।

    2. 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.ps1

      Get-Clipboard वह पढ़ता है जो आपने copy किया और Set-Content उसे file में लिखता है; script सादी ASCII है, इसलिए वह encoding सुरक्षित है। यह एक सेकंड से कम लेता है और कुछ print नहीं करता। जाँचें कि सब कुछ पहुँच गया:

      (Get-Content .\opnsense-dns-bypass.ps1).Count
      491

      अलग संख्या का मतलब हो सकता है कि copy बीच में कट गई या बदल गई। Page पर वापस जाएँ, दोबारा Copy पर click करें और पहला command दोहराएँ।

    3. 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 करें। फिर:

      1. बाईं ओर के menu में System पर click करें, फिर Access, फिर Users।
      2. जिस administrator के रूप में आप log in करते हैं, उसकी row के आख़िर में pencil (edit) icon पर click करें।
      3. User की settings में API keys वाला section ढूँढें (OPNsense के दस्तावेज़ उसे ApiKeys tab कहते हैं) और उसके grid में key बनाने वाले button का इस्तेमाल करें।
      4. 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 का नियंत्रण देता है।

    4. 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, LastWriteTime
      Name                  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)।

    5. 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 के बिना script Check चलाती है।

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      यह 10 से 60 सेकंड लेता है और router पर कुछ नहीं बदलता। यह router की configuration का backup router-backups folder में, जो opnsense-dns के अंदर है, एक log logs में 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 चालू करें। अगर कोई पीली line Apply 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.txt opnsense-dns folder में नहीं है। 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 नहीं कर सकता। यहीं रुक जाएँ।
    6. 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 इस्तेमाल करें।

    7. जाँचें कि काम हुआ। Step 5 का Check command फिर चलाएँ:

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      अब तीनों Bypass lines False दिखाती हैं और दोनों Router lines True। 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 चालू है।

    8. इसे बंद करें, ज़रूरत हो तो 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-backups folder में है, और उसे 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-backups folder भी 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&current=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 भेजे जाने से पहले उसे मंज़ूरी दे।

    ప్రతి టెస్ట్‌లోనూ పాసైంది, తప్పు చోట

    చదవడానికి 10 నిమిషాలు · ఇంగ్లీష్ మూలం నుంచి అనువదించినది. Code, commands, సాంకేతిక పేర్లు ఇంగ్లీష్‌లోనే ఉన్నాయి.

    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

    1. మూడు modes. Check చదివి report ఇస్తుంది. Apply మార్పు చేస్తుంది. Rollback రెండు rules నీ redirect నీ off చేస్తుంది, దేన్నీ delete చేయదు. -Mode లేని command Check నడుపుతుంది.
    2. వెర్షన్ guard. script ముందుగా router ఏం నడుపుతోందో అడుగుతుంది. జవాబు 26.7 series కాకపోతే ఆగిపోతుంది.
    3. వెర్షన్ guard తర్వాత backup. ఏ configuration ని చదవడానికి గానీ మార్చడానికి గానీ ముందే, ప్రతి రన్ router పూర్తి configuration ని ఒక కొత్త file లోకి download చేస్తుంది. ఉన్న file ని overwrite చేయడానికి నిరాకరిస్తుంది.
    4. ప్రతి మార్పునూ టెస్ట్ చేయండి. ముందు alias, తర్వాత రెండు rules, తర్వాత redirect. వెర్షన్ 2.3 లో ఒక టెస్ట్ ఫెయిల్ అయితే ఆ రన్ చేసిన మార్పులన్నీ undo అయ్యేవి. వెర్షన్ 2.4 నుంచి, redirect ఒక్కటే ఫెయిల్ అయితే redirect ఒక్కటే off అవుతుంది; పాసైన rules అలాగే ఉంటాయి.
    5. 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 కి నేను తీసుకెళ్లేవి

    1. script ని నడపబోయే PowerShell మీదే టెస్ట్ చేయండి, టెస్ట్‌లను కూడా అక్కడే నడపండి. నా harness PowerShell 7 కింద పాసైంది, 5.1 కింద మొదటి రన్‌లో ఫెయిల్ అయింది.
    2. mock జవాబులను నిజమైన జవాబుల నుంచి కట్టండి. router get_item నుంచి save చేసిన ఒక జవాబు ఉండి ఉంటే, router script ని చూడక ముందే వైఫల్యం 2 పట్టుబడేది.
    3. write mode చేసే ప్రతి read నీ read-only mode కూడా చేసేలా చూడండి. ఇక్కడ Check, Apply alias ని వేర్వేరు endpoints ద్వారా చదివాయి.
    4. object ఆశించినప్పుడు Invoke-RestMethod నుంచి string వస్తే దాన్ని failure గా చూడండి. అది ప్రతిసారీ error ఇవ్వదు.
    5. redirect ని on చేశాక, firewall state timeout కంటే ఎక్కువ సేపు ఆగండి. ఇంతకు ముందు query చేయని పేరుతో టెస్ట్ చేయండి.
    6. undo delete చేయకుండా disable చేస్తే, గత రన్ వదిలినవాటి కోసం తర్వాతి రన్ వెతికేలా చేయండి.
    7. టెస్ట్‌లు ఫెయిల్ కాగలవని చెక్ చేయడానికి script ని కావాలని పాడుచేయండి.
    8. API key ని script బయట ఉంచండి, పని అయ్యాక దాన్ని delete చేయండి. నేను root user 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 ని పునరుద్ధరించదు.
    1. PowerShell తెరిచి ఒక folder సృష్టించండి. Start menu తెరిచి, powershell అని type చేసి Enter నొక్కండి. Windows PowerShell అనే title తో ఒక window తెరుచుకుంటుంది, దాని prompt PS తో మొదలవుతుంది. 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 ని అందులోకి తీసుకెళ్తుంది, తర్వాత prompt opnsense-dns> తో ముగుస్తుంది. ఒక్కొక్కటి ఒక సెకను కంటే తక్కువ పడుతుంది. మొదటి లైన్ folder ఉందని చెబితే, ముందుకు వెళ్లండి. ఈ window ని తెరిచి ఉంచండి, ఈ folder ని OneDrive, Dropbox, shared locations బయట ఉంచండి: ఇక్కడ save అయ్యే backups లో router మొత్తం configuration ఉంటుంది.

    2. 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.ps1

      Get-Clipboard మీరు copy చేసినదాన్ని చదువుతుంది, Set-Content దాన్ని ఒక file లో రాస్తుంది; script plain ASCII, కాబట్టి ఆ encoding సురక్షితం. ఇది ఒక సెకను కంటే తక్కువ పడుతుంది, ఏదీ print చేయదు. అంతా వచ్చిందో చెక్ చేయండి:

      (Get-Content .\opnsense-dns-bypass.ps1).Count
      491

      వేరే సంఖ్య వస్తే, copy మధ్యలోనే ఆగిపోయిందని లేదా మారిందని అనిపిస్తుంది. page కి తిరిగి వెళ్లి, Copy మీద మళ్లీ click చేసి, మొదటి command ను మళ్లీ నడపండి.

    3. 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 అవండి. తర్వాత:

      1. ఎడమవైపు menu లో System మీద, తర్వాత Access మీద, తర్వాత Users మీద click చేయండి.
      2. మీరు log in అయ్యే administrator వరుస చివర ఉన్న పెన్సిల్ (edit) icon మీద click చేయండి.
      3. user settings లో API keys section ను కనుక్కోండి (OPNsense documentation దాన్ని ApiKeys tab అంటుంది), దాని grid లో key ను సృష్టించే button ను వాడండి.
      4. కొన్ని సెకన్లలో 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 మీద నియంత్రణ ఇస్తుంది.

    4. key file ను folder లో పెట్టండి. PowerShell కి తిరిగి వచ్చి, మీ Downloads folder లోని కొత్త text files జాబితా చూడండి:

      Get-ChildItem "$env:USERPROFILE\Downloads" -Filter *.txt | Sort-Object LastWriteTime -Descending | Select-Object -First 3 Name, LastWriteTime
      Name                  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వ దశ).

    5. 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 లేకుండా script Check నడుపుతుంది.

      powershell -ExecutionPolicy Bypass -File .\opnsense-dns-bypass.ps1 -KeyFile .\apikey.txt -Router $RouterUrl

      ఇది 10 నుంచి 60 సెకన్లు పడుతుంది, router మీద ఏదీ మార్చదు. router configuration backup ను router-backups folder లో (అది 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.txt opnsense-dns folder లో లేదు. 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 చేయలేదు. ఇక్కడే ఆగండి.
    6. Apply నడపండి. ఇది router ను మారుస్తుంది. ఇది DoH_IPs alias ను 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వ దశ వాడండి.

    7. అది పనిచేసిందో చెక్ చేయండి. 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 గా ఉంటుంది.

    8. దాన్ని 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-backups folder నుంచి ఎంచుకుని 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-backups folder ను కూడా 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 = $false

    router 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&current=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.

    ผ่านทุกการทดสอบ ในที่ที่ผิด

    อ่าน 10 นาที · แปลจากต้นฉบับภาษาอังกฤษ; โค้ด คำสั่ง และชื่อทางเทคนิคคงไว้เป็นภาษาอังกฤษ

    บ่ายวันที่ 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 ต้องทำตาม

    1. สามโหมด Check อ่านและรายงาน Apply ทำการเปลี่ยนแปลง Rollback ปิด rule สองตัวและ redirect โดยไม่ลบอะไร คำสั่งที่ไม่ระบุ -Mode จะรัน Check
    2. ตรวจเวอร์ชัน script ถาม router ก่อนว่ารันอะไรอยู่ และหยุดถ้าคำตอบไม่ใช่ซีรีส์ 26.7
    3. backup เป็นลำดับถัดไป ก่อนจะอ่านหรือเปลี่ยน configuration ใด ๆ ทุกการรันจะดาวน์โหลด configuration ทั้งหมดของ router ลงไฟล์ใหม่ และไม่ยอมเขียนทับไฟล์ที่มีอยู่แล้ว
    4. ทดสอบทุกการเปลี่ยนแปลง alias ก่อน แล้วตามด้วย rule ทั้งสอง แล้วจึง redirect ในเวอร์ชัน 2.3 ถ้าการทดสอบล้มเหลว จะ undo ทุกอย่างที่การรันนั้นเปลี่ยนไป ตั้งแต่เวอร์ชัน 2.4 ถ้าล้มเหลวเฉพาะ redirect ก็จะปิดเฉพาะ redirect ส่วน rule ที่ผ่านแล้วยังอยู่
    5. ไม่มีความลับใน 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 ตัวต่อไป

    1. ทดสอบบน PowerShell ที่จะใช้รัน script และรันการทดสอบบนตัวนั้นด้วย (harness ผ่านบน PowerShell 7 และล้มเหลวในการรันครั้งแรกบน 5.1)
    2. สร้างคำตอบของ mock จากคำตอบจริง คำตอบที่ save มาจาก get_item ของ router จะจับความล้มเหลวครั้งที่ 2 ได้ก่อนที่ router จะเห็น script
    3. ทำให้โหมดอ่านอย่างเดียวอ่านทุกอย่างที่โหมดเขียนจะอ่าน ในกรณีนี้ Check และ Apply อ่าน alias ผ่าน endpoint ต่างกัน
    4. ถือว่าสตริงจาก Invoke-RestMethod คือความล้มเหลว เมื่อคุณคาดว่าจะได้ object มันไม่ได้แจ้ง error เสมอไป
    5. หลังเปิด redirect ให้รอนานกว่า state timeout ของ firewall และทดสอบด้วยชื่อที่ยังไม่เคย query มาก่อน
    6. ถ้า undo ใช้วิธีปิดแทนการลบ ให้การรันครั้งถัดไปมองหาสิ่งที่ครั้งก่อนทิ้งไว้
    7. ทำให้ script พังโดยตั้งใจ เพื่อตรวจว่าการทดสอบล้มเหลวได้
    8. เก็บ 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” หรือค่าที่คุณตั้งใน $NatDesc script ไม่ได้สร้างมัน และไม่ได้ตรวจว่ามันสร้างไว้อย่างไร
    • 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
    1. เปิด PowerShell และสร้างโฟลเดอร์ เปิดเมนู Start พิมพ์ powershell แล้วกด Enter หน้าต่างชื่อ Windows PowerShell จะเปิดขึ้น และ prompt ของมันขึ้นต้นด้วย PS ถ้า prompt ไม่มี PS แสดงว่าคุณอยู่ใน Command Prompt ให้ปิดแล้วเปิด PowerShell แทน เพราะคำสั่งด้านล่างใช้ได้เฉพาะใน PowerShell คลิกในหน้าต่าง ใช้สองบรรทัดด้านล่างทีละบรรทัด: คลิก PS> เพื่อคัดลอกบรรทัดนั้น วางมัน (Ctrl + V หรือคลิกขวา) แล้วกด Enter

      New-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

    2. บันทึก 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.ps1

      Get-Clipboard อ่านสิ่งที่คุณคัดลอก และ Set-Content เขียนลงไฟล์ ตัว script เป็น ASCII ล้วน encoding นี้จึงปลอดภัย ใช้เวลาไม่ถึงหนึ่งวินาทีและไม่พิมพ์อะไร ตรวจว่าทั้งหมดมาครบ:

      (Get-Content .\opnsense-dns-bypass.ps1).Count
      491

      ตัวเลขที่ต่างออกไปบ่งว่าการคัดลอกถูกตัดหรือถูกเปลี่ยน กลับไปที่หน้านั้น คลิก Copy อีกครั้ง แล้วทำคำสั่งแรกซ้ำ

    3. สร้าง API key บน router ในเว็บเบราว์เซอร์ พิมพ์ https:// ตามด้วย address ที่คุณใช้เปิดหน้า settings ของ router (เช่น https://192.168.1.1) แล้วกด Enter เบราว์เซอร์อาจเตือนว่าการเชื่อมต่อไม่เป็นส่วนตัว เพราะ router เซ็น certificate เอง เลือกตัวเลือกที่ไปต่อยัง address นั้น (ใน Chrome: Advanced แล้ว Proceed) ล็อกอินด้วย login ของคุณเองบน router จากนั้น:

      1. ในเมนูทางซ้าย คลิก System แล้ว Access แล้ว Users
      2. คลิกไอคอนดินสอ (edit) ที่ท้ายแถวของผู้ดูแลที่คุณล็อกอินเป็น
      3. หาส่วน API keys ในการตั้งค่าของ user (เอกสารของ OPNsense เรียกว่าแท็บ ApiKeys) และใช้ปุ่มในตารางของมันที่สร้าง key
      4. เบราว์เซอร์จะดาวน์โหลดไฟล์ข้อความขนาดเล็กภายในไม่กี่วินาที ไฟล์มีบรรทัด 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

    4. ใส่ไฟล์ key ในโฟลเดอร์ กลับมาที่ PowerShell แสดงรายการไฟล์ข้อความใหม่ล่าสุดในโฟลเดอร์ Downloads ของคุณ:

      Get-ChildItem "$env:USERPROFILE\Downloads" -Filter *.txt | Sort-Object LastWriteTime -Descending | Select-Object -First 3 Name, LastWriteTime
      Name                  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)

    5. รัน 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 ที่นายจ้างตั้งไว้ ถ้าไม่มี -Mode script จะรัน Check

      powershell -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 ไม่ได้ หยุดที่นี่
    6. รัน 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

    7. ตรวจว่าได้ผล รันคำสั่ง 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 เปิดใช้งานอยู่

    8. ปิดการแก้ไข กู้คืนถ้าจำเป็น และลบ 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&current=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

    Code is the same in every language. MIT licence. कोड हर भाषा में एक ही है। కోడ్ అన్ని భాషలలో ఒకేలా ఉంటుంది. โค้ดเหมือนกันทุกภาษา

    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&current=1'
        $alias   = @($aliases.rows | Where-Object { $_.name -eq $AliasName }) | Select-Object -First 1
        $rules   = Api GET '/api/firewall/filter/search_rule?rowCount=-1&current=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&current=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&current=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&current=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&current=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&current=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.
    
  • The paste is still in its box

    The paste is still in its box

    Choose a language: English, Hindi, Telugu or Thai.

    On 15 October 2026 I had two fixes for one problem on my desk: a 4 g tube of ARCTIC MX-7 thermal paste and a 120 mm Noctua fan. The problem was my router, a fanless mini PC running OPNsense in a closed plywood cabinet. The day before, its CPU had touched 91 °C.

    The advice I found online was to open the case and replace the paste. I fitted the fan first, because it needed no screwdriver. Before I did, I decided which result would send me back for the paste.

    I never needed it. The router had been logging its own temperature all along. Between 16 September and the evening of 15 October, no hour averaged below 60 °C. In the four days after the fan went on, no hour averaged above 49 °C. The paste is still in its box.

    I did this work with Claude, Anthropic’s AI model, which could read my router through my own browser session. I chose the parts, fitted the fan and set the rule. Claude pulled the temperature records and did the arithmetic, and on 28 October it read back the router’s hourly data for this post.

    The box and the cabinet

    The router is a six-port fanless mini PC sold under the name “Shenzhen Weibu”. Inside is an Intel Pentium Gold 8505: one performance core and four efficient cores, six threads, 15 W base power and up to 55 W in turbo, according to Intel’s specification page. It has 20 GB of RAM and six Intel I226-V 2.5 GbE ports, and runs OPNsense 26.7. The case is the heatsink. Its top is a block of fins.

    It sits in a closed plywood cabinet with other network gear. A slotted grille in the cabinet’s side panel is the only planned way out for warm air.

    The router before the fan, seen from its USB end: a black case whose top is a block of fins, beside the slotted grille in the cabinet's side panel

    Was 91 °C dangerous? Not by Intel’s numbers. The same page lists the chip’s maximum junction temperature (TJUNCTION) as 100 °C, and a processor at that limit slows itself down rather than failing. The 91 °C was also only the highest sampled reading; the router reads the sensor once a minute, so the peaks in between went unrecorded. Even so, the heat had become a reason to look at a new router. The hourly average sat near 70 °C day and night, and the SSD, the memory and the network chips share the same hot case. Heat shortens the life of electronics in general, though I measured neither that nor the SSD’s temperature on this box.

    Why the fan went first

    A repaste is the usual advice for a hot mini PC, and it may well have helped. It would also have meant:

    • a configuration backup first;
    • 99 per cent isopropyl alcohol and lint-free wipes;
    • 45 to 60 minutes with the network offline;
    • opening a sealed case whose screws and thermal pads I had never seen.

    A fan lying on the fins needed none of that, and could come off in a second. It has costs of its own. It gives up what a fanless box is for: no noise, no dust drawn in, no moving part to wear out.

    So I set the rule before fitting it: repaste only if the overnight readings still reach the 80s with the fan in place.

    The fan

    I chose a Noctua NF-F12 5V PWM. Noctua’s specification gives 120 mm, 5 V, up to 1,500 rpm, 0.65 W typical and 22.4 dB(A) at full speed, with a USB power cable in the box. Mine plugs into one of the router’s own USB ports. Powered from USB, the fan gets no speed signal, and Noctua’s own guide says a PWM fan with no signal runs at full speed. Noctua marks it “5V PWM version, not for use in PCs”: a PC’s 12 V fan header is the wrong supply for it.

    On my router, the 120 mm fan covers most of the top. Pick a fan about the size of the router’s top. Noctua also sells 5 V versions in smaller sizes, such as the 80 mm NF-A8 5V PWM. A cheaper 5 V USB fan would also move air; I have not tried one.

    I fitted it at about 17:30 on 15 October. It lies flat on the top fins, not screwed down, blowing down into them. Reading a photo, Claude first had the airflow the wrong way round; I checked the arrow moulded into the frame. Either direction should help, but I wanted to know which one I was measuring.

    The Noctua fan lying flat on the router's finned top, seen from above The router from its network-port end, cabled, with the fan resting on top

    What the router recorded

    OPNsense reads the CPU temperature once a minute and keeps hourly averages for weeks. How to read yours is further down.

    Line chart of the router's hourly average CPU temperature from 16 September 2026 to four days after the fan was fitted. It runs between about 65 and 74 °C until 9 October, peaks at 77 °C during the clean-up on 10 October, settles between about 60 and 71 °C, and falls to about 46 °C in the hour after the fan was fitted at 17:30 on 15 October, where it stays.

    Hourly averages of cpu0, from the router’s hourly archive:

    Period Hours Average Lowest hour Highest hour
    16 September – 9 October 567 69.7 °C 65.3 °C 73.7 °C
    11 October – 15 October, until the fan 114 66.2 °C 60.5 °C 70.9 °C
    15 October, after the fan (four days) 100 46.4 °C 42.6 °C 48.6 °C

    I left out 10 October, the day of a configuration clean-up described below. Against the days just before it, the fan took about 20 °C off the average. The before and after ranges do not overlap: the coolest hour before the fan was 12 °C warmer than the warmest hour after it.

    The rule I had set was about the overnight readings. On 15 October I read the 03:00–10:00 window from the per-minute record, and on 16 October I read the same window again:

    cpu0, 03:00–10:00 15 October, no fan 16 October, fan
    Average 65.6 °C 46.7 °C
    Maximum 90.3 °C 73.6 °C
    Readings at 80 °C or above 19 0

    No reading reached the 80s. The rule said leave the case shut.

    My rule used single readings, and single readings jump. Each is one instant: on 28 October consecutive minutes read 35.3, 68.2, 69.0 and 35.7 °C. An average over hours would have made a better test. By hourly averages the gap is wider still: no hour after the fan went above 48.6 °C.

    Deep dive: the 15 October per-minute windows

    Read from the per-minute record on 15 October.

    Window, 15 October 2026 Readings Average Median 95th percentile Maximum At 80 °C or above
    03:00–10:00, no fan 420 65.6 °C 69.0 °C 79.8 °C 90.3 °C 19
    12:00–17:20, no fan 320 65.5 °C 68.7 °C 80.1 °C 90.7 °C 16
    17:31–19:12, fan 101 46.0 °C 48.7 °C 60.5 °C 69.6 °C 0
    19:20–19:37, after a firmware update and reboot 17 54.1 °C 57.1 °C 70.8 °C 70.8 °C 0

    The last row is higher because the router had just rebooted after a firmware update and was loading about 2.7 million blocklist entries. It is not a resting figure.

    What this does and does not show

    It shows that a fan was enough here. It does not show that a repaste would not also have helped; I never tried one. The fan does not take heat out of the cabinet. It forces cabinet air through the router’s fins. The closed cabinet made the starting point worse, so the gain here is probably larger than it would be in open air.

    • I did not measure the room temperature. The drop came within one hour, and a room does not cool 20 °C in an hour. The router also reacts little to the daily cycle: from 16 September to 9 October, the average for each hour of the day stayed between 69.2 and 70.3 °C, a swing of about 1 °C.
    • The firmware changed the same evening. The router installed a firmware update at 19:12 on 15 October. The drop came first: the 101 minutes between fitting the fan and the update averaged 46.0 °C.
    • A configuration clean-up came five days earlier. On 10 October I removed a WireGuard VPN client, an unused proxy stack (Squid, ClamAV, Redis and their companions) and the NAT rules that fed it, trimmed my DNS blocklists, and unplugged a USB network adapter. The hourly average was 69.7 °C from 16 September to 9 October and 66.2 °C from 11 October until the fan. That fall came in steps over three or four days, and I cannot separate those changes from the weather. It is why the comparison above uses only the days just before the fan.
    • No power settings changed. The router’s configuration history goes back to 13 October (30 revisions) and shows no change to power settings, thermal settings or tunables in that time.
    • I did not control the load. These are ordinary days on a home network.
    • It is one router in one cabinet.
    A hunch I did not prove: the dashboard

    On 13 October, with about 20 hours of uptime, I compared CPU time by process. Unbound, the DNS resolver, had used 16 seconds, about 0.02 per cent of one core, while answering about 10,000 unwanted lookups a day from devices on the network. The PHP processes that serve the web interface and the API had used 5 minutes 9 seconds, about 20 times as much, and that snapshot misses PHP workers that had already exited.

    Even so, 5 minutes in 20 hours is about 0.4 per cent of one core. If the open dashboard, whose widgets refresh every few seconds, raised the temperature, it did so in short bursts. I suspected those bursts behind some 78 °C spikes I saw that week. I did not test it.

    Reading your own router

    OPNsense draws its health records under Reporting → Health. To look at the CPU temperature graph:

    1. Open the router’s web interface in a browser: type the address you use to manage the router into the address bar, press Enter, and log in. If you do not know the address, ask whoever set the router up. A router uses its own security certificate, so the browser may warn that the connection is not private; for your own router’s address that is expected. Click Advanced, then the link that continues to the address (Proceed in Chrome, Accept the Risk and Continue in Firefox).
    2. In the menu, open Reporting → Health. The page loads in a few seconds and changes nothing. It lists its reports by topic.
    3. Find the CPU temperature report in the page’s list of reports. If there is none, open System → Settings → Miscellaneous → Thermal Sensors; mine is set to “Intel Core CPU on-die thermal sensor (coretemp)”. Changing that setting changes the router: write down the old value first, press Save*, and wait a few minutes while the router takes its readings. To undo it, choose the old value again; setting it back to none needs a reboot.

    The same data comes from the router’s API, at GET /api/diagnostics/systemhealth/get_system_health/cputemp-system/0. The number at the end picks an archive: /0 is one value a minute, and higher numbers are coarser. How long each lasts depends on when the router’s temperature database was created:

    Archive My router (database from an older OPNsense) A new OPNsense 26.x install
    /0 1 minute, 1,000 slots: 16 hours 40 minutes 1 minute, 1,200 slots: 20 hours
    /1 5 minutes, 1,000 slots: about 3½ days 5 minutes, 720 slots: 60 hours
    /2 1 hour, 1,000 slots: about 6 weeks 1 hour, 1,860 slots: about 11 weeks
    /3 12 hours, 3,000 slots: about 4 years 1 day, 2,284 slots: about 6 years

    OPNsense keeps an existing database through upgrades, so an older router keeps the older layout. The last column is from the 26.7 source code; I have not seen a new install.

    Two things follow. Read last night’s per-minute record this morning; by the evening those minutes are gone, and only the coarser averages remain. And the hourly archive is long enough for a before-and-after you did not plan. Mine already held a month of “before” when I fitted the fan.

    Deep dive: what the archives hold, and why hourly figures hide spikes

    The API serves only averages. OPNsense’s fetchData.py processes only the round-robin archives whose consolidation function is AVERAGE, and builds one “set” per archive. The router stores one instant reading of the sensor each minute; each hourly value is the average of those readings. A single reading of 91 °C barely moves it.

    Slots with no reading come back as empty values. The same script drops empty slots only at the start of a series. So the count of slots understates the archive’s length when its oldest slots are empty, as on a young database. The snippet below reports readings and empty slots separately.

    Deep dive: a console snippet to summarise your own router (for a PC)

    The Health graph shows the shape. This prints the numbers: the average, median, 95th percentile and maximum, and how many readings reached 80 °C, for one archive. It sends one read request (a GET) to the router’s own health API and changes nothing.

    Before you start

    • You need a PC with Chrome or Firefox, and a login to the router’s web interface that can open Reporting → Health.
    • You type in the browser’s developer console, on the router’s own page. You install nothing.
    • It takes two to three minutes.
    • It changes nothing on the router or the PC, so there is nothing to undo. Close the console when you finish.
    • In the boxes below, Copy copies the whole box. A dashed box shows what you should see; you do not type it.

    Steps

    1. Open the router’s web interface in Chrome or Firefox: type the address you use to manage the router into the address bar, press Enter, and log in. You should see the OPNsense dashboard. If no login page appears, check the address and that the PC is on the home network. If the browser warns that the connection is not private, see the note in step 1 of the graph steps above.
    2. Stay on any OPNsense page and open the browser console: Ctrl+Shift+J in Chrome or Ctrl+Shift+K in Firefox on Windows and Linux; Cmd+Option+J or Cmd+Option+K on a Mac. A panel opens beside or below the page, with a line to type on. If it opens on another tab, click the Console tab.
    3. Click Copy in the box below. It copies the whole snippet.

      // Paste into the browser console on any OPNsense page while logged in.
      // Read-only: one GET to the router's own health API. Changes nothing.
      (async () => {
        const LEVEL = 0; // archive: 0 is the finest (one value a minute); higher numbers are coarser. How many exist depends on the router.
        const url = '/api/diagnostics/systemhealth/get_system_health/cputemp-system/' + LEVEL;
        let d;
        try {
          const r = await fetch(url);
          if (r.status === 401) { console.log('HTTP 401: not logged in. Log in to the OPNsense web interface in this browser, then paste again.'); return; }
          if (r.status === 403) { console.log('HTTP 403: logged in, but this user may not read Reporting > Health. Use an account with that privilege.'); return; }
          if (!r.ok) { console.log('HTTP ' + r.status + ' from ' + url); return; }
          d = await r.json();
        } catch (e) {
          console.log('No JSON came back (' + e.message + '). Run this on an OPNsense page while logged in.'); return;
        }
        const series = d && d.set && d.set.data && d.set.data[0];
        if (!series || !Array.isArray(series.values)) { console.log('No temperature series at LEVEL ' + LEVEL + '. A higher LEVEL may not exist on this router; at LEVEL 0, check that Reporting > Health shows a CPU temperature graph.'); return; }
        const pts = series.values.filter(p => p[1] !== null && !isNaN(p[1]));
        const empty = series.values.length - pts.length;
        if (pts.length === 0) { console.log('The series ' + series.key + ' has no readings at this level.'); return; }
        const v = pts.map(p => p[1]).sort((a, b) => a - b);
        const n = v.length;
        const median = n % 2 ? v[(n - 1) / 2] : (v[n / 2 - 1] + v[n / 2]) / 2;
        const p95 = v[Math.min(n - 1, Math.ceil(0.95 * n) - 1)]; // nearest-rank
        const when = t => new Date(t).toLocaleString(); // your browser's time zone; each time marks the end of its interval
        console.log('Series ' + series.key + ', one value every ' + d.set.step_size + ' s');
        console.log('From ' + when(pts[0][0]) + ' to ' + when(pts[n - 1][0]) + ': ' + n + ' readings, ' + empty + ' empty slots');
        console.log('Average ' + (v.reduce((a, b) => a + b, 0) / n).toFixed(1) + ' °C, median ' + median.toFixed(1) +
          ', 95th percentile ' + p95.toFixed(1) + ', maximum ' + v[n - 1].toFixed(1));
        console.log('Readings at 80 °C or above: ' + v.filter(x => x >= 80).length);
      })();
    4. Click the line in the console, paste with Ctrl+V (Cmd+V on a Mac) and press Enter. Browsers may block pasting into the console, because pasting a stranger’s code into a logged-in page is a known trick. Read the snippet before you allow it. If the browser asks you to type “allow pasting”, do what its message says, then paste again.

    5. Within a second or two you should see four lines (ignore a line that starts with “Promise”): the series name, the time range with the number of readings and empty slots, the summary figures, and the count of readings at 80 °C or above. Times are in your browser’s time zone, and each marks the end of its interval. On my router, on 28 October 2026, it printed this (I left out the times; their format follows your browser’s settings):

      Series cpu0temp, one value every 60 s
      From <start time> to <end time>: 1000 readings, 0 empty slots
      Average 43.9 °C, median 47.7, 95th percentile 57.8, maximum 72.5
      Readings at 80 °C or above: 0
    6. “HTTP 401” means the browser is not logged in to OPNsense: log in and repeat step 4. “HTTP 403” means you are logged in as a user without access to Reporting → Health.

    7. To read the hourly archive, paste the snippet into a plain text editor first (Notepad on Windows, TextEdit set to plain text on a Mac), change const LEVEL = 0; to const LEVEL = 2;, copy all of it from there, and repeat steps 4 and 5.
    8. Compare the average with the level of the Reporting → Health graph for the same archive. They should agree.
    9. When you finish, close the panel with the × at its top right. Nothing was changed on the router.

    The verdict

    The case stays shut and the paste stays in its box.

    What is left is small. Fasten the fan, and lift it: rubber feet of 10 to 15 mm would hold it in place and let air reach the fins under its hub, which a fan lying flat starves. That is general practice for fans over heatsinks; I have not measured it here. Keep the side grille clear. The cabinet as a whole is a separate problem: the fan can cool the router only towards the temperature of the cabinet air, which is warmer than the room. I worked through that separately and may write it up.

    Before the fan, the heat was a reason to look at a new router. It is not any more.

    What I would tell someone with a fanless box in a warm cupboard

    1. Read what the router already records before you open anything. On OPNsense that is Reporting → Health, or the API above.
    2. Check how long each archive lasts on your router. It depends on when its database was created.
    3. Decide which result sends you to the next step, before you change anything.
    4. Judge averages, not single readings. Consecutive minute readings can differ by 30 °C.
    5. Try the cheap, reversible fix first, and weigh what it costs: a fan brings noise and dust to a box bought to have neither.
    Glossary
    • Fanless (passive) cooling: the case is the heatsink; heat leaves by conduction and natural airflow, with no fan.
    • Thermal paste / repaste: the compound between the CPU and the heatsink that fills microscopic gaps. Repasting means cleaning off the old compound and applying new.
    • P-core / E-core: Intel’s performance and efficient cores in one chip. The Pentium Gold 8505 has one of the first and four of the second.
    • TJUNCTION: the highest temperature Intel allows at the chip itself. For the 8505 it is 100 °C.
    • PWM: pulse-width modulation; a signal wire that tells a fan how fast to spin.
    • Round-robin database (RRD): a fixed-size store that keeps recent data at fine resolution and older data as coarser averages, overwriting the oldest.
    • Median / 95th percentile: the median is the middle reading (or the average of the two middle readings); 95 per cent of readings are at or below the 95th percentile.
    • API: the router’s programming interface; the same data the web pages show, returned as JSON.
    • Tunables: kernel settings that OPNsense applies at boot, listed under System → Settings → Tunables.

    Paste अब भी अपने डिब्बे में है

    15 अक्टूबर 2026 को मेरी मेज़ पर एक ही समस्या के दो इलाज रखे थे: ARCTIC MX-7 thermal paste की 4 g की ट्यूब और 120 mm का एक Noctua fan। समस्या मेरा router था: एक fanless mini PC, जो बंद plywood कैबिनेट में OPNsense चलाता है। एक दिन पहले उसका CPU 91 °C तक पहुँच गया था।

    ऑनलाइन जो सलाह मिली, वह यही थी कि case खोलो और paste बदल दो। मैंने पहले fan लगाया, क्योंकि उसके लिए screwdriver नहीं चाहिए था। लगाने से पहले मैंने तय कर लिया कि कौन-सा नतीजा मुझे वापस paste की ओर भेजेगा।

    उसकी ज़रूरत नहीं पड़ी। Router शुरू से अपना तापमान खुद दर्ज कर रहा था। 16 सितंबर से 15 अक्टूबर की शाम तक किसी भी घंटे का औसत 60 °C से नीचे नहीं गया। Fan लगने के बाद के चार दिनों में किसी भी घंटे का औसत 49 °C से ऊपर नहीं गया। Paste अब भी अपने डिब्बे में है।

    यह काम मैंने Anthropic के AI मॉडल Claude के साथ किया, जो मेरे अपने browser session के ज़रिए मेरा router पढ़ सकता था। Parts मैंने चुने, fan मैंने लगाया और नियम मैंने तय किया। तापमान के रिकॉर्ड Claude ने निकाले और हिसाब उसी ने लगाया। 28 अक्टूबर को इस पोस्ट के लिए उसने router का hourly data दोबारा पढ़ा।

    Box और कैबिनेट

    यह router छह port वाला fanless mini PC है, जो “Shenzhen Weibu” नाम से बिकता है। अंदर Intel Pentium Gold 8505 है: एक performance core और चार efficient cores, छह threads, 15 W base power और turbo में 55 W तक, Intel के specification पेज के अनुसार। इसमें 20 GB RAM और छह Intel I226-V 2.5 GbE ports हैं, और यह OPNsense 26.7 चलाता है। इसका case ही heatsink है। ऊपर का हिस्सा fins का एक ब्लॉक है।

    यह दूसरे network उपकरणों के साथ एक बंद plywood कैबिनेट में रखा है। कैबिनेट के साइड पैनल में झिरियों वाली एक ग्रिल ही गर्म हवा के निकलने का तय रास्ता है।

    Fan लगने से पहले router, USB वाले सिरे से: काला case, जिसका ऊपरी हिस्सा fins का ब्लॉक है, और बगल में कैबिनेट के साइड पैनल की झिरियों वाली ग्रिल

    क्या 91 °C ख़तरनाक था? Intel के आँकड़ों के हिसाब से नहीं। उसी पेज पर chip का अधिकतम junction तापमान (TJUNCTION) 100 °C दिया है, और उस सीमा पर processor ख़राब होने के बजाय अपनी रफ़्तार घटा लेता है। एक बात और: 91 °C सिर्फ़ उन readings में सबसे ऊँचा था जो router ने लीं; router sensor को मिनट में एक बार पढ़ता है, इसलिए बीच के peaks दर्ज नहीं हुए। फिर भी यह गर्मी नया router देखने की एक वजह बन गई थी। Hourly औसत दिन-रात 70 °C के आसपास रहता था, और SSD, memory और network chips उसी गर्म case में हैं। गर्मी आम तौर पर electronics की उम्र घटाती है, हालाँकि इस box पर मैंने न यह नापा, न SSD का तापमान।

    Fan पहले क्यों

    गर्म mini PC के लिए repaste आम सलाह है, और काफ़ी मुमकिन है कि उससे फ़ायदा होता। पर उसके लिए यह सब करना पड़ता:

    • पहले configuration का backup;
    • 99 प्रतिशत isopropyl alcohol और रेशे न छोड़ने वाले wipes;
    • 45 से 60 मिनट तक network बंद;
    • एक sealed case खोलना, जिसके screws और thermal pads मैंने कभी नहीं देखे थे।

    Fins पर रखे fan के लिए इनमें से कुछ नहीं चाहिए था, और उसे एक सेकंड में हटाया जा सकता था। उसके अपने नुक़सान भी हैं। वह वही छीन लेता है जिसके लिए fanless box लिया जाता है: न शोर, न खिंचकर आती धूल, न घिसने वाला कोई हिस्सा।

    इसलिए लगाने से पहले मैंने नियम तय किया: repaste तभी, जब fan लगे होने पर भी रात की readings 80 या उससे ऊपर पहुँचें।

    Fan

    मैंने Noctua NF-F12 5V PWM चुना। Noctua के specification के अनुसार यह 120 mm, 5 V, अधिकतम 1,500 rpm, सामान्यतः 0.65 W और पूरी रफ़्तार पर 22.4 dB(A) का है, और डिब्बे में USB power cable आती है। मेरा fan router के अपने ही एक USB port में लगा है। USB से चलाने पर fan को रफ़्तार का कोई signal नहीं मिलता, और Noctua की अपनी guide कहती है कि बिना signal के PWM fan पूरी रफ़्तार पर चलता है। Noctua इस पर “5V PWM version, not for use in PCs” लिखता है, यानी यह 5V PWM संस्करण है, PC में इस्तेमाल के लिए नहीं: PC का 12 V fan header इसके लिए ग़लत supply है।

    मेरे router पर 120 mm का fan ऊपरी सतह का ज़्यादातर हिस्सा ढक लेता है। Router के ऊपरी हिस्से के लगभग बराबर आकार का fan चुनें। Noctua छोटे आकारों में भी 5 V संस्करण बेचता है, जैसे 80 mm का NF-A8 5V PWM। कोई सस्ता 5 V USB fan भी हवा चलाएगा; मैंने ऐसा कोई fan आज़माया नहीं।

    मैंने इसे 15 अक्टूबर को लगभग 17:30 पर लगाया। यह ऊपर के fins पर सपाट रखा है, screws से कसा नहीं है, और हवा नीचे fins में फेंकता है। एक फ़ोटो पढ़ते हुए Claude ने पहले हवा की दिशा उल्टी बताई; मैंने frame पर बना तीर देखा। किसी भी दिशा में हवा चले, मदद मिलनी चाहिए, पर मैं जानना चाहता था कि मैं किस दिशा को नाप रहा हूँ।

    Router के fins वाले ऊपरी हिस्से पर सपाट रखा Noctua fan, ऊपर से देखने पर Network ports वाले सिरे से router: ports में cables लगे हैं और ऊपर fan रखा है

    Router ने क्या दर्ज किया

    OPNsense CPU तापमान मिनट में एक बार पढ़ता है और hourly औसत हफ़्तों तक रखता है। अपने router का तापमान कैसे पढ़ें, यह आगे है।

    16 सितंबर 2026 से fan लगने के चार दिन बाद तक router के CPU तापमान के hourly औसत का line chart। 9 अक्टूबर तक यह लगभग 65 से 74 °C के बीच रहता है, 10 अक्टूबर की configuration की सफ़ाई के दौरान 77 °C तक जाता है, फिर लगभग 60 से 71 °C के बीच टिकता है, और 15 अक्टूबर को 17:30 पर fan लगने के बाद वाले घंटे में लगभग 46 °C पर गिरकर वहीं रहता है।

    cpu0 के hourly औसत, router के hourly archive से:

    अवधि घंटे औसत सबसे ठंडा घंटा सबसे गर्म घंटा
    16 सितंबर – 9 अक्टूबर 567 69.7 °C 65.3 °C 73.7 °C
    11 अक्टूबर – 15 अक्टूबर, fan लगने तक 114 66.2 °C 60.5 °C 70.9 °C
    15 अक्टूबर, fan के बाद (चार दिन) 100 46.4 °C 42.6 °C 48.6 °C

    10 अक्टूबर मैंने छोड़ दिया है; उस दिन की configuration की सफ़ाई का ज़िक्र नीचे है। ठीक पहले के दिनों की तुलना में fan ने औसत लगभग 20 °C घटाया। पहले और बाद के दायरे एक-दूसरे को छूते नहीं: fan से पहले का सबसे ठंडा घंटा, बाद के सबसे गर्म घंटे से 12 °C ज़्यादा गर्म था।

    मैंने जो नियम तय किया था, वह रात की readings के बारे में था। 15 अक्टूबर को मैंने per-minute रिकॉर्ड से 03:00–10:00 का समय पढ़ा, और 16 अक्टूबर को वही समय फिर पढ़ा:

    cpu0, 03:00–10:00 15 अक्टूबर, बिना fan 16 अक्टूबर, fan के साथ
    औसत 65.6 °C 46.7 °C
    अधिकतम 90.3 °C 73.6 °C
    80 °C या उससे ऊपर की readings 19 0

    कोई reading 80 या उससे ऊपर नहीं पहुँची। नियम के मुताबिक़ case बंद ही रहना था।

    मेरा नियम अकेली readings पर टिका था, और अकेली readings उछलती हैं। हर reading एक पल की होती है: 28 अक्टूबर को लगातार मिनटों में 35.3, 68.2, 69.0 और 35.7 °C दर्ज हुए। घंटों का औसत बेहतर कसौटी होता। Hourly औसत के हिसाब से अंतर और भी बड़ा है: fan के बाद कोई घंटा 48.6 °C से ऊपर नहीं गया।

    गहराई से: 15 अक्टूबर के per-minute समय-खंड

    15 अक्टूबर को per-minute रिकॉर्ड से पढ़ा गया।

    समय, 15 अक्टूबर 2026 Readings औसत Median 95th percentile अधिकतम 80 °C या ऊपर
    03:00–10:00, बिना fan 420 65.6 °C 69.0 °C 79.8 °C 90.3 °C 19
    12:00–17:20, बिना fan 320 65.5 °C 68.7 °C 80.1 °C 90.7 °C 16
    17:31–19:12, fan के साथ 101 46.0 °C 48.7 °C 60.5 °C 69.6 °C 0
    19:20–19:37, firmware update और reboot के बाद 17 54.1 °C 57.1 °C 70.8 °C 70.8 °C 0

    आख़िरी पंक्ति ज़्यादा है, क्योंकि router अभी-अभी firmware update के बाद reboot हुआ था और लगभग 27 लाख blocklist entries लोड कर रहा था। यह आराम की स्थिति का आँकड़ा नहीं है।

    यह क्या दिखाता है और क्या नहीं

    यह दिखाता है कि यहाँ एक fan काफ़ी था। इससे यह साबित नहीं होता कि repaste से भी फ़ायदा न होता; मैंने उसे कभी आज़माया नहीं। Fan कैबिनेट से गर्मी बाहर नहीं निकालता। वह कैबिनेट की हवा को router के fins के बीच से धकेलता है। बंद कैबिनेट ने शुरुआती स्थिति को और बिगाड़ा था, इसलिए यहाँ का फ़ायदा शायद खुली हवा में होने वाले फ़ायदे से ज़्यादा है।

    • मैंने कमरे का तापमान नहीं नापा। गिरावट एक घंटे के भीतर आई, और कोई कमरा एक घंटे में 20 °C ठंडा नहीं होता। साथ ही, router पर दिन-रात के चक्र का असर कम पड़ता है: 16 सितंबर से 9 अक्टूबर तक दिन के हर घंटे का औसत 69.2 और 70.3 °C के बीच रहा, यानी लगभग 1 °C का उतार-चढ़ाव।
    • उसी शाम firmware बदला। Router पर 15 अक्टूबर को 19:12 पर firmware update हुआ। गिरावट पहले आई: fan लगने और update के बीच के 101 मिनटों का औसत 46.0 °C था।
    • Configuration की सफ़ाई पाँच दिन पहले हुई थी। 10 अक्टूबर को मैंने एक WireGuard VPN client हटाया, बिना इस्तेमाल पड़ा एक proxy stack (Squid, ClamAV, Redis और उनके साथी) और उसे traffic भेजने वाले NAT rules हटाए, अपनी DNS blocklists छाँटीं, और एक USB network adapter निकाल दिया। Hourly औसत 16 सितंबर से 9 अक्टूबर तक 69.7 °C था और 11 अक्टूबर से fan लगने तक 66.2 °C। यह गिरावट तीन-चार दिनों में क़दम-दर-क़दम आई, और मैं उन बदलावों के असर को मौसम से अलग नहीं कर सकता। इसी वजह से ऊपर की तुलना में सिर्फ़ fan से ठीक पहले के दिन लिए गए हैं।
    • कोई power settings नहीं बदलीं। Router का configuration history 13 अक्टूबर से शुरू होता है (30 revisions) और तब से power settings, thermal settings या tunables में कोई बदलाव नहीं दिखाता।
    • मैंने load को नियंत्रित नहीं किया। ये घर के network के आम दिन हैं।
    • यह सिर्फ़ एक router है, एक ही कैबिनेट में।
    एक अनुमान जो मैंने साबित नहीं किया: dashboard

    13 अक्टूबर को, लगभग 20 घंटे के uptime पर, मैंने process के हिसाब से CPU time की तुलना की। DNS resolver Unbound ने 16 सेकंड लिए थे, यानी एक core का लगभग 0.02 प्रतिशत, जबकि वह network के devices से रोज़ आने वाले लगभग 10,000 अनचाहे lookups का जवाब दे रहा था। Web interface और API चलाने वाले PHP processes ने 5 मिनट 9 सेकंड लिए थे, लगभग 20 गुना, और उस snapshot में वे PHP workers नहीं गिने गए जो तब तक बंद हो चुके थे।

    फिर भी, 20 घंटों में 5 मिनट एक core का लगभग 0.4 प्रतिशत है। अगर खुले dashboard ने, जिसके widgets हर कुछ सेकंड में refresh होते हैं, तापमान बढ़ाया, तो छोटे-छोटे झटकों में बढ़ाया। उस हफ़्ते दिखे कुछ 78 °C वाले spikes के पीछे मुझे इन्हीं झटकों का शक था। मैंने इसकी जाँच नहीं की।

    अपने router को पढ़ना

    OPNsense अपने health रिकॉर्ड Reporting → Health में ग्राफ़ के रूप में दिखाता है। CPU तापमान का ग्राफ़ देखने के लिए:

    1. Browser में router का web interface खोलें: address bar में वह पता लिखें जिससे आप router का प्रबंधन करते हैं, Enter दबाएँ, और log in करें। अगर आपको पता न मालूम हो, तो जिसने router लगाया था उससे पूछ लें। Router अपना ही security certificate इस्तेमाल करता है, इसलिए browser चेतावनी दे सकता है कि connection private नहीं है; आपके अपने router के पते के लिए यह अपेक्षित है। Advanced पर click करें, फिर उस link पर जो पते पर आगे बढ़ाता है (Chrome में Proceed, Firefox में Accept the Risk and Continue)।
    2. Menu में Reporting → Health खोलें। पेज कुछ सेकंड में लोड होता है और कुछ नहीं बदलता। यह अपनी reports को विषय के हिसाब से सूचीबद्ध करता है।
    3. पेज की reports की सूची में CPU तापमान की report ढूँढें। अगर कोई न हो, तो System → Settings → Miscellaneous → Thermal Sensors खोलें; मेरे यहाँ यह “Intel Core CPU on-die thermal sensor (coretemp)” पर सेट है। इस setting को बदलने से router बदल जाता है: पहले पुराना मान लिख लें, Save* दबाएँ, और कुछ मिनट रुकें जब तक router अपनी readings न ले ले। इसे पलटने के लिए पुराना मान फिर चुनें; इस setting को वापस none पर करने के लिए reboot चाहिए।

    यही data router के API से भी मिलता है, GET /api/diagnostics/systemhealth/get_system_health/cputemp-system/0 पर। आख़िर का अंक एक archive चुनता है: /0 में हर मिनट का एक मान है, और बड़े अंकों वाले archives में मान लंबे अंतराल पर होते हैं, यानी कम बारीक। हर archive कितनी देर का है, यह इस पर निर्भर है कि router का तापमान database कब बना था:

    Archive मेरा router (पुराने OPNsense से बना database) नया OPNsense 26.x install
    /0 1 मिनट, 1,000 slots: 16 घंटे 40 मिनट 1 मिनट, 1,200 slots: 20 घंटे
    /1 5 मिनट, 1,000 slots: लगभग 3½ दिन 5 मिनट, 720 slots: 60 घंटे
    /2 1 घंटा, 1,000 slots: लगभग 6 हफ़्ते 1 घंटा, 1,860 slots: लगभग 11 हफ़्ते
    /3 12 घंटे, 3,000 slots: लगभग 4 साल 1 दिन, 2,284 slots: लगभग 6 साल

    OPNsense upgrade के बाद भी मौजूदा database को बनाए रखता है, इसलिए पुराना router पुराना layout ही रखता है। आख़िरी कॉलम 26.7 के source code से है; मैंने कोई नया install नहीं देखा।

    इससे दो बातें निकलती हैं। पिछली रात का per-minute रिकॉर्ड आज सुबह पढ़ें; शाम तक वे मिनट जा चुके होते हैं और सिर्फ़ लंबे अंतराल के औसत बचते हैं। और hourly archive इतना लंबा है कि बिना योजना के भी पहले-और-बाद की तुलना हो जाती है। Fan लगाते समय मेरे archive में एक महीने का “पहले” दर्ज हो चुका था।

    गहराई से: archives में क्या रहता है, और hourly आँकड़े spikes क्यों छिपा लेते हैं

    API सिर्फ़ औसत देता है। OPNsense की fetchData.py केवल उन round-robin archives को process करती है जिनका consolidation function AVERAGE है, और हर archive का एक “set” बनाती है। Router हर मिनट sensor की एक तात्कालिक reading रखता है; हर hourly मान उन readings का औसत है। 91 °C की एक अकेली reading उसे मुश्किल से हिलाती है।

    जिन slots में कोई reading नहीं है, वे ख़ाली मानों के रूप में लौटते हैं। यही script ख़ाली slots को सिर्फ़ series की शुरुआत में हटा देती है। इसलिए जब archive के सबसे पुराने slots ख़ाली हों, जैसे नए database में, तो slots की गिनती archive की लंबाई को कम करके दिखाती है। नीचे का snippet readings और ख़ाली slots अलग-अलग बताता है।

    गहराई से: अपने router का सार निकालने के लिए एक console snippet (PC के लिए)

    Health ग्राफ़ उतार-चढ़ाव का रूप दिखाता है। यह snippet आँकड़े छापता है: एक archive के लिए औसत, median, 95th percentile और अधिकतम, और कितनी readings 80 °C तक पहुँचीं। यह router के अपने health API को एक read request (एक GET) भेजता है और कुछ नहीं बदलता।

    शुरू करने से पहले

    • आपको Chrome या Firefox वाला PC चाहिए, और router के web interface का ऐसा login जो Reporting → Health खोल सके।
    • आप browser के developer console में, router के अपने पेज पर टाइप करते हैं। कुछ install नहीं करना पड़ता।
    • इसमें दो से तीन मिनट लगते हैं।
    • यह router या PC पर कुछ नहीं बदलता, इसलिए वापस करने को कुछ नहीं है। काम पूरा होने पर console बंद कर दें।
    • नीचे के डिब्बों में Copy पूरे डिब्बे को copy करता है। टूटी रेखाओं वाला डिब्बा वह दिखाता है जो आपको दिखना चाहिए; उसे आप टाइप नहीं करते।

    चरण

    1. Chrome या Firefox में router का web interface खोलें: address bar में वह पता लिखें जिससे आप router का प्रबंधन करते हैं, Enter दबाएँ, और log in करें। आपको OPNsense का dashboard दिखना चाहिए। अगर login पेज न दिखे, तो पता जाँचें और देखें कि PC घर के network पर है। अगर browser चेतावनी दे कि connection private नहीं है, तो ऊपर graph के चरणों के चरण 1 में दिया note देखें।
    2. किसी भी OPNsense पेज पर रहते हुए browser console खोलें: Windows और Linux पर Chrome में Ctrl+Shift+J या Firefox में Ctrl+Shift+K; Mac पर Cmd+Option+J या Cmd+Option+K। पेज के बगल में या नीचे एक panel खुलता है, जिसमें टाइप करने के लिए एक पंक्ति होती है। अगर वह किसी दूसरे tab पर खुले, तो Console tab पर click करें।
    3. नीचे के डिब्बे में Copy दबाएँ। यह पूरा snippet copy कर लेता है।

      // Paste into the browser console on any OPNsense page while logged in.
      // Read-only: one GET to the router's own health API. Changes nothing.
      (async () => {
        const LEVEL = 0; // archive: 0 is the finest (one value a minute); higher numbers are coarser. How many exist depends on the router.
        const url = '/api/diagnostics/systemhealth/get_system_health/cputemp-system/' + LEVEL;
        let d;
        try {
          const r = await fetch(url);
          if (r.status === 401) { console.log('HTTP 401: not logged in. Log in to the OPNsense web interface in this browser, then paste again.'); return; }
          if (r.status === 403) { console.log('HTTP 403: logged in, but this user may not read Reporting > Health. Use an account with that privilege.'); return; }
          if (!r.ok) { console.log('HTTP ' + r.status + ' from ' + url); return; }
          d = await r.json();
        } catch (e) {
          console.log('No JSON came back (' + e.message + '). Run this on an OPNsense page while logged in.'); return;
        }
        const series = d && d.set && d.set.data && d.set.data[0];
        if (!series || !Array.isArray(series.values)) { console.log('No temperature series at LEVEL ' + LEVEL + '. A higher LEVEL may not exist on this router; at LEVEL 0, check that Reporting > Health shows a CPU temperature graph.'); return; }
        const pts = series.values.filter(p => p[1] !== null && !isNaN(p[1]));
        const empty = series.values.length - pts.length;
        if (pts.length === 0) { console.log('The series ' + series.key + ' has no readings at this level.'); return; }
        const v = pts.map(p => p[1]).sort((a, b) => a - b);
        const n = v.length;
        const median = n % 2 ? v[(n - 1) / 2] : (v[n / 2 - 1] + v[n / 2]) / 2;
        const p95 = v[Math.min(n - 1, Math.ceil(0.95 * n) - 1)]; // nearest-rank
        const when = t => new Date(t).toLocaleString(); // your browser's time zone; each time marks the end of its interval
        console.log('Series ' + series.key + ', one value every ' + d.set.step_size + ' s');
        console.log('From ' + when(pts[0][0]) + ' to ' + when(pts[n - 1][0]) + ': ' + n + ' readings, ' + empty + ' empty slots');
        console.log('Average ' + (v.reduce((a, b) => a + b, 0) / n).toFixed(1) + ' °C, median ' + median.toFixed(1) +
          ', 95th percentile ' + p95.toFixed(1) + ', maximum ' + v[n - 1].toFixed(1));
        console.log('Readings at 80 °C or above: ' + v.filter(x => x >= 80).length);
      })();
    4. Console की पंक्ति पर click करें, Ctrl+V (Mac पर Cmd+V) से paste करें और Enter दबाएँ। Browsers console में paste करना रोक सकते हैं, क्योंकि logged-in पेज में किसी अजनबी का code paste करवाना एक जानी-पहचानी चाल है। अनुमति देने से पहले snippet पढ़ लें। अगर browser “allow pasting” टाइप करने को कहे, तो उसके संदेश के अनुसार करें, फिर दोबारा paste करें।

    5. एक-दो सेकंड में चार पंक्तियाँ दिखनी चाहिए (“Promise” से शुरू होने वाली पंक्ति को छोड़ दें): series का नाम, readings और ख़ाली slots की संख्या के साथ समय की अवधि, सार के आँकड़े, और 80 °C या उससे ऊपर की readings की गिनती। समय आपके browser के time zone में होते हैं, और हर समय अपने अंतराल का अंत बताता है। 28 अक्टूबर 2026 को मेरे router पर इसने यह छापा (मैंने समय छोड़ दिए हैं; उनका रूप आपके browser की settings पर निर्भर करता है):

      Series cpu0temp, one value every 60 s
      From <start time> to <end time>: 1000 readings, 0 empty slots
      Average 43.9 °C, median 47.7, 95th percentile 57.8, maximum 72.5
      Readings at 80 °C or above: 0
    6. “HTTP 401” का मतलब है कि browser OPNsense में logged in नहीं है: log in करें और चरण 4 दोहराएँ। “HTTP 403” का मतलब है कि आप ऐसे user से logged in हैं जिसे Reporting → Health की अनुमति नहीं है।

    7. Hourly archive पढ़ने के लिए snippet को पहले किसी plain text editor में paste करें (Windows पर Notepad, Mac पर plain text पर सेट TextEdit), const LEVEL = 0; को const LEVEL = 2; करें, वहाँ से पूरा copy करें, और चरण 4 और 5 दोहराएँ।
    8. औसत की तुलना उसी archive के Reporting → Health ग्राफ़ के level से करें। दोनों मेल खाने चाहिए।
    9. काम पूरा होने पर panel को उसके ऊपर दाईं ओर के × से बंद करें। Router पर कुछ नहीं बदला गया।

    फ़ैसला

    Case बंद रहेगा और paste अपने डिब्बे में।

    जो बचा है वह छोटा है। Fan को अपनी जगह पर पक्का करें, और उसे ऊपर उठाएँ: 10 से 15 mm के rubber feet उसे जगह पर रखेंगे और उसके hub के नीचे के fins तक हवा पहुँचने देंगे, जिन्हें सपाट पड़ा fan हवा से वंचित रखता है। Heatsinks के ऊपर लगे fans के लिए यह आम तरीका है; मैंने इसे यहाँ नापा नहीं। साइड की ग्रिल खुली रखें। पूरा कैबिनेट एक अलग समस्या है: fan router को ठंडा तो करता है, पर सिर्फ़ कैबिनेट की हवा के तापमान के क़रीब तक; और कैबिनेट की हवा कमरे की हवा से गर्म है। उस पर मैंने अलग से काम किया और शायद उस पर लिखूँ।

    Fan से पहले यह गर्मी नया router देखने की एक वजह थी। अब नहीं है।

    गर्म अलमारी में fanless box रखने वाले से मैं क्या कहूँगा

    1. पहले वह पढ़ें जो router पहले से दर्ज करता है, कुछ भी खोलने से पहले। OPNsense पर यह Reporting → Health है, या ऊपर वाला API।
    2. देखें कि आपके router पर हर archive कितनी देर का है। यह इस पर निर्भर है कि उसका database कब बना था।
    3. कुछ भी बदलने से पहले तय करें कि कौन-सा नतीजा आपको अगले कदम पर भेजेगा।
    4. अकेली readings पर नहीं, औसत पर फ़ैसला करें। लगातार मिनटों की readings में 30 °C का अंतर हो सकता है।
    5. पहले सस्ता और वापस लिया जा सकने वाला उपाय आज़माएँ, और उसकी क़ीमत भी तौलें: fan उस box में शोर और धूल लाता है जो इन दोनों से बचने के लिए लिया गया था।
    शब्दावली
    • Fanless (passive) cooling: case ही heatsink है; गर्मी बिना fan के, चालन और हवा के प्राकृतिक बहाव से निकलती है।
    • Thermal paste / repaste: CPU और heatsink के बीच का वह पदार्थ जो सूक्ष्म खाली जगहें भरता है। Repaste का मतलब पुराना पदार्थ साफ़ करके नया लगाना।
    • P-core / E-core: एक ही chip में Intel के performance और efficient cores। Pentium Gold 8505 में पहले वाला एक और दूसरे वाले चार हैं।
    • TJUNCTION: ख़ुद chip के भीतर Intel द्वारा अनुमत सबसे ऊँचा तापमान। 8505 के लिए यह 100 °C है।
    • PWM: pulse-width modulation; एक signal तार जो fan को बताता है कि कितनी तेज़ घूमे।
    • Round-robin database (RRD): तय आकार का भंडार, जो हाल का data बारीक रूप में और पुराना data लंबे अंतराल के औसत के रूप में रखता है, और सबसे पुराने को मिटाकर लिखता है।
    • Median / 95th percentile: median बीच की reading है (या दो बीच वाली readings का औसत); 95 प्रतिशत readings 95th percentile के बराबर या उससे नीचे होती हैं।
    • API: router का programming interface; वही data जो web पेज दिखाते हैं, JSON के रूप में।
    • Tunables: kernel settings जिन्हें OPNsense boot के समय लागू करता है; ये System → Settings → Tunables में सूचीबद्ध हैं।

    Paste ఇంకా దాని పెట్టెలోనే ఉంది

    15 అక్టోబర్ 2026న నా డెస్క్ మీద ఒకే సమస్యకు రెండు పరిష్కారాలు ఉన్నాయి: 4 g ARCTIC MX-7 thermal paste ట్యూబ్ ఒకటి, 120 mm Noctua fan ఒకటి. సమస్య నా router. అది మూసి ఉన్న ప్లైవుడ్ క్యాబినెట్‌లో OPNsense నడుపుతున్న ఒక fanless mini PC. అంతకు ముందు రోజు దాని CPU 91 °C ను తాకింది.

    ఆన్‌లైన్‌లో నాకు దొరికిన సలహా కేస్ తెరిచి paste మార్చమని. స్క్రూడ్రైవర్ అవసరం లేదు కాబట్టి నేను ముందు fan పెట్టాను. పెట్టే ముందే, ఏ ఫలితం వస్తే paste దగ్గరకు తిరిగి వెళ్ళాలో నిర్ణయించుకున్నాను.

    ఆ అవసరం రాలేదు. Router మొదటి నుంచీ తన ఉష్ణోగ్రతను తానే నమోదు చేసుకుంటూ ఉంది. 16 సెప్టెంబర్ నుంచి 15 అక్టోబర్ సాయంత్రం వరకు, ఏ గంట సగటూ 60 °C కంటే తక్కువ లేదు. Fan పెట్టిన తర్వాతి నాలుగు రోజుల్లో, ఏ గంట సగటూ 49 °C దాటలేదు. Paste ఇంకా దాని పెట్టెలోనే ఉంది.

    ఈ పని నేను Anthropic తయారుచేసిన AI మోడల్ Claude తో కలిసి చేశాను. అది నా సొంత బ్రౌజర్ సెషన్ ద్వారా నా router ను చదవగలిగింది. పార్టులు నేను ఎంచుకున్నాను, fan నేను పెట్టాను, నియమం నేను పెట్టాను. Claude ఉష్ణోగ్రత రికార్డులు తీసి లెక్కలు చేసింది. 28 అక్టోబర్‌న ఈ పోస్ట్ కోసం router గంటవారీ డేటాను మళ్ళీ చదివి చెప్పింది.

    బాక్స్, క్యాబినెట్

    ఈ router ఆరు పోర్టులు ఉన్న ఒక fanless mini PC. దీన్ని “Shenzhen Weibu” పేరుతో అమ్ముతారు. లోపల Intel Pentium Gold 8505 ఉంది. Intel స్పెసిఫికేషన్ పేజీ ప్రకారం దానిలో ఒక పెర్ఫార్మెన్స్ కోర్, నాలుగు ఎఫిషియెంట్ కోర్లు, ఆరు థ్రెడ్లు ఉన్నాయి; బేస్ పవర్ 15 W, టర్బోలో 55 W వరకు. దీనికి 20 GB RAM, ఆరు Intel I226-V 2.5 GbE పోర్టులు ఉన్నాయి. ఇది OPNsense 26.7 నడుపుతుంది. కేసే heatsink. దాని పైభాగం fins ఉన్న ఒక బ్లాక్.

    ఇది ఇతర నెట్‌వర్క్ పరికరాలతో కలిసి మూసి ఉన్న ఒక ప్లైవుడ్ క్యాబినెట్‌లో ఉంటుంది. క్యాబినెట్ పక్క ప్యానెల్‌లోని చీలికల గ్రిల్ ఒక్కటే వేడి గాలి బయటకు పోవడానికి అనుకున్న దారి.

    Fan పెట్టక ముందు router, USB వైపు నుంచి: పైభాగం fins బ్లాక్‌గా ఉన్న నల్లటి కేస్, పక్కనే క్యాబినెట్ పక్క ప్యానెల్‌లోని చీలికల గ్రిల్

    91 °C ప్రమాదకరమా? Intel అంకెల ప్రకారం కాదు. అదే పేజీ చిప్ గరిష్ఠ junction ఉష్ణోగ్రత (TJUNCTION) 100 °C అని చెబుతుంది. ఆ పరిమితికి చేరిన ప్రాసెసర్ పాడవడానికి బదులు తన వేగాన్ని తానే తగ్గించుకుంటుంది. పైగా 91 °C అనేది నమోదైన రీడింగుల్లో అత్యధికం మాత్రమే; router సెన్సార్‌ను నిమిషానికి ఒకసారి చదువుతుంది, కాబట్టి రెండు రీడింగుల మధ్య వచ్చిన గరిష్ఠాలు నమోదు కాలేదు. అయినా, ఈ వేడి కొత్త router చూడడానికి ఒక కారణంగా మారింది. గంటవారీ సగటు పగలూ రాత్రీ 70 °C దగ్గరే ఉంది, SSD, మెమరీ, నెట్‌వర్క్ చిప్‌లు అదే వేడి కేస్‌లో ఉంటాయి. సాధారణంగా వేడి ఎలక్ట్రానిక్స్ ఆయుష్షును తగ్గిస్తుంది, కానీ ఆ ప్రభావాన్ని గానీ SSD ఉష్ణోగ్రతను గానీ ఈ బాక్స్ మీద నేను కొలవలేదు.

    Fan ఎందుకు ముందు

    వేడెక్కే mini PC కి repaste అనేది మామూలుగా ఇచ్చే సలహా, అది సహాయపడి ఉండవచ్చు కూడా. కానీ దానికి ఇవి కూడా అవసరమయ్యేవి:

    • ముందుగా ఒక కాన్ఫిగరేషన్ బ్యాకప్;
    • 99 శాతం ఐసోప్రొపైల్ ఆల్కహాల్, పోగులు వదలని వైప్స్;
    • నెట్‌వర్క్ 45 నుంచి 60 నిమిషాలు ఆఫ్‌లైన్‌లో ఉండడం;
    • నేను ఎప్పుడూ చూడని స్క్రూలు, thermal pads ఉన్న సీల్ చేసిన కేస్‌ను తెరవడం.

    Fins మీద పడుకోబెట్టిన fan కి అవేవీ అవసరం లేదు, దాన్ని ఒక్క క్షణంలో తీసేయొచ్చు కూడా. దానికీ దాని నష్టాలు ఉన్నాయి. Fanless బాక్స్ దేనికోసమో దాన్నే ఇది వదులుకుంటుంది: శబ్దం లేకపోవడం, దుమ్ము లోపలికి రాకపోవడం, అరిగిపోయే కదిలే భాగం లేకపోవడం.

    అందుకే పెట్టే ముందే నియమం పెట్టుకున్నాను: fan ఉన్నా రాత్రి రీడింగులు ఇంకా 80ల్లోకి వెళ్తేనే repaste.

    Fan

    నేను Noctua NF-F12 5V PWM ఎంచుకున్నాను. Noctua స్పెసిఫికేషన్ ప్రకారం ఇది 120 mm, 5 V, 1,500 rpm వరకు, సాధారణంగా 0.65 W, పూర్తి వేగంలో 22.4 dB(A); బాక్స్‌లో ఒక USB పవర్ కేబుల్ ఉంటుంది. నా fan router లోని ఒక USB పోర్టుకు కనెక్ట్ అయి ఉంది. USB నుంచి పవర్ ఇస్తే fan కి వేగాన్ని చెప్పే సిగ్నల్ ఏదీ అందదు. సిగ్నల్ లేని PWM fan పూర్తి వేగంతో తిరుగుతుందని Noctua సొంత గైడ్ చెబుతుంది. Noctua దీని మీద “5V PWM version, not for use in PCs” అని గుర్తు పెడుతుంది, అంటే ఇది 5V PWM వెర్షన్, PC లలో వాడడానికి కాదు: PC లోని 12 V fan header దీనికి తగిన సప్లై కాదు.

    నా router మీద 120 mm fan పైభాగంలో ఎక్కువ భాగాన్ని కప్పుతుంది. Router పైభాగం పరిమాణానికి దగ్గరగా ఉండే fan ను ఎంచుకోండి. Noctua చిన్న పరిమాణాల్లోనూ 5 V వెర్షన్లు అమ్ముతుంది, ఉదాహరణకు 80 mm NF-A8 5V PWM. చౌకైన 5 V USB fan కూడా గాలిని కదిలిస్తుంది; నేను అలాంటిది ప్రయత్నించలేదు.

    15 అక్టోబర్‌న సుమారు 17:30కి దీన్ని పెట్టాను. ఇది పై fins మీద స్క్రూలు లేకుండా సమతలంగా పడుకుని ఉంది, వాటిలోకి కిందికి గాలి ఊదుతుంది. ఫోటో చూసి చదివినప్పుడు Claude మొదట గాలి దిశను తారుమారుగా చెప్పింది; ఫ్రేమ్‌లో అచ్చుపోసిన బాణాన్ని నేను చెక్ చేశాను. ఏ దిశ అయినా సహాయపడాలి, కానీ నేను కొలుస్తున్నది ఏ దిశనో తెలుసుకోవాలనుకున్నాను.

    router fins ఉన్న పైభాగం మీద సమతలంగా పడుకున్న Noctua fan, పై నుంచి చూసినప్పుడు నెట్‌వర్క్ పోర్టుల వైపు నుంచి router, పోర్టులకు కేబుల్స్ ఉన్నాయి, పైన fan ఉంది

    Router ఏమి నమోదు చేసింది

    OPNsense నిమిషానికి ఒకసారి CPU ఉష్ణోగ్రతను చదువుతుంది, గంటవారీ సగటులను వారాల తరబడి ఉంచుతుంది. మీ router ది ఎలా చదవాలో కింద ఉంది.

    16 సెప్టెంబర్ 2026 నుంచి fan పెట్టిన నాలుగు రోజుల తర్వాత వరకు router గంటవారీ సగటు CPU ఉష్ణోగ్రత లైన్ చార్ట్. 9 అక్టోబర్ వరకు ఇది సుమారు 65 నుంచి 74 °C మధ్య ఉంటుంది, 10 అక్టోబర్ క్లీన్-అప్ సమయంలో 77 °C గరిష్ఠానికి చేరుతుంది, తర్వాత సుమారు 60 నుంచి 71 °C మధ్య స్థిరపడుతుంది, 15 అక్టోబర్ 17:30కి fan పెట్టిన తర్వాతి గంటలో సుమారు 46 °C కి పడిపోయి అక్కడే ఉంటుంది.

    Router గంటవారీ archive నుంచి, cpu0 గంటవారీ సగటులు:

    కాలం గంటలు సగటు అతి తక్కువ గంట సగటు అతి ఎక్కువ గంట సగటు
    16 సెప్టెంబర్ – 9 అక్టోబర్ 567 69.7 °C 65.3 °C 73.7 °C
    11 అక్టోబర్ – 15 అక్టోబర్, fan పెట్టే వరకు 114 66.2 °C 60.5 °C 70.9 °C
    15 అక్టోబర్, fan పెట్టిన తర్వాత (నాలుగు రోజులు) 100 46.4 °C 42.6 °C 48.6 °C

    10 అక్టోబర్‌ను వదిలేశాను; కింద వివరించిన కాన్ఫిగరేషన్ క్లీన్-అప్ జరిగిన రోజు అది. Fan కి వెంటనే ముందున్న రోజులతో పోలిస్తే, fan సగటు నుంచి సుమారు 20 °C తగ్గించింది. ముందు, తర్వాత పరిధులు ఒకదానితో ఒకటి కలవవు: fan కి ముందు అత్యంత చల్లని గంట, fan తర్వాత అత్యంత వేడి గంట కంటే 12 °C ఎక్కువ వేడిగా ఉంది.

    నేను పెట్టిన నియమం రాత్రి రీడింగుల గురించి. 15 అక్టోబర్‌న నిమిషవారీ రికార్డు నుంచి 03:00–10:00 విండోను చదివాను, 16 అక్టోబర్‌న అదే విండోను మళ్ళీ చదివాను:

    cpu0, 03:00–10:00 15 అక్టోబర్, fan లేకుండా 16 అక్టోబర్, fan తో
    సగటు 65.6 °C 46.7 °C
    గరిష్ఠం 90.3 °C 73.6 °C
    80 °C లేదా అంతకు పైన ఉన్న రీడింగులు 19 0

    ఏ రీడింగూ 80ల్లోకి చేరలేదు. నియమం ప్రకారం కేస్ మూసే ఉంచాలి.

    నా నియమం ఒక్కొక్క రీడింగును వాడింది, ఒక్కొక్క రీడింగు ఎగుడుదిగుడుగా ఉంటుంది. ప్రతి రీడింగూ ఒక క్షణం విలువ మాత్రమే: 28 అక్టోబర్‌న వరుస నిమిషాల్లో 35.3, 68.2, 69.0, 35.7 °C వచ్చాయి. కొన్ని గంటల సగటు అయితే మెరుగైన పరీక్ష అయ్యేది. గంటవారీ సగటుల ప్రకారం తేడా ఇంకా ఎక్కువ: fan తర్వాత ఏ గంట సగటూ 48.6 °C దాటలేదు.

    లోతైన వివరణ: 15 అక్టోబర్ నిమిషవారీ విండోలు

    15 అక్టోబర్‌న నిమిషవారీ రికార్డు నుంచి చదివినవి.

    విండో, 15 అక్టోబర్ 2026 రీడింగులు సగటు మీడియన్ 95వ పర్సెంటైల్ గరిష్ఠం 80 °C లేదా పైన
    03:00–10:00, fan లేకుండా 420 65.6 °C 69.0 °C 79.8 °C 90.3 °C 19
    12:00–17:20, fan లేకుండా 320 65.5 °C 68.7 °C 80.1 °C 90.7 °C 16
    17:31–19:12, fan తో 101 46.0 °C 48.7 °C 60.5 °C 69.6 °C 0
    19:20–19:37, firmware అప్‌డేట్, రీబూట్ తర్వాత 17 54.1 °C 57.1 °C 70.8 °C 70.8 °C 0

    చివరి వరుస ఎక్కువగా ఉంది, ఎందుకంటే router అప్పుడే firmware update తర్వాత రీబూట్ అయి, ఆ సమయంలో సుమారు 2.7 మిలియన్ blocklist ఎంట్రీలను లోడ్ చేస్తూ ఉంది. అది విశ్రాంతి స్థితిలోని అంకె కాదు.

    ఇది ఏమి చూపిస్తుంది, ఏమి చూపించదు

    ఇక్కడ fan సరిపోయిందని ఇది చూపిస్తుంది. Repaste కూడా సహాయపడేది కాదని ఇది చూపించదు; నేను repaste ప్రయత్నించలేదు. Fan క్యాబినెట్ నుంచి వేడిని బయటకు తీయదు. అది క్యాబినెట్ గాలిని router fins గుండా బలవంతంగా పంపుతుంది. మూసిన క్యాబినెట్ వల్ల మొదలుపెట్టిన స్థితి మరింత చెడ్డగా ఉండింది, కాబట్టి ఇక్కడ వచ్చిన మెరుగుదల బహిరంగ గాలిలో వచ్చేదానికంటే బహుశా ఎక్కువ.

    • గది ఉష్ణోగ్రతను నేను కొలవలేదు. తగ్గుదల ఒక్క గంటలోనే వచ్చింది, ఒక గది ఒక గంటలో 20 °C చల్లబడదు. Router రోజువారీ పగలు-రాత్రి చక్రానికి కూడా కొద్దిగానే స్పందిస్తుంది: 16 సెప్టెంబర్ నుంచి 9 అక్టోబర్ వరకు, రోజులోని ప్రతి గంట సగటు 69.2, 70.3 °C మధ్యే ఉంది, అంటే సుమారు 1 °C హెచ్చుతగ్గు.
    • అదే సాయంత్రం firmware మారింది. 15 అక్టోబర్ 19:12కి router firmware అప్‌డేట్ అయింది. తగ్గుదల ముందే వచ్చింది: fan పెట్టడానికీ అప్‌డేట్‌కీ మధ్య ఉన్న 101 నిమిషాల సగటు 46.0 °C.
    • ఐదు రోజుల ముందు ఒక కాన్ఫిగరేషన్ క్లీన్-అప్ జరిగింది. 10 అక్టోబర్‌న నేను ఒక WireGuard VPN క్లయింట్‌ను, వాడని ఒక ప్రాక్సీ స్టాక్‌ను (Squid, ClamAV, Redis, వాటితో పాటు ఉండేవి), దానికి ట్రాఫిక్ పంపే NAT రూల్స్‌ను తీసేశాను; నా DNS blocklists ను కుదించాను; ఒక USB నెట్‌వర్క్ అడాప్టర్ ప్లగ్ తీసేశాను. గంటవారీ సగటు 16 సెప్టెంబర్ నుంచి 9 అక్టోబర్ వరకు 69.7 °C, 11 అక్టోబర్ నుంచి fan వరకు 66.2 °C. ఆ తగ్గుదల మూడు నాలుగు రోజుల్లో దశలవారీగా వచ్చింది; ఆ మార్పుల ప్రభావాన్ని వాతావరణం ప్రభావం నుంచి నేను వేరు చేయలేను. అందుకే పైన ఉన్న పోలిక fan కి వెంటనే ముందున్న రోజులను మాత్రమే వాడుతుంది.
    • పవర్ సెట్టింగులు ఏవీ మారలేదు. Router కాన్ఫిగరేషన్ చరిత్ర 13 అక్టోబర్ నుంచి ఉంది (30 రివిజన్లు). ఆ కాలంలో పవర్ సెట్టింగులు, thermal సెట్టింగులు, tunables లో ఏ మార్పూ అది చూపించదు.
    • లోడ్‌ను నేను నియంత్రించలేదు. ఇవి ఇంటి నెట్‌వర్క్ మీద మామూలు రోజులు.
    • ఇది ఒక క్యాబినెట్‌లోని ఒక router మాత్రమే.
    నేను నిరూపించని ఒక అనుమానం: dashboard

    13 అక్టోబర్‌న, సుమారు 20 గంటల అప్‌టైమ్ తర్వాత, ప్రాసెస్ వారీగా CPU సమయాన్ని పోల్చాను. DNS రిసాల్వర్ అయిన Unbound 16 సెకన్లు వాడింది, అంటే ఒక కోర్‌లో సుమారు 0.02 శాతం; ఆ సమయంలో అది నెట్‌వర్క్‌లోని పరికరాల నుంచి వచ్చే రోజుకు సుమారు 10,000 అనవసరమైన లుకప్‌లకు సమాధానం ఇస్తోంది. వెబ్ ఇంటర్‌ఫేస్‌ను, API ని నడిపే PHP ప్రాసెస్‌లు 5 నిమిషాల 9 సెకన్లు వాడాయి, సుమారు 20 రెట్లు ఎక్కువ; అప్పటికే ముగిసిపోయిన PHP workers ను ఆ స్నాప్‌షాట్ లెక్కలోకి తీసుకోలేదు.

    అయినా, 20 గంటల్లో 5 నిమిషాలు అంటే ఒక కోర్‌లో సుమారు 0.4 శాతం. కొన్ని సెకన్లకు ఒకసారి రిఫ్రెష్ అయ్యే విడ్జెట్‌లు ఉన్న dashboard తెరిచి ఉండడం ఉష్ణోగ్రతను పెంచి ఉంటే, అది చిన్న బర్స్ట్‌లలోనే. ఆ వారం నేను చూసిన కొన్ని 78 °C స్పైక్‌ల వెనుక ఆ బర్స్ట్‌లు ఉన్నాయని అనుమానించాను. దాన్ని నేను పరీక్షించలేదు.

    మీ సొంత router ను చదవడం

    OPNsense తన health రికార్డులను Reporting → Health కింద గ్రాఫ్‌లుగా చూపిస్తుంది. CPU ఉష్ణోగ్రత గ్రాఫ్‌ను చూడడానికి:

    1. బ్రౌజర్‌లో router వెబ్ ఇంటర్‌ఫేస్ తెరవండి: router ను నిర్వహించడానికి మీరు వాడే చిరునామాను అడ్రస్ బార్‌లో టైప్ చేసి, Enter నొక్కి, లాగిన్ అవ్వండి. చిరునామా మీకు తెలియకపోతే, router ను సెటప్ చేసిన వారిని అడగండి. router తన సొంత సెక్యూరిటీ సర్టిఫికెట్‌ను వాడుతుంది, కాబట్టి కనెక్షన్ ప్రైవేట్ కాదని బ్రౌజర్ హెచ్చరించవచ్చు; మీ router చిరునామాకు అది సాధారణమే. Advanced క్లిక్ చేయండి, తర్వాత ఆ చిరునామాకు కొనసాగించే లింక్‌ను క్లిక్ చేయండి (Chrome లో Proceed, Firefox లో Accept the Risk and Continue).
    2. మెనూలో Reporting → Health తెరవండి. పేజీ కొన్ని సెకన్లలో లోడ్ అవుతుంది, ఏదీ మార్చదు. అది తన రిపోర్ట్‌లను అంశాల వారీగా జాబితా చేస్తుంది.
    3. CPU ఉష్ణోగ్రత రిపోర్ట్‌ను పేజీలోని రిపోర్ట్‌ల జాబితాలో కనుగొనండి. అది లేకపోతే, System → Settings → Miscellaneous → Thermal Sensors తెరవండి; నాది “Intel Core CPU on-die thermal sensor (coretemp)” కు సెట్ అయి ఉంది. ఆ సెట్టింగ్ మార్చడం router ను మారుస్తుంది: ముందు పాత విలువను రాసి పెట్టుకోండి, Save* నొక్కండి, router రీడింగులు తీసుకునే వరకు కొన్ని నిమిషాలు వేచి ఉండండి. దాన్ని వెనక్కి తీసుకోవడానికి, పాత విలువను మళ్ళీ ఎంచుకోండి; ఈ సెట్టింగ్‌ను తిరిగి none కు పెట్టడానికి reboot అవసరం.

    అదే డేటా router API నుంచి GET /api/diagnostics/systemhealth/get_system_health/cputemp-system/0 వద్ద వస్తుంది. చివరి అంకె ఒక archive ను ఎంచుకుంటుంది: /0 అంటే నిమిషానికి ఒక విలువ, అంతకంటే పెద్ద అంకెల archives మరింత స్థూలంగా ఉంటాయి. ఒక్కొక్కటి ఎంత కాలం ఉంటుందనేది router ఉష్ణోగ్రత డేటాబేస్ ఎప్పుడు సృష్టించారనే దాని మీద ఆధారపడుతుంది:

    Archive నా router (పాత OPNsense నుంచి వచ్చిన డేటాబేస్) కొత్త OPNsense 26.x ఇన్‌స్టాల్
    /0 1 నిమిషం, 1,000 స్లాట్లు: 16 గంటల 40 నిమిషాలు 1 నిమిషం, 1,200 స్లాట్లు: 20 గంటలు
    /1 5 నిమిషాలు, 1,000 స్లాట్లు: సుమారు 3½ రోజులు 5 నిమిషాలు, 720 స్లాట్లు: 60 గంటలు
    /2 1 గంట, 1,000 స్లాట్లు: సుమారు 6 వారాలు 1 గంట, 1,860 స్లాట్లు: సుమారు 11 వారాలు
    /3 12 గంటలు, 3,000 స్లాట్లు: సుమారు 4 సంవత్సరాలు 1 రోజు, 2,284 స్లాట్లు: సుమారు 6 సంవత్సరాలు

    అప్‌గ్రేడ్‌ల సమయంలో OPNsense ఉన్న డేటాబేస్‌ను అలాగే ఉంచుతుంది, కాబట్టి పాత router పాత అమరికనే కొనసాగిస్తుంది. చివరి కాలమ్ 26.7 సోర్స్ కోడ్ నుంచి తీసుకున్నది; కొత్త ఇన్‌స్టాల్‌ను నేను చూడలేదు.

    దీని నుంచి రెండు విషయాలు తెలుస్తాయి. నిన్న రాత్రి నిమిషవారీ రికార్డును ఈ ఉదయమే చదవండి; సాయంత్రానికి ఆ నిమిషాలు పోతాయి, స్థూల సగటులు మాత్రమే మిగులుతాయి. ఇంకా, గంటల archive ఎంత పొడవుగా ఉంటుందంటే, మీరు ప్లాన్ చేయని ముందు-తర్వాత పోలికకు కూడా అది సరిపోతుంది. నేను fan పెట్టేనాటికే నా router లో ఒక నెల “ముందు” డేటా ఉంది.

    లోతైన వివరణ: archives లో ఏముంటుంది, గంటవారీ అంకెలు స్పైక్‌లను ఎందుకు దాచేస్తాయి

    API సగటులను మాత్రమే ఇస్తుంది. OPNsense లోని fetchData.py consolidation function AVERAGE గా ఉన్న round-robin archives ను మాత్రమే ప్రాసెస్ చేస్తుంది, ప్రతి archive కి ఒక “set” తయారుచేస్తుంది. Router ప్రతి నిమిషం సెన్సార్ నుంచి ఆ క్షణపు రీడింగ్ ఒకటి నిల్వ చేస్తుంది; ప్రతి గంటవారీ విలువ ఆ రీడింగుల సగటు. 91 °C అనే ఒక్క రీడింగ్ దాన్ని దాదాపు కదిలించదు.

    రీడింగ్ లేని స్లాట్లు ఖాళీ విలువలుగా వస్తాయి. అదే స్క్రిప్ట్ ఖాళీ స్లాట్లను ఒక సిరీస్ మొదట్లో మాత్రమే తొలగిస్తుంది. కాబట్టి archive లోని అన్నిటికంటే పాత స్లాట్లు ఖాళీగా ఉన్నప్పుడు, అంటే కొత్త డేటాబేస్‌లో, స్లాట్ల లెక్క archive పొడవును తక్కువగా చూపిస్తుంది. కింది snippet రీడింగులను, ఖాళీ స్లాట్లను వేరువేరుగా చూపిస్తుంది.

    లోతైన వివరణ: మీ router సారాంశం చూపించే ఒక console snippet (PC కోసం)

    Health గ్రాఫ్ ఆకారాన్ని చూపిస్తుంది. ఇది అంకెలను ప్రింట్ చేస్తుంది: ఒక archive కి సగటు, మీడియన్, 95వ పర్సెంటైల్, గరిష్ఠం, 80 °C కి చేరిన రీడింగులు ఎన్ని. ఇది router సొంత health API కి ఒక చదివే అభ్యర్థనను (ఒక GET) పంపుతుంది, ఏమీ మార్చదు.

    ప్రారంభించే ముందు

    • మీకు Chrome లేదా Firefox ఉన్న ఒక PC, Reporting → Health తెరవగల router వెబ్ ఇంటర్‌ఫేస్ లాగిన్ కావాలి.
    • మీరు బ్రౌజర్ డెవలపర్ console లో, router సొంత పేజీలో టైప్ చేస్తారు. ఏదీ ఇన్‌స్టాల్ చేయరు.
    • దీనికి రెండు మూడు నిమిషాలు పడుతుంది.
    • ఇది router లో గానీ PC లో గానీ ఏమీ మార్చదు, కాబట్టి వెనక్కి తీసుకోవాల్సింది ఏమీ లేదు. పూర్తయ్యాక console ను మూసివేయండి.
    • కింది పెట్టెల్లో Copy పెట్టె మొత్తాన్ని కాపీ చేస్తుంది. గీతల అంచు ఉన్న పెట్టె మీకు కనిపించవలసినది చూపిస్తుంది; దాన్ని మీరు టైప్ చేయరు.

    దశలు

    1. Chrome లేదా Firefox లో router వెబ్ ఇంటర్‌ఫేస్ తెరవండి: router ను నిర్వహించడానికి మీరు వాడే చిరునామాను అడ్రస్ బార్‌లో టైప్ చేసి, Enter నొక్కి, లాగిన్ అవ్వండి. మీకు OPNsense dashboard కనిపించాలి. లాగిన్ పేజీ రాకపోతే, చిరునామాను, PC హోమ్ నెట్‌వర్క్‌లో ఉందో లేదో చూడండి. బ్రౌజర్ కనెక్షన్ ప్రైవేట్ కాదని హెచ్చరిస్తే, పైన గ్రాఫ్ దశల్లోని 1వ దశలోని గమనికను చూడండి.
    2. ఏదైనా OPNsense పేజీలోనే ఉండి బ్రౌజర్ console తెరవండి: Windows, Linux లో Chrome అయితే Ctrl+Shift+J, Firefox అయితే Ctrl+Shift+K; Mac లో Cmd+Option+J లేదా Cmd+Option+K. పేజీ పక్కన లేదా కింద ఒక ప్యానెల్ తెరుచుకుంటుంది, టైప్ చేయడానికి ఒక లైన్‌తో. అది వేరే ట్యాబ్‌లో తెరుచుకుంటే, Console ట్యాబ్‌ను క్లిక్ చేయండి.
    3. కింది పెట్టెలో Copy క్లిక్ చేయండి. అది snippet మొత్తాన్ని కాపీ చేస్తుంది.

      // Paste into the browser console on any OPNsense page while logged in.
      // Read-only: one GET to the router's own health API. Changes nothing.
      (async () => {
        const LEVEL = 0; // archive: 0 is the finest (one value a minute); higher numbers are coarser. How many exist depends on the router.
        const url = '/api/diagnostics/systemhealth/get_system_health/cputemp-system/' + LEVEL;
        let d;
        try {
          const r = await fetch(url);
          if (r.status === 401) { console.log('HTTP 401: not logged in. Log in to the OPNsense web interface in this browser, then paste again.'); return; }
          if (r.status === 403) { console.log('HTTP 403: logged in, but this user may not read Reporting > Health. Use an account with that privilege.'); return; }
          if (!r.ok) { console.log('HTTP ' + r.status + ' from ' + url); return; }
          d = await r.json();
        } catch (e) {
          console.log('No JSON came back (' + e.message + '). Run this on an OPNsense page while logged in.'); return;
        }
        const series = d && d.set && d.set.data && d.set.data[0];
        if (!series || !Array.isArray(series.values)) { console.log('No temperature series at LEVEL ' + LEVEL + '. A higher LEVEL may not exist on this router; at LEVEL 0, check that Reporting > Health shows a CPU temperature graph.'); return; }
        const pts = series.values.filter(p => p[1] !== null && !isNaN(p[1]));
        const empty = series.values.length - pts.length;
        if (pts.length === 0) { console.log('The series ' + series.key + ' has no readings at this level.'); return; }
        const v = pts.map(p => p[1]).sort((a, b) => a - b);
        const n = v.length;
        const median = n % 2 ? v[(n - 1) / 2] : (v[n / 2 - 1] + v[n / 2]) / 2;
        const p95 = v[Math.min(n - 1, Math.ceil(0.95 * n) - 1)]; // nearest-rank
        const when = t => new Date(t).toLocaleString(); // your browser's time zone; each time marks the end of its interval
        console.log('Series ' + series.key + ', one value every ' + d.set.step_size + ' s');
        console.log('From ' + when(pts[0][0]) + ' to ' + when(pts[n - 1][0]) + ': ' + n + ' readings, ' + empty + ' empty slots');
        console.log('Average ' + (v.reduce((a, b) => a + b, 0) / n).toFixed(1) + ' °C, median ' + median.toFixed(1) +
          ', 95th percentile ' + p95.toFixed(1) + ', maximum ' + v[n - 1].toFixed(1));
        console.log('Readings at 80 °C or above: ' + v.filter(x => x >= 80).length);
      })();
    4. console లోని లైన్‌ను క్లిక్ చేసి, Ctrl+V తో (Mac లో Cmd+V) పేస్ట్ చేసి Enter నొక్కండి. బ్రౌజర్లు console లో పేస్ట్ చేయడాన్ని ఆపవచ్చు, ఎందుకంటే లాగిన్ అయిన పేజీలో తెలియని వ్యక్తి కోడ్‌ను పేస్ట్ చేయించడం ఒక తెలిసిన మోసం. అనుమతించే ముందు snippet ను చదవండి. బ్రౌజర్ “allow pasting” అని టైప్ చేయమని అడిగితే, దాని సందేశం చెప్పినట్టు చేసి, మళ్ళీ పేస్ట్ చేయండి.

    5. ఒకటి రెండు సెకన్లలో మీకు నాలుగు లైన్లు కనిపించాలి (“Promise” తో మొదలయ్యే లైన్‌ను పట్టించుకోకండి): సిరీస్ పేరు, రీడింగులు ఎన్ని, ఖాళీ స్లాట్లు ఎన్ని అనే వివరాలతో సమయ పరిధి, సారాంశ అంకెలు, 80 °C లేదా అంతకంటే ఎక్కువ ఉన్న రీడింగుల లెక్క. సమయాలు మీ బ్రౌజర్ టైమ్ జోన్‌లో ఉంటాయి; ప్రతి సమయం దాని వ్యవధి ముగిసిన క్షణాన్ని సూచిస్తుంది. నా router లో, 28 అక్టోబర్ 2026న, ఇది ఇలా ప్రింట్ చేసింది (సమయాలను నేను వదిలేశాను; వాటి ఫార్మాట్ మీ బ్రౌజర్ సెట్టింగ్‌లను బట్టి ఉంటుంది):

      Series cpu0temp, one value every 60 s
      From <start time> to <end time>: 1000 readings, 0 empty slots
      Average 43.9 °C, median 47.7, 95th percentile 57.8, maximum 72.5
      Readings at 80 °C or above: 0
    6. “HTTP 401” అంటే బ్రౌజర్ OPNsense లో లాగిన్ అయి లేదు: లాగిన్ అయి 4వ దశను మళ్ళీ చేయండి. “HTTP 403” అంటే Reporting → Health చూసే అనుమతి లేని యూజర్‌గా మీరు లాగిన్ అయ్యారు.

    7. గంటవారీ archive చదవడానికి, snippet ను ముందు ఒక సాధారణ టెక్స్ట్ ఎడిటర్‌లో పేస్ట్ చేయండి (Windows లో Notepad, Mac లో plain text కు సెట్ చేసిన TextEdit), const LEVEL = 0; ను const LEVEL = 2; కు మార్చండి, అక్కడి నుంచి మొత్తాన్ని కాపీ చేసి, 4, 5 దశలను మళ్ళీ చేయండి.
    8. ఆ సగటును అదే archive కు సంబంధించిన Reporting → Health గ్రాఫ్ స్థాయితో పోల్చండి. రెండూ సరిపోలాలి.
    9. పూర్తయ్యాక, ప్యానెల్‌ను దాని కుడి పైన ఉన్న × తో మూసివేయండి. router లో ఏదీ మార్చబడలేదు.

    తీర్పు

    కేస్ మూసే ఉంటుంది, paste దాని పెట్టెలోనే ఉంటుంది.

    మిగిలింది చిన్న పని. Fan ను బిగించండి, పైకి లేపండి: 10 నుంచి 15 mm రబ్బర్ కాళ్ళు దాన్ని స్థానంలో పట్టి ఉంచగలవు, దాని hub కింద ఉన్న fins కు గాలి చేరనివ్వగలవు; సమతలంగా పడుకున్న fan ఆ fins కు గాలి సరిగా అందనివ్వదు. Heatsinks మీద పెట్టే fans కు ఇది సాధారణ పద్ధతి; ఇక్కడ నేను దీన్ని కొలవలేదు. పక్క గ్రిల్‌కు అడ్డు లేకుండా చూడండి. క్యాబినెట్ మొత్తం వేరే సమస్య: fan router ను క్యాబినెట్ గాలి ఉష్ణోగ్రతకు దగ్గరగా మాత్రమే చల్లబరచగలదు, ఆ గాలి గది కంటే వేడిగా ఉంటుంది. దాన్ని నేను వేరుగా పరిశీలించాను, దాని గురించి తర్వాత రాస్తానేమో.

    Fan కి ముందు, ఈ వేడి కొత్త router చూడడానికి ఒక కారణంగా ఉండేది. ఇప్పుడు కాదు.

    వేడి అల్మరాలో fanless బాక్స్ ఉన్నవారికి నేను చెప్పేది

    1. Router ఇప్పటికే ఏమి నమోదు చేస్తుందో చదవండి, ఏదైనా తెరిచే ముందు. OPNsense లో అది Reporting → Health, లేదా పైన చెప్పిన API.
    2. మీ router లో ప్రతి archive ఎంత కాలం ఉంటుందో చెక్ చేసుకోండి. అది దాని డేటాబేస్ ఎప్పుడు సృష్టించారనే దాని మీద ఆధారపడుతుంది.
    3. ఏ ఫలితం వస్తే తర్వాతి దశకు వెళ్ళాలో నిర్ణయించుకోండి, ఏదైనా మార్చే ముందే.
    4. ఒక్కొక్క రీడింగును కాదు, సగటులను బట్టి తేల్చండి. వరుస నిమిషాల రీడింగుల మధ్య 30 °C తేడా ఉండవచ్చు.
    5. చౌకైన, వెనక్కి తీసుకోగల పరిష్కారాన్ని ముందు ప్రయత్నించండి, దాని నష్టాన్నీ బేరీజు వేయండి: శబ్దం, దుమ్ము లేకుండా ఉండాలని కొన్న బాక్స్‌కు fan ఆ రెండింటినీ తెస్తుంది.
    పదకోశం
    • Fanless (passive) cooling: కేసే heatsink; fan లేకుండా, ఉష్ణ వహనం, సహజ గాలి ప్రవాహం ద్వారా వేడి బయటకు పోతుంది.
    • Thermal paste / repaste: CPU కీ heatsink కీ మధ్య ఉండి, సూక్ష్మమైన ఖాళీలను నింపే పదార్థం. Repaste అంటే పాత పదార్థాన్ని శుభ్రంగా తుడిచి కొత్తది పూయడం.
    • P-core / E-core: ఒకే చిప్‌లో ఉండే Intel పెర్ఫార్మెన్స్ కోర్లు, ఎఫిషియెంట్ కోర్లు. Pentium Gold 8505 లో మొదటి రకం ఒకటి, రెండో రకం నాలుగు ఉన్నాయి.
    • TJUNCTION: చిప్‌లోనే Intel అనుమతించే అత్యధిక ఉష్ణోగ్రత. 8505 కి అది 100 °C.
    • PWM: pulse-width modulation; fan ఎంత వేగంగా తిరగాలో చెప్పే ఒక సిగ్నల్ వైర్.
    • Round-robin database (RRD): స్థిర పరిమాణం ఉన్న ఒక నిల్వ. ఇటీవలి డేటాను సూక్ష్మ వివరంగా, పాత డేటాను స్థూల సగటులుగా ఉంచుతుంది, అన్నిటికంటే పాత డేటాను తుడిచి దాని మీద రాస్తుంది.
    • మీడియన్ / 95వ పర్సెంటైల్: మీడియన్ అంటే మధ్యలో ఉండే రీడింగ్ (లేదా మధ్యలో ఉండే రెండు రీడింగుల సగటు); 95 శాతం రీడింగులు 95వ పర్సెంటైల్ వద్ద గానీ దాని కంటే కింద గానీ ఉంటాయి.
    • API: router ప్రోగ్రామింగ్ ఇంటర్‌ఫేస్; వెబ్ పేజీలు చూపించే డేటానే JSON గా ఇస్తుంది.
    • Tunables: OPNsense బూట్ సమయంలో వర్తింపజేసే kernel సెట్టింగులు; ఇవి System → Settings → Tunables కింద కనిపిస్తాయి.

    Thermal paste ยังอยู่ในกล่อง

    เมื่อวันที่ 15 ตุลาคม 2026 ผมมีทางแก้สองทางสำหรับปัญหาเดียววางอยู่บนโต๊ะ: thermal paste ARCTIC MX-7 หนึ่งหลอดขนาด 4 g และ fan Noctua ขนาด 120 mm ปัญหาคือ router ของผม ซึ่งเป็น mini PC แบบ fanless ที่รัน OPNsense อยู่ในตู้ไม้อัดแบบปิด วันก่อนหน้านั้น CPU ของมันขึ้นไปแตะ 91 °C

    คำแนะนำที่ผมเจอในอินเทอร์เน็ตคือให้เปิดเคสแล้วเปลี่ยน paste ใหม่ ผมติด fan ก่อน เพราะไม่ต้องใช้ไขควง ก่อนติด ผมตัดสินใจไว้ว่าผลแบบไหนจะทำให้ผมต้องกลับไปใช้ paste

    ผมไม่เคยต้องใช้มัน router บันทึกอุณหภูมิของตัวเองไว้ตลอดอยู่แล้ว ระหว่างวันที่ 16 กันยายนถึงช่วงเย็นของวันที่ 15 ตุลาคม ไม่มีชั่วโมงไหนที่ค่าเฉลี่ยต่ำกว่า 60 °C ในสี่วันหลังติด fan ไม่มีชั่วโมงไหนที่ค่าเฉลี่ยสูงกว่า 49 °C ตอนนี้ paste ยังอยู่ในกล่อง

    ผมทำงานนี้ร่วมกับ Claude ซึ่งเป็นโมเดล AI ของ Anthropic โดย Claude อ่านข้อมูลจาก router ผ่าน browser session ของผมเองได้ ผมเป็นคนเลือกชิ้นส่วน ติด fan และตั้งเกณฑ์ Claude ดึงบันทึกอุณหภูมิและคำนวณตัวเลข และเมื่อวันที่ 28 ตุลาคม ก็ดึงข้อมูลรายชั่วโมงของ router มาอีกครั้งสำหรับโพสต์นี้

    ตัวเครื่องและตู้

    router ตัวนี้เป็น mini PC แบบ fanless หกพอร์ต ขายภายใต้ชื่อ “Shenzhen Weibu” ข้างในเป็น Intel Pentium Gold 8505: performance core หนึ่งคอร์และ efficient core สี่คอร์ หก thread กำลังไฟพื้นฐาน 15 W และสูงสุด 55 W ในโหมด turbo ตามหน้าสเปกของ Intel มี RAM 20 GB และพอร์ต Intel I226-V 2.5 GbE หกพอร์ต รัน OPNsense 26.7 ตัวเคสคือ heatsink ด้านบนทั้งแผ่นเป็น fins

    มันอยู่ในตู้ไม้อัดแบบปิดร่วมกับอุปกรณ์เครือข่ายอื่น ตะแกรงแบบช่องบนแผงข้างตู้เป็นทางระบายลมร้อนทางเดียวที่ตั้งใจทำไว้

    router ก่อนติด fan มองจากด้านที่มีพอร์ต USB: ตัวเคสสีดำที่ด้านบนเป็นแผง fins อยู่ข้างตะแกรงแบบช่องบนแผงข้างของตู้

    91 °C อันตรายไหม? ตามตัวเลขของ Intel ไม่อันตราย หน้าเดียวกันระบุอุณหภูมิ junction สูงสุดของชิป (TJUNCTION) ไว้ที่ 100 °C และโปรเซสเซอร์ที่แตะขีดนั้นจะลดความเร็วตัวเองลง ไม่ใช่พัง อีกอย่าง 91 °C เป็นแค่ค่าสูงสุดในบรรดาค่าที่อ่านตามรอบ router อ่าน sensor นาทีละครั้ง ค่าที่พุ่งขึ้นระหว่างนั้นจึงไม่ถูกบันทึก ถึงอย่างนั้น ความร้อนก็กลายเป็นเหตุผลให้ผมมองหา router ตัวใหม่ ค่าเฉลี่ยรายชั่วโมงอยู่ราว 70 °C ทั้งกลางวันและกลางคืน และ SSD หน่วยความจำ และชิปเครือข่าย อยู่ในเคสร้อนอันเดียวกัน โดยทั่วไปความร้อนทำให้อุปกรณ์อิเล็กทรอนิกส์อายุสั้นลง แต่ผมไม่ได้วัดทั้งเรื่องนั้นและอุณหภูมิของ SSD บนเครื่องนี้

    ทำไมเลือก fan ก่อน

    การ repaste เป็นคำแนะนำปกติสำหรับ mini PC ที่ร้อน และก็อาจช่วยได้จริง แต่ถ้าทำ ก็จะต้อง:

    • สำรอง configuration ไว้ก่อน
    • แอลกอฮอล์ไอโซโพรพิล 99 เปอร์เซ็นต์ และผ้าเช็ดที่ไม่ทิ้งขุย
    • 45 ถึง 60 นาทีที่เครือข่ายออฟไลน์
    • เปิดเคสที่ปิดผนึกไว้ ซึ่งผมไม่เคยเห็นสกรูและ thermal pad ข้างในมาก่อน

    fan ที่วางบน fins ไม่ต้องใช้อะไรในรายการนั้นเลย และถอดออกได้ในวินาทีเดียว แต่มันก็มีต้นทุนของมันเอง มันทำให้เสียสิ่งที่เป็นเหตุผลของการมีเครื่อง fanless ไป: ไม่มีเสียง ไม่ดูดฝุ่นเข้า ไม่มีชิ้นส่วนเคลื่อนไหวที่สึกหรอ

    ผมจึงตั้งเกณฑ์ไว้ก่อนติด: จะ repaste ก็ต่อเมื่อค่าที่อ่านได้ช่วงกลางคืนยังขึ้นไปถึงระดับ 80 กว่า °C ทั้งที่ติด fan แล้ว

    ตัว fan

    ผมเลือก Noctua NF-F12 5V PWM สเปก ของ Noctua ระบุขนาด 120 mm ไฟ 5 V ความเร็วสูงสุด 1,500 rpm กินไฟปกติ 0.65 W และดัง 22.4 dB(A) ที่ความเร็วสูงสุด มีสาย USB สำหรับจ่ายไฟมาในกล่อง ตัวของผมเสียบอยู่กับพอร์ต USB ช่องหนึ่งของ router เอง เมื่อจ่ายไฟจาก USB fan จะไม่ได้รับสัญญาณความเร็ว และคู่มือของ Noctua เอง บอกว่า fan แบบ PWM ที่ไม่มีสัญญาณจะหมุนที่ความเร็วสูงสุด Noctua ระบุว่ารุ่นนี้เป็น “5V PWM version, not for use in PCs” ซึ่งหมายความว่า เป็นรุ่น 5V PWM ไม่ได้มีไว้ใช้กับ PC: fan header 12 V ของ PC เป็นแหล่งจ่ายไฟที่ผิดสำหรับมัน

    บน router ของผม fan ขนาด 120 mm คลุมด้านบนส่วนใหญ่ เลือก fan ที่มีขนาดใกล้เคียงกับด้านบนของ router Noctua ยังขายรุ่น 5 V ขนาดเล็กกว่านี้ด้วย เช่น NF-A8 5V PWM ขนาด 80 mm fan USB 5 V ที่ราคาถูกกว่าก็น่าจะเป่าลมได้เช่นกัน แต่ผมยังไม่เคยลอง

    ผมติดตั้งมันราว 17:30 ของวันที่ 15 ตุลาคม มันวางราบอยู่บน fins ด้านบน ไม่ได้ขันสกรูยึด และเป่าลมลงไปใน fins ตอนอ่านจากรูปถ่าย Claude เข้าใจทิศทางลมกลับด้านในตอนแรก ผมจึงดูลูกศรที่ขึ้นรูปไว้บนกรอบ แบบไหนก็น่าจะช่วยได้ แต่ผมอยากรู้ว่ากำลังวัดแบบไหนอยู่

    fan Noctua วางราบบน fins ด้านบนของ router มองจากด้านบน router มองจากด้านพอร์ตเครือข่าย มีสายเสียบอยู่ และมี fan วางอยู่ด้านบน

    สิ่งที่ router บันทึกไว้

    OPNsense อ่านอุณหภูมิ CPU นาทีละครั้ง และเก็บค่าเฉลี่ยรายชั่วโมงไว้หลายสัปดาห์ วิธีอ่านข้อมูลของ router คุณเองอยู่ด้านล่าง

    กราฟเส้นของอุณหภูมิ CPU เฉลี่ยรายชั่วโมงของ router ตั้งแต่ 16 กันยายน 2026 ถึงสี่วันหลังติด fan เส้นอยู่ระหว่างราว 65 ถึง 74 °C จนถึง 9 ตุลาคม ขึ้นสูงสุดที่ 77 °C ระหว่างการเก็บกวาด configuration เมื่อ 10 ตุลาคม จากนั้นทรงตัวระหว่างราว 60 ถึง 71 °C และลดลงเหลือราว 46 °C ในชั่วโมงหลังติด fan เวลา 17:30 ของวันที่ 15 ตุลาคม แล้วอยู่ที่ระดับนั้น

    ค่าเฉลี่ยรายชั่วโมงของ cpu0 จาก archive รายชั่วโมงของ router:

    ช่วงเวลา จำนวนชั่วโมง ค่าเฉลี่ย ชั่วโมงที่ต่ำสุด ชั่วโมงที่สูงสุด
    16 กันยายน – 9 ตุลาคม 567 69.7 °C 65.3 °C 73.7 °C
    11 ตุลาคม – 15 ตุลาคม ก่อนติด fan 114 66.2 °C 60.5 °C 70.9 °C
    15 ตุลาคม หลังติด fan (สี่วัน) 100 46.4 °C 42.6 °C 48.6 °C

    ผมไม่นับวันที่ 10 ตุลาคม ซึ่งเป็นวันเก็บกวาด configuration ที่เล่าไว้ด้านล่าง เมื่อเทียบกับไม่กี่วันก่อนติด fan ตัว fan ลดค่าเฉลี่ยลงราว 20 °C ช่วงค่าก่อนและหลังไม่ซ้อนทับกัน: ชั่วโมงที่เย็นที่สุดก่อนติด fan ยังร้อนกว่าชั่วโมงที่ร้อนที่สุดหลังติด fan อยู่ 12 °C

    เกณฑ์ที่ผมตั้งไว้ดูจากค่าที่อ่านได้ช่วงกลางคืน วันที่ 15 ตุลาคม ผมอ่านช่วง 03:00–10:00 จากข้อมูลรายนาที และวันที่ 16 ตุลาคม ผมอ่านช่วงเดียวกันอีกครั้ง:

    cpu0, 03:00–10:00 15 ตุลาคม ไม่มี fan 16 ตุลาคม มี fan
    ค่าเฉลี่ย 65.6 °C 46.7 °C
    ค่าสูงสุด 90.3 °C 73.6 °C
    จำนวนค่าที่ 80 °C ขึ้นไป 19 0

    ไม่มีค่าไหนขึ้นไปถึงระดับ 80 กว่า เกณฑ์บอกว่าให้ปิดเคสไว้ตามเดิม

    เกณฑ์ของผมใช้ค่าเดี่ยว และค่าเดี่ยวกระโดดไปมา แต่ละค่าคือค่า ณ ขณะเดียว: วันที่ 28 ตุลาคม นาทีที่ต่อกันอ่านได้ 35.3, 68.2, 69.0 และ 35.7 °C ถ้าใช้ค่าเฉลี่ยหลายชั่วโมงจะเป็นการทดสอบที่ดีกว่า เมื่อดูจากค่าเฉลี่ยรายชั่วโมง ความต่างยิ่งมากขึ้นอีก: หลังติด fan ไม่มีชั่วโมงไหนสูงกว่า 48.6 °C

    เจาะลึก: ช่วงเวลารายนาทีของวันที่ 15 ตุลาคม

    อ่านจากข้อมูลรายนาทีเมื่อวันที่ 15 ตุลาคม

    ช่วงเวลา วันที่ 15 ตุลาคม 2026 จำนวนค่า ค่าเฉลี่ย ค่ามัธยฐาน เปอร์เซ็นไทล์ที่ 95 ค่าสูงสุด จำนวนค่าที่ 80 °C ขึ้นไป
    03:00–10:00 ไม่มี fan 420 65.6 °C 69.0 °C 79.8 °C 90.3 °C 19
    12:00–17:20 ไม่มี fan 320 65.5 °C 68.7 °C 80.1 °C 90.7 °C 16
    17:31–19:12 มี fan 101 46.0 °C 48.7 °C 60.5 °C 69.6 °C 0
    19:20–19:37 หลังอัปเดต firmware และ reboot 17 54.1 °C 57.1 °C 70.8 °C 70.8 °C 0

    แถวสุดท้ายสูงกว่าเพราะ router เพิ่ง reboot หลังอัปเดต firmware และกำลังโหลดรายการ blocklist ราว 2.7 ล้านรายการ ไม่ใช่ตัวเลขตอนที่เครื่องอยู่ตัวแล้ว

    สิ่งที่ผลนี้แสดง และไม่ได้แสดง

    ผลนี้แสดงว่า fan เพียงพอสำหรับกรณีนี้ แต่ไม่ได้แสดงว่าการ repaste จะไม่ช่วยด้วย เพราะผมไม่เคยลอง fan ไม่ได้นำความร้อนออกจากตู้ มันบังคับให้อากาศในตู้ไหลผ่าน fins ของ router ตู้ที่ปิดทำให้จุดเริ่มต้นแย่กว่าปกติ ผลที่ได้ตรงนี้จึงน่าจะมากกว่าตอนที่ router ตั้งอยู่ในที่โล่ง

    • ผมไม่ได้วัดอุณหภูมิห้อง อุณหภูมิลดลงภายในหนึ่งชั่วโมง และห้องไม่เย็นลง 20 °C ในชั่วโมงเดียว นอกจากนี้ router ยังตอบสนองต่อรอบกลางวันกลางคืนเพียงเล็กน้อย: ตั้งแต่ 16 กันยายนถึง 9 ตุลาคม ค่าเฉลี่ยของแต่ละชั่วโมงในรอบวันอยู่ระหว่าง 69.2 ถึง 70.3 °C ต่างกันราว 1 °C
    • firmware เปลี่ยนในเย็นวันเดียวกัน router อัปเดต firmware เวลา 19:12 ของวันที่ 15 ตุลาคม อุณหภูมิลดลงก่อน: 101 นาทีระหว่างติด fan กับการอัปเดตมีค่าเฉลี่ย 46.0 °C
    • มีการเก็บกวาด configuration ห้าวันก่อนหน้านั้น วันที่ 10 ตุลาคม ผมลบ WireGuard VPN client, proxy stack ที่ไม่ได้ใช้ (Squid, ClamAV, Redis และส่วนประกอบที่มาด้วยกัน) และ NAT rule ที่ส่งทราฟฟิกเข้าไปหามัน ลดขนาด DNS blocklist และถอด USB network adapter ออก ค่าเฉลี่ยรายชั่วโมงอยู่ที่ 69.7 °C ตั้งแต่ 16 กันยายนถึง 9 ตุลาคม และ 66.2 °C ตั้งแต่ 11 ตุลาคมจนถึงตอนติด fan การลดลงนั้นเกิดเป็นขั้นๆ ในสามถึงสี่วัน และผมแยกผลของการเปลี่ยนแปลงเหล่านั้นออกจากผลของสภาพอากาศไม่ได้ นี่คือเหตุผลที่การเปรียบเทียบด้านบนใช้เฉพาะไม่กี่วันก่อนติด fan
    • การตั้งค่าพลังงานไม่ได้เปลี่ยน ประวัติ configuration ของ router ย้อนไปถึงวันที่ 13 ตุลาคม (30 revision) และไม่มีการเปลี่ยนการตั้งค่าพลังงาน การตั้งค่าความร้อน หรือ tunables ในช่วงนั้น
    • ผมไม่ได้ควบคุมโหลด นี่คือวันปกติของเครือข่ายในบ้าน
    • นี่คือ router ตัวเดียวในตู้ใบเดียว
    ข้อสันนิษฐานที่ผมไม่ได้พิสูจน์: dashboard

    วันที่ 13 ตุลาคม ตอน uptime ราว 20 ชั่วโมง ผมเปรียบเทียบ CPU time ของแต่ละ process Unbound ซึ่งเป็น DNS resolver ใช้ไป 16 วินาที ราว 0.02 เปอร์เซ็นต์ของหนึ่งคอร์ ระหว่างที่ตอบ lookup ที่ไม่ต้องการราว 10,000 ครั้งต่อวันจากอุปกรณ์ในเครือข่าย ส่วน process ของ PHP ที่ให้บริการ web interface และ API ใช้ไป 5 นาที 9 วินาที ซึ่งเป็นราว 20 เท่าของ Unbound และ snapshot นั้นไม่ได้นับ PHP worker ที่จบการทำงานไปแล้ว

    ถึงอย่างนั้น 5 นาทีใน 20 ชั่วโมงก็เป็นราว 0.4 เปอร์เซ็นต์ของหนึ่งคอร์ ถ้า dashboard ที่เปิดค้างไว้ ซึ่ง widget ของมันรีเฟรชทุกไม่กี่วินาที ทำให้อุณหภูมิสูงขึ้น ก็เกิดเป็นช่วงสั้นๆ ที่โหลดพุ่ง ผมสงสัยว่าช่วงโหลดพุ่งเหล่านั้นอยู่เบื้องหลังค่าพุ่ง 78 °C บางครั้งที่ผมเห็นในสัปดาห์นั้น ผมไม่ได้ทดสอบ

    อ่านข้อมูลจาก router ของคุณเอง

    OPNsense แสดงบันทึกสถานะของระบบเป็นกราฟที่ Reporting → Health วิธีดูกราฟอุณหภูมิ CPU:

    1. เปิด web interface ของ router ใน browser: พิมพ์ที่อยู่ที่คุณใช้จัดการ router ลงในแถบที่อยู่ กด Enter แล้ว log in ถ้าคุณไม่ทราบที่อยู่ ให้ถามคนที่ตั้งค่า router ให้คุณ ตัว router ใช้ใบรับรองความปลอดภัยของตัวเอง browser จึงอาจเตือนว่าการเชื่อมต่อไม่เป็นส่วนตัว สำหรับที่อยู่ของ router ของคุณเอง นั่นเป็นเรื่องที่คาดไว้ได้ คลิก Advanced แล้วคลิกลิงก์ที่ไปต่อยังที่อยู่นั้น (Proceed ใน Chrome, Accept the Risk and Continue ใน Firefox)
    2. ในเมนู เปิด Reporting → Health หน้านี้โหลดภายในไม่กี่วินาทีและไม่เปลี่ยนแปลงอะไร หน้านี้แสดงรายการ report แยกตามหัวข้อ
    3. หา report อุณหภูมิ CPU ในรายการ report ของหน้านั้น ถ้าไม่มี ให้เปิด System → Settings → Miscellaneous → Thermal Sensors ของผมตั้งไว้เป็น “Intel Core CPU on-die thermal sensor (coretemp)” การเปลี่ยนค่านี้เป็นการเปลี่ยน router: จดค่าเดิมไว้ก่อน กด Save* แล้วรอไม่กี่นาทีระหว่างที่ router อ่านค่า ถ้าจะยกเลิก ให้เลือกค่าเดิมอีกครั้ง ถ้าตั้งกลับเป็น none ต้อง reboot

    ข้อมูลชุดเดียวกันดึงได้จาก API ของ router ที่ GET /api/diagnostics/systemhealth/get_system_health/cputemp-system/0 ตัวเลขท้ายสุดใช้เลือก archive: /0 คือค่าหนึ่งค่าต่อนาที และตัวเลขที่สูงขึ้นจะหยาบขึ้น แต่ละ archive เก็บได้นานแค่ไหนขึ้นกับว่าฐานข้อมูลอุณหภูมิของ router ถูกสร้างเมื่อไร:

    Archive router ของผม (ฐานข้อมูลจาก OPNsense รุ่นเก่า) OPNsense 26.x ที่ติดตั้งใหม่
    /0 1 นาที, 1,000 ช่อง: 16 ชั่วโมง 40 นาที 1 นาที, 1,200 ช่อง: 20 ชั่วโมง
    /1 5 นาที, 1,000 ช่อง: ราว 3½ วัน 5 นาที, 720 ช่อง: 60 ชั่วโมง
    /2 1 ชั่วโมง, 1,000 ช่อง: ราว 6 สัปดาห์ 1 ชั่วโมง, 1,860 ช่อง: ราว 11 สัปดาห์
    /3 12 ชั่วโมง, 3,000 ช่อง: ราว 4 ปี 1 วัน, 2,284 ช่อง: ราว 6 ปี

    OPNsense เก็บฐานข้อมูลเดิมไว้ตลอดการอัปเกรด ดังนั้น router ที่ติดตั้งมาตั้งแต่ OPNsense รุ่นเก่าจึงยังใช้รูปแบบเดิม คอลัมน์สุดท้ายมาจาก source code ของ 26.7 ผมยังไม่เคยเห็นเครื่องที่ติดตั้งใหม่

    จากตรงนี้ได้สองเรื่อง ให้อ่านข้อมูลรายนาทีของเมื่อคืนภายในเช้านี้ พอถึงตอนเย็น ข้อมูลนาทีเหล่านั้นหายไปแล้ว เหลือแต่ค่าเฉลี่ยที่หยาบกว่า และ archive รายชั่วโมงก็ยาวพอสำหรับการเทียบก่อนและหลังที่คุณไม่ได้วางแผนไว้ ของผมมีข้อมูล “ก่อน” อยู่แล้วหนึ่งเดือนตอนที่ผมติด fan

    เจาะลึก: archive เก็บอะไรไว้ และทำไมตัวเลขรายชั่วโมงจึงซ่อนค่าที่พุ่งขึ้นชั่วครู่

    API ส่งให้แค่ค่าเฉลี่ย fetchData.py ของ OPNsense ประมวลผลเฉพาะ round-robin archive ที่มี consolidation function เป็น AVERAGE และสร้าง “set” หนึ่งชุดต่อหนึ่ง archive router เก็บค่าที่อ่านจาก sensor ณ ขณะหนึ่งไว้นาทีละหนึ่งค่า ค่ารายชั่วโมงแต่ละค่าคือค่าเฉลี่ยของค่าที่อ่านได้เหล่านั้น ค่าที่อ่านได้ 91 °C เพียงค่าเดียวแทบไม่ทำให้ค่านี้ขยับ

    ช่องที่ไม่มีค่า จะส่งกลับมาเป็นค่าว่าง สคริปต์เดียวกันตัดช่องที่ไม่มีค่าออกเฉพาะที่จุดเริ่มต้นของ series ดังนั้นจำนวนช่องจะน้อยกว่าความยาวของ archive เมื่อช่องที่เก่าที่สุดว่าง เช่นในฐานข้อมูลที่เพิ่งสร้าง snippet ด้านล่างรายงานจำนวนค่าที่อ่านได้และจำนวนช่องที่ไม่มีค่าแยกกัน

    เจาะลึก: console snippet สำหรับสรุปข้อมูล router ของคุณเอง (สำหรับ PC)

    กราฟ Health แสดงรูปร่างของข้อมูล snippet นี้พิมพ์ตัวเลขออกมา: ค่าเฉลี่ย ค่ามัธยฐาน เปอร์เซ็นไทล์ที่ 95 และค่าสูงสุด และจำนวนค่าที่อ่านได้ที่ถึง 80 °C ของ archive หนึ่ง snippet นี้ส่งคำขออ่านหนึ่งครั้ง (GET) ไปที่ health API ของ router เอง และไม่เปลี่ยนแปลงอะไร

    ก่อนเริ่ม

    • คุณต้องมี PC ที่มี Chrome หรือ Firefox และ login เข้า web interface ของ router ที่เปิด Reporting → Health ได้
    • คุณพิมพ์ใน developer console ของ browser บนหน้าของ router เอง คุณไม่ต้องติดตั้งอะไร
    • ใช้เวลาสองถึงสามนาที
    • ไม่เปลี่ยนแปลงอะไรบน router หรือ PC จึงไม่มีอะไรต้องย้อนกลับ ปิด console เมื่อทำเสร็จ
    • ในกล่องด้านล่าง ปุ่ม Copy จะคัดลอกทั้งกล่อง กล่องเส้นประแสดงสิ่งที่คุณควรเห็น คุณไม่ต้องพิมพ์มัน

    ขั้นตอน

    1. เปิด web interface ของ router ใน Chrome หรือ Firefox: พิมพ์ที่อยู่ที่คุณใช้จัดการ router ลงในแถบที่อยู่ กด Enter แล้ว log in คุณควรเห็น dashboard ของ OPNsense ถ้าไม่มีหน้า login ขึ้นมา ให้ตรวจที่อยู่ และตรวจว่า PC อยู่ในเครือข่ายภายในบ้าน ถ้า browser เตือนว่าการเชื่อมต่อไม่เป็นส่วนตัว ดูหมายเหตุในข้อ 1 ของขั้นตอนดูกราฟด้านบน
    2. อยู่ในหน้าใดก็ได้ของ OPNsense แล้วเปิด console ของ browser: กด Ctrl+Shift+J ใน Chrome หรือ Ctrl+Shift+K ใน Firefox บน Windows และ Linux หรือกด Cmd+Option+J หรือ Cmd+Option+K บน Mac แผงจะเปิดขึ้นข้างหรือใต้หน้าเว็บ พร้อมบรรทัดสำหรับพิมพ์ ถ้ามันเปิดที่แท็บอื่น ให้คลิกแท็บ Console
    3. คลิก Copy ในกล่องด้านล่าง มันคัดลอก snippet ทั้งหมด

      // Paste into the browser console on any OPNsense page while logged in.
      // Read-only: one GET to the router's own health API. Changes nothing.
      (async () => {
        const LEVEL = 0; // archive: 0 is the finest (one value a minute); higher numbers are coarser. How many exist depends on the router.
        const url = '/api/diagnostics/systemhealth/get_system_health/cputemp-system/' + LEVEL;
        let d;
        try {
          const r = await fetch(url);
          if (r.status === 401) { console.log('HTTP 401: not logged in. Log in to the OPNsense web interface in this browser, then paste again.'); return; }
          if (r.status === 403) { console.log('HTTP 403: logged in, but this user may not read Reporting > Health. Use an account with that privilege.'); return; }
          if (!r.ok) { console.log('HTTP ' + r.status + ' from ' + url); return; }
          d = await r.json();
        } catch (e) {
          console.log('No JSON came back (' + e.message + '). Run this on an OPNsense page while logged in.'); return;
        }
        const series = d && d.set && d.set.data && d.set.data[0];
        if (!series || !Array.isArray(series.values)) { console.log('No temperature series at LEVEL ' + LEVEL + '. A higher LEVEL may not exist on this router; at LEVEL 0, check that Reporting > Health shows a CPU temperature graph.'); return; }
        const pts = series.values.filter(p => p[1] !== null && !isNaN(p[1]));
        const empty = series.values.length - pts.length;
        if (pts.length === 0) { console.log('The series ' + series.key + ' has no readings at this level.'); return; }
        const v = pts.map(p => p[1]).sort((a, b) => a - b);
        const n = v.length;
        const median = n % 2 ? v[(n - 1) / 2] : (v[n / 2 - 1] + v[n / 2]) / 2;
        const p95 = v[Math.min(n - 1, Math.ceil(0.95 * n) - 1)]; // nearest-rank
        const when = t => new Date(t).toLocaleString(); // your browser's time zone; each time marks the end of its interval
        console.log('Series ' + series.key + ', one value every ' + d.set.step_size + ' s');
        console.log('From ' + when(pts[0][0]) + ' to ' + when(pts[n - 1][0]) + ': ' + n + ' readings, ' + empty + ' empty slots');
        console.log('Average ' + (v.reduce((a, b) => a + b, 0) / n).toFixed(1) + ' °C, median ' + median.toFixed(1) +
          ', 95th percentile ' + p95.toFixed(1) + ', maximum ' + v[n - 1].toFixed(1));
        console.log('Readings at 80 °C or above: ' + v.filter(x => x >= 80).length);
      })();
    4. คลิกที่บรรทัดใน console วางด้วย Ctrl+V (Cmd+V บน Mac) แล้วกด Enter browser อาจบล็อกการวางลงใน console เพราะการวางโค้ดของคนแปลกหน้าลงในหน้าที่ log in อยู่เป็นกลลวงที่รู้จักกัน อ่าน snippet ก่อนจะอนุญาต ถ้า browser ขอให้พิมพ์ “allow pasting” ให้ทำตามข้อความนั้น แล้ววางอีกครั้ง

    5. ภายในหนึ่งหรือสองวินาที คุณควรเห็นสี่บรรทัด (ไม่ต้องสนใจบรรทัดที่ขึ้นต้นด้วย “Promise”): ชื่อ series ช่วงเวลาพร้อมจำนวนค่าที่อ่านได้และจำนวนช่องที่ไม่มีค่า ตัวเลขสรุป และจำนวนค่าที่อ่านได้ที่ 80 °C ขึ้นไป เวลาที่แสดงเป็นเขตเวลาของ browser ของคุณ และแต่ละเวลาคือจุดสิ้นสุดของช่วงนั้น บน router ของผม เมื่อวันที่ 28 ตุลาคม 2026 มันพิมพ์ออกมาว่า (ผมตัดเวลาออก รูปแบบของเวลาเป็นไปตามการตั้งค่าของ browser ของคุณ):

      Series cpu0temp, one value every 60 s
      From <start time> to <end time>: 1000 readings, 0 empty slots
      Average 43.9 °C, median 47.7, 95th percentile 57.8, maximum 72.5
      Readings at 80 °C or above: 0
    6. “HTTP 401” แปลว่า browser ยังไม่ได้ log in เข้า OPNsense: ให้ log in แล้วทำข้อ 4 ซ้ำ “HTTP 403” แปลว่าคุณ log in ด้วย user ที่ไม่มีสิทธิ์เข้า Reporting → Health

    7. หากต้องการอ่าน archive รายชั่วโมง ให้วาง snippet ลงใน text editor ธรรมดาก่อน (Notepad บน Windows, TextEdit ที่ตั้งเป็น plain text บน Mac) เปลี่ยน const LEVEL = 0; เป็น const LEVEL = 2; คัดลอกทั้งหมดจากตรงนั้น แล้วทำข้อ 4 และ 5 ซ้ำ
    8. เทียบค่าเฉลี่ยกับระดับของเส้นกราฟ Reporting → Health ของ archive เดียวกัน ทั้งสองควรตรงกัน
    9. เมื่อทำเสร็จ ให้ปิดแผงด้วย × ที่มุมขวาบน router ไม่ถูกเปลี่ยนแปลงอะไร

    คำตัดสิน

    เคสยังปิดอยู่ และ paste ก็ยังอยู่ในกล่อง

    สิ่งที่เหลือเป็นงานเล็ก ยึด fan และยกมันขึ้น: ขายางสูง 10 ถึง 15 mm จะยึด fan ไว้กับที่ และให้ลมไปถึง fins ที่อยู่ใต้ดุมของมัน ซึ่ง fan ที่วางราบทำให้ขาดลม นั่นเป็นวิธีปฏิบัติทั่วไปสำหรับ fan ที่วางเหนือ heatsink ผมยังไม่ได้วัดผลกับเครื่องนี้ ดูแลไม่ให้มีอะไรบังตะแกรงข้างตู้ ตัวตู้ทั้งตู้เป็นอีกปัญหาหนึ่ง: fan ทำให้ router เย็นลงได้แค่เข้าใกล้อุณหภูมิของอากาศในตู้ ซึ่งอุ่นกว่าห้อง ผมไล่คิดเรื่องนั้นแยกต่างหาก และอาจเขียนเล่าทีหลัง

    ก่อนติด fan ความร้อนเป็นเหตุผลให้ผมมองหา router ตัวใหม่ ตอนนี้ไม่ใช่แล้ว

    สิ่งที่ผมจะบอกคนที่มีเครื่อง fanless อยู่ในตู้ที่อุ่น

    1. อ่านสิ่งที่ router บันทึกไว้อยู่แล้ว ก่อนจะเปิดอะไร บน OPNsense คือ Reporting → Health หรือ API ด้านบน
    2. ตรวจว่าแต่ละ archive บน router ของคุณเก็บข้อมูลได้นานแค่ไหน ขึ้นกับว่าฐานข้อมูลของมันถูกสร้างเมื่อไร
    3. ตัดสินใจไว้ก่อนว่าผลแบบไหนจะพาคุณไปขั้นต่อไป ก่อนจะเปลี่ยนอะไร
    4. ตัดสินจากค่าเฉลี่ย ไม่ใช่ค่าเดี่ยว ค่ารายนาทีที่ต่อกันอาจต่างกันได้ 30 °C
    5. ลองวิธีที่ต้นทุนต่ำและย้อนกลับได้ก่อน และชั่งดูว่ามันมีต้นทุนอะไร: fan นำเสียงและฝุ่นมาสู่เครื่องที่ซื้อมาเพื่อไม่ให้มีทั้งสองอย่าง
    อภิธานศัพท์
    • การระบายความร้อนแบบ fanless (passive): ตัวเคสคือ heatsink ความร้อนออกไปทางการนำความร้อนและการไหลเวียนของอากาศตามธรรมชาติ โดยไม่มี fan
    • Thermal paste / repaste: สารที่อยู่ระหว่าง CPU กับ heatsink ซึ่งเติมช่องว่างระดับจุลภาค การ repaste คือการเช็ดสารเก่าออกแล้วทาสารใหม่
    • P-core / E-core: performance core และ efficient core ของ Intel ในชิปตัวเดียว Pentium Gold 8505 มีแบบแรกหนึ่งคอร์และแบบหลังสี่คอร์
    • TJUNCTION: อุณหภูมิสูงสุดที่ Intel อนุญาตที่ตัวชิป สำหรับ 8505 คือ 100 °C
    • PWM: pulse-width modulation สายสัญญาณที่บอก fan ว่าต้องหมุนเร็วแค่ไหน
    • Round-robin database (RRD): ที่เก็บข้อมูลขนาดคงที่ ซึ่งเก็บข้อมูลล่าสุดแบบละเอียด และเก็บข้อมูลเก่าเป็นค่าเฉลี่ยที่หยาบกว่า โดยเขียนทับข้อมูลที่เก่าที่สุด
    • ค่ามัธยฐาน / เปอร์เซ็นไทล์ที่ 95: ค่ามัธยฐานคือค่าที่อยู่ตรงกลาง (หรือค่าเฉลี่ยของสองค่าที่อยู่ตรงกลาง) ค่าที่อ่านได้ 95 เปอร์เซ็นต์อยู่ที่หรือต่ำกว่าเปอร์เซ็นไทล์ที่ 95
    • API: ส่วนเชื่อมต่อของ router ที่ให้โปรแกรมอื่นเรียกใช้ได้ ให้ข้อมูลชุดเดียวกับที่หน้าเว็บแสดง ในรูป JSON
    • Tunables: การตั้งค่า kernel ที่ OPNsense ใช้ตอน boot อยู่ในรายการที่ System → Settings → Tunables
  • The Pi-hole that wasn’t dead: getting back in without a password

    The Pi-hole that wasn’t dead: getting back in without a password

    If your Pi-hole admin page stopped loading after the v6 upgrade: try http://<pi-address>:8080/admin, or https://<pi-address>/admin and accept the certificate warning. That was my whole problem. If neither loads, Step 5 shows how to find the port in a minute. The rest of this post is how I found it the long way round, and what I changed while I was in there.

    On 25 October 2026 the Pi-hole admin page would not load. The browser said the site could not be reached and that the Pi had refused to connect. It had said the same when I last tried, in 2025, and I had let it go.

    This time I also found I had forgotten both passwords: the one for the Pi-hole web page and the one for the Pi’s own login. SSH answered, but pi / raspberry was refused. That is expected. Raspberry Pi OS images have shipped without a default user since 2022.

    One thing did not fit. The internet in the house still worked, and ads were still blocked.

    I did the work over two days with Claude. I made the decisions and ran every command on the Pi; the diagnosis plan, the scripts and some of the wrong turns came from the model. The wrong turns are in here as well, because they were the useful part.

    New to the command line? How to read the boxes

    PS> means: type this in PowerShell on Windows (Start menu → type powershell → Enter). $ means: type this in a terminal on Linux or a Mac, or on the Pi after you have logged in with ssh. Do not type the $ or PS> itself.

    Each line that starts with $ or PS> is one command. Click that $ 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; you do not type it.

    The setup

    • Raspberry Pi 4 Model B, on the official Raspberry Pi 15 W USB-C supply (5.1 V, 3 A).
    • SanDisk 128 GB microSD card, made in February 2024.
    • Wired by Ethernet to a mesh Wi-Fi router. The ISP’s fibre router sits in front of it.
    • Raspberry Pi OS Bookworm, desktop edition, installed in May 2024. Pi-hole v5 installed the same month, upgraded to v6 in July 2025.
    • The router hands out the Pi as the only DNS server. That is what makes ad-blocking cover every device in the house, and it is also why the Pi matters more than its size suggests.

    In this article the Pi is 192.168.x.51 and the router is 192.168.x.1.

    Test DNS before you decide Pi-hole is down

    A dead web page and a dead Pi-hole are different things. From a Windows laptop:

    nslookup doubleclick.net 192.168.x.51

    The answer was 0.0.0.0. The Pi was answering DNS queries and blocking an ad domain. Pi-hole was working. Only its web page looked dead.

    That changed the job. I was not repairing an outage. I was getting back into a box that worked, without breaking it on the way in.

    Step 1: protect the house before touching the Pi

    With the Pi as the only DNS server, pulling its card stops name resolution for every phone, TV and laptop in the house.

    Changing the router’s DNS a few minutes before the work is not enough. Devices keep the DNS server they were given until their DHCP lease renews, which can take hours. So on the night of 25 October I set the router’s primary DNS to 1.1.1.1. By morning every device had picked it up and the Pi could go offline without anyone noticing.

    I kept one rollback rule through the whole job: the original card, untouched, goes back in and the house is as it was.

    When the work was done, I set the router’s primary DNS back to the Pi. The lease delay works the same way in reverse: each device returns to the Pi when its lease renews. To hurry a Windows laptop, run ipconfig /renew; on a phone, turn Wi-Fi off and on. Then nslookup doubleclick.net with no server named should answer 0.0.0.0.

    Step 2: image the card first

    I had no spare card, so any change would be made on the original. A full image came first.

    On Windows I used Win32 Disk Imager:

    1. Choose a file name for the image on a drive with 130 GB free.
    2. Select the card’s drive letter.
    3. Tick Read Only Allocated Partitions.
    4. Press Read. Not Write. Write copies the image file onto the card and destroys what is on it.

    128 GB at about 28 MB/s took roughly 75 minutes.

    I then checked the image’s structure:

    • MBR signature 55aa present.
    • Partition 1: FAT, labelled bootfs.
    • Partition 2: ext4, labelled rootfs, ext4 magic number 0xEF53 in the right place, and its end matches the end of the image file, so the copy was not cut short.

    That proves the layout, not every byte. Win32 Disk Imager’s Verify Only button compares the whole image with the card; it takes about as long again.

    One side lesson. The image was the full 128 GB though the card turned out to be 6% used. “Read Only Allocated Partitions” stops at the end of the last partition, and on a Pi the root partition expands to fill the card at first boot. The size of the image says nothing about how full the card is.

    I also copied the files from the boot partition, which Windows shows as a drive called bootfs. Those are the files I was about to edit.

    Step 3: getting in without a password

    By then I had a screen and a keyboard on the Pi, and it booted to its desktop. I did not try them. On Raspberry Pi OS the desktop user can often run sudo without a password, so a terminal there may have been enough to reset the password. I wanted SSH from the laptop, by key, for everything that followed: commands I could paste, files I could copy, and no password to remember. So I took the longer route.

    Raspberry Pi Imager has the mechanism built in, for Bookworm images. When you set a user name or Wi-Fi in Imager, it writes a script to the boot partition and asks systemd to run it once at first boot, from the kernel command line. I used the same mechanism with my own script.

    The reset needs three files on the boot partition: the script, pi_reset.sh; the laptop’s SSH public key, saved as pi_key.pub; and an edited cmdline.txt. cmdline.txt is a single line. The edit appends this to its end, with one space before it and no line break:

    systemd.run=/boot/firmware/pi_reset.sh systemd.run_success_action=reboot systemd.unit=kernel-command-line.target

    Bookworm mounts the boot partition at /boot/firmware; older images use /boot. I made the edit with a short Python helper that refuses to touch a line that already carries such an entry.

    At boot the script adds the key for root and for every login user, enables SSH, writes pi_reset.log to the boot partition, removes its own entry from cmdline.txt and deletes itself. systemd then reboots the Pi. The script, the helper and the copy steps are in The kit at the end.

    Three cautions:

    • Public key only. The private key never leaves the laptop.
    • Line endings. A script saved with Windows (CRLF) line endings does not run at all. Then nothing reboots the Pi and nothing removes the entry from cmdline.txt, so the Pi stops at the same point on every boot, with no network. The helper converts the script to Unix (LF) endings for you. If a Pi does hang this way, put the card in the laptop and copy your original cmdline.txt back.
    • Test the cleanup. If the cleanup damages cmdline.txt, the Pi will not boot. Before I put the card back, I ran the script’s cleanup against the edited cmdline.txt and compared the result with my copy of the original. It matched byte for byte. The kit has the one-line test.

    The Pi booted, ran the script, rebooted, and this worked with no password:

    ssh root@192.168.x.51

    Debian’s default SSH setting, PermitRootLogin prohibit-password, refuses root passwords but allows root login by key. The log on the boot partition named my old user. The kit’s version of the script also writes the cleaned cmdline.txt line into the log, so the cleanup can be confirmed without opening the file.

    One distraction: on the desktop edition a Wi-Fi password prompt appeared on the screen after the reboot. On a wired Pi it does not matter. Cancel it.

    Step 4: diagnosis from the logs

    Before changing anything I ran one script, pi_diag.sh (in The kit), that changes no settings. If the page had stopped answering, I wanted to know whether power, the card or the software was failing. The script gathers everything below into one report and removes hardware addresses from it.

    Power. vcgencmd get_throttled returns a bit field of power and heat events since boot. It read 0x0. I then loaded all four cores for 60 seconds:

    for i in 1 2 3 4; do timeout 60 sh -c 'while :; do :; done' & done; wait
    vcgencmd get_throttled
    vcgencmd measure_temp

    Still 0x0, and no “Undervoltage” lines in the journal, which held entries back to May 2026. The supply passes. The temperature reached 73 °C; a GPIO fan overlay in config.txt switches the fan on at 70 °C, so that is the fan doing its job.

    Card. The kernel reports the card’s identity:

    cat /sys/block/mmcblk0/device/{name,manfid,oemid,date}

    SN128, SanDisk, made 02/2024. No mmc or ext4 errors in the logs. df -h showed 6.5 GB used of 117 GB. The card passes.

    Where the space went. /var/log held 785 MB. Pi-hole’s query database held 325 MB, a year of history. gravity.db and gravity_old.db were about 145 MB each. The rest was the desktop: Chromium, Firefox, VLC, CUPS, VNC. A DNS server needs none of them.

    Restarts. About 20 boots since May. The times are unreliable, because the Pi has no clock battery and restores the last saved time at boot. Power cuts are the likely cause, and I found no damage from them. A plug that sits loose in its socket is worth checking if your count is higher than your power cuts.

    Pi-hole. pihole -v showed v6 (Core 6.1.4, Web 6.2.1, FTL 6.2.3). The apt history dates the upgrade to July 2025. lighttpd was inactive and disabled. In v5 that would be the fault. In v6 it is correct, because FTL now serves the web page itself.

    Before I changed anything I took a settings backup:

    pihole-FTL --teleporter

    That writes a Teleporter zip in the current folder. The v5 command, pihole -a -t, no longer exists in v6.

    Step 5: why the Pi-hole admin page was not loading

    pihole-FTL --config webserver.port

    returned:

    8080o,443os,[::]:8080o,[::]:443os

    and ss -tlnp | grep -i ftl showed FTL listening on 8080, 443 and 53.

    When Pi-hole upgraded from v5 to v6 in July 2025, its new web server ended up on port 8080. That is a known outcome of v5-to-v6 upgrades; the cause is not settled. http://192.168.x.51:8080/admin had worked the whole time.

    Nothing was broken. The page had not died twice. It had been on 8080 since July 2025, and I had looked at port 80 twice. My bookmark pointed at port 80, and nothing listens there any more.

    What would have found this in a minute. I did not need the card image or the reset to see it. From the laptop, in PowerShell:

    Test-NetConnection 192.168.x.51 -Port 80
    Test-NetConnection 192.168.x.51 -Port 8080

    TcpTestSucceeded : False on 80 and True on 8080 tells the whole story. On Linux or a Mac, nc -zv 192.168.x.51 8080 does the same. I would still have needed a way in for the forgotten passwords. But I would have gone in knowing the box was healthy, and the morning would have been shorter.

    I kept 8080 and changed the bookmark. To move it back to 80, first make sure nothing else holds port 80, then change the setting and check:

    sudo systemctl disable --now lighttpd
    sudo pihole-FTL --config webserver.port '80o,443os,[::]:80o,[::]:443os'
    sudo systemctl restart pihole-FTL
    sudo ss -tlnp | grep ':80 '

    The last line should show pihole-FTL. The o in 80o makes the port optional: if something else holds it, FTL skips it without an error. If you use the health check in the kit, set its WEB_URL to the new port.

    Step 6: modernise in place, no reflash

    The power, the card and the software were all healthy. A clean reinstall would have fixed nothing and cost a morning. Bookworm is still supported: Debian handed security support for it to the Debian LTS team in July 2026, and LTS runs to 30 June 2028.

    Boot to the console, not the desktop.

    sudo systemctl set-default multi-user.target

    Update the OS and keep security updates coming.

    sudo apt-get update && sudo apt-get -y full-upgrade
    sudo apt-get install -y unattended-upgrades

    In /etc/apt/apt.conf.d/20auto-upgrades:

    APT::Periodic::Update-Package-Lists "1";
    APT::Periodic::Unattended-Upgrade "1";

    I left automatic reboots off. I would rather reboot a DNS server when I choose.

    This Pi runs 64-bit Raspberry Pi OS. Its Debian packages match the default rule in unattended-upgrades, so Debian security fixes install themselves. The kernel and firmware come from Raspberry Pi’s own archive and still need sudo apt full-upgrade by hand; the monthly report below says when a reboot is due. To see what would install on your own Pi: sudo unattended-upgrade --dry-run -d.

    Cap the journal at 64 MB. My Pi already kept its logs on disk; the setting makes that explicit. The folder may not exist yet:

    sudo mkdir -p /etc/systemd/journald.conf.d

    Then, in /etc/systemd/journald.conf.d/size.conf:

    [Journal]
    Storage=persistent
    SystemMaxUse=64M

    then sudo systemctl restart systemd-journald.

    Update Pi-hole.

    sudo pihole -up

    This took it to the current v6 release, and then printed “Everything is up to date!”, which reads as if nothing had happened. Confirm with pihole -v and cat /etc/pihole/versions rather than trusting the last line.

    Keep 30 days of query history, not a year.

    sudo pihole-FTL --config database.maxDBdays 30

    Old rows are deleted daily. SQLite reuses the space rather than shrinking the file, so the database stops growing instead of getting smaller.

    Set a new web password.

    sudo pihole setpassword

    Save the password in a password manager before you type it. I did not, forgot it within minutes, and reset it the same way.

    Step 7: make it look after itself

    The page had been “dead” for months without my knowing what was wrong. I wanted the Pi to tell me, and to fix the one failure a restart can fix, without making anything worse.

    A health check every 15 minutes, run by a systemd timer. In order:

    • Pause during updates. If Pi-hole is updating itself or rebuilding its block lists, it may stop its own DNS on purpose, so the check stands aside. If that lasts over 30 minutes, it alerts and checks anyway.
    • Is DNS answering at all? It asks Pi-hole for pi.hole. Any reply counts, even “no such name”. Only no reply at all is a DNS failure. A failed check is repeated once after 5 seconds, so one dropped packet changes nothing.
    • If DNS is not answering: restart pihole-FTL, wait up to 60 seconds for it, and report whether it came back. At most two restarts in six hours; after that it only alerts, so a fault a restart cannot fix does not keep cutting the house’s DNS.
    • If DNS answers, three more checks, each of which only alerts: the test domain (added once with pihole deny health.blocked.test) must come back 0.0.0.0, or ad-blocking may have stopped; the admin page at WEB_URL must answer, where a redirect or a login prompt counts as alive; and an outside name must resolve, or the internet is down. None of these is fixed by a restart, and a restart would cut DNS for the whole house.
    • The card and the power. An alert when the card passes 80%. An alert when the under-voltage or throttling flags first appear (get_throttled bits 16 and 18, mask 0x50000), not again every day.
    • Limits. Every run has a five-minute ceiling, so a stuck command cannot quietly end all monitoring. State lives in /run, in RAM; the only writes to the card are systemd’s log lines for each run.

    Notifications go through ntfy, a free phone app that needs no account. You subscribe to a topic, and anything posted to that topic arrives on the phone:

    curl -s -d "Pi-hole DNS failed after restart" https://ntfy.sh/<your-long-random-topic>

    Anyone who knows the topic name can read it and post to it, so make it long and random and treat it like a password. Repeat alerts are suppressed: once an hour for DNS down, every six hours for the web page and the internet, once a day for the card.

    The worst-case message says how to restore the house without me: open the router, go to DHCP settings, set the primary DNS to 1.1.1.1. Whoever reads it does not need to know what a Pi-hole is. The check cannot see what the router hands out, so it will not notice a house left on 1.1.1.1; ipconfig /all on a laptop shows which DNS server it was given.

    One trap, and it was real on my Pi. That worst-case alert is sent when DNS is down, and curl has to look up ntfy.sh before it can send anything. My Pi uses Pi-hole as its own resolver, so in that moment the lookup would fail and the alert would never leave. To see whether your Pi is in the same position:

    cat /etc/resolv.conf

    A nameserver line of 127.0.0.1, ::1 or the Pi’s own address means it is. The kit closes it twice. The alert helper looks up ntfy.sh through 1.1.1.1, or 9.9.9.9 if that fails, and hands the address to curl. And, optionally, the Pi’s own lookups get a fallback: Pi-hole first, then 1.1.1.1. That keeps updates, Tailscale and alerts working on the Pi when Pi-hole is down. The house still uses only the Pi.

    Why every 15 minutes? The check takes well under a second of CPU, so cost is not the limit. The interval sets how long the house can be without DNS before the Pi repairs itself. I started at 5 minutes and settled on 15. Choose 5 if you want faster repair.

    A monthly report to the phone on the 1st: Pi-hole versions and whether an update waits, OS packages waiting, whether automatic security updates are switched on, whether a reboot is due (the running kernel against the installed one), the Pi’s own DNS servers, the date of the last backup, card use, database size, power flags and uptime. Pi-hole itself I update by hand on that prompt. Pi-hole’s developers advise against unattended Pi-hole updates, and I agree with them for a box everything depends on.

    A weekly settings backup every Sunday with pihole-FTL --teleporter, keeping the last four, readable by root only because they hold the web password hash. One warning that cost nothing to learn: with no argument, --teleporter exports a backup; given a file name, it imports that file and overwrites your settings. The backups sit on the same card, so I copy them to the laptop now and then.

    How it was tested. Every failure path ran against mock versions of the Pi’s commands: healthy, web page down, test domain not blocked, internet down, a single brief failure, DNS dead and recovering, DNS dead for good, a third failure within six hours, an update in progress, and the power flags. The tests passed and still missed the trap above: a mocked curl never looks anything up. A review also found that an earlier version restarted Pi-hole when only the web page failed, which would have cut the house’s DNS to fix a page. That is why only “no reply at all” now leads to a restart.

    The scripts, their timers and the install steps are in The kit.

    Step 8: remote administration with Tailscale

    The last piece was reaching the Pi to administer it from outside the house. I used Tailscale:

    curl -fsSL https://tailscale.com/install.sh | sh
    sudo tailscale up --accept-dns=false
    sudo tailscale set --auto-update

    --accept-dns=false matters on a Pi-hole. Without it, Tailscale rewrites the Pi’s own DNS settings.

    In the Tailscale admin console I disabled key expiry for the Pi. By default a device’s key expires after about 180 days and the device drops off the network. That will happen when you are furthest from it.

    SSH now works from anywhere through the Pi’s Tailscale address. Port forwarding looked like a dead end: the ISP appears to use carrier-grade NAT, because its public hostname contains “cgn”. The firmer test is the internet-side address on the ISP router; one in 100.64.0.0/10 means carrier-grade NAT, and there is no public address to forward. A mesh VPN is the practical route.

    Tailscale warned that “UDP GRO forwarding is suboptimally configured on eth0”. That matters only if the Pi forwards heavy UDP traffic as a subnet router or exit node. For SSH, ignore it.

    Note, 27 October 2026. On 25 October a researcher published “Tailworm”, a report of 11 flaws in Tailscale 1.104.2, the current version at the time. The serious ones are in Tailscale SSH, Tailscale’s own SSH server, and need an attacker who already controls a device that is allowed to log in. This Pi does not run Tailscale SSH. I reach it with ordinary OpenSSH over the tailnet, which the report does not touch. Auto-update is on, so the fix will arrive when Tailscale ships one. At the time of writing Tailscale had issued no bulletin, CVE or fixed version.

    To check your own devices, run tailscale debug prefs on each one. "RunSSH": false means Tailscale SSH is off.

    Two network surprises

    1. A second, unfiltered Wi-Fi. At one point the laptop could not reach the Pi by its LAN address though everything looked right. ipconfig showed an address in a different range from the mesh, with the ISP’s DNS servers. The laptop had joined the ISP fibre router’s own Wi-Fi, not the mesh. Every device on that network bypasses Pi-hole. The fix: move anything that still uses that Wi-Fi to the mesh or to a cable, then switch off the ISP router’s Wi-Fi. If you run a mesh behind an ISP router, check that the ISP router’s Wi-Fi is off.

    2. The wrong window. Test-NetConnection is a PowerShell command. In Command Prompt it fails with “not recognized”. Several of my “commands not working” moments were the right command in the wrong window.

    What I thought, and what it was

    I thought the Pi-hole had died twice. It had moved its web page once, during an upgrade, and I had been knocking on the old door.

    The morning of 26 October 2026 went on imaging the card, getting back in and reading logs. By noon the Pi was updated, watching itself, and serving the house again. By the afternoon I could reach it from anywhere.

    What I would tell anyone with a Pi-hole whose page has vanished:

    1. Test DNS first. nslookup an ad domain against the Pi.
    2. Check which ports answer (Test-NetConnection <pi> -Port 8080), then try :8080/admin.
    3. Move the house off the Pi’s DNS the night before you touch it.
    4. Image the card and check the image before you edit anything.
    5. Save the new password before you type it.
    6. Point the router back at the Pi when you are done.

    The kit

    Every script in this post, ready to copy. The names carry a pi_ prefix; rename them if you like, but keep the names the same across scripts, units and commands. The scripts on the Pi run as root.

    1. Reset: back in without a password

    You need a laptop that can read the card’s boot partition (Windows can), a card reader, an SSH key pair on the laptop, and Python 3 for the helper.

    1. Check for an SSH key on the laptop. In PowerShell: Test-Path $env:USERPROFILE\.ssh\id_ed25519.pub. If it says False, create one with ssh-keygen -t ed25519, accept the default file and set a passphrase. If it says True, do not create another: a new key replaces the old one and breaks anything that uses it.
    2. Make a folder for the kit. Save pi_reset.sh and pi_make_cmdline.py (below) in it. Check that Windows has not added .txt to either name. Copy the public key in beside them: Copy-Item $env:USERPROFILE\.ssh\id_ed25519.pub .\pi_key.pub
    3. Power the Pi off and put its card in the reader. If Windows offers to format a drive, click Cancel: that is the Linux partition, which Windows cannot read.
    4. Copy the whole boot drive (labelled bootfs, or boot on older images) to a backup folder. Copy its cmdline.txt into the kit folder as cmdline_old.txt.
    5. In the kit folder run python pi_make_cmdline.py cmdline_old.txt bootfs (use boot for an older image). It prints the old and new line, writes a new cmdline.txt, and converts pi_reset.sh to Unix (LF) line endings. Your cmdline_old.txt is not changed.
    6. Test the cleanup before you trust it. This applies the script’s cleanup to the new line and compares the result with the original:
    python -c "import re;a=open('cmdline_old.txt',newline='').read();b=re.sub(r' systemd\.run.*','',open('cmdline.txt',newline='').read());print(a==b)"

    It must print True. If it prints False, stop and compare the two files by eye.

    1. Copy pi_reset.sh, pi_key.pub and the new cmdline.txt to the boot drive. Let it replace cmdline.txt; the original is in your backup.
    2. Eject the drive, put the card back and power on. Wait about four minutes: boot, script, reboot, boot. Then ssh root@192.168.x.51.
    • If the key is refused, power off, put the card in the laptop and read pi_reset.log on the boot drive. It lists the users the key was added for.
    • If the Pi does not answer at all after ten minutes, the script did not run and the Pi stops at the same point on every boot. Power off, put the card in the laptop, and copy cmdline_old.txt from your kit folder onto the boot drive as cmdline.txt. That returns the card to where it started.
    1. Once in, give your own user a password and save it in a password manager, so access no longer depends on one laptop’s key: passwd <your-user>. If you would rather not leave root login open, first open a second window and check that ssh <your-user>@192.168.x.51 and sudo -v both work. Then:
    echo 'PermitRootLogin no' > /etc/ssh/sshd_config.d/no-root.conf
    systemctl restart ssh

    Keep the first window open until a new login as your user works. With root login off, the later commands in this kit change: log in as <your-user>@, run the diagnosis with sudo bash, and copy backups with sudo cp into your home folder before scp.

    pi_reset.sh:

    #!/bin/bash
    # pi_reset.sh - one-shot, headless access fix for the Pi.
    # Run once by systemd at boot via cmdline.txt "systemd.run=...". It:
    #   - appends the laptop's PUBLIC key (pi_key.pub on the boot partition) to
    #     root's and every login user's authorized_keys (no password is read or set);
    #   - enables ssh; writes pi_reset.log on the boot partition (user names, OS);
    #   - removes its own cmdline entry and itself. systemd then reboots the Pi.
    set +e
    B=/boot/firmware
    [ -f "$B/cmdline.txt" ] || B=/boot
    LOG="$B/pi_reset.log"
    addkey() {  # append the key on its own line, even if the file lacks a final newline
      [ -s "$1" ] && [ -n "$(tail -c1 "$1")" ] && echo >> "$1"
      cat "$B/pi_key.pub" >> "$1"
    }
    {
      echo "pi_reset start $(date -Is)"
      echo "boot dir: $B"
      if [ -s "$B/pi_key.pub" ]; then
        install -d -m 700 /root/.ssh
        addkey /root/.ssh/authorized_keys
        chmod 600 /root/.ssh/authorized_keys
        echo "key added for root"
        getent passwd | awk -F: '$3>=1000 && $3<60000 {print $1 ":" $6}' |
        while IFS=: read -r u h; do
          [ -d "$h" ] || continue
          g=$(id -gn "$u")
          install -d -m 700 -o "$u" -g "$g" "$h/.ssh"
          addkey "$h/.ssh/authorized_keys"
          chown "$u:$g" "$h/.ssh/authorized_keys"
          chmod 600 "$h/.ssh/authorized_keys"
          echo "key added for user: $u"
        done
      else
        echo "ERROR: $B/pi_key.pub missing or empty - nothing changed"
      fi
      systemctl enable ssh
      echo "sshd PermitRootLogin lines (none = Debian default prohibit-password, key login allowed):"
      grep -hiE '^[[:space:]]*PermitRootLogin' /etc/ssh/sshd_config /etc/ssh/sshd_config.d/*.conf 2>/dev/null
      # shellcheck disable=SC1091
      echo "os: $(. /etc/os-release; echo "$PRETTY_NAME")"
      echo "pi_reset end $(date -Is)"
    } >> "$LOG" 2>&1
    sed -i 's| systemd.run.*||g' "$B/cmdline.txt"
    echo "cmdline.txt after cleanup: $(cat "$B/cmdline.txt")" >> "$LOG"
    rm -f "$B/pi_reset.sh"
    sync
    exit 0

    pi_make_cmdline.py:

    #!/usr/bin/env python3
    # pi_make_cmdline.py - build the reset cmdline.txt.
    # usage: python3 pi_make_cmdline.py cmdline_old.txt bootfs|boot
    # Reads the old card's cmdline.txt copy, appends the one-shot systemd.run entry,
    # writes cmdline.txt next to it (LF ending). The original copy is not changed.
    # If pi_reset.sh sits in the same folder, it is converted to Unix (LF) line endings.
    import sys, os, hashlib
    src, label = sys.argv[1], sys.argv[2]
    base = {"bootfs": "/boot/firmware", "boot": "/boot"}[label]
    raw = open(src, "rb").read()
    line = raw.decode("ascii").replace("\r", "").strip()
    if "\n" in line:
        sys.exit("STOP: cmdline has more than one line - check it by hand")
    if "systemd.run" in line or "init=/bin/sh" in line:
        sys.exit("STOP: cmdline already carries a run/init entry - check it by hand")
    new = line + f" systemd.run={base}/pi_reset.sh systemd.run_success_action=reboot systemd.unit=kernel-command-line.target\n"
    out = os.path.join(os.path.dirname(os.path.abspath(src)), "cmdline.txt")
    open(out, "wb").write(new.encode("ascii"))
    print("old :", line)
    print("new :", new.rstrip())
    rs = os.path.join(os.path.dirname(os.path.abspath(src)), "pi_reset.sh")
    if os.path.exists(rs):
        b = open(rs, "rb").read()
        if b"\r" in b:
            open(rs, "wb").write(b.replace(b"\r\n", b"\n"))
            print("pi_reset.sh: converted to LF line endings")
        else:
            print("pi_reset.sh: line endings already LF")
    else:
        print("WARNING: pi_reset.sh not found next to", src)
    print("sha256 old copy", hashlib.sha256(raw).hexdigest()[:16], "new", hashlib.sha256(new.encode()).hexdigest()[:16])

    2. Diagnosis (changes no settings)

    One run collects power, card, log, disk and Pi-hole facts into a report in /root, with hardware addresses removed. It also writes a Teleporter backup and a copy of /etc/pihole without the query database, both to the card itself; on my Pi that copy was about 130 MB, because it includes the blocklist databases. It takes about 70 seconds, most of it the 60-second load test. From the laptop:

    scp pi_diag.sh root@192.168.x.51:/root/
    ssh root@192.168.x.51 "bash /root/pi_diag.sh"

    pi_diag.sh:

    #!/bin/bash
    # pi_diag.sh - diagnosis of a Pi-hole card. Changes no settings.
    # Run as root:  bash /root/pi_diag.sh
    # Writes /root/pi_diag_<date>.txt (hardware addresses scrubbed), a Pi-hole
    # Teleporter backup and a copy of /etc/pihole (without the query database) in /root.
    # Changes no settings. Includes a 60-second full-CPU load test to check the power supply.
    set +e
    TS=$(date +%Y%m%d_%H%M)
    OUT=/root/pi_diag_$TS.txt
    scrub() { sed -E 's/([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}/[hw-addr removed]/g'; }
    sec() { echo; echo "===== $* ====="; }
    logs() { dmesg 2>/dev/null; journalctl -k --no-pager 2>/dev/null; zcat -f /var/log/kern.log* /var/log/syslog* /var/log/messages* 2>/dev/null; }
    {
      sec "when"; date -Is; uptime
      sec "os"; cat /etc/os-release; uname -a
      sec "model"; tr -d '\0' < /proc/device-tree/model; echo
      sec "power: throttled flags since this boot (0x0 = never)"; vcgencmd get_throttled; vcgencmd measure_volts core; vcgencmd measure_temp
      sec "power: undervoltage lines in kept logs"; logs | grep -iE 'under-?voltage|voltage normali[sz]ed' | sort | uniq -c | tail -40
      sec "card: identity"; for f in name manfid oemid date type; do printf '%s: ' "$f"; cat "/sys/block/mmcblk0/device/$f" 2>/dev/null; done
      sec "card: errors in kept logs"; logs | grep -iE 'mmc0|mmcblk|I/O error|EXT4-fs (error|warning)|Buffer I/O|remount.*read-only' | sort | uniq -c | sort -rn | head -60
      sec "journal boots kept"; journalctl --list-boots --no-pager 2>/dev/null | tail -20
      sec "reboots and shutdowns"; last -x reboot shutdown 2>/dev/null | head -20
      sec "disk"; df -h; du -sh /var/log /etc/pihole /var/log/pihole 2>/dev/null; ls -la /etc/pihole
      sec "pihole version and status"; pihole -v 2>&1; pihole status 2>&1
      sec "failed services"; systemctl --no-pager --failed
      for s in pihole-FTL lighttpd; do sec "service $s"; systemctl --no-pager -l status "$s" 2>&1 | head -30; done
      sec "lighttpd error logs"; tail -60 /var/log/lighttpd/error*.log 2>/dev/null
      sec "php"; php -v 2>&1 | head -2; ls /etc/php 2>/dev/null; grep -rh php /etc/lighttpd/conf-enabled/ 2>/dev/null | head -20
      sec "apt history (dates, commands, php, lighttpd, pihole)"; zcat -f /var/log/apt/history.log* 2>/dev/null | grep -E '^(Start-Date|Commandline)|php|lighttpd|pihole' | tail -150
      sec "FTL log tail"; tail -40 /var/log/pihole/FTL.log /var/log/pihole-FTL.log 2>/dev/null
    } 2>&1 | scrub > "$OUT"
    cd /root || exit 1
    {
      sec "teleporter backup"
      if pihole -v 2>/dev/null | grep -q 'version is v6'; then pihole-FTL --teleporter; else pihole -a -t; fi
      tar czf "/root/pihole_etc_$TS.tgz" --exclude='pihole-FTL.db*' --exclude='macvendor.db' /etc/pihole /etc/dnsmasq.d 2>&1
      sec "power: 60-second full-CPU load test"
      echo "before: $(vcgencmd get_throttled)"
      for i in 1 2 3 4; do timeout 60 sh -c 'while :; do :; done' & done; wait
      echo "after:  $(vcgencmd get_throttled)  $(vcgencmd measure_volts core)  $(vcgencmd measure_temp)"
      sec "files in /root"; ls -la /root
    } 2>&1 | scrub >> "$OUT"
    echo "REPORT WRITTEN: $OUT"

    3. Health check, monthly report and weekly backup

    All commands run on the Pi over SSH.

    Tools. The scripts use dig and curl:

    sudo apt-get install -y dnsutils curl

    Settings file. This reads the port your admin page uses (the first plain-HTTP entry, skipping the HTTPS ones), makes a random ntfy topic, and writes both, with the test domain, to /etc/pi-health.conf. The scripts read it from there, so they hold no secret.

    P=$(sudo pihole-FTL --config webserver.port | tr ',' '\n' | grep -v 's' | grep -oE '^[0-9]+' | head -1)
    T="pihole-$(tr -dc a-z0-9 < /dev/urandom | head -c 20)"
    printf 'TOPIC=%s\nHC_DOMAIN=health.blocked.test\nWEB_URL=http://127.0.0.1:%s/admin/\n' "$T" "$P" | sudo tee /etc/pi-health.conf
    sudo chmod 600 /etc/pi-health.conf

    tee prints the three lines. Check that WEB_URL shows your port (80 on a fresh v6 install, 8080 on many upgraded ones). Subscribe to the topic in the ntfy app. Running these lines again makes a new topic and replaces the old one, so your phone would need to subscribe again. If you later move the admin page to another port, change WEB_URL to match.

    Optional: an outside “dead man’s switch” service gives you a ping address and alerts you when the pings stop, which covers a Pi that loses power or its internet. Add PING_URL=<that address> to the same file.

    Test domain. Block it and check the answer:

    sudo pihole deny health.blocked.test
    dig +short @127.0.0.1 health.blocked.test

    The second line must print 0.0.0.0. If it prints nothing, the health check will report that blocking has stopped on every run; fix this first.

    Scripts. Save each one with sudo nano /usr/local/bin/<name> (paste, then Ctrl + O, Enter, Ctrl + X), then make them executable:

    sudo chmod 755 /usr/local/bin/pi_ntfy.sh /usr/local/bin/pi_health.sh /usr/local/bin/pi_report.sh /usr/local/bin/pi_backup.sh

    pi_ntfy.sh, the alert helper the other scripts call:

    #!/bin/bash
    # pi_ntfy.sh - send one phone notification through ntfy.sh.
    # Usage: pi_ntfy.sh "Title" "message"     Exit 0 only if ntfy accepted it.
    # ntfy.sh is looked up through 1.1.1.1, then 9.9.9.9 - not through Pi-hole - so alerts
    # still go out when Pi-hole's DNS has failed. Falls back to a normal lookup if both fail.
    set -u
    # shellcheck disable=SC1091
    . /etc/pi-health.conf          # TOPIC=...
    ip="" r=()
    for ns in 1.1.1.1 9.9.9.9; do
      ip=$(dig +short +time=3 +tries=1 @"$ns" ntfy.sh A 2>/dev/null | grep -m1 -E '^[0-9]+(\.[0-9]+){3}$')
      [ -n "$ip" ] && break
    done
    [ -n "$ip" ] && r=(--resolve "ntfy.sh:443:$ip")
    curl -fsS -m 15 "${r[@]}" -H "Title: $1" -d "$2" "https://ntfy.sh/$TOPIC" >/dev/null

    pi_health.sh:

    #!/bin/bash
    # pi_health.sh - Pi-hole health check, run every 15 minutes by pi-health.timer.
    #  - pihole-FTL is restarted ONLY when DNS gives no reply at all. A web-page-only fault,
    #    a test domain that is no longer blocked, or an odd answer is reported, never
    #    "fixed" by a restart (a restart cuts the house's DNS).
    #  - at most 2 restarts in 6 hours; after that it alerts only.
    #  - a failed check is repeated once after 5 s before anything is done;
    #  - after a restart, waits up to 60 s for DNS instead of a fixed 20 s;
    #  - pauses while Pi-hole is updating itself or rebuilding its block lists, but alerts
    #    and resumes checking if that has lasted over 30 minutes;
    #  - alerts go through pi_ntfy.sh (ntfy.sh looked up via 1.1.1.1 / 9.9.9.9);
    #  - the admin page address comes from WEB_URL in /etc/pi-health.conf;
    #  - power alert only when the throttle flags change, not every day;
    #  - optional PING_URL in /etc/pi-health.conf: pinged every run, so an outside
    #    monitor can alert when the Pi goes silent (power, card or home-internet failure).
    # State lives in /run (RAM); nothing is written to the card except the journal line.
    set -u
    # shellcheck disable=SC1091
    . /etc/pi-health.conf          # TOPIC=..., HC_DOMAIN=..., WEB_URL=..., optional PING_URL=...
    WEB_URL=${WEB_URL:-http://127.0.0.1:8080/admin/}
    ST=/run/pi-health; mkdir -p "$ST"
    now=$(date +%s)
    notify() {  # key, seconds-between-repeats, message
      local f="$ST/$1" last
      last=$(cat "$f" 2>/dev/null || echo 0)
      if (( now - last >= $2 )); then
        /usr/local/bin/pi_ntfy.sh "Pi-hole" "$3" && echo "$now" > "$f"
      fi
    }
    q()          { dig +short +time=2 +tries=1 @127.0.0.1 "$1" A 2>/dev/null; }
    # Any reply at all (NOERROR, NXDOMAIN, REFUSED...) means FTL is answering; dig exits 9
    # only when no reply came back. Answered locally, so it needs no internet.
    dns_alive()  { dig +time=2 +tries=1 @127.0.0.1 pi.hole A >/dev/null 2>&1; }
    blocking_ok(){ [ "$(q "$HC_DOMAIN")" = "0.0.0.0" ]; }
    web_ok()     { case "$(curl -s -o /dev/null -m 5 -w '%{http_code}' "$WEB_URL")" in 200|301|302|303|307|308|401) return 0;; esac; return 1; }
    net_ok()     { q google.com | grep -qE '^[0-9]+(\.[0-9]+){3}$'; }
    retry()      { "$@" || { sleep 5; "$@"; }; }
    
    # Pi-hole updating itself or rebuilding block lists: FTL may be stopped on purpose.
    # Matches only bash running Pi-hole's own gravity.sh / update.sh / basic-install.sh.
    if pgrep -f '^(/usr)?(/bin/)?bash .*(/opt/pihole/(gravity|update)|basic-install)\.sh' >/dev/null; then
      [ -f "$ST/skip_since" ] || echo "$now" > "$ST/skip_since"
      if (( now - $(cat "$ST/skip_since") < 1800 )); then exit 0; fi
      notify skiplong 21600 "A Pi-hole update or block-list rebuild has been running over 30 minutes. Checking anyway."
    else
      rm -f "$ST/skip_since"
    fi
    
    if ! retry dns_alive; then
      # restarts in the last 6 hours (timestamps kept in RAM)
      touch "$ST/restarts"
      recent=$(awk -v c=$((now - 21600)) '$1 >= c' "$ST/restarts" | wc -l)
      if (( recent >= 2 )); then
        notify down 3600 "Pi-hole DNS NOT answering; already restarted twice in 6 hours, not restarting again. House internet may be down. Fix now: router settings > DHCP > Primary DNS 1.1.1.1 > Save."
      else
        echo "$now" >> "$ST/restarts"
        systemctl restart pihole-FTL
        ok=""
        for _ in $(seq 12); do sleep 5; dns_alive && { ok=1; break; }; done
        if [ -n "$ok" ]; then
          notify recovered 3600 "Pi-hole DNS had stopped answering and recovered after a restart."
        else
          notify down 3600 "Pi-hole DNS NOT working after restart. House internet may be down. Fix now: router settings > DHCP > Primary DNS 1.1.1.1 > Save."
        fi
      fi
    else
      retry blocking_ok || notify noblock 86400 "Pi-hole answers, but the blocked test domain ($HC_DOMAIN) is not blocked. Ad-blocking may not be working. No restart made."
      retry web_ok      || notify webdown 21600 "Pi-hole web page ($WEB_URL) not answering; DNS and ad-blocking still work. No restart made (it would cut the house's DNS). Fix: ssh in and run: systemctl restart pihole-FTL"
      retry net_ok      || notify net 21600 "Pi-hole is up but cannot reach the internet (ISP or router problem)."
    fi
    
    use=$(df --output=pcent / | tail -1 | tr -dc 0-9)
    (( ${use:-0} >= 80 )) && notify disk 86400 "Card is ${use}% full."
    thr=$(vcgencmd get_throttled 2>/dev/null | cut -d= -f2)
    if [ -n "$thr" ] && (( (thr & 0x50000) != 0 )) && [ "$thr" != "$(cat "$ST/thr_seen" 2>/dev/null)" ]; then
      notify power 0 "Under-voltage or throttling has occurred since boot ($thr). Check the power supply." && echo "$thr" > "$ST/thr_seen"
    fi
    [ -n "${PING_URL:-}" ] && curl -fsS -m 10 -o /dev/null "$PING_URL"
    exit 0

    pi_report.sh:

    #!/bin/bash
    # pi_report.sh - monthly status to the phone (pi-report.timer).
    # Sends through pi_ntfy.sh (works even if Pi-hole DNS is down);
    # reports whether the running kernel is older than the installed one (reboot needed),
    # whether automatic security updates are switched on, the Pi's own DNS servers and the
    # last weekly backup; strips colour codes from Pi-hole's update check.
    # shellcheck disable=SC1091
    . /etc/pi-health.conf
    apt-get -qq update >/dev/null 2>&1
    upg=$(apt list --upgradable 2>/dev/null | grep -c upgradable)
    ph=$(pihole -up --check-only 2>&1 | sed 's/\x1b\[[0-9;]*[A-Za-z]//g' | grep -iE 'update available|up to date|everything is up' | head -3 | tr -s ' \n' ' ')
    k=$(uname -r); newest=$(ls -1dt /lib/modules/*"${k##*+rpt-}" 2>/dev/null | head -1)
    if [ -n "$newest" ] && [ "$(basename "$newest")" != "$k" ]; then
      rb="YES (running $k, installed $(basename "$newest")) - run: systemctl reboot (back in about 2 min)"
    else rb="no"; fi
    au="$(apt-config dump 2>/dev/null | grep -E '^APT::Periodic::Unattended-Upgrade ' | grep -q '"1"' && echo on || echo OFF)"
    bk=$(ls -1t /var/backups/pihole/*.zip 2>/dev/null | head -1)
    if [ -n "$bk" ]; then bk="$(basename "$bk") ($(date -r "$bk" +%d/%m/%Y))"; else bk="NONE"; fi
    msg="Monthly report $(date +%d/%m/%Y)
    Pi-hole: $(pihole -v 2>&1 | tr '\n' ' ')
    Pi-hole updates: ${ph:-unknown}
    OS packages waiting: $upg. Debian security fixes install themselves (automatic: $au);
    Raspberry Pi kernel/firmware and other updates need, by hand: apt update && apt full-upgrade
    Reboot needed: $rb
    Tailscale: $(tailscale status --json 2>/dev/null | grep -q '"BackendState": *"Running"' && echo connected || echo 'NOT connected')
    Pi's own DNS: $(grep -E '^nameserver' /etc/resolv.conf | awk '{print $2}' | tr '\n' ' ')
    Last backup: $bk
    Card used: $(df -h --output=pcent / | tail -1 | tr -d ' ')
    Query DB: $(du -h /etc/pihole/pihole-FTL.db 2>/dev/null | cut -f1)
    Power flags since boot: $(vcgencmd get_throttled 2>/dev/null)
    Up: $(uptime -p)"
    /usr/local/bin/pi_ntfy.sh "Pi-hole monthly" "$msg"

    pi_backup.sh:

    #!/bin/bash
    # pi_backup.sh - weekly Pi-hole Teleporter export, keeps the last 4 (pi-backup.timer).
    # Files: /var/backups/pihole/*.zip, readable by root only (they hold the web password hash).
    set -e
    umask 077
    D=/var/backups/pihole
    mkdir -p "$D"; chmod 700 "$D"; cd "$D"
    # WARNING: with NO argument, --teleporter EXPORTS a zip into the current directory
    # (hence the cd above). With a file argument it IMPORTS that zip and overwrites the
    # Pi-hole settings. Never add an argument here.
    pihole-FTL --teleporter >/dev/null
    ls -1t ./*.zip 2>/dev/null | tail -n +5 | xargs -r rm -f --

    To copy the backups off now and then, from the laptop: scp "root@192.168.x.51:/var/backups/pihole/*.zip" .

    Units. Save these six files in /etc/systemd/system/ the same way. The times in the two timers are examples; set your own.

    pi-health.service:

    [Unit]
    Description=Pi-hole health check
    [Service]
    Type=oneshot
    TimeoutStartSec=5min
    ExecStart=/usr/local/bin/pi_health.sh

    pi-health.timer:

    [Unit]
    Description=Pi-hole health check every 15 minutes
    [Timer]
    OnBootSec=5min
    OnUnitActiveSec=15min
    AccuracySec=30s
    [Install]
    WantedBy=timers.target

    pi-report.service:

    [Unit]
    Description=Pi-hole monthly report
    Wants=network-online.target
    After=network-online.target
    [Service]
    Type=oneshot
    TimeoutStartSec=15min
    ExecStart=/usr/local/bin/pi_report.sh

    pi-report.timer:

    [Unit]
    Description=Pi-hole monthly report, 1st of the month 10:00
    [Timer]
    OnCalendar=*-*-01 10:00
    Persistent=true
    [Install]
    WantedBy=timers.target

    pi-backup.service:

    [Unit]
    Description=Pi-hole weekly Teleporter backup
    [Service]
    Type=oneshot
    TimeoutStartSec=5min
    ExecStart=/usr/local/bin/pi_backup.sh

    pi-backup.timer:

    [Unit]
    Description=Pi-hole weekly backup, Sunday 11:00
    [Timer]
    OnCalendar=Sun 11:00
    Persistent=true
    [Install]
    WantedBy=timers.target

    Start and test.

    sudo systemctl daemon-reload
    sudo systemctl enable --now pi-health.timer pi-report.timer pi-backup.timer
    systemctl list-timers 'pi-*' --no-pager
    sudo /usr/local/bin/pi_backup.sh && sudo ls -la /var/backups/pihole
    sudo /usr/local/bin/pi_report.sh
    sudo systemctl start pi-health.service
    systemctl status pi-health.service --no-pager

    Expect three timers with their next run times, one backup zip, the monthly report on your phone within a minute, and status=0/SUCCESS for the health check. That status only says the check ran; it exits cleanly whatever it found. A healthy Pi sends no health alert, so the report is your proof that notifications reach the phone. The report runs apt-get update and Pi-hole’s update check; it installs nothing.

    4. Optional: a fallback for the Pi’s own lookups

    This gives the Pi itself a second DNS server, 1.1.1.1, after Pi-hole. The router still hands out only the Pi, so the house is unchanged. It applies to Raspberry Pi OS Bookworm, where NetworkManager writes /etc/resolv.conf; check that first:

    grep 'Generated by NetworkManager' /etc/resolv.conf

    If that prints nothing, skip this section. Otherwise, save this as pi_nm_dns.conf in your home folder:

    # /etc/NetworkManager/conf.d/90-pi-dns.conf
    # The Pi's OWN lookups (apt, Tailscale, alerts) use Pi-hole first, then 1.1.1.1 if
    # Pi-hole is not answering. Affects only the Pi itself, not the house (the router still
    # hands out the Pi as the only DNS server). Undo: move this file away and run
    #   nmcli general reload
    [global-dns-domain-*]
    servers=127.0.0.1,1.1.1.1

    A DNS change over SSH can cut you off, so arm an automatic undo first, then apply it:

    sudo systemd-run --unit=pi-dns-undo --on-active=10min /bin/sh -c 'mv /etc/NetworkManager/conf.d/90-pi-dns.conf /root/ && nmcli general reload'
    sudo install -m 644 ~/pi_nm_dns.conf /etc/NetworkManager/conf.d/90-pi-dns.conf
    sudo nmcli general reload
    grep nameserver /etc/resolv.conf

    The last line should show 127.0.0.1 and then 1.1.1.1. If your SSH session still works and that is what you see, keep it by cancelling the undo:

    sudo systemctl stop pi-dns-undo.timer

    If anything looks wrong, do nothing: ten minutes later the file is moved to /root and the old settings return.

  • A parse error, a stalled upgrade, and fifteen years of silence

    A parse error, a stalled upgrade, and fifteen years of silence

    I knew this site was broken. I did not know for how long, or why, and for years I did not look. It sat at techblog.viveksanghi.com returning nothing, and every year that passed made it a slightly larger thing to open.

    When I finally opened it, the server turned out to have been keeping a precise record of what happened.

    I did the work over one evening with Claude, which matters to how this reads. I made the decisions and ran every command on my own server; the diagnosis, the scripts and several confident wrong turns came from the model. The wrong turns are in here too, because they were the useful part. Tech is a hobby for me. Law is what earns my living, and a fifteen-year-old broken WordPress had long since stopped being a thing I could justify an evening on. Having something that would grind through log files and SQL dumps without getting bored changed that arithmetic.

    What the server was saying

    The first question was whether anything was alive at all. The domain resolved to my host’s IP, same as my other sites, so DNS was fine. HTTPS failed on a certificate error. Over plain HTTP I got a 301 to the www hostname, then a 500 Internal Server Error with an empty response body.

    An empty 500 is a particular kind of unhelpful. No error on the page, no stack trace, nothing to search for. It means PHP died before producing output, with display_errors off, which on a production host it should be.

    The useful clue came from the access log rather than the error log:

    2026-09-02 21:24:28   200   /favicon.ico

    A 200. Static files were being served. That one line rules out most of what an empty 500 can mean. Apache was healthy, the virtual host was configured, the document root pointed at the right folder. Only PHP was dying.

    Which meant anything on the site that was not PHP could still be read. So we asked for the file every WordPress install ships and nobody ever deletes:

    curl http://techblog.viveksanghi.com/readme.html
    Version 3.1.2
    Semantic Personal Publishing Platform

    WordPress 3.1.2, released April 2011.

    The one-line cause

    The error log had been recording the same entry for years:

    [techblog.viveksanghi.com] [warn] mod_fcgid: stderr: PHP Parse error:
    syntax error, unexpected token "new" in
    /home/<user>/techblog.viveksanghi.com/wp-settings.php on line 219

    Line 219 of WordPress 3.1.2 reads:

    $wp_the_query =& new WP_Query();

    That =& is assignment by reference to a newly created object. It was correct in PHP 4, where objects were copied on assignment and the reference avoided the copy. PHP 5 made objects handle-based and the construction became pointless. It was deprecated in PHP 5.3 and removed in PHP 7.0.

    Removed, not deprecated. In PHP 7 and later this is not a warning or a runtime error. It is a parse error. PHP refuses to compile the file, so nothing in it executes, no error handler runs, no output is produced, and Apache has nothing to return but a bare 500.

    The site did not break from anything I did. It broke when my host moved past PHP 5, and it has been serving 500s to search engines and bots ever since.

    Could it be patched? The construction appears 252 times across WordPress core. PHP stops at the first one, but fixing that line only exposes the next. This is not a bug you repair. It is a language incompatibility, and the only answer is a newer WordPress.

    The timestamp in the root directory

    Sitting in the web root was a file called .maintenance, containing one line:

    <?php $upgrading = 1309848013; ?>

    WordPress writes that file when it begins a core update and deletes it when the update finishes. This one was never deleted.

    That Unix timestamp is 05/07/2011, 06:40 UTC.

    WordPress 3.2 was released on 04/07/2011. Alongside .maintenance were two directories in wp-content called wordpress-3.tmp and wordpress-31.tmp, the staging folders the updater uses while unpacking.

    So: the day after 3.2 came out, I clicked update. It stalled. It left the lock file, the temp directories, and a site still running 3.1.2.

    The lock file did no harm. WordPress ignores a .maintenance older than ten minutes, a sensible piece of defensive design and the reason the site kept serving afterwards. But it dates the incident to the minute.

    What the logs cannot tell you is what the site looked like when it stopped.

    It was running Grid Focus, a theme I had modified by hand over several years until not much of the original remained, with a stack of plugins I had chosen one at a time. The update took it down. I troubleshot for a while. Then life happened, and I lost interest the way you do when a thing stops being fun and starts being a chore.

    So I let it sit. Somewhere between 2020 and 2022 I paid a freelancer on Fiverr to bring it back, and for a while it worked. That did not last either.

    Both theme folders were still on the server when I finally went looking. grid_focus_public and gridfocus-v1.5.1b, sitting among fifty other themes I had collected and forgotten, exactly where I left them in 2011.

    Five years of nobody noticing

    The site did not go down in 2011. It went stale in 2011 and died some years later when PHP moved on. The first half is provable.

    An old wp-dbmanager install had been taking weekly database backups and leaving them in wp-content. There were 134 of them, 2.7 GB in total, running from 29/05/2011 to 31/07/2016.

    Comparing the oldest against the newest, by table:

    techblog_..._20110612.sql   posts: 274,916 bytes   comments: 370,174 bytes
    techblog_..._20160731.sql   posts: 274,916 bytes   comments: 370,174 bytes

    Byte for byte identical. Not a single post or comment changed between June 2011 and July 2016. The blog stopped in 2011 and the backups kept copying the same corpse every Sunday until they stopped too.

    But the dumps grew from 1.4 MB to 37 MB over those years. Something was expanding. Breaking the 2016 file down by table:

    12,549,505  wp_usermeta
       370,174  wp_comments
       342,650  wp_options
       274,916  wp_posts
        79,785  wp_postmeta

    Twelve and a half megabytes of user metadata against 275 KB of actual writing, reaching about 35 MB by the final backups. Open registration on an unpatched WordPress 3.1.2, and five years of bots signing up. The comments stayed clean, which I put down to Akismet and the captcha plugin, though I cannot prove that from the data. Nothing at all was guarding the registration form.

    Ninety per cent of my database was junk accounts.

    Deciding not to repair

    Reviving the 3.1.2 install was never really available. There is no supported upgrade path across fifteen years, and the parse error fires before WordPress prints a byte, so I could not reach an admin screen to start one.

    Rebuilding felt right for a less technical reason. The install carried 44 plugins and 51 themes. Among the plugins were disable-wordpress-core-update and disable-wordpress-plugin-updates, which explains a good deal about why it was still on 3.1.2. Copies of wordpress-28.zip through wordpress-284.zip sat in wp-content, publicly readable. There was a forum directory, empty, and two bbPress integration plugins pointing at it.

    A WordPress 3.1.2 install had been exposed to the open internet for roughly eight years before PHP killed it, and that version has a long published list of vulnerabilities. There is an irony worth sitting with: the parse error that took the site down has probably been protecting it since about 2019.

    So: current WordPress, content carried across, nothing else.

    Getting the content out

    The live database was reachable but not trustworthy, and I had 134 dumps provably unchanged since 2011. We took the last one and parsed it directly rather than restoring it anywhere.

    Two things came out of that which looking at the site would never have shown.

    The comments were duplicated. The table held 840. After normalising whitespace and stripping tags, only 606 were distinct. 234 were exact duplicates of another comment on the same post by the same author, each pair differing only in whether the
    tags had survived:

    id=7    2006-09-06 16:54   'Thanks for viewing my Blog. Well... I must say...'
    id=505  2006-09-06 11:24   'Thanks for viewing my Blog. Well... I must say...'

    The second copies sit in a contiguous block of IDs above 500. The database name pointed to Blogger, and the install had a blogger-blogspot-redirect plugin. A Blogger import run twice in 2006, once preserving HTML and once stripping it. Twenty years, and I never noticed, because on the page a duplicate comment just looks like somebody posting twice.

    The spam was not where anyone expected. Given the state of the usermeta table, the assumption was that comments would be full of pharma and casino links. A pattern search for the usual vocabulary returned zero matches. The volume by year decays the way real traffic does, 571 in 2006, 208 in 2007, then single and double digits as the blog went quiet, rather than flooding the way a farmed table does.

    The first attempt to find spam scored comments by link density. On a blog about Blogger and WordPress hacks that is a terrible signal, and it flagged 43 comments, most of them my own replies containing four or five links to code examples. Claude had produced that heuristic, run it, looked at the output and thrown it away unprompted, which was the right call and not one I would have caught if it had not shown me the list.

    The second pass went by author name and destination domain and found the real thing: thirteen keyword-anchor link drops, the kind where the author name is the product. “Mens Suit” linking to a suit retailer. “Website Design Atlanta”, three times. “beats for sale”. “laptop battery”. Short, on-topic enough, easy to approve by accident in 2010.

    That left 593 comments, all genuine, threading intact.

    There was also a post dated 26/12/2020 in a database dumped in 2016. A draft whose post_date carried a mistyped year, its post_modified correctly reading 27/12/2010. It had been sitting ten years in the future for a decade.

    What the rehearsal caught

    Rather than trust the import, we rehearsed it: MariaDB and WP-CLI in a throwaway container, the same WordPress version, a replica of the uploads folder, the real import file.

    Every expected number came back right except one. Attachments came out as zero instead of eighteen.

    The WordPress importer does not simply create attachment records. For each attachment it downloads the file from the URL in wp:attachment_url. In the container that URL was unreachable, so every attachment failed silently.

    On a real server it is worse than a clean failure. The URL points at the site being restored, over HTTPS, at a moment when the certificate has not been issued. And if the download does succeed, it writes a second copy of every file beside the ones already sitting in wp-content/uploads.

    The fix is to tell it not to:

    wp import export.xml --authors=create --skip=attachment

    and then register the files already on disk, in place:

    find wp-content/uploads -type f \( -iname '*.jpg' -o -iname '*.gif' \) \
      | grep -vE -- '-[0-9]+x[0-9]+\.[A-Za-z]+$' \
      | while read -r f; do wp media import "$f" --skip-copy; done

    The grep -v matters. Of 56 files in the uploads folder, 36 were WordPress’s own generated thumbnails. Without that filter every -150x150 crop becomes its own media library entry.

    Nobody would have found this by reading the script. It appeared only by running the whole thing end to end against a real database.

    Four ways the deploy script was wrong

    This is the part I would not have predicted before the evening started. The script that rebuilt the site was written for me to paste into an SSH session, and it had to be fixed four times before it ran clean. Every failure was caught by the script’s own preflight, before anything on my server was touched.

    getent does not exist on my host’s shell. The DNS check used it. The script would have aborted in preflight with a confusing error. Replaced with a PHP lookup, since PHP is guaranteed present there.

    pipefail and head do not mix. The script ran wp --info | head -3. head closes the pipe after three lines, wp gets SIGPIPE and exits 141, and set -o pipefail with set -e turns that into a silent abort. The three lines of output on my screen were the last thing the script printed before killing itself, and the failure looked like nothing at all.

    A $ in a password. My admin password was randomly generated and contained a dollar sign. Inside double quotes bash reads a $ followed by a digit or a name as a parameter; this one did not exist, and set -u correctly aborted. The config block now uses single quotes.

    --raw wrote an undefined constant. This one actually reached my server. The script ran wp config set WP_AUTO_UPDATE_CORE minor --raw, which writes define('WP_AUTO_UPDATE_CORE', minor); without quotes. In PHP 8 an undefined constant is a fatal error, so WordPress could not load at all, and the script reported it as “cannot reach the database” — which was wrong and sent me looking in the wrong place.

    There was a fifth, structural, caught before I ran anything: the original script tested the database connection after renaming my site directory. If the database had been unreachable, it would have moved my entire site aside and then died. That ordering was reversed so every destructive step sits behind a check that has already passed.

    I record these because the honest version of “an AI helped me fix my site” includes the four times it handed me something broken. What made it work was not that the output was right first time. It was that each failure was cheap, legible, and caught before it cost anything.

    The redirect loop I caused myself

    With WordPress installed and content imported, the site returned a redirect loop. techblog.viveksanghi.com redirected to www.techblog.viveksanghi.com, which redirected straight back, forever.

    We assumed the host was misconfigured. I opened a support ticket saying so. One command showed we were half wrong:

    curl -sI http://techblog.viveksanghi.com/readme.html      → 301
    curl -sI http://www.techblog.viveksanghi.com/readme.html  → 200 OK

    A static file that exists on disk gets redirected at the bare hostname and served at www. That first redirect happens above .htaccess, in the host’s virtual host configuration, and nothing on my side could override it. That half was the host’s, and they removed it inside a couple of hours when asked properly.

    The second redirect was mine. Static files at www served fine and only WordPress-handled paths bounced. That is redirect_canonical doing its job, because siteurl and home were set to the bare hostname while the server was serving www. Each half behaved correctly. Together they were an infinite loop.

    Testing a static file rather than the homepage is what separated them. On the homepage both redirects are in play and the trace tells you nothing about which layer owns which. I cancelled the first ticket and filed a more accurate one.

    What I would tell someone with a site in this state

    Test a static file first. Whether readme.html serves tells you in one request whether the web server is broken or only PHP is. Almost everything that followed came out of that one 200.

    The error log is the whole answer, and it is not in the panel. The hosting control panel showed access logs and traffic graphs for days. The actual parse error, repeating identically for years, was in a file on disk.

    Check whether your content changed before you value your backups. 134 weekly backups sound like excellent hygiene. Comparing the first against the last showed 134 copies of the same 2011 content, with only the spam growing. Backup count measures nothing.

    Rehearse the restore. A throwaway database and a full dry run took under an hour and caught a defect that would have cost the entire media library, silently, with a success message.

    Suspect your own configuration before your host’s. I was three quarters of the way to blaming my host for a redirect loop I had created myself.

    If you are working with a model, make it show you its output, not just its conclusions. Every one of the four script defects and the bad spam heuristic surfaced because something got printed and looked wrong. None of them surfaced from reading the code.

    The site is back. Seventy-five posts, 17/04/2006 to 25/05/2011, and 593 comments, on WordPress 7.1 with a clean database and no plugins carried across.

    Sixty-eight images in the older posts still point at photos1.blogger.com and the bp1 to bp3 hosts, which Google retired years ago. Those have been broken far longer than the site was, and there is nothing left to restore them from. I am inclined to leave them, with a note. A blog that ran from 2006 should be allowed to show its age somewhere.