Commit Graph

1391 Commits

Author SHA1 Message Date
Andrey Drobyshev
d2f8308813 daemon/selinux-relabel: run setfiles with "-T 0", if supported
Since SELinux userspace v3.4 [1], setfiles command supports "-T nthreads"
option, which allows parallel execution.  "-T 0" allows using as many
threads as there're available CPU cores.  This might speed up the process
of filesystem relabeling in case the appliance is being run with multiple
vCPUs.  The latter is true for at least v2v starting from d2b64ecc67
("v2v: Set the number of vCPUs to same as host number of pCPUs.").

For instance, when running virt-v2v-in-place on my 12-core Xeon host
with SSD, with appliance being run with 8 vCPUs (the upper limit specified
in d2b64ecc67), and on the ~150GiB disk VM (physical size on the host),
I get the following results:

./in-place/virt-v2v-in-place -i libvirt fedora37-vm -v -x

Without this patch:
...
commandrvf: setfiles -F -e /sysroot/dev -e /sysroot/proc -e /sysroot/sys -m -C -r /sysroot -v /sysroot/etc/selinux/targeted/contexts/files/file_contexts /sysroot/^M
libguestfs: trace: v2v: selinux_relabel = 0
libguestfs: trace: v2v: rm_f "/.autorelabel"
guestfsd: => selinux_relabel (0x1d3) took 17.94 secs
...

With this patch:
...
commandrvf: setfiles -F -e /sysroot/dev -e /sysroot/proc -e /sysroot/sys -m -C -T 0 -r /sysroot -v /sysroot/etc/selinux/targeted/contexts/files/file_contexts /sysroot/^M
libguestfs: trace: v2v: selinux_relabel = 0
libguestfs: trace: v2v: rm_f "/.autorelabel"
guestfsd: => selinux_relabel (0x1d3) took 5.88 secs
...

So in my scenario it's getting 3 times faster.

[1] https://github.com/SELinuxProject/selinux/releases/tag/3.4

Signed-off-by: Andrey Drobyshev <andrey.drobyshev@virtuozzo.com>
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
Reviewed-by: Richard W.M. Jones <rjones@redhat.com>
(cherry picked from commit d0d8e67384)
2024-07-09 14:42:43 +01:00
Andrey Drobyshev
917455b158 daemon/selinux-relabel: search for "invalid option" in setfiles output
'X' in the setiles' stderr doesn't necessarily mean that option 'X'
doesn't exist.  For instance, when passing '-T' we get: "setfiles:
option requires an argument -- 'T'".

Signed-off-by: Andrey Drobyshev <andrey.drobyshev@virtuozzo.com>
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
Reviewed-by: Richard W.M. Jones <rjones@redhat.com>
(cherry picked from commit 152d6e4bdf)
2024-07-09 14:42:43 +01:00
Andrey Drobyshev
d2e6dce96a daemon/selinux-relabel: don't exclude "/selinux" if it's non-existent
Since RHBZ#726528, filesystem.rpm doesn't include /selinux.  setfiles
then gives us the warning: "Can't stat exclude path "/sysroot/selinux",
No such file or directory - ignoring."

Though the warning is harmless, let's get rid of it by checking the
existence of /selinux directory.

Signed-off-by: Andrey Drobyshev <andrey.drobyshev@virtuozzo.com>
Reviewed-by: Laszlo Ersek <lersek@redhat.com>
Reviewed-by: Richard W.M. Jones <rjones@redhat.com>
(cherry picked from commit 9ced5fac8c)
2024-07-09 14:42:43 +01:00
Richard W.M. Jones
fd31d30b75 daemon/findfs.ml: Fix whitespace
(cherry picked from commit 4c5c0782af)
(cherry picked from commit 37a47a9b5d)
2024-07-09 14:08:41 +01:00
Richard W.M. Jones
55a6c32c46 daemon: Add an OCaml binding for get_random_uuid function
(cherry picked from commit a25f419802)
(cherry picked from commit ae2344f8f2)
2024-07-09 14:08:41 +01:00
Richard W.M. Jones
f9a070f827 daemon: Move gdisk function to a new file
After subsequent commits, this will be the only remaining use of
gdisk, so put it in its own file now.

(cherry picked from commit d5c6e15180)
(cherry picked from commit d400b0637e)
2024-07-09 14:08:41 +01:00
Richard W.M. Jones
f2bfa98f05 daemon: part_get_gpt_type: Remove unhelpful MBR fallback behaviour
This was an accident of the parted implementation, and wasn't really
used anywhere.  Remove it.

(cherry picked from commit 2811e42b43)
(cherry picked from commit cbfe36b7c7)
2024-07-09 14:08:41 +01:00
Richard W.M. Jones
c56d8e9da1 daemon/parted: Assume sfdisk --part-type exists
This "new" parameter was added in 2014:

  commit 8eab3194ce1737a167812d5e84d83b0dfc253fac
  Author: Karel Zak <kzak@redhat.com>
  Date:   Mon Sep 15 12:37:52 2014 +0200

    sfdisk: add --parttype

    The patch also makes --{id,change-id,print-id} deprecated in favour
    of --parttype. The original --id is too generic option name and the
    --print-id and --change-id are unnecessary and inconsistent with
    another sfdisk options (e.g. we don't have --change-bootable)

Also remove an extraneous / incorrect comment about parted.  As
history has played out, sfdisk proves to be the better tool and parted
is a PITA.

(cherry picked from commit 857615d6d2)
(cherry picked from commit c749314646)
2024-07-09 14:08:41 +01:00
Richard W.M. Jones
c7c0c97e3e daemon: parted: Print field we are extracting in error message
(cherry picked from commit c8cefa6f0f)
(cherry picked from commit 4fdc89fb51)
2024-07-09 14:08:41 +01:00
Richard W.M. Jones
5c3ca4ec85 daemon: Find -lcamlstr{nat,byt} and -lunix{nat,byt}, and require -lzstd
OCaml 5.1 changes the names of these libraries for some reason.

Also in OCaml 5.1, if using those libraries you must link with -lzstd.
Since zstd was already described as "required" (although we only used
it in the appliance), there is no official change to the requirements,
but I have added a configure time check for the library.

Thanks: Jerry James <loganjerry@gmail.com>
(cherry picked from commit f8cbd71400)
2024-07-09 14:08:41 +01:00
Richard W.M. Jones
13578ecdba Replace Pervasives.* with Stdlib.*
Since OCaml 4.07 (released 2018-07-10) the always-loaded standard
library module has been called Stdlib.  The old Pervasives module was
finally removed in OCaml 5.

$ perl -pi.bak -e 's/Pervasives\./Stdlib./g' -- `git ls-files`

OCaml >= 4.07 is now required.

Also update the common submodule with:

  commit d61cd820b49e403848d15c5deaccbf8dd7045370
  Author: Jürgen Hötzel
  Date:   Sat May 20 18:16:40 2023 +0200

    Add support for OCaml 5.0

(cherry picked from commit 3cb094083e)
2024-07-09 14:06:52 +01:00
Richard W.M. Jones
75c30fe750 Rework Std_utils.Option so it works like the OCaml stdlib module
OCaml 4.08 introduces a stdlib Option module which looks a bit like
ours but has a number of differences.  In particular our functions
Option.may and Option.default have no corresponding functions in
stdlib, although there are close enough equivalents.

This change was automated using this command:

$ perl -pi.bak \
  -e 's/Option.may/Option.iter/g; s/Option.default /Option.value ~default:/g' \
  `git ls-files`

Update common module to include:

  commit cffa077323fafcdfcf78e230c022afa891a6b3ff
  Author: Richard W.M. Jones <rjones@redhat.com>
  Date:   Mon Feb 20 12:11:51 2023 +0000

    mlstdutils: Rework the Option module to be compatible with stdlib

(cherry picked from commit 250ee85839)
2023-02-21 20:42:25 +00:00
Richard W.M. Jones
e2c7bddf10 Update copyright dates for 2023
Run this command across the source:

  perl -pi.bak -e 's/(20[012][0-9])-20[12][012]/$1-2023/g' `git ls-files`

and remove changes to po{,-docs}/*.po{,t} (these will be regenerated
later when we run 'make dist').
2023-02-07 10:50:48 +00:00
Richard W.M. Jones
fbf7fe8793 build: Remove bundled copy of ocaml-augeas
This is now an external dependency.
2023-01-19 23:00:23 +00:00
Richard W.M. Jones
f3dd67affe New API: inspect_get_build_id
Add an API to return the build ID of the guest.  This to allow a
future change to be able to distinguish between Windows 10 and Windows 11
which can only be done using the build ID.

For Windows we can read the CurrentBuildNumber key from the registry.
For Linux there happens to be a BUILD_ID field in /etc/os-release.
I've never seen a Linux distro that actually uses this.

Reviewed-by: Laszlo Ersek <lersek@redhat.com>
2022-12-02 10:16:57 +00:00
Richard W.M. Jones
23986d3c4f file: Use -S option with -z
The file(1) manual suggests using -S (disable seccomp) with -z since
the set of system calls provided by the seccomp policy does not allow
the subprocess to run.  This is obvious when you use file -z on a
compressed file on a Linux distro that enables file's seccomp policy
(Arch does this, Fedora does not):

  $ file -zbsL lib-i586.so.zst
  Bad system call

I also fixed some incorrect text in the manual.

Thanks: Toolybird for pointing to this fix
Reported-by: David Runge
Fixes: https://github.com/libguestfs/libguestfs/issues/100
2022-11-28 10:21:00 +00:00
Richard W.M. Jones
001683e885 appliance: Remove LD_PRELOAD=libSegFault.so
This feature was removed in glibc 2.35:
https://savannah.gnu.org/forum/forum.php?forum_id=10111
2022-10-24 10:41:09 +01:00
Richard W.M. Jones
c2dd84b263 daemon: Make vg_scan and lvm_scan no-ops if no LVM feature
If the LVM ("lvm2") feature is not available, these calls would fail.
Really they ought to be part of the "lvm2" optgroup which would cause
the generator to call reply_with_unavailable_feature and generate the
correct ENOTSUP error.  When vgscan was originally added in 2010 it
was not added to the optgroup, and when lvm_scan was later added in
2018 and deprecating vgscan, the same mistake was copied.

Before this commit they will try to run the lvm pvscan command which
will fail returning some other error (instead of ENOTSUP).

Fix this by turning the calls into no-ops if the LVM feature is not
available, since scanning for LVM objects when there is no LVM can be
safely turned into a no-op.

See also
https://listman.redhat.com/archives/libguestfs/2022-September/thread.html#29908

Also this updates the common module to pick up a related fix:

  commit 4b4a5b84647b1496d034bcdff910930ca5f5c486
  Author: Richard W.M. Jones <rjones@redhat.com>
  Date:   Fri Sep 23 15:18:43 2022 +0100

    options: Don't attempt to scan LVs if "lvm2" feature is not available

Reported-by: Laszlo Ersek <lersek@redhat.com>
Acked-by: Laszlo Ersek <lersek@redhat.com>
Fixes: 55dfcb2211 ("New API: lvm_scan, deprecate vgscan")
Fixes: 9752039e52 ("New API: vgscan")
2022-09-27 15:53:48 +01:00
Richard W.M. Jones
0b3c6cc0c0 daemon: Remove remaining uses of custom printf %Q and %R
We have traditionally used custom printf formatters %Q and %R, where
%Q replaces the argument with a shell-quoted string, and %R replaces
the argument with a sysroot-prefixed shell-quoted string.  They are
actually pretty useful, but unfortunately only supported by glibc.

We only used them in about a dozen places in the daemon (much code
having been replaced by OCaml which does not need them).

In every remaining case we were constructing a command using code like
this:

  asprintf_nowarn (&cmd,
         "cd %Q && find -print0 | %s -0 -o -H %s --quiet", ...);

We can replace this with:

  char *cmd;
  size_t cmd_size;
  fp = open_memstream (&cmd, &cmd_size);
  fprintf (fp, "cd ");
  shell_quote (dir, fp);
  fprintf (fp, " && find -print0 | %s -0 -o -H %s --quiet", ...);
  fclose (fp);
2022-08-16 10:39:01 +01:00
Richard W.M. Jones
ad8b1b09ee daemon: grub: Remove incorrect use of printf specifier %R
This code is attempting to construct a grub-install command like:

  grub-install --root-directory=/sysroot/boot /dev/sda

In fact it was adding quoting to the --root-directory parameter where
it was not needed (because our "command" function uses exec).

Remove use of %R here (to avoid the extra quoting) and just use the
sysroot prefix directly.
2022-08-16 10:21:33 +01:00
Richard W.M. Jones
0e784824e8 daemon: Add zstd support to guestfs_file_architecture
This is required so we can determine the file architecture of
zstd-compressed Linux kernel modules as used by OpenSUSE and maybe
other distros in future.

Note that zstd becomes a required package, but it is widely available
in current Linux distros.

The package names come from https://pkgs.org/download/zstd and my own
research.
2022-08-09 19:04:41 +01:00
Richard W.M. Jones
4a517601c7 daemon: Parse /etc/hostname files containing comments
Thanks: Dawid Zamirski
Link: https://www.freedesktop.org/software/systemd/man/hostname.html
Acked-by: Laszlo Ersek <lersek@redhat.com>
2022-07-20 13:22:39 +01:00
Laszlo Ersek
9a3e9a6c03 introduce the "clevis_luks_unlock" API
Introduce a new guestfs API called "clevis_luks_unlock". At the libguestfs
level, it is quite simple; it wraps the "clevis luks unlock" guest command
(implemented by the "clevis-luks-unlock" executable, which is in fact a
shell script).

The complexity is instead in the network-based disk encryption
(Clevis/Tang) scheme. Useful documentation:

- https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9/html-single/security_hardening/index#configuring-automated-unlocking-of-encrypted-volumes-using-policy-based-decryption_security-hardening
- https://github.com/latchset/clevis#clevis
- https://github.com/latchset/tang#tang

The package providing "clevis-luks-unlock" is usually called
"clevis-luks", occasionally "clevis". Some distros don't package clevis at
all. Add the new API under a new option group (which may not be available)
called "clevisluks".

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1809453
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Message-Id: <20220630122048.19335-3-lersek@redhat.com>
Reviewed-by: Richard W.M. Jones <rjones@redhat.com>
2022-07-01 15:07:26 +02:00
Richard W.M. Jones
1087d314cc daemon: Remove workaround for -Wanalyzer-mismatching-deallocation
On older GCC:

debug.c:116:32: error: unknown option after ‘#pragma GCC diagnostic’ kind [-Werror=pragmas]
  116 | #pragma GCC diagnostic ignored "-Wanalyzer-mismatching-deallocation"
      |                                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors
make[3]: *** [Makefile:2039: guestfsd-debug.o] Error 1

The upstream bug (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99193)
has now been fixed so the workaround is not necessary with the latest
GCC, so just delete the workaround.
2022-06-17 13:24:19 +01:00
Laszlo Ersek
8fc4d16715 appliance, daemon: disable lvm2 devicesfile
In guestfs-tools commit 4fe8a03cd2d3 ('sysprep: remove lvm2's default
"system.devices" file', 2022-04-11), we disabled the use of LVM2's new
"devicesfile" feature, which could interfere with the cloning of virtual
machines.

We suspected in

  https://bugzilla.redhat.com/show_bug.cgi?id=2072493#c6

that the same lvm2 feature could affect the libguestfs appliance itself,
but decided in

  https://bugzilla.redhat.com/show_bug.cgi?id=2072493#c8
  https://bugzilla.redhat.com/show_bug.cgi?id=2072493#c10

that this would not be the case, because "appliance/init" already
constructed a pristine LVM_SYSTEM_DIR.

Unfortunately, that's not enough: due to the "use_devicesfile=1" default
(on RHEL9 anyway), some "lvm" invocation, possibly inside the
lvm-set-filter API, *creates* "$LVM_SYSTEM_DIR/devices/system.devices".
And then we get (minimally) warnings such as

> Please remove the lvm.conf global_filter, it is ignored with the devices
> file.
> Please remove the lvm.conf filter, it is ignored with the devices file.

when using the lvm-set-filter API.

Explicitly disable the "devices file" in "appliance/init", and also
whenever we rewrite "lvm.conf" -- that is, in set_filter()
[daemon/lvm-filter.c]. In the former, check for the feature by locating
the devicesfile-related utilities "lvmdevices" and "vgimportdevices". In
the C code, invoke the utilities with the "--help" option instead. (In
"appliance/init",  I thought it was best not to call any lvm2 utilities
even with "--help", with our lvm2.conf still under construction there.) If
either utility is available, set "use_devicesfile = 0".

Cc: David Teigland <teigland@redhat.com>
Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1965941
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Message-Id: <20220530141027.16167-1-lersek@redhat.com>
Acked-by: Richard W.M. Jones <rjones@redhat.com>
[lersek@redhat.com: style fix: break "devicesfile_feature" in the function
 definition to a new line]
2022-05-31 08:47:58 +02:00
Richard W.M. Jones
488245ed6c daemon: rpm: Check return values from librpm calls
We previously didn't bother to check the return values from any librpm
calls.  In some cases where possibly the RPM database is faulty, this
caused us to return a zero-length list of installed applications (but
no error indication).

One way to reproduce this is given below.  Note this reproducer will
only work when run on a RHEL 8 host (or more specifically, with
rpm <= 4.16):

$ virt-builder fedora-28
$ guestfish -a fedora-28.img -i rm /var/lib/rpm/Packages
$ guestfish --ro -a fedora-28.img -i inspect-list-applications /dev/sda4 -vx
...
chroot: /sysroot: running 'librpm'
error: cannot open Packages index using db5 - Read-only file system (30)
error: cannot open Packages database in
error: cannot open Packages index using db5 - Read-only file system (30)
error: cannot open Packages database in
librpm returned 0 installed packages
...

With this commit we get an error instead:

...
chroot: /sysroot: running 'librpm'
error: cannot open Packages index using db5 - Read-only file system (30)
error: cannot open Packages database in
ocaml_exn: 'internal_list_rpm_applications' raised 'Failure' exception
guestfsd: error: rpmtsInitIterator
guestfsd: => internal_list_rpm_applications (0x1fe) took 0.01 secs
libguestfs: trace: internal_list_rpm_applications = NULL (error)
libguestfs: error: internal_list_rpm_applications: rpmtsInitIterator
libguestfs: trace: inspect_list_applications2 = NULL (error)
libguestfs: trace: inspect_list_applications = NULL (error)
...

Not in this case, but in some cases of corrupt RPM databases it is
possible to recover them by running "rpmdb --rebuilddb" as a guest
command (ie. with guestfs_sh).

See-also: https://bugzilla.redhat.com/show_bug.cgi?id=2089623#c12
Fixes: https://bugzilla.redhat.com/show_bug.cgi?id=2089623
Fixes: commit c9ee831aff
Reported-by: Xiaodai Wang
Reported-by: Ming Xie
Acked-by: Laszlo Ersek <lersek@redhat.com>
2022-05-26 10:16:21 +01:00
Laszlo Ersek
a39b79f607 daemon/selinux-relabel: tolerate relabeling errors
Option "-C" of setfiles(8) causes setfiles(8) to exit with status 1 rather
than status 255 if it encounters relabeling errors, but no other (fatal)
error. Pass "-C" to setfiles(8) in "selinux-relabel", because we don't
want the "selinux-relabel" API to fail if setfiles(8) only encounters
relabeling errors.

(NB even without "-C", setfiles(8) continues traversing the directory
tree(s) and relabeling files across relabeling errors, so this change is
specifically about the exit status.)

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1794518
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Message-Id: <20220511122345.14208-3-lersek@redhat.com>
Reviewed-by: Richard W.M. Jones <rjones@redhat.com>
2022-05-11 17:02:17 +02:00
Laszlo Ersek
5345d42635 daemon/selinux-relabel: generalize setfiles_has_m_option()
Allow the caller to pass in the option to check for, and to store the
result in a (usually static) variable of their choice.

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1794518
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Message-Id: <20220511122345.14208-2-lersek@redhat.com>
Reviewed-by: Richard W.M. Jones <rjones@redhat.com>
2022-05-11 17:01:57 +02:00
Laszlo Ersek
4864d21cb8 guestfs_readdir(): minimize the number of send_file_write() calls
In guestfs_readdir(), the daemon currently sends each XDR-encoded
"guestfs_int_dirent" to the library with a separate send_file_write()
call.

Determine the largest encoded size (from the longest filename that a
"guestfs_int_dirent" could carry, from readdir()'s "struct dirent"), and
batch up the XDR encodings until the next encoding might not fit in
GUESTFS_MAX_CHUNK_SIZE. Call send_file_write() only then.

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1674392
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Message-Id: <20220502085601.15012-3-lersek@redhat.com>
Reviewed-by: Richard W.M. Jones <rjones@redhat.com>
2022-05-03 10:54:00 +02:00
Laszlo Ersek
45b7f1736b guestfs_readdir(): rewrite with FileOut transfer, to lift protocol limit
Currently the guestfs_readdir() API can not list long directories, due to
it sending back the whole directory listing in a single guestfs protocol
response, which is limited to GUESTFS_MESSAGE_MAX (approx. 4MB) in size.

Introduce the "internal_readdir" action, for transferring the directory
listing from the daemon to the library through a FileOut parameter.
Rewrite guestfs_readdir() on top of this new internal function:

- The new "internal_readdir" action is a daemon action. Do not repurpose
  the "readdir" proc_nr (138) for "internal_readdir", as some distros ship
  the binary appliance to their users, and reusing the proc_nr could
  create a mismatch between library & appliance with obscure symptoms.
  Replace the old proc_nr (138) with a new proc_nr (511) instead; a
  mismatch would then produce a clear error message. Assume the new action
  will first be released in libguestfs-1.48.2.

- Turn "readdir" from a daemon action into a non-daemon one. Call the
  daemon action guestfs_internal_readdir() manually, receive the FileOut
  parameter into a temp file, then deserialize the dirents array from the
  temp file.

This patch sneakily fixes an independent bug, too. In the pre-patch
do_readdir() function [daemon/readdir.c], when readdir() returns NULL, we
don't distinguish "end of directory stream" from "readdir() failed". This
rewrite fixes this problem -- I didn't see much value separating out the
fix for the original do_readdir().

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1674392
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Message-Id: <20220502085601.15012-2-lersek@redhat.com>
Reviewed-by: Richard W.M. Jones <rjones@redhat.com>
2022-05-03 10:53:48 +02:00
Richard W.M. Jones
bc96e0b7d7 daemon: Fix compilation with older rpm that lacks RPMVSF_MASK_NOSIGNATURES
On RHEL 7 (rpm-devel-4.11.3-45.el7.x86_64):

rpm-c.c: In function ‘guestfs_int_daemon_rpm_start_iterator’:
rpm-c.c:97:44: error: ‘RPMVSF_MASK_NOSIGNATURES’ undeclared (first use in this function)
   rpmtsSetVSFlags (ts, rpmtsVSFlags (ts) | RPMVSF_MASK_NOSIGNATURES);
                                            ^
rpm-c.c:97:44: note: each undeclared identifier is reported only once for each function it appears in

Fixes: commit aa6f8038f8
2022-04-25 16:40:12 +01:00
Richard W.M. Jones
d64d2b7649 daemon/utils.ml: Replace Bytes.get_uint8 with native call
Bytes.get_uint8 was added in OCaml 4.08.  To support OCaml >= 4.04 (in
particular, RHEL 8 has OCaml 4.07) we have to replace this function
with the equivalent native call.  We can remove this commit once the
baseline OCaml moves up.

Updates: commit edfebee404
2022-04-14 11:32:35 +01:00
Richard W.M. Jones
aa6f8038f8 daemon/rpm-c.c: Disable signature checking in librpm
Older distros (eg CentOS 6) used SHA-1 RPM package signatures which
some newer distros (eg RHEL 9.0) prevent us from verifying.

This resulted in packages with SHA-1 signatures being skipped by
librpm (there is a warning in debug output, but if you're not looking
at that then the package is silently ignored).  In some cases
essential packages like the kernel were skipped, which would be
visible as a failure of virt-v2v.  In other cases (eg virt-inspector)
you'd just see fewer installed packages in the <applications> list.

Since verifying package signatures is not essential for inspection,
disable this feature in librpm.

Reported-by: Xiaodai Wang
Thanks: Panu Matilainen
Fixes: https://bugzilla.redhat.com/show_bug.cgi?id=2064182
Signed-off-by: Richard W.M. Jones <rjones@redhat.com>
2022-03-15 11:00:08 +00:00
Richard W.M. Jones
4256737227 lib: Remove drive hotplugging support
This was a feature that allowed you to add drives to the appliance
after launching it.  It was complicated to implement, and only worked
for the libvirt backend (not "direct", which is the default backend).

It also turned out to be a bad idea.  The original concept was that
appliance creation was slow, so to examine multiple guests you should
launch the handle once then hot-add the disks from each guest in turn
to manipulate them.  However this is terrible from a security point of
view, especially for multi-tenant, because the drives from one guest
might compromise the appliance and thus the filesystems/drives from
subsequent guests.

It also turns out that hotplugging is very slow.  Nowadays appliance
creation should be faster than hotplugging.

The main use case for this was virt-df, but virt-df no longer uses it
after we discovered the problems outlined above.
2022-03-09 09:28:02 +00:00
Richard W.M. Jones
55be87367d lib: Remove 9p APIs
These APIs were an experimental feature for passing through 9p
filesystems from the host to the libguestfs appliance.  It was never
possible to use this without hacking the qemu command line of the
appliance to add such drives by hand.  It also didn't fit the
libguestfs model very well.  And 9p is generally deprecated in
upstream qemu.

Note that for ABI reasons these APIs are not actually removed, they
have been changed so that they always return an error.  These APIs
were actually hard-removed from all versions of RHEL.

See-also: https://bugzilla.redhat.com/921710
2022-03-09 09:28:02 +00:00
Neil Hanlon
631962c0e8 Add detection support for Rocky Linux (CentOS/RHEL-like)
Fixes: https://bugzilla.redhat.com/show_bug.cgi?id=2030709
Thanks: label@rockylinux.org

---

RWMJ notes: I fixed the original patch so it compiled.  This patch
sets osinfo to "rocky8", which doesn't exist in the osinfo db yet.
Arguably we might want to set this to "centos8", but we can see what
libosinfo decides to do.  Here is partial virt-inspector output on a
Rocky Linux disk image:

$ ./run virt-inspector -a disk.img
<?xml version="1.0"?>
<operatingsystems>
  <operatingsystem>
    <root>/dev/rl/root</root>
    <name>linux</name>
    <arch>x86_64</arch>
    <distro>rocky</distro>
    <product_name>Rocky Linux 8.5 (Green Obsidian)</product_name>
    <major_version>8</major_version>
    <minor_version>5</minor_version>
    <package_format>rpm</package_format>
    <package_management>dnf</package_management>
    <hostname>localhost.localdomain</hostname>
    <osinfo>rocky8</osinfo>
    <mountpoints>
      <mountpoint dev="/dev/rl/root">/</mountpoint>
      <mountpoint dev="/dev/sda1">/boot</mountpoint>
    </mountpoints>
    <filesystems>
      <filesystem dev="/dev/rl/root">
        <type>xfs</type>
        <uuid>fed8331f-9f25-40cd-883e-090cd640559d</uuid>
      </filesystem>
      <filesystem dev="/dev/rl/swap">
        <type>swap</type>
        <uuid>6da2c121-ea7d-49ce-98a3-14a37fceaadd</uuid>
      </filesystem>
      <filesystem dev="/dev/sda1">
        <type>xfs</type>
        <uuid>4efafe61-2d20-4d93-8055-537e09bfd033</uuid>
      </filesystem>
    </filesystems>
2021-12-10 09:09:47 +00:00
Laszlo Ersek
d829f9ff9a daemon/listfs: don't call "sgdisk -i" on bogus MBR partition table entry
The "is_partition_can_hold_filesystem" function calls
"Parted.part_get_gpt_type" on the partition if:
- the partition table type is GPT,
- or the partition table type is MBR, and the partition is primary or
  logical.

The one entry in the fake MBR partition table described in the previous
patch passes the second branch of this check, therefore
"Parted.part_get_gpt_type" is reached, and it invokes "sgdisk -i 1" on the
disk.

Surprisingly (not), while "sgdisk -i" copes fine with valid MBR partition
tables, it chokes on the fake one. The output does not contain the
"Partition GUID code" line, and so "sgdisk_info_extract_field" throws an
exception.

Prevent calling "Parted.part_get_gpt_type" on a bogus MBR partition table,
similarly to the "extended entry in MBR partition table" case; the
difference is that the bogus primary entry, unlike a valid extended entry,
*can* hold a filesystem.

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1931821
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Acked-by: Richard W.M. Jones <rjones@redhat.com>
Message-Id: <20211125094954.9713-6-lersek@redhat.com>
2021-11-26 10:17:54 +01:00
Laszlo Ersek
edfebee404 daemon/parted: work around part table type misreporting by "parted"
"parted" incorrectly reports "loop" rather than "msdos" for the partition
table type, when the (fake) partition table comes from the "--mbr" option
of "mkfs.fat" (in dosfstools-4.2+), and the FAT variant in question is
FAT16 or FAT32. (See RHBZ#2026224.) Work this around by
- parsing the partition table ourselves, and
- overriding "loop" with "msdos" when appropriate.

Note that when the FAT variant is FAT12, "parted" fails to parse the fake
MBR partition table completely (see RHBZ#2026220), which we cannot work
around. However, FAT12 should be a rare corner case in libguestfs usage --
"mkfs.fat" auto-chooses FAT12 only below 9MB disk size, and even "-F 12"
can only be forced up to and including 255MB disk size.

Add the helper function "has_bogus_mbr" to the Utils module; we'll use it
elsewhere too.

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1931821
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Acked-by: Richard W.M. Jones <rjones@redhat.com>
Message-Id: <20211125094954.9713-5-lersek@redhat.com>
[lersek@redhat.com: drop "fun" keyword, and use partial application, in
 the definition of "sec0at" [Rich]]
2021-11-26 10:17:05 +01:00
Laszlo Ersek
c33c2a1d13 daemon/parted: simplify print_partition_table() prototype
Since commit 994ca1f8eb ("daemon: Reimplement 'part_get_mbr_part_type'
API in OCaml.", 2018-05-02), we've not had any calls to
print_partition_table() that would pass a "false" argument for the
"add_m_option" parameter.

Remove the parameter, and inside part_get_mbr_part_type(), remove the dead
branch.

Relatedly, update the comment on the
"print_partition_table_machine_readable" OCaml function, originally from
commit 32e661f421 ("daemon: Reimplement ‘part_list’ API in OCaml.",
2017-07-27). Because print_partition_table() now passes "-m" to "parted"
unconditionally, and there are no use cases left that would *forbid* "-m",
"print_partition_table_machine_readable" is almost equivalent to
print_partition_table() -- modulo the enforcement of the "BYT;" header.

Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Acked-by: Richard W.M. Jones <rjones@redhat.com>
Message-Id: <20211125094954.9713-4-lersek@redhat.com>
2021-11-26 10:16:06 +01:00
Laszlo Ersek
e3671362af daemon/9p: fix wrong pathname in error message
The directory that readdir() and closedir() work on is BUS_PATH
("/sys/bus/virtio/drivers/9pnet_virtio"), not "/sys/block". Fix the error
messages that are sent when readdir() or closedir() fails.

(The invalid "sys/block" pathname could be a leftover from when the
directory reading logic was (perhaps) copied from "daemon/sync.c".)

Fixes: 5f10c33503
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Acked-by: Richard W.M. Jones <rjones@redhat.com>
Message-Id: <20211125094954.9713-3-lersek@redhat.com>
2021-11-26 10:16:05 +01:00
Laszlo Ersek
0ab9305055 daemon/mkfs: disable creation of fake MBR partition table with "mkfs.fat"
Search the usage output of "mkfs.fat" for "--mbr[="; cache the result for
further invocations. If the option is supported, pass "--mbr=n" to
"mkfs.fat". This will prevent the creation of a bogus partition table
whose first (and only) entry describes a partition that contains the
partition table.

(Such a bogus partition table breaks "parted", which is a tool used by
libguestfs extensively, both internally and in public libguestfs APIs.)

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1931821
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Acked-by: Richard W.M. Jones <rjones@redhat.com>
Message-Id: <20211125094954.9713-2-lersek@redhat.com>
2021-11-26 10:16:05 +01:00
Richard W.M. Jones
a69cde79ca daemon: Replace "noalloc" with [@@noalloc] 2021-11-09 10:20:37 +00:00
Laszlo Ersek
305b02e7e7 daemon: inspection: Add support for Kylin (RHBZ#1995391).
Similar-to: cd08039d24
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Message-Id: <20211013163023.21786-1-lersek@redhat.com>
Acked-by: Richard W.M. Jones <rjones@redhat.com>
2021-10-14 19:49:56 +02:00
Laszlo Ersek
e597fc5317 daemon/yara: fix undefined behavior due to Yara 4.0 API changes
Currently, the Yara test case ("yara/test-yara-scan.sh") fails, with the
following obscure error message:

> ><fs> yara-scan /text.txt
> libguestfs: error: deserialise_yara_detection_list:

Namely, the Yara rule match list serialization / de-serialization, between
the daemon and the library, is broken. It is caused by the following
incompatible pointer passing (i.e., undefined behavior), in function
do_internal_yara_scan(), file "daemon/yara.c":

>   r = yr_rules_scan_fd (rules, fd, 0, yara_rules_callback, (void *) path, 0);
                                        ^^^^^^^^^^^^^^^^^^^

The prototype of yara_rules_callback() is:

> static int
> yara_rules_callback (int code, void *message, void *data)

however, in Yara commit 2b121b166d25 ("Track string matches using
YR_SCAN_CONTEXT.", 2020-02-27), which was included in the upstream v4.0.0
release, the rules callback prototype was changed as follows:

> diff --git a/libyara/include/yara/types.h b/libyara/include/yara/types.h
> index cad095cd70c2..f415033c4aa6 100644
> --- a/libyara/include/yara/types.h
> +++ b/libyara/include/yara/types.h
> @@ -661,6 +644,7 @@ struct YR_MEMORY_BLOCK_ITERATOR
>
>
>  typedef int (*YR_CALLBACK_FUNC)(
> +    YR_SCAN_CONTEXT* context,
>      int message,
>      void* message_data,
>      void* user_data);

Therefore, the yara_rules_callback() function is entered with a mismatched
parameter list in the daemon, and so it passes garbage to
send_detection_info(), for serializing the match list.

This incompatible change was in fact documented by the Yara project:

  https://github.com/VirusTotal/yara/wiki/Backward-incompatible-changes-in-YARA-4.0-API#scanning-callback

Gcc too warns about the incompatible pointer type, under
"-Wincompatible-pointer-types". However, libguestfs is built without
"-Werror" by default, so the warning is easy to miss, and the bug only
manifests at runtime.

(The same problem exists for yr_compiler_set_callback() /
compile_error_callback():

  https://github.com/VirusTotal/yara/wiki/Backward-incompatible-changes-in-YARA-4.0-API#compiler-callback

except that this instance of the problem is not triggered by the test
case, as the rule list always compiles.)

Rather than simply fixing the parameter lists, consider the following
approach.

If Yara's YR_CALLBACK_FUNC and YR_COMPILER_CALLBACK_FUNC typedefs were not
for *pointer* types but actual *function* prototypes, then we could use
them directly in the declarations of our callback functions. Then any
future changes in the param lists would force a "conflicting types"
*compilation error* (not a warning). Illustration:

  /* this is *not* a pointer type */
  typedef int HELLO_FUNC (void);

  /* function declarations */
  static HELLO_FUNC my_hello_good;
  static HELLO_FUNC my_hello_bad;

  /* function definition, with explicit parameter list */
  static int my_hello_good (void) { return 1; }

  /* function definition with wrong param list -> compilation error */
  static int my_hello_bad (int i) { return i; }

Unfortunately, given that the Yara-provided typedefs are already pointers,
we can't do this, in standard C anyway. Type derivation only allows for
array, structure, union, function, and pointer type derivation; it does
not allow "undoing" previous derivations.

However, using gcc's "typeof" keyword, the idea is possible. Given
YR_CALLBACK_FUNC, the expression

  (YR_CALLBACK_FUNC)NULL

is a well-defined null pointer, and the function designator expression

  *(YR_CALLBACK_FUNC)NULL

has the desired function type.

Of course, evaluating this expression would be undefined behavior, but in
the GCC extension expression

  typeof (*(YR_CALLBACK_FUNC)NULL)

the operand of the "typeof" operator is never evaluated, as it does not
have a variably modified type. We can therefore use this "typeof" in the
same role as HELLO_FUNC had in the above example.

Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Message-Id: <20211011223627.20856-4-lersek@redhat.com>
Acked-by: Richard W.M. Jones <rjones@redhat.com>
[lersek@redhat.com: clean up whitespace in "YR_RULE *rule"]
2021-10-12 16:48:04 +02:00
Laszlo Ersek
3f6f2fb8f6 daemon/inspect_fs_unix: recognize modern Pardus GNU/Linux releases
Recent Pardus releases seem to have abandoned the original
"/etc/pardus-release" file, which the current Pardus detection, from
commit 233530d354 ("inspect: Add detection of Pardus.", 2010-10-29), is
based upon.

Instead, Pardus apparently adopted the "/etc/os-release" specification
<https://www.freedesktop.org/software/systemd/man/os-release.html>, with
"ID=pardus". Extend the "distro_of_os_release_id" function accordingly.
Keep the original method for recognizing earlier releases.

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1993842
Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Message-Id: <20211001125338.8956-1-lersek@redhat.com>
Acked-by: Richard W.M. Jones <rjones@redhat.com>
2021-10-01 15:34:25 +02:00
Laszlo Ersek
523b0180d8 daemon_utils_tests: generalize ocaml-hivex[-devel] lookup
Pass $(HIVEX_LIBS) with -cclib under the "daemon_utils_tests_LINK" target;
otherwise the OCaml compiler does not tell the linker where "-lhivex" can
be found, and the linking step fails if "-lhivex" is not on a system
library path.

Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Message-Id: <20210908133542.19002-3-lersek@redhat.com>
Acked-by: Richard W.M. Jones <rjones@redhat.com>
2021-09-09 14:52:03 +02:00
Laszlo Ersek
53e03eefae daemon: generalize ocaml-hivex[-devel] lookup
"ocamlc -where" is supposed to "print the location of the standard library
and exit". While this directory contains core OCaml C header files, it
does not contain hivex-related C header files. Trim "guestfsd_CPPFLAGS"
accordingly.

Furthermore, the hivex module for OCaml may exist elsewhere than under the
OCaml standard library directory. Invoke "ocamlfind query hivex" to find
this module. This is what AC_CHECK_OCAML_PKG(hivex) does too, in
"m4/guestfs-ocaml.m4" and "m4/ocaml.m4".

Signed-off-by: Laszlo Ersek <lersek@redhat.com>
Message-Id: <20210908133542.19002-2-lersek@redhat.com>
Acked-by: Richard W.M. Jones <rjones@redhat.com>
2021-09-09 14:52:02 +02:00
Richard W.M. Jones
a7245fba7a daemon/utils.c: Fix potential unbounded stack usage
utils.c: In function 'prog_exists':
utils.c:650:1: error: stack usage might be unbounded [-Werror=stack-usage=]
  650 | prog_exists (const char *prog)
      | ^
2021-09-07 15:55:48 +01:00
Richard W.M. Jones
58599031f8 daemon/xattr.c: Increase size of temporary buffer for %zu
Found by GCC -fanalyzer:

xattr.c:478:32: error: '%zu' directive output may be truncated writing between 1 and 19 bytes into a region of size 16 [-Werror=format-truncation=]
  478 |     snprintf (num, sizeof num, "%zu", nr_attrs);
      |                                ^
xattr.c:478:32: note: directive argument in the range [0, 2305843009213693950]
/usr/include/bits/stdio2.h:71:10: note: '__builtin___snprintf_chk' output between 2 and 20 bytes into a destination of size 16
   71 |   return __builtin___snprintf_chk (__s, __n, __USE_FORTIFY_LEVEL - 1,
      |          ^
2021-09-07 15:55:43 +01:00
Richard W.M. Jones
d00c36410b daemon/luks.c: Ignore bogus GCC -fanalyzer double-free warning
As far as I can tell the analysis is completely bogus.  We don't
double-free the tempfile string in do_luks_add_key.  Therefore add a
GCC suppression around the remove_temp function.

luks.c: In function 'do_luks_add_key':
luks.c:84:3: error: double-'free' of 'tempfile_14' [CWE-415] [-Werror=analyzer-double-free]
   84 |   free (tempfile);
      |   ^~~~~~~~~~~~~~~
  'do_luks_add_key': events 1-2
    |
    |  143 | do_luks_add_key (const char *device, const char *key, const char *newkey,
    |      | ^~~~~~~~~~~~~~~
    |      | |
    |      | (1) entry to 'do_luks_add_key'
    |......
    |  146 |   char *keyfile = write_key_to_temp (key);
    |      |                   ~~~~~~~~~~~~~~~~~~~~~~~
    |      |                   |
    |      |                   (2) calling 'write_key_to_temp' from 'do_luks_add_key'
    |
    +--> 'write_key_to_temp': events 3-12
           |
           |   41 | write_key_to_temp (const char *key)
           |      | ^~~~~~~~~~~~~~~~~
           |      | |
           |      | (3) entry to 'write_key_to_temp'
           |......
           |   47 |   tempfile = strdup ("/tmp/luksXXXXXX");
           |      |              ~~~~~~~~~~~~~~~~~~~~~~~~~~
           |      |              |
           |      |              (4) allocated here
           |   48 |   if (!tempfile) {
           |      |      ~
           |      |      |
           |      |      (5) assuming 'tempfile_14' is non-NULL
           |      |      (6) following 'false' branch (when 'tempfile_14' is non-NULL)...
           |......
           |   53 |   fd = mkstemp (tempfile);
           |      |   ~~
           |      |   |
           |      |   (7) ...to here
           |   54 |   if (fd == -1) {
           |      |      ~
           |      |      |
           |      |      (8) following 'false' branch...
           |......
           |   59 |   len = strlen (key);
           |      |   ~~~
           |      |   |
           |      |   (9) ...to here
           |   60 |   if (xwrite (fd, key, len) == -1) {
           |      |      ~
           |      |      |
           |      |      (10) following 'false' branch...
           |......
           |   66 |   if (close (fd) == -1) {
           |      |   ~~ ~
           |      |   |  |
           |      |   |  (12) following 'false' branch...
           |      |   (11) ...to here
           |
         'write_key_to_temp': event 13
           |
           |cc1:
           | (13): ...to here
           |
    <------+
    |
  'do_luks_add_key': events 14-17
    |
    |  146 |   char *keyfile = write_key_to_temp (key);
    |      |                   ^~~~~~~~~~~~~~~~~~~~~~~
    |      |                   |
    |      |                   (14) returning to 'do_luks_add_key' from 'write_key_to_temp'
    |  147 |   if (!keyfile)
    |      |      ~
    |      |      |
    |      |      (15) following 'false' branch...
    |......
    |  150 |   char *newkeyfile = write_key_to_temp (newkey);
    |      |   ~~~~               ~~~~~~~~~~~~~~~~~~~~~~~~~~
    |      |   |                  |
    |      |   |                  (17) calling 'write_key_to_temp' from 'do_luks_add_key'
    |      |   (16) ...to here
    |
    +--> 'write_key_to_temp': events 18-26
           |
           |   41 | write_key_to_temp (const char *key)
           |      | ^~~~~~~~~~~~~~~~~
           |      | |
           |      | (18) entry to 'write_key_to_temp'
           |......
           |   47 |   tempfile = strdup ("/tmp/luksXXXXXX");
           |      |              ~~~~~~~~~~~~~~~~~~~~~~~~~~
           |      |              |
           |      |              (19) allocated here
           |   48 |   if (!tempfile) {
           |      |      ~
           |      |      |
           |      |      (20) following 'false' branch (when 'tempfile_14' is non-NULL)...
           |......
           |   53 |   fd = mkstemp (tempfile);
           |      |   ~~
           |      |   |
           |      |   (21) ...to here
           |   54 |   if (fd == -1) {
           |      |      ~
           |      |      |
           |      |      (22) following 'false' branch...
           |......
           |   59 |   len = strlen (key);
           |      |   ~~~
           |      |   |
           |      |   (23) ...to here
           |   60 |   if (xwrite (fd, key, len) == -1) {
           |      |      ~
           |      |      |
           |      |      (24) following 'false' branch...
           |......
           |   66 |   if (close (fd) == -1) {
           |      |   ~~ ~
           |      |   |  |
           |      |   |  (26) following 'false' branch...
           |      |   (25) ...to here
           |
         'write_key_to_temp': event 27
           |
           |cc1:
           | (27): ...to here
           |
    <------+
    |
  'do_luks_add_key': events 28-32
    |
    |   84 |   free (tempfile);
    |      |   ~~~~~~~~~~~~~~~
    |      |   |
    |      |   (31) first 'free' here
    |      |   (32) second 'free' here; first 'free' was at (31)
    |......
    |  150 |   char *newkeyfile = write_key_to_temp (newkey);
    |      |                      ^~~~~~~~~~~~~~~~~~~~~~~~~~
    |      |                      |
    |      |                      (28) returning to 'do_luks_add_key' from 'write_key_to_temp'
    |  151 |   if (!newkeyfile) {
    |      |      ~
    |      |      |
    |      |      (29) following 'false' branch...
    |......
    |  156 |   const char *argv[MAX_ARGS];
    |      |   ~~~~~
    |      |   |
    |      |   (30) ...to here
    |
cc1: all warnings being treated as errors
2021-09-07 14:53:06 +01:00