Search code examples
c++coredump

Coredump file not generated when changing user


The following code generates coredump file:

#include <iostream>
#include <string>
#include <pwd.h>
#include <grp.h>
#include <sys/resource.h>

int main() {
    int b = 0;
    int a = 140/b;

    return 0;
}   

Output: Floating point exception (core dumped)

Coredump is generated in /opt/cores

$ ls -al /opt/cores
total 188
drwxrwxrwx  2 root root   4096 Jan 13 16:46 .
drwxr-xr-x 28 root root   4096 Jan 12 11:57 ..
-rw-------  1 root root 344064 Jan 13 16:46 core.prueba.6776.8

However, this doesn't generate coredump file:

#include <iostream>
#include <string>
#include <pwd.h>
#include <grp.h>
#include <sys/resource.h>

int main() {
    std::string usr = "nobody";
    std::string grp = "oinstall";

    group* gp = getgrnam(grp.data());
    passwd* user = getpwnam(usr.data());
    if (gp && user && setgid(gp->gr_gid) == 0 && setuid(user->pw_uid) == 0) {
        std::cout << "changed!" << std::endl;
    } else {
        std::cout << "not changed =(" << std::endl;
    }   
    struct rlimit rlim;
    rlim.rlim_cur = RLIM_INFINITY;
    rlim.rlim_max = RLIM_INFINITY;
    if (setrlimit(RLIMIT_CORE, &rlim) != 0) {
        std::cout << "setrlimit error" << std::endl;
    }   

    getrlimit(RLIMIT_CORE, &rlim);

    std::cout << "rlim_cur: " << (int)rlim.rlim_cur <<", rlim_max: " << (int)rlim.rlim_max << std::endl;
    int b = 0;
    int a = 140/b;

    return 0;
}  

Output:

changed!
rlim_cur: -1, rlim_max: -1
Floating point exception

I've run the first piece of code with the changed user and it generates the coredump file, so the directory has the right permissions. The problem is when I change user in the code. Any clues?

This happens on Linux (CentOS 6, CentOS 7, RHEL 6).

In Solaris works fine.


Solution

  • nos was right about the security mechanism.

    The solution was to add this after changing user:

    prctl(PR_SET_DUMPABLE, 1, 0,0,0);

    Now the coredump is generated.