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 bymonitored processes. The data leakage is possible both in scenarios ofdirect usage of perf_events system call API[2] and over data filesgenerated by Perf tool user mode utility (Perf)[3] ,[4] . The riskdepends on the nature of data that perf_events performance monitoringunits (PMU)[2] and Perf collect and expose for performance analysis.Collected system and performance data may be split into severalcategories:

  1. System hardware and software configuration data, for example: a CPUmodel and its cache configuration, an amount of available memory andits topology, used kernel and Perf versions, performance monitoringsetup including experiment time, events configuration, Perf commandline parameters, etc.

  2. User and kernel module paths and their load addresses with sizes,process and thread names with their PIDs and TIDs, timestamps forcaptured hardware and software events.

  3. Content of kernel software counters (e.g., for context switches, pagefaults, CPU migrations), architectural hardware performance counters(PMC)[8] and machine specific registers (MSR)[9] that provideexecution 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 contextstate.

  4. Content of architectural execution context registers (e.g., RIP, RSP,RBP on x86_64), process user and kernel space memory addresses anddata, content of various architectural MSRs that capture data fromthis category.

Data that belong to the fourth category can potentially containsensitive process data. If PMUs in some monitoring modes capture valuesof execution context registers or data from process memory then accessto such monitoring modes requires to be ordered and secured properly.So, perf_events performance monitoring and observability operations arethe subject for security access control management[5] .

perf_events access control

To perform security checks, the Linux implementation splits processesinto two categories[6] : a) privileged processes (whose effective userID is 0, referred to as superuser or root), and b) unprivilegedprocesses (whose effective UID is nonzero). Privileged processes bypassall kernel security permission checks so perf_events performancemonitoring is fully available to privileged processes without access,scope and resource restrictions.

Unprivileged processes are subject to a full security permission checkbased on the process’s credentials[5] (usually: effective UID,effective GID, and supplementary group list).

Linux divides the privileges traditionally associated with superuserinto distinct units, known as capabilities[6] , which can beindependently enabled and disabled on per-thread basis for processes andfiles of unprivileged users.

Unprivileged processes with enabled CAP_PERFMON capability are treatedas privileged processes with respect to perf_events performancemonitoring and observability operations, thus, bypassscope permissionschecks in the kernel. CAP_PERFMON implements the principle of leastprivilege[13] (POSIX 1003.1e: 2.2.2.39) for performance monitoring andobservability operations in the kernel and provides a secure approach toperformance monitoring and observability in the system.

For backward compatibility reasons the access to perf_events monitoring andobservability operations is also open for CAP_SYS_ADMIN privilegedprocesses but CAP_SYS_ADMIN usage for secure monitoring and observabilityuse cases is discouraged with respect to the CAP_PERFMON capability.If system audit records[14] for a process using perf_events system callAPI contain denial records of acquiring both CAP_PERFMON and CAP_SYS_ADMINcapabilities then providing the process with CAP_PERFMON capability singlyis recommended as the preferred secure approach to resolve double accessdenial logging related to usage of performance monitoring and observability.

Prior Linux v5.9 unprivileged processes using perf_events system callare 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 areeffectively permitted to pass the check. Starting from Linux v5.9CAP_SYS_PTRACE capability is not required and CAP_PERFMON is enough tobe provided for processes to make performance monitoring and observabilityoperations.

Other capabilities being granted to unprivileged processes caneffectively enable capturing of additional data required for laterperformance 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 creatededicated groups of privileged Perf users who are permitted to executeperformance monitoring and observability without limits. The followingsteps can be taken to create such groups of privileged Perf users.

  1. Create perf_users group of privileged Perf users, assign perf_usersgroup to Perf tool executable and limit access to the executable forother 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
  1. Assign the required capabilities to the Perf tool executable file andenable members of perf_users group with monitoring and observabilityprivileges[6] :

# setcap "cap_perfmon,cap_sys_ptrace,cap_syslog=ep" perf# setcap -v "cap_perfmon,cap_sys_ptrace,cap_syslog=ep" perfperf: OK# getcap perfperf = 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 thatit 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 conductingperformance monitoring and observability by using functionality of theconfigured Perf tool executable that, when executes, passes perf_eventssubsystem 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 arenot supported by the file system) then creation of the capabilitiesprivileged environment, naturally shell, is possible. The shell providesinherent processes with CAP_PERFMON and other required capabilities so thatperformance monitoring and observability operations are available in theenvironment without limits. Access to the environment can be open via sudoutility for members of perf_users group only. In order to create suchenvironment:

  1. Create shell script that uses capsh utility[16] to assign CAP_PERFMONand other required capabilities into ambient capability set of the shellprocess, lock the process security bits after enabling SECBIT_NO_SETUID_FIXUP,SECBIT_NOROOT and SECBIT_NO_CAP_AMBIENT_RAISE bits and then changethe process identity to sudo caller of the script who should essentiallybe 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.shellexec /usr/sbin/capsh --iab=^cap_perfmon --secbits=239 --user=$SUDO_USER -- -l
  1. 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
  1. Check that members of perf_users group have access to the privilegedshell and have CAP_PERFMON and other required capabilities enabledin permitted, effective and ambient capability sets of an inherent process:

$ iduid=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/statusCapInh:        0000004000000000CapPrm:        0000004000000000CapEff:        0000004000000000CapBnd:        000000ffffffffffCapAmb:        0000004000000000$ capsh --decode=00000040000000000x0000004000000000=cap_perfmon

As a result, members of perf_users group have access to the privilegedenvironment where they can use tools employing performance monitoring APIsgoverned by CAP_PERFMON Linux capability.

This specific access control management is only available to superuseror root running processes with CAP_SETPCAP, CAP_SETFCAP[6]capabilities.

Unprivileged users

perf_eventsscope andaccess control for unprivileged processesis governed by perf_event_paranoid[2] setting:

-1:

Impose noscope andaccess restrictions on using perf_eventsperformance monitoring. Per-user per-cpu perf_event_mlock_kb[2]locking limit is ignored when allocating memory buffers for storingperformance data. This is the least secure mode since allowedmonitoredscope is maximized and no perf_events specific limitsare imposed onresources allocated for performance monitoring.

>=0:

scope includes per-process and system wide performance monitoringbut excludes raw tracepoints and ftrace function tracepointsmonitoring. CPU and system events happened when executing either inuser or in kernel space can be monitored and captured for lateranalysis. Per-user per-cpu perf_event_mlock_kb locking limit isimposed but ignored for unprivileged processes with CAP_IPC_LOCK[6] capability.

>=1:

scope includes per-process performance monitoring only andexcludes system wide performance monitoring. CPU and system eventshappened when executing either in user or in kernel space can bemonitored and captured for later analysis. Per-user per-cpuperf_event_mlock_kb locking limit is imposed but ignored forunprivileged processes with CAP_IPC_LOCK capability.

>=2:

scope includes per-process performance monitoring only. CPU andsystem events happened when executing in user space only can bemonitored and captured for later analysis. Per-user per-cpuperf_event_mlock_kb locking limit is imposed but ignored forunprivileged processes with CAP_IPC_LOCK capability.

Resource control

Open file descriptors

The perf_events system call API[2] allocates file descriptors forevery configured PMU event. Open file descriptors are a per-processaccountable resource governed by the RLIMIT_NOFILE[11] limit(ulimit -n), which is usually derived from the login shell process. Whenconfiguring Perf collection for a long list of events on a large serversystem, this limit can be easily hit preventing required monitoringconfiguration. RLIMIT_NOFILE limit can be increased on per-user basismodifying content of the limits.conf file[12] . Ordinarily, a Perfsampling session (perf record) requires an amount of open perf_eventfile descriptors that is not less than the number of monitored eventsmultiplied by the number of monitored CPUs.

Memory allocation

The amount of memory available to user processes for capturingperformance monitoring data is governed by the perf_event_mlock_kb[2]setting. This perf_event specific resource setting defines overallper-cpu limits of memory allowed for mapping by the user processes toexecute performance monitoring. The setting essentially extends theRLIMIT_MEMLOCK[11] limit, but only for memory regions mappedspecifically for capturing monitored performance events and related data.

For example, if a machine has eight cores and perf_event_mlock_kb limitis 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) forperf_event mmap buffers. In particular, this means that, if the userwants to start two or more performance monitoring processes, the user isrequired to manually distribute the available 4128 KiB between themonitoring processes, for example, using the --mmap-pages Perf recordmode option. Otherwise, the first started performance monitoring processallocates all available 4128 KiB and the other processes will fail toproceed due to the lack of memory.

RLIMIT_MEMLOCK and perf_event_mlock_kb resource constraints are ignoredfor processes with the CAP_IPC_LOCK capability. Thus, perf_events/Perfprivileged users can be provided with memory above the constraints forperf_events/Perf performance monitoring purpose by providing the Perfexecutable with CAP_IPC_LOCK capability.

Bibliography

[1]

https://lwn.net/Articles/337493/

[2](1,2,3,4,5,6,7)

http://man7.org/linux/man-pages/man2/perf_event_open.2.html

[3](1,2)

http://web.eece.maine.edu/~vweaver/projects/perf_events/

[4]

https://perf.wiki.kernel.org/index.php/Main_Page

[5](1,2)

https://www.kernel.org/doc/html/latest/security/credentials.html

[6](1,2,3,4,5,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](1,2)

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](1,2)

https://git.kernel.org/pub/scm/libs/libcap/libcap.git/