在不使用--privileged的情况下,在Docker容器内使用perf

25

我尝试在Docker容器中使用perf工具记录给定命令。

kernel.perf_event_paranoid设置为1,但是当我不加--privileged标志时,容器的行为就像设置为2一样。

我可以使用--privileged,但我要对perf工具运行的代码进行安全考虑,并且如果我同意通过允许perf工具来承担轻微的安全风险,则给容器授予特权权限似乎存在更高级别的风险。

是否有其他方法在容器内使用perf?

~$ docker version
Client:
 Version:      17.03.1-ce
 API version:  1.27
 Go version:   go1.7.5
 Git commit:   7392c3b/17.03.1-ce
 Built:        Tue May 30 17:59:44 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.03.1-ce
 API version:  1.27 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   7392c3b/17.03.1-ce
 Built:        Tue May 30 17:59:44 2017
 OS/Arch:      linux/amd64
 Experimental: false

~$ cat /proc/sys/kernel/perf_event_paranoid
1
~$ perf record ./my-executable
perf_event_open(..., PERF_FLAG_FD_CLOEXEC) failed with unexpected error 1 (Operation not permitted)
perf_event_open(..., 0) failed unexpectedly with error 1 (Operation not permitted)
Error:
You may not have permission to collect stats.
Consider tweaking /proc/sys/kernel/perf_event_paranoid:
 -1 - Not paranoid at all
  0 - Disallow raw tracepoint access for unpriv
  1 - Disallow cpu events for unpriv
  2 - Disallow kernel profiling for unpriv
2个回答

38
经过一些研究,问题并不在于 perf_event_paranoid,而是因为在docker中已经将 perf_event_open(syscall)列入黑名单: https://docs.docker.com/engine/security/seccomp/ "Docker v17.06: Seccomp security profiles for Docker"

默认配置文件会阻止一些重要的syscalls

perf_event_open Tracing/profiling syscall, which could leak a lot of information on the host.

我的第一个解决方法是编写一个脚本,下载官方的seccomp文件 https://github.com/moby/moby/blob/master/profiles/seccomp/default.json,并将 perf_event_open 添加到白名单的syacall列表中。

然后我使用 --security-opt seccomp=my-seccomp.json 命令以my-seccomp.json文件作为docker的安全配置启动。


我能在正在运行的容器中更新它吗?或者至少可以通过docker-compose注入它吗? - Rajeev Ranjan
当我在寻找在容器中运行Async Profiler的特定问题的解决方案时,我发现了这个问题和答案。他们README中的这一部分与此相关:https://github.com/jvm-profiling-tools/async-profiler#profiling-java-in-a-container - Juraj Martinka

1

使用 --cap-add SYS_ADMIN 命令运行Docker。


5
CAP_SYS_ADMIN权限允许很多其他特权,这会使得容器内的代码通过加载模块来接管主机内核吗?(原文链接:https://lwn.net/Articles/486306/) - Peter Cordes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接