mirror of
https://github.com/veracrypt/VeraCrypt.git
synced 2026-09-29 03:05:35 +00:00
macOS: harden volume discovery and FUSE-T teardown
Run display discovery asynchronously and bound batched disk-image inventory queries. Filter auxiliary mounts by basename, filesystem and owner, and keep unresolved candidates separate from verified volumes. Allow targeted dismounts despite incomplete discovery while requiring complete results for slot allocation and empty-inventory decisions. Use nonthrowing GUI snapshots with monotonic freshness, completion events and safe window lifetimes. Suspend inactivity decisions while the snapshot is stale, without restarting idle timers: activity counters are cumulative per volume instance. Refresh logout targets and retry only failed ones. Show a progress dialog for interactive unmounts, but keep automatic ones synchronous, so a quit or logout request that arrives meanwhile is handled afterwards rather than refused. Guard core operations against reentry and route wait-dialog requests only from worker threads, so a main-thread message cannot wait for itself. Bind teardown to captured mount and service identities, including process start time. Report a service exit that cannot be confirmed after auxiliary mount removal as a distinct error that keeps the original details. Such volumes are not retried, and a multi-volume unmount reports all of them together with any other failure or a declined prompt. Warn about it after automatic unmounts and at quit, and keep the background application until the warning is acknowledged. Keep rollback responsive, and let services remove their auxiliary directories without probing mounted paths. Preserve released /control compatibility and perform best-effort cleanup for older services. Reap bounded subprocesses as soon as their output ends. A child that survives SIGKILL is reaped by a later call, which starts no new child until then. Keep subjects and subprocess command, status and error output when formatting exceptions for wrapping and logs. Clarify discovery and rollback diagnostics. Fix the localization-dependent busy-volume regression assertion and extend discovery, snapshot, process identity, cleanup, GUI lifecycle, inactivity and teardown coverage.
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
# macOS lifecycle regression checks
|
||||
|
||||
Run these checks on macOS with Xcode Command Line Tools and Python 3. They do not
|
||||
require administrator privileges, mounted containers, or an installed test app.
|
||||
|
||||
Build the matching VeraCrypt sources first. Use a clean build after changing
|
||||
headers: the current makefiles do not track every header dependency. The archive
|
||||
architecture must match the compiler's default architecture.
|
||||
|
||||
From the repository root, set `VC_TEST_BUILD_SRC` to the `src` directory of that
|
||||
build, then run:
|
||||
|
||||
```sh
|
||||
VC_TEST_BUILD_SRC=/absolute/path/to/build/src
|
||||
python3 Tests/test_macos_discovery.py --platform-archive "$VC_TEST_BUILD_SRC/Platform/Platform.a"
|
||||
python3 Tests/test_fuset_cleanup.py --build-dir "$VC_TEST_BUILD_SRC"
|
||||
```
|
||||
|
||||
The discovery runner compiles the production plist and batch-refresh methods
|
||||
with an in-memory inventory provider. It checks exact and legacy alias matches,
|
||||
unresolved inventory, stale-field invalidation, one query per refresh, and fresh
|
||||
discovery before destructive operations. It also runs `macos_process_test.cpp`
|
||||
against the real platform archive, checking subprocess deadlines, output limits,
|
||||
descriptor isolation, error reporting, and child reaping with its own helper
|
||||
processes. `macos_volume_state_test.cpp` includes production headers directly to
|
||||
check auxiliary mount owner/backend/basename filtering and initial, partial,
|
||||
invalidated, and stale snapshot decisions.
|
||||
|
||||
The cleanup runner compiles production cleanup and rollback methods with mocked
|
||||
mount, service, and device operations. It checks failure ordering, reporting of
|
||||
unconfirmed service exits after auxiliary-mount removal, retryable busy
|
||||
unmounts, per-volume hidden-protection refresh, and responsive probes during
|
||||
busy startup rollback. It also runs the production multi-volume unmount loop
|
||||
with scripted outcomes: every unconfirmed service exit must be reported, even
|
||||
when another volume fails or a forced-unmount prompt is declined. Finally, it
|
||||
runs `macos_cleanup_state_test.cpp` against the real serialization code to
|
||||
check that cleanup failure details survive IPC and that local display state
|
||||
leaves the legacy `/control` bytes unchanged.
|
||||
|
||||
These tests exercise state and serialization contracts. They do not establish
|
||||
real backend timing, GUI rendering, or filesystem behavior under forced unmount.
|
||||
|
||||
For an ordinary integration check with a FUSE-T GUI build, close other VeraCrypt
|
||||
processes and dismount their volumes first. In a logged-in macOS desktop session:
|
||||
|
||||
```sh
|
||||
python3 Tests/test_macos_gui_lifecycle.py --binary "$VC_TEST_BUILD_SRC/Main/VeraCrypt"
|
||||
python3 Tests/test_macos_gui_inactivity.py --binary "$VC_TEST_BUILD_SRC/Main/VeraCrypt"
|
||||
python3 Tests/test_macos_gui_teardown.py --binary "$VC_TEST_BUILD_SRC/Main/VeraCrypt"
|
||||
```
|
||||
|
||||
These use isolated preferences and disposable file containers. The lifecycle
|
||||
check verifies write/fsync/remount integrity, background startup with a mounted
|
||||
volume, refresh after a CLI dismount, and automatic GUI exit. It checks service
|
||||
exit, closed backing-file handles, and removal of the auxiliary mount and
|
||||
shutdown endpoint. The inactivity check takes about two minutes: it verifies
|
||||
that automatically unmounting one idle volume does not restart another volume's
|
||||
idle timer. The teardown check needs an unsigned local build and clang, and
|
||||
takes about three minutes. It slows a service down with `fuset_startup_faults.c`
|
||||
and verifies two automatic-unmount cases: a normal quit request that arrives
|
||||
meanwhile is honored, including unmount on quit; and when service exit cannot be
|
||||
confirmed, a warning keeps the background application from exiting silently.
|
||||
That warning stays on screen until the test ends. Failed-run artifacts are
|
||||
retained for diagnosis; use `--keep-artifacts` to retain successful runs as well.
|
||||
|
||||
Use disposable containers for ordinary create/write/fsync/unmount/remount checks,
|
||||
released-client compatibility, and user/root ownership combinations. Keep logs
|
||||
private and verify service exit, closed backing-file handles, removed auxiliary
|
||||
mounts and endpoints, and payload integrity after remounting.
|
||||
@@ -1,4 +1,5 @@
|
||||
/* Scoped macOS fault injection for test_fuset_dismount.py --startup-faults.
|
||||
/* Scoped macOS fault injection for test_fuset_dismount.py --startup-faults
|
||||
* and test_macos_gui_teardown.py (delayed service teardown).
|
||||
* Copyright (c) 2026 AM Crypto. Licensed under the Apache License 2.0.
|
||||
*/
|
||||
#include <errno.h>
|
||||
@@ -92,6 +93,12 @@ static int test_stat (const char *path, struct stat *value)
|
||||
return stat (path, value);
|
||||
}
|
||||
|
||||
static unsigned fault_delay (void)
|
||||
{
|
||||
const char *delay = getenv ("VC_FUSET_TEST_DELAY");
|
||||
return delay ? (unsigned) atoi (delay) : 10;
|
||||
}
|
||||
|
||||
static int test_unmount (const char *path, int flags)
|
||||
{
|
||||
const char *gate = getenv ("VC_FUSET_TEST_UNMOUNT_GATE");
|
||||
@@ -101,9 +108,26 @@ static int test_unmount (const char *path, int flags)
|
||||
errno = EBUSY;
|
||||
return -1;
|
||||
}
|
||||
if (mode_is ("unmount-delay") && fixture_path (path, ""))
|
||||
{
|
||||
/* The service removes SMB slowly; its caller waits for the reply. */
|
||||
mark_fault();
|
||||
sleep (fault_delay());
|
||||
}
|
||||
return unmount (path, flags);
|
||||
}
|
||||
|
||||
static int test_unlinkat (int fd, const char *path, int flags)
|
||||
{
|
||||
if (mode_is ("cleanup-delay") && (flags & AT_REMOVEDIR) && strstr (path, ".veracrypt_aux_mnt"))
|
||||
{
|
||||
/* The service outlives its caller's exit wait after SMB removal. */
|
||||
mark_fault();
|
||||
sleep (fault_delay());
|
||||
}
|
||||
return unlinkat (fd, path, flags);
|
||||
}
|
||||
|
||||
#define INTERPOSE(replacement, original) \
|
||||
__attribute__((used)) static const struct { const void *replace; const void *replacee; } \
|
||||
interpose_##original __attribute__((section("__DATA,__interpose"))) = { \
|
||||
@@ -113,3 +137,4 @@ INTERPOSE (test_connect, connect);
|
||||
INTERPOSE (test_open, open);
|
||||
INTERPOSE (test_stat, stat);
|
||||
INTERPOSE (test_unmount, unmount);
|
||||
INTERPOSE (test_unlinkat, unlinkat);
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// Exercise cleanup-failure IPC and preserve the released /control wire format.
|
||||
#include "Volume/VolumeInfo.h"
|
||||
#include "Core/CoreException.h"
|
||||
#include "Platform/MemoryStream.h"
|
||||
#include "Platform/StringConverter.h"
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <unistd.h>
|
||||
|
||||
using namespace VeraCrypt;
|
||||
|
||||
static void Require (bool condition, const char *message)
|
||||
{
|
||||
if (!condition) throw std::runtime_error (message);
|
||||
}
|
||||
|
||||
int main ()
|
||||
{
|
||||
try
|
||||
{
|
||||
shared_ptr <VolumeInfo> volume (new VolumeInfo);
|
||||
volume->EncryptionAlgorithmBlockSize = volume->EncryptionAlgorithmKeySize = volume->EncryptionAlgorithmMinBlockSize = 0;
|
||||
volume->HeaderCreationTime = volume->VolumeCreationTime = 0;
|
||||
volume->HiddenVolumeProtectionTriggered = volume->SystemEncryption = volume->MasterKeyVulnerable = false;
|
||||
volume->MinRequiredProgramVersion = volume->Pkcs5IterationCount = volume->ProgramVersion = 0;
|
||||
volume->Protection = VolumeProtection::None;
|
||||
volume->SerialInstanceNumber = 123456789;
|
||||
volume->Size = volume->TopWriteOffset = volume->TotalDataRead = volume->TotalDataWritten = 0;
|
||||
volume->SlotNumber = 7;
|
||||
volume->Type = VolumeType::Normal;
|
||||
volume->Pim = 0;
|
||||
volume->AuxMountPoint = "/private/tmp/unit-aux";
|
||||
volume->Path = VolumePath (wstring (L"/private/tmp/unit-container"));
|
||||
volume->VirtualDevice = "/dev/disk42";
|
||||
|
||||
shared_ptr <MemoryStream> controlBefore (new MemoryStream), controlAfter (new MemoryStream);
|
||||
volume->Serialize (controlBefore);
|
||||
volume->Discovery = VolumeInfo::ControlUnavailable;
|
||||
volume->Serialize (controlAfter);
|
||||
ConstBufferPtr before = *controlBefore, after = *controlAfter;
|
||||
Require (before.Size() == after.Size() && memcmp (before.Get(), after.Get(), before.Size()) == 0, "local status changed the legacy control format");
|
||||
shared_ptr <Stream> control (new MemoryStream (before));
|
||||
Require (Serializable::DeserializeNew <VolumeInfo> (control)->Discovery == VolumeInfo::DiscoveryUnknown, "local hint unexpectedly serialized");
|
||||
|
||||
shared_ptr <VolumeInfo> clone = volume->Clone();
|
||||
clone->VirtualDevice = DevicePath();
|
||||
clone->Discovery = VolumeInfo::ImageAbsent;
|
||||
Require (!volume->VirtualDevice.IsEmpty() && volume->Discovery == VolumeInfo::ControlUnavailable, "clone shared mutable fields");
|
||||
|
||||
// A core helper reports an unconfirmed service exit through the regular exception serializer.
|
||||
DismountServiceCleanupFailed failure ("unit", L"pid=1234, auxiliary mount=/private/tmp/unit-aux");
|
||||
shared_ptr <Stream> stream (new MemoryStream);
|
||||
failure.Serialize (stream);
|
||||
shared_ptr <DismountServiceCleanupFailed> restored = Serializable::DeserializeNew <DismountServiceCleanupFailed> (stream);
|
||||
Require (restored->GetSubject() == failure.GetSubject() && string (restored->what()) == "unit", "lost cleanup failure details");
|
||||
|
||||
// Wrappers and background logs format errors with ToExceptionString.
|
||||
Require (StringConverter::ToExceptionString (*restored).find (failure.GetSubject()) != wstring::npos, "formatting dropped cleanup failure details");
|
||||
ExecutedProcessFailed inventory ("unit", "/usr/bin/hdiutil", 7, "inventory-error-detail\n");
|
||||
wstring formatted = StringConverter::ToExceptionString (inventory);
|
||||
Require (formatted.find (L"/usr/bin/hdiutil (7): inventory-error-detail") != wstring::npos, "formatting dropped subprocess failure details");
|
||||
std::cout << "PASS: cleanup failure IPC and formatting, subprocess failure formatting, snapshot independence, unchanged control format\n";
|
||||
}
|
||||
catch (std::exception &e) { std::cerr << e.what() << '\n'; return 1; }
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// Read-only subprocess tests. Every child is this test executable; no mounts,
|
||||
// privilege changes, or installed VeraCrypt services are involved.
|
||||
#include "Platform/Platform.h"
|
||||
#include "Platform/Unix/Process.h"
|
||||
#include <chrono>
|
||||
#include <fcntl.h>
|
||||
#include <iostream>
|
||||
#include <signal.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
using namespace VeraCrypt;
|
||||
|
||||
static void Require (bool condition, const char *message)
|
||||
{
|
||||
if (!condition) throw std::runtime_error (message);
|
||||
}
|
||||
|
||||
static int DescriptorCount ()
|
||||
{
|
||||
int count = 0;
|
||||
for (int fd = 0; fd < 256; ++fd)
|
||||
if (fcntl (fd, F_GETFD) != -1) ++count;
|
||||
return count;
|
||||
}
|
||||
|
||||
int main (int argc, char **argv)
|
||||
{
|
||||
if (argc > 1)
|
||||
{
|
||||
std::string mode = argv[1];
|
||||
if (mode == "success")
|
||||
{
|
||||
char byte;
|
||||
if (read (STDIN_FILENO, &byte, 1) != 0 || fcntl (80, F_GETFD) != -1) return 9;
|
||||
write (STDOUT_FILENO, "complete", 8);
|
||||
return 0;
|
||||
}
|
||||
if (mode == "failure") { write (STDERR_FILENO, "expected", 8); return 7; }
|
||||
if (mode == "closed") { close (STDOUT_FILENO); close (STDERR_FILENO); sleep (5); return 0; }
|
||||
if (mode == "stream")
|
||||
{
|
||||
for (;;) { write (STDOUT_FILENO, ".", 1); usleep (100); }
|
||||
}
|
||||
if (mode == "large")
|
||||
{
|
||||
char data[8192] = {};
|
||||
for (;;) write (STDOUT_FILENO, data, sizeof (data));
|
||||
}
|
||||
sleep (5);
|
||||
return 0;
|
||||
}
|
||||
try
|
||||
{
|
||||
uint64 startTime = Process::GetProcessStartTime (getpid());
|
||||
Require (startTime != 0 && Process::IsProcessRunning (getpid(), startTime), "own process instance not recognized");
|
||||
Require (!Process::IsProcessRunning (getpid(), startTime + 1), "different process instance accepted");
|
||||
Require (Process::IsProcessRunning (getpid()), "unknown birth time discarded a live process");
|
||||
int nullFd = open ("/dev/null", O_RDONLY);
|
||||
Require (nullFd >= 0 && dup2 (nullFd, 80) == 80, "test descriptor setup");
|
||||
close (nullFd);
|
||||
int before = DescriptorCount();
|
||||
std::cout << "process: success" << std::endl;
|
||||
Require (Process::ExecuteBounded (argv[0], { "success" }, 1000) == "complete", "output/descriptor isolation");
|
||||
std::cout << "process: failure" << std::endl;
|
||||
try { Process::ExecuteBounded (argv[0], { "failure" }, 1000); throw std::runtime_error ("missing child error"); }
|
||||
catch (ExecutedProcessFailed &e) { Require (e.GetExitCode() == 7 && e.GetErrorOutput() == "expected", "child error details"); }
|
||||
for (const auto &mode : { "silent", "closed", "stream" })
|
||||
{
|
||||
std::cout << "process: " << mode << std::endl;
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
try { Process::ExecuteBounded (argv[0], { mode }, 150); throw std::runtime_error ("missing timeout"); }
|
||||
catch (TimeOut &) { }
|
||||
Require (std::chrono::steady_clock::now() - start < std::chrono::seconds (2), "deadline overrun");
|
||||
int status;
|
||||
Require (waitpid (-1, &status, WNOHANG) == -1 && errno == ECHILD, "timed-out child not reaped");
|
||||
}
|
||||
std::cout << "process: output cap" << std::endl;
|
||||
try { Process::ExecuteBounded (argv[0], { "large" }, 1000, 64); throw std::runtime_error ("missing output cap"); }
|
||||
catch (ParameterTooLarge &) { }
|
||||
int status;
|
||||
Require (waitpid (-1, &status, WNOHANG) == -1 && errno == ECHILD, "output-limited child not reaped");
|
||||
Require (DescriptorCount() == before, "descriptor leak");
|
||||
close (80);
|
||||
std::cout << "PASS: output, errors, descriptor isolation, silent/closed/stream deadlines, output cap, reaping\n";
|
||||
}
|
||||
catch (std::exception &e) { std::cerr << e.what() << '\n'; return 1; }
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Check production discovery policy without creating mounts or native windows.
|
||||
#include "Core/Unix/MountedFilesystem.h"
|
||||
#include "Main/VolumeSnapshot.h"
|
||||
#include <iostream>
|
||||
|
||||
using namespace VeraCrypt;
|
||||
|
||||
static void Require (bool condition, const char *message)
|
||||
{
|
||||
if (!condition) throw std::runtime_error (message);
|
||||
}
|
||||
|
||||
int main ()
|
||||
{
|
||||
try
|
||||
{
|
||||
VolumeSnapshotState state;
|
||||
using Clock = VolumeSnapshotState::Clock;
|
||||
using std::chrono::seconds;
|
||||
const Clock::time_point start = Clock::now();
|
||||
Require (!state.HasSample() && !state.CanConfirmEmpty (true, start), "initial empty list was authoritative");
|
||||
state.RecordSample (start, true);
|
||||
Require (state.CanConfirmEmpty (true, start + seconds (1)), "fresh complete empty list ignored");
|
||||
Require (!state.CanConfirmEmpty (false, start + seconds (1)), "nonempty list allowed auto-close");
|
||||
Require (!state.IsFresh (start + seconds (8)) && !state.CanConfirmEmpty (true, start + seconds (8)), "stale empty list allowed auto-close");
|
||||
state.RecordSample (start + seconds (8), true);
|
||||
state.Invalidate();
|
||||
Require (state.HasSample() && !state.IsFresh (start + seconds (9)) && !state.IsComplete(), "invalidated display sample remained authoritative");
|
||||
state.RecordSample (start + seconds (10), false);
|
||||
Require (state.IsFresh (start + seconds (11)) && !state.CanConfirmEmpty (true, start + seconds (11)), "partial inventory treated as complete absence");
|
||||
state.RecordSample (start + seconds (12), true);
|
||||
Require (state.HasSample() && !state.CanConfirmEmpty (true, start + seconds (18)), "slow result allowed auto-close");
|
||||
|
||||
MountedFilesystem mount;
|
||||
const string prefix = ".veracrypt_aux_mnt";
|
||||
mount.MountPoint = "/private/tmp/.veracrypt_aux_mnt-unit";
|
||||
mount.Owner = 501;
|
||||
for (const char *type : { "smbfs", "nfs", "macfuse", "osxfuse", "fusefs" })
|
||||
{
|
||||
mount.Type = type;
|
||||
Require (mount.IsAuxiliaryMountCandidate (prefix, 501, 501), "supported auxiliary backend ignored");
|
||||
}
|
||||
mount.Type = "apfs";
|
||||
Require (!mount.IsAuxiliaryMountCandidate (prefix, 501, 501), "unrelated filesystem entered discovery");
|
||||
mount.Type = "smbfs";
|
||||
mount.MountPoint = "/private/tmp/.veracrypt_aux_mnt-parent/ordinary";
|
||||
Require (!mount.IsAuxiliaryMountCandidate (prefix, 501, 501), "parent path qualified as auxiliary mount");
|
||||
mount.MountPoint = "/private/tmp/ordinary.veracrypt_aux_mnt";
|
||||
Require (!mount.IsAuxiliaryMountCandidate (prefix, 501, 501), "substring qualified as auxiliary basename");
|
||||
mount.MountPoint = "/private/tmp/.veracrypt_aux_mnt-unit";
|
||||
mount.Owner = 502;
|
||||
Require (!mount.IsAuxiliaryMountCandidate (prefix, 501, 502), "another user's mount entered discovery");
|
||||
Require (mount.IsAuxiliaryMountCandidate (prefix, 0, 502), "elevated caller lost original user's mount");
|
||||
Require (!mount.IsAuxiliaryMountCandidate (prefix, 0, 501), "root included unrelated user's mount");
|
||||
mount.Owner = 0;
|
||||
Require (mount.IsAuxiliaryMountCandidate (prefix, 501, 501), "root-owned auxiliary mount ignored");
|
||||
std::cout << "PASS: startup/partial/stale snapshot policy, auxiliary basename/backend/owner scope\n";
|
||||
}
|
||||
catch (std::exception &e) { std::cerr << e.what() << '\n'; return 1; }
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Test production cleanup state transitions with an in-memory FUSE service.
|
||||
|
||||
--build-dir is the src directory of a matching macOS build. All mount, process
|
||||
and discovery operations in this harness are mocked; it never operates on a
|
||||
real mount, service, or device.
|
||||
"""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def check_rollback(work, build_dir):
|
||||
source = (ROOT / "src/Driver/Fuse/FuseService.cpp").read_text()
|
||||
worker = source[source.index("\tclass FuseServiceShutdownContext"):source.index("\n\t// Hold the original parent")]
|
||||
worker = worker.replace("\tprivate:", "\tpublic:") # Test access to Serve; Start is never called.
|
||||
prelude = r'''
|
||||
#include "Platform/Platform.h"
|
||||
#include "Platform/Unix/Pipe.h"
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <iostream>
|
||||
#include <poll.h>
|
||||
#include <sys/mount.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/un.h>
|
||||
#include <unistd.h>
|
||||
namespace VeraCrypt {
|
||||
using FuseServiceClock=std::chrono::steady_clock;
|
||||
static const uint64 VC_FUSE_SHUTDOWN_VERSION=3, VC_FUSE_SHUTDOWN_PROBE=0, VC_FUSE_SHUTDOWN_DISMOUNT=1, VC_FUSE_SHUTDOWN_FORCE=1;
|
||||
static const char *VC_FUSE_SHUTDOWN_DIRECTORY_PREFIX="/unused-unit-path/";
|
||||
static std::string FuseServiceShutdownDirectory;
|
||||
static bool Mounted=true, Busy=true;
|
||||
static int Attempts=0, Replies=0, Reply=-1, Polls=0, Finished=0;
|
||||
static uint64 Command=VC_FUSE_SHUTDOWN_PROBE;
|
||||
struct fuse {};
|
||||
struct FuseService {
|
||||
static uid_t GetUserId(){return getuid();} static gid_t GetGroupId(){return getgid();}
|
||||
static uint64 GetSerialInstanceNumber(){return 42;} static unsigned GetSlotNumber(){return 7;}
|
||||
};
|
||||
struct SystemLog { static void WriteError(const std::string &){} static void WriteException(const std::exception &){} };
|
||||
static void fuse_exit(fuse *){++Finished;}
|
||||
static void fuse_service_unmount(fuse *){}
|
||||
static bool fuse_service_find_mount(const char *,fsid_t &id){id.val[0]=101;id.val[1]=202;return Mounted;}
|
||||
static bool fuse_service_same_mount(const fsid_t &a,const fsid_t &b){return a.val[0]==b.val[0] && a.val[1]==b.val[1];}
|
||||
static sockaddr_un fuse_service_shutdown_address(const std::string &){return {};}
|
||||
static void fuse_service_configure_socket(int){}
|
||||
static bool fuse_service_socket_wait(int,short,int,int){return Polls++==0;}
|
||||
static bool fuse_service_socket_transfer(int,void *data,size_t size,bool sending,int=-1,int=10000){
|
||||
if(!sending){
|
||||
if(size!=sizeof(uint64)*8)throw std::runtime_error("unexpected mock request");
|
||||
uint64 frame[8]={3,Command,static_cast<uint64>(getpid()),42,7,0,101,202};
|
||||
memcpy(data,frame,size);
|
||||
} else if(size==sizeof(int32)){++Replies;Reply=*static_cast<int32 *>(data);}
|
||||
return true;
|
||||
}
|
||||
static int FakeUnmount(const char *,int flags){
|
||||
++Attempts;
|
||||
if(flags!=MNT_FORCE)throw std::runtime_error("provisional rollback lost force mode");
|
||||
if(Busy){errno=EBUSY;return -1;}Mounted=false;return 0;
|
||||
}
|
||||
static int FakePoll(struct pollfd *,nfds_t,int){return 1;}
|
||||
static ssize_t FakeRecv(int,void *,size_t,int){return 0;}
|
||||
static int FakeAccept(int,struct sockaddr *,socklen_t *){return open("/dev/null",O_RDWR);}
|
||||
static int FakePeer(int,uid_t *uid,gid_t *gid){*uid=getuid();*gid=getgid();return 0;}
|
||||
#define unmount FakeUnmount
|
||||
#define poll FakePoll
|
||||
#define recv FakeRecv
|
||||
#define accept FakeAccept
|
||||
#define getpeereid FakePeer
|
||||
'''
|
||||
tests = r'''
|
||||
static void Require(bool value,const char *message){if(!value)throw std::runtime_error(message);}
|
||||
int Run(){
|
||||
for(uint64 command:{VC_FUSE_SHUTDOWN_PROBE,VC_FUSE_SHUTDOWN_DISMOUNT}){
|
||||
Mounted=Busy=true;Attempts=Replies=Polls=Finished=0;Reply=-1;Command=command;
|
||||
int startup=1000;
|
||||
FuseServiceShutdownContext worker(NULL,"/in-memory-unit-mount",startup);
|
||||
worker.StopPipe.reset(new Pipe);
|
||||
worker.StartupReported=true;
|
||||
worker.Serve();
|
||||
Require(worker.StartupAborted && Mounted && Finished==0,"busy rollback stopped FUSE");
|
||||
Require(Replies==1 && Reply==(command==VC_FUSE_SHUTDOWN_PROBE?0:EBUSY),"busy rollback starved endpoint");
|
||||
Require(Attempts==(command==VC_FUSE_SHUTDOWN_PROBE?1:2),"rollback request retry storm");
|
||||
Busy=false;worker.NextRollbackAttempt=FuseServiceClock::time_point();
|
||||
worker.Serve();
|
||||
Require(worker.Unmounted && !Mounted && Finished==1,"rollback did not resume after busy cleared");
|
||||
}
|
||||
std::cout<<"PASS: busy provisional rollback remains probeable, reports busy, and completes on retry\n";
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
int main(){try{return VeraCrypt::Run();}catch(std::exception &e){std::cerr<<e.what()<<'\n';return 1;}}
|
||||
'''
|
||||
unit = work / "rollback.cpp"
|
||||
unit.write_text(prelude + worker + tests)
|
||||
command = ["clang++", "-std=c++11", "-DTC_UNIX", "-DTC_MACOSX", "-I" + str(ROOT / "src"), str(unit), str(build_dir.resolve() / "Platform/Platform.a"), "-Wl,-dead_strip", "-o", str(work / "rollback")]
|
||||
subprocess.run(command, check=True)
|
||||
subprocess.run([str(work / "rollback")], check=True, timeout=10)
|
||||
|
||||
|
||||
def check_dismount_reporting(work, build_dir):
|
||||
source = (ROOT / "src/Main/UserInterface.cpp").read_text()
|
||||
end = source.index("\tvoid UserInterface::DisplayVolumeProperties")
|
||||
start = source.index("\tvoid UserInterface::DismountVolumes")
|
||||
helper = source.find("\tstatic void ThrowUnconfirmedCleanups")
|
||||
method = source[helper if 0 <= helper < start else start:end]
|
||||
prelude = r"""
|
||||
#include "Volume/VolumeInfo.h"
|
||||
#include "Volume/VolumeException.h"
|
||||
#include "Core/CoreException.h"
|
||||
#include "Platform/ForEach.h"
|
||||
#include "Platform/StringConverter.h"
|
||||
#include <deque>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
namespace VeraCrypt {
|
||||
struct wxString : std::wstring {
|
||||
wxString () {}
|
||||
wxString (const std::wstring &text) : std::wstring (text) {}
|
||||
bool IsEmpty () const { return empty(); }
|
||||
std::wstring ToStdWstring () const { return *this; }
|
||||
wxString &operator+= (wchar_t c) { push_back (c); return *this; }
|
||||
wxString &operator+= (const std::wstring &text) { append (text); return *this; }
|
||||
};
|
||||
struct StringFormatter {
|
||||
StringFormatter (const std::wstring &format, const std::wstring &argument) : Text (format + L" " + argument) {}
|
||||
operator std::wstring () const { return Text; }
|
||||
std::wstring Text;
|
||||
};
|
||||
static struct { std::wstring operator[] (const char *key) const { return StringConverter::ToWide (std::string (key)); } } LangString;
|
||||
enum Outcome { Unmounted, Busy, Unconfirmed, Failed };
|
||||
static std::map <std::wstring, std::deque <Outcome> > Plan;
|
||||
static bool ForceAnswer;
|
||||
class UserInterface {
|
||||
public:
|
||||
struct BusyScope { BusyScope (const UserInterface *) {} };
|
||||
void DismountVolumes (VolumeInfoList volumes, bool ignoreOpenFiles, bool interactive, bool emergencyCleanupRequested = false) const;
|
||||
shared_ptr <VolumeInfo> DismountVolumeThread (shared_ptr <VolumeInfo> volume, bool, bool = true) const {
|
||||
std::deque <Outcome> &steps = Plan[wstring (volume->Path)];
|
||||
Outcome outcome = steps.empty() ? Unmounted : steps.front();
|
||||
if (!steps.empty()) steps.pop_front();
|
||||
if (outcome == Busy) throw MountedVolumeInUse (SRC_POS);
|
||||
if (outcome == Unconfirmed) throw DismountServiceCleanupFailed (SRC_POS, L"service of " + wstring (volume->Path));
|
||||
if (outcome == Failed) throw ParameterIncorrect (SRC_POS);
|
||||
return volume;
|
||||
}
|
||||
bool AskYesNo (const std::wstring &, bool, bool) const { return ForceAnswer; }
|
||||
void ShowWarning (const std::wstring &) const {}
|
||||
void ShowInfo (const std::wstring &) const {}
|
||||
static wxString ExceptionToMessage (const exception &e) { return StringConverter::ToExceptionString (e); }
|
||||
struct { bool Verbose; } Preferences = { false };
|
||||
};
|
||||
"""
|
||||
tests = r"""
|
||||
static void Require (bool condition, const char *message) { if (!condition) throw std::runtime_error (message); }
|
||||
static VolumeInfoList Volumes () {
|
||||
VolumeInfoList volumes;
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
shared_ptr <VolumeInfo> volume (new VolumeInfo);
|
||||
volume->Path = VolumePath (wstring (i == 0 ? L"A" : L"B"));
|
||||
volume->SerialInstanceNumber = i + 1;
|
||||
volume->HiddenVolumeProtectionTriggered = false;
|
||||
volumes.push_back (volume);
|
||||
}
|
||||
return volumes;
|
||||
}
|
||||
// Returns the details reported for unconfirmed cleanups, or the name of the other outcome.
|
||||
static std::wstring Run (std::deque <Outcome> a, std::deque <Outcome> b, bool interactive, bool force = false) {
|
||||
UserInterface ui; Plan.clear(); Plan[L"A"] = a; Plan[L"B"] = b; ForceAnswer = force;
|
||||
try { ui.DismountVolumes (Volumes(), false, interactive); return L"<no error>"; }
|
||||
catch (DismountServiceCleanupFailed &e) { return e.GetSubject(); }
|
||||
catch (UserAbort &) { return L"<cancelled>"; }
|
||||
catch (MountedVolumeInUse &) { return L"<busy>"; }
|
||||
catch (ParameterIncorrect &) { return L"<failed>"; }
|
||||
}
|
||||
static bool Has (const std::wstring &text, const wchar_t *part) { return text.find (part) != std::wstring::npos; }
|
||||
int Run () {
|
||||
std::wstring r = Run ({Unconfirmed}, {Unmounted}, false);
|
||||
Require (Has (r, L"service of A"), "unconfirmed cleanup lost when the other volume unmounts");
|
||||
r = Run ({Unconfirmed}, {Busy, Busy}, false);
|
||||
Require (Has (r, L"service of A") && Has (r, L"MountedVolumeInUse"), "unconfirmed cleanup lost when the other volume stays busy");
|
||||
r = Run ({Unconfirmed}, {Failed, Failed}, false);
|
||||
Require (Has (r, L"service of A") && Has (r, L"ParameterIncorrect"), "unconfirmed cleanup lost when the other volume fails");
|
||||
r = Run ({Unconfirmed}, {Busy}, true, false);
|
||||
Require (Has (r, L"service of A"), "unconfirmed cleanup lost when forced unmount is declined");
|
||||
r = Run ({Unconfirmed}, {Unconfirmed}, false);
|
||||
Require (Has (r, L"service of A") && Has (r, L"service of B"), "only one of two unconfirmed cleanups reported");
|
||||
Require (Run ({Unmounted}, {Busy, Busy}, false) == L"<busy>", "busy volume error changed without unconfirmed cleanup");
|
||||
Require (Run ({Unmounted}, {Busy}, true, false) == L"<cancelled>", "cancellation changed without unconfirmed cleanup");
|
||||
Require (Run ({Unmounted}, {Busy, Unmounted}, true, true) == L"<no error>", "forced second pass failed");
|
||||
std::cout << "PASS: multi-volume unmount reports every unconfirmed cleanup with other failures and cancellation\n";
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
int main () { try { return VeraCrypt::Run(); } catch (std::exception &e) { std::cerr << e.what() << '\n'; return 1; } }
|
||||
"""
|
||||
unit = work / "dismount_reporting.cpp"
|
||||
unit.write_text(prelude + method + tests)
|
||||
command = ["clang++", "-std=c++11", "-DTC_UNIX", "-DTC_MACOSX"]
|
||||
command += ["-I" + str(ROOT / p) for p in ("src", "src/Crypto", "src/Common", "src/Crypto/Argon2/include")]
|
||||
command += [str(unit)] + [str(build_dir.resolve() / name) for name in ("Volume/Volume.a", "Platform/Platform.a")]
|
||||
command += ["-Wl,-dead_strip", "-o", str(work / "dismount_reporting")]
|
||||
subprocess.run(command, check=True)
|
||||
subprocess.run([str(work / "dismount_reporting")], check=True, timeout=20)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--build-dir", required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
source = (ROOT / "src/Core/Unix/MacOSX/CoreMacOSX.cpp").read_text()
|
||||
dismount = source[source.index("\tshared_ptr <VolumeInfo> CoreMacOSX::DismountVolume"):source.index("\tstatic void ClearDiskImageInfo")]
|
||||
# Reuse the fully initialized public metadata fixture from the IPC test.
|
||||
fixture = (ROOT / "Tests/macos_cleanup_state_test.cpp").read_text()
|
||||
fixture = fixture[fixture.index("\t\tshared_ptr <VolumeInfo> volume"):fixture.index("\n\t\tshared_ptr <MemoryStream> controlBefore")]
|
||||
prelude = r"""
|
||||
#include "Volume/VolumeInfo.h"
|
||||
#include "Core/CoreException.h"
|
||||
#include "Platform/MemoryStream.h"
|
||||
#include <iostream>
|
||||
#include <unistd.h>
|
||||
namespace VeraCrypt {
|
||||
enum RequestMode { RequestOk, RequestBusy, RequestLostAfterUnmount };
|
||||
static bool Mounted=true, FailWait=true, FailDiscovery=false, FailPreflight=false;
|
||||
static RequestMode Request=RequestOk;
|
||||
static int Preflights=0, Requests=0, Waits=0, Discoveries=0, Commands=0, CapturedReads=0;
|
||||
static void FakeSync() {}
|
||||
#define sync FakeSync
|
||||
struct FuseService {
|
||||
struct DismountRequest { pid_t ProcessId; uint64 ProcessStartTime, SerialInstanceNumber; unsigned SlotNumber; bool IgnoreOpenFiles, LegacyService; std::string SocketDirectory, AuxMountPoint; int32 MountId[2]; };
|
||||
static DismountRequest PrepareDismount(const DirectoryPath &aux,uint64 serial,unsigned slot,bool force) {
|
||||
++Preflights;
|
||||
if(!Mounted || FailPreflight)throw MountServiceUnavailable("mock preflight");
|
||||
DismountRequest request={}; request.ProcessId=1234; request.ProcessStartTime=987654321; request.SerialInstanceNumber=serial; request.SlotNumber=slot;
|
||||
request.AuxMountPoint=aux; request.IgnoreOpenFiles=force; request.MountId[0]=101; request.MountId[1]=202; return request;
|
||||
}
|
||||
static bool IsDismountMountPresent(const DismountRequest &) { return Mounted; }
|
||||
static pid_t RequestDismount(const DismountRequest &request) {
|
||||
++Requests;
|
||||
if(Request==RequestBusy)throw MountedVolumeInUse("mock busy");
|
||||
Mounted=false;
|
||||
if(Request==RequestLostAfterUnmount)throw MountServiceUnavailable("mock request", L"service reply lost");
|
||||
return request.ProcessId;
|
||||
}
|
||||
static void WaitForDismount(pid_t pid,const DirectoryPath &,unsigned,int,uint64 startTime) {
|
||||
++Waits; if(pid!=1234 || startTime!=987654321)throw std::runtime_error("wrong service identity");
|
||||
if(FailWait)throw DismountServiceCleanupFailed("mock timeout", L"pid=1234, auxiliary mount=/in-memory");
|
||||
}
|
||||
static void DismountLegacy(const DismountRequest &) { throw std::runtime_error("unexpected legacy path"); }
|
||||
};
|
||||
struct Process {
|
||||
static std::string Execute(const std::string &,const std::list<std::string> &) { ++Commands; throw std::runtime_error("unexpected disk command"); }
|
||||
};
|
||||
class CoreMacOSX {
|
||||
public:
|
||||
shared_ptr<VolumeInfo> DismountVolume(shared_ptr<VolumeInfo>, bool=false, bool=false);
|
||||
void UpdateMountedVolumeInfo(shared_ptr<VolumeInfo> volume) {
|
||||
++Discoveries; if(FailDiscovery)throw VolumeDiscoveryFailed("mock inventory");
|
||||
volume->VirtualDevice=DevicePath(); volume->MountPoint=DirectoryPath();
|
||||
}
|
||||
shared_ptr<VolumeInfo> ValidateMountedVolume(shared_ptr<VolumeInfo> volume) const { ++CapturedReads; return volume; }
|
||||
};
|
||||
"""
|
||||
tests = r"""
|
||||
static void Require(bool condition,const char *message) { if(!condition)throw std::runtime_error(message); }
|
||||
int Run() {
|
||||
auto volume=MakeVolume(); CoreMacOSX core;
|
||||
FailPreflight=true;
|
||||
try { core.DismountVolume(volume); throw std::runtime_error("preflight ignored"); }
|
||||
catch(MountServiceUnavailable &) {}
|
||||
Require(Discoveries==0 && Requests==0, "operation after failed preflight");
|
||||
FailPreflight=false; FailDiscovery=true;
|
||||
try { core.DismountVolume(volume); throw std::runtime_error("unknown inventory ignored"); }
|
||||
catch(VolumeDiscoveryFailed &) {}
|
||||
Require(Requests==0, "unmounted with unknown image ownership");
|
||||
FailDiscovery=false;
|
||||
try { core.DismountVolume(volume); throw std::runtime_error("cleanup reported as complete"); }
|
||||
catch(DismountServiceCleanupFailed &e) {
|
||||
Require(e.GetSubject().find(L"pid=1234, auxiliary mount=/in-memory")!=std::wstring::npos, "cleanup error lost service details");
|
||||
}
|
||||
Require(!Mounted && Requests==1 && Waits==1, "service exit was not awaited after SMB removal");
|
||||
Mounted=true; FailWait=false; Request=RequestLostAfterUnmount;
|
||||
try { core.DismountVolume(volume); throw std::runtime_error("lost request after SMB removal reported as complete"); }
|
||||
catch(DismountServiceCleanupFailed &e) {
|
||||
Require(e.GetSubject().find(L"service reply lost")!=std::wstring::npos, "cleanup error lost request details");
|
||||
}
|
||||
Mounted=true; Request=RequestBusy;
|
||||
try { core.DismountVolume(volume); throw std::runtime_error("busy auxiliary unmount reported as complete"); }
|
||||
catch(MountedVolumeInUse &) {}
|
||||
Require(Mounted, "busy auxiliary unmount changed the mount");
|
||||
Request=RequestOk; volume->Protection=VolumeProtection::HiddenVolumeReadOnly;
|
||||
core.DismountVolume(volume);
|
||||
Require(CapturedReads==1 && !Mounted && Commands==0, "hidden-protection refresh did not use captured volume");
|
||||
std::cout << "PASS: preflight/discovery failures stop teardown, unconfirmed exits keep details, busy SMB stays retryable, per-volume hidden-protection refresh\n";
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
int main() { try { return VeraCrypt::Run(); } catch(std::exception &e) { std::cerr<<e.what()<<'\n'; return 1; } }
|
||||
"""
|
||||
with tempfile.TemporaryDirectory(prefix="vc-cleanup-unit-") as temporary:
|
||||
work = Path(temporary)
|
||||
unit = work / "cleanup.cpp"
|
||||
unit.write_text(prelude + dismount + "\nstatic shared_ptr<VolumeInfo> MakeVolume() {\n" + fixture + "\nreturn volume;\n}\n" + tests)
|
||||
command = ["clang++", "-std=c++11", "-DTC_UNIX", "-DTC_MACOSX", "-DVC_MACOSX_FUSET"]
|
||||
command += ["-I" + str(ROOT / p) for p in ("src", "src/Crypto", "src/Common", "src/Crypto/Argon2/include")]
|
||||
command += [str(unit)] + [str(args.build_dir.resolve() / name) for name in ("Core/Core.a", "Volume/Volume.a", "Platform/Platform.a")]
|
||||
command += ["-Wl,-dead_strip", "-o", str(work / "cleanup")]
|
||||
subprocess.run(command, check=True)
|
||||
subprocess.run([str(work / "cleanup")], check=True, timeout=20)
|
||||
ipc_command = ["clang++", "-std=c++11", "-DTC_UNIX", "-DTC_MACOSX"]
|
||||
ipc_command += ["-I" + str(ROOT / p) for p in ("src", "src/Crypto", "src/Common", "src/Crypto/Argon2/include")]
|
||||
ipc_command += [str(ROOT / "Tests/macos_cleanup_state_test.cpp")]
|
||||
# The test references no other symbol from the object that registers core
|
||||
# exception types for IPC, so the archive alone would not link it.
|
||||
ipc_command += [str(args.build_dir.resolve() / name) for name in ("Core/CoreException.o", "Core/Core.a", "Volume/Volume.a", "Platform/Platform.a")]
|
||||
ipc_command += ["-Wl,-dead_strip", "-o", str(work / "ipc")]
|
||||
subprocess.run(ipc_command, check=True)
|
||||
subprocess.run([str(work / "ipc")], check=True, timeout=20)
|
||||
check_rollback(work, args.build_dir)
|
||||
check_dismount_reporting(work, args.build_dir)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -217,8 +217,11 @@ class DismountChecks:
|
||||
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")
|
||||
# CLI errors are localized. Check the refusal and retained
|
||||
# service instead of its internal C++ exception name.
|
||||
os.kill(self.active["pid"], 0)
|
||||
if not any(f" on {self.active['aux']} (" in line for line in self.mounted_paths()):
|
||||
raise AssertionError("Busy unmount removed the auxiliary mount")
|
||||
else:
|
||||
self.run(label + "-detach", ["/usr/bin/hdiutil", "detach", old_device])
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit checks for macOS discovery; no mounted volumes or sudo needed.
|
||||
|
||||
Compiles the production plist helpers and batch-refresh methods with a fake
|
||||
inventory provider, so tests can supply incomplete inventories safely. Optional
|
||||
--platform-archive runs the real bounded process runner from a matching build.
|
||||
"""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--platform-archive", type=Path)
|
||||
args = parser.parse_args()
|
||||
with tempfile.TemporaryDirectory(prefix="vc-discovery-unit-") as temporary:
|
||||
work = Path(temporary)
|
||||
image = work / ".veracrypt_aux_mnt-test" / "volume.dmg"
|
||||
image.parent.mkdir()
|
||||
image.touch()
|
||||
alias = work / "path-alias"
|
||||
alias.symlink_to(work, target_is_directory=True)
|
||||
exact = dict(**{"image-path": str(image.resolve()), "system-entities": [{"dev-entry": "/dev/disk42", "mount-point": "/Volumes/unit"}]})
|
||||
alias_image = dict(exact, **{"image-path": str(alias / image.relative_to(work))})
|
||||
unknown_alias = dict(exact, **{"image-path": str(work / "missing" / image.parent.name / image.name)})
|
||||
cases = {
|
||||
"exact": {"images": [exact]},
|
||||
"alias": {"images": [alias_image]},
|
||||
"absent": {"images": []},
|
||||
"unrelated": {"images": [{"image-path": "/offline/unrelated.dmg"}]},
|
||||
"exact_after_unknown": {"images": [unknown_alias, {}, exact]},
|
||||
"unknown_alias": {"images": [unknown_alias]},
|
||||
"unknown_record": {"images": [{}]},
|
||||
"bad_entities": {"images": [{"image-path": str(image.resolve())}]},
|
||||
}
|
||||
for name, contents in cases.items():
|
||||
(work / name).write_bytes(plistlib.dumps(contents))
|
||||
(work / "broken").write_text("invalid plist")
|
||||
|
||||
source = (ROOT / "src/Core/Unix/MacOSX/CoreMacOSX.cpp").read_text()
|
||||
helpers = source[source.index("\tclass CFHolder"):source.index("\tstatic bool AuxiliaryControlFileHasVirtualDevice")]
|
||||
refresh = source[source.index("\tstatic void ClearDiskImageInfo"):source.index("\t// Strict /dev/diskN")]
|
||||
prelude = r'''
|
||||
#include "Platform/Finally.h"
|
||||
#include <CoreFoundation/CoreFoundation.h>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#define throw_sys_sub_if(condition, subject) do { if (condition) throw std::runtime_error(subject); } while(false)
|
||||
using DevicePath = std::string;
|
||||
struct DirectoryPath : std::string {
|
||||
using std::string::string;
|
||||
DirectoryPath() {}
|
||||
DirectoryPath(const std::string &s) : std::string(s) {}
|
||||
bool IsEmpty() const { return empty(); }
|
||||
};
|
||||
struct ParameterIncorrect : std::runtime_error { ParameterIncorrect(const std::string &s) : std::runtime_error(s) {} };
|
||||
struct VolumeDiscoveryFailed : std::runtime_error { VolumeDiscoveryFailed(const std::string &s, const std::wstring &) : std::runtime_error(s) {} };
|
||||
struct StringConverter {
|
||||
static std::string Trim(std::string s) { size_t b=s.find_first_not_of(" \t\r\n"); if(b==std::string::npos)return ""; return s.substr(b,s.find_last_not_of(" \t\r\n")-b+1); }
|
||||
static std::wstring ToExceptionString(const std::exception &) { return L"failure"; }
|
||||
};
|
||||
static std::string Inventory;
|
||||
static int Queries;
|
||||
struct Process { static std::string ExecuteBounded(const std::string &, const std::list<std::string> &, int deadline) { if(deadline!=2000)throw std::runtime_error("discovery deadline"); ++Queries; return Inventory; } };
|
||||
struct FuseService { static std::string GetVolumeImagePath() { return "/volume.dmg"; } };
|
||||
struct SystemLog { static void WriteException(const std::exception &) {} };
|
||||
#define foreach(declaration, collection) for (declaration : collection)
|
||||
struct VolumeInfo {
|
||||
enum DiscoveryState { DiscoveryUnknown, ImageAttached, ImageAbsent, ControlUnavailable };
|
||||
DiscoveryState Discovery = DiscoveryUnknown;
|
||||
DirectoryPath AuxMountPoint, MountPoint;
|
||||
DevicePath VirtualDevice;
|
||||
};
|
||||
using VolumeInfoList = std::list<std::shared_ptr<VolumeInfo>>;
|
||||
struct MountedFilesystem { DirectoryPath MountPoint; };
|
||||
using MountedFilesystemList = std::list<std::shared_ptr<MountedFilesystem>>;
|
||||
class CoreMacOSX {
|
||||
public:
|
||||
void UpdateMountedVolumesInfo(VolumeInfoList &) const;
|
||||
void UpdateMountedVolumeInfo(std::shared_ptr<VolumeInfo>) const;
|
||||
void UpdateMountedVolumeInfo(std::shared_ptr<VolumeInfo>, const std::string &) const;
|
||||
MountedFilesystemList GetMountedFilesystems(const DevicePath &) const { return {}; }
|
||||
};
|
||||
'''
|
||||
# Production path types expose IsEmpty(); keep that interface in the mock.
|
||||
prelude = prelude.replace("using DevicePath = std::string;", "")
|
||||
prelude = prelude.replace("struct ParameterIncorrect", "using DevicePath = DirectoryPath;\nstruct ParameterIncorrect")
|
||||
tests = r'''
|
||||
static void Require(bool condition, const char *message) { if(!condition)throw std::runtime_error(message); }
|
||||
static std::string Read(const std::string &path) { std::ifstream f(path); return std::string(std::istreambuf_iterator<char>(f), {}); }
|
||||
int main(int argc, char **argv) {
|
||||
try {
|
||||
std::string root=argv[1], image=argv[2];
|
||||
for (const auto &name : {"exact", "alias", "exact_after_unknown"}) {
|
||||
DevicePath device; DirectoryPath mount;
|
||||
Require(FindDiskImageInfoByImagePath(Read(root+"/"+name),image,device,mount), "positive match lost");
|
||||
Require(device=="/dev/disk42" && mount=="/Volumes/unit", "wrong mapping");
|
||||
}
|
||||
for (const auto &name : {"absent", "unrelated"}) {
|
||||
DevicePath device; DirectoryPath mount;
|
||||
Require(!FindDiskImageInfoByImagePath(Read(root+"/"+name),image,device,mount), "false match");
|
||||
}
|
||||
for (const auto &name : {"unknown_alias", "unknown_record", "bad_entities", "broken"}) {
|
||||
bool failed=false; DevicePath device; DirectoryPath mount;
|
||||
try { FindDiskImageInfoByImagePath(Read(root+"/"+name),image,device,mount); }
|
||||
catch(std::exception &) { failed=true; }
|
||||
Require(failed, "unknown inventory treated as absent");
|
||||
}
|
||||
VolumeInfoList volumes;
|
||||
for(int i=0;i<3;++i) { auto volume=std::make_shared<VolumeInfo>(); volume->AuxMountPoint=image.substr(0,image.rfind('/')); volumes.push_back(volume); }
|
||||
CoreMacOSX core;
|
||||
Queries=0; Inventory=Read(root+"/exact"); core.UpdateMountedVolumesInfo(volumes);
|
||||
Require(Queries==1, "more than one inventory per enumeration");
|
||||
for(auto volume:volumes)Require(volume->Discovery==VolumeInfo::ImageAttached, "attached status");
|
||||
Inventory=Read(root+"/broken"); core.UpdateMountedVolumesInfo(volumes);
|
||||
for(auto volume:volumes)Require(volume->Discovery==VolumeInfo::DiscoveryUnknown && volume->VirtualDevice.empty() && volume->MountPoint.empty(), "stale device survived failure");
|
||||
Inventory=Read(root+"/absent"); core.UpdateMountedVolumesInfo(volumes);
|
||||
for(auto volume:volumes)Require(volume->Discovery==VolumeInfo::ImageAbsent, "absent status");
|
||||
Inventory=Read(root+"/exact"); core.UpdateMountedVolumeInfo(volumes.front());
|
||||
Require(Queries==4 && volumes.front()->VirtualDevice=="/dev/disk42", "destructive lookup reused display snapshot");
|
||||
std::cout << "PASS: exact/alias matches, unrelated and incomplete inventories, batch query count, unknown/absent states, fresh lookup\n";
|
||||
} catch(std::exception &e) { std::cerr << e.what() << '\n'; return 1; }
|
||||
}
|
||||
'''
|
||||
unit = work / "discovery.cpp"
|
||||
unit.write_text(prelude + helpers + refresh + tests)
|
||||
command = ["clang++", "-std=c++11", "-I" + str(ROOT / "src"), str(unit), "-framework", "CoreFoundation", "-o", str(work / "discovery")]
|
||||
subprocess.run(command, check=True)
|
||||
subprocess.run([str(work / "discovery"), str(work), str(image)], check=True, timeout=20)
|
||||
if args.platform_archive:
|
||||
command = ["clang++", "-std=c++11", "-DTC_UNIX", "-DTC_MACOSX", "-I" + str(ROOT / "src"), str(ROOT / "Tests/macos_process_test.cpp"), str(args.platform_archive.resolve()), "-Wl,-dead_strip", "-o", str(work / "process")]
|
||||
subprocess.run(command, check=True)
|
||||
subprocess.run([str(work / "process")], check=True, timeout=20)
|
||||
command = ["clang++", "-std=c++11", "-DTC_UNIX", "-DTC_MACOSX", "-I" + str(ROOT / "src"), str(ROOT / "Tests/macos_volume_state_test.cpp"), str(args.platform_archive.resolve()), "-Wl,-dead_strip", "-o", str(work / "state")]
|
||||
subprocess.run(command, check=True)
|
||||
subprocess.run([str(work / "state")], check=True, timeout=20)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inactivity auto-dismount in the background GUI; no sudo required.
|
||||
|
||||
Requires a logged-in macOS desktop and no other VeraCrypt processes or mounts.
|
||||
Two disposable containers are mounted without a filesystem, so nothing else
|
||||
reads or writes them. The GUI's automatic unmount of the first volume must not
|
||||
restart the idle timer of the second. Takes about two minutes.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--binary", required=True, type=Path)
|
||||
parser.add_argument("--keep-artifacts", action="store_true")
|
||||
args = parser.parse_args()
|
||||
binary = args.binary.resolve(strict=True)
|
||||
mounts = lambda: subprocess.check_output(["/sbin/mount"], text=True)
|
||||
if ".veracrypt_aux_mnt" in mounts():
|
||||
raise RuntimeError("Dismount existing VeraCrypt volumes before this isolated GUI test")
|
||||
processes = subprocess.check_output(["/bin/ps", "-axo", "comm="], text=True)
|
||||
if any(Path(line.strip()).name.lower() == "veracrypt" for line in processes.splitlines()):
|
||||
raise RuntimeError("Close other VeraCrypt processes before this isolated GUI test")
|
||||
|
||||
root = Path(tempfile.mkdtemp(prefix="vc-gui-inactivity-")).resolve()
|
||||
print("Artifacts:", root, flush=True)
|
||||
temporary = root / "tmp"
|
||||
config = root / "config" / "VeraCrypt"
|
||||
temporary.mkdir(mode=0o700)
|
||||
config.mkdir(parents=True)
|
||||
prefs = dict(BackgroundTaskEnabled=1, CloseBackgroundTaskOnNoVolumes=1, DismountOnInactivity=1,
|
||||
MaxVolumeIdleTime=1, ForceAutoDismount=1, DismountOnLogOff=0, WipeCacheOnAutoDismount=0,
|
||||
MountFavoritesOnLogon=0, MountDevicesOnLogon=0, OpenExplorerWindowAfterMount=0, SaveHistory=0)
|
||||
(config / "Configuration.xml").write_text("<VeraCrypt><configuration>" + "".join(
|
||||
f'<config key="{key}">{value}</config>' for key, value in prefs.items()
|
||||
) + "</configuration></VeraCrypt>")
|
||||
env = dict(os.environ, TMPDIR=str(temporary) + "/", XDG_CONFIG_HOME=str(root / "config"))
|
||||
contents = root / "VeraCryptTest.app" / "Contents"
|
||||
executable = contents / "MacOS" / "VeraCrypt"
|
||||
executable.parent.mkdir(parents=True)
|
||||
shutil.copy2(binary, executable)
|
||||
(contents / "Info.plist").write_bytes(plistlib.dumps(dict(
|
||||
CFBundleExecutable="VeraCrypt", CFBundleName="VeraCrypt Inactivity Test",
|
||||
CFBundleIdentifier=f"org.idrix.veracrypt.inactivity-test.{os.getpid()}",
|
||||
CFBundlePackageType="APPL", NSHighResolutionCapable=True)))
|
||||
password = "Disposable-inactivity-only"
|
||||
volumes = {name: root / f"{name}.hc" for name in ("first", "second")}
|
||||
gui = None
|
||||
succeeded = False
|
||||
|
||||
def vc(label, *options):
|
||||
result = subprocess.run([str(binary), "--text", "--non-interactive", *map(str, options)],
|
||||
env=env, capture_output=True, text=True, timeout=90)
|
||||
(root / (label + ".log")).write_text(result.stdout + result.stderr)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"{label} failed; see {root / (label + '.log')}")
|
||||
|
||||
def aux_mounts():
|
||||
return {line for line in mounts().splitlines() if str(temporary) in line and ".veracrypt_aux_mnt" in line}
|
||||
|
||||
def mount(name):
|
||||
before = aux_mounts()
|
||||
vc("mount-" + name, "--mount", volumes[name], "--filesystem=none", "--password=" + password,
|
||||
"--pim=1", "--keyfiles=", "--protect-hidden=no")
|
||||
added = aux_mounts() - before
|
||||
assert len(added) == 1, "Expected one new auxiliary mount"
|
||||
return added.pop()
|
||||
|
||||
try:
|
||||
for name, volume in volumes.items():
|
||||
vc("create-" + name, "--create", volume, "--size=33554432", "--volume-type=normal",
|
||||
"--encryption=AES", "--hash=sha512", "--filesystem=FAT", "--password=" + password,
|
||||
"--pim=1", "--keyfiles=", "--random-source=/dev/urandom")
|
||||
first = mount("first")
|
||||
with (root / "gui.log").open("w") as log:
|
||||
gui = subprocess.Popen([str(executable), "--background-task"], env=env,
|
||||
stdout=log, stderr=log, start_new_session=True)
|
||||
start = time.monotonic()
|
||||
time.sleep(30)
|
||||
second = mount("second")
|
||||
second_mounted = time.monotonic()
|
||||
gone = {}
|
||||
while time.monotonic() - start < 150 and len(gone) < 2:
|
||||
current = aux_mounts()
|
||||
for name, line in (("first", first), ("second", second)):
|
||||
if name not in gone and line not in current:
|
||||
gone[name] = time.monotonic()
|
||||
time.sleep(0.5)
|
||||
assert "first" in gone, "First idle volume was not unmounted automatically"
|
||||
assert "second" in gone, "Second idle volume was not unmounted automatically"
|
||||
idle = gone["second"] - second_mounted
|
||||
print(f"first unmounted after {gone['first'] - start:.0f} s; second after {idle:.0f} s idle", flush=True)
|
||||
# One minute limit plus discovery and timer granularity. A restarted
|
||||
# timer would add the time between the two mounts (about 30 s).
|
||||
assert idle < 80, "Automatic unmount of one volume restarted another volume's idle timer"
|
||||
assert gui.wait(timeout=20) == 0, "Background app did not exit cleanly"
|
||||
succeeded = True
|
||||
print("PASS: independent idle timers, automatic unmounts, automatic exit", flush=True)
|
||||
finally:
|
||||
if gui and gui.poll() is None:
|
||||
gui.terminate()
|
||||
gui.wait(timeout=10)
|
||||
for name, volume in volumes.items():
|
||||
if aux_mounts():
|
||||
subprocess.run([str(binary), "--text", "--non-interactive", "--unmount", str(volume)],
|
||||
env=env, capture_output=True, text=True, timeout=90)
|
||||
if succeeded and not args.keep_artifacts:
|
||||
assert not aux_mounts(), "Disposable mount remains"
|
||||
shutil.rmtree(root)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ordinary FUSE-T container and background GUI lifecycle; no sudo required.
|
||||
|
||||
Requires a logged-in macOS desktop and no other VeraCrypt processes or mounts.
|
||||
Uses only a disposable container, isolated preferences, and a local app bundle.
|
||||
No fault injection, device reassignment, or forced unmount is performed.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--binary", required=True, type=Path)
|
||||
parser.add_argument("--keep-artifacts", action="store_true")
|
||||
args = parser.parse_args()
|
||||
binary = args.binary.resolve(strict=True)
|
||||
mounts = lambda: subprocess.check_output(["/sbin/mount"], text=True)
|
||||
if ".veracrypt_aux_mnt" in mounts():
|
||||
raise RuntimeError("Dismount existing VeraCrypt volumes before this isolated GUI test")
|
||||
processes = subprocess.check_output(["/bin/ps", "-axo", "comm="], text=True)
|
||||
if any(Path(line.strip()).name.lower() == "veracrypt" for line in processes.splitlines()):
|
||||
raise RuntimeError("Close other VeraCrypt processes before this isolated GUI test")
|
||||
|
||||
root = Path(tempfile.mkdtemp(prefix="vc-gui-lifecycle-")).resolve()
|
||||
print("Artifacts:", root, flush=True)
|
||||
temporary = root / "tmp"
|
||||
mountpoint = root / "mount"
|
||||
config = root / "config" / "VeraCrypt"
|
||||
temporary.mkdir(mode=0o700)
|
||||
mountpoint.mkdir()
|
||||
config.mkdir(parents=True)
|
||||
prefs = dict(BackgroundTaskEnabled=1, CloseBackgroundTaskOnNoVolumes=1,
|
||||
DismountOnInactivity=0, DismountOnLogOff=1, DismountOnPowerSaving=0,
|
||||
MountFavoritesOnLogon=0, MountDevicesOnLogon=0,
|
||||
OpenExplorerWindowAfterMount=0, SaveHistory=0)
|
||||
(config / "Configuration.xml").write_text("<VeraCrypt><configuration>" + "".join(
|
||||
f'<config key="{key}">{value}</config>' for key, value in prefs.items()
|
||||
) + "</configuration></VeraCrypt>")
|
||||
env = dict(os.environ, TMPDIR=str(temporary) + "/", XDG_CONFIG_HOME=str(root / "config"))
|
||||
contents = root / "VeraCryptTest.app" / "Contents"
|
||||
executable = contents / "MacOS" / "VeraCrypt"
|
||||
executable.parent.mkdir(parents=True)
|
||||
shutil.copy2(binary, executable)
|
||||
(contents / "Info.plist").write_bytes(plistlib.dumps(dict(
|
||||
CFBundleExecutable="VeraCrypt", CFBundleName="VeraCrypt Lifecycle Test",
|
||||
CFBundleIdentifier=f"org.idrix.veracrypt.lifecycle-test.{os.getpid()}",
|
||||
CFBundlePackageType="APPL", NSHighResolutionCapable=True)))
|
||||
volume = root / "ordinary.hc"
|
||||
password = "Disposable-normal-lifecycle-only"
|
||||
gui = None
|
||||
active = None
|
||||
succeeded = False
|
||||
|
||||
def vc(label, *options):
|
||||
result = subprocess.run([str(binary), "--text", "--non-interactive", *map(str, options)],
|
||||
env=env, capture_output=True, text=True, timeout=90)
|
||||
(root / (label + ".log")).write_text(result.stdout + result.stderr)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"{label} failed; see {root / (label + '.log')}")
|
||||
|
||||
def mount(read_only=False):
|
||||
nonlocal active
|
||||
vc("mount", "--mount", volume, mountpoint, "--password=" + password,
|
||||
"--pim=1", "--keyfiles=", "--protect-hidden=no",
|
||||
*(["--mount-options=ro"] if read_only else []))
|
||||
identities = list(temporary.glob(".veracrypt_aux_mnt*/shutdown"))
|
||||
assert len(identities) == 1, "Expected one disposable FUSE-T service"
|
||||
aux = identities[0].parent
|
||||
active = (int(identities[0].read_text().split()[0]), aux,
|
||||
Path((aux / "shutdown-socket").read_text().strip()))
|
||||
|
||||
def confirm_closed():
|
||||
if active:
|
||||
pid, aux, endpoint = active
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("Disposable service still running")
|
||||
assert not aux.exists() and not endpoint.exists(), "Cleanup paths remain"
|
||||
assert str(root) not in mounts(), "Disposable mount remains"
|
||||
handles = subprocess.run(["/usr/sbin/lsof", "-t", str(volume)], capture_output=True, text=True)
|
||||
assert handles.returncode == 1 and not handles.stdout.strip(), "Backing file still open"
|
||||
|
||||
try:
|
||||
vc("create", "--create", volume, "--size=33554432", "--volume-type=normal",
|
||||
"--encryption=AES", "--hash=sha512", "--filesystem=FAT", "--password=" + password,
|
||||
"--pim=1", "--keyfiles=", "--random-source=/dev/urandom")
|
||||
mount()
|
||||
payload = bytes(range(256)) * 4096
|
||||
with (mountpoint / "payload.bin").open("wb") as stream:
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
vc("unmount-write", "--unmount", volume)
|
||||
confirm_closed()
|
||||
mount(read_only=True)
|
||||
assert hashlib.sha256((mountpoint / "payload.bin").read_bytes()).digest() == hashlib.sha256(payload).digest()
|
||||
with (root / "gui.log").open("w") as log:
|
||||
gui = subprocess.Popen([str(executable), "--background-task"], env=env,
|
||||
stdout=log, stderr=log, start_new_session=True)
|
||||
time.sleep(5)
|
||||
assert gui.poll() is None, "Background app exited with a mounted volume"
|
||||
vc("unmount-readonly", "--unmount", volume)
|
||||
assert gui.wait(timeout=20) == 0, "Background app did not exit cleanly"
|
||||
confirm_closed()
|
||||
succeeded = True
|
||||
print("PASS: payload integrity, initial background discovery, external-dismount refresh, automatic exit, service/file cleanup", flush=True)
|
||||
finally:
|
||||
if gui and gui.poll() is None:
|
||||
gui.terminate()
|
||||
gui.wait(timeout=10)
|
||||
if str(root) in mounts():
|
||||
vc("test-cleanup", "--unmount", volume)
|
||||
if succeeded and not args.keep_artifacts:
|
||||
confirm_closed()
|
||||
shutil.rmtree(root)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,190 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Automatic GUI unmounts while a volume's service is slow; no sudo required.
|
||||
|
||||
Requires a logged-in macOS desktop, clang, an unsigned local build, and no other
|
||||
VeraCrypt processes or mounts. Disposable containers are mounted without a
|
||||
filesystem; fuset_startup_faults.c slows down only their own services.
|
||||
|
||||
1. A normal quit request (the quit Apple event also sent by logout) arrives while
|
||||
an automatic unmount is in progress. It must be honored afterwards, including
|
||||
unmount on quit for the remaining volume.
|
||||
2. An automatic unmount cannot confirm that the service exited. The background
|
||||
application must keep a warning (shown on screen until the test ends) instead
|
||||
of exiting silently.
|
||||
Takes about three minutes.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
QUIT_SOURCE = r"""
|
||||
#import <AppKit/AppKit.h>
|
||||
#include <stdlib.h>
|
||||
int main (int argc, char **argv)
|
||||
{
|
||||
@autoreleasepool {
|
||||
NSRunningApplication *app = argc > 1 ? [NSRunningApplication runningApplicationWithProcessIdentifier:atoi (argv[1])] : nil;
|
||||
return app && [app terminate] ? 0 : 1;
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class Leg:
|
||||
def __init__(self, parent, name, prefs):
|
||||
self.parent, self.name = parent, name
|
||||
self.root = parent / name
|
||||
self.temporary = self.root / "tmp"
|
||||
config = self.root / "config" / "VeraCrypt"
|
||||
self.temporary.mkdir(parents=True, mode=0o700)
|
||||
config.mkdir(parents=True)
|
||||
defaults = dict(BackgroundTaskEnabled=1, DismountOnInactivity=1, MaxVolumeIdleTime=1, ForceAutoDismount=1,
|
||||
WipeCacheOnAutoDismount=0, WipeCacheOnClose=0, MountFavoritesOnLogon=0,
|
||||
MountDevicesOnLogon=0, OpenExplorerWindowAfterMount=0, SaveHistory=0)
|
||||
defaults.update(prefs)
|
||||
(config / "Configuration.xml").write_text("<VeraCrypt><configuration>" + "".join(
|
||||
f'<config key="{key}">{value}</config>' for key, value in defaults.items()
|
||||
) + "</configuration></VeraCrypt>")
|
||||
self.env = dict(os.environ, TMPDIR=str(self.temporary) + "/", XDG_CONFIG_HOME=str(self.root / "config"))
|
||||
self.gui = None
|
||||
self.volumes = []
|
||||
|
||||
def vc(self, binary, label, *options, extra=None):
|
||||
result = subprocess.run([str(binary), "--text", "--non-interactive", *map(str, options)],
|
||||
env=dict(self.env, **(extra or {})), capture_output=True, text=True, timeout=90)
|
||||
(self.root / (label + ".log")).write_text(result.stdout + result.stderr)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"{label} failed; see {self.root / (label + '.log')}")
|
||||
|
||||
def aux_mounts(self):
|
||||
mounts = subprocess.check_output(["/sbin/mount"], text=True)
|
||||
return {line for line in mounts.splitlines() if str(self.temporary) in line and ".veracrypt_aux_mnt" in line}
|
||||
|
||||
def mount(self, binary, name, password, faults=None):
|
||||
volume = self.root / (name + ".hc")
|
||||
self.vc(binary, "create-" + name, "--create", volume, "--size=33554432", "--volume-type=normal",
|
||||
"--encryption=AES", "--hash=sha512", "--filesystem=FAT", "--password=" + password,
|
||||
"--pim=1", "--keyfiles=", "--random-source=/dev/urandom")
|
||||
before = self.aux_mounts()
|
||||
self.vc(binary, "mount-" + name, "--mount", volume, "--filesystem=none", "--password=" + password,
|
||||
"--pim=1", "--keyfiles=", "--protect-hidden=no", extra=faults)
|
||||
added = self.aux_mounts() - before
|
||||
assert len(added) == 1, "Expected one new auxiliary mount"
|
||||
self.volumes.append(volume)
|
||||
return added.pop()
|
||||
|
||||
def start_gui(self, bundle):
|
||||
with (self.root / "gui.log").open("w") as log:
|
||||
self.gui = subprocess.Popen([str(bundle), "--background-task"], env=self.env,
|
||||
stdout=log, stderr=log, start_new_session=True)
|
||||
return time.monotonic()
|
||||
|
||||
def cleanup(self, binary):
|
||||
if self.gui and self.gui.poll() is None:
|
||||
self.gui.send_signal(signal.SIGTERM)
|
||||
try:
|
||||
self.gui.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.gui.kill()
|
||||
self.gui.wait(timeout=10)
|
||||
for volume in self.volumes:
|
||||
if self.aux_mounts():
|
||||
subprocess.run([str(binary), "--text", "--non-interactive", "--unmount", str(volume)],
|
||||
env=self.env, capture_output=True, text=True, timeout=90)
|
||||
|
||||
|
||||
def wait_for(condition, timeout):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if condition():
|
||||
return True
|
||||
time.sleep(0.2)
|
||||
return condition()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--binary", required=True, type=Path)
|
||||
parser.add_argument("--keep-artifacts", action="store_true")
|
||||
args = parser.parse_args()
|
||||
binary = args.binary.resolve(strict=True)
|
||||
if ".veracrypt_aux_mnt" in subprocess.check_output(["/sbin/mount"], text=True):
|
||||
raise RuntimeError("Dismount existing VeraCrypt volumes before this isolated GUI test")
|
||||
processes = subprocess.check_output(["/bin/ps", "-axo", "comm="], text=True)
|
||||
if any(Path(line.strip()).name.lower() == "veracrypt" for line in processes.splitlines()):
|
||||
raise RuntimeError("Close other VeraCrypt processes before this isolated GUI test")
|
||||
|
||||
root = Path(tempfile.mkdtemp(prefix="vc-gui-teardown-")).resolve()
|
||||
print("Artifacts:", root, flush=True)
|
||||
contents = root / "VeraCryptTest.app" / "Contents"
|
||||
bundle = contents / "MacOS" / "VeraCrypt"
|
||||
bundle.parent.mkdir(parents=True)
|
||||
shutil.copy2(binary, bundle)
|
||||
(contents / "Info.plist").write_bytes(plistlib.dumps(dict(
|
||||
CFBundleExecutable="VeraCrypt", CFBundleName="VeraCrypt Teardown Test",
|
||||
CFBundleIdentifier=f"org.idrix.veracrypt.teardown-test.{os.getpid()}",
|
||||
CFBundlePackageType="APPL", NSHighResolutionCapable=True)))
|
||||
faults = root / "service-faults.dylib"
|
||||
subprocess.run(["/usr/bin/xcrun", "clang", "-dynamiclib", "-Wall", "-Wextra", "-O2",
|
||||
str(Path(__file__).with_name("fuset_startup_faults.c")), "-o", str(faults)], check=True)
|
||||
quit_tool = root / "quit-application"
|
||||
subprocess.run(["/usr/bin/xcrun", "clang", "-x", "objective-c", "-fobjc-arc", "-framework", "AppKit",
|
||||
"-", "-o", str(quit_tool)], input=QUIT_SOURCE, text=True, check=True)
|
||||
password = "Disposable-teardown-only"
|
||||
legs = []
|
||||
succeeded = False
|
||||
try:
|
||||
# 1. Quit request during an automatic unmount.
|
||||
leg = Leg(root, "quit", dict(CloseBackgroundTaskOnNoVolumes=0, DismountOnLogOff=1))
|
||||
legs.append(leg)
|
||||
marker = leg.root / "unmount-started"
|
||||
slow = leg.mount(binary, "slow", password, dict(
|
||||
DYLD_INSERT_LIBRARIES=str(faults), VC_FUSET_TEST_FAULT="unmount-delay", VC_FUSET_TEST_DELAY="8",
|
||||
VC_FUSET_TEST_ROOT=str(root), VC_FUSET_TEST_FAULT_MARKER=str(marker)))
|
||||
started = leg.start_gui(bundle)
|
||||
time.sleep(30)
|
||||
other = leg.mount(binary, "other", password)
|
||||
other_idle_deadline = time.monotonic() + 60
|
||||
assert wait_for(marker.exists, 120), "Automatic unmount did not start"
|
||||
subprocess.run([str(quit_tool), str(leg.gui.pid)], check=True)
|
||||
assert wait_for(lambda: leg.gui.poll() is not None, 40), "Quit request during an automatic unmount was not honored"
|
||||
exited = time.monotonic()
|
||||
assert leg.gui.returncode == 0, "Application did not exit cleanly after the quit request"
|
||||
remaining = leg.aux_mounts() & {slow, other}
|
||||
assert not remaining, "Volumes remained mounted after quit"
|
||||
assert exited < other_idle_deadline, "The remaining volume was not unmounted by the quit request"
|
||||
print(f"quit honored {exited - started:.0f} s after GUI start; both volumes unmounted", flush=True)
|
||||
|
||||
# 2. Automatic unmount whose service exit cannot be confirmed.
|
||||
leg = Leg(root, "unconfirmed", dict(CloseBackgroundTaskOnNoVolumes=1, DismountOnLogOff=0))
|
||||
legs.append(leg)
|
||||
slow = leg.mount(binary, "slow", password, dict(
|
||||
DYLD_INSERT_LIBRARIES=str(faults), VC_FUSET_TEST_FAULT="cleanup-delay", VC_FUSET_TEST_DELAY="15",
|
||||
VC_FUSET_TEST_ROOT=str(root), VC_FUSET_TEST_FAULT_MARKER=str(leg.root / "cleanup-delayed")))
|
||||
service = int(next(leg.temporary.glob(".veracrypt_aux_mnt*/shutdown")).read_text().split()[0])
|
||||
leg.start_gui(bundle)
|
||||
assert wait_for(lambda: slow not in leg.aux_mounts(), 120), "Automatic unmount did not start"
|
||||
service_alive = lambda: subprocess.run(["/bin/kill", "-0", str(service)], capture_output=True).returncode == 0
|
||||
assert wait_for(lambda: not service_alive(), 40), "Delayed service did not exit"
|
||||
time.sleep(8)
|
||||
assert leg.gui.poll() is None, \
|
||||
f"Background application exited (status {leg.gui.returncode}) after an unconfirmed cleanup"
|
||||
print("unconfirmed cleanup kept the background application and its warning", flush=True)
|
||||
succeeded = True
|
||||
print("PASS: quit during automatic unmount, unmount on quit, unconfirmed cleanup warning", flush=True)
|
||||
finally:
|
||||
for leg in legs:
|
||||
leg.cleanup(binary)
|
||||
if succeeded and not args.keep_artifacts:
|
||||
assert not any(leg.aux_mounts() for leg in legs), "Disposable mount remains"
|
||||
shutil.rmtree(root)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user