Commit Graph
32 Commits
Author SHA1 Message Date
Michael Crosby bd709ba8cb fix: default to restricted OCI capability set (#786)
Changes the default Linux capability set for container processes from
`.allCapabilities` to `.defaultOCICapabilities`, making the library
secure-by-default. Callers that genuinely need elevated capabilities
must now opt in explicitly.

Signed-off-by: michael_crosby <michael_crosby@apple.com>
2026-07-02 12:45:15 -04:00
Michael Crosby b438e97b93 Add cloud-hypervisor VMM backend for Linux hosts (#782)
apple/containerization currently runs containers in per-container VMs on
macOS hosts via Virtualization.framework. This adds a second VMM backend
so the same Swift orchestration layer (LinuxContainer / LinuxPod /
Vminitd gRPC contract) runs on Linux hosts via cloud-hypervisor + KVM.

**CloudHypervisor Swift package** (`Sources/CloudHypervisor/`) — a thin
client for cloud-hypervisor's REST-over-UDS API, layered on
AsyncHTTPClient. Endpoints cover VMM / VM lifecycle / hotplug (disk, fs,
net, vsock, remove-device). Cross-platform (compiles on macOS for unit
tests; consumed at runtime only by the Linux side of Containerization).

**CH backend in Containerization** — one cloud-hypervisor subprocess per
VM, gated behind `#if os(Linux)`. CHVirtualMachineManager /
CHVirtualMachineInstance mirror the VZ shape behind the existing
VirtualMachineManager / VirtualMachineInstance protocol. CHProcess and
VirtiofsdProcess manage the binaries; CHHotplugProvider handles
virtio-blk and virtio-fs runtime hotplug (with one virtiofsd per unique
source-hash tag, refcounted across containers).

**Linux host networking** — BridgeManager brings up a Linux bridge with
an IPv4 subnet and (opt-in via `--enable-nat`) iptables MASQUERADE +
scoped FORWARD rules. LinuxBridgedNetwork enslaves a fresh TAP per
container to the bridge. State is recorded under `/run/containerization`
so `cctl bridge delete` reverses exactly what create did. Bridge
teardown verifies the link kind via sysfs to refuse deleting non-bridge
interfaces.

**cctl run / bridge** — end-to-end Linux container run path (image pull,
ext4 rootfs assembly, VM boot, container exec) plus `cctl bridge
create|delete` for the host network plumbing.

**Build & dist** — `make linux-build` / `make linux-integration` build
and exercise the host side inside an apple/container `--virtualization`
dev container. `make dist-x86_64` produces a deployment tarball (cctl +
cloud-hypervisor + virtiofsd + initfs + kernel) cross-compiled from the
aarch64 dev container; pipeline documented in `docs/x86_64-build.md`.
Static-musl C deps and the Zig cross compiler are pinned by SHA256.

The host orchestrator runs as root. Per-VM runtime state lives under
`/run/containerization/ch/<UUID>` with mode 0700; UDS sockets inside are
bound with mode 0600. Vminitd's gRPC channel inherits that trust
boundary — socket-file perms are the auth.

Sandbox flags are upstream-secure by default. Two per-component opt-outs
exist for the apple/container dev-container case (where the host seccomp
profile SIGSYS-kills CH and virtiofsd):
- `CONTAINERIZATION_NO_CH_SECCOMP=1` — `cloud-hypervisor --seccomp
false`.
- `CONTAINERIZATION_NO_VIRTIOFSD_SANDBOX=1` — `virtiofsd --sandbox
none`. Each emits a one-shot `logger.warning` at process start. Legacy
alias `CONTAINERIZATION_RELAXED_SANDBOX=1` flips both. cctl spawns both
binaries with `setsid` and a minimal env allowlist (PATH / HOME /
RUST_LOG / RUST_BACKTRACE) so the parent's secrets don't leak to
children.

`make linux-integration` runs the cross-platform integration suite
against a real cloud-hypervisor VM inside the dev container. Linux runs
the cross-platform subset (`process true`/`false`/`echo hi`, virtiofs
round-trip, hotplug); the macOS suite is unchanged.

Signed-off-by: michael_crosby <michael_crosby@apple.com>
2026-07-02 11:20:22 -04:00
Aditya Ramani 44bec8b993 Support disk image based pod volumes (#780)
The `PodVolume` type in `LinuxPod` only defined the `nbd` enum value -
however, disk based images are also supported and the pattern is
essentially the same

Signed-off-by: Aditya Ramani <a_ramani@apple.com>
2026-06-26 10:55:36 -07:00
Aditya Ramani d55cc188ce Allow setting log level for vminitd (#772)
The `--log-level` option when running the agent sub-command for vminitd
was being silently ignored cause of the way the agent is being run. As a
workaround we need to read `/proc/self/cmdline` to get the right args
2026-06-16 18:04:31 -07:00
e1e31b7ae9 add IPv6 support (#752)
Extends the network plumbing to support per-interface IPv6 address
configuration.
The `Interface` protocol supports `ipv6Address` and `ipv6Gateway`.
The agent's networking RPCs carry per-family fields via new
`InterfaceAddress`, `LinkRoute`, and `DefaultRoute` types in
`ContainerizationExtras`.
`NetlinkSession` adds IPv6 methods for address and route operations.

---------

Co-authored-by: michael_crosby <michael_crosby@apple.com>
Co-authored-by: Michael Crosby <crosbymichael@gmail.com>
2026-06-03 12:07:20 -04:00
David Palma 25558e6b85 ImageStore: Preserve source index mediaType on push (#750)
- Closes #749.
- ExportOperation hardcoded the pushed index descriptor's
  mediaType to the OCI image index type. RegistryClient.push
  uses that descriptor's mediaType as the HTTP Content-Type
  header. When the source index was in
  Docker manifest.list.v2+json format (the common case for
  images pulled from Docker Hub and other public registries),
  the body's embedded mediaType field disagreed with the
  header, and OCI registries rejected the index PUT with
  HTTP 400 MANIFEST_INVALID.
- Use the source index's mediaType for the pushed descriptor
  so the header always matches the body. Per-architecture
  child manifests are unaffected because they were already
  pushed with their actual mediaType.
- Add a parameterized unit test for ExportOperation.export
  covering both Docker manifest.list
2026-05-21 17:48:40 -07:00
Michael Crosby 872f601f93 add hotplug interfaces for vmms (#740)
Signed-off-by: michael_crosby <michael_crosby@apple.com>
2026-05-18 10:29:36 -07:00
Yibo Zhuang 9a6f0d4c52 Add support for network block device (NBD) (#690)
This change adds support for attaching network block device (NBD) to
both LinuxContainer and LinuxPod.

For LinuxContainer, whether to use the underlying
`VZNetworkBlockDeviceStorageDeviceAttachment` is determined by the URL
of the container Mount source.

For LinuxPod, adds additional API to support pod-level volumes that can
be mounted into multiple containers. The PodVolume type provides enum to
support multiple types of volume source. LinuxContainer can reference
the pod level volume using the `Mount.sharedMount()` constructor with
the name referencing the name of the pod volume. This will allow the NBD
to be attached to the pod at the VM level and then bind-mounted into the
container.

For integration tests, added a lightweight NBD server implementation in
swift that speaks the NBD protocol to ensure there is sufficient
coverage for the changes introduced.

Apple Virtualization NBD support documentation:

https://developer.apple.com/documentation/virtualization/vznetworkblockdevicestoragedeviceattachment
2026-04-28 10:56:17 -07:00
Danny Canter 0f4c8cf592 Make unit tests runnable on Linux (#686)
Closes #606

This lets the unit tests be runnable on linux. The change:

- Adds a linux-test makefile target so we can run the unit tests locally
- Fixes up some test code to work on Linux (mostly ifdefs)
- Runs the unit tests in CI now
2026-04-15 16:58:03 -07:00
Raj 636715513c Add multi-reference push to ImageStore (#661) 2026-04-07 16:41:58 -07:00
Danny Canter 3c4215702b LinuxContainer/LinuxPod: Sort mounts by depth (#601) 2026-04-03 10:28:47 -07:00
Anthony 35f97f225d Add progress handler for rootfs unpacking (#515)
I've added an optional progress handler for rootfs unpacking so that
consumers can show progress. The Ubuntu image takes about 8 seconds to
unpack on my machine, and I'm developing an app where it would be useful
to show progress in the UI.

Total size is determined in an optional first pass that scans archive
headers. Bytes written are then reported during unpacking. The optional
first pass adds 15 (Alpine) to 115 (Ubuntu) ms to unpacking duration on
my machine, depending on image size.
2026-04-02 17:33:55 -07:00
Maxime Grenu 1951816427 fix(dns): validate nameserver addresses are valid IP addresses (#534)
## What

Add a `DNS.validate()` method that verifies all nameserver entries are
valid IPv4 or IPv6 addresses. The method is called from
`Vminitd.configureDNS()` before applying the configuration.

## Why

Closes #467. Currently, any arbitrary string can be passed as a
nameserver in `DNSConfiguration`, which silently results in an invalid
`/etc/resolv.conf` inside the container. Hostname strings like
`dns.example.com` would be written to resolv.conf but would not work as
nameservers.

## How

- Added `DNS.validate() throws` method in `DNSConfiguration.swift` that
iterates over all nameservers and attempts to parse each as either an
`IPv4Address` or `IPv6Address` (using the existing parsers in
`ContainerizationExtras`)
- Added `import ContainerizationExtras` to `DNSConfiguration.swift` (the
`Containerization` target already depends on `ContainerizationExtras`)
- Called `config.validate()` at the start of `Vminitd.configureDNS()` so
validation happens before any GRPC call

## Testing

Added 6 new unit tests in `DNSTests.swift`:
- ✅ Valid IPv4 nameservers accepted
- ✅ Valid IPv6 nameservers accepted  
- ✅ Mixed IPv4/IPv6 nameservers accepted
- ✅ Empty nameserver list accepted
- ❌ Hostname rejected
- ❌ Invalid address rejected

## Checklist

- [x] Tests added
- [x] No breaking changes to existing API (validate() is a new method,
existing init is unchanged)
- [x] Follows existing patterns (uses ContainerizationExtras IP address
types, ContainerizationError for errors)

Signed-off-by: Maxime Grenu <maxime.grenu@gmail.com>
2026-03-25 02:40:07 -07:00
Danny Canter d8fcd1e9ca Network: Move to standalone type (#584)
The network protocol and VMNetNetwork implementation currently are
housed on ContainerManager even though they are generally useful types
even outside of this easy to use helper type. This change moves them to
not be nested types anymore, as well as exposes a new param on
VMNetNetworks constructor so we can pass the type of network.
2026-03-19 11:33:46 -07:00
Anthony b6b95ac897 Add per-container networking flag to ContainerManager.create() (#549)
This PR adds a `networking: Bool = true` parameter to
`ContainerManager.create()` so callers can opt out of network interface
creation on a per-container basis.

## Motivation

Currently, `ContainerManager.create()` unconditionally allocates a vmnet
network interface for every container (when the manager has a network
configured). Some use cases don't need network access and benefit from
having it disabled to reduce attack surface.

There's no way to achieve this today without either:
- Initializing the `ContainerManager` without a network (which disables
networking for *all* containers)
- Clearing `config.interfaces` in the configuration closure (which
wastes an IP allocation from the vmnet pool since `network.create(id)`
has already been called)

## Changes

- Add `networking: Bool = true` to all three `create()` overloads on
`ContainerManager`
- When `false`, `self.network?.create(id)` is skipped entirely. No
interface is allocated, and no DNS is configured.
- `releaseNetwork`/`delete` remain safe to call regardless, since
`Allocator.release` silently ignores unknown IDs.
- Add unit test `testNetworkingFalseSkipsInterfaceCreation` using the
existing `NilGatewayNetwork` fixture
- Add integration tests `testNetworkingDisabled` and
`testNetworkingEnabled` that create containers through a network-enabled
`ContainerManager` and verify the presence/absence of `eth0` via
`/sys/class/net/`
2026-02-22 17:08:49 -08:00
Manoj Mahapatra 98391937da Guard against if ipv4Gateway is nil, removed fore unwrap (#524)
- Guarded against ipv4Gateway if nil and throw
`ContainerizationError(.invalidState, ...)` instead of force unwraping
- Added a unit test
`ContainerManagerTests.testCreateThrowsWhenGatewayMissing`
2026-02-10 22:20:03 -08:00
J Logan 3e93416b9a Merge commit from fork
* Admit only valid OCI layout files when loading image.

- Adds `AdmissionMapper` protocol for validating archive
  member paths and normalizing them to relative paths
  under the extraction root directory.
- Renames `Reader.swift` to `ArchiveReader.swift` to
  match type name.
- Rework `TempDir` to address `NSString.utf8String`
  deprecation warning in Swift 6.2.3.
- Rework `ArchiveReader.extractContent()` to use an
  `AdmissionMapper` to validate and remap archive
   members before extracting.
- Adds `IdentityAdmissionWrapper` for naive extraction.
- Adds `NoSymlinkAdmissionWrapper` that only extracts
  regular files and directories under the extraction root.
- Adds `OCIImageAdmissionWrapper` that only extracts
  valid OCI image layout paths.
- Use `OCIImageAdmissionWrapper` for `cctl image load`
  and print rejected paths.

* PR feedback.

* Adds public init() for TrustedAdmissionMapper.

* Replace AdmissionMapper with more secure extraction.

- Adds FileDescriptor.mkdirSecure() to prevent
  root escapes on member pathnames, and to prevent
  symlink traversal.
- Adds FileDescriptor.unlinkRecursive() to
  facilitate overwrites when there are multiple
  archive entries with the same member path.
- Adds FileDescriptor.validateSymlinkTargetInRoot()
  to validate that extracted symlink targets do
  not escape the root.
- Rewrite ArchiveReader.extractContents() to use
  secure path functions.

* Remove unneeded symlink check, rename files.

* Simplify the lexical normalizer workaround.

* Reject member paths containing parent traversal components.

* Remove unused lexical normalization workaround.

* Fix leaking fds, extract absolute members as relative.
2026-01-15 12:52:02 -06:00
Kathryn Baldauf ec2ee3e94d Update license header on all files to include the current year (#470)
Related to https://github.com/apple/container/pull/1024

Signed-off-by: Kathryn Baldauf <k_baldauf@apple.com>
2026-01-05 13:08:48 -08:00
RahulThennarasu 4d47c58a3d Fix: Allow OCI archives without manifest annotations (#397)
Fixes #369

Per the OCI Image Spec, manifest descriptor annotations are optional.
Previously, archives without annotations would fail to import with
"Failed to import image".

**Changes:**
- Modified `getImageReferencefromDescriptor` to return digest-based
references (`untagged@sha256:...`) when annotations are missing
- Removed guard that skipped manifests without annotations
- Added test case with `scratch_no_annotations.tar`

**Testing:**
All 167 tests pass, including new test for images without annotations.
2025-11-15 00:32:15 -03:00
Danny Canter 4f996d3509 LinuxContainer: Move Process type out of Configuration (#340)
As a first step to making a pod type, move the nested process
configuration out of LinuxContainer.Configuration.Process and into a
standalone LinuxProcessConfiguration type.
2025-10-20 10:52:48 -07:00
J Logan 995a231348 Removes "all rights reserved" from license header. (#309) 2025-10-03 13:27:59 -07:00
Michael Crosby cb6b78f580 dns config should have options not opts (#303)
Signed-off-by: crosbymichael <michael_crosby@apple.com>
2025-09-29 16:35:58 -04:00
Eric Ernst f92c0cd8c6 containerization: Add additional tests (#273)
Add additional tests, with varying levels of utility.

Before: Overall Code Coverage: 41.73%
After: Overall Code Coverage: 42.95%

Signed-off-by: Eric Ernst <eric_ernst@apple.com>
2025-08-26 13:13:05 -07:00
Aditya Ramani b24b72a7e4 Reference image via sha for test (#190)
CI was failing since the test image we use had a tag re-pushed. Pinning
the test to reference the image version by its sha

---------

Signed-off-by: Aditya Ramani <a_ramani@apple.com>
2025-07-01 17:58:40 -07:00
Kathryn Baldauf 7c063dfbe4 Remove most uses of env variables for image registries (#100)
When we were testing the repo, we added authentication to most of the
registry tests so that we could access private images. Now that the
images are public, this PR removes the use of REGISTRY_TOKEN and
REGISTRY_USERNAME in tests that no longer require authenticating.

Note: REGISTRY_TOKEN, REGISTRY_USERNAME, and REGISTRY_HOST are still
required in the CI to push images and for a few registry tests. So the
env variables are not completely removed. The variables are only used in
the test tool cctl and in our swift tests.

Signed-off-by: Kathryn Baldauf <k_baldauf@apple.com>
2025-06-12 10:16:43 -04:00
Michael Crosby 5d2d7a1bc3 update license header removing new line (#99)
Fixes #63

Signed-off-by: crosbymichael <michael_crosby@apple.com>
2025-06-12 09:57:35 -04:00
Dmitry Kovba f245ae63b3 Improve @SendableProperty (#91)
This PR ensures that we enter a lock inside the `@SendableProperty`
implementation as soon as we access a computed property. Additionally,
it mirrors the access level of the original property. Both changes are
required for [improved
accuracy](https://github.com/apple/container/pull/144) of progress
updates in container. Additionally, it should resolve
https://github.com/apple/containerization/issues/60 that occurs on
certain configurations.

Please tag as 0.1.1 after merging.
2025-06-11 14:13:21 -04:00
Kathryn Baldauf 73596530fe Remove image push tests (#55)
This removes two image push tests. We cannot have the CI push to our
ghcr registry since external users do not have write access for pushing
the image. We will explore a better solution.

Signed-off-by: Kathryn Baldauf <k_baldauf@apple.com>
2025-06-09 17:28:24 -07:00
Dmitry Kovba 8013608979 Resolve a compilation error and warnings in make test (#29) 2025-06-06 14:41:41 -07:00
Danny Canter f49f668936 Updates to license headers (#17)
- Capitalize containerization.
- Wrap "All rights reserved" to a new line.

Signed-off-by: Danny Canter <danny_canter@apple.com>
2025-06-05 16:16:22 -07:00
Kathryn Baldauf 502dab6108 Update containerization apple main (#4)
Signed-off-by: Kathryn Baldauf <k_baldauf@apple.com>
2025-06-05 16:15:44 -07:00
+6 3407cc3f16 initial commit
Co-authored-by: Aditya Ramani <a_ramani@apple.com>
Co-authored-by: Agam Dua <agam_dua@apple.com>
Co-authored-by: Danny Canter <danny_canter@apple.com>
Co-authored-by: Dmitry Kovba <dkovba@apple.com>
Co-authored-by: Eric Ernst <eric_ernst@apple.com>
Co-authored-by: Evan Hazlett <ehazlett@apple.com>
Co-authored-by: Gilbert Song <gilbertsong@apple.com>
Co-authored-by: Hugh Bussell <hbussell@apple.com>
Co-authored-by: John Logan <john_logan@apple.com>
Co-authored-by: Kathryn Baldauf <k_baldauf@apple.com>
Co-authored-by: Madhu Venugopal <mvenugopal@apple.com>
Co-authored-by: Michael Crosby <michael_crosby@apple.com>
Co-authored-by: Sidhartha Mani <sidhartha_mani@apple.com>
Co-authored-by: Tanweer Noor <tnoor@apple.com>
Co-authored-by: Ximena Perez Diaz <xperez528@gmail.com>
Co-authored-by: Yibo Zhuang <yzhuang@apple.com>
2025-06-05 16:15:21 -07:00