aboutsummaryrefslogtreecommitdiff
path: root/bon_suid.cpp
blob: 50a116be38d766c2c1c9657b82915e04f736d380 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <pwd.h>
#include <grp.h>
#include <unistd.h>
#include <stdio.h>
#include "bonnie.h"

int bon_setugid(CPCCHAR userName, CPCCHAR groupName, bool quiet)
{
  int id = 0;
  uid_t userId = 0;
  gid_t groupId = 0;
  bool setGroup = false;
  struct passwd *pw;
  struct group *gr;
  if(userName)
  {
    if(sscanf(userName, "%d", &id) == 1)
    {
      userId = uid_t(id);
      pw = getpwuid(userId);
      if(pw)
      {
        groupId = pw->pw_gid;
        setGroup = true;
      }
      else
      {
        gr = getgrnam("nogroup");
        if(gr)
        {
          groupId = gr->gr_gid;
          setGroup = true;
        }
      }
    }
    else
    {
      pw = getpwnam(userName);
      if(!pw)
      {
        fprintf(stderr, "Can't find user %s\n", userName);
        return 1;
      }
      userId = pw->pw_uid;
      groupId = pw->pw_gid;
      setGroup = true;
    }
  }
  if(groupName)
  {
    if(sscanf(groupName, "%d", &id) == 1)
    {
      groupId = gid_t(id);
      setGroup = true;
    }
    else
    {
      gr = getgrnam(groupName);
      if(!gr)
      {
        fprintf(stderr, "Can't find group %s\n", groupName);
        return 1;
      }
      groupId = gr->gr_gid;
      setGroup = true;
    }
  }
  if(setGroup)
  {
    if(setgid(groupId))
    {
      fprintf(stderr, "Can't set gid to %d.\n", int(groupId));
      return 1;
    }
  }
  if(setuid(userId))
  {
    fprintf(stderr, "Can't set uid to %d.\n", int(userId));
    return 1;
  }
  if(!quiet)
    fprintf(stderr, "Using uid:%d, gid:%d.\n", int(getuid()), int(getgid()));
  return 0;
}