1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef KERNEL_LITE_UIDGID_TEST 17 #define KERNEL_LITE_UIDGID_TEST 18 19 #include <gtest/gtest.h> 20 #include "utils.h" 21 #include "log.h" 22 #include "KernelConstants.h" 23 24 // max test number of uid/gid, not actual max number 25 const int MAX_UGID = 100000; 26 static int groupNum = -1; 27 const int ARRAY_SIZE = 10; 28 static gid_t groupsArray[ARRAY_SIZE] = {0}; 29 30 // Assert all uid == expectUid 31 #define AssertAllUid(expectUid) do { \ 32 uid_t uid, euid, suid; \ 33 getresuid(&uid, &euid, &suid); \ 34 ASSERT_EQ(uid, expectUid); \ 35 ASSERT_EQ(euid, expectUid); \ 36 ASSERT_EQ(suid, expectUid); \ 37 } while (0) 38 39 // Assert all gid == expectGid 40 #define AssertAllGid(expectGid) do { \ 41 gid_t gid, egid, sgid; \ 42 getresgid(&gid, &egid, &sgid); \ 43 ASSERT_EQ(gid, expectGid); \ 44 ASSERT_EQ(egid, expectGid); \ 45 ASSERT_EQ(sgid, expectGid); \ 46 } while (0) 47 48 class UidGidTest : public testing::Test { 49 public: 50 // return a rand uid or gid, speacial value excluded. GetRandID()51 static uid_t GetRandID() 52 { 53 int id; 54 do { 55 id = GetRandom(MAX_UGID); 56 } while (id == 0 || id == SHELL_UID || id == SHELL_GID); 57 return id; 58 } 59 protected: SetUpTestCase()60 static void SetUpTestCase() 61 { 62 for (int i = 0; i < ARRAY_SIZE; i++) { 63 groupsArray[i] = -1; 64 } 65 groupNum = getgroups(0, groupsArray); 66 EXPECT_NE(groupNum, -1); 67 int rt = getgroups(groupNum, groupsArray); 68 EXPECT_EQ(rt, groupNum); 69 } 70 TearDown()71 void TearDown() 72 { 73 LOG("TearDown: reset uid and gid"); 74 gid_t groupIds[groupNum]; 75 LOG("TearDown: reset uid and gid %d", sizeof(groupIds) / sizeof(gid_t)); 76 for (int i = 0; i < groupNum; i++) { 77 groupIds[i] = groupsArray[i]; 78 } 79 setuid(SHELL_UID); 80 setgid(SHELL_GID); 81 AssertAllUid(SHELL_UID); 82 AssertAllGid(SHELL_GID); 83 int rt = setgroups(groupNum, groupIds); 84 EXPECT_EQ(rt, 0); 85 } 86 }; 87 88 #endif 89