Files
snapd/interfaces/system_key_test.go
Oliver Calder 0ff642e82e many: include prompt prefix in apparmor rules (#13822)
* features,i/{apparmor,builtin}: include prompt prefix in home interface

If prompting is supported and enabled, include the prompt prefix in
AppArmor rules for the home interface, which will cause AppArmor to send
a prompt when accessing any file in $HOME.

In the future, if other interfaces include the ###PROMPT### prefix in
their rule snippets, this will also be handled accordingly.

At the moment, the status of prompting support is checked whenever the
AppArmor backend prepares profiles. This is okay, since AppArmor support
for prompting depends on kernel and parser features, which are only
probed once after snapd starts. However, to ensure that the same
supported value is used even if that were not the case, and in case we
wish to only use the prompt prefix for some snaps or interfaces, we may
wish to embed whether to use the prompt prefix in the AppArmor
Specification instead.

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* features: adjust unsupported messages when checking apparmor features errors

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* interfaces: add prompting status to system key

Include whether prompting is supported and enabled as a single field in
the system key. This way, if `(supported && enabled)` changes, security
profiles will be regenerated when snapd starts up.

Currently, prompting support only changes when the AppArmor kernel or
parser features change, and profile regeneration is the only other place
where it is checked whether AppArmor prompting is supported and enabled.
Thus, including whether prompting is supported and enabled in the system
key ensures that security profiles are regenerated when necessary during
snapd startup, and only when necessary (e.g. not if support changed but
prompting flag remained disabled nor if flag changed but prompting
remained unsupported).

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* o/c/configcore: restart snapd when prompting value changes

When the prompting flag changes and the result entails that security
profiles should be regenerated, restart snapd to do so.

This is required iff prompting is supported and the experimental
apparmor-prompting flag changes -- if prompting is not supported,
prompting can't be used, so no need to regenerate profiles. Importantly,
prompting support is based entirely on the available AppArmor kernel and
parser features, and these are only probed once during snapd startup, so
prompting support cannot change (under the current implementation)
except when snapd restarts.

Since `(supported && enabled)` is part of the system key, and a restart
is only triggered if prompting is supported and the flag value changes
(which is equivalent to `(supported && enabled)`, since the supported
value cannot change while snapd is running), restarting after the flag
has changed causes the system key to be different, and thus to trigger a
security profile regeneration, as desired.

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* interfaces,o/ifacestate: set prompting in apparmor spec

Rather than checking whether AppArmor prompting is supported and enabled
whenever the AppArmor backend is processing a snippet, instead include
that precomputed value in the Specification itself, and place it there
via `buildConfinementOptions`. This way, any spec created with the same
`confinementOptions` will make the same decision as to whether to
include prompt prefixes on relevant rules.

Currently, `buildConfinementOptions` simply checks whether prompting is
supported and enabled via the methods on `features.AppArmorPrompting`,
but ideally, this value would be looked up from either the system key
or by checking whether the prompting listener is running. It remains to
be seen how the value computed as part of the system key can be
guaranteed to be the same as that used elsewhere, either in
`buildConfinementOptions` or when deciding whether to start the
listener.

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* o/c/configcore: request snapd restart whenever prompting flag changes

Previously, a snapd restart was only requested when the status of the
"apparmor-prompting" experimental feature flag changed and prompting was
supported. However, since prompting support is dependent on AppArmor
kernel and parser features which are probed only once during startup,
and systems which do not use vendored AppArmor may have had an update to
the system AppArmor package which newly supports AppArmor prompting, it
is safer to request a restart of snapd to re-check for prompting
support.

This way, if one is enabling prompting for the first time on a system
without prompting support, they can have snapd installed, update their
kernel or apparmor installation to support prompting, and then set the
prompting flag to enable prompting without needing to manually restart
snapd.

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* interfaces: support optional trailing space after ###PROMPT###

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

i/apparmor: move promptReplacer definition to before its use

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* tests: add test of restart behavior when setting experimental.apparmor-prompting

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* tests: refactor prompting test to reset failed count and safely check for restarts

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

tests: add shellcheck exception for apparmor prompting flag restart test

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* tests: check that snapd PID != 0 and use snap changes to wait for feature change to complete

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* tests: check for start-limit-hit before calling reset-failed

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* tests: add ubuntu core to apparmor prompting flag restart test

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* tests: check apparmor-prompting value after setting it unchanged

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* Revert "tests: check for start-limit-hit before calling reset-failed"

This reverts commit bea68516c3287fa44d6718f0794484746ae99ac5.

* tests: check systemd start-limit-hit when apparmor-prompting flag changed

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* o/configstate/configcore: add unit tests for doExperimentalApparmorPromptingDaemonRestart

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* i/builtin: add missing prompt prefix and adjust test

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* i/apparmor: add test for prompt prefix substitution

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* many: pass prompting value into system key functions

As such, we now precompute whether prompting is supported and enabled in
`InterfaceManager.StartUp()`, store it in the `InterfaceManager`
instance, and pass it into the call to `WriteSystemKey()`.

Additionally, we make `buildConfinementOptions` a method of
`InterfaceManager`, thus eliminating the need to check within the system
key functions whether prompting is supported and enabled.

However, there remains a problem that `snap run` calls
`SystemKeyMismatch()`, which previously invoked
`apparmor.ParserFeatures()` via `AppArmorPrompting.IsSupported()`, and
now calls `AppArmorPrompting.IsSupported()` directly and passes the
result into `SystemKeyMismatch()`. In either case, we really want this
to be avoided if at all possible, since `snap run` does not have access
to the cached value from the `InterfaceManager`, and thus must invoke
the `apparmor_parser` binary to check parser features whenever we want
to run any snap.

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* many: don't probe parser features when checking system key mismatch

Since `snap run` calls `SystemKeyMismatch()`, we want to avoid needing
to call `AppArmorPrompting.IsSupported()` if at all possible, since this
calls `apparmor.ParserFeatures()`, which executes the `apparmor_parser`
binary. We can and should call `AppArmorPrompting.IsSupported()` when
writing the system key, but not when checking for a mismatch.

The system key written to disk should correctly hold the list of kernel
and parser features, the parser mtime, and whether or not prompting was
previously supported and enabled. We can check whether apparmor parser
features have changed by checking the parser mtime, without needing to
probe parser features -- this optimization is already used by
`SystemKeyMismatch()`. If we knew whether prompting was previously
supported (regardless of whether it was enabled), then so long as the
parser and kernel features are unchanged, we know that prompting support
is also unchanged.

Thus, if we add a second prompting-related field to the system key, this
one storing whether prompting is supported (ignoring enabled), we can
check if prompting support is unchanged without needing to call
`AppArmorPrompting.IsSupported()`.

Furthermore, `SystemKeyMismatch()` is the function in question, and if
there is any mismatch detected, it should return such as soon as
possible, regardless of what the mismatch is. Therefore, if we know that
either kernel or parser features have changed, then we can immediately
return that there is a mismatch, and we don't need to check whether
those feature changes affect prompting support.

Therefore, the new cases which we must worry about when checking for a
system key mismatch are the following, when all other system key fields
are unchanged (note that prompting must be supported in order to be
supported&&enabled):

1. supported: F, supported&&enabled: F, newFlag: F, mismatch: F
2. supported: F, supported&&enabled: F, newFlag: T, mismatch: F
3. supported: T, supported&&enabled: F, newFlag: F, mismatch: F
4. supported: T, supported&&enabled: F, newFlag: T, mismatch: T
5. supported: T, supported&&enabled: T, newFlag: F, mismatch: T
6. supported: T, supported&&enabled: T, newFlag: T, mismatch: F

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* interfaces: fix test string formatting

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* o/configstate/configcore: adjust prompting-related comments

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* tests: increase prompting check_snapd_restarted timeout and add systemd show

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* tests: reset start limit when checking if snapd restarted after prompting change

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* many: add system key extra data to hold prompting enabled status

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* many: only store one apparmor prompting value in system key

When checking for a system key mismatch, use the stored AppArmor
parser features from the system key on disk (along with the kernel
features from the newly-generated key) to check whether prompting is
supported, and AND that with the `AppArmorPrompting` value passed in
with the `SystemKeyExtraData`. If the kernel or parser features have
changed, the system key will be a mismatch anyway, so it is perfectly
safe to use the existing parser features to check for prompting support.

As such, the functions to check for prompting support have been moved
from `features` to `sandbox/apparmor`, and the support check has been
separated from the call to get `ParserFeatures()` and
`KernelFeatures()`, so that the values from the system key can be passed
in instead of invoking those functions.

Using the system key's stored parser and kernel features, there is no
need to save whether prompting is supported as part of the system key,
simplifying the key and the logic used to set the prompting value.

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* tests: explicitly install jq in apparmor-prompting-flag-restart test

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* many: consolidate checks for apparmor prompting support

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* interfaces,s/apparmor: use features struct when checking prompting support

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* tests: improve logging in apparmor-prompting-flag-restart test

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

* tests: fix prompting flag restart test on core18

For some reason, when snapd fails due to start-limit-hit on core18, the
snapd.failure.service starts and acquires the state lock, thus
preventing snapd from successfully becoming "active" again and leaving
it retrying at "activating". It is unclear why this happens on core18
and not elsewhere.

As a fix, when resetting the start limit, stop snapd.failure.service
manually to ensure that snapd can successfully start.

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>

---------

Signed-off-by: Oliver Calder <oliver.calder@canonical.com>
2024-06-11 18:13:00 +01:00

569 lines
16 KiB
Go

// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2018-2024 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package interfaces_test
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
. "gopkg.in/check.v1"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/features"
"github.com/snapcore/snapd/interfaces"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/sandbox/apparmor"
"github.com/snapcore/snapd/sandbox/cgroup"
"github.com/snapcore/snapd/sandbox/seccomp"
"github.com/snapcore/snapd/testutil"
)
type systemKeySuite struct {
testutil.BaseTest
tmp string
apparmorFeatures string
buildID string
seccompCompilerVersion seccomp.VersionInfo
}
var _ = Suite(&systemKeySuite{})
func (s *systemKeySuite) SetUpTest(c *C) {
s.BaseTest.SetUpTest(c)
s.tmp = c.MkDir()
dirs.SetRootDir(s.tmp)
err := os.MkdirAll(filepath.Dir(dirs.SnapSystemKeyFile), 0755)
c.Assert(err, IsNil)
err = os.MkdirAll(dirs.DistroLibExecDir, 0755)
c.Assert(err, IsNil)
err = os.Symlink("/proc/self/exe", filepath.Join(dirs.DistroLibExecDir, "snapd"))
c.Assert(err, IsNil)
s.apparmorFeatures = filepath.Join(s.tmp, "/sys/kernel/security/apparmor/features")
s.buildID = "this-is-my-build-id"
s.seccompCompilerVersion = seccomp.VersionInfo("123 2.3.3 abcdef123 -")
testutil.MockCommand(c, filepath.Join(dirs.DistroLibExecDir, "snap-seccomp"), fmt.Sprintf(`
if [ "$1" = "version-info" ]; then echo "%s"; exit 0; fi
exit 1
`, s.seccompCompilerVersion))
s.AddCleanup(seccomp.MockActions([]string{"allow", "errno", "kill", "log", "trace", "trap"}))
}
func (s *systemKeySuite) TearDownTest(c *C) {
s.BaseTest.TearDownTest(c)
dirs.SetRootDir("/")
}
func (s *systemKeySuite) testInterfaceWriteSystemKey(c *C, remoteFSHome, overlayRoot bool) {
var overlay string
if overlayRoot {
overlay = "overlay"
}
restore := interfaces.MockIsHomeUsingRemoteFS(func() (bool, error) { return remoteFSHome, nil })
defer restore()
restore = interfaces.MockReadBuildID(func(p string) (string, error) {
c.Assert(p, Equals, filepath.Join(dirs.DistroLibExecDir, "snapd"))
return s.buildID, nil
})
defer restore()
restore = interfaces.MockIsRootWritableOverlay(func() (string, error) { return overlay, nil })
defer restore()
restore = cgroup.MockVersion(1, nil)
defer restore()
promptingSupported := features.AppArmorPrompting.IsSupported()
promptingEnabled := true
extraData := interfaces.SystemKeyExtraData{
AppArmorPrompting: promptingEnabled,
}
err := interfaces.WriteSystemKey(extraData)
c.Assert(err, IsNil)
systemKey, err := os.ReadFile(dirs.SnapSystemKeyFile)
c.Assert(err, IsNil)
kernelFeatures, _ := apparmor.KernelFeatures()
apparmorFeaturesStr, err := json.Marshal(kernelFeatures)
c.Assert(err, IsNil)
apparmorParserMtime, err := json.Marshal(apparmor.ParserMtime())
c.Assert(err, IsNil)
parserFeatures, _ := apparmor.ParserFeatures()
apparmorParserFeaturesStr, err := json.Marshal(parserFeatures)
c.Assert(err, IsNil)
apparmorPromptingStr, err := json.Marshal(promptingSupported && promptingEnabled)
c.Assert(err, IsNil)
seccompActionsStr, err := json.Marshal(seccomp.Actions())
c.Assert(err, IsNil)
compiler, err := seccomp.NewCompiler(func(name string) (string, error) {
return filepath.Join(dirs.DistroLibExecDir, "snap-seccomp"), nil
})
c.Assert(err, IsNil)
seccompCompilerVersion, err := compiler.VersionInfo()
c.Assert(err, IsNil)
c.Assert(seccompCompilerVersion, Equals, s.seccompCompilerVersion)
c.Check(string(systemKey), testutil.EqualsWrapped, fmt.Sprintf(`{"version":%d,"build-id":"%s","apparmor-features":%s,"apparmor-parser-mtime":%s,"apparmor-parser-features":%s,"apparmor-prompting":%s,"nfs-home":%v,"overlay-root":%q,"seccomp-features":%s,"seccomp-compiler-version":"%s","cgroup-version":"1"}`,
interfaces.SystemKeyVersion,
s.buildID,
apparmorFeaturesStr,
apparmorParserMtime,
apparmorParserFeaturesStr,
apparmorPromptingStr,
remoteFSHome,
overlay,
seccompActionsStr,
seccompCompilerVersion,
))
}
func (s *systemKeySuite) TestInterfaceWriteSystemKeyNoRemoteFS(c *C) {
s.testInterfaceWriteSystemKey(c, false, false)
}
func (s *systemKeySuite) TestInterfaceWriteSystemKeyWithRemoteFS(c *C) {
s.testInterfaceWriteSystemKey(c, true, false)
}
func (s *systemKeySuite) TestInterfaceWriteSystemKeyWithOverlayRoot(c *C) {
s.testInterfaceWriteSystemKey(c, false, true)
}
// bonus points to someone who actually runs this
func (s *systemKeySuite) TestInterfaceWriteSystemKeyWithRemoteFSWithOverlayRoot(c *C) {
s.testInterfaceWriteSystemKey(c, true, true)
}
func (s *systemKeySuite) TestInterfaceWriteSystemKeyErrorOnBuildID(c *C) {
restore := interfaces.MockIsHomeUsingRemoteFS(func() (bool, error) { return false, nil })
defer restore()
restore = interfaces.MockReadBuildID(func(p string) (string, error) {
c.Assert(p, Equals, filepath.Join(dirs.DistroLibExecDir, "snapd"))
return "", fmt.Errorf("no build ID for you")
})
defer restore()
extraData := interfaces.SystemKeyExtraData{}
err := interfaces.WriteSystemKey(extraData)
c.Assert(err, ErrorMatches, "no build ID for you")
}
func (s *systemKeySuite) TestInterfaceSystemKeyMismatchHappy(c *C) {
s.AddCleanup(interfaces.MockSystemKey(`
{
"build-id": "7a94e9736c091b3984bd63f5aebfc883c4d859e0",
"apparmor-features": ["caps", "dbus"]
}
`))
extraData := interfaces.SystemKeyExtraData{
AppArmorPrompting: true,
}
// no system-key yet -> Error
c.Assert(osutil.FileExists(dirs.SnapSystemKeyFile), Equals, false)
_, err := interfaces.SystemKeyMismatch(extraData)
c.Assert(err, Equals, interfaces.ErrSystemKeyMissing)
// create a system-key -> no mismatch anymore
err = interfaces.WriteSystemKey(extraData)
c.Assert(err, IsNil)
mismatch, err := interfaces.SystemKeyMismatch(extraData)
c.Assert(err, IsNil)
c.Check(mismatch, Equals, false)
// change our system-key to have more apparmor features
s.AddCleanup(interfaces.MockSystemKey(`
{
"build-id": "7a94e9736c091b3984bd63f5aebfc883c4d859e0",
"apparmor-features": ["caps", "dbus", "more", "and", "more"]
}
`))
mismatch, err = interfaces.SystemKeyMismatch(extraData)
c.Assert(err, IsNil)
c.Check(mismatch, Equals, true)
}
func (s *systemKeySuite) TestInterfaceSystemKeyMismatchParserMtimeHappy(c *C) {
s.AddCleanup(interfaces.MockSystemKey(`
{
"build-id": "7a94e9736c091b3984bd63f5aebfc883c4d859e0",
"apparmor-parser-mtime": 1234
}
`))
extraData := interfaces.SystemKeyExtraData{}
// no system-key yet -> Error
c.Assert(osutil.FileExists(dirs.SnapSystemKeyFile), Equals, false)
_, err := interfaces.SystemKeyMismatch(extraData)
c.Assert(err, Equals, interfaces.ErrSystemKeyMissing)
// create a system-key -> no mismatch anymore
err = interfaces.WriteSystemKey(extraData)
c.Assert(err, IsNil)
mismatch, err := interfaces.SystemKeyMismatch(extraData)
c.Assert(err, IsNil)
c.Check(mismatch, Equals, false)
// change our system-key to have a different parser mtime
s.AddCleanup(interfaces.MockSystemKey(`
{
"build-id": "7a94e9736c091b3984bd63f5aebfc883c4d859e0",
"apparmor-parser-mtime": 5678
}
`))
mismatch, err = interfaces.SystemKeyMismatch(extraData)
c.Assert(err, IsNil)
c.Check(mismatch, Equals, true)
}
func (s *systemKeySuite) TestInterfaceSystemKeyMismatchAppArmorPromptingHappy(c *C) {
s.AddCleanup(interfaces.MockSystemKey(`
{
"build-id": "7a94e9736c091b3984bd63f5aebfc883c4d859e0",
"apparmor-prompting": false
}
`))
extraData := interfaces.SystemKeyExtraData{
AppArmorPrompting: true,
}
// no system-key yet -> Error
c.Assert(osutil.FileExists(dirs.SnapSystemKeyFile), Equals, false)
_, err := interfaces.SystemKeyMismatch(extraData)
c.Assert(err, Equals, interfaces.ErrSystemKeyMissing)
// create a system-key -> no mismatch anymore
err = interfaces.WriteSystemKey(extraData)
c.Assert(err, IsNil)
// Even though prompting flag is enabled, since prompting unsupported,
// both prompting-related fields will still be false.
mismatch, err := interfaces.SystemKeyMismatch(extraData)
c.Assert(err, IsNil)
c.Check(mismatch, Equals, false)
for _, testCase := range []struct {
supported bool // previously (and currently) supported
prevValue bool // previously supported and enabled
newValue bool // new "enabled" value
mismatch bool // whether there should be a mismatch
}{
{
supported: false,
prevValue: false,
newValue: false,
mismatch: false,
},
{
supported: false,
prevValue: false,
newValue: true,
mismatch: false,
},
{
supported: true,
prevValue: false,
newValue: false,
mismatch: false,
},
{
supported: true,
prevValue: true,
newValue: false,
mismatch: true,
},
{
supported: true,
prevValue: false,
newValue: true,
mismatch: true,
},
{
supported: true,
prevValue: true,
newValue: true,
mismatch: false,
},
} {
s.AddCleanup(interfaces.MockSystemKey(fmt.Sprintf(`
{
"build-id": "7a94e9736c091b3984bd63f5aebfc883c4d859e0",
"apparmor-prompting": %t
}
`, testCase.prevValue)))
restore := interfaces.MockApparmorPromptingSupportedByFeatures(func(apparmorFeatures *apparmor.FeaturesSupported) (bool, string) {
return testCase.supported, ""
})
extraData = interfaces.SystemKeyExtraData{
AppArmorPrompting: testCase.prevValue,
}
err = interfaces.WriteSystemKey(extraData)
c.Assert(err, IsNil)
extraData = interfaces.SystemKeyExtraData{
AppArmorPrompting: testCase.newValue,
}
mismatch, err = interfaces.SystemKeyMismatch(extraData)
c.Assert(err, IsNil)
c.Check(mismatch, Equals, testCase.mismatch, Commentf("test case: %+v", testCase))
restore()
}
}
func (s *systemKeySuite) TestInterfaceSystemKeyMismatchVersions(c *C) {
// we calculate v1
s.AddCleanup(interfaces.MockSystemKey(`
{
"version":1,
"build-id": "7a94e9736c091b3984bd63f5aebfc883c4d859e0"
}`))
// and the on-disk version is v2
err := os.WriteFile(dirs.SnapSystemKeyFile, []byte(`
{
"version":2,
"build-id": "7a94e9736c091b3984bd63f5aebfc883c4d859e0"
}`), 0644)
c.Assert(err, IsNil)
extraData := interfaces.SystemKeyExtraData{}
// when we encounter different versions we get the right error
_, err = interfaces.SystemKeyMismatch(extraData)
c.Assert(err, Equals, interfaces.ErrSystemKeyVersion)
}
func (s *systemKeySuite) TestStaticVersion(c *C) {
// this is a static check to ensure we remember to bump the
// version when we add fields
//
// *** IF THIS FAILS, YOU NEED TO BUMP THE VERSION BEFORE "FIXING" THIS ***
var sk interfaces.SystemKey
// XXX: this checks needs to become smarter once we remove or change
// existing fields, in which case the version will gets a bump but the
// number of fields decreases or remains unchanged
c.Check(reflect.ValueOf(sk).NumField(), Equals, interfaces.SystemKeyVersion)
c.Check(fmt.Sprintf("%+v", sk), Equals, "{"+strings.Join([]string{
"Version:0",
"BuildID:",
"AppArmorFeatures:[]",
"AppArmorParserMtime:0",
"AppArmorParserFeatures:[]",
"AppArmorPrompting:false",
"NFSHome:false",
"OverlayRoot:",
"SecCompActions:[]",
"SeccompCompilerVersion:",
"CgroupVersion:",
}, " ")+"}")
}
func (s *systemKeySuite) TestRecordedSystemKey(c *C) {
_, err := interfaces.RecordedSystemKey()
c.Check(err, Equals, interfaces.ErrSystemKeyMissing)
restore := interfaces.MockSystemKey(`
{
"build-id": "7a94e9736c091b3984bd63f5aebfc883c4d859e0",
"apparmor-features": ["caps"]
}
`)
defer restore()
extraData := interfaces.SystemKeyExtraData{}
c.Assert(interfaces.WriteSystemKey(extraData), IsNil)
// just to ensure we really re-read it from the disk with RecordedSystemKey
interfaces.MockSystemKey(`{"build-id":"foo"}`)
key, err := interfaces.RecordedSystemKey()
c.Assert(err, IsNil)
sysKey, ok := key.(*interfaces.SystemKey)
c.Assert(ok, Equals, true)
c.Check(sysKey.BuildID, Equals, "7a94e9736c091b3984bd63f5aebfc883c4d859e0")
}
func (s *systemKeySuite) TestCurrentSystemKey(c *C) {
restore := interfaces.MockSystemKey(`{"build-id": "7a94e9736c091b3984bd63f5aebfc883c4d859e0"}`)
defer restore()
key, err := interfaces.CurrentSystemKey()
c.Assert(err, IsNil)
sysKey, ok := key.(*interfaces.SystemKey)
c.Assert(ok, Equals, true)
c.Check(sysKey.BuildID, Equals, "7a94e9736c091b3984bd63f5aebfc883c4d859e0")
}
func (s *systemKeySuite) TestSystemKeysMatch(c *C) {
_, err := interfaces.SystemKeysMatch(nil, nil)
c.Check(err, ErrorMatches, `SystemKeysMatch: arguments are not system keys`)
restore := interfaces.MockSystemKey(`{"build-id": "7a94e9736c091b3984bd63f5aebfc883c4d859e0"}`)
defer restore()
key1, err := interfaces.CurrentSystemKey()
c.Assert(err, IsNil)
_, err = interfaces.SystemKeysMatch(key1, nil)
c.Check(err, ErrorMatches, `SystemKeysMatch: arguments are not system keys`)
_, err = interfaces.SystemKeysMatch(nil, key1)
c.Check(err, ErrorMatches, `SystemKeysMatch: arguments are not system keys`)
interfaces.MockSystemKey(`{"build-id": "8888e9736c091b3984bd63f5aebfc883c4d85988"}`)
key2, err := interfaces.CurrentSystemKey()
c.Assert(err, IsNil)
ok, err := interfaces.SystemKeysMatch(key1, key2)
c.Assert(err, IsNil)
c.Check(ok, Equals, false)
key3, err := interfaces.CurrentSystemKey()
c.Assert(err, IsNil)
ok, err = interfaces.SystemKeysMatch(key2, key3)
c.Assert(err, IsNil)
c.Check(ok, Equals, true)
}
func (s *systemKeySuite) TestSystemKeysUnmarshalSame(c *C) {
restore := interfaces.MockApparmorPromptingSupportedByFeatures(func(apparmorFeatures *apparmor.FeaturesSupported) (bool, string) {
return true, ""
})
defer restore()
appArmorPrompting := true
extraData := interfaces.SystemKeyExtraData{
AppArmorPrompting: appArmorPrompting,
}
// whitespace here simulates the serialization across HTTP, etc. that should
// not trigger any differences
// use a full system-key to fully test serialization, etc.
systemKeyJSON := fmt.Sprintf(`
{
"apparmor-features": [
"caps",
"dbus",
"domain",
"file",
"mount",
"namespaces",
"network",
"network_v8",
"policy",
"ptrace",
"query",
"rlimit",
"signal"
],
"apparmor-parser-features": [],
"apparmor-parser-mtime": 1589907589,
"apparmor-prompting": %t,
"build-id": "cb94e5eeee4cf7ecda53f8308a984cb155b55732",
"cgroup-version": "1",
"nfs-home": false,
"overlay-root": "",
"seccomp-compiler-version": "e6e309ad8aee052e5aa695dfaa040328ae1559c5 2.4.3 9b218ef9a4e508dd8a7f848095cb8875d10a4bf28428ad81fdc3f8dac89108f7 bpf-actlog",
"seccomp-features": [
"allow",
"errno",
"kill_process",
"kill_thread",
"log",
"trace",
"trap",
"user_notif"
],
"version": 11
}`, appArmorPrompting)
// write the mocked system key to disk
restore = interfaces.MockSystemKey(systemKeyJSON)
defer restore()
err := interfaces.WriteSystemKey(extraData)
c.Assert(err, IsNil)
// now unmarshal the specific json to a system key object
key1, err := interfaces.UnmarshalJSONSystemKey(bytes.NewBuffer([]byte(systemKeyJSON)))
c.Assert(err, IsNil)
// now read the system key from disk
key2, err := interfaces.RecordedSystemKey()
c.Assert(err, IsNil)
// the two system-keys should be the same
ok, err := interfaces.SystemKeysMatch(key1, key2)
c.Assert(err, IsNil)
c.Check(ok, Equals, true, Commentf("key1:%#v key2:%#v", key1, key2))
}
func (s *systemKeySuite) TestRemoveSystemKey(c *C) {
extraData := interfaces.SystemKeyExtraData{}
systemKeyJSON := `{}`
// write the mocked system key to disk
restore := interfaces.MockSystemKey(systemKeyJSON)
defer restore()
err := interfaces.WriteSystemKey(extraData)
c.Assert(err, IsNil)
c.Check(dirs.SnapSystemKeyFile, testutil.FilePresent)
// remove the system key
err = interfaces.RemoveSystemKey()
c.Assert(err, IsNil)
c.Check(dirs.SnapSystemKeyFile, testutil.FileAbsent)
// also check that no error is returned when trying to remove system key
// when it does not exist in the first place
err = interfaces.RemoveSystemKey()
c.Assert(err, IsNil)
}