From ddc02ba7a6cc92d07cf073395b2d41347a8d35fb Mon Sep 17 00:00:00 2001 From: Roland Reichwein Date: Sun, 5 Apr 2020 15:11:44 +0200 Subject: Drop privileges --- privileges.cpp | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 privileges.cpp (limited to 'privileges.cpp') diff --git a/privileges.cpp b/privileges.cpp new file mode 100644 index 0000000..94f1fed --- /dev/null +++ b/privileges.cpp @@ -0,0 +1,49 @@ +#include "privileges.h" + +#include +#include +#include +#include +#include +#include + +#include "config.h" + +using namespace std::string_literals; + +namespace { + + int get_number_from_process(std::string command) { + char value[100]; + + FILE* p = popen(command.data(), "r"); + if (p == NULL) + throw std::runtime_error("Error executing: "s + command); + + if (fgets(value, sizeof(value), p) == NULL) + throw std::runtime_error("Error reading from command: "s + command); + + pclose(p); + + return atoi(value); + } + +} + +void drop_privileges(const Config& config) +{ + // skip when run as user + if (geteuid() != 0) { + std::cout << "Note: not running as root -> not dropping privileges" << std::endl; + return; + } + + int gid = get_number_from_process("id -g "s + config.Group()); + if (setgid(gid) == -1) + throw std::runtime_error("setgid()"); + + int uid = get_number_from_process("id -u "s + config.User()); + if (setuid(uid) == -1) + throw std::runtime_error("setuid()"); +} + -- cgit v1.2.3