]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/test/test-secure-bits.c
docs/RANDOM_SEEDS: update NetBSD link
[thirdparty/systemd.git] / src / test / test-secure-bits.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4
5 #include "securebits-util.h"
6 #include "strv.h"
7 #include "tests.h"
8 #include "unit-file.h"
9
10 static const char * const string_bits[] = {
11 "keep-caps",
12 "keep-caps-locked",
13 "no-setuid-fixup",
14 "no-setuid-fixup-locked",
15 "noroot",
16 "noroot-locked",
17 NULL
18 };
19
20 TEST(secure_bits_basic) {
21 _cleanup_free_ char *joined = NULL, *str = NULL;
22 int r;
23
24 /* Check if converting each bit from string and back to string yields
25 * the same value */
26 STRV_FOREACH(bit, string_bits) {
27 _cleanup_free_ char *s = NULL;
28
29 r = secure_bits_from_string(*bit);
30 assert_se(r > 0);
31 assert_se(secure_bits_is_valid(r));
32 assert_se(secure_bits_to_string_alloc(r, &s) >= 0);
33 printf("%s = 0x%x = %s\n", *bit, (unsigned)r, s);
34 assert_se(streq(*bit, s));
35 }
36
37 /* Ditto, but with all bits at once */
38 joined = strv_join((char**)string_bits, " ");
39 assert_se(joined);
40 r = secure_bits_from_string(joined);
41 assert_se(r > 0);
42 assert_se(secure_bits_is_valid(r));
43 assert_se(secure_bits_to_string_alloc(r, &str) >= 0);
44 printf("%s = 0x%x = %s\n", joined, (unsigned)r, str);
45 assert_se(streq(joined, str));
46
47 str = mfree(str);
48
49 /* Empty string */
50 assert_se(secure_bits_from_string("") == 0);
51 assert_se(secure_bits_from_string(" ") == 0);
52
53 /* Only invalid entries */
54 assert_se(secure_bits_from_string("foo bar baz") == 0);
55
56 /* Empty secure bits */
57 assert_se(secure_bits_to_string_alloc(0, &str) >= 0);
58 assert_se(isempty(str));
59
60 str = mfree(str);
61
62 /* Bits to string with check */
63 assert_se(secure_bits_to_string_alloc_with_check(INT_MAX, &str) == -EINVAL);
64 assert_se(str == NULL);
65 assert_se(secure_bits_to_string_alloc_with_check(
66 (1 << SECURE_KEEP_CAPS) | (1 << SECURE_KEEP_CAPS_LOCKED),
67 &str) >= 0);
68 assert_se(streq(str, "keep-caps keep-caps-locked"));
69 }
70
71 TEST(secure_bits_mix) {
72 static struct sbit_table {
73 const char *input;
74 const char *expected;
75 } sbit_table[] = {
76 { "keep-caps keep-caps keep-caps", "keep-caps" },
77 { "keep-caps noroot keep-caps", "keep-caps noroot" },
78 { "noroot foo bar baz noroot", "noroot" },
79 { "noroot \"foo\" \"bar keep-caps", "noroot" },
80 { "\"noroot foo\" bar keep-caps", "keep-caps" },
81 {}
82 };
83
84 for (const struct sbit_table *s = sbit_table; s->input; s++) {
85 _cleanup_free_ char *str = NULL;
86 int r;
87
88 r = secure_bits_from_string(s->input);
89 assert_se(r > 0);
90 assert_se(secure_bits_is_valid(r));
91 assert_se(secure_bits_to_string_alloc(r, &str) >= 0);
92 printf("%s = 0x%x = %s\n", s->input, (unsigned)r, str);
93 assert_se(streq(s->expected, str));
94 }
95 }
96
97 DEFINE_TEST_MAIN(LOG_DEBUG);