Skip to content

Latest commit

 

History

8 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

dns-guard

One PowerShell script that makes doomscrolling annoying enough to skip. No installers, no accounts, no telemetry — ~350 lines you can read before you run.

  • Blocks Instagram and TikTok system-wide via the hosts file — works in every browser and app on the machine
  • Blocks YouTube Shorts via browser URL policies (Chrome, Edge, Firefox) — youtube.com/shorts lands on a "blocked by your administrator" page
  • Optional DNS content filter, one config switch: adultCloudflare Family (1.1.1.3) blocks porn + malware and nothing else; or familyAdGuard Family strict parental mode (also blocks ads/trackers, forces SafeSearch and YouTube Restricted Mode)
  • Watchdog: a SYSTEM scheduled task re-applies the block every 15 minutes and at boot, in case "evening you" deletes it
  • Lockout recipe below: make undoing this genuinely inconvenient for future you

Requirements

  • Windows 11 (or Windows 10 — everything works except encrypted DNS/DoH, which is skipped automatically)
  • Admin rights for -Install / -Uninstall

Quick start

Simplest: download the repo as ZIP, unzip, right-click install.batRun as administrator.

Or from an elevated PowerShell (right-click Start → Terminal (Admin)):

git clone https://github.com/max1k1/dns-guard
cd dns-guard
powershell -ExecutionPolicy Bypass -File .\dns-guard.ps1 -Install

Check it worked:

powershell -ExecutionPolicy Bypass -File .\dns-guard.ps1 -Status

Instagram and TikTok should now fail to load in any browser (ERR_ADDRESS_INVALID or similar). YouTube, work sites, everything else — untouched.

Commands

Command Admin? What it does
-Install yes Writes the hosts block, sets AdGuard Family DNS (if enabled), registers the watchdog. Re-run it after editing the config.
-Status no Shows hosts block, per-adapter DNS, DoH registration, watchdog state, and a live resolution check.
-Uninstall yes Removes the hosts section and the watchdog, resets DNS to DHCP (only where dns-guard set it).
-Enforce Internal — what the watchdog task runs every 15 minutes.

Configuration

Open dns-guard.ps1, edit the CONFIG block at the top, run -Install again:

  • $DnsFilter = 'adult' — the DNS content filter. 'adult' (default) blocks porn and malware, nothing else. 'family' is the strict parental mode: additionally blocks ads/trackers (can break embeds and news-site widgets), forces SafeSearch and YouTube Restricted Mode — which among other things hides YouTube comments. 'off' leaves system DNS alone.
  • $BlockYouTubeShorts = $true — block youtube.com/shorts with browser policies (see below). Set to $false to leave YouTube completely alone.
  • $BlockedDomains — the hosts-file blocklist. Add or remove any hostnames you like (exact names, no wildcards — tiktok.com and www.tiktok.com are separate entries).

YouTube Shorts

DNS can't see URL paths — Shorts and normal videos share youtube.com, so a resolver-level block would kill all of YouTube. dns-guard blocks Shorts one layer up instead, with browser policies ($BlockYouTubeShorts, on by default):

  • Chrome + Edgeyoutube.com/shorts goes into the URLBlocklist policy: direct links, address-bar entry and page reloads land on "Blocked by your administrator". The policy lives in HKLM, so changing it needs admin rights, and the watchdog re-adds it every 15 minutes.
  • Firefox (if installed) — the same block via WebsiteFilter in distribution\policies.json.
  • Unhook force-install (Chrome + Edge) — registered via ExtensionInstallForcelist, so the extension cannot be removed or disabled without admin rights. Browsers only honor force-installs on managed machines (domain/Entra-joined or MDM-enrolled) and silently ignore them on regular home PCs — there, install Unhook manually (Chrome / Edge / Firefox) and tick "Hide all Shorts".

The honest gap: URL policies fire on real navigations, and YouTube is a single-page app — clicking a Shorts tile inside an already-open YouTube tab can still play it. That's exactly what Unhook covers: with the tiles and the Shorts tab hidden there's nothing to click, and the policy kills links, reloads and muscle-memory typing.

Heads-up on Unhook's defaults: a fresh install hides the entire home feed and related-videos sidebar, which looks like "YouTube is broken". Open the Unhook popup on any YouTube page, untick "Hide home feed" / "Hide related videos" if you want those back, and tick everything with Shorts in the name (the "Hide all Shorts" master toggle is the important one). Extension checkboxes are per-user by design — Chrome does not let policies or scripts edit another extension's settings.

Lock yourself out (recommended)

Everything dns-guard sets — hosts, DNS, browser policies, the watchdog — already takes admin rights to change. The real lock is: stop being admin. setup-lock.ps1 walks you through it in two deliberate steps.

# elevated PowerShell, step 1 — create the lock account:
powershell -ExecutionPolicy Bypass -File .\setup-lock.ps1

It generates a random 10-digit password (write it on paper — not a file, not your phone), creates a local admin account admin-lock, then makes you re-type the password from the paper to prove your copy is correct. A CLI-created account has no security questions — the one-minute password-reset backdoor of the Settings-app flow simply doesn't exist.

# step 2, the point of no return — demote yourself to Standard user:
powershell -ExecutionPolicy Bypass -File .\setup-lock.ps1 -Demote

It verifies the paper password one last time, adds you to docker-users if Docker Desktop is installed (dev life goes on), then removes your account from Administrators. Sign out and back in — from now on editing hosts, changing DNS, uninstalling dns-guard or installing software pops a UAC prompt asking for the admin-lock password.

Then the paper goes somewhere with real friction — a drawer at the office, a friend, your partner. Not your desk. The impulse lives three minutes; the paper should live twenty minutes away.

Notes:

  • Normal development (Node, git, IDEs) is unaffected by Standard-user life.
  • Lose the paper and there's no other admin → Windows-recovery land. Treat it like a physical key.
  • One thing stays user-editable after demotion: extension checkboxes (Unhook's included) — browsers keep extension settings per-user by design. The URL-policy layer stays locked.

New machine / a friend's machine

The whole thing is this folder. Grab the ZIP and right-click install.bat → Run as administrator — or fully from an elevated PowerShell:

irm https://raw.githubusercontent.com/max1k1/dns-guard/main/dns-guard.ps1 -OutFile dns-guard.ps1
powershell -ExecutionPolicy Bypass -File .\dns-guard.ps1 -Install

# optional, the lockout described above:
irm https://raw.githubusercontent.com/max1k1/dns-guard/main/setup-lock.ps1 -OutFile setup-lock.ps1
powershell -ExecutionPolicy Bypass -File .\setup-lock.ps1        # + later: -Demote

Two manual bits remain: Unhook's checkboxes (tick "Hide all Shorts", untick the feed-hiding defaults), and on non-managed home machines installing Unhook from the store yourself — force-install is only honored on managed (domain/Entra-joined) Windows.

How it works

  • Hosts file — each blocked domain gets 0.0.0.0 (IPv4) and :: (IPv6) entries between # >>> dns-guard >>> markers. The rest of the file is never touched.
  • DNS — the selected filter's servers (Cloudflare Family 1.1.1.3/1.0.0.3 or AdGuard Family 94.140.14.15/94.140.15.16, plus IPv6) are set on every physical adapter, Wi-Fi and Ethernet, so plugging in a cable doesn't bypass the filter. On Windows 11, DNS-over-HTTPS is enabled for these servers with UDP fallback allowed (the same servers answer either way, so filtering holds and connectivity never breaks). Switching providers or uninstalling cleans up the previous one.
  • Browser policiesyoutube.com/shorts is appended to Chrome's and Edge's URLBlocklist registry policies and Firefox's WebsiteFilter, without touching entries set by anything else; -Uninstall removes only dns-guard's own entries.
  • Watchdog — a scheduled task running as SYSTEM re-checks the hosts section, DNS and the Shorts policies every 15 minutes and at boot, and restores them if changed. The enforced copy of the script lives in C:\ProgramData\dns-guard, writable only by admins.

Honest limitations

  • This is friction, not a wall. Any admin can undo it in minutes — that's why the lockout section exists. The design goal is to outlast a three-minute impulse, not a determined attacker.
  • A VPN with its own DNS bypasses the family filter (the hosts block still applies).
  • A browser's built-in "Secure DNS" pointed at another provider bypasses the DNS filter, and in Firefox may also bypass the hosts block. Either turn it off or point it at your filter's DoH template (https://family.cloudflare-dns.com/dns-query for adult, https://family.adguard-dns.com/dns-query for family).
  • The Shorts policies cover Chrome, Edge and Firefox; other Chromium browsers (Brave, Opera, Vivaldi) use their own policy locations and aren't covered.
  • Phones are not covered. On Android/iOS, set Private DNS / encrypted DNS to family.adguard-dns.com.
  • Hosts entries are exact-match — an app hopping to a brand-new subdomain may slip through until you add it to the list.
  • If your antivirus guards the hosts file, approve the change when it asks.

Uninstall

# elevated PowerShell:
powershell -ExecutionPolicy Bypass -File .\dns-guard.ps1 -Uninstall

If you followed the lockout section, this is the moment that requires the paper. Working as intended.

Быстрый старт (по-русски)

  1. Скачай ZIP, распакуй.
  2. Правый клик по install.batЗапуск от имени администратора.
  3. Инста и тикток перестают открываться на всём компе. Проверка: двойной клик по status.bat.

DNS-фильтр по умолчанию — 'adult': режет только порно и малварь, больше ничего. Нужен строгий детский режим (плюс блок рекламы, SafeSearch и ютуб без комментариев) — открой скрипт, поставь $DnsFilter = 'family'; не нужен вовсе — 'off'. После правки снова запусти -Install. Свои домены добавляются в список $BlockedDomains там же.

Убрать всё: -Uninstall (нужны права админа). Shorts блокируются политикой браузера: прямые ссылки, адресная строка и перезагрузка страницы — сразу «Blocked by your administrator»; плитки в ленте дополнительно прячет расширение Unhook, галочка «Hide all Shorts». Внимание: свежий Unhook по умолчанию прячет ещё и всю главную ленту — если ютуб «опустел», сними в его попапе галочки «Hide home feed» и «Hide related videos».

Чтобы не снять блок самому в два часа ночи — замок: powershell -ExecutionPolicy Bypass -File .\setup-lock.ps1 сгенерирует случайный пароль (запиши на бумажку!), создаст учётку admin-lock и проверит бумажку; когда готов — тот же скрипт с -Demote переведёт тебя в обычные пользователи. Бумажку — подальше от дома.

License

MIT

About

Self-control blocker for Windows: hosts-level Instagram/TikTok block, optional AdGuard Family DNS, YouTube Shorts browser policies, SYSTEM watchdog

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages