From 1ccb55cf6572952737f3c9c3a99485c87cf0e992 Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Fri, 27 Nov 2026 16:22:06 +0100 Subject: [PATCH 1/4] Build Debian package with dpkg-deb so it works on arm64 runners jiro4989/build-deb-action runs a prebuilt amd64-only Docker image, which fails on the ubuntu-22.04-arm runner with a platform mismatch. Generate the DEBIAN/control file and call dpkg-deb directly instead; the step still exposes file_name for the release upload. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index bc4a09de..c85f775f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -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 + 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 < + 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' }} From bdeb9e7f754e517687e2ffe42d8a9a39c512cae0 Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Tue, 1 Dec 2026 14:54:36 +0100 Subject: [PATCH 2/4] Addessed GHSA-5qr8-cfvx-c7vx as advised for agent crash --- agent_version.txt | 2 +- src/mtconnect/sink/rest_sink/rest_service.cpp | 6 + .../rest_sink/websocket_request_manager.hpp | 11 +- .../sink/rest_sink/websocket_session.hpp | 12 ++ test_package/CMakeLists.txt | 12 +- test_package/websockets_rest_sink_test.cpp | 40 +++++++ test_package/websockets_test.cpp | 106 ++++++++++++++++++ 7 files changed, 185 insertions(+), 4 deletions(-) diff --git a/agent_version.txt b/agent_version.txt index 94a38ce1..d250ff62 100644 --- a/agent_version.txt +++ b/agent_version.txt @@ -1 +1 @@ -2.8.0.6 +2.8.0.7 diff --git a/src/mtconnect/sink/rest_sink/rest_service.cpp b/src/mtconnect/sink/rest_sink/rest_service.cpp index 9c6fa3c4..4a4b874e 100644 --- a/src/mtconnect/sink/rest_sink/rest_service.cpp +++ b/src/mtconnect/sink/rest_sink/rest_service.cpp @@ -1138,6 +1138,12 @@ namespace mtconnect { checkRange(printer, interval, -1, numeric_limits().max(), "interval"); checkRange(printer, heartbeatIn, 1, numeric_limits().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 lock(m_sinkContract->getCircularBuffer()); diff --git a/src/mtconnect/sink/rest_sink/websocket_request_manager.hpp b/src/mtconnect/sink/rest_sink/websocket_request_manager.hpp index 003e49d7..1b90bc39 100644 --- a/src/mtconnect/sink/rest_sink/websocket_request_manager.hpp +++ b/src/mtconnect/sink/rest_sink/websocket_request_manager.hpp @@ -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). diff --git a/src/mtconnect/sink/rest_sink/websocket_session.hpp b/src/mtconnect/sink/rest_sink/websocket_session.hpp index 666d40fa..3d6f41e4 100644 --- a/src/mtconnect/sink/rest_sink/websocket_session.hpp +++ b/src/mtconnect/sink/rest_sink/websocket_session.hpp @@ -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"; @@ -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())); diff --git a/test_package/CMakeLists.txt b/test_package/CMakeLists.txt index ffce8c28..ef746898 100644 --- a/test_package/CMakeLists.txt +++ b/test_package/CMakeLists.txt @@ -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}") diff --git a/test_package/websockets_rest_sink_test.cpp b/test_package/websockets_rest_sink_test.cpp index ea373ff6..cca5bea3 100644 --- a/test_package/websockets_rest_sink_test.cpp +++ b/test_package/websockets_rest_sink_test.cpp @@ -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"); + } +} diff --git a/test_package/websockets_test.cpp b/test_package/websockets_test.cpp index c399fef2..2d78c1a8 100644 --- a/test_package/websockets_test.cpp +++ b/test_package/websockets_test.cpp @@ -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; @@ -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(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(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(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); +} From 39bb0cf9188922bb51cb087c8c8bb85da8fc3bf1 Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Tue, 1 Dec 2026 18:29:24 +0100 Subject: [PATCH 3/4] Addressed GHSA-vw7q-qc2r-cf92: stack exhaustion from deeply nested WebSocket JSON Parse WebSocket requests with RapidJSON's iterative parser so nesting depth no longer consumes worker-thread stack; a ~200 kB message of '[' could crash the agent. Apply the same flag to the entity and device JSON parsers. Also validate array parameters in WebSocket requests: non-string elements were read with GetString() and could segfault, and an empty array threw instead of producing an empty value. Co-Authored-By: Claude Opus 5.5 --- src/mtconnect/entity/json_parser.cpp | 2 +- src/mtconnect/parser/json_parser.cpp | 2 +- .../rest_sink/websocket_request_manager.hpp | 26 +++++-- test_package/websockets_test.cpp | 77 +++++++++++++++++++ 4 files changed, 100 insertions(+), 7 deletions(-) diff --git a/src/mtconnect/entity/json_parser.cpp b/src/mtconnect/entity/json_parser.cpp index 60020631..a1f1c26f 100644 --- a/src/mtconnect/entity/json_parser.cpp +++ b/src/mtconnect/entity/json_parser.cpp @@ -182,7 +182,7 @@ namespace mtconnect { NAMED_SCOPE("entity.json_parser"); EntityPtr entity; rj::Document jsonDoc; - jsonDoc.Parse(document.c_str()); + jsonDoc.Parse(document.c_str()); if (jsonDoc.HasParseError()) { diff --git a/src/mtconnect/parser/json_parser.cpp b/src/mtconnect/parser/json_parser.cpp index 4c04aea2..72ed65a6 100644 --- a/src/mtconnect/parser/json_parser.cpp +++ b/src/mtconnect/parser/json_parser.cpp @@ -57,7 +57,7 @@ namespace mtconnect::parser { list deviceList; rj::Document doc; - doc.Parse(jsonDoc.c_str()); + doc.Parse(jsonDoc.c_str()); if (doc.HasParseError()) { diff --git a/src/mtconnect/sink/rest_sink/websocket_request_manager.hpp b/src/mtconnect/sink/rest_sink/websocket_request_manager.hpp index 1b90bc39..4ebc7857 100644 --- a/src/mtconnect/sink/rest_sink/websocket_request_manager.hpp +++ b/src/mtconnect/sink/rest_sink/websocket_request_manager.hpp @@ -130,7 +130,10 @@ namespace mtconnect::sink::rest_sink { using namespace std; Document doc; - doc.Parse(buffer.c_str()); + // Parse iteratively: the default recursive parser uses one stack frame per nesting level, + // so a deeply nested message from a client exhausts the worker thread's stack + // (GHSA-vw7q-qc2r-cf92). + doc.Parse(buffer.c_str()); RequestPtr request; @@ -192,11 +195,24 @@ namespace mtconnect::sink::rest_sink { case rapidjson::kArrayType: { const auto& array = it.value.GetArray(); - std::stringstream buf; + string str; for (const auto& s : array) - buf << s.GetString() << ";"; - string str = buf.str(); - str.erase(str.length() - 1); // Remove last ; + { + // GetString() on a non-string value reads the value's bits as a pointer. + if (!s.IsString()) + { + stringstream err; + err << "Websocket Read Error: array parameter '" << it.name.GetString() + << "' must contain only strings"; + LOG(warning) << err.str(); + auto error = Error::make(Error::ErrorCode::INVALID_REQUEST, err.str()); + throw RestError(error, m_httpRequest->m_accepts, rest_sink::status::bad_request, + std::nullopt, "ERROR"); + } + if (!str.empty()) + str += ';'; + str.append(s.GetString(), s.GetStringLength()); + } request->m_parameters.emplace(make_pair(it.name.GetString(), ParameterValue(str))); break; } diff --git a/test_package/websockets_test.cpp b/test_package/websockets_test.cpp index 2d78c1a8..c8b5e603 100644 --- a/test_package/websockets_test.cpp +++ b/test_package/websockets_test.cpp @@ -379,6 +379,83 @@ TEST_F(WebsocketsTest, should_return_error_when_bad_json_is_sent) ASSERT_EQ("InvalidRequest: Websocket Read Error(offset (0)): Invalid value.", m_client->m_result); } +// GHSA-vw7q-qc2r-cf92: deeply nested JSON must not exhaust the stack. +TEST_F(WebsocketsTest, should_return_error_when_deeply_nested_json_is_sent) +{ + m_server->addRouting({boost::beast::http::verb::get, "/sample?interval={integer}", + [](SessionPtr, RequestPtr) { return true; }}) + .command("sample"); + m_server->addCommands(); + + start(); + startClient(); + + string nested(1'000'000, '['); + asio::spawn(m_context, std::bind(&Client::request, m_client.get(), nested, std::placeholders::_1), + boost::asio::detached); + + m_client->waitFor(5s, [this]() { return m_client->m_done; }); + + ASSERT_TRUE(m_client->m_done); + ASSERT_EQ(0, m_client->m_result.find("InvalidRequest: Websocket Read Error")); +} + +TEST_F(WebsocketsTest, should_return_error_when_array_parameter_has_non_string_values) +{ + bool called {false}; + m_server->addRouting({boost::beast::http::verb::get, "/sample?interval={integer}", + [&](SessionPtr, RequestPtr) { return called = true; }}) + .command("sample"); + m_server->addCommands(); + + start(); + startClient(); + + asio::spawn(m_context, + std::bind(&Client::request, m_client.get(), + R"({"id": "1", "request": "sample", "path": [1, {"a": 2}]})"s, + std::placeholders::_1), + boost::asio::detached); + + m_client->waitFor(2s, [this]() { return m_client->m_done; }); + + ASSERT_TRUE(m_client->m_done); + ASSERT_FALSE(called); + ASSERT_EQ("InvalidRequest: Websocket Read Error: array parameter 'path' must contain only strings", + m_client->m_result); +} + +TEST_F(WebsocketsTest, should_accept_empty_array_parameter) +{ + string path {"unset"}; + m_server->addRouting({boost::beast::http::verb::get, "/sample?path={string}&interval={integer}", + [&](SessionPtr session, RequestPtr request) { + path = request->parameter("path").value_or("missing"); + ResponsePtr resp = make_unique(status::ok); + resp->m_body = "ok"; + resp->m_requestId = request->m_requestId; + session->writeResponse(std::move(resp), []() {}); + return true; + }}) + .command("sample"); + m_server->addCommands(); + + start(); + startClient(); + + asio::spawn(m_context, + std::bind(&Client::request, m_client.get(), + R"({"id": "1", "request": "sample", "path": []})"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("ok", m_client->m_result); + ASSERT_EQ("", path); +} + TEST_F(WebsocketsTest, should_return_multiple_errors_when_parameters_are_invalid) { weak_ptr savedSession; From 706746ce5dd93bf7aa894df724697287b4e1701e Mon Sep 17 00:00:00 2001 From: Will Sobel Date: Thu, 3 Dec 2026 12:42:17 +0100 Subject: [PATCH 4/4] Change the maintainer of the deb package to AMT --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c85f775f..0c591298 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -210,7 +210,7 @@ jobs: Priority: optional Architecture: ${{ matrix.arch }} Installed-Size: $(du -sk --exclude=DEBIAN pkgroot | cut -f1) - Maintainer: Datanomix + Maintainer: Association for Manufacturing Technology Description: MTConnect Agent for Ubuntu (${{ matrix.arch }}) EOF FILE_NAME="mtconnect-agent_${PACKAGE_VERSION}_${{ matrix.arch }}.deb"