fix(flatpak): file dialogs and forwarded descriptors work in Flatpak apps (#3190)

* fix(flatpak): file dialogs and forwarded descriptors work in Flatpak apps

Flatpak apps opened from the desktop could not open files: the file
chooser's result went through a document store that cannot mount on
Android, and image loaders started with flatpak-spawn --forward-fd lost
their D-Bus descriptor because the app relaunches sandboxes and only
stdio survived.

- A session document store hands picked files and folders back in place
  instead of failing without a mount.
- The bwrap shim offers its inherited descriptors once over a private
  socket, and the native hook puts them back on their original numbers
  before the program starts.
- The native hook resolves /proc/<pid>/root paths to the other
  process's sandbox, so xdg-desktop-portal reads .flatpak-info and
  identifies the calling app.

* fix(flatpak): check documents against the app's view and harden fd forwarding

The document store hands a picked file back in place only when the
calling app's own sandbox can open it with the requested access, so
paths the app cannot see are refused instead of handed out broken.
/proc/<pid>/root lookups follow links inside that process's view,
duplicated root descriptors keep their mapping, and close_range drops
stale records. Forwarded descriptors survive targets at the fd limit,
truncated offers are ignored, and the shim refuses more descriptors
than one message can carry.

* fix(flatpak): match picked documents by file identity and keep O_NOFOLLOW on process roots

The document store accepts an in-place path only when the app's view
holds the same file (device and inode) as the picked descriptor, and
reads each process root once. A bare /proc/<pid>/root opened with
O_NOFOLLOW is no longer mapped, so it fails like the kernel's link.

* Keep a trailing-slash process root translated and track only directory roots
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-25 03:03:03 -05:00
1 parent 19d8819137
commit 953549704a
14 files changed
+1336 -7

No files matched your search

@@ -3,13 +3,16 @@ import base64
import fcntl
import json
import os
import secrets
import signal
import socket
import struct
import subprocess
import sys
import threading
SOCKET_FILE = "/etc/droiddeck/bwrap-socket"
MAX_FORWARDED_FDS = 253
def socket_name():
@@ -94,6 +97,7 @@ class Spec:
self.json_fds = []
self.keep_fds = []
self.lock_files = []
self.lock_fds = []
self.command = []
self.argv0 = None
self.env_tool = None
@@ -363,6 +367,7 @@ def hold_locks(s):
sys.stderr.write("bwrap: Can't lock file %s: %s\n" % (path, e.strerror))
sys.exit(1)
os.set_inheritable(fd, True)
s.lock_fds.append(fd)
def report_pid(s, pid):
@@ -379,8 +384,28 @@ def report_pid(s, pid):
pass
def bind_flatpak_info(s):
if not s.env.get("DDNATV_ROOT"):
return
for op in s.ops:
if op["t"] != "file" or op["dest"] != "/.flatpak-info":
continue
try:
fd = os.memfd_create("flatpak-info", 0)
except (AttributeError, OSError):
return
data = memoryview(op["data"])
while data:
data = data[os.write(fd, data):]
os.lseek(fd, 0, os.SEEK_SET)
entry = "/proc/%d/fd/%d:/.flatpak-info" % (os.getpid(), fd)
binds = s.env.get("DDNATV_BINDS")
s.env["DDNATV_BINDS"] = binds + "|" + entry if binds else entry
def run_here(s):
report_pid(s, os.getpid())
bind_flatpak_info(s)
for fd in s.json_fds:
os.close(fd)
if s.cwd:
@@ -410,7 +435,53 @@ def recv_exact(sock, n):
return buf
def inherited_fds(s):
own = set(s.info_fds + s.json_fds + s.keep_fds + s.lock_fds)
fds = []
for name in os.listdir("/proc/self/fd"):
fd = int(name)
if fd <= 2 or fd in own:
continue
try:
if os.get_inheritable(fd):
fds.append(fd)
except OSError:
pass
return sorted(fds)
def hand_over(listener, fds):
try:
conn, _ = listener.accept()
except OSError:
return
finally:
listener.close()
with conn:
creds = conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
if struct.unpack("3i", creds)[1] != os.getuid():
return
conn.sendmsg([",".join(map(str, fds)).encode()],
[(socket.SOL_SOCKET, socket.SCM_RIGHTS, struct.pack("%di" % len(fds), *fds))])
def offer_fds(s):
fds = inherited_fds(s)
if not fds:
return
if len(fds) > MAX_FORWARDED_FDS:
sys.stderr.write("bwrap: Too many inherited file descriptors: %d\n" % len(fds))
sys.exit(1)
name = "droiddeck-fds-" + secrets.token_hex(16)
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
listener.bind("\0" + name)
listener.listen(1)
s.env["DROIDDECK_FDS"] = name
threading.Thread(target=hand_over, args=(listener, fds), daemon=True).start()
def run_by_app(s):
offer_fds(s)
ops = []
for op in s.ops:
op = dict(op)
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/python3
import configparser
import os
import stat
import sys
import gi
gi.require_version("Gio", "2.0")
from gi.repository import Gio, GLib
NAME = "org.freedesktop.portal.Documents"
PATH = "/org/freedesktop/portal/documents"
VERSION = 5
PROC = sys.argv[1] if len(sys.argv) > 1 else "/proc"
AS_NEEDED_BY_APP = 1 << 2
DIRECTORY = 1 << 3
FAILED = "org.freedesktop.portal.Error.Failed"
NOT_FOUND = "org.freedesktop.portal.Error.NotFound"
NOT_ALLOWED = "org.freedesktop.portal.Error.NotAllowed"
INVALID = "org.freedesktop.portal.Error.InvalidArgument"
INTROSPECTION = """
<node>
<interface name="org.freedesktop.portal.Documents">
<method name="GetMountPoint"><arg type="ay" direction="out"/></method>
<method name="Add">
<arg type="h" direction="in"/><arg type="b" direction="in"/><arg type="b" direction="in"/>
<arg type="s" direction="out"/>
</method>
<method name="AddNamed">
<arg type="h" direction="in"/><arg type="ay" direction="in"/><arg type="b" direction="in"/>
<arg type="b" direction="in"/><arg type="s" direction="out"/>
</method>
<method name="AddFull">
<arg type="ah" direction="in"/><arg type="u" direction="in"/><arg type="s" direction="in"/>
<arg type="as" direction="in"/><arg type="as" direction="out"/><arg type="a{sv}" direction="out"/>
</method>
<method name="AddNamedFull">
<arg type="h" direction="in"/><arg type="ay" direction="in"/><arg type="u" direction="in"/>
<arg type="s" direction="in"/><arg type="as" direction="in"/><arg type="s" direction="out"/>
<arg type="a{sv}" direction="out"/>
</method>
<method name="GrantPermissions">
<arg type="s" direction="in"/><arg type="s" direction="in"/><arg type="as" direction="in"/>
</method>
<method name="RevokePermissions">
<arg type="s" direction="in"/><arg type="s" direction="in"/><arg type="as" direction="in"/>
</method>
<method name="Delete"><arg type="s" direction="in"/></method>
<method name="Lookup"><arg type="ay" direction="in"/><arg type="s" direction="out"/></method>
<method name="Info">
<arg type="s" direction="in"/><arg type="ay" direction="out"/><arg type="a{sas}" direction="out"/>
</method>
<method name="List"><arg type="s" direction="in"/><arg type="a{say}" direction="out"/></method>
<method name="GetHostPaths"><arg type="as" direction="in"/><arg type="a{say}" direction="out"/></method>
<property name="version" type="u" access="read"/>
</interface>
</node>
"""
def passed_fds(invocation, handles):
fd_list = invocation.get_message().get_unix_fd_list()
fds = fd_list.peek_fds() if fd_list else []
return [fds[h] if 0 <= h < len(fds) else -1 for h in handles]
def usable(fd, flags):
try:
mode = os.fstat(fd).st_mode
except OSError:
return False
return stat.S_ISDIR(mode) if flags & DIRECTORY else stat.S_ISREG(mode)
def app_name(pid):
info = configparser.ConfigParser(interpolation=None)
try:
with open(os.path.join(PROC, pid, "root/.flatpak-info")) as f:
info.read_file(f)
except (OSError, UnicodeDecodeError, configparser.Error):
return None
return info.get("Application", "name", fallback=None)
def root_of(pid):
try:
return os.stat(os.path.join(PROC, str(pid), "root", "."))
except OSError:
return None
def app_pids(app_id):
roots = {pid: root_of(pid) for pid in os.listdir(PROC) if pid.isdigit() and app_name(pid) == app_id}
own = root_of(os.getpid())
apart = [pid for pid, root in roots.items() if not (own and root and os.path.samestat(own, root))]
return apart or list(roots)
def access_mode(permissions):
mode = os.R_OK if "read" in permissions else 0
return mode | os.W_OK if "write" in permissions else mode
def under(path, prefix):
return path == prefix or path.startswith(prefix.rstrip("/") + "/")
def spellings(path):
root = os.environ.get("DDNATV_ROOT", "").rstrip("/")
if root and under(path, root):
path = path[len(root):] or "/"
names = [path]
for bind in filter(None, os.environ.get("DDNATV_BINDS", "").split("|")):
host, _, guest = bind.partition(":")
if host and guest and under(path, guest):
name = host + path[len(guest.rstrip("/")):]
if not (root and under(name, root)) and name not in names:
names.append(name)
return names
def same_file(path, picked):
try:
return os.path.samestat(os.stat(path), picked)
except OSError:
return False
def app_reaches(app_id, path, picked, permissions):
if not app_id:
return True
mode = access_mode(permissions) or os.F_OK
roots = [os.path.join(PROC, pid, "root") for pid in app_pids(app_id)]
return any(same_file(root + name, picked) and os.access(root + name, mode)
for root in roots for name in spellings(path))
def fd_path(fd):
try:
path = os.readlink("/proc/self/fd/%d" % fd)
except OSError:
return None
return path if path.startswith("/") else None
def reachable_in_place(invocation, flags, handles, directories, app_id, permissions):
if not flags & AS_NEEDED_BY_APP:
invocation.return_dbus_error(NOT_ALLOWED, "Documents can only be shared in place")
return False
fds = passed_fds(invocation, handles)
if not all(fd >= 0 and usable(fd, DIRECTORY if directories else flags) for fd in fds):
invocation.return_dbus_error(INVALID, "Invalid fd passed")
return False
if not all(fd_path(fd) and app_reaches(app_id, fd_path(fd), os.fstat(fd), permissions) for fd in fds):
invocation.return_dbus_error(NOT_ALLOWED, "The application can't reach this location without the document store")
return False
return True
def on_call(connection, sender, path, interface, method, params, invocation):
args = params.unpack()
if method == "AddFull":
handles, flags = args[0], args[1]
if reachable_in_place(invocation, flags, handles, False, args[2], args[3]):
invocation.return_value(GLib.Variant("(asa{sv})", ([""] * len(handles), {})))
elif method == "AddNamedFull":
if reachable_in_place(invocation, args[2], [args[0]], True, args[3], args[4]):
invocation.return_value(GLib.Variant("(sa{sv})", ("", {})))
elif method == "Lookup":
invocation.return_value(GLib.Variant("(s)", ("",)))
elif method == "List":
invocation.return_value(GLib.Variant("(a{say})", ({},)))
elif method == "GetHostPaths":
invocation.return_value(GLib.Variant("(a{say})", ({},)))
elif method in ("Add", "AddNamed"):
invocation.return_dbus_error(NOT_ALLOWED, "Documents can only be shared in place")
elif method in ("GrantPermissions", "RevokePermissions", "Delete", "Info"):
invocation.return_dbus_error(NOT_FOUND, "Invalid document id")
else:
invocation.return_dbus_error(FAILED, "No document store mount")
def on_get(connection, sender, path, interface, prop):
return GLib.Variant("u", VERSION) if prop == "version" else None
def main():
loop = GLib.MainLoop()
info = Gio.DBusNodeInfo.new_for_xml(INTROSPECTION).interfaces[0]
bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
bus.register_object(PATH, info, on_call, on_get, None)
Gio.bus_own_name_on_connection(bus, NAME, Gio.BusNameOwnerFlags.DO_NOT_QUEUE, None, lambda *_: loop.quit())
loop.run()
return 1
if __name__ == "__main__":
sys.exit(main())
@@ -66,6 +66,14 @@ ensure_machine_id() {
} 2>/dev/null
ensure_machine_id
write_document_store_service() {
[ -x /usr/local/bin/droiddeck-documents ] || return 0
mkdir -p /usr/local/share/dbus-1/services &&
printf '[D-BUS Service]\nName=org.freedesktop.portal.Documents\nExec=/usr/local/bin/droiddeck-documents\n' \
> /usr/local/share/dbus-1/services/org.freedesktop.portal.Documents.service
} 2>/dev/null
write_document_store_service
write_system_bus_config() {
mkdir -p /run/dbus /usr/local/share/droiddeck
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'