aboutsummaryrefslogtreecommitdiff
path: root/keyring
diff options
context:
space:
mode:
Diffstat (limited to 'keyring')
-rw-r--r--keyring/keyring.go100
-rw-r--r--keyring/keyring_test.go95
-rw-r--r--keyring/user_keyring.go221
3 files changed, 416 insertions, 0 deletions
diff --git a/keyring/keyring.go b/keyring/keyring.go
new file mode 100644
index 0000000..7a5fd64
--- /dev/null
+++ b/keyring/keyring.go
@@ -0,0 +1,100 @@
+/*
+ * keyring.go - Add/remove encryption policy keys to/from kernel
+ *
+ * Copyright 2019 Google LLC
+ * Author: Eric Biggers (ebiggers@google.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+// Package keyring manages adding, removing, and getting the status of
+// encryption policy keys to/from the kernel. Most public functions are in
+// keyring.go, and they delegate to user_keyring.go.
+package keyring
+
+import (
+ "os/user"
+ "strconv"
+
+ "github.com/pkg/errors"
+
+ "github.com/google/fscrypt/crypto"
+ "github.com/google/fscrypt/metadata"
+ "github.com/google/fscrypt/util"
+)
+
+// Keyring error values
+var (
+ ErrKeyAdd = util.SystemError("could not add key to the keyring")
+ ErrKeyRemove = util.SystemError("could not remove key from the keyring")
+ ErrKeyNotPresent = errors.New("key not present or already removed")
+ ErrKeySearch = errors.New("could not find key with descriptor")
+ ErrSessionUserKeying = errors.New("user keyring not linked into session keyring")
+ ErrAccessUserKeyring = errors.New("could not access user keyring")
+ ErrLinkUserKeyring = util.SystemError("could not link user keyring into root keyring")
+)
+
+// Options are the options which specify *which* keyring the key should be
+// added/removed/gotten to, and how.
+type Options struct {
+ // User is the user for whom the key should be added/removed/gotten.
+ User *user.User
+ // Service is the prefix to prepend to the description of the keys.
+ Service string
+}
+
+// AddEncryptionKey adds an encryption policy key to a kernel keyring.
+func AddEncryptionKey(key *crypto.Key, descriptor string, options *Options) error {
+ if err := util.CheckValidLength(metadata.PolicyKeyLen, key.Len()); err != nil {
+ return errors.Wrap(err, "policy key")
+ }
+ return userAddKey(key, options.Service+descriptor, options.User)
+}
+
+// RemoveEncryptionKey removes an encryption policy key from a kernel keyring.
+func RemoveEncryptionKey(descriptor string, options *Options) error {
+ return userRemoveKey(options.Service+descriptor, options.User)
+}
+
+// KeyStatus is an enum that represents the status of a key in a kernel keyring.
+type KeyStatus int
+
+// The possible values of KeyStatus.
+const (
+ KeyStatusUnknown = 0 + iota
+ KeyAbsent
+ KeyPresent
+)
+
+func (status KeyStatus) String() string {
+ switch status {
+ case KeyStatusUnknown:
+ return "Unknown"
+ case KeyAbsent:
+ return "Absent"
+ case KeyPresent:
+ return "Present"
+ default:
+ return strconv.Itoa(int(status))
+ }
+}
+
+// GetEncryptionKeyStatus gets the status of an encryption policy key in a
+// kernel keyring.
+func GetEncryptionKeyStatus(descriptor string, options *Options) (KeyStatus, error) {
+ _, err := userFindKey(options.Service+descriptor, options.User)
+ if err != nil {
+ return KeyAbsent, nil
+ }
+ return KeyPresent, nil
+}
diff --git a/keyring/keyring_test.go b/keyring/keyring_test.go
new file mode 100644
index 0000000..10ff874
--- /dev/null
+++ b/keyring/keyring_test.go
@@ -0,0 +1,95 @@
+/*
+ * keyring_test.go - tests for the keyring package
+ *
+ * Copyright 2017 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package keyring
+
+import (
+ "testing"
+
+ "golang.org/x/sys/unix"
+
+ "github.com/google/fscrypt/crypto"
+ "github.com/google/fscrypt/metadata"
+ "github.com/google/fscrypt/util"
+)
+
+// Reader that always returns the same byte
+type ConstReader byte
+
+func (r ConstReader) Read(b []byte) (n int, err error) {
+ for i := range b {
+ b[i] = byte(r)
+ }
+ return len(b), nil
+}
+
+// Makes a key of the same repeating byte
+func makeKey(b byte, n int) (*crypto.Key, error) {
+ return crypto.NewFixedLengthKeyFromReader(ConstReader(b), n)
+}
+
+var (
+ fakeValidDescriptor = "0123456789abcdef"
+ defaultService = unix.FSCRYPT_KEY_DESC_PREFIX
+ testUser, _ = util.EffectiveUser()
+ fakeValidPolicyKey, _ = makeKey(42, metadata.PolicyKeyLen)
+ fakeInvalidPolicyKey, _ = makeKey(42, metadata.PolicyKeyLen-1)
+)
+
+// Adds and removes a key with various services.
+func TestAddRemoveKeys(t *testing.T) {
+ for _, service := range []string{defaultService, "ext4:", "f2fs:"} {
+ options := &Options{
+ User: testUser,
+ Service: service,
+ }
+ if err := AddEncryptionKey(fakeValidPolicyKey, fakeValidDescriptor, options); err != nil {
+ t.Error(err)
+ }
+ if err := RemoveEncryptionKey(fakeValidDescriptor, options); err != nil {
+ t.Error(err)
+ }
+ }
+}
+
+// Adds a key twice (both should succeed)
+func TestAddTwice(t *testing.T) {
+ options := &Options{
+ User: testUser,
+ Service: defaultService,
+ }
+ if err := AddEncryptionKey(fakeValidPolicyKey, fakeValidDescriptor, options); err != nil {
+ t.Error(err)
+ }
+ if err := AddEncryptionKey(fakeValidPolicyKey, fakeValidDescriptor, options); err != nil {
+ t.Error("AddEncryptionKey should not fail if key already exists")
+ }
+ RemoveEncryptionKey(fakeValidDescriptor, options)
+}
+
+// Makes sure trying to add a key of the wrong length fails
+func TestAddWrongLengthKey(t *testing.T) {
+ options := &Options{
+ User: testUser,
+ Service: defaultService,
+ }
+ if err := AddEncryptionKey(fakeInvalidPolicyKey, fakeValidDescriptor, options); err == nil {
+ RemoveEncryptionKey(fakeValidDescriptor, options)
+ t.Error("AddEncryptionKey should fail with wrong-length key")
+ }
+}
diff --git a/keyring/user_keyring.go b/keyring/user_keyring.go
new file mode 100644
index 0000000..adac71a
--- /dev/null
+++ b/keyring/user_keyring.go
@@ -0,0 +1,221 @@
+/*
+ * user_keyring.go - Add/remove encryption policy keys to/from user keyrings
+ *
+ * Copyright 2017 Google Inc.
+ * Author: Joe Richey (joerichey@google.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package keyring
+
+import (
+ "os/user"
+ "runtime"
+ "unsafe"
+
+ "github.com/pkg/errors"
+ "golang.org/x/sys/unix"
+
+ "fmt"
+ "log"
+
+ "github.com/google/fscrypt/crypto"
+ "github.com/google/fscrypt/security"
+ "github.com/google/fscrypt/util"
+)
+
+// KeyType is always logon as required by filesystem encryption.
+const KeyType = "logon"
+
+// userAddKey puts the provided policy key into the user keyring for the
+// specified user with the provided description, and type logon.
+func userAddKey(key *crypto.Key, description string, targetUser *user.User) error {
+ runtime.LockOSThread() // ensure target user keyring remains possessed in thread keyring
+ defer runtime.UnlockOSThread()
+
+ // Create our payload (containing an FscryptKey)
+ payload, err := crypto.NewBlankKey(int(unsafe.Sizeof(unix.FscryptKey{})))
+ if err != nil {
+ return err
+ }
+ defer payload.Wipe()
+
+ // Cast the payload to an FscryptKey so we can initialize the fields.
+ fscryptKey := (*unix.FscryptKey)(payload.UnsafePtr())
+ // Mode is ignored by the kernel
+ fscryptKey.Mode = 0
+ fscryptKey.Size = uint32(key.Len())
+ copy(fscryptKey.Raw[:], key.Data())
+
+ keyringID, err := UserKeyringID(targetUser, true)
+ if err != nil {
+ return err
+ }
+ keyID, err := unix.AddKey(KeyType, description, payload.Data(), keyringID)
+ log.Printf("KeyctlAddKey(%s, %s, <data>, %d) = %d, %v",
+ KeyType, description, keyringID, keyID, err)
+ if err != nil {
+ return errors.Wrap(ErrKeyAdd, err.Error())
+ }
+ return nil
+}
+
+// userRemoveKey tries to remove a policy key from the user keyring with the
+// provided description. An error is returned if the key does not exist.
+func userRemoveKey(description string, targetUser *user.User) error {
+ runtime.LockOSThread() // ensure target user keyring remains possessed in thread keyring
+ defer runtime.UnlockOSThread()
+
+ keyID, err := userFindKey(description, targetUser)
+ if err != nil {
+ return ErrKeyNotPresent
+ }
+
+ // We use KEYCTL_INVALIDATE instead of KEYCTL_REVOKE because
+ // invalidating a key immediately removes it.
+ _, err = unix.KeyctlInt(unix.KEYCTL_INVALIDATE, keyID, 0, 0, 0)
+ log.Printf("KeyctlInvalidate(%d) = %v", keyID, err)
+ if err != nil {
+ return errors.Wrap(ErrKeyRemove, err.Error())
+ }
+ return nil
+}
+
+// userFindKey tries to locate a key in the user keyring with the provided
+// description. The key ID is returned if we can find the key. An error is
+// returned if the key does not exist.
+func userFindKey(description string, targetUser *user.User) (int, error) {
+ runtime.LockOSThread() // ensure target user keyring remains possessed in thread keyring
+ defer runtime.UnlockOSThread()
+
+ keyringID, err := UserKeyringID(targetUser, false)
+ if err != nil {
+ return 0, err
+ }
+
+ keyID, err := unix.KeyctlSearch(keyringID, KeyType, description, 0)
+ log.Printf("KeyctlSearch(%d, %s, %s) = %d, %v", keyringID, KeyType, description, keyID, err)
+ if err != nil {
+ return 0, errors.Wrap(ErrKeySearch, err.Error())
+ }
+ return keyID, err
+}
+
+// UserKeyringID returns the key id of the target user's user keyring. We also
+// ensure that the keyring will be accessible by linking it into the thread
+// keyring and linking it into the root user keyring (permissions allowing). If
+// checkSession is true, an error is returned if a normal user requests their
+// user keyring, but it is not in the current session keyring.
+func UserKeyringID(targetUser *user.User, checkSession bool) (int, error) {
+ runtime.LockOSThread() // ensure target user keyring remains possessed in thread keyring
+ defer runtime.UnlockOSThread()
+
+ uid := util.AtoiOrPanic(targetUser.Uid)
+ targetKeyring, err := userKeyringIDLookup(uid)
+ if err != nil {
+ return 0, errors.Wrap(ErrAccessUserKeyring, err.Error())
+ }
+
+ if !util.IsUserRoot() {
+ // Make sure the returned keyring will be accessible by checking
+ // that it is in the session keyring.
+ if checkSession && !isUserKeyringInSession(uid) {
+ return 0, ErrSessionUserKeying
+ }
+ return targetKeyring, nil
+ }
+
+ // Make sure the returned keyring will be accessible by linking it into
+ // the root user's user keyring (which will not be garbage collected).
+ rootKeyring, err := userKeyringIDLookup(0)
+ if err != nil {
+ return 0, errors.Wrap(ErrLinkUserKeyring, err.Error())
+ }
+
+ if rootKeyring != targetKeyring {
+ if err = keyringLink(targetKeyring, rootKeyring); err != nil {
+ return 0, errors.Wrap(ErrLinkUserKeyring, err.Error())
+ }
+ }
+ return targetKeyring, nil
+}
+
+func userKeyringIDLookup(uid int) (keyringID int, err error) {
+
+ // Our goals here are to:
+ // - Find the user keyring (for the provided uid)
+ // - Link it into the current thread keyring (so we can use it)
+ // - Make no permanent changes to the process privileges
+ // Complicating this are the facts that:
+ // - The value of KEY_SPEC_USER_KEYRING is determined by the ruid
+ // - Keyring linking permissions use the euid
+ // So we have to change both the ruid and euid to make this work,
+ // setting the suid to 0 so that we can later switch back.
+ ruid, euid, suid := security.GetUids()
+ if ruid != uid || euid != uid {
+ if err = security.SetUids(uid, uid, 0); err != nil {
+ return
+ }
+ defer func() {
+ resetErr := security.SetUids(ruid, euid, suid)
+ if resetErr != nil {
+ err = resetErr
+ }
+ }()
+ }
+
+ // We get the value of KEY_SPEC_USER_KEYRING. Note that this will also
+ // trigger the creation of the uid keyring if it does not yet exist.
+ keyringID, err = unix.KeyctlGetKeyringID(unix.KEY_SPEC_USER_KEYRING, true)
+ log.Printf("keyringID(_uid.%d) = %d, %v", uid, keyringID, err)
+ if err != nil {
+ return 0, err
+ }
+
+ // We still want to use this keyring after our privileges are reset. So
+ // we link it into the thread keyring, preventing a loss of access.
+ //
+ // We must be under LockOSThread() for this to work reliably. Note that
+ // we can't just use the process keyring, since it doesn't work reliably
+ // in Go programs, due to the Go runtime creating threads before the
+ // program starts and has a chance to create the process keyring.
+ if err = keyringLink(keyringID, unix.KEY_SPEC_THREAD_KEYRING); err != nil {
+ return 0, err
+ }
+
+ return keyringID, nil
+}
+
+// isUserKeyringInSession tells us if the user's uid keyring is in the current
+// session keyring.
+func isUserKeyringInSession(uid int) bool {
+ // We cannot use unix.KEY_SPEC_SESSION_KEYRING directly as that might
+ // create a session keyring if one does not exist.
+ sessionKeyring, err := unix.KeyctlGetKeyringID(unix.KEY_SPEC_SESSION_KEYRING, false)
+ log.Printf("keyringID(session) = %d, %v", sessionKeyring, err)
+ if err != nil {
+ return false
+ }
+
+ description := fmt.Sprintf("_uid.%d", uid)
+ id, err := unix.KeyctlSearch(sessionKeyring, "keyring", description, 0)
+ log.Printf("KeyctlSearch(%d, keyring, %s) = %d, %v", sessionKeyring, description, id, err)
+ return err == nil
+}
+
+func keyringLink(keyID int, keyringID int) error {
+ _, err := unix.KeyctlInt(unix.KEYCTL_LINK, keyID, keyringID, 0, 0)
+ log.Printf("KeyctlLink(%d, %d) = %v", keyID, keyringID, err)
+ return err
+}