diff --git a/src/linux/Platform.cmake b/src/linux/Platform.cmake index 79fcdbf3..45b0ad17 100644 --- a/src/linux/Platform.cmake +++ b/src/linux/Platform.cmake @@ -23,6 +23,8 @@ set(PLATFORM_SOURCES linux/rsakeyfingerprint_linux.cpp linux/file_operations_linux.cpp linux/platformquirks_linux.cpp + linux/x11hostaccess.h + linux/x11hostaccess.cpp ) # Only include DBus-dependent and GUI components for non-CLI builds diff --git a/src/linux/platformquirks_linux.cpp b/src/linux/platformquirks_linux.cpp index af936c2a..c6f47269 100644 --- a/src/linux/platformquirks_linux.cpp +++ b/src/linux/platformquirks_linux.cpp @@ -12,6 +12,8 @@ */ #include "../platformquirks.h" +#include "x11hostaccess.h" +#include #include #include #include @@ -160,24 +162,68 @@ namespace { return nullptr; } - // Grant root access to the user's X11 display via xhost. + // Grant root access to the user's X11 display by adding "si:localuser:root" to + // the X server's host access list, which is what `xhost +SI:localuser:root` does. // Must be run as the original (non-root) user who owns the display session, // since root doesn't yet have permission to connect. + // The X11 exchange is done in-process (X11HostAccess) rather than by running + // xhost(1): xhost is an optional package on several distributions, and when + // it is missing the elevated instance aborts with + // "qt.qpa.xcb: could not connect to display". // Uses +SI:localuser:root (server-interpreted, narrowly scoped to root only). - void grantRootDisplayAccess(uid_t uid, gid_t gid) { + void grantRootDisplayAccess(uid_t uid, gid_t gid, const char* originalHome) { + const char* display = ::getenv("DISPLAY"); + X11HostAccess::GrantPlan plan; + char reason[X11HostAccess::kMaxReason]; + if (!X11HostAccess::prepareGrant(display, ::getenv("XAUTHORITY"), originalHome, "root", plan, + reason, sizeof(reason))) { + std::fprintf(stderr, "Not granting root access to the X11 display: %s\n", reason); + return; + } + + // The child reports what it saw (result or failure) through this pipe + int reportPipe[2]; + if (pipe(reportPipe) != 0) { + reportPipe[0] = reportPipe[1] = -1; + } + pid_t pid = fork(); - if (pid < 0) return; + if (pid < 0) { + if (reportPipe[0] >= 0) { + close(reportPipe[0]); + close(reportPipe[1]); + } + return; + } if (pid == 0) { // POSIX: only async-signal-safe functions between fork() and exec() - if (setgid(gid) != 0) _exit(1); - if (setuid(uid) != 0) _exit(1); - execlp("xhost", "xhost", "+SI:localuser:root", nullptr); - _exit(127); + if (reportPipe[0] >= 0) close(reportPipe[0]); + if (setgid(gid) != 0) _exit(X11HostAccess::PrivilegeDropFailed); + if (setuid(uid) != 0) _exit(X11HostAccess::PrivilegeDropFailed); + X11HostAccess::runGrant(plan, reportPipe[1]); + } + + char report[X11HostAccess::kMaxReason] = {0}; + if (reportPipe[0] >= 0) { + close(reportPipe[1]); + size_t total = 0; + ssize_t n; + while (total < sizeof(report) - 1 && + (n = read(reportPipe[0], report + total, sizeof(report) - 1 - total)) > 0) { + total += static_cast(n); + } + report[total] = '\0'; + close(reportPipe[0]); } - int status; - waitpid(pid, &status, 0); + int status = 0; + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {} + + const bool granted = X11HostAccess::describeOutcome(status, report, reason, sizeof(reason)); + std::fprintf(stderr, granted ? "Granted root access to X11 display %s (%s)\n" + : "WARNING: could not grant root access to X11 display %s: %s\n", + display, reason); } } @@ -342,11 +388,11 @@ void applyQuirks() { std::fprintf(stderr, "XAUTHORITY already set to: %s\n", currentXauthority); } - // If an X11 display is available, grant root access via xhost. + // If an X11 display is available, grant root access to it. // This runs as the original user (who owns the display session) // and must happen after DISPLAY and XAUTHORITY are configured. if (::getenv("DISPLAY")) { - grantRootDisplayAccess(originalUid, pwResult->pw_gid); + grantRootDisplayAccess(originalUid, pwResult->pw_gid, pwResult->pw_dir); } std::fprintf(stderr, "Set HOME to: %s\n", pwResult->pw_dir); diff --git a/src/linux/x11hostaccess.cpp b/src/linux/x11hostaccess.cpp new file mode 100644 index 00000000..bfc15a2b --- /dev/null +++ b/src/linux/x11hostaccess.cpp @@ -0,0 +1,666 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * X11 host access for the elevated instance: the in-process equivalent of + * `xhost +SI:localuser:`. + * + * Only three pieces of the X11 protocol are needed to add a user to the X + * server's host access list: the connection setup, ChangeHosts and ListHosts. + * Doing them here avoids a runtime dependency on xhost(1), which is an + * optional package on several distributions. + */ + +#include "x11hostaccess.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace X11HostAccess { + +namespace { + +constexpr char kByteOrder = 'l'; /* little-endian */ +constexpr unsigned short kProtocolMajor = 11; +constexpr unsigned char kRequestChangeHosts = 109; /* X_ChangeHosts */ +constexpr unsigned char kRequestListHosts = 110; /* X_ListHosts */ +constexpr unsigned char kHostInsert = 0; +constexpr unsigned char kFamilyServerInterpreted = 5; +constexpr unsigned short kAuthFamilyLocal = 256; /* Xauth family of local connections */ +constexpr unsigned short kAuthFamilyWild = 65535; /* FamilyWild */ +constexpr char kCookieName[] = "MIT-MAGIC-COOKIE-1"; +constexpr char kLocalUserType[] = "localuser"; /* server-interpreted address type */ + +constexpr size_t kMaxCookieLength = 64; +constexpr size_t kMaxAuthoritySize = 256 * 1024; +constexpr size_t kMaxTargetUserLength = 32; + +const unsigned char kListHostsRequest[4] = {kRequestListHosts, 0, 1, 0}; + +/* Buffers for what the X server sends. Static rather than on the stack: the + * child reuses whatever stack the forking thread had, and may not allocate. */ +unsigned char replyBody[256 * 1024]; + +unsigned readU16(const unsigned char* p) { + return static_cast(p[0]) | (static_cast(p[1]) << 8); +} + +unsigned readU32(const unsigned char* p) { + return readU16(p) | (readU16(p + 2) << 16); +} + +/* Xauthority files are big-endian, the connection is not. */ +unsigned readNetworkU16(const unsigned char* p) { + return (static_cast(p[0]) << 8) | static_cast(p[1]); +} + +void writeU16(unsigned char* p, unsigned value) { + p[0] = static_cast(value); + p[1] = static_cast(value >> 8); +} + +size_t pad4(size_t n) { + return (n + 3) & ~size_t(3); +} + +/* Accepts the local forms of "[protocol/][host]:display[.screen]": an empty + * host, "unix" or "unix/". Anything else names a remote display, and host + * access lists do not apply to network connections. */ +bool parseLocalDisplay(const char* display, int& displayNumber) { + const char* colon = strrchr(display, ':'); + if (!colon || colon[1] == '\0') { + return false; + } + + const char* host = display; + if (const char* slash = strchr(display, '/'); slash && slash < colon) { + if (slash - display != 4 || memcmp(display, "unix", 4) != 0) { + return false; + } + host = slash + 1; + } + const size_t hostLength = static_cast(colon - host); + if (hostLength != 0 && !(hostLength == 4 && memcmp(host, "unix", 4) == 0)) { + return false; + } + + const char* p = colon + 1; + if (*p < '0' || *p > '9') { + return false; + } + int number = 0; + for (int digits = 0; *p >= '0' && *p <= '9'; ++p) { + if (++digits > 4) { + return false; + } + number = number * 10 + (*p - '0'); + } + if (*p != '\0' && *p != '.') { + return false; + } + displayNumber = number; + return true; +} + +/* Finds the display's MIT-MAGIC-COOKIE-1 record the way libXau does for + * Xlib: the query is for family FamilyLocal with the host name as address, + * and a record's empty display number matches every display. */ +bool findCookie(const unsigned char* data, size_t size, const char* hostname, const char* displayNumber, + unsigned char* cookie, size_t& cookieLength) { + const size_t hostnameLength = strlen(hostname); + const size_t queryNumberLength = strlen(displayNumber); + const unsigned char* p = data; + const unsigned char* const end = data + size; + + /* Reads one length-prefixed field; false when the file is truncated. */ + const auto field = [&](const unsigned char*& value, size_t& length) -> bool { + if (static_cast(end - p) < 2) { + return false; + } + length = readNetworkU16(p); + p += 2; + if (static_cast(end - p) < length) { + return false; + } + value = p; + p += length; + return true; + }; + + while (p != end) { + if (static_cast(end - p) < 2) { + break; /* corrupt tail */ + } + const unsigned family = readNetworkU16(p); + p += 2; + const unsigned char *address, *number, *name, *value; + size_t addressLength, numberLength, nameLength, valueLength; + if (!field(address, addressLength) || !field(number, numberLength) || + !field(name, nameLength) || !field(value, valueLength)) { + break; + } + /* The query is for a local connection: its family and address have to + * match, unless the record is a wildcard. */ + const bool familyMatches = family == kAuthFamilyWild || family == kAuthFamilyLocal; + const bool addressMatches = family == kAuthFamilyWild || + (addressLength == hostnameLength && + memcmp(address, hostname, hostnameLength) == 0); + const bool numberMatches = numberLength == 0 || + (numberLength == queryNumberLength && + memcmp(number, displayNumber, queryNumberLength) == 0); + const bool nameMatches = nameLength == strlen(kCookieName) && + memcmp(name, kCookieName, nameLength) == 0; + if (familyMatches && addressMatches && numberMatches && nameMatches && + valueLength > 0 && valueLength <= kMaxCookieLength) { + memcpy(cookie, value, valueLength); + cookieLength = valueLength; + return true; + } + } + return false; +} + +std::vector readFile(const char* path) { + std::vector data; + const int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) { + return data; + } + unsigned char buffer[4096]; + while (data.size() < kMaxAuthoritySize) { + const ssize_t n = read(fd, buffer, sizeof(buffer)); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + break; + } + data.insert(data.end(), buffer, + buffer + std::min(static_cast(n), kMaxAuthoritySize - data.size())); + } + close(fd); + return data; +} + +/* xConnClientPrefix followed by the authorization strings. Without a cookie + * the connection relies on the host access list, like Xlib does. */ +void buildSetup(GrantPlan& plan, const unsigned char* cookie, size_t cookieLength) { + const size_t nameLength = cookie ? strlen(kCookieName) : 0; + unsigned char* p = plan.setup; + *p++ = kByteOrder; + *p++ = 0; + writeU16(p, kProtocolMajor); + p += 2; + writeU16(p, 0); + p += 2; + writeU16(p, static_cast(nameLength)); + p += 2; + writeU16(p, static_cast(cookieLength)); + p += 2; + writeU16(p, 0); + p += 2; + if (cookie) { + memcpy(p, kCookieName, nameLength); + p += pad4(nameLength); + memcpy(p, cookie, cookieLength); + p += pad4(cookieLength); + } + plan.setupLength = static_cast(p - plan.setup); +} + +/* xChangeHostsReq inserting "localuser\0\0" (FamilyServerInterpreted). */ +void buildChangeHosts(GrantPlan& plan, const char* targetUser) { + const size_t userLength = strlen(targetUser); + const size_t addressLength = sizeof(kLocalUserType) + userLength + 1; + unsigned char* p = plan.changeHosts; + *p++ = kRequestChangeHosts; + *p++ = kHostInsert; + writeU16(p, static_cast((8 + pad4(addressLength)) / 4)); + p += 2; + *p++ = kFamilyServerInterpreted; + *p++ = 0; + writeU16(p, static_cast(addressLength)); + p += 2; + memcpy(p, kLocalUserType, sizeof(kLocalUserType)); /* includes the separator */ + p += sizeof(kLocalUserType); + memcpy(p, targetUser, userLength + 1); /* includes the terminator */ + p += userLength + 1; + memset(p, 0, pad4(addressLength) - addressLength); + + plan.changeHostsLength = 8 + pad4(addressLength); + memcpy(plan.target, plan.changeHosts + 8, addressLength); + plan.targetLength = addressLength; +} + +int connectToDisplay(const char* path) { + const int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0) { + return -1; + } + sockaddr_un address = {}; + address.sun_family = AF_UNIX; + const size_t prefix = path[0] == '\0' ? 1 : 0; /* leading NUL: abstract socket */ + const size_t length = strlen(path + prefix); + if (length >= sizeof(address.sun_path) - prefix) { + close(fd); + return -1; + } + memcpy(address.sun_path, path, prefix + length); + const socklen_t addressLength = + static_cast(offsetof(sockaddr_un, sun_path) + prefix + length); + if (connect(fd, reinterpret_cast(&address), addressLength) != 0) { + close(fd); + return -1; + } + return fd; +} + +enum class ReadResult { Ok, EndOfFile, TimedOut, Failed }; + +ReadResult readExactly(int fd, unsigned char* buffer, size_t length) { + while (length > 0) { + const ssize_t n = recv(fd, buffer, length, 0); + if (n > 0) { + buffer += n; + length -= static_cast(n); + } else if (n == 0) { + return ReadResult::EndOfFile; + } else if (errno != EINTR) { + return (errno == EAGAIN || errno == EWOULDBLOCK) ? ReadResult::TimedOut : ReadResult::Failed; + } + } + return ReadResult::Ok; +} + +/* For the pipe back to the parent. */ +bool writeExactly(int fd, const unsigned char* buffer, size_t length) { + while (length > 0) { + const ssize_t n = write(fd, buffer, length); + if (n > 0) { + buffer += n; + length -= static_cast(n); + } else if (n < 0 && errno == EINTR) { + continue; + } else { + return false; + } + } + return true; +} + +/* For the connection to the X server. */ +bool sendExactly(int fd, const unsigned char* buffer, size_t length) { + while (length > 0) { + const ssize_t n = send(fd, buffer, length, MSG_NOSIGNAL); + if (n > 0) { + buffer += n; + length -= static_cast(n); + } else if (n < 0 && errno == EINTR) { + continue; + } else { + return false; + } + } + return true; +} + +/* Reads a reply body into replyBody, discarding anything beyond its size. */ +ReadResult readBody(int fd, size_t length, size_t& kept) { + kept = std::min(length, sizeof(replyBody)); + const ReadResult result = readExactly(fd, replyBody, kept); + if (result != ReadResult::Ok) { + return result; + } + unsigned char discard[4096]; + for (length -= kept; length > 0;) { + const size_t chunk = std::min(length, sizeof(discard)); + const ReadResult skipped = readExactly(fd, discard, chunk); + if (skipped != ReadResult::Ok) { + return skipped; + } + length -= chunk; + } + return ReadResult::Ok; +} + +ExitCode exitCodeFor(ReadResult result) { + switch (result) { + case ReadResult::EndOfFile: return ProtocolError; + case ReadResult::TimedOut: return Timeout; + default: return IoError; + } +} + +/* Single-line report for the parent. Memory operations and write() only: + * the child may not use stdio or allocate. */ +struct Report { + char text[kMaxReason]; + size_t length = 0; + + void append(const char* s, size_t n) { + if (n >= kMaxReason - length) { + n = kMaxReason - length - 1; + } + memcpy(text + length, s, n); + length += n; + } + void add(const char* s) { + append(s, strlen(s)); + } + void add(unsigned number) { + char digits[10]; + size_t n = 0; + do { + digits[n++] = static_cast('0' + number % 10); + number /= 10; + } while (number != 0); + while (n > 0) { + append(digits + --n, 1); + } + } +}; + +/* Writes the NUL-terminated report, if wanted, and exits. */ +[[noreturn]] void finish(Report& report, int reportFd, ExitCode code) { + report.text[report.length] = '\0'; + if (reportFd >= 0) { + writeExactly(reportFd, reinterpret_cast(report.text), report.length + 1); + } + _exit(code); +} + +void describeReadFailure(Report& report, ReadResult result) { + switch (result) { + case ReadResult::EndOfFile: report.add("the X server closed the connection"); break; + case ReadResult::TimedOut: report.add("timed out waiting for the X server"); break; + default: report.add("I/O error while talking to the X server"); break; + } +} + +/* One xHostEntry in human-readable form: "si::" for the + * server-interpreted family, otherwise just the family number. */ +void addHost(Report& report, const unsigned char* entry, size_t length) { + const unsigned char* address = entry + 4; + if (entry[0] == kFamilyServerInterpreted) { + if (const void* separator = memchr(address, '\0', length)) { + const size_t typeLength = static_cast(static_cast(separator) - address) + 1; + report.add("si:"); + report.append(reinterpret_cast(address), typeLength - 1); + report.add(":"); + size_t valueLength = length - typeLength; + if (valueLength > 0 && address[length - 1] == '\0') { + --valueLength; + } + report.append(reinterpret_cast(address) + typeLength, valueLength); + return; + } + } + report.add("family "); + report.add(static_cast(entry[0])); +} + +/* The user asked for, as "si:localuser:". */ +void addTarget(Report& report, const GrantPlan& plan) { + report.add("si:"); + report.add(kLocalUserType); + report.add(":"); + report.append(plan.target + sizeof(kLocalUserType), plan.targetLength - sizeof(kLocalUserType) - 1); +} + +} // namespace + +bool prepareGrant(const char* display, const char* xauthority, const char* homeDirectory, + const char* targetUser, GrantPlan& plan, char* reason, size_t reasonCapacity) { + plan = GrantPlan{}; + reason[0] = '\0'; + const auto decline = [&](const char* why) { + snprintf(reason, reasonCapacity, "%s (DISPLAY=%s)", why, display ? display : ""); + return false; + }; + + if (!display) { + return decline("$DISPLAY is not set, no X11 display to grant access to"); + } + int displayNumber = 0; + if (!parseLocalDisplay(display, displayNumber)) { + return decline("$DISPLAY is not a local display, host access lists do not apply"); + } + if (!targetUser || *targetUser == '\0' || strlen(targetUser) > kMaxTargetUserLength) { + return decline("no valid user to grant access to"); + } + + /* The filesystem socket first: every X server provides it, and the + * abstract socket is a Linux extra. */ + snprintf(plan.socketPath[0], sizeof(plan.socketPath[0]), "/tmp/.X11-unix/X%d", displayNumber); + snprintf(plan.socketPath[1] + 1, sizeof(plan.socketPath[1]) - 1, "/tmp/.X11-unix/X%d", displayNumber); + plan.socketCount = kMaxSocketPaths; + + /* Like Xlib: $XAUTHORITY when set, otherwise ~/.Xauthority. */ + char path[PATH_MAX]; + if (xauthority && *xauthority) { + snprintf(path, sizeof(path), "%s", xauthority); + } else if (homeDirectory && *homeDirectory) { + snprintf(path, sizeof(path), "%s/.Xauthority", homeDirectory); + } else { + path[0] = '\0'; + } + const std::vector authority = path[0] ? readFile(path) : std::vector(); + + char hostname[HOST_NAME_MAX + 1] = {}; + gethostname(hostname, sizeof(hostname) - 1); + char number[8]; + snprintf(number, sizeof(number), "%d", displayNumber); + + unsigned char cookie[kMaxCookieLength]; + size_t cookieLength = 0; + bool haveCookie = findCookie(authority.data(), authority.size(), hostname, number, cookie, cookieLength); + if (!haveCookie) { + /* libX11 also looks under "hostname/unix", the usual entry on + * distributions where the X server is started by a display manager. */ + const std::string localName = std::string(hostname) + "/unix"; + haveCookie = findCookie(authority.data(), authority.size(), localName.c_str(), number, cookie, cookieLength); + } + + buildSetup(plan, haveCookie ? cookie : nullptr, cookieLength); + buildChangeHosts(plan, targetUser); + return true; +} + +[[noreturn]] void runGrant(const GrantPlan& plan, int reportFd) { + Report report; + + /* Paths are stored the abstract way, with a leading NUL. */ + const auto printable = [&plan](int i) { + return plan.socketPath[i][0] == '\0' ? plan.socketPath[i] + 1 : plan.socketPath[i]; + }; + + int fd = -1; + for (int i = 0; i < plan.socketCount && fd < 0; ++i) { + fd = connectToDisplay(plan.socketPath[i]); + } + struct sigaction action = {}; + if (fd < 0) { + report.add("could not connect to the X display socket "); + for (int i = 0; i < plan.socketCount; ++i) { + report.add(i ? " or " : ""); + report.add(printable(i)); + } + finish(report, reportFd, CouldNotConnect); + } + + /* Bound every blocking read: a wedged server must not hang startup. */ + timeval timeout = {}; + timeout.tv_sec = static_cast(plan.timeoutSeconds); + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); + /* The per-read limit does not cover a server that trickles bytes, so put + * an upper bound on the whole exchange as well: with SIGALRM at its + * default disposition the child is simply killed and the parent reports it. */ + sigaction(SIGALRM, nullptr, &action); + action.sa_handler = SIG_DFL; + sigemptyset(&action.sa_mask); + action.sa_flags = 0; + sigaction(SIGALRM, &action, nullptr); + sigset_t unblock; + sigemptyset(&unblock); + sigaddset(&unblock, SIGALRM); + sigprocmask(SIG_UNBLOCK, &unblock, nullptr); + alarm(plan.timeoutSeconds * 2); + + if (!sendExactly(fd, plan.setup, plan.setupLength)) { + report.add("failed to send the connection setup to the X server"); + finish(report, reportFd, IoError); + } + + /* xConnSetupPrefix: success, reasonLength, majorVersion, minorVersion (2 + * bytes each), then additionalLength in 4-byte units at offset 6. The + * additionalLength*4 bytes of setup information follow and have to be + * consumed before the first reply can be read. */ + unsigned char prefix[8]; + ReadResult result = readExactly(fd, prefix, sizeof(prefix)); + size_t bodyLength = 0; + if (result == ReadResult::Ok) { + result = readBody(fd, static_cast(readU16(prefix + 6)) * 4u, bodyLength); + } + if (result != ReadResult::Ok) { + describeReadFailure(report, result); + finish(report, reportFd, exitCodeFor(result)); + } + if (prefix[0] != 1) { + report.add(prefix[0] == 0 ? "the X server rejected the connection: " + : "the X server requested an unsupported authentication exchange: "); + const size_t reasonLength = std::min(prefix[1], bodyLength); + report.append(reinterpret_cast(replyBody), reasonLength); + if (reasonLength == 0) { + report.add("(no reason given)"); + } + finish(report, reportFd, SetupRejected); + } + + if (!plan.listOnly && !sendExactly(fd, plan.changeHosts, plan.changeHostsLength)) { + report.add("failed to send the ChangeHosts request to the X server"); + finish(report, reportFd, IoError); + } + if (!sendExactly(fd, kListHostsRequest, sizeof(kListHostsRequest))) { + report.add("failed to send the ListHosts request to the X server"); + finish(report, reportFd, IoError); + } + + for (;;) { + unsigned char header[32]; + result = readExactly(fd, header, sizeof(header)); + if (result == ReadResult::Ok && header[0] == 1) { + result = readBody(fd, static_cast(readU32(header + 4)) * 4u, bodyLength); + } + if (result != ReadResult::Ok) { + report.add("no reply to ListHosts: "); + describeReadFailure(report, result); + finish(report, reportFd, exitCodeFor(result)); + } + + if (header[0] == 0) { /* XError: type, code, ..., minor, major */ + if (header[10] == kRequestChangeHosts) { + report.add("the X server refused the ChangeHosts request (error "); + report.add(static_cast(header[1])); + report.add(")"); + finish(report, reportFd, ChangeHostsRefused); + } + if (header[10] == kRequestListHosts) { + report.add("the X server refused to list its host access list (error "); + report.add(static_cast(header[1])); + report.add(")"); + finish(report, reportFd, ListHostsRefused); + } + continue; /* not about our requests */ + } + if (header[0] != 1) { + continue; /* no events are expected here */ + } + + /* The only request of ours that gets a reply is ListHosts: + * xListHostsReply has "enabled" in header[1], nHosts at offset 8, + * followed by xHostEntry records: family, pad, length, address. */ + const bool accessControlEnabled = header[1] != 0; + const bool truncated = static_cast(readU32(header + 4)) * 4u > sizeof(replyBody); + const unsigned hostCount = readU16(header + 8); + bool found = false; + Report list; + size_t offset = 0; + for (unsigned i = 0; i < hostCount; ++i) { + if (bodyLength - offset < 4) { + break; + } + const unsigned char* entry = replyBody + offset; + const size_t length = readU16(entry + 2); + if (length > bodyLength - offset - 4) { + break; + } + if (entry[0] == kFamilyServerInterpreted && length == plan.targetLength && + memcmp(entry + 4, plan.target, length) == 0) { + found = true; + } + list.add(offset ? ", " : ""); + addHost(list, entry, length); + offset = std::min(bodyLength, offset + 4 + pad4(length)); + } + + addTarget(report, plan); + report.add(accessControlEnabled ? (found ? " is on the host access list (" : " is not on the host access list (") + : " may connect, access control is disabled (host access list: "); + if (offset == 0) { + list.add("empty"); + } + report.append(list.text, list.length); + report.add(")"); + if (truncated && !(found || !accessControlEnabled)) { + report.add("; the list was too large to inspect in full"); + } + finish(report, reportFd, found || !accessControlEnabled ? Ok : NotGranted); + } +} + +bool describeOutcome(int waitStatus, const char* report, char* reason, size_t reasonCapacity) { + reason[0] = '\0'; + if (WIFEXITED(waitStatus)) { + const int code = WEXITSTATUS(waitStatus); + if (code == Ok) { + snprintf(reason, reasonCapacity, "%s", report); + return true; + } + const char* what = "unexpected failure"; + switch (code) { + case PrivilegeDropFailed: what = "could not drop back to the original user"; break; + case CouldNotConnect: what = "the original user cannot connect to the X display"; break; + case SetupRejected: what = "the X server refused the connection"; break; + case IoError: what = "I/O error while talking to the X server"; break; + case Timeout: what = "timeout while talking to the X server"; break; + case ChangeHostsRefused: what = "the X server refused to change its host access list"; break; + case ListHostsRefused: what = "the X server refused to report its host access list"; break; + case ProtocolError: what = "unexpected reply from the X server"; break; + case NotGranted: what = "the user is not on the X server's host access list"; break; + default: break; + } + snprintf(reason, reasonCapacity, "%s", report && *report ? report : what); + return false; + } + if (WIFSIGNALED(waitStatus)) { + snprintf(reason, reasonCapacity, "the grant helper was killed by signal %d", WTERMSIG(waitStatus)); + } else { + snprintf(reason, reasonCapacity, "the grant helper did not exit normally"); + } + return false; +} + +} // namespace X11HostAccess diff --git a/src/linux/x11hostaccess.h b/src/linux/x11hostaccess.h new file mode 100644 index 00000000..f56a422c --- /dev/null +++ b/src/linux/x11hostaccess.h @@ -0,0 +1,77 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * X11 host access for the elevated instance: the in-process equivalent of + * `xhost +SI:localuser:`. + * + * Deliberately free of Qt, X11 and xcb. The part that talks to the X server + * runs in a forked child of a multi-threaded process, where only + * async-signal-safe calls are permitted, so all parsing and allocation happens + * in the parent, before fork(). + */ +#ifndef X11HOSTACCESS_H +#define X11HOSTACCESS_H + +#include +#include + +namespace X11HostAccess { + +constexpr int kMaxSocketPaths = 2; /* filesystem socket, then the abstract socket */ +constexpr int kMaxReason = 512; + +/* Everything the forked child needs, prepared by prepareGrant(). */ +struct GrantPlan { + /* Unix sockets to try, in order (the abstract socket has a leading '\0'). */ + char socketPath[kMaxSocketPaths][108]; + int socketCount = 0; + /* Connection setup: xConnClientPrefix plus the authorization strings, padded. */ + unsigned char setup[256]; + size_t setupLength = 0; + /* ChangeHosts(Insert, FamilyServerInterpreted, "localuser\0\0"). */ + unsigned char changeHosts[64]; + size_t changeHostsLength = 0; + /* The server-interpreted address the host access list must contain afterwards. */ + char target[64]; + size_t targetLength = 0; + /* Report the host access list without changing it (diagnostics, tests). */ + bool listOnly = false; + /* How long to wait for the X server before giving up. */ + unsigned timeoutSeconds = 5; +}; + +/* Child exit codes; only Ok means the user may connect. */ +enum ExitCode : int { + Ok = 0, + PrivilegeDropFailed = 1, + CouldNotConnect = 10, + SetupRejected, + IoError, + Timeout, + ChangeHostsRefused, + ListHostsRefused, + ProtocolError, + NotGranted, +}; + +/* Resolves DISPLAY and, when there is one, its MIT-MAGIC-COOKIE-1 entry. + * xauthority falls back to "/.Xauthority" when null. + * Returns false, filling reason, when DISPLAY is unset, malformed or not a + * local display: host access lists only govern local connections. */ +bool prepareGrant(const char* display, const char* xauthority, const char* homeDirectory, + const char* targetUser, GrantPlan& plan, char* reason, size_t reasonCapacity); + +/* Child side, to be called after dropping back to the original user. Asks + * the X server to add targetUser to its host access list and verifies the + * result by reading the list back. Async-signal-safe; never returns. + * When reportFd >= 0, a single-line NUL-terminated report is written there + * first. */ +[[noreturn]] void runGrant(const GrantPlan& plan, int reportFd); + +/* Parent side: turns the child's wait() status and report into a verdict and + * a human-readable reason. */ +bool describeOutcome(int waitStatus, const char* report, char* reason, size_t reasonCapacity); + +} // namespace X11HostAccess + +#endif // X11HOSTACCESS_H diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index 421529f7..139583f2 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -231,6 +231,9 @@ elseif(APPLE) else() set(PLATFORMQUIRKS_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/../linux/platformquirks_linux.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../linux/x11hostaccess.h + ${CMAKE_CURRENT_SOURCE_DIR}/../linux/x11hostaccess.cpp + x11hostaccess_test.cpp ) set(PLATFORMQUIRKS_LIBS "") endif() diff --git a/src/test/platformquirks_test.cpp b/src/test/platformquirks_test.cpp index f27ab6fa..fe8663b8 100644 --- a/src/test/platformquirks_test.cpp +++ b/src/test/platformquirks_test.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include "platformquirks.h" using Catch::Matchers::ContainsSubstring; diff --git a/src/test/x11hostaccess_test.cpp b/src/test/x11hostaccess_test.cpp new file mode 100644 index 00000000..fb343908 --- /dev/null +++ b/src/test/x11hostaccess_test.cpp @@ -0,0 +1,687 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * Tests for the X11 host access exchange in linux/x11hostaccess.cpp. + * + * The "X server" is a fake that speaks just enough of the protocol for that + * exchange - connection setup, ChangeHosts, ListHosts - so the tests run + * everywhere, including CI, without a display. + */ + +#include + +#include "../linux/x11hostaccess.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using X11HostAccess::ExitCode; +using X11HostAccess::GrantPlan; + +constexpr unsigned char kChangeHosts = 109; +constexpr unsigned char kListHosts = 110; +constexpr unsigned char kFamilyServerInterpreted = 5; +constexpr char kCookieName[] = "MIT-MAGIC-COOKIE-1"; + +/* "si:localuser:" as the server-interpreted address: "localuser\0\0" */ +std::string localUser(const std::string& user) { + return std::string("localuser\0", 10) + user + std::string("\0", 1); +} + +size_t pad4(size_t n) { + return (n + 3) & ~size_t(3); +} + +bool readExactly(int fd, unsigned char* buffer, size_t length) { + while (length > 0) { + const ssize_t n = read(fd, buffer, length); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + return false; + } + buffer += n; + length -= static_cast(n); + } + return true; +} + +void writeAll(int fd, const std::vector& bytes) { + size_t offset = 0; + while (offset < bytes.size()) { + const ssize_t n = send(fd, bytes.data() + offset, bytes.size() - offset, MSG_NOSIGNAL); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + return; // the client gave up: fine for a fake + } + offset += static_cast(n); + } +} + +void putU16(std::vector& bytes, size_t at, unsigned value) { + bytes[at] = static_cast(value); + bytes[at + 1] = static_cast(value >> 8); +} + +/* One record of an Xauthority file: five big-endian length-prefixed fields. */ +void appendAuthorityRecord(std::vector& file, unsigned short family, const std::string& address, + const std::string& number, const std::string& name, const std::string& value) { + const auto field = [&](unsigned short length, const std::string& value) { + file.push_back(static_cast(length >> 8)); + file.push_back(static_cast(length)); + file.insert(file.end(), value.begin(), value.end()); + }; + field(family, ""); + field(static_cast(address.size()), address); + field(static_cast(number.size()), number); + field(static_cast(name.size()), name); + field(static_cast(value.size()), value); +} + +/* A private directory under /tmp that removes its files when done. */ +class TempDirectory { +public: + TempDirectory() { + char path[] = "/tmp/x11hostaccess-auth-XXXXXX"; + REQUIRE(mkdtemp(path) != nullptr); + base_ = path; + } + + ~TempDirectory() { + for (const std::string& name : names_) { + unlink((base_ + "/" + name).c_str()); + } + rmdir(base_.c_str()); + } + + TempDirectory(const TempDirectory&) = delete; + TempDirectory& operator=(const TempDirectory&) = delete; + + const std::string& base() const { + return base_; + } + + /* Path of a file about to be created in the directory. */ + std::string path(const char* name) { + names_.emplace_back(name); + return base_ + "/" + name; + } + +private: + std::string base_; + std::vector names_; +}; + +class FakeXServer { +public: + enum class Behaviour { + InsertAndList, // honour ChangeHosts and list the entry back + ListWithoutUser, // swallow ChangeHosts, list the initial entries + AccessControlDisabled, // swallow ChangeHosts, report access control disabled + RefuseChangeHosts, // XError (BadValue) in reply to ChangeHosts + RefuseConnection, // fail the connection setup with a reason + CloseAfterSetup, // stop answering once the setup reply was sent + Stall, // accept the requests, never answer + Trickle, // answer one byte at a time, never finishing + }; + + struct Observed { + std::string authorizationName; + std::string authorizationData; + unsigned char insertedFamily = 0; + std::string insertedAddress; + bool listHostsRequested = false; + }; + + explicit FakeXServer(std::vector initialHosts = {}) : hosts_(std::move(initialHosts)) { + char directory[] = "/tmp/x11hostaccess-XXXXXX"; + REQUIRE(mkdtemp(directory) != nullptr); + directory_ = directory; + socketPath_ = directory_ + "/X0"; + + listenFd_ = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + REQUIRE(listenFd_ >= 0); + sockaddr_un address = {}; + address.sun_family = AF_UNIX; + std::strncpy(address.sun_path, socketPath_.c_str(), sizeof(address.sun_path) - 1); + REQUIRE(bind(listenFd_, reinterpret_cast(&address), sizeof(address)) == 0); + REQUIRE(listen(listenFd_, 1) == 0); + } + + ~FakeXServer() { + if (thread_.joinable()) { + shutdown(listenFd_, SHUT_RDWR); + thread_.join(); + } + close(listenFd_); + unlink(socketPath_.c_str()); + rmdir(directory_.c_str()); + } + + FakeXServer(const FakeXServer&) = delete; + FakeXServer& operator=(const FakeXServer&) = delete; + + const std::string& socketPath() const { + return socketPath_; + } + + void start(Behaviour behaviour) { + thread_ = std::thread([this, behaviour] { serve(behaviour); }); + } + + /* Waits for the server side of the exchange to end. */ + bool wait(unsigned seconds = 10) { + std::unique_lock lock(mutex_); + return done_.wait_for(lock, std::chrono::seconds(seconds), [this] { return finished_; }); + } + + Observed observed() { + std::lock_guard lock(mutex_); + return observed_; + } + +private: + void serve(Behaviour behaviour) { + const int fd = accept(listenFd_, nullptr, nullptr); + if (fd < 0) { + return; + } + const timeval timeout = {5, 0}; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); + + Observed observed; + unsigned char prefix[12]; + if (readExactly(fd, prefix, sizeof(prefix))) { + const size_t nameLength = prefix[6] | (prefix[7] << 8); + const size_t dataLength = prefix[8] | (prefix[9] << 8); + std::vector authorization(pad4(nameLength) + pad4(dataLength)); + if (readExactly(fd, authorization.data(), authorization.size())) { + observed.authorizationName.assign(authorization.begin(), authorization.begin() + nameLength); + observed.authorizationData.assign(authorization.begin() + pad4(nameLength), + authorization.begin() + pad4(nameLength) + dataLength); + serveRequests(fd, behaviour, observed); + } + } + close(fd); + std::lock_guard lock(mutex_); + observed_ = observed; + finished_ = true; + done_.notify_all(); + } + + void serveRequests(int fd, Behaviour behaviour, Observed& observed) { + if (behaviour == Behaviour::RefuseConnection) { + const std::string reason = "No protocol specified"; + /* xConnSetupPrefix: success, reasonLength, major, minor, additionalLength (offset 6) */ + std::vector reply = {0, static_cast(reason.size()), 11, 0, 0, 0, + static_cast(pad4(reason.size()) / 4), 0}; + reply.insert(reply.end(), reason.begin(), reason.end()); + reply.resize(8 + pad4(reason.size())); + writeAll(fd, reply); + return; + } + /* xConnSetupPrefix with a non-empty setup body (160 bytes), like a real + * server: the client has to consume it before it can read a reply. */ + std::vector setup = {1, 0, 11, 0, 0, 0, 40, 0}; + setup.resize(8 + 160, 0x5a); + writeAll(fd, setup); + if (behaviour == Behaviour::CloseAfterSetup) { + /* Half-close, like a server giving up on this client: the client + * reads end-of-file while its own writes still succeed. */ + shutdown(fd, SHUT_WR); + unsigned char sink[4096]; + while (read(fd, sink, sizeof(sink)) > 0) { + } + return; + } + + for (;;) { + unsigned char header[4]; + if (!readExactly(fd, header, sizeof(header))) { + return; + } + const size_t length = (header[2] | (header[3] << 8)) * 4; + std::vector rest(length > 4 ? length - 4 : 0); + if (!rest.empty() && !readExactly(fd, rest.data(), rest.size())) { + return; + } + + if (header[0] == kChangeHosts) { + /* xChangeHostsReq: mode in header[1]; then family, pad, hostLength, address */ + observed.insertedFamily = rest[0]; + const size_t hostLength = rest[2] | (rest[3] << 8); + observed.insertedAddress.assign(rest.begin() + 4, rest.begin() + 4 + hostLength); + if (behaviour == Behaviour::RefuseChangeHosts) { + std::vector error(32); + error[1] = 2; /* BadValue */ + error[10] = kChangeHosts; + writeAll(fd, error); + } + } else if (header[0] == kListHosts) { + observed.listHostsRequested = true; + if (behaviour == Behaviour::Stall) { + unsigned char sink[4096]; + while (read(fd, sink, sizeof(sink)) > 0) { + } + return; + } + if (behaviour == Behaviour::Trickle) { + /* Each byte arrives well within the client's per-read + * timeout, so only an overall deadline can end this. */ + static const unsigned char reply[32] = {1, 1}; + for (size_t sent = 0; sent < sizeof(reply); ++sent) { + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + if (send(fd, reply + sent, 1, MSG_NOSIGNAL) != 1) { + break; + } + } + return; + } + if (behaviour == Behaviour::InsertAndList && !observed.insertedAddress.empty()) { + hosts_.push_back(observed.insertedAddress); + } + writeListHostsReply(fd, behaviour == Behaviour::AccessControlDisabled ? 0 : 1, hosts_); + return; + } + } + } + + static void writeListHostsReply(int fd, unsigned char enabled, const std::vector& hosts) { + std::vector body; + for (const std::string& host : hosts) { + body.push_back(kFamilyServerInterpreted); + body.push_back(0); + body.push_back(static_cast(host.size())); + body.push_back(0); + body.insert(body.end(), host.begin(), host.end()); + body.resize(pad4(body.size())); + } + std::vector reply(32); + reply[0] = 1; + reply[1] = enabled; + putU16(reply, 4, static_cast(body.size() / 4)); + putU16(reply, 6, 0); + putU16(reply, 8, static_cast(hosts.size())); + putU16(reply, 10, 0); + reply.insert(reply.end(), body.begin(), body.end()); + writeAll(fd, reply); + } + + std::string directory_; + std::string socketPath_; + int listenFd_ = -1; + std::vector hosts_; // server thread only, once started + std::thread thread_; + std::mutex mutex_; + std::condition_variable done_; + Observed observed_; // guarded by mutex_ + bool finished_ = false; // guarded by mutex_ +}; + +struct Outcome { + int code; + std::string report; +}; + +/* Runs runGrant() the way the imager does: in a forked child that reports + * through a pipe. */ +Outcome runInChild(GrantPlan plan) { + int fds[2]; + REQUIRE(pipe(fds) == 0); + const pid_t pid = fork(); + REQUIRE(pid >= 0); + if (pid == 0) { + // Child of a multi-threaded process: async-signal-safe code only + close(fds[0]); + X11HostAccess::runGrant(plan, fds[1]); + _exit(99); + } + close(fds[1]); + + std::string report; + char buffer[X11HostAccess::kMaxReason]; + ssize_t n; + while ((n = read(fds[0], buffer, sizeof(buffer))) > 0) { + report.append(buffer, static_cast(n)); + } + close(fds[0]); + report.erase(std::remove(report.begin(), report.end(), '\0'), report.end()); + + int status = 0; + REQUIRE(waitpid(pid, &status, 0) == pid); + return {WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status), report}; +} + +/* A plan for ":0" redirected to the fake server's socket. */ +GrantPlan planFor(const FakeXServer& server) { + GrantPlan plan; + char reason[X11HostAccess::kMaxReason]; + REQUIRE(X11HostAccess::prepareGrant(":0", nullptr, nullptr, "root", plan, reason, sizeof(reason))); + plan.socketCount = 1; + std::memcpy(plan.socketPath[0], server.socketPath().c_str(), server.socketPath().size() + 1); + plan.timeoutSeconds = 5; + return plan; +} + +} // namespace + +TEST_CASE("DISPLAY names resolve to local sockets or are declined", "[x11hostaccess]") { + char reason[X11HostAccess::kMaxReason]; + GrantPlan plan; + + SECTION("a local display yields the filesystem socket and the abstract one") { + REQUIRE(X11HostAccess::prepareGrant(":0", nullptr, nullptr, "root", plan, reason, sizeof(reason))); + CHECK(plan.socketCount == 2); + CHECK(std::string(plan.socketPath[0]) == "/tmp/.X11-unix/X0"); + CHECK(plan.socketPath[1][0] == '\0'); + CHECK(std::string(plan.socketPath[1] + 1) == "/tmp/.X11-unix/X0"); + } + + SECTION("display numbers, screens and the unix host are accepted") { + REQUIRE(X11HostAccess::prepareGrant("unix:1", nullptr, nullptr, "root", plan, reason, sizeof(reason))); + CHECK(std::string(plan.socketPath[0]) == "/tmp/.X11-unix/X1"); + REQUIRE(X11HostAccess::prepareGrant("unix/:12.0", nullptr, nullptr, "root", plan, reason, sizeof(reason))); + CHECK(std::string(plan.socketPath[0]) == "/tmp/.X11-unix/X12"); + } + + SECTION("remote, malformed or missing displays are declined with a reason") { + for (const char* display : {"localhost:0", "host:0", "tcp/host:0", ":", ":x", "unix:abc", "", ":0x"}) { + INFO(display); + CHECK_FALSE(X11HostAccess::prepareGrant(display, nullptr, nullptr, "root", plan, reason, sizeof(reason))); + CHECK(std::string(reason).find("DISPLAY=") != std::string::npos); + } + CHECK_FALSE(X11HostAccess::prepareGrant(nullptr, nullptr, nullptr, "root", plan, reason, sizeof(reason))); + CHECK(std::string(reason).find("not set") != std::string::npos); + } +} + +TEST_CASE("The connection setup carries the display's MIT-MAGIC-COOKIE-1", "[x11hostaccess]") { + char hostname[256] = {}; + REQUIRE(gethostname(hostname, sizeof(hostname) - 1) == 0); + const std::string host = hostname; + + const std::string otherCookie(16, '\x11'); + const std::string cookie(16, '\xAB'); + const size_t nameLength = std::strlen(kCookieName); + const size_t setupLength = 12 + pad4(nameLength) + 16; + + std::vector expectedSetup(12); + expectedSetup[0] = 'l'; + expectedSetup[2] = 11; + expectedSetup[6] = static_cast(nameLength); + expectedSetup[8] = 16; + expectedSetup.insert(expectedSetup.end(), kCookieName, kCookieName + nameLength); + expectedSetup.resize(setupLength); + std::copy(cookie.begin(), cookie.end(), expectedSetup.begin() + static_cast(12 + pad4(nameLength))); + + /* An Xauthority file to go with each section; created where the test wants it. */ + TempDirectory directory; + const auto writeAuthority = [&](const char* name, const std::vector& content) { + const std::string path = directory.path(name); + FILE* file = std::fopen(path.c_str(), "wb"); + REQUIRE(file != nullptr); + REQUIRE(std::fwrite(content.data(), 1, content.size(), file) == content.size()); + REQUIRE(std::fclose(file) == 0); + return path; + }; + + char reason[X11HostAccess::kMaxReason]; + GrantPlan plan; + + SECTION("the cookie for the display is sent, not the one for another display") { + std::vector authority; + appendAuthorityRecord(authority, 256, host, "1", kCookieName, otherCookie); + appendAuthorityRecord(authority, 256, host, "0", kCookieName, cookie); + authority.insert(authority.end(), {0, 1, 0}); /* corrupt tail: ignored */ + const std::string path = writeAuthority("Xauthority", authority); + + REQUIRE(X11HostAccess::prepareGrant(":0", path.c_str(), nullptr, "root", plan, reason, sizeof(reason))); + CHECK(plan.setupLength == setupLength); + CHECK(std::vector(plan.setup, plan.setup + plan.setupLength) == expectedSetup); + } + + SECTION("a wildcard record matches every display") { + std::vector authority; + appendAuthorityRecord(authority, 65535, "", "", kCookieName, cookie); + const std::string path = writeAuthority("Xauthority", authority); + + REQUIRE(X11HostAccess::prepareGrant(":7", path.c_str(), nullptr, "root", plan, reason, sizeof(reason))); + CHECK(std::vector(plan.setup, plan.setup + plan.setupLength) == expectedSetup); + } + + SECTION("display managers store the address as /unix") { + std::vector authority; + appendAuthorityRecord(authority, 256, host + "/unix", "0", kCookieName, cookie); + const std::string path = writeAuthority("Xauthority", authority); + + REQUIRE(X11HostAccess::prepareGrant(":0", path.c_str(), nullptr, "root", plan, reason, sizeof(reason))); + CHECK(std::vector(plan.setup, plan.setup + plan.setupLength) == expectedSetup); + } + + SECTION("without $XAUTHORITY the cookie is read from /.Xauthority") { + std::vector authority; + appendAuthorityRecord(authority, 256, host, "0", kCookieName, cookie); + writeAuthority(".Xauthority", authority); + + REQUIRE(X11HostAccess::prepareGrant(":0", nullptr, directory.base().c_str(), "root", plan, reason, + sizeof(reason))); + CHECK(std::vector(plan.setup, plan.setup + plan.setupLength) == expectedSetup); + } + + SECTION("a display the file has no entry for connects without a cookie") { + std::vector authority; + appendAuthorityRecord(authority, 256, host, "1", kCookieName, cookie); + const std::string path = writeAuthority("Xauthority", authority); + + REQUIRE(X11HostAccess::prepareGrant(":3", path.c_str(), nullptr, "root", plan, reason, sizeof(reason))); + CHECK(plan.setupLength == 12); + } + + SECTION("an unreadable authority file is not an error") { + REQUIRE(X11HostAccess::prepareGrant(":0", "/nonexistent/Xauthority", nullptr, "root", plan, reason, + sizeof(reason))); + CHECK(plan.setupLength == 12); + } +} + +TEST_CASE("root is added to the X server's host access list", "[x11hostaccess]") { + FakeXServer server({localUser("master")}); + server.start(FakeXServer::Behaviour::InsertAndList); + + const Outcome outcome = runInChild(planFor(server)); + REQUIRE(server.wait()); + + CHECK(outcome.code == ExitCode::Ok); + CHECK(outcome.report == "si:localuser:root is on the host access list (si:localuser:master, si:localuser:root)"); + CHECK(server.observed().insertedFamily == kFamilyServerInterpreted); + CHECK(server.observed().insertedAddress == localUser("root")); + CHECK(server.observed().listHostsRequested); +} + +TEST_CASE("Every way the grant can fail is reported", "[x11hostaccess]") { + SECTION("the server lists hosts, but not root") { + FakeXServer server({localUser("master")}); + server.start(FakeXServer::Behaviour::ListWithoutUser); + const Outcome outcome = runInChild(planFor(server)); + REQUIRE(server.wait()); + CHECK(outcome.code == ExitCode::NotGranted); + CHECK(outcome.report == "si:localuser:root is not on the host access list (si:localuser:master)"); + } + + SECTION("the server refuses the ChangeHosts request") { + FakeXServer server; + server.start(FakeXServer::Behaviour::RefuseChangeHosts); + const Outcome outcome = runInChild(planFor(server)); + REQUIRE(server.wait()); + CHECK(outcome.code == ExitCode::ChangeHostsRefused); + CHECK(outcome.report == "the X server refused the ChangeHosts request (error 2)"); + } + + SECTION("the server refuses the connection") { + FakeXServer server; + server.start(FakeXServer::Behaviour::RefuseConnection); + const Outcome outcome = runInChild(planFor(server)); + REQUIRE(server.wait()); + CHECK(outcome.code == ExitCode::SetupRejected); + CHECK(outcome.report == "the X server rejected the connection: No protocol specified"); + } + + SECTION("the server stops answering") { + FakeXServer server; + server.start(FakeXServer::Behaviour::CloseAfterSetup); + const Outcome outcome = runInChild(planFor(server)); + REQUIRE(server.wait()); + CHECK(outcome.code == ExitCode::ProtocolError); + CHECK(outcome.report == "no reply to ListHosts: the X server closed the connection"); + } + + SECTION("the server stalls") { + FakeXServer server; + server.start(FakeXServer::Behaviour::Stall); + GrantPlan plan = planFor(server); + plan.timeoutSeconds = 1; + const Outcome outcome = runInChild(plan); + REQUIRE(server.wait()); + CHECK(outcome.code == ExitCode::Timeout); + CHECK(outcome.report == "no reply to ListHosts: timed out waiting for the X server"); + } + + SECTION("the server trickles bytes, keeping every single read alive") { + FakeXServer server; + server.start(FakeXServer::Behaviour::Trickle); + GrantPlan plan = planFor(server); + plan.timeoutSeconds = 1; // deadline: twice this + const auto started = std::chrono::steady_clock::now(); + const Outcome outcome = runInChild(plan); + REQUIRE(server.wait()); + const auto seconds = std::chrono::duration_cast( + std::chrono::steady_clock::now() - started).count(); + CHECK(outcome.code == -SIGALRM); // killed by the deadline + CHECK(seconds < 10); + } + + SECTION("nothing is listening on the socket") { + char reason[X11HostAccess::kMaxReason]; + GrantPlan plan; + REQUIRE(X11HostAccess::prepareGrant(":0", nullptr, nullptr, "root", plan, reason, sizeof(reason))); + plan.socketCount = 1; + std::memcpy(plan.socketPath[0], "/tmp/x11hostaccess-nothing/X0", sizeof("/tmp/x11hostaccess-nothing/X0")); + const Outcome outcome = runInChild(plan); + CHECK(outcome.code == ExitCode::CouldNotConnect); + CHECK(outcome.report == "could not connect to the X display socket /tmp/x11hostaccess-nothing/X0"); + } + + SECTION("access control is disabled, so nobody needs to be listed") { + FakeXServer server({localUser("master")}); + server.start(FakeXServer::Behaviour::AccessControlDisabled); + const Outcome outcome = runInChild(planFor(server)); + REQUIRE(server.wait()); + CHECK(outcome.code == ExitCode::Ok); + CHECK(outcome.report == + "si:localuser:root may connect, access control is disabled (host access list: si:localuser:master)"); + } +} + +TEST_CASE("listOnly reports the host access list without changing it", "[x11hostaccess]") { + SECTION("root is not listed") { + FakeXServer server({localUser("master")}); + server.start(FakeXServer::Behaviour::InsertAndList); + GrantPlan plan = planFor(server); + plan.listOnly = true; + const Outcome outcome = runInChild(plan); + REQUIRE(server.wait()); + CHECK(outcome.code == ExitCode::NotGranted); + CHECK(outcome.report == "si:localuser:root is not on the host access list (si:localuser:master)"); + CHECK(server.observed().insertedAddress.empty()); + CHECK(server.observed().listHostsRequested); + } + + SECTION("root is listed") { + FakeXServer server({localUser("master"), localUser("root")}); + server.start(FakeXServer::Behaviour::InsertAndList); + GrantPlan plan = planFor(server); + plan.listOnly = true; + const Outcome outcome = runInChild(plan); + REQUIRE(server.wait()); + CHECK(outcome.code == ExitCode::Ok); + CHECK(outcome.report == "si:localuser:root is on the host access list (si:localuser:master, si:localuser:root)"); + } + + SECTION("an empty list") { + FakeXServer server; + server.start(FakeXServer::Behaviour::InsertAndList); + GrantPlan plan = planFor(server); + plan.listOnly = true; + const Outcome outcome = runInChild(plan); + REQUIRE(server.wait()); + CHECK(outcome.code == ExitCode::NotGranted); + CHECK(outcome.report == "si:localuser:root is not on the host access list (empty)"); + } +} + +TEST_CASE("describeOutcome explains every way the helper can end", "[x11hostaccess]") { + char reason[X11HostAccess::kMaxReason]; + + CHECK(X11HostAccess::describeOutcome(ExitCode::Ok << 8, "all good", reason, sizeof(reason))); + CHECK(std::string(reason) == "all good"); + + CHECK_FALSE(X11HostAccess::describeOutcome(ExitCode::SetupRejected << 8, "the X server said no", reason, + sizeof(reason))); + CHECK(std::string(reason) == "the X server said no"); + + const int codes[] = {X11HostAccess::PrivilegeDropFailed, X11HostAccess::CouldNotConnect, X11HostAccess::IoError, + X11HostAccess::Timeout, X11HostAccess::ChangeHostsRefused, + X11HostAccess::ListHostsRefused, X11HostAccess::ProtocolError, + X11HostAccess::NotGranted, 99}; + for (const int code : codes) { + INFO(code); + CHECK_FALSE(X11HostAccess::describeOutcome(code << 8, "", reason, sizeof(reason))); + CHECK(std::strlen(reason) > 0); + } + CHECK_FALSE(X11HostAccess::describeOutcome(ExitCode::NotGranted << 8, "", reason, sizeof(reason))); + CHECK(std::string(reason) == "the user is not on the X server's host access list"); + + CHECK_FALSE(X11HostAccess::describeOutcome(SIGKILL, "", reason, sizeof(reason))); + CHECK(std::string(reason) == "the grant helper was killed by signal 9"); +} + +/* Read-only check against a real X server: lists the host access list, changes + * nothing. Run with X11HOSTACCESS_TEST_DISPLAY=:0 to include it. */ +TEST_CASE("The exchange works against a real X server", "[x11hostaccess][.hidden]") { + const char* display = std::getenv("X11HOSTACCESS_TEST_DISPLAY"); + if (!display) { + SKIP("set X11HOSTACCESS_TEST_DISPLAY to test against a real X server"); + } + + GrantPlan plan; + char reason[X11HostAccess::kMaxReason]; + REQUIRE(X11HostAccess::prepareGrant(display, nullptr, nullptr, "root", plan, reason, sizeof(reason))); + plan.listOnly = true; + + const Outcome outcome = runInChild(plan); + CHECK((outcome.code == ExitCode::Ok || outcome.code == ExitCode::NotGranted)); + WARN("X server " << display << ": " << outcome.report); +}