implement caps check for ptrace

This commit is contained in:
mykola2312 2024-07-21 00:20:37 +03:00
parent abe4af91e4
commit 0d57997a19
4 changed files with 36 additions and 1 deletions

View file

@ -6,7 +6,7 @@ BIN_DIR = bin
CC = gcc
LD = ld
CFLAGS = -Wall -I$(INC_DIR)
LDFLAGS =
LDFLAGS = -lcap
BLACKJACK_SRC = main.c process.c
BLACKJACK_OBJ := $(addprefix $(OBJ_DIR)/,$(patsubst %.c,%.o,$(BLACKJACK_SRC)))

View file

@ -52,4 +52,7 @@ int is_considered_active(process_state_t state);
// find any active (running) thread and returns 0 and success, otherwise non zero
int find_active_thread(process_status_t* list, size_t count, process_status_t** thread);
// check if this process has any capability or is ran as root to be able to ptrace attach
int check_ptrace_permissions();
#endif

View file

@ -71,5 +71,13 @@ int main(int argc, char** argv)
free(threads);
free(list);
if (!check_ptrace_permissions())
{
fputs("this process doesn't have permission to ptrace.\n", stderr);
fputs("either run as root or set caps.\n", stderr);
return 1;
}
return 0;
}

View file

@ -1,6 +1,7 @@
#define _DEFAULT_SOURCE
#include "process.h"
#include "debug.h"
#include <sys/capability.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
@ -212,3 +213,26 @@ int find_active_thread(process_status_t* list, size_t count, process_status_t**
}
return 1;
}
int check_ptrace_permissions()
{
if (!geteuid())
{
// we're running as root
return 1;
}
// otherwise, check CAPS
cap_t cap = cap_get_pid(getpid());
cap_flag_value_t cap_flag_value;
if (cap)
{
if (!cap_get_flag(cap, CAP_SYS_ADMIN, CAP_EFFECTIVE, &cap_flag_value))
if (cap_flag_value == CAP_SET) return 1;
if (!cap_get_flag(cap, CAP_SYS_ADMIN, CAP_PERMITTED, &cap_flag_value))
if (cap_flag_value == CAP_SET) return 1;
}
return 0;
}