mirror of
https://github.com/netbirdio/gvisor.git
synced 2026-05-22 17:12:49 -07:00
Implement a subset of keyctl(2) and keyrings(7) for better Docker support.
The intention of this change is to cover a sufficient surface to accommodate
the use of running Docker within gVisor, rather than a full implementation.
This implements the following features:
- Keys as a first-class concept in the kernel.
- Tracking keys in user namespaces.
- Task session keyrings: possession, inheritance.
- Key permission enforcement.
- The following `keyctl(2)` operations:
- `KEYCTL_GET_KEYRING_ID`
- `KEYCTL_DESCRIBE`
- `KEYCTL_JOIN_SESSION_KEYRING`
- `KEYCTL_SETPERM`
Notably, this does not implement:
- The ability to actually add any keys other than the session keyring
(which does not hold any cryptographic key data).
- Other special keyrings (thread keyring, process keyring, user session
keyring, etc.).
- Lots of `keyctl(2)` operations.
- Key expiration.
- Key garbage collection. Keys live until their user namespace is destroyed.
However, each user namespace is limited to 200 keys, so memory growth is
bounded.
- `add_key(2)`
- `request_key(2)`
... However, this makes design choices that seem odd given the limited scope
of this change, but make sense when taking into account the desire to
eventually accommodate them in the future. For example, there are many
`switch` statements with only one option for session keyrings, which would get
more options when adding support for other special keyrings. Similarly, the
signature of `PossessedKeys` takes in all 3 special "possessed" keyrings, but
currently only ever gets the session keyring as non-nil.
PiperOrigin-RevId: 567047896
This commit is contained in:
committed by
gVisor bot
parent
81a42184e1
commit
02f70b5df0
@@ -280,6 +280,7 @@ go_library(
|
||||
"task_futex.go",
|
||||
"task_identity.go",
|
||||
"task_image.go",
|
||||
"task_key.go",
|
||||
"task_list.go",
|
||||
"task_log.go",
|
||||
"task_mutex.go",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
load("//pkg/sync/locking:locking.bzl", "declare_mutex", "declare_rwmutex")
|
||||
load("//tools:defs.bzl", "go_library")
|
||||
load("//tools/go_generics:defs.bzl", "go_template_instance")
|
||||
load("//pkg/sync/locking:locking.bzl", "declare_mutex")
|
||||
|
||||
package(
|
||||
default_applicable_licenses = ["//:license"],
|
||||
@@ -54,6 +54,20 @@ declare_mutex(
|
||||
prefix = "userNamespace",
|
||||
)
|
||||
|
||||
declare_rwmutex(
|
||||
name = "keyset_mutex",
|
||||
out = "keyset_mutex.go",
|
||||
package = "auth",
|
||||
prefix = "keyset",
|
||||
)
|
||||
|
||||
declare_mutex(
|
||||
name = "keyset_transaction_mutex",
|
||||
out = "keyset_transaction_mutex.go",
|
||||
package = "auth",
|
||||
prefix = "keysetTransaction",
|
||||
)
|
||||
|
||||
go_library(
|
||||
name = "auth",
|
||||
srcs = [
|
||||
@@ -67,6 +81,9 @@ go_library(
|
||||
"id_map_functions.go",
|
||||
"id_map_range.go",
|
||||
"id_map_set.go",
|
||||
"key.go",
|
||||
"keyset_mutex.go",
|
||||
"keyset_transaction_mutex.go",
|
||||
"user_namespace.go",
|
||||
"user_namespace_mutex.go",
|
||||
],
|
||||
@@ -78,6 +95,7 @@ go_library(
|
||||
"//pkg/context",
|
||||
"//pkg/errors/linuxerr",
|
||||
"//pkg/log",
|
||||
"//pkg/rand",
|
||||
"//pkg/sentry/seccheck",
|
||||
"//pkg/sentry/seccheck/points:points_go_proto",
|
||||
"//pkg/sync",
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
// Copyright 2020 The gVisor Authors.
|
||||
//
|
||||
// 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 auth
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"gvisor.dev/gvisor/pkg/errors/linuxerr"
|
||||
"gvisor.dev/gvisor/pkg/rand"
|
||||
)
|
||||
|
||||
// KeySerial is a key ID type.
|
||||
// Only strictly positive IDs are valid key IDs.
|
||||
// The zero ID is meaningless but is specified when creating new keyrings.
|
||||
// Strictly negative IDs are used for special key IDs which are internally
|
||||
// translated to real key IDs (e.g. KEY_SPEC_SESSION_KEYRING is translated
|
||||
// to the caller process's session keyring).
|
||||
type KeySerial int32
|
||||
|
||||
// KeyType is the type of a key.
|
||||
// This is an enum, but is also exposed to userspace in KEYCTL_DESCRIBE.
|
||||
// For this reason, it must match Linux.
|
||||
type KeyType string
|
||||
|
||||
// List of known key types.
|
||||
const (
|
||||
KeyTypeKeyring KeyType = "keyring"
|
||||
// Other types are not yet supported.
|
||||
)
|
||||
|
||||
// KeyPermission represents a permission on a key.
|
||||
type KeyPermission int
|
||||
|
||||
// List of known key permissions.
|
||||
const (
|
||||
KeyView KeyPermission = iota
|
||||
KeyRead
|
||||
KeyWrite
|
||||
KeySearch
|
||||
KeyLink
|
||||
KeySetAttr
|
||||
)
|
||||
|
||||
// KeyPermissions is the full set of permissions on a single Key.
|
||||
type KeyPermissions uint64
|
||||
|
||||
const (
|
||||
// MaxKeyDescSize is the maximum size of the "Description" field of keys.
|
||||
// Corresponds to `KEY_MAX_DESC_SIZE` in Linux.
|
||||
MaxKeyDescSize = 4096
|
||||
|
||||
// maxSetSize is the maximum number of a keys in a `Set`.
|
||||
// By default, Linux limits this number to 200 per non-root user.
|
||||
// Here, we limit it to 200 per Set, which is stricter.
|
||||
maxSetSize = 200
|
||||
)
|
||||
|
||||
// Key represents a key in the keyrings subsystem.
|
||||
//
|
||||
// +stateify savable
|
||||
type Key struct {
|
||||
// ID is the ID of the key, also often referred to as "serial number".
|
||||
// Note that key IDs passed in syscalls may be negative when they refer to
|
||||
// "special keys", sometimes also referred to as "shortcut IDs".
|
||||
// Key IDs of real instantiated keys are always > 0.
|
||||
// The key ID never changes and is unique within a KeySet (i.e. a user
|
||||
// namespace).
|
||||
// It must be chosen with cryptographic randomness to make enumeration
|
||||
// attacks harder.
|
||||
ID KeySerial
|
||||
|
||||
// Description is a description of the key. It is also often referred to the
|
||||
// "name" of the key. Keys are canonically identified by their ID, but the
|
||||
// syscall ABI also allows look up keys by their description.
|
||||
// It may not be larger than `KeyMaxDescSize`.
|
||||
// Confusingly, the information returned by the KEYCTL_DESCRIBE operation,
|
||||
// which you'd think means "get the key description", actually returns a
|
||||
// superset of this `Description`.
|
||||
Description string
|
||||
|
||||
// kuid is the owner of the key in the root namespace.
|
||||
// kuid is only mutable in KeySet transactions.
|
||||
kuid KUID
|
||||
|
||||
// kgid is the group of the key in the root namespace.
|
||||
// kgid is only mutable in KeySet transactions.
|
||||
kgid KGID
|
||||
|
||||
// perms is a bitfield of key permissions.
|
||||
// perms is only mutable in KeySet transactions.
|
||||
perms KeyPermissions
|
||||
}
|
||||
|
||||
// Type returns the type of this key.
|
||||
func (*Key) Type() KeyType {
|
||||
return KeyTypeKeyring
|
||||
}
|
||||
|
||||
// KUID returns the KUID (owner ID) of the key.
|
||||
func (k *Key) KUID() KUID { return k.kuid }
|
||||
|
||||
// KGID returns the KGID (group ID) of the key.
|
||||
func (k *Key) KGID() KGID { return k.kgid }
|
||||
|
||||
// Permissions returns the permission bits of the key.
|
||||
func (k *Key) Permissions() KeyPermissions { return k.perms }
|
||||
|
||||
// String is a human-friendly representation of the key.
|
||||
// Notably, this is *not* the string returned to userspace when requested
|
||||
// using `KEYCTL_DESCRIBE`.
|
||||
func (k *Key) String() string {
|
||||
return fmt.Sprintf("id=%d,perms=0x%x,desc=%q", k.ID, k.perms, k.Description)
|
||||
}
|
||||
|
||||
// Bitmasks for permission checks.
|
||||
const (
|
||||
keyPossessorPermissionsMask = 0x3f000000
|
||||
keyPossessorPermissionsShift = 24
|
||||
keyOwnerPermissionsMask = 0x003f0000
|
||||
keyOwnerPermissionsShift = 16
|
||||
keyGroupPermissionsMask = 0x00003f00
|
||||
keyGroupPermissionsShift = 8
|
||||
keyOtherPermissionsMask = 0x0000003f
|
||||
keyOtherPermissionsShift = 0
|
||||
|
||||
keyPermissionView = 0x00000001
|
||||
keyPermissionRead = 0x00000002
|
||||
keyPermissionWrite = 0x00000004
|
||||
keyPermissionSearch = 0x00000008
|
||||
keyPermissionLink = 0x00000010
|
||||
keyPermissionSetAttr = 0x00000020
|
||||
keyPermissionAll = (keyPermissionView |
|
||||
keyPermissionRead |
|
||||
keyPermissionWrite |
|
||||
keyPermissionSearch |
|
||||
keyPermissionLink |
|
||||
keyPermissionSetAttr)
|
||||
)
|
||||
|
||||
// String returns a human-readable version of the permission bits.
|
||||
func (p KeyPermissions) String() string {
|
||||
var perms strings.Builder
|
||||
for i, s := range [4]struct {
|
||||
kind string
|
||||
shift int
|
||||
}{
|
||||
{kind: "possessor", shift: keyPossessorPermissionsShift},
|
||||
{kind: "owner", shift: keyOwnerPermissionsShift},
|
||||
{kind: "group", shift: keyGroupPermissionsShift},
|
||||
{kind: "other", shift: keyOtherPermissionsShift},
|
||||
} {
|
||||
if i != 0 {
|
||||
perms.WriteRune(',')
|
||||
}
|
||||
perms.WriteString(s.kind)
|
||||
perms.WriteRune('=')
|
||||
kindPerms := p >> s.shift
|
||||
for _, b := range [6]struct {
|
||||
mask int
|
||||
r rune
|
||||
}{
|
||||
{mask: keyPermissionView, r: 'v'},
|
||||
{mask: keyPermissionRead, r: 'r'},
|
||||
{mask: keyPermissionWrite, r: 'w'},
|
||||
{mask: keyPermissionSearch, r: 's'},
|
||||
{mask: keyPermissionLink, r: 'l'},
|
||||
{mask: keyPermissionSetAttr, r: 'a'},
|
||||
} {
|
||||
if uint64(kindPerms)&uint64(b.mask) != 0 {
|
||||
perms.WriteRune(b.r)
|
||||
} else {
|
||||
perms.WriteRune('-')
|
||||
}
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("%08x[%s]", uint64(p), perms.String())
|
||||
}
|
||||
|
||||
// Default key settings.
|
||||
const (
|
||||
// Default session keyring name.
|
||||
DefaultSessionKeyringName = "_ses"
|
||||
|
||||
// Default permissions for unnamed session keyrings:
|
||||
// Possessors have full permissions.
|
||||
// Owners have view and read permissions.
|
||||
DefaultUnnamedSessionKeyringPermissions KeyPermissions = ((keyPermissionAll << keyPossessorPermissionsShift) |
|
||||
((keyPermissionView | keyPermissionRead) << keyOwnerPermissionsShift))
|
||||
|
||||
// Default permissions for named session keyrings:
|
||||
// Possessors have full permissions.
|
||||
// Owners have view, read, and link permissions.
|
||||
DefaultNamedSessionKeyringPermissions KeyPermissions = ((keyPermissionAll << keyPossessorPermissionsShift) |
|
||||
((keyPermissionView | keyPermissionRead | keyPermissionLink) << keyOwnerPermissionsShift))
|
||||
)
|
||||
|
||||
// PossessedKeys is an opaque type used during key permission check.
|
||||
// When iterating over all keys, the possessed set of keys should only be
|
||||
// built once. Since key possession is a recursive property, it can be
|
||||
// expensive to determine. PossessedKeys holds all possessed keys at
|
||||
// the time it is computed.
|
||||
// PossessedKeys is short-lived; it should only live for so long as there
|
||||
// are no changes to the KeySet or to any key permissions.
|
||||
type PossessedKeys struct {
|
||||
// possessed is a list of possessed key IDs.
|
||||
possessed map[KeySerial]struct{}
|
||||
}
|
||||
|
||||
// PossessedKeys returns a new fully-expanded set of PossessedKeys.
|
||||
// The keys passed in are the set of keys that a task directly possesses:
|
||||
// session keyring, process keyring, thread keyring. Each key may be nil.
|
||||
// PossessedKeys is short-lived; it should only live for so long as there
|
||||
// are no changes to the KeySet or to any key permissions.
|
||||
func (c *Credentials) PossessedKeys(sessionKeyring, processKeyring, threadKeyring *Key) *PossessedKeys {
|
||||
possessed := &PossessedKeys{possessed: make(map[KeySerial]struct{})}
|
||||
for _, k := range [3]*Key{sessionKeyring, processKeyring, threadKeyring} {
|
||||
if k == nil {
|
||||
continue
|
||||
}
|
||||
// The possessor still needs "search" permission in order to actually possess anything.
|
||||
if ((k.perms&keyPossessorPermissionsMask)>>keyPossessorPermissionsShift)&keyPermissionSearch != 0 {
|
||||
possessed.possessed[k.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// If we implement keyrings that contain other keys, this is where the
|
||||
// recursion would happen.
|
||||
|
||||
return possessed
|
||||
}
|
||||
|
||||
// HasKeyPermission returns whether the credentials grant `permission` on `k`.
|
||||
//
|
||||
//go:nosplit
|
||||
func (c *Credentials) HasKeyPermission(k *Key, possessed *PossessedKeys, permission KeyPermission) bool {
|
||||
perms := k.perms & keyOtherPermissionsMask
|
||||
if _, ok := possessed.possessed[k.ID]; ok {
|
||||
perms |= (k.perms & keyPossessorPermissionsMask) >> keyPossessorPermissionsShift
|
||||
}
|
||||
if c.EffectiveKUID == k.kuid {
|
||||
perms |= (k.perms & keyOwnerPermissionsMask) >> keyOwnerPermissionsShift
|
||||
}
|
||||
if c.EffectiveKGID == k.kgid {
|
||||
perms |= (k.perms & keyGroupPermissionsMask) >> keyGroupPermissionsShift
|
||||
}
|
||||
switch permission {
|
||||
case KeyView:
|
||||
return perms&keyPermissionView != 0
|
||||
case KeyRead:
|
||||
return perms&keyPermissionRead != 0
|
||||
case KeyWrite:
|
||||
return perms&keyPermissionWrite != 0
|
||||
case KeySearch:
|
||||
return perms&keyPermissionSearch != 0
|
||||
case KeyLink:
|
||||
return perms&keyPermissionLink != 0
|
||||
case KeySetAttr:
|
||||
return perms&keyPermissionSetAttr != 0
|
||||
default:
|
||||
panic("unknown key permission")
|
||||
}
|
||||
}
|
||||
|
||||
// KeySet is a set of keys.
|
||||
//
|
||||
// +stateify savable
|
||||
type KeySet struct {
|
||||
// txnMu is used for transactionality of key changes.
|
||||
// This blocks multiple tasks for concurrently changing the keyset or the
|
||||
// permissions of any keys.
|
||||
txnMu keysetTransactionMutex `state:"nosave"`
|
||||
|
||||
// mu protects the fields below.
|
||||
// Within functions on `KeySet`, `mu` may only be locked for reading.
|
||||
// Locking `mu` for writing may only be done in `LockedKeySet` functions.
|
||||
mu keysetRWMutex `state:"nosave"`
|
||||
|
||||
// keys maps key IDs to the underlying Key struct.
|
||||
// It is initially nil to save on heap space.
|
||||
// It is only initialized when doing mutable transactions on it using `Do`.
|
||||
keys map[KeySerial]*Key
|
||||
}
|
||||
|
||||
// LockedKeySet is a KeySet in a transaction.
|
||||
// It exposes functions that can mutate the KeySet or its keys.
|
||||
type LockedKeySet struct {
|
||||
*KeySet
|
||||
}
|
||||
|
||||
// Do executes the given function as a transaction on the KeySet.
|
||||
// It returns the error that `fn` returns.
|
||||
// This is the only function where functions that lock the KeySet.mu for
|
||||
// writing may be called.
|
||||
func (s *KeySet) Do(fn func(*LockedKeySet) error) error {
|
||||
s.txnMu.Lock()
|
||||
defer s.txnMu.Unlock()
|
||||
ls := &LockedKeySet{s}
|
||||
ls.mu.Lock()
|
||||
if s.keys == nil {
|
||||
// Initialize the map from its zero value, if it hasn't been done yet.
|
||||
s.keys = make(map[KeySerial]*Key)
|
||||
}
|
||||
ls.mu.Unlock()
|
||||
return fn(ls)
|
||||
}
|
||||
|
||||
// Lookup looks up a key by ID.
|
||||
// Callers must exercise care to verify that the key can be accessed with
|
||||
// proper credentials.
|
||||
func (s *KeySet) Lookup(keyID KeySerial) (*Key, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
key, found := s.keys[keyID]
|
||||
if !found {
|
||||
return nil, linuxerr.ENOKEY
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// ForEach iterates over all keys.
|
||||
// If `fn` returns true, iteration stops immediately.
|
||||
// Callers must exercise care to only process keys to which they have access.
|
||||
func (s *KeySet) ForEach(fn func(*Key) bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
for _, key := range s.keys {
|
||||
if fn(key) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// getNewID returns a new random key ID strictly larger than zero.
|
||||
// It uses cryptographic randomness in order to make enumeration attacks
|
||||
// harder.
|
||||
func getNewID() (KeySerial, error) {
|
||||
var newID int32
|
||||
for newID == 0 {
|
||||
if err := binary.Read(rand.Reader, binary.LittleEndian, &newID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
if newID < 0 {
|
||||
newID = -newID
|
||||
}
|
||||
return KeySerial(newID), nil
|
||||
}
|
||||
|
||||
// Add adds a new Key to the KeySet.
|
||||
func (s *LockedKeySet) Add(description string, creds *Credentials, perms KeyPermissions) (*Key, error) {
|
||||
if len(description) >= MaxKeyDescSize {
|
||||
return nil, linuxerr.EINVAL
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(s.keys) >= maxSetSize {
|
||||
return nil, linuxerr.EDQUOT
|
||||
}
|
||||
newID, err := getNewID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for s.keys[newID] != nil {
|
||||
newID, err = getNewID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
k := &Key{
|
||||
ID: newID,
|
||||
Description: description,
|
||||
kuid: creds.EffectiveKUID,
|
||||
kgid: creds.EffectiveKGID,
|
||||
perms: perms,
|
||||
}
|
||||
s.keys[newID] = k
|
||||
return k, nil
|
||||
}
|
||||
|
||||
// SetPerms sets the permissions on a given key.
|
||||
// The caller must have SetAttr permission on the key.
|
||||
func (s *LockedKeySet) SetPerms(key *Key, newPerms KeyPermissions) {
|
||||
key.perms = newPerms
|
||||
}
|
||||
@@ -33,6 +33,9 @@ type UserNamespace struct {
|
||||
// namespace. owner is immutable.
|
||||
owner KUID
|
||||
|
||||
// Keys is the set of keys in this namespace.
|
||||
Keys KeySet
|
||||
|
||||
// mu protects the following fields.
|
||||
//
|
||||
// If mu will be locked in multiple UserNamespaces, it must be locked in
|
||||
|
||||
@@ -952,6 +952,8 @@ func (k *Kernel) CreateProcess(args CreateProcessArgs) (*ThreadGroup, ThreadID,
|
||||
ContainerID: args.ContainerID,
|
||||
InitialCgroups: args.InitialCgroups,
|
||||
UserCounters: k.GetUserCounters(args.Credentials.RealKUID),
|
||||
// A task with no parent starts out with no session keyring.
|
||||
SessionKeyring: nil,
|
||||
}
|
||||
config.NetworkNamespace.IncRef()
|
||||
t, err := k.tasks.NewTask(ctx, config)
|
||||
|
||||
@@ -598,6 +598,12 @@ type Task struct {
|
||||
// The userCounters pointer is exclusive to the task goroutine, but the
|
||||
// userCounters instance must be atomically accessed.
|
||||
userCounters *userCounters
|
||||
|
||||
// sessionKeyring is a pointer to the task's session keyring, if set.
|
||||
// It is guaranteed to be of type "keyring".
|
||||
//
|
||||
// +checklocks:mu
|
||||
sessionKeyring *auth.Key
|
||||
}
|
||||
|
||||
// Task related metrics
|
||||
|
||||
@@ -165,6 +165,7 @@ func (t *Task) Clone(args *linux.CloneArgs) (ThreadID, *SyscallControl, error) {
|
||||
// above Task.mu. So we copy t.image with t.mu held and call Fork() on the copy.
|
||||
t.mu.Lock()
|
||||
curImage := t.image
|
||||
sessionKeyring := t.sessionKeyring
|
||||
t.mu.Unlock()
|
||||
image, err := curImage.Fork(t, t.k, args.Flags&linux.CLONE_VM != 0)
|
||||
if err != nil {
|
||||
@@ -173,6 +174,12 @@ func (t *Task) Clone(args *linux.CloneArgs) (ThreadID, *SyscallControl, error) {
|
||||
cu.Add(func() {
|
||||
image.release(t)
|
||||
})
|
||||
|
||||
if args.Flags&linux.CLONE_NEWUSER != 0 {
|
||||
// If the task is in a new user namespace, it cannot share keys.
|
||||
sessionKeyring = nil
|
||||
}
|
||||
|
||||
// clone() returns 0 in the child.
|
||||
image.Arch.SetReturn(0)
|
||||
if args.Stack != 0 {
|
||||
@@ -259,6 +266,7 @@ func (t *Task) Clone(args *linux.CloneArgs) (ThreadID, *SyscallControl, error) {
|
||||
RSeqSignature: rseqSignature,
|
||||
ContainerID: t.ContainerID(),
|
||||
UserCounters: uc,
|
||||
SessionKeyring: sessionKeyring,
|
||||
}
|
||||
if args.Flags&linux.CLONE_THREAD == 0 {
|
||||
cfg.Parent = t
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
// Copyright 2023 The gVisor Authors.
|
||||
//
|
||||
// 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 kernel
|
||||
|
||||
import (
|
||||
"gvisor.dev/gvisor/pkg/errors/linuxerr"
|
||||
"gvisor.dev/gvisor/pkg/sentry/kernel/auth"
|
||||
)
|
||||
|
||||
// SessionKeyring returns this Task's session keyring.
|
||||
// Session keyrings are inherited from the parent when a task is started.
|
||||
// If the session keyring is unset, it is implicitly initialized.
|
||||
// As such, this function should never return ENOKEY.
|
||||
func (t *Task) SessionKeyring() (*auth.Key, error) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if t.sessionKeyring != nil {
|
||||
// Verify that we still have access to this keyring.
|
||||
creds := t.Credentials()
|
||||
if !creds.HasKeyPermission(t.sessionKeyring, creds.PossessedKeys(t.sessionKeyring, nil, nil), auth.KeySearch) {
|
||||
return nil, linuxerr.EACCES
|
||||
}
|
||||
return t.sessionKeyring, nil
|
||||
}
|
||||
// If we don't have a session keyring, implicitly create one.
|
||||
return t.joinNewSessionKeyringLocked(auth.DefaultSessionKeyringName, auth.DefaultUnnamedSessionKeyringPermissions)
|
||||
}
|
||||
|
||||
// joinNewSessionKeyringLocked creates a new session keyring with the given
|
||||
// description, and joins it immediately.
|
||||
// Preconditions: t.mu is held.
|
||||
//
|
||||
// +checklocks:t.mu
|
||||
func (t *Task) joinNewSessionKeyringLocked(newKeyDesc string, newKeyPerms auth.KeyPermissions) (*auth.Key, error) {
|
||||
var sessionKeyring *auth.Key
|
||||
err := t.UserNamespace().Keys.Do(func(keySet *auth.LockedKeySet) error {
|
||||
creds := t.Credentials()
|
||||
var err error
|
||||
sessionKeyring, err = keySet.Add(newKeyDesc, creds, newKeyPerms)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Debugf("Joining newly-created session keyring with ID %d, permissions %v", sessionKeyring.ID, newKeyPerms)
|
||||
t.sessionKeyring = sessionKeyring
|
||||
return sessionKeyring, nil
|
||||
}
|
||||
|
||||
// JoinSessionKeyring causes the task to join a keyring with the given
|
||||
// key description (not ID).
|
||||
// If `keyDesc` is nil, then the task joins a newly-instantiated session
|
||||
// keyring instead.
|
||||
func (t *Task) JoinSessionKeyring(keyDesc *string) (*auth.Key, error) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
creds := t.Credentials()
|
||||
possessed := creds.PossessedKeys(t.sessionKeyring, nil, nil)
|
||||
var sessionKeyring *auth.Key
|
||||
newKeyPerms := auth.DefaultUnnamedSessionKeyringPermissions
|
||||
newKeyDesc := auth.DefaultSessionKeyringName
|
||||
if keyDesc != nil {
|
||||
creds.UserNamespace.Keys.ForEach(func(k *auth.Key) bool {
|
||||
if k.Description == *keyDesc && creds.HasKeyPermission(k, possessed, auth.KeySearch) {
|
||||
sessionKeyring = k
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
if sessionKeyring != nil {
|
||||
t.Debugf("Joining existing session keyring with ID %d", sessionKeyring.ID)
|
||||
t.sessionKeyring = sessionKeyring
|
||||
return sessionKeyring, nil
|
||||
}
|
||||
newKeyDesc = *keyDesc
|
||||
newKeyPerms = auth.DefaultNamedSessionKeyringPermissions
|
||||
}
|
||||
return t.joinNewSessionKeyringLocked(newKeyDesc, newKeyPerms)
|
||||
}
|
||||
|
||||
// LookupKey looks up a key by ID using this task's credentials.
|
||||
func (t *Task) LookupKey(keyID auth.KeySerial) (*auth.Key, error) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
creds := t.Credentials()
|
||||
key, err := creds.UserNamespace.Keys.Lookup(keyID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !creds.HasKeyPermission(key, creds.PossessedKeys(t.sessionKeyring, nil, nil), auth.KeySearch) {
|
||||
return nil, linuxerr.EACCES
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// SetPermsOnKey sets the permission bits on the given key using the task's
|
||||
// credentials.
|
||||
func (t *Task) SetPermsOnKey(key *auth.Key, perms auth.KeyPermissions) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
creds := t.Credentials()
|
||||
possessed := creds.PossessedKeys(t.sessionKeyring, nil, nil)
|
||||
return creds.UserNamespace.Keys.Do(func(keySet *auth.LockedKeySet) error {
|
||||
if !creds.HasKeyPermission(key, possessed, auth.KeySetAttr) {
|
||||
return linuxerr.EACCES
|
||||
}
|
||||
keySet.SetPerms(key, perms)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -102,6 +102,10 @@ type TaskConfig struct {
|
||||
|
||||
// UserCounters is user resource counters.
|
||||
UserCounters *userCounters
|
||||
|
||||
// SessionKeyring is the session keyring associated with the parent task.
|
||||
// It may be nil.
|
||||
SessionKeyring *auth.Key
|
||||
}
|
||||
|
||||
// NewTask creates a new task defined by cfg.
|
||||
@@ -171,6 +175,7 @@ func (ts *TaskSet) newTask(ctx context.Context, cfg *TaskConfig) (*Task, error)
|
||||
containerID: cfg.ContainerID,
|
||||
cgroups: make(map[Cgroup]struct{}),
|
||||
userCounters: cfg.UserCounters,
|
||||
sessionKeyring: cfg.SessionKeyring,
|
||||
}
|
||||
t.netns = cfg.NetworkNamespace
|
||||
t.creds.Store(cfg.Credentials)
|
||||
|
||||
@@ -26,6 +26,7 @@ go_library(
|
||||
"sys_identity.go",
|
||||
"sys_inotify.go",
|
||||
"sys_iouring.go",
|
||||
"sys_key.go",
|
||||
"sys_membarrier.go",
|
||||
"sys_mempolicy.go",
|
||||
"sys_mmap.go",
|
||||
|
||||
@@ -302,7 +302,7 @@ var AMD64 = &kernel.SyscallTable{
|
||||
247: syscalls.Supported("waitid", Waitid),
|
||||
248: syscalls.Error("add_key", linuxerr.EACCES, "Not available to user.", nil),
|
||||
249: syscalls.Error("request_key", linuxerr.EACCES, "Not available to user.", nil),
|
||||
250: syscalls.Error("keyctl", linuxerr.EACCES, "Not available to user.", nil),
|
||||
250: syscalls.PartiallySupported("keyctl", Keyctl, "Only supports session keyrings with zero keys in them.", nil),
|
||||
251: syscalls.CapError("ioprio_set", linux.CAP_SYS_ADMIN, "", nil), // requires cap_sys_nice or cap_sys_admin (depending)
|
||||
252: syscalls.CapError("ioprio_get", linux.CAP_SYS_ADMIN, "", nil), // requires cap_sys_nice or cap_sys_admin (depending)
|
||||
253: syscalls.PartiallySupportedPoint("inotify_init", InotifyInit, PointInotifyInit, "inotify events are only available inside the sandbox.", nil),
|
||||
@@ -650,7 +650,7 @@ var ARM64 = &kernel.SyscallTable{
|
||||
216: syscalls.Supported("mremap", Mremap),
|
||||
217: syscalls.Error("add_key", linuxerr.EACCES, "Not available to user.", nil),
|
||||
218: syscalls.Error("request_key", linuxerr.EACCES, "Not available to user.", nil),
|
||||
219: syscalls.Error("keyctl", linuxerr.EACCES, "Not available to user.", nil),
|
||||
219: syscalls.PartiallySupported("keyctl", Keyctl, "Only supports session keyrings with zero keys in them.", nil),
|
||||
220: syscalls.PartiallySupportedPoint("clone", Clone, PointClone, "Options CLONE_PIDFD, CLONE_NEWCGROUP, CLONE_PARENT, CLONE_NEWTIME, CLONE_CLEAR_SIGHAND, and CLONE_SYSVSEM not supported.", nil),
|
||||
221: syscalls.SupportedPoint("execve", Execve, PointExecve),
|
||||
222: syscalls.Supported("mmap", Mmap),
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
// Copyright 2023 The gVisor Authors.
|
||||
//
|
||||
// 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 linux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"gvisor.dev/gvisor/pkg/abi/linux"
|
||||
"gvisor.dev/gvisor/pkg/errors/linuxerr"
|
||||
"gvisor.dev/gvisor/pkg/log"
|
||||
"gvisor.dev/gvisor/pkg/sentry/arch"
|
||||
"gvisor.dev/gvisor/pkg/sentry/kernel"
|
||||
"gvisor.dev/gvisor/pkg/sentry/kernel/auth"
|
||||
)
|
||||
|
||||
// Keyctl implements Linux syscall keyctl(2).
|
||||
func Keyctl(t *kernel.Task, sysno uintptr, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
|
||||
switch args[0].Int() {
|
||||
case linux.KEYCTL_GET_KEYRING_ID:
|
||||
return keyCtlGetKeyringID(t, args)
|
||||
case linux.KEYCTL_DESCRIBE:
|
||||
return keyctlDescribe(t, args)
|
||||
case linux.KEYCTL_JOIN_SESSION_KEYRING:
|
||||
return keyctlJoinSessionKeyring(t, args)
|
||||
case linux.KEYCTL_SETPERM:
|
||||
return keyctlSetPerm(t, args)
|
||||
}
|
||||
log.Debugf("Unimplemented keyctl operation: %d", args[0].Int())
|
||||
kernel.IncrementUnimplementedSyscallCounter(sysno)
|
||||
return 0, nil, linuxerr.ENOSYS
|
||||
}
|
||||
|
||||
// keyCtlGetKeyringID implements keyctl(2) with operation
|
||||
// KEYCTL_GET_KEYRING_ID.
|
||||
func keyCtlGetKeyringID(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
|
||||
keyID := auth.KeySerial(args[1].Int())
|
||||
var key *auth.Key
|
||||
var err error
|
||||
if keyID > 0 {
|
||||
// Not a special key ID, so return as-is.
|
||||
return uintptr(keyID), nil, nil
|
||||
}
|
||||
switch keyID {
|
||||
case linux.KEY_SPEC_SESSION_KEYRING:
|
||||
key, err = t.SessionKeyring()
|
||||
default:
|
||||
if keyID <= 0 {
|
||||
// Other special key IDs are not implemented.
|
||||
return 0, nil, linuxerr.ENOSYS
|
||||
}
|
||||
// For positive key IDs, KEYCTL_GET_KEYRING_ID can be used as an existence
|
||||
// and permissions check.
|
||||
key, err = t.LookupKey(keyID)
|
||||
}
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
return uintptr(key.ID), nil, nil
|
||||
}
|
||||
|
||||
// keyctlDescribe implements keyctl(2) with operation KEYCTL_DESCRIBE.
|
||||
func keyctlDescribe(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
|
||||
keyID := auth.KeySerial(args[1].Int())
|
||||
bufPtr := args[2].Pointer()
|
||||
bufSize := args[3].SizeT()
|
||||
|
||||
// Get address range to write to.
|
||||
if bufSize > math.MaxInt32 {
|
||||
bufSize = math.MaxInt32
|
||||
}
|
||||
|
||||
var key *auth.Key
|
||||
var err error
|
||||
switch keyID {
|
||||
case linux.KEY_SPEC_SESSION_KEYRING:
|
||||
key, err = t.SessionKeyring()
|
||||
default:
|
||||
key, err = t.LookupKey(keyID)
|
||||
}
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
uid := t.UserNamespace().MapFromKUID(key.KUID())
|
||||
gid := t.UserNamespace().MapFromKGID(key.KGID())
|
||||
keyDesc := fmt.Sprintf("%s;%d;%d;%08x;%s\x00", key.Type(), uid, gid, uint64(key.Permissions()), key.Description)
|
||||
if bufSize > 0 {
|
||||
toWrite := uint(len(keyDesc))
|
||||
if toWrite > bufSize {
|
||||
toWrite = bufSize
|
||||
}
|
||||
_, err = t.CopyOutBytes(bufPtr, []byte(keyDesc)[:toWrite])
|
||||
}
|
||||
// The KEYCTL_DESCRIBE operation returns the length of the full string,
|
||||
// regardless of whether or not it was fully written out to userspace.
|
||||
// It includes the zero byte at the end in the returned length.
|
||||
return uintptr(len(keyDesc)), nil, err
|
||||
}
|
||||
|
||||
// keyctlJoinSessionKeyring implements keyctl(2) with operation
|
||||
// KEYCTL_JOIN_SESSION_KEYRING.
|
||||
func keyctlJoinSessionKeyring(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
|
||||
keyDescPtr := args[1].Pointer()
|
||||
var key *auth.Key
|
||||
var err error
|
||||
if keyDescPtr == 0 {
|
||||
// Creating an anonymous keyring.
|
||||
key, err = t.JoinSessionKeyring(nil)
|
||||
} else {
|
||||
// Joining a named keyring. Read in its description.
|
||||
var keyringDesc string
|
||||
keyringDesc, err = t.CopyInString(keyDescPtr, auth.MaxKeyDescSize)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
key, err = t.JoinSessionKeyring(&keyringDesc)
|
||||
}
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
return uintptr(key.ID), nil, nil
|
||||
}
|
||||
|
||||
// keyctlSetPerm implements keyctl(2) with operation KEYCTL_SETPERM.
|
||||
func keyctlSetPerm(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
|
||||
keyID := auth.KeySerial(args[1].Int())
|
||||
newPerms := auth.KeyPermissions(args[2].Uint64())
|
||||
var key *auth.Key
|
||||
var err error
|
||||
switch keyID {
|
||||
case linux.KEY_SPEC_SESSION_KEYRING:
|
||||
key, err = t.SessionKeyring()
|
||||
default:
|
||||
key, err = t.UserNamespace().Keys.Lookup(keyID)
|
||||
}
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
return 0, nil, t.SetPermsOnKey(key, newPerms)
|
||||
}
|
||||
@@ -316,6 +316,10 @@ syscall_test(
|
||||
test = "//test/syscalls/linux:kcov_test",
|
||||
)
|
||||
|
||||
syscall_test(
|
||||
test = "//test/syscalls/linux:keys_test",
|
||||
)
|
||||
|
||||
syscall_test(
|
||||
test = "//test/syscalls/linux:kill_test",
|
||||
)
|
||||
|
||||
@@ -1176,6 +1176,23 @@ cc_binary(
|
||||
],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "keys_test",
|
||||
testonly = 1,
|
||||
srcs = ["keys.cc"],
|
||||
linkstatic = 1,
|
||||
deps = [
|
||||
gtest,
|
||||
"//test/util:posix_error",
|
||||
"//test/util:test_main",
|
||||
"//test/util:thread_util",
|
||||
"@com_google_absl//absl/random",
|
||||
"@com_google_absl//absl/strings",
|
||||
"@com_google_absl//absl/strings:str_format",
|
||||
"@com_google_absl//absl/synchronization",
|
||||
],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "kill_test",
|
||||
testonly = 1,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user