1 /*
2  * Copyright (C) 2017 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 <linux/futex.h>
18 #include <pthread.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21 
22 #include <atomic>
23 #include <chrono>
24 #include <string>
25 #include <thread>
26 #include <vector>
27 
28 #include <android-base/file.h>
29 #include <android-base/scopeguard.h>
30 #include <gtest/gtest.h>
31 #include <selinux/android.h>
32 #include <selinux/label.h>
33 #include <selinux/selinux.h>
34 
35 using namespace std::chrono_literals;
36 using namespace std::string_literals;
37 
38 template <typename T, typename F>
WriteFromMultipleThreads(std::vector<std::pair<std::string,T>> & files_and_parameters,F function)39 void WriteFromMultipleThreads(std::vector<std::pair<std::string, T>>& files_and_parameters,
40                               F function) {
41     auto num_threads = files_and_parameters.size();
42     pthread_barrier_t barrier;
43     pthread_barrier_init(&barrier, nullptr, num_threads);
44     auto barrier_destroy =
45         android::base::make_scope_guard([&barrier]() { pthread_barrier_destroy(&barrier); });
46 
47     auto make_thread_function = [&function, &barrier](const auto& file, const auto& parameter) {
48         return [&]() {
49             function(parameter);
50             pthread_barrier_wait(&barrier);
51             android::base::WriteStringToFile("<empty>", file);
52         };
53     };
54 
55     std::vector<std::thread> threads;
56     for (const auto& [file, parameter] : files_and_parameters) {
57         threads.emplace_back(std::thread(make_thread_function(file, parameter)));
58     }
59 
60     for (auto& thread : threads) {
61         thread.join();
62     }
63 }
64 
TEST(ueventd,setegid_IsPerThread)65 TEST(ueventd, setegid_IsPerThread) {
66     if (getuid() != 0) {
67         GTEST_SKIP() << "Skipping test, must be run as root.";
68         return;
69     }
70 
71     TemporaryDir dir;
72 
73     gid_t gid = 0;
74     std::vector<std::pair<std::string, gid_t>> files_and_gids;
75     std::generate_n(std::back_inserter(files_and_gids), 100, [&gid, &dir]() {
76         gid++;
77         return std::pair(dir.path + "/gid_"s + std::to_string(gid), gid);
78     });
79 
80     WriteFromMultipleThreads(files_and_gids, [](gid_t gid) { EXPECT_EQ(0, setegid(gid)); });
81 
82     for (const auto& [file, expected_gid] : files_and_gids) {
83         struct stat info;
84         ASSERT_EQ(0, stat(file.c_str(), &info));
85         EXPECT_EQ(expected_gid, info.st_gid);
86     }
87 }
88 
TEST(ueventd,setfscreatecon_IsPerThread)89 TEST(ueventd, setfscreatecon_IsPerThread) {
90     if (getuid() != 0) {
91         GTEST_SKIP() << "Skipping test, must be run as root.";
92         return;
93     }
94     if (!is_selinux_enabled() || security_getenforce() == 1) {
95         GTEST_SKIP() << "Skipping test, SELinux must be enabled and in permissive mode.";
96         return;
97     }
98 
99     const char* const contexts[] = {
100         "u:object_r:audio_device:s0",
101         "u:object_r:sensors_device:s0",
102         "u:object_r:video_device:s0",
103         "u:object_r:zero_device:s0",
104     };
105 
106     TemporaryDir dir;
107     std::vector<std::pair<std::string, std::string>> files_and_contexts;
108     for (const char* context : contexts) {
109         files_and_contexts.emplace_back(dir.path + "/context_"s + context, context);
110     }
111 
112     WriteFromMultipleThreads(files_and_contexts, [](const std::string& context) {
113         EXPECT_EQ(0, setfscreatecon(context.c_str()));
114     });
115 
116     for (const auto& [file, expected_context] : files_and_contexts) {
117         char* file_context;
118         ASSERT_GT(getfilecon(file.c_str(), &file_context), 0);
119         EXPECT_EQ(expected_context, file_context);
120         freecon(file_context);
121     }
122 }
123 
TEST(ueventd,selabel_lookup_MultiThreaded)124 TEST(ueventd, selabel_lookup_MultiThreaded) {
125     if (getuid() != 0) {
126         GTEST_SKIP() << "Skipping test, must be run as root.";
127         return;
128     }
129 
130     // Test parameters
131     constexpr auto num_threads = 10;
132     constexpr auto run_time = 200ms;
133 
134     std::unique_ptr<selabel_handle, decltype(&selabel_close)> sehandle(
135         selinux_android_file_context_handle(), &selabel_close);
136 
137     ASSERT_TRUE(sehandle);
138 
139     struct {
140         const char* file;
141         int mode;
142         std::string expected_context;
143     } files_and_modes[] = {
144         {"/dev/zero", 020666, ""},
145         {"/dev/null", 020666, ""},
146         {"/dev/random", 020666, ""},
147         {"/dev/urandom", 020666, ""},
148     };
149 
150     // Precondition, ensure that we can lookup all of these from a single thread, and store the
151     // expected context for each.
152     for (size_t i = 0; i < arraysize(files_and_modes); ++i) {
153         char* secontext;
154         ASSERT_EQ(0, selabel_lookup(sehandle.get(), &secontext, files_and_modes[i].file,
155                                     files_and_modes[i].mode));
156         files_and_modes[i].expected_context = secontext;
157         freecon(secontext);
158     }
159 
160     // Now that we know we can access them, and what their context should be, run in parallel.
161     std::atomic_bool stopped = false;
162     std::atomic_uint num_api_failures = 0;
163     std::atomic_uint num_context_check_failures = 0;
164     std::atomic_uint num_successes = 0;
165 
166     auto thread_function = [&]() {
167         while (!stopped) {
168             for (size_t i = 0; i < arraysize(files_and_modes); ++i) {
169                 char* secontext;
170                 int result = selabel_lookup(sehandle.get(), &secontext, files_and_modes[i].file,
171                                             files_and_modes[i].mode);
172                 if (result != 0) {
173                     num_api_failures++;
174                 } else {
175                     if (files_and_modes[i].expected_context != secontext) {
176                         num_context_check_failures++;
177                     } else {
178                         num_successes++;
179                     }
180                     freecon(secontext);
181                 }
182             }
183         }
184     };
185 
186     std::vector<std::thread> threads;
187     std::generate_n(back_inserter(threads), num_threads,
188                     [&]() { return std::thread(thread_function); });
189 
190     std::this_thread::sleep_for(run_time);
191     stopped = true;
192     for (auto& thread : threads) {
193         thread.join();
194     }
195 
196     EXPECT_EQ(0U, num_api_failures);
197     EXPECT_EQ(0U, num_context_check_failures);
198     EXPECT_GT(num_successes, 0U);
199 }
200