Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

i/builtin: support desktop-file-ids in desktop files rule generation #14444

Merged
2 changes: 1 addition & 1 deletion interfaces/builtin/desktop_legacy.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ func (iface *desktopLegacyInterface) AppArmorConnectedPlug(spec *apparmor.Specif
// interfaces (like desktop-launch), so they are added here with the minimum
// priority, while those other, more privileged, interfaces will add an empty
// string with a bigger privilege value.
desktopSnippet := strings.Join(getDesktopFileRules(plug.Snap().DesktopPrefix()), "\n")
desktopSnippet := strings.Join(getDesktopFileRules(plug.Snap()), "\n")
spec.AddPrioritizedSnippet(desktopSnippet, prioritizedSnippetDesktopFileAccess, desktopLegacyAndUnity7Priority)

return nil
Expand Down
10 changes: 6 additions & 4 deletions interfaces/builtin/desktop_legacy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,6 @@ func (s *DesktopLegacyInterfaceSuite) TestAppArmorSpec(c *C) {
// getDesktopFileRules() rules
c.Assert(spec.SnippetForTag("snap.consumer.app"), testutil.Contains, `# This leaks the names of snaps with desktop files`)
c.Assert(spec.SnippetForTag("snap.consumer.app"), testutil.Contains, `/var/lib/snapd/desktop/applications/ r,`)
c.Assert(spec.SnippetForTag("snap.consumer.app"), testutil.Contains, `/var/lib/snapd/desktop/applications/@{SNAP_INSTANCE_DESKTOP}_*.desktop r,`)
c.Assert(spec.SnippetForTag("snap.consumer.app"), testutil.Contains, `deny /var/lib/snapd/desktop/applications/@{SNAP_INSTANCE_DESKTOP}[^_.]*.desktop r,`)
c.Assert(spec.SnippetForTag("snap.consumer.app"), testutil.Contains, `deny /var/lib/snapd/desktop/applications/[^c]* r,`)
c.Assert(spec.SnippetForTag("snap.consumer.app"), testutil.Contains, `deny /var/lib/snapd/desktop/applications/consume[^r]* r,`)

// connected plug to core slot
appSet, err = interfaces.NewSnapAppSet(s.coreSlot.Snap(), nil)
Expand All @@ -111,3 +107,9 @@ func (s *DesktopLegacyInterfaceSuite) TestStaticInfo(c *C) {
func (s *DesktopLegacyInterfaceSuite) TestInterfaces(c *C) {
c.Check(builtin.Interfaces(), testutil.DeepContains, s.iface)
}

// Test how desktop-legacy interface interacts desktop-file-ids attribute in desktop interface.
var _ = Suite(&desktopFileRulesBaseSuite{
iface: "desktop-legacy",
slotYaml: desktopLegacyCoreYaml,
})
11 changes: 10 additions & 1 deletion interfaces/builtin/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,17 @@ import (
. "gopkg.in/check.v1"

"github.com/snapcore/snapd/interfaces"
"github.com/snapcore/snapd/sandbox/apparmor"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/snaptest"
"github.com/snapcore/snapd/testutil"
)

var (
RegisterIface = registerIface
ResolveSpecialVariable = resolveSpecialVariable
ImplicitSystemPermanentSlot = implicitSystemPermanentSlot
ImplicitSystemConnectedSlot = implicitSystemConnectedSlot
AareExclusivePatterns = aareExclusivePatterns
GetDesktopFileRules = getDesktopFileRules
StringListAttribute = stringListAttribute
PolkitPoliciesSupported = polkitPoliciesSupported
Expand Down Expand Up @@ -146,3 +147,11 @@ func MockPolkitDaemonPaths(path1, path2 string) (restore func()) {
polkitDaemonPath2 = oldDaemonPath2
}
}

func MockApparmorGenerateAAREExclusionPatterns(fn func(excludePatterns []string, opts *apparmor.AAREExclusionPatternsOptions) (string, error)) (restore func()) {
return testutil.Mock(&apparmorGenerateAAREExclusionPatterns, fn)
}

func MockDesktopFilesFromMount(fn func(s *snap.Info) ([]string, error)) (restore func()) {
return testutil.Mock(&desktopFilesFromMount, fn)
}
2 changes: 1 addition & 1 deletion interfaces/builtin/unity7.go
Original file line number Diff line number Diff line change
Expand Up @@ -695,7 +695,7 @@ func (iface *unity7Interface) AppArmorConnectedPlug(spec *apparmor.Specification
// interfaces (like desktop-launch), so they are added here with the minimum
// priority, while those other, more privileged, interfaces will add an empty
// string with a bigger privilege value.
desktopSnippet := strings.Join(getDesktopFileRules(plug.Snap().DesktopPrefix()), "\n")
desktopSnippet := strings.Join(getDesktopFileRules(plug.Snap()), "\n")
spec.AddPrioritizedSnippet(desktopSnippet, prioritizedSnippetDesktopFileAccess, desktopLegacyAndUnity7Priority)
return nil
}
Expand Down
10 changes: 6 additions & 4 deletions interfaces/builtin/unity7_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,6 @@ func (s *Unity7InterfaceSuite) TestUsedSecuritySystems(c *C) {
// getDesktopFileRules() rules
c.Assert(apparmorSpec.SnippetForTag("snap.other-snap.app2"), testutil.Contains, `# This leaks the names of snaps with desktop files`)
c.Assert(apparmorSpec.SnippetForTag("snap.other-snap.app2"), testutil.Contains, `/var/lib/snapd/desktop/applications/ r,`)
c.Assert(apparmorSpec.SnippetForTag("snap.other-snap.app2"), testutil.Contains, `/var/lib/snapd/desktop/applications/@{SNAP_INSTANCE_DESKTOP}_*.desktop r,`)
c.Assert(apparmorSpec.SnippetForTag("snap.other-snap.app2"), testutil.Contains, `deny /var/lib/snapd/desktop/applications/@{SNAP_INSTANCE_DESKTOP}[^_.]*.desktop r,`)
c.Assert(apparmorSpec.SnippetForTag("snap.other-snap.app2"), testutil.Contains, `deny /var/lib/snapd/desktop/applications/[^o]* r,`)
c.Assert(apparmorSpec.SnippetForTag("snap.other-snap.app2"), testutil.Contains, `deny /var/lib/snapd/desktop/applications/other-sna[^p]* r,`)

// connected plugs for instance name have a non-nil security snippet for apparmor
apparmorSpec = apparmor.NewSpecification(s.plugInst.AppSet())
Expand Down Expand Up @@ -124,3 +120,9 @@ func (s *Unity7InterfaceSuite) TestUsedSecuritySystems(c *C) {
func (s *Unity7InterfaceSuite) TestInterfaces(c *C) {
c.Check(builtin.Interfaces(), testutil.DeepContains, s.iface)
}

// Test how unity7 interface interacts desktop-file-ids attribute in desktop interface.
var _ = Suite(&desktopFileRulesBaseSuite{
iface: "unity7",
slotYaml: unity7mockSlotSnapInfoYaml,
})
127 changes: 88 additions & 39 deletions interfaces/builtin/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,12 @@ import (
"fmt"
"path/filepath"
"regexp"
"strings"

"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/interfaces"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/sandbox/apparmor"
"github.com/snapcore/snapd/snap"
)

Expand Down Expand Up @@ -76,61 +79,107 @@ func verifySlotPathAttribute(slotRef *interfaces.SlotRef, attrs interfaces.Attre
return cleanPath, nil
}

// aareExclusivePatterns takes a string and generates deny alternations. Eg,
// aareExclusivePatterns("foo") returns:
//
// []string{
// "[^f]*",
// "f[^o]*",
// "fo[^o]*",
// }
//
// For a more generic version of this see GenerateAAREExclusionPatterns
// TODO: can this be rewritten to use/share code with that function instead?
func aareExclusivePatterns(orig string) []string {
// This function currently is only intended to be used with desktop
// prefixes as calculated by info.DesktopPrefix (the snap name and
// instance name, if present). To avoid having to worry about aare
// special characters, etc, perform ValidateDesktopPrefix() and return
// an empty list if invalid. If this function is modified for other
// input, aare/quoting/etc will have to be considered.
if !snap.ValidateDesktopPrefix(orig) {
return nil
func getDesktopFileRulesFallback() []string {
return []string{
"# Support applications which use the unity messaging menu, xdg-mime, etc",
"# This leaks the names of snaps with desktop files",
fmt.Sprintf("%s/ r,", dirs.SnapDesktopFilesDir),
"# Allowing reading only our desktop files (required by (at least) the unity",
"# messaging menu).",
"# parallel-installs: this leaks read access to desktop files owned by keyed",
"# instances of @{SNAP_NAME} to @{SNAP_NAME} snap",
fmt.Sprintf("%s/@{SNAP_INSTANCE_DESKTOP}_*.desktop r,", dirs.SnapDesktopFilesDir),
"# Explicitly deny access to other snap's desktop files",
fmt.Sprintf("deny %s/@{SNAP_INSTANCE_DESKTOP}[^_.]*.desktop r,", dirs.SnapDesktopFilesDir),
// XXX: Do we need to generate extensive deny rules for the fallback too?
}
ZeyadYasser marked this conversation as resolved.
Show resolved Hide resolved
}

s := make([]string, len(orig))

prefix := ""
for i, letter := range orig {
prefix = orig[:i]
s[i] = fmt.Sprintf("%s[^%c]*", prefix, letter)
}
return s
var apparmorGenerateAAREExclusionPatterns = apparmor.GenerateAAREExclusionPatterns
var desktopFilesFromMount = func(s *snap.Info) ([]string, error) {
opts := snap.DesktopFilesFromMountOptions{MangleFileNames: true}
return s.DesktopFilesFromMount(opts)
ZeyadYasser marked this conversation as resolved.
Show resolved Hide resolved
}

// getDesktopFileRules(<snap instance name>) generates snippet rules for
// allowing access to the specified snap's desktop files in
// dirs.SnapDesktopFilesDir, but explicitly denies access to all other snaps'
// desktop files since xdg libraries may try to read all the desktop files
// in the dir, causing excessive noise. (LP: #1868051)
func getDesktopFileRules(snapInstanceName string) []string {
// getDesktopFileRules generates snippet rules for allowing access to the
// specified snap's desktop files in dirs.SnapDesktopFilesDir, but explicitly
// denies access to all other snaps' desktop files since xdg libraries may try
// to read all the desktop files in the dir, causing excessive noise. (LP: #1868051)
//
// The snap must be mounted.
func getDesktopFileRules(s *snap.Info) []string {
ZeyadYasser marked this conversation as resolved.
Show resolved Hide resolved
baseDir := dirs.SnapDesktopFilesDir

rules := []string{
"# Support applications which use the unity messaging menu, xdg-mime, etc",
"# This leaks the names of snaps with desktop files",
fmt.Sprintf("%s/ r,", baseDir),
}

// Generate allow rules
rules = append(rules,
"# Allowing reading only our desktop files (required by (at least) the unity",
"# messaging menu).",
"# parallel-installs: this leaks read access to desktop files owned by keyed",
"# instances of @{SNAP_NAME} to @{SNAP_NAME} snap",
fmt.Sprintf("%s/@{SNAP_INSTANCE_DESKTOP}_*.desktop r,", baseDir),
"# Explicitly deny access to other snap's desktop files",
fmt.Sprintf("deny %s/@{SNAP_INSTANCE_DESKTOP}[^_.]*.desktop r,", baseDir),
fmt.Sprintf("%s/@{SNAP_INSTANCE_DESKTOP}_*.desktop r,", dirs.SnapDesktopFilesDir),
)
// For allow rules let's be more defensive and not depend on desktop files
// shipped by the snap like what is done below in the deny rules so that if
// a snap figured out a way to trick the checks below it can only shoot
// itself in the foot and deny more stuff.
// Although, given the extensive use of ValidateNoAppArmorRegexp below this
// should never, but still it is better to play it safe with allow rules
ZeyadYasser marked this conversation as resolved.
Show resolved Hide resolved
desktopFileIDs, err := s.DesktopPlugFileIDs()
if err != nil {
logger.Noticef("error: %v", err)
ZeyadYasser marked this conversation as resolved.
Show resolved Hide resolved
return getDesktopFileRulesFallback()
}
for _, desktopFileID := range desktopFileIDs {
// Validate IDs, This check should never be triggered because
// desktop-file-ids are already validated during install.
// But still it is better to play it safe and check AARE characters anyway.
if err := apparmor.ValidateNoAppArmorRegexp(desktopFileID); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wonder if this should perhaps be done in snap.Validate()

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally, Yes. But we don't know if there are snaps already in the store with desktop files with undesired names. adding the check in snap.Validate() could break existing installs (but maybe for such snaps, we should?).

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't we do any validation on the ids? I'm sure there are some checks that we can do just based on dbus rules, no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do validation in the desktop interface's BeforePreparePlug

// https://specifications.freedesktop.org/desktop-entry-spec/latest/file-naming.html
// Desktop file id must be a valid D-Bus name:
// - A sequence of non-empty elements separated by dots
// - None of which starts with a digit
// - Each of which contains only characters from the set [A-Za-z0-9-_]
//
// XXX: dashes "-" are not recommended but supported, should they be removed?
// https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names
var desktopFileIDRegexp = regexp.MustCompile(`^([A-Za-z_-][\w-]*)(\.[A-Za-z_-][\w-]*)*$`)
func (iface *desktopInterface) validateDesktopFileIDs(attribs interfaces.Attrer) error {

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added the check here to avoid depending on other parts working as expected and having the checks validate input standalone without any assumptions.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer this is done in snap.Validate() since any existing snaps should be updated. However, if we are concerned about breaking things too much, we should ensure that review-tools implements similar validation logic for desktop-file-ids so we can avoid snaps being uploaded with anything that might try and abuse this (also recall this needs a snap declaration as well which adds additional protection too).

Copy link
Contributor Author

@ZeyadYasser ZeyadYasser Sep 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No snaps on the store currently should have desktop-file-ids yet, I think we could add a check for them in snap.Validate() and fail hard there during install/pack. I was confused at first and thought this was for existing desktop file names as well.

Copy link
Contributor Author

@ZeyadYasser ZeyadYasser Sep 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I got confused a bit, I don't think we can this check to snap.Validate(). As Samuele mentioned the bad plug will not be there to validate since the snap plugs and slots are sanitized before getting validated so when we reach snap.Validate a bad desktop-file-ids attribute won't be there.

snap.BadInterfaces = make(map[string]string)
SanitizePlugsSlots(snap)

I don't see a clean way of force validating desktop-file-ids because they are sanitized (and disappear if bad) just before validation. Only thing left of them is an error message under info.BadInterfaces that is shown when running snap pack --check-skeleton.

$ snap pack --check-skeleton squashfs-root build
snap "hello" has bad plugs or slots: desktop (desktop-file-ids entry "org.he&&llo.Example" is not a valid D-Bus well-known name)

Maybe I am confused about what is required here, but I think adding validation on the container level snap.validateContainer() for desktop file names on pack/build as @bboozzoo suggested #14444 (comment) is a great idea + checks from review tools to prevent new revision with weird desktop file names.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So it looks like an error here is unexpected and we should return early rather than simply ignore it. snap pack --check-skeleton raises an error with bad plugs/slots, but actual pack does not, which I think was intentional.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated that part to return and error instead of doing the fallback as this indicates something dangerous that the early validation and sanitization was bypassed by the snap.

logger.Noticef("error: %v", err)
ZeyadYasser marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also why not fail and let AppArmorConnectedPlug return an error?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, Since desktop-file-ids is a new concept, I believe we can just fail. but for existing prefixed desktop files we could break some snaps but it would be very rare. A snap with weird desktop file names + unity7/desktop-legacy plugs.

CC: @pedronis @jhenstridge

return getDesktopFileRulesFallback()
}
rules = append(rules, fmt.Sprintf("%s/%s r,", baseDir, desktopFileID+".desktop"))
}

// Generate deny rules to suppress apparmor warnings
desktopFiles, err := desktopFilesFromMount(s)
if err != nil {
logger.Noticef("error: %v", err)
ZeyadYasser marked this conversation as resolved.
Show resolved Hide resolved
return getDesktopFileRulesFallback()
}
if len(desktopFiles) == 0 {
// Nothing to do
return getDesktopFileRulesFallback()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we switch to the fallback in this case?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is to be consistent with the original implementation, which didn't care about existing desktop files.

func getDesktopFileRules(snapInstanceName string) []string {
baseDir := dirs.SnapDesktopFilesDir
rules := []string{
"# Support applications which use the unity messaging menu, xdg-mime, etc",
"# This leaks the names of snaps with desktop files",
fmt.Sprintf("%s/ r,", baseDir),
"# Allowing reading only our desktop files (required by (at least) the unity",
"# messaging menu).",
"# parallel-installs: this leaks read access to desktop files owned by keyed",
"# instances of @{SNAP_NAME} to @{SNAP_NAME} snap",
fmt.Sprintf("%s/@{SNAP_INSTANCE_DESKTOP}_*.desktop r,", baseDir),
"# Explicitly deny access to other snap's desktop files",
fmt.Sprintf("deny %s/@{SNAP_INSTANCE_DESKTOP}[^_.]*.desktop r,", baseDir),
}
for _, t := range aareExclusivePatterns(snapInstanceName) {
rules = append(rules, fmt.Sprintf("deny %s/%s r,", baseDir, t))
}
return rules
}

I know a snap depending on the undocumented behavior that unity7 and desktop-legacy gives it access to list desktop files should not be supported, but who knows what snap will break if that changes?

}
excludeOpts := &apparmor.AAREExclusionPatternsOptions{
Prefix: fmt.Sprintf("deny %s", baseDir),
Suffix: ".desktop r,",
}
excludePatterns := make([]string, 0, len(desktopFiles))
for _, desktopFile := range desktopFiles {
// Check that desktop files found don't contain AARE characters.
// This check should never be triggered because:
// - Prefixed desktop files are sanitized to only contain non-AARE characters
// - Desktop file ids are validated to only contain non-AARE characters
// But still it is better to play it safe and check AARE characters anyway.
if err := apparmor.ValidateNoAppArmorRegexp(desktopFile); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

snap.Validate() is also used when packing a snap, maybe it'd be useful to issue a warning if the there's anything wrong with the desktop files.

Hm I don't recall why we don't do any sanity checks of desktop files in validation code, and rather let them fail during install.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I agree. A warning there wouldn't break existing snaps.

Hm I don't recall why we don't do any sanity checks of desktop files in validation code, and rather let them fail during install.

No idea, I recently landed changes there to validate their file types, but there weren't any other validations. I think without epochs we cannot do better on the container validation side.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A followup material, but we could look into tweaking snap.Validate() interface to pass additional parameter describing the scenario in which it is invoked, and in case of pack/build-time validation fail hard on some new checks we introduce.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A followup material, but we could look into tweaking snap.Validate() interface to pass additional parameter describing the scenario in which it is invoked, and in case of pack/build-time validation fail hard on some new checks we introduce.

This sounds like a great idea.

And we should also extend review-tools to implement similar checks against desktop file names etc.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filed a ticket to track this idea https://warthogs.atlassian.net/browse/SNAPDENG-32333

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just have one comment, I think the desktop file names check should be on the container level, so I think snap.validateContainer() would be more appropriate to add the additional scenario parameter.

logger.Noticef("error: %v", err)
return getDesktopFileRulesFallback()
}
excludePatterns = append(excludePatterns, "/"+strings.TrimSuffix(filepath.Base(desktopFile), ".desktop"))
}
for _, t := range aareExclusivePatterns(snapInstanceName) {
rules = append(rules, fmt.Sprintf("deny %s/%s r,", baseDir, t))
excludeRules, err := apparmorGenerateAAREExclusionPatterns(excludePatterns, excludeOpts)
if err != nil {
logger.Noticef("error: %v", err)
return getDesktopFileRulesFallback()
}
rules = append(rules, "# Explicitly deny access to other snap's desktop files")
rules = append(rules, excludeRules)

return rules
}
Expand Down
Loading
Loading