1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "common/libs/utils/users.h"
18
19 #include <cerrno>
20 #include <cstring>
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include <grp.h>
24
25 #include <algorithm>
26 #include <vector>
27
28 #include <glog/logging.h>
29
30 namespace {
GroupIdFromName(const std::string & group_name)31 gid_t GroupIdFromName(const std::string& group_name) {
32 struct group grp{};
33 struct group* grp_p{};
34 std::vector<char> buffer(100);
35 int result = 0;
36 while(true) {
37 result = getgrnam_r(group_name.c_str(), &grp, buffer.data(), buffer.size(),
38 &grp_p);
39 if (result != ERANGE) {
40 break;
41 }
42 buffer.resize(2*buffer.size());
43 }
44 if (result == 0) {
45 if (grp_p != nullptr) {
46 return grp.gr_gid;
47 } else {
48 LOG(ERROR) << "Group " << group_name << " does not exist";
49 return -1;
50 }
51 } else {
52 LOG(ERROR) << "Unable to get group id for group " << group_name << ": "
53 << std::strerror(result);
54 return -1;
55 }
56 }
57
GetSuplementaryGroups()58 std::vector<gid_t> GetSuplementaryGroups() {
59 int num_groups = getgroups(0, nullptr);
60 if (num_groups < 0) {
61 LOG(ERROR) << "Unable to get number of suplementary groups: "
62 << std::strerror(errno);
63 return {};
64 }
65 std::vector<gid_t> groups(num_groups + 1);
66 int retval = getgroups(groups.size(), groups.data());
67 if (retval < 0) {
68 LOG(ERROR) << "Error obtaining list of suplementary groups (list size: "
69 << groups.size() << "): " << std::strerror(errno);
70 return {};
71 }
72 return groups;
73 }
74 } // namespace
75
InGroup(const std::string & group)76 bool cvd::InGroup(const std::string& group) {
77 auto gid = GroupIdFromName(group);
78 if (gid == static_cast<gid_t>(-1)) {
79 return false;
80 }
81
82 if (gid == getegid()) {
83 return true;
84 }
85
86 auto groups = GetSuplementaryGroups();
87
88 if (std::find(groups.cbegin(), groups.cend(), gid) != groups.cend()) {
89 return true;
90 }
91 return false;
92 }