I have a problem with my Linux daemon program. It starts with root privileges, does some configuration, then permanently drops privileges by switching to some user and group and continues working. The switch to the non-privileged user is done like this:
void switch_to_user_group(std::string const& username, std::string const& groupname)
{
// Switch to user/group
gid_t gid = getgid();
if (!groupname.empty())
{
gid = get_group_id(groupname);
if (0 != setgid(gid))
{
std::cout << "Failed to switch to group " << gid << std::endl;
std::abort();
}
}
if (!username.empty())
{
uid_t uid = get_user_id(username);
if (initgroups(username.c_str(), gid) != 0)
{
std::cout << "initgroups failed" << std::endl;
std::abort();
}
if (0 != setuid(uid))
{
std::cout << "Failed to switch to user " << uid << std::endl;
std::abort();
}
}
}
The switch performs correctly, I can see the process in ps and top running under my user. The problem is that I can't attach to this process from gdb, even after it has dropped the privileges. The output is:
Attaching to process 15716
Could not attach to process. If your uid matches the uid of the target
process, check the setting of /proc/sys/kernel/yama/ptrace_scope, or try
again as the root user. For more details, see /etc/sysctl.d/10-ptrace.conf
ptrace: Operation not permitted.
I'm running gdb under the same user the process switched to, and I am able to attach to other processes that were initially started under under that user. I tried this on Kubuntu 13.10 (YAMA is disabled), Debian 6 and 7 with the same result.
So my questions are:
- Why can't ptrace attach to a process that has the same effective and real UID as gdb?
- Is it possible to drop privileges of my program in a way so that I can attach to it from the unprivileged gdb? How?
Thanks.