[MG_Remote, MG_Test, ci] (P7): one constant-time token comparison serves both server policy sites, a configured token shorter than 16 bytes refuses the listen by name, and CI builds flatc so the TCP supervisor smoke runs and must pass

This commit is contained in:
2026-09-22 21:00:57 -04:00
parent 8a445a3098
commit 8fa1821ab2
10 changed files with 387 additions and 26 deletions
+31
View File
@@ -2,8 +2,10 @@
#pragma once
#include "CapsCodec.h"
#include "Protocol/generated/protocol_generated.h"
#include "Transport/AuthToken.h"
#include "Transport/ITransport.h"
#include <MG_Util/Debug/Log.h>
#include <cstddef>
#include <cstdlib>
#include <cstring>
@@ -37,6 +39,35 @@ namespace MobileGL::MG_Remote {
return true;
}
// PH-7 (1)(2), ID-P7-3. THE TOKEN POLICY, ONCE, FOR BOTH SERVER-SIDE SITES.
//
// ServerSession::Accept and ServerMain::RunSession each had their own reading of it (see
// Transport/AuthToken.h for what the three readings were). They now call this, so the answer
// to "is this peer allowed to open a session" is one function with one comparison, and it is
// the constant-time one.
//
// THE FOUR STATES, stated here because they were implicit and therefore different at each
// site:
// in-process - there is no peer; the "connection" is this process. Never authenticated.
// no token - not an empty credential: the LISTEN policy has already confined this
// server to loopback (SocketTransport.cpp's ListenTcp), so there is nothing
// left for a token to add. A peer that sends one anyway is not refused for
// it; ServerMain used to do that and no document ever said so.
// token, match - welcomed.
// token, mismatch - `Refuse{Authentication}`, detail "token mismatch", and the value is
// not in the line. A missing token field is a mismatch, not a separate case.
inline MobileGLResult AuthenticatePeerToken(Transport::ITransport& transport,
const ::flatbuffers::String* presented) {
if (transport.Role() == Transport::TransportRole::InProcess) return MOBILEGL_OK;
const char* expected = Transport::ConfiguredAuthToken();
if (expected == nullptr) return MOBILEGL_OK;
const char* bytes = presented == nullptr ? "" : presented->c_str();
const std::size_t size = presented == nullptr ? 0u : presented->size();
if (Transport::ConstantTimeTokenMatch(expected, bytes, size)) return MOBILEGL_OK;
return RefuseHandshake(transport, ::MobileGL::Wire::RefuseCode::Authentication,
"token mismatch");
}
inline MobileGLResult ValidatePeerHandshake(Transport::ITransport& transport,
Uint32 major, Uint32 minor, Uint64 fingerprint,
const char* stamp, ::MobileGL::Wire::DialMode dial) {
+8 -8
View File
@@ -87,14 +87,14 @@ void SendLogAck(void* pointer) {
if (ValidatePeerHandshake(*control, hello->abiMajor(), hello->abiMinor(),
hello->wireFingerprint(), hello->buildFingerprint() ? hello->buildFingerprint()->c_str() : nullptr,
hello->dialMode()) != MOBILEGL_OK) ::_exit(0);
if (tcp) {
const char* expected = std::getenv("MOBILEGL_IPC_TOKEN");
const std::string token = hello->token() ? hello->token()->str() : std::string();
if (token != (expected ? expected : "")) {
Refuse(*control, Protocol::RefuseCode::Authentication, "TCP token mismatch");
::_exit(0);
}
}
// PH-7 (1). The SAME policy ServerSession::Accept applies, from Handshake.h, so the
// supervisor's pre-fork answer and the session's post-fork answer cannot drift. What went:
// a `std::string` comparison (byte-at-a-time, early-returning) that ALSO refused a peer for
// presenting a token to a server that had configured none, and a `tcp` guard that made the
// unix control socket exempt by construction rather than by the policy's own reasoning.
// RefuseHandshake logs `Refuse{Authentication}` and sends the peer the frame; the supervisor's
// local Refuse() helper stays for the refusals that are its own (Busy, backend).
if (AuthenticatePeerToken(*control, hello->token()) != MOBILEGL_OK) ::_exit(0);
MobileGL::MG_ConfigLoader::Init();
MobileGL::MG_Config::Transport = MobileGL::MG_Config::TransportMode::Spawn;
MobileGL::MG_Pipe::MGPipeSetServerProcessRole(true);
+5 -6
View File
@@ -545,12 +545,11 @@ namespace MobileGL::MG_Remote::Server {
if (stream && transport.Role() == Transport::TransportRole::InProcess)
return RefuseHandshake(transport, ::MobileGL::Wire::RefuseCode::LinkTerms,
"stream requires a data connection");
const char* expectedToken = std::getenv("MOBILEGL_IPC_TOKEN");
if (transport.Role() != Transport::TransportRole::InProcess && expectedToken != nullptr &&
expectedToken[0] != '\0' && (hello->token() == nullptr ||
std::strcmp(hello->token()->c_str(), expectedToken) != 0))
return RefuseHandshake(transport, ::MobileGL::Wire::RefuseCode::Authentication,
"token mismatch");
// PH-7 (1). One policy, one constant-time comparison, shared with ServerMain's supervisor
// child (Handshake.h AuthenticatePeerToken). This site used std::strcmp, which returns at
// the first differing byte.
const MobileGLResult authenticated = AuthenticatePeerToken(transport, hello->token());
if (authenticated != MOBILEGL_OK) return authenticated;
if (hello->backendType() >= static_cast<Uint32>(BackendType::BackendTypeCount) ||
(m_backend != nullptr && hello->backendType() != static_cast<Uint32>(m_backend->GetBackendType())))
return RefuseHandshake(transport, ::MobileGL::Wire::RefuseCode::Backend,
+90
View File
@@ -0,0 +1,90 @@
// MobileGL - MobileGL/MG_Remote/Transport/AuthToken.h
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
// PH-7 (1)(2)(3), ID-P7-3. THE ONE PLACE THAT KNOWS WHAT `MOBILEGL_IPC_TOKEN` MEANS.
//
// It was three places, and the three did not agree:
//
// SocketTransport.cpp's ListenTcp asked only "is it non-empty", and a one-byte token
// therefore unlocked a `tcp://0.0.0.0` listen.
// ServerSession.cpp compared with `std::strcmp` under "the role is not InProcess AND a token
// is configured".
// ServerMain.cpp compared with `std::string::operator==` under "the control connection is
// TCP", which additionally demanded that a peer present an EMPTY token to a server that had
// configured none - a rule the other site did not have and no document states.
//
// Two of the three compared byte-at-a-time and returned at the first differing byte. That is the
// textbook remote timing oracle: an attacker who can retry learns the token one byte at a time
// instead of guessing 2^128. Whether it is exploitable over a LAN at these timings is beside the
// point; the comparison costs the same either way, and a security property nobody has to
// re-derive is worth more than a measurement.
//
// WHY A MINIMUM LENGTH IS A LISTEN-TIME REFUSAL AND NOT A WARNING. Ph's threat model (ID-P7-3)
// is "anybody who can reach the port has a remote code path". The answer to it is the token, so
// a token an attacker can enumerate is not an answer - it is the appearance of one, which is
// worse than no token at all, because `no token` is already handled: it confines the listener to
// loopback. A four-byte token, before this file, did not confine anything. 16 bytes is the
// floor, it is checked where the listener is opened, and a short token FAILS THE LISTEN rather
// than silently degrading to loopback-only: an operator who set a token and got a loopback
// server would have no way to tell that from success, which is the exact silence Ph exists to
// remove.
//
// The token is never logged, at any level, on any path. The refusals name the policy, not the
// secret (CONTRACT-P65: "错令牌返回 Refuse,不打印令牌值").
#pragma once
#include <cstddef>
#include <cstdlib>
#include <cstring>
namespace MobileGL::MG_Remote::Transport {
// 128 bits of secret, in the encoding an environment variable can carry. The same width as
// `Welcome.dataNonce` (PH-7 (4)) for the same reason: below it, guessing is cheaper than
// attacking anything else in this design.
inline constexpr std::size_t kMinimumAuthTokenBytes = 16;
// The configured token, or nullptr when none is configured. An EMPTY value is "none": every
// TCP lane in this tree sets `MOBILEGL_IPC_TOKEN=` precisely to say so (see
// MG_IntegrationTest/CMakeLists.txt's three arm environments), and an empty string is not a
// secret under any reading.
inline const char* ConfiguredAuthToken() {
const char* value = std::getenv("MOBILEGL_IPC_TOKEN");
return value != nullptr && value[0] != '\0' ? value : nullptr;
}
// Long enough to be a credential. Asked only of a CONFIGURED token; "none" is a separate
// state with its own policy (loopback-only), not a zero-length token.
inline bool AuthTokenIsLongEnough(const char* token) {
return token != nullptr && std::strlen(token) >= kMinimumAuthTokenBytes;
}
// Constant time in the CONTENTS of both operands.
//
// The loop runs over the expected token's length and never leaves early, so the time depends
// on that length - which is this process's own configuration, fixed before any peer connects
// and not attacker-controlled - and on nothing the peer sent. The two lengths are folded into
// the accumulator rather than branched on, so a peer cannot learn the token's length from a
// faster answer either. Past the presented token's end the comparison reads a zero, which is
// a value, not a short-circuit: `presented` is never indexed out of its own bounds.
inline bool ConstantTimeTokenMatch(const char* expected, const char* presented,
std::size_t presentedSize) {
if (expected == nullptr) return false;
const std::size_t expectedSize = std::strlen(expected);
std::size_t difference = expectedSize ^ presentedSize;
for (std::size_t index = 0; index < expectedSize; ++index) {
const unsigned char theirs =
index < presentedSize ? static_cast<unsigned char>(presented[index]) : 0u;
difference |= static_cast<unsigned char>(
static_cast<unsigned char>(expected[index]) ^ theirs);
}
return difference == 0;
}
} // namespace MobileGL::MG_Remote::Transport
@@ -8,6 +8,7 @@
#include "SocketTransport.h"
#include "AuthToken.h"
#include "Doorbell.h" // kWaitForever
#include "FdPassing.h"
#include "WireLog.h"
@@ -153,8 +154,24 @@ namespace MobileGL::MG_Remote::Transport {
MobileGLResult ListenTcp(const std::string& name, int* outFd) {
addrinfo* addresses = nullptr;
if (!TcpAddress(name, &addresses)) return MOBILEGL_ERR_INVALID_ARGUMENT;
const char* token = std::getenv("MOBILEGL_IPC_TOKEN");
const bool authenticated = token != nullptr && token[0] != '\0';
// PH-7 (3), ID-P7-3. A CONFIGURED TOKEN IS EITHER A CREDENTIAL OR A REFUSAL.
//
// This read `getenv(...) != nullptr && token[0] != '\0'`, so ANY non-empty value -
// one byte - opened a `tcp://0.0.0.0` listen. The listen is the only place that can
// still say no cheaply and to the operator rather than to a peer, so the length is
// asked here, and a short token fails the listen outright instead of quietly
// becoming a loopback-only server that looks exactly like a working one.
// AuthToken.h holds the constant and the reason.
const char* token = ConfiguredAuthToken();
if (token != nullptr && !AuthTokenIsLongEnough(token)) {
WireLogError("MG_Remote: Refuse{Authentication} MOBILEGL_IPC_TOKEN is %zu bytes "
"and the minimum is %zu (PH-7 (3)); refusing to listen on %s rather "
"than authenticating with a guessable secret",
std::strlen(token), kMinimumAuthTokenBytes, name.c_str());
::freeaddrinfo(addresses);
return MOBILEGL_ERR_PROTOCOL_MISMATCH;
}
const bool authenticated = token != nullptr;
MobileGLResult result = MOBILEGL_ERR_UNSUPPORTED;
for (auto* address = addresses; address; address = address->ai_next) {
if (!authenticated && !Loopback(address->ai_addr)) {
@@ -36,6 +36,7 @@
// is one this side already reassembled out of bytes nobody else can re-deliver.
#include <MG_Remote/Protocol/generated/protocol_generated.h> // RefuseCode, for the word below
#include <MG_Remote/Transport/AuthToken.h> // PH-7 (3): the minimum and the comparison
#include <MG_Remote/Transport/Doorbell.h> // kWaitForever
#include <MG_Remote/Transport/FdPassing.h>
#include <MG_Remote/Transport/SocketTransport.h>
@@ -131,6 +132,55 @@ TEST(SocketTransportTest, TcpRejectsMalformedNamesAndUnauthenticatedWildcard) {
if (wasSet) ::setenv("MOBILEGL_IPC_TOKEN", saved.c_str(), 1);
}
// PH-7 (3), ID-P7-3. A CONFIGURED TOKEN IS EITHER A CREDENTIAL OR A REFUSAL.
//
// The listen policy used to ask only "non-empty", so a one-byte MOBILEGL_IPC_TOKEN opened a
// wildcard listen. The end-to-end half of this - the supervisor PROCESS dying with a named
// reason rather than degrading to a loopback server that looks like success - is
// TcpLane.SupervisorProtocolControls; this is the cheap half, and it also pins that the refusal
// applies on LOOPBACK, where a short token would otherwise be harmless. Silently accepting it
// there is what would let a short token reach a deployment.
TEST(SocketTransportTest, TcpRefusesToListenWithATokenShorterThanTheMinimum) {
const char* prior = std::getenv("MOBILEGL_IPC_TOKEN");
const std::string saved = prior ? prior : "";
const bool wasSet = prior != nullptr;
const std::string tooShort(kMinimumAuthTokenBytes - 1, 'x');
::setenv("MOBILEGL_IPC_TOKEN", tooShort.c_str(), 1);
int listener = -1;
EXPECT_EQ(SocketTransport::Listen("tcp://127.0.0.1:40697", &listener),
MOBILEGL_ERR_PROTOCOL_MISMATCH);
EXPECT_EQ(listener, -1);
// One more byte and the same endpoint comes up, so the refusal above is the LENGTH and not
// the port, the address family or the environment variable's mere presence.
const std::string longEnough(kMinimumAuthTokenBytes, 'x');
::setenv("MOBILEGL_IPC_TOKEN", longEnough.c_str(), 1);
EXPECT_EQ(SocketTransport::Listen("tcp://127.0.0.1:40697", &listener), MOBILEGL_OK);
EXPECT_GE(listener, 0);
if (listener >= 0) ::close(listener);
if (wasSet) ::setenv("MOBILEGL_IPC_TOKEN", saved.c_str(), 1);
else ::unsetenv("MOBILEGL_IPC_TOKEN");
}
// The comparison itself. `std::strcmp` and `std::string::operator==` - the two this replaced -
// both stop at the first differing byte; these cases pin the answers, and the loop in
// AuthToken.h is what makes the time not depend on WHERE the difference is.
TEST(SocketTransportTest, TheTokenComparisonAnswersLengthAndPrefixTheSameWay) {
const char* expected = "0123456789abcdef";
EXPECT_TRUE(ConstantTimeTokenMatch(expected, "0123456789abcdef", 16));
EXPECT_FALSE(ConstantTimeTokenMatch(expected, "0123456789abcdeF", 16));
EXPECT_FALSE(ConstantTimeTokenMatch(expected, "Z123456789abcdef", 16));
// A correct PREFIX is not a match, and neither is a correct token with anything after it.
EXPECT_FALSE(ConstantTimeTokenMatch(expected, "0123456789abcde", 15));
EXPECT_FALSE(ConstantTimeTokenMatch(expected, "0123456789abcdefg", 17));
EXPECT_FALSE(ConstantTimeTokenMatch(expected, "", 0));
// An embedded NUL is compared, not truncated at: `presented` carries its own length because
// a flatbuffers string can hold one and c_str()-plus-strcmp would have stopped there.
const char embedded[] = {'0', '\0', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
EXPECT_FALSE(ConstantTimeTokenMatch(expected, embedded, sizeof(embedded)));
EXPECT_FALSE(ConstantTimeTokenMatch(nullptr, "anything", 8));
}
namespace {
MobileGLByteSpan Span(const std::string& text) {