요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
.. _perf_security:
Perf events and tool security
=============================
Overview
--------
Usage of Performance Counters for Linux (perf_events) [1]_ , [2]_ , [3]_
can impose a considerable risk of leaking sensitive data accessed by
monitored processes. The data leakage is possible both in scenarios of
direct usage of perf_events system call API [2]_ and over data files
generated by Perf tool user mode utility (Perf) [3]_ , [4]_ . The risk
depends on the nature of data that perf_events performance monitoring
units (PMU) [2]_ and Perf collect and expose for performance analysis.
Collected system and performance data may be split into several
categories:
1. System hardware and software configuration data, for example: a CPU
model and its cache configuration, an amount of available memory and
its topology, used kernel and Perf versions, performance monitoring
setup including experiment time, events configuration, Perf command
line parameters, etc.
2. User and kernel module paths and their load addresses with sizes,
process and thread names with their PIDs and TIDs, timestamps for
captured hardware and software events.
3. Content of kernel software counters (e.g., for context switches, page
faults, CPU migrations), architectural hardware performance counters
(PMC) [8]_ and machine specific registers (MSR) [9]_ that provide
execution metrics for various monitored parts of the system (e.g.,
memory controller (IMC), interconnect (QPI/UPI) or peripheral (PCIe)
uncore counters) without direct attribution to any execution context
state.
4. Content of architectural execution context registers (e.g., RIP, RSP,
RBP on x86_64), process user and kernel space memory addresses and
data, content of various architectural MSRs that capture data from
this category.
Data that belong to the fourth category can potentially contain
sensitive process data. If PMUs in some monitoring modes capture values
of execution context registers or data from process memory then access
to such monitoring modes requires to be ordered and secured properly.
So, perf_events performance monitoring and observability operations are
the subject for security access control management [5]_ .
perf_events access control
-------------------------------
To perform security checks, the Linux implementation splits processes
into two categories [6]_ : a) privileged processes (whose effective user
ID is 0, referred to as superuser or root), and b) unprivileged
processes (whose effective UID is nonzero). Privileged processes bypass
all kernel security permission checks so perf_events performance
monitoring is fully available to privileged processes without access,
scope and resource restrictions.
Unprivileged processes are subject to a full security permission check
based on the process's credentials [5]_ (usually: effective UID,
effective GID, and supplementary group list).
Linux divides the privileges traditionally associated with superuser
into distinct units, known as capabilities [6]_ , which can be
independently enabled and disabled on per-thread basis for processes and
files of unprivileged users.
Unprivileged processes with enabled CAP_PERFMON capability are treated
as privileged processes with respect to perf_events performance
monitoring and observability operations, thus, bypass *scope* permissions
checks in the kernel. CAP_PERFMON implements the principle of least
privilege [13]_ (POSIX 1003.1e: 2.2.2.39) for performance monitoring and
observability operations in the kernel and provides a secure approach to
performance monitoring and observability in the system.
For backward compatibility reasons the access to perf_events monitoring and
observability operations is also open for CAP_SYS_ADMIN privileged
processes but CAP_SYS_ADMIN usage for secure monitoring and observability
use cases is discouraged with respect to the CAP_PERFMON capability.
If system audit records [14]_ for a process using perf_events system call
API contain denial records of acquiring both CAP_PERFMON and CAP_SYS_ADMIN
capabilities then providing the process with CAP_PERFMON capability singly
is recommended as the preferred secure approach to resolve double access
denial logging related to usage of performance monitoring and observability.
Prior Linux v5.9 unprivileged processes using perf_events system call
are also subject for PTRACE_MODE_READ_REALCREDS ptrace access mode check
[7]_ , whose outcome determines whether monitoring is permitted.
So unprivileged processes provided with CAP_SYS_PTRACE capability are
effectively permitted to pass the check. Starting from Linux v5.9
CAP_SYS_PTRACE capability is not required and CAP_PERFMON is enough to
be provided for processes to make performance monitoring and observability
operations.
Other capabilities being granted to unprivileged processes can
effectively enable capturing of additional data required for later
performance analysis of monitored processes or a system. For example,
CAP_SYSLOG capability permits reading kernel space memory addresses from
/proc/kallsyms file.
Privileged Perf users groups
---------------------------------
Mechanisms of capabilities, privileged capability-dumb files [6]_,
file system ACLs [10]_ and sudo [15]_ utility can be used to create
dedicated groups of privileged Perf users who are permitted to execute
performance monitoring and observability without limits. The following
steps can be taken to create such groups of privileged Perf users.
1. Create perf_users group of privileged Perf users, assign perf_users
group to Perf tool executable and limit access to the executable for
other users in the system who are not in the perf_users group:
::
# groupadd perf_users
# ls -alhF
-rwxr-xr-x 2 root root 11M Oct 19 15:12 perf
# chgrp perf_users perf
# ls -alhF
-rwxr-xr-x 2 root perf_users 11M Oct 19 15:12 perf
# chmod o-rwx perf
# ls -alhF
-rwxr-x--- 2 root perf_users 11M Oct 19 15:12 perf
2. Assign the required capabilities to the Perf tool executable file and
enable members of perf_users group with monitoring and observability
privileges [6]_ :
::
# setcap "cap_perfmon,cap_sys_ptrace,cap_syslog=ep" perf
# setcap -v "cap_perfmon,cap_sys_ptrace,cap_syslog=ep" perf
perf: OK
# getcap perf
perf = cap_sys_ptrace,cap_syslog,cap_perfmon+ep
If the libcap [16]_ installed doesn't yet support "cap_perfmon", use "38" instead,
i.e.:
::
# setcap "38,cap_ipc_lock,cap_sys_ptrace,cap_syslog=ep" perf
Note that you may need to have 'cap_ipc_lock' in the mix for tools such as
'perf top', alternatively use 'perf top -m N', to reduce the memory that
it uses for the perf ring buffer, see the memory allocation section below.
Using a libcap without support for CAP_PERFMON will make cap_get_flag(caps, 38,
CAP_EFFECTIVE, &val) fail, which will lead the default event to be 'cycles:u',
so as a workaround explicitly ask for the 'cycles' event, i.e.:
::
# perf top -e cycles
To get kernel and user samples with a perf binary with just CAP_PERFMON.
As a result, members of perf_users group are capable of conducting
performance monitoring and observability by using functionality of the
configured Perf tool executable that, when executes, passes perf_events
subsystem scope checks.
In case Perf tool executable can't be assigned required capabilities (e.g.
file system is mounted with nosuid option or extended attributes are
not supported by the file system) then creation of the capabilities
privileged environment, naturally shell, is possible. The shell provides
inherent processes with CAP_PERFMON and other required capabilities so that
performance monitoring and observability operations are available in the
environment without limits. Access to the environment can be open via sudo
utility for members of perf_users group only. In order to create such
environment:
1. Create shell script that uses capsh utility [16]_ to assign CAP_PERFMON
and other required capabilities into ambient capability set of the shell
process, lock the process security bits after enabling SECBIT_NO_SETUID_FIXUP,
SECBIT_NOROOT and SECBIT_NO_CAP_AMBIENT_RAISE bits and then change
the process identity to sudo caller of the script who should essentially
be a member of perf_users group:
::
# ls -alh /usr/local/bin/perf.shell
-rwxr-xr-x. 1 root root 83 Oct 13 23:57 /usr/local/bin/perf.shell
# cat /usr/local/bin/perf.shell
exec /usr/sbin/capsh --iab=^cap_perfmon --secbits=239 --user=$SUDO_USER -- -l
2. Extend sudo policy at /etc/sudoers file with a rule for perf_users group:
::
# grep perf_users /etc/sudoers
%perf_users ALL=/usr/local/bin/perf.shell
3. Check that members of perf_users group have access to the privileged
shell and have CAP_PERFMON and other required capabilities enabled
in permitted, effective and ambient capability sets of an inherent process:
::
$ id
uid=1003(capsh_test) gid=1004(capsh_test) groups=1004(capsh_test),1000(perf_users) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
$ sudo perf.shell
[sudo] password for capsh_test:
$ grep Cap /proc/self/status
CapInh: 0000004000000000
CapPrm: 0000004000000000
CapEff: 0000004000000000
CapBnd: 000000ffffffffff
CapAmb: 0000004000000000
$ capsh --decode=0000004000000000
0x0000004000000000=cap_perfmon
As a result, members of perf_users group have access to the privileged
environment where they can use tools employing performance monitoring APIs
governed by CAP_PERFMON Linux capability.
This specific access control management is only available to superuser
or root running processes with CAP_SETPCAP, CAP_SETFCAP [6]_
capabilities.
Unprivileged users
-----------------------------------
perf_events *scope* and *access* control for unprivileged processes
is governed by perf_event_paranoid [2]_ setting:
-1:
Impose no *scope* and *access* restrictions on using perf_events
performance monitoring. Per-user per-cpu perf_event_mlock_kb [2]_
locking limit is ignored when allocating memory buffers for storing
performance data. This is the least secure mode since allowed
monitored *scope* is maximized and no perf_events specific limits
are imposed on *resources* allocated for performance monitoring.
>=0:
*scope* includes per-process and system wide performance monitoring
but excludes raw tracepoints and ftrace function tracepoints
monitoring. CPU and system events happened when executing either in
user or in kernel space can be monitored and captured for later
analysis. Per-user per-cpu perf_event_mlock_kb locking limit is
imposed but ignored for unprivileged processes with CAP_IPC_LOCK
[6]_ capability.
>=1:
*scope* includes per-process performance monitoring only and
excludes system wide performance monitoring. CPU and system events
happened when executing either in user or in kernel space can be
monitored and captured for later analysis. Per-user per-cpu
perf_event_mlock_kb locking limit is imposed but ignored for
unprivileged processes with CAP_IPC_LOCK capability.
>=2:
*scope* includes per-process performance monitoring only. CPU and
system events happened when executing in user space only can be
monitored and captured for later analysis. Per-user per-cpu
perf_event_mlock_kb locking limit is imposed but ignored for
unprivileged processes with CAP_IPC_LOCK capability.
Resource control
---------------------------------
Open file descriptors
+++++++++++++++++++++
The perf_events system call API [2]_ allocates file descriptors for
every configured PMU event. Open file descriptors are a per-process
accountable resource governed by the RLIMIT_NOFILE [11]_ limit
(ulimit -n), which is usually derived from the login shell process. When
configuring Perf collection for a long list of events on a large server
system, this limit can be easily hit preventing required monitoring
configuration. RLIMIT_NOFILE limit can be increased on per-user basis
modifying content of the limits.conf file [12]_ . Ordinarily, a Perf
sampling session (perf record) requires an amount of open perf_event
file descriptors that is not less than the number of monitored events
multiplied by the number of monitored CPUs.
Memory allocation
+++++++++++++++++
The amount of memory available to user processes for capturing
performance monitoring data is governed by the perf_event_mlock_kb [2]_
setting. This perf_event specific resource setting defines overall
per-cpu limits of memory allowed for mapping by the user processes to
execute performance monitoring. The setting essentially extends the
RLIMIT_MEMLOCK [11]_ limit, but only for memory regions mapped
specifically for capturing monitored performance events and related data.
For example, if a machine has eight cores and perf_event_mlock_kb limit
is set to 516 KiB, then a user process is provided with 516 KiB * 8 =
4128 KiB of memory above the RLIMIT_MEMLOCK limit (ulimit -l) for
perf_event mmap buffers. In particular, this means that, if the user
wants to start two or more performance monitoring processes, the user is
required to manually distribute the available 4128 KiB between the
monitoring processes, for example, using the --mmap-pages Perf record
mode option. Otherwise, the first started performance monitoring process
allocates all available 4128 KiB and the other processes will fail to
proceed due to the lack of memory.
RLIMIT_MEMLOCK and perf_event_mlock_kb resource constraints are ignored
for processes with the CAP_IPC_LOCK capability. Thus, perf_events/Perf
privileged users can be provided with memory above the constraints for
perf_events/Perf performance monitoring purpose by providing the Perf
executable with CAP_IPC_LOCK capability.
Bibliography
------------
.. [1] `<https://lwn.net/Articles/337493/>`_
.. [2] `<http://man7.org/linux/man-pages/man2/perf_event_open.2.html>`_
.. [3] `<http://web.eece.maine.edu/~vweaver/projects/perf_events/>`_
.. [4] `<https://perf.wiki.kernel.org/index.php/Main_Page>`_
.. [5] `<https://www.kernel.org/doc/html/latest/security/credentials.html>`_
.. [6] `<http://man7.org/linux/man-pages/man7/capabilities.7.html>`_
.. [7] `<http://man7.org/linux/man-pages/man2/ptrace.2.html>`_
.. [8] `<https://en.wikipedia.org/wiki/Hardware_performance_counter>`_
.. [9] `<https://en.wikipedia.org/wiki/Model-specific_register>`_
.. [10] `<http://man7.org/linux/man-pages/man5/acl.5.html>`_
.. [11] `<http://man7.org/linux/man-pages/man2/getrlimit.2.html>`_
.. [12] `<http://man7.org/linux/man-pages/man5/limits.conf.5.html>`_
.. [13] `<https://sites.google.com/site/fullycapable>`_
.. [14] `<http://man7.org/linux/man-pages/man8/auditd.8.html>`_
.. [15] `<https://man7.org/linux/man-pages/man8/sudo.8.html>`_
.. [16] `<https://git.kernel.org/pub/scm/libs/libcap/libcap.git/>`_
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
Perf data의 네 보안 등급
1-48`Performance Counters for Linux (perf_events)` 사용은 monitoring 대상 process가 접근한 민감한 data를 유출할 상당한 위험이 있습니다. 유출은 `perf_events system call API`를 직접 사용할 때와 user-mode utility인 `Perf`가 생성한 data file을 통해 모두 발생할 수 있습니다.
위험은 `perf_events`의 performance monitoring unit(`PMU`)과 Perf가 performance analysis를 위해 어떤 data를 수집·노출하는지에 따라 달라집니다. 수집하는 system·performance data는 네 범주로 나눌 수 있습니다.
| 등급 | Data 범주 | 예시 |
|---|---|---|
| 1 | System hardware·software configuration | CPU model/cache, memory size/topology, kernel·Perf version, experiment time, event와 command-line 설정 |
| 2 | Identity와 mapping metadata | Module path/load address/size, process·thread name, PID/TID, event timestamp |
| 3 | 집계 counter와 metric | Context switch·page fault·CPU migration, PMC/MSR, IMC·QPI/UPI·PCIe uncore counter |
| 4 | Execution context와 memory content | RIP/RSP/RBP, user·kernel memory address와 data, 값을 capture하는 architectural MSR |
1등급은 CPU model/cache, memory와 topology, kernel·Perf version, experiment time, event configuration과 Perf command-line parameter 같은 system configuration입니다.
2등급은 user·kernel module path와 load address/size, process·thread name과 PID/TID, hardware·software event timestamp입니다.
3등급은 context switch·page fault·CPU migration 같은 kernel software counter, architectural performance counter(`PMC`), machine specific register(`MSR`)와 IMC·QPI/UPI·PCIe uncore counter처럼 특정 execution-context state에 직접 귀속되지 않는 metric입니다.
4등급은 x86_64의 `RIP`, `RSP`, `RBP` 같은 architectural execution-context register, process의 user/kernel-space memory address와 data, 이 범주의 값을 capture하는 architectural MSR 내용입니다.
4등급 data에는 민감한 process data가 들어갈 수 있습니다. PMU mode가 execution-context register나 process memory 값을 capture한다면 해당 monitoring mode의 접근을 올바르게 정렬하고 보호해야 합니다.
따라서 `perf_events` performance monitoring과 observability operation은 security access-control 관리 대상입니다.
perf_events access control과 capability
49-101Linux는 security check를 위해 process를 effective user ID가 0인 privileged process(root)와 effective UID가 0이 아닌 unprivileged process로 나눕니다.
Privileged process는 kernel security permission check를 모두 우회하므로 access·scope·resource restriction 없이 `perf_events` monitoring 전체를 사용할 수 있습니다. Unprivileged process는 보통 effective UID, effective GID와 supplementary group list로 구성된 credential에 따라 전체 permission check를 받습니다.
Linux capability는 전통적으로 superuser에 묶인 privilege를 독립된 단위로 나눠 unprivileged user의 process와 file에 대해 thread별로 켜고 끌 수 있게 합니다.
| Capability | perf_events 관련 역할 |
|---|---|
| `CAP_PERFMON` | perf_events scope check를 우회하는 최소 권한의 권장 capability |
| `CAP_SYS_ADMIN` | Backward compatibility로 허용되지만 secure monitoring 용도에는 권장하지 않음 |
| `CAP_SYS_PTRACE` | Linux v5.9 이전 `PTRACE_MODE_READ_REALCREDS` check 통과에 사용; v5.9부터 불필요 |
| `CAP_SYSLOG` | `/proc/kallsyms`의 kernel-space memory address 읽기 허용 |
| `CAP_IPC_LOCK` | `perf_event_mlock_kb`와 `RLIMIT_MEMLOCK` memory constraint 무시 |
| `CAP_SETPCAP`, `CAP_SETFCAP` | Capability 기반 access-control 환경을 설정하는 root process에 필요 |
`CAP_PERFMON`이 활성화된 unprivileged process는 performance monitoring·observability에서 privileged process처럼 취급되어 kernel의 scope permission check를 우회합니다. 이는 POSIX 1003.1e: 2.2.2.39의 principle of least privilege를 구현하는 권장 방식입니다.
Backward compatibility 때문에 `CAP_SYS_ADMIN` process에도 접근이 열려 있지만 secure monitoring에는 `CAP_PERFMON`을 권장합니다. Audit record에 `CAP_PERFMON`과 `CAP_SYS_ADMIN` 획득 실패가 모두 기록된다면 double denial logging을 해소하기 위해 `CAP_PERFMON`만 부여하는 것이 좋습니다.
Linux v5.9 이전에는 unprivileged `perf_events` system call이 `PTRACE_MODE_READ_REALCREDS` ptrace access-mode check도 받았고 `CAP_SYS_PTRACE`로 이를 통과할 수 있었습니다. Linux v5.9부터 `CAP_SYS_PTRACE`는 필요 없으며 `CAP_PERFMON`이면 충분합니다.
다른 capability는 후속 analysis에 필요한 data를 더 수집하게 할 수 있습니다. 예를 들어 `CAP_SYSLOG`는 `/proc/kallsyms`에서 kernel-space memory address를 읽도록 허용합니다.
File capability를 쓰는 perf_users group
102-164Capability, privileged capability-dumb file, filesystem ACLs와 `sudo`를 사용하면 제한 없이 monitoring·observability를 수행할 전용 privileged Perf user group을 만들 수 있습니다.
먼저 `perf_users` group을 만들고 Perf executable의 group을 바꾼 뒤 group 밖의 user에게서 executable access를 제거합니다.
# groupadd perf_users
# ls -alhF
-rwxr-xr-x 2 root root 11M Oct 19 15:12 perf
# chgrp perf_users perf
# ls -alhF
-rwxr-xr-x 2 root perf_users 11M Oct 19 15:12 perf
# chmod o-rwx perf
# ls -alhF
-rwxr-x--- 2 root perf_users 11M Oct 19 15:12 perf
다음으로 필요한 capability를 Perf executable에 부여하고 결과를 검증합니다.
# setcap "cap_perfmon,cap_sys_ptrace,cap_syslog=ep" perf
# setcap -v "cap_perfmon,cap_sys_ptrace,cap_syslog=ep" perf
perf: OK
# getcap perf
perf = cap_sys_ptrace,cap_syslog,cap_perfmon+ep
설치된 `libcap`이 아직 `cap_perfmon` 이름을 지원하지 않으면 capability number `38`을 대신 사용합니다.
# setcap "38,cap_ipc_lock,cap_sys_ptrace,cap_syslog=ep" perf
`perf top` 같은 tool에는 `cap_ipc_lock`이 추가로 필요할 수 있습니다. 또는 `perf top -m N`으로 perf ring buffer memory 사용량을 줄일 수 있습니다.
`CAP_PERFMON`을 모르는 libcap에서는 `cap_get_flag(caps, 38, CAP_EFFECTIVE, &val)`이 실패하여 default event가 `cycles:u`가 됩니다. Kernel과 user sample을 모두 얻으려면 `CAP_PERFMON`만 가진 Perf binary에서 `cycles` event를 명시합니다.
# perf top -e cycles
그 결과 `perf_users` member는 실행 시 `perf_events` subsystem scope check를 통과하는 구성된 Perf executable로 performance monitoring과 observability를 수행할 수 있습니다.
File capability가 불가능한 privileged shell
165-222Filesystem이 `nosuid` option으로 mount됐거나 extended attribute를 지원하지 않아 Perf executable에 capability를 줄 수 없다면 capability-privileged environment, 보통 shell을 만들 수 있습니다.
이 shell은 내부 process에 `CAP_PERFMON`과 필요한 capability를 제공하며, `perf_users` member만 `sudo`로 환경에 들어오게 제한할 수 있습니다.
먼저 `capsh`로 shell process의 ambient capability set에 `CAP_PERFMON`을 넣는 script를 만듭니다. `SECBIT_NO_SETUID_FIXUP`, `SECBIT_NOROOT`, `SECBIT_NO_CAP_AMBIENT_RAISE`를 활성화한 뒤 security bit를 잠그고 process identity를 script의 sudo caller로 바꿉니다.
# ls -alh /usr/local/bin/perf.shell
-rwxr-xr-x. 1 root root 83 Oct 13 23:57 /usr/local/bin/perf.shell
# cat /usr/local/bin/perf.shell
exec /usr/sbin/capsh --iab=^cap_perfmon --secbits=239 --user=$SUDO_USER -- -l
그 다음 `/etc/sudoers`에 `perf_users` group용 rule을 추가합니다.
# grep perf_users /etc/sudoers
%perf_users ALL=/usr/local/bin/perf.shell
Group member가 privileged shell에 들어가고 내부 process의 permitted, effective, ambient capability set에 `CAP_PERFMON`이 있는지 확인합니다.
$ id
uid=1003(capsh_test) gid=1004(capsh_test) groups=1004(capsh_test),1000(perf_users) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
$ sudo perf.shell
[sudo] password for capsh_test:
$ grep Cap /proc/self/status
CapInh: 0000004000000000
CapPrm: 0000004000000000
CapEff: 0000004000000000
CapBnd: 000000ffffffffff
CapAmb: 0000004000000000
$ capsh --decode=0000004000000000
0x0000004000000000=cap_perfmon
이 환경에서는 `CAP_PERFMON`이 관리하는 performance-monitoring API를 사용하는 tool을 실행할 수 있습니다.
이 access-control 설정 자체는 `CAP_SETPCAP`과 `CAP_SETFCAP` capability를 가진 superuser 또는 root process만 수행할 수 있습니다.
Unprivileged user의 perf_event_paranoid
223-260Unprivileged process의 `perf_events` scope와 access는 `perf_event_paranoid` setting이 제어합니다.
| 값 | Monitoring scope | Execution space | Memory lock |
|---|---|---|---|
| `-1` | Per-process + system-wide; raw/ftrace 허용 | User + kernel | `perf_event_mlock_kb` 무시 |
| `>=0` | Per-process + system-wide; raw tracepoints와 ftrace function tracepoints 제외 | User + kernel | 적용, `CAP_IPC_LOCK`이면 무시 |
| `>=1` | Per-process만; system-wide 제외 | User + kernel | 적용, `CAP_IPC_LOCK`이면 무시 |
| `>=2` | Per-process만 | User만 | 적용, `CAP_IPC_LOCK`이면 무시 |
`-1`은 scope·access 제한이 없고 `perf_event_mlock_kb`도 무시하는 가장 덜 안전한 mode입니다. Monitoring scope가 최대이고 performance resource에 perf_events 전용 limit가 적용되지 않습니다.
`>=0`은 per-process와 system-wide monitoring을 허용하지만 raw tracepoints와 ftrace function tracepoints는 제외합니다. User와 kernel 실행 중 발생한 CPU·system event를 capture할 수 있습니다.
`>=1`은 system-wide monitoring을 제외하고 per-process monitoring만 허용합니다. User와 kernel event는 계속 capture할 수 있습니다.
`>=2`는 per-process의 user-space event만 허용합니다. `>=0`부터 `perf_event_mlock_kb`가 적용되지만 `CAP_IPC_LOCK`을 가진 unprivileged process에는 적용되지 않습니다.
File descriptor와 capture memory 제한
261-305| Resource | 제어 항목 | 필요량 | 조정 |
|---|---|---|---|
| Open file descriptors | `RLIMIT_NOFILE` (`ulimit -n`) | 대략 event 수 × monitored CPU 수 이상의 perf_event descriptor | `limits.conf`에서 user별 조정 |
| Mapped capture memory | `perf_event_mlock_kb` + `RLIMIT_MEMLOCK` (`ulimit -l`) | User별 per-CPU 추가 한도 | `--mmap-pages`로 여러 monitoring process 사이에 수동 배분 |
`perf_events system call API`는 구성한 PMU event마다 file descriptor를 할당합니다. 이는 보통 login shell에서 물려받는 process별 `RLIMIT_NOFILE` limit, 즉 `ulimit -n`의 적용을 받습니다.
큰 server에서 긴 event 목록을 수집하면 이 limit에 쉽게 도달해 필요한 monitoring 구성을 막을 수 있습니다. `limits.conf`를 수정해 user별 `RLIMIT_NOFILE`을 늘릴 수 있습니다. 보통 `perf record` sampling session에는 monitored event 수 × monitored CPU 수보다 적지 않은 perf_event file descriptor가 필요합니다.
Capture memory는 `perf_event_mlock_kb`가 제어합니다. 이는 monitoring data capture용으로 mapping한 memory에 한해 `RLIMIT_MEMLOCK`, 즉 `ulimit -l` 위로 허용되는 user별 per-CPU 추가 limit입니다.
예를 들어 8-core machine에서 `perf_event_mlock_kb`가 516 KiB이면 user process는 perf_event mmap buffer용으로 `516 KiB * 8 = 4128 KiB`를 `RLIMIT_MEMLOCK` 위에 추가로 받습니다.
Monitoring process를 둘 이상 시작한다면 `--mmap-pages` Perf record option 등을 사용해 4128 KiB를 process 사이에 수동 배분해야 합니다. 그렇지 않으면 먼저 시작한 process가 4128 KiB 전체를 할당해 나머지가 memory 부족으로 진행하지 못합니다.
`CAP_IPC_LOCK`을 가진 process는 `RLIMIT_MEMLOCK`과 `perf_event_mlock_kb` constraint를 무시합니다. 따라서 Perf executable에 `CAP_IPC_LOCK`을 주어 privileged user에게 해당 limit 이상의 monitoring memory를 제공할 수 있습니다.
Bibliography
306-325원문이 인용한 perf_events, credential, capability, ptrace, resource limit, audit, sudo와 libcap reference입니다.
- [1] Perf events 소개
https://lwn.net/Articles/337493/ - [2] perf_event_open(2)
http://man7.org/linux/man-pages/man2/perf_event_open.2.html - [3] perf_events project
http://web.eece.maine.edu/~vweaver/projects/perf_events/ - [4] Perf wiki
https://perf.wiki.kernel.org/index.php/Main_Page - [5] Linux credentials
https://www.kernel.org/doc/html/latest/security/credentials.html - [6] capabilities(7)
http://man7.org/linux/man-pages/man7/capabilities.7.html - [7] ptrace(2)
http://man7.org/linux/man-pages/man2/ptrace.2.html - [8] Hardware performance counter
https://en.wikipedia.org/wiki/Hardware_performance_counter - [9] Model-specific register
https://en.wikipedia.org/wiki/Model-specific_register - [10] acl(5)
http://man7.org/linux/man-pages/man5/acl.5.html - [11] getrlimit(2)
http://man7.org/linux/man-pages/man2/getrlimit.2.html - [12] limits.conf(5)
http://man7.org/linux/man-pages/man5/limits.conf.5.html - [13] Fully Capable
https://sites.google.com/site/fullycapable - [14] auditd(8)
http://man7.org/linux/man-pages/man8/auditd.8.html - [15] sudo(8)
https://man7.org/linux/man-pages/man8/sudo.8.html - [16] libcap
https://git.kernel.org/pub/scm/libs/libcap/libcap.git/
보안 운영 핵심
perf-security.rst:1-325Monitoring data 민감도와 필요한 scope를 먼저 정한 뒤 `CAP_PERFMON`, `perf_event_paranoid`, file descriptor와 mmap memory limit를 최소 권한으로 조합합니다.