将 GDB 附加到正在运行的进程的 PID 时出现权限错误

将 GDB 附加到正在运行的进程的 PID 时出现权限错误

我有一个这样的玩具C++程序

#include <iostream>
int main() {
    int n{};
    std::cin >> n; // waits for input
    std::cout << n << std::endl;
}

它在执行注释行时暂停,等待用户输入并为我提供了附加调试器所需的所有时间。

我在一个终端中运行这个程序,然后在另一个终端中输入

gdb -p $(pidof that-executable)

目的是将调试器附加到上面源代码编译成的可执行文件。

但是,尝试会导致以下错误:

GNU gdb (GDB) 12.1
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-pc-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word".
Attaching to process 1086551
ptrace: Operation not permitted.

答案1

gdbgdb考虑到允许攻击者执行的操作(从用户环境中的对等进程窃取或更改私钥等),可能会出于安全原因而被阻止。因此,现代操作系统通常会限制gdb可以访问的内容。

最好的方法可能是在下面运行程序,gdb而不是附加到进程;这通常是默认允许的,尽管设置起来可能很棘手。

否则,可能有一个配置值(例如/proc/sys/kernel/yama/ptrace_scope例如Linux,或kern.global_ptraceOpenBSD 上的 sysctl),用于调整gdb允许访问的内容。或者,运行gdbroot,但这可能会引入其他问题。或者,Linux 上的容器可能首先需要被授予该SYS_PTRACE功能。已调用的进程prctl(PR_SET_DUMPABLE...)可能很难追踪。

在 Linux 上,selinux 或其他此类安全框架也可能导致操作失败。尝试将它们设置为宽松。

答案2

中概述了两种可能的解决方案(一种是临时的,一种是永久的)这是 AskUbuntu 上类似(如果不相同)问题的答案

这部分运行具有临时功能的程序这个 ArchLinux 维基给出了替代解决方案。

我已经测试了第一个链接的临时解决方案和第二个链接的解决方案。他们都工作。

由于我不确定什么是正确的方法,所以我也在 ArchLinux 论坛上询问

相关内容