1 // Copyright (C) 2011-2012 Red Hat Inc.
3 // This program is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU General Public License as
5 // published by the Free Software Foundation; either version 2 of the
6 // License, or (at your option) any later version.
8 // This program is distributed in the hope that it will be useful, but
9 // WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU
11 // General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include <sys/types.h>
24 #include "privilege.h"
28 const char *pr_name (privilege_t p
)
30 /* Test the given privilege credentials in descending order. */
31 if (pr_contains (p
, pr_stapdev
))
33 if (pr_contains (p
, pr_stapsys
))
35 if (pr_contains (p
, pr_stapusr
))
42 int pr_contains (privilege_t actual
, privilege_t required
)
44 return (actual
& required
) == required
;
47 /* Determine the privilege credentials of the current user. If the user is not root, this
48 is determined by the user's group memberships. */
49 privilege_t
get_privilege_credentials (void)
51 static privilege_t stp_privilege
= pr_unknown
;
53 /* Have we already computed this? */
54 if (stp_privilege
!= pr_unknown
)
57 /* If the real uid of the user is root, then this user has all privileges. */
60 stp_privilege
= pr_all
;
64 /* The privilege credentials will be represented by a bit mask of the user's group memberships.
65 Start with an empty mask. */
66 stp_privilege
= pr_none
;
68 /* These are the gids of the groups we are interested in. */
69 gid_t stapdev_gid
= get_gid("stapdev");
70 gid_t stapsys_gid
= get_gid("stapsys");
71 gid_t stapusr_gid
= get_gid("stapusr");
73 /* If none of the groups was found, then the group memberships are irrelevant. */
74 if (stapdev_gid
== (gid_t
)-1 && stapsys_gid
== (gid_t
)-1 && stapusr_gid
== (gid_t
)-1)
77 /* Obtain a list of the user's groups. */
78 gid_t gidlist
[NGROUPS_MAX
];
79 int ngids
= getgroups(NGROUPS_MAX
, gidlist
);
82 cerr
<< _("Unable to retrieve group list") << endl
;
86 stp_privilege
= pr_none
;
88 /* According to the getgroups() man page, getgroups() may not
89 * return the effective gid, so examine the effective gid first first followed by the group
90 * gids obtained by getgroups. */
93 for (i
= -1, gid
= getegid(); i
< ngids
; ++i
, gid
= gidlist
[i
])
95 if (gid
== stapdev_gid
)
96 stp_privilege
= privilege_t (stp_privilege
| pr_stapdev
| pr_stapsys
| pr_stapusr
);
97 else if (gid
== stapsys_gid
)
98 stp_privilege
= privilege_t (stp_privilege
| pr_stapsys
| pr_stapusr
);
99 else if (gid
== stapusr_gid
)
100 stp_privilege
= privilege_t (stp_privilege
| pr_stapusr
);
102 if (stp_privilege
== pr_all
)
106 return stp_privilege
;