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 <android-base/logging.h>
29 
30 namespace cuttlefish {
31 namespace {
GroupIdFromName(const std::string & group_name)32 gid_t GroupIdFromName(const std::string& group_name) {
33   struct group grp{};
34   struct group* grp_p{};
35   std::vector<char> buffer(100);
36   int result = 0;
37   while(true) {
38     result = getgrnam_r(group_name.c_str(), &grp, buffer.data(), buffer.size(),
39                         &grp_p);
40     if (result != ERANGE) {
41       break;
42     }
43     buffer.resize(2*buffer.size());
44   }
45   if (result == 0) {
46     if (grp_p != nullptr) {
47       return grp.gr_gid;
48     } else {
49       // Caller may be checking with non-existent group name
50       return -1;
51     }
52   } else {
53     LOG(ERROR) << "Unable to get group id for group " << group_name << ": "
54                << std::strerror(result);
55     return -1;
56   }
57 }
58 
GetSuplementaryGroups()59 std::vector<gid_t> GetSuplementaryGroups() {
60   int num_groups = getgroups(0, nullptr);
61   if (num_groups < 0) {
62     LOG(ERROR) << "Unable to get number of suplementary groups: "
63                << std::strerror(errno);
64     return {};
65   }
66   std::vector<gid_t> groups(num_groups + 1);
67   int retval = getgroups(groups.size(), groups.data());
68   if (retval < 0) {
69     LOG(ERROR) << "Error obtaining list of suplementary groups (list size: "
70                << groups.size() << "): " << std::strerror(errno);
71     return {};
72   }
73   return groups;
74 }
75 }  // namespace
76 
InGroup(const std::string & group)77 bool InGroup(const std::string& group) {
78   auto gid = GroupIdFromName(group);
79   if (gid == static_cast<gid_t>(-1)) {
80     return false;
81   }
82 
83   if (gid == getegid()) {
84     return true;
85   }
86 
87   auto groups = GetSuplementaryGroups();
88 
89   if (std::find(groups.cbegin(), groups.cend(), gid) != groups.cend()) {
90     return true;
91   }
92   return false;
93 }
94 
95 } // namespace cuttlefish
96