diff --git a/Tests/fuset_startup_faults.c b/Tests/fuset_startup_faults.c new file mode 100644 index 00000000..afa0605a --- /dev/null +++ b/Tests/fuset_startup_faults.c @@ -0,0 +1,115 @@ +/* Scoped macOS fault injection for test_fuset_dismount.py --startup-faults. + * Copyright (c) 2026 AM Crypto. Licensed under the Apache License 2.0. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int mode_is (const char *mode) +{ + const char *fault = getenv ("VC_FUSET_TEST_FAULT"); + return fault && strcmp (fault, mode) == 0; +} + +static int fixture_path (const char *path, const char *suffix) +{ + const char *root = getenv ("VC_FUSET_TEST_ROOT"); + size_t size = strlen (path), suffix_size = strlen (suffix); + return root && strncmp (path, root, strlen (root)) == 0 + && path[strlen (root)] == '/' && size >= suffix_size + && strcmp (path + size - suffix_size, suffix) == 0; +} + +static void mark_fault (void) +{ + const char *path = getenv ("VC_FUSET_TEST_FAULT_MARKER"); + if (path) + { + int fd = open (path, O_WRONLY | O_CREAT, 0600); + if (fd != -1) + close (fd); + } +} + +static int test_connect (int fd, const struct sockaddr *address, socklen_t length) +{ + static const char prefix[] = "/private/tmp/.veracrypt-shutdown-"; + if ((mode_is ("refused") || mode_is ("rollback-blocked")) && address->sa_family == AF_UNIX + && strncmp (((const struct sockaddr_un *) address)->sun_path, prefix, sizeof (prefix) - 1) == 0) + { + mark_fault(); + const char *log = getenv ("VC_FUSET_TEST_SOCKET_LOG"); + if (log) + { + int output = open (log, O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (output != -1) + { + const char *path = ((const struct sockaddr_un *) address)->sun_path; + write (output, path, strlen (path)); + close (output); + } + } + errno = ECONNREFUSED; + return -1; + } + return connect (fd, address, length); +} + +static int test_open (const char *path, int flags, ...) +{ + if (mode_is ("metadata") && fixture_path (path, "/shutdown-socket")) + { + mark_fault(); + errno = EIO; + return -1; + } + if (flags & O_CREAT) + { + va_list args; + va_start (args, flags); + int mode = va_arg (args, int); + va_end (args); + return open (path, flags, mode); + } + return open (path, flags); +} + +static int test_stat (const char *path, struct stat *value) +{ + if (mode_is ("control") && fixture_path (path, "/control")) + { + mark_fault(); + errno = ENOENT; + return -1; + } + return stat (path, value); +} + +static int test_unmount (const char *path, int flags) +{ + const char *gate = getenv ("VC_FUSET_TEST_UNMOUNT_GATE"); + if (mode_is ("rollback-blocked") && gate && fixture_path (path, "") && access (gate, F_OK) == 0) + { + mark_fault(); + errno = EBUSY; + return -1; + } + return unmount (path, flags); +} + +#define INTERPOSE(replacement, original) \ + __attribute__((used)) static const struct { const void *replace; const void *replacee; } \ + interpose_##original __attribute__((section("__DATA,__interpose"))) = { \ + (const void *) replacement, (const void *) original } + +INTERPOSE (test_connect, connect); +INTERPOSE (test_open, open); +INTERPOSE (test_stat, stat); +INTERPOSE (test_unmount, unmount); diff --git a/Tests/test_fuset_dismount.py b/Tests/test_fuset_dismount.py new file mode 100644 index 00000000..18a43c8c --- /dev/null +++ b/Tests/test_fuset_dismount.py @@ -0,0 +1,462 @@ +#!/usr/bin/env python3 +"""Exercise macOS FUSE-T dismount using a disposable file container, without sudo. + +Usage: + python3 Tests/test_fuset_dismount.py --binary /path/to/patched/VeraCrypt + +Optional compatibility checks use binaries built from these protocol generations: + --released-binary /Applications/VeraCrypt.app/Contents/MacOS/VeraCrypt + --file-protocol-binary /path/to/d7bc65be/VeraCrypt + +An unsigned/local build can also exercise startup rollback with --startup-faults +(requires clang and permits DYLD injection only in the disposable test clients). + +Artifacts are retained in a private temporary directory. Every unmount targets +the test container explicitly. Existing volumes are never dismounted by the test. +The released-binary leg records legacy process remnants, then terminates only +the captured test processes after their filesystems have been unmounted. +""" + +import argparse +import errno +import hashlib +import json +import os +import plistlib +import signal +import socket +import struct +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import time + + +class DismountChecks: + def __init__(self, args): + self.binary = str(Path(args.binary).resolve()) + self.released = str(Path(args.released_binary).resolve()) if args.released_binary else None + self.file_protocol = str(Path(args.file_protocol_binary).resolve()) if args.file_protocol_binary else None + self.startup_faults = getattr(args, "startup_faults", False) + self.root = Path(tempfile.mkdtemp(prefix="veracrypt-dismount-test-")).resolve() + self.volume = self.root / "test.hc" + self.mountpoint = self.root / "mount" + self.tmpdir = self.root / "tmp" + self.mountpoint.mkdir() + self.tmpdir.mkdir() + self.env = dict(os.environ, TMPDIR=str(self.tmpdir) + "/") + self.results = [] + self.active = None + self.password = "Disposable-FUSE-T-test-only" + self.payload = bytes(range(256)) * 32769 + self.digest = hashlib.sha256(self.payload).hexdigest() + print("Artifacts:", self.root, flush=True) + + def record(self, entry): + self.results.append(entry) + (self.root / "results.json").write_text(json.dumps(self.results, indent=2)) + + def run(self, label, args, expected=0): + started = time.monotonic() + result = subprocess.run(list(map(str, args)), env=self.env, capture_output=True, + text=True, timeout=90) + output = result.stdout + result.stderr + (self.root / (label + ".log")).write_text(output) + self.record(dict(label=label, returncode=result.returncode, + seconds=round(time.monotonic() - started, 3), output=output)) + print(label, "exit", result.returncode, flush=True) + if expected is not None and result.returncode != expected: + raise AssertionError(f"{label}: expected {expected}, got {result.returncode}: {output}") + return result + + def vc(self, label, *args, binary=None, expected=0): + return self.run(label, [binary or self.binary, "--text", "--non-interactive", *args], expected) + + def mount(self, label, binary=None, options=()): + binary = binary or self.binary + # Retain the cleanup client even if mount fails after creating its service. + self.active = dict(binary=binary) + self.vc(label, "--mount", self.volume, self.mountpoint, + "--password=" + self.password, "--pim=1", "--keyfiles=", + "--protect-hidden=no", *options, binary=binary) + auxiliaries = [p.parent for p in self.tmpdir.glob(".veracrypt_aux_mnt*/control")] + if len(auxiliaries) != 1: + raise AssertionError(f"Expected one test service, found {auxiliaries}") + aux = auxiliaries[0] + self.active.update(aux=aux) + identity = aux / "shutdown" + if identity.exists(): + pid, serial, slot = map(int, identity.read_text().split()) + self.active.update(pid=pid, serial=serial, slot=slot) + endpoint = aux / "shutdown-socket" + if endpoint.exists(): + self.active["endpoint"] = Path(endpoint.read_text().strip()) + self.active["holders"] = self.container_holders() + + def container_holders(self): + result = subprocess.run(["/usr/sbin/lsof", "-t", str(self.volume)], + capture_output=True, text=True) + if result.returncode not in (0, 1): + raise AssertionError(result.stderr) + return sorted(set(map(int, result.stdout.split()))) + + def image(self, path): + result = subprocess.run(["/usr/bin/hdiutil", "info", "-plist"], + capture_output=True, check=True) + images = [image for image in plistlib.loads(result.stdout)["images"] + if Path(image["image-path"]).resolve() == path.resolve()] + if len(images) > 1: + raise AssertionError(images) + return images[0] if images else None + + def device(self): + image = self.image(self.active["aux"] / "volume.dmg") + if not image: + raise AssertionError("Test image is not attached") + return next(entity["dev-entry"] for entity in image["system-entities"] + if "dev-entry" in entity) + + def cleanup_released_service(self): + # The fallback restores unmounting; it cannot retrofit process teardown + # into an already-running released service. Record this limitation and + # clean only the captured test processes after all filesystems are gone. + assert not self.mounted_paths() + assert not self.image(self.active["aux"] / "volume.dmg") + holders = self.container_holders() + self.record(dict(label="released-service-remnants", holders=holders)) + assert set(holders) <= set(self.active["holders"]) + for pid in holders: + process = subprocess.run(["/bin/ps", "-p", str(pid), "-o", "uid=,args="], + capture_output=True, text=True) + if not process.stdout.strip(): + continue + uid, command = process.stdout.strip().split(None, 1) + assert int(uid) == os.getuid() + assert self.released in command or ("go-nfsv4" in command and str(self.tmpdir) in command) + os.kill(pid, signal.SIGTERM) + time.sleep(0.5) + for pid in self.container_holders(): + assert pid in holders + # Released signal handlers can also linger. All test filesystems + # are unmounted; these exact processes still hold only our fixture. + os.kill(pid, signal.SIGKILL) + self.confirm_closed("released-service-fixture-cleanup") + + def mounted_paths(self): + return [line for line in subprocess.check_output(["/sbin/mount"], text=True).splitlines() + if str(self.tmpdir) + "/" in line or f" on {self.mountpoint} (" in line] + + def confirm_closed(self, label): + deadline = time.monotonic() + 5 + while True: + handles = subprocess.run(["/usr/sbin/lsof", "-nP", str(self.volume)], + capture_output=True, text=True) + if handles.returncode not in (0, 1): + raise AssertionError(handles.stderr) + processes = subprocess.check_output(["/bin/ps", "-axo", "pid=,args="], text=True) + backend = [line for line in processes.splitlines() + if "go-nfsv4" in line and str(self.root) in line] + services = [line for line in processes.splitlines() if str(self.volume) in line] + inventory = plistlib.loads(subprocess.check_output(["/usr/bin/hdiutil", "info", "-plist"])) + images = [entry for entry in inventory["images"] + if str(self.root) in entry.get("image-path", "") + and entry["image-path"].endswith("/volume.dmg")] + alive = False + if "pid" in self.active: + try: + os.kill(self.active["pid"], 0) + alive = True + except ProcessLookupError: + pass + endpoint = self.active.get("endpoint") + state = dict(label=label, mounts=self.mounted_paths(), handles=handles.stdout, + service_alive=alive, endpoint_exists=bool(endpoint and endpoint.exists()), + backend=backend, services=services, images=images) + if not any(state[key] for key in ("mounts", "handles", "service_alive", "endpoint_exists", "backend", "services", "images")): + self.record(state) + self.active = None + return + if time.monotonic() >= deadline: + self.record(state) + raise AssertionError(state) + time.sleep(0.1) + + def unmount(self, label, binary=None, force=False): + options = ["--force"] if force else [] + self.vc(label, *options, "--unmount", self.volume, binary=binary) + self.confirm_closed(label + "-closed") + + def assert_volume_unchanged(self, before): + if self.mounted_paths() != before: + raise AssertionError("A failed preflight changed the mount table") + os.kill(self.active["pid"], 0) + if hashlib.sha256((self.mountpoint / "payload.bin").read_bytes()).hexdigest() != self.digest: + raise AssertionError("A failed preflight changed payload data") + + def expect_incompatible(self, label, force=False): + before = self.mounted_paths() + options = ["--force"] if force else [] + result = self.vc(label, *options, "--unmount", self.volume, expected=1) + if "version of VeraCrypt that mounted it" not in result.stdout + result.stderr: + raise AssertionError("Missing actionable compatibility message") + self.assert_volume_unchanged(before) + + def check_device_reuse(self): + decoy = self.root / "decoy.dmg" + mountpoint = self.root / "decoy-mount" + mountpoint.mkdir() + self.run("decoy-create", ["/usr/bin/hdiutil", "create", "-size", "32m", "-fs", "HFS+", + "-layout", "NONE", "-volname", "VC-disposable-decoy", decoy]) + for busy in (True, False): + label = "busy-device-reuse" if busy else "external-eject-device-reuse" + self.mount(label + "-mount") + old_device = self.device() + if busy: + with (self.active["aux"] / "control").open("rb") as held: + held.read(1) + result = self.vc(label + "-refused", "--unmount", self.volume, expected=1) + if "MountedVolumeInUse" not in result.stdout + result.stderr: + raise AssertionError("Busy unmount did not use MountedVolumeInUse") + else: + self.run(label + "-detach", ["/usr/bin/hdiutil", "detach", old_device]) + try: + self.run(label + "-decoy-attach", ["/usr/bin/hdiutil", "attach", decoy, + "-mountpoint", mountpoint, "-nobrowse"]) + attached = self.image(decoy) + devices = [entity.get("dev-entry") for entity in attached["system-entities"]] + if old_device not in devices: + raise AssertionError(f"Device reuse was not exercised: {old_device}, {devices}") + listing = self.vc(label + "-list", "--list", "--verbose", self.volume).stdout + if old_device in listing or str(mountpoint) in listing: + raise AssertionError("Listing retained a device now owned by another image") + marker = mountpoint / "keep-mounted.txt" + marker.write_text("This is a separate disposable disk image.\n") + with marker.open("rb") as held: + self.unmount(label + "-retry", force=not busy) + if not self.image(decoy) or not held.read(): + raise AssertionError("Retry detached the unrelated test image") + finally: + image = self.image(decoy) + if image: + device = next(entity["dev-entry"] for entity in image["system-entities"] + if "dev-entry" in entity) + self.run(label + "-decoy-cleanup", ["/usr/bin/hdiutil", "detach", device]) + + def check_socket_errors(self): + self.mount("socket-validation-mount") + state = self.active + mount_id = struct.unpack("=II", struct.pack("=Q", os.statvfs(state["aux"]).f_fsid)) + frame = [3, 0, state["pid"], state["serial"], state["slot"], 0, *mount_id] + before = self.mounted_paths() + for name, index, value, expected in (("version", 0, 999, errno.EPROTONOSUPPORT), + ("identity", 3, state["serial"] + 1, errno.EINVAL), + ("mount-instance", 6, mount_id[0] ^ 1, errno.ESTALE)): + request = frame.copy() + request[index] = value + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.settimeout(5) + client.connect(str(state["endpoint"] / "socket")) + client.sendall(struct.pack("=8Q", *request)) + result = struct.unpack("=i", client.recv(4))[0] + if result != expected: + raise AssertionError((name, result, expected)) + self.assert_volume_unchanged(before) + self.record(dict(label="socket-rejected-" + name, error=result)) + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: + client.settimeout(3) + client.connect(str(state["endpoint"] / "socket")) + client.sendall(b"\x03") + # A partial frame must expire without needing another request. + if client.recv(1): + raise AssertionError("Partial request did not expire") + self.unmount("socket-validation-unmount") + + def check_path_aliases(self): + alias = self.root / "tmp-alias" + alias.symlink_to(self.tmpdir, target_is_directory=True) + original_tmpdir = self.env["TMPDIR"] + try: + self.env["TMPDIR"] = str(alias) + "/" + for force in (False, True): + label = "alias-force" if force else "alias-normal" + self.mount(label + "-mount") + image = self.image(self.active["aux"] / "volume.dmg") + if image["image-path"] != str(self.active["aux"] / "volume.dmg"): + raise AssertionError("New image was attached through a noncanonical path") + device = self.device() + listing = self.vc(label + "-list", "--list", "--verbose", self.volume).stdout + if device not in listing or str(self.mountpoint) not in listing: + raise AssertionError("Aliased TMPDIR lost the device or mount directory") + if force: + with (self.mountpoint / "alias-write.bin").open("wb", buffering=0) as output: + output.write(self.payload) + self.unmount(label + "-unmount", force=True) + else: + self.unmount(label + "-unmount") + self.mount("alias-integrity-remount", options=("--mount-options=ro",)) + if hashlib.sha256((self.mountpoint / "alias-write.bin").read_bytes()).hexdigest() != self.digest: + raise AssertionError("Aliased forced dismount lost completed writes") + self.unmount("alias-integrity-cleanup") + + if self.released: + # A released service retains the alias in hdiutil's inventory. + # New clients must resolve it even though new mounts are canonical. + self.mount("released-alias-mount", binary=self.released) + listing = self.vc("released-alias-list", "--list", "--verbose", self.volume).stdout + if self.device() not in listing or str(self.mountpoint) not in listing: + raise AssertionError("Released service's image alias was not resolved") + self.vc("released-alias-unmount", "--unmount", self.volume) + self.cleanup_released_service() + finally: + self.env["TMPDIR"] = original_tmpdir + + def check_startup_rollback(self): + library = self.root / "startup-faults.dylib" + source = Path(__file__).with_name("fuset_startup_faults.c") + self.run("build-startup-faults", ["/usr/bin/xcrun", "clang", "-dynamiclib", "-Wall", "-Wextra", + "-O2", source, "-o", library]) + for fault in ("refused", "metadata", "control", "rollback-blocked"): + label = "startup-" + fault + socket_log = self.root / (label + "-socket.txt") + fault_marker = self.root / (label + "-fault-reached") + gate = self.root / (label + "-gate") + if fault == "rollback-blocked": + gate.touch() + self.active = dict(binary=self.binary) + fault_env = dict(DYLD_INSERT_LIBRARIES=str(library), VC_FUSET_TEST_FAULT=fault, + VC_FUSET_TEST_ROOT=str(self.root), VC_FUSET_TEST_SOCKET_LOG=str(socket_log), + VC_FUSET_TEST_UNMOUNT_GATE=str(gate), VC_FUSET_TEST_FAULT_MARKER=str(fault_marker)) + old_env = self.env + self.env = dict(old_env, **fault_env) + try: + result = self.vc(label + "-mount", "--mount", self.volume, self.mountpoint, + "--password=" + self.password, "--pim=1", "--keyfiles=", + "--protect-hidden=no", expected=1) + if not fault_marker.exists(): + raise AssertionError("Fault injection was not reached; use an unsigned/local build") + if socket_log.exists(): + self.active["endpoint"] = Path(socket_log.read_text()).parent + if fault == "rollback-blocked": + if "volume may still be accessible" not in result.stdout + result.stderr: + raise AssertionError("Failed rollback did not report the remaining partial mount") + if not self.container_holders(): + raise AssertionError("Rollback failure was not exercised") + finally: + self.env = old_env + gate.unlink(missing_ok=True) + # Removing the gate also checks that a failed rollback is retried + # by the service after the caller has already reported the failure. + self.confirm_closed(label + "-rolled-back") + self.mount(label + "-retry-mount") + self.unmount(label + "-retry-unmount") + + def checks(self): + self.vc("create", "--create", self.volume, "--size=67108864", "--volume-type=normal", + "--encryption=AES", "--hash=sha512", "--filesystem=FAT", + "--password=" + self.password, "--pim=1", "--keyfiles=", + "--random-source=/dev/urandom") + self.mount("normal-mount") + with (self.mountpoint / "payload.bin").open("wb") as output: + output.write(self.payload) + output.flush() + os.fsync(output.fileno()) + self.unmount("normal-unmount") + + self.mount("readonly-mount", options=("--mount-options=ro",)) + if hashlib.sha256((self.mountpoint / "payload.bin").read_bytes()).hexdigest() != self.digest: + raise AssertionError("Payload failed verification after remount") + self.unmount("readonly-unmount") + + self.mount("no-filesystem-mount", options=("--filesystem=none",)) + self.unmount("no-filesystem-unmount") + + self.mount("external-eject-mount") + listing = self.vc("external-eject-properties", "--list", "--verbose", self.volume).stdout + device = re.search(r"^Virtual Device: (.+)$", listing, re.M).group(1) + self.run("external-eject", ["/usr/bin/hdiutil", "detach", device]) + self.unmount("external-eject-cleanup") + + self.mount("busy-mount") + with (self.active["aux"] / "control").open("rb") as held: + held.read(1) + self.vc("busy-unmount-refused", "--unmount", self.volume, expected=1) + os.kill(self.active["pid"], 0) + self.unmount("busy-release-retry") + + self.mount("force-mount") + with (self.active["aux"] / "control").open("rb") as held: + held.read(1) + self.unmount("force-unmount", force=True) + + for iteration in range(3): + label = f"force-integrity-{iteration}" + payload = bytes([iteration + 1]) * (16 * 1024 * 1024) + self.mount(label + "-mount") + with (self.mountpoint / "unsynced.bin").open("wb", buffering=0) as output: + output.write(payload) + self.unmount(label + "-unmount", force=True) + self.mount(label + "-remount", options=("--mount-options=ro",)) + if (self.mountpoint / "unsynced.bin").read_bytes() != payload: + raise AssertionError("Forced dismount did not preserve completed writes") + self.unmount(label + "-verified") + + self.check_device_reuse() + self.check_socket_errors() + self.check_path_aliases() + if self.startup_faults: + self.check_startup_rollback() + + if self.released: + for force in (False, True): + label = "released-service-force" if force else "released-service-normal" + self.mount(label + "-mount", binary=self.released) + options = ["--force"] if force else [] + self.vc(label + "-unmount", *options, "--unmount", self.volume) + self.cleanup_released_service() + self.mount("released-client-mount") + self.unmount("released-client-unmount", binary=self.released) + + if self.file_protocol: + self.mount("file-client-mount") + self.unmount("file-client-unmount", binary=self.file_protocol) + self.mount("file-service-mount", binary=self.file_protocol) + self.expect_incompatible("file-service-preflight") + self.unmount("file-service-original-client-cleanup", binary=self.file_protocol) + + self.record(dict(result="passed", payload_sha256=self.digest)) + + def cleanup(self): + if self.active is not None: + if not self.mounted_paths() and not self.container_holders(): + self.confirm_closed("failure-already-cleaned") + return + # Older services cannot understand the new force request; use their + # original client for cleanup. Test file handles have been closed. + original = self.active["binary"] + if original == self.released: + self.vc("failure-cleanup", "--unmount", self.volume, binary=original, expected=None) + self.cleanup_released_service() + else: + self.unmount("failure-cleanup", binary=original, force=original == self.binary) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--binary", required=True) + parser.add_argument("--released-binary") + parser.add_argument("--file-protocol-binary") + parser.add_argument("--startup-faults", action="store_true") + args = parser.parse_args() + if sys.platform != "darwin" or os.geteuid() == 0: + parser.error("Run on macOS as an ordinary user with FUSE-T installed") + checks = DismountChecks(args) + try: + checks.checks() + finally: + checks.cleanup() + + +if __name__ == "__main__": + main() diff --git a/src/Common/Language.xml b/src/Common/Language.xml index f205f6f9..bfefe1a8 100644 --- a/src/Common/Language.xml +++ b/src/Common/Language.xml @@ -1691,6 +1691,8 @@ Warning: VeraCrypt could not validate the installed EFI bootloader files against one complete embedded resource set and confirm that all known required signing CAs are present in db and not listed by dbx. Firmware may reject VeraCrypt when Secure Boot is enabled.\n\nBefore booting with Secure Boot enabled, restore the required Microsoft certificates and current dbx as needed, then run VeraCrypt Repair/Reinstall. Do not remove Microsoft Corporation UEFI CA 2011 until db contains both Microsoft UEFI CA 2023 and Microsoft Option ROM UEFI CA 2023 and the actual installed files match VeraCrypt's 2023 set. This check cannot model every image-hash or security-version revocation. Make sure you have an up-to-date VeraCrypt Rescue Disk. Warning: VeraCrypt could not validate the embedded signature and known-CA compatibility of the Windows Boot Manager it chainloads (bootmgfw_ms.vc). The file may be missing, unreadable, not a Windows Boot Manager, have an unrecognized embedded signer, or use a known signing CA that is absent from db or listed by dbx. The handoff to Windows may fail when Secure Boot is enabled.\n\nComplete or repair the Windows Secure Boot certificate and boot-manager update, keep the VeraCrypt System Favorites service enabled, and run VeraCrypt Repair/Reinstall. Repair also checks Windows' serviced EFI_EX/EFI copies for a compatible current Boot Manager. If Windows cannot start, temporarily disable Secure Boot to recover. Make sure you have an up-to-date VeraCrypt Rescue Disk. Warning: The embedded signature of the Windows Boot Manager used by VeraCrypt (bootmgfw_ms.vc) is still issued by Microsoft Windows Production PCA 2011, although firmware db already contains Windows UEFI CA 2023. Its known CA is currently allowed, but it will no longer start after the PCA 2011 certificate is added to dbx.\n\nDo not apply the PCA 2011 revocation (AvailableUpdates bit 0x80, including combined value 0x280) yet. First complete the Windows 2023 boot-manager update while the VeraCrypt System Favorites service is enabled, then run VeraCrypt Repair/Reinstall so VeraCrypt can import a compatible serviced EFI_EX/EFI copy. Verify the embedded issuer of bootmgfw_ms.vc is Windows UEFI CA 2023 and make sure you have an up-to-date VeraCrypt Rescue Disk. + The service running this volume does not support the requested dismount operation.\n\nDismount the volume using the version of VeraCrypt that mounted it, then mount it again with this version. Close files using the volume if necessary. Always dismount volumes before upgrading VeraCrypt. + VeraCrypt could not complete cleanup after a failed mount. The volume may still be accessible.\n\nDismount the volume in VeraCrypt. If dismounting fails, restart the computer before relying on the volume being locked. diff --git a/src/Core/CoreException.h b/src/Core/CoreException.h index 5211c8e5..d0b81754 100644 --- a/src/Core/CoreException.h +++ b/src/Core/CoreException.h @@ -53,6 +53,8 @@ namespace VeraCrypt TC_EXCEPTION (LoopDeviceSetupFailed); \ TC_EXCEPTION (MountPointRequired); \ TC_EXCEPTION (MountPointUnavailable); \ + TC_EXCEPTION (MountServiceIncompatible); \ + TC_EXCEPTION (MountServiceCleanupFailed); \ TC_EXCEPTION (NoDriveLetterAvailable); \ TC_EXCEPTION (TemporaryDirectoryFailure); \ TC_EXCEPTION (UnsupportedSectorSizeHiddenVolumeProtection); \ diff --git a/src/Core/Unix/CoreUnix.cpp b/src/Core/Unix/CoreUnix.cpp index 34845c90..d84bace9 100644 --- a/src/Core/Unix/CoreUnix.cpp +++ b/src/Core/Unix/CoreUnix.cpp @@ -602,6 +602,12 @@ namespace VeraCrypt mountedVol->AuxMountPoint = mf.MountPoint; +#ifdef TC_MACOSX + // The control file can retain a disk number after detach. Always resolve + // the image first, before consulting the mount table for that device. + try { UpdateMountedVolumeInfo (mountedVol); } + catch (exception &e) { SystemLog::WriteException (e); } +#else if (mountedVol->MountPoint.IsEmpty() && !mountedVol->VirtualDevice.IsEmpty()) { MountedFilesystemList mpl = GetMountedFilesystems (mountedVol->VirtualDevice); @@ -612,6 +618,7 @@ namespace VeraCrypt if (mountedVol->MountPoint.IsEmpty() || mountedVol->VirtualDevice.IsEmpty()) UpdateMountedVolumeInfo (mountedVol); +#endif volumes.push_back (mountedVol); @@ -1129,9 +1136,20 @@ namespace VeraCrypt throw DeviceSectorSizeMismatch (SRC_POS, StringConverter::ToWide(devSectorSize) + L" != " + StringConverter::ToWide((uint32) volSectorSize)); } + string fuseMountPoint; +#ifdef VC_MACOSX_FUSET + // An older service may still be shutting down after its SMB mount has + // disappeared. FUSE-T also uses the pathname during backend teardown, + // so a replacement volume must have a different auxiliary path. + string mountTemplate = string (GetTempDirectory()) + "/" + GetFuseMountDirPrefix() + "-XXXXXXXXXXXX"; + vector mountDirectory (mountTemplate.begin(), mountTemplate.end()); + mountDirectory.push_back ('\0'); + throw_sys_if (mkdtemp (&mountDirectory[0]) == NULL); + fuseMountPoint = &mountDirectory[0]; + throw_sys_if (chmod (fuseMountPoint.c_str(), S_IRUSR | S_IXUSR) == -1); +#else // Find a free mount point for FUSE service MountedFilesystemList mountedFilesystems = GetMountedFilesystems (); - string fuseMountPoint; for (int i = 1; true; i++) { stringstream path; @@ -1168,6 +1186,7 @@ namespace VeraCrypt } } } +#endif #ifdef VC_MACOSX_FUSET uint64 fuseServiceSerialInstanceNumber; @@ -1175,6 +1194,14 @@ namespace VeraCrypt try { +#ifdef TC_MACOSX + // FUSE canonicalizes its mount path. Give hdiutil the same path so + // its inventory identifies the image even when TMPDIR is a symlink. + char *canonicalPath = realpath (fuseMountPoint.c_str(), NULL); + throw_sys_if (canonicalPath == NULL); + finally_do_arg (char *, canonicalPath, { free (finally_arg); }); + fuseMountPoint = canonicalPath; +#endif #ifdef VC_MACOSX_FUSET fuseServiceSerialInstanceNumber = FuseService::Mount (volume, options.SlotNumber, fuseMountPoint); #else diff --git a/src/Core/Unix/MacOSX/CoreMacOSX.cpp b/src/Core/Unix/MacOSX/CoreMacOSX.cpp index 2ddcf5e9..bce0be4f 100644 --- a/src/Core/Unix/MacOSX/CoreMacOSX.cpp +++ b/src/Core/Unix/MacOSX/CoreMacOSX.cpp @@ -96,30 +96,12 @@ namespace VeraCrypt return CFPropertyListCreateWithData (kCFAllocatorDefault, (CFDataRef) data.Get(), kCFPropertyListImmutable, nullptr, nullptr); } - static string NormalizeDiskImagePath (const string &path) + static string CanonicalizeDiskImagePath (const string &path) { - string normalized; - bool previousSlash = false; - - for (string::const_iterator i = path.begin(); i != path.end(); ++i) - { - if (*i == '/') - { - if (previousSlash) - continue; - - previousSlash = true; - } - else - previousSlash = false; - - normalized += *i; - } - - if (normalized.find ("/private/") == 0) - normalized.erase (0, 8); - - return normalized; + char *canonicalPath = realpath (path.c_str(), NULL); + throw_sys_sub_if (canonicalPath == NULL, path); + finally_do_arg (char *, canonicalPath, { free (finally_arg); }); + return canonicalPath; } // Walk a "system-entities" array (from hdiutil attach/info). Prefer the entity @@ -195,15 +177,22 @@ namespace VeraCrypt args.push_back ("-plist"); string xml = Process::Execute ("/usr/bin/hdiutil", args); - string normalizedImagePath = NormalizeDiskImagePath (imagePath); + string canonicalImagePath = CanonicalizeDiskImagePath (imagePath); + // TMPDIR aliases change the parent path, not VeraCrypt's auxiliary + // directory name or the image filename appended to it. + size_t imageSeparator = canonicalImagePath.find_last_of ('/'); + size_t auxiliarySeparator = canonicalImagePath.find_last_of ('/', imageSeparator - 1); + if (imageSeparator == string::npos || auxiliarySeparator == string::npos) + throw ParameterIncorrect (SRC_POS); + const string imageSuffix = canonicalImagePath.substr (auxiliarySeparator); CFHolder plist (ParsePropertyList (xml)); if (!plist.Get() || CFGetTypeID (plist.Get()) != CFDictionaryGetTypeID()) - return false; + throw ParameterIncorrect (SRC_POS); CFTypeRef images = CFDictionaryGetValue ((CFDictionaryRef) plist.Get(), CFSTR ("images")); // borrowed if (!images || CFGetTypeID (images) != CFArrayGetTypeID()) - return false; + throw ParameterIncorrect (SRC_POS); CFArrayRef imageArray = (CFArrayRef) images; CFIndex count = CFArrayGetCount (imageArray); @@ -211,21 +200,34 @@ namespace VeraCrypt { CFTypeRef image = CFArrayGetValueAtIndex (imageArray, i); // borrowed if (!image || CFGetTypeID (image) != CFDictionaryGetTypeID()) - continue; + throw ParameterIncorrect (SRC_POS); CFDictionaryRef imageDict = (CFDictionaryRef) image; string currentImagePath = CFDictionaryGetStdString (imageDict, "image-path"); - if (NormalizeDiskImagePath (currentImagePath) != normalizedImagePath) - continue; + if (currentImagePath.empty()) + throw ParameterIncorrect (SRC_POS); + if (currentImagePath != canonicalImagePath) + { + // Older clients attached through TMPDIR aliases. Resolve those too, + // but do not access unrelated disk images (which may be offline). + if (currentImagePath[0] != '/' || currentImagePath.size() < imageSuffix.size() + || currentImagePath.compare (currentImagePath.size() - imageSuffix.size(), imageSuffix.size(), imageSuffix) != 0) + continue; + // Failure to resolve a candidate is not proof that our image is gone. + if (CanonicalizeDiskImagePath (currentImagePath) != canonicalImagePath) + continue; + } - // Matching image found: extract from its system-entities (mirrors the - // previous behavior of returning the result for the first match). + // A missing image and an unreadable inventory are different states. + // Callers must never fall back to a cached disk number on an error. CFTypeRef entities = CFDictionaryGetValue (imageDict, CFSTR ("system-entities")); // borrowed if (!entities || CFGetTypeID (entities) != CFArrayGetTypeID()) - return false; + throw ParameterIncorrect (SRC_POS); - return ExtractDeviceAndMountPointFromEntities ((CFArrayRef) entities, device, mountPoint); + if (!ExtractDeviceAndMountPointFromEntities ((CFArrayRef) entities, device, mountPoint)) + throw ParameterIncorrect (SRC_POS); + return true; } return false; @@ -268,16 +270,32 @@ namespace VeraCrypt shared_ptr CoreMacOSX::DismountVolume (shared_ptr mountedVolume, bool ignoreOpenFiles, bool syncVolumeInfo) { - if (!mountedVolume->AuxMountPoint.IsEmpty()) - { - try - { - UpdateMountedVolumeInfo (mountedVolume); - } - catch (...) { } - } + if (!mountedVolume || mountedVolume->AuxMountPoint.IsEmpty()) + throw ParameterIncorrect (SRC_POS); +#ifdef VC_MACOSX_FUSET + // Validate the mount and check the service protocol before detaching + // the disk image. Retain its identity independently of SMB metadata. + const FuseService::DismountRequest dismountRequest = FuseService::PrepareDismount (mountedVolume->AuxMountPoint, + mountedVolume->SerialInstanceNumber, mountedVolume->SlotNumber, ignoreOpenFiles); +#endif - if (!mountedVolume->VirtualDevice.IsEmpty() && mountedVolume->VirtualDevice.IsBlockDevice()) + // Resolve ownership immediately before detach, including retries after a + // busy auxiliary unmount or an external eject. BSD disk numbers are reused. +#ifdef VC_MACOSX_FUSET + if (!FuseService::IsDismountMountPresent (dismountRequest)) + { + if (!dismountRequest.LegacyService) + FuseService::WaitForDismount (FuseService::RequestDismount (dismountRequest), mountedVolume->AuxMountPoint, mountedVolume->SlotNumber); + return mountedVolume; + } +#endif + UpdateMountedVolumeInfo (mountedVolume); + + if (!mountedVolume->VirtualDevice.IsEmpty() && mountedVolume->VirtualDevice.IsBlockDevice() +#ifdef VC_MACOSX_FUSET + && FuseService::IsDismountMountPresent (dismountRequest) +#endif + ) { list args; args.push_back ("detach"); @@ -313,29 +331,26 @@ namespace VeraCrypt sync(); VolumeInfoList ml = GetMountedVolumes (mountedVolume->Path); - if (ml.size() > 0) + if (ml.size() > 0 && ml.front()->SerialInstanceNumber == mountedVolume->SerialInstanceNumber) mountedVolume = ml.front(); } #ifdef VC_MACOSX_FUSET - pid_t fuseServiceProcessId = FuseService::RequestDismount (mountedVolume->AuxMountPoint, - mountedVolume->SerialInstanceNumber, mountedVolume->SlotNumber); -#endif - + // The service unmounts SMB while its FUSE loop can still answer requests. + if (!dismountRequest.LegacyService) + { + pid_t fuseServiceProcessId = FuseService::RequestDismount (dismountRequest); + FuseService::WaitForDismount (fuseServiceProcessId, mountedVolume->AuxMountPoint, mountedVolume->SlotNumber); + } + else + FuseService::DismountLegacy (dismountRequest); +#else list args; args.push_back ("--"); args.push_back (mountedVolume->AuxMountPoint); for (int t = 0; true; t++) { -#ifdef VC_MACOSX_FUSET - try - { - if (GetMountedFilesystems (DevicePath(), mountedVolume->AuxMountPoint).empty()) - break; - } - catch (...) { } -#endif try { Process::Execute ("/sbin/umount", args); @@ -348,9 +363,6 @@ namespace VeraCrypt Thread::Sleep (200); } } - -#ifdef VC_MACOSX_FUSET - FuseService::WaitForDismount (fuseServiceProcessId, mountedVolume->AuxMountPoint, mountedVolume->SlotNumber); #endif try @@ -364,29 +376,21 @@ namespace VeraCrypt void CoreMacOSX::UpdateMountedVolumeInfo (shared_ptr mountedVolume) const { - if (!mountedVolume || mountedVolume->AuxMountPoint.IsEmpty()) + if (!mountedVolume) return; - try - { - DevicePath recoveredVirtualDevice; - DirectoryPath recoveredMountPoint; - - if (FindDiskImageInfoByImagePath (string (mountedVolume->AuxMountPoint) + FuseService::GetVolumeImagePath(), recoveredVirtualDevice, recoveredMountPoint)) - { - if (!recoveredVirtualDevice.IsEmpty()) - { - if (mountedVolume->VirtualDevice != recoveredVirtualDevice && recoveredMountPoint.IsEmpty()) - mountedVolume->MountPoint = DirectoryPath(); - - mountedVolume->VirtualDevice = recoveredVirtualDevice; - } - - if (!recoveredMountPoint.IsEmpty()) - mountedVolume->MountPoint = recoveredMountPoint; - } - } - catch (...) { } + // Clear stale metadata even if discovery fails. Destructive callers get + // the exception; enumeration can still show the auxiliary mount for retry. + mountedVolume->VirtualDevice = DevicePath(); + mountedVolume->MountPoint = DirectoryPath(); + if (mountedVolume->AuxMountPoint.IsEmpty()) + return; + DevicePath recoveredVirtualDevice; + DirectoryPath recoveredMountPoint; + if (!FindDiskImageInfoByImagePath (string (mountedVolume->AuxMountPoint) + FuseService::GetVolumeImagePath(), recoveredVirtualDevice, recoveredMountPoint)) + return; + mountedVolume->VirtualDevice = recoveredVirtualDevice; + mountedVolume->MountPoint = recoveredMountPoint; if (mountedVolume->MountPoint.IsEmpty() && !mountedVolume->VirtualDevice.IsEmpty()) { @@ -434,6 +438,7 @@ namespace VeraCrypt void CoreMacOSX::CheckFilesystem (shared_ptr mountedVolume, bool repair) const { + UpdateMountedVolumeInfo (mountedVolume); // Honor the check-vs-repair distinction by running diskutil on the VeraCrypt // virtual device (diskutil unmounts the inner filesystem itself as needed). // The Core layer has no GUI, so results are shown in a Terminal window via a diff --git a/src/Driver/Fuse/FuseService.cpp b/src/Driver/Fuse/FuseService.cpp index 812f6e87..d344b5f4 100644 --- a/src/Driver/Fuse/FuseService.cpp +++ b/src/Driver/Fuse/FuseService.cpp @@ -34,7 +34,6 @@ #include #include #include -#include #include #include #include @@ -50,13 +49,17 @@ #include "FuseService.h" #if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) +#include #include +#include +#include +#include +#include #undef fuse_unmount #ifdef ERR_SUCCESS #undef ERR_SUCCESS #endif #endif -#include "Platform/FileStream.h" #include "Platform/MemoryStream.h" #include "Platform/Serializable.h" #include "Platform/SystemLog.h" @@ -74,14 +77,13 @@ namespace VeraCrypt static const ino_t VC_FUSE_INODE_AUX_DEVICE_INFO = 4; #if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) static const ino_t VC_FUSE_INODE_SHUTDOWN = 5; - static atomic FuseServiceShutdownRequested (false); - static Thread FuseServiceShutdownThread; - - struct FuseServiceShutdownContext - { - explicit FuseServiceShutdownContext (struct fuse *fuseHandle) : FuseHandle (fuseHandle) { } - struct fuse *FuseHandle; - }; + static const ino_t VC_FUSE_INODE_SHUTDOWN_SOCKET = 6; + static string FuseServiceShutdownDirectory; + static const char *VC_FUSE_SHUTDOWN_DIRECTORY_PREFIX = "/private/tmp/.veracrypt-shutdown-"; + static const uint64 VC_FUSE_SHUTDOWN_VERSION = 3; + static const uint64 VC_FUSE_SHUTDOWN_PROBE = 0; + static const uint64 VC_FUSE_SHUTDOWN_DISMOUNT = 1; + static const uint64 VC_FUSE_SHUTDOWN_FORCE = 1; #endif static const uint64 VC_FUSE_BLOCK_SIZE = 4096; static const uint64 VC_FUSE_METADATA_SIZE = 64 * 1024; @@ -134,6 +136,69 @@ namespace VeraCrypt return true; } + static sockaddr_un fuse_service_shutdown_address (const string &directory) + { + string path = directory + "/socket"; + sockaddr_un address; + Memory::Zero (&address, sizeof (address)); + if (path.size() >= sizeof (address.sun_path)) + throw ParameterIncorrect (SRC_POS); + address.sun_family = AF_UNIX; + address.sun_len = sizeof (address); + memcpy (address.sun_path, path.c_str(), path.size() + 1); + return address; + } + + static void fuse_service_configure_socket (int fd) + { + throw_sys_if (fcntl (fd, F_SETFD, FD_CLOEXEC) == -1); + throw_sys_if (fcntl (fd, F_SETFL, O_NONBLOCK) == -1); + int enabled = 1; + throw_sys_if (setsockopt (fd, SOL_SOCKET, SO_NOSIGPIPE, &enabled, sizeof (enabled)) == -1); + } + + typedef chrono::steady_clock FuseServiceClock; + + static int fuse_service_remaining_time (const FuseServiceClock::time_point &deadline) + { + long long remaining = chrono::duration_cast (deadline - FuseServiceClock::now()).count(); + if (remaining <= 0) + throw TimeOut (SRC_POS); + return static_cast (remaining); + } + + static bool fuse_service_socket_wait (int fd, short events, int stopFd, int timeOut) + { + const FuseServiceClock::time_point deadline = FuseServiceClock::now() + chrono::milliseconds (timeOut); + pollfd descriptors[2] = { { fd, events, 0 }, { stopFd, POLLIN, 0 } }; + int result; + do { result = poll (descriptors, stopFd == -1 ? 1 : 2, fuse_service_remaining_time (deadline)); } while (result == -1 && errno == EINTR); + throw_sys_if (result == -1); + if (result == 0) + throw TimeOut (SRC_POS); + return descriptors[1].revents == 0; + } + + static bool fuse_service_socket_transfer (int fd, void *buffer, size_t size, bool sending, int stopFd = -1, int timeOut = 10000) + { + const FuseServiceClock::time_point deadline = FuseServiceClock::now() + chrono::milliseconds (timeOut); + uint8 *position = static_cast (buffer); + while (size > 0) + { + if (!fuse_service_socket_wait (fd, sending ? POLLOUT : POLLIN, stopFd, fuse_service_remaining_time (deadline))) + return false; + ssize_t transferred = sending ? send (fd, position, size, 0) : recv (fd, position, size, 0); + if (transferred == -1 && (errno == EINTR || errno == EAGAIN)) + continue; + throw_sys_if (transferred == -1); + if (transferred == 0) + return false; + position += transferred; + size -= transferred; + } + return true; + } + static void fuse_service_unmount (struct fuse *fuseHandle) { struct fuse_session *session = fuse_get_session (fuseHandle); @@ -142,21 +207,320 @@ namespace VeraCrypt fuse_unmount (NULL, channel); } - static TC_THREAD_PROC fuse_service_shutdown (void *contextArg) + static bool fuse_service_find_mount (const char *mountPoint, fsid_t &mountId) { - unique_ptr context (static_cast (contextArg)); - - // Give the write reply a chance to reach the caller before closing the - // channel. Joining this worker in fuse_service_main protects the handle. - Thread::Sleep (100); - fuse_exit (context->FuseHandle); - fuse_service_unmount (context->FuseHandle); - - return 0; + int count = getfsstat (NULL, 0, MNT_NOWAIT); + throw_sys_if (count == -1); + for (;;) + { + vector mounts (count + 1); + count = getfsstat (&mounts[0], mounts.size() * sizeof (mounts[0]), MNT_NOWAIT); + throw_sys_if (count == -1); + if (static_cast (count) >= mounts.size()) + continue; + for (int i = 0; i < count; ++i) + if (strcmp (mounts[i].f_mntonname, mountPoint) == 0) + { + mountId = mounts[i].f_fsid; + return true; + } + return false; + } } - static int fuse_service_main (int argc, char *argv[], const struct fuse_operations *operations) + static bool fuse_service_same_mount (const fsid_t &left, const fsid_t &right) { + return left.val[0] == right.val[0] && left.val[1] == right.val[1]; + } + + class FuseServiceShutdownContext + { + public: + FuseServiceShutdownContext (struct fuse *fuseHandle, const char *mountPoint, int &startupFd) + : FuseHandle (fuseHandle), MountPoint (mountPoint), StartupFd (startupFd), ListenFd (-1), DirectoryFd (-1), DirectoryCreated (false), + ThreadStarted (false), Unmounted (false), MountSeen (false), StartupReported (false), StartupAborted (false) { } + + ~FuseServiceShutdownContext () noexcept + { + if (ThreadStarted) + { + uint8 stop = 0; + while (write (StopPipe->PeekWriteFD(), &stop, sizeof (stop)) == -1 && errno == EINTR) { } + try { ShutdownThread.Join(); } + catch (...) + { + // Destroying a context still used by the worker is unsafe. Join + // failures are fatal, but must not unwind a noexcept destructor. + SystemLog::WriteError ("Cannot join VeraCrypt FUSE shutdown worker"); + _exit (1); + } + } + if (!Unmounted) + fuse_service_unmount (FuseHandle); + if (ListenFd != -1) + close (ListenFd); + if (DirectoryCreated) + { + // The mounting user may rename the directory of an elevated service. + // Keep cleanup relative to the original directory, without following links. + if (DirectoryFd != -1) + { + unlinkat (DirectoryFd, "socket", 0); + close (DirectoryFd); + } + rmdir (Directory.c_str()); + } + } + + void Start () + { + string directoryTemplate = string (VC_FUSE_SHUTDOWN_DIRECTORY_PREFIX) + "XXXXXXXXXXXX"; + vector directory (directoryTemplate.begin(), directoryTemplate.end()); + directory.push_back ('\0'); + throw_sys_if (mkdtemp (&directory[0]) == NULL); + Directory = &directory[0]; + DirectoryCreated = true; + FuseServiceShutdownDirectory = Directory; + DirectoryFd = open (Directory.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + throw_sys_if (DirectoryFd == -1); + ListenFd = socket (AF_UNIX, SOCK_STREAM, 0); + throw_sys_if (ListenFd == -1); + fuse_service_configure_socket (ListenFd); + sockaddr_un address = fuse_service_shutdown_address (Directory); + throw_sys_if (::bind (ListenFd, reinterpret_cast (&address), sizeof (address)) == -1); + throw_sys_if (chmod (address.sun_path, 0600) == -1); + if (geteuid() == 0) + { + throw_sys_if (chown (address.sun_path, FuseService::GetUserId(), FuseService::GetGroupId()) == -1); + throw_sys_if (chown (Directory.c_str(), FuseService::GetUserId(), FuseService::GetGroupId()) == -1); + } + throw_sys_if (listen (ListenFd, 32) == -1); + StopPipe.reset (new Pipe); + throw_sys_if (fcntl (StopPipe->PeekReadFD(), F_SETFD, FD_CLOEXEC) == -1); + throw_sys_if (fcntl (StopPipe->PeekWriteFD(), F_SETFD, FD_CLOEXEC) == -1); + ShutdownThread.Start (Run, this); + ThreadStarted = true; + } + + private: + static TC_THREAD_PROC Run (void *argument) + { + FuseServiceShutdownContext &context = *static_cast (argument); + for (;;) + { + try { context.Serve(); return 0; } + catch (exception &e) { SystemLog::WriteException (e); } + catch (...) { SystemLog::WriteException (UnknownException (SRC_POS)); } + // Transient accept/getfsstat failures must not leave an apparently + // live endpoint with no worker. Back off, remaining interruptible. + pollfd stop = { context.StopPipe->PeekReadFD(), POLLIN, 0 }; + int result; + do { result = poll (&stop, 1, 1000); } while (result == -1 && errno == EINTR); + if (result > 0) + return 0; + } + } + + bool MountPresent () + { + fsid_t current; + if (!fuse_service_find_mount (MountPoint, current)) + return false; + if (!MountSeen) + { + MountId = current; + MountSeen = true; + } + return fuse_service_same_mount (MountId, current); + } + + bool StartupCancelled () + { + if (StartupFd == -1) + return false; + if (StartupAborted) + return true; + pollfd descriptor = { StartupFd, POLLIN, 0 }; + int result = poll (&descriptor, 1, 0); + if (result == 0 || (result == -1 && errno == EINTR)) + return false; + uint8 commit = 0; + ssize_t size = result > 0 ? recv (StartupFd, &commit, sizeof (commit), 0) : -1; + if (size == -1 && (errno == EINTR || errno == EAGAIN)) + return false; + if (size == sizeof (commit) && commit == 1) + { + close (StartupFd); + StartupFd = -1; + return false; + } + // EOF, a broken channel, or anything other than commit means that + // the mounting caller failed or exited before accepting this service. + StartupAborted = true; + return true; + } + + void Serve () + { + int stopFd = StopPipe->PeekReadFD(); + if (!StartupReported) + { + StartupReported = true; + pid_t processId = getpid(); + fuse_service_socket_transfer (StartupFd, &processId, sizeof (processId), true, stopFd); + } + for (;;) + { + bool present = MountPresent(); + if (StartupCancelled()) + { + // No disk image has been attached yet. Roll back independently + // of SMB metadata and the public shutdown socket, while FUSE + // can still answer the auxiliary filesystem's final requests. + if (present && unmount (MountPoint, MNT_FORCE) != 0) + { + int error = errno; + if ((error != EINVAL && error != ENOENT) || MountPresent()) + throw SystemException (SRC_POS, error); + } + FinishDismount(); + return; + } + // All clients (including released clients and Finder) can remove + // SMB without notifying us. Initial absence is not a dismount. + if (!present && MountSeen) + { + FinishDismount(); + return; + } + try + { + if (!fuse_service_socket_wait (ListenFd, POLLIN, stopFd, 1000)) + return; + } + catch (TimeOut&) { continue; } + + int fd = accept (ListenFd, NULL, NULL); + if (fd == -1 && (errno == EINTR || errno == EAGAIN || errno == ECONNABORTED)) + continue; + if (fd == -1 && (errno == EBADF || errno == EINVAL || errno == ENOTSOCK)) + { + // Retire a broken listener, but keep watching for external + // unmount. Do not advertise an endpoint that cannot answer. + close (ListenFd); + ListenFd = -1; + unlinkat (DirectoryFd, "socket", 0); + } + throw_sys_if (fd == -1); + finally_do_arg (int, fd, { close (finally_arg); }); + bool dismounted = false; + try + { + fuse_service_configure_socket (fd); + uid_t uid; + gid_t gid; + throw_sys_if (getpeereid (fd, &uid, &gid) == -1); + if (uid != 0 && uid != FuseService::GetUserId()) + continue; + + // One fixed native-endian frame: version, command, PID, serial, + // slot, flags, and the two words of the auxiliary filesystem ID. + // A partial request has an absolute deadline, so it cannot keep + // the mount watcher occupied indefinitely. + uint64 request[8]; + if (!fuse_service_socket_transfer (fd, request, sizeof (request), false, stopFd, 1000)) + continue; + bool probe = request[1] == VC_FUSE_SHUTDOWN_PROBE; + int32 error = EINVAL; + if (request[0] != VC_FUSE_SHUTDOWN_VERSION) + error = EPROTONOSUPPORT; + else if ((probe || request[1] == VC_FUSE_SHUTDOWN_DISMOUNT) + && request[2] == static_cast (getpid()) + && request[3] == FuseService::GetSerialInstanceNumber() + && request[4] == FuseService::GetSlotNumber() + && (request[5] & ~VC_FUSE_SHUTDOWN_FORCE) == 0) + { + bool present = MountPresent(); + if (!MountSeen) + error = EAGAIN; + else if (request[6] != static_cast (MountId.val[0]) + || request[7] != static_cast (MountId.val[1])) + error = ESTALE; + else + { + error = 0; + // Keep FUSE answering flush/close requests until unmount + // finishes. Never act on a replacement at the same path. + for (int attempt = 0; !probe && present; ++attempt) + { + error = unmount (MountPoint, (request[5] & VC_FUSE_SHUTDOWN_FORCE) ? MNT_FORCE : 0) == 0 ? 0 : errno; + if ((error == EINVAL || error == ENOENT) && !MountPresent()) + error = 0; + if (error != EBUSY || attempt == 10) + break; + Thread::Sleep (200); + present = MountPresent(); + if (!present) + error = 0; + } + dismounted = !probe && error == 0; + } + } + // Reply independently of the stop pipe: successful unmount can + // make the FUSE loop exit before the caller receives its result. + fuse_service_socket_transfer (fd, &error, sizeof (error), true, -1, 1000); + } + catch (TimeOut&) { } + catch (exception &e) { SystemLog::WriteException (e); } + catch (...) { SystemLog::WriteException (UnknownException (SRC_POS)); } + + if (dismounted) + { + FinishDismount(); + return; + } + } + } + + void FinishDismount () + { + fuse_exit (FuseHandle); + fuse_service_unmount (FuseHandle); + Unmounted = true; + } + + struct fuse *FuseHandle; + const char *MountPoint; + int &StartupFd; + string Directory; + int ListenFd; + int DirectoryFd; + bool DirectoryCreated; + bool ThreadStarted; + bool Unmounted; + bool MountSeen; + bool StartupReported; + bool StartupAborted; + fsid_t MountId; + unique_ptr StopPipe; + Thread ShutdownThread; + }; + + static int fuse_service_main (int argc, char *argv[], const struct fuse_operations *operations, int startupFd) + { + // On rollback, EOF must only reach the caller after fuse_destroy has + // closed the volume. The worker closes this early only after commit. + finally_do_arg (int *, &startupFd, { if (*finally_arg != -1) close (*finally_arg); }); + // FUSE-T execs its backend during setup. This child no longer needs any + // inherited descriptors across exec, including helper pipes and /dev/null. + const int descriptorLimit = getdtablesize(); + for (int fd = 3; fd < descriptorLimit; ++fd) + { + int flags = fcntl (fd, F_GETFD); + if (flags == -1 && errno == EBADF) + continue; + throw_sys_if (flags == -1 || fcntl (fd, F_SETFD, flags | FD_CLOEXEC) == -1); + } char *mountPoint = NULL; int multithreaded = 0; struct fuse *fuseHandle = fuse_setup (argc, argv, operations, sizeof (*operations), @@ -164,14 +528,17 @@ namespace VeraCrypt if (!fuseHandle) return 1; - int result = multithreaded ? fuse_loop_mt (fuseHandle) : fuse_loop (fuseHandle); - - // The loop has completed all callbacks, so no new shutdown worker can - // be started. Keep the handle alive until an existing worker has finished. - if (FuseServiceShutdownRequested.load()) - FuseServiceShutdownThread.Join(); - else - fuse_service_unmount (fuseHandle); + int result = -1; + try + { + FuseServiceShutdownContext shutdown (fuseHandle, mountPoint, startupFd); + shutdown.Start(); + result = multithreaded ? fuse_loop_mt (fuseHandle) : fuse_loop (fuseHandle); + // The context wakes and joins the socket worker before destroying the + // FUSE handle, including when the loop exits without a shutdown request. + } + catch (exception &e) { SystemLog::WriteException (e); } + catch (...) { SystemLog::WriteException (UnknownException (SRC_POS)); } // Do not call fuse_teardown: the channel has already been unmounted. fuse_remove_signal_handlers (fuse_get_session (fuseHandle)); @@ -340,6 +707,14 @@ namespace VeraCrypt statData->st_ino = VC_FUSE_INODE_SHUTDOWN; fuse_service_set_stat_blocks (statData); } + else if (strcmp (path, FuseService::GetShutdownSocketPath()) == 0) + { + statData->st_mode = S_IFREG | 0400; + statData->st_nlink = 1; + statData->st_size = FuseServiceShutdownDirectory.size() + 1; + statData->st_ino = VC_FUSE_INODE_SHUTDOWN_SOCKET; + fuse_service_set_stat_blocks (statData); + } #endif else { @@ -439,7 +814,8 @@ namespace VeraCrypt } #if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) - if (strcmp (path, FuseService::GetShutdownPath()) == 0) + if (strcmp (path, FuseService::GetShutdownPath()) == 0 + || strcmp (path, FuseService::GetShutdownSocketPath()) == 0) { fi->direct_io = 1; return 0; @@ -529,9 +905,11 @@ namespace VeraCrypt } #if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) - if (strcmp (path, FuseService::GetShutdownPath()) == 0) + if (strcmp (path, FuseService::GetShutdownPath()) == 0 + || strcmp (path, FuseService::GetShutdownSocketPath()) == 0) { - string identity = fuse_service_get_shutdown_identity(); + string identity = strcmp (path, FuseService::GetShutdownPath()) == 0 + ? fuse_service_get_shutdown_identity() : FuseServiceShutdownDirectory + "\n"; if (offset < 0) return -EINVAL; @@ -597,6 +975,8 @@ namespace VeraCrypt #if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) if (fuse_service_fill_dir_entry (buf, filler, FuseService::GetShutdownPath() + 1, S_IFREG | 0600, VC_FUSE_INODE_SHUTDOWN, 0) != 0) return 0; + if (fuse_service_fill_dir_entry (buf, filler, FuseService::GetShutdownSocketPath() + 1, S_IFREG | 0400, VC_FUSE_INODE_SHUTDOWN_SOCKET, 0) != 0) + return 0; #endif } catch (...) @@ -650,33 +1030,18 @@ namespace VeraCrypt pid_t processId; uint64 serialInstanceNumber; VolumeSlotNumber slotNumber; - struct fuse_context *context = fuse_get_context(); - - if (offset != 0 || !context || !context->fuse + if (offset != 0 || size == 0 || size > 256 || !fuse_service_parse_shutdown_identity (string (buf, size), processId, serialInstanceNumber, slotNumber) - || processId != getpid() - || serialInstanceNumber != FuseService::GetSerialInstanceNumber() + || processId != getpid() || serialInstanceNumber != FuseService::GetSerialInstanceNumber() || slotNumber != FuseService::GetSlotNumber()) return -EINVAL; - bool expected = false; - if (FuseServiceShutdownRequested.compare_exchange_strong (expected, true)) - { - try - { - unique_ptr shutdownContext (new FuseServiceShutdownContext (context->fuse)); - FuseServiceShutdownThread.Start (fuse_service_shutdown, shutdownContext.get()); - shutdownContext.release(); - } - catch (...) - { - FuseServiceShutdownRequested = false; - throw; - } - } + // This is a compatibility notification, not an instruction to + // close FUSE. The worker waits for the client's SMB unmount. return size; } #endif + } #ifdef TC_FREEBSD // FreeBSD apparently retries failed write operations forever, which may lead to a system crash. @@ -870,8 +1235,31 @@ namespace VeraCrypt const uint64 serialInstanceNumber = (uint64)tv.tv_sec * 1000000ULL + tv.tv_usec; ExecFunctor execFunctor (openVolume, slotNumber, serialInstanceNumber); +#if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) + // This inherited channel binds startup to this exact child, without + // depending on a working public socket or readable SMB metadata. + int startup[2]; + throw_sys_if (socketpair (AF_UNIX, SOCK_STREAM, 0, startup) == -1); + finally_do_arg (int *, startup, { if (finally_arg[0] != -1) close (finally_arg[0]); if (finally_arg[1] != -1) close (finally_arg[1]); }); + fuse_service_configure_socket (startup[0]); + fuse_service_configure_socket (startup[1]); + execFunctor.StartupFd = startup[1]; + execFunctor.StartupPeerFd = startup[0]; + pid_t startupProcessId = 0; + try + { +#endif Process::Execute ("fuse", args, -1, &execFunctor); +#if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) + close (startup[1]); + startup[1] = -1; + pid_t processId; + if (!fuse_service_socket_transfer (startup[0], &processId, sizeof (processId), false) || processId <= 1) + throw SystemException (SRC_POS, EPIPE); + startupProcessId = processId; +#endif + for (int t = 0; true; t++) { try @@ -890,6 +1278,45 @@ namespace VeraCrypt Thread::Sleep (100); } +#if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) + // Make sure the watcher has observed this mount before a caller can + // immediately dismount it with a released (non-notifying) client. + PrepareDismount (fuseMountPoint, serialInstanceNumber, slotNumber, false); + uint8 commit = 1; + if (!fuse_service_socket_transfer (startup[0], &commit, sizeof (commit), true)) + throw SystemException (SRC_POS, EPIPE); + } + catch (...) + { + if (startup[1] != -1) + { + close (startup[1]); + startup[1] = -1; + } + try + { + // Half-close requests rollback; retain the read end to observe + // teardown even when the original failure was a socket refusal. + throw_sys_if (shutdown (startup[0], SHUT_WR) == -1 && errno != ENOTCONN); + uint8 reply; + const FuseServiceClock::time_point deadline = FuseServiceClock::now() + chrono::seconds (10); + while (fuse_service_socket_transfer (startup[0], &reply, sizeof (reply), false, -1, fuse_service_remaining_time (deadline))) { } + if (startupProcessId > 1) + WaitForDismount (startupProcessId, fuseMountPoint, slotNumber); + } + catch (exception &e) + { + SystemLog::WriteException (e); + throw MountServiceCleanupFailed (SRC_POS, StringConverter::ToWide (fuseMountPoint)); + } + catch (...) + { + SystemLog::WriteException (UnknownException (SRC_POS)); + throw MountServiceCleanupFailed (SRC_POS, StringConverter::ToWide (fuseMountPoint)); + } + throw; + } +#endif return serialInstanceNumber; } @@ -928,34 +1355,212 @@ namespace VeraCrypt } #if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) - pid_t FuseService::RequestDismount (const DirectoryPath &fuseMountPoint, uint64 serialInstanceNumber, VolumeSlotNumber slotNumber) + static string fuse_service_read_metadata (const string &path, size_t limit) { - shared_ptr shutdownFile (new File); - shutdownFile->Open (string (fuseMountPoint) + GetShutdownPath()); - - FileStream shutdownReader (shutdownFile); - string identity = shutdownReader.ReadToEnd(); - shutdownFile->Close(); - if (identity.empty() || identity.size() > 256) + File file; + file.Open (path); + Buffer buffer (limit); + uint64 size = file.Read (buffer); + if (size == 0 || size == buffer.Size()) throw ParameterIncorrect (SRC_POS); + return string (reinterpret_cast (buffer.Ptr()), size); + } - pid_t processId; - uint64 serviceSerialInstanceNumber; - VolumeSlotNumber serviceSlotNumber; - if (!fuse_service_parse_shutdown_identity (identity, processId, serviceSerialInstanceNumber, serviceSlotNumber) - || serviceSerialInstanceNumber != serialInstanceNumber || serviceSlotNumber != slotNumber) + static bool fuse_service_request_mount_present (const FuseService::DismountRequest &request) + { + fsid_t current; + return fuse_service_find_mount (request.AuxMountPoint.c_str(), current) + && current.val[0] == request.MountId[0] && current.val[1] == request.MountId[1]; + } + + bool FuseService::IsDismountMountPresent (const DismountRequest &request) + { + return fuse_service_request_mount_present (request); + } + + static void fuse_service_validate_legacy (const FuseService::DismountRequest &request) + { + string control = fuse_service_read_metadata (request.AuxMountPoint + FuseService::GetControlPath(), 1024 * 1024); + shared_ptr stream (new MemoryStream (ConstBufferPtr (reinterpret_cast (control.data()), control.size()))); + shared_ptr volume = Serializable::DeserializeNew (stream); + if (!volume || volume->SerialInstanceNumber != request.SerialInstanceNumber || volume->SlotNumber != request.SlotNumber + || !fuse_service_request_mount_present (request)) + throw ParameterIncorrect (SRC_POS); + } + + static int fuse_service_connect_shutdown (const FuseService::DismountRequest &request) + { + // macOS also returns ECONNREFUSED for a full AF_UNIX listen backlog. + // Retry briefly; an unavailable endpoint is not a protocol mismatch. + const FuseServiceClock::time_point deadline = FuseServiceClock::now() + chrono::seconds (2); + for (;;) { - stringstream logMessage; - logMessage << "Refusing to shut down mismatched VeraCrypt FUSE service: slot=" << slotNumber - << ", auxiliary mount=" << string (fuseMountPoint); - SystemLog::WriteError (logMessage.str()); - throw ParameterIncorrect (SRC_POS); + int fd = socket (AF_UNIX, SOCK_STREAM, 0); + throw_sys_if (fd == -1); + try + { + fuse_service_configure_socket (fd); + sockaddr_un address = fuse_service_shutdown_address (request.SocketDirectory); + if (connect (fd, reinterpret_cast (&address), sizeof (address)) == -1) + { + throw_sys_if (errno != EINPROGRESS); + fuse_service_socket_wait (fd, POLLOUT, -1, fuse_service_remaining_time (deadline)); + int error; + socklen_t size = sizeof (error); + throw_sys_if (getsockopt (fd, SOL_SOCKET, SO_ERROR, &error, &size) == -1); + if (error != 0) + throw SystemException (SRC_POS, error); + } + + pid_t peerPid; + socklen_t peerPidSize = sizeof (peerPid); + throw_sys_if (getsockopt (fd, SOL_LOCAL, LOCAL_PEERPID, &peerPid, &peerPidSize) == -1); + if (peerPid != request.ProcessId) + throw ParameterIncorrect (SRC_POS); + return fd; + } + catch (SystemException &e) + { + close (fd); + if ((e.GetErrorCode() != ECONNREFUSED && e.GetErrorCode() != ENOENT) + || FuseServiceClock::now() >= deadline) + throw; + Thread::Sleep (100); + } + catch (...) + { + close (fd); + throw; + } + } + } + + static int32 fuse_service_shutdown_command (int fd, const FuseService::DismountRequest &request, uint64 command, int timeOut) + { + uint64 frame[8] = { VC_FUSE_SHUTDOWN_VERSION, command, static_cast (request.ProcessId), + request.SerialInstanceNumber, request.SlotNumber, request.IgnoreOpenFiles ? VC_FUSE_SHUTDOWN_FORCE : 0, + static_cast (request.MountId[0]), static_cast (request.MountId[1]) }; + int32 error; + if (!fuse_service_socket_transfer (fd, frame, sizeof (frame), true) + || !fuse_service_socket_transfer (fd, &error, sizeof (error), false, -1, timeOut)) + throw SystemException (SRC_POS, EPIPE); + if (error == EPROTONOSUPPORT) + throw MountServiceIncompatible (SRC_POS); + return error; + } + + FuseService::DismountRequest FuseService::PrepareDismount (const DirectoryPath &fuseMountPoint, uint64 serialInstanceNumber, VolumeSlotNumber slotNumber, bool ignoreOpenFiles) + { + DismountRequest request = {}; + request.SerialInstanceNumber = serialInstanceNumber; + request.SlotNumber = slotNumber; + request.IgnoreOpenFiles = ignoreOpenFiles; + char *canonicalPath = realpath (string (fuseMountPoint).c_str(), NULL); + throw_sys_if (canonicalPath == NULL); + finally_do_arg (char *, canonicalPath, { free (finally_arg); }); + request.AuxMountPoint = canonicalPath; + fsid_t mountId; + if (!fuse_service_find_mount (canonicalPath, mountId)) + throw SystemException (SRC_POS, ENOENT); + request.MountId[0] = mountId.val[0]; + request.MountId[1] = mountId.val[1]; + + string identity; + try { identity = fuse_service_read_metadata (request.AuxMountPoint + GetShutdownPath(), 256); } + catch (SystemException &e) + { + if (e.GetErrorCode() != ENOENT) + throw; + // Released versions have no shutdown endpoint. Validate their + // control metadata and retain the mount instance for the old flow. + // Never take this fallback for a broken or mismatched socket service. + fuse_service_validate_legacy (request); + request.LegacyService = true; + return request; } - shutdownFile->Open (string (fuseMountPoint) + GetShutdownPath(), File::OpenWrite); - shutdownFile->Write (ConstBufferPtr (reinterpret_cast (identity.data()), identity.size())); - shutdownFile->Close(); - return processId; + uint64 serviceSerialInstanceNumber; + VolumeSlotNumber serviceSlotNumber; + if (!fuse_service_parse_shutdown_identity (identity, request.ProcessId, serviceSerialInstanceNumber, serviceSlotNumber) + || serviceSerialInstanceNumber != serialInstanceNumber || serviceSlotNumber != slotNumber) + throw ParameterIncorrect (SRC_POS); + + try { request.SocketDirectory = fuse_service_read_metadata (request.AuxMountPoint + GetShutdownSocketPath(), 256); } + catch (SystemException &e) + { + // The file-only development protocol cannot keep FUSE serving + // throughout SMB unmount. Its clients can still dismount new services. + if (e.GetErrorCode() == ENOENT) + throw MountServiceIncompatible (SRC_POS); + throw; + } + const string prefix (VC_FUSE_SHUTDOWN_DIRECTORY_PREFIX); + if (request.SocketDirectory.size() != prefix.size() + 13 || request.SocketDirectory.back() != '\n' + || request.SocketDirectory.compare (0, prefix.size(), prefix) != 0 + || request.SocketDirectory.find_first_not_of ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", prefix.size()) != request.SocketDirectory.size() - 1) + throw ParameterIncorrect (SRC_POS); + request.SocketDirectory.pop_back(); + if (!fuse_service_request_mount_present (request)) + throw SystemException (SRC_POS, ESTALE); + + int fd = fuse_service_connect_shutdown (request); + finally_do_arg (int, fd, { close (finally_arg); }); + int32 error = fuse_service_shutdown_command (fd, request, VC_FUSE_SHUTDOWN_PROBE, 10000); + if (error != 0) + throw SystemException (SRC_POS, error); + return request; + } + + pid_t FuseService::RequestDismount (const DismountRequest &request) + { + try + { + // Reconnect after hdiutil detach so a long flush cannot hold open a + // preflight connection beyond the service's request deadline. + int fd = fuse_service_connect_shutdown (request); + finally_do_arg (int, fd, { close (finally_arg); }); + int32 error = fuse_service_shutdown_command (fd, request, VC_FUSE_SHUTDOWN_DISMOUNT, 60000); + if (error == EBUSY) + throw MountedVolumeInUse (SRC_POS); + if (error != 0) + throw SystemException (SRC_POS, error); + } + catch (SystemException &e) + { + // External unmount may have completed between preflight and request. + // It is only success when the captured mount instance is already gone. + if ((e.GetErrorCode() != ENOENT && e.GetErrorCode() != ECONNREFUSED && e.GetErrorCode() != EPIPE) + || fuse_service_request_mount_present (request)) + throw; + } + return request.ProcessId; + } + + void FuseService::DismountLegacy (const DismountRequest &request) + { + if (!request.LegacyService) + throw ParameterIncorrect (SRC_POS); + if (!fuse_service_request_mount_present (request)) + return; + fuse_service_validate_legacy (request); + for (int attempt = 0; ; ++attempt) + { + if (!fuse_service_request_mount_present (request)) + return; + if (unmount (request.AuxMountPoint.c_str(), request.IgnoreOpenFiles ? MNT_FORCE : 0) == 0) + return; + int error = errno; + if ((error == EINVAL || error == ENOENT) && !fuse_service_request_mount_present (request)) + return; + if (error == EBUSY && attempt < 10) + { + Thread::Sleep (200); + continue; + } + if (error == EBUSY) + throw MountedVolumeInUse (SRC_POS); + throw SystemException (SRC_POS, error); + } } void FuseService::WaitForDismount (pid_t processId, const DirectoryPath &fuseMountPoint, VolumeSlotNumber slotNumber, int timeOut) @@ -1009,6 +1614,9 @@ namespace VeraCrypt void FuseService::ExecFunctor::operator() (int argc, char *argv[]) { +#if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) + close (StartupPeerFd); +#endif FuseService::OpenVolumeInfo.SerialInstanceNumber = SerialInstanceNumber; FuseService::MountedVolume = MountedVolume; @@ -1068,6 +1676,9 @@ namespace VeraCrypt if (forkedPid == 0) { +#if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) + close (StartupFd); +#endif CloseMountedVolume(); struct sigaction action; @@ -1096,7 +1707,7 @@ namespace VeraCrypt #endif #if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) - _exit (fuse_service_main (argc, argv, &fuse_service_oper)); + _exit (fuse_service_main (argc, argv, &fuse_service_oper, StartupFd)); #elif defined(VC_FUSE3) _exit (fuse_main (argc, argv, &fuse_service_oper, nullptr)); #elif defined(TC_OPENBSD) diff --git a/src/Driver/Fuse/FuseService.h b/src/Driver/Fuse/FuseService.h index ba4be10e..600abb0b 100644 --- a/src/Driver/Fuse/FuseService.h +++ b/src/Driver/Fuse/FuseService.h @@ -28,11 +28,20 @@ namespace VeraCrypt struct ExecFunctor : public ProcessExecFunctor { ExecFunctor (shared_ptr openVolume, VolumeSlotNumber slotNumber, uint64 serialInstanceNumber) - : MountedVolume (openVolume), SlotNumber (slotNumber), SerialInstanceNumber (serialInstanceNumber) + : +#if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) + StartupFd (-1), StartupPeerFd (-1), +#endif + MountedVolume (openVolume), SlotNumber (slotNumber), SerialInstanceNumber (serialInstanceNumber) { } virtual void operator() (int argc, char *argv[]); +#if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) + int StartupFd; + int StartupPeerFd; +#endif + protected: shared_ptr MountedVolume; VolumeSlotNumber SlotNumber; @@ -51,6 +60,7 @@ namespace VeraCrypt static const char *GetVolumeImagePath (); #if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) static const char *GetShutdownPath () { return "/shutdown"; } + static const char *GetShutdownSocketPath () { return "/shutdown-socket"; } #endif static string GetDeviceType () { return "veracrypt"; } static gid_t GetGroupId () { return GroupId; } @@ -66,7 +76,22 @@ namespace VeraCrypt static void ReceiveAuxDeviceInfo (const ConstBufferPtr &buffer); static void SendAuxDeviceInfo (const DirectoryPath &fuseMountPoint, const DevicePath &virtualDevice, const DevicePath &loopDevice = DevicePath()); #if defined(TC_MACOSX) && defined(VC_MACOSX_FUSET) - static pid_t RequestDismount (const DirectoryPath &fuseMountPoint, uint64 serialInstanceNumber, VolumeSlotNumber slotNumber); + struct DismountRequest + { + pid_t ProcessId; + uint64 SerialInstanceNumber; + VolumeSlotNumber SlotNumber; + bool IgnoreOpenFiles; + bool LegacyService; + string SocketDirectory; + string AuxMountPoint; + int32 MountId[2]; + }; + + static DismountRequest PrepareDismount (const DirectoryPath &fuseMountPoint, uint64 serialInstanceNumber, VolumeSlotNumber slotNumber, bool ignoreOpenFiles); + static pid_t RequestDismount (const DismountRequest &request); + static bool IsDismountMountPresent (const DismountRequest &request); + static void DismountLegacy (const DismountRequest &request); static void WaitForDismount (pid_t processId, const DirectoryPath &fuseMountPoint, VolumeSlotNumber slotNumber, int timeOut = 10000); #endif static void WriteVolumeSectors (const ConstBufferPtr &buffer, uint64 byteOffset); diff --git a/src/Main/Forms/MainFrame.cpp b/src/Main/Forms/MainFrame.cpp index ce6d0edd..cf462b3d 100644 --- a/src/Main/Forms/MainFrame.cpp +++ b/src/Main/Forms/MainFrame.cpp @@ -20,6 +20,7 @@ #endif #include "Common/SecurityToken.h" +#include "Platform/SystemLog.h" #include "Main/Main.h" #include "Main/Resources.h" #include "Main/Application.h" @@ -817,7 +818,8 @@ namespace VeraCrypt { Gui->DismountVolumes (Core->GetMountedVolumes(), GetPreferences().ForceAutoDismount, false); } - catch (...) { } + catch (exception &e) { SystemLog::WriteException (e); } + catch (...) { SystemLog::WriteException (UnknownException (SRC_POS)); } } #endif diff --git a/src/Main/Forms/WaitDialog.cpp b/src/Main/Forms/WaitDialog.cpp index 579df614..fbcfe39b 100644 --- a/src/Main/Forms/WaitDialog.cpp +++ b/src/Main/Forms/WaitDialog.cpp @@ -58,6 +58,8 @@ namespace VeraCrypt VC_CONVERT_EXCEPTION (LoopDeviceSetupFailed); VC_CONVERT_EXCEPTION (MountPointRequired); VC_CONVERT_EXCEPTION (MountPointUnavailable); + VC_CONVERT_EXCEPTION (MountServiceIncompatible); + VC_CONVERT_EXCEPTION (MountServiceCleanupFailed); VC_CONVERT_EXCEPTION (NoDriveLetterAvailable); VC_CONVERT_EXCEPTION (TemporaryDirectoryFailure); VC_CONVERT_EXCEPTION (UnsupportedSectorSizeHiddenVolumeProtection); diff --git a/src/Main/GraphicUserInterface.cpp b/src/Main/GraphicUserInterface.cpp index 053f215b..bf033e56 100644 --- a/src/Main/GraphicUserInterface.cpp +++ b/src/Main/GraphicUserInterface.cpp @@ -26,6 +26,7 @@ #endif #include "Common/SecurityToken.h" +#include "Platform/SystemLog.h" #include "Application.h" #include "GraphicUserInterface.h" #include "FatalErrorHandler.h" @@ -234,7 +235,8 @@ namespace VeraCrypt wxBusyCursor busy; DismountVolumes (mountedVolumes, alwaysForce ? true : GetPreferences().ForceAutoDismount, false); } - catch (...) { } + catch (exception &e) { SystemLog::WriteException (e); } + catch (...) { SystemLog::WriteException (UnknownException (SRC_POS)); } if (Core->GetMountedVolumes().size() < mountedVolumeCount) OnVolumesAutoDismounted(); diff --git a/src/Main/UserInterface.cpp b/src/Main/UserInterface.cpp index c1a4675e..2a291305 100644 --- a/src/Main/UserInterface.cpp +++ b/src/Main/UserInterface.cpp @@ -218,7 +218,7 @@ namespace VeraCrypt } catch (MountedVolumeInUse&) { - if (!firstPass) + if (!firstPass || (!interactive && !twoPassMode)) throw; if (twoPassMode || !interactive) @@ -560,6 +560,8 @@ namespace VeraCrypt EX2MSG (MissingVolumeData, LangString["LINUX_EX2MSG_MISSINGVOLUMEDATA"]); EX2MSG (MountPointRequired, LangString["LINUX_EX2MSG_MOUNTPOINTREQUIRED"]); EX2MSG (MountPointUnavailable, LangString["LINUX_EX2MSG_MOUNTPOINTUNAVAILABLE"]); + EX2MSG (MountServiceIncompatible, LangString["MOUNT_SERVICE_INCOMPATIBLE"]); + EX2MSG (MountServiceCleanupFailed, LangString["MOUNT_SERVICE_CLEANUP_FAILED"]); EX2MSG (NoDriveLetterAvailable, LangString["NO_FREE_DRIVES"]); EX2MSG (PasswordEmpty, LangString["LINUX_EX2MSG_PASSWORDEMPTY"]); EX2MSG (PasswordIncorrect, LangString["PASSWORD_WRONG"]); @@ -1910,6 +1912,8 @@ const FileManager fileManagers[] = { VC_CONVERT_EXCEPTION (LoopDeviceSetupFailed); VC_CONVERT_EXCEPTION (MountPointRequired); VC_CONVERT_EXCEPTION (MountPointUnavailable); + VC_CONVERT_EXCEPTION (MountServiceIncompatible); + VC_CONVERT_EXCEPTION (MountServiceCleanupFailed); VC_CONVERT_EXCEPTION (NoDriveLetterAvailable); VC_CONVERT_EXCEPTION (TemporaryDirectoryFailure); VC_CONVERT_EXCEPTION (UnsupportedSectorSizeHiddenVolumeProtection); diff --git a/src/Platform/File.h b/src/Platform/File.h index 39b79bd7..345d7954 100644 --- a/src/Platform/File.h +++ b/src/Platform/File.h @@ -88,7 +88,7 @@ namespace VeraCrypt void SeekAt (uint64 position) const; void SeekEnd (int ofset) const; #ifndef TC_WINDOWS - void SetCloseOnExec (); + void SetCloseOnExec () const; #endif void SetLength (uint64 length) const; void Write (const ConstBufferPtr &buffer) const; diff --git a/src/Platform/Unix/File.cpp b/src/Platform/Unix/File.cpp index c1eb3461..efd5a1cc 100644 --- a/src/Platform/Unix/File.cpp +++ b/src/Platform/Unix/File.cpp @@ -412,7 +412,7 @@ namespace VeraCrypt throw_sys_sub_if (lseek (FileHandle, offset, SEEK_END) == -1, wstring (Path)); } - void File::SetCloseOnExec () + void File::SetCloseOnExec () const { if_debug (ValidateState()); int flags = fcntl (FileHandle, F_GETFD);