← Back to dashboard
sandboxtoolingfreshReader view (for NotebookLM)

WSL Ubuntu Sandbox Guide

What is a WSL sandbox?

The real model

A hygiene sandbox, not a security one, and Microsoft now says so in writing.

WSL's security.md: WSL 'is not a security sandbox for running untrusted code', a distro 'is not a security boundary from the Windows host or from other distributions running for the same user', and settings like [interop] enabled=false and [automount] enabled=false 'do not turn a distribution into a sandbox'. The architecture explains it. Distros share one utility VM's kernel, network namespace and /mnt/wsl tmpfs, and only get their own PID, mount, user and cgroup namespaces (isolateDistroCgroup, default true). WSL deliberately bridges the Hyper-V wall with DrvFs, interop and localhost relays. .wslconfig is VM-global, and networkingMode now reads none | nat | mirrored | consomme (the old virtioproxy). So the distro is for clean, reproducible repros and toolchain experiments. Single processes drop to docker run --rm --network none, or wslc run --network none, now built into WSL (GA in 3.0.1, needs 2.9.3+, configured by its own settings.yaml rather than .wslconfig). Anything you actually distrust goes to a separately managed VM: a Docker Sandboxes microVM (winget Docker.sbx, Windows Hypervisor Platform, Locked Down network preset), Windows Sandbox on Pro editions, or a disposable cloud VM. On the Windows 11 Home dev box, sbx or the cloud are the realistic options.

Seven moves that make a sandbox

Four wsl.exe verbs for the hygiene tier, then the step down to a container and the step up to a real VM.

Text
███████╗ █████╗ ███╗   ██╗██████╗ ██████╗  ██████╗ ██╗  ██╗
██╔════╝██╔══██╗████╗  ██║██╔══██╗██╔══██╗██╔═══██╗╚██╗██╔╝
███████╗███████║██╔██╗ ██║██║  ██║██████╔╝██║   ██║ ╚███╔╝
╚════██║██╔══██║██║╚██╗██║██║  ██║██╔══██╗██║   ██║ ██╔██╗
███████║██║  ██║██║ ╚████║██████╔╝██████╔╝╚██████╔╝██╔╝ ██╗
╚══════╝╚═╝  ╚═╝╚═╝  ╚═══╝╚═════╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═╝

WSL Ubuntu Sandbox Guide

Focus: Standing up a disposable Ubuntu on Windows for experiments: spin-up, snapshot, blast-radius reduction, and a one-command nuke, so a risky install or a customer repro never lands in your real dev distro. It also covers when a WSL distro is the wrong tool and which separately managed VM to use instead.

Not this guide: cloud code-execution sandboxes for AI agents (Vercel Sandbox, E2B, Daytona, Cloudflare Sandbox, Anthropic's code execution tool). Those are hosted services with SDKs; this folder is about local, on-your-laptop isolation on Windows.

Overview

The wsl/ guide covers WSL as your primary dev environment. This one covers the opposite posture: a distro you expect to break. The core workflow is four verbs on the same wsl.exe binary you already have. No extra tooling, no VM images to download.

VerbCommandCost
Spin upwsl --install Ubuntu-26.04 --name lab~1 min, one download
Snapshotwsl --export lab lab-clean.tar.gz --format tar.gzseconds to minutes, one file
Restorewsl --import lab-2 D:\wsl\lab-2 lab-clean.tar.gzseconds
Nukewsl --unregister labinstant, unrecoverable

Read this before you trust it with anything

WSL's own security model document (in the microsoft/WSL repo, doc/docs/technical-documentation/security.md) is blunt, and it overrides any looser framing you may have read elsewhere, including earlier versions of this guide:

WSL provides a Linux environment that is deeply integrated with Windows. It is not a security sandbox for running untrusted code.

Code running in WSL should be treated as having the same trust level as code running under the Windows account that launched it. WSL distributions provide functional process and file system separation, but a distribution is not a security boundary from the Windows host or from other distributions running for the same user.

And on the hardening switches this guide recommends:

Unless a setting is explicitly documented as a security control, do not use it as a containment boundary. [...] These settings change the available integration features, but they do not turn a distribution into a sandbox or isolate it from Windows resources available to the user.

The architecture explains why. All WSL 2 distros for a user run inside one shared utility VM. Per Microsoft Learn, distros "share the same network namespace, device tree (other than /dev/pts), CPU/Kernel/Memory/Swap, /init binary, but have their own PID namespace, Mount namespace, User namespace, Cgroup namespace, and init process." The Hyper-V boundary between that VM and Windows is real. But WSL deliberately punches integration holes through it (DrvFs/Plan9 file sharing, interop, localhost relays) on your behalf, so you can't rely on the VM wall as containment.

What a WSL sandbox is good for: keeping your dev distro clean, making experiments reproducible from a known base, and containing accidents (a bad apt pin, a curl | bash that rewrites your shell profile, a toolchain that fights your real one).

What it is not for: code you believe is hostile. That needs a separately managed VM (see the tier table).

Which tier do you actually need?

TierWhat you getReset costReach for it when
Second WSL distroOwn ext4 VHDX plus mount/PID/user/cgroup namespaces. Not a security boundary.wsl --unregister, instantA whole toolchain, a repro that needs systemd, an install script from a source you trust but don't want on your dev distro
Snapshot + importThe above, plus a known-good starting pointRe-import a tarball, under a minuteYou need to run the same experiment five times from a clean base
Container (docker run or wslc run)Own network namespace (--network none) and per-container cgroup capsAutomatic on --rmOne process, one command, no persistent state. Microsoft: a container "does not make WSL a security boundary from the Windows host."
Docker Sandboxes (sbx)A microVM per sandbox with its own Docker daemon, filesystem and network, plus deny-by-default network presetsDelete the sandboxRunning an AI coding agent or an unfamiliar install script you actually distrust, on any Windows 11 edition with Windows Hypervisor Platform
Windows Sandbox (wsb)Disposable Windows VM with a separate kernel. Networking can be disabled in a .wsb fileClose the windowDetonating a Windows binary or attachment. Pro/Enterprise/Education only, not on Home
Full Hyper-V VM or disposable cloud VMSeparate kernel, separate network stack, checkpointsRestore a checkpoint or destroy the VMReal malware analysis, kernel modules, anything that must not share your Windows identity. Hyper-V Manager also needs Pro or higher; on Home, use a cloud VM

Official Documentation

Versions verified 2026-10-20

ComponentVersionSource
WSL, latest stable3.0.3 (2026-10-09). 3.0.1 (2026-09-29) made WSL containers GAgithub.com/microsoft/WSL/releases
WSL, latest pre-release3.0.4 (2026-10-20)same
WSL 2.7 servicing branch2.7.14 (2026-09-11)same
WSL kernel shipped in 3.0.36.18.54.13.0.3 release notes
Docker Engine29.9.1 (2026-10-14)github.com/moby/moby/releases
Docker Sandboxes CLI (Docker.sbx on winget)0.48.0winget show Docker.sbx
ubuntu Docker image tags26.04, 24.04, 22.04, latestDocker Hub

Run wsl --version first. The flags below were read from a local wsl --help (2.6.3). A much older inbox WSL may not have --manage, --install --name, or --export --format, and WSL containers need 2.9.3 or later. wsl --update gets you current.


Quickstart: a throwaway Ubuntu in 60 seconds

Bash
# Stand up a SECOND Ubuntu named "lab". --name is what makes a second
# copy of an already-installed distro possible.
wsl.exe --install Ubuntu-26.04 --name lab --no-launch

# Enter it
wsl.exe -d lab

# ...break things...

# Nuke it. Instant. Unrecoverable. That's the point.
wsl.exe --unregister lab

From PowerShell, drop the .exe. Everything below uses wsl (PowerShell form) except where a Linux-side command is being run.

Confirm what's installed and which VM version each distro is on:

Bash
wsl.exe --list --verbose
wsl.exe --version          # verify your WSL build supports the flags below
wsl.exe --list --online    # real, current distro names for --install

As of 2026-10-20, --list --online offers Ubuntu (the moving "latest" entry), Ubuntu-26.04, Ubuntu-24.04, Ubuntu-22.04, Debian, kali-linux, archlinux, FedoraLinux-44, FedoraLinux-43, openSUSE-Tumbleweed, openSUSE-Leap-16.0, RLCPlus-9/RLCPlus-10 (Rocky Linux Plus), plus the AlmaLinux, SUSE Linux Enterprise, Oracle Linux and eLxr families. Use the NAME column verbatim. Pin a versioned name (Ubuntu-26.04) in scripts; Ubuntu moves.

Placing and sizing the sandbox

Put the sandbox VHDX somewhere you don't mind filling up, and cap it:

PowerShell
wsl --install Ubuntu-26.04 `
  --name lab `
  --location D:\wsl\lab `
  --vhd-size 40GB `
  --no-launch
Install flagEffect
--name <Name>Registers under a custom name, which is how you run N copies of one distro
--location <Path>Where the ext4.vhdx lives (default is [general] distributionInstallPath, itself defaulting to %LocalAppData%\wsl)
--vhd-size <Size>Caps the virtual disk (default defaultVhdSize is 1 TB)
--no-launch, -nRegister without launching, so you can write wsl.conf before first boot
--fixed-vhdFixed-size rather than dynamically expanding disk
--from-file <Path>Install from a local distro file instead of the store
--web-downloadDownload from the internet instead of the Microsoft Store
--version <1|2>Force WSL 1 or WSL 2 for this distro

Snapshot and restore

This is the part that turns a second distro into a sandbox. Get the environment to a known-good state, export it, and from then on every experiment starts from that file.

Take the golden snapshot

PowerShell
# Terminate first so the filesystem is quiescent
wsl --terminate lab

# tar is the portable format; tar.gz / tar.xz trade CPU for size
wsl --export lab D:\wsl\snapshots\lab-clean.tar.gz --format tar.gz

--format accepts tar, tar.gz, tar.xz, and vhd. Microsoft Learn's basic-commands page still documents only the older --vhd switch on export. The binary accepts both, and --format vhd is the current spelling. A .vhdx export restores fastest (no untar) but is far larger and WSL 2 only.

<FileName> can be - for stdout (and - for stdin on import), so an export can be streamed into another tool. Do this from cmd or a POSIX shell, not PowerShell, whose object pipeline mangles binary streams:

Bash
# Git Bash / WSL: stream a snapshot straight to a compressor
export WSL_UTF8=1
wsl.exe --export lab - | zstd -T0 -19 -o /d/wsl/snapshots/lab-clean.tar.zst

Restore into a fresh distro

PowerShell
wsl --import lab-2 D:\wsl\lab-2 D:\wsl\snapshots\lab-clean.tar.gz --version 2
wsl -d lab-2
Import flagEffect
--version <1|2>WSL version for the new distro
--vhdThe source file is a .vhdx, not a tar. WSL copies it to <InstallLocation>

For a .vhdx you want to attach without copying (fast, but the file becomes the live disk):

PowerShell
wsl --import-in-place lab-3 D:\wsl\images\lab.vhdx

The VHD must be formatted ext4.

The reset loop

PowerShell
# One experiment, start to finish
wsl --unregister lab
wsl --import lab D:\wsl\lab D:\wsl\snapshots\lab-clean.tar.gz --version 2
wsl -d lab -- bash -lc './experiment.sh'

Because --unregister deletes the root filesystem outright, this loop takes a few seconds. Treat lab-clean.tar.gz as immutable and never export over it from a dirty distro. A full script is in examples/reset-lab.ps1.

Post-import housekeeping

An imported distro has no launcher executable, which breaks the usual ubuntu config --default-user trick. Use wsl --manage instead:

PowerShell
wsl --manage lab --set-default-user amani     # imported distros boot as root otherwise
wsl --manage lab --set-sparse true            # auto-reclaim freed disk space
wsl --manage lab --resize 60GB                # grow (or shrink) the VHDX
wsl --manage lab --move E:\wsl\lab            # relocate the distro's disk

Or set it inside the distro before you snapshot, in /etc/wsl.conf:

INI
[user]
default=amani

Reducing the blast radius

A fresh distro automounts your Windows drives and can launch Windows binaries as you. Turn that off in /etc/wsl.conf before you take the golden snapshot. Per the security model quoted above, this reduces accident surface; it is not containment. It stops a sloppy script from writing to /mnt/c/Users/you. It does not stop code that is trying to get out.

Bash
# Inside the sandbox distro
sudo tee /etc/wsl.conf >/dev/null <<'EOF'
# Do not mount C:\ (and friends) into the sandbox at all.
[automount]
enabled = false
mountFsTab = false

# Do not let Linux processes launch Windows binaries, and keep the
# Windows PATH out of $PATH.
[interop]
enabled = false
appendWindowsPath = false

[network]
hostname = lab
generateResolvConf = true

[user]
default = amani

[boot]
systemd = true
EOF

Then, from Windows:

PowerShell
wsl --terminate lab   # settings only apply after the distro fully stops

The same file is in examples/wsl.conf. What each switch buys you:

SettingWithout itWith it
[automount] enabled=false/mnt/c exposes your entire Windows profile (SSH keys, .env.local, browser profiles), writable as your Windows userDrives aren't mounted automatically. They can still be mounted manually, which is why this is hygiene, not a wall
[interop] enabled=falseA script can run powershell.exe, explorer.exe, or any Windows binary as youThe normal Windows-launch workflow is disabled
[interop] appendWindowsPath=falseWindows PATH entries leak into $PATH, so a typo can silently invoke a Windows toolClean Linux-only PATH
[boot] systemd=trueNo service manager, so many repros won't reproduceReal systemctl, matching production

Microsoft's enterprise guidance explains why automount matters: when a Linux binary in WSL touches a Windows file, it does so with the permissions of the Windows user who ran wsl.exe. Root inside the sandbox is not Windows admin, but it is you on Windows, for every file you can reach.

What you still don't get

  • Not a security boundary. Straight from the security model: not from the Windows host, and not from your other distros. Launching WSL elevated vs. non-elevated doesn't create separate guest boundaries either, and resources an elevated session gave the VM can stay available for the VM's lifetime.
  • Shared kernel. Every distro runs on the one microsoft-standard-WSL2 kernel.
  • Shared network namespace. A listener in the sandbox collides with your dev distro's :3000, and the sandbox can reach services your dev distro serves on localhost.
  • Shared /mnt/wsl. A tmpfs visible from every running distro.
  • .wslconfig is VM-global. There's no per-distro memory or CPU cap. isolateDistroCgroup (default true, needs cgroup v2) gives each distro its own cgroup tree, but the memory and CPU limits you can set are still for the whole VM.
  • wsl --debug-shell opens a root shell in the utility VM itself. It's a diagnostic tool, and a reminder of where the shared layer sits.
  • Docker Desktop registers its own docker-desktop distro in the same VM.

For anything genuinely hostile, use a separately managed VM: sbx, Windows Sandbox, Hyper-V, or a disposable cloud box. Don't use a WSL distro.


Resource limits with .wslconfig

.wslconfig lives on the Windows side at %UserProfile%\.wslconfig and governs the whole WSL 2 VM. Its job here is to keep a runaway make -j$(nproc) in the sandbox from freezing Windows.

INI
# %UserProfile%\.wslconfig   -  applies to the VM shared by ALL WSL 2 distros
[wsl2]
memory=8GB              # default: 50% of host RAM
processors=4            # default: all logical processors
swap=4GB                # default: 25% of memory, rounded up to the nearest GB
swapFile=D:\\wsl\\swap.vhdx   # default: %Temp%\swap.vhdx
defaultVhdSize=64GB     # cap new distro disks (default 1 TB)
vmIdleTimeout=60000     # ms of idle before the VM shuts down (Windows 11)
nestedVirtualization=true
localhostForwarding=true

[general]
instanceIdleTimeout=15000          # ms a distro sits idle before it stops; -1 disables
distributionInstallPath=D:\\wsl    # default home for new distros

[experimental]
autoMemoryReclaim=gradual   # disabled | gradual | dropCache (default)
sparseVhd=true              # every new VHDX is sparse, so disk comes back on delete

Notes that will save you an hour:

  • Paths need escaped backslashes (D:\\wsl\\swap.vhdx). Sizes take GB/MB suffixes; bare numbers are bytes.
  • Nothing applies until the VM restarts. Run wsl --shutdown; a --terminate of one distro isn't enough. Wait about 8 seconds (Microsoft's "8 second rule") before relaunching.
  • A malformed file doesn't stop WSL from booting. Per Microsoft Learn, it launches without your settings applied. (Separately, since 2.9.13 WSL keeps parsing a Linux-side config such as wsl.conf past an invalid line instead of stopping, and warns on an escaped CR.) Verify with free -h and nproc inside a distro after the shutdown.
  • .wslconfig does not apply to WSL containers (wslc.exe). Those have their own settings.yaml (see below).
  • Windows 11 ships a WSL Settings app that edits this file. Microsoft recommends it over hand-editing.

Per-experiment limits

Since .wslconfig can't cap a single distro, cap the workload instead, with systemd-run inside the sandbox:

Bash
# Needs [boot] systemd=true in the sandbox's wsl.conf
sudo systemd-run --scope \
  -p MemoryMax=2G -p CPUQuota=200% -p TasksMax=512 \
  ./experiment.sh

(--user scopes work too, but only where systemd has delegated the memory and pids controllers to the user slice. sudo is the version that always applies.)

Or run the experiment in a container, which is the next section.


Networking isolation

WSL's network knobs are all in [wsl2], and all global:

INI
[wsl2]
networkingMode=mirrored   # nat (default) | mirrored | consomme | none   (bridged is deprecated)
firewall=true             # Windows Firewall + Hyper-V rules filter WSL traffic (default)
dnsTunneling=true         # DNS via virtualization rather than packets, VPN-friendly
autoProxy=true            # inherit the Windows HTTP proxy
  • networkingMode=none disconnects WSL networking entirely. That's a real air-gap, but for every distro at once. It works as a deliberate "offline experiment" mode: set it, wsl --shutdown, run the experiment, revert.
  • consomme is the mode formerly called virtioproxy (renamed in WSL 2.9.3). Since 2.3.25, if NAT fails WSL falls back to Consomme. bridged has been deprecated since 2.4.5.
  • firewall=true (Windows 11 22H2+) means your Windows Firewall rules already apply to WSL. Per-distro rules are possible via Hyper-V Firewall.
  • For per-sandbox network isolation that doesn't disturb your dev distro, don't fight .wslconfig. Use a container with --network none, or nftables inside the sandbox distro itself.

Containers: the lighter tier

When the experiment is one process rather than a whole environment, a container is faster, tighter, and self-cleaning. Keep the security model in mind: a container inside WSL "inherit[s] the security properties of [its] container runtime configuration and WSL." It gets its own network namespace and cgroup caps. It doesn't get a new trust boundary from Windows.

Docker

From inside your normal distro (or via Docker Desktop's WSL integration):

Bash
# Ephemeral, network-isolated Ubuntu shell. Gone the moment you exit.
docker run --rm -it --network none ubuntu:26.04 bash

A hardened version for running something you don't fully trust:

Bash
docker run --rm -it \
  --network none \
  --memory 2g --cpus 2 --pids-limit 512 \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  --read-only --tmpfs /tmp:rw,noexec,nosuid,size=256m \
  --user 1000:1000 \
  -v "$PWD/artifacts:/out:rw" \
  -w /out \
  ubuntu:26.04 bash
FlagWhy it's there
--rmContainer and its writable layer are removed on exit, so no cleanup discipline is required
--network noneLoopback-only network namespace. A second WSL distro can't give you this.
--memory / --cpus / --pids-limitReal cgroup caps, so a fork bomb hits the limit, not your laptop
--cap-drop ALL + --security-opt no-new-privilegesNo CAP_*, no setuid escalation
--read-only + --tmpfs /tmpImmutable root, plus scratch space that can't execute
--user 1000:1000Not root. Without user-namespace remapping, container root maps to root on the shared kernel
-v ...:/outOne narrow, explicit path for results to escape through

examples/vet-npm-offline.sh wraps this into a "download online, then install offline and watch" recipe for vetting an unfamiliar npm package.

WSL containers (wslc.exe): no Docker Desktop needed

WSL containers went generally available in WSL 3.0.1 (2026-09-29) and need WSL 2.9.3+. wslc.exe ships inside WSL. There's no separate engine to install, and the CLI deliberately mirrors Docker's:

PowerShell
wslc version
wslc run --rm -it ubuntu:26.04 bash
wslc run --rm --network none ubuntu:26.04 bash -c "id && ip addr"
wslc container list --all
wslc container prune
wslc image prune

What's documented (Microsoft Learn plus the 2.9.3 release notes):

  • Per-container limits --cpus, --memory and --ulimit, plus --shm-size and stop signals.
  • Network modes including --network none (exercised in the WSL repo's own E2E tests) and container:<name>.
  • Containers run in a per-user session VM. .wslconfig does not apply to it. You configure it in %LOCALAPPDATA%\wslc\settings.yaml, which you open with wslc settings:
YAML
session:
  cpuCount: 4              # default: all logical processors
  memorySize: 8GB          # default: 50% of Windows memory
  maxStorageSize: 100GB    # default: 1TB
  storagePath: D:\wslc     # default: %LOCALAPPDATA%
  defaultBindingAddress: 127.0.0.1   # where -p binds by default (keep it local)
  hostLoopback: none       # default host.wslc.internal; none stops containers resolving the host by name
  idleTimeout: 30          # seconds before an idle session VM stops

Session settings are read when the session starts. Run wslc system session terminate to apply changes. An invalid setting prints a warning with the file and line number and falls back to the default.

Use wslc when you want Docker-style throwaway containers on a machine without Docker Desktop. Don't treat it as a stronger boundary than Docker. Microsoft documents its sessions as process-isolated from each other, but the security model's container caveat still applies. Docker flags beyond those listed above (--cap-drop, --read-only, --user) weren't verified against wslc for this review, so check wslc run --help before you rely on them.


Stepping up: separately managed VMs for untrusted code

This is the tier the WSL security model actually tells you to use: "a separately managed virtual machine outside WSL with appropriately restricted access."

Docker Sandboxes (sbx)

Docker's agent sandbox. Each sandbox is a microVM with its own Docker daemon, filesystem and network. Docker Desktop and Docker Engine are not required.

PowerShell
# One-time: Windows 11, 64-bit Intel/AMD, Windows Hypervisor Platform (elevated)
Enable-WindowsOptionalFeature -Online -FeatureName HypervisorPlatform -All
winget install -h Docker.sbx          # per-user install, no admin

sbx run --name vet-lab claude         # or another agent from the agents list
sbx policy ls                         # show network rules
sbx policy allow network registry.npmjs.org

On first run you pick a network preset: Open (no restrictions), Balanced (default deny, with common dev sites allowed), or Locked Down (everything blocked unless you allow it). Use Locked Down for vetting, then allow exactly the registry you need. Central org policy (network, filesystem, MCP) is a separate paid Docker subscription. Local pricing and a GA/beta label weren't stated on the pages checked.

Windows Sandbox

A disposable Windows VM with its own kernel. It's not available on Windows Home. Networking is on by default, so turn it off in a .wsb file, and map folders read-only:

XML
<Configuration>
  <Networking>Disable</Networking>
  <ClipboardRedirection>Disable</ClipboardRedirection>
  <AudioInput>Disable</AudioInput>
  <ProtectedClient>Enable</ProtectedClient>
  <MappedFolders>
    <MappedFolder>
      <HostFolder>D:\quarantine</HostFolder>
      <SandboxFolder>C:\quarantine</SandboxFolder>
      <ReadOnly>true</ReadOnly>
    </MappedFolder>
  </MappedFolders>
</Configuration>

ProtectedClient runs the sandbox inside AppContainer isolation, which adds a layer at the cost of copy/paste. The same file is in examples/quarantine.wsb. On Windows 11 24H2+ there's also a CLI: wsb start --config "<Configuration><Networking>Disable</Networking></Configuration>" (Microsoft's CLI page writes the value as Disabled; the .wsb reference lists Disable). Only one instance runs at a time, and it always uses the host's own Windows build.

Hyper-V or a disposable cloud VM

For real malware analysis or kernel work, use a full VM with checkpoints. Hyper-V Manager needs Pro or higher. On Windows 11 Home (codeAmani's main dev box), the practical choices are sbx or a short-lived cloud VM you destroy afterwards.


The nuke-and-rebuild script

Keep this next to the golden snapshot. It's the whole workflow in one file. A commented copy is in examples/reset-lab.ps1.

PowerShell
# D:\wsl\reset-lab.ps1
param(
  # No default for $Name: --unregister has no undo, so the caller must say it out loud.
  [Parameter(Mandatory)][string]$Name,
  [string]$Root     = "D:\wsl\lab",
  [string]$Snapshot = "D:\wsl\snapshots\lab-clean.tar.gz"
)

$env:WSL_UTF8 = 1   # otherwise wsl.exe output is UTF-16 and every match fails

if (-not (Test-Path $Snapshot)) { throw "No snapshot at $Snapshot" }
if ($Name -match '^Ubuntu') { throw "Refusing to nuke an Ubuntu* distro; sandbox names should not start with Ubuntu" }

# Only tear down if it is actually registered.
if ((wsl --list --quiet) -contains $Name) {
  wsl --terminate  $Name
  wsl --unregister $Name
  if ($LASTEXITCODE -ne 0) { throw "unregister failed for $Name" }
}

New-Item -ItemType Directory -Force -Path $Root | Out-Null
wsl --import $Name $Root $Snapshot --version 2
if ($LASTEXITCODE -ne 0) { throw "import failed from $Snapshot" }

wsl --manage $Name --set-sparse true

Write-Host "Sandbox '$Name' rebuilt from $Snapshot"
wsl --list --verbose

And the one-way door, spelled out because it deserves it:

PowerShell
wsl --unregister lab

--unregister deletes the distro's root filesystem. There is no recycle bin, no undo, and no prompt. Type the distro name carefully: wsl --unregister Ubuntu and wsl --unregister lab are very close in muscle memory.


Scripting wsl.exe from agents and CI

wsl.exe emits UTF-16LE with no BOM by default, which turns into interleaved NUL bytes in any pipeline that assumes UTF-8 (the classic "why is my output U b u n t u"). Set WSL_UTF8 to 1. It's a plain setting, not a secret:

Bash
export WSL_UTF8=1
wsl.exe --list --verbose
PowerShell
$env:WSL_UTF8 = 1
wsl --list --verbose

Two more scripting notes:

  • From Git Bash / MSYS, Windows paths in wsl.exe arguments get path-mangled. Run export MSYS_NO_PATHCONV=1 first, or run those commands from PowerShell.
  • wsl.exe returns -1 (255) on failure with a Wsl/Service/... error code on stderr. Check the exit code; don't parse the message. The 3.0.3 release added logic to "reject commands with extra arguments" (the notes don't say whether that covers wsl.exe, wslc.exe, or both), so if a script that passed stray arguments starts failing after an update, check that first.
SettingValueWhere
WSL_UTF81Shell environment. Makes wsl.exe print UTF-8
MSYS_NO_PATHCONV1Git Bash only. Stops path mangling of Windows paths

codeAmani notes

A sandbox is where risky things go, not where secrets go.

  • Never seed a sandbox distro with real credentials. Hazina bindings, .env.local, ~/.ssh, ~/.aws, and cloud CLI tokens stay in the dev distro. With automount and interop off, they aren't casually reachable from the sandbox, but Microsoft is clear that this isn't a boundary. So the rule is "no secrets in the sandbox, ever", not "the sandbox can't see my secrets." If an experiment needs a credential, mint a scoped test key and revoke it when the distro is unregistered.
  • Untrusted code goes one tier up. Exploit PoCs, unknown binaries, and AI coding agents running with broad permissions on unfamiliar repos belong in an sbx microVM (Locked Down preset) or a disposable cloud VM, not in lab. Windows Sandbox and Hyper-V aren't options on the Windows 11 Home dev box.
  • Pairs with the security guide's isolated-lab requirement. Scanners, dependency-confusion checks, and gitleaks runs against third-party repos you don't suspect can live in lab, one snapshot-restore per run, so results are never contaminated by the previous one. Escalate to sbx the moment "don't suspect" turns into "not sure".
  • Customer-bug repros. Import the golden snapshot, install exactly the reported versions, reproduce, capture the diff, unregister. No "it works on my machine", because the machine was clean an hour ago.
  • Vetting a new dependency before it enters the catalog. libraries/ build-vs-buy calls often hinge on running an unfamiliar package's install script. Use examples/vet-npm-offline.sh (download online with scripts disabled, then install with the network off) and watch what it tries to do.
  • Supply-chain posture. The sandbox is where you observe. It doesn't replace the real controls: SLSA provenance, npm audit signatures, dependency review, and secret scanning still gate anything codeAmani ships (see supply-chain/CLAUDE_CODE_INTEGRATION.md).
  • Low-bandwidth reality for the Kenya-targeted builds. Snapshot-and-restore is the bandwidth win: one Ubuntu-26.04 download, then every rebuild is a local tarball. Export as tar.xz if a teammate on a metered connection has to pull the golden image, and keep --format tar for local speed. Testing a duka-order-bot or boda-dispatch webhook path against a throttled interface (tc qdisc) is easiest in a sandbox. Remember distros share one network namespace, so shape traffic inside a container or an nftables-scoped interface, not on the shared eth0.
  • Don't run production-adjacent work in a sandbox you plan to nuke. Anything worth keeping goes back to git before --unregister. The sandbox has no backup, by design.
  • Keep WSL current. WSL ships security fixes frequently (2.7.11 and 2.9.3 both carried CVE fixes). Run wsl --update before relying on the flags in this guide.
  • wsl/CLAUDE_CODE_INTEGRATION.md: WSL as your primary dev environment (filesystem performance, /mnt/c rules, Claude Code inside WSL, networking modes, systemd). Read that one first; this guide assumes it.
  • docker/CLAUDE_CODE_INTEGRATION.md: Docker in depth, for the container tier.
  • security/CLAUDE_CODE_INTEGRATION.md: the isolated-lab requirement this guide serves.
  • supply-chain/CLAUDE_CODE_INTEGRATION.md: SLSA provenance for anything that leaves the lab.