]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/virt.c
man/systemd.mount: tmpfs automatically gains After=swap.target dep
[thirdparty/systemd.git] / src / basic / virt.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #if defined(__i386__) || defined(__x86_64__)
4 #include <cpuid.h>
5 #endif
6 #include <errno.h>
7 #include <stdint.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10
11 #include "alloc-util.h"
12 #include "cgroup-util.h"
13 #include "dirent-util.h"
14 #include "env-util.h"
15 #include "errno-util.h"
16 #include "fd-util.h"
17 #include "fileio.h"
18 #include "macro.h"
19 #include "missing_threads.h"
20 #include "process-util.h"
21 #include "stat-util.h"
22 #include "string-table.h"
23 #include "string-util.h"
24 #include "virt.h"
25
26 enum {
27 SMBIOS_VM_BIT_SET,
28 SMBIOS_VM_BIT_UNSET,
29 SMBIOS_VM_BIT_UNKNOWN,
30 };
31
32 static Virtualization detect_vm_cpuid(void) {
33
34 /* CPUID is an x86 specific interface. */
35 #if defined(__i386__) || defined(__x86_64__)
36
37 static const struct {
38 const char sig[13];
39 Virtualization id;
40 } vm_table[] = {
41 { "XenVMMXenVMM", VIRTUALIZATION_XEN },
42 { "KVMKVMKVM", VIRTUALIZATION_KVM }, /* qemu with KVM */
43 { "Linux KVM Hv", VIRTUALIZATION_KVM }, /* qemu with KVM + HyperV Enlightenments */
44 { "TCGTCGTCGTCG", VIRTUALIZATION_QEMU }, /* qemu without KVM */
45 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
46 { "VMwareVMware", VIRTUALIZATION_VMWARE },
47 /* https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/reference/tlfs */
48 { "Microsoft Hv", VIRTUALIZATION_MICROSOFT },
49 /* https://wiki.freebsd.org/bhyve */
50 { "bhyve bhyve ", VIRTUALIZATION_BHYVE },
51 { "QNXQVMBSQG", VIRTUALIZATION_QNX },
52 /* https://projectacrn.org */
53 { "ACRNACRNACRN", VIRTUALIZATION_ACRN },
54 /* https://www.lockheedmartin.com/en-us/products/Hardened-Security-for-Intel-Processors.html */
55 { "SRESRESRESRE", VIRTUALIZATION_SRE },
56 };
57
58 uint32_t eax, ebx, ecx, edx;
59 bool hypervisor;
60
61 /* http://lwn.net/Articles/301888/ */
62
63 /* First detect whether there is a hypervisor */
64 if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0)
65 return VIRTUALIZATION_NONE;
66
67 hypervisor = ecx & 0x80000000U;
68
69 if (hypervisor) {
70 union {
71 uint32_t sig32[3];
72 char text[13];
73 } sig = {};
74
75 /* There is a hypervisor, see what it is */
76 __cpuid(0x40000000U, eax, ebx, ecx, edx);
77
78 sig.sig32[0] = ebx;
79 sig.sig32[1] = ecx;
80 sig.sig32[2] = edx;
81
82 log_debug("Virtualization found, CPUID=%s", sig.text);
83
84 for (size_t i = 0; i < ELEMENTSOF(vm_table); i++)
85 if (memcmp_nn(sig.text, sizeof(sig.text),
86 vm_table[i].sig, sizeof(vm_table[i].sig)) == 0)
87 return vm_table[i].id;
88
89 log_debug("Unknown virtualization with CPUID=%s. Add to vm_table[]?", sig.text);
90 return VIRTUALIZATION_VM_OTHER;
91 }
92 #endif
93 log_debug("No virtualization found in CPUID");
94
95 return VIRTUALIZATION_NONE;
96 }
97
98 static Virtualization detect_vm_device_tree(void) {
99 #if defined(__arm__) || defined(__aarch64__) || defined(__powerpc__) || defined(__powerpc64__)
100 _cleanup_free_ char *hvtype = NULL;
101 int r;
102
103 r = read_one_line_file("/proc/device-tree/hypervisor/compatible", &hvtype);
104 if (r == -ENOENT) {
105 _cleanup_closedir_ DIR *dir = NULL;
106 _cleanup_free_ char *compat = NULL;
107
108 if (access("/proc/device-tree/ibm,partition-name", F_OK) == 0 &&
109 access("/proc/device-tree/hmc-managed?", F_OK) == 0 &&
110 access("/proc/device-tree/chosen/qemu,graphic-width", F_OK) != 0)
111 return VIRTUALIZATION_POWERVM;
112
113 dir = opendir("/proc/device-tree");
114 if (!dir) {
115 if (errno == ENOENT) {
116 log_debug_errno(errno, "/proc/device-tree: %m");
117 return VIRTUALIZATION_NONE;
118 }
119 return -errno;
120 }
121
122 FOREACH_DIRENT(de, dir, return -errno)
123 if (strstr(de->d_name, "fw-cfg")) {
124 log_debug("Virtualization QEMU: \"fw-cfg\" present in /proc/device-tree/%s", de->d_name);
125 return VIRTUALIZATION_QEMU;
126 }
127
128 r = read_one_line_file("/proc/device-tree/compatible", &compat);
129 if (r < 0 && r != -ENOENT)
130 return r;
131 if (r >= 0 && streq(compat, "qemu,pseries")) {
132 log_debug("Virtualization %s found in /proc/device-tree/compatible", compat);
133 return VIRTUALIZATION_QEMU;
134 }
135
136 log_debug("No virtualization found in /proc/device-tree/*");
137 return VIRTUALIZATION_NONE;
138 } else if (r < 0)
139 return r;
140
141 log_debug("Virtualization %s found in /proc/device-tree/hypervisor/compatible", hvtype);
142 if (streq(hvtype, "linux,kvm"))
143 return VIRTUALIZATION_KVM;
144 else if (strstr(hvtype, "xen"))
145 return VIRTUALIZATION_XEN;
146 else if (strstr(hvtype, "vmware"))
147 return VIRTUALIZATION_VMWARE;
148 else
149 return VIRTUALIZATION_VM_OTHER;
150 #else
151 log_debug("This platform does not support /proc/device-tree");
152 return VIRTUALIZATION_NONE;
153 #endif
154 }
155
156 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__) || defined(__loongarch_lp64)
157 static Virtualization detect_vm_dmi_vendor(void) {
158 static const char* const dmi_vendors[] = {
159 "/sys/class/dmi/id/product_name", /* Test this before sys_vendor to detect KVM over QEMU */
160 "/sys/class/dmi/id/sys_vendor",
161 "/sys/class/dmi/id/board_vendor",
162 "/sys/class/dmi/id/bios_vendor",
163 "/sys/class/dmi/id/product_version", /* For Hyper-V VMs test */
164 NULL
165 };
166
167 static const struct {
168 const char *vendor;
169 Virtualization id;
170 } dmi_vendor_table[] = {
171 { "KVM", VIRTUALIZATION_KVM },
172 { "OpenStack", VIRTUALIZATION_KVM }, /* Detect OpenStack instance as KVM in non x86 architecture */
173 { "KubeVirt", VIRTUALIZATION_KVM }, /* Detect KubeVirt instance as KVM in non x86 architecture */
174 { "Amazon EC2", VIRTUALIZATION_AMAZON },
175 { "QEMU", VIRTUALIZATION_QEMU },
176 { "VMware", VIRTUALIZATION_VMWARE }, /* https://kb.vmware.com/s/article/1009458 */
177 { "VMW", VIRTUALIZATION_VMWARE },
178 { "innotek GmbH", VIRTUALIZATION_ORACLE },
179 { "VirtualBox", VIRTUALIZATION_ORACLE },
180 { "Xen", VIRTUALIZATION_XEN },
181 { "Bochs", VIRTUALIZATION_BOCHS },
182 { "Parallels", VIRTUALIZATION_PARALLELS },
183 /* https://wiki.freebsd.org/bhyve */
184 { "BHYVE", VIRTUALIZATION_BHYVE },
185 { "Hyper-V", VIRTUALIZATION_MICROSOFT },
186 { "Apple Virtualization", VIRTUALIZATION_APPLE },
187 };
188 int r;
189
190 STRV_FOREACH(vendor, dmi_vendors) {
191 _cleanup_free_ char *s = NULL;
192
193 r = read_one_line_file(*vendor, &s);
194 if (r < 0) {
195 if (r == -ENOENT)
196 continue;
197
198 return r;
199 }
200
201 for (size_t i = 0; i < ELEMENTSOF(dmi_vendor_table); i++)
202 if (startswith(s, dmi_vendor_table[i].vendor)) {
203 log_debug("Virtualization %s found in DMI (%s)", s, *vendor);
204 return dmi_vendor_table[i].id;
205 }
206 }
207 log_debug("No virtualization found in DMI vendor table.");
208 return VIRTUALIZATION_NONE;
209 }
210
211 static int detect_vm_smbios(void) {
212 /* The SMBIOS BIOS Characteristics Extension Byte 2 (Section 2.1.2.2 of
213 * https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0.pdf), specifies that
214 * the 4th bit being set indicates a VM. The BIOS Characteristics table is exposed via the kernel in
215 * /sys/firmware/dmi/entries/0-0. Note that in the general case, this bit being unset should not
216 * imply that the system is running on bare-metal. For example, QEMU 3.1.0 (with or without KVM)
217 * with SeaBIOS does not set this bit. */
218 _cleanup_free_ char *s = NULL;
219 size_t readsize;
220 int r;
221
222 r = read_full_virtual_file("/sys/firmware/dmi/entries/0-0/raw", &s, &readsize);
223 if (r < 0) {
224 log_debug_errno(r, "Unable to read /sys/firmware/dmi/entries/0-0/raw, "
225 "using the virtualization information found in DMI vendor table, ignoring: %m");
226 return SMBIOS_VM_BIT_UNKNOWN;
227 }
228 if (readsize < 20 || s[1] < 20) {
229 /* The spec indicates that byte 1 contains the size of the table, 0x12 + the number of
230 * extension bytes. The data we're interested in is in extension byte 2, which would be at
231 * 0x13. If we didn't read that much data, or if the BIOS indicates that we don't have that
232 * much data, we don't infer anything from the SMBIOS. */
233 log_debug("Only read %zu bytes from /sys/firmware/dmi/entries/0-0/raw (expected 20). "
234 "Using the virtualization information found in DMI vendor table.", readsize);
235 return SMBIOS_VM_BIT_UNKNOWN;
236 }
237
238 uint8_t byte = (uint8_t) s[19];
239 if (byte & (1U<<4)) {
240 log_debug("DMI BIOS Extension table indicates virtualization.");
241 return SMBIOS_VM_BIT_SET;
242 }
243 log_debug("DMI BIOS Extension table does not indicate virtualization.");
244 return SMBIOS_VM_BIT_UNSET;
245 }
246 #endif /* defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__) || defined(__loongarch_lp64) */
247
248 static Virtualization detect_vm_dmi(void) {
249 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__) || defined(__loongarch_lp64)
250
251 int r;
252 r = detect_vm_dmi_vendor();
253
254 /* The DMI vendor tables in /sys/class/dmi/id don't help us distinguish between Amazon EC2
255 * virtual machines and bare-metal instances, so we need to look at SMBIOS. */
256 if (r == VIRTUALIZATION_AMAZON) {
257 switch (detect_vm_smbios()) {
258 case SMBIOS_VM_BIT_SET:
259 return VIRTUALIZATION_AMAZON;
260 case SMBIOS_VM_BIT_UNSET:
261 return VIRTUALIZATION_NONE;
262 case SMBIOS_VM_BIT_UNKNOWN: {
263 /* The DMI information we are after is only accessible to the root user,
264 * so we fallback to using the product name which is less restricted
265 * to distinguish metal systems from virtualized instances */
266 _cleanup_free_ char *s = NULL;
267 const char *e;
268
269 r = read_full_virtual_file("/sys/class/dmi/id/product_name", &s, NULL);
270 /* In EC2, virtualized is much more common than metal, so if for some reason
271 * we fail to read the DMI data, assume we are virtualized. */
272 if (r < 0) {
273 log_debug_errno(r, "Can't read /sys/class/dmi/id/product_name,"
274 " assuming virtualized: %m");
275 return VIRTUALIZATION_AMAZON;
276 }
277 e = strstrafter(truncate_nl(s), ".metal");
278 if (e && IN_SET(*e, 0, '-')) {
279 log_debug("DMI product name has '.metal', assuming no virtualization");
280 return VIRTUALIZATION_NONE;
281 } else
282 return VIRTUALIZATION_AMAZON;
283 }
284 default:
285 assert_not_reached();
286 }
287 }
288
289 /* If we haven't identified a VM, but the firmware indicates that there is one, indicate as much. We
290 * have no further information about what it is. */
291 if (r == VIRTUALIZATION_NONE && detect_vm_smbios() == SMBIOS_VM_BIT_SET)
292 return VIRTUALIZATION_VM_OTHER;
293 return r;
294 #else
295 return VIRTUALIZATION_NONE;
296 #endif
297 }
298
299 #define XENFEAT_dom0 11 /* xen/include/public/features.h */
300 #define PATH_FEATURES "/sys/hypervisor/properties/features"
301 /* Returns -errno, or 0 for domU, or 1 for dom0 */
302 static int detect_vm_xen_dom0(void) {
303 _cleanup_free_ char *domcap = NULL;
304 int r;
305
306 r = read_one_line_file(PATH_FEATURES, &domcap);
307 if (r < 0 && r != -ENOENT)
308 return r;
309 if (r >= 0) {
310 unsigned long features;
311
312 /* Here, we need to use sscanf() instead of safe_atoul()
313 * as the string lacks the leading "0x". */
314 r = sscanf(domcap, "%lx", &features);
315 if (r == 1) {
316 r = !!(features & (1U << XENFEAT_dom0));
317 log_debug("Virtualization XEN, found %s with value %08lx, "
318 "XENFEAT_dom0 (indicating the 'hardware domain') is%s set.",
319 PATH_FEATURES, features, r ? "" : " not");
320 return r;
321 }
322 log_debug("Virtualization XEN, found %s, unhandled content '%s'",
323 PATH_FEATURES, domcap);
324 }
325
326 r = read_one_line_file("/proc/xen/capabilities", &domcap);
327 if (r == -ENOENT) {
328 log_debug("Virtualization XEN because /proc/xen/capabilities does not exist");
329 return 0;
330 }
331 if (r < 0)
332 return r;
333
334 for (const char *i = domcap;;) {
335 _cleanup_free_ char *cap = NULL;
336
337 r = extract_first_word(&i, &cap, ",", 0);
338 if (r < 0)
339 return r;
340 if (r == 0) {
341 log_debug("Virtualization XEN DomU found (/proc/xen/capabilities)");
342 return 0;
343 }
344
345 if (streq(cap, "control_d")) {
346 log_debug("Virtualization XEN Dom0 ignored (/proc/xen/capabilities)");
347 return 1;
348 }
349 }
350 }
351
352 static Virtualization detect_vm_xen(void) {
353 /* The presence of /proc/xen indicates some form of a Xen domain
354 The check for Dom0 is handled outside this function */
355 if (access("/proc/xen", F_OK) < 0) {
356 log_debug("Virtualization XEN not found, /proc/xen does not exist");
357 return VIRTUALIZATION_NONE;
358 }
359 log_debug("Virtualization XEN found (/proc/xen exists)");
360 return VIRTUALIZATION_XEN;
361 }
362
363 static Virtualization detect_vm_hypervisor(void) {
364 _cleanup_free_ char *hvtype = NULL;
365 int r;
366
367 r = read_one_line_file("/sys/hypervisor/type", &hvtype);
368 if (r == -ENOENT)
369 return VIRTUALIZATION_NONE;
370 if (r < 0)
371 return r;
372
373 log_debug("Virtualization %s found in /sys/hypervisor/type", hvtype);
374
375 if (streq(hvtype, "xen"))
376 return VIRTUALIZATION_XEN;
377 else
378 return VIRTUALIZATION_VM_OTHER;
379 }
380
381 static Virtualization detect_vm_uml(void) {
382 _cleanup_fclose_ FILE *f = NULL;
383 int r;
384
385 /* Detect User-Mode Linux by reading /proc/cpuinfo */
386 f = fopen("/proc/cpuinfo", "re");
387 if (!f) {
388 if (errno == ENOENT) {
389 log_debug("/proc/cpuinfo not found, assuming no UML virtualization.");
390 return VIRTUALIZATION_NONE;
391 }
392 return -errno;
393 }
394
395 for (;;) {
396 _cleanup_free_ char *line = NULL;
397 const char *t;
398
399 r = read_line(f, LONG_LINE_MAX, &line);
400 if (r < 0)
401 return r;
402 if (r == 0)
403 break;
404
405 t = startswith(line, "vendor_id\t: ");
406 if (t) {
407 if (startswith(t, "User Mode Linux")) {
408 log_debug("UML virtualization found in /proc/cpuinfo");
409 return VIRTUALIZATION_UML;
410 }
411
412 break;
413 }
414 }
415
416 log_debug("UML virtualization not found in /proc/cpuinfo.");
417 return VIRTUALIZATION_NONE;
418 }
419
420 static Virtualization detect_vm_zvm(void) {
421
422 #if defined(__s390__)
423 _cleanup_free_ char *t = NULL;
424 int r;
425
426 r = get_proc_field("/proc/sysinfo", "VM00 Control Program", WHITESPACE, &t);
427 if (r == -ENOENT)
428 return VIRTUALIZATION_NONE;
429 if (r < 0)
430 return r;
431
432 log_debug("Virtualization %s found in /proc/sysinfo", t);
433 if (streq(t, "z/VM"))
434 return VIRTUALIZATION_ZVM;
435 else
436 return VIRTUALIZATION_KVM;
437 #else
438 log_debug("This platform does not support /proc/sysinfo");
439 return VIRTUALIZATION_NONE;
440 #endif
441 }
442
443 /* Returns a short identifier for the various VM implementations */
444 Virtualization detect_vm(void) {
445 static thread_local Virtualization cached_found = _VIRTUALIZATION_INVALID;
446 bool other = false;
447 int xen_dom0 = 0;
448 Virtualization v, dmi;
449
450 if (cached_found >= 0)
451 return cached_found;
452
453 /* We have to use the correct order here:
454 *
455 * → First, try to detect Oracle Virtualbox, Amazon EC2 Nitro, and Parallels, even if they use KVM,
456 * as well as Xen even if it cloaks as Microsoft Hyper-V. Attempt to detect uml at this stage also
457 * since it runs as a user-process nested inside other VMs. Also check for Xen now, because Xen PV
458 * mode does not override CPUID when nested inside another hypervisor.
459 *
460 * → Second, try to detect from CPUID, this will report KVM for whatever software is used even if
461 * info in DMI is overwritten.
462 *
463 * → Third, try to detect from DMI. */
464
465 dmi = detect_vm_dmi();
466 if (IN_SET(dmi,
467 VIRTUALIZATION_ORACLE,
468 VIRTUALIZATION_XEN,
469 VIRTUALIZATION_AMAZON,
470 VIRTUALIZATION_PARALLELS)) {
471 v = dmi;
472 goto finish;
473 }
474
475 /* Detect UML */
476 v = detect_vm_uml();
477 if (v < 0)
478 return v;
479 if (v != VIRTUALIZATION_NONE)
480 goto finish;
481
482 /* Detect Xen */
483 v = detect_vm_xen();
484 if (v < 0)
485 return v;
486 if (v == VIRTUALIZATION_XEN) {
487 /* If we are Dom0, then we expect to not report as a VM. However, as we might be nested
488 * inside another hypervisor which can be detected via the CPUID check, wait to report this
489 * until after the CPUID check. */
490 xen_dom0 = detect_vm_xen_dom0();
491 if (xen_dom0 < 0)
492 return xen_dom0;
493 if (xen_dom0 == 0)
494 goto finish;
495 } else if (v != VIRTUALIZATION_NONE)
496 assert_not_reached();
497
498 /* Detect from CPUID */
499 v = detect_vm_cpuid();
500 if (v < 0)
501 return v;
502 if (v == VIRTUALIZATION_VM_OTHER)
503 other = true;
504 else if (v != VIRTUALIZATION_NONE)
505 goto finish;
506
507 /* If we are in Dom0 and have not yet finished, finish with the result of detect_vm_cpuid */
508 if (xen_dom0 > 0)
509 goto finish;
510
511 /* Now, let's get back to DMI */
512 if (dmi < 0)
513 return dmi;
514 if (dmi == VIRTUALIZATION_VM_OTHER)
515 other = true;
516 else if (dmi != VIRTUALIZATION_NONE) {
517 v = dmi;
518 goto finish;
519 }
520
521 /* Check high-level hypervisor sysfs file */
522 v = detect_vm_hypervisor();
523 if (v < 0)
524 return v;
525 if (v == VIRTUALIZATION_VM_OTHER)
526 other = true;
527 else if (v != VIRTUALIZATION_NONE)
528 goto finish;
529
530 v = detect_vm_device_tree();
531 if (v < 0)
532 return v;
533 if (v == VIRTUALIZATION_VM_OTHER)
534 other = true;
535 else if (v != VIRTUALIZATION_NONE)
536 goto finish;
537
538 v = detect_vm_zvm();
539 if (v < 0)
540 return v;
541
542 finish:
543 if (v == VIRTUALIZATION_NONE && other)
544 v = VIRTUALIZATION_VM_OTHER;
545
546 cached_found = v;
547 log_debug("Found VM virtualization %s", virtualization_to_string(v));
548 return v;
549 }
550
551 static const char *const container_table[_VIRTUALIZATION_MAX] = {
552 [VIRTUALIZATION_LXC] = "lxc",
553 [VIRTUALIZATION_LXC_LIBVIRT] = "lxc-libvirt",
554 [VIRTUALIZATION_SYSTEMD_NSPAWN] = "systemd-nspawn",
555 [VIRTUALIZATION_DOCKER] = "docker",
556 [VIRTUALIZATION_PODMAN] = "podman",
557 [VIRTUALIZATION_RKT] = "rkt",
558 [VIRTUALIZATION_WSL] = "wsl",
559 [VIRTUALIZATION_PROOT] = "proot",
560 [VIRTUALIZATION_POUCH] = "pouch",
561 };
562
563 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(container, int);
564
565 static int running_in_cgroupns(void) {
566 int r;
567
568 if (!cg_ns_supported())
569 return false;
570
571 r = cg_all_unified();
572 if (r < 0)
573 return r;
574
575 if (r) {
576 /* cgroup v2 */
577
578 r = access("/sys/fs/cgroup/cgroup.events", F_OK);
579 if (r < 0) {
580 if (errno != ENOENT)
581 return -errno;
582 /* All kernel versions have cgroup.events in nested cgroups. */
583 return false;
584 }
585
586 /* There's no cgroup.type in the root cgroup, and future kernel versions
587 * are unlikely to add it since cgroup.type is something that makes no sense
588 * whatsoever in the root cgroup. */
589 r = access("/sys/fs/cgroup/cgroup.type", F_OK);
590 if (r == 0)
591 return true;
592 if (r < 0 && errno != ENOENT)
593 return -errno;
594
595 /* On older kernel versions, there's no cgroup.type */
596 r = access("/sys/kernel/cgroup/features", F_OK);
597 if (r < 0) {
598 if (errno != ENOENT)
599 return -errno;
600 /* This is an old kernel that we know for sure has cgroup.events
601 * only in nested cgroups. */
602 return true;
603 }
604
605 /* This is a recent kernel, and cgroup.type doesn't exist, so we must be
606 * in the root cgroup. */
607 return false;
608 } else {
609 /* cgroup v1 */
610
611 /* If systemd controller is not mounted, do not even bother. */
612 r = access("/sys/fs/cgroup/systemd", F_OK);
613 if (r < 0) {
614 if (errno != ENOENT)
615 return -errno;
616 return false;
617 }
618
619 /* release_agent only exists in the root cgroup. */
620 r = access("/sys/fs/cgroup/systemd/release_agent", F_OK);
621 if (r < 0) {
622 if (errno != ENOENT)
623 return -errno;
624 return true;
625 }
626
627 return false;
628 }
629 }
630
631 static Virtualization detect_container_files(void) {
632 static const struct {
633 const char *file_path;
634 Virtualization id;
635 } container_file_table[] = {
636 /* https://github.com/containers/podman/issues/6192 */
637 /* https://github.com/containers/podman/issues/3586#issuecomment-661918679 */
638 { "/run/.containerenv", VIRTUALIZATION_PODMAN },
639 /* https://github.com/moby/moby/issues/18355 */
640 /* Docker must be the last in this table, see below. */
641 { "/.dockerenv", VIRTUALIZATION_DOCKER },
642 };
643
644 for (size_t i = 0; i < ELEMENTSOF(container_file_table); i++) {
645 if (access(container_file_table[i].file_path, F_OK) >= 0)
646 return container_file_table[i].id;
647
648 if (errno != ENOENT)
649 log_debug_errno(errno,
650 "Checking if %s exists failed, ignoring: %m",
651 container_file_table[i].file_path);
652 }
653
654 return VIRTUALIZATION_NONE;
655 }
656
657 Virtualization detect_container(void) {
658 static thread_local Virtualization cached_found = _VIRTUALIZATION_INVALID;
659 _cleanup_free_ char *m = NULL, *o = NULL, *p = NULL;
660 const char *e = NULL;
661 Virtualization v;
662 int r;
663
664 if (cached_found >= 0)
665 return cached_found;
666
667 /* /proc/vz exists in container and outside of the container, /proc/bc only outside of the container. */
668 if (access("/proc/vz", F_OK) < 0) {
669 if (errno != ENOENT)
670 log_debug_errno(errno, "Failed to check if /proc/vz exists, ignoring: %m");
671 } else if (access("/proc/bc", F_OK) < 0) {
672 if (errno == ENOENT) {
673 v = VIRTUALIZATION_OPENVZ;
674 goto finish;
675 }
676
677 log_debug_errno(errno, "Failed to check if /proc/bc exists, ignoring: %m");
678 }
679
680 /* "Official" way of detecting WSL https://github.com/Microsoft/WSL/issues/423#issuecomment-221627364 */
681 r = read_one_line_file("/proc/sys/kernel/osrelease", &o);
682 if (r < 0)
683 log_debug_errno(r, "Failed to read /proc/sys/kernel/osrelease, ignoring: %m");
684 else if (strstr(o, "Microsoft") || strstr(o, "WSL")) {
685 v = VIRTUALIZATION_WSL;
686 goto finish;
687 }
688
689 /* proot doesn't use PID namespacing, so we can just check if we have a matching tracer for this
690 * invocation without worrying about it being elsewhere.
691 */
692 r = get_proc_field("/proc/self/status", "TracerPid", WHITESPACE, &p);
693 if (r < 0)
694 log_debug_errno(r, "Failed to read our own trace PID, ignoring: %m");
695 else if (!streq(p, "0")) {
696 pid_t ptrace_pid;
697
698 r = parse_pid(p, &ptrace_pid);
699 if (r < 0)
700 log_debug_errno(r, "Failed to parse our own tracer PID, ignoring: %m");
701 else {
702 _cleanup_free_ char *ptrace_comm = NULL;
703 const char *pf;
704
705 pf = procfs_file_alloca(ptrace_pid, "comm");
706 r = read_one_line_file(pf, &ptrace_comm);
707 if (r < 0)
708 log_debug_errno(r, "Failed to read %s, ignoring: %m", pf);
709 else if (startswith(ptrace_comm, "proot")) {
710 v = VIRTUALIZATION_PROOT;
711 goto finish;
712 }
713 }
714 }
715
716 /* The container manager might have placed this in the /run/host/ hierarchy for us, which is best
717 * because we can be consumed just like that, without special privileges. */
718 r = read_one_line_file("/run/host/container-manager", &m);
719 if (r > 0) {
720 e = m;
721 goto translate_name;
722 }
723 if (!IN_SET(r, -ENOENT, 0))
724 return log_debug_errno(r, "Failed to read /run/host/container-manager: %m");
725
726 if (getpid_cached() == 1) {
727 /* If we are PID 1 we can just check our own environment variable, and that's authoritative.
728 * We distinguish three cases:
729 * - the variable is not defined → we jump to other checks
730 * - the variable is defined to an empty value → we are not in a container
731 * - anything else → some container, either one of the known ones or "container-other"
732 */
733 e = getenv("container");
734 if (!e)
735 goto check_files;
736 if (isempty(e)) {
737 v = VIRTUALIZATION_NONE;
738 goto finish;
739 }
740
741 goto translate_name;
742 }
743
744 /* Otherwise, PID 1 might have dropped this information into a file in /run. This is better than accessing
745 * /proc/1/environ, since we don't need CAP_SYS_PTRACE for that. */
746 r = read_one_line_file("/run/systemd/container", &m);
747 if (r > 0) {
748 e = m;
749 goto translate_name;
750 }
751 if (!IN_SET(r, -ENOENT, 0))
752 return log_debug_errno(r, "Failed to read /run/systemd/container: %m");
753
754 /* Fallback for cases where PID 1 was not systemd (for example, cases where init=/bin/sh is used. */
755 r = getenv_for_pid(1, "container", &m);
756 if (r > 0) {
757 e = m;
758 goto translate_name;
759 }
760 if (r < 0) /* This only works if we have CAP_SYS_PTRACE, hence let's better ignore failures here */
761 log_debug_errno(r, "Failed to read $container of PID 1, ignoring: %m");
762
763 check_files:
764 /* Check for existence of some well-known files. We only do this after checking
765 * for other specific container managers, otherwise we risk mistaking another
766 * container manager for Docker: the /.dockerenv file could inadvertently end up
767 * in a file system image. */
768 v = detect_container_files();
769 if (v < 0)
770 return v;
771 if (v != VIRTUALIZATION_NONE)
772 goto finish;
773
774 r = running_in_cgroupns();
775 if (r > 0) {
776 v = VIRTUALIZATION_CONTAINER_OTHER;
777 goto finish;
778 }
779 if (r < 0)
780 log_debug_errno(r, "Failed to detect cgroup namespace: %m");
781
782 /* If none of that worked, give up, assume no container manager. */
783 v = VIRTUALIZATION_NONE;
784 goto finish;
785
786 translate_name:
787 if (streq(e, "oci")) {
788 /* Some images hardcode container=oci, but OCI is not a specific container manager.
789 * Try to detect one based on well-known files. */
790 v = detect_container_files();
791 if (v == VIRTUALIZATION_NONE)
792 v = VIRTUALIZATION_CONTAINER_OTHER;
793 goto finish;
794 }
795 v = container_from_string(e);
796 if (v < 0)
797 v = VIRTUALIZATION_CONTAINER_OTHER;
798
799 finish:
800 log_debug("Found container virtualization %s.", virtualization_to_string(v));
801 cached_found = v;
802 return v;
803 }
804
805 Virtualization detect_virtualization(void) {
806 int v;
807
808 v = detect_container();
809 if (v != VIRTUALIZATION_NONE)
810 return v;
811
812 return detect_vm();
813 }
814
815 static int userns_has_mapping(const char *name) {
816 _cleanup_fclose_ FILE *f = NULL;
817 uid_t a, b, c;
818 int r;
819
820 f = fopen(name, "re");
821 if (!f) {
822 log_debug_errno(errno, "Failed to open %s: %m", name);
823 return errno == ENOENT ? false : -errno;
824 }
825
826 errno = 0;
827 r = fscanf(f, UID_FMT " " UID_FMT " " UID_FMT "\n", &a, &b, &c);
828 if (r == EOF) {
829 if (ferror(f))
830 return log_debug_errno(errno_or_else(EIO), "Failed to read %s: %m", name);
831
832 log_debug("%s is empty, we're in an uninitialized user namespace", name);
833 return true;
834 }
835 if (r != 3)
836 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Failed to parse %s: %m", name);
837
838 if (a == 0 && b == 0 && c == UINT32_MAX) {
839 /* The kernel calls mappings_overlap() and does not allow overlaps */
840 log_debug("%s has a full 1:1 mapping", name);
841 return false;
842 }
843
844 /* Anything else implies that we are in a user namespace */
845 log_debug("Mapping found in %s, we're in a user namespace", name);
846 return true;
847 }
848
849 int running_in_userns(void) {
850 _cleanup_free_ char *line = NULL;
851 int r;
852
853 r = userns_has_mapping("/proc/self/uid_map");
854 if (r != 0)
855 return r;
856
857 r = userns_has_mapping("/proc/self/gid_map");
858 if (r != 0)
859 return r;
860
861 /* "setgroups" file was added in kernel v3.18-rc6-15-g9cc46516dd. It is also possible to compile a
862 * kernel without CONFIG_USER_NS, in which case "setgroups" also does not exist. We cannot
863 * distinguish those two cases, so assume that we're running on a stripped-down recent kernel, rather
864 * than on an old one, and if the file is not found, return false. */
865 r = read_virtual_file("/proc/self/setgroups", SIZE_MAX, &line, NULL);
866 if (r < 0) {
867 log_debug_errno(r, "/proc/self/setgroups: %m");
868 return r == -ENOENT ? false : r;
869 }
870
871 strstrip(line); /* remove trailing newline */
872
873 r = streq(line, "deny");
874 /* See user_namespaces(7) for a description of this "setgroups" contents. */
875 log_debug("/proc/self/setgroups contains \"%s\", %s user namespace", line, r ? "in" : "not in");
876 return r;
877 }
878
879 int running_in_chroot(void) {
880 int r;
881
882 /* If we're PID1, /proc may not be mounted (and most likely we're not in a chroot). But PID1 will
883 * mount /proc, so all other programs can assume that if /proc is *not* available, we're in some
884 * chroot. */
885
886 if (getenv_bool("SYSTEMD_IGNORE_CHROOT") > 0)
887 return 0;
888
889 r = inode_same("/proc/1/root", "/", 0);
890 if (r == -ENOENT) {
891 r = proc_mounted();
892 if (r == 0) {
893 if (getpid_cached() == 1)
894 return false; /* We will mount /proc, assuming we're not in a chroot. */
895
896 log_debug("/proc is not mounted, assuming we're in a chroot.");
897 return true;
898 }
899 if (r > 0) /* If we have fake /proc/, we can't do the check properly. */
900 return -ENOSYS;
901 }
902 if (r < 0)
903 return r;
904
905 return r == 0;
906 }
907
908 #if defined(__i386__) || defined(__x86_64__)
909 struct cpuid_table_entry {
910 uint32_t flag_bit;
911 const char *name;
912 };
913
914 static const struct cpuid_table_entry leaf1_edx[] = {
915 { 0, "fpu" },
916 { 1, "vme" },
917 { 2, "de" },
918 { 3, "pse" },
919 { 4, "tsc" },
920 { 5, "msr" },
921 { 6, "pae" },
922 { 7, "mce" },
923 { 8, "cx8" },
924 { 9, "apic" },
925 { 11, "sep" },
926 { 12, "mtrr" },
927 { 13, "pge" },
928 { 14, "mca" },
929 { 15, "cmov" },
930 { 16, "pat" },
931 { 17, "pse36" },
932 { 19, "clflush" },
933 { 23, "mmx" },
934 { 24, "fxsr" },
935 { 25, "sse" },
936 { 26, "sse2" },
937 { 28, "ht" },
938 };
939
940 static const struct cpuid_table_entry leaf1_ecx[] = {
941 { 0, "pni" },
942 { 1, "pclmul" },
943 { 3, "monitor" },
944 { 9, "ssse3" },
945 { 12, "fma3" },
946 { 13, "cx16" },
947 { 19, "sse4_1" },
948 { 20, "sse4_2" },
949 { 22, "movbe" },
950 { 23, "popcnt" },
951 { 25, "aes" },
952 { 26, "xsave" },
953 { 27, "osxsave" },
954 { 28, "avx" },
955 { 29, "f16c" },
956 { 30, "rdrand" },
957 };
958
959 static const struct cpuid_table_entry leaf7_ebx[] = {
960 { 3, "bmi1" },
961 { 5, "avx2" },
962 { 8, "bmi2" },
963 { 18, "rdseed" },
964 { 19, "adx" },
965 { 29, "sha_ni" },
966 };
967
968 static const struct cpuid_table_entry leaf81_edx[] = {
969 { 11, "syscall" },
970 { 27, "rdtscp" },
971 { 29, "lm" },
972 };
973
974 static const struct cpuid_table_entry leaf81_ecx[] = {
975 { 0, "lahf_lm" },
976 { 5, "abm" },
977 };
978
979 static const struct cpuid_table_entry leaf87_edx[] = {
980 { 8, "constant_tsc" },
981 };
982
983 static bool given_flag_in_set(const char *flag, const struct cpuid_table_entry *set, size_t set_size, uint32_t val) {
984 for (size_t i = 0; i < set_size; i++) {
985 if ((UINT32_C(1) << set[i].flag_bit) & val &&
986 streq(flag, set[i].name))
987 return true;
988 }
989 return false;
990 }
991
992 static bool real_has_cpu_with_flag(const char *flag) {
993 uint32_t eax, ebx, ecx, edx;
994
995 if (__get_cpuid(1, &eax, &ebx, &ecx, &edx)) {
996 if (given_flag_in_set(flag, leaf1_ecx, ELEMENTSOF(leaf1_ecx), ecx))
997 return true;
998
999 if (given_flag_in_set(flag, leaf1_edx, ELEMENTSOF(leaf1_edx), edx))
1000 return true;
1001 }
1002
1003 if (__get_cpuid(7, &eax, &ebx, &ecx, &edx)) {
1004 if (given_flag_in_set(flag, leaf7_ebx, ELEMENTSOF(leaf7_ebx), ebx))
1005 return true;
1006 }
1007
1008 if (__get_cpuid(0x80000001U, &eax, &ebx, &ecx, &edx)) {
1009 if (given_flag_in_set(flag, leaf81_ecx, ELEMENTSOF(leaf81_ecx), ecx))
1010 return true;
1011
1012 if (given_flag_in_set(flag, leaf81_edx, ELEMENTSOF(leaf81_edx), edx))
1013 return true;
1014 }
1015
1016 if (__get_cpuid(0x80000007U, &eax, &ebx, &ecx, &edx))
1017 if (given_flag_in_set(flag, leaf87_edx, ELEMENTSOF(leaf87_edx), edx))
1018 return true;
1019
1020 return false;
1021 }
1022 #endif
1023
1024 bool has_cpu_with_flag(const char *flag) {
1025 /* CPUID is an x86 specific interface. Assume on all others that no CPUs have those flags. */
1026 #if defined(__i386__) || defined(__x86_64__)
1027 return real_has_cpu_with_flag(flag);
1028 #else
1029 return false;
1030 #endif
1031 }
1032
1033 static const char *const virtualization_table[_VIRTUALIZATION_MAX] = {
1034 [VIRTUALIZATION_NONE] = "none",
1035 [VIRTUALIZATION_KVM] = "kvm",
1036 [VIRTUALIZATION_AMAZON] = "amazon",
1037 [VIRTUALIZATION_QEMU] = "qemu",
1038 [VIRTUALIZATION_BOCHS] = "bochs",
1039 [VIRTUALIZATION_XEN] = "xen",
1040 [VIRTUALIZATION_UML] = "uml",
1041 [VIRTUALIZATION_VMWARE] = "vmware",
1042 [VIRTUALIZATION_ORACLE] = "oracle",
1043 [VIRTUALIZATION_MICROSOFT] = "microsoft",
1044 [VIRTUALIZATION_ZVM] = "zvm",
1045 [VIRTUALIZATION_PARALLELS] = "parallels",
1046 [VIRTUALIZATION_BHYVE] = "bhyve",
1047 [VIRTUALIZATION_QNX] = "qnx",
1048 [VIRTUALIZATION_ACRN] = "acrn",
1049 [VIRTUALIZATION_POWERVM] = "powervm",
1050 [VIRTUALIZATION_APPLE] = "apple",
1051 [VIRTUALIZATION_SRE] = "sre",
1052 [VIRTUALIZATION_VM_OTHER] = "vm-other",
1053
1054 [VIRTUALIZATION_SYSTEMD_NSPAWN] = "systemd-nspawn",
1055 [VIRTUALIZATION_LXC_LIBVIRT] = "lxc-libvirt",
1056 [VIRTUALIZATION_LXC] = "lxc",
1057 [VIRTUALIZATION_OPENVZ] = "openvz",
1058 [VIRTUALIZATION_DOCKER] = "docker",
1059 [VIRTUALIZATION_PODMAN] = "podman",
1060 [VIRTUALIZATION_RKT] = "rkt",
1061 [VIRTUALIZATION_WSL] = "wsl",
1062 [VIRTUALIZATION_PROOT] = "proot",
1063 [VIRTUALIZATION_POUCH] = "pouch",
1064 [VIRTUALIZATION_CONTAINER_OTHER] = "container-other",
1065 };
1066
1067 DEFINE_STRING_TABLE_LOOKUP(virtualization, Virtualization);