요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
====================
Credentials in Linux
====================
By: David Howells <dhowells@redhat.com>
.. contents:: :local:
Overview
========
There are several parts to the security check performed by Linux when one
object acts upon another:
1. Objects.
Objects are things in the system that may be acted upon directly by
userspace programs. Linux has a variety of actionable objects, including:
- Tasks
- Files/inodes
- Sockets
- Message queues
- Shared memory segments
- Semaphores
- Keys
As a part of the description of all these objects there is a set of
credentials. What's in the set depends on the type of object.
2. Object ownership.
Amongst the credentials of most objects, there will be a subset that
indicates the ownership of that object. This is used for resource
accounting and limitation (disk quotas and task rlimits for example).
In a standard UNIX filesystem, for instance, this will be defined by the
UID marked on the inode.
3. The objective context.
Also amongst the credentials of those objects, there will be a subset that
indicates the 'objective context' of that object. This may or may not be
the same set as in (2) - in standard UNIX files, for instance, this is the
defined by the UID and the GID marked on the inode.
The objective context is used as part of the security calculation that is
carried out when an object is acted upon.
4. Subjects.
A subject is an object that is acting upon another object.
Most of the objects in the system are inactive: they don't act on other
objects within the system. Processes/tasks are the obvious exception:
they do stuff; they access and manipulate things.
Objects other than tasks may under some circumstances also be subjects.
For instance an open file may send SIGIO to a task using the UID and EUID
given to it by a task that called ``fcntl(F_SETOWN)`` upon it. In this case,
the file struct will have a subjective context too.
5. The subjective context.
A subject has an additional interpretation of its credentials. A subset
of its credentials forms the 'subjective context'. The subjective context
is used as part of the security calculation that is carried out when a
subject acts.
A Linux task, for example, has the FSUID, FSGID and the supplementary
group list for when it is acting upon a file - which are quite separate
from the real UID and GID that normally form the objective context of the
task.
6. Actions.
Linux has a number of actions available that a subject may perform upon an
object. The set of actions available depends on the nature of the subject
and the object.
Actions include reading, writing, creating and deleting files; forking or
signalling and tracing tasks.
7. Rules, access control lists and security calculations.
When a subject acts upon an object, a security calculation is made. This
involves taking the subjective context, the objective context and the
action, and searching one or more sets of rules to see whether the subject
is granted or denied permission to act in the desired manner on the
object, given those contexts.
There are two main sources of rules:
a. Discretionary access control (DAC):
Sometimes the object will include sets of rules as part of its
description. This is an 'Access Control List' or 'ACL'. A Linux
file may supply more than one ACL.
A traditional UNIX file, for example, includes a permissions mask that
is an abbreviated ACL with three fixed classes of subject ('user',
'group' and 'other'), each of which may be granted certain privileges
('read', 'write' and 'execute' - whatever those map to for the object
in question). UNIX file permissions do not allow the arbitrary
specification of subjects, however, and so are of limited use.
A Linux file might also sport a POSIX ACL. This is a list of rules
that grants various permissions to arbitrary subjects.
b. Mandatory access control (MAC):
The system as a whole may have one or more sets of rules that get
applied to all subjects and objects, regardless of their source.
SELinux and Smack are examples of this.
In the case of SELinux and Smack, each object is given a label as part
of its credentials. When an action is requested, they take the
subject label, the object label and the action and look for a rule
that says that this action is either granted or denied.
Types of Credentials
====================
The Linux kernel supports the following types of credentials:
1. Traditional UNIX credentials.
- Real User ID
- Real Group ID
The UID and GID are carried by most, if not all, Linux objects, even if in
some cases it has to be invented (FAT or CIFS files for example, which are
derived from Windows). These (mostly) define the objective context of
that object, with tasks being slightly different in some cases.
- Effective, Saved and FS User ID
- Effective, Saved and FS Group ID
- Supplementary groups
These are additional credentials used by tasks only. Usually, an
EUID/EGID/GROUPS will be used as the subjective context, and real UID/GID
will be used as the objective. For tasks, it should be noted that this is
not always true.
2. Capabilities.
- Set of permitted capabilities
- Set of inheritable capabilities
- Set of effective capabilities
- Capability bounding set
These are only carried by tasks. They indicate superior capabilities
granted piecemeal to a task that an ordinary task wouldn't otherwise have.
These are manipulated implicitly by changes to the traditional UNIX
credentials, but can also be manipulated directly by the ``capset()``
system call.
The permitted capabilities are those caps that the process might grant
itself to its effective or permitted sets through ``capset()``. This
inheritable set might also be so constrained.
The effective capabilities are the ones that a task is actually allowed to
make use of itself.
The inheritable capabilities are the ones that may get passed across
``execve()``.
The bounding set limits the capabilities that may be inherited across
``execve()``, especially when a binary is executed that will execute as
UID 0.
3. Secure management flags (securebits).
These are only carried by tasks. These govern the way the above
credentials are manipulated and inherited over certain operations such as
execve(). They aren't used directly as objective or subjective
credentials.
4. Keys and keyrings.
These are only carried by tasks. They carry and cache security tokens
that don't fit into the other standard UNIX credentials. They are for
making such things as network filesystem keys available to the file
accesses performed by processes, without the necessity of ordinary
programs having to know about security details involved.
Keyrings are a special type of key. They carry sets of other keys and can
be searched for the desired key. Each process may subscribe to a number
of keyrings:
Per-thread keying
Per-process keyring
Per-session keyring
When a process accesses a key, if not already present, it will normally be
cached on one of these keyrings for future accesses to find.
For more information on using keys, see ``Documentation/security/keys/*``.
5. LSM
The Linux Security Module allows extra controls to be placed over the
operations that a task may do. Currently Linux supports several LSM
options.
Some work by labelling the objects in a system and then applying sets of
rules (policies) that say what operations a task with one label may do to
an object with another label.
6. AF_KEY
This is a socket-based approach to credential management for networking
stacks [RFC 2367]. It isn't discussed by this document as it doesn't
interact directly with task and file credentials; rather it keeps system
level credentials.
When a file is opened, part of the opening task's subjective context is
recorded in the file struct created. This allows operations using that file
struct to use those credentials instead of the subjective context of the task
that issued the operation. An example of this would be a file opened on a
network filesystem where the credentials of the opened file should be presented
to the server, regardless of who is actually doing a read or a write upon it.
File Markings
=============
Files on disk or obtained over the network may have annotations that form the
objective security context of that file. Depending on the type of filesystem,
this may include one or more of the following:
* UNIX UID, GID, mode;
* Windows user ID;
* Access control list;
* LSM security label;
* UNIX exec privilege escalation bits (SUID/SGID);
* File capabilities exec privilege escalation bits.
These are compared to the task's subjective security context, and certain
operations allowed or disallowed as a result. In the case of execve(), the
privilege escalation bits come into play, and may allow the resulting process
extra privileges, based on the annotations on the executable file.
Task Credentials
================
In Linux, all of a task's credentials are held in (uid, gid) or through
(groups, keys, LSM security) a refcounted structure of type 'struct cred'.
Each task points to its credentials by a pointer called 'cred' in its
task_struct.
Once a set of credentials has been prepared and committed, it may not be
changed, barring the following exceptions:
1. its reference count may be changed;
2. the reference count on the group_info struct it points to may be changed;
3. the reference count on the security data it points to may be changed;
4. the reference count on any keyrings it points to may be changed;
5. any keyrings it points to may be revoked, expired or have their security
attributes changed; and
6. the contents of any keyrings to which it points may be changed (the whole
point of keyrings being a shared set of credentials, modifiable by anyone
with appropriate access).
To alter anything in the cred struct, the copy-and-replace principle must be
adhered to. First take a copy, then alter the copy and then use RCU to change
the task pointer to make it point to the new copy. There are wrappers to aid
with this (see below).
A task may only alter its _own_ credentials; it is no longer permitted for a
task to alter another's credentials. This means the ``capset()`` system call
is no longer permitted to take any PID other than the one of the current
process. Also ``keyctl_instantiate()`` and ``keyctl_negate()`` functions no
longer permit attachment to process-specific keyrings in the requesting
process as the instantiating process may need to create them.
Immutable Credentials
---------------------
Once a set of credentials has been made public (by calling ``commit_creds()``
for example), it must be considered immutable, barring two exceptions:
1. The reference count may be altered.
2. While the keyring subscriptions of a set of credentials may not be
changed, the keyrings subscribed to may have their contents altered.
To catch accidental credential alteration at compile time, struct task_struct
has _const_ pointers to its credential sets, as does struct file. Furthermore,
certain functions such as ``get_cred()`` and ``put_cred()`` operate on const
pointers, thus rendering casts unnecessary, but require to temporarily ditch
the const qualification to be able to alter the reference count.
Accessing Task Credentials
--------------------------
A task being able to alter only its own credentials permits the current process
to read or replace its own credentials without the need for any form of locking
-- which simplifies things greatly. It can just call::
const struct cred *current_cred()
to get a pointer to its credentials structure, and it doesn't have to release
it afterwards.
There are convenience wrappers for retrieving specific aspects of a task's
credentials (the value is simply returned in each case)::
uid_t current_uid(void) Current's real UID
gid_t current_gid(void) Current's real GID
uid_t current_euid(void) Current's effective UID
gid_t current_egid(void) Current's effective GID
uid_t current_fsuid(void) Current's file access UID
gid_t current_fsgid(void) Current's file access GID
kernel_cap_t current_cap(void) Current's effective capabilities
struct user_struct *current_user(void) Current's user account
There are also convenience wrappers for retrieving specific associated pairs of
a task's credentials::
void current_uid_gid(uid_t *, gid_t *);
void current_euid_egid(uid_t *, gid_t *);
void current_fsuid_fsgid(uid_t *, gid_t *);
which return these pairs of values through their arguments after retrieving
them from the current task's credentials.
In addition, there is a function for obtaining a reference on the current
process's current set of credentials::
const struct cred *get_current_cred(void);
and functions for getting references to one of the credentials that don't
actually live in struct cred::
struct user_struct *get_current_user(void);
struct group_info *get_current_groups(void);
which get references to the current process's user accounting structure and
supplementary groups list respectively.
Once a reference has been obtained, it must be released with ``put_cred()``,
``free_uid()`` or ``put_group_info()`` as appropriate.
Accessing Another Task's Credentials
------------------------------------
While a task may access its own credentials without the need for locking, the
same is not true of a task wanting to access another task's credentials. It
must use the RCU read lock and ``rcu_dereference()``.
The ``rcu_dereference()`` is wrapped by::
const struct cred *__task_cred(struct task_struct *task);
This should be used inside the RCU read lock, as in the following example::
void foo(struct task_struct *t, struct foo_data *f)
{
const struct cred *tcred;
...
rcu_read_lock();
tcred = __task_cred(t);
f->uid = tcred->uid;
f->gid = tcred->gid;
f->groups = get_group_info(tcred->groups);
rcu_read_unlock();
...
}
Should it be necessary to hold another task's credentials for a long period of
time, and possibly to sleep while doing so, then the caller should get a
reference on them using::
const struct cred *get_task_cred(struct task_struct *task);
This does all the RCU magic inside of it. The caller must call put_cred() on
the credentials so obtained when they're finished with.
.. note::
The result of ``__task_cred()`` should not be passed directly to
``get_cred()`` as this may race with ``commit_cred()``.
There are a couple of convenience functions to access bits of another task's
credentials, hiding the RCU magic from the caller::
uid_t task_uid(task) Task's real UID
uid_t task_euid(task) Task's effective UID
If the caller is holding the RCU read lock at the time anyway, then::
__task_cred(task)->uid
__task_cred(task)->euid
should be used instead. Similarly, if multiple aspects of a task's credentials
need to be accessed, RCU read lock should be used, ``__task_cred()`` called,
the result stored in a temporary pointer and then the credential aspects called
from that before dropping the lock. This prevents the potentially expensive
RCU magic from being invoked multiple times.
Should some other single aspect of another task's credentials need to be
accessed, then this can be used::
task_cred_xxx(task, member)
where 'member' is a non-pointer member of the cred struct. For instance::
uid_t task_cred_xxx(task, suid);
will retrieve 'struct cred::suid' from the task, doing the appropriate RCU
magic. This may not be used for pointer members as what they point to may
disappear the moment the RCU read lock is dropped.
Altering Credentials
--------------------
As previously mentioned, a task may only alter its own credentials, and may not
alter those of another task. This means that it doesn't need to use any
locking to alter its own credentials.
To alter the current process's credentials, a function should first prepare a
new set of credentials by calling::
struct cred *prepare_creds(void);
this locks current->cred_replace_mutex and then allocates and constructs a
duplicate of the current process's credentials, returning with the mutex still
held if successful. It returns NULL if not successful (out of memory).
The mutex prevents ``ptrace()`` from altering the ptrace state of a process
while security checks on credentials construction and changing is taking place
as the ptrace state may alter the outcome, particularly in the case of
``execve()``.
The new credentials set should be altered appropriately, and any security
checks and hooks done. Both the current and the proposed sets of credentials
are available for this purpose as current_cred() will return the current set
still at this point.
When replacing the group list, the new list must be sorted before it
is added to the credential, as a binary search is used to test for
membership. In practice, this means groups_sort() should be
called before set_groups() or set_current_groups().
groups_sort() must not be called on a ``struct group_list`` which
is shared as it may permute elements as part of the sorting process
even if the array is already sorted.
When the credential set is ready, it should be committed to the current process
by calling::
int commit_creds(struct cred *new);
This will alter various aspects of the credentials and the process, giving the
LSM a chance to do likewise, then it will use ``rcu_assign_pointer()`` to
actually commit the new credentials to ``current->cred``, it will release
``current->cred_replace_mutex`` to allow ``ptrace()`` to take place, and it
will notify the scheduler and others of the changes.
This function is guaranteed to return 0, so that it can be tail-called at the
end of such functions as ``sys_setresuid()``.
Note that this function consumes the caller's reference to the new credentials.
The caller should _not_ call ``put_cred()`` on the new credentials afterwards.
Furthermore, once this function has been called on a new set of credentials,
those credentials may _not_ be changed further.
Should the security checks fail or some other error occur after
``prepare_creds()`` has been called, then the following function should be
invoked::
void abort_creds(struct cred *new);
This releases the lock on ``current->cred_replace_mutex`` that
``prepare_creds()`` got and then releases the new credentials.
A typical credentials alteration function would look something like this::
int alter_suid(uid_t suid)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
new->suid = suid;
ret = security_alter_suid(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
Managing Credentials
--------------------
There are some functions to help manage credentials:
- ``void put_cred(const struct cred *cred);``
This releases a reference to the given set of credentials. If the
reference count reaches zero, the credentials will be scheduled for
destruction by the RCU system.
- ``const struct cred *get_cred(const struct cred *cred);``
This gets a reference on a live set of credentials, returning a pointer to
that set of credentials.
Open File Credentials
=====================
When a new file is opened, a reference is obtained on the opening task's
credentials and this is attached to the file struct as ``f_cred`` in place of
``f_uid`` and ``f_gid``. Code that used to access ``file->f_uid`` and
``file->f_gid`` should now access ``file->f_cred->fsuid`` and
``file->f_cred->fsgid``.
It is safe to access ``f_cred`` without the use of RCU or locking because the
pointer will not change over the lifetime of the file struct, and nor will the
contents of the cred struct pointed to, barring the exceptions listed above
(see the Task Credentials section).
To avoid "confused deputy" privilege escalation attacks, access control checks
during subsequent operations on an opened file should use these credentials
instead of "current"'s credentials, as the file may have been passed to a more
privileged process.
Overriding the VFS's Use of Credentials
=======================================
Under some circumstances it is desirable to override the credentials used by
the VFS, and that can be done by calling into such as ``vfs_mkdir()`` with a
different set of credentials. This is done in the following places:
* ``sys_faccessat()``.
* ``vfs_coredump()``.
* nfs4recover.c.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
문서 정보와 범위
1-8이 문서는 David Howells가 작성한 Linux 자격 증명 모델 설명서다. 객체와 주체의 보안 문맥, `struct cred`의 불변성과 교체 절차, 현재 태스크 및 다른 태스크의 자격 증명 접근 방법, 열린 파일에 고정되는 자격 증명을 다룬다.
====================
Credentials in Linux
====================
By: David Howells <dhowells@redhat.com>
.. contents:: :local:
객체와 객체 소유권
9-39Linux의 보안 검사는 한 객체가 다른 객체에 작용할 때 수행된다. 사용자 공간 프로그램이 직접 다룰 수 있는 객체에는 태스크, 파일과 inode, 소켓, 메시지 큐, 공유 메모리 세그먼트, 세마포어, 키가 있다. 각 객체의 설명에는 자격 증명 집합이 포함되며, 구체적인 구성은 객체 종류마다 다르다.
대부분의 객체 자격 증명에는 소유권을 나타내는 부분집합이 있다. 이 정보는 디스크 할당량이나 태스크 자원 한도 같은 자원 회계와 제한에 쓰인다. 표준 UNIX 파일 시스템에서는 inode에 기록된 UID가 대표적인 소유권 정보다.
객체의 종류와 소유권 정보가 보안 판단의 기초가 된다.
Overview
========
There are several parts to the security check performed by Linux when one
object acts upon another:
1. Objects.
Objects are things in the system that may be acted upon directly by
userspace programs. Linux has a variety of actionable objects, including:
- Tasks
- Files/inodes
- Sockets
- Message queues
- Shared memory segments
- Semaphores
- Keys
As a part of the description of all these objects there is a set of
credentials. What's in the set depends on the type of object.
2. Object ownership.
Amongst the credentials of most objects, there will be a subset that
indicates the ownership of that object. This is used for resource
accounting and limitation (disk quotas and task rlimits for example).
In a standard UNIX filesystem, for instance, this will be defined by the
UID marked on the inode.
객관적 문맥, 주체와 주관적 문맥
40-74객체 자격 증명의 다른 부분집합은 객체의 객관적 문맥(objective context)을 나타낸다. 이 집합은 소유권 집합과 같을 수도, 다를 수도 있다. 표준 UNIX 파일에서는 inode의 UID와 GID가 객관적 문맥을 정의하며, 객체가 작용을 받을 때 수행하는 보안 계산에 사용된다.
다른 객체에 작용하는 객체를 주체(subject)라고 한다. 대부분의 객체는 비활성 상태지만 프로세스와 태스크는 다른 객체를 접근하고 조작한다. 태스크 이외의 객체도 상황에 따라 주체가 될 수 있다. 예를 들어 열린 파일은 `fcntl(F_SETOWN)`을 호출한 태스크가 부여한 UID와 EUID를 사용해 다른 태스크로 `SIGIO`를 보낼 수 있으므로, 이때 `struct file`도 주관적 문맥을 갖는다.
주체 자격 증명의 일부는 주관적 문맥(subjective context)을 이룬다. 태스크가 파일에 작용할 때는 FSUID, FSGID, 보조 그룹 목록이 주관적 문맥이 된다. 이는 일반적으로 태스크의 객관적 문맥을 이루는 실제 UID와 GID와 구별된다.
주체의 행위는 주관적 문맥과 대상 객체의 객관적 문맥을 함께 사용해 판정한다.
3. The objective context.
Also amongst the credentials of those objects, there will be a subset that
indicates the 'objective context' of that object. This may or may not be
the same set as in (2) - in standard UNIX files, for instance, this is the
defined by the UID and the GID marked on the inode.
The objective context is used as part of the security calculation that is
carried out when an object is acted upon.
4. Subjects.
A subject is an object that is acting upon another object.
Most of the objects in the system are inactive: they don't act on other
objects within the system. Processes/tasks are the obvious exception:
they do stuff; they access and manipulate things.
Objects other than tasks may under some circumstances also be subjects.
For instance an open file may send SIGIO to a task using the UID and EUID
given to it by a task that called ``fcntl(F_SETOWN)`` upon it. In this case,
the file struct will have a subjective context too.
5. The subjective context.
A subject has an additional interpretation of its credentials. A subset
of its credentials forms the 'subjective context'. The subjective context
is used as part of the security calculation that is carried out when a
subject acts.
A Linux task, for example, has the FSUID, FSGID and the supplementary
group list for when it is acting upon a file - which are quite separate
from the real UID and GID that normally form the objective context of the
task.
행위와 DAC·MAC 규칙
75-121주체가 수행할 수 있는 행위는 주체와 객체의 성격에 따라 달라진다. 파일 읽기·쓰기·생성·삭제, 태스크 fork, signal 전송, tracing 등이 그 예다. 보안 계산은 주관적 문맥, 객관적 문맥, 요청 행위를 하나 이상의 규칙 집합과 대조해 허용 또는 거부를 결정한다.
임의 접근 제어(DAC)에서는 객체 자체가 ACL을 포함할 수 있다. 전통적인 UNIX 권한 비트는 사용자·그룹·기타 세 부류에 읽기·쓰기·실행 권한을 부여하는 축약된 ACL이다. 임의의 주체를 지정할 수 없어 표현력이 제한되지만, Linux 파일은 별도의 POSIX ACL을 사용해 임의 주체에 여러 권한을 부여할 수도 있다.
강제 접근 제어(MAC)는 출처와 무관하게 모든 주체와 객체에 적용되는 시스템 전역 규칙 집합이다. SELinux와 Smack은 객체 자격 증명에 보안 레이블을 넣고, 주체 레이블·객체 레이블·요청 행위를 정책 규칙과 대조해 허용 여부를 판단한다.
두 제어 방식은 규칙의 위치와 판정 입력이 다르다.
6. Actions.
Linux has a number of actions available that a subject may perform upon an
object. The set of actions available depends on the nature of the subject
and the object.
Actions include reading, writing, creating and deleting files; forking or
signalling and tracing tasks.
7. Rules, access control lists and security calculations.
When a subject acts upon an object, a security calculation is made. This
involves taking the subjective context, the objective context and the
action, and searching one or more sets of rules to see whether the subject
is granted or denied permission to act in the desired manner on the
object, given those contexts.
There are two main sources of rules:
a. Discretionary access control (DAC):
Sometimes the object will include sets of rules as part of its
description. This is an 'Access Control List' or 'ACL'. A Linux
file may supply more than one ACL.
A traditional UNIX file, for example, includes a permissions mask that
is an abbreviated ACL with three fixed classes of subject ('user',
'group' and 'other'), each of which may be granted certain privileges
('read', 'write' and 'execute' - whatever those map to for the object
in question). UNIX file permissions do not allow the arbitrary
specification of subjects, however, and so are of limited use.
A Linux file might also sport a POSIX ACL. This is a list of rules
that grants various permissions to arbitrary subjects.
b. Mandatory access control (MAC):
The system as a whole may have one or more sets of rules that get
applied to all subjects and objects, regardless of their source.
SELinux and Smack are examples of this.
In the case of SELinux and Smack, each object is given a label as part
of its credentials. When an action is requested, they take the
subject label, the object label and the action and look for a rule
that says that this action is either granted or denied.
UNIX 자격 증명, capability와 securebits
122-178전통적인 UNIX 자격 증명에는 실제 UID·GID와 태스크 전용인 effective, saved, FS UID·GID 및 보조 그룹이 있다. UID와 GID는 FAT나 CIFS처럼 Windows에서 유래해 값을 만들어야 하는 경우를 포함해 거의 모든 Linux 객체에 부여된다. 보통 태스크의 EUID·EGID·GROUPS가 주관적 문맥, 실제 UID·GID가 객관적 문맥으로 쓰이지만 항상 그런 것은 아니다.
태스크는 permitted, inheritable, effective capability 집합과 capability bounding set을 가진다. 이들은 일반 태스크에 없는 상위 권한을 기능별로 나눠 부여한다. UNIX 자격 증명 변경에 따라 암묵적으로 조정되거나 `capset()`으로 직접 조정할 수 있다. permitted 집합은 프로세스가 effective 또는 permitted 집합에 부여할 수 있는 capability를, effective 집합은 지금 실제로 사용할 수 있는 capability를 뜻한다. inheritable 집합은 `execve()`를 넘어 전달될 수 있고, bounding set은 특히 UID 0으로 실행되는 바이너리에서 상속 가능한 capability의 상한을 정한다.
securebits는 태스크만 보유하며 `execve()` 같은 연산에서 위 자격 증명이 조작되고 상속되는 방식을 제어한다. 그 자체가 객관적 또는 주관적 자격 증명으로 직접 사용되지는 않는다.
태스크 capability 네 집합의 역할을 구분한다.
Types of Credentials
====================
The Linux kernel supports the following types of credentials:
1. Traditional UNIX credentials.
- Real User ID
- Real Group ID
The UID and GID are carried by most, if not all, Linux objects, even if in
some cases it has to be invented (FAT or CIFS files for example, which are
derived from Windows). These (mostly) define the objective context of
that object, with tasks being slightly different in some cases.
- Effective, Saved and FS User ID
- Effective, Saved and FS Group ID
- Supplementary groups
These are additional credentials used by tasks only. Usually, an
EUID/EGID/GROUPS will be used as the subjective context, and real UID/GID
will be used as the objective. For tasks, it should be noted that this is
not always true.
2. Capabilities.
- Set of permitted capabilities
- Set of inheritable capabilities
- Set of effective capabilities
- Capability bounding set
These are only carried by tasks. They indicate superior capabilities
granted piecemeal to a task that an ordinary task wouldn't otherwise have.
These are manipulated implicitly by changes to the traditional UNIX
credentials, but can also be manipulated directly by the ``capset()``
system call.
The permitted capabilities are those caps that the process might grant
itself to its effective or permitted sets through ``capset()``. This
inheritable set might also be so constrained.
The effective capabilities are the ones that a task is actually allowed to
make use of itself.
The inheritable capabilities are the ones that may get passed across
``execve()``.
The bounding set limits the capabilities that may be inherited across
``execve()``, especially when a binary is executed that will execute as
UID 0.
3. Secure management flags (securebits).
These are only carried by tasks. These govern the way the above
credentials are manipulated and inherited over certain operations such as
execve(). They aren't used directly as objective or subjective
credentials.
키·키링, LSM, AF_KEY와 파일 자격 증명
179-226키와 키링은 태스크만 보유하며 표준 UNIX 자격 증명에 맞지 않는 보안 토큰을 운반하고 캐시한다. 예를 들어 일반 프로그램이 세부 보안 절차를 몰라도 네트워크 파일 시스템 키를 파일 접근에 제공할 수 있다. 키링은 다른 키의 집합을 보유하고 검색할 수 있는 특수한 키이며, 프로세스는 스레드별·프로세스별·세션별 키링을 구독할 수 있다. 처음 접근한 키는 일반적으로 이후 검색을 위해 이들 키링 중 하나에 캐시된다. 자세한 내용은 `Documentation/security/keys/*`를 참조한다.
Linux Security Module(LSM)은 태스크 연산에 추가 통제를 적용한다. 일부 LSM은 시스템 객체에 레이블을 붙이고 한 레이블의 태스크가 다른 레이블의 객체에 수행할 수 있는 연산을 정책으로 규정한다. `AF_KEY`는 RFC 2367의 소켓 기반 네트워크 스택 자격 증명 관리 방식이다. 태스크·파일 자격 증명과 직접 상호작용하지 않고 시스템 수준 자격 증명을 유지하므로 이 문서의 범위에서는 제외한다.
파일을 열면 연 태스크의 주관적 문맥 일부가 생성된 `struct file`에 기록된다. 이후 해당 파일 구조체를 통한 연산은 연산을 실제로 요청한 태스크의 현재 문맥 대신 저장된 자격 증명을 사용할 수 있다. 네트워크 파일 시스템에서는 누가 read 또는 write를 수행하든 서버에 파일을 열 때의 자격 증명을 제시해야 하는 경우가 대표적이다.
프로세스가 구독할 수 있는 키링 범위다.
4. Keys and keyrings.
These are only carried by tasks. They carry and cache security tokens
that don't fit into the other standard UNIX credentials. They are for
making such things as network filesystem keys available to the file
accesses performed by processes, without the necessity of ordinary
programs having to know about security details involved.
Keyrings are a special type of key. They carry sets of other keys and can
be searched for the desired key. Each process may subscribe to a number
of keyrings:
Per-thread keying
Per-process keyring
Per-session keyring
When a process accesses a key, if not already present, it will normally be
cached on one of these keyrings for future accesses to find.
For more information on using keys, see ``Documentation/security/keys/*``.
5. LSM
The Linux Security Module allows extra controls to be placed over the
operations that a task may do. Currently Linux supports several LSM
options.
Some work by labelling the objects in a system and then applying sets of
rules (policies) that say what operations a task with one label may do to
an object with another label.
6. AF_KEY
This is a socket-based approach to credential management for networking
stacks [RFC 2367]. It isn't discussed by this document as it doesn't
interact directly with task and file credentials; rather it keeps system
level credentials.
When a file is opened, part of the opening task's subjective context is
recorded in the file struct created. This allows operations using that file
struct to use those credentials instead of the subjective context of the task
that issued the operation. An example of this would be a file opened on a
network filesystem where the credentials of the opened file should be presented
to the server, regardless of who is actually doing a read or a write upon it.
파일 표식과 태스크 자격 증명
227-285디스크 또는 네트워크의 파일은 객관적 보안 문맥을 이루는 표식을 가질 수 있다. 파일 시스템에 따라 UNIX UID·GID·mode, Windows 사용자 ID, ACL, LSM 보안 레이블, SUID·SGID 실행 권한 상승 비트, 파일 capability 실행 권한 상승 비트가 포함된다. 이들은 태스크의 주관적 보안 문맥과 비교되어 연산을 허용하거나 거부한다. `execve()`에서는 실행 파일 표식에 따라 결과 프로세스에 추가 권한이 주어질 수 있다.
Linux에서 태스크의 모든 자격 증명은 UID·GID 값으로 직접 또는 그룹·키·LSM 보안 정보를 가리키는 참조 계수 기반 `struct cred` 안에 보관된다. 각 `task_struct`는 `cred` 포인터로 자신의 자격 증명을 가리킨다. 준비되어 commit된 자격 증명 집합의 본체는 바꿀 수 없다. 다만 자체 참조 계수, 연결된 `group_info`·보안 데이터·키링의 참조 계수는 바뀔 수 있고, 키링은 폐기·만료·보안 속성 변경 또는 내용 변경이 가능하다.
`struct cred`의 값을 바꾸려면 copy-and-replace 원칙을 따라야 한다. 기존 자격 증명을 복사하고 사본을 수정한 뒤 RCU로 태스크 포인터를 새 사본으로 전환한다. 태스크는 자기 자격 증명만 바꿀 수 있으며 다른 태스크의 자격 증명은 바꿀 수 없다. 따라서 `capset()`은 현재 프로세스 이외의 PID를 받을 수 없고, `keyctl_instantiate()`와 `keyctl_negate()`도 요청 프로세스의 프로세스별 키링에 붙이는 동작을 더 이상 허용하지 않는다.
공개된 cred를 직접 수정하지 않고 새 사본을 만들어 원자적으로 교체한다.
File Markings
=============
Files on disk or obtained over the network may have annotations that form the
objective security context of that file. Depending on the type of filesystem,
this may include one or more of the following:
* UNIX UID, GID, mode;
* Windows user ID;
* Access control list;
* LSM security label;
* UNIX exec privilege escalation bits (SUID/SGID);
* File capabilities exec privilege escalation bits.
These are compared to the task's subjective security context, and certain
operations allowed or disallowed as a result. In the case of execve(), the
privilege escalation bits come into play, and may allow the resulting process
extra privileges, based on the annotations on the executable file.
Task Credentials
================
In Linux, all of a task's credentials are held in (uid, gid) or through
(groups, keys, LSM security) a refcounted structure of type 'struct cred'.
Each task points to its credentials by a pointer called 'cred' in its
task_struct.
Once a set of credentials has been prepared and committed, it may not be
changed, barring the following exceptions:
1. its reference count may be changed;
2. the reference count on the group_info struct it points to may be changed;
3. the reference count on the security data it points to may be changed;
4. the reference count on any keyrings it points to may be changed;
5. any keyrings it points to may be revoked, expired or have their security
attributes changed; and
6. the contents of any keyrings to which it points may be changed (the whole
point of keyrings being a shared set of credentials, modifiable by anyone
with appropriate access).
To alter anything in the cred struct, the copy-and-replace principle must be
adhered to. First take a copy, then alter the copy and then use RCU to change
the task pointer to make it point to the new copy. There are wrappers to aid
with this (see below).
A task may only alter its _own_ credentials; it is no longer permitted for a
task to alter another's credentials. This means the ``capset()`` system call
is no longer permitted to take any PID other than the one of the current
process. Also ``keyctl_instantiate()`` and ``keyctl_negate()`` functions no
longer permit attachment to process-specific keyrings in the requesting
process as the instantiating process may need to create them.
공개된 자격 증명의 불변성
286-303`commit_creds()` 등으로 공개된 자격 증명은 불변으로 취급해야 한다. 예외는 참조 계수를 바꾸는 것과, 자격 증명이 구독하는 키링 자체를 바꾸지 않은 채 그 키링의 내용을 바꾸는 것뿐이다.
실수로 자격 증명을 수정하는 코드를 컴파일 단계에서 잡기 위해 `struct task_struct`와 `struct file`은 자격 증명 집합을 `const` 포인터로 보유한다. `get_cred()`와 `put_cred()`도 `const` 포인터를 받아 불필요한 cast를 없앤다. 다만 참조 계수를 실제로 변경할 때 내부적으로 일시적으로 const 한정을 내려놓아야 한다.
Immutable Credentials
---------------------
Once a set of credentials has been made public (by calling ``commit_creds()``
for example), it must be considered immutable, barring two exceptions:
1. The reference count may be altered.
2. While the keyring subscriptions of a set of credentials may not be
changed, the keyrings subscribed to may have their contents altered.
To catch accidental credential alteration at compile time, struct task_struct
has _const_ pointers to its credential sets, as does struct file. Furthermore,
certain functions such as ``get_cred()`` and ``put_cred()`` operate on const
pointers, thus rendering casts unnecessary, but require to temporarily ditch
the const qualification to be able to alter the reference count.
현재 태스크 자격 증명 접근
304-356태스크는 자기 자격 증명만 변경할 수 있으므로 현재 프로세스는 별도 잠금 없이 자신의 자격 증명을 읽거나 교체할 수 있다. `current_cred()`는 현재 자격 증명 구조체 포인터를 반환하며 호출자가 이를 해제할 필요가 없다.
특정 값은 `current_uid()`, `current_gid()`, `current_euid()`, `current_egid()`, `current_fsuid()`, `current_fsgid()`, `current_cap()`, `current_user()` 편의 함수로 얻는다. UID·GID 쌍은 `current_uid_gid()`, `current_euid_egid()`, `current_fsuid_fsgid()`가 인자를 통해 반환한다.
오래 보유할 참조가 필요하면 `get_current_cred()`를 사용한다. `struct cred` 밖에 실제 객체가 있는 사용자 회계 구조와 보조 그룹 목록은 각각 `get_current_user()`와 `get_current_groups()`로 참조한다. 얻은 참조는 종류에 맞게 `put_cred()`, `free_uid()`, `put_group_info()`로 반드시 해제해야 한다.
반환값의 수명과 해제 책임이 API마다 다르다.
Accessing Task Credentials
--------------------------
A task being able to alter only its own credentials permits the current process
to read or replace its own credentials without the need for any form of locking
-- which simplifies things greatly. It can just call::
const struct cred *current_cred()
to get a pointer to its credentials structure, and it doesn't have to release
it afterwards.
There are convenience wrappers for retrieving specific aspects of a task's
credentials (the value is simply returned in each case)::
uid_t current_uid(void) Current's real UID
gid_t current_gid(void) Current's real GID
uid_t current_euid(void) Current's effective UID
gid_t current_egid(void) Current's effective GID
uid_t current_fsuid(void) Current's file access UID
gid_t current_fsgid(void) Current's file access GID
kernel_cap_t current_cap(void) Current's effective capabilities
struct user_struct *current_user(void) Current's user account
There are also convenience wrappers for retrieving specific associated pairs of
a task's credentials::
void current_uid_gid(uid_t *, gid_t *);
void current_euid_egid(uid_t *, gid_t *);
void current_fsuid_fsgid(uid_t *, gid_t *);
which return these pairs of values through their arguments after retrieving
them from the current task's credentials.
In addition, there is a function for obtaining a reference on the current
process's current set of credentials::
const struct cred *get_current_cred(void);
and functions for getting references to one of the credentials that don't
actually live in struct cred::
struct user_struct *get_current_user(void);
struct group_info *get_current_groups(void);
which get references to the current process's user accounting structure and
supplementary groups list respectively.
Once a reference has been obtained, it must be released with ``put_cred()``,
``free_uid()`` or ``put_group_info()`` as appropriate.
다른 태스크 자격 증명 접근
357-426다른 태스크의 자격 증명을 읽을 때는 RCU read lock과 `rcu_dereference()`가 필요하다. `__task_cred(task)`가 dereference를 감싸지만 반드시 RCU read-side critical section 안에서 사용해야 한다. 여러 필드를 읽을 때는 한 번 호출한 결과를 임시 포인터에 저장하고 필요한 값을 모두 복사한 뒤 잠금을 해제해 반복되는 RCU 비용을 피한다.
다른 태스크의 자격 증명을 오래 보유하거나 보유한 채 sleep할 수 있어야 한다면 `get_task_cred(task)`로 참조를 얻고 끝난 뒤 `put_cred()`를 호출한다. 이 함수가 필요한 RCU 절차를 내부에서 처리한다. `__task_cred()` 결과를 `get_cred()`에 직접 넘기면 `commit_cred()`와 경합할 수 있으므로 금지된다.
단일 UID는 `task_uid(task)`와 `task_euid(task)`로 읽을 수 있다. 이미 RCU read lock을 보유했다면 `__task_cred(task)->uid`처럼 직접 읽는 편이 낫다. 포인터가 아닌 단일 `struct cred` 멤버는 `task_cred_xxx(task, member)`로 읽을 수 있지만, RCU lock을 놓는 즉시 가리키는 객체가 사라질 수 있으므로 포인터 멤버에는 사용할 수 없다.
짧은 접근과 장기 보유는 서로 다른 API 수명 규칙을 따른다.
Accessing Another Task's Credentials
------------------------------------
While a task may access its own credentials without the need for locking, the
same is not true of a task wanting to access another task's credentials. It
must use the RCU read lock and ``rcu_dereference()``.
The ``rcu_dereference()`` is wrapped by::
const struct cred *__task_cred(struct task_struct *task);
This should be used inside the RCU read lock, as in the following example::
void foo(struct task_struct *t, struct foo_data *f)
{
const struct cred *tcred;
...
rcu_read_lock();
tcred = __task_cred(t);
f->uid = tcred->uid;
f->gid = tcred->gid;
f->groups = get_group_info(tcred->groups);
rcu_read_unlock();
...
}
Should it be necessary to hold another task's credentials for a long period of
time, and possibly to sleep while doing so, then the caller should get a
reference on them using::
const struct cred *get_task_cred(struct task_struct *task);
This does all the RCU magic inside of it. The caller must call put_cred() on
the credentials so obtained when they're finished with.
.. note::
The result of ``__task_cred()`` should not be passed directly to
``get_cred()`` as this may race with ``commit_cred()``.
There are a couple of convenience functions to access bits of another task's
credentials, hiding the RCU magic from the caller::
uid_t task_uid(task) Task's real UID
uid_t task_euid(task) Task's effective UID
If the caller is holding the RCU read lock at the time anyway, then::
__task_cred(task)->uid
__task_cred(task)->euid
should be used instead. Similarly, if multiple aspects of a task's credentials
need to be accessed, RCU read lock should be used, ``__task_cred()`` called,
the result stored in a temporary pointer and then the credential aspects called
from that before dropping the lock. This prevents the potentially expensive
RCU magic from being invoked multiple times.
Should some other single aspect of another task's credentials need to be
accessed, then this can be used::
task_cred_xxx(task, member)
where 'member' is a non-pointer member of the cred struct. For instance::
uid_t task_cred_xxx(task, suid);
will retrieve 'struct cred::suid' from the task, doing the appropriate RCU
magic. This may not be used for pointer members as what they point to may
disappear the moment the RCU read lock is dropped.
자격 증명 변경 절차
427-490현재 프로세스의 자격 증명을 바꾸려면 먼저 `prepare_creds()`를 호출한다. 이 함수는 `current->cred_replace_mutex`를 잠그고 현재 자격 증명의 복제본을 할당·구성한다. 성공하면 mutex를 잡은 채 새 `struct cred *`를 반환하고, 메모리가 부족하면 `NULL`을 반환한다. mutex는 자격 증명 구성과 변경의 보안 검사 중 `ptrace()` 상태가 바뀌어 판정 결과, 특히 `execve()` 결과에 영향을 주는 일을 막는다.
새 자격 증명에 필요한 변경과 보안 검사·훅을 수행하는 동안 `current_cred()`는 여전히 기존 집합을 반환하므로 두 집합을 비교할 수 있다. 그룹 목록을 교체할 때 membership 검사가 이진 검색을 사용하므로 `set_groups()` 또는 `set_current_groups()` 전에 `groups_sort()`로 정렬해야 한다. 정렬은 이미 정렬된 배열도 재배치할 수 있으므로 공유 중인 `struct group_list`에는 호출하면 안 된다.
준비가 끝나면 `commit_creds(new)`가 자격 증명과 프로세스 상태를 조정하고 LSM 훅을 호출한 뒤 `rcu_assign_pointer()`로 `current->cred`를 교체한다. 이후 `cred_replace_mutex`를 해제하고 scheduler 등 관련 구성 요소에 변경을 알린다. 항상 0을 반환하므로 `sys_setresuid()` 같은 함수 끝에서 tail call할 수 있다. 이 함수는 호출자의 새 자격 증명 참조를 소비하므로 이후 `put_cred()`를 호출하거나 새 집합을 더 수정해서는 안 된다.
`prepare_creds()` 뒤 보안 검사가 실패하거나 다른 오류가 발생하면 `abort_creds(new)`를 호출한다. 이 함수는 `prepare_creds()`가 잡은 `cred_replace_mutex`를 해제하고 새 자격 증명도 해제한다.
새 cred는 검사 결과에 따라 commit되거나 폐기된다.
Altering Credentials
--------------------
As previously mentioned, a task may only alter its own credentials, and may not
alter those of another task. This means that it doesn't need to use any
locking to alter its own credentials.
To alter the current process's credentials, a function should first prepare a
new set of credentials by calling::
struct cred *prepare_creds(void);
this locks current->cred_replace_mutex and then allocates and constructs a
duplicate of the current process's credentials, returning with the mutex still
held if successful. It returns NULL if not successful (out of memory).
The mutex prevents ``ptrace()`` from altering the ptrace state of a process
while security checks on credentials construction and changing is taking place
as the ptrace state may alter the outcome, particularly in the case of
``execve()``.
The new credentials set should be altered appropriately, and any security
checks and hooks done. Both the current and the proposed sets of credentials
are available for this purpose as current_cred() will return the current set
still at this point.
When replacing the group list, the new list must be sorted before it
is added to the credential, as a binary search is used to test for
membership. In practice, this means groups_sort() should be
called before set_groups() or set_current_groups().
groups_sort() must not be called on a ``struct group_list`` which
is shared as it may permute elements as part of the sorting process
even if the array is already sorted.
When the credential set is ready, it should be committed to the current process
by calling::
int commit_creds(struct cred *new);
This will alter various aspects of the credentials and the process, giving the
LSM a chance to do likewise, then it will use ``rcu_assign_pointer()`` to
actually commit the new credentials to ``current->cred``, it will release
``current->cred_replace_mutex`` to allow ``ptrace()`` to take place, and it
will notify the scheduler and others of the changes.
This function is guaranteed to return 0, so that it can be tail-called at the
end of such functions as ``sys_setresuid()``.
Note that this function consumes the caller's reference to the new credentials.
The caller should _not_ call ``put_cred()`` on the new credentials afterwards.
Furthermore, once this function has been called on a new set of credentials,
those credentials may _not_ be changed further.
Should the security checks fail or some other error occur after
``prepare_creds()`` has been called, then the following function should be
invoked::
void abort_creds(struct cred *new);
This releases the lock on ``current->cred_replace_mutex`` that
``prepare_creds()`` got and then releases the new credentials.
SUID 변경 예제
491-513예제 `alter_suid()`는 표준적인 변경 패턴을 보여 준다. `prepare_creds()`가 실패하면 `-ENOMEM`을 반환하고, 성공하면 `new->suid`를 바꾼 뒤 `security_alter_suid(new)`로 보안 검사를 수행한다. 검사가 실패하면 `abort_creds(new)`로 사본과 잠금을 정리하고 오류를 반환한다. 성공 경로는 `commit_creds(new)`를 그대로 반환해 새 집합을 현재 태스크에 적용한다.
A typical credentials alteration function would look something like this::
int alter_suid(uid_t suid)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
new->suid = suid;
ret = security_alter_suid(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
자격 증명 참조 관리
514-530`put_cred(const struct cred *cred)`는 자격 증명 집합의 참조 하나를 해제한다. 참조 계수가 0이 되면 RCU 시스템이 해당 자격 증명의 파괴를 예약한다. `get_cred(const struct cred *cred)`는 살아 있는 자격 증명 집합의 참조를 하나 얻고 그 포인터를 반환한다. 따라서 참조를 얻은 각 경로는 대응하는 `put_cred()`를 보장해야 한다.
Managing Credentials
--------------------
There are some functions to help manage credentials:
- ``void put_cred(const struct cred *cred);``
This releases a reference to the given set of credentials. If the
reference count reaches zero, the credentials will be scheduled for
destruction by the RCU system.
- ``const struct cred *get_cred(const struct cred *cred);``
This gets a reference on a live set of credentials, returning a pointer to
that set of credentials.
열린 파일에 고정되는 자격 증명
531-549새 파일을 열면 커널은 연 태스크의 자격 증명 참조를 얻어 `f_uid`와 `f_gid` 대신 `struct file`의 `f_cred`에 붙인다. 과거 `file->f_uid`와 `file->f_gid`를 읽던 코드는 각각 `file->f_cred->fsuid`와 `file->f_cred->fsgid`를 사용해야 한다.
`f_cred` 포인터는 파일 구조체의 수명 동안 바뀌지 않고 앞서 설명한 예외를 제외하면 가리키는 `struct cred` 내용도 불변이므로 RCU나 별도 잠금 없이 접근해도 안전하다. 열린 파일이 더 높은 권한의 프로세스에 전달될 수 있으므로, 이후 연산의 접근 제어는 현재 태스크의 자격 증명이 아니라 `f_cred`를 사용해야 confused deputy 권한 상승 공격을 피할 수 있다.
Open File Credentials
=====================
When a new file is opened, a reference is obtained on the opening task's
credentials and this is attached to the file struct as ``f_cred`` in place of
``f_uid`` and ``f_gid``. Code that used to access ``file->f_uid`` and
``file->f_gid`` should now access ``file->f_cred->fsuid`` and
``file->f_cred->fsgid``.
It is safe to access ``f_cred`` without the use of RCU or locking because the
pointer will not change over the lifetime of the file struct, and nor will the
contents of the cred struct pointed to, barring the exceptions listed above
(see the Task Credentials section).
To avoid "confused deputy" privilege escalation attacks, access control checks
during subsequent operations on an opened file should use these credentials
instead of "current"'s credentials, as the file may have been passed to a more
privileged process.
VFS 자격 증명 사용 재정의
550-559일부 상황에서는 VFS가 사용할 자격 증명을 일시적으로 재정의할 필요가 있다. 예를 들어 다른 자격 증명 집합으로 `vfs_mkdir()` 같은 함수를 호출하는 경우다. 원문은 이 방식을 사용하는 위치로 `sys_faccessat()`, `vfs_coredump()`, `nfs4recover.c`를 열거한다.
원문에 기록된 대표 호출 위치다.
Overriding the VFS's Use of Credentials
=======================================
Under some circumstances it is desirable to override the credentials used by
the VFS, and that can be done by calling into such as ``vfs_mkdir()`` with a
different set of credentials. This is done in the following places:
* ``sys_faccessat()``.
* ``vfs_coredump()``.
* nfs4recover.c.
요약·해설
credentials.rst:1-559이 문서는 보안 판정의 주체·객체 문맥부터 `struct cred`의 불변성과 참조 수명, 현재·다른 태스크의 안전한 접근, 새 자격 증명의 준비·검사·commit 또는 abort, 열린 파일의 `f_cred`까지 커널 자격 증명 API의 핵심 규칙을 연결해 설명합니다.