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