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"
26 #include "extract-word.h"
29 #include "glob-util.h"
30 #include "hostname-util.h"
32 #include "limits-util.h"
35 #include "mountpoint-util.h"
36 #include "parse-util.h"
37 #include "path-util.h"
38 #include "proc-cmdline.h"
39 #include "process-util.h"
40 #include "selinux-util.h"
41 #include "smack-util.h"
42 #include "stat-util.h"
43 #include "string-table.h"
44 #include "string-util.h"
45 #include "tomoyo-util.h"
46 #include "user-util.h"
50 Condition
* condition_new(ConditionType type
, const char *parameter
, bool trigger
, bool negate
) {
54 assert(type
< _CONDITION_TYPE_MAX
);
55 assert((!parameter
) == (type
== CONDITION_NULL
));
57 c
= new(Condition
, 1);
68 c
->parameter
= strdup(parameter
);
76 void condition_free(Condition
*c
) {
83 Condition
* condition_free_list_type(Condition
*head
, ConditionType type
) {
86 LIST_FOREACH_SAFE(conditions
, c
, n
, head
)
87 if (type
< 0 || c
->type
== type
) {
88 LIST_REMOVE(conditions
, head
, c
);
92 assert(type
>= 0 || !head
);
96 static int condition_test_kernel_command_line(Condition
*c
) {
97 _cleanup_free_
char *line
= NULL
;
103 assert(c
->parameter
);
104 assert(c
->type
== CONDITION_KERNEL_COMMAND_LINE
);
106 r
= proc_cmdline(&line
);
110 equal
= strchr(c
->parameter
, '=');
113 _cleanup_free_
char *word
= NULL
;
116 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_QUOTES
|EXTRACT_RELAX
);
123 found
= streq(word
, c
->parameter
);
127 f
= startswith(word
, c
->parameter
);
128 found
= f
&& IN_SET(*f
, 0, '=');
139 /* Listed in order of checking. Note that some comparators are prefixes of others, hence the longest
140 * should be listed first. */
141 ORDER_LOWER_OR_EQUAL
,
142 ORDER_GREATER_OR_EQUAL
,
151 static OrderOperator
parse_order(const char **s
) {
153 static const char *const prefix
[_ORDER_MAX
] = {
154 [ORDER_LOWER_OR_EQUAL
] = "<=",
155 [ORDER_GREATER_OR_EQUAL
] = ">=",
157 [ORDER_GREATER
] = ">",
159 [ORDER_UNEQUAL
] = "!=",
164 for (i
= 0; i
< _ORDER_MAX
; i
++) {
167 e
= startswith(*s
, prefix
[i
]);
174 return _ORDER_INVALID
;
177 static bool test_order(int k
, OrderOperator p
) {
184 case ORDER_LOWER_OR_EQUAL
:
193 case ORDER_GREATER_OR_EQUAL
:
200 assert_not_reached("unknown order");
205 static int condition_test_kernel_version(Condition
*c
) {
211 assert(c
->parameter
);
212 assert(c
->type
== CONDITION_KERNEL_VERSION
);
214 assert_se(uname(&u
) >= 0);
217 order
= parse_order(&p
);
219 /* No prefix? Then treat as glob string */
221 return fnmatch(skip_leading_chars(c
->parameter
, NULL
), u
.release
, 0) == 0;
223 return test_order(str_verscmp(u
.release
, skip_leading_chars(p
, NULL
)), order
);
226 static int condition_test_memory(Condition
*c
) {
233 assert(c
->parameter
);
234 assert(c
->type
== CONDITION_MEMORY
);
236 m
= physical_memory();
239 order
= parse_order(&p
);
241 order
= ORDER_GREATER_OR_EQUAL
; /* default to >= check, if nothing is specified. */
243 r
= safe_atou64(p
, &k
);
245 return log_debug_errno(r
, "Failed to parse size: %m");
247 return test_order(CMP(m
, k
), order
);
250 static int condition_test_cpus(Condition
*c
) {
257 assert(c
->parameter
);
258 assert(c
->type
== CONDITION_CPUS
);
260 n
= cpus_in_affinity_mask();
262 return log_debug_errno(n
, "Failed to determine CPUs in affinity mask: %m");
265 order
= parse_order(&p
);
267 order
= ORDER_GREATER_OR_EQUAL
; /* default to >= check, if nothing is specified. */
269 r
= safe_atou(p
, &k
);
271 return log_debug_errno(r
, "Failed to parse number of CPUs: %m");
273 return test_order(CMP((unsigned) n
, k
), order
);
276 static int condition_test_user(Condition
*c
) {
279 _cleanup_free_
char *username
= NULL
;
283 assert(c
->parameter
);
284 assert(c
->type
== CONDITION_USER
);
286 r
= parse_uid(c
->parameter
, &id
);
288 return id
== getuid() || id
== geteuid();
290 if (streq("@system", c
->parameter
))
291 return uid_is_system(getuid()) || uid_is_system(geteuid());
293 username
= getusername_malloc();
297 if (streq(username
, c
->parameter
))
300 if (getpid_cached() == 1)
301 return streq(c
->parameter
, "root");
304 r
= get_user_creds(&u
, &id
, NULL
, NULL
, NULL
, USER_CREDS_ALLOW_MISSING
);
308 return id
== getuid() || id
== geteuid();
311 static int condition_test_control_group_controller(Condition
*c
) {
313 CGroupMask system_mask
, wanted_mask
= 0;
316 assert(c
->parameter
);
317 assert(c
->type
== CONDITION_CONTROL_GROUP_CONTROLLER
);
319 r
= cg_mask_supported(&system_mask
);
321 return log_debug_errno(r
, "Failed to determine supported controllers: %m");
323 r
= cg_mask_from_string(c
->parameter
, &wanted_mask
);
324 if (r
< 0 || wanted_mask
<= 0) {
325 /* This won't catch the case that we have an unknown controller
326 * mixed in with valid ones -- these are only assessed on the
327 * validity of the valid controllers found. */
328 log_debug("Failed to parse cgroup string: %s", c
->parameter
);
332 return FLAGS_SET(system_mask
, wanted_mask
);
335 static int condition_test_group(Condition
*c
) {
340 assert(c
->parameter
);
341 assert(c
->type
== CONDITION_GROUP
);
343 r
= parse_gid(c
->parameter
, &id
);
347 /* Avoid any NSS lookups if we are PID1 */
348 if (getpid_cached() == 1)
349 return streq(c
->parameter
, "root");
351 return in_group(c
->parameter
) > 0;
354 static int condition_test_virtualization(Condition
*c
) {
358 assert(c
->parameter
);
359 assert(c
->type
== CONDITION_VIRTUALIZATION
);
361 if (streq(c
->parameter
, "private-users"))
362 return running_in_userns();
364 v
= detect_virtualization();
368 /* First, compare with yes/no */
369 b
= parse_boolean(c
->parameter
);
373 /* Then, compare categorization */
374 if (streq(c
->parameter
, "vm"))
375 return VIRTUALIZATION_IS_VM(v
);
377 if (streq(c
->parameter
, "container"))
378 return VIRTUALIZATION_IS_CONTAINER(v
);
380 /* Finally compare id */
381 return v
!= VIRTUALIZATION_NONE
&& streq(c
->parameter
, virtualization_to_string(v
));
384 static int condition_test_architecture(Condition
*c
) {
388 assert(c
->parameter
);
389 assert(c
->type
== CONDITION_ARCHITECTURE
);
391 a
= uname_architecture();
395 if (streq(c
->parameter
, "native"))
396 b
= native_architecture();
398 b
= architecture_from_string(c
->parameter
);
399 if (b
< 0) /* unknown architecture? Then it's definitely not ours */
406 static int condition_test_host(Condition
*c
) {
407 _cleanup_free_
char *h
= NULL
;
412 assert(c
->parameter
);
413 assert(c
->type
== CONDITION_HOST
);
415 if (sd_id128_from_string(c
->parameter
, &x
) >= 0) {
417 r
= sd_id128_get_machine(&y
);
421 return sd_id128_equal(x
, y
);
424 h
= gethostname_malloc();
428 return fnmatch(c
->parameter
, h
, FNM_CASEFOLD
) == 0;
431 static int condition_test_ac_power(Condition
*c
) {
435 assert(c
->parameter
);
436 assert(c
->type
== CONDITION_AC_POWER
);
438 r
= parse_boolean(c
->parameter
);
442 return (on_ac_power() != 0) == !!r
;
445 static int condition_test_security(Condition
*c
) {
447 assert(c
->parameter
);
448 assert(c
->type
== CONDITION_SECURITY
);
450 if (streq(c
->parameter
, "selinux"))
451 return mac_selinux_use();
452 if (streq(c
->parameter
, "smack"))
453 return mac_smack_use();
454 if (streq(c
->parameter
, "apparmor"))
455 return mac_apparmor_use();
456 if (streq(c
->parameter
, "audit"))
458 if (streq(c
->parameter
, "ima"))
460 if (streq(c
->parameter
, "tomoyo"))
461 return mac_tomoyo_use();
462 if (streq(c
->parameter
, "uefi-secureboot"))
463 return is_efi_secure_boot();
468 static int condition_test_capability(Condition
*c
) {
469 unsigned long long capabilities
= (unsigned long long) -1;
470 _cleanup_fclose_
FILE *f
= NULL
;
474 assert(c
->parameter
);
475 assert(c
->type
== CONDITION_CAPABILITY
);
477 /* If it's an invalid capability, we don't have it */
478 value
= capability_from_name(c
->parameter
);
482 /* If it's a valid capability we default to assume
485 f
= fopen("/proc/self/status", "re");
490 _cleanup_free_
char *line
= NULL
;
493 r
= read_line(f
, LONG_LINE_MAX
, &line
);
499 p
= startswith(line
, "CapBnd:");
501 if (sscanf(line
+7, "%llx", &capabilities
) != 1)
508 return !!(capabilities
& (1ULL << value
));
511 static int condition_test_needs_update(Condition
*c
) {
513 struct stat usr
, other
;
516 assert(c
->parameter
);
517 assert(c
->type
== CONDITION_NEEDS_UPDATE
);
519 /* If the file system is read-only we shouldn't suggest an update */
520 if (path_is_read_only_fs(c
->parameter
) > 0)
523 /* Any other failure means we should allow the condition to be true,
524 * so that we rather invoke too many update tools than too
527 if (!path_is_absolute(c
->parameter
))
530 p
= strjoina(c
->parameter
, "/.updated");
531 if (lstat(p
, &other
) < 0)
534 if (lstat("/usr/", &usr
) < 0)
538 * First, compare seconds as they are always accurate...
540 if (usr
.st_mtim
.tv_sec
!= other
.st_mtim
.tv_sec
)
541 return usr
.st_mtim
.tv_sec
> other
.st_mtim
.tv_sec
;
544 * ...then compare nanoseconds.
546 * A false positive is only possible when /usr's nanoseconds > 0
547 * (otherwise /usr cannot be strictly newer than the target file)
548 * AND the target file's nanoseconds == 0
549 * (otherwise the filesystem supports nsec timestamps, see stat(2)).
551 if (usr
.st_mtim
.tv_nsec
> 0 && other
.st_mtim
.tv_nsec
== 0) {
552 _cleanup_free_
char *timestamp_str
= NULL
;
556 r
= parse_env_file(NULL
, p
, "TIMESTAMP_NSEC", ×tamp_str
);
558 log_error_errno(r
, "Failed to parse timestamp file '%s', using mtime: %m", p
);
561 log_debug("No data in timestamp file '%s', using mtime", p
);
565 r
= safe_atou64(timestamp_str
, ×tamp
);
567 log_error_errno(r
, "Failed to parse timestamp value '%s' in file '%s', using mtime: %m", timestamp_str
, p
);
571 timespec_store(&other
.st_mtim
, timestamp
);
574 return usr
.st_mtim
.tv_nsec
> other
.st_mtim
.tv_nsec
;
577 static int condition_test_first_boot(Condition
*c
) {
581 assert(c
->parameter
);
582 assert(c
->type
== CONDITION_FIRST_BOOT
);
584 r
= parse_boolean(c
->parameter
);
588 return (access("/run/systemd/first-boot", F_OK
) >= 0) == !!r
;
591 static int condition_test_path_exists(Condition
*c
) {
593 assert(c
->parameter
);
594 assert(c
->type
== CONDITION_PATH_EXISTS
);
596 return access(c
->parameter
, F_OK
) >= 0;
599 static int condition_test_path_exists_glob(Condition
*c
) {
601 assert(c
->parameter
);
602 assert(c
->type
== CONDITION_PATH_EXISTS_GLOB
);
604 return glob_exists(c
->parameter
) > 0;
607 static int condition_test_path_is_directory(Condition
*c
) {
609 assert(c
->parameter
);
610 assert(c
->type
== CONDITION_PATH_IS_DIRECTORY
);
612 return is_dir(c
->parameter
, true) > 0;
615 static int condition_test_path_is_symbolic_link(Condition
*c
) {
617 assert(c
->parameter
);
618 assert(c
->type
== CONDITION_PATH_IS_SYMBOLIC_LINK
);
620 return is_symlink(c
->parameter
) > 0;
623 static int condition_test_path_is_mount_point(Condition
*c
) {
625 assert(c
->parameter
);
626 assert(c
->type
== CONDITION_PATH_IS_MOUNT_POINT
);
628 return path_is_mount_point(c
->parameter
, NULL
, AT_SYMLINK_FOLLOW
) > 0;
631 static int condition_test_path_is_read_write(Condition
*c
) {
633 assert(c
->parameter
);
634 assert(c
->type
== CONDITION_PATH_IS_READ_WRITE
);
636 return path_is_read_only_fs(c
->parameter
) <= 0;
639 static int condition_test_directory_not_empty(Condition
*c
) {
643 assert(c
->parameter
);
644 assert(c
->type
== CONDITION_DIRECTORY_NOT_EMPTY
);
646 r
= dir_is_empty(c
->parameter
);
647 return r
<= 0 && r
!= -ENOENT
;
650 static int condition_test_file_not_empty(Condition
*c
) {
654 assert(c
->parameter
);
655 assert(c
->type
== CONDITION_FILE_NOT_EMPTY
);
657 return (stat(c
->parameter
, &st
) >= 0 &&
658 S_ISREG(st
.st_mode
) &&
662 static int condition_test_file_is_executable(Condition
*c
) {
666 assert(c
->parameter
);
667 assert(c
->type
== CONDITION_FILE_IS_EXECUTABLE
);
669 return (stat(c
->parameter
, &st
) >= 0 &&
670 S_ISREG(st
.st_mode
) &&
671 (st
.st_mode
& 0111));
674 static int condition_test_null(Condition
*c
) {
676 assert(c
->type
== CONDITION_NULL
);
678 /* Note that during parsing we already evaluate the string and
679 * store it in c->negate */
683 int condition_test(Condition
*c
) {
685 static int (*const condition_tests
[_CONDITION_TYPE_MAX
])(Condition
*c
) = {
686 [CONDITION_PATH_EXISTS
] = condition_test_path_exists
,
687 [CONDITION_PATH_EXISTS_GLOB
] = condition_test_path_exists_glob
,
688 [CONDITION_PATH_IS_DIRECTORY
] = condition_test_path_is_directory
,
689 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = condition_test_path_is_symbolic_link
,
690 [CONDITION_PATH_IS_MOUNT_POINT
] = condition_test_path_is_mount_point
,
691 [CONDITION_PATH_IS_READ_WRITE
] = condition_test_path_is_read_write
,
692 [CONDITION_DIRECTORY_NOT_EMPTY
] = condition_test_directory_not_empty
,
693 [CONDITION_FILE_NOT_EMPTY
] = condition_test_file_not_empty
,
694 [CONDITION_FILE_IS_EXECUTABLE
] = condition_test_file_is_executable
,
695 [CONDITION_KERNEL_COMMAND_LINE
] = condition_test_kernel_command_line
,
696 [CONDITION_KERNEL_VERSION
] = condition_test_kernel_version
,
697 [CONDITION_VIRTUALIZATION
] = condition_test_virtualization
,
698 [CONDITION_SECURITY
] = condition_test_security
,
699 [CONDITION_CAPABILITY
] = condition_test_capability
,
700 [CONDITION_HOST
] = condition_test_host
,
701 [CONDITION_AC_POWER
] = condition_test_ac_power
,
702 [CONDITION_ARCHITECTURE
] = condition_test_architecture
,
703 [CONDITION_NEEDS_UPDATE
] = condition_test_needs_update
,
704 [CONDITION_FIRST_BOOT
] = condition_test_first_boot
,
705 [CONDITION_USER
] = condition_test_user
,
706 [CONDITION_GROUP
] = condition_test_group
,
707 [CONDITION_CONTROL_GROUP_CONTROLLER
] = condition_test_control_group_controller
,
708 [CONDITION_NULL
] = condition_test_null
,
709 [CONDITION_CPUS
] = condition_test_cpus
,
710 [CONDITION_MEMORY
] = condition_test_memory
,
716 assert(c
->type
>= 0);
717 assert(c
->type
< _CONDITION_TYPE_MAX
);
719 r
= condition_tests
[c
->type
](c
);
721 c
->result
= CONDITION_ERROR
;
725 b
= (r
> 0) == !c
->negate
;
726 c
->result
= b
? CONDITION_SUCCEEDED
: CONDITION_FAILED
;
730 bool condition_test_list(Condition
*first
, const char *(*to_string
)(ConditionType t
), condition_test_logger_t logger
, void *userdata
) {
734 assert(!!logger
== !!to_string
);
736 /* If the condition list is empty, then it is true */
740 /* Otherwise, if all of the non-trigger conditions apply and
741 * if any of the trigger conditions apply (unless there are
742 * none) we return true */
743 LIST_FOREACH(conditions
, c
, first
) {
746 r
= condition_test(c
);
750 logger(userdata
, LOG_WARNING
, r
, __FILE__
, __LINE__
, __func__
,
751 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
753 c
->trigger
? "|" : "",
754 c
->negate
? "!" : "",
757 logger(userdata
, LOG_DEBUG
, 0, __FILE__
, __LINE__
, __func__
,
760 c
->trigger
? "|" : "",
761 c
->negate
? "!" : "",
763 condition_result_to_string(c
->result
));
766 if (!c
->trigger
&& r
<= 0)
769 if (c
->trigger
&& triggered
<= 0)
773 return triggered
!= 0;
776 void condition_dump(Condition
*c
, FILE *f
, const char *prefix
, const char *(*to_string
)(ConditionType t
)) {
780 prefix
= strempty(prefix
);
783 "%s\t%s: %s%s%s %s\n",
786 c
->trigger
? "|" : "",
787 c
->negate
? "!" : "",
789 condition_result_to_string(c
->result
));
792 void condition_dump_list(Condition
*first
, FILE *f
, const char *prefix
, const char *(*to_string
)(ConditionType t
)) {
795 LIST_FOREACH(conditions
, c
, first
)
796 condition_dump(c
, f
, prefix
, to_string
);
799 static const char* const condition_type_table
[_CONDITION_TYPE_MAX
] = {
800 [CONDITION_ARCHITECTURE
] = "ConditionArchitecture",
801 [CONDITION_VIRTUALIZATION
] = "ConditionVirtualization",
802 [CONDITION_HOST
] = "ConditionHost",
803 [CONDITION_KERNEL_COMMAND_LINE
] = "ConditionKernelCommandLine",
804 [CONDITION_KERNEL_VERSION
] = "ConditionKernelVersion",
805 [CONDITION_SECURITY
] = "ConditionSecurity",
806 [CONDITION_CAPABILITY
] = "ConditionCapability",
807 [CONDITION_AC_POWER
] = "ConditionACPower",
808 [CONDITION_NEEDS_UPDATE
] = "ConditionNeedsUpdate",
809 [CONDITION_FIRST_BOOT
] = "ConditionFirstBoot",
810 [CONDITION_PATH_EXISTS
] = "ConditionPathExists",
811 [CONDITION_PATH_EXISTS_GLOB
] = "ConditionPathExistsGlob",
812 [CONDITION_PATH_IS_DIRECTORY
] = "ConditionPathIsDirectory",
813 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = "ConditionPathIsSymbolicLink",
814 [CONDITION_PATH_IS_MOUNT_POINT
] = "ConditionPathIsMountPoint",
815 [CONDITION_PATH_IS_READ_WRITE
] = "ConditionPathIsReadWrite",
816 [CONDITION_DIRECTORY_NOT_EMPTY
] = "ConditionDirectoryNotEmpty",
817 [CONDITION_FILE_NOT_EMPTY
] = "ConditionFileNotEmpty",
818 [CONDITION_FILE_IS_EXECUTABLE
] = "ConditionFileIsExecutable",
819 [CONDITION_USER
] = "ConditionUser",
820 [CONDITION_GROUP
] = "ConditionGroup",
821 [CONDITION_CONTROL_GROUP_CONTROLLER
] = "ConditionControlGroupController",
822 [CONDITION_NULL
] = "ConditionNull",
823 [CONDITION_CPUS
] = "ConditionCPUs",
824 [CONDITION_MEMORY
] = "ConditionMemory",
827 DEFINE_STRING_TABLE_LOOKUP(condition_type
, ConditionType
);
829 static const char* const assert_type_table
[_CONDITION_TYPE_MAX
] = {
830 [CONDITION_ARCHITECTURE
] = "AssertArchitecture",
831 [CONDITION_VIRTUALIZATION
] = "AssertVirtualization",
832 [CONDITION_HOST
] = "AssertHost",
833 [CONDITION_KERNEL_COMMAND_LINE
] = "AssertKernelCommandLine",
834 [CONDITION_KERNEL_VERSION
] = "AssertKernelVersion",
835 [CONDITION_SECURITY
] = "AssertSecurity",
836 [CONDITION_CAPABILITY
] = "AssertCapability",
837 [CONDITION_AC_POWER
] = "AssertACPower",
838 [CONDITION_NEEDS_UPDATE
] = "AssertNeedsUpdate",
839 [CONDITION_FIRST_BOOT
] = "AssertFirstBoot",
840 [CONDITION_PATH_EXISTS
] = "AssertPathExists",
841 [CONDITION_PATH_EXISTS_GLOB
] = "AssertPathExistsGlob",
842 [CONDITION_PATH_IS_DIRECTORY
] = "AssertPathIsDirectory",
843 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = "AssertPathIsSymbolicLink",
844 [CONDITION_PATH_IS_MOUNT_POINT
] = "AssertPathIsMountPoint",
845 [CONDITION_PATH_IS_READ_WRITE
] = "AssertPathIsReadWrite",
846 [CONDITION_DIRECTORY_NOT_EMPTY
] = "AssertDirectoryNotEmpty",
847 [CONDITION_FILE_NOT_EMPTY
] = "AssertFileNotEmpty",
848 [CONDITION_FILE_IS_EXECUTABLE
] = "AssertFileIsExecutable",
849 [CONDITION_USER
] = "AssertUser",
850 [CONDITION_GROUP
] = "AssertGroup",
851 [CONDITION_CONTROL_GROUP_CONTROLLER
] = "AssertControlGroupController",
852 [CONDITION_NULL
] = "AssertNull",
853 [CONDITION_CPUS
] = "AssertCPUs",
854 [CONDITION_MEMORY
] = "AssertMemory",
857 DEFINE_STRING_TABLE_LOOKUP(assert_type
, ConditionType
);
859 static const char* const condition_result_table
[_CONDITION_RESULT_MAX
] = {
860 [CONDITION_UNTESTED
] = "untested",
861 [CONDITION_SUCCEEDED
] = "succeeded",
862 [CONDITION_FAILED
] = "failed",
863 [CONDITION_ERROR
] = "error",
866 DEFINE_STRING_TABLE_LOOKUP(condition_result
, ConditionResult
);