← Documents Documentation/admin-guide/perf-security.rst GitHub 원문 ↗

Linux 6.18.37 · Administration

Perf events and tool security

perf_events data의 민감도, CAP_PERFMON 기반 권한 분리, unprivileged scope와 resource limit를 설명합니다.

Source pathDocumentation/admin-guide/perf-security.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

보안 운영 핵심

perf-security.rst:1-325

Monitoring data 민감도와 필요한 scope를 먼저 정한 뒤 `CAP_PERFMON`, `perf_event_paranoid`, file descriptor와 mmap memory limit를 최소 권한으로 조합합니다.

관점핵심
민감도Execution context register와 process memory를 담을 수 있는 4등급 data가 가장 민감
권장 권한`CAP_PERFMON`; `CAP_SYS_ADMIN`은 backward compatibility 용도
전용 group`perf_users`에만 executable access와 file capability를 부여
대체 환경File capability가 불가능하면 `capsh` shell을 `sudoers`로 제한
비특권 범위`perf_event_paranoid` 값이 높을수록 system-wide·kernel monitoring을 축소
Resource`RLIMIT_NOFILE`, `perf_event_mlock_kb`, `RLIMIT_MEMLOCK`을 함께 계산

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. _perf_security:
2
3 Perf events and tool security
4 =============================
5
6 Overview
7 --------
8
9 Usage of Performance Counters for Linux (perf_events) [1]_ , [2]_ , [3]_
10 can impose a considerable risk of leaking sensitive data accessed by
11 monitored processes. The data leakage is possible both in scenarios of
12 direct usage of perf_events system call API [2]_ and over data files
13 generated by Perf tool user mode utility (Perf) [3]_ , [4]_ . The risk
14 depends on the nature of data that perf_events performance monitoring
15 units (PMU) [2]_ and Perf collect and expose for performance analysis.
16 Collected system and performance data may be split into several
17 categories:
18
19 1. System hardware and software configuration data, for example: a CPU
20 model and its cache configuration, an amount of available memory and
21 its topology, used kernel and Perf versions, performance monitoring
22 setup including experiment time, events configuration, Perf command
23 line parameters, etc.
24
25 2. User and kernel module paths and their load addresses with sizes,
26 process and thread names with their PIDs and TIDs, timestamps for
27 captured hardware and software events.
28
29 3. Content of kernel software counters (e.g., for context switches, page
30 faults, CPU migrations), architectural hardware performance counters
31 (PMC) [8]_ and machine specific registers (MSR) [9]_ that provide
32 execution metrics for various monitored parts of the system (e.g.,
33 memory controller (IMC), interconnect (QPI/UPI) or peripheral (PCIe)
34 uncore counters) without direct attribution to any execution context
35 state.
36
37 4. Content of architectural execution context registers (e.g., RIP, RSP,
38 RBP on x86_64), process user and kernel space memory addresses and
39 data, content of various architectural MSRs that capture data from
40 this category.
41
42 Data that belong to the fourth category can potentially contain
43 sensitive process data. If PMUs in some monitoring modes capture values
44 of execution context registers or data from process memory then access
45 to such monitoring modes requires to be ordered and secured properly.
46 So, perf_events performance monitoring and observability operations are
47 the subject for security access control management [5]_ .
48
49 perf_events access control
50 -------------------------------
51
52 To perform security checks, the Linux implementation splits processes
53 into two categories [6]_ : a) privileged processes (whose effective user
54 ID is 0, referred to as superuser or root), and b) unprivileged
55 processes (whose effective UID is nonzero). Privileged processes bypass
56 all kernel security permission checks so perf_events performance
57 monitoring is fully available to privileged processes without access,
58 scope and resource restrictions.
59
60 Unprivileged processes are subject to a full security permission check
61 based on the process's credentials [5]_ (usually: effective UID,
62 effective GID, and supplementary group list).
63
64 Linux divides the privileges traditionally associated with superuser
65 into distinct units, known as capabilities [6]_ , which can be
66 independently enabled and disabled on per-thread basis for processes and
67 files of unprivileged users.
68
69 Unprivileged processes with enabled CAP_PERFMON capability are treated
70 as privileged processes with respect to perf_events performance
71 monitoring and observability operations, thus, bypass *scope* permissions
72 checks in the kernel. CAP_PERFMON implements the principle of least
73 privilege [13]_ (POSIX 1003.1e: 2.2.2.39) for performance monitoring and
74 observability operations in the kernel and provides a secure approach to
75 performance monitoring and observability in the system.
76
77 For backward compatibility reasons the access to perf_events monitoring and
78 observability operations is also open for CAP_SYS_ADMIN privileged
79 processes but CAP_SYS_ADMIN usage for secure monitoring and observability
80 use cases is discouraged with respect to the CAP_PERFMON capability.
81 If system audit records [14]_ for a process using perf_events system call
82 API contain denial records of acquiring both CAP_PERFMON and CAP_SYS_ADMIN
83 capabilities then providing the process with CAP_PERFMON capability singly
84 is recommended as the preferred secure approach to resolve double access
85 denial logging related to usage of performance monitoring and observability.
86
87 Prior Linux v5.9 unprivileged processes using perf_events system call
88 are also subject for PTRACE_MODE_READ_REALCREDS ptrace access mode check
89 [7]_ , whose outcome determines whether monitoring is permitted.
90 So unprivileged processes provided with CAP_SYS_PTRACE capability are
91 effectively permitted to pass the check. Starting from Linux v5.9
92 CAP_SYS_PTRACE capability is not required and CAP_PERFMON is enough to
93 be provided for processes to make performance monitoring and observability
94 operations.
95
96 Other capabilities being granted to unprivileged processes can
97 effectively enable capturing of additional data required for later
98 performance analysis of monitored processes or a system. For example,
99 CAP_SYSLOG capability permits reading kernel space memory addresses from
100 /proc/kallsyms file.
101
102 Privileged Perf users groups
103 ---------------------------------
104
105 Mechanisms of capabilities, privileged capability-dumb files [6]_,
106 file system ACLs [10]_ and sudo [15]_ utility can be used to create
107 dedicated groups of privileged Perf users who are permitted to execute
108 performance monitoring and observability without limits. The following
109 steps can be taken to create such groups of privileged Perf users.
110
111 1. Create perf_users group of privileged Perf users, assign perf_users
112 group to Perf tool executable and limit access to the executable for
113 other users in the system who are not in the perf_users group:
114
115 ::
116
117 # groupadd perf_users
118 # ls -alhF
119 -rwxr-xr-x 2 root root 11M Oct 19 15:12 perf
120 # chgrp perf_users perf
121 # ls -alhF
122 -rwxr-xr-x 2 root perf_users 11M Oct 19 15:12 perf
123 # chmod o-rwx perf
124 # ls -alhF
125 -rwxr-x--- 2 root perf_users 11M Oct 19 15:12 perf
126
127 2. Assign the required capabilities to the Perf tool executable file and
128 enable members of perf_users group with monitoring and observability
129 privileges [6]_ :
130
131 ::
132
133 # setcap "cap_perfmon,cap_sys_ptrace,cap_syslog=ep" perf
134 # setcap -v "cap_perfmon,cap_sys_ptrace,cap_syslog=ep" perf
135 perf: OK
136 # getcap perf
137 perf = cap_sys_ptrace,cap_syslog,cap_perfmon+ep
138
139 If the libcap [16]_ installed doesn't yet support "cap_perfmon", use "38" instead,
140 i.e.:
141
142 ::
143
144 # setcap "38,cap_ipc_lock,cap_sys_ptrace,cap_syslog=ep" perf
145
146 Note that you may need to have 'cap_ipc_lock' in the mix for tools such as
147 'perf top', alternatively use 'perf top -m N', to reduce the memory that
148 it uses for the perf ring buffer, see the memory allocation section below.
149
150 Using a libcap without support for CAP_PERFMON will make cap_get_flag(caps, 38,
151 CAP_EFFECTIVE, &val) fail, which will lead the default event to be 'cycles:u',
152 so as a workaround explicitly ask for the 'cycles' event, i.e.:
153
154 ::
155
156 # perf top -e cycles
157
158 To get kernel and user samples with a perf binary with just CAP_PERFMON.
159
160 As a result, members of perf_users group are capable of conducting
161 performance monitoring and observability by using functionality of the
162 configured Perf tool executable that, when executes, passes perf_events
163 subsystem scope checks.
164
165 In case Perf tool executable can't be assigned required capabilities (e.g.
166 file system is mounted with nosuid option or extended attributes are
167 not supported by the file system) then creation of the capabilities
168 privileged environment, naturally shell, is possible. The shell provides
169 inherent processes with CAP_PERFMON and other required capabilities so that
170 performance monitoring and observability operations are available in the
171 environment without limits. Access to the environment can be open via sudo
172 utility for members of perf_users group only. In order to create such
173 environment:
174
175 1. Create shell script that uses capsh utility [16]_ to assign CAP_PERFMON
176 and other required capabilities into ambient capability set of the shell
177 process, lock the process security bits after enabling SECBIT_NO_SETUID_FIXUP,
178 SECBIT_NOROOT and SECBIT_NO_CAP_AMBIENT_RAISE bits and then change
179 the process identity to sudo caller of the script who should essentially
180 be a member of perf_users group:
181
182 ::
183
184 # ls -alh /usr/local/bin/perf.shell
185 -rwxr-xr-x. 1 root root 83 Oct 13 23:57 /usr/local/bin/perf.shell
186 # cat /usr/local/bin/perf.shell
187 exec /usr/sbin/capsh --iab=^cap_perfmon --secbits=239 --user=$SUDO_USER -- -l
188
189 2. Extend sudo policy at /etc/sudoers file with a rule for perf_users group:
190
191 ::
192
193 # grep perf_users /etc/sudoers
194 %perf_users ALL=/usr/local/bin/perf.shell
195
196 3. Check that members of perf_users group have access to the privileged
197 shell and have CAP_PERFMON and other required capabilities enabled
198 in permitted, effective and ambient capability sets of an inherent process:
199
200 ::
201
202 $ id
203 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
204 $ sudo perf.shell
205 [sudo] password for capsh_test:
206 $ grep Cap /proc/self/status
207 CapInh: 0000004000000000
208 CapPrm: 0000004000000000
209 CapEff: 0000004000000000
210 CapBnd: 000000ffffffffff
211 CapAmb: 0000004000000000
212 $ capsh --decode=0000004000000000
213 0x0000004000000000=cap_perfmon
214
215 As a result, members of perf_users group have access to the privileged
216 environment where they can use tools employing performance monitoring APIs
217 governed by CAP_PERFMON Linux capability.
218
219 This specific access control management is only available to superuser
220 or root running processes with CAP_SETPCAP, CAP_SETFCAP [6]_
221 capabilities.
222
223 Unprivileged users
224 -----------------------------------
225
226 perf_events *scope* and *access* control for unprivileged processes
227 is governed by perf_event_paranoid [2]_ setting:
228
229 -1:
230 Impose no *scope* and *access* restrictions on using perf_events
231 performance monitoring. Per-user per-cpu perf_event_mlock_kb [2]_
232 locking limit is ignored when allocating memory buffers for storing
233 performance data. This is the least secure mode since allowed
234 monitored *scope* is maximized and no perf_events specific limits
235 are imposed on *resources* allocated for performance monitoring.
236
237 >=0:
238 *scope* includes per-process and system wide performance monitoring
239 but excludes raw tracepoints and ftrace function tracepoints
240 monitoring. CPU and system events happened when executing either in
241 user or in kernel space can be monitored and captured for later
242 analysis. Per-user per-cpu perf_event_mlock_kb locking limit is
243 imposed but ignored for unprivileged processes with CAP_IPC_LOCK
244 [6]_ capability.
245
246 >=1:
247 *scope* includes per-process performance monitoring only and
248 excludes system wide performance monitoring. CPU and system events
249 happened when executing either in user or in kernel space can be
250 monitored and captured for later analysis. Per-user per-cpu
251 perf_event_mlock_kb locking limit is imposed but ignored for
252 unprivileged processes with CAP_IPC_LOCK capability.
253
254 >=2:
255 *scope* includes per-process performance monitoring only. CPU and
256 system events happened when executing in user space only can be
257 monitored and captured for later analysis. Per-user per-cpu
258 perf_event_mlock_kb locking limit is imposed but ignored for
259 unprivileged processes with CAP_IPC_LOCK capability.
260
261 Resource control
262 ---------------------------------
263
264 Open file descriptors
265 +++++++++++++++++++++
266
267 The perf_events system call API [2]_ allocates file descriptors for
268 every configured PMU event. Open file descriptors are a per-process
269 accountable resource governed by the RLIMIT_NOFILE [11]_ limit
270 (ulimit -n), which is usually derived from the login shell process. When
271 configuring Perf collection for a long list of events on a large server
272 system, this limit can be easily hit preventing required monitoring
273 configuration. RLIMIT_NOFILE limit can be increased on per-user basis
274 modifying content of the limits.conf file [12]_ . Ordinarily, a Perf
275 sampling session (perf record) requires an amount of open perf_event
276 file descriptors that is not less than the number of monitored events
277 multiplied by the number of monitored CPUs.
278
279 Memory allocation
280 +++++++++++++++++
281
282 The amount of memory available to user processes for capturing
283 performance monitoring data is governed by the perf_event_mlock_kb [2]_
284 setting. This perf_event specific resource setting defines overall
285 per-cpu limits of memory allowed for mapping by the user processes to
286 execute performance monitoring. The setting essentially extends the
287 RLIMIT_MEMLOCK [11]_ limit, but only for memory regions mapped
288 specifically for capturing monitored performance events and related data.
289
290 For example, if a machine has eight cores and perf_event_mlock_kb limit
291 is set to 516 KiB, then a user process is provided with 516 KiB * 8 =
292 4128 KiB of memory above the RLIMIT_MEMLOCK limit (ulimit -l) for
293 perf_event mmap buffers. In particular, this means that, if the user
294 wants to start two or more performance monitoring processes, the user is
295 required to manually distribute the available 4128 KiB between the
296 monitoring processes, for example, using the --mmap-pages Perf record
297 mode option. Otherwise, the first started performance monitoring process
298 allocates all available 4128 KiB and the other processes will fail to
299 proceed due to the lack of memory.
300
301 RLIMIT_MEMLOCK and perf_event_mlock_kb resource constraints are ignored
302 for processes with the CAP_IPC_LOCK capability. Thus, perf_events/Perf
303 privileged users can be provided with memory above the constraints for
304 perf_events/Perf performance monitoring purpose by providing the Perf
305 executable with CAP_IPC_LOCK capability.
306
307 Bibliography
308 ------------
309
310 .. [1] `<https://lwn.net/Articles/337493/>`_
311 .. [2] `<http://man7.org/linux/man-pages/man2/perf_event_open.2.html>`_
312 .. [3] `<http://web.eece.maine.edu/~vweaver/projects/perf_events/>`_
313 .. [4] `<https://perf.wiki.kernel.org/index.php/Main_Page>`_
314 .. [5] `<https://www.kernel.org/doc/html/latest/security/credentials.html>`_
315 .. [6] `<http://man7.org/linux/man-pages/man7/capabilities.7.html>`_
316 .. [7] `<http://man7.org/linux/man-pages/man2/ptrace.2.html>`_
317 .. [8] `<https://en.wikipedia.org/wiki/Hardware_performance_counter>`_
318 .. [9] `<https://en.wikipedia.org/wiki/Model-specific_register>`_
319 .. [10] `<http://man7.org/linux/man-pages/man5/acl.5.html>`_
320 .. [11] `<http://man7.org/linux/man-pages/man2/getrlimit.2.html>`_
321 .. [12] `<http://man7.org/linux/man-pages/man5/limits.conf.5.html>`_
322 .. [13] `<https://sites.google.com/site/fullycapable>`_
323 .. [14] `<http://man7.org/linux/man-pages/man8/auditd.8.html>`_
324 .. [15] `<https://man7.org/linux/man-pages/man8/sudo.8.html>`_
325 .. [16] `<https://git.kernel.org/pub/scm/libs/libcap/libcap.git/>`_
326

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 범주예시
1System hardware·software configurationCPU model/cache, memory size/topology, kernel·Perf version, experiment time, event와 command-line 설정
2Identity와 mapping metadataModule path/load address/size, process·thread name, PID/TID, event timestamp
3집계 counter와 metricContext switch·page fault·CPU migration, PMC/MSR, IMC·QPI/UPI·PCIe uncore counter
4Execution context와 memory contentRIP/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-101

Linux는 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별로 켜고 끌 수 있게 합니다.

Capabilityperf_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-164

Capability, 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-222

Filesystem이 `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-260

Unprivileged process의 `perf_events` scope와 access는 `perf_event_paranoid` setting이 제어합니다.

Monitoring scopeExecution spaceMemory 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입니다.