← Documents Documentation/security/credentials.rst GitHub 원문 ↗

Linux 6.18.37 · Security

Linux 자격 증명(Credentials)

Linux의 객체·주체 보안 문맥과 struct cred 불변성, RCU 접근, prepare/commit/abort 교체 절차, 열린 파일 자격 증명을 설명합니다.

Source pathDocumentation/security/credentials.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

credentials.rst:1-559

이 문서는 보안 판정의 주체·객체 문맥부터 `struct cred`의 불변성과 참조 수명, 현재·다른 태스크의 안전한 접근, 새 자격 증명의 준비·검사·commit 또는 abort, 열린 파일의 `f_cred`까지 커널 자격 증명 API의 핵심 규칙을 연결해 설명합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 ====================
2 Credentials in Linux
3 ====================
4
5 By: David Howells <[email protected]>
6
7 .. contents:: :local:
8
9 Overview
10 ========
11
12 There are several parts to the security check performed by Linux when one
13 object acts upon another:
14
15 1. Objects.
16
17 Objects are things in the system that may be acted upon directly by
18 userspace programs. Linux has a variety of actionable objects, including:
19
20 - Tasks
21 - Files/inodes
22 - Sockets
23 - Message queues
24 - Shared memory segments
25 - Semaphores
26 - Keys
27
28 As a part of the description of all these objects there is a set of
29 credentials. What's in the set depends on the type of object.
30
31 2. Object ownership.
32
33 Amongst the credentials of most objects, there will be a subset that
34 indicates the ownership of that object. This is used for resource
35 accounting and limitation (disk quotas and task rlimits for example).
36
37 In a standard UNIX filesystem, for instance, this will be defined by the
38 UID marked on the inode.
39
40 3. The objective context.
41
42 Also amongst the credentials of those objects, there will be a subset that
43 indicates the 'objective context' of that object. This may or may not be
44 the same set as in (2) - in standard UNIX files, for instance, this is the
45 defined by the UID and the GID marked on the inode.
46
47 The objective context is used as part of the security calculation that is
48 carried out when an object is acted upon.
49
50 4. Subjects.
51
52 A subject is an object that is acting upon another object.
53
54 Most of the objects in the system are inactive: they don't act on other
55 objects within the system. Processes/tasks are the obvious exception:
56 they do stuff; they access and manipulate things.
57
58 Objects other than tasks may under some circumstances also be subjects.
59 For instance an open file may send SIGIO to a task using the UID and EUID
60 given to it by a task that called ``fcntl(F_SETOWN)`` upon it. In this case,
61 the file struct will have a subjective context too.
62
63 5. The subjective context.
64
65 A subject has an additional interpretation of its credentials. A subset
66 of its credentials forms the 'subjective context'. The subjective context
67 is used as part of the security calculation that is carried out when a
68 subject acts.
69
70 A Linux task, for example, has the FSUID, FSGID and the supplementary
71 group list for when it is acting upon a file - which are quite separate
72 from the real UID and GID that normally form the objective context of the
73 task.
74
75 6. Actions.
76
77 Linux has a number of actions available that a subject may perform upon an
78 object. The set of actions available depends on the nature of the subject
79 and the object.
80
81 Actions include reading, writing, creating and deleting files; forking or
82 signalling and tracing tasks.
83
84 7. Rules, access control lists and security calculations.
85
86 When a subject acts upon an object, a security calculation is made. This
87 involves taking the subjective context, the objective context and the
88 action, and searching one or more sets of rules to see whether the subject
89 is granted or denied permission to act in the desired manner on the
90 object, given those contexts.
91
92 There are two main sources of rules:
93
94 a. Discretionary access control (DAC):
95
96 Sometimes the object will include sets of rules as part of its
97 description. This is an 'Access Control List' or 'ACL'. A Linux
98 file may supply more than one ACL.
99
100 A traditional UNIX file, for example, includes a permissions mask that
101 is an abbreviated ACL with three fixed classes of subject ('user',
102 'group' and 'other'), each of which may be granted certain privileges
103 ('read', 'write' and 'execute' - whatever those map to for the object
104 in question). UNIX file permissions do not allow the arbitrary
105 specification of subjects, however, and so are of limited use.
106
107 A Linux file might also sport a POSIX ACL. This is a list of rules
108 that grants various permissions to arbitrary subjects.
109
110 b. Mandatory access control (MAC):
111
112 The system as a whole may have one or more sets of rules that get
113 applied to all subjects and objects, regardless of their source.
114 SELinux and Smack are examples of this.
115
116 In the case of SELinux and Smack, each object is given a label as part
117 of its credentials. When an action is requested, they take the
118 subject label, the object label and the action and look for a rule
119 that says that this action is either granted or denied.
120
121
122 Types of Credentials
123 ====================
124
125 The Linux kernel supports the following types of credentials:
126
127 1. Traditional UNIX credentials.
128
129 - Real User ID
130 - Real Group ID
131
132 The UID and GID are carried by most, if not all, Linux objects, even if in
133 some cases it has to be invented (FAT or CIFS files for example, which are
134 derived from Windows). These (mostly) define the objective context of
135 that object, with tasks being slightly different in some cases.
136
137 - Effective, Saved and FS User ID
138 - Effective, Saved and FS Group ID
139 - Supplementary groups
140
141 These are additional credentials used by tasks only. Usually, an
142 EUID/EGID/GROUPS will be used as the subjective context, and real UID/GID
143 will be used as the objective. For tasks, it should be noted that this is
144 not always true.
145
146 2. Capabilities.
147
148 - Set of permitted capabilities
149 - Set of inheritable capabilities
150 - Set of effective capabilities
151 - Capability bounding set
152
153 These are only carried by tasks. They indicate superior capabilities
154 granted piecemeal to a task that an ordinary task wouldn't otherwise have.
155 These are manipulated implicitly by changes to the traditional UNIX
156 credentials, but can also be manipulated directly by the ``capset()``
157 system call.
158
159 The permitted capabilities are those caps that the process might grant
160 itself to its effective or permitted sets through ``capset()``. This
161 inheritable set might also be so constrained.
162
163 The effective capabilities are the ones that a task is actually allowed to
164 make use of itself.
165
166 The inheritable capabilities are the ones that may get passed across
167 ``execve()``.
168
169 The bounding set limits the capabilities that may be inherited across
170 ``execve()``, especially when a binary is executed that will execute as
171 UID 0.
172
173 3. Secure management flags (securebits).
174
175 These are only carried by tasks. These govern the way the above
176 credentials are manipulated and inherited over certain operations such as
177 execve(). They aren't used directly as objective or subjective
178 credentials.
179
180 4. Keys and keyrings.
181
182 These are only carried by tasks. They carry and cache security tokens
183 that don't fit into the other standard UNIX credentials. They are for
184 making such things as network filesystem keys available to the file
185 accesses performed by processes, without the necessity of ordinary
186 programs having to know about security details involved.
187
188 Keyrings are a special type of key. They carry sets of other keys and can
189 be searched for the desired key. Each process may subscribe to a number
190 of keyrings:
191
192 Per-thread keying
193 Per-process keyring
194 Per-session keyring
195
196 When a process accesses a key, if not already present, it will normally be
197 cached on one of these keyrings for future accesses to find.
198
199 For more information on using keys, see ``Documentation/security/keys/*``.
200
201 5. LSM
202
203 The Linux Security Module allows extra controls to be placed over the
204 operations that a task may do. Currently Linux supports several LSM
205 options.
206
207 Some work by labelling the objects in a system and then applying sets of
208 rules (policies) that say what operations a task with one label may do to
209 an object with another label.
210
211 6. AF_KEY
212
213 This is a socket-based approach to credential management for networking
214 stacks [RFC 2367]. It isn't discussed by this document as it doesn't
215 interact directly with task and file credentials; rather it keeps system
216 level credentials.
217
218
219 When a file is opened, part of the opening task's subjective context is
220 recorded in the file struct created. This allows operations using that file
221 struct to use those credentials instead of the subjective context of the task
222 that issued the operation. An example of this would be a file opened on a
223 network filesystem where the credentials of the opened file should be presented
224 to the server, regardless of who is actually doing a read or a write upon it.
225
226
227 File Markings
228 =============
229
230 Files on disk or obtained over the network may have annotations that form the
231 objective security context of that file. Depending on the type of filesystem,
232 this may include one or more of the following:
233
234 * UNIX UID, GID, mode;
235 * Windows user ID;
236 * Access control list;
237 * LSM security label;
238 * UNIX exec privilege escalation bits (SUID/SGID);
239 * File capabilities exec privilege escalation bits.
240
241 These are compared to the task's subjective security context, and certain
242 operations allowed or disallowed as a result. In the case of execve(), the
243 privilege escalation bits come into play, and may allow the resulting process
244 extra privileges, based on the annotations on the executable file.
245
246
247 Task Credentials
248 ================
249
250 In Linux, all of a task's credentials are held in (uid, gid) or through
251 (groups, keys, LSM security) a refcounted structure of type 'struct cred'.
252 Each task points to its credentials by a pointer called 'cred' in its
253 task_struct.
254
255 Once a set of credentials has been prepared and committed, it may not be
256 changed, barring the following exceptions:
257
258 1. its reference count may be changed;
259
260 2. the reference count on the group_info struct it points to may be changed;
261
262 3. the reference count on the security data it points to may be changed;
263
264 4. the reference count on any keyrings it points to may be changed;
265
266 5. any keyrings it points to may be revoked, expired or have their security
267 attributes changed; and
268
269 6. the contents of any keyrings to which it points may be changed (the whole
270 point of keyrings being a shared set of credentials, modifiable by anyone
271 with appropriate access).
272
273 To alter anything in the cred struct, the copy-and-replace principle must be
274 adhered to. First take a copy, then alter the copy and then use RCU to change
275 the task pointer to make it point to the new copy. There are wrappers to aid
276 with this (see below).
277
278 A task may only alter its _own_ credentials; it is no longer permitted for a
279 task to alter another's credentials. This means the ``capset()`` system call
280 is no longer permitted to take any PID other than the one of the current
281 process. Also ``keyctl_instantiate()`` and ``keyctl_negate()`` functions no
282 longer permit attachment to process-specific keyrings in the requesting
283 process as the instantiating process may need to create them.
284
285
286 Immutable Credentials
287 ---------------------
288
289 Once a set of credentials has been made public (by calling ``commit_creds()``
290 for example), it must be considered immutable, barring two exceptions:
291
292 1. The reference count may be altered.
293
294 2. While the keyring subscriptions of a set of credentials may not be
295 changed, the keyrings subscribed to may have their contents altered.
296
297 To catch accidental credential alteration at compile time, struct task_struct
298 has _const_ pointers to its credential sets, as does struct file. Furthermore,
299 certain functions such as ``get_cred()`` and ``put_cred()`` operate on const
300 pointers, thus rendering casts unnecessary, but require to temporarily ditch
301 the const qualification to be able to alter the reference count.
302
303
304 Accessing Task Credentials
305 --------------------------
306
307 A task being able to alter only its own credentials permits the current process
308 to read or replace its own credentials without the need for any form of locking
309 -- which simplifies things greatly. It can just call::
310
311 const struct cred *current_cred()
312
313 to get a pointer to its credentials structure, and it doesn't have to release
314 it afterwards.
315
316 There are convenience wrappers for retrieving specific aspects of a task's
317 credentials (the value is simply returned in each case)::
318
319 uid_t current_uid(void) Current's real UID
320 gid_t current_gid(void) Current's real GID
321 uid_t current_euid(void) Current's effective UID
322 gid_t current_egid(void) Current's effective GID
323 uid_t current_fsuid(void) Current's file access UID
324 gid_t current_fsgid(void) Current's file access GID
325 kernel_cap_t current_cap(void) Current's effective capabilities
326 struct user_struct *current_user(void) Current's user account
327
328 There are also convenience wrappers for retrieving specific associated pairs of
329 a task's credentials::
330
331 void current_uid_gid(uid_t *, gid_t *);
332 void current_euid_egid(uid_t *, gid_t *);
333 void current_fsuid_fsgid(uid_t *, gid_t *);
334
335 which return these pairs of values through their arguments after retrieving
336 them from the current task's credentials.
337
338
339 In addition, there is a function for obtaining a reference on the current
340 process's current set of credentials::
341
342 const struct cred *get_current_cred(void);
343
344 and functions for getting references to one of the credentials that don't
345 actually live in struct cred::
346
347 struct user_struct *get_current_user(void);
348 struct group_info *get_current_groups(void);
349
350 which get references to the current process's user accounting structure and
351 supplementary groups list respectively.
352
353 Once a reference has been obtained, it must be released with ``put_cred()``,
354 ``free_uid()`` or ``put_group_info()`` as appropriate.
355
356
357 Accessing Another Task's Credentials
358 ------------------------------------
359
360 While a task may access its own credentials without the need for locking, the
361 same is not true of a task wanting to access another task's credentials. It
362 must use the RCU read lock and ``rcu_dereference()``.
363
364 The ``rcu_dereference()`` is wrapped by::
365
366 const struct cred *__task_cred(struct task_struct *task);
367
368 This should be used inside the RCU read lock, as in the following example::
369
370 void foo(struct task_struct *t, struct foo_data *f)
371 {
372 const struct cred *tcred;
373 ...
374 rcu_read_lock();
375 tcred = __task_cred(t);
376 f->uid = tcred->uid;
377 f->gid = tcred->gid;
378 f->groups = get_group_info(tcred->groups);
379 rcu_read_unlock();
380 ...
381 }
382
383 Should it be necessary to hold another task's credentials for a long period of
384 time, and possibly to sleep while doing so, then the caller should get a
385 reference on them using::
386
387 const struct cred *get_task_cred(struct task_struct *task);
388
389 This does all the RCU magic inside of it. The caller must call put_cred() on
390 the credentials so obtained when they're finished with.
391
392 .. note::
393 The result of ``__task_cred()`` should not be passed directly to
394 ``get_cred()`` as this may race with ``commit_cred()``.
395
396 There are a couple of convenience functions to access bits of another task's
397 credentials, hiding the RCU magic from the caller::
398
399 uid_t task_uid(task) Task's real UID
400 uid_t task_euid(task) Task's effective UID
401
402 If the caller is holding the RCU read lock at the time anyway, then::
403
404 __task_cred(task)->uid
405 __task_cred(task)->euid
406
407 should be used instead. Similarly, if multiple aspects of a task's credentials
408 need to be accessed, RCU read lock should be used, ``__task_cred()`` called,
409 the result stored in a temporary pointer and then the credential aspects called
410 from that before dropping the lock. This prevents the potentially expensive
411 RCU magic from being invoked multiple times.
412
413 Should some other single aspect of another task's credentials need to be
414 accessed, then this can be used::
415
416 task_cred_xxx(task, member)
417
418 where 'member' is a non-pointer member of the cred struct. For instance::
419
420 uid_t task_cred_xxx(task, suid);
421
422 will retrieve 'struct cred::suid' from the task, doing the appropriate RCU
423 magic. This may not be used for pointer members as what they point to may
424 disappear the moment the RCU read lock is dropped.
425
426
427 Altering Credentials
428 --------------------
429
430 As previously mentioned, a task may only alter its own credentials, and may not
431 alter those of another task. This means that it doesn't need to use any
432 locking to alter its own credentials.
433
434 To alter the current process's credentials, a function should first prepare a
435 new set of credentials by calling::
436
437 struct cred *prepare_creds(void);
438
439 this locks current->cred_replace_mutex and then allocates and constructs a
440 duplicate of the current process's credentials, returning with the mutex still
441 held if successful. It returns NULL if not successful (out of memory).
442
443 The mutex prevents ``ptrace()`` from altering the ptrace state of a process
444 while security checks on credentials construction and changing is taking place
445 as the ptrace state may alter the outcome, particularly in the case of
446 ``execve()``.
447
448 The new credentials set should be altered appropriately, and any security
449 checks and hooks done. Both the current and the proposed sets of credentials
450 are available for this purpose as current_cred() will return the current set
451 still at this point.
452
453 When replacing the group list, the new list must be sorted before it
454 is added to the credential, as a binary search is used to test for
455 membership. In practice, this means groups_sort() should be
456 called before set_groups() or set_current_groups().
457 groups_sort() must not be called on a ``struct group_list`` which
458 is shared as it may permute elements as part of the sorting process
459 even if the array is already sorted.
460
461 When the credential set is ready, it should be committed to the current process
462 by calling::
463
464 int commit_creds(struct cred *new);
465
466 This will alter various aspects of the credentials and the process, giving the
467 LSM a chance to do likewise, then it will use ``rcu_assign_pointer()`` to
468 actually commit the new credentials to ``current->cred``, it will release
469 ``current->cred_replace_mutex`` to allow ``ptrace()`` to take place, and it
470 will notify the scheduler and others of the changes.
471
472 This function is guaranteed to return 0, so that it can be tail-called at the
473 end of such functions as ``sys_setresuid()``.
474
475 Note that this function consumes the caller's reference to the new credentials.
476 The caller should _not_ call ``put_cred()`` on the new credentials afterwards.
477
478 Furthermore, once this function has been called on a new set of credentials,
479 those credentials may _not_ be changed further.
480
481
482 Should the security checks fail or some other error occur after
483 ``prepare_creds()`` has been called, then the following function should be
484 invoked::
485
486 void abort_creds(struct cred *new);
487
488 This releases the lock on ``current->cred_replace_mutex`` that
489 ``prepare_creds()`` got and then releases the new credentials.
490
491
492 A typical credentials alteration function would look something like this::
493
494 int alter_suid(uid_t suid)
495 {
496 struct cred *new;
497 int ret;
498
499 new = prepare_creds();
500 if (!new)
501 return -ENOMEM;
502
503 new->suid = suid;
504 ret = security_alter_suid(new);
505 if (ret < 0) {
506 abort_creds(new);
507 return ret;
508 }
509
510 return commit_creds(new);
511 }
512
513
514 Managing Credentials
515 --------------------
516
517 There are some functions to help manage credentials:
518
519 - ``void put_cred(const struct cred *cred);``
520
521 This releases a reference to the given set of credentials. If the
522 reference count reaches zero, the credentials will be scheduled for
523 destruction by the RCU system.
524
525 - ``const struct cred *get_cred(const struct cred *cred);``
526
527 This gets a reference on a live set of credentials, returning a pointer to
528 that set of credentials.
529
530
531 Open File Credentials
532 =====================
533
534 When a new file is opened, a reference is obtained on the opening task's
535 credentials and this is attached to the file struct as ``f_cred`` in place of
536 ``f_uid`` and ``f_gid``. Code that used to access ``file->f_uid`` and
537 ``file->f_gid`` should now access ``file->f_cred->fsuid`` and
538 ``file->f_cred->fsgid``.
539
540 It is safe to access ``f_cred`` without the use of RCU or locking because the
541 pointer will not change over the lifetime of the file struct, and nor will the
542 contents of the cred struct pointed to, barring the exceptions listed above
543 (see the Task Credentials section).
544
545 To avoid "confused deputy" privilege escalation attacks, access control checks
546 during subsequent operations on an opened file should use these credentials
547 instead of "current"'s credentials, as the file may have been passed to a more
548 privileged process.
549
550 Overriding the VFS's Use of Credentials
551 =======================================
552
553 Under some circumstances it is desirable to override the credentials used by
554 the VFS, and that can be done by calling into such as ``vfs_mkdir()`` with a
555 different set of credentials. This is done in the following places:
556
557 * ``sys_faccessat()``.
558 * ``vfs_coredump()``.
559 * nfs4recover.c.
560

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

문서 정보와 범위

1-8

이 문서는 David Howells가 작성한 Linux 자격 증명 모델 설명서다. 객체와 주체의 보안 문맥, `struct cred`의 불변성과 교체 절차, 현재 태스크 및 다른 태스크의 자격 증명 접근 방법, 열린 파일에 고정되는 자격 증명을 다룬다.

====================
Credentials in Linux
====================

By: David Howells <[email protected]>

.. contents:: :local:

객체와 객체 소유권

9-39

Linux의 보안 검사는 한 객체가 다른 객체에 작용할 때 수행된다. 사용자 공간 프로그램이 직접 다룰 수 있는 객체에는 태스크, 파일과 inode, 소켓, 메시지 큐, 공유 메모리 세그먼트, 세마포어, 키가 있다. 각 객체의 설명에는 자격 증명 집합이 포함되며, 구체적인 구성은 객체 종류마다 다르다.

대부분의 객체 자격 증명에는 소유권을 나타내는 부분집합이 있다. 이 정보는 디스크 할당량이나 태스크 자원 한도 같은 자원 회계와 제한에 쓰인다. 표준 UNIX 파일 시스템에서는 inode에 기록된 UID가 대표적인 소유권 정보다.

보안 검사의 기본 요소
요소용도
객체태스크, 파일, 소켓, IPC, 키행위의 대상
소유권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은 객체 자격 증명에 보안 레이블을 넣고, 주체 레이블·객체 레이블·요청 행위를 정책 규칙과 대조해 허용 여부를 판단한다.

DAC와 MAC
방식규칙 위치대표 예
DAC객체의 권한 비트 또는 ACLUNIX mode, 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 집합
집합의미
permitted부여할 수 있는 capability 범위
effective현재 실제로 사용할 수 있는 capability
inheritableexecve()를 넘어 전달 가능한 capability
boundingexecve() 상속의 상한

태스크 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()`도 요청 프로세스의 프로세스별 키링에 붙이는 동작을 더 이상 허용하지 않는다.

자격 증명 교체 원칙
현재 struct cred 복사새 사본만 수정보안 검사와 훅 수행RCU로 current->cred 교체

공개된 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반환 대상호출자 해제
current_cred()현재 cred 포인터불필요
get_current_cred()참조를 얻은 credput_cred()
get_current_user()사용자 회계 구조free_uid()
get_current_groups()보조 그룹 목록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을 놓는 즉시 가리키는 객체가 사라질 수 있으므로 포인터 멤버에는 사용할 수 없다.

다른 태스크의 cred 읽기
짧은 접근: rcu_read_lock()__task_cred(task) 한 번 호출필요한 값 또는 참조 복사rcu_read_unlock()장기 보유는 get_task_cred()와 put_cred() 사용

짧은 접근과 장기 보유는 서로 다른 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`를 해제하고 새 자격 증명도 해제한다.

prepare-commit/abort 수명 주기
prepare_creds()사본 변경과 보안 검사성공: commit_creds(new)실패: abort_creds(new)commit 뒤 new를 다시 사용하지 않음

새 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`를 열거한다.

VFS 자격 증명 재정의 사용처
위치형태
sys_faccessat()시스템 호출 처리
vfs_coredump()코어 덤프 파일 작업
nfs4recover.cNFSv4 복구 경로

원문에 기록된 대표 호출 위치다.

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.