Skip to content
API Documentation
BastionGuard™
privilege_utils.cpp
Go to the documentation of this file.
1#include "privilege_utils.hpp"
2
3#include <cerrno>
4#include <cstring>
5#include <cstdlib>
6#include <string>
7#include <unistd.h>
8
10 return ::geteuid() == 0;
11}
12
13bool PrivilegeUtils::can_read_source(const std::string& path) {
14 return !path.empty() && ::access(path.c_str(), R_OK) == 0;
15}
16
18#ifdef __linux__
19 char buf[4096] = {0};
20 const ssize_t n = ::readlink("/proc/self/exe", buf, sizeof(buf) - 1);
21 if (n > 0) {
22 buf[n] = '\0';
23 return std::string(buf);
24 }
25#endif
26 return "bastionguard-recovery-data";
27}
28
29std::string PrivilegeUtils::shell_quote(const std::string& s) {
30 std::string out = "'";
31 for (char c : s) {
32 if (c == '\'') out += "'\\''";
33 else out.push_back(c);
34 }
35 out += "'";
36 return out;
37}
38
39std::string PrivilegeUtils::build_pkexec_relaunch_command(const std::string& extra_args) {
40 const std::string exe = shell_quote(self_executable_path());
41 std::string cmd = "pkexec ";
42 cmd += exe;
43 if (!extra_args.empty()) {
44 cmd += " ";
45 cmd += extra_args;
46 }
47 return cmd;
48}
49
50bool PrivilegeUtils::launch_pkexec_relaunch(std::string& error, const std::string& extra_args) {
51 const std::string cmd = build_pkexec_relaunch_command(extra_args) + " >/dev/null 2>&1 &";
52 const int rc = std::system(cmd.c_str());
53 if (rc != 0) {
54 error = std::string("pkexec launch failed: ") + std::strerror(errno);
55 return false;
56 }
57 return true;
58}
static std::string build_pkexec_relaunch_command(const std::string &extra_args="")
static std::string shell_quote(const std::string &s)
static std::string self_executable_path()
static bool is_running_as_root()
static bool launch_pkexec_relaunch(std::string &error, const std::string &extra_args="")
static bool can_read_source(const std::string &path)