github.com/kubiko/snapd@v0.0.0-20201013125620-d4f3094d9ddf/cmd/libsnap-confine-private/privs-test.c (about) 1 /* 2 * Copyright (C) 2017 Canonical Ltd 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License version 3 as 6 * published by the Free Software Foundation. 7 * 8 * This program is distributed in the hope that it will be useful, 9 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License 14 * along with this program. If not, see <http://www.gnu.org/licenses/>. 15 * 16 */ 17 18 #include "privs.h" 19 #include "privs.c" 20 21 #include <glib.h> 22 23 // Test that dropping permissions really works 24 static void test_sc_privs_drop(void) 25 { 26 if (geteuid() != 0 || getuid() == 0) { 27 g_test_skip("run this test after chown root.root; chmod u+s"); 28 return; 29 } 30 if (getegid() != 0 || getgid() == 0) { 31 g_test_skip("run this test after chown root.root; chmod g+s"); 32 return; 33 } 34 if (g_test_subprocess()) { 35 // We start as a regular user with effective-root identity. 36 g_assert_cmpint(getuid(), !=, 0); 37 g_assert_cmpint(getgid(), !=, 0); 38 39 g_assert_cmpint(geteuid(), ==, 0); 40 g_assert_cmpint(getegid(), ==, 0); 41 42 // We drop the privileges. 43 sc_privs_drop(); 44 45 // The we are no longer root. 46 g_assert_cmpint(getuid(), !=, 0); 47 g_assert_cmpint(geteuid(), !=, 0); 48 g_assert_cmpint(getgid(), !=, 0); 49 g_assert_cmpint(getegid(), !=, 0); 50 51 // We don't have any supplementary groups. 52 gid_t groups[2]; 53 int num_groups = getgroups(1, groups); 54 g_assert_cmpint(num_groups, ==, 1); 55 g_assert_cmpint(groups[0], ==, getgid()); 56 57 // All done. 58 return; 59 } 60 g_test_trap_subprocess(NULL, 0, G_TEST_SUBPROCESS_INHERIT_STDERR); 61 g_test_trap_assert_passed(); 62 } 63 64 static void __attribute__((constructor)) init(void) 65 { 66 g_test_add_func("/privs/sc_privs_drop", test_sc_privs_drop); 67 }