程式語言 - GNU - C/C++ - Set Capability(In Container)



參考資訊:
http://www.vishalchovatiya.com/clone-system-call-example/

main.c

#define _GNU_SOURCE
#include <sys/wait.h>
#include <sys/utsname.h>
#include <sched.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/capability.h>

static int child(void *argv)
{
    cap_t caps = {0};
    unsigned cap_num = 1;
    cap_value_t cap_list[1] = {0};

    caps = cap_init();
    cap_clear(caps);
    cap_set_proc(caps);
    
    cap_list[0] = CAP_SYS_ADMIN;
    cap_set_flag(caps, CAP_EFFECTIVE, cap_num, cap_list, CAP_SET);
    cap_set_flag(caps, CAP_INHERITABLE, cap_num, cap_list, CAP_SET);
    cap_set_flag(caps, CAP_PERMITTED, cap_num, cap_list, CAP_SET);
    cap_set_proc(caps);
    cap_free(caps);
    return 0;
}

int main(int argc, char **argv)
{
    const unsigned int STACK_SIZE = 4096;

    char *stack = malloc(STACK_SIZE);
    if (stack) {
        pid_t pid = clone(child, stack + STACK_SIZE, CLONE_NEWPID | CLONE_NEWUSER | CLONE_NEWCGROUP | CLONE_VFORK, NULL);
        waitpid(pid, NULL, 0);
        free(stack);
    }
    return 0;
}

使用者也可以使用如下命令切換namespace

$ unshare -pUCf