summaryrefslogtreecommitdiffhomepage
path: root/privileges.cpp
blob: 94f1fed8603d0228bbd9847465c52cb307ad9c95 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "privileges.h"

#include <cstdlib>
#include <iostream>
#include <string>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

#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()");
}