]> git.ipfire.org Git - thirdparty/systemd.git/blame_incremental - src/basic/virt.c
detect-virt: also detect "microsoft" as WSL
[thirdparty/systemd.git] / src / basic / virt.c
... / ...
CommitLineData
1/* SPDX-License-Identifier: LGPL-2.1+ */
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 "dirent-util.h"
13#include "env-util.h"
14#include "fd-util.h"
15#include "fileio.h"
16#include "macro.h"
17#include "process-util.h"
18#include "stat-util.h"
19#include "string-table.h"
20#include "string-util.h"
21#include "virt.h"
22
23#if defined(__i386__) || defined(__x86_64__)
24static const char *const vm_table[_VIRTUALIZATION_MAX] = {
25 [VIRTUALIZATION_XEN] = "XenVMMXenVMM",
26 [VIRTUALIZATION_KVM] = "KVMKVMKVM",
27 [VIRTUALIZATION_QEMU] = "TCGTCGTCGTCG",
28 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
29 [VIRTUALIZATION_VMWARE] = "VMwareVMware",
30 /* https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/reference/tlfs */
31 [VIRTUALIZATION_MICROSOFT] = "Microsoft Hv",
32 /* https://wiki.freebsd.org/bhyve */
33 [VIRTUALIZATION_BHYVE] = "bhyve bhyve ",
34 [VIRTUALIZATION_QNX] = "QNXQVMBSQG",
35 /* https://projectacrn.org */
36 [VIRTUALIZATION_ACRN] = "ACRNACRNACRN",
37};
38
39DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(vm, int);
40#endif
41
42static int detect_vm_cpuid(void) {
43
44 /* CPUID is an x86 specific interface. */
45#if defined(__i386__) || defined(__x86_64__)
46
47 uint32_t eax, ebx, ecx, edx;
48 bool hypervisor;
49
50 /* http://lwn.net/Articles/301888/ */
51
52 /* First detect whether there is a hypervisor */
53 if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0)
54 return VIRTUALIZATION_NONE;
55
56 hypervisor = ecx & 0x80000000U;
57
58 if (hypervisor) {
59 union {
60 uint32_t sig32[3];
61 char text[13];
62 } sig = {};
63 int v;
64
65 /* There is a hypervisor, see what it is */
66 __cpuid(0x40000000U, eax, ebx, ecx, edx);
67
68 sig.sig32[0] = ebx;
69 sig.sig32[1] = ecx;
70 sig.sig32[2] = edx;
71
72 log_debug("Virtualization found, CPUID=%s", sig.text);
73
74 v = vm_from_string(sig.text);
75 if (v < 0)
76 return VIRTUALIZATION_VM_OTHER;
77
78 return v;
79 }
80#endif
81 log_debug("No virtualization found in CPUID");
82
83 return VIRTUALIZATION_NONE;
84}
85
86static int detect_vm_device_tree(void) {
87#if defined(__arm__) || defined(__aarch64__) || defined(__powerpc__) || defined(__powerpc64__)
88 _cleanup_free_ char *hvtype = NULL;
89 int r;
90
91 r = read_one_line_file("/proc/device-tree/hypervisor/compatible", &hvtype);
92 if (r == -ENOENT) {
93 _cleanup_closedir_ DIR *dir = NULL;
94 struct dirent *dent;
95
96 dir = opendir("/proc/device-tree");
97 if (!dir) {
98 if (errno == ENOENT) {
99 log_debug_errno(errno, "/proc/device-tree: %m");
100 return VIRTUALIZATION_NONE;
101 }
102 return -errno;
103 }
104
105 FOREACH_DIRENT(dent, dir, return -errno)
106 if (strstr(dent->d_name, "fw-cfg")) {
107 log_debug("Virtualization QEMU: \"fw-cfg\" present in /proc/device-tree/%s", dent->d_name);
108 return VIRTUALIZATION_QEMU;
109 }
110
111 log_debug("No virtualization found in /proc/device-tree/*");
112 return VIRTUALIZATION_NONE;
113 } else if (r < 0)
114 return r;
115
116 log_debug("Virtualization %s found in /proc/device-tree/hypervisor/compatible", hvtype);
117 if (streq(hvtype, "linux,kvm"))
118 return VIRTUALIZATION_KVM;
119 else if (strstr(hvtype, "xen"))
120 return VIRTUALIZATION_XEN;
121 else if (strstr(hvtype, "vmware"))
122 return VIRTUALIZATION_VMWARE;
123 else
124 return VIRTUALIZATION_VM_OTHER;
125#else
126 log_debug("This platform does not support /proc/device-tree");
127 return VIRTUALIZATION_NONE;
128#endif
129}
130
131static int detect_vm_dmi(void) {
132#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
133
134 static const char *const dmi_vendors[] = {
135 "/sys/class/dmi/id/product_name", /* Test this before sys_vendor to detect KVM over QEMU */
136 "/sys/class/dmi/id/sys_vendor",
137 "/sys/class/dmi/id/board_vendor",
138 "/sys/class/dmi/id/bios_vendor"
139 };
140
141 static const struct {
142 const char *vendor;
143 int id;
144 } dmi_vendor_table[] = {
145 { "KVM", VIRTUALIZATION_KVM },
146 { "QEMU", VIRTUALIZATION_QEMU },
147 { "VMware", VIRTUALIZATION_VMWARE }, /* https://kb.vmware.com/s/article/1009458 */
148 { "VMW", VIRTUALIZATION_VMWARE },
149 { "innotek GmbH", VIRTUALIZATION_ORACLE },
150 { "Oracle Corporation", VIRTUALIZATION_ORACLE },
151 { "Xen", VIRTUALIZATION_XEN },
152 { "Bochs", VIRTUALIZATION_BOCHS },
153 { "Parallels", VIRTUALIZATION_PARALLELS },
154 /* https://wiki.freebsd.org/bhyve */
155 { "BHYVE", VIRTUALIZATION_BHYVE },
156 };
157 unsigned i;
158 int r;
159
160 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
161 _cleanup_free_ char *s = NULL;
162 unsigned j;
163
164 r = read_one_line_file(dmi_vendors[i], &s);
165 if (r < 0) {
166 if (r == -ENOENT)
167 continue;
168
169 return r;
170 }
171
172 for (j = 0; j < ELEMENTSOF(dmi_vendor_table); j++)
173 if (startswith(s, dmi_vendor_table[j].vendor)) {
174 log_debug("Virtualization %s found in DMI (%s)", s, dmi_vendors[i]);
175 return dmi_vendor_table[j].id;
176 }
177 }
178#endif
179
180 log_debug("No virtualization found in DMI");
181
182 return VIRTUALIZATION_NONE;
183}
184
185static int detect_vm_xen(void) {
186
187 /* Check for Dom0 will be executed later in detect_vm_xen_dom0
188 The presence of /proc/xen indicates some form of a Xen domain */
189 if (access("/proc/xen", F_OK) < 0) {
190 log_debug("Virtualization XEN not found, /proc/xen does not exist");
191 return VIRTUALIZATION_NONE;
192 }
193
194 log_debug("Virtualization XEN found (/proc/xen exists)");
195 return VIRTUALIZATION_XEN;
196}
197
198#define XENFEAT_dom0 11 /* xen/include/public/features.h */
199#define PATH_FEATURES "/sys/hypervisor/properties/features"
200/* Returns -errno, or 0 for domU, or 1 for dom0 */
201static int detect_vm_xen_dom0(void) {
202 _cleanup_free_ char *domcap = NULL;
203 int r;
204
205 r = read_one_line_file(PATH_FEATURES, &domcap);
206 if (r < 0 && r != -ENOENT)
207 return r;
208 if (r >= 0) {
209 unsigned long features;
210
211 /* Here, we need to use sscanf() instead of safe_atoul()
212 * as the string lacks the leading "0x". */
213 r = sscanf(domcap, "%lx", &features);
214 if (r == 1) {
215 r = !!(features & (1U << XENFEAT_dom0));
216 log_debug("Virtualization XEN, found %s with value %08lx, "
217 "XENFEAT_dom0 (indicating the 'hardware domain') is%s set.",
218 PATH_FEATURES, features, r ? "" : " not");
219 return r;
220 }
221 log_debug("Virtualization XEN, found %s, unhandled content '%s'",
222 PATH_FEATURES, domcap);
223 }
224
225 r = read_one_line_file("/proc/xen/capabilities", &domcap);
226 if (r == -ENOENT) {
227 log_debug("Virtualization XEN because /proc/xen/capabilities does not exist");
228 return 0;
229 }
230 if (r < 0)
231 return r;
232
233 for (const char *i = domcap;;) {
234 _cleanup_free_ char *cap = NULL;
235
236 r = extract_first_word(&i, &cap, ",", 0);
237 if (r < 0)
238 return r;
239 if (r == 0) {
240 log_debug("Virtualization XEN DomU found (/proc/xen/capabilities)");
241 return 0;
242 }
243
244 if (streq(cap, "control_d")) {
245 log_debug("Virtualization XEN Dom0 ignored (/proc/xen/capabilities)");
246 return 1;
247 }
248 }
249}
250
251static int detect_vm_hypervisor(void) {
252 _cleanup_free_ char *hvtype = NULL;
253 int r;
254
255 r = read_one_line_file("/sys/hypervisor/type", &hvtype);
256 if (r == -ENOENT)
257 return VIRTUALIZATION_NONE;
258 if (r < 0)
259 return r;
260
261 log_debug("Virtualization %s found in /sys/hypervisor/type", hvtype);
262
263 if (streq(hvtype, "xen"))
264 return VIRTUALIZATION_XEN;
265 else
266 return VIRTUALIZATION_VM_OTHER;
267}
268
269static int detect_vm_uml(void) {
270 _cleanup_fclose_ FILE *f = NULL;
271 int r;
272
273 /* Detect User-Mode Linux by reading /proc/cpuinfo */
274 f = fopen("/proc/cpuinfo", "re");
275 if (!f) {
276 if (errno == ENOENT) {
277 log_debug("/proc/cpuinfo not found, assuming no UML virtualization.");
278 return VIRTUALIZATION_NONE;
279 }
280 return -errno;
281 }
282
283 for (;;) {
284 _cleanup_free_ char *line = NULL;
285 const char *t;
286
287 r = read_line(f, LONG_LINE_MAX, &line);
288 if (r < 0)
289 return r;
290 if (r == 0)
291 break;
292
293 t = startswith(line, "vendor_id\t: ");
294 if (t) {
295 if (startswith(t, "User Mode Linux")) {
296 log_debug("UML virtualization found in /proc/cpuinfo");
297 return VIRTUALIZATION_UML;
298 }
299
300 break;
301 }
302 }
303
304 log_debug("UML virtualization not found in /proc/cpuinfo.");
305 return VIRTUALIZATION_NONE;
306}
307
308static int detect_vm_zvm(void) {
309
310#if defined(__s390__)
311 _cleanup_free_ char *t = NULL;
312 int r;
313
314 r = get_proc_field("/proc/sysinfo", "VM00 Control Program", WHITESPACE, &t);
315 if (r == -ENOENT)
316 return VIRTUALIZATION_NONE;
317 if (r < 0)
318 return r;
319
320 log_debug("Virtualization %s found in /proc/sysinfo", t);
321 if (streq(t, "z/VM"))
322 return VIRTUALIZATION_ZVM;
323 else
324 return VIRTUALIZATION_KVM;
325#else
326 log_debug("This platform does not support /proc/sysinfo");
327 return VIRTUALIZATION_NONE;
328#endif
329}
330
331/* Returns a short identifier for the various VM implementations */
332int detect_vm(void) {
333 static thread_local int cached_found = _VIRTUALIZATION_INVALID;
334 bool other = false;
335 int r, dmi;
336
337 if (cached_found >= 0)
338 return cached_found;
339
340 /* We have to use the correct order here:
341 *
342 * → First, try to detect Oracle Virtualbox, even if it uses KVM, as well as Xen even if it cloaks as Microsoft
343 * Hyper-V.
344 *
345 * → Second, try to detect from CPUID, this will report KVM for whatever software is used even if info in DMI is
346 * overwritten.
347 *
348 * → Third, try to detect from DMI. */
349
350 dmi = detect_vm_dmi();
351 if (IN_SET(dmi, VIRTUALIZATION_ORACLE, VIRTUALIZATION_XEN)) {
352 r = dmi;
353 goto finish;
354 }
355
356 r = detect_vm_cpuid();
357 if (r < 0)
358 return r;
359 if (r == VIRTUALIZATION_VM_OTHER)
360 other = true;
361 else if (r != VIRTUALIZATION_NONE)
362 goto finish;
363
364 /* Now, let's get back to DMI */
365 if (dmi < 0)
366 return dmi;
367 if (dmi == VIRTUALIZATION_VM_OTHER)
368 other = true;
369 else if (dmi != VIRTUALIZATION_NONE) {
370 r = dmi;
371 goto finish;
372 }
373
374 /* x86 xen will most likely be detected by cpuid. If not (most likely
375 * because we're not an x86 guest), then we should try the /proc/xen
376 * directory next. If that's not found, then we check for the high-level
377 * hypervisor sysfs file.
378 */
379
380 r = detect_vm_xen();
381 if (r < 0)
382 return r;
383 if (r == VIRTUALIZATION_VM_OTHER)
384 other = true;
385 else if (r != VIRTUALIZATION_NONE)
386 goto finish;
387
388 r = detect_vm_hypervisor();
389 if (r < 0)
390 return r;
391 if (r == VIRTUALIZATION_VM_OTHER)
392 other = true;
393 else if (r != VIRTUALIZATION_NONE)
394 goto finish;
395
396 r = detect_vm_device_tree();
397 if (r < 0)
398 return r;
399 if (r == VIRTUALIZATION_VM_OTHER)
400 other = true;
401 else if (r != VIRTUALIZATION_NONE)
402 goto finish;
403
404 r = detect_vm_uml();
405 if (r < 0)
406 return r;
407 if (r == VIRTUALIZATION_VM_OTHER)
408 other = true;
409 else if (r != VIRTUALIZATION_NONE)
410 goto finish;
411
412 r = detect_vm_zvm();
413 if (r < 0)
414 return r;
415
416finish:
417 /* x86 xen Dom0 is detected as XEN in hypervisor and maybe others.
418 * In order to detect the Dom0 as not virtualization we need to
419 * double-check it */
420 if (r == VIRTUALIZATION_XEN) {
421 int dom0;
422
423 dom0 = detect_vm_xen_dom0();
424 if (dom0 < 0)
425 return dom0;
426 if (dom0 > 0)
427 r = VIRTUALIZATION_NONE;
428 } else if (r == VIRTUALIZATION_NONE && other)
429 r = VIRTUALIZATION_VM_OTHER;
430
431 cached_found = r;
432 log_debug("Found VM virtualization %s", virtualization_to_string(r));
433 return r;
434}
435
436static const char *const container_table[_VIRTUALIZATION_MAX] = {
437 [VIRTUALIZATION_LXC] = "lxc",
438 [VIRTUALIZATION_LXC_LIBVIRT] = "lxc-libvirt",
439 [VIRTUALIZATION_SYSTEMD_NSPAWN] = "systemd-nspawn",
440 [VIRTUALIZATION_DOCKER] = "docker",
441 [VIRTUALIZATION_PODMAN] = "podman",
442 [VIRTUALIZATION_RKT] = "rkt",
443 [VIRTUALIZATION_WSL] = "wsl",
444};
445
446DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(container, int);
447
448int detect_container(void) {
449 static thread_local int cached_found = _VIRTUALIZATION_INVALID;
450 _cleanup_free_ char *m = NULL;
451 _cleanup_free_ char *o = NULL;
452 const char *e = NULL;
453 int r;
454
455 if (cached_found >= 0)
456 return cached_found;
457
458 /* /proc/vz exists in container and outside of the container, /proc/bc only outside of the container. */
459 if (access("/proc/vz", F_OK) >= 0 &&
460 access("/proc/bc", F_OK) < 0) {
461 r = VIRTUALIZATION_OPENVZ;
462 goto finish;
463 }
464
465 /* "Official" way of detecting WSL https://github.com/Microsoft/WSL/issues/423#issuecomment-221627364,
466 * ... and a working one, since the official one doesn't actually work ;(
467 */
468 r = read_one_line_file("/proc/sys/kernel/osrelease", &o);
469 if (r >= 0 &&
470 (strstr(o, "Microsoft") || strstr(o, "microsoft") || strstr(o, "WSL"))) {
471 r = VIRTUALIZATION_WSL;
472 goto finish;
473 }
474
475 if (getpid_cached() == 1) {
476 /* If we are PID 1 we can just check our own environment variable, and that's authoritative.
477 * We distinguish three cases:
478 * - the variable is not defined → we jump to other checks
479 * - the variable is defined to an empty value → we are not in a container
480 * - anything else → some container, either one of the known ones or "container-other"
481 */
482 e = getenv("container");
483 if (!e)
484 goto check_sched;
485 if (isempty(e)) {
486 r = VIRTUALIZATION_NONE;
487 goto finish;
488 }
489
490 goto translate_name;
491 }
492
493 /* Otherwise, PID 1 might have dropped this information into a file in /run. This is better than accessing
494 * /proc/1/environ, since we don't need CAP_SYS_PTRACE for that. */
495 r = read_one_line_file("/run/systemd/container", &m);
496 if (r > 0) {
497 e = m;
498 goto translate_name;
499 }
500 if (!IN_SET(r, -ENOENT, 0))
501 return log_debug_errno(r, "Failed to read /run/systemd/container: %m");
502
503 /* Fallback for cases where PID 1 was not systemd (for example, cases where init=/bin/sh is used. */
504 r = getenv_for_pid(1, "container", &m);
505 if (r > 0) {
506 e = m;
507 goto translate_name;
508 }
509 if (r < 0) /* This only works if we have CAP_SYS_PTRACE, hence let's better ignore failures here */
510 log_debug_errno(r, "Failed to read $container of PID 1, ignoring: %m");
511
512 /* Interestingly /proc/1/sched actually shows the host's PID for what we see as PID 1. If the PID
513 * shown there is not 1, we know we are in a PID namespace and hence a container. */
514 check_sched:
515 r = read_one_line_file("/proc/1/sched", &m);
516 if (r >= 0) {
517 const char *t;
518
519 t = strrchr(m, '(');
520 if (!t)
521 return -EIO;
522
523 if (!startswith(t, "(1,")) {
524 r = VIRTUALIZATION_CONTAINER_OTHER;
525 goto finish;
526 }
527 } else if (r != -ENOENT)
528 return r;
529
530 /* If that didn't work, give up, assume no container manager. */
531 r = VIRTUALIZATION_NONE;
532 goto finish;
533
534translate_name:
535 r = container_from_string(e);
536 if (r < 0)
537 r = VIRTUALIZATION_CONTAINER_OTHER;
538
539finish:
540 log_debug("Found container virtualization %s.", virtualization_to_string(r));
541 cached_found = r;
542 return r;
543}
544
545int detect_virtualization(void) {
546 int r;
547
548 r = detect_container();
549 if (r == 0)
550 r = detect_vm();
551
552 return r;
553}
554
555static int userns_has_mapping(const char *name) {
556 _cleanup_fclose_ FILE *f = NULL;
557 _cleanup_free_ char *buf = NULL;
558 size_t n_allocated = 0;
559 ssize_t n;
560 uint32_t a, b, c;
561 int r;
562
563 f = fopen(name, "re");
564 if (!f) {
565 log_debug_errno(errno, "Failed to open %s: %m", name);
566 return errno == ENOENT ? false : -errno;
567 }
568
569 n = getline(&buf, &n_allocated, f);
570 if (n < 0) {
571 if (feof(f)) {
572 log_debug("%s is empty, we're in an uninitialized user namespace", name);
573 return true;
574 }
575
576 return log_debug_errno(errno, "Failed to read %s: %m", name);
577 }
578
579 r = sscanf(buf, "%"PRIu32" %"PRIu32" %"PRIu32, &a, &b, &c);
580 if (r < 3)
581 return log_debug_errno(errno, "Failed to parse %s: %m", name);
582
583 if (a == 0 && b == 0 && c == UINT32_MAX) {
584 /* The kernel calls mappings_overlap() and does not allow overlaps */
585 log_debug("%s has a full 1:1 mapping", name);
586 return false;
587 }
588
589 /* Anything else implies that we are in a user namespace */
590 log_debug("Mapping found in %s, we're in a user namespace", name);
591 return true;
592}
593
594int running_in_userns(void) {
595 _cleanup_free_ char *line = NULL;
596 int r;
597
598 r = userns_has_mapping("/proc/self/uid_map");
599 if (r != 0)
600 return r;
601
602 r = userns_has_mapping("/proc/self/gid_map");
603 if (r != 0)
604 return r;
605
606 /* "setgroups" file was added in kernel v3.18-rc6-15-g9cc46516dd. It is also
607 * possible to compile a kernel without CONFIG_USER_NS, in which case "setgroups"
608 * also does not exist. We cannot distinguish those two cases, so assume that
609 * we're running on a stripped-down recent kernel, rather than on an old one,
610 * and if the file is not found, return false.
611 */
612 r = read_one_line_file("/proc/self/setgroups", &line);
613 if (r < 0) {
614 log_debug_errno(r, "/proc/self/setgroups: %m");
615 return r == -ENOENT ? false : r;
616 }
617
618 truncate_nl(line);
619 r = streq(line, "deny");
620 /* See user_namespaces(7) for a description of this "setgroups" contents. */
621 log_debug("/proc/self/setgroups contains \"%s\", %s user namespace", line, r ? "in" : "not in");
622 return r;
623}
624
625int running_in_chroot(void) {
626 int r;
627
628 if (getenv_bool("SYSTEMD_IGNORE_CHROOT") > 0)
629 return 0;
630
631 r = files_same("/proc/1/root", "/", 0);
632 if (r < 0)
633 return r;
634
635 return r == 0;
636}
637
638static const char *const virtualization_table[_VIRTUALIZATION_MAX] = {
639 [VIRTUALIZATION_NONE] = "none",
640 [VIRTUALIZATION_KVM] = "kvm",
641 [VIRTUALIZATION_QEMU] = "qemu",
642 [VIRTUALIZATION_BOCHS] = "bochs",
643 [VIRTUALIZATION_XEN] = "xen",
644 [VIRTUALIZATION_UML] = "uml",
645 [VIRTUALIZATION_VMWARE] = "vmware",
646 [VIRTUALIZATION_ORACLE] = "oracle",
647 [VIRTUALIZATION_MICROSOFT] = "microsoft",
648 [VIRTUALIZATION_ZVM] = "zvm",
649 [VIRTUALIZATION_PARALLELS] = "parallels",
650 [VIRTUALIZATION_BHYVE] = "bhyve",
651 [VIRTUALIZATION_QNX] = "qnx",
652 [VIRTUALIZATION_ACRN] = "acrn",
653 [VIRTUALIZATION_VM_OTHER] = "vm-other",
654
655 [VIRTUALIZATION_SYSTEMD_NSPAWN] = "systemd-nspawn",
656 [VIRTUALIZATION_LXC_LIBVIRT] = "lxc-libvirt",
657 [VIRTUALIZATION_LXC] = "lxc",
658 [VIRTUALIZATION_OPENVZ] = "openvz",
659 [VIRTUALIZATION_DOCKER] = "docker",
660 [VIRTUALIZATION_PODMAN] = "podman",
661 [VIRTUALIZATION_RKT] = "rkt",
662 [VIRTUALIZATION_WSL] = "wsl",
663 [VIRTUALIZATION_CONTAINER_OTHER] = "container-other",
664};
665
666DEFINE_STRING_TABLE_LOOKUP(virtualization, int);