Specifications and snippets

sandbox internals for snapd developers

Each security backend builds a fresh specification of one snap by letting the interface repository replay the snap's slots, plugs and connections into it. An interface contributes by having a method named after the backend and the case, such as AppArmorConnectedPlug, which adds snippets scoped to the security tags of the apps and hooks bound to that plug. The backend then fills a template with the snippets, one profile file per tag.

On the map: sandbox internals district

▶ Watch this deck — 8 scenes, ~6 min

Part of journeys

01 From a connection to a profile file

TEMPLATE PLUS SNIPPETS profile "snap.acme-agent.agent" { … /dev/tty[A-Z]*[0-9] rwk, … }boilerplate, and one meter line: from where? interface repositoryacme-agentnetworkmetersnapdacme-gadget AppArmor specificationof acme-agentsnap.acme-agent.agentone specification per backend, built fresh each time network: rules for socketsmeter: rules for serial ports templateprofile … {#include <…/base>…###SNIPPETS###} profile forsnap.acme-agent.agentand one for each hook
The agent's AppArmor profile is boilerplate with one serial-port line; where does it come from? The interface repository holds acme-agent with its network plug connected to snapd and its meter plug connected to acme-gadget; an AppArmor specification of acme-agent collects a network snippet and a meter snippet under snap.acme-agent.agent; the snippets drop into the template's single hole, giving the profile for snap.acme-agent.agent and one for each hook

For each backend, snapd builds a specification of the snap from its plugs, slots and connections. Snippets are filed per app or hook, then fill the backend's template: one profile file per security tag.

Open the agent's AppArmor profile and most of it is boilerplate. So where does the part about the meter come from? Start with acme-agent: its network plug and its meter plug, both connected. For each security backend, snapd builds a fresh, empty specification of the snap, and lets every plug, slot and connection add its snippets. Network adds rules for sockets, then meter adds rules for serial-ports, each filed under the app it belongs to. The template is shared boilerplate with one hole. The snippets drop in, and out comes one profile per app and per hook. Change anything, and it's all built again from scratch.

02 "The repository walk: four calls" for snapd developers

THE REPOSITORY WALK Setup, in each backendrepo.SnapSpecification(b.Name(), appSet, opts)under the repository lock find the backend by namespec := backend.NewSpecification(appSet, opts) for each slotacme-agent has none: skippedAddPermanentSlot → AddConnectedSlot per connection for each plug: networkAddPermanentPlug → AddConnectedPlug(snapd:network) for each plug: meterAddPermanentPlug → AddConnectedPlug(acme-gadget:meter)two plugs, four calls eleven backends with AppArmorone setup walks the snap eleven timesthe first error ends the walk: no specification, nothing written
Each backend's Setup calls repo.SnapSpecification; the repository finds the backend by name and gets a new empty specification, then walks acme-agent: slots first, none here; then the network plug with AddPermanentPlug and AddConnectedPlug for snapd:network, and the meter plug with AddPermanentPlug and AddConnectedPlug for acme-gadget:meter; eleven backends make eleven walks per setup, and any error means nothing is written

SnapSpecification calls AddPermanentSlot, AddConnectedSlot, AddPermanentPlug and AddConnectedPlug on the backend's new spec, under the repository lock. The first error aborts the walk and nothing is written.

Here's the walk inside. Each backend's Setup makes one call into the repository: SnapSpecification. It finds the backend by name and asks it for a new, empty specification. Then it walks the snap, slots first. For each slot it calls AddPermanentSlot once, and AddConnectedSlot once per connection. acme-agent has no slots. Then the plugs: AddPermanentPlug for network, and AddConnectedPlug for its connection to snapd. The same for meter and its gadget slot. Two plugs, four calls. With AppArmor there are eleven backends, so one setup walks the snap eleven times. The first error ends the walk: that backend writes nothing.

03 Does the interface have the method? for snapd developers

THE DEFINER LOOKUP func (spec *Specification) AddConnectedPlug(iface, plug, slot) error {type definer interface {AppArmorConnectedPlug(spec, plug, slot) error}if iface, ok := iface.(definer); ok {tags, err := …SecurityTagsForConnectedPlug(plug)restore := spec.setScope(tags)defer restore()return iface.AppArmorConnectedPlug(spec, plug, slot)}return nil} scope: the security tags bound to this plug networka commonInterface literalconnectedPlugAppArmor: …connectedPlugSecComp: …the struct's methods add them:AppArmorConnectedPlug ✓SecCompConnectedPlug ✓ serial-porthand-writtenUDevPermanentSlotAppArmorConnectedPlugUDevConnectedPlugseccomp: no SecCompConnectedPlug, skipped misspell it as AppArmorConnectPlug: not called, and no errorprefixes: AppArmor SecComp UDev KMod Mount DBus Systemd Polkit Ldconfig Configfiles Symlinks
The AppArmor specification's AddConnectedPlug declares a local definer interface with one method, AppArmorConnectedPlug, type-asserts the interface against it, sets the scope to the plug's security tags and calls it; network is a commonInterface literal whose two string fields become AppArmorConnectedPlug and SecCompConnectedPlug; serial-port writes UDevPermanentSlot, AppArmorConnectedPlug and UDevConnectedPlug by hand and has no seccomp method, so the seccomp spec skips it; a misspelled method is not called and gives no error

Each Add… method type-asserts against a local definer interface, for example one with AppArmorConnectedPlug. Only ldconfig, configfiles and symlinks use an exported type, ConnectedPlugCallback. commonInterface fields such as connectedPlugAppArmor and connectedPlugSecComp become those methods; network is only such a literal.

How does a specification know what an interface contributes? It doesn't ask. Each add method declares, right in its body, a one-method interface with the name it wants, here AppArmorConnectedPlug, and checks whether the interface value has it. If it does, the spec narrows itself to the right security tags and calls it. Network is just a commonInterface value with two strings in it, and the struct's own methods add them. serial-port writes its methods by hand, and has no seccomp method at all. There's no registry and, for most backends, no exported type to implement, so a misspelled method is quietly skipped, with no error.

04 Tags decide where a snippet lands for snapd developers

SECURITY TAGS acme-agent snap.yamlplugs:network:meter:interface: serial-portapps:agent:plugs: [meter]snap.acme-agent.agentsnap.acme-agent.hook.configuresnap.acme-agent.hook.remove networknetworknetworknetwork: top level, so unscoped /dev/tty[A-Z]*[0-9] rwk,meter: listed under agent, so scopedsetScope([snap.acme-agent.agent]) …, TAG+="snap_acme-agent_agent". becomes _ and + becomes __component hooks: snap.acme-agent+<component>.hook.<hook>; a parallel instance puts its instance name in the tag
acme-agent's snap.yaml declares network and meter at the top level and lists meter under the agent app; three lanes for the security tags snap.acme-agent.agent, snap.acme-agent.hook.configure and snap.acme-agent.hook.remove; the unscoped network snippet lands in all three, the meter rule only in the agent's lane after setScope with the agent's tag; the udev rule tags the device with snap_acme-agent_agent

Tags: snap.<instance>.<app>, snap.<instance>.hook.<hook>, snap.<instance>+<component>.hook.<hook>. The spec scopes each call to the tags bound to the plug or slot; the udev tag replaces . with _ and + with __.

Snippets don't go into one big pile. Every profile file belongs to one security tag: one for the agent, one for the configure hook, one for the remove hook. So before calling an interface, the spec narrows its scope to the tags that plug is bound to. Network is declared at the top level and listed nowhere else, so it's bound to everything: the daemon and both hooks get its rules. Meter is listed under the agent, so only the agent's profile gets the serial rule. The udev backend uses the same tag, --dots turned into underscores, to mark the meter's device for the agent alone.

05 Permanent and connected snippets for snapd developers

PERMANENT AND CONNECTED acme-gadgetmeterusb-vendor: 0xabcdusb-product: 0x1234path: /dev/serial-port-metermeteracme-agent UDevPermanentSlotSUBSYSTEM=="tty", SUBSYSTEMS=="usb",ATTRS{idVendor}=="abcd",ATTRS{idProduct}=="1234",SYMLINK+="serial-port-meter"from the moment the gadget is set up AppArmorConnectedPlug/dev/tty[A-Z]*[0-9] rwk,UDevConnectedPlug → TagDevice…, ATTRS{idVendor}=="abcd",ATTRS{idProduct}=="1234",TAG+="snap_acme-agent_agent" from the slot disconnectedthe gadget's rule stays a path-only slot is validated after filepath.Clean, but the raw path is written:path: /dev/./ttyS1 → KERNEL=="./ttyS1", which matches no device
acme-gadget's meter slot with usb-vendor 0xabcd, usb-product 0x1234 and path /dev/serial-port-meter gets a permanent udev symlink rule from UDevPermanentSlot; once connected, acme-agent's meter plug gets the AppArmor rule /dev/tty[A-Z]*[0-9] rwk, and a udev rule built from the slot's vendor and product tagged snap_acme-agent_agent; after a disconnect the agent's rules are gone and the gadget's stays; a path-only slot is validated after filepath.Clean but written raw, so /dev/./ttyS1 gives a rule that matches no device

Permanent definers get snap.PlugInfo or snap.SlotInfo; connected ones get ConnectedPlug and ConnectedSlot with static and dynamic attributes of both sides. Current behaviour: serial-port validates filepath.Clean(path) but writes the raw path into the udev rule, so an unclean path matches no device. The vendor and product values are examples.

Snippets come in two kinds. Permanent ones depend only on a plug or slot existing. So the gadget's meter slot writes its udev symlink rule as soon as the gadget is set up, connected or not. Connected ones run once per connection and see both ends. The agent gets a serial rule in AppArmor, and a udev rule built from the gadget's vendor and product numbers. Disconnect, and the next setup finds no connection: the agent's rules are gone, the gadget's stay. One catch in serial-port: a path-only slot is checked after cleaning the path, but the rule gets it raw, so an unclean path matches no device.

06 The AppArmor template, placeholder by placeholder for snapd developers

THE APPARMOR TEMPLATE defaultCoreRuntimeTemplate, base core22###VAR######PROFILEATTACH### ###FLAGS### {#include <abstractions/base>…###SNIPPETS###} picked by base and confinementother base:defaultOtherBaseTemplateclassic, not jailmode:classicTemplateinterface snippets ignored @{SNAP_NAME}="acme-agent"@{SNAP_REVISION}="…" … profile "snap.acme-agent.agent"flags=(attach_disconnected,mediate_deleted) {+complain in devmode # Description: Can access the network as a client./dev/tty[A-Z]*[0-9] rwk,sorted as text… and coreSnippet on Ubuntu Corethen de-duplicated and parametric rules snap.acme-agent.agentsnap-update-ns.acme-agentgets the AddUpdateNS snippetsboth written to /var/lib/snapd/apparmor/profiles/, mode 0644
The AppArmor template defaultCoreRuntimeTemplate for base core22, with its placeholders replaced in turn: ###VAR### by the snap's variables, ###PROFILEATTACH### by profile snap.acme-agent.agent, ###FLAGS### by attach_disconnected and mediate_deleted, and ###SNIPPETS###, last before the closing brace, by the sorted snippets of network and meter, followed by de-duplicated and parametric rules; other bases use defaultOtherBaseTemplate and classic snaps classicTemplate, which ignores interface snippets; the profile and the separate snap-update-ns.acme-agent profile are written to /var/lib/snapd/apparmor/profiles

Template by base and confinement; ###VAR###, ###PROFILEATTACH###, ###FLAGS###, then ###SNIPPETS### (sorted, then de-duplicated and parametric snippets) last before }. AddUpdateNS text goes to snap-update-ns.<instance>. Under classicTemplate interface snippets are ignored.

Watch the agent's AppArmor profile being made. First the backend picks a template by the snap's base and its confinement. For a classic snap it would pick one that ignores every interface snippet. Then it replaces each placeholder in turn. The variables get the snap's name and revision. The attach line gets the security tag, and the flags get the defaults, plus complain in devmode. Last, just before the closing brace, come the snippets, sorted as text, with de-duplicated and parametric rules after them, so their order follows the text, not the order of connections. The rules that snap-update-ns needs go to a separate profile of their own.

07 "Seccomp: concatenate, then compile" for snapd developers

CONCATENATE, THEN COMPILE snap.acme-agent.agent.src# snap-seccomp version information:a new compiler changes every file @complain (devmode) · @unrestricted (classic)strict, like the agent: no mode line defaultTemplate bind · socket AF_NETLINK - NETLINK_ROUTE · …network's snippet, sorted, duplicates keptmeter adds none: serial-port has no seccomp method uid and gid syscallsthen the bind workaround if AppArmor is not Full snap-seccomp compileonly when the .src changedsnap.acme-agent.agent.bin2snap-confine, at the next start
The seccomp source snap.acme-agent.agent.src is five pieces in a fixed order: the snap-seccomp version header, an optional mode line (@complain for devmode, @unrestricted for classic, none for strict), defaultTemplate, the sorted snippets with network's system calls and none from meter, and the uid and gid system calls; a changed source is compiled by snap-seccomp into snap.acme-agent.agent.bin2, which snap-confine loads at the next start

<tag>.src is the version header, an optional @complain or @unrestricted, defaultTemplate, the sorted snippets, the uid/gid syscalls and workarounds. Changed sources are compiled to <tag>.bin2; snap-confine loads it at the next start.

Seccomp is simpler. There are no placeholders, just pieces put together in a fixed order. The compiler's version comes first, so a new snap-seccomp changes every file and every filter gets rebuilt. Then a mode line: complain for devmode, unrestricted for classic, nothing for a strict snap like the agent. Then the template. Then the snippets, sorted. For the agent that's network's system calls, and nothing from meter. Then the calls for switching users and groups. Only a source that changed is compiled into a binary filter, and snap-confine loads it the next time the agent starts.

08 Where to go from here

ROADS repositoryspecificationtemplateprofile file The security backendswhat each does with its files Setting up a snap's securitywhen, and for which snaps The home interfaceone interface's snippetsInterfaces by classificationhow each is built Interfaces: buses and boardsgadget slots become rules Confinementthe profiles at workHooks: how they workhow plugs are scoped
Roads from Specifications and snippets, attached to the pipeline repository, specification, template, profile file: The security backends, Setting up a snap's security, The home interface, Interfaces by classification, Interfaces: buses and boards, Confinement, and Hooks: how they work

Roads: the security backends, setting up a snap's security, the home interface, interfaces by classification, buses and boards, confinement, and how hooks work.

A specification is a fresh collection of snippets, filed by tag and poured into a template. What each backend then does with its files is in the security backends. When a specification is built, and for which snaps, is in setting up a snap's security. For one interface's snippets in full, see the home interface, and interfaces by classification groups all of them by how they're built. The gadget slots are in buses and boards. Confinement shows the profiles at work, and how hooks work explains how plugs are scoped to hooks.

Read more

The four calls

interfaces.Specification has four methods. Repository.SnapSpecification calls them on the new specification that the backend returns from NewSpecification(appSet, opts), under the repository lock.

MethodCalledReceives
AddPermanentSlotonce for each slot of the snap*snap.SlotInfo: static attributes from snap.yaml
AddConnectedSlotonce for each connection of that slot*ConnectedPlug and *ConnectedSlot: static and dynamic attributes of both ends
AddPermanentPlugonce for each plug of the snap*snap.PlugInfo
AddConnectedPlugonce for each connection of that plug*ConnectedPlug and *ConnectedSlot

Slots are walked first, then plugs. The walk ranges over Go maps, so the order of the calls changes from one walk to the next. The first error ends the walk and the backend reports cannot obtain <backend> specification for snap "<name>": <error>; nothing is written. Every backend's Setup makes its own walk, so one setup of a snap walks it eleven times when AppArmor is available, ten times without it.

A connection whose definer always fails stays in the in-memory repository, so every later setup of that snap fails the same way until snapd restarts (comment at interfaces/repo.go:965-978).

Definers

Each Add… method declares a local one-method interface and type-asserts the interface value against it. The method name is the backend prefix followed by PermanentPlug, PermanentSlot, ConnectedPlug or ConnectedSlot.

BackendPrefix
apparmorAppArmor
seccompSecComp
udevUDev
kmodKMod
mountMount
dbusDBus
systemdSystemd
polkitPolkit
ldconfigLdconfig
configfilesConfigfiles
symlinksSymlinks

Only ldconfig, configfiles and symlinks use an exported type for the plug side, ConnectedPlugCallback; their plug-side definers are accepted only for the system snap. A misspelled method name is not called and gives no error.

commonInterface turns string fields into definers: connectedPlugAppArmor, connectedPlugSecComp, connectedPlugUDev, connectedPlugUpdateNSAppArmor, connectedPlugMount, the four …KModModules lists and flags such as suppressHomeIx and controlsDeviceCgroup. It has plug-side connected definers only for AppArmor, seccomp, udev and mount; slot-side rules need hand-written methods. network is only a commonInterface literal with connectedPlugAppArmor and connectedPlugSecComp. An interface that embeds commonInterface and writes its own AppArmorConnectedPlug hides the embedded one and must call it itself to keep the common fields.

Security tags

RunnableTagudev tag
appsnap.<instance>.<app>snap_<instance>_<app>
hooksnap.<instance>.hook.<hook>snap_<instance>_hook_<hook>
component hooksnap.<instance>+<component>.hook.<hook>snap_<instance>__<component>_hook_<hook>

The udev tag replaces . with _ and + with __. Before calling a definer, the spec sets its scope to the tags of the apps and hooks bound to the plug or slot, and restores it afterwards. A plug declared at the top level and listed under no app or hook is bound to every app and hook. Component hooks receive only such unscoped plugs. When the scope is empty, AddSnippet on the AppArmor, seccomp and dbus specs does nothing.

Some settings are per snap, not per tag, even when the plug is bound to one app: the AppArmor flags set by SetSuppressHomeIx, SetUsesPtraceTrace, SetSuppressPtraceTrace, SetUsesSysModuleCapability, SetSuppressSysModuleCapability and SetSuppressPycacheDeny, the udev SetControlsDeviceCgroup (which drops every udev rule of the snap), and all mount, kmod and polkit content.

for snapd developers

Recording methods

SpecMethods an interface may call
apparmorAddSnippet, AddPrioritizedSnippet, AddDeduplicatedSnippet, AddParametricSnippet, AddUpdateNS, AddUpdateNSf, and the flag setters above
seccompAddSnippet
dbusAddSnippet
udevAddSnippet (untagged rule), TagDevice, TriggerSubsystem, SetControlsDeviceCgroup
mountAddMountEntry, AddUserMountEntry, AddUserEnsureDirs
kmodAddModule, SetModuleOptions, DisallowModule
systemdAddService, AddDropIn
polkitAddPolicy, AddRule
ldconfigAddLibDirs
configfilesAddPathContent
symlinksAddSymlink

The backends add more after the walk: AppArmor and mount add the parallel-instance, layout and extra-layout entries, and AppArmor adds its base prioritized snippets. These are not interface contributions.

TagDevice(snippet) adds, for each tag in scope, # <interface>, the snippet with , TAG+="<udev tag>" appended, and a rule that runs snap-device-helper for devices with that tag.

for snapd developers

Order and duplicates

ContainerOrder in the outputDuplicates
AppArmor AddSnippet, prioritized and base snippetssorted as textkept
AppArmor AddDeduplicatedSnippetinsertion order, after the sorted blockmerged
AppArmor AddParametricSnippettemplates sorted; values in insertion ordervalues merged
AppArmor AddUpdateNSinsertion ordermerged by exact text
seccomp AddSnippetsorted as textkept
dbus AddSnippetinsertion orderkept
udev AddSnippet, TagDevicesorted by tag, then textmerged by exact text
mount AddMountEntryinsertion order; a later different entry at the same mount point is renamed <dir>-2, <dir>-3merged if source and type match

Insertion order is the order of the walk, which ranges over maps.

The AppArmor profile

addContent picks defaultCoreRuntimeTemplate for a core or coreNN base and defaultOtherBaseTemplate otherwise. A classic snap without jailmode gets classicTemplate, which ignores every interface snippet. The placeholders are replaced by function:

PlaceholderReplaced by
###VAR###@{SNAP_NAME}, @{SNAP_INSTANCE_NAME}, @{SNAP_INSTANCE_DESKTOP}, @{SNAP_COMMAND_NAME}, @{SNAP_REVISION}, @{PROFILE_DBUS}, @{INSTALL_DIR}
###PROFILEATTACH###profile "<tag>"
###FLAGS###flags=(attach_disconnected,mediate_deleted), plus unconfined when requested and supported, or complain for devmode and classic without jailmode
###SNIPPETS###the tag's snippets, then extras such as the core snippet on Ubuntu Core and the remote-home and overlay-root snippets

###SNIPPETS### is the last line before the closing brace. Inside the snippets, ###HOME_IX### becomes ix (or nothing if any interface of the snap suppressed it) and ###PROMPT### becomes prompt when prompting applies. The home interface's rule ###PROMPT### owner @{HOME}/[^s.]** rwkl###HOME_IX###, therefore ends up as owner @{HOME}/[^s.]** rwklix,.

One file per tag, mode 0644, in /var/lib/snapd/apparmor/profiles/. The AddUpdateNS text goes into one more profile, snap-update-ns.<instance>, which a classic snap also gets.

The seccomp source

/var/lib/snapd/seccomp/bpf/<tag>.src, mode 0644, is a concatenation:

1. # snap-seccomp version information: and the version line. 2. @unrestricted for classic without jailmode, @complain for devmode without jailmode. 3. defaultTemplate. 4. The tag's snippets, sorted, duplicates kept. A classic snap keeps its snippets here. 5. The uid and gid system calls, per system username where the snap has any. 6. The bind workaround when AppArmor support is not full, and the deprecated socketcall rules when the base needs them.

A changed .src is compiled by snap-seccomp to <tag>.bin2, which snap-confine loads when the app or hook starts. The .bin2 of a removed .src is deleted.

Other files

BackendFile
udev/etc/udev/rules.d/70-snap.<snap>.rules
mount/var/lib/snapd/mount/snap.<snap>.fstab, one per snap

What each backend writes and how it applies it is in The security backends.

Current behaviour to know

serial-port, hidraw, i2c and iio check the slot's path after filepath.Clean, but write the raw value into the rules. A slot with path: /dev/./ttyS1 is accepted and gives KERNEL=="./ttyS1", which matches no device. spi uses the cleaned path everywhere. These slots are limited to core and gadget snaps.

Not covered

The gateway example uses the invented snaps acme-agent and acme-gadget; the usb-vendor and usb-product values are examples. Which rules each interface adds is in the interface decks, not here.

Further reading

No published page describes how specifications are built.

Roads from here

INTERFACES AND CONFINEMENT

INTERFACE FAMILIES · every interface, grouped by what it touches

HOOKS · code snapd runs inside a snap

SANDBOX INTERNALS · the mount namespace