Skip to content
Merged
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 <support@datanomix.io>
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: Association for Manufacturing Technology <wsobel@amtonline.org>
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
2 changes: 1 addition & 1 deletion src/mtconnect/entity/json_parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ namespace mtconnect {
NAMED_SCOPE("entity.json_parser");
EntityPtr entity;
rj::Document jsonDoc;
jsonDoc.Parse(document.c_str());
jsonDoc.Parse<rj::kParseIterativeFlag>(document.c_str());

if (jsonDoc.HasParseError())
{
Expand Down
2 changes: 1 addition & 1 deletion src/mtconnect/parser/json_parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ namespace mtconnect::parser {
list<DevicePtr> deviceList;

rj::Document doc;
doc.Parse(jsonDoc.c_str());
doc.Parse<rj::kParseIterativeFlag>(jsonDoc.c_str());

if (doc.HasParseError())
{
Expand Down
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
37 changes: 30 additions & 7 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 Expand Up @@ -123,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<kParseIterativeFlag>(buffer.c_str());

RequestPtr request;

Expand Down Expand Up @@ -185,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;
}
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");
}
}
Loading
Loading