1 /* Copyright 2017 The Chromium OS Authors. All rights reserved.
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  *
5  * Test system.[ch] module code using gtest.
6  */
7 
8 #include <ftw.h>
9 #include <limits.h>
10 #include <linux/securebits.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/stat.h>
15 #include <sys/statvfs.h>
16 #include <unistd.h>
17 
18 #include <gtest/gtest.h>
19 
20 #include <string>
21 
22 #include "system.h"
23 
24 namespace {
25 
26 // A random path that really really should not exist on the host.
27 constexpr const char kNoSuchDir[] = "/.x/..x/...x/path/should/not/exist/";
28 
29 // A random file that should exist on both Linux and Android.
30 constexpr const char kValidFile[] = "/etc/hosts";
31 
32 // A random directory that should exist.
33 constexpr const char kValidDir[] = "/";
34 
35 // A random character device that should exist.
36 constexpr const char kValidCharDev[] = "/dev/null";
37 
is_android()38 constexpr bool is_android() {
39 #if defined(__ANDROID__)
40   return true;
41 #else
42   return false;
43 #endif
44 }
45 
46 // Returns a template path that can be used as an argument to mkstemp / mkdtemp.
temp_path_pattern()47 constexpr const char* temp_path_pattern() {
48   if (is_android())
49     return "/data/local/tmp/minijail.tests.XXXXXX";
50   else
51     return "minijail.tests.XXXXXX";
52 }
53 
54 // Recursively deletes the subtree rooted at |path|.
rmdir_recursive(const std::string & path)55 bool rmdir_recursive(const std::string& path) {
56   auto callback = [](const char* child, const struct stat*, int file_type,
57                      struct FTW*) -> int {
58     if (file_type == FTW_DP) {
59       if (rmdir(child) == -1) {
60         fprintf(stderr, "rmdir(%s): %s", child, strerror(errno));
61         return -1;
62       }
63     } else if (file_type == FTW_F) {
64       if (unlink(child) == -1) {
65         fprintf(stderr, "unlink(%s): %s", child, strerror(errno));
66         return -1;
67       }
68     }
69     return 0;
70   };
71 
72   return nftw(path.c_str(), callback, 128, FTW_DEPTH) == 0;
73 }
74 
75 // Creates a temporary directory that will be cleaned up upon leaving scope.
76 class TemporaryDir {
77  public:
TemporaryDir()78   TemporaryDir() : path(temp_path_pattern()) {
79     if (mkdtemp(const_cast<char*>(path.c_str())) == nullptr)
80       path.clear();
81   }
~TemporaryDir()82   ~TemporaryDir() {
83     if (!is_valid())
84       return;
85     rmdir_recursive(path.c_str());
86   }
87 
is_valid() const88   bool is_valid() const { return !path.empty(); }
89 
90   std::string path;
91 
92  private:
93   TemporaryDir(const TemporaryDir&) = delete;
94   TemporaryDir& operator=(const TemporaryDir&) = delete;
95 };
96 
97 // Creates a named temporary file that will be cleaned up upon leaving scope.
98 class TemporaryFile {
99  public:
TemporaryFile()100   TemporaryFile() : path(temp_path_pattern()) {
101     int fd = mkstemp(const_cast<char*>(path.c_str()));
102     if (fd == -1) {
103       path.clear();
104       return;
105     }
106     close(fd);
107   }
~TemporaryFile()108   ~TemporaryFile() {
109     if (!is_valid())
110       return;
111     unlink(path.c_str());
112   }
113 
is_valid() const114   bool is_valid() const { return !path.empty(); }
115 
116   std::string path;
117 
118  private:
119   TemporaryFile(const TemporaryFile&) = delete;
120   TemporaryFile& operator=(const TemporaryFile&) = delete;
121 };
122 
123 }  // namespace
124 
TEST(secure_noroot_set_and_locked,zero_mask)125 TEST(secure_noroot_set_and_locked, zero_mask) {
126   ASSERT_EQ(secure_noroot_set_and_locked(0), 0);
127 }
128 
TEST(secure_noroot_set_and_locked,set)129 TEST(secure_noroot_set_and_locked, set) {
130   ASSERT_EQ(secure_noroot_set_and_locked(issecure_mask(SECURE_NOROOT) |
131                                          issecure_mask(SECURE_NOROOT_LOCKED)),
132             1);
133 }
134 
TEST(secure_noroot_set_and_locked,not_set)135 TEST(secure_noroot_set_and_locked, not_set) {
136   ASSERT_EQ(secure_noroot_set_and_locked(issecure_mask(SECURE_KEEP_CAPS) |
137                                          issecure_mask(SECURE_NOROOT_LOCKED)),
138             0);
139 }
140 
141 // Sanity check for the cap range.
TEST(get_last_valid_cap,basic)142 TEST(get_last_valid_cap, basic) {
143   unsigned int cap = get_last_valid_cap();
144 
145   // We pick 35 as it's been that since at least v3.0.
146   // If this test is run on older kernels, it might fail.
147   EXPECT_GE(cap, 35u);
148 
149   // Pick a really large number that we probably won't hit for a long time.
150   // It helps that caps are bitfields.
151   EXPECT_LT(cap, 128u);
152 }
153 
154 // Might be useful to figure out the return value, but for now,
155 // just make sure it doesn't crash?
TEST(cap_ambient_supported,smoke)156 TEST(cap_ambient_supported, smoke) {
157   cap_ambient_supported();
158 }
159 
160 // Invalid indexes should return errors, not crash.
TEST(setup_pipe_end,bad_index)161 TEST(setup_pipe_end, bad_index) {
162   EXPECT_LT(setup_pipe_end(nullptr, 2), 0);
163   EXPECT_LT(setup_pipe_end(nullptr, 3), 0);
164   EXPECT_LT(setup_pipe_end(nullptr, 4), 0);
165 }
166 
167 // Verify getting the first fd works.
TEST(setup_pipe_end,index0)168 TEST(setup_pipe_end, index0) {
169   int fds[2];
170   EXPECT_EQ(0, pipe(fds));
171   // This should close fds[1] and return fds[0].
172   EXPECT_EQ(fds[0], setup_pipe_end(fds, 0));
173   // Use close() to verify open/close state.
174   EXPECT_EQ(-1, close(fds[1]));
175   EXPECT_EQ(0, close(fds[0]));
176 }
177 
178 // Verify getting the second fd works.
TEST(setup_pipe_end,index1)179 TEST(setup_pipe_end, index1) {
180   int fds[2];
181   EXPECT_EQ(0, pipe(fds));
182   // This should close fds[0] and return fds[1].
183   EXPECT_EQ(fds[1], setup_pipe_end(fds, 1));
184   // Use close() to verify open/close state.
185   EXPECT_EQ(-1, close(fds[0]));
186   EXPECT_EQ(0, close(fds[1]));
187 }
188 
189 // Invalid indexes should return errors, not crash.
TEST(setup_and_dupe_pipe_end,bad_index)190 TEST(setup_and_dupe_pipe_end, bad_index) {
191   EXPECT_LT(setup_and_dupe_pipe_end(nullptr, 2, -1), 0);
192   EXPECT_LT(setup_and_dupe_pipe_end(nullptr, 3, -1), 0);
193   EXPECT_LT(setup_and_dupe_pipe_end(nullptr, 4, -1), 0);
194 }
195 
196 // An invalid path should return an error.
TEST(write_pid_to_path,bad_path)197 TEST(write_pid_to_path, bad_path) {
198   EXPECT_NE(0, write_pid_to_path(0, kNoSuchDir));
199 }
200 
201 // Make sure we can write a pid to the file.
TEST(write_pid_to_path,basic)202 TEST(write_pid_to_path, basic) {
203   TemporaryFile tmp;
204   ASSERT_TRUE(tmp.is_valid());
205 
206   EXPECT_EQ(0, write_pid_to_path(1234, tmp.path.c_str()));
207   FILE *fp = fopen(tmp.path.c_str(), "re");
208   EXPECT_NE(nullptr, fp);
209   char data[6] = {};
210   EXPECT_EQ(5u, fread(data, 1, sizeof(data), fp));
211   fclose(fp);
212   EXPECT_EQ(0, strcmp(data, "1234\n"));
213 }
214 
215 // If the destination exists, there's nothing to do.
216 // Also check trailing slash handling.
TEST(mkdir_p,dest_exists)217 TEST(mkdir_p, dest_exists) {
218   EXPECT_EQ(0, mkdir_p("/", 0, true));
219   EXPECT_EQ(0, mkdir_p("///", 0, true));
220   EXPECT_EQ(0, mkdir_p("/proc", 0, true));
221   EXPECT_EQ(0, mkdir_p("/proc/", 0, true));
222   EXPECT_EQ(0, mkdir_p("/dev", 0, true));
223   EXPECT_EQ(0, mkdir_p("/dev/", 0, true));
224 }
225 
226 // Create a directory tree that doesn't exist.
TEST(mkdir_p,create_tree)227 TEST(mkdir_p, create_tree) {
228   TemporaryDir dir;
229   ASSERT_TRUE(dir.is_valid());
230 
231   // Run `mkdir -p <path>/a/b/c`.
232   std::string path_a = dir.path + "/a";
233   std::string path_a_b = path_a + "/b";
234   std::string path_a_b_c = path_a_b + "/c";
235 
236   // First try creating it as a file.
237   EXPECT_EQ(0, mkdir_p(path_a_b_c.c_str(), 0700, false));
238 
239   // Make sure the final path doesn't exist yet.
240   struct stat st;
241   EXPECT_EQ(0, stat(path_a_b.c_str(), &st));
242   EXPECT_EQ(true, S_ISDIR(st.st_mode));
243   EXPECT_EQ(-1, stat(path_a_b_c.c_str(), &st));
244 
245   // Then create it as a complete dir.
246   EXPECT_EQ(0, mkdir_p(path_a_b_c.c_str(), 0700, true));
247 
248   // Make sure the final dir actually exists.
249   EXPECT_EQ(0, stat(path_a_b_c.c_str(), &st));
250   EXPECT_EQ(true, S_ISDIR(st.st_mode));
251 }
252 
253 // If the destination exists, there's nothing to do.
TEST(setup_mount_destination,dest_exists)254 TEST(setup_mount_destination, dest_exists) {
255   // Pick some paths that should always exist.  We pass in invalid pointers
256   // for other args so we crash if the dest check doesn't short circuit.
257   EXPECT_EQ(0, setup_mount_destination(nullptr, kValidDir, 0, 0, false,
258                                        nullptr));
259   EXPECT_EQ(0, setup_mount_destination(nullptr, "/proc", 0, 0, true, nullptr));
260   EXPECT_EQ(0, setup_mount_destination(nullptr, "/dev", 0, 0, false, nullptr));
261 }
262 
263 // Mount flags should be obtained for bind-mounts
TEST(setup_mount_destination,mount_flags)264 TEST(setup_mount_destination, mount_flags) {
265   struct statvfs stvfs_buf;
266   ASSERT_EQ(0, statvfs("/proc", &stvfs_buf));
267 
268   TemporaryDir dir;
269   ASSERT_TRUE(dir.is_valid());
270 
271   unsigned long mount_flags = -1;
272   // Passing -1 for user ID/group ID tells chown to make no changes.
273   std::string proc = dir.path + "/proc";
274   EXPECT_EQ(0, setup_mount_destination("/proc", proc.c_str(), -1, -1, true,
275                                        &mount_flags));
276   EXPECT_EQ(stvfs_buf.f_flag, mount_flags);
277   EXPECT_EQ(0, rmdir(proc.c_str()));
278 
279   // Same thing holds for children of a mount.
280   mount_flags = -1;
281   std::string proc_self = dir.path + "/proc_self";
282   EXPECT_EQ(0, setup_mount_destination("/proc/self", proc_self.c_str(), -1, -1,
283                                        true, &mount_flags));
284   EXPECT_EQ(stvfs_buf.f_flag, mount_flags);
285   EXPECT_EQ(0, rmdir(proc_self.c_str()));
286 }
287 
288 // When given a bind mount where the source is relative, reject it.
TEST(setup_mount_destination,reject_relative_bind)289 TEST(setup_mount_destination, reject_relative_bind) {
290   // Pick a destination we know doesn't exist.
291   EXPECT_NE(0, setup_mount_destination("foo", kNoSuchDir, 0, 0, true, nullptr));
292 }
293 
294 // A mount of a pseudo filesystem should make the destination dir.
TEST(setup_mount_destination,create_pseudo_fs)295 TEST(setup_mount_destination, create_pseudo_fs) {
296   TemporaryDir dir;
297   ASSERT_TRUE(dir.is_valid());
298 
299   // Passing -1 for user ID/group ID tells chown to make no changes.
300   std::string no_chmod = dir.path + "/no_chmod";
301   EXPECT_EQ(0, setup_mount_destination("none", no_chmod.c_str(), -1, -1, false,
302                                        nullptr));
303   // We check it's a directory by deleting it as such.
304   EXPECT_EQ(0, rmdir(no_chmod.c_str()));
305 
306   // Confirm that a bad user ID/group ID fails the function as expected.
307   // On Android, Bionic manages user IDs directly: there is no /etc/passwd file.
308   // This results in most user IDs being valid. Instead of trying to find an
309   // invalid user ID, just skip this check.
310   if (!is_android()) {
311     std::string with_chmod = dir.path + "/with_chmod";
312     EXPECT_NE(0, setup_mount_destination("none", with_chmod.c_str(),
313                                          UINT_MAX / 2, UINT_MAX / 2, false,
314                                          nullptr));
315   }
316 }
317 
318 // If the source path does not exist, we should error out.
TEST(setup_mount_destination,missing_source)319 TEST(setup_mount_destination, missing_source) {
320   // The missing dest path is so we can exercise the source logic.
321   EXPECT_NE(0, setup_mount_destination(kNoSuchDir, kNoSuchDir, 0, 0, false,
322                                        nullptr));
323   EXPECT_NE(0, setup_mount_destination(kNoSuchDir, kNoSuchDir, 0, 0, true,
324                                        nullptr));
325 }
326 
327 // A bind mount of a directory should create the destination dir.
TEST(setup_mount_destination,create_bind_dir)328 TEST(setup_mount_destination, create_bind_dir) {
329   TemporaryDir dir;
330   ASSERT_TRUE(dir.is_valid());
331 
332   // Passing -1 for user ID/group ID tells chown to make no changes.
333   std::string child_dir = dir.path + "/child_dir";
334   EXPECT_EQ(0, setup_mount_destination(kValidDir, child_dir.c_str(), -1, -1,
335                                        true, nullptr));
336   // We check it's a directory by deleting it as such.
337   EXPECT_EQ(0, rmdir(child_dir.c_str()));
338 }
339 
340 // A bind mount of a file should create the destination file.
TEST(setup_mount_destination,create_bind_file)341 TEST(setup_mount_destination, create_bind_file) {
342   TemporaryDir dir;
343   ASSERT_TRUE(dir.is_valid());
344 
345   // Passing -1 for user ID/group ID tells chown to make no changes.
346   std::string child_file = dir.path + "/child_file";
347   EXPECT_EQ(0, setup_mount_destination(kValidFile, child_file.c_str(), -1, -1,
348                                        true, nullptr));
349   // We check it's a file by deleting it as such.
350   EXPECT_EQ(0, unlink(child_file.c_str()));
351 }
352 
353 // A mount of a character device should create the destination char.
TEST(setup_mount_destination,create_char_dev)354 TEST(setup_mount_destination, create_char_dev) {
355   TemporaryDir dir;
356   ASSERT_TRUE(dir.is_valid());
357 
358   // Passing -1 for user ID/group ID tells chown to make no changes.
359   std::string child_dev = dir.path + "/child_dev";
360   EXPECT_EQ(0, setup_mount_destination(kValidCharDev, child_dev.c_str(), -1, -1,
361                                        false, nullptr));
362   // We check it's a directory by deleting it as such.
363   EXPECT_EQ(0, rmdir(child_dev.c_str()));
364 }
365