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     // TODO(b/63712782): Structured bindings + templated containers are broken in clang :(
57     // for (const auto& [file, parameter] : files_and_parameters) {
58     for (const auto& pair : files_and_parameters) {
59         const auto& file = pair.first;
60         const auto& parameter = pair.second;
61         threads.emplace_back(std::thread(make_thread_function(file, parameter)));
62     }
63 
64     for (auto& thread : threads) {
65         thread.join();
66     }
67 }
68 
TEST(ueventd,setegid_IsPerThread)69 TEST(ueventd, setegid_IsPerThread) {
70     if (getuid() != 0) {
71         GTEST_SKIP() << "Skipping test, must be run as root.";
72         return;
73     }
74 
75     TemporaryDir dir;
76 
77     gid_t gid = 0;
78     std::vector<std::pair<std::string, gid_t>> files_and_gids;
79     std::generate_n(std::back_inserter(files_and_gids), 100, [&gid, &dir]() {
80         gid++;
81         return std::pair(dir.path + "/gid_"s + std::to_string(gid), gid);
82     });
83 
84     WriteFromMultipleThreads(files_and_gids, [](gid_t gid) { EXPECT_EQ(0, setegid(gid)); });
85 
86     for (const auto& [file, expected_gid] : files_and_gids) {
87         struct stat info;
88         ASSERT_EQ(0, stat(file.c_str(), &info));
89         EXPECT_EQ(expected_gid, info.st_gid);
90     }
91 }
92 
TEST(ueventd,setfscreatecon_IsPerThread)93 TEST(ueventd, setfscreatecon_IsPerThread) {
94     if (getuid() != 0) {
95         GTEST_SKIP() << "Skipping test, must be run as root.";
96         return;
97     }
98     if (!is_selinux_enabled() || security_getenforce() == 1) {
99         GTEST_SKIP() << "Skipping test, SELinux must be enabled and in permissive mode.";
100         return;
101     }
102 
103     const char* const contexts[] = {
104         "u:object_r:audio_device:s0",
105         "u:object_r:sensors_device:s0",
106         "u:object_r:video_device:s0"
107         "u:object_r:zero_device:s0",
108     };
109 
110     TemporaryDir dir;
111     std::vector<std::pair<std::string, std::string>> files_and_contexts;
112     for (const char* context : contexts) {
113         files_and_contexts.emplace_back(dir.path + "/context_"s + context, context);
114     }
115 
116     WriteFromMultipleThreads(files_and_contexts, [](const std::string& context) {
117         EXPECT_EQ(0, setfscreatecon(context.c_str()));
118     });
119 
120     for (const auto& [file, expected_context] : files_and_contexts) {
121         char* file_context;
122         ASSERT_GT(getfilecon(file.c_str(), &file_context), 0);
123         EXPECT_EQ(expected_context, file_context);
124         freecon(file_context);
125     }
126 }
127 
TEST(ueventd,selabel_lookup_MultiThreaded)128 TEST(ueventd, selabel_lookup_MultiThreaded) {
129     if (getuid() != 0) {
130         GTEST_SKIP() << "Skipping test, must be run as root.";
131         return;
132     }
133 
134     // Test parameters
135     constexpr auto num_threads = 10;
136     constexpr auto run_time = 200ms;
137 
138     std::unique_ptr<selabel_handle, decltype(&selabel_close)> sehandle(
139         selinux_android_file_context_handle(), &selabel_close);
140 
141     ASSERT_TRUE(sehandle);
142 
143     struct {
144         const char* file;
145         int mode;
146         std::string expected_context;
147     } files_and_modes[] = {
148         {"/dev/zero", 020666, ""},
149         {"/dev/null", 020666, ""},
150         {"/dev/random", 020666, ""},
151         {"/dev/urandom", 020666, ""},
152     };
153 
154     // Precondition, ensure that we can lookup all of these from a single thread, and store the
155     // expected context for each.
156     for (size_t i = 0; i < arraysize(files_and_modes); ++i) {
157         char* secontext;
158         ASSERT_EQ(0, selabel_lookup(sehandle.get(), &secontext, files_and_modes[i].file,
159                                     files_and_modes[i].mode));
160         files_and_modes[i].expected_context = secontext;
161         freecon(secontext);
162     }
163 
164     // Now that we know we can access them, and what their context should be, run in parallel.
165     std::atomic_bool stopped = false;
166     std::atomic_uint num_api_failures = 0;
167     std::atomic_uint num_context_check_failures = 0;
168     std::atomic_uint num_successes = 0;
169 
170     auto thread_function = [&]() {
171         while (!stopped) {
172             for (size_t i = 0; i < arraysize(files_and_modes); ++i) {
173                 char* secontext;
174                 int result = selabel_lookup(sehandle.get(), &secontext, files_and_modes[i].file,
175                                             files_and_modes[i].mode);
176                 if (result != 0) {
177                     num_api_failures++;
178                 } else {
179                     if (files_and_modes[i].expected_context != secontext) {
180                         num_context_check_failures++;
181                     } else {
182                         num_successes++;
183                     }
184                     freecon(secontext);
185                 }
186             }
187         }
188     };
189 
190     std::vector<std::thread> threads;
191     std::generate_n(back_inserter(threads), num_threads,
192                     [&]() { return std::thread(thread_function); });
193 
194     std::this_thread::sleep_for(run_time);
195     stopped = true;
196     for (auto& thread : threads) {
197         thread.join();
198     }
199 
200     EXPECT_EQ(0U, num_api_failures);
201     EXPECT_EQ(0U, num_context_check_failures);
202     EXPECT_GT(num_successes, 0U);
203 }
204