Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 20 additions & 8 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -197,14 +197,26 @@ jobs:
- name: Create Debian Package
if: ${{ startsWith(github.ref, 'refs/tags/') && matrix.shared == 'False' }}
id: create_debian_package
uses: jiro4989/build-deb-action@v3
with:
package: mtconnect-agent
package_root: ${{ github.workspace}}/pkgroot
version: ${{ env.PACKAGE_VERSION }}
arch: ${{ matrix.arch }}
desc: "MTConnect Agent for Ubuntu (${{ matrix.arch }})"
maintainer: Datanomix <[email protected]>
shell: bash
working-directory: ${{ github.workspace }}
# Uses dpkg-deb directly (preinstalled on Ubuntu runners) instead of a Docker-based
# action, since those images are amd64-only and fail on the arm64 runner.
run: |
mkdir -p pkgroot/DEBIAN
cat > pkgroot/DEBIAN/control <<EOF
Package: mtconnect-agent
Version: ${PACKAGE_VERSION}
Section: misc
Priority: optional
Architecture: ${{ matrix.arch }}
Installed-Size: $(du -sk --exclude=DEBIAN pkgroot | cut -f1)
Maintainer: Datanomix <[email protected]>
Description: MTConnect Agent for Ubuntu (${{ matrix.arch }})
EOF
FILE_NAME="mtconnect-agent_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"
dpkg-deb --root-owner-group --build pkgroot "$FILE_NAME"
dpkg-deb --info "$FILE_NAME"
echo "file_name=$FILE_NAME" >> "$GITHUB_OUTPUT"

- name: Release
if: ${{ startsWith(github.ref, 'refs/tags/') && matrix.shared == 'False' }}
Expand Down
2 changes: 1 addition & 1 deletion agent_version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.8.0.6
2.8.0.7
6 changes: 6 additions & 0 deletions src/mtconnect/sink/rest_sink/rest_service.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1138,6 +1138,12 @@ namespace mtconnect {

checkRange(printer, interval, -1, numeric_limits<int>().max(), "interval");
checkRange(printer, heartbeatIn, 1, numeric_limits<int>().max(), "heartbeat");
{
// Same limits as fetchSampleData(), applied before the stream is set up so an invalid
// count is reported as a request error instead of failing the first chunk.
int upperCountLimit = m_sinkContract->getCircularBuffer().getBufferSize() + 1;
checkRange(printer, count, -upperCountLimit, upperCountLimit, "count", true);
}
if (from)
{
std::lock_guard<CircularBuffer> lock(m_sinkContract->getCircularBuffer());
Expand Down
11 changes: 9 additions & 2 deletions src/mtconnect/sink/rest_sink/websocket_request_manager.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,18 @@ namespace mtconnect::sink::rest_sink {
/// @brief Destroy the request manager
~WebsocketRequestManager() {}

/// @brief clear the request and the set of requests
/// @brief release the HTTP request and what each request holds on to
///
/// The request entries themselves are not destroyed: a response that is still being written
/// refers to the stream buffer of its request. They go away with the manager.
void reset()
{
m_httpRequest.reset();
m_requests.clear();
for (auto& request : m_requests)
{
request.second.m_complete = nullptr;
request.second.m_request.reset();
}
}

/// @brief Set the current request (used for testing).
Expand Down
12 changes: 12 additions & 0 deletions src/mtconnect/sink/rest_sink/websocket_session.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,14 @@ namespace mtconnect::sink::rest_sink {
if (ec)
return super::fail(boost::beast::http::status::internal_server_error, "shutdown", ec);

// close() released the request manager. Do not parse anything that arrives afterwards and do
// not read again: the session goes away when its last handler has completed.
if (!super::m_isOpen)
{
LOG(debug) << "Message received after the websocket session was closed, ignoring";
return;
}

if (len == 0)
{
LOG(debug) << "Empty message received";
Expand Down Expand Up @@ -404,6 +412,10 @@ namespace mtconnect::sink::rest_sink {
super::fail(boost::beast::http::status::not_found, txt.str());
}

// The request handler may have closed the session.
if (!super::m_isOpen)
return;

derived().stream().async_read(
m_buffer,
beast::bind_front_handler(&WebsocketSessionImpl::onRead, derived().shared_ptr()));
Expand Down
12 changes: 11 additions & 1 deletion test_package/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,17 @@ macro(add_agent_test AGENT_TEST_NAME ADD_TEST_HELPER SUB_FOLDER)
# Organize into folders
set_target_properties(${AGENT_TEST_NAME}_test PROPERTIES FOLDER "test/${SUB_FOLDER}")

gtest_discover_tests(${AGENT_TEST_NAME}_test DISCOVERY_MODE PRE_TEST)
# Fill freed memory with a pattern so use-after-free bugs show up as corrupted data
# (see GHSA-5qr8-cfvx-c7vx).
if(APPLE)
gtest_discover_tests(${AGENT_TEST_NAME}_test DISCOVERY_MODE PRE_TEST
PROPERTIES ENVIRONMENT "MallocScribble=1")
elseif(UNIX)
gtest_discover_tests(${AGENT_TEST_NAME}_test DISCOVERY_MODE PRE_TEST
PROPERTIES ENVIRONMENT "MALLOC_PERTURB_=85")
else()
gtest_discover_tests(${AGENT_TEST_NAME}_test DISCOVERY_MODE PRE_TEST)
endif()

if(MSVC AND ${ARGC} GREATER 3)
message(info ": Setting /bigobj for ${_sources}")
Expand Down
40 changes: 40 additions & 0 deletions test_package/websockets_rest_sink_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -654,3 +654,43 @@ TEST_F(WebsocketsRestSinkTest, should_return_error_for_bad_parameter_value)
"query parameter 'at': invalid type, expected uint64");
}
}

// GHSA-5qr8-cfvx-c7vx: A streaming sample with an invalid count used to fail on the first chunk,
// which closed the websocket session and released the request manager state. The next request on
// the same connection then dereferenced a null HTTP request and crashed the agent.
TEST_F(WebsocketsRestSinkTest, should_reject_streaming_sample_with_invalid_count_before_streaming)
{
addAdapter();

m_agentTestHelper->m_adapter->processData("2026-01-01T12:00:00Z|avail|AVAILABLE");

{
PARSE_XML_WS_RESPONSE(
R"({ "id": "1", "request": "sample", "format": "xml", "interval": 100, "count": 0 })");
ASSERT_EQ("1", id);
ASSERT_XML_PATH_EQUAL(doc, "//m:OutOfRange@errorCode", "OUT_OF_RANGE");
ASSERT_XML_PATH_EQUAL(doc, "//m:OutOfRange/m:QueryParameter@name", "count");
}

// The session must still be usable after the error.
m_agentTestHelper->m_ioContext.run_for(50ms);

{
PARSE_XML_WS_RESPONSE(R"({ "id": "2", "request": "probe"})");
ASSERT_EQ("2", id);
ASSERT_XML_PATH_EQUAL(doc, "//m:Devices/m:Device@name", "LinuxCNC");
}
}

TEST_F(WebsocketsRestSinkTest, should_reject_streaming_sample_with_count_larger_than_buffer)
{
addAdapter();

{
PARSE_XML_WS_RESPONSE(
R"({ "id": "1", "request": "sample", "format": "xml", "interval": 100, "count": 10000 })");
ASSERT_EQ("1", id);
ASSERT_XML_PATH_EQUAL(doc, "//m:OutOfRange@errorCode", "OUT_OF_RANGE");
ASSERT_XML_PATH_EQUAL(doc, "//m:OutOfRange/m:QueryParameter@name", "count");
}
}
106 changes: 106 additions & 0 deletions test_package/websockets_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,12 @@ class Client
m_done = true;
}

void startRead()
{
m_done = false;
m_stream.async_read(m_buffer, beast::bind_front_handler(&Client::onRead, this));
}

void request(const string& payload, asio::yield_context yield)
{
cout << "spawnRequest: done: false" << endl;
Expand Down Expand Up @@ -440,3 +446,103 @@ TEST_F(WebsocketsTest, should_return_error_for_an_invalid_command)
ASSERT_TRUE(m_client->m_done);
ASSERT_EQ("InvalidURI: 0.0.0.0: Command failed: sample", m_client->m_result);
}

// GHSA-5qr8-cfvx-c7vx: After a request handler closed the websocket session (as the streaming
// sample error path does), the read loop kept running and the next message was parsed with a null
// HTTP request, crashing the agent.
TEST_F(WebsocketsTest, should_not_process_requests_after_session_is_closed)
{
bool probeCalled = false;
auto probe = [&](SessionPtr session, RequestPtr request) -> bool {
probeCalled = true;
ResponsePtr resp = make_unique<Response>(status::ok);
resp->m_body = "All Devices for "s + *request->m_requestId;
resp->m_requestId = request->m_requestId;
session->writeResponse(std::move(resp));
return true;
};

// Simulates RestService::streamNextSampleChunk failing: write an error and close the session
// asynchronously, after the read loop has already been re-armed.
auto sample = [&](SessionPtr session, RequestPtr request) -> bool {
ResponsePtr resp = make_unique<Response>(status::bad_request);
resp->m_body = "Error for "s + *request->m_requestId;
resp->m_requestId = request->m_requestId;
session->writeFailureResponse(std::move(resp));
asio::post(m_context, [session]() { session->close(); });
return true;
};

m_server->addRouting({boost::beast::http::verb::get, "/probe", probe}).command("probe");
m_server->addRouting({boost::beast::http::verb::get, "/sample", sample}).command("sample");
m_server->addCommands();

start();
startClient();
ASSERT_TRUE(m_client->m_connected);

asio::spawn(m_context,
std::bind(&Client::request, m_client.get(), R"({"id":"1","request":"sample"})"s,
std::placeholders::_1),
boost::asio::detached);
m_client->waitFor(2s, [this]() { return m_client->m_done; });
ASSERT_TRUE(m_client->m_done);
ASSERT_EQ("Error for 1", m_client->m_result);

// Let the posted close run.
m_context.run_for(50ms);

m_client->startRead();
for (auto msg : {R"({"id":"2","request":"probe"})"s, "not json"s})
{
asio::spawn(
m_context,
[this, msg](asio::yield_context yield) {
beast::error_code ec;
m_client->m_stream.async_write(asio::buffer(msg), yield[ec]);
},
boost::asio::detached);
}

m_client->waitFor(1s, [this]() { return m_client->m_done; });

ASSERT_FALSE(probeCalled);
ASSERT_NE("All Devices for 2", m_client->m_result);
}

// GHSA-5qr8-cfvx-c7vx: Closing the websocket session destroyed the request entries, including the
// stream buffer a pending async_write was still sending from (heap use after free).
TEST_F(WebsocketsTest, should_finish_writing_response_when_session_is_closed)
{
string body;
body.reserve(4 * 1024 * 1024);
for (int i = 0; body.size() < 4 * 1024 * 1024; i++)
body.append(to_string(i)).append(";");

auto probe = [&](SessionPtr session, RequestPtr request) -> bool {
ResponsePtr resp = make_unique<Response>(status::ok);
resp->m_body = body;
resp->m_requestId = request->m_requestId;
session->writeResponse(std::move(resp));
// Close while the large response is still being written
session->close();
return true;
};

m_server->addRouting({boost::beast::http::verb::get, "/probe", probe}).command("probe");
m_server->addCommands();

start();
startClient();
ASSERT_TRUE(m_client->m_connected);

asio::spawn(m_context,
std::bind(&Client::request, m_client.get(), R"({"id":"1","request":"probe"})"s,
std::placeholders::_1),
boost::asio::detached);
m_client->waitFor(5s, [this]() { return m_client->m_done; });

ASSERT_TRUE(m_client->m_done);
ASSERT_EQ(body.size(), m_client->m_result.size());
ASSERT_TRUE(body == m_client->m_result);
}
Loading