tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Run tazel custom inside a MicroVM
- Commit
f200feb603d132e63498d9e7a333c974d79fab98- Author
- Leitwolf11 ·
- Parents
f433ebe1b308
Changes
.github/workflows/ci.yml | 50 +++ CHANGELOG.md | 3 + THIRD-PARTY-NOTICES.md | 14 + Tazel.slnx | 1 + docs/README.md | 1 + docs/architecture.md | 2 + docs/microvm.md | 66 ++++ microvm/build.cs | 230 +++++++++++++ microvm/kernel.config | 58 ++++ src/Progmasoft.Tazel.Guest/Agent.cs | 306 +++++++++++++++++ src/Progmasoft.Tazel.Guest/Libc.cs | 79 +++++ .../Progmasoft.Tazel.Guest.csproj | 23 ++ src/Progmasoft.Tazel.Guest/Program.cs | 40 +++ src/Progmasoft.Tazel.Guest/VsockStream.cs | 127 ++++++++ src/Progmasoft.Tazel/Cli/Commands.cs | 19 +- src/Progmasoft.Tazel/Cli/MoreCommands.cs | 61 ++++ src/Progmasoft.Tazel/MicroVm/MicroVmFiles.cs | 186 +++++++++++ src/Progmasoft.Tazel/MicroVm/Sandbox.cs | 362 +++++++++++++++++++++ src/Progmasoft.Tazel/Output/ErrorCodes.cs | 9 + src/Progmasoft.Tazel/Program.cs | 6 + src/Shared/MicroVmProtocol.cs | 234 +++++++++++++ tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs | 2 +- tests/Progmasoft.Tazel.Tests/MicroVmTests.cs | 165 ++++++++++ .../Progmasoft.Tazel.Tests.csproj | 1 + tests/Progmasoft.Tazel.Tests/TemporaryModule.cs | 3 +- 25 files changed, 2039 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6632540..2ec0e97 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -138,3 +138,53 @@ jobs: path: artifacts/reference/ if-no-files-found: error retention-days: 7 + + microvm: + name: MicroVM (ubuntu-26.04, KVM) + runs-on: ubuntu-26.04 + timeout-minutes: 45 + permissions: + contents: read # the checkout + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5 + with: + global-json-file: global.json + + # The runners have KVM; the device is opened to the runner's user, and virtiofsd and the kernel's build tools are + # installed from Ubuntu. + - name: Open KVM and install virtiofsd + shell: bash + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + sudo apt-get update + sudo apt-get install -y --no-install-recommends virtiofsd flex bison bc libelf-dev + ls -l /dev/kvm + + # The kernel's tree, built once per kernel.config and builder; the agent and the initramfs are built every time. + - name: Restore the kernel build + uses: actions/cache@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 + with: + path: ${{ runner.temp }}/microvm-work/linux-* + key: microvm-kernel-${{ hashFiles('microvm/kernel.config', 'microvm/build.cs') }} + + - name: Build the MicroVM image + shell: bash + run: dotnet run microvm/build.cs -- "$RUNNER_TEMP/microvm-work" "$RUNNER_TEMP/microvm-image" + + - name: Boot it and run commands inside + shell: bash + env: + TAZEL_MICROVM_IMAGE: ${{ runner.temp }}/microvm-image + TAZEL_REQUIRE_MICROVM: "1" + run: >- + dotnet test --solution Tazel.slnx -c Release + --filter-class 'Progmasoft.Tazel.Tests.MicroVmBootTests' + --filter-class 'Progmasoft.Tazel.Tests.MicroVmProtocolTests' + --filter-class 'Progmasoft.Tazel.Tests.MicroVmFilesTests' + --no-progress diff --git a/CHANGELOG.md b/CHANGELOG.md index 0dea928..a8fbfbb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,9 @@ The first version of Tazel, written in C# for .NET 10. `tazel vendor`, and `tazel portal-modules search` and `info`; `tazel help --long`. - Modules of Tazel Portal Modules as dependencies: each at the highest version asked for, checked by SHA-256, from `vendor/` first. +- The MicroVM: with `sandboxing-with-microvm`, `tazel custom` runs in a Linux guest under Cloud Hypervisor on KVM + that sees the module and the host's `/usr`, read-only, and nothing else; its agent `tazel-guest`, and + `microvm/build.cs`, which builds the guest image. - Plugins: `Progmasoft.Tazel.PluginApi`, the project SDK `Progmasoft.Tazel.PluginSdk` that packs a plugin with `dotnet pack`, the template `dotnet new tazel-plugin`, local plugins loaded each into its own load context, and build steps that plugins and `BUILD.csx` files declare. diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 5192a19..01422e4 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -15,3 +15,17 @@ Tazel ships with the libraries below. Their licenses are in [LICENSES/](LICENSES The libraries that only build and test Tazel (xUnit, CsCheck, Snapshooter, Coverlet, BenchmarkDotNet, SharpFuzz, DocFX) are not part of what is shipped. + +## The image of the MicroVM + +The guest image (`microvm/build.cs`) holds, besides the .NET runtime of `tazel-guest` (MIT, .NET Foundation and +Contributors): + +| Component | License | Source | +| --- | --- | --- | +| Linux 6.18.64 | GPL-2.0-only WITH Linux-syscall-note | https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.18.64.tar.xz | +| musl 1.2.6 (Alpine musl-1.2.6-r3) | MIT | https://musl.libc.org | +| libgcc and libstdc++ of GCC 15.2.0 (Alpine 15.2.0-r5) | GPL-3.0-or-later WITH GCC-exception-3.1 | https://gcc.gnu.org | + +Cloud Hypervisor (Apache-2.0 AND BSD-3-Clause) and virtiofsd (Apache-2.0 AND BSD-3-Clause) are not shipped: Tazel +fetches Cloud Hypervisor from its release and uses the host's virtiofsd. diff --git a/Tazel.slnx b/Tazel.slnx index bd7fab6..842b089 100644 --- a/Tazel.slnx +++ b/Tazel.slnx @@ -2,6 +2,7 @@ <Folder Name="/src/"> <Project Path="src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj" /> <Project Path="src/Progmasoft.Tazel/Progmasoft.Tazel.csproj" /> + <Project Path="src/Progmasoft.Tazel.Guest/Progmasoft.Tazel.Guest.csproj" /> <Project Path="src/Progmasoft.Tazel.PluginApi/Progmasoft.Tazel.PluginApi.csproj" /> <Project Path="src/Progmasoft.Tazel.PluginSdk/Progmasoft.Tazel.PluginSdk.csproj" /> <Project Path="src/Progmasoft.Tazel.PluginTemplates/Progmasoft.Tazel.PluginTemplates.csproj" /> diff --git a/docs/README.md b/docs/README.md index 80d40a6..c0b606c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,6 +7,7 @@ | --- | --- | | [Project files](project-files.md) | `MODULE.csx`, `BUILD.csx` and toolchains, with every setting | | [Plugins](plugins.md) | making, packing and loading plugins, and their build steps | +| [MicroVM](microvm.md) | the sandbox: what tazel custom runs in, what it needs, and building its image | | [Commands](commands.md) | the commands of `tazel`, their options, and `tazel_options.txt`, `tazel_custom.txt` and `tazel_envs.txt` | | [Architecture](architecture.md) | the projects of the solution and how a build runs | | [Development](development.md) | building, testing, fuzzing and benchmarking Tazel, and its CI | diff --git a/docs/architecture.md b/docs/architecture.md index f801f0a..216f0ba 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -12,6 +12,8 @@ | `src/Progmasoft.Tazel.PluginApi` | the API of plugins and their build steps (NuGet `Progmasoft.Tazel.PluginApi`) | | `src/Progmasoft.Tazel.PluginSdk` | the MSBuild project SDK of plugins and the task that packs them | | `src/Progmasoft.Tazel.PluginTemplates` | `dotnet new tazel-plugin` | +| `src/Progmasoft.Tazel.Guest` | `tazel-guest`, the first process of the MicroVM's Linux guest | +| `microvm/` | the guest kernel's options and `build.cs`, which builds the guest image | | `src/Shared` | the reproducible archive writer, compiled into tazel and the SDK task | | `tests/Progmasoft.Tazel.Tests` | xUnit tests, with CsCheck for properties and Snapshooter for snapshots | | `benchmarks/Progmasoft.Tazel.Benchmarks` | BenchmarkDotNet measurements of the readers | diff --git a/docs/microvm.md b/docs/microvm.md new file mode 100644 index 0000000..a2e9e58 --- /dev/null +++ b/docs/microvm.md @@ -0,0 +1,66 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> + +# The MicroVM + +`tazel_options.txt` asks for a sandbox: + +```text +sandboxing-with-microvm: true; +microvm-memory: 1024; # MiB, or "auto" (1024) +microvm-cpus: 2; # or "auto" (half the processors, 1 to 4) +``` + +Then `tazel custom` runs its commands inside a MicroVM: a Linux guest under +[Cloud Hypervisor](https://www.cloudhypervisor.org) on KVM. The guest sees the module (or the directory of the command +when it is in no module) at the same path, writable, and the host's `/usr`, read-only, so commands run with the tools +of the host; nothing else of the host is visible. Commands get `PATH`, `HOME=/root`, `TMPDIR=/tmp` and +`LANG=C.UTF-8`, and none of the host's environment. A shell step, `s("...")`, goes to the guest's `/bin/sh`. + +Builds, tests and plugins do not run in the MicroVM, so a sandbox asked for stops them; `microvm-network: true` is +refused, as the MicroVM has no network. + +## What it needs + +- x86_64 Linux with KVM: `/dev/kvm`, readable and writable by the user. +- virtiofsd, which shares the directories (`/usr/libexec/virtiofsd`, `/usr/lib/virtiofsd`, PATH, or `TAZEL_VIRTIOFSD`). +- Cloud Hypervisor v55.0: fetched once into `~/.cache/tazel/cloud-hypervisor` and checked against its SHA-256, or + `TAZEL_CLOUD_HYPERVISOR`. +- The image of the guest: fetched once from the release of this Tazel into `~/.cache/tazel/microvm`, or a directory + named by `TAZEL_MICROVM_IMAGE`. Every file is checked against the `SHA256SUMS` of the image before it boots. + +## How it works + +```text +tazel ──vsock (Cloud Hypervisor's Unix socket, CONNECT 1024)──▶ tazel-guest (PID 1 in the guest) + │ │ + ├─ cloud-hypervisor (a process of its own) ├─ mounts /proc, /sys, /dev, /tmp, /run + ├─ virtiofsd × 3 (the module, /usr read-only, /etc) ├─ mounts the shares (virtio-fs) + └─ waits for Ready, sends Run, prints Output, returns Exit └─ runs each command, streams its output +``` + +- The guest kernel is a long-term Linux of kernel.org on top of `tinyconfig` with `microvm/kernel.config`: virtio + (PCI, console, vsock, file system), PVH boot, no modules and no network device. +- The initramfs holds `tazel-guest` (`src/Progmasoft.Tazel.Guest`), published self-contained for linux-musl and + trimmed, beside musl's loader, and the libraries of Alpine it needs (musl, libgcc, libstdc++). The kernel starts the + loader as the first process, so the guest's `/lib` is free to be the host's `/usr/lib`. +- The agent reaches the C library through `[LibraryImport]`; it refuses a working directory outside what was shared + for writing. +- The messages are a kind byte, a little-endian length and a payload (`src/Shared/MicroVmProtocol.cs`, the same file + on both sides). +- Cloud Hypervisor and virtiofsd are processes of their own: when one of them dies, the command fails with E0504 and + the end of the guest's console; Tazel goes on. At the end Tazel asks the guest to power off, then stops what is left + and removes its runtime directory. + +## Building the image + +```text +dotnet run microvm/build.cs -- <work directory> <output directory> +TAZEL_MICROVM_IMAGE=<output directory> tazel custom <command> +``` + +It needs make, a C compiler, flex, bison and bc for the kernel. Every download (the kernel and the three Alpine +packages) is checked against the SHA-256 in `microvm/build.cs`, and the same inputs give the same bytes. + +The kernel is licensed under GPL-2.0, musl under MIT, and libgcc and libstdc++ under GPL-3.0 with the GCC Runtime +Library Exception; a release of the image comes with the exact kernel source it was built from. diff --git a/microvm/build.cs b/microvm/build.cs new file mode 100644 index 0000000..37f9925 --- /dev/null +++ b/microvm/build.cs @@ -0,0 +1,230 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +// Builds the guest image of Tazel's MicroVM for x86_64: the Linux kernel of kernel.org with kernel.config on top of +// tinyconfig, and an initramfs that holds the agent, published self-contained for linux-musl, and the four libraries +// of Alpine it runs on. Every download is checked against the SHA-256 written here; the same inputs give the same +// bytes. +// +// dotnet run microvm/build.cs -- <work directory> <output directory> +// +// The output directory gets vmlinux, initramfs.cpio.gz, kernel.config (the whole configuration) and SHA256SUMS. + +using System; +using System.Diagnostics; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; +using System.Security.Cryptography; +using System.Text; + +const string KernelVersion = "6.18.64"; +const string KernelSha256 = "020d45510c539972e6f14c5c71566878d3b7ef56fb082b3e09134f2ebaade562"; +const string Alpine = "https://dl-cdn.alpinelinux.org/alpine/v3.24/main/x86_64"; +(string File, string Sha256)[] packages = +[ + ("musl-1.2.6-r3.apk", "e142255d0fa397f14318996bc10378093dcc069dc3dd1b6818c8f28a789c21da"), + ("libgcc-15.2.0-r5.apk", "393dcd32629f06d7d85409c272d142d0c082772d10b87ef55ee82f47de3be637"), + ("libstdc++-15.2.0-r5.apk", "14c987b556f5385a5db18376e788c75f37d85321b8dc1920d926ea7daac1d6f6"), +]; + +if (!OperatingSystem.IsLinux()) +{ + Console.Error.WriteLine("the image of the MicroVM is built on Linux"); + return 2; +} + +if (args.Length != 2) +{ + Console.Error.WriteLine("usage: dotnet run microvm/build.cs -- <work directory> <output directory>"); + return 2; +} + +var repository = Path.GetFullPath(Path.Combine(AppContext.GetData("EntryPointFileDirectoryPath") as string ?? "microvm", "..")); +var work = Path.GetFullPath(args[0]); +var output = Path.GetFullPath(args[1]); +Directory.CreateDirectory(work); +Directory.CreateDirectory(output); +using var http = new HttpClient(); + +// The kernel. +var tarball = await Fetch($"https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-{KernelVersion}.tar.xz", KernelSha256, + Path.Combine(work, $"linux-{KernelVersion}.tar.xz")); +var source = Path.Combine(work, $"linux-{KernelVersion}"); +if (!File.Exists(Path.Combine(source, "Makefile"))) +{ + Run(work, "tar", "-xf", tarball); +} + +string[] reproducible = ["KBUILD_BUILD_TIMESTAMP=2026-01-01", "KBUILD_BUILD_USER=tazel", "KBUILD_BUILD_HOST=tazel"]; +Run(source, "make", "tinyconfig"); +Run(source, Path.Combine(source, "scripts", "kconfig", "merge_config.sh"), "-m", ".config", Path.Combine(repository, "microvm", "kernel.config")); +Run(source, "make", "olddefconfig"); +RunWith(source, reproducible, ["make", $"-j{Environment.ProcessorCount}", "vmlinux"]); +File.Copy(Path.Combine(source, "vmlinux"), Path.Combine(output, "vmlinux"), overwrite: true); +File.Copy(Path.Combine(source, ".config"), Path.Combine(output, "kernel.config"), overwrite: true); + +// The agent and the libraries it runs on. +var root = Path.Combine(work, "initramfs"); +if (Directory.Exists(root)) +{ + Directory.Delete(root, recursive: true); +} + +var agent = Path.Combine(root, "tazel", "agent"); +var libraries = Path.Combine(root, "tazel", "lib"); +Directory.CreateDirectory(libraries); +Run(repository, "dotnet", "publish", "src/Progmasoft.Tazel.Guest", "-c", "Release", "-r", "linux-musl-x64", "--self-contained", + "-p:PublishTrimmed=true", "-p:DebugType=none", "-o", agent); +var unpacked = Path.Combine(work, "alpine"); +foreach (var (file, sha) in packages) +{ + var apk = await Fetch($"{Alpine}/{Uri.EscapeDataString(file)}", sha, Path.Combine(work, file)); + Directory.CreateDirectory(unpacked); + // An apk is gzip members one after another; tar reads through them. + Run(unpacked, "tar", "-xzf", apk, "--warning=no-unknown-keyword"); +} + +foreach (var (from, to) in new[] +{ + ("lib/libc.musl-x86_64.so.1", "libc.musl-x86_64.so.1"), + ("usr/lib/libgcc_s.so.1", "libgcc_s.so.1"), + ("usr/lib/libstdc++.so.6.0.34", "libstdc++.so.6"), +}) +{ + File.Copy(Path.Combine(unpacked, from), Path.Combine(libraries, to), overwrite: true); +} + +// The loader beside the agent: run as the program, it makes the agent's directory the one .NET looks in. +File.Copy(Path.Combine(unpacked, "lib", "ld-musl-x86_64.so.1"), Path.Combine(agent, "ld-musl-x86_64.so.1"), overwrite: true); +foreach (var directory in new[] { "dev", "proc", "sys", "tmp", "run", "usr", "etc", "root" }) +{ + Directory.CreateDirectory(Path.Combine(root, directory)); +} + +var initramfs = Path.Combine(output, "initramfs.cpio.gz"); +using (var file = File.Create(initramfs)) +using (var gzip = new GZipStream(file, CompressionLevel.SmallestSize)) +{ + Cpio.Write(gzip, root); +} + +var sums = new StringBuilder(); +foreach (var name in new[] { "initramfs.cpio.gz", "kernel.config", "vmlinux" }) +{ + sums.Append(CultureInvariant($"{Sha256(Path.Combine(output, name))} {name}\n")); +} + +await File.WriteAllTextAsync(Path.Combine(output, "SHA256SUMS"), sums.ToString()); +Console.WriteLine($"wrote {output}"); +Console.Write(sums); +return 0; + +async Task<string> Fetch(string url, string sha, string path) +{ + if (!File.Exists(path) || Sha256(path) != sha) + { + Console.WriteLine($"fetching {url}"); + await using var download = await http.GetStreamAsync(url); + await using var file = File.Create(path + ".partial"); + await download.CopyToAsync(file); + file.Close(); + File.Move(path + ".partial", path, overwrite: true); + } + + var actual = Sha256(path); + return actual == sha ? path : throw new InvalidDataException($"{url} has the SHA-256 {actual}, not {sha}"); +} + +static string Sha256(string path) +{ + using var stream = File.OpenRead(path); + return Convert.ToHexStringLower(SHA256.HashData(stream)); +} + +static void Run(string directory, params string[] command) => RunWith(directory, [], command); + +static void RunWith(string directory, string[] environment, string[] command) +{ + var start = new ProcessStartInfo(command[0]) { WorkingDirectory = directory, UseShellExecute = false }; + foreach (var argument in command.Skip(1)) + { + start.ArgumentList.Add(argument); + } + + foreach (var entry in environment) + { + var equals = entry.IndexOf('='); + start.Environment[entry[..equals]] = entry[(equals + 1)..]; + } + + using var process = Process.Start(start)!; + process.WaitForExit(); + if (process.ExitCode != 0) + { + throw new InvalidOperationException($"{string.Join(' ', command)} failed with {process.ExitCode}"); + } +} + +static string CultureInvariant(FormattableString text) => FormattableString.Invariant(text); + +/// <summary> +/// The "newc" cpio format the kernel unpacks: files sorted by path, owned by root, dated at the epoch, with +/// /dev/console as a device, so the agent has a console before it mounts /dev. +/// </summary> +[System.Runtime.Versioning.SupportedOSPlatform("linux")] +static class Cpio +{ + public static void Write(Stream stream, string root) + { + var inode = 1; + var entries = Directory.EnumerateFileSystemEntries(root, "*", SearchOption.AllDirectories) + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .Order(StringComparer.Ordinal) + .ToList(); + foreach (var name in entries) + { + var path = Path.Combine(root, name); + var info = new FileInfo(path); + if (info.LinkTarget is { } target) + { + Entry(stream, inode++, name, 0xA000 | 0x1FF, Encoding.UTF8.GetBytes(target), 0, 0); + } + else if (Directory.Exists(path)) + { + Entry(stream, inode++, name, 0x4000 | 0x1ED, [], 0, 0); + if (name == "dev") + { + Entry(stream, inode++, "dev/console", 0x2000 | 0x180, [], 5, 1); + } + } + else + { + var executable = (File.GetUnixFileMode(path) & UnixFileMode.UserExecute) != 0; + Entry(stream, inode++, name, 0x8000 | (executable ? 0x1ED : 0x1A4), File.ReadAllBytes(path), 0, 0); + } + } + + Entry(stream, 0, "TRAILER!!!", 0, [], 0, 0); + } + + private static void Entry(Stream stream, int inode, string name, int mode, byte[] data, int major, int minor) + { + var nameBytes = Encoding.UTF8.GetBytes(name + "\0"); + var header = string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"070701{inode:X8}{mode:X8}{0:X8}{0:X8}{1:X8}{0:X8}{data.Length:X8}{0:X8}{0:X8}{major:X8}{minor:X8}{nameBytes.Length:X8}{0:X8}"); + stream.Write(Encoding.ASCII.GetBytes(header)); + stream.Write(nameBytes); + Pad(stream, 110 + nameBytes.Length); + stream.Write(data); + Pad(stream, data.Length); + } + + private static void Pad(Stream stream, int length) + { + var padding = (4 - (length % 4)) % 4; + stream.Write(new byte[padding]); + } +} diff --git a/microvm/kernel.config b/microvm/kernel.config new file mode 100644 index 0000000..fc64ec0 --- /dev/null +++ b/microvm/kernel.config @@ -0,0 +1,58 @@ +# The options Tazel's MicroVM guest needs on top of `make tinyconfig`, for x86_64 under Cloud Hypervisor. +CONFIG_64BIT=y +CONFIG_SMP=y +CONFIG_NR_CPUS=64 +CONFIG_PVH=y +CONFIG_HYPERVISOR_GUEST=y +CONFIG_PARAVIRT=y +CONFIG_KVM_GUEST=y +CONFIG_ACPI=y +CONFIG_PCI=y +CONFIG_PCI_MSI=y +CONFIG_PRINTK=y +CONFIG_TTY=y +CONFIG_HVC_DRIVER=y +CONFIG_VIRTIO_CONSOLE=y +CONFIG_SERIAL_8250=y +CONFIG_SERIAL_8250_CONSOLE=y +CONFIG_BLK_DEV_INITRD=y +CONFIG_RD_GZIP=y +CONFIG_BINFMT_ELF=y +CONFIG_BINFMT_SCRIPT=y +CONFIG_MULTIUSER=y +CONFIG_POSIX_TIMERS=y +CONFIG_FUTEX=y +CONFIG_EPOLL=y +CONFIG_SIGNALFD=y +CONFIG_TIMERFD=y +CONFIG_EVENTFD=y +CONFIG_SHMEM=y +CONFIG_AIO=y +CONFIG_IO_URING=y +CONFIG_ADVISE_SYSCALLS=y +CONFIG_MEMBARRIER=y +CONFIG_RSEQ=y +CONFIG_FILE_LOCKING=y +CONFIG_HIGH_RES_TIMERS=y +CONFIG_PROC_FS=y +CONFIG_PROC_SYSCTL=y +CONFIG_SYSFS=y +CONFIG_TMPFS=y +CONFIG_DEVTMPFS=y +CONFIG_DEVTMPFS_MOUNT=y +CONFIG_UNIX98_PTYS=y +CONFIG_NET=y +CONFIG_UNIX=y +CONFIG_INET=y +CONFIG_VSOCKETS=y +CONFIG_VIRTIO_VSOCKETS=y +CONFIG_VIRTIO_MENU=y +CONFIG_VIRTIO=y +CONFIG_VIRTIO_PCI=y +CONFIG_VIRTIO_MMIO=y +CONFIG_FUSE_FS=y +CONFIG_VIRTIO_FS=y +CONFIG_HW_RANDOM=y +CONFIG_HW_RANDOM_VIRTIO=y +CONFIG_RTC_CLASS=y +CONFIG_MODULES=n diff --git a/src/Progmasoft.Tazel.Guest/Agent.cs b/src/Progmasoft.Tazel.Guest/Agent.cs new file mode 100644 index 0000000..28926ff --- /dev/null +++ b/src/Progmasoft.Tazel.Guest/Agent.cs @@ -0,0 +1,306 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.MicroVm; + +namespace Progmasoft.Tazel.Guest; + +/// <summary>A directory of the host the guest sees, from <c>tazel.share=tag,ro|rw,path</c> on the kernel command line.</summary> +/// <param name="Tag">The virtio-fs tag.</param> +/// <param name="Path">Where it is mounted: the same path as on the host.</param> +/// <param name="ReadOnly">Whether the guest may only read it.</param> +internal sealed record Share(string Tag, string Path, bool ReadOnly) +{ + /// <summary>The shares of a kernel command line; the path is base64url, as a path may hold spaces.</summary> + public static IReadOnlyList<Share> Parse(string commandLine) + { + ArgumentNullException.ThrowIfNull(commandLine); + var shares = new List<Share>(); + foreach (var word in commandLine.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)) + { + if (!word.StartsWith("tazel.share=", StringComparison.Ordinal)) + { + continue; + } + + var parts = word["tazel.share=".Length..].Split(','); + if (parts.Length != 3 || parts[1] is not ("ro" or "rw")) + { + throw new FormatException($"'{word}' is not tazel.share=tag,ro|rw,path"); + } + + var path = MicroVmProtocol.DecodePath(parts[2]); + if (!path.StartsWith('/') || path.Split('/').Contains("..")) + { + throw new FormatException($"the share {parts[0]} has the path '{path}'"); + } + + shares.Add(new Share(parts[0], path, parts[1] == "ro")); + } + + return shares; + } + +} + +/// <summary> +/// The first process of the guest: it mounts what the guest needs, listens on vsock, runs the commands Tazel sends, +/// and powers the machine off when told to or when it cannot go on. +/// </summary> +internal sealed class Agent(IReadOnlyList<Share> shares) +{ + /// <summary>The PATH of the agent and the one it searches when a command brings none.</summary> + public const string DefaultPath = MicroVmProtocol.DefaultPath; + + public static string Version => typeof(Agent).Assembly.GetName().Version?.ToString(3) ?? "0.0.0"; + + /// <summary>Mounts the kernel's file systems and the shares, and points the root's directories into /usr.</summary> + [System.Runtime.Versioning.SupportedOSPlatform("linux")] + public void Boot() + { + MountOrFail("sysfs", "/sys", "sysfs", Libc.MsNosuid | Libc.MsNodev | Libc.MsNoexec, null); + MountOrFail("devtmpfs", "/dev", "devtmpfs", Libc.MsNosuid, "mode=0755"); + MountOrFail("devpts", "/dev/pts", "devpts", Libc.MsNosuid | Libc.MsNoexec, "gid=5,mode=0620,ptmxmode=0666"); + MountOrFail("tmpfs", "/tmp", "tmpfs", Libc.MsNosuid | Libc.MsNodev, "mode=1777"); + MountOrFail("tmpfs", "/run", "tmpfs", Libc.MsNosuid | Libc.MsNodev, "mode=0755"); + foreach (var share in shares) + { + MountOrFail(share.Tag, share.Path, "virtiofs", share.ReadOnly ? Libc.MsRdonly : 0, null); + } + + // Merged /usr: the host's tools find their loader and libraries where they were built to look. + if (Directory.Exists("/usr/bin")) + { + Link("/bin", "usr/bin"); + Link("/sbin", Directory.Exists("/usr/sbin") ? "usr/sbin" : "usr/bin"); + Link("/lib", "usr/lib"); + Link("/lib64", Directory.Exists("/usr/lib64") ? "usr/lib64" : "usr/lib"); + } + + Directory.CreateDirectory("/root"); + var name = "tazel"u8; + _ = Libc.SetHostName(name, (nuint)name.Length); + Environment.SetEnvironmentVariable("PATH", DefaultPath); + } + + /// <summary>Serves connections until one asks the machine to power off.</summary> + [System.Runtime.Versioning.SupportedOSPlatform("linux")] + public void Serve() + { + var listener = Libc.Socket(Libc.AfVsock, Libc.SockStream, 0); + if (listener < 0) + { + throw new IOException($"vsock: {Libc.LastError()}"); + } + + var address = new Libc.SockaddrVm { Family = Libc.AfVsock, Port = MicroVmProtocol.Port, Cid = Libc.VmaddrCidAny }; + if (Libc.Bind(listener, address, 16) != 0 || Libc.Listen(listener, 64) != 0) + { + throw new IOException($"vsock port {MicroVmProtocol.Port}: {Libc.LastError()}"); + } + + using var off = new ManualResetEventSlim(); + var accepting = new Thread(() => + { + while (true) + { + var connection = Libc.Accept(listener, IntPtr.Zero, IntPtr.Zero); + if (connection >= 0) + { + _ = Task.Run(() => ServeAsync(new VsockStream(connection), off)); + } + } + }) { IsBackground = true, Name = "vsock" }; + accepting.Start(); + off.Wait(); + } + + /// <summary>Writes everything out and powers off; the monitor ends with the machine.</summary> + [System.Runtime.Versioning.SupportedOSPlatform("linux")] + public static void PowerOff() + { + Libc.Sync(); + _ = Libc.Reboot(Libc.RebootPowerOff); + Thread.Sleep(Timeout.Infinite); + } + + /// <summary>The program <paramref name="name"/> names: itself when it has a slash, else the first on <paramref name="path"/>.</summary> + [System.Runtime.Versioning.SupportedOSPlatform("linux")] + public static string? Find(string name, string path) + { + ArgumentNullException.ThrowIfNull(name); + if (name.Contains('/', StringComparison.Ordinal)) + { + return File.Exists(name) ? name : null; + } + + return (path ?? DefaultPath).Split(':', StringSplitOptions.RemoveEmptyEntries) + .Select(directory => Path.Combine(directory, name)) + .FirstOrDefault(candidate => File.Exists(candidate) && + (File.GetUnixFileMode(candidate) & (UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute)) != 0); + } + + /// <summary>Whether <paramref name="directory"/> is inside a share the guest may write.</summary> + public bool Inside(string directory) + { + var full = Path.GetFullPath(directory); + return shares.Any(share => !share.ReadOnly && + (full == share.Path || full.StartsWith(share.Path.TrimEnd('/') + "/", StringComparison.Ordinal))); + } + + [System.Runtime.Versioning.SupportedOSPlatform("linux")] + private async Task ServeAsync(VsockStream stream, ManualResetEventSlim off) + { + using (stream) + { + try + { + var message = await MicroVmProtocol.ReadAsync(stream, CancellationToken.None).ConfigureAwait(false); + switch (message?.Kind) + { + case MessageKind.Hello: + await MicroVmProtocol.WriteAsync(stream, MessageKind.Ready, Encoding.UTF8.GetBytes(Version), CancellationToken.None) + .ConfigureAwait(false); + break; + case MessageKind.Run: + await RunAsync(stream, MicroVmProtocol.DecodeRun(message.Value.Payload)).ConfigureAwait(false); + break; + case MessageKind.PowerOff: + off.Set(); + break; + } + } + catch (Exception error) when (error is IOException or InvalidDataException or EndOfStreamException) + { + // The host went away or sent something broken; the connection ends, the agent goes on. + } + } + } + + [System.Runtime.Versioning.SupportedOSPlatform("linux")] + private async Task RunAsync(VsockStream stream, RunRequest request) + { + if (request.Arguments.Count == 0) + { + await Refuse(stream, "the command is empty").ConfigureAwait(false); + return; + } + + if (!Inside(request.Directory) || !Directory.Exists(request.Directory)) + { + await Refuse(stream, $"{request.Directory} is not inside a directory Tazel shared").ConfigureAwait(false); + return; + } + + var program = Find(request.Arguments[0], request.Environment.GetValueOrDefault("PATH", DefaultPath)); + if (program is null) + { + await Refuse(stream, $"{request.Arguments[0]} is not found in the MicroVM").ConfigureAwait(false); + return; + } + + var start = new ProcessStartInfo(program) + { + WorkingDirectory = request.Directory, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }; + foreach (var argument in request.Arguments.Skip(1)) + { + start.ArgumentList.Add(argument); + } + + start.Environment.Clear(); + foreach (var (name, value) in request.Environment) + { + start.Environment[name] = value; + } + + using var process = new Process { StartInfo = start }; + try + { + process.Start(); + } + catch (System.ComponentModel.Win32Exception error) + { + await Refuse(stream, $"{program} could not be started: {error.Message}").ConfigureAwait(false); + return; + } + + process.StandardInput.Close(); + var stop = Task.Run(async () => + { + // The host sends Stop, or goes away, while the command runs. + try + { + await MicroVmProtocol.ReadAsync(stream, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception error) when (error is IOException or InvalidDataException or EndOfStreamException) + { + } + + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + } + }); + var output = Pump(process.StandardOutput.BaseStream, 1, stream); + var errors = Pump(process.StandardError.BaseStream, 2, stream); + await Task.WhenAll(output, errors).ConfigureAwait(false); + await process.WaitForExitAsync().ConfigureAwait(false); + await MicroVmProtocol.WriteAsync(stream, MessageKind.Exit, MicroVmProtocol.EncodeStatus(process.ExitCode), CancellationToken.None) + .ConfigureAwait(false); + _ = stop; + } + + [System.Runtime.Versioning.SupportedOSPlatform("linux")] + private static async Task Pump(Stream from, byte which, VsockStream to) + { + var buffer = new byte[65536]; + while (true) + { + var read = await from.ReadAsync(buffer.AsMemory(1, buffer.Length - 1)).ConfigureAwait(false); + if (read == 0) + { + return; + } + + buffer[0] = which; + await MicroVmProtocol.WriteAsync(to, MessageKind.Output, buffer.AsMemory(0, read + 1), CancellationToken.None) + .ConfigureAwait(false); + } + } + + [System.Runtime.Versioning.SupportedOSPlatform("linux")] + private static Task Refuse(VsockStream stream, string why) => + MicroVmProtocol.WriteAsync(stream, MessageKind.Error, Encoding.UTF8.GetBytes(why), CancellationToken.None); + + [System.Runtime.Versioning.SupportedOSPlatform("linux")] + private static void MountOrFail(string source, string target, string type, ulong flags, string? data) + { + Directory.CreateDirectory(target); + if (Libc.Mount(source, target, type, flags, data) != 0) + { + throw new IOException($"mounting {type} {source} on {target}: {Libc.LastError()}"); + } + } + + [System.Runtime.Versioning.SupportedOSPlatform("linux")] + private static void Link(string path, string target) + { + if (!Path.Exists(path)) + { + File.CreateSymbolicLink(path, target); + } + } +} diff --git a/src/Progmasoft.Tazel.Guest/Libc.cs b/src/Progmasoft.Tazel.Guest/Libc.cs new file mode 100644 index 0000000..8bb5313 --- /dev/null +++ b/src/Progmasoft.Tazel.Guest/Libc.cs @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Progmasoft.Tazel.Guest; + +/// <summary>The calls into the C library the agent needs, generated by <c>[LibraryImport]</c>.</summary> +[System.Runtime.Versioning.SupportedOSPlatform("linux")] +internal static partial class Libc +{ + public const int AfVsock = 40; + public const int SockStream = 1; + public const uint VmaddrCidAny = 0xFFFFFFFF; + public const ulong MsRdonly = 1; + public const ulong MsNosuid = 2; + public const ulong MsNodev = 4; + public const ulong MsNoexec = 8; + public const int RebootPowerOff = 0x4321FEDC; + + private const string Library = "libc"; + + /// <summary> + /// The C library is the one the program was loaded with, so its symbols are looked up through the program itself; + /// that works on musl and on glibc, whatever the file of the library is called. + /// </summary> + public static void Resolve() => + NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(), + (name, _, _) => name == Library ? NativeLibrary.GetMainProgramHandle() : IntPtr.Zero); + + [LibraryImport(Library, EntryPoint = "mount", SetLastError = true, StringMarshalling = StringMarshalling.Utf8)] + public static partial int Mount(string source, string target, string type, ulong flags, string? data); + + [LibraryImport(Library, EntryPoint = "sethostname", SetLastError = true)] + public static partial int SetHostName(ReadOnlySpan<byte> name, nuint length); + + [LibraryImport(Library, EntryPoint = "sync")] + public static partial void Sync(); + + [LibraryImport(Library, EntryPoint = "reboot", SetLastError = true)] + public static partial int Reboot(int how); + + [LibraryImport(Library, EntryPoint = "socket", SetLastError = true)] + public static partial int Socket(int domain, int type, int protocol); + + [LibraryImport(Library, EntryPoint = "bind", SetLastError = true)] + public static partial int Bind(int socket, in SockaddrVm address, uint length); + + [LibraryImport(Library, EntryPoint = "listen", SetLastError = true)] + public static partial int Listen(int socket, int backlog); + + [LibraryImport(Library, EntryPoint = "accept", SetLastError = true)] + public static partial int Accept(int socket, IntPtr address, IntPtr length); + + [LibraryImport(Library, EntryPoint = "read", SetLastError = true)] + public static unsafe partial nint Read(int fd, byte* buffer, nuint count); + + [LibraryImport(Library, EntryPoint = "write", SetLastError = true)] + public static unsafe partial nint Write(int fd, byte* buffer, nuint count); + + [LibraryImport(Library, EntryPoint = "close", SetLastError = true)] + public static partial int Close(int fd); + + /// <summary>The text of the last error of the C library.</summary> + public static string LastError() => Marshal.GetLastPInvokeErrorMessage(); + + /// <summary><c>struct sockaddr_vm</c>.</summary> + [StructLayout(LayoutKind.Sequential)] + public struct SockaddrVm + { + public ushort Family; + public ushort Reserved; + public uint Port; + public uint Cid; + public uint Zero; + } +} diff --git a/src/Progmasoft.Tazel.Guest/Progmasoft.Tazel.Guest.csproj b/src/Progmasoft.Tazel.Guest/Progmasoft.Tazel.Guest.csproj new file mode 100644 index 0000000..24504fc --- /dev/null +++ b/src/Progmasoft.Tazel.Guest/Progmasoft.Tazel.Guest.csproj @@ -0,0 +1,23 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: MIT --> +<!-- The agent of Tazel's MicroVM: the first process of the Linux guest. Published self-contained for linux-musl. --> +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <OutputType>Exe</OutputType> + <RootNamespace>Progmasoft.Tazel.Guest</RootNamespace> + <AssemblyName>tazel-guest</AssemblyName> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <RuntimeIdentifiers>linux-musl-x64;linux-musl-arm64</RuntimeIdentifiers> + <UseAppHost>true</UseAppHost> + <SatelliteResourceLanguages>en</SatelliteResourceLanguages> + <AutoreleasePoolSupport>false</AutoreleasePoolSupport> + <UseSystemResourceKeys>true</UseSystemResourceKeys> + <EventSourceSupport>false</EventSourceSupport> + </PropertyGroup> + <ItemGroup> + <Compile Include="../Shared/MicroVmProtocol.cs" Link="Shared/MicroVmProtocol.cs" /> + </ItemGroup> + <ItemGroup> + <InternalsVisibleTo Include="Progmasoft.Tazel.Tests" /> + </ItemGroup> +</Project> diff --git a/src/Progmasoft.Tazel.Guest/Program.cs b/src/Progmasoft.Tazel.Guest/Program.cs new file mode 100644 index 0000000..25177c4 --- /dev/null +++ b/src/Progmasoft.Tazel.Guest/Program.cs @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; + +namespace Progmasoft.Tazel.Guest; + +/// <summary>The entry of the agent; as the first process of the guest, it never returns.</summary> +[System.Runtime.Versioning.SupportedOSPlatform("linux")] +internal static class Program +{ + public static int Main() + { + Libc.Resolve(); + try + { + // The shares are on the kernel command line, so /proc comes first. + Directory.CreateDirectory("/proc"); + if (Libc.Mount("proc", "/proc", "proc", Libc.MsNosuid | Libc.MsNodev | Libc.MsNoexec, null) != 0) + { + throw new IOException($"mounting /proc: {Libc.LastError()}"); + } + + var shares = Share.Parse(File.ReadAllText("/proc/cmdline")); + var agent = new Agent(shares); + agent.Boot(); + Console.Error.WriteLine($"tazel-guest {Agent.Version}: ready on vsock port {MicroVm.MicroVmProtocol.Port}"); + agent.Serve(); + } + catch (Exception error) when (error is IOException or FormatException or UnauthorizedAccessException) + { + // The console is the monitor's log; Tazel shows its end when the machine does not answer. + Console.Error.WriteLine($"tazel-guest: {error.Message}"); + } + + Agent.PowerOff(); + return 0; + } +} diff --git a/src/Progmasoft.Tazel.Guest/VsockStream.cs b/src/Progmasoft.Tazel.Guest/VsockStream.cs new file mode 100644 index 0000000..833f12b --- /dev/null +++ b/src/Progmasoft.Tazel.Guest/VsockStream.cs @@ -0,0 +1,127 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Progmasoft.Tazel.Guest; + +/// <summary>A connected vsock socket as a stream, over read and write; .NET has no vsock address family.</summary> +[System.Runtime.Versioning.SupportedOSPlatform("linux")] +internal sealed class VsockStream(int fd) : Stream +{ + private readonly Lock _writing = new(); + private int _fd = fd; + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override unsafe int Read(byte[] buffer, int offset, int count) + { + ArgumentNullException.ThrowIfNull(buffer); + fixed (byte* start = &buffer[offset]) + { + while (true) + { + var read = Libc.Read(_fd, start, (nuint)count); + if (read >= 0) + { + return (int)read; + } + + if (System.Runtime.InteropServices.Marshal.GetLastPInvokeError() != 4) + { + throw new IOException($"reading the connection failed: {Libc.LastError()}"); + } + } + } + } + + // A blocking read on a thread of its own, so the agent serves other connections meanwhile. + public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + Task.Factory.StartNew(() => Read(buffer, offset, count), cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default); + + public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) + { + var array = new byte[buffer.Length]; + return new ValueTask<int>(ReadAsync(array, 0, array.Length, cancellationToken).ContinueWith( + task => + { + array.AsSpan(0, task.Result).CopyTo(buffer.Span); + return task.Result; + }, + cancellationToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default)); + } + + public override unsafe void Write(byte[] buffer, int offset, int count) + { + ArgumentNullException.ThrowIfNull(buffer); + lock (_writing) + { + fixed (byte* start = buffer) + { + var done = 0; + while (done < count) + { + var written = Libc.Write(_fd, start + offset + done, (nuint)(count - done)); + if (written < 0) + { + if (System.Runtime.InteropServices.Marshal.GetLastPInvokeError() == 4) + { + continue; + } + + throw new IOException($"writing the connection failed: {Libc.LastError()}"); + } + + done += (int)written; + } + } + } + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + Write(buffer, offset, count); + return Task.CompletedTask; + } + + public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) + { + var array = buffer.ToArray(); + Write(array, 0, array.Length); + return ValueTask.CompletedTask; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + var fd = Interlocked.Exchange(ref _fd, -1); + if (fd >= 0) + { + Libc.Close(fd); + } + + base.Dispose(disposing); + } +} diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 109d8ee..fcfc4ea 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -61,7 +61,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector case PackageCommand: return await PackageAsync().ConfigureAwait(false); case CustomCommandLine custom: - return Custom(custom); + return await CustomAsync(custom, cancel).ConfigureAwait(false); case BuildCommand build: return await BuildAsync(build.Labels, build.Flags, BuildKind.Build, null, cancel).ConfigureAwait(false); case TestCommand test: @@ -83,8 +83,8 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector } /// <summary> - /// Stops a command that would run what a project brings when a sandbox is asked for: this Tazel has no MicroVM to - /// start, so nothing runs rather than run on the host. + /// Stops a command that would run what a project brings when a sandbox is asked for: this Tazel runs tazel custom + /// inside its MicroVM, and builds, tests and plugins not, so nothing runs rather than run on the host. /// </summary> private void RefuseWithoutSandbox() { @@ -92,8 +92,8 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector if (file is not null) { throw new ProjectException( - $"{file} asks for sandboxing-with-microvm, and this Tazel has no MicroVM to start, so nothing ran; " + - "set it to false to run without the sandbox"); + $"{file} asks for sandboxing-with-microvm; this Tazel runs tazel custom inside its MicroVM, and not " + + "builds, tests or plugins, so nothing ran; set it to false to run them without the sandbox"); } } @@ -149,9 +149,9 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector return 0; } - private int Custom(CustomCommandLine custom) + private async Task<int> CustomAsync(CustomCommandLine custom, CancellationToken cancel) { - RefuseWithoutSandbox(); + var (options, sandboxFile) = TazelOptionsFile.Effective(workingDirectory); var file = Path.Combine(workingDirectory, CustomCommandFiles.FileName); if (!File.Exists(file)) { @@ -178,6 +178,11 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector throw new CommandLineException($"'{command.Name}' takes {command.Required} arguments, and {arguments.Count} were given"); } + if (sandboxFile is not null) + { + return await CustomInMicroVmAsync(command, arguments, options, sandboxFile, cancel).ConfigureAwait(false); + } + var environment = Processes.Inherited(); foreach (var step in command.Steps) { diff --git a/src/Progmasoft.Tazel/Cli/MoreCommands.cs b/src/Progmasoft.Tazel/Cli/MoreCommands.cs index f03c095..b6ff0b6 100644 --- a/src/Progmasoft.Tazel/Cli/MoreCommands.cs +++ b/src/Progmasoft.Tazel/Cli/MoreCommands.cs @@ -171,6 +171,67 @@ internal sealed partial class Commands } } + /// <summary> + /// Runs the steps of a custom command inside a MicroVM that sees the module, or the directory of the command when + /// it is in no module, and the host's /usr read-only; a shell step goes to the guest's /bin/sh. + /// </summary> + private async Task<int> CustomInMicroVmAsync( + Dsl.Custom.CustomCommand command, IReadOnlyList<string> arguments, TazelOptions options, string sandboxFile, + CancellationToken cancel) + { + if (options.MicrovmNetwork) + { + throw new MicroVm.MicroVmException( + $"{sandboxFile} asks for microvm-network, and this Tazel's MicroVM has no network, so nothing ran; " + + "set microvm-network: false;"); + } + + if (!OperatingSystem.IsLinux()) + { + throw new MicroVm.MicroVmException( + $"{sandboxFile} asks for sandboxing-with-microvm, and this Tazel starts its MicroVM on Linux only"); + } + + string shared; + try + { + shared = ModuleFiles.FindRoot(workingDirectory); + } + catch (ProjectException) + { + shared = Path.GetFullPath(workingDirectory); + } + + var files = await MicroVm.MicroVmFiles.FindAsync(TazelVersion, reporter.Status, cancel).ConfigureAwait(false); + var size = new MicroVm.MicroVmSize( + options.MicrovmMemory.Amount ?? 1024, options.MicrovmCpus.Amount ?? Math.Clamp(Environment.ProcessorCount / 2, 1, 4)); + reporter.Status($"starting the MicroVM ({size.MemoryMiB} MiB, {size.Processors} processor{(size.Processors == 1 ? "" : "s")})"); + var sandbox = await MicroVm.Sandbox.StartAsync(files, [new MicroVm.SharedDirectory(shared, ReadOnly: false)], size, cancel) + .ConfigureAwait(false); + await using (sandbox.ConfigureAwait(false)) + { + var output = Console.OpenStandardOutput(); + var errors = Console.OpenStandardError(); + foreach (var step in command.Steps) + { + var started = step switch + { + Dsl.Custom.CustomStep.Program program => program.Expanded(arguments), + Dsl.Custom.CustomStep.Shell shell => shell.Started(windows: false), + _ => throw new InvalidOperationException("a step of no kind"), + }; + var status = await sandbox.RunAsync(started, Path.GetFullPath(workingDirectory), output, errors, cancel) + .ConfigureAwait(false); + if (status != 0) + { + return status; + } + } + } + + return 0; + } + private async Task<int> FetchAsync() { RefuseWithoutSandbox(); diff --git a/src/Progmasoft.Tazel/MicroVm/MicroVmFiles.cs b/src/Progmasoft.Tazel/MicroVm/MicroVmFiles.cs new file mode 100644 index 0000000..9a555f0 --- /dev/null +++ b/src/Progmasoft.Tazel/MicroVm/MicroVmFiles.cs @@ -0,0 +1,186 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Progmasoft.Tazel.Archive; +using Progmasoft.Tazel.Driver; + +namespace Progmasoft.Tazel.MicroVm; + +/// <summary>What a MicroVM is started from: the guest kernel and initramfs, the monitor, and virtiofsd.</summary> +/// <param name="Kernel">The guest kernel, an ELF vmlinux that boots through PVH.</param> +/// <param name="Initramfs">The initramfs with the agent.</param> +/// <param name="Monitor">Cloud Hypervisor.</param> +/// <param name="Virtiofsd">The virtio-fs daemon of the host.</param> +internal sealed record MicroVmFiles(string Kernel, string Initramfs, string Monitor, string Virtiofsd) +{ + /// <summary>The Cloud Hypervisor release Tazel runs, and the SHA-256 of its static x86_64 program.</summary> + public const string MonitorVersion = "v55.0"; + + private const string MonitorSha256 = "ce7133bf535ed5a4e2a63ea1f26025445a5b1241f73ddfb81ff2fbcb2e803a59"; + + /// <summary> + /// Finds every file, fetching what is missing into the cache of the user: the image from + /// <c>TAZEL_MICROVM_IMAGE</c> (a directory with <c>SHA256SUMS</c>, as <c>microvm/build.cs</c> writes it) or the + /// release of this Tazel, the monitor from <c>TAZEL_CLOUD_HYPERVISOR</c> or its release, and virtiofsd from the + /// host. Each file is checked against its SHA-256 before it is used. + /// </summary> + public static async Task<MicroVmFiles> FindAsync(Version tazel, Action<string> status, CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(tazel); + ArgumentNullException.ThrowIfNull(status); + if (!OperatingSystem.IsLinux() || RuntimeInformation.OSArchitecture != Architecture.X64) + { + throw new MicroVmException( + $"this Tazel starts its MicroVM on x86_64 Linux with KVM, and this machine is {RuntimeInformation.RuntimeIdentifier}"); + } + + if (!File.Exists("/dev/kvm")) + { + throw new MicroVmException("/dev/kvm is not there; the MicroVM needs KVM, so turn on virtualization in the firmware"); + } + + var cache = Path.Combine(Environment.GetEnvironmentVariable("XDG_CACHE_HOME") is { Length: > 0 } xdg + ? xdg + : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".cache"), "tazel"); + var image = Environment.GetEnvironmentVariable("TAZEL_MICROVM_IMAGE") is { Length: > 0 } given + ? given + : await FetchImageAsync(tazel, Path.Combine(cache, "microvm", tazel.ToString(3)), status, cancel).ConfigureAwait(false); + CheckImage(image); + var monitor = Environment.GetEnvironmentVariable("TAZEL_CLOUD_HYPERVISOR") is { Length: > 0 } chosen + ? chosen + : await FetchMonitorAsync(Path.Combine(cache, "cloud-hypervisor", MonitorVersion), status, cancel).ConfigureAwait(false); + var virtiofsd = Environment.GetEnvironmentVariable("TAZEL_VIRTIOFSD") is { Length: > 0 } daemon + ? daemon + : new[] { "/usr/libexec/virtiofsd", "/usr/lib/virtiofsd", "/usr/lib/qemu/virtiofsd" }.FirstOrDefault(File.Exists) + ?? Host.Which("virtiofsd") + ?? throw new MicroVmException("virtiofsd is not installed; the MicroVM shares the module through it (the package is virtiofsd)"); + return new MicroVmFiles(Path.Combine(image, "vmlinux"), Path.Combine(image, "initramfs.cpio.gz"), monitor, virtiofsd); + } + + /// <summary>Checks that every file of an image matches its <c>SHA256SUMS</c>.</summary> + public static void CheckImage(string directory) + { + var sums = Path.Combine(directory, "SHA256SUMS"); + if (!File.Exists(sums)) + { + throw new MicroVmException($"{directory} has no SHA256SUMS, so its image cannot be checked"); + } + + var text = File.ReadAllText(sums); + foreach (var name in new[] { "vmlinux", "initramfs.cpio.gz" }) + { + var expected = Sha256Sums.SumFor(text, name, sums) + ?? throw new MicroVmException($"{sums} does not name {name}"); + var path = Path.Combine(directory, name); + if (!File.Exists(path) || !string.Equals(Sha256Sums.Sha256(path), expected, StringComparison.Ordinal)) + { + throw new MicroVmException($"{path} does not match its SHA256SUMS; build or fetch the image again"); + } + } + } + + private static async Task<string> FetchImageAsync(Version tazel, string directory, Action<string> status, CancellationToken cancel) + { + if (File.Exists(Path.Combine(directory, "SHA256SUMS"))) + { + return directory; + } + + var version = tazel.ToString(3); + var name = $"tazel-microvm-{version}-x86_64.tazel.tar.xz"; + var url = $"https://github.com/Progmasoft/tazel/releases/download/tazel-{version}/{name}"; + status($"fetching the MicroVM image {name}"); + var downloads = directory + ".download"; + Directory.CreateDirectory(downloads); + var archive = Path.Combine(downloads, name); + var sums = await DownloadAsync(url + ".sha256sums", archive + ".sha256sums", cancel).ConfigureAwait(false); + await DownloadAsync(url, archive, cancel).ConfigureAwait(false); + var expected = Sha256Sums.SumFor(await File.ReadAllTextAsync(sums, cancel).ConfigureAwait(false), name, url + ".sha256sums"); + if (expected is null || !string.Equals(Sha256Sums.Sha256(archive), expected, StringComparison.Ordinal)) + { + throw new MicroVmException($"{url} does not match its .sha256sums"); + } + + var root = ModuleArchive.Unpack(archive, directory + ".partial", "vmlinux"); + if (Directory.Exists(directory)) + { + Directory.Delete(directory, recursive: true); + } + + Directory.Move(root, directory); + Directory.Delete(downloads, recursive: true); + return directory; + } + + [System.Runtime.Versioning.SupportedOSPlatform("linux")] + private static async Task<string> FetchMonitorAsync(string directory, Action<string> status, CancellationToken cancel) + { + var path = Path.Combine(directory, "cloud-hypervisor"); + if (File.Exists(path) && Sha256Sums.Sha256(path) == MonitorSha256) + { + return path; + } + + status($"fetching Cloud Hypervisor {MonitorVersion}"); + Directory.CreateDirectory(directory); + var url = $"https://github.com/cloud-hypervisor/cloud-hypervisor/releases/download/{MonitorVersion}/cloud-hypervisor-static"; + await DownloadAsync(url, path + ".partial", cancel).ConfigureAwait(false); + var actual = Sha256Sums.Sha256(path + ".partial"); + if (actual != MonitorSha256) + { + File.Delete(path + ".partial"); + throw new MicroVmException($"{url} has the SHA-256 {actual}, not that of Cloud Hypervisor {MonitorVersion}"); + } + + File.SetUnixFileMode(path + ".partial", UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + File.Move(path + ".partial", path, overwrite: true); + return path; + } + + private static async Task<string> DownloadAsync(string url, string path, CancellationToken cancel) + { + using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(10) }; + using var response = await http.GetAsync(new Uri(url), HttpCompletionOption.ResponseHeadersRead, cancel).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + throw new MicroVmException( + $"{url} answered {(int)response.StatusCode}; build the image with dotnet run microvm/build.cs and set TAZEL_MICROVM_IMAGE"); + } + + var file = File.Create(path); + await using (file.ConfigureAwait(false)) + { + await response.Content.CopyToAsync(file, cancel).ConfigureAwait(false); + } + + return path; + } +} + +/// <summary>The MicroVM could not be started or stopped answering.</summary> +public sealed class MicroVmException : Exception +{ + /// <summary>What went wrong.</summary> + public MicroVmException(string message) + : base(message) + { + } + + /// <summary>Nothing to say.</summary> + public MicroVmException() + { + } + + /// <summary>What went wrong, and why.</summary> + public MicroVmException(string message, Exception inner) + : base(message, inner) + { + } +} diff --git a/src/Progmasoft.Tazel/MicroVm/Sandbox.cs b/src/Progmasoft.Tazel/MicroVm/Sandbox.cs new file mode 100644 index 0000000..f8a8ae2 --- /dev/null +++ b/src/Progmasoft.Tazel/MicroVm/Sandbox.cs @@ -0,0 +1,362 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Progmasoft.Tazel.MicroVm; + +/// <summary>A directory of the host the MicroVM sees at the same path.</summary> +/// <param name="Path">The directory.</param> +/// <param name="ReadOnly">Whether the guest may only read it.</param> +internal sealed record SharedDirectory(string Path, bool ReadOnly); + +/// <summary>How big a MicroVM is.</summary> +/// <param name="MemoryMiB">Its memory.</param> +/// <param name="Processors">Its processors.</param> +internal sealed record MicroVmSize(int MemoryMiB, int Processors); + +/// <summary> +/// One MicroVM: Cloud Hypervisor and a virtiofsd per shared directory, each a process of its own, so the death of any +/// of them ends the commands inside with an error and never Tazel. Commands reach the agent over vsock: Tazel connects +/// to the Unix socket of the monitor and asks for the agent's port. +/// </summary> +[System.Runtime.Versioning.SupportedOSPlatform("linux")] +internal sealed class Sandbox : IAsyncDisposable +{ + /// <summary>The environment every command inside gets, and nothing of the host's.</summary> + public static readonly IReadOnlyDictionary<string, string> Environment = new Dictionary<string, string>(StringComparer.Ordinal) + { + ["PATH"] = MicroVmProtocol.DefaultPath, + ["HOME"] = "/root", + ["TMPDIR"] = "/tmp", + ["LANG"] = "C.UTF-8", + }; + + private readonly string _runtime; + private readonly List<Process> _daemons = []; + private readonly Process _monitor; + private readonly string _vsock; + private readonly string _console; + + private Sandbox(string runtime, Process monitor, string vsock, string console) + { + _runtime = runtime; + _monitor = monitor; + _vsock = vsock; + _console = console; + } + + /// <summary>Starts a MicroVM that sees <paramref name="shares"/> and waits until its agent answers.</summary> + public static async Task<Sandbox> StartAsync( + MicroVmFiles files, IReadOnlyList<SharedDirectory> shares, MicroVmSize size, CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(files); + ArgumentNullException.ThrowIfNull(shares); + ArgumentNullException.ThrowIfNull(size); + var runtime = Directory.CreateTempSubdirectory("tazel-microvm-").FullName; + File.SetUnixFileMode(runtime, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + var daemons = new List<Process>(); + try + { + // The guest's /usr is the host's, read-only, and its /etc a few files of Tazel's. + var all = new List<SharedDirectory>(shares) { new("/usr", ReadOnly: true), new(WriteEtc(runtime), ReadOnly: true) }; + var command = new StringBuilder("console=hvc0 quiet panic=0 rdinit=/tazel/agent/ld-musl-x86_64.so.1"); + var arguments = new List<string>(); + for (var i = 0; i < all.Count; i++) + { + var tag = $"s{i}"; + var socket = Path.Combine(runtime, $"{tag}.sock"); + daemons.Add(StartVirtiofsd(files.Virtiofsd, all[i], socket)); + arguments.AddRange(["--fs", $"tag={tag},socket={socket},num_queues=1,queue_size=512"]); + var guestPath = i == all.Count - 1 ? "/etc" : all[i].Path; + command.Append(CultureInfo.InvariantCulture, + $" tazel.share={tag},{(all[i].ReadOnly ? "ro" : "rw")},{MicroVmProtocol.EncodePath(guestPath)}"); + } + + command.Append(" -- --library-path /tazel/lib /tazel/agent/tazel-guest"); + foreach (var share in all.Select((share, i) => (share, i))) + { + await WaitForAsync(Path.Combine(runtime, $"s{share.i}.sock"), daemons[share.i], "virtiofsd", cancel).ConfigureAwait(false); + } + + var vsock = Path.Combine(runtime, "vsock.sock"); + var console = Path.Combine(runtime, "console.log"); + var start = new ProcessStartInfo(files.Monitor) + { + UseShellExecute = false, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var argument in new[] + { + "--kernel", files.Kernel, "--initramfs", files.Initramfs, "--cmdline", command.ToString(), + "--cpus", $"boot={size.Processors}", "--memory", $"size={size.MemoryMiB}M,shared=on", + "--vsock", $"cid=3,socket={vsock}", "--console", $"file={console}", "--serial", "off", + }.Concat(arguments)) + { + start.ArgumentList.Add(argument); + } + + var monitor = Process.Start(start) ?? throw new MicroVmException($"{files.Monitor} could not be started"); + monitor.StandardInput.Close(); + var sandbox = new Sandbox(runtime, monitor, vsock, console); + sandbox._daemons.AddRange(daemons); + await sandbox.WaitUntilReadyAsync(cancel).ConfigureAwait(false); + return sandbox; + } + catch + { + foreach (var daemon in daemons) + { + Kill(daemon); + } + + Directory.Delete(runtime, recursive: true); + throw; + } + } + + /// <summary> + /// Runs <paramref name="arguments"/> in <paramref name="directory"/> inside, with <see cref="Environment"/>; what it + /// prints goes to <paramref name="output"/> and <paramref name="errors"/>. Returns its exit status. + /// </summary> + public async Task<int> RunAsync( + IReadOnlyList<string> arguments, string directory, Stream output, Stream errors, CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(errors); + using var connection = await ConnectAsync(cancel).ConfigureAwait(false); + var stream = new NetworkStream(connection, ownsSocket: false); + await using (stream.ConfigureAwait(false)) + { + await MicroVmProtocol.WriteAsync(stream, MessageKind.Run, + MicroVmProtocol.Encode(new RunRequest(arguments, Environment, directory)), cancel).ConfigureAwait(false); + using var stop = cancel.Register(() => connection.Shutdown(SocketShutdown.Both)); + while (true) + { + var message = await MicroVmProtocol.ReadAsync(stream, CancellationToken.None).ConfigureAwait(false); + switch (message?.Kind) + { + case MessageKind.Output: + var target = message.Value.Payload[0] == 2 ? errors : output; + await target.WriteAsync(message.Value.Payload.AsMemory(1), CancellationToken.None).ConfigureAwait(false); + await target.FlushAsync(CancellationToken.None).ConfigureAwait(false); + break; + case MessageKind.Exit: + return MicroVmProtocol.DecodeStatus(message.Value.Payload); + case MessageKind.Error: + throw new MicroVmException(Encoding.UTF8.GetString(message.Value.Payload)); + case null: + cancel.ThrowIfCancellationRequested(); + throw new MicroVmException($"the MicroVM stopped answering while {arguments[0]} ran{ConsoleTail()}"); + default: + throw new MicroVmException($"the agent sent a message of the kind {message.Value.Kind}"); + } + } + } + } + + /// <summary>Asks the guest to power off, then stops whatever is left.</summary> + public async ValueTask DisposeAsync() + { + try + { + if (!_monitor.HasExited) + { + using var connection = await ConnectAsync(CancellationToken.None, TimeSpan.FromSeconds(2)).ConfigureAwait(false); + var stream = new NetworkStream(connection, ownsSocket: false); + await using (stream.ConfigureAwait(false)) + { + await MicroVmProtocol.WriteAsync(stream, MessageKind.PowerOff, ReadOnlyMemory<byte>.Empty, CancellationToken.None) + .ConfigureAwait(false); + } + + using var wait = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await _monitor.WaitForExitAsync(wait.Token).ConfigureAwait(false); + } + } + catch (Exception error) when (error is MicroVmException or IOException or SocketException or OperationCanceledException) + { + // It does not answer; it is stopped below. + } + finally + { + Kill(_monitor); + foreach (var daemon in _daemons) + { + Kill(daemon); + } + + _monitor.Dispose(); + Directory.Delete(_runtime, recursive: true); + } + } + + private static string WriteEtc(string runtime) + { + var etc = Path.Combine(runtime, "etc"); + Directory.CreateDirectory(etc); + File.WriteAllText(Path.Combine(etc, "passwd"), "root:x:0:0:root:/root:/bin/sh\nnobody:x:65534:65534:nobody:/:/bin/false\n"); + File.WriteAllText(Path.Combine(etc, "group"), "root:x:0:\ntty:x:5:\nnobody:x:65534:\n"); + File.WriteAllText(Path.Combine(etc, "hosts"), "127.0.0.1 localhost tazel\n::1 localhost tazel\n"); + File.WriteAllText(Path.Combine(etc, "hostname"), "tazel\n"); + // The host's tools look for their libraries through the cache of the host's loader. + foreach (var name in new[] { "ld.so.cache", "ld.so.conf" }) + { + if (File.Exists(Path.Combine("/etc", name))) + { + File.Copy(Path.Combine("/etc", name), Path.Combine(etc, name)); + } + } + + return etc; + } + + private static Process StartVirtiofsd(string program, SharedDirectory share, string socket) + { + var start = new ProcessStartInfo(program) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + foreach (var argument in new[] { $"--socket-path={socket}", $"--shared-dir={share.Path}", "--sandbox=namespace", "--cache=auto" } + .Concat(share.ReadOnly ? ["--readonly"] : Array.Empty<string>())) + { + start.ArgumentList.Add(argument); + } + + var process = Process.Start(start) ?? throw new MicroVmException($"{program} could not be started"); + process.OutputDataReceived += (_, _) => { }; + process.ErrorDataReceived += (_, _) => { }; + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + return process; + } + + private static async Task WaitForAsync(string socket, Process daemon, string what, CancellationToken cancel) + { + for (var i = 0; i < 100 && !File.Exists(socket); i++) + { + if (daemon.HasExited) + { + throw new MicroVmException($"{what} ended with {daemon.ExitCode} before it was ready"); + } + + await Task.Delay(50, cancel).ConfigureAwait(false); + } + + if (!File.Exists(socket)) + { + throw new MicroVmException($"{what} did not open {socket} within five seconds"); + } + } + + private async Task WaitUntilReadyAsync(CancellationToken cancel) + { + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(60); + while (DateTime.UtcNow < deadline) + { + if (_monitor.HasExited) + { + var errors = await _monitor.StandardError.ReadToEndAsync(cancel).ConfigureAwait(false); + throw new MicroVmException( + $"Cloud Hypervisor ended with {_monitor.ExitCode} while the MicroVM started: {errors.Trim()}{ConsoleTail()}"); + } + + try + { + using var connection = await ConnectAsync(cancel, TimeSpan.FromSeconds(1)).ConfigureAwait(false); + var stream = new NetworkStream(connection, ownsSocket: false); + await using (stream.ConfigureAwait(false)) + { + await MicroVmProtocol.WriteAsync(stream, MessageKind.Hello, ReadOnlyMemory<byte>.Empty, cancel).ConfigureAwait(false); + if (await MicroVmProtocol.ReadAsync(stream, cancel).ConfigureAwait(false) is { Kind: MessageKind.Ready }) + { + return; + } + } + } + catch (Exception error) when (error is MicroVmException or IOException or SocketException) + { + // The agent is not listening yet. + } + + await Task.Delay(100, cancel).ConfigureAwait(false); + } + + throw new MicroVmException($"the agent of the MicroVM did not answer within a minute{ConsoleTail()}"); + } + + /// <summary>A connection to the agent: Cloud Hypervisor's hybrid vsock takes "CONNECT port" and answers "OK".</summary> + private async Task<Socket> ConnectAsync(CancellationToken cancel, TimeSpan? timeout = null) + { + using var limit = CancellationTokenSource.CreateLinkedTokenSource(cancel); + limit.CancelAfter(timeout ?? TimeSpan.FromSeconds(10)); + var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); + try + { + await socket.ConnectAsync(new UnixDomainSocketEndPoint(_vsock), limit.Token).ConfigureAwait(false); + await socket.SendAsync(Encoding.ASCII.GetBytes($"CONNECT {MicroVmProtocol.Port}\n"), limit.Token).ConfigureAwait(false); + var line = new List<byte>(); + var one = new byte[1]; + while (line.Count < 64) + { + if (await socket.ReceiveAsync(one, limit.Token).ConfigureAwait(false) == 0) + { + throw new MicroVmException("the monitor closed the vsock connection"); + } + + if (one[0] == '\n') + { + break; + } + + line.Add(one[0]); + } + + return Encoding.ASCII.GetString(line.ToArray()).StartsWith("OK ", StringComparison.Ordinal) + ? socket + : throw new MicroVmException("the agent is not listening"); + } + catch + { + socket.Dispose(); + throw; + } + } + + private string ConsoleTail() + { + try + { + var lines = File.Exists(_console) ? File.ReadAllLines(_console) : []; + return lines.Length == 0 ? "" : "; the console of the MicroVM ends with:\n " + string.Join("\n ", lines.TakeLast(8)); + } + catch (IOException) + { + return ""; + } + } + + private static void Kill(Process process) + { + try + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + process.WaitForExit(5000); + } + } + catch (InvalidOperationException) + { + // It ended by itself. + } + } +} diff --git a/src/Progmasoft.Tazel/Output/ErrorCodes.cs b/src/Progmasoft.Tazel/Output/ErrorCodes.cs index dd412bd..335bab1 100644 --- a/src/Progmasoft.Tazel/Output/ErrorCodes.cs +++ b/src/Progmasoft.Tazel/Output/ErrorCodes.cs @@ -75,6 +75,7 @@ internal static partial class ErrorCodes public const string ActionsFailed = "E0501"; public const string NoDaemon = "E0502"; public const string Stopped = "E0503"; + public const string MicroVm = "E0504"; public const string Label = "E0600"; private const string Lexer = "the text files: tazel_custom.txt, tazel_options.txt and tazel_envs.txt"; @@ -238,6 +239,14 @@ internal static partial class ErrorCodes new(Stopped, "the command was stopped", "Ctrl+C or a signal stopped Tazel. The actions that were running were stopped too; what finished is kept, and " + "the next build goes on from there.", null, null, "MODULE.csx, BUILD.csx and builds"), + new(MicroVm, "the MicroVM could not run the command", + "tazel_options.txt asks for sandboxing-with-microvm, so tazel custom runs inside a MicroVM: a Linux guest " + + "under Cloud Hypervisor that sees the module and the host's /usr, read-only, and nothing else of the host. It " + + "needs x86_64 Linux with KVM (/dev/kvm), virtiofsd, and the image of the guest: Tazel fetches the image of its " + + "release and Cloud Hypervisor once and checks them, and TAZEL_MICROVM_IMAGE names an image built with " + + "dotnet run microvm/build.cs. The message says which of these failed. The MicroVM has no network, so " + + "microvm-network: true is refused, and builds, tests and plugins do not run in it, so a sandbox stops them.", + "microvm-network: true;", "microvm-network: false;", "MODULE.csx, BUILD.csx and builds"), new(Label, "a label Tazel cannot read", "A label names a target: //dir:name, //:name, :name in the current package, @dependency//dir:name; //dir/... " + "and //... are patterns of packages. Names hold letters, digits and _ + . -.", diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index 2d44bfe..84d048e 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -62,6 +62,12 @@ internal static class Program reporter.Diagnostic(diagnostic); return 1; } + catch (MicroVm.MicroVmException error) + { + reporter.Error(ErrorCodes.MicroVm, error.Message, null, + "The sandbox stayed shut, and so did the door to your machine."); + return 1; + } catch (Exception error) when (error is ProjectException or LabelException or TazelOptionsException or CustomCommandsException) { diff --git a/src/Shared/MicroVmProtocol.cs b/src/Shared/MicroVmProtocol.cs new file mode 100644 index 0000000..aafe00d --- /dev/null +++ b/src/Shared/MicroVmProtocol.cs @@ -0,0 +1,234 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Progmasoft.Tazel.MicroVm; + +/// <summary>The kinds of message between Tazel and the agent of its MicroVM.</summary> +internal enum MessageKind : byte +{ + /// <summary>Host to guest: run a command; <see cref="RunRequest"/>.</summary> + Run = 1, + + /// <summary>Host to guest: stop the command of this connection.</summary> + Stop = 2, + + /// <summary>Host to guest: write everything out and power off.</summary> + PowerOff = 3, + + /// <summary>Host to guest: are you there? The agent answers <see cref="Ready"/>.</summary> + Hello = 4, + + /// <summary>Guest to host: the agent is up; the payload is its version.</summary> + Ready = 10, + + /// <summary>Guest to host: output of the command; the first byte is 1 for stdout or 2 for stderr.</summary> + Output = 11, + + /// <summary>Guest to host: the command ended; the payload is its exit status, a signal as 128 + its number.</summary> + Exit = 12, + + /// <summary>Guest to host: the command could not run; the payload is why.</summary> + Error = 13, +} + +/// <summary>A command for the guest: its arguments, its whole environment and where it runs.</summary> +/// <param name="Arguments">The program and its arguments; the program is found on the PATH of <paramref name="Environment"/>.</param> +/// <param name="Environment">Every variable the command gets, and nothing else.</param> +/// <param name="Directory">The working directory, inside a shared directory.</param> +internal sealed record RunRequest(IReadOnlyList<string> Arguments, IReadOnlyDictionary<string, string> Environment, string Directory); + +/// <summary> +/// The messages of a MicroVM connection: a kind byte, a little-endian 32-bit length, and the payload. Strings are a +/// length and UTF-8. It is the same file in Tazel and in the agent; no JSON library is needed on either side. +/// </summary> +internal static class MicroVmProtocol +{ + /// <summary>The vsock port the agent listens on.</summary> + public const uint Port = 1024; + + /// <summary>The PATH of commands inside, and the one the agent searches when a command brings none.</summary> + public const string DefaultPath = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; + + /// <summary>A path as <c>tazel.share=</c> writes it on the kernel command line: base64url without padding.</summary> + public static string EncodePath(string path) => + Convert.ToBase64String(Encoding.UTF8.GetBytes(path)).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + /// <summary>Reads a path <see cref="EncodePath"/> wrote.</summary> + public static string DecodePath(string text) + { + ArgumentNullException.ThrowIfNull(text); + var padded = text.Replace('-', '+').Replace('_', '/'); + return Encoding.UTF8.GetString(Convert.FromBase64String(padded + new string('=', (4 - (padded.Length % 4)) % 4))); + } + + /// <summary>The most a payload may hold; a larger length means the stream is broken.</summary> + public const int MaxPayload = 16 * 1024 * 1024; + + /// <summary>Writes one message.</summary> + public static async Task WriteAsync(Stream stream, MessageKind kind, ReadOnlyMemory<byte> payload, CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(stream); + var header = new byte[5]; + header[0] = (byte)kind; + BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(1), payload.Length); + await stream.WriteAsync(header, cancel).ConfigureAwait(false); + if (payload.Length > 0) + { + await stream.WriteAsync(payload, cancel).ConfigureAwait(false); + } + + await stream.FlushAsync(cancel).ConfigureAwait(false); + } + + /// <summary>Reads one message, or null at the end of the stream.</summary> + public static async Task<(MessageKind Kind, byte[] Payload)?> ReadAsync(Stream stream, CancellationToken cancel) + { + ArgumentNullException.ThrowIfNull(stream); + var header = new byte[5]; + if (!await ReadExactlyAsync(stream, header, cancel).ConfigureAwait(false)) + { + return null; + } + + var length = BinaryPrimitives.ReadInt32LittleEndian(header.AsSpan(1)); + if (length < 0 || length > MaxPayload) + { + throw new InvalidDataException($"a message says it holds {length} bytes"); + } + + var payload = new byte[length]; + if (!await ReadExactlyAsync(stream, payload, cancel).ConfigureAwait(false)) + { + throw new EndOfStreamException("the connection ended inside a message"); + } + + return ((MessageKind)header[0], payload); + } + + /// <summary>The payload of <see cref="MessageKind.Run"/>.</summary> + public static byte[] Encode(RunRequest request) + { + ArgumentNullException.ThrowIfNull(request); + using var buffer = new MemoryStream(); + WriteInt(buffer, request.Arguments.Count); + foreach (var argument in request.Arguments) + { + WriteString(buffer, argument); + } + + WriteInt(buffer, request.Environment.Count); + foreach (var (name, value) in request.Environment) + { + WriteString(buffer, name); + WriteString(buffer, value); + } + + WriteString(buffer, request.Directory); + return buffer.ToArray(); + } + + /// <summary>Reads the payload of <see cref="MessageKind.Run"/>.</summary> + public static RunRequest DecodeRun(byte[] payload) + { + ArgumentNullException.ThrowIfNull(payload); + var position = 0; + var count = ReadCount(payload, ref position); + var arguments = new List<string>(count); + for (var i = 0; i < count; i++) + { + arguments.Add(ReadString(payload, ref position)); + } + + var variables = ReadCount(payload, ref position); + var environment = new Dictionary<string, string>(StringComparer.Ordinal); + for (var i = 0; i < variables; i++) + { + var name = ReadString(payload, ref position); + environment[name] = ReadString(payload, ref position); + } + + var directory = ReadString(payload, ref position); + if (position != payload.Length) + { + throw new InvalidDataException("a run message has bytes after its directory"); + } + + return new RunRequest(arguments, environment, directory); + } + + /// <summary>The payload of <see cref="MessageKind.Exit"/>.</summary> + public static byte[] EncodeStatus(int status) + { + var payload = new byte[4]; + BinaryPrimitives.WriteInt32LittleEndian(payload, status); + return payload; + } + + /// <summary>Reads the payload of <see cref="MessageKind.Exit"/>.</summary> + public static int DecodeStatus(byte[] payload) => + payload is { Length: 4 } ? BinaryPrimitives.ReadInt32LittleEndian(payload) : throw new InvalidDataException("an exit message is not 4 bytes"); + + private static void WriteInt(Stream stream, int value) + { + Span<byte> bytes = stackalloc byte[4]; + BinaryPrimitives.WriteInt32LittleEndian(bytes, value); + stream.Write(bytes); + } + + private static void WriteString(Stream stream, string value) + { + var bytes = Encoding.UTF8.GetBytes(value); + WriteInt(stream, bytes.Length); + stream.Write(bytes); + } + + private static int ReadCount(byte[] payload, ref int position) + { + if (payload.Length - position < 4) + { + throw new InvalidDataException("a message ends inside a number"); + } + + var value = BinaryPrimitives.ReadInt32LittleEndian(payload.AsSpan(position)); + position += 4; + return value < 0 || value > payload.Length ? throw new InvalidDataException($"a message holds the count {value}") : value; + } + + private static string ReadString(byte[] payload, ref int position) + { + var length = ReadCount(payload, ref position); + if (payload.Length - position < length) + { + throw new InvalidDataException("a message ends inside a string"); + } + + var value = Encoding.UTF8.GetString(payload, position, length); + position += length; + return value; + } + + private static async Task<bool> ReadExactlyAsync(Stream stream, byte[] buffer, CancellationToken cancel) + { + var read = 0; + while (read < buffer.Length) + { + var count = await stream.ReadAsync(buffer.AsMemory(read), cancel).ConfigureAwait(false); + if (count == 0) + { + return read == 0 ? false : throw new EndOfStreamException("the connection ended inside a message"); + } + + read += count; + } + + return true; + } +} diff --git a/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs b/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs index 3c24229..0b427fa 100644 --- a/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs +++ b/tests/Progmasoft.Tazel.Tests/BuildCommandTests.cs @@ -110,7 +110,7 @@ public sealed class BuildCommandTests module.Write("tazel_options.txt", "sandboxing-with-microvm: true;"); var (status, output) = await module.TazelAsync(".", "build", "//..."); Assert.Equal(1, status); - Assert.Contains("this Tazel has no MicroVM to start, so nothing ran", output, StringComparison.Ordinal); + Assert.Contains("and not builds, tests or plugins, so nothing ran", output, StringComparison.Ordinal); } [Fact] diff --git a/tests/Progmasoft.Tazel.Tests/MicroVmTests.cs b/tests/Progmasoft.Tazel.Tests/MicroVmTests.cs new file mode 100644 index 0000000..6005aa7 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/MicroVmTests.cs @@ -0,0 +1,165 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +extern alias guest; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Agent = guest::Progmasoft.Tazel.Guest.Agent; +using Share = guest::Progmasoft.Tazel.Guest.Share; +using Progmasoft.Tazel.MicroVm; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class MicroVmProtocolTests +{ + [Fact] + public async Task ARunRequestCrossesTheConnectionUnchanged() + { + var request = new RunRequest(["sh", "-c", "echo ü \"x\""], + new Dictionary<string, string>(StringComparer.Ordinal) { ["PATH"] = "/usr/bin", ["EMPTY"] = "" }, "/work/my module"); + using var stream = new MemoryStream(); + await MicroVmProtocol.WriteAsync(stream, MessageKind.Run, MicroVmProtocol.Encode(request), TestContext.Current.CancellationToken); + stream.Position = 0; + var message = await MicroVmProtocol.ReadAsync(stream, TestContext.Current.CancellationToken); + Assert.Equal(MessageKind.Run, message!.Value.Kind); + var read = MicroVmProtocol.DecodeRun(message.Value.Payload); + Assert.Equal(request.Arguments, read.Arguments); + Assert.Equal(request.Environment.OrderBy(e => e.Key), read.Environment.OrderBy(e => e.Key)); + Assert.Equal(request.Directory, read.Directory); + Assert.Null(await MicroVmProtocol.ReadAsync(stream, TestContext.Current.CancellationToken)); + } + + [Fact] + public void AStatusIsFourBytes() + { + Assert.Equal(-1, MicroVmProtocol.DecodeStatus(MicroVmProtocol.EncodeStatus(-1))); + Assert.Throws<InvalidDataException>(() => MicroVmProtocol.DecodeStatus([1, 2])); + } + + [Theory] + [InlineData(new byte[] { 1, 255, 255, 255, 127 })] + [InlineData(new byte[] { 1, 10, 0, 0, 0, 1, 2 })] + public async Task ABrokenStreamIsRefused(byte[] bytes) + { + using var stream = new MemoryStream(bytes); + var error = await Assert.ThrowsAnyAsync<Exception>(() => MicroVmProtocol.ReadAsync(stream, TestContext.Current.CancellationToken)); + Assert.True(error is InvalidDataException or EndOfStreamException, error.GetType().Name); + } + + [Fact] + public void ARunMessageWithBytesLeftOverIsRefused() => + Assert.Throws<InvalidDataException>(() => MicroVmProtocol.DecodeRun( + [.. MicroVmProtocol.Encode(new RunRequest(["x"], new Dictionary<string, string>(), "/")), 0])); + + [Theory] + [InlineData("/home/someone/my module")] + [InlineData("/ü/ö")] + [InlineData("/")] + public void SharesNameTheirPathOnTheKernelCommandLine(string path) + { + var shares = Share.Parse($"console=hvc0 tazel.share=s0,rw,{MicroVmProtocol.EncodePath(path)} quiet tazel.share=s1,ro,{MicroVmProtocol.EncodePath("/usr")}"); + Assert.Equal([new Share("s0", path, false), new Share("s1", "/usr", true)], shares); + } + + [Theory] + [InlineData("tazel.share=s0,rx,Lw")] + [InlineData("tazel.share=s0,rw")] + [InlineData("tazel.share=s0,rw,cmVsYXRpdmU")] + [InlineData("tazel.share=s0,rw,Ly4uL2V0Yw")] + public void AShareThatIsNotRightStopsTheAgent(string word) => + Assert.Throws<FormatException>(() => Share.Parse(word)); + + [Fact] + public void TheAgentRunsOnlyInsideWhatIsSharedForWriting() + { + var agent = new Agent([new Share("s0", "/work/module", false), new Share("s1", "/usr", true)]); + Assert.True(agent.Inside("/work/module")); + Assert.True(agent.Inside("/work/module/sub")); + Assert.False(agent.Inside("/work/module-other")); + Assert.False(agent.Inside("/work/module/../other")); + Assert.False(agent.Inside("/usr/bin")); + } +} + +public sealed class MicroVmFilesTests +{ + [Fact] + public void AnImageThatDoesNotMatchItsSumsIsRefused() + { + using var image = new TemporaryModule().Write("vmlinux", "kernel").Write("initramfs.cpio.gz", "initramfs"); + Assert.Contains("has no SHA256SUMS", Assert.Throws<MicroVmException>(() => MicroVmFiles.CheckImage(image.Root)).Message, + StringComparison.Ordinal); + image.Write("SHA256SUMS", + $"{Archive.Sha256Sums.Sha256(Path.Combine(image.Root, "vmlinux"))} vmlinux\n{new string('0', 64)} initramfs.cpio.gz\n"); + Assert.Contains("initramfs.cpio.gz does not match", Assert.Throws<MicroVmException>(() => MicroVmFiles.CheckImage(image.Root)).Message, + StringComparison.Ordinal); + } + + [Fact] + public async Task ANetworkIsRefusedBeforeAnythingStarts() + { + using var module = new TemporaryModule().Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("tazel_options.txt", "sandboxing-with-microvm: true;\nmicrovm-network: true;\n") + .Write("tazel_custom.txt", "hello: (\"echo\" \"hi\");\n"); + var (status, output) = await module.TazelAsync(".", "custom", "hello"); + Assert.Equal(1, status); + Assert.Contains("error[E0504]", output, StringComparison.Ordinal); + Assert.Contains("has no network, so nothing ran", output, StringComparison.Ordinal); + } + + [Fact] + public async Task BuildsAreStillStoppedByASandbox() + { + using var module = new TemporaryModule().Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("tazel_options.txt", "sandboxing-with-microvm: true;\n"); + var (status, output) = await module.TazelAsync(".", "build", "//..."); + Assert.Equal(1, status); + Assert.Contains("runs tazel custom inside its MicroVM, and not builds, tests or plugins", output, StringComparison.Ordinal); + } +} + +/// <summary> +/// The MicroVM itself, booted: on x86_64 Linux with KVM and an image named by TAZEL_MICROVM_IMAGE, as CI has them. +/// </summary> +public sealed class MicroVmBootTests +{ + private static string? Unavailable() + { + if (!OperatingSystem.IsLinux() || !File.Exists("/dev/kvm")) + { + return "no KVM here"; + } + + return Environment.GetEnvironmentVariable("TAZEL_MICROVM_IMAGE") is { Length: > 0 } ? null : "TAZEL_MICROVM_IMAGE is not set"; + } + + [Fact] + public async Task ACustomCommandRunsInsideAndSeesOnlyTheModule() + { + // CI sets TAZEL_REQUIRE_MICROVM, so a MicroVM that cannot start there fails instead of being skipped. + if (Unavailable() is { } why) + { + Assert.False(Environment.GetEnvironmentVariable("TAZEL_REQUIRE_MICROVM") == "1", why); + Assert.Skip(why); + } + + using var module = new TemporaryModule().Write("MODULE.csx", TemporaryModule.ModuleFile) + .Write("tazel_options.txt", "sandboxing-with-microvm: true;\nmicrovm-memory: 768;\nmicrovm-cpus: 1;\n") + .Write("tazel_custom.txt", """ + inside: s("echo kernel $(uname -r); echo home=$HOME; test -d /home && ls /home | wc -l || echo no-home") ("touch" "made-inside"); + fail: s("exit 7") ("touch" "never"); + """); + var (status, output) = await module.TazelAsync(".", "custom", "inside"); + Assert.True(status == 0, output); + Assert.True(File.Exists(Path.Combine(module.Root, "made-inside")), output); + + (status, output) = await module.TazelAsync(".", "custom", "fail"); + Assert.Equal(7, status); + Assert.False(File.Exists(Path.Combine(module.Root, "never"))); + } +} diff --git a/tests/Progmasoft.Tazel.Tests/Progmasoft.Tazel.Tests.csproj b/tests/Progmasoft.Tazel.Tests/Progmasoft.Tazel.Tests.csproj index 709efb8..b1bec4c 100644 --- a/tests/Progmasoft.Tazel.Tests/Progmasoft.Tazel.Tests.csproj +++ b/tests/Progmasoft.Tazel.Tests/Progmasoft.Tazel.Tests.csproj @@ -12,6 +12,7 @@ <ItemGroup> <ProjectReference Include="../../src/Progmasoft.Tazel/Progmasoft.Tazel.csproj" /> <ProjectReference Include="../../src/Progmasoft.Tazel.Dsl/Progmasoft.Tazel.Dsl.csproj" /> + <ProjectReference Include="../../src/Progmasoft.Tazel.Guest/Progmasoft.Tazel.Guest.csproj" Aliases="guest" /> </ItemGroup> <ItemGroup> <PackageReference Include="xunit.v3" /> diff --git a/tests/Progmasoft.Tazel.Tests/TemporaryModule.cs b/tests/Progmasoft.Tazel.Tests/TemporaryModule.cs index 1a18795..aea8149 100644 --- a/tests/Progmasoft.Tazel.Tests/TemporaryModule.cs +++ b/tests/Progmasoft.Tazel.Tests/TemporaryModule.cs @@ -45,7 +45,8 @@ internal sealed class TemporaryModule : IDisposable public async Task<(int Status, string Output)> TazelAsync(string directory, params string[] arguments) { using var output = new StringWriter(); - var status = await Program.RunAsync([.. arguments, "--color", "never"], Path.Combine(Root, directory), output, + // Before the command: after tazel custom, every word belongs to the custom command. + var status = await Program.RunAsync(["--color", "never", .. arguments], Path.Combine(Root, directory), output, Xunit.TestContext.Current.CancellationToken); return (status, output.ToString()); }