1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/types.h>
11 #include <sys/utsname.h>
17 #include "alloc-util.h"
18 #include "apparmor-util.h"
19 #include "architecture.h"
20 #include "audit-util.h"
22 #include "cgroup-util.h"
23 #include "condition.h"
24 #include "cpu-set-util.h"
27 #include "extract-word.h"
30 #include "glob-util.h"
31 #include "hostname-util.h"
33 #include "limits-util.h"
36 #include "mountpoint-util.h"
37 #include "parse-util.h"
38 #include "path-util.h"
39 #include "proc-cmdline.h"
40 #include "process-util.h"
41 #include "selinux-util.h"
42 #include "smack-util.h"
43 #include "stat-util.h"
44 #include "string-table.h"
45 #include "string-util.h"
46 #include "tomoyo-util.h"
47 #include "user-util.h"
51 Condition
* condition_new(ConditionType type
, const char *parameter
, bool trigger
, bool negate
) {
55 assert(type
< _CONDITION_TYPE_MAX
);
56 assert((!parameter
) == (type
== CONDITION_NULL
));
58 c
= new(Condition
, 1);
69 c
->parameter
= strdup(parameter
);
77 void condition_free(Condition
*c
) {
84 Condition
* condition_free_list_type(Condition
*head
, ConditionType type
) {
87 LIST_FOREACH_SAFE(conditions
, c
, n
, head
)
88 if (type
< 0 || c
->type
== type
) {
89 LIST_REMOVE(conditions
, head
, c
);
93 assert(type
>= 0 || !head
);
97 static int condition_test_kernel_command_line(Condition
*c
) {
98 _cleanup_free_
char *line
= NULL
;
104 assert(c
->parameter
);
105 assert(c
->type
== CONDITION_KERNEL_COMMAND_LINE
);
107 r
= proc_cmdline(&line
);
111 equal
= strchr(c
->parameter
, '=');
114 _cleanup_free_
char *word
= NULL
;
117 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
124 found
= streq(word
, c
->parameter
);
128 f
= startswith(word
, c
->parameter
);
129 found
= f
&& IN_SET(*f
, 0, '=');
140 /* Listed in order of checking. Note that some comparators are prefixes of others, hence the longest
141 * should be listed first. */
142 ORDER_LOWER_OR_EQUAL
,
143 ORDER_GREATER_OR_EQUAL
,
152 static OrderOperator
parse_order(const char **s
) {
154 static const char *const prefix
[_ORDER_MAX
] = {
155 [ORDER_LOWER_OR_EQUAL
] = "<=",
156 [ORDER_GREATER_OR_EQUAL
] = ">=",
158 [ORDER_GREATER
] = ">",
160 [ORDER_UNEQUAL
] = "!=",
165 for (i
= 0; i
< _ORDER_MAX
; i
++) {
168 e
= startswith(*s
, prefix
[i
]);
175 return _ORDER_INVALID
;
178 static bool test_order(int k
, OrderOperator p
) {
185 case ORDER_LOWER_OR_EQUAL
:
194 case ORDER_GREATER_OR_EQUAL
:
201 assert_not_reached("unknown order");
206 static int condition_test_kernel_version(Condition
*c
) {
212 assert(c
->parameter
);
213 assert(c
->type
== CONDITION_KERNEL_VERSION
);
215 assert_se(uname(&u
) >= 0);
218 order
= parse_order(&p
);
220 /* No prefix? Then treat as glob string */
222 return fnmatch(skip_leading_chars(c
->parameter
, NULL
), u
.release
, 0) == 0;
224 return test_order(str_verscmp(u
.release
, skip_leading_chars(p
, NULL
)), order
);
227 static int condition_test_memory(Condition
*c
) {
234 assert(c
->parameter
);
235 assert(c
->type
== CONDITION_MEMORY
);
237 m
= physical_memory();
240 order
= parse_order(&p
);
242 order
= ORDER_GREATER_OR_EQUAL
; /* default to >= check, if nothing is specified. */
244 r
= safe_atou64(p
, &k
);
246 return log_debug_errno(r
, "Failed to parse size: %m");
248 return test_order(CMP(m
, k
), order
);
251 static int condition_test_cpus(Condition
*c
) {
258 assert(c
->parameter
);
259 assert(c
->type
== CONDITION_CPUS
);
261 n
= cpus_in_affinity_mask();
263 return log_debug_errno(n
, "Failed to determine CPUs in affinity mask: %m");
266 order
= parse_order(&p
);
268 order
= ORDER_GREATER_OR_EQUAL
; /* default to >= check, if nothing is specified. */
270 r
= safe_atou(p
, &k
);
272 return log_debug_errno(r
, "Failed to parse number of CPUs: %m");
274 return test_order(CMP((unsigned) n
, k
), order
);
277 static int condition_test_user(Condition
*c
) {
280 _cleanup_free_
char *username
= NULL
;
284 assert(c
->parameter
);
285 assert(c
->type
== CONDITION_USER
);
287 r
= parse_uid(c
->parameter
, &id
);
289 return id
== getuid() || id
== geteuid();
291 if (streq("@system", c
->parameter
))
292 return uid_is_system(getuid()) || uid_is_system(geteuid());
294 username
= getusername_malloc();
298 if (streq(username
, c
->parameter
))
301 if (getpid_cached() == 1)
302 return streq(c
->parameter
, "root");
305 r
= get_user_creds(&u
, &id
, NULL
, NULL
, NULL
, USER_CREDS_ALLOW_MISSING
);
309 return id
== getuid() || id
== geteuid();
312 static int condition_test_control_group_controller(Condition
*c
) {
314 CGroupMask system_mask
, wanted_mask
= 0;
317 assert(c
->parameter
);
318 assert(c
->type
== CONDITION_CONTROL_GROUP_CONTROLLER
);
320 r
= cg_mask_supported(&system_mask
);
322 return log_debug_errno(r
, "Failed to determine supported controllers: %m");
324 r
= cg_mask_from_string(c
->parameter
, &wanted_mask
);
325 if (r
< 0 || wanted_mask
<= 0) {
326 /* This won't catch the case that we have an unknown controller
327 * mixed in with valid ones -- these are only assessed on the
328 * validity of the valid controllers found. */
329 log_debug("Failed to parse cgroup string: %s", c
->parameter
);
333 return FLAGS_SET(system_mask
, wanted_mask
);
336 static int condition_test_group(Condition
*c
) {
341 assert(c
->parameter
);
342 assert(c
->type
== CONDITION_GROUP
);
344 r
= parse_gid(c
->parameter
, &id
);
348 /* Avoid any NSS lookups if we are PID1 */
349 if (getpid_cached() == 1)
350 return streq(c
->parameter
, "root");
352 return in_group(c
->parameter
) > 0;
355 static int condition_test_virtualization(Condition
*c
) {
359 assert(c
->parameter
);
360 assert(c
->type
== CONDITION_VIRTUALIZATION
);
362 if (streq(c
->parameter
, "private-users"))
363 return running_in_userns();
365 v
= detect_virtualization();
369 /* First, compare with yes/no */
370 b
= parse_boolean(c
->parameter
);
374 /* Then, compare categorization */
375 if (streq(c
->parameter
, "vm"))
376 return VIRTUALIZATION_IS_VM(v
);
378 if (streq(c
->parameter
, "container"))
379 return VIRTUALIZATION_IS_CONTAINER(v
);
381 /* Finally compare id */
382 return v
!= VIRTUALIZATION_NONE
&& streq(c
->parameter
, virtualization_to_string(v
));
385 static int condition_test_architecture(Condition
*c
) {
389 assert(c
->parameter
);
390 assert(c
->type
== CONDITION_ARCHITECTURE
);
392 a
= uname_architecture();
396 if (streq(c
->parameter
, "native"))
397 b
= native_architecture();
399 b
= architecture_from_string(c
->parameter
);
400 if (b
< 0) /* unknown architecture? Then it's definitely not ours */
407 static int condition_test_host(Condition
*c
) {
408 _cleanup_free_
char *h
= NULL
;
413 assert(c
->parameter
);
414 assert(c
->type
== CONDITION_HOST
);
416 if (sd_id128_from_string(c
->parameter
, &x
) >= 0) {
418 r
= sd_id128_get_machine(&y
);
422 return sd_id128_equal(x
, y
);
425 h
= gethostname_malloc();
429 return fnmatch(c
->parameter
, h
, FNM_CASEFOLD
) == 0;
432 static int condition_test_ac_power(Condition
*c
) {
436 assert(c
->parameter
);
437 assert(c
->type
== CONDITION_AC_POWER
);
439 r
= parse_boolean(c
->parameter
);
443 return (on_ac_power() != 0) == !!r
;
446 static int condition_test_security(Condition
*c
) {
448 assert(c
->parameter
);
449 assert(c
->type
== CONDITION_SECURITY
);
451 if (streq(c
->parameter
, "selinux"))
452 return mac_selinux_use();
453 if (streq(c
->parameter
, "smack"))
454 return mac_smack_use();
455 if (streq(c
->parameter
, "apparmor"))
456 return mac_apparmor_use();
457 if (streq(c
->parameter
, "audit"))
459 if (streq(c
->parameter
, "ima"))
461 if (streq(c
->parameter
, "tomoyo"))
462 return mac_tomoyo_use();
463 if (streq(c
->parameter
, "uefi-secureboot"))
464 return is_efi_secure_boot();
469 static int condition_test_capability(Condition
*c
) {
470 unsigned long long capabilities
= (unsigned long long) -1;
471 _cleanup_fclose_
FILE *f
= NULL
;
475 assert(c
->parameter
);
476 assert(c
->type
== CONDITION_CAPABILITY
);
478 /* If it's an invalid capability, we don't have it */
479 value
= capability_from_name(c
->parameter
);
483 /* If it's a valid capability we default to assume
486 f
= fopen("/proc/self/status", "re");
491 _cleanup_free_
char *line
= NULL
;
494 r
= read_line(f
, LONG_LINE_MAX
, &line
);
500 p
= startswith(line
, "CapBnd:");
502 if (sscanf(line
+7, "%llx", &capabilities
) != 1)
509 return !!(capabilities
& (1ULL << value
));
512 static int condition_test_needs_update(Condition
*c
) {
514 struct stat usr
, other
;
517 assert(c
->parameter
);
518 assert(c
->type
== CONDITION_NEEDS_UPDATE
);
520 /* If the file system is read-only we shouldn't suggest an update */
521 if (path_is_read_only_fs(c
->parameter
) > 0)
524 /* Any other failure means we should allow the condition to be true,
525 * so that we rather invoke too many update tools than too
528 if (!path_is_absolute(c
->parameter
))
531 p
= strjoina(c
->parameter
, "/.updated");
532 if (lstat(p
, &other
) < 0)
535 if (lstat("/usr/", &usr
) < 0)
539 * First, compare seconds as they are always accurate...
541 if (usr
.st_mtim
.tv_sec
!= other
.st_mtim
.tv_sec
)
542 return usr
.st_mtim
.tv_sec
> other
.st_mtim
.tv_sec
;
545 * ...then compare nanoseconds.
547 * A false positive is only possible when /usr's nanoseconds > 0
548 * (otherwise /usr cannot be strictly newer than the target file)
549 * AND the target file's nanoseconds == 0
550 * (otherwise the filesystem supports nsec timestamps, see stat(2)).
552 if (usr
.st_mtim
.tv_nsec
> 0 && other
.st_mtim
.tv_nsec
== 0) {
553 _cleanup_free_
char *timestamp_str
= NULL
;
557 r
= parse_env_file(NULL
, p
, "TIMESTAMP_NSEC", ×tamp_str
);
559 log_error_errno(r
, "Failed to parse timestamp file '%s', using mtime: %m", p
);
562 log_debug("No data in timestamp file '%s', using mtime", p
);
566 r
= safe_atou64(timestamp_str
, ×tamp
);
568 log_error_errno(r
, "Failed to parse timestamp value '%s' in file '%s', using mtime: %m", timestamp_str
, p
);
572 timespec_store(&other
.st_mtim
, timestamp
);
575 return usr
.st_mtim
.tv_nsec
> other
.st_mtim
.tv_nsec
;
578 static int condition_test_first_boot(Condition
*c
) {
582 assert(c
->parameter
);
583 assert(c
->type
== CONDITION_FIRST_BOOT
);
585 r
= parse_boolean(c
->parameter
);
589 return (access("/run/systemd/first-boot", F_OK
) >= 0) == !!r
;
592 static int condition_test_path_exists(Condition
*c
) {
594 assert(c
->parameter
);
595 assert(c
->type
== CONDITION_PATH_EXISTS
);
597 return access(c
->parameter
, F_OK
) >= 0;
600 static int condition_test_path_exists_glob(Condition
*c
) {
602 assert(c
->parameter
);
603 assert(c
->type
== CONDITION_PATH_EXISTS_GLOB
);
605 return glob_exists(c
->parameter
) > 0;
608 static int condition_test_path_is_directory(Condition
*c
) {
610 assert(c
->parameter
);
611 assert(c
->type
== CONDITION_PATH_IS_DIRECTORY
);
613 return is_dir(c
->parameter
, true) > 0;
616 static int condition_test_path_is_symbolic_link(Condition
*c
) {
618 assert(c
->parameter
);
619 assert(c
->type
== CONDITION_PATH_IS_SYMBOLIC_LINK
);
621 return is_symlink(c
->parameter
) > 0;
624 static int condition_test_path_is_mount_point(Condition
*c
) {
626 assert(c
->parameter
);
627 assert(c
->type
== CONDITION_PATH_IS_MOUNT_POINT
);
629 return path_is_mount_point(c
->parameter
, NULL
, AT_SYMLINK_FOLLOW
) > 0;
632 static int condition_test_path_is_read_write(Condition
*c
) {
634 assert(c
->parameter
);
635 assert(c
->type
== CONDITION_PATH_IS_READ_WRITE
);
637 return path_is_read_only_fs(c
->parameter
) <= 0;
640 static int condition_test_directory_not_empty(Condition
*c
) {
644 assert(c
->parameter
);
645 assert(c
->type
== CONDITION_DIRECTORY_NOT_EMPTY
);
647 r
= dir_is_empty(c
->parameter
);
648 return r
<= 0 && r
!= -ENOENT
;
651 static int condition_test_file_not_empty(Condition
*c
) {
655 assert(c
->parameter
);
656 assert(c
->type
== CONDITION_FILE_NOT_EMPTY
);
658 return (stat(c
->parameter
, &st
) >= 0 &&
659 S_ISREG(st
.st_mode
) &&
663 static int condition_test_file_is_executable(Condition
*c
) {
667 assert(c
->parameter
);
668 assert(c
->type
== CONDITION_FILE_IS_EXECUTABLE
);
670 return (stat(c
->parameter
, &st
) >= 0 &&
671 S_ISREG(st
.st_mode
) &&
672 (st
.st_mode
& 0111));
675 static int condition_test_null(Condition
*c
) {
677 assert(c
->type
== CONDITION_NULL
);
679 /* Note that during parsing we already evaluate the string and
680 * store it in c->negate */
684 int condition_test(Condition
*c
) {
686 static int (*const condition_tests
[_CONDITION_TYPE_MAX
])(Condition
*c
) = {
687 [CONDITION_PATH_EXISTS
] = condition_test_path_exists
,
688 [CONDITION_PATH_EXISTS_GLOB
] = condition_test_path_exists_glob
,
689 [CONDITION_PATH_IS_DIRECTORY
] = condition_test_path_is_directory
,
690 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = condition_test_path_is_symbolic_link
,
691 [CONDITION_PATH_IS_MOUNT_POINT
] = condition_test_path_is_mount_point
,
692 [CONDITION_PATH_IS_READ_WRITE
] = condition_test_path_is_read_write
,
693 [CONDITION_DIRECTORY_NOT_EMPTY
] = condition_test_directory_not_empty
,
694 [CONDITION_FILE_NOT_EMPTY
] = condition_test_file_not_empty
,
695 [CONDITION_FILE_IS_EXECUTABLE
] = condition_test_file_is_executable
,
696 [CONDITION_KERNEL_COMMAND_LINE
] = condition_test_kernel_command_line
,
697 [CONDITION_KERNEL_VERSION
] = condition_test_kernel_version
,
698 [CONDITION_VIRTUALIZATION
] = condition_test_virtualization
,
699 [CONDITION_SECURITY
] = condition_test_security
,
700 [CONDITION_CAPABILITY
] = condition_test_capability
,
701 [CONDITION_HOST
] = condition_test_host
,
702 [CONDITION_AC_POWER
] = condition_test_ac_power
,
703 [CONDITION_ARCHITECTURE
] = condition_test_architecture
,
704 [CONDITION_NEEDS_UPDATE
] = condition_test_needs_update
,
705 [CONDITION_FIRST_BOOT
] = condition_test_first_boot
,
706 [CONDITION_USER
] = condition_test_user
,
707 [CONDITION_GROUP
] = condition_test_group
,
708 [CONDITION_CONTROL_GROUP_CONTROLLER
] = condition_test_control_group_controller
,
709 [CONDITION_NULL
] = condition_test_null
,
710 [CONDITION_CPUS
] = condition_test_cpus
,
711 [CONDITION_MEMORY
] = condition_test_memory
,
717 assert(c
->type
>= 0);
718 assert(c
->type
< _CONDITION_TYPE_MAX
);
720 r
= condition_tests
[c
->type
](c
);
722 c
->result
= CONDITION_ERROR
;
726 b
= (r
> 0) == !c
->negate
;
727 c
->result
= b
? CONDITION_SUCCEEDED
: CONDITION_FAILED
;
731 bool condition_test_list(Condition
*first
, const char *(*to_string
)(ConditionType t
), condition_test_logger_t logger
, void *userdata
) {
735 assert(!!logger
== !!to_string
);
737 /* If the condition list is empty, then it is true */
741 /* Otherwise, if all of the non-trigger conditions apply and
742 * if any of the trigger conditions apply (unless there are
743 * none) we return true */
744 LIST_FOREACH(conditions
, c
, first
) {
747 r
= condition_test(c
);
751 logger(userdata
, LOG_WARNING
, r
, __FILE__
, __LINE__
, __func__
,
752 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
754 c
->trigger
? "|" : "",
755 c
->negate
? "!" : "",
758 logger(userdata
, LOG_DEBUG
, 0, __FILE__
, __LINE__
, __func__
,
761 c
->trigger
? "|" : "",
762 c
->negate
? "!" : "",
764 condition_result_to_string(c
->result
));
767 if (!c
->trigger
&& r
<= 0)
770 if (c
->trigger
&& triggered
<= 0)
774 return triggered
!= 0;
777 void condition_dump(Condition
*c
, FILE *f
, const char *prefix
, const char *(*to_string
)(ConditionType t
)) {
781 prefix
= strempty(prefix
);
784 "%s\t%s: %s%s%s %s\n",
787 c
->trigger
? "|" : "",
788 c
->negate
? "!" : "",
790 condition_result_to_string(c
->result
));
793 void condition_dump_list(Condition
*first
, FILE *f
, const char *prefix
, const char *(*to_string
)(ConditionType t
)) {
796 LIST_FOREACH(conditions
, c
, first
)
797 condition_dump(c
, f
, prefix
, to_string
);
800 static const char* const condition_type_table
[_CONDITION_TYPE_MAX
] = {
801 [CONDITION_ARCHITECTURE
] = "ConditionArchitecture",
802 [CONDITION_VIRTUALIZATION
] = "ConditionVirtualization",
803 [CONDITION_HOST
] = "ConditionHost",
804 [CONDITION_KERNEL_COMMAND_LINE
] = "ConditionKernelCommandLine",
805 [CONDITION_KERNEL_VERSION
] = "ConditionKernelVersion",
806 [CONDITION_SECURITY
] = "ConditionSecurity",
807 [CONDITION_CAPABILITY
] = "ConditionCapability",
808 [CONDITION_AC_POWER
] = "ConditionACPower",
809 [CONDITION_NEEDS_UPDATE
] = "ConditionNeedsUpdate",
810 [CONDITION_FIRST_BOOT
] = "ConditionFirstBoot",
811 [CONDITION_PATH_EXISTS
] = "ConditionPathExists",
812 [CONDITION_PATH_EXISTS_GLOB
] = "ConditionPathExistsGlob",
813 [CONDITION_PATH_IS_DIRECTORY
] = "ConditionPathIsDirectory",
814 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = "ConditionPathIsSymbolicLink",
815 [CONDITION_PATH_IS_MOUNT_POINT
] = "ConditionPathIsMountPoint",
816 [CONDITION_PATH_IS_READ_WRITE
] = "ConditionPathIsReadWrite",
817 [CONDITION_DIRECTORY_NOT_EMPTY
] = "ConditionDirectoryNotEmpty",
818 [CONDITION_FILE_NOT_EMPTY
] = "ConditionFileNotEmpty",
819 [CONDITION_FILE_IS_EXECUTABLE
] = "ConditionFileIsExecutable",
820 [CONDITION_USER
] = "ConditionUser",
821 [CONDITION_GROUP
] = "ConditionGroup",
822 [CONDITION_CONTROL_GROUP_CONTROLLER
] = "ConditionControlGroupController",
823 [CONDITION_NULL
] = "ConditionNull",
824 [CONDITION_CPUS
] = "ConditionCPUs",
825 [CONDITION_MEMORY
] = "ConditionMemory",
828 DEFINE_STRING_TABLE_LOOKUP(condition_type
, ConditionType
);
830 static const char* const assert_type_table
[_CONDITION_TYPE_MAX
] = {
831 [CONDITION_ARCHITECTURE
] = "AssertArchitecture",
832 [CONDITION_VIRTUALIZATION
] = "AssertVirtualization",
833 [CONDITION_HOST
] = "AssertHost",
834 [CONDITION_KERNEL_COMMAND_LINE
] = "AssertKernelCommandLine",
835 [CONDITION_KERNEL_VERSION
] = "AssertKernelVersion",
836 [CONDITION_SECURITY
] = "AssertSecurity",
837 [CONDITION_CAPABILITY
] = "AssertCapability",
838 [CONDITION_AC_POWER
] = "AssertACPower",
839 [CONDITION_NEEDS_UPDATE
] = "AssertNeedsUpdate",
840 [CONDITION_FIRST_BOOT
] = "AssertFirstBoot",
841 [CONDITION_PATH_EXISTS
] = "AssertPathExists",
842 [CONDITION_PATH_EXISTS_GLOB
] = "AssertPathExistsGlob",
843 [CONDITION_PATH_IS_DIRECTORY
] = "AssertPathIsDirectory",
844 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = "AssertPathIsSymbolicLink",
845 [CONDITION_PATH_IS_MOUNT_POINT
] = "AssertPathIsMountPoint",
846 [CONDITION_PATH_IS_READ_WRITE
] = "AssertPathIsReadWrite",
847 [CONDITION_DIRECTORY_NOT_EMPTY
] = "AssertDirectoryNotEmpty",
848 [CONDITION_FILE_NOT_EMPTY
] = "AssertFileNotEmpty",
849 [CONDITION_FILE_IS_EXECUTABLE
] = "AssertFileIsExecutable",
850 [CONDITION_USER
] = "AssertUser",
851 [CONDITION_GROUP
] = "AssertGroup",
852 [CONDITION_CONTROL_GROUP_CONTROLLER
] = "AssertControlGroupController",
853 [CONDITION_NULL
] = "AssertNull",
854 [CONDITION_CPUS
] = "AssertCPUs",
855 [CONDITION_MEMORY
] = "AssertMemory",
858 DEFINE_STRING_TABLE_LOOKUP(assert_type
, ConditionType
);
860 static const char* const condition_result_table
[_CONDITION_RESULT_MAX
] = {
861 [CONDITION_UNTESTED
] = "untested",
862 [CONDITION_SUCCEEDED
] = "succeeded",
863 [CONDITION_FAILED
] = "failed",
864 [CONDITION_ERROR
] = "error",
867 DEFINE_STRING_TABLE_LOOKUP(condition_result
, ConditionResult
);