Разрешения песочницы🔗
Одна из основных целей Flatpak - повысить безопасность настольных систем за счет изоляции приложений друг от друга. Это достигается с помощью песочницы и означает, что по умолчанию приложения, запускаемые с Flatpak, имеют чрезвычайно ограниченный доступ к среде хоста. Это включает:
Нет доступа к каким-либо файлам хоста, кроме среды выполнения, приложения,
~/.var/app/$FLATPAK_ID, and$XDG_RUNTIME_DIR/app/$FLATPAK_ID. Только два последних доступны для записи.Нет доступа к сети.
Нет доступа к каким-либо узлам устройства (кроме
/dev/null, etc).Нет доступа к процессам вне песочницы.
Ограниченные счета. Например, приложения не могут использовать нестандартные типы сетевых сокетов или отслеживать другие процессы ptrace.
Ограниченный доступ к экземпляру сеанса D-Bus - приложение может владеть только собственным именем на шине.
Нет доступа к хост-службам, таким как X11, системный D-Bus или PulseAudio.
Большинству приложений, чтобы быть полезными, потребуется доступ к некоторым из этих ресурсов. В первую очередь это делается на этапе завершающей сборки, который можно настроить в разделе finish-args файла манифеста (см. manifestests).
Порталы🔗
Порталы уже упоминались в Основные понятия. Они представляют собой основу для предоставления доступа к ресурсам за пределами песочницы, в том числе:
Открытие файлов с помощью собственного диалогового окна выбора файлов
Открытие URIs
Печать
Отображение уведомлений
Снятие скриншотов
Запрет пользовательского сеанса на завершение, приостановку, простой или отключение
Получение информации о состоянии сети
Во многих случаях порталы используют системный компонент, чтобы неявно запрашивать разрешение у пользователя перед предоставлением доступа к определенному ресурсу. Например, в случае открытия файла выбор файла пользователем с помощью диалогового окна выбора файла интерпретируется как неявное предоставление приложению доступа к любому выбранному файлу.
Такой подход позволяет приложениям избежать необходимости настраивать общий доступ к большим объемам данных или службам и дает пользователям контроль над тем, к чему их приложения имеют доступ.
Interface toolkits like GTK3 and Qt5 implement transparent support for portals, meaning that applications don’t need to do any additional work to use them (it is worth checking which portals each toolkit supports). Applications that aren’t using a toolkit with support for portals can refer to the xdg-desktop-portal API documentation for information on how to use them.
Рекомендации по разрешениям🔗
Примечание
Note, that these permissions are completely static and variable
expansion or substitution (for example in --filesystem or --env)
is not possible.
Хотя разработчики приложений имеют контроль над разрешениями песочницы, которые они хотят настроить, рекомендуется применять передовые методы, которые могут применяться. Например, служба хостинга Flathub предъявляет требования к тому, какие разрешения могут использоваться, а программное обеспечение на хосте может предупреждать пользователей, если используются определенные разрешения.
Следующие рекомендации описывают, какие разрешения можно использовать свободно, какие можно использовать по мере необходимости, а каких следует избегать.
Стандартные разрешения🔗
The following permissions are commonly used by applications.
--allow=bluetooth- Allow access to Bluetooth (AF_BLUETOOTH) sockets--device=dri- отрисовка OpenGL--share=ipc- Share IPC namespace with the host [1]--share=network- Access the network [2]--socket=pulseaudio- Access to PulseAudio. It includes sound input (mic), sound output/playback, MIDI and ALSA sound devices in/dev/snd. This permission can be sensitive in certain situations.--socket=cups- Talk to the CUPS printing system.$CUPS_SERVERor server defined in CUPS’sclient.conf. Falls back to/var/run/cups/cups.sock.--socket=pcsc- Smart card access$PCSCLITE_CSOCK_NAME.--socket=gpg-agent- Talk to the GPG agent running on host. This may allow acquiring additional permissions that can be used to perform priviledged GPG operations. The gives access to the socket ingpgconf --list-dir agent-socket. This is not commonly needed unless the application interacts with GPG such as e-mail clients or GPG frontends.--socket=ssh-auth- Allow access to$SSH_AUTH_SOCK. This is not commonly needed unless the application interacts with SSH such as Git clients or SSH frontends.--socket=inherit-wayland-socket- Inherit the$WAYLAND_SOCKETenvironment variable from the parent process (for example, the compositor). This is not commonly needed unless the application needs access to the parent process’ Wayland state. Input method applications may need this. It’s a very sensitive permission as it prevents Wayland client state from being sandboxed.
Примечание
Applications that do not support native Wayland should use
only --socket=x11 and applications that do, should use
--socket=fallback-x11 and --socket=wayland.
The two configurations here will make the application work on both
X11 and Wayland sessions of the desktop environment.
--socket=wayland- Show windows with Wayland--socket=x11- Show windows using X11--socket=fallback-x11- Show windows using X11, if Wayland is not available, overridesx11socket permission. Note that you must still use--socket=waylandfor wayland permission
Доступ к D-Bus🔗
D-Bus access is filtered by default. The default policy for the session bus
only allows the application to own its own namespace named by
$FLATPAK_ID, subnames of it and org.mpris.MediaPlayer2.$FLATPAK_ID
for MPRIS.
Furthermore, it is only allowed to talk to names matching those patterns,
the bus itself org.freedesktop.DBus and portal APIs of the form
org.freedesktop.portal.*.
Access to the entire bus with --socket=system-bus or
--socket=session-bus stops the filtering and using them is a security
risk. So they must be avoided, unless the application is a development
tool.
flatpak run --log-session-bus $FLATPAK_ID can be used to find the specific
D-Bus permissions needed. See Audit session or system bus traffic
for more information.
Право собственности
Any ownership beyond what is granted by default ie. own namespace and
org.mpris.MediaPlayer2.$FLATPAK_ID is typically unnecessary
although there can be exceptions.
Разговор
It is recommended to use the minimum required talk-name permissions.
Доступ к файловой системе🔗
As a general rule, static and permanent filesystem access should be limited as much as possible. This includes:
Использование порталов в качестве альтернативы общему доступу к файловой системе везде, где это возможно.
Использование доступа только для чтения везде, где это возможно, с использованием параметра
:ro.Using Базовые каталоги XDG to store application’s cache, config and state. Then no additional filesystem access would be required.
Avoiding full home access and instead using XDG directories such as
xdg-musicorxdg-downloadetc.
The following permission options are available:
:ro- read-only access:create- read/write access, and create the directory if it doesn’t exist
Additionally the following permissions are available:
|
Complete host operating system with no exclusions mounted at |
|
|
Access to all toplevel paths and subpaths of |
Paths provided by |
|
Host’s |
Host’s |
|
Host’s |
Mounted at |
|
Access the home directory |
Except |
|
Access an arbitrary path except any reserved path |
Includes any subpaths |
|
Arbitrary path relative to the home directory |
Includes any subpaths |
|
Access the XDG desktop directory |
|
|
Access the XDG documents directory |
|
|
Access the XDG download directory |
|
|
Access the XDG music directory |
|
|
Access the XDG pictures directory |
|
|
Access the XDG public directory |
|
|
Access the XDG videos directory |
|
|
Access the XDG templates directory |
|
|
Access the XDG config directory [3] |
|
|
Access the XDG cache directory [3] |
|
|
Access the XDG data directory [3] |
|
|
Access subdirectories of the XDG runtime directory |
|
Except host, host-etc, host-os paths can be added to all the above
filesystem options. For example, --filesystem=xdg-documents/path.
Other filesystem access guidelines include:
The
--persist=DIRoption can be used to map directories from the user’s home directory into the sandbox filesystem. This only works if the application has nohomeor a broader permission likehostthat includeshome.For example, if an application hardcodes the directory
~/.foo, without anyhomeaccess and no--persistthe directory will be lost from the sandbox once exited due to the filesystem being set up as tmpfs by flatpak unless overriden. A--persist=.foobind mounts~/.fooinside the sandbox to~/.var/app/$FLATPAK_ID/.fooon host thus allowing an app to persistently store data in~/.var/app/$FLATPAK_ID/.foowhich would otherwise be lost.A
--persist=.will persist all directories.This does not support
:create, :ro, :rwsuffixes or special values likexdg-documents. However, the directory will be created by flatpak if it doesn’t already exist.This makes it possible to avoid configuring access to the entire home directory, and can be useful for applications that hardcode file paths in
~/.If an application uses
$TMPDIRto contain lock files you may want to add a wrapper script that sets it to$XDG_RUNTIME_DIR/app/$FLATPAK_ID(tmpfs) or/var/tmp(persistent on host).Сохранение и совместное использование конфигурация с установкой отличной от Flatpak следует избегать.
Reserved Paths🔗
The following paths and subpaths of them are reserved and asking access
to them with --filesystem will have no effect:
/app, /bin, /dev, /etc, /lib, /lib32, /lib64, /proc, /run/flatpak, /run/host, /sbin, /usr
The entire /run is not allowed but all subpaths of /run except
/run/flatpak, /run/host are allowed to be exposed via
--filesystem. Additionally, if /var/run on the host is a symlink to
../run, exposing it or a subpath of it, is not allowed.
Additionally the following directories from host need to be explicitly
requested with --filesystem and are not available with
home, host, host-os, host-etc by default:
~/.var/app- The app can access only its own directory in~/.var/app/$FLATPAK_ID$XDG_DATA_HOME/flatpak(~/.local/share/flatpak)/boot/efi/root/sys- Only/sys/block, /sys/bus, /sys/class, /sys/dev, /sys/devicesare shared as read-only by default (if exists)/tmp/var- Note that by default/var/{cache, config, data, tmp}inside the sandbox are the same as~/.var/app/$FLATPAK_ID/{cache, config, data, cache/tmp}. However an explicit--filesystem=/varwill make only/varfrom host available and those will no longer be available./var/lib/flatpak-/vardoes not give access to this.
Доступ к устройству🔗
You can provide the following device permissions:
|
Direct Rendering Interface. Necessary for GL. |
|
Kernel based Virtual Machine |
|
Shared Memory in |
|
Input devices as exposed in |
|
Raw USB devices as exposed in |
|
All devices, including all of the above except |
Примечание
Using newer permissions like input or usb will have no effect
on older Flatpak versions and will fail when used through Flatpak
commandline.
While not ideal, --device=all can be used to access devices like
webcams, CD/DVD drives etc.
USB portal🔗
Since 1.15.11.
Sandboxed access to individual USB devices can be controlled by portals. Flatpak allows specifying enumerable USB devices to allow access.
Like --device=usb, this is just about accessing the raw USB
device, that needs libusb (or equivalent). By using the portal, you
can restrict which device can be requested (enumerable) and then
request an explicit permission to access. For example, if you run a
scanner driver, there is no reason for USB security devices to be
accessible.
A list of valid use cases includes scanners (handled, for example by SANE), photo cameras (handled by libgphoto2), flashing devices, etc.
While this is portal dependent and xdg-desktop-portal is currently
the only portal implementation, the overall permission flow is as
follows:
The Flatpak package specifies the devices it wishes to enumerate through
finish-args.The application requests the portal to enumerate the available USB devices based on that list. If the list is empty it will enumerate all USB devices.
When the application wants to access the device, it will make a request for the device it wants to access via the portal.
The portal then requests permission from the user if not already granted.
If the permission was granted, a file descriptor for the device is passed back to the application.
The application is then able to open the devices it is supposed to use while the others would be hidden.
Specifying the enumerable devices🔗
You can specify devices on the flatpak command line, and by
extension in the finish arguments for Flatpak Builder. Enumerable
devices are specified with a query passed with --usb= while hidden
devices are specified with a query passed with --nousb=. The
hidden list takes precedence over the enumerable list, like an
exception list. The goal is to be able to specify a broad range and
then exclude the few devices that shall not be enumerated.
Queries are made out of rules. These rules are composable with +.
The rule all enumerates every USB device. There is no further rule
allowed in the query.
The vnd and dev rules specify a USB vendor and a USB device ID
respectively. A vendor can be specified alone, but a device rule
always comes with a vendor rule as a device ID is only unique within a
vendor. Vendor and device ID are specified with 4 digit hex
numbers. For more information about the USB IDs, you can refer to the
Linux USB ID repository
cls specifies the device USB class and subclass. Both class and
subclass are two digit hex numbers separated by a colon :. You
can use * to specify any subclass within the class.
Some examples of the syntax:
vnd:1234: Devices from vendor1234vnd:1234+dev:3456: Only device3456from vendor1234.vnd:1234+cls:06:*: All the PTP devices from vendor1234.cls:06:*: All the PTP devices.
This permission only allows to enumerate devices. To open them, permission must be requested from the portal. It is not possible to open a device that is not enumerable.
Примечание
The --device=usb permission is broader than what the USB portal
is supposed to provide and allows unfettered access to any USB
device on the bus.
In some situations you may need to specify a very long list of devices.
Device lists can be passed in one single argument, or through a file.
When using --usb-list, the queries are separated by a semi-colon
;, with queries for hidden devices (i.e. those that would be
passed with --nousb) prefixed with !.
When using --usb-list-file, the filename of the file containing
USB queries is passed line by line. Like with --usb-list queries
for hidden devices are prefixed with !. Empty lines and lines
starting with a # are ignored. When used with flatpak override
or flatpak build-finish the file is no longer needed afterwards as
the list is persisted internally.
доступ к dconf🔗
По состоянию на xdg-desktop-portal 1.1.0 и glib 2.60.5 (во время выполнения) вам не нужен прямой доступ DConf в большинстве случаев.
На данный момент эта версия glib включена в org.freedesktop.Platform//19.08 and org.gnome.Platform//3.34 и новее.
Если приложение существовало до этих runtimes, вы можете сообщить flatpak (>= 1.3.4), чтобы перенести настройки DConf на хосте в песочницу, добавив --metadata=X-DConf=migrate-path=/org/example/foo/ в finish-args. Путь должен быть похож на ваше ID приложения или его не допущено (случай игнорируется и _ и - , обработанные одинаково).
Если вы нацеливаете более старые runtimes или требуют прямых доступа DConf по другим причинам, вы можете использовать эти разрешения:
--filesystem=xdg-run/dconf
--filesystem=~/.config/dconf:ro
--talk-name=ca.desrt.dconf
--env=DCONF_USER_CONFIG_DIR=.config/dconf
С этими разрешениями glib продолжит использовать dconf напрямую.
If you use a newer runtime where dconf is no longer built and still need it
you will have to build the dconf GIO module
and set --env=GIO_EXTRA_MODULES=/app/lib/gio/modules/.
gvfs-доступ🔗
Начиная с gvfs 1.48, демоны и приложения gvfs используют для связи сокет на диске, а не абстрактный сокет, поэтому инфраструктура gvfs продолжает работать, когда поддержка сети отключена в изолированной программной среде приложения.
В зависимости от того, как приложение использует gvfs, необходимо передать ряд различных параметров.
--talk-name=org.gtk.vfs.* необходим для связи с демонами gvfs через D-Bus и составления списка подключений с использованием GIO APIs.
--filesystem=xdg-run/gvfsd необходимо использовать API-интерфейсы GIO для просмотра и доступа к неродным файлам с использованием API-интерфейсов GIO, используя URL-адреса, а не пути FUSE.
--filesystem=xdg-run/gvfs необходим для предоставления доступа к монтированию FUSE, которое могут использовать не-GIO и устаревшие приложения. Это то, что заставит родные файлы появиться в /run/user/`id -u`/gvfs/.
Типичные приложения GNOME и GTK должны использовать:
--talk-name=org.gtk.vfs.*
--filesystem=xdg-run/gvfsd
Типичные приложения, отличные от GNOME и GTK, должны использовать:
--filesystem=xdg-run/gvfs
Ни одно приложение не должно использовать --talk-name=org.gtk.vfs в своем манифесте, так как нет сервисов D-Bus с именем org.gtk.vfs.
These permission grants the app, the ability to communicate with the
gvfs daemon and backends running on host. Depending on the backends
installed or running on host, it grants the ability to list mounted
devices (USB, optical etc.), detach/format/eject them, mount them
locally, read and write data. This is usually used with network storages
like WebDAV, Google Drive, SMB etc. but backends exist for MTP/PTP,
USB,
special locations like trash:// and the
local filesystem
too. So the app can access, read and write data from all of these
locations provided the daemon and backends are installed and running
on host.
External drive access🔗
External drives are mounted by the host system using systemd, udev, udisk fstab etc. and each of them can have different defaults. Flatpak has no control over how and where they get mounted. The following filesystem permissions should work in most cases:
--filesystem=/media
--filesystem=/run/media
--filesystem=/mnt
If --filesystem=host is used /media, /run/media is shared
automatically if they exist.
Note that these should not have subpaths in them unless the value of the subpath can be consistently pre-determined. Block device naming depends on the kernel/fstab configuration and cannot be pre-determined.
Conditional permissions🔗
Since 1.17.0, Flatpak supports conditional permissions which allows them to be granted only when certain runtime conditions are satisfied and fallback otherwise. The intention of the system is to allow users or developers to specify tighter permission grants (as they are added in new Flatpak versions) while fallback to older grants for backwards compatibility at run time.
Примечание
Older Flatpak versions will fail when encountering unknown commandline options, while unrecognized metadata entries will be silently ignored.
Flatpak manifests using conditional flags (for example,
--socket-if= etc.) will require Flatpak 1.17.0 or newer to
build and attempting to build them with older Flatpak versions will
produce an error.
The following flags are available to specify conditional permissions in CLI and in Flatpak manifests:
--socket-if=
--device-if=
--share-if=
--allow-if=
The syntax of all the options are --socket-if=PERMISSION:CONDITION
and so on where PERMISSION is the available grants for that flag
(e.g., those listed for --socket=). Conditions can be negated by
prefixing with !. The following conditions are supported:
true- Always evaluates to truefalse- Always evaluates to falsehas-input-device- True if the Flatpak version supports--device=inputhas-wayland- True if the current desktop session supports Wayland
Multiple conditionals can be specified for the same grant, in which
case the permission is granted if any condition matches. If no
conditional rule evaluates to true, the grant is denied
unless it is also unconditionally allowed. Duplicate conditions are
ignored.
Examples🔗
If an application requires only access to
inputdevice permission, the following flags can be used to move away from--device=allto--device=input:- --device-if=all:!has-input-device - --device=input
This allows older Flatpak versions which do not understand the
inputdevice permission to function by having the broaderallaccess. Newer Flatpak versions which understand the conditional system (and therefore understands theinputpermission) will denyalldue to--device-if=all:!has-input-deviceand allow onlyinputdue to--device=input.The following permissions can be used to restrict from
--device=allto--device=usbin a backwards compatible way if only access tousbis required:- --device-if=all:!has-usb-device - --device=usb
The following permission can be used to restrict to
--device=usbif the portal is available and falling back to--device=usbif not:- --device-if=usb:!has-usb-portal
To explicitly deny a permission that might be granted through runtime
metadata or overrides --nosocket=NAME, --unshare=NAME etc. can be
used:
- --nosocket=x11
This denial can be combined with conditional grants to remove unconditional access while allowing conditional access:
- --nosocket=x11
- --socket-if=x11:!has-wayland
This denies unconditional X11 access but allows X11 conditionally when Wayland is unavailable. Older Flatpak versions will see only the final X11 grant and allow X11 unconditionally, while newer versions recognise the conditional logic and evaluates it at runtime.
Footnotes