From a42fe418412b0888a4092c119cdc9d443df80d8f Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:38:27 +0100 Subject: [PATCH 01/51] Add failing WebSocket frame parser tests Signed-off-by: entlein --- .../protocols/websocket/BUILD.bazel | 41 ++++ .../protocols/websocket/parse.cc | 32 +++ .../socket_tracer/protocols/websocket/parse.h | 36 ++++ .../protocols/websocket/parse_test.cc | 189 ++++++++++++++++++ .../socket_tracer/protocols/websocket/types.h | 59 ++++++ 5 files changed, 357 insertions(+) create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel b/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel new file mode 100644 index 00000000000..e381e516523 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel @@ -0,0 +1,41 @@ +# Copyright 2018- The Pixie Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +load("//bazel:pl_build_system.bzl", "pl_cc_library", "pl_cc_test") + +package(default_visibility = ["//src/stirling:__subpackages__"]) + +pl_cc_library( + name = "cc_library", + srcs = glob( + ["*.cc"], + exclude = [ + "**/*_test.cc", + "**/*_benchmark.cc", + ], + ), + hdrs = glob(["*.h"]), + deps = [ + "//src/stirling/source_connectors/socket_tracer/protocols/common:cc_library", + "//src/stirling/utils:cc_library", + ], +) + +pl_cc_test( + name = "parse_test", + srcs = ["parse_test.cc"], + deps = [":cc_library"], +) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc new file mode 100644 index 00000000000..63bd477df81 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc @@ -0,0 +1,32 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h" + +namespace px { +namespace stirling { +namespace protocols { + +template <> +ParseState ParseFrame(message_type_t, std::string_view*, websocket::Frame*, NoState*) { + return ParseState::kInvalid; +} + +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h new file mode 100644 index 00000000000..3f1425ae9a5 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h @@ -0,0 +1,36 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include + +#include "src/stirling/source_connectors/socket_tracer/protocols/common/interface.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h" + +namespace px { +namespace stirling { +namespace protocols { + +template <> +ParseState ParseFrame(message_type_t type, std::string_view* buf, websocket::Frame* frame, + NoState* state); + +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc new file mode 100644 index 00000000000..dd11359eb10 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc @@ -0,0 +1,189 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h" + +#include + +#include "src/common/testing/testing.h" + +namespace px { +namespace stirling { +namespace protocols { +namespace websocket { + +constexpr uint8_t kUnmaskedText[] = {0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f}; +constexpr uint8_t kMaskedText[] = {0x81, 0x85, 0x37, 0xfa, 0x21, 0x3d, + 0x7f, 0x9f, 0x4d, 0x51, 0x58}; +constexpr uint8_t kFragmentedText[] = {0x01, 0x03, 0x48, 0x65, 0x6c, 0x80, 0x02, 0x6c, 0x6f}; +constexpr uint8_t kUnmaskedPing[] = {0x89, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f}; +constexpr uint8_t kMaskedPong[] = {0x8a, 0x85, 0x37, 0xfa, 0x21, 0x3d, + 0x7f, 0x9f, 0x4d, 0x51, 0x58}; +constexpr uint8_t kCompressedText[] = {0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00}; +constexpr uint8_t kReservedOpcode[] = {0x83, 0x00}; +constexpr uint8_t kFragmentedPing[] = {0x09, 0x00}; +constexpr uint8_t kOversizedClose[] = {0x88, 0x7e, 0x00, 0x7e}; + +template +std::string Bytes(const uint8_t (&arr)[N]) { + return std::string(CreateCharArrayView(arr)); +} + +std::string Frame16(uint16_t len) { + std::string frame = {'\x82', '\x7e', static_cast(len >> 8), static_cast(len & 0xff)}; + return frame + std::string(len, 'x'); +} + +std::string Frame64(uint64_t len) { + std::string frame = {'\x82', '\x7f'}; + for (int shift = 56; shift >= 0; shift -= 8) { + frame.push_back(static_cast((len >> shift) & 0xff)); + } + return frame + std::string(len, 'x'); +} + +class WebSocketParseTest : public ::testing::Test { + protected: + ParseState Parse(std::string_view* buf) { + return ParseFrame(message_type_t::kRequest, buf, &frame_, &state_); + } + + Frame frame_; + NoState state_; +}; + +TEST_F(WebSocketParseTest, UnmaskedTextFrame) { + std::string_view buf = CreateCharArrayView(kUnmaskedText); + + ASSERT_EQ(Parse(&buf), ParseState::kSuccess); + EXPECT_TRUE(frame_.fin); + EXPECT_EQ(frame_.opcode, Opcode::kText); + EXPECT_FALSE(frame_.masked); + EXPECT_EQ(frame_.payload_length, 5U); + EXPECT_EQ(frame_.payload, "Hello"); + EXPECT_TRUE(buf.empty()); +} + +TEST_F(WebSocketParseTest, MaskedTextFrameIsUnmasked) { + std::string_view buf = CreateCharArrayView(kMaskedText); + + ASSERT_EQ(Parse(&buf), ParseState::kSuccess); + EXPECT_TRUE(frame_.masked); + EXPECT_EQ(frame_.opcode, Opcode::kText); + EXPECT_EQ(frame_.payload, "Hello"); + EXPECT_TRUE(buf.empty()); +} + +TEST_F(WebSocketParseTest, FragmentedTextFrames) { + std::string_view buf = CreateCharArrayView(kFragmentedText); + + ASSERT_EQ(Parse(&buf), ParseState::kSuccess); + EXPECT_FALSE(frame_.fin); + EXPECT_EQ(frame_.opcode, Opcode::kText); + EXPECT_EQ(frame_.payload, "Hel"); + + ASSERT_EQ(Parse(&buf), ParseState::kSuccess); + EXPECT_TRUE(frame_.fin); + EXPECT_EQ(frame_.opcode, Opcode::kContinuation); + EXPECT_EQ(frame_.payload, "lo"); + EXPECT_TRUE(buf.empty()); +} + +TEST_F(WebSocketParseTest, ControlFrames) { + std::string_view ping = CreateCharArrayView(kUnmaskedPing); + ASSERT_EQ(Parse(&ping), ParseState::kSuccess); + EXPECT_EQ(frame_.opcode, Opcode::kPing); + EXPECT_EQ(frame_.payload, "Hello"); + + std::string_view pong = CreateCharArrayView(kMaskedPong); + ASSERT_EQ(Parse(&pong), ParseState::kSuccess); + EXPECT_EQ(frame_.opcode, Opcode::kPong); + EXPECT_EQ(frame_.payload, "Hello"); +} + +TEST_F(WebSocketParseTest, CompressedFrameKeepsRsvBits) { + std::string_view buf = CreateCharArrayView(kCompressedText); + + ASSERT_EQ(Parse(&buf), ParseState::kSuccess); + EXPECT_EQ(frame_.rsv, 0x4); + EXPECT_EQ(frame_.opcode, Opcode::kText); + EXPECT_EQ(frame_.payload, Bytes(kCompressedText).substr(2)); +} + +TEST_F(WebSocketParseTest, ExtendedPayloadLengths) { + std::string frame16 = Frame16(256); + std::string_view buf16 = frame16; + ASSERT_EQ(Parse(&buf16), ParseState::kSuccess); + EXPECT_EQ(frame_.opcode, Opcode::kBinary); + EXPECT_EQ(frame_.payload_length, 256U); + EXPECT_EQ(frame_.payload.size(), 256U); + EXPECT_TRUE(buf16.empty()); + + std::string frame64 = Frame64(65536); + std::string_view buf64 = frame64; + ASSERT_EQ(Parse(&buf64), ParseState::kSuccess); + EXPECT_EQ(frame_.payload_length, 65536U); + EXPECT_EQ(frame_.payload.size(), 65536U); + EXPECT_TRUE(buf64.empty()); +} + +TEST_F(WebSocketParseTest, BackToBackFrames) { + std::string data = Bytes(kMaskedText) + Bytes(kUnmaskedPing); + std::string_view buf = data; + + ASSERT_EQ(Parse(&buf), ParseState::kSuccess); + EXPECT_EQ(frame_.opcode, Opcode::kText); + EXPECT_EQ(buf.size(), sizeof(kUnmaskedPing)); + + ASSERT_EQ(Parse(&buf), ParseState::kSuccess); + EXPECT_EQ(frame_.opcode, Opcode::kPing); + EXPECT_TRUE(buf.empty()); +} + +TEST_F(WebSocketParseTest, IncompleteFramesNeedMoreData) { + std::string full = Bytes(kMaskedText); + for (size_t len : {1UL, 2UL, 5UL, full.size() - 1}) { + std::string_view buf(full.data(), len); + EXPECT_EQ(Parse(&buf), ParseState::kNeedsMoreData) << len; + EXPECT_EQ(buf.size(), len) << len; + } + + std::string frame64 = Frame64(65536); + std::string_view header_only(frame64.data(), 6); + EXPECT_EQ(Parse(&header_only), ParseState::kNeedsMoreData); +} + +TEST_F(WebSocketParseTest, InvalidFrames) { + std::string_view reserved = CreateCharArrayView(kReservedOpcode); + EXPECT_EQ(Parse(&reserved), ParseState::kInvalid); + + std::string_view fragmented_ping = CreateCharArrayView(kFragmentedPing); + EXPECT_EQ(Parse(&fragmented_ping), ParseState::kInvalid); + + std::string_view oversized_close = CreateCharArrayView(kOversizedClose); + EXPECT_EQ(Parse(&oversized_close), ParseState::kInvalid); + + std::string msb_set = {'\x82', '\x7f', '\x80', 0, 0, 0, 0, 0, 0, 0}; + std::string_view msb_view = msb_set; + EXPECT_EQ(Parse(&msb_view), ParseState::kInvalid); +} + +} // namespace websocket +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h new file mode 100644 index 00000000000..3f432a4d616 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h @@ -0,0 +1,59 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include + +#include "src/common/base/base.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/common/event_parser.h" + +namespace px { +namespace stirling { +namespace protocols { +namespace websocket { + +enum class Opcode : uint8_t { + kContinuation = 0x0, + kText = 0x1, + kBinary = 0x2, + kClose = 0x8, + kPing = 0x9, + kPong = 0xa, +}; + +struct Frame : public FrameBase { + bool fin = false; + uint8_t rsv = 0; + Opcode opcode = Opcode::kContinuation; + bool masked = false; + uint64_t payload_length = 0; + std::string payload; + + size_t ByteSize() const override { return sizeof(Frame) + payload.size(); } + + std::string ToString() const override { + return absl::Substitute("Frame: {fin: $0, rsv: $1, opcode: $2, masked: $3, len: $4}", fin, rsv, + magic_enum::enum_name(opcode), masked, payload_length); + } +}; + +} // namespace websocket +} // namespace protocols +} // namespace stirling +} // namespace px From ea3ebbef7a54e314c3e2ad902d07d8d6175efb23 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:39:15 +0100 Subject: [PATCH 02/51] Parse WebSocket frames Signed-off-by: entlein --- .../protocols/websocket/parse.cc | 83 ++++++++++++++++++- 1 file changed, 81 insertions(+), 2 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc index 63bd477df81..40b5d941614 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc @@ -18,13 +18,92 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h" +#include +#include + +#include "src/stirling/utils/binary_decoder.h" + namespace px { namespace stirling { namespace protocols { +namespace websocket { +namespace { + +constexpr uint8_t kFinBit = 0x80; +constexpr uint8_t kRsvBits = 0x70; +constexpr uint8_t kRsvShift = 4; +constexpr uint8_t kOpcodeBits = 0x0f; +constexpr uint8_t kControlOpcodeBit = 0x08; +constexpr uint8_t kMaskBit = 0x80; +constexpr uint8_t kPayloadLengthBits = 0x7f; +constexpr uint8_t kPayloadLength16 = 126; +constexpr uint8_t kPayloadLength64 = 127; +constexpr uint64_t kPayloadLength64MSB = 1ULL << 63; +constexpr uint64_t kMaxControlPayloadLength = 125; +constexpr size_t kMaskingKeySize = 4; + +bool IsControl(Opcode opcode) { return static_cast(opcode) & kControlOpcodeBit; } + +} // namespace +} // namespace websocket + template <> -ParseState ParseFrame(message_type_t, std::string_view*, websocket::Frame*, NoState*) { - return ParseState::kInvalid; +ParseState ParseFrame(message_type_t, std::string_view* buf, websocket::Frame* frame, NoState*) { + using websocket::Opcode; + + BinaryDecoder decoder(*buf); + PX_ASSIGN_OR(uint8_t b0, decoder.ExtractBEInt(), return ParseState::kNeedsMoreData); + PX_ASSIGN_OR(uint8_t b1, decoder.ExtractBEInt(), return ParseState::kNeedsMoreData); + + std::optional opcode = magic_enum::enum_cast(b0 & websocket::kOpcodeBits); + if (!opcode.has_value()) { + return ParseState::kInvalid; + } + const bool fin = b0 & websocket::kFinBit; + const bool control = websocket::IsControl(opcode.value()); + if (control && !fin) { + return ParseState::kInvalid; + } + + uint64_t payload_length = b1 & websocket::kPayloadLengthBits; + if (payload_length == websocket::kPayloadLength16) { + PX_ASSIGN_OR(payload_length, decoder.ExtractBEInt(), + return ParseState::kNeedsMoreData); + } else if (payload_length == websocket::kPayloadLength64) { + PX_ASSIGN_OR(payload_length, decoder.ExtractBEInt(), + return ParseState::kNeedsMoreData); + if (payload_length & websocket::kPayloadLength64MSB) { + return ParseState::kInvalid; + } + } + if (control && payload_length > websocket::kMaxControlPayloadLength) { + return ParseState::kInvalid; + } + + const bool masked = b1 & websocket::kMaskBit; + std::string_view masking_key; + if (masked) { + PX_ASSIGN_OR(masking_key, decoder.ExtractString(websocket::kMaskingKeySize), + return ParseState::kNeedsMoreData); + } + PX_ASSIGN_OR(std::string_view payload, decoder.ExtractString(payload_length), + return ParseState::kNeedsMoreData); + + frame->fin = fin; + frame->rsv = (b0 & websocket::kRsvBits) >> websocket::kRsvShift; + frame->opcode = opcode.value(); + frame->masked = masked; + frame->payload_length = payload_length; + frame->payload.assign(payload); + if (masked) { + for (size_t i = 0; i < frame->payload.size(); ++i) { + frame->payload[i] ^= masking_key[i % websocket::kMaskingKeySize]; + } + } + + buf->remove_prefix(buf->size() - decoder.BufSize()); + return ParseState::kSuccess; } } // namespace protocols From 20b0b0cadfd84022e9efa9cca7f2b291a7291c88 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:41:16 +0100 Subject: [PATCH 03/51] Add failing WebSocket message stitcher tests Signed-off-by: entlein --- .../protocols/websocket/BUILD.bazel | 6 + .../protocols/websocket/stitcher.cc | 33 ++++ .../protocols/websocket/stitcher.h | 37 +++++ .../protocols/websocket/stitcher_test.cc | 149 ++++++++++++++++++ .../socket_tracer/protocols/websocket/types.h | 34 ++++ 5 files changed, 259 insertions(+) create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel b/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel index e381e516523..c40e16f3925 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel @@ -39,3 +39,9 @@ pl_cc_test( srcs = ["parse_test.cc"], deps = [":cc_library"], ) + +pl_cc_test( + name = "stitcher_test", + srcs = ["stitcher_test.cc"], + deps = [":cc_library"], +) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc new file mode 100644 index 00000000000..973667fe9d2 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc @@ -0,0 +1,33 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h" + +namespace px { +namespace stirling { +namespace protocols { + +template <> +RecordsWithErrorCount StitchFrames(std::deque*, + std::deque*, NoState*) { + return {}; +} + +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h new file mode 100644 index 00000000000..ef022e6be06 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h @@ -0,0 +1,37 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include + +#include "src/stirling/source_connectors/socket_tracer/protocols/common/interface.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h" + +namespace px { +namespace stirling { +namespace protocols { + +template <> +RecordsWithErrorCount StitchFrames(std::deque* req_frames, + std::deque* resp_frames, + NoState* state); + +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc new file mode 100644 index 00000000000..aaa2e5856fb --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc @@ -0,0 +1,149 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h" + +#include +#include + +#include "src/common/testing/testing.h" + +namespace px { +namespace stirling { +namespace protocols { +namespace websocket { + +Frame MakeFrame(Opcode opcode, bool fin, std::string payload, uint64_t timestamp_ns, + uint8_t rsv = 0) { + Frame frame; + frame.timestamp_ns = timestamp_ns; + frame.fin = fin; + frame.rsv = rsv; + frame.opcode = opcode; + frame.payload_length = payload.size(); + frame.payload = std::move(payload); + return frame; +} + +class WebSocketStitcherTest : public ::testing::Test { + protected: + RecordsWithErrorCount Stitch() { return StitchFrames(&req_frames_, &resp_frames_, &state_); } + + std::deque req_frames_; + std::deque resp_frames_; + NoState state_; +}; + +TEST_F(WebSocketStitcherTest, OneRecordPerMessageInEachDirection) { + req_frames_.push_back(MakeFrame(Opcode::kText, true, "hi", 1)); + resp_frames_.push_back(MakeFrame(Opcode::kBinary, true, "yo", 2)); + + RecordsWithErrorCount result = Stitch(); + + ASSERT_EQ(result.records.size(), 2U); + EXPECT_EQ(result.error_count, 0); + EXPECT_EQ(result.records[0].msg.type, message_type_t::kRequest); + EXPECT_EQ(result.records[0].msg.opcode, Opcode::kText); + EXPECT_EQ(result.records[0].msg.payload, "hi"); + EXPECT_EQ(result.records[0].msg.timestamp_ns, 1U); + EXPECT_EQ(result.records[0].msg.fragments, 1U); + EXPECT_EQ(result.records[1].msg.type, message_type_t::kResponse); + EXPECT_EQ(result.records[1].msg.opcode, Opcode::kBinary); + EXPECT_EQ(result.records[1].msg.payload, "yo"); + EXPECT_TRUE(req_frames_.empty()); + EXPECT_TRUE(resp_frames_.empty()); +} + +TEST_F(WebSocketStitcherTest, FragmentsAreReassembled) { + req_frames_.push_back(MakeFrame(Opcode::kText, false, "Hel", 1, 0x4)); + req_frames_.push_back(MakeFrame(Opcode::kContinuation, true, "lo", 3)); + + RecordsWithErrorCount result = Stitch(); + + ASSERT_EQ(result.records.size(), 1U); + EXPECT_EQ(result.records[0].msg.opcode, Opcode::kText); + EXPECT_EQ(result.records[0].msg.payload, "Hello"); + EXPECT_EQ(result.records[0].msg.timestamp_ns, 1U); + EXPECT_EQ(result.records[0].msg.fragments, 2U); + EXPECT_TRUE(result.records[0].msg.compressed); + EXPECT_TRUE(req_frames_.empty()); +} + +TEST_F(WebSocketStitcherTest, ControlFrameBetweenFragments) { + req_frames_.push_back(MakeFrame(Opcode::kText, false, "Hel", 1)); + req_frames_.push_back(MakeFrame(Opcode::kPing, true, "p", 2)); + req_frames_.push_back(MakeFrame(Opcode::kContinuation, true, "lo", 3)); + + RecordsWithErrorCount result = Stitch(); + + ASSERT_EQ(result.records.size(), 2U); + EXPECT_EQ(result.records[0].msg.opcode, Opcode::kPing); + EXPECT_EQ(result.records[0].msg.payload, "p"); + EXPECT_EQ(result.records[1].msg.opcode, Opcode::kText); + EXPECT_EQ(result.records[1].msg.payload, "Hello"); + EXPECT_TRUE(req_frames_.empty()); +} + +TEST_F(WebSocketStitcherTest, IncompleteMessageWaitsForItsLastFragment) { + req_frames_.push_back(MakeFrame(Opcode::kText, false, "Hel", 1)); + req_frames_.push_back(MakeFrame(Opcode::kPing, true, "p", 2)); + + RecordsWithErrorCount first = Stitch(); + + ASSERT_EQ(first.records.size(), 1U); + EXPECT_EQ(first.records[0].msg.opcode, Opcode::kPing); + ASSERT_EQ(req_frames_.size(), 1U); + EXPECT_EQ(req_frames_.front().payload, "Hel"); + + req_frames_.push_back(MakeFrame(Opcode::kContinuation, true, "lo", 3)); + RecordsWithErrorCount second = Stitch(); + + ASSERT_EQ(second.records.size(), 1U); + EXPECT_EQ(second.records[0].msg.payload, "Hello"); + EXPECT_TRUE(req_frames_.empty()); +} + +TEST_F(WebSocketStitcherTest, ContinuationWithoutStartIsAnError) { + req_frames_.push_back(MakeFrame(Opcode::kContinuation, true, "lo", 1)); + req_frames_.push_back(MakeFrame(Opcode::kText, true, "next", 2)); + + RecordsWithErrorCount result = Stitch(); + + ASSERT_EQ(result.records.size(), 1U); + EXPECT_EQ(result.records[0].msg.payload, "next"); + EXPECT_EQ(result.error_count, 1); + EXPECT_TRUE(req_frames_.empty()); +} + +TEST_F(WebSocketStitcherTest, NewMessageBeforeLastFragmentIsAnError) { + req_frames_.push_back(MakeFrame(Opcode::kText, false, "lost", 1)); + req_frames_.push_back(MakeFrame(Opcode::kBinary, true, "next", 2)); + + RecordsWithErrorCount result = Stitch(); + + ASSERT_EQ(result.records.size(), 1U); + EXPECT_EQ(result.records[0].msg.opcode, Opcode::kBinary); + EXPECT_EQ(result.records[0].msg.payload, "next"); + EXPECT_EQ(result.error_count, 1); + EXPECT_TRUE(req_frames_.empty()); +} + +} // namespace websocket +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h index 3f432a4d616..5028e988c3e 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h @@ -28,6 +28,8 @@ namespace stirling { namespace protocols { namespace websocket { +using stream_id_t = uint16_t; + enum class Opcode : uint8_t { kContinuation = 0x0, kText = 0x1, @@ -53,6 +55,38 @@ struct Frame : public FrameBase { } }; +struct Message { + uint64_t timestamp_ns = 0; + message_type_t type = message_type_t::kUnknown; + Opcode opcode = Opcode::kContinuation; + bool compressed = false; + size_t fragments = 0; + std::string payload; + + std::string ToString() const { + return absl::Substitute("Message: {type: $0, opcode: $1, compressed: $2, fragments: $3, len: $4}", + magic_enum::enum_name(type), magic_enum::enum_name(opcode), compressed, + fragments, payload.size()); + } +}; + +struct Record { + Message msg; + + std::string ToString() const { return absl::Substitute("[msg=$0]", msg.ToString()); } +}; + +struct ProtocolTraits : public BaseProtocolTraits { + using frame_type = Frame; + using record_type = Record; + using state_type = NoState; + using key_type = stream_id_t; + + static void ConvertTimestamps(Record* record, ConvertTimestampsFuncType func) { + record->msg.timestamp_ns = func(record->msg.timestamp_ns); + } +}; + } // namespace websocket } // namespace protocols } // namespace stirling From a84af5b50985ea8234ce6d192e26a65036f09c97 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:41:40 +0100 Subject: [PATCH 04/51] Stitch WebSocket frames into messages Signed-off-by: entlein --- .../protocols/websocket/parse.cc | 3 - .../protocols/websocket/stitcher.cc | 72 ++++++++++++++++++- .../socket_tracer/protocols/websocket/types.h | 2 + 3 files changed, 71 insertions(+), 6 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc index 40b5d941614..62ea6c49ab6 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc @@ -34,7 +34,6 @@ constexpr uint8_t kFinBit = 0x80; constexpr uint8_t kRsvBits = 0x70; constexpr uint8_t kRsvShift = 4; constexpr uint8_t kOpcodeBits = 0x0f; -constexpr uint8_t kControlOpcodeBit = 0x08; constexpr uint8_t kMaskBit = 0x80; constexpr uint8_t kPayloadLengthBits = 0x7f; constexpr uint8_t kPayloadLength16 = 126; @@ -43,8 +42,6 @@ constexpr uint64_t kPayloadLength64MSB = 1ULL << 63; constexpr uint64_t kMaxControlPayloadLength = 125; constexpr size_t kMaskingKeySize = 4; -bool IsControl(Opcode opcode) { return static_cast(opcode) & kControlOpcodeBit; } - } // namespace } // namespace websocket diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc index 973667fe9d2..dbd3a502f02 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc @@ -18,14 +18,80 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h" +#include +#include + namespace px { namespace stirling { namespace protocols { +namespace websocket { +namespace { + +constexpr uint8_t kRsv1 = 0x4; + +Message StartMessage(message_type_t type, Frame* frame) { + Message msg; + msg.timestamp_ns = frame->timestamp_ns; + msg.type = type; + msg.opcode = frame->opcode; + msg.compressed = frame->rsv & kRsv1; + msg.fragments = 1; + msg.payload = std::move(frame->payload); + return msg; +} + +int StitchDirection(message_type_t type, std::deque* frames, std::vector* records) { + int error_count = 0; + std::deque pending; + + for (Frame& frame : *frames) { + if (IsControl(frame.opcode)) { + records->push_back({StartMessage(type, &frame)}); + continue; + } + if (frame.opcode == Opcode::kContinuation) { + if (pending.empty()) { + ++error_count; + continue; + } + pending.push_back(std::move(frame)); + } else { + if (!pending.empty()) { + ++error_count; + pending.clear(); + } + pending.push_back(std::move(frame)); + } + if (!pending.back().fin) { + continue; + } + Message msg = StartMessage(type, &pending.front()); + for (size_t i = 1; i < pending.size(); ++i) { + msg.payload.append(pending[i].payload); + ++msg.fragments; + } + records->push_back({std::move(msg)}); + pending.clear(); + } + + *frames = std::move(pending); + return error_count; +} + +} // namespace +} // namespace websocket + template <> -RecordsWithErrorCount StitchFrames(std::deque*, - std::deque*, NoState*) { - return {}; +RecordsWithErrorCount StitchFrames(std::deque* req_frames, + std::deque* resp_frames, + NoState*) { + RecordsWithErrorCount result; + result.error_count += + websocket::StitchDirection(message_type_t::kRequest, req_frames, &result.records); + result.error_count += + websocket::StitchDirection(message_type_t::kResponse, resp_frames, &result.records); + return result; } } // namespace protocols diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h index 5028e988c3e..d203672f4d4 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h @@ -39,6 +39,8 @@ enum class Opcode : uint8_t { kPong = 0xa, }; +inline bool IsControl(Opcode opcode) { return static_cast(opcode) & 0x8; } + struct Frame : public FrameBase { bool fin = false; uint8_t rsv = 0; From 46738f81b11bca54de925003c2eab7f0ebf64e23 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:42:45 +0100 Subject: [PATCH 05/51] Name the WebSocket record type in stitcher tests Signed-off-by: entlein --- .../socket_tracer/protocols/websocket/stitcher_test.cc | 5 ++++- .../socket_tracer/protocols/websocket/types.h | 7 ++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc index aaa2e5856fb..6eda1420a9c 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc @@ -20,6 +20,7 @@ #include #include +#include #include "src/common/testing/testing.h" @@ -42,7 +43,9 @@ Frame MakeFrame(Opcode opcode, bool fin, std::string payload, uint64_t timestamp class WebSocketStitcherTest : public ::testing::Test { protected: - RecordsWithErrorCount Stitch() { return StitchFrames(&req_frames_, &resp_frames_, &state_); } + RecordsWithErrorCount Stitch() { + return StitchFrames(&req_frames_, &resp_frames_, &state_); + } std::deque req_frames_; std::deque resp_frames_; diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h index d203672f4d4..9b9148ba88c 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h @@ -66,9 +66,10 @@ struct Message { std::string payload; std::string ToString() const { - return absl::Substitute("Message: {type: $0, opcode: $1, compressed: $2, fragments: $3, len: $4}", - magic_enum::enum_name(type), magic_enum::enum_name(opcode), compressed, - fragments, payload.size()); + return absl::Substitute( + "Message: {type: $0, opcode: $1, compressed: $2, fragments: $3, len: $4}", + magic_enum::enum_name(type), magic_enum::enum_name(opcode), compressed, fragments, + payload.size()); } }; From 5e239206fa808443ae97aa32fb655b61683880ed Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:46:24 +0100 Subject: [PATCH 06/51] Add failing HTTP upgrade to WebSocket handover tests Signed-off-by: entlein --- src/carnot/funcs/protocols/protocols.h | 2 + src/shared/protocols/protocols.h | 1 + .../socket_tracer/bcc_bpf_intf/common.h | 1 + .../socket_tracer/conn_tracker.cc | 3 + .../socket_tracer/conn_tracker.h | 2 + .../socket_tracer/conn_tracker_test.cc | 82 +++++++++++++++++++ .../socket_tracer/data_stream.cc | 3 + .../socket_tracer/protocols/BUILD.bazel | 1 + .../socket_tracer/protocols/stitchers.h | 1 + .../socket_tracer/protocols/types.h | 4 +- .../socket_tracer/socket_trace_connector.cc | 4 + 11 files changed, 103 insertions(+), 1 deletion(-) diff --git a/src/carnot/funcs/protocols/protocols.h b/src/carnot/funcs/protocols/protocols.h index 7c60b873b79..7aaf7266a81 100644 --- a/src/carnot/funcs/protocols/protocols.h +++ b/src/carnot/funcs/protocols/protocols.h @@ -53,6 +53,8 @@ inline std::string ProtocolName(int protocol) { return "Kafka"; case px::protocols::Protocol::kAMQP: return "AMQP"; + case px::protocols::Protocol::kWebSocket: + return "WebSocket"; default: return absl::StrCat("Invalid (", protocol, ")"); } diff --git a/src/shared/protocols/protocols.h b/src/shared/protocols/protocols.h index d3b0d7072b8..883953067cc 100644 --- a/src/shared/protocols/protocols.h +++ b/src/shared/protocols/protocols.h @@ -40,6 +40,7 @@ enum class Protocol { kMux = 11, kAMQP = 12, kTLS = 13, + kWebSocket = 14, }; } // namespace protocols diff --git a/src/stirling/source_connectors/socket_tracer/bcc_bpf_intf/common.h b/src/stirling/source_connectors/socket_tracer/bcc_bpf_intf/common.h index 7277c3f864f..6e0d4dd3e83 100644 --- a/src/stirling/source_connectors/socket_tracer/bcc_bpf_intf/common.h +++ b/src/stirling/source_connectors/socket_tracer/bcc_bpf_intf/common.h @@ -52,6 +52,7 @@ enum traffic_protocol_t { kProtocolMux = 11, kProtocolAMQP = 12, kProtocolTLS = 13, + kProtocolWebSocket = 14, // We use magic enum to iterate through protocols in C++ land, // and don't want the C-enum-size trick to show up there. #ifndef __cplusplus diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker.cc index fadc2af95dd..a23947fdd39 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker.cc @@ -675,6 +675,7 @@ auto CreateTraceRoles() { res.Set(kProtocolMux, {kRoleServer}); res.Set(kProtocolAMQP, {kRoleServer}); res.Set(kProtocolTLS, {kRoleServer}); + res.Set(kProtocolWebSocket, {kRoleServer}); DCHECK(res.AreAllKeysSet()); return res; @@ -812,6 +813,8 @@ void ConnTracker::IterationPreTick( UpdateState(cluster_cidrs); } +bool ConnTracker::MaybeUpgradeToWebSocket() { return false; } + void ConnTracker::IterationPostTick() { if (death_countdown_ > 0) { --death_countdown_; diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker.h b/src/stirling/source_connectors/socket_tracer/conn_tracker.h index 3a272e4b2c1..fff4869b030 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker.h +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker.h @@ -481,6 +481,8 @@ class ConnTracker : NotCopyMoveable { */ void IterationPostTick(); + bool MaybeUpgradeToWebSocket(); + /** * Sets the duration after which a connection is deemed to be inactive. * After becoming inactive, the connection may either (1) have its buffers purged, diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc index 66917a1c3f6..fc9f6e635fd 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc @@ -19,12 +19,14 @@ #include "src/stirling/source_connectors/socket_tracer/conn_tracker.h" #include +#include #include #include #include #include +#include #include #include "protocols/http/types.h" @@ -42,10 +44,12 @@ using ::px::operator<<; namespace http = protocols::http; namespace mysql = protocols::mysql; +namespace websocket = protocols::websocket; using ::testing::Field; using ::testing::IsEmpty; using ::testing::SizeIs; +using std::string_view_literals::operator""sv; using testing::kHTTPReq0; using testing::kHTTPReq1; @@ -351,6 +355,84 @@ TEST_F(ConnTrackerTest, TrackerHTTP101Disable) { ASSERT_TRUE(tracker.IsZombie()); } +TEST_F(ConnTrackerTest, TrackerHTTP101UpgradesToWebSocket) { + constexpr std::string_view kServerText = "\x81\x02hi"sv; + constexpr std::string_view kClientMaskedText = "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58"sv; + constexpr std::string_view kClientPing = "\x89\x00"sv; + + struct socket_control_event_t conn = event_gen_.InitConn(); + std::unique_ptr req0 = event_gen_.InitSendEvent(kHTTPUpgradeReq); + std::unique_ptr resp0 = + event_gen_.InitRecvEvent(absl::StrCat(kHTTPUpgradeResp, kServerText)); + std::unique_ptr req1 = event_gen_.InitSendEvent(kClientMaskedText); + std::unique_ptr req2 = event_gen_.InitSendEvent(kClientPing); + + ConnTracker tracker; + tracker.InitProtocolState(); + tracker.AddControlEvent(conn); + tracker.AddDataEvent(std::move(req0)); + tracker.AddDataEvent(std::move(resp0)); + tracker.AddDataEvent(std::move(req1)); + + std::vector http_records = tracker.ProcessToRecords(); + ASSERT_THAT(http_records, SizeIs(1)); + EXPECT_EQ(http_records[0].resp.resp_status, 101); + + EXPECT_TRUE(tracker.MaybeUpgradeToWebSocket()); + tracker.IterationPostTick(); + EXPECT_EQ(tracker.protocol(), kProtocolWebSocket); + EXPECT_NE(tracker.state(), ConnTracker::State::kDisabled); + + std::vector ws_records = + tracker.ProcessToRecords(); + tracker.IterationPostTick(); + ASSERT_THAT(ws_records, SizeIs(2)); + EXPECT_EQ(ws_records[0].msg.type, message_type_t::kRequest); + EXPECT_EQ(ws_records[0].msg.payload, "Hello"); + EXPECT_EQ(ws_records[1].msg.type, message_type_t::kResponse); + EXPECT_EQ(ws_records[1].msg.payload, "hi"); + + tracker.AddDataEvent(std::move(req2)); + ws_records = tracker.ProcessToRecords(); + tracker.IterationPostTick(); + ASSERT_THAT(ws_records, SizeIs(1)); + EXPECT_EQ(ws_records[0].msg.opcode, websocket::Opcode::kPing); + EXPECT_NE(tracker.state(), ConnTracker::State::kDisabled); +} + +TEST_F(ConnTrackerTest, TrackerHTTPUpgradeRejectedStaysHTTP) { + constexpr std::string_view kRejectResp = + "HTTP/1.1 403 Forbidden\r\n" + "Content-Length: 0\r\n" + "\r\n"; + + struct socket_control_event_t conn = event_gen_.InitConn(); + std::unique_ptr req0 = event_gen_.InitSendEvent(kHTTPUpgradeReq); + std::unique_ptr resp0 = event_gen_.InitRecvEvent(kRejectResp); + std::unique_ptr req1 = event_gen_.InitSendEvent(kHTTPReq1); + std::unique_ptr resp1 = event_gen_.InitRecvEvent(kHTTPResp1); + + ConnTracker tracker; + tracker.InitProtocolState(); + tracker.AddControlEvent(conn); + tracker.AddDataEvent(std::move(req0)); + tracker.AddDataEvent(std::move(resp0)); + + std::vector records = tracker.ProcessToRecords(); + EXPECT_FALSE(tracker.MaybeUpgradeToWebSocket()); + tracker.IterationPostTick(); + ASSERT_THAT(records, SizeIs(1)); + EXPECT_EQ(records[0].resp.resp_status, 403); + + tracker.AddDataEvent(std::move(req1)); + tracker.AddDataEvent(std::move(resp1)); + records = tracker.ProcessToRecords(); + tracker.IterationPostTick(); + ASSERT_THAT(records, SizeIs(1)); + EXPECT_EQ(tracker.protocol(), kProtocolHTTP); + EXPECT_NE(tracker.state(), ConnTracker::State::kDisabled); +} + TEST_F(ConnTrackerTest, DataEventsChangesCounter) { auto frame0 = event_gen_.InitRecvEvent(kHTTPReq0); auto frame1 = event_gen_.InitSendEvent(kHTTPResp0); diff --git a/src/stirling/source_connectors/socket_tracer/data_stream.cc b/src/stirling/source_connectors/socket_tracer/data_stream.cc index d0fda642539..7415fd50c61 100644 --- a/src/stirling/source_connectors/socket_tracer/data_stream.cc +++ b/src/stirling/source_connectors/socket_tracer/data_stream.cc @@ -219,6 +219,9 @@ template void DataStream::ProcessBytesToFrames< template void DataStream::ProcessBytesToFrames(message_type_t type, protocols::NoState* state); +template void DataStream::ProcessBytesToFrames( + message_type_t type, protocols::NoState* state); void DataStream::Reset() { data_buffer_.Reset(); has_new_events_ = false; diff --git a/src/stirling/source_connectors/socket_tracer/protocols/BUILD.bazel b/src/stirling/source_connectors/socket_tracer/protocols/BUILD.bazel index 1026cd6945c..176198810d4 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/BUILD.bazel +++ b/src/stirling/source_connectors/socket_tracer/protocols/BUILD.bazel @@ -47,5 +47,6 @@ pl_cc_library( "//src/stirling/source_connectors/socket_tracer/protocols/pgsql:cc_library", "//src/stirling/source_connectors/socket_tracer/protocols/redis:cc_library", "//src/stirling/source_connectors/socket_tracer/protocols/tls:cc_library", + "//src/stirling/source_connectors/socket_tracer/protocols/websocket:cc_library", ], ) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/stitchers.h b/src/stirling/source_connectors/socket_tracer/protocols/stitchers.h index bbdbd2449c0..c32b934b571 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/stitchers.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/stitchers.h @@ -32,3 +32,4 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/pgsql/stitcher.h" // IWYU pragma: export #include "src/stirling/source_connectors/socket_tracer/protocols/redis/stitcher.h" // IWYU pragma: export #include "src/stirling/source_connectors/socket_tracer/protocols/tls/stitcher.h" // IWYU pragma: export +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h" // IWYU pragma: export diff --git a/src/stirling/source_connectors/socket_tracer/protocols/types.h b/src/stirling/source_connectors/socket_tracer/protocols/types.h index 560da8e2433..e76eefb5ecd 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/types.h @@ -35,6 +35,7 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/pgsql/types.h" #include "src/stirling/source_connectors/socket_tracer/protocols/redis/types.h" #include "src/stirling/source_connectors/socket_tracer/protocols/tls/types.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h" namespace px { namespace stirling { @@ -55,7 +56,8 @@ using FrameDequeVariant = std::variant>, absl::flat_hash_map>, absl::flat_hash_map>, - absl::flat_hash_map>>; + absl::flat_hash_map>, + absl::flat_hash_map>>; // clang-format off } // namespace protocols diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index d5ae9c02a91..6e732a1f021 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -303,6 +303,10 @@ void SocketTraceConnector::InitProtocolTransferSpecs() { kTLSTableNum, {kRoleClient, kRoleServer}, TRANSFER_STREAM_PROTOCOL(tls)}}, + {kProtocolWebSocket, TransferSpec{/* trace_mode */ px::stirling::TraceMode::Off, + /* table_num */ static_cast(-1), + /* trace_roles */ {}, + /* transfer_fn */ nullptr}}, {kProtocolUnknown, TransferSpec{/* trace_mode */ px::stirling::TraceMode::Off, /* table_num */ static_cast(-1), /* trace_roles */ {}, From 354b6955743e69bb2fa1d2bcc4563badd502f193 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:47:46 +0100 Subject: [PATCH 07/51] Hand an upgraded HTTP connection over to the WebSocket parser Signed-off-by: entlein --- .../socket_tracer/conn_tracker.cc | 20 +++++++++- .../socket_tracer/conn_tracker.h | 1 + .../socket_tracer/data_stream.h | 7 ++++ .../socket_tracer/protocols/http/parse.cc | 37 +++++++++++++++++-- .../socket_tracer/protocols/http/types.h | 3 ++ .../socket_tracer/socket_trace_connector.cc | 3 ++ 6 files changed, 65 insertions(+), 6 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker.cc index a23947fdd39..1d620e0ee71 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker.cc @@ -158,7 +158,7 @@ void ConnTracker::AddDataEvent(std::unique_ptr event) { return; } - if (event->attr.protocol != protocol_) { + if (event->attr.protocol != protocol_ && event->attr.protocol != upgraded_from_) { return; } @@ -813,7 +813,23 @@ void ConnTracker::IterationPreTick( UpdateState(cluster_cidrs); } -bool ConnTracker::MaybeUpgradeToWebSocket() { return false; } +bool ConnTracker::MaybeUpgradeToWebSocket() { + if (protocol_ != kProtocolHTTP) { + return false; + } + auto* state = protocol_state(); + if (state == nullptr || !state->global.websocket_upgrade_accepted) { + return false; + } + + CONN_TRACE(1) << "Protocol upgraded: HTTP->WebSocket"; + upgraded_from_ = protocol_; + protocol_ = kProtocolWebSocket; + protocol_state_.reset(); + send_data_.SwitchProtocol(protocol_); + recv_data_.SwitchProtocol(protocol_); + return true; +} void ConnTracker::IterationPostTick() { if (death_countdown_ > 0) { diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker.h b/src/stirling/source_connectors/socket_tracer/conn_tracker.h index fff4869b030..19e2d45989f 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker.h +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker.h @@ -705,6 +705,7 @@ class ConnTracker : NotCopyMoveable { bool is_tracked_upid_ = false; traffic_protocol_t protocol_ = kProtocolUnknown; + traffic_protocol_t upgraded_from_ = kProtocolUnknown; endpoint_role_t role_ = kRoleUnknown; bool ssl_ = false; ssl_source_t ssl_source_ = kSSLNone; diff --git a/src/stirling/source_connectors/socket_tracer/data_stream.h b/src/stirling/source_connectors/socket_tracer/data_stream.h index 44336c2da6e..69dc2dd9d90 100644 --- a/src/stirling/source_connectors/socket_tracer/data_stream.h +++ b/src/stirling/source_connectors/socket_tracer/data_stream.h @@ -229,6 +229,13 @@ class DataStream : NotCopyMoveable { void set_protocol(traffic_protocol_t protocol) { protocol_ = protocol; } + void SwitchProtocol(traffic_protocol_t protocol) { + protocol_ = protocol; + frames_ = std::monostate(); + last_parse_state_ = ParseState::kInvalid; + has_new_events_ = true; + } + /** * Cleanup frames that are parsed from the BPF events, when the condition is right. */ diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc index ae377dc2e77..2f4547a94dd 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc @@ -21,6 +21,8 @@ #include +#include + #include #include #include @@ -34,6 +36,16 @@ namespace stirling { namespace protocols { namespace http { +namespace { + +bool IsWebSocketUpgrade(const HeadersMap& headers) { + const auto upgrade_iter = headers.find(kUpgrade); + return upgrade_iter != headers.end() && + absl::EqualsIgnoreCase(upgrade_iter->second, kWebSocketUpgrade); +} + +} // namespace + namespace pico_wrapper { constexpr size_t kMaxNumHeaders = 50; @@ -183,6 +195,10 @@ ParseState ParseResponseBody(std::string_view* buf, Message* result, State* stat if (upgrade_iter == result->headers.end()) { LOG(WARNING) << "Expected an Upgrade header with HTTP status 101"; } + if (IsWebSocketUpgrade(result->headers)) { + state->websocket_upgrade_accepted = true; + return ParseState::kEOS; + } LOG(WARNING) << "HTTP upgrades are not yet supported"; return ParseState::kEOS; @@ -267,10 +283,23 @@ ParseState ParseResponse(std::string_view* buf, Message* result, State* state) { */ ParseState ParseFrame(message_type_t type, std::string_view* buf, Message* result, State* state) { switch (type) { - case message_type_t::kRequest: - return ParseRequest(buf, result); - case message_type_t::kResponse: - return ParseResponse(buf, result, state); + case message_type_t::kRequest: { + if (state->websocket_upgrade_requested) { + return ParseState::kNeedsMoreData; + } + ParseState parse_state = ParseRequest(buf, result); + if (parse_state == ParseState::kSuccess && IsWebSocketUpgrade(result->headers)) { + state->websocket_upgrade_requested = true; + } + return parse_state; + } + case message_type_t::kResponse: { + ParseState parse_state = ParseResponse(buf, result, state); + if (parse_state == ParseState::kSuccess && result->resp_status >= 200) { + state->websocket_upgrade_requested = false; + } + return parse_state; + } default: return ParseState::kInvalid; } diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/types.h b/src/stirling/source_connectors/socket_tracer/protocols/http/types.h index b7345329e3d..b6fe1373f1e 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/types.h @@ -45,6 +45,7 @@ inline constexpr char kContentLength[] = "Content-Length"; inline constexpr char kContentType[] = "Content-Type"; inline constexpr char kTransferEncoding[] = "Transfer-Encoding"; inline constexpr char kUpgrade[] = "Upgrade"; +inline constexpr char kWebSocketUpgrade[] = "websocket"; struct Message : public FrameBase { message_type_t type = message_type_t::kUnknown; @@ -102,6 +103,8 @@ struct Record { struct State { bool conn_closed = false; + bool websocket_upgrade_requested = false; + bool websocket_upgrade_accepted = false; }; struct StateWrapper { diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index 6e732a1f021..ae2b8143652 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -869,6 +869,9 @@ void SocketTraceConnector::TransferDataImpl(ConnectorContext* ctx) { if (transfer_spec.transfer_fn != nullptr) { current_conn_tracker_buffer_size += transfer_spec.transfer_fn(*this, ctx, conn_tracker, data_table); + if (protocol_transfer_specs_[kProtocolWebSocket].enabled) { + conn_tracker->MaybeUpgradeToWebSocket(); + } } else { // If there's no transfer function, then the tracker should not be holding any data. // http::ProtocolTraits is used as a placeholder; the frames deque is expected to be From 008eb2df8f63714c86098eedc07d6c149334b602 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:49:23 +0100 Subject: [PATCH 08/51] Add failing websocket_events table test Signed-off-by: entlein --- .../socket_tracer/conn_tracker_test.cc | 6 +- .../socket_tracer/socket_trace_connector.cc | 17 +++- .../socket_tracer/socket_trace_connector.h | 4 +- .../socket_trace_connector_test.cc | 49 ++++++++++++ .../socket_tracer/socket_trace_tables.h | 1 + .../socket_tracer/websocket_table.h | 79 +++++++++++++++++++ 6 files changed, 149 insertions(+), 7 deletions(-) create mode 100644 src/stirling/source_connectors/socket_tracer/websocket_table.h diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc index fc9f6e635fd..cd7a08abc21 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc @@ -357,14 +357,16 @@ TEST_F(ConnTrackerTest, TrackerHTTP101Disable) { TEST_F(ConnTrackerTest, TrackerHTTP101UpgradesToWebSocket) { constexpr std::string_view kServerText = "\x81\x02hi"sv; - constexpr std::string_view kClientMaskedText = "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58"sv; + constexpr std::string_view kClientMaskedText = + "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58"sv; constexpr std::string_view kClientPing = "\x89\x00"sv; struct socket_control_event_t conn = event_gen_.InitConn(); std::unique_ptr req0 = event_gen_.InitSendEvent(kHTTPUpgradeReq); std::unique_ptr resp0 = event_gen_.InitRecvEvent(absl::StrCat(kHTTPUpgradeResp, kServerText)); - std::unique_ptr req1 = event_gen_.InitSendEvent(kClientMaskedText); + std::unique_ptr req1 = + event_gen_.InitSendEvent(kClientMaskedText); std::unique_ptr req2 = event_gen_.InitSendEvent(kClientPing); ConnTracker tracker; diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index ae2b8143652..2d9f64d242e 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -122,6 +122,11 @@ DEFINE_int32( gflags::Int32FromEnv("PX_STIRLING_ENABLE_TLS_TRACING", px::stirling::TraceMode::Off), "If true, stirling will trace and process TLS protocol (not the TLS payload) messages. Note: " "this disables tracing the plaintext within encrypted connections until gh#2095 is addressed."); +DEFINE_int32(stirling_enable_websocket_tracing, + gflags::Int32FromEnv("PX_STIRLING_ENABLE_WEBSOCKET_TRACING", + px::stirling::TraceMode::Off), + "If true, stirling will trace and process WebSocket messages on upgraded HTTP " + "connections."); DEFINE_bool(stirling_disable_golang_tls_tracing, gflags::BoolFromEnv("PX_STIRLING_DISABLE_GOLANG_TLS_TRACING", false), "If true, stirling will not trace TLS traffic for Go applications. This implies " @@ -303,10 +308,10 @@ void SocketTraceConnector::InitProtocolTransferSpecs() { kTLSTableNum, {kRoleClient, kRoleServer}, TRANSFER_STREAM_PROTOCOL(tls)}}, - {kProtocolWebSocket, TransferSpec{/* trace_mode */ px::stirling::TraceMode::Off, - /* table_num */ static_cast(-1), - /* trace_roles */ {}, - /* transfer_fn */ nullptr}}, + {kProtocolWebSocket, TransferSpec{FLAGS_stirling_enable_websocket_tracing, + kWebSocketTableNum, + {kRoleClient, kRoleServer}, + TRANSFER_STREAM_PROTOCOL(websocket)}}, {kProtocolUnknown, TransferSpec{/* trace_mode */ px::stirling::TraceMode::Off, /* table_num */ static_cast(-1), /* trace_roles */ {}, @@ -1780,6 +1785,10 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke #endif } +template <> +void SocketTraceConnector::AppendMessage(ConnectorContext*, const ConnTracker&, + protocols::websocket::Record, DataTable*) {} + void SocketTraceConnector::SetupOutput(const std::filesystem::path& path) { DCHECK(!path.empty()); diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.h b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.h index 1c939ffeba7..9bfeedce7b0 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.h +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.h @@ -67,6 +67,7 @@ DECLARE_int32(stirling_enable_mux_tracing); DECLARE_int32(stirling_enable_amqp_tracing); DECLARE_int32(stirling_enable_mongodb_tracing); DECLARE_int32(stirling_enable_tls_tracing); +DECLARE_int32(stirling_enable_websocket_tracing); DECLARE_bool(stirling_disable_self_tracing); DECLARE_string(stirling_role_to_trace); @@ -98,7 +99,7 @@ class SocketTraceConnector : public BCCSourceConnector { // PROTOCOL_LIST static constexpr auto kTables = MakeArray( kConnStatsTable, kHTTPTable, kMySQLTable, kCQLTable, kPGSQLTable, kDNSTable, kRedisTable, - kNATSTable, kKafkaTable, kMuxTable, kAMQPTable, kMongoDBTable, kTLSTable); + kNATSTable, kKafkaTable, kMuxTable, kAMQPTable, kMongoDBTable, kTLSTable, kWebSocketTable); static constexpr uint32_t kConnStatsTableNum = TableNum(kTables, kConnStatsTable); static constexpr uint32_t kHTTPTableNum = TableNum(kTables, kHTTPTable); @@ -113,6 +114,7 @@ class SocketTraceConnector : public BCCSourceConnector { static constexpr uint32_t kAMQPTableNum = TableNum(kTables, kAMQPTable); static constexpr uint32_t kMongoDBTableNum = TableNum(kTables, kMongoDBTable); static constexpr uint32_t kTLSTableNum = TableNum(kTables, kTLSTable); + static constexpr uint32_t kWebSocketTableNum = TableNum(kTables, kWebSocketTable); static constexpr auto kSamplingPeriod = std::chrono::milliseconds{200}; // TODO(yzhao): This is not used right now. Eventually use this to control data push frequency. diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc index 44849e47ff8..8a33bb6b3cb 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc @@ -19,8 +19,10 @@ #include "src/stirling/source_connectors/socket_tracer/socket_trace_connector.h" #include +#include #include +#include #include #include @@ -223,6 +225,53 @@ TEST_F(SocketTraceConnectorTest, Basic) { EXPECT_THAT(ToStringVector(records[kHTTPRespBodyIdx]), ElementsAre("foo")); } +class SocketTraceConnectorWebSocketTest : public SocketTraceConnectorTest { + protected: + void SetUp() override { + FLAGS_stirling_enable_websocket_tracing = TraceMode::On; + SocketTraceConnectorTest::SetUp(); + } + + void TearDown() override { FLAGS_stirling_enable_websocket_tracing = TraceMode::Off; } + + DataTable* websocket_table_ = data_tables_[SocketTraceConnector::kWebSocketTableNum]; +}; + +TEST_F(SocketTraceConnectorWebSocketTest, UpgradedConnectionProducesWebSocketEvents) { + using std::string_view_literals::operator""sv; + constexpr std::string_view kServerText = "\x81\x02hi"sv; + constexpr std::string_view kClientMaskedText = + "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58"sv; + + struct socket_control_event_t conn = event_gen_.InitConn(); + std::unique_ptr req = + event_gen_.InitSendEvent(testing::kHTTPUpgradeReq); + std::unique_ptr resp = event_gen_.InitRecvEvent( + absl::StrCat(testing::kHTTPUpgradeResp, kServerText)); + std::unique_ptr client_msg = + event_gen_.InitSendEvent(kClientMaskedText); + + source_->AcceptControlEvent(conn); + source_->AcceptDataEvent(std::move(req)); + source_->AcceptDataEvent(std::move(resp)); + source_->AcceptDataEvent(std::move(client_msg)); + connector_->TransferData(ctx_.get()); + connector_->TransferData(ctx_.get()); + + std::vector http_tablets = http_table_->ConsumeRecords(); + ASSERT_NOT_EMPTY_AND_GET_RECORDS(RecordBatch & http_records, http_tablets); + ASSERT_THAT(http_records, RecordBatchSizeIs(1)); + + std::vector tablets = websocket_table_->ConsumeRecords(); + ASSERT_NOT_EMPTY_AND_GET_RECORDS(RecordBatch & records, tablets); + ASSERT_THAT(records, RecordBatchSizeIs(2)); + EXPECT_THAT(ToStringVector(records[kWebSocketPayloadIdx]), ElementsAre("Hello", "hi")); + EXPECT_THAT(ToIntVector(records[kWebSocketDirectionIdx]), ElementsAre(1, 2)); + EXPECT_THAT(ToIntVector(records[kWebSocketOpcodeIdx]), ElementsAre(1, 1)); + EXPECT_THAT(ToIntVector(records[kWebSocketPayloadSizeIdx]), + ElementsAre(5, 2)); +} + TEST_F(SocketTraceConnectorTest, HTTPDelayedRespBody) { struct socket_control_event_t conn = event_gen_.InitConn(); std::unique_ptr event0_req = event_gen_.InitSendEvent(kReq4); diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_tables.h b/src/stirling/source_connectors/socket_tracer/socket_trace_tables.h index 20098738c31..83e8161a624 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_tables.h +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_tables.h @@ -33,3 +33,4 @@ #include "src/stirling/source_connectors/socket_tracer/pgsql_table.h" #include "src/stirling/source_connectors/socket_tracer/redis_table.h" #include "src/stirling/source_connectors/socket_tracer/tls_table.h" +#include "src/stirling/source_connectors/socket_tracer/websocket_table.h" diff --git a/src/stirling/source_connectors/socket_tracer/websocket_table.h b/src/stirling/source_connectors/socket_tracer/websocket_table.h new file mode 100644 index 00000000000..0d8eb0bc974 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/websocket_table.h @@ -0,0 +1,79 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "src/stirling/core/output.h" +#include "src/stirling/core/types.h" +#include "src/stirling/source_connectors/socket_tracer/canonical_types.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h" + +namespace px { +namespace stirling { + +// clang-format off +static constexpr DataElement kWebSocketElements[] = { + canonical_data_elements::kTime, + canonical_data_elements::kUPID, + canonical_data_elements::kRemoteAddr, + canonical_data_elements::kRemotePort, + canonical_data_elements::kLocalAddr, + canonical_data_elements::kLocalPort, + canonical_data_elements::kTraceRole, + canonical_data_elements::kEncrypted, + {"direction", "1 if the client sent the message, 2 if the server sent it", + types::DataType::INT64, + types::SemanticType::ST_NONE, + types::PatternType::GENERAL_ENUM}, + {"opcode", "WebSocket opcode of the message (1 text, 2 binary, 8 close, 9 ping, 10 pong)", + types::DataType::INT64, + types::SemanticType::ST_NONE, + types::PatternType::GENERAL_ENUM}, + {"compressed", "Whether the message is compressed with permessage-deflate", + types::DataType::BOOLEAN, + types::SemanticType::ST_NONE, + types::PatternType::GENERAL_ENUM}, + {"fragments", "Number of frames the message was sent in", + types::DataType::INT64, + types::SemanticType::ST_NONE, + types::PatternType::GENERAL}, + {"payload", "Message payload, truncated", + types::DataType::STRING, + types::SemanticType::ST_NONE, + types::PatternType::GENERAL}, + {"payload_size", "Message payload size (before any truncation)", + types::DataType::INT64, + types::SemanticType::ST_BYTES, + types::PatternType::METRIC_GAUGE}, +#ifndef NDEBUG + canonical_data_elements::kPXInfo, +#endif +}; +// clang-format on + +static constexpr auto kWebSocketTable = + DataTableSchema("websocket_events", "WebSocket messages", kWebSocketElements); +DEFINE_PRINT_TABLE(WebSocket) + +constexpr int kWebSocketDirectionIdx = kWebSocketTable.ColIndex("direction"); +constexpr int kWebSocketOpcodeIdx = kWebSocketTable.ColIndex("opcode"); +constexpr int kWebSocketPayloadIdx = kWebSocketTable.ColIndex("payload"); +constexpr int kWebSocketPayloadSizeIdx = kWebSocketTable.ColIndex("payload_size"); + +} // namespace stirling +} // namespace px From 89c7e501d9bac915d37beab96a76091489a29705 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:49:45 +0100 Subject: [PATCH 09/51] Write WebSocket messages to websocket_events Signed-off-by: entlein --- .../socket_tracer/socket_trace_connector.cc | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index 2d9f64d242e..f7ade028d34 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -1786,8 +1786,34 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke } template <> -void SocketTraceConnector::AppendMessage(ConnectorContext*, const ConnTracker&, - protocols::websocket::Record, DataTable*) {} +void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracker& conn_tracker, + protocols::websocket::Record record, + DataTable* data_table) { + protocols::websocket::Message& msg = record.msg; + + md::UPID upid(ctx->GetASID(), conn_tracker.conn_id().upid.pid, + conn_tracker.conn_id().upid.start_time_ticks); + + const size_t payload_size = msg.payload.size(); + DataTable::RecordBuilder<&kWebSocketTable> r(data_table, msg.timestamp_ns); + r.Append(msg.timestamp_ns); + r.Append(upid.value()); + r.Append(conn_tracker.remote_endpoint().AddrStr()); + r.Append(conn_tracker.remote_endpoint().port()); + r.Append(conn_tracker.local_endpoint().AddrStr()); + r.Append(conn_tracker.local_endpoint().port()); + r.Append(conn_tracker.role()); + r.Append(conn_tracker.ssl()); + r.Append(static_cast(msg.type)); + r.Append(static_cast(msg.opcode)); + r.Append(msg.compressed); + r.Append(msg.fragments); + r.Append(std::move(msg.payload), FLAGS_max_body_bytes); + r.Append(payload_size); +#ifndef NDEBUG + r.Append(PXInfoString(conn_tracker, record)); +#endif +} void SocketTraceConnector::SetupOutput(const std::filesystem::path& path) { DCHECK(!path.empty()); From fdd58a66d0d394dcb489c6e1eecd7732e53ba058 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:50:13 +0100 Subject: [PATCH 10/51] Declare that WebSocket streams have no frame boundary to resync on Signed-off-by: entlein --- .../source_connectors/socket_tracer/conn_tracker_test.cc | 5 ++--- .../socket_tracer/protocols/websocket/parse.cc | 5 +++++ .../socket_tracer/protocols/websocket/parse.h | 4 ++++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc index cd7a08abc21..8db090f7236 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc @@ -29,9 +29,9 @@ #include #include -#include "protocols/http/types.h" #include "src/common/testing/testing.h" #include "src/stirling/source_connectors/socket_tracer/conn_stats.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/http/types.h" #include "src/stirling/source_connectors/socket_tracer/protocols/mysql/test_utils.h" #include "src/stirling/source_connectors/socket_tracer/testing/event_generator.h" #include "src/stirling/testing/common.h" @@ -385,8 +385,7 @@ TEST_F(ConnTrackerTest, TrackerHTTP101UpgradesToWebSocket) { EXPECT_EQ(tracker.protocol(), kProtocolWebSocket); EXPECT_NE(tracker.state(), ConnTracker::State::kDisabled); - std::vector ws_records = - tracker.ProcessToRecords(); + std::vector ws_records = tracker.ProcessToRecords(); tracker.IterationPostTick(); ASSERT_THAT(ws_records, SizeIs(2)); EXPECT_EQ(ws_records[0].msg.type, message_type_t::kRequest); diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc index 62ea6c49ab6..8b6a274a578 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc @@ -103,6 +103,11 @@ ParseState ParseFrame(message_type_t, std::string_view* buf, websocket::Frame* f return ParseState::kSuccess; } +template <> +size_t FindFrameBoundary(message_type_t, std::string_view, size_t, NoState*) { + return std::string_view::npos; +} + } // namespace protocols } // namespace stirling } // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h index 3f1425ae9a5..3ca20e48033 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h @@ -31,6 +31,10 @@ template <> ParseState ParseFrame(message_type_t type, std::string_view* buf, websocket::Frame* frame, NoState* state); +template <> +size_t FindFrameBoundary(message_type_t type, std::string_view buf, + size_t start_pos, NoState* state); + } // namespace protocols } // namespace stirling } // namespace px From 855c788297a715013df9d13dd91a4a23b8b0699c Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:50:13 +0100 Subject: [PATCH 11/51] Fix include order in the HTTP parser Signed-off-by: entlein --- .../source_connectors/socket_tracer/protocols/http/parse.cc | 3 +-- .../source_connectors/socket_tracer/protocols/http/types.h | 1 + 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc index 2f4547a94dd..d3a0643f205 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc @@ -19,9 +19,8 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/http/parse.h" #include "src/stirling/source_connectors/socket_tracer/protocols/http/body_decoder.h" -#include - #include +#include #include #include diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/types.h b/src/stirling/source_connectors/socket_tracer/protocols/http/types.h index b6fe1373f1e..5b99e0ac9b1 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/types.h @@ -19,6 +19,7 @@ #pragma once #include +#include #include #include "src/common/base/utils.h" From 446f449151c9599df24cadc4af4b7a023e298225 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:54:05 +0100 Subject: [PATCH 12/51] Expect websocket_events rows in timestamp order Signed-off-by: entlein --- .../socket_tracer/socket_trace_connector_test.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc index 8a33bb6b3cb..23b67de476b 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc @@ -265,11 +265,11 @@ TEST_F(SocketTraceConnectorWebSocketTest, UpgradedConnectionProducesWebSocketEve std::vector tablets = websocket_table_->ConsumeRecords(); ASSERT_NOT_EMPTY_AND_GET_RECORDS(RecordBatch & records, tablets); ASSERT_THAT(records, RecordBatchSizeIs(2)); - EXPECT_THAT(ToStringVector(records[kWebSocketPayloadIdx]), ElementsAre("Hello", "hi")); - EXPECT_THAT(ToIntVector(records[kWebSocketDirectionIdx]), ElementsAre(1, 2)); + EXPECT_THAT(ToStringVector(records[kWebSocketPayloadIdx]), ElementsAre("hi", "Hello")); + EXPECT_THAT(ToIntVector(records[kWebSocketDirectionIdx]), ElementsAre(2, 1)); EXPECT_THAT(ToIntVector(records[kWebSocketOpcodeIdx]), ElementsAre(1, 1)); EXPECT_THAT(ToIntVector(records[kWebSocketPayloadSizeIdx]), - ElementsAre(5, 2)); + ElementsAre(2, 5)); } TEST_F(SocketTraceConnectorTest, HTTPDelayedRespBody) { From 1cb1453217fe7472708c86d3e6c0da1c0de75867 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 02:57:00 +0100 Subject: [PATCH 13/51] Format the WebSocket connector test Signed-off-by: entlein --- .../socket_tracer/socket_trace_connector_test.cc | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc index 23b67de476b..0f23b2f3941 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc @@ -240,14 +240,13 @@ class SocketTraceConnectorWebSocketTest : public SocketTraceConnectorTest { TEST_F(SocketTraceConnectorWebSocketTest, UpgradedConnectionProducesWebSocketEvents) { using std::string_view_literals::operator""sv; constexpr std::string_view kServerText = "\x81\x02hi"sv; - constexpr std::string_view kClientMaskedText = - "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58"sv; + constexpr std::string_view kClientMaskedText = "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58"sv; struct socket_control_event_t conn = event_gen_.InitConn(); std::unique_ptr req = event_gen_.InitSendEvent(testing::kHTTPUpgradeReq); - std::unique_ptr resp = event_gen_.InitRecvEvent( - absl::StrCat(testing::kHTTPUpgradeResp, kServerText)); + std::unique_ptr resp = + event_gen_.InitRecvEvent(absl::StrCat(testing::kHTTPUpgradeResp, kServerText)); std::unique_ptr client_msg = event_gen_.InitSendEvent(kClientMaskedText); @@ -268,8 +267,7 @@ TEST_F(SocketTraceConnectorWebSocketTest, UpgradedConnectionProducesWebSocketEve EXPECT_THAT(ToStringVector(records[kWebSocketPayloadIdx]), ElementsAre("hi", "Hello")); EXPECT_THAT(ToIntVector(records[kWebSocketDirectionIdx]), ElementsAre(2, 1)); EXPECT_THAT(ToIntVector(records[kWebSocketOpcodeIdx]), ElementsAre(1, 1)); - EXPECT_THAT(ToIntVector(records[kWebSocketPayloadSizeIdx]), - ElementsAre(2, 5)); + EXPECT_THAT(ToIntVector(records[kWebSocketPayloadSizeIdx]), ElementsAre(2, 5)); } TEST_F(SocketTraceConnectorTest, HTTPDelayedRespBody) { From 8d171e6ffce63dab39b6dbb498791125b3d6f5f5 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 03:13:29 +0100 Subject: [PATCH 14/51] Add failing test for escaped non-text WebSocket payloads Signed-off-by: entlein --- .../socket_trace_connector_test.cc | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc index 0f23b2f3941..f799ead05ab 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc @@ -270,6 +270,31 @@ TEST_F(SocketTraceConnectorWebSocketTest, UpgradedConnectionProducesWebSocketEve EXPECT_THAT(ToIntVector(records[kWebSocketPayloadSizeIdx]), ElementsAre(2, 5)); } +TEST_F(SocketTraceConnectorWebSocketTest, NonTextPayloadsAreEscaped) { + using std::string_view_literals::operator""sv; + constexpr std::string_view kServerStdout = "\x82\x04\x01hi\n"sv; + constexpr std::string_view kServerClose = "\x88\x02\x03\xe8"sv; + + struct socket_control_event_t conn = event_gen_.InitConn(); + std::unique_ptr req = + event_gen_.InitSendEvent(testing::kHTTPUpgradeReq); + std::unique_ptr resp = event_gen_.InitRecvEvent( + absl::StrCat(testing::kHTTPUpgradeResp, kServerStdout, kServerClose)); + + source_->AcceptControlEvent(conn); + source_->AcceptDataEvent(std::move(req)); + source_->AcceptDataEvent(std::move(resp)); + connector_->TransferData(ctx_.get()); + connector_->TransferData(ctx_.get()); + + std::vector tablets = websocket_table_->ConsumeRecords(); + ASSERT_NOT_EMPTY_AND_GET_RECORDS(RecordBatch & records, tablets); + ASSERT_THAT(records, RecordBatchSizeIs(2)); + EXPECT_THAT(ToStringVector(records[kWebSocketPayloadIdx]), + ElementsAre("\\x01hi\\x0A", "\\x03\\xE8")); + EXPECT_THAT(ToIntVector(records[kWebSocketPayloadSizeIdx]), ElementsAre(4, 2)); +} + TEST_F(SocketTraceConnectorTest, HTTPDelayedRespBody) { struct socket_control_event_t conn = event_gen_.InitConn(); std::unique_ptr event0_req = event_gen_.InitSendEvent(kReq4); From bcc3138c0ce2cc7e4fd80b9bf4c557a64de91be4 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 03:13:29 +0100 Subject: [PATCH 15/51] Escape non-text WebSocket payloads Signed-off-by: entlein --- .../socket_tracer/socket_trace_connector.cc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index f7ade028d34..e3a49e84364 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -1808,7 +1808,12 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke r.Append(static_cast(msg.opcode)); r.Append(msg.compressed); r.Append(msg.fragments); - r.Append(std::move(msg.payload), FLAGS_max_body_bytes); + if (msg.opcode == protocols::websocket::Opcode::kText) { + r.Append(std::move(msg.payload), FLAGS_max_body_bytes); + } else { + r.Append(BytesToString(msg.payload), + FLAGS_max_body_bytes); + } r.Append(payload_size); #ifndef NDEBUG r.Append(PXInfoString(conn_tracker, record)); From a85554fd75e3bc1539c2dcbc7726dfcd0f588602 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 14:12:40 +0100 Subject: [PATCH 16/51] Test WebSocket subprotocol and Kubernetes exec session decoding Signed-off-by: entlein --- .../socket_tracer/conn_tracker.cc | 6 +- .../socket_tracer/conn_tracker_test.cc | 40 +++ .../socket_tracer/data_stream.cc | 6 +- .../protocols/http/parse_test.cc | 26 ++ .../socket_tracer/protocols/http/types.h | 3 + .../protocols/websocket/BUILD.bazel | 6 + .../protocols/websocket/k8s_exec.cc | 41 +++ .../protocols/websocket/k8s_exec.h | 48 ++++ .../protocols/websocket/k8s_exec_test.cc | 249 ++++++++++++++++++ .../protocols/websocket/parse.cc | 6 +- .../socket_tracer/protocols/websocket/parse.h | 4 +- .../protocols/websocket/parse_test.cc | 2 +- .../protocols/websocket/stitcher.cc | 34 ++- .../protocols/websocket/stitcher.h | 2 +- .../protocols/websocket/stitcher_test.cc | 32 ++- .../socket_tracer/protocols/websocket/types.h | 63 ++++- .../socket_tracer/socket_trace_connector.cc | 11 +- .../socket_trace_connector_test.cc | 44 ++++ .../socket_tracer/websocket_table.h | 20 ++ 19 files changed, 624 insertions(+), 19 deletions(-) create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker.cc index 1d620e0ee71..0b35536fad6 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker.cc @@ -822,10 +822,14 @@ bool ConnTracker::MaybeUpgradeToWebSocket() { return false; } + protocols::websocket::StateWrapper ws_state; + ws_state.global.path = std::move(state->global.websocket_path); + ws_state.global.subprotocol = std::move(state->global.websocket_subprotocol); + CONN_TRACE(1) << "Protocol upgraded: HTTP->WebSocket"; upgraded_from_ = protocol_; protocol_ = kProtocolWebSocket; - protocol_state_.reset(); + protocol_state_ = std::move(ws_state); send_data_.SwitchProtocol(protocol_); recv_data_.SwitchProtocol(protocol_); return true; diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc index 8db090f7236..175b4cf95ad 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc @@ -401,6 +401,46 @@ TEST_F(ConnTrackerTest, TrackerHTTP101UpgradesToWebSocket) { EXPECT_NE(tracker.state(), ConnTracker::State::kDisabled); } +TEST_F(ConnTrackerTest, TrackerWebSocketUpgradeKeepsSubprotocol) { + constexpr std::string_view kExecReq = + "GET /exec/ns/pod/ctr?command=hostname&output=1 HTTP/1.1\r\n" + "Connection: Upgrade\r\n" + "Upgrade: websocket\r\n" + "Sec-WebSocket-Protocol: v5.channel.k8s.io\r\n" + "\r\n"; + constexpr std::string_view kExecResp = + "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Protocol: v5.channel.k8s.io\r\n" + "\r\n"; + constexpr std::string_view kStdout = "\x82\x05\x01pod\n"sv; + + struct socket_control_event_t conn = event_gen_.InitConn(); + std::unique_ptr req0 = event_gen_.InitSendEvent(kExecReq); + std::unique_ptr resp0 = + event_gen_.InitRecvEvent(absl::StrCat(kExecResp, kStdout)); + + ConnTracker tracker; + tracker.InitProtocolState(); + tracker.AddControlEvent(conn); + tracker.AddDataEvent(std::move(req0)); + tracker.AddDataEvent(std::move(resp0)); + tracker.ProcessToRecords(); + ASSERT_TRUE(tracker.MaybeUpgradeToWebSocket()); + tracker.IterationPostTick(); + + auto* state = tracker.protocol_state(); + ASSERT_NE(state, nullptr); + EXPECT_EQ(state->global.subprotocol, "v5.channel.k8s.io"); + EXPECT_EQ(state->global.path, "/exec/ns/pod/ctr?command=hostname&output=1"); + + std::vector ws_records = tracker.ProcessToRecords(); + ASSERT_THAT(ws_records, SizeIs(1)); + EXPECT_EQ(ws_records[0].kind, websocket::RecordKind::kExec); + EXPECT_EQ(ws_records[0].msg.payload, "hostname"); +} + TEST_F(ConnTrackerTest, TrackerHTTPUpgradeRejectedStaysHTTP) { constexpr std::string_view kRejectResp = "HTTP/1.1 403 Forbidden\r\n" diff --git a/src/stirling/source_connectors/socket_tracer/data_stream.cc b/src/stirling/source_connectors/socket_tracer/data_stream.cc index 7415fd50c61..4bd1e240b83 100644 --- a/src/stirling/source_connectors/socket_tracer/data_stream.cc +++ b/src/stirling/source_connectors/socket_tracer/data_stream.cc @@ -220,8 +220,10 @@ template void DataStream::ProcessBytesToFrames(message_type_t type, protocols::NoState* state); template void DataStream::ProcessBytesToFrames( - message_type_t type, protocols::NoState* state); + protocols::websocket::Frame, + protocols::websocket::StateWrapper>( + message_type_t type, protocols::websocket::StateWrapper* state); + void DataStream::Reset() { data_buffer_.Reset(); has_new_events_ = false; diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/parse_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/parse_test.cc index 333130e9e36..4e460bbcfab 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/parse_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/parse_test.cc @@ -358,6 +358,32 @@ TEST_F(HTTPParserTest, Status101) { EXPECT_THAT(parsed_messages[0], ElementsAre(HasBody(""))); } +TEST_F(HTTPParserTest, WebSocketUpgradeKeepsPathAndSubprotocol) { + StateWrapper state{}; + std::string req = + "GET /api/v1/namespaces/ns/pods/pod/exec?command=sh&stdin=true&tty=true HTTP/1.1\r\n" + "Host: 127.0.0.1:6443\r\n" + "Connection: Upgrade\r\n" + "Upgrade: websocket\r\n" + "Sec-WebSocket-Protocol: v5.channel.k8s.io,v4.channel.k8s.io\r\n" + "\r\n"; + std::string resp = + "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Protocol: v5.channel.k8s.io\r\n" + "\r\n"; + + absl::flat_hash_map> parsed_messages; + ParseFramesLoop(message_type_t::kRequest, req, &parsed_messages, &state); + ParseFramesLoop(message_type_t::kResponse, resp, &parsed_messages, &state); + + EXPECT_TRUE(state.global.websocket_upgrade_accepted); + EXPECT_EQ(state.global.websocket_path, + "/api/v1/namespaces/ns/pods/pod/exec?command=sh&stdin=true&tty=true"); + EXPECT_EQ(state.global.websocket_subprotocol, "v5.channel.k8s.io"); +} + TEST_F(HTTPParserTest, Status204) { StateWrapper state{}; std::string msg = diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/types.h b/src/stirling/source_connectors/socket_tracer/protocols/http/types.h index 5b99e0ac9b1..9ddead8c9a9 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/types.h @@ -47,6 +47,7 @@ inline constexpr char kContentType[] = "Content-Type"; inline constexpr char kTransferEncoding[] = "Transfer-Encoding"; inline constexpr char kUpgrade[] = "Upgrade"; inline constexpr char kWebSocketUpgrade[] = "websocket"; +inline constexpr char kSecWebSocketProtocol[] = "Sec-WebSocket-Protocol"; struct Message : public FrameBase { message_type_t type = message_type_t::kUnknown; @@ -106,6 +107,8 @@ struct State { bool conn_closed = false; bool websocket_upgrade_requested = false; bool websocket_upgrade_accepted = false; + std::string websocket_path; + std::string websocket_subprotocol; }; struct StateWrapper { diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel b/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel index c40e16f3925..e0f3c5f6d6b 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel @@ -45,3 +45,9 @@ pl_cc_test( srcs = ["stitcher_test.cc"], deps = [":cc_library"], ) + +pl_cc_test( + name = "k8s_exec_test", + srcs = ["k8s_exec_test.cc"], + deps = [":cc_library"], +) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc new file mode 100644 index 00000000000..317eadebf34 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc @@ -0,0 +1,41 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h" + +namespace px { +namespace stirling { +namespace protocols { +namespace websocket { + +bool IsK8sChannelProtocol(std::string_view) { return false; } + +std::string K8sExecCommand(std::string_view) { return ""; } + +bool K8sExecTTY(std::string_view) { return false; } + +std::string CleanTerminalOutput(std::string_view output, bool) { return std::string(output); } + +std::string Printable(std::string_view data) { return std::string(data); } + +void DecodeK8sExec(std::string_view, std::vector, ExecState*, std::vector*) {} + +} // namespace websocket +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h new file mode 100644 index 00000000000..4b2679fbecc --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h @@ -0,0 +1,48 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include + +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h" + +namespace px { +namespace stirling { +namespace protocols { +namespace websocket { + +bool IsK8sChannelProtocol(std::string_view subprotocol); + +std::string K8sExecCommand(std::string_view path); + +bool K8sExecTTY(std::string_view path); + +std::string CleanTerminalOutput(std::string_view output, bool tty); + +std::string Printable(std::string_view data); + +void DecodeK8sExec(std::string_view path, std::vector messages, ExecState* state, + std::vector* records); + +} // namespace websocket +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc new file mode 100644 index 00000000000..1999330dd12 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc @@ -0,0 +1,249 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h" + +#include +#include +#include + +#include + +#include "src/common/testing/testing.h" + +namespace px { +namespace stirling { +namespace protocols { +namespace websocket { + +using std::string_view_literals::operator""sv; +using ::testing::AllOf; +using ::testing::ElementsAre; +using ::testing::Field; +using ::testing::IsEmpty; + +constexpr std::string_view kKubeletTTYPath = "/exec/ws-demo/ws-demo/ws-demo?command=sh&input=1&output=1&tty=1"; +constexpr std::string_view kStatusSuccess = R"({"metadata":{},"status":"Success"})"; + +Message Msg(uint64_t timestamp_ns, message_type_t type, std::string_view payload, + Opcode opcode = Opcode::kBinary) { + Message msg; + msg.timestamp_ns = timestamp_ns; + msg.type = type; + msg.opcode = opcode; + msg.fragments = 1; + msg.payload = std::string(payload); + return msg; +} + +Message In(uint64_t timestamp_ns, std::string_view payload) { + return Msg(timestamp_ns, message_type_t::kRequest, payload); +} + +Message Out(uint64_t timestamp_ns, std::string_view payload) { + return Msg(timestamp_ns, message_type_t::kResponse, payload); +} + +auto IsRecord(RecordKind kind, std::string_view payload, std::string_view output) { + return AllOf(Field(&Record::kind, kind), + Field(&Record::msg, Field(&Message::payload, std::string(payload))), + Field(&Record::output, std::string(output))); +} + +TEST(K8sExecTest, ChannelSubprotocols) { + EXPECT_TRUE(IsK8sChannelProtocol("v5.channel.k8s.io")); + EXPECT_TRUE(IsK8sChannelProtocol("v4.channel.k8s.io")); + EXPECT_TRUE(IsK8sChannelProtocol("channel.k8s.io")); + EXPECT_FALSE(IsK8sChannelProtocol("base64.channel.k8s.io")); + EXPECT_FALSE(IsK8sChannelProtocol("v4.base64.channel.k8s.io")); + EXPECT_FALSE(IsK8sChannelProtocol("SPDY/3.1+portforward.k8s.io")); + EXPECT_FALSE(IsK8sChannelProtocol("graphql-transport-ws")); + EXPECT_FALSE(IsK8sChannelProtocol("")); +} + +TEST(K8sExecTest, CommandFromURL) { + EXPECT_EQ(K8sExecCommand("/api/v1/namespaces/ws-demo/pods/ws-demo/exec?command=tar&command=cf&" + "command=-&command=%2Fetc%2Fpasswd&container=ws-demo&stderr=true&" + "stdout=true"), + "tar cf - /etc/passwd"); + EXPECT_EQ(K8sExecCommand(kKubeletTTYPath), "sh"); + EXPECT_EQ(K8sExecCommand("/exec/ns/pod/ctr?command=echo&command=a+b"), "echo a b"); + EXPECT_EQ(K8sExecCommand("/api/v1/namespaces/ns/pods/pod/attach?container=c"), ""); +} + +TEST(K8sExecTest, TTYFromURL) { + EXPECT_TRUE(K8sExecTTY(kKubeletTTYPath)); + EXPECT_TRUE(K8sExecTTY("/api/v1/namespaces/ns/pods/pod/exec?command=sh&tty=true&stdin=true")); + EXPECT_FALSE(K8sExecTTY("/api/v1/namespaces/ns/pods/pod/exec?command=ls&stdout=true")); + EXPECT_FALSE(K8sExecTTY("/exec/ns/pod/ctr?command=sh&tty=0")); +} + +TEST(K8sExecTest, CleanTerminalOutput) { + EXPECT_EQ(CleanTerminalOutput("\r\nuid=0(root) gid=0(root)\r\n/ # ", true), + "uid=0(root) gid=0(root)\n"); + EXPECT_EQ(CleanTerminalOutput("\r\n\x1b[1;34mbin\x1b[m \x1b[1;34metc\x1b[m\r\n/ # ", true), + "bin etc\n"); + EXPECT_EQ(CleanTerminalOutput("\r\n/ # ", true), ""); + EXPECT_EQ(CleanTerminalOutput("\x1b]0;title\x07ok\r\n$ ", true), "ok\n"); + EXPECT_EQ(CleanTerminalOutput("a\nb", false), "a\nb"); +} + +TEST(K8sExecTest, PrintableEscapesOnlyNonText) { + EXPECT_EQ(Printable("ls -la\n\tx"), "ls -la\n\tx"); + EXPECT_EQ(Printable("\x01hi"), "\\x01hi"); +} + +TEST(K8sExecTest, TTYSessionBecomesOneRowPerCommand) { + std::vector messages = { + Out(1, "\x01"), + In(2, "\x04{\"Width\":0,\"Height\":0}\n"), + Out(3, "\x01/ # "), + In(4, "\x00id"sv), + Out(5, "\x01id"), + In(6, "\x00\r"sv), + Out(7, "\x01\r\n"), + Out(8, "\x01uid=0(root) gid=0(root) groups=0(root),10(wheel)\r\n"), + Out(9, "\x01/ # "), + Msg(10, message_type_t::kRequest, "", Opcode::kPing), + Msg(11, message_type_t::kResponse, "", Opcode::kPong), + In(12, "\x00""cat"sv), + Out(13, "\x01""cat"), + In(14, "\x00 /etc/hostname"sv), + Out(15, "\x01 /etc/hostname"), + In(16, "\x00\r"sv), + Out(17, "\x01\r\n"), + Out(18, "\x01ws-demo\r\n/ # "), + In(19, "\x00""exi"sv), + Out(20, "\x01""exi"), + In(21, "\x00t"sv), + Out(22, "\x01t"), + In(23, "\x00\r"sv), + Out(24, "\x01\r\n"), + Out(25, absl::StrCat("\x03", kStatusSuccess)), + Msg(26, message_type_t::kResponse, "\x03\xe8", Opcode::kClose), + }; + ExecState state; + std::vector records; + + DecodeK8sExec(kKubeletTTYPath, std::move(messages), &state, &records); + + EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "sh", ""), + IsRecord(RecordKind::kInput, "id", + "uid=0(root) gid=0(root) groups=0(root),10(wheel)\n"), + IsRecord(RecordKind::kInput, "cat /etc/hostname", "ws-demo\n"), + IsRecord(RecordKind::kInput, "exit", ""), + IsRecord(RecordKind::kExit, kStatusSuccess, ""))); + EXPECT_EQ(records[0].msg.timestamp_ns, 1U); + EXPECT_EQ(records[1].msg.timestamp_ns, 4U); + EXPECT_EQ(records[2].msg.timestamp_ns, 12U); + EXPECT_EQ(records[4].msg.timestamp_ns, 25U); +} + +TEST(K8sExecTest, LineEditingIsApplied) { + std::vector messages = { + In(1, "\x00lx"sv), In(2, "\x00\x7f"sv), In(3, "\x00s\r"sv), Out(4, "\x01\r\nbin\r\n/ # "), + In(5, "\x00junk"sv), In(6, "\x00\x15"sv), In(7, "\x00pwd\r"sv), + Out(8, "\x01\r\n/\r\n/ # "), + }; + ExecState state; + std::vector records; + + DecodeK8sExec(kKubeletTTYPath, std::move(messages), &state, &records); + + EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "sh", ""), + IsRecord(RecordKind::kInput, "ls", "bin\n"))); + EXPECT_EQ(state.pending->line, "pwd"); +} + +TEST(K8sExecTest, AbandonedLineIsKept) { + std::vector messages = { + In(1, "\x00""cat /etc/shadow"sv), + In(2, "\x00\x03"sv), + Out(3, "\x01^C\r\n/ # "), + In(4, "\x00\x04"sv), + Out(5, absl::StrCat("\x03", kStatusSuccess)), + }; + ExecState state; + std::vector records; + + DecodeK8sExec(kKubeletTTYPath, std::move(messages), &state, &records); + + EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "sh", ""), + IsRecord(RecordKind::kInput, "cat /etc/shadow^C", "^C\n"), + IsRecord(RecordKind::kInput, "^D", ""), + IsRecord(RecordKind::kExit, kStatusSuccess, ""))); +} + +TEST(K8sExecTest, NonTTYOutputGoesToExitRow) { + constexpr std::string_view kPath = + "/api/v1/namespaces/ws-demo/pods/ws-demo/exec?command=tar&command=cf&command=-&" + "command=%2Fetc%2Fpasswd&container=ws-demo&stderr=true&stdout=true"; + const std::string tar = absl::StrCat("etc/passwd", std::string(4, '\0')); + std::vector messages = { + Out(1, "\x01"), + Out(2, "\x02tar: removing leading '/' from member names\n"), + Out(3, absl::StrCat("\x01", tar)), + Out(4, absl::StrCat("\x03", kStatusSuccess)), + }; + ExecState state; + std::vector records; + + DecodeK8sExec(kPath, std::move(messages), &state, &records); + + ASSERT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "tar cf - /etc/passwd", ""), + IsRecord(RecordKind::kExit, kStatusSuccess, + absl::StrCat("tar: removing leading '/' from member " + "names\n", + tar)))); + EXPECT_EQ(records[1].output_size, 44U + tar.size()); +} + +TEST(K8sExecTest, SessionContinuesAcrossCalls) { + ExecState state; + std::vector records; + + DecodeK8sExec(kKubeletTTYPath, {Out(1, "\x01/ # "), In(2, "\x00i"sv)}, &state, &records); + DecodeK8sExec(kKubeletTTYPath, {In(3, "\x00""d\r"sv), Out(4, "\x01\r\nuid=0\r\n/ # ")}, &state, + &records); + DecodeK8sExec(kKubeletTTYPath, {Out(5, absl::StrCat("\x03", kStatusSuccess))}, &state, &records); + + EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "sh", ""), + IsRecord(RecordKind::kInput, "id", "uid=0\n"), + IsRecord(RecordKind::kExit, kStatusSuccess, ""))); + EXPECT_EQ(records[1].msg.timestamp_ns, 2U); +} + +TEST(K8sExecTest, BufferedOutputIsBounded) { + constexpr std::string_view kPath = "/exec/ns/pod/ctr?command=cat&command=big&output=1"; + const std::string chunk = absl::StrCat("\x01", std::string(100000, 'a')); + ExecState state; + std::vector records; + + DecodeK8sExec(kPath, {Out(1, chunk), Out(2, absl::StrCat("\x03", kStatusSuccess))}, &state, + &records); + + ASSERT_EQ(records.size(), 2U); + EXPECT_EQ(records[1].output_size, 100000U); + EXPECT_LT(records[1].output.size(), 100000U); + EXPECT_THAT(state.output, IsEmpty()); +} + +} // namespace websocket +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc index 8b6a274a578..2d2c8f76c9b 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc @@ -46,7 +46,8 @@ constexpr size_t kMaskingKeySize = 4; } // namespace websocket template <> -ParseState ParseFrame(message_type_t, std::string_view* buf, websocket::Frame* frame, NoState*) { +ParseState ParseFrame(message_type_t, std::string_view* buf, websocket::Frame* frame, + websocket::StateWrapper*) { using websocket::Opcode; BinaryDecoder decoder(*buf); @@ -104,7 +105,8 @@ ParseState ParseFrame(message_type_t, std::string_view* buf, websocket::Frame* f } template <> -size_t FindFrameBoundary(message_type_t, std::string_view, size_t, NoState*) { +size_t FindFrameBoundary(message_type_t, std::string_view, size_t, + websocket::StateWrapper*) { return std::string_view::npos; } diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h index 3ca20e48033..09353a63916 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h @@ -29,11 +29,11 @@ namespace protocols { template <> ParseState ParseFrame(message_type_t type, std::string_view* buf, websocket::Frame* frame, - NoState* state); + websocket::StateWrapper* state); template <> size_t FindFrameBoundary(message_type_t type, std::string_view buf, - size_t start_pos, NoState* state); + size_t start_pos, websocket::StateWrapper* state); } // namespace protocols } // namespace stirling diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc index dd11359eb10..1ba4b812691 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc @@ -64,7 +64,7 @@ class WebSocketParseTest : public ::testing::Test { } Frame frame_; - NoState state_; + StateWrapper state_; }; TEST_F(WebSocketParseTest, UnmaskedTextFrame) { diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc index dbd3a502f02..223cf805c30 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc @@ -18,9 +18,12 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h" +#include #include #include +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h" + namespace px { namespace stirling { namespace protocols { @@ -41,13 +44,14 @@ Message StartMessage(message_type_t type, Frame* frame) { return msg; } -int StitchDirection(message_type_t type, std::deque* frames, std::vector* records) { +int StitchDirection(message_type_t type, std::deque* frames, + std::vector* messages) { int error_count = 0; std::deque pending; for (Frame& frame : *frames) { if (IsControl(frame.opcode)) { - records->push_back({StartMessage(type, &frame)}); + messages->push_back(StartMessage(type, &frame)); continue; } if (frame.opcode == Opcode::kContinuation) { @@ -71,7 +75,7 @@ int StitchDirection(message_type_t type, std::deque* frames, std::vector< msg.payload.append(pending[i].payload); ++msg.fragments; } - records->push_back({std::move(msg)}); + messages->push_back(std::move(msg)); pending.clear(); } @@ -85,12 +89,30 @@ int StitchDirection(message_type_t type, std::deque* frames, std::vector< template <> RecordsWithErrorCount StitchFrames(std::deque* req_frames, std::deque* resp_frames, - NoState*) { + websocket::StateWrapper* state) { RecordsWithErrorCount result; + std::vector messages; result.error_count += - websocket::StitchDirection(message_type_t::kRequest, req_frames, &result.records); + websocket::StitchDirection(message_type_t::kRequest, req_frames, &messages); result.error_count += - websocket::StitchDirection(message_type_t::kResponse, resp_frames, &result.records); + websocket::StitchDirection(message_type_t::kResponse, resp_frames, &messages); + + websocket::State empty_state; + websocket::State* global = state == nullptr ? &empty_state : &state->global; + if (websocket::IsK8sChannelProtocol(global->subprotocol)) { + std::stable_sort(messages.begin(), messages.end(), + [](const websocket::Message& a, const websocket::Message& b) { + return a.timestamp_ns < b.timestamp_ns; + }); + websocket::DecodeK8sExec(global->path, std::move(messages), &global->exec, &result.records); + } else { + for (websocket::Message& msg : messages) { + result.records.push_back({std::move(msg)}); + } + } + for (websocket::Record& record : result.records) { + record.subprotocol = global->subprotocol; + } return result; } diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h index ef022e6be06..c2db5f9e07f 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h @@ -30,7 +30,7 @@ namespace protocols { template <> RecordsWithErrorCount StitchFrames(std::deque* req_frames, std::deque* resp_frames, - NoState* state); + websocket::StateWrapper* state); } // namespace protocols } // namespace stirling diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc index 6eda1420a9c..92fb8c3a8bd 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc @@ -49,7 +49,7 @@ class WebSocketStitcherTest : public ::testing::Test { std::deque req_frames_; std::deque resp_frames_; - NoState state_; + StateWrapper state_; }; TEST_F(WebSocketStitcherTest, OneRecordPerMessageInEachDirection) { @@ -146,6 +146,36 @@ TEST_F(WebSocketStitcherTest, NewMessageBeforeLastFragmentIsAnError) { EXPECT_TRUE(req_frames_.empty()); } +TEST_F(WebSocketStitcherTest, RawFramesCarrySubprotocol) { + state_.global.subprotocol = "graphql-transport-ws"; + req_frames_.push_back(MakeFrame(Opcode::kText, true, R"({"type":"ping"})", 1)); + + RecordsWithErrorCount result = Stitch(); + + ASSERT_EQ(result.records.size(), 1U); + EXPECT_EQ(result.records[0].kind, RecordKind::kFrame); + EXPECT_EQ(result.records[0].subprotocol, "graphql-transport-ws"); +} + +TEST_F(WebSocketStitcherTest, K8sExecSessionIsDecoded) { + state_.global.subprotocol = "v5.channel.k8s.io"; + state_.global.path = "/api/v1/namespaces/ns/pods/pod/exec?command=hostname&stdout=true"; + resp_frames_.push_back(MakeFrame(Opcode::kBinary, true, "\x01pod\n", 1)); + resp_frames_.push_back( + MakeFrame(Opcode::kBinary, true, "\x03{\"metadata\":{},\"status\":\"Success\"}", 2)); + resp_frames_.push_back(MakeFrame(Opcode::kClose, true, "\x03\xe8", 3)); + + RecordsWithErrorCount result = Stitch(); + + ASSERT_EQ(result.records.size(), 2U); + EXPECT_EQ(result.records[0].kind, RecordKind::kExec); + EXPECT_EQ(result.records[0].msg.payload, "hostname"); + EXPECT_EQ(result.records[1].kind, RecordKind::kExit); + EXPECT_EQ(result.records[1].output, "pod\n"); + EXPECT_EQ(result.records[1].subprotocol, "v5.channel.k8s.io"); + EXPECT_TRUE(resp_frames_.empty()); +} + } // namespace websocket } // namespace protocols } // namespace stirling diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h index 9b9148ba88c..dfbabc8b7ce 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h @@ -18,7 +18,10 @@ #pragma once +#include #include +#include +#include #include "src/common/base/base.h" #include "src/stirling/source_connectors/socket_tracer/protocols/common/event_parser.h" @@ -73,16 +76,72 @@ struct Message { } }; +enum class RecordKind : uint8_t { + kFrame, + kExec, + kInput, + kExit, +}; + +inline std::string_view RecordKindName(RecordKind kind) { + switch (kind) { + case RecordKind::kFrame: + return "frame"; + case RecordKind::kExec: + return "exec"; + case RecordKind::kInput: + return "input"; + case RecordKind::kExit: + return "exit"; + } + return "unknown"; +} + struct Record { Message msg; + RecordKind kind = RecordKind::kFrame; + std::string subprotocol; + std::string output; + size_t output_size = 0; + + std::string ToString() const { + return absl::Substitute("[kind=$0 subprotocol=$1 msg=$2 output_size=$3]", + RecordKindName(kind), subprotocol, msg.ToString(), output_size); + } +}; + +struct PendingInput { + uint64_t timestamp_ns = 0; + std::string line; +}; + +struct ExecState { + bool started = false; + bool tty = false; + bool last_cr = false; + std::string line; + uint64_t line_timestamp_ns = 0; + std::optional pending; + std::string output; + size_t output_size = 0; +}; + +struct State { + std::string path; + std::string subprotocol; + ExecState exec; +}; - std::string ToString() const { return absl::Substitute("[msg=$0]", msg.ToString()); } +struct StateWrapper { + State global; + std::monostate send; + std::monostate recv; }; struct ProtocolTraits : public BaseProtocolTraits { using frame_type = Frame; using record_type = Record; - using state_type = NoState; + using state_type = StateWrapper; using key_type = stream_id_t; static void ConvertTimestamps(Record* record, ConvertTimestampsFuncType func) { diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index e3a49e84364..c69795a8d87 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -47,6 +47,7 @@ #include "src/stirling/source_connectors/socket_tracer/proto/sock_event.pb.h" #include "src/stirling/source_connectors/socket_tracer/protocols/http/utils.h" #include "src/stirling/source_connectors/socket_tracer/protocols/http2/grpc.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h" #include "src/stirling/utils/linux_headers.h" #include "src/stirling/utils/proc_path_tools.h" @@ -1804,17 +1805,25 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke r.Append(conn_tracker.local_endpoint().port()); r.Append(conn_tracker.role()); r.Append(conn_tracker.ssl()); + r.Append(std::move(record.subprotocol)); + r.Append(std::string(protocols::websocket::RecordKindName(record.kind))); r.Append(static_cast(msg.type)); r.Append(static_cast(msg.opcode)); r.Append(msg.compressed); r.Append(msg.fragments); - if (msg.opcode == protocols::websocket::Opcode::kText) { + if (record.kind != protocols::websocket::RecordKind::kFrame) { + r.Append(protocols::websocket::Printable(msg.payload), + FLAGS_max_body_bytes); + } else if (msg.opcode == protocols::websocket::Opcode::kText) { r.Append(std::move(msg.payload), FLAGS_max_body_bytes); } else { r.Append(BytesToString(msg.payload), FLAGS_max_body_bytes); } r.Append(payload_size); + r.Append(protocols::websocket::Printable(record.output), + FLAGS_max_body_bytes); + r.Append(record.output_size); #ifndef NDEBUG r.Append(PXInfoString(conn_tracker, record)); #endif diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc index f799ead05ab..5861b08463d 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc @@ -295,6 +295,50 @@ TEST_F(SocketTraceConnectorWebSocketTest, NonTextPayloadsAreEscaped) { EXPECT_THAT(ToIntVector(records[kWebSocketPayloadSizeIdx]), ElementsAre(4, 2)); } +TEST_F(SocketTraceConnectorWebSocketTest, K8sExecSessionProducesCommandRows) { + using std::string_view_literals::operator""sv; + constexpr std::string_view kExecReq = + "GET /exec/ns/pod/ctr?command=sh&input=1&output=1&tty=1 HTTP/1.1\r\n" + "Connection: Upgrade\r\n" + "Upgrade: websocket\r\n" + "Sec-WebSocket-Protocol: v5.channel.k8s.io\r\n" + "\r\n"; + constexpr std::string_view kExecResp = + "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Protocol: v5.channel.k8s.io\r\n" + "\r\n"; + constexpr std::string_view kPrompt = "\x82\x05\x01/ # "sv; + constexpr std::string_view kStdinId = "\x82\x03\x00id"sv; + constexpr std::string_view kStdinEnter = "\x82\x02\x00\r"sv; + constexpr std::string_view kStdout = "\x82\x0e\x01\r\nuid=0\r\n/ # "sv; + constexpr std::string_view kStatus = + "\x82\x23\x03" R"({"metadata":{},"status":"Success"})"sv; + + struct socket_control_event_t conn = event_gen_.InitConn(); + source_->AcceptControlEvent(conn); + source_->AcceptDataEvent(event_gen_.InitSendEvent(kExecReq)); + source_->AcceptDataEvent( + event_gen_.InitRecvEvent(absl::StrCat(kExecResp, kPrompt))); + connector_->TransferData(ctx_.get()); + source_->AcceptDataEvent(event_gen_.InitSendEvent(kStdinId)); + source_->AcceptDataEvent(event_gen_.InitSendEvent(kStdinEnter)); + source_->AcceptDataEvent(event_gen_.InitRecvEvent(kStdout)); + source_->AcceptDataEvent(event_gen_.InitRecvEvent(kStatus)); + connector_->TransferData(ctx_.get()); + + std::vector tablets = websocket_table_->ConsumeRecords(); + ASSERT_NOT_EMPTY_AND_GET_RECORDS(RecordBatch & records, tablets); + ASSERT_THAT(records, RecordBatchSizeIs(3)); + EXPECT_THAT(ToStringVector(records[kWebSocketKindIdx]), ElementsAre("exec", "input", "exit")); + EXPECT_THAT(ToStringVector(records[kWebSocketSubprotocolIdx]), + ElementsAre("v5.channel.k8s.io", "v5.channel.k8s.io", "v5.channel.k8s.io")); + EXPECT_THAT(ToStringVector(records[kWebSocketPayloadIdx]), + ElementsAre("sh", "id", R"({"metadata":{},"status":"Success"})")); + EXPECT_THAT(ToStringVector(records[kWebSocketOutputIdx]), ElementsAre("", "uid=0\n", "")); +} + TEST_F(SocketTraceConnectorTest, HTTPDelayedRespBody) { struct socket_control_event_t conn = event_gen_.InitConn(); std::unique_ptr event0_req = event_gen_.InitSendEvent(kReq4); diff --git a/src/stirling/source_connectors/socket_tracer/websocket_table.h b/src/stirling/source_connectors/socket_tracer/websocket_table.h index 0d8eb0bc974..e3a7ba4ecec 100644 --- a/src/stirling/source_connectors/socket_tracer/websocket_table.h +++ b/src/stirling/source_connectors/socket_tracer/websocket_table.h @@ -36,6 +36,14 @@ static constexpr DataElement kWebSocketElements[] = { canonical_data_elements::kLocalPort, canonical_data_elements::kTraceRole, canonical_data_elements::kEncrypted, + {"subprotocol", "WebSocket subprotocol selected by the server", + types::DataType::STRING, + types::SemanticType::ST_NONE, + types::PatternType::GENERAL_ENUM}, + {"kind", "frame for a raw message; exec, input or exit for a decoded Kubernetes exec session", + types::DataType::STRING, + types::SemanticType::ST_NONE, + types::PatternType::GENERAL_ENUM}, {"direction", "1 if the client sent the message, 2 if the server sent it", types::DataType::INT64, types::SemanticType::ST_NONE, @@ -60,6 +68,14 @@ static constexpr DataElement kWebSocketElements[] = { types::DataType::INT64, types::SemanticType::ST_BYTES, types::PatternType::METRIC_GAUGE}, + {"output", "Output that followed an exec input or exit, truncated", + types::DataType::STRING, + types::SemanticType::ST_NONE, + types::PatternType::GENERAL}, + {"output_size", "Output size (before any truncation)", + types::DataType::INT64, + types::SemanticType::ST_BYTES, + types::PatternType::METRIC_GAUGE}, #ifndef NDEBUG canonical_data_elements::kPXInfo, #endif @@ -70,10 +86,14 @@ static constexpr auto kWebSocketTable = DataTableSchema("websocket_events", "WebSocket messages", kWebSocketElements); DEFINE_PRINT_TABLE(WebSocket) +constexpr int kWebSocketSubprotocolIdx = kWebSocketTable.ColIndex("subprotocol"); +constexpr int kWebSocketKindIdx = kWebSocketTable.ColIndex("kind"); constexpr int kWebSocketDirectionIdx = kWebSocketTable.ColIndex("direction"); constexpr int kWebSocketOpcodeIdx = kWebSocketTable.ColIndex("opcode"); constexpr int kWebSocketPayloadIdx = kWebSocketTable.ColIndex("payload"); constexpr int kWebSocketPayloadSizeIdx = kWebSocketTable.ColIndex("payload_size"); +constexpr int kWebSocketOutputIdx = kWebSocketTable.ColIndex("output"); +constexpr int kWebSocketOutputSizeIdx = kWebSocketTable.ColIndex("output_size"); } // namespace stirling } // namespace px From d9138afb8174a18e54298ec681f548b4c43d265c Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 14:13:42 +0100 Subject: [PATCH 17/51] Decode Kubernetes exec sessions in WebSocket traces Signed-off-by: entlein --- .../socket_tracer/protocols/http/parse.cc | 5 + .../protocols/websocket/k8s_exec.cc | 293 +++++++++++++++++- 2 files changed, 292 insertions(+), 6 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc index d3a0643f205..b97c625dd84 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc @@ -196,6 +196,10 @@ ParseState ParseResponseBody(std::string_view* buf, Message* result, State* stat } if (IsWebSocketUpgrade(result->headers)) { state->websocket_upgrade_accepted = true; + const auto subprotocol_iter = result->headers.find(kSecWebSocketProtocol); + if (subprotocol_iter != result->headers.end()) { + state->websocket_subprotocol = subprotocol_iter->second; + } return ParseState::kEOS; } @@ -289,6 +293,7 @@ ParseState ParseFrame(message_type_t type, std::string_view* buf, Message* resul ParseState parse_state = ParseRequest(buf, result); if (parse_state == ParseState::kSuccess && IsWebSocketUpgrade(result->headers)) { state->websocket_upgrade_requested = true; + state->websocket_path = result->req_path; } return parse_state; } diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc index 317eadebf34..96682d8e8af 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc @@ -18,22 +18,303 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h" +#include +#include + +#include +#include +#include +#include + +#include "src/common/base/base.h" + namespace px { namespace stirling { namespace protocols { namespace websocket { -bool IsK8sChannelProtocol(std::string_view) { return false; } +namespace { + +constexpr std::string_view kChannelProtocolSuffix = "channel.k8s.io"; +constexpr std::string_view kBase64ChannelProtocol = "base64.channel.k8s.io"; +constexpr uint8_t kStdinChannel = 0; +constexpr uint8_t kStdoutChannel = 1; +constexpr uint8_t kStderrChannel = 2; +constexpr uint8_t kStatusChannel = 3; +constexpr size_t kMaxBufferedOutput = 4096; +constexpr char kEsc = '\x1b'; +constexpr char kBel = '\x07'; +constexpr char kBackspace = '\x08'; +constexpr char kDelete = '\x7f'; +constexpr char kCtrlC = '\x03'; +constexpr char kCtrlD = '\x04'; +constexpr char kCtrlU = '\x15'; + +int HexValue(char c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } + return -1; +} + +std::string QueryUnescape(std::string_view value) { + std::string out; + out.reserve(value.size()); + for (size_t i = 0; i < value.size(); ++i) { + if (value[i] == '+') { + out.push_back(' '); + } else if (value[i] == '%' && i + 2 < value.size() && HexValue(value[i + 1]) >= 0 && + HexValue(value[i + 2]) >= 0) { + out.push_back(static_cast(HexValue(value[i + 1]) * 16 + HexValue(value[i + 2]))); + i += 2; + } else { + out.push_back(value[i]); + } + } + return out; +} + +std::vector QueryValues(std::string_view path, std::string_view key) { + std::vector values; + size_t query_start = path.find('?'); + if (query_start == std::string_view::npos) { + return values; + } + for (std::string_view param : absl::StrSplit(path.substr(query_start + 1), '&')) { + std::pair kv = + absl::StrSplit(param, absl::MaxSplits('=', 1)); + if (kv.first == key) { + values.push_back(QueryUnescape(kv.second)); + } + } + return values; +} + +void PopUTF8Char(std::string* line) { + while (!line->empty()) { + const bool continuation = (static_cast(line->back()) & 0xc0) == 0x80; + line->pop_back(); + if (!continuation) { + return; + } + } +} + +std::string StripEscapeSequences(std::string_view text) { + std::string out; + out.reserve(text.size()); + for (size_t i = 0; i < text.size(); ++i) { + if (text[i] != kEsc) { + out.push_back(text[i]); + continue; + } + if (i + 1 >= text.size()) { + break; + } + if (text[i + 1] == '[') { + i += 2; + while (i < text.size() && (text[i] < 0x40 || text[i] > 0x7e)) { + ++i; + } + } else if (text[i + 1] == ']') { + i += 2; + while (i < text.size() && text[i] != kBel && + !(text[i] == kEsc && i + 1 < text.size() && text[i + 1] == '\\')) { + ++i; + } + if (i < text.size() && text[i] == kEsc) { + ++i; + } + } else { + ++i; + } + } + return out; +} + +Record MakeRecord(RecordKind kind, message_type_t type, uint64_t timestamp_ns, + std::string payload) { + Record record; + record.kind = kind; + record.msg.timestamp_ns = timestamp_ns; + record.msg.type = type; + record.msg.opcode = Opcode::kBinary; + record.msg.fragments = 1; + record.msg.payload = std::move(payload); + return record; +} + +void TakeOutput(ExecState* state, Record* record) { + record->output = CleanTerminalOutput(state->output, state->tty); + record->output_size = state->output_size; + state->output.clear(); + state->output_size = 0; +} + +void AppendOutput(ExecState* state, std::string_view data) { + state->output_size += data.size(); + const size_t room = kMaxBufferedOutput - std::min(kMaxBufferedOutput, state->output.size()); + state->output.append(data.substr(0, room)); +} + +void EmitPending(ExecState* state, std::vector* records) { + if (!state->pending.has_value()) { + return; + } + Record record = MakeRecord(RecordKind::kInput, message_type_t::kRequest, + state->pending->timestamp_ns, std::move(state->pending->line)); + TakeOutput(state, &record); + records->push_back(std::move(record)); + state->pending.reset(); +} + +void SubmitLine(ExecState* state, std::string_view suffix, std::vector* records) { + EmitPending(state, records); + state->pending = PendingInput{state->line_timestamp_ns, absl::StrCat(state->line, suffix)}; + state->line.clear(); + state->output.clear(); + state->output_size = 0; +} + +void HandleStdin(uint64_t timestamp_ns, std::string_view data, ExecState* state, + std::vector* records) { + for (char c : data) { + const bool after_cr = state->last_cr; + state->last_cr = c == '\r'; + switch (c) { + case '\r': + case '\n': + if (!state->line.empty()) { + SubmitLine(state, "", records); + } else if (c == '\n' && after_cr) { + continue; + } + break; + case kBackspace: + case kDelete: + PopUTF8Char(&state->line); + break; + case kCtrlU: + state->line.clear(); + break; + case kCtrlC: + if (!state->line.empty()) { + SubmitLine(state, "^C", records); + } + break; + case kCtrlD: + if (state->line.empty()) { + state->line_timestamp_ns = timestamp_ns; + SubmitLine(state, "^D", records); + } + break; + default: + if (state->line.empty()) { + state->line_timestamp_ns = timestamp_ns; + } + state->line.push_back(c); + break; + } + } +} + +} // namespace + +bool IsK8sChannelProtocol(std::string_view subprotocol) { + return absl::EndsWith(subprotocol, kChannelProtocolSuffix) && + !absl::EndsWith(subprotocol, kBase64ChannelProtocol); +} -std::string K8sExecCommand(std::string_view) { return ""; } +std::string K8sExecCommand(std::string_view path) { + return absl::StrJoin(QueryValues(path, "command"), " "); +} -bool K8sExecTTY(std::string_view) { return false; } +bool K8sExecTTY(std::string_view path) { + for (const std::string& value : QueryValues(path, "tty")) { + if (value == "true" || value == "1") { + return true; + } + } + return false; +} -std::string CleanTerminalOutput(std::string_view output, bool) { return std::string(output); } +std::string CleanTerminalOutput(std::string_view output, bool tty) { + if (!tty) { + return std::string(output); + } + std::string text = StripEscapeSequences(output); + std::string out; + out.reserve(text.size()); + for (size_t i = 0; i < text.size(); ++i) { + if (text[i] == '\r' && i + 1 < text.size() && text[i + 1] == '\n') { + continue; + } + out.push_back(text[i]); + } + if (absl::StartsWith(out, "\n")) { + out.erase(0, 1); + } + const size_t last_newline = out.rfind('\n'); + out.resize(last_newline == std::string::npos ? 0 : last_newline + 1); + return out; +} -std::string Printable(std::string_view data) { return std::string(data); } +std::string Printable(std::string_view data) { + const bool printable = std::all_of(data.begin(), data.end(), [](char c) { + return (c >= 0x20 && c < 0x7f) || c == '\n' || c == '\t'; + }); + if (printable) { + return std::string(data); + } + return BytesToString(data); +} -void DecodeK8sExec(std::string_view, std::vector, ExecState*, std::vector*) {} +void DecodeK8sExec(std::string_view path, std::vector messages, ExecState* state, + std::vector* records) { + for (Message& msg : messages) { + if (IsControl(msg.opcode) || msg.payload.empty()) { + continue; + } + if (!state->started) { + state->started = true; + state->tty = K8sExecTTY(path); + records->push_back(MakeRecord(RecordKind::kExec, message_type_t::kRequest, msg.timestamp_ns, + K8sExecCommand(path))); + } + const uint8_t channel = msg.payload[0]; + std::string_view data = std::string_view(msg.payload).substr(1); + if (msg.type == message_type_t::kRequest) { + if (channel == kStdinChannel) { + HandleStdin(msg.timestamp_ns, data, state, records); + } + continue; + } + switch (channel) { + case kStdoutChannel: + case kStderrChannel: + if (state->line.empty()) { + AppendOutput(state, data); + } + break; + case kStatusChannel: { + EmitPending(state, records); + Record record = MakeRecord(RecordKind::kExit, message_type_t::kResponse, msg.timestamp_ns, + std::string(data)); + TakeOutput(state, &record); + records->push_back(std::move(record)); + break; + } + default: + break; + } + } +} } // namespace websocket } // namespace protocols From 068f94299cc0a2b1204081f9c9e5c8abed3320ca Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 14:15:07 +0100 Subject: [PATCH 18/51] Test tar manifests and non-TTY stdin in Kubernetes exec sessions Signed-off-by: entlein --- .../protocols/websocket/k8s_exec_test.cc | 111 ++++++++++++++++++ .../socket_tracer/protocols/websocket/types.h | 1 + 2 files changed, 112 insertions(+) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc index 1999330dd12..374efd69aaf 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc @@ -23,6 +23,8 @@ #include #include +#include +#include #include "src/common/testing/testing.h" @@ -243,6 +245,115 @@ TEST(K8sExecTest, BufferedOutputIsBounded) { EXPECT_THAT(state.output, IsEmpty()); } +std::string TarHeader(std::string_view name, uint64_t mode, uint64_t size, char typeflag = '0') { + std::string header(512, '\0'); + header.replace(0, name.size(), name); + const std::string mode_field = absl::StrFormat("%07o", mode); + header.replace(100, mode_field.size(), mode_field); + const std::string size_field = absl::StrFormat("%011o", size); + header.replace(124, size_field.size(), size_field); + header[156] = typeflag; + header.replace(257, 6, std::string("ustar\0", 6)); + header.replace(263, 2, "00"); + return header; +} + +std::string TarEntry(std::string_view name, uint64_t mode, std::string_view content) { + std::string entry = TarHeader(name, mode, content.size()); + entry.append(content); + entry.append((512 - content.size() % 512) % 512, '\0'); + return entry; +} + +std::string TarArchive(const std::vector& entries) { + std::string archive = absl::StrJoin(entries, ""); + archive.append(1024, '\0'); + return archive; +} + +TEST(K8sExecTest, TarFromStdoutBecomesManifest) { + constexpr std::string_view kPath = + "/api/v1/namespaces/ns/pods/pod/exec?command=tar&command=cf&command=-&command=%2Fetc&" + "stdout=true"; + const std::string archive = + TarArchive({TarEntry("etc/passwd", 0644, "root:x:0:0:root:/root:/bin/sh\n"), + TarEntry("etc/shadow", 0640, std::string(700, 'x'))}); + std::vector messages = {Out(1, "\x01")}; + for (size_t pos = 0; pos < archive.size(); pos += 300) { + messages.push_back(Out(2 + pos, absl::StrCat("\x01", archive.substr(pos, 300)))); + } + messages.push_back(Out(10000, absl::StrCat("\x03", kStatusSuccess))); + ExecState state; + std::vector records; + + DecodeK8sExec(kPath, std::move(messages), &state, &records); + + ASSERT_EQ(records.size(), 2U); + EXPECT_EQ(records[1].kind, RecordKind::kExit); + EXPECT_EQ(records[1].output, + absl::StrCat("etc/passwd mode=0644 size=30 head=\"root:x:0:0:root:/root:/bin/sh\\n\"\n", + "etc/shadow mode=0640 size=700 head=\"", std::string(64, 'x'), "\"\n")); + EXPECT_EQ(records[1].output_size, archive.size()); +} + +TEST(K8sExecTest, TarLongNameIsResolved) { + constexpr std::string_view kPath = "/exec/ns/pod/ctr?command=tar&command=cf&command=-&output=1"; + const std::string long_name = absl::StrCat("data/", std::string(120, 'n')); + std::string long_name_entry = TarHeader("././@LongLink", 0, long_name.size() + 1, 'L'); + long_name_entry.append(long_name); + long_name_entry.push_back('\0'); + long_name_entry.append((512 - (long_name.size() + 1) % 512) % 512, '\0'); + const std::string archive = TarArchive({long_name_entry, TarEntry("data/nnn", 0600, "v")}); + ExecState state; + std::vector records; + + DecodeK8sExec(kPath, + {Out(1, absl::StrCat("\x01", archive)), Out(2, absl::StrCat("\x03", kStatusSuccess))}, + &state, &records); + + ASSERT_EQ(records.size(), 2U); + EXPECT_EQ(records[1].output, absl::StrCat(long_name, " mode=0600 size=1 head=\"v\"\n")); +} + +TEST(K8sExecTest, NonTTYStdinIsOneInputRow) { + constexpr std::string_view kPath = "/exec/ns/pod/ctr?command=sh&input=1&output=1"; + ExecState state; + std::vector records; + + DecodeK8sExec(kPath, + {In(1, "\x00id\n"sv), In(2, "\x00hostname\n"sv), Out(3, "\x01uid=0\npod\n"), + Out(4, absl::StrCat("\x03", kStatusSuccess))}, + &state, &records); + + EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "sh", ""), + IsRecord(RecordKind::kInput, "id\nhostname\n", ""), + IsRecord(RecordKind::kExit, kStatusSuccess, "uid=0\npod\n"))); + EXPECT_EQ(records[1].msg.timestamp_ns, 1U); + EXPECT_EQ(records[1].payload_size, 12U); +} + +TEST(K8sExecTest, TarOnStdinBecomesManifest) { + constexpr std::string_view kPath = + "/api/v1/namespaces/ns/pods/pod/exec?command=tar&command=xmf&command=-&command=-C&" + "command=%2Ftmp&stdin=true"; + const std::string archive = TarArchive({TarEntry("payload.sh", 0755, "#!/bin/sh\necho hi\n")}); + ExecState state; + std::vector records; + + DecodeK8sExec(kPath, + {In(1, absl::StrCat(std::string(1, '\0'), archive)), + In(2, "\xff\x00"sv), Out(3, absl::StrCat("\x03", kStatusSuccess))}, + &state, &records); + + EXPECT_THAT(records, + ElementsAre(IsRecord(RecordKind::kExec, "tar xmf - -C /tmp", ""), + IsRecord(RecordKind::kInput, + "payload.sh mode=0755 size=18 head=\"#!/bin/sh\\necho hi\\n\"\n", + ""), + IsRecord(RecordKind::kExit, kStatusSuccess, ""))); + EXPECT_EQ(records[1].payload_size, archive.size()); +} + } // namespace websocket } // namespace protocols } // namespace stirling diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h index dfbabc8b7ce..d6f6781afef 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h @@ -101,6 +101,7 @@ struct Record { Message msg; RecordKind kind = RecordKind::kFrame; std::string subprotocol; + size_t payload_size = 0; std::string output; size_t output_size = 0; From 5eea991e8215ba62bf47aa3687a87b265843cf18 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 14:16:36 +0100 Subject: [PATCH 19/51] Summarize tar streams and non-TTY stdin in Kubernetes exec sessions Signed-off-by: entlein --- .../protocols/websocket/k8s_exec.cc | 181 +++++++++++++++++- .../socket_tracer/protocols/websocket/types.h | 25 +++ .../socket_tracer/socket_trace_connector.cc | 4 +- 3 files changed, 204 insertions(+), 6 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc index 96682d8e8af..21dc228021c 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc @@ -21,10 +21,13 @@ #include #include +#include #include #include +#include #include #include +#include #include "src/common/base/base.h" @@ -49,6 +52,23 @@ constexpr char kDelete = '\x7f'; constexpr char kCtrlC = '\x03'; constexpr char kCtrlD = '\x04'; constexpr char kCtrlU = '\x15'; +constexpr size_t kTarBlockSize = 512; +constexpr size_t kTarMaxEntries = 1024; +constexpr size_t kTarHeadSize = 64; +constexpr size_t kTarMaxLongName = 4096; +constexpr std::string_view kTarMagic = "ustar"; +constexpr size_t kTarMagicOffset = 257; +constexpr size_t kTarModeOffset = 100; +constexpr size_t kTarModeSize = 8; +constexpr size_t kTarSizeOffset = 124; +constexpr size_t kTarSizeSize = 12; +constexpr size_t kTarTypeOffset = 156; +constexpr size_t kTarNameSize = 100; +constexpr size_t kTarPrefixOffset = 345; +constexpr size_t kTarPrefixSize = 155; +constexpr char kTarLongNameType = 'L'; +constexpr char kTarPaxType = 'x'; +constexpr char kTarPaxGlobalType = 'g'; int HexValue(char c) { if (c >= '0' && c <= '9') { @@ -138,6 +158,124 @@ std::string StripEscapeSequences(std::string_view text) { return out; } +std::string_view CString(std::string_view field) { + return field.substr(0, field.find('\0')); +} + +uint64_t ParseOctal(std::string_view field) { + uint64_t value = 0; + for (char c : field) { + if (c >= '0' && c <= '7') { + value = value * 8 + (c - '0'); + } else if (value != 0 || (c != ' ' && c != '\0')) { + break; + } + } + return value; +} + +uint64_t RoundUpToBlock(uint64_t size) { + return (size + kTarBlockSize - 1) / kTarBlockSize * kTarBlockSize; +} + +void ParseTarHeader(std::string_view header, TarStream* tar) { + if (std::all_of(header.begin(), header.end(), [](char c) { return c == '\0'; }) || + header.substr(kTarMagicOffset, kTarMagic.size()) != kTarMagic) { + tar->done = true; + return; + } + const uint64_t size = ParseOctal(header.substr(kTarSizeOffset, kTarSizeSize)); + tar->skip = RoundUpToBlock(size); + tar->capture_left = 0; + const char type = header[kTarTypeOffset]; + if (type == kTarLongNameType) { + tar->long_name = true; + tar->next_name.clear(); + tar->capture_left = std::min(size, kTarMaxLongName); + return; + } + if (type == kTarPaxType || type == kTarPaxGlobalType) { + return; + } + std::string name = std::string(CString(header.substr(0, kTarNameSize))); + std::string_view prefix = CString(header.substr(kTarPrefixOffset, kTarPrefixSize)); + if (!tar->next_name.empty()) { + name = std::string(CString(tar->next_name)); + tar->next_name.clear(); + } else if (!prefix.empty()) { + name = absl::StrCat(prefix, "/", name); + } + if (tar->entries.size() >= kTarMaxEntries) { + return; + } + tar->entries.push_back( + {std::move(name), ParseOctal(header.substr(kTarModeOffset, kTarModeSize)), size, ""}); + tar->capture_left = std::min(size, kTarHeadSize); +} + +std::string FeedTar(TarStream* tar, std::string_view data) { + if (tar->checked && !tar->is_tar) { + return std::string(data); + } + size_t pos = 0; + while (pos < data.size() && !tar->done) { + if (tar->skip > 0) { + const size_t n = std::min(tar->skip, data.size() - pos); + const size_t captured = std::min(n, tar->capture_left); + if (captured > 0) { + std::string* target = tar->long_name ? &tar->next_name : &tar->entries.back().head; + target->append(data.substr(pos, captured)); + tar->capture_left -= captured; + } + tar->skip -= n; + pos += n; + if (tar->skip == 0) { + tar->long_name = false; + } + continue; + } + const size_t n = std::min(kTarBlockSize - tar->held.size(), data.size() - pos); + tar->held.append(data.substr(pos, n)); + pos += n; + if (tar->held.size() < kTarBlockSize) { + break; + } + if (!tar->checked) { + tar->checked = true; + tar->is_tar = tar->held.substr(kTarMagicOffset, kTarMagic.size()) == kTarMagic; + if (!tar->is_tar) { + std::string passthrough = absl::StrCat(tar->held, data.substr(pos)); + tar->held.clear(); + return passthrough; + } + } + ParseTarHeader(tar->held, tar); + tar->held.clear(); + } + return ""; +} + +std::string TarManifest(const TarStream& tar) { + std::string manifest; + for (const TarEntryInfo& entry : tar.entries) { + absl::StrAppend(&manifest, absl::Substitute("$0 mode=$1 size=$2 head=\"$3\"\n", entry.name, + absl::StrFormat("%04o", entry.mode), entry.size, + absl::CEscape(entry.head))); + } + return manifest; +} + +std::string DrainStream(TarStream* tar, std::string* buffer) { + std::string out = absl::StrCat(*buffer, tar->is_tar ? TarManifest(*tar) : tar->held); + tar->held.clear(); + return out; +} + +void AppendCapped(std::string* buffer, std::string_view data) { + const size_t room = kMaxBufferedOutput - std::min(kMaxBufferedOutput, buffer->size()); + buffer->append(data.substr(0, room)); +} + Record MakeRecord(RecordKind kind, message_type_t type, uint64_t timestamp_ns, std::string payload) { Record record; @@ -147,11 +285,13 @@ Record MakeRecord(RecordKind kind, message_type_t type, uint64_t timestamp_ns, record.msg.opcode = Opcode::kBinary; record.msg.fragments = 1; record.msg.payload = std::move(payload); + record.payload_size = record.msg.payload.size(); return record; } void TakeOutput(ExecState* state, Record* record) { - record->output = CleanTerminalOutput(state->output, state->tty); + record->output = state->tty ? CleanTerminalOutput(state->output, state->tty) + : DrainStream(&state->stdout_tar, &state->output); record->output_size = state->output_size; state->output.clear(); state->output_size = 0; @@ -159,8 +299,20 @@ void TakeOutput(ExecState* state, Record* record) { void AppendOutput(ExecState* state, std::string_view data) { state->output_size += data.size(); - const size_t room = kMaxBufferedOutput - std::min(kMaxBufferedOutput, state->output.size()); - state->output.append(data.substr(0, room)); + AppendCapped(&state->output, data); +} + +void EmitStdin(ExecState* state, std::vector* records) { + if (state->stdin_size == 0) { + return; + } + Record record = MakeRecord(RecordKind::kInput, message_type_t::kRequest, + state->stdin_timestamp_ns, + DrainStream(&state->stdin_tar, &state->stdin_data)); + record.payload_size = state->stdin_size; + records->push_back(std::move(record)); + state->stdin_data.clear(); + state->stdin_size = 0; } void EmitPending(ExecState* state, std::vector* records) { @@ -290,20 +442,39 @@ void DecodeK8sExec(std::string_view path, std::vector messages, ExecSta const uint8_t channel = msg.payload[0]; std::string_view data = std::string_view(msg.payload).substr(1); if (msg.type == message_type_t::kRequest) { - if (channel == kStdinChannel) { + if (channel != kStdinChannel) { + continue; + } + if (state->tty) { HandleStdin(msg.timestamp_ns, data, state, records); + } else if (!data.empty()) { + if (state->stdin_size == 0) { + state->stdin_timestamp_ns = msg.timestamp_ns; + } + state->stdin_size += data.size(); + AppendCapped(&state->stdin_data, FeedTar(&state->stdin_tar, data)); } continue; } switch (channel) { case kStdoutChannel: + if (state->tty) { + if (state->line.empty()) { + AppendOutput(state, data); + } + } else { + state->output_size += data.size(); + AppendCapped(&state->output, FeedTar(&state->stdout_tar, data)); + } + break; case kStderrChannel: - if (state->line.empty()) { + if (!state->tty || state->line.empty()) { AppendOutput(state, data); } break; case kStatusChannel: { EmitPending(state, records); + EmitStdin(state, records); Record record = MakeRecord(RecordKind::kExit, message_type_t::kResponse, msg.timestamp_ns, std::string(data)); TakeOutput(state, &record); diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h index d6f6781afef..bb5cebb4075 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h @@ -22,6 +22,7 @@ #include #include #include +#include #include "src/common/base/base.h" #include "src/stirling/source_connectors/socket_tracer/protocols/common/event_parser.h" @@ -111,6 +112,25 @@ struct Record { } }; +struct TarEntryInfo { + std::string name; + uint64_t mode = 0; + uint64_t size = 0; + std::string head; +}; + +struct TarStream { + bool checked = false; + bool is_tar = false; + bool done = false; + bool long_name = false; + std::string held; + uint64_t skip = 0; + uint64_t capture_left = 0; + std::string next_name; + std::vector entries; +}; + struct PendingInput { uint64_t timestamp_ns = 0; std::string line; @@ -125,6 +145,11 @@ struct ExecState { std::optional pending; std::string output; size_t output_size = 0; + TarStream stdout_tar; + uint64_t stdin_timestamp_ns = 0; + std::string stdin_data; + size_t stdin_size = 0; + TarStream stdin_tar; }; struct State { diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index c69795a8d87..c366de2ea3a 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -1795,7 +1795,9 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke md::UPID upid(ctx->GetASID(), conn_tracker.conn_id().upid.pid, conn_tracker.conn_id().upid.start_time_ticks); - const size_t payload_size = msg.payload.size(); + const size_t payload_size = record.kind == protocols::websocket::RecordKind::kFrame + ? msg.payload.size() + : record.payload_size; DataTable::RecordBuilder<&kWebSocketTable> r(data_table, msg.timestamp_ns); r.Append(msg.timestamp_ns); r.Append(upid.value()); From c53fc50d9a59616aacfad11b4d4dd4164d421ef2 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 14:49:43 +0100 Subject: [PATCH 20/51] Initialize WebSocket records field by field Signed-off-by: entlein --- .../socket_tracer/protocols/websocket/stitcher.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc index 223cf805c30..7f094c400b5 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc @@ -107,7 +107,9 @@ RecordsWithErrorCount StitchFrames(std::dequepath, std::move(messages), &global->exec, &result.records); } else { for (websocket::Message& msg : messages) { - result.records.push_back({std::move(msg)}); + websocket::Record record; + record.msg = std::move(msg); + result.records.push_back(std::move(record)); } } for (websocket::Record& record : result.records) { From 188a368ad501ef40624cfc4435c58d641839458b Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 13:55:47 +0000 Subject: [PATCH 21/51] format Signed-off-by: entlein --- .../socket_tracer/conn_tracker_test.cc | 3 +- .../socket_tracer/data_stream.cc | 6 +- .../protocols/websocket/k8s_exec.cc | 10 ++-- .../protocols/websocket/k8s_exec_test.cc | 58 ++++++++++++------- .../protocols/websocket/stitcher.cc | 3 +- .../socket_tracer/protocols/websocket/types.h | 4 +- .../socket_trace_connector_test.cc | 3 +- 7 files changed, 49 insertions(+), 38 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc index 175b4cf95ad..d7fdccdcbc4 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc @@ -357,8 +357,7 @@ TEST_F(ConnTrackerTest, TrackerHTTP101Disable) { TEST_F(ConnTrackerTest, TrackerHTTP101UpgradesToWebSocket) { constexpr std::string_view kServerText = "\x81\x02hi"sv; - constexpr std::string_view kClientMaskedText = - "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58"sv; + constexpr std::string_view kClientMaskedText = "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58"sv; constexpr std::string_view kClientPing = "\x89\x00"sv; struct socket_control_event_t conn = event_gen_.InitConn(); diff --git a/src/stirling/source_connectors/socket_tracer/data_stream.cc b/src/stirling/source_connectors/socket_tracer/data_stream.cc index 4bd1e240b83..a1f00a68856 100644 --- a/src/stirling/source_connectors/socket_tracer/data_stream.cc +++ b/src/stirling/source_connectors/socket_tracer/data_stream.cc @@ -219,9 +219,9 @@ template void DataStream::ProcessBytesToFrames< template void DataStream::ProcessBytesToFrames(message_type_t type, protocols::NoState* state); -template void DataStream::ProcessBytesToFrames( +template void +DataStream::ProcessBytesToFrames( message_type_t type, protocols::websocket::StateWrapper* state); void DataStream::Reset() { diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc index 21dc228021c..d8aba56da66 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc @@ -158,9 +158,7 @@ std::string StripEscapeSequences(std::string_view text) { return out; } -std::string_view CString(std::string_view field) { - return field.substr(0, field.find('\0')); -} +std::string_view CString(std::string_view field) { return field.substr(0, field.find('\0')); } uint64_t ParseOctal(std::string_view field) { uint64_t value = 0; @@ -306,9 +304,9 @@ void EmitStdin(ExecState* state, std::vector* records) { if (state->stdin_size == 0) { return; } - Record record = MakeRecord(RecordKind::kInput, message_type_t::kRequest, - state->stdin_timestamp_ns, - DrainStream(&state->stdin_tar, &state->stdin_data)); + Record record = + MakeRecord(RecordKind::kInput, message_type_t::kRequest, state->stdin_timestamp_ns, + DrainStream(&state->stdin_tar, &state->stdin_data)); record.payload_size = state->stdin_size; records->push_back(std::move(record)); state->stdin_data.clear(); diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc index 374efd69aaf..266e9e4ff4a 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc @@ -39,7 +39,8 @@ using ::testing::ElementsAre; using ::testing::Field; using ::testing::IsEmpty; -constexpr std::string_view kKubeletTTYPath = "/exec/ws-demo/ws-demo/ws-demo?command=sh&input=1&output=1&tty=1"; +constexpr std::string_view kKubeletTTYPath = + "/exec/ws-demo/ws-demo/ws-demo?command=sh&input=1&output=1&tty=1"; constexpr std::string_view kStatusSuccess = R"({"metadata":{},"status":"Success"})"; Message Msg(uint64_t timestamp_ns, message_type_t type, std::string_view payload, @@ -123,15 +124,23 @@ TEST(K8sExecTest, TTYSessionBecomesOneRowPerCommand) { Out(9, "\x01/ # "), Msg(10, message_type_t::kRequest, "", Opcode::kPing), Msg(11, message_type_t::kResponse, "", Opcode::kPong), - In(12, "\x00""cat"sv), - Out(13, "\x01""cat"), + In(12, + "\x00" + "cat"sv), + Out(13, + "\x01" + "cat"), In(14, "\x00 /etc/hostname"sv), Out(15, "\x01 /etc/hostname"), In(16, "\x00\r"sv), Out(17, "\x01\r\n"), Out(18, "\x01ws-demo\r\n/ # "), - In(19, "\x00""exi"sv), - Out(20, "\x01""exi"), + In(19, + "\x00" + "exi"sv), + Out(20, + "\x01" + "exi"), In(21, "\x00t"sv), Out(22, "\x01t"), In(23, "\x00\r"sv), @@ -158,9 +167,8 @@ TEST(K8sExecTest, TTYSessionBecomesOneRowPerCommand) { TEST(K8sExecTest, LineEditingIsApplied) { std::vector messages = { - In(1, "\x00lx"sv), In(2, "\x00\x7f"sv), In(3, "\x00s\r"sv), Out(4, "\x01\r\nbin\r\n/ # "), - In(5, "\x00junk"sv), In(6, "\x00\x15"sv), In(7, "\x00pwd\r"sv), - Out(8, "\x01\r\n/\r\n/ # "), + In(1, "\x00lx"sv), In(2, "\x00\x7f"sv), In(3, "\x00s\r"sv), Out(4, "\x01\r\nbin\r\n/ # "), + In(5, "\x00junk"sv), In(6, "\x00\x15"sv), In(7, "\x00pwd\r"sv), Out(8, "\x01\r\n/\r\n/ # "), }; ExecState state; std::vector records; @@ -174,7 +182,9 @@ TEST(K8sExecTest, LineEditingIsApplied) { TEST(K8sExecTest, AbandonedLineIsKept) { std::vector messages = { - In(1, "\x00""cat /etc/shadow"sv), + In(1, + "\x00" + "cat /etc/shadow"sv), In(2, "\x00\x03"sv), Out(3, "\x01^C\r\n/ # "), In(4, "\x00\x04"sv), @@ -220,8 +230,12 @@ TEST(K8sExecTest, SessionContinuesAcrossCalls) { std::vector records; DecodeK8sExec(kKubeletTTYPath, {Out(1, "\x01/ # "), In(2, "\x00i"sv)}, &state, &records); - DecodeK8sExec(kKubeletTTYPath, {In(3, "\x00""d\r"sv), Out(4, "\x01\r\nuid=0\r\n/ # ")}, &state, - &records); + DecodeK8sExec(kKubeletTTYPath, + {In(3, + "\x00" + "d\r"sv), + Out(4, "\x01\r\nuid=0\r\n/ # ")}, + &state, &records); DecodeK8sExec(kKubeletTTYPath, {Out(5, absl::StrCat("\x03", kStatusSuccess))}, &state, &records); EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "sh", ""), @@ -307,9 +321,9 @@ TEST(K8sExecTest, TarLongNameIsResolved) { ExecState state; std::vector records; - DecodeK8sExec(kPath, - {Out(1, absl::StrCat("\x01", archive)), Out(2, absl::StrCat("\x03", kStatusSuccess))}, - &state, &records); + DecodeK8sExec( + kPath, {Out(1, absl::StrCat("\x01", archive)), Out(2, absl::StrCat("\x03", kStatusSuccess))}, + &state, &records); ASSERT_EQ(records.size(), 2U); EXPECT_EQ(records[1].output, absl::StrCat(long_name, " mode=0600 size=1 head=\"v\"\n")); @@ -341,16 +355,16 @@ TEST(K8sExecTest, TarOnStdinBecomesManifest) { std::vector records; DecodeK8sExec(kPath, - {In(1, absl::StrCat(std::string(1, '\0'), archive)), - In(2, "\xff\x00"sv), Out(3, absl::StrCat("\x03", kStatusSuccess))}, + {In(1, absl::StrCat(std::string(1, '\0'), archive)), In(2, "\xff\x00"sv), + Out(3, absl::StrCat("\x03", kStatusSuccess))}, &state, &records); - EXPECT_THAT(records, - ElementsAre(IsRecord(RecordKind::kExec, "tar xmf - -C /tmp", ""), - IsRecord(RecordKind::kInput, - "payload.sh mode=0755 size=18 head=\"#!/bin/sh\\necho hi\\n\"\n", - ""), - IsRecord(RecordKind::kExit, kStatusSuccess, ""))); + EXPECT_THAT( + records, + ElementsAre(IsRecord(RecordKind::kExec, "tar xmf - -C /tmp", ""), + IsRecord(RecordKind::kInput, + "payload.sh mode=0755 size=18 head=\"#!/bin/sh\\necho hi\\n\"\n", ""), + IsRecord(RecordKind::kExit, kStatusSuccess, ""))); EXPECT_EQ(records[1].payload_size, archive.size()); } diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc index 7f094c400b5..3212b3d0a20 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc @@ -92,8 +92,7 @@ RecordsWithErrorCount StitchFrames(std::deque result; std::vector messages; - result.error_count += - websocket::StitchDirection(message_type_t::kRequest, req_frames, &messages); + result.error_count += websocket::StitchDirection(message_type_t::kRequest, req_frames, &messages); result.error_count += websocket::StitchDirection(message_type_t::kResponse, resp_frames, &messages); diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h index bb5cebb4075..65e69964a26 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h @@ -107,8 +107,8 @@ struct Record { size_t output_size = 0; std::string ToString() const { - return absl::Substitute("[kind=$0 subprotocol=$1 msg=$2 output_size=$3]", - RecordKindName(kind), subprotocol, msg.ToString(), output_size); + return absl::Substitute("[kind=$0 subprotocol=$1 msg=$2 output_size=$3]", RecordKindName(kind), + subprotocol, msg.ToString(), output_size); } }; diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc index 5861b08463d..83762928f92 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc @@ -314,7 +314,8 @@ TEST_F(SocketTraceConnectorWebSocketTest, K8sExecSessionProducesCommandRows) { constexpr std::string_view kStdinEnter = "\x82\x02\x00\r"sv; constexpr std::string_view kStdout = "\x82\x0e\x01\r\nuid=0\r\n/ # "sv; constexpr std::string_view kStatus = - "\x82\x23\x03" R"({"metadata":{},"status":"Success"})"sv; + "\x82\x23\x03" + R"({"metadata":{},"status":"Success"})"sv; struct socket_control_event_t conn = event_gen_.InitConn(); source_->AcceptControlEvent(conn); From a65d8a2559c69b5618e09fc4bafc3e6787db1fe8 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 17:08:55 +0100 Subject: [PATCH 22/51] Test bounded WebSocket payloads, resync and exec input redaction Signed-off-by: entlein --- .../protocols/websocket/k8s_exec_test.cc | 167 ++++++++++++++++-- .../protocols/websocket/parse_test.cc | 115 +++++++++++- .../protocols/websocket/stitcher_test.cc | 44 ++++- .../socket_trace_connector_test.cc | 43 +++++ 4 files changed, 350 insertions(+), 19 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc index 266e9e4ff4a..5b40595191a 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -51,6 +52,7 @@ Message Msg(uint64_t timestamp_ns, message_type_t type, std::string_view payload msg.opcode = opcode; msg.fragments = 1; msg.payload = std::string(payload); + msg.payload_size = msg.payload.size(); return msg; } @@ -167,8 +169,11 @@ TEST(K8sExecTest, TTYSessionBecomesOneRowPerCommand) { TEST(K8sExecTest, LineEditingIsApplied) { std::vector messages = { - In(1, "\x00lx"sv), In(2, "\x00\x7f"sv), In(3, "\x00s\r"sv), Out(4, "\x01\r\nbin\r\n/ # "), - In(5, "\x00junk"sv), In(6, "\x00\x15"sv), In(7, "\x00pwd\r"sv), Out(8, "\x01\r\n/\r\n/ # "), + In(1, "\x00lx"sv), Out(2, "\x01lx"), In(3, "\x00\x7f"sv), + Out(4, "\x01\b \b"), In(5, "\x00s"sv), Out(6, "\x01s"), + In(7, "\x00\r"sv), Out(8, "\x01\r\nbin\r\n/ # "), In(9, "\x00junk"sv), + Out(10, "\x01junk"), In(11, "\x00\x15"sv), In(12, "\x00pwd\r"sv), + Out(13, "\x01\r\n/\r\n/ # "), }; ExecState state; std::vector records; @@ -184,11 +189,14 @@ TEST(K8sExecTest, AbandonedLineIsKept) { std::vector messages = { In(1, "\x00" - "cat /etc/shadow"sv), - In(2, "\x00\x03"sv), - Out(3, "\x01^C\r\n/ # "), - In(4, "\x00\x04"sv), - Out(5, absl::StrCat("\x03", kStatusSuccess)), + "cat /etc/hosts"sv), + Out(2, + "\x01" + "cat /etc/hosts"), + In(3, "\x00\x03"sv), + Out(4, "\x01^C\r\n/ # "), + In(5, "\x00\x04"sv), + Out(6, absl::StrCat("\x03", kStatusSuccess)), }; ExecState state; std::vector records; @@ -196,7 +204,7 @@ TEST(K8sExecTest, AbandonedLineIsKept) { DecodeK8sExec(kKubeletTTYPath, std::move(messages), &state, &records); EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "sh", ""), - IsRecord(RecordKind::kInput, "cat /etc/shadow^C", "^C\n"), + IsRecord(RecordKind::kInput, "cat /etc/hosts^C", "^C\n"), IsRecord(RecordKind::kInput, "^D", ""), IsRecord(RecordKind::kExit, kStatusSuccess, ""))); } @@ -229,14 +237,15 @@ TEST(K8sExecTest, SessionContinuesAcrossCalls) { ExecState state; std::vector records; - DecodeK8sExec(kKubeletTTYPath, {Out(1, "\x01/ # "), In(2, "\x00i"sv)}, &state, &records); + DecodeK8sExec(kKubeletTTYPath, {Out(1, "\x01/ # "), In(2, "\x00i"sv), Out(3, "\x01i")}, &state, + &records); DecodeK8sExec(kKubeletTTYPath, - {In(3, + {In(4, "\x00" "d\r"sv), - Out(4, "\x01\r\nuid=0\r\n/ # ")}, + Out(5, "\x01\r\nuid=0\r\n/ # ")}, &state, &records); - DecodeK8sExec(kKubeletTTYPath, {Out(5, absl::StrCat("\x03", kStatusSuccess))}, &state, &records); + DecodeK8sExec(kKubeletTTYPath, {Out(6, absl::StrCat("\x03", kStatusSuccess))}, &state, &records); EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "sh", ""), IsRecord(RecordKind::kInput, "id", "uid=0\n"), @@ -291,7 +300,7 @@ TEST(K8sExecTest, TarFromStdoutBecomesManifest) { "stdout=true"; const std::string archive = TarArchive({TarEntry("etc/passwd", 0644, "root:x:0:0:root:/root:/bin/sh\n"), - TarEntry("etc/shadow", 0640, std::string(700, 'x'))}); + TarEntry("etc/group", 0640, std::string(700, 'x'))}); std::vector messages = {Out(1, "\x01")}; for (size_t pos = 0; pos < archive.size(); pos += 300) { messages.push_back(Out(2 + pos, absl::StrCat("\x01", archive.substr(pos, 300)))); @@ -306,7 +315,7 @@ TEST(K8sExecTest, TarFromStdoutBecomesManifest) { EXPECT_EQ(records[1].kind, RecordKind::kExit); EXPECT_EQ(records[1].output, absl::StrCat("etc/passwd mode=0644 size=30 head=\"root:x:0:0:root:/root:/bin/sh\\n\"\n", - "etc/shadow mode=0640 size=700 head=\"", std::string(64, 'x'), "\"\n")); + "etc/group mode=0640 size=700 head=\"", std::string(64, 'x'), "\"\n")); EXPECT_EQ(records[1].output_size, archive.size()); } @@ -343,7 +352,7 @@ TEST(K8sExecTest, NonTTYStdinIsOneInputRow) { IsRecord(RecordKind::kInput, "id\nhostname\n", ""), IsRecord(RecordKind::kExit, kStatusSuccess, "uid=0\npod\n"))); EXPECT_EQ(records[1].msg.timestamp_ns, 1U); - EXPECT_EQ(records[1].payload_size, 12U); + EXPECT_EQ(records[1].msg.payload_size, 12U); } TEST(K8sExecTest, TarOnStdinBecomesManifest) { @@ -365,7 +374,133 @@ TEST(K8sExecTest, TarOnStdinBecomesManifest) { IsRecord(RecordKind::kInput, "payload.sh mode=0755 size=18 head=\"#!/bin/sh\\necho hi\\n\"\n", ""), IsRecord(RecordKind::kExit, kStatusSuccess, ""))); - EXPECT_EQ(records[1].payload_size, archive.size()); + EXPECT_EQ(records[1].msg.payload_size, archive.size()); +} + +TEST(K8sExecTest, EchoOffInputIsRedacted) { + std::vector messages = { + Out(1, "\x01/ # "), + In(2, "\x00su"sv), + Out(3, "\x01su"), + In(4, "\x00\r"sv), + Out(5, "\x01\r\nPassword: "), + In(6, "\x00hunter2"sv), + In(7, "\x00\r"sv), + Out(8, "\x01\r\n/ # "), + Out(9, absl::StrCat("\x03", kStatusSuccess)), + }; + ExecState state; + std::vector records; + + DecodeK8sExec(kKubeletTTYPath, std::move(messages), &state, &records); + + EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "sh", ""), + IsRecord(RecordKind::kInput, "su", ""), + IsRecord(RecordKind::kInput, "", ""), + IsRecord(RecordKind::kExit, kStatusSuccess, ""))); +} + +TEST(K8sExecTest, PastedLineKeepsCommandAndDropsEcho) { + std::vector messages = { + Out(1, "\x01/ # "), + In(2, "\x00ls\r"sv), + Out(3, "\x01ls\r\nbin\r\n/ # "), + Out(4, absl::StrCat("\x03", kStatusSuccess)), + }; + ExecState state; + std::vector records; + + DecodeK8sExec(kKubeletTTYPath, std::move(messages), &state, &records); + + EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "sh", ""), + IsRecord(RecordKind::kInput, "ls", "bin\n"), + IsRecord(RecordKind::kExit, kStatusSuccess, ""))); +} + +TEST(K8sExecTest, InputLineIsBounded) { + const std::string typed(10000, 'a'); + ExecState state; + std::vector records; + + DecodeK8sExec(kKubeletTTYPath, + {In(1, absl::StrCat(std::string(1, '\0'), typed)), Out(2, "\x01" "aaaa"), + In(3, "\x00\r"sv), Out(4, absl::StrCat("\x03", kStatusSuccess))}, + &state, &records); + + ASSERT_EQ(records.size(), 3U); + EXPECT_EQ(records[1].kind, RecordKind::kInput); + EXPECT_EQ(records[1].msg.payload, std::string(4096, 'a')); +} + +std::string TarTwoFiles() { + return TarArchive( + {TarEntry("big.bin", 0644, std::string(5000, 'b')), TarEntry("small.txt", 0600, "hi")}); +} + +constexpr std::string_view kTarStdoutPath = + "/api/v1/namespaces/ns/pods/pod/exec?command=tar&command=cf&command=-&command=%2Fdata&" + "stdout=true"; + +Message TruncatedOut(uint64_t timestamp_ns, std::string_view data, size_t kept) { + Message msg = Out(timestamp_ns, absl::StrCat("\x01", data.substr(0, kept))); + msg.payload_size = 1 + data.size(); + return msg; +} + +TEST(K8sExecTest, TruncatedTarContentKeepsManifest) { + const std::string archive = TarTwoFiles(); + constexpr size_t kFirstMessage = 512 + 5120; + ExecState state; + std::vector records; + + DecodeK8sExec(kTarStdoutPath, + {TruncatedOut(1, archive.substr(0, kFirstMessage), 612), + Out(2, absl::StrCat("\x01", archive.substr(kFirstMessage))), + Out(3, absl::StrCat("\x03", kStatusSuccess))}, + &state, &records); + + ASSERT_EQ(records.size(), 2U); + EXPECT_EQ(records[1].output, + absl::StrCat("big.bin mode=0644 size=5000 head=\"", std::string(64, 'b'), "\"\n", + "small.txt mode=0600 size=2 head=\"hi\"\n")); + EXPECT_EQ(records[1].output_size, archive.size()); +} + +TEST(K8sExecTest, TarLossAcrossHeaderIsMarked) { + const std::string archive = TarTwoFiles(); + constexpr size_t kFirstMessage = 512 + 5120 + 100; + ExecState state; + std::vector records; + + DecodeK8sExec(kTarStdoutPath, + {TruncatedOut(1, archive.substr(0, kFirstMessage), 612), + Out(2, absl::StrCat("\x01", archive.substr(kFirstMessage))), + Out(3, absl::StrCat("\x03", kStatusSuccess))}, + &state, &records); + + ASSERT_EQ(records.size(), 2U); + EXPECT_EQ(records[1].output, + absl::StrCat("big.bin mode=0644 size=5000 head=\"", std::string(64, 'b'), "\"\n", + "[TRUNCATED]\n")); +} + +TEST(K8sExecTest, TarManifestIsBounded) { + std::vector entries; + for (int i = 0; i < 200; ++i) { + entries.push_back(TarEntry(absl::StrCat("dir/", std::string(90, 'f'), i), 0644, "x")); + } + const std::string archive = TarArchive(entries); + ExecState state; + std::vector records; + + DecodeK8sExec(kTarStdoutPath, + {Out(1, absl::StrCat("\x01", archive)), Out(2, absl::StrCat("\x03", kStatusSuccess))}, + &state, &records); + + ASSERT_EQ(records.size(), 2U); + EXPECT_LE(records[1].output.size(), 4096U); + EXPECT_TRUE(absl::StartsWith(records[1].output, absl::StrCat("dir/", std::string(90, 'f'), "0"))); + EXPECT_EQ(records[1].output_size, archive.size()); } } // namespace websocket diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc index 1ba4b812691..afdaf348bb5 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc @@ -138,7 +138,7 @@ TEST_F(WebSocketParseTest, ExtendedPayloadLengths) { std::string_view buf64 = frame64; ASSERT_EQ(Parse(&buf64), ParseState::kSuccess); EXPECT_EQ(frame_.payload_length, 65536U); - EXPECT_EQ(frame_.payload.size(), 65536U); + EXPECT_EQ(frame_.payload.size(), FLAGS_websocket_payload_limit_bytes); EXPECT_TRUE(buf64.empty()); } @@ -166,6 +166,9 @@ TEST_F(WebSocketParseTest, IncompleteFramesNeedMoreData) { std::string frame64 = Frame64(65536); std::string_view header_only(frame64.data(), 6); EXPECT_EQ(Parse(&header_only), ParseState::kNeedsMoreData); + + std::string_view below_limit(frame64.data(), 10 + FLAGS_websocket_payload_limit_bytes - 1); + EXPECT_EQ(Parse(&below_limit), ParseState::kNeedsMoreData); } TEST_F(WebSocketParseTest, InvalidFrames) { @@ -183,6 +186,116 @@ TEST_F(WebSocketParseTest, InvalidFrames) { EXPECT_EQ(Parse(&msb_view), ParseState::kInvalid); } +TEST_F(WebSocketParseTest, ReservedRsvBitsAreInvalid) { + std::string rsv2 = {'\xa1', '\x00'}; + std::string_view rsv2_view = rsv2; + EXPECT_EQ(Parse(&rsv2_view), ParseState::kInvalid); + + std::string rsv3 = {'\x91', '\x00'}; + std::string_view rsv3_view = rsv3; + EXPECT_EQ(Parse(&rsv3_view), ParseState::kInvalid); +} + +TEST_F(WebSocketParseTest, PayloadIsCappedAtLimit) { + PX_SET_FOR_SCOPE(FLAGS_websocket_payload_limit_bytes, 16); + std::string frame = Frame16(300); + frame[4] = 'a'; + std::string_view buf = frame; + + ASSERT_EQ(Parse(&buf), ParseState::kSuccess); + EXPECT_EQ(frame_.payload_length, 300U); + EXPECT_EQ(frame_.payload, "a" + std::string(15, 'x')); + EXPECT_LT(frame_.ByteSize(), sizeof(Frame) + 300); + EXPECT_TRUE(buf.empty()); +} + +TEST_F(WebSocketParseTest, MaskedPayloadPrefixIsUnmasked) { + PX_SET_FOR_SCOPE(FLAGS_websocket_payload_limit_bytes, 3); + std::string_view buf = CreateCharArrayView(kMaskedText); + + ASSERT_EQ(Parse(&buf), ParseState::kSuccess); + EXPECT_EQ(frame_.payload_length, 5U); + EXPECT_EQ(frame_.payload, "Hel"); + EXPECT_TRUE(buf.empty()); +} + +TEST_F(WebSocketParseTest, LargeFrameIsEmittedBeforeItIsFullyBuffered) { + PX_SET_FOR_SCOPE(FLAGS_websocket_payload_limit_bytes, 16); + std::string data = Frame64(65536) + Bytes(kUnmaskedPing); + constexpr size_t kHeaderSize = 10; + constexpr size_t kFirstChunk = 1000; + std::string_view first(data.data(), kFirstChunk); + + ASSERT_EQ(Parse(&first), ParseState::kSuccess); + EXPECT_EQ(frame_.payload_length, 65536U); + EXPECT_EQ(frame_.payload, std::string(16, 'x')); + EXPECT_TRUE(first.empty()); + + std::string_view middle(data.data() + kFirstChunk, 30000); + EXPECT_EQ(Parse(&middle), ParseState::kIgnored); + EXPECT_TRUE(middle.empty()); + + std::string_view rest(data.data() + kFirstChunk + 30000, data.size() - kFirstChunk - 30000); + EXPECT_EQ(Parse(&rest), ParseState::kIgnored); + EXPECT_EQ(rest.size(), sizeof(kUnmaskedPing)); + ASSERT_EQ(Parse(&rest), ParseState::kSuccess); + EXPECT_EQ(frame_.opcode, Opcode::kPing); + EXPECT_TRUE(rest.empty()); + EXPECT_EQ(data.size(), kHeaderSize + 65536 + sizeof(kUnmaskedPing)); +} + +TEST_F(WebSocketParseTest, DirectionsSkipIndependently) { + PX_SET_FOR_SCOPE(FLAGS_websocket_payload_limit_bytes, 16); + std::string big = Frame16(300); + std::string_view req(big.data(), 100); + ASSERT_EQ(ParseFrame(message_type_t::kRequest, &req, &frame_, &state_), ParseState::kSuccess); + + std::string_view resp = CreateCharArrayView(kUnmaskedText); + ASSERT_EQ(ParseFrame(message_type_t::kResponse, &resp, &frame_, &state_), ParseState::kSuccess); + EXPECT_EQ(frame_.payload, "Hello"); +} + +TEST_F(WebSocketParseTest, FindFrameBoundarySkipsGarbage) { + std::string data = "xxxx" + Bytes(kMaskedText) + Bytes(kMaskedPong); + EXPECT_EQ(FindFrameBoundary(message_type_t::kRequest, data, 1, &state_), 4U); +} + +TEST_F(WebSocketParseTest, FindFrameBoundaryRequiresDirectionalMasking) { + std::string data = Bytes(kMaskedText) + Bytes(kUnmaskedText) + Bytes(kUnmaskedPing); + EXPECT_EQ(FindFrameBoundary(message_type_t::kResponse, data, 1, &state_), + sizeof(kMaskedText)); + EXPECT_EQ(FindFrameBoundary(message_type_t::kRequest, data, 1, &state_), + std::string_view::npos); +} + +TEST_F(WebSocketParseTest, FindFrameBoundaryWithoutFrameIsNpos) { + EXPECT_EQ(FindFrameBoundary(message_type_t::kRequest, "xxxx", 0, &state_), + std::string_view::npos); +} + +TEST_F(WebSocketParseTest, ResyncDropsPendingSkip) { + PX_SET_FOR_SCOPE(FLAGS_websocket_payload_limit_bytes, 16); + std::string big = Frame16(300); + std::string_view head(big.data(), 100); + ASSERT_EQ(Parse(&head), ParseState::kSuccess); + + std::string data = "xxxx" + Bytes(kMaskedText); + ASSERT_EQ(FindFrameBoundary(message_type_t::kRequest, data, 1, &state_), 4U); + std::string_view next = std::string_view(data).substr(4); + ASSERT_EQ(Parse(&next), ParseState::kSuccess); + EXPECT_EQ(frame_.payload, "Hello"); +} + +TEST_F(WebSocketParseTest, K8sChannelProtocolKeepsLargerPayloads) { + PX_SET_FOR_SCOPE(FLAGS_websocket_payload_limit_bytes, 16); + state_.global.subprotocol = "v5.channel.k8s.io"; + std::string frame = Frame16(4000); + std::string_view buf = frame; + + ASSERT_EQ(Parse(&buf), ParseState::kSuccess); + EXPECT_EQ(frame_.payload.size(), 4000U); +} + } // namespace websocket } // namespace protocols } // namespace stirling diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc index 92fb8c3a8bd..043f48cbc59 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc @@ -23,6 +23,7 @@ #include #include "src/common/testing/testing.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h" namespace px { namespace stirling { @@ -73,7 +74,7 @@ TEST_F(WebSocketStitcherTest, OneRecordPerMessageInEachDirection) { } TEST_F(WebSocketStitcherTest, FragmentsAreReassembled) { - req_frames_.push_back(MakeFrame(Opcode::kText, false, "Hel", 1, 0x4)); + req_frames_.push_back(MakeFrame(Opcode::kText, false, "Hel", 1)); req_frames_.push_back(MakeFrame(Opcode::kContinuation, true, "lo", 3)); RecordsWithErrorCount result = Stitch(); @@ -81,12 +82,51 @@ TEST_F(WebSocketStitcherTest, FragmentsAreReassembled) { ASSERT_EQ(result.records.size(), 1U); EXPECT_EQ(result.records[0].msg.opcode, Opcode::kText); EXPECT_EQ(result.records[0].msg.payload, "Hello"); + EXPECT_EQ(result.records[0].msg.payload_size, 5U); EXPECT_EQ(result.records[0].msg.timestamp_ns, 1U); EXPECT_EQ(result.records[0].msg.fragments, 2U); - EXPECT_TRUE(result.records[0].msg.compressed); + EXPECT_FALSE(result.records[0].msg.compressed); EXPECT_TRUE(req_frames_.empty()); } +TEST_F(WebSocketStitcherTest, CompressedPayloadIsRemoved) { + req_frames_.push_back(MakeFrame(Opcode::kText, false, "\xf2\x48", 1, 0x4)); + req_frames_.push_back(MakeFrame(Opcode::kContinuation, true, "\xcd", 3)); + + RecordsWithErrorCount result = Stitch(); + + ASSERT_EQ(result.records.size(), 1U); + EXPECT_TRUE(result.records[0].msg.compressed); + EXPECT_EQ(result.records[0].msg.payload, ""); + EXPECT_EQ(result.records[0].msg.payload_size, 3U); +} + +TEST_F(WebSocketStitcherTest, TruncatedFrameKeepsItsPayloadSize) { + Frame frame = MakeFrame(Opcode::kBinary, true, "abc", 1); + frame.payload_length = 1000; + resp_frames_.push_back(std::move(frame)); + + RecordsWithErrorCount result = Stitch(); + + ASSERT_EQ(result.records.size(), 1U); + EXPECT_EQ(result.records[0].msg.payload, "abc"); + EXPECT_EQ(result.records[0].msg.payload_size, 1000U); +} + +TEST_F(WebSocketStitcherTest, ReassembledPayloadIsCappedAtLimit) { + PX_SET_FOR_SCOPE(FLAGS_websocket_payload_limit_bytes, 4); + req_frames_.push_back(MakeFrame(Opcode::kText, false, "Hel", 1)); + req_frames_.push_back(MakeFrame(Opcode::kContinuation, false, "lo", 2)); + req_frames_.push_back(MakeFrame(Opcode::kContinuation, true, "!!", 3)); + + RecordsWithErrorCount result = Stitch(); + + ASSERT_EQ(result.records.size(), 1U); + EXPECT_EQ(result.records[0].msg.payload, "Hell"); + EXPECT_EQ(result.records[0].msg.payload_size, 7U); + EXPECT_EQ(result.records[0].msg.fragments, 3U); +} + TEST_F(WebSocketStitcherTest, ControlFrameBetweenFragments) { req_frames_.push_back(MakeFrame(Opcode::kText, false, "Hel", 1)); req_frames_.push_back(MakeFrame(Opcode::kPing, true, "p", 2)); diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc index 83762928f92..cc1e7571313 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -234,6 +235,20 @@ class SocketTraceConnectorWebSocketTest : public SocketTraceConnectorTest { void TearDown() override { FLAGS_stirling_enable_websocket_tracing = TraceMode::Off; } + RecordBatch TransferUpgradedServerFrames(std::string_view frames) { + source_->AcceptControlEvent(event_gen_.InitConn()); + source_->AcceptDataEvent(event_gen_.InitSendEvent(testing::kHTTPUpgradeReq)); + source_->AcceptDataEvent(event_gen_.InitRecvEvent( + absl::StrCat(testing::kHTTPUpgradeResp, frames))); + connector_->TransferData(ctx_.get()); + connector_->TransferData(ctx_.get()); + std::vector tablets = websocket_table_->ConsumeRecords(); + if (tablets.empty()) { + return {}; + } + return tablets[0].records; + } + DataTable* websocket_table_ = data_tables_[SocketTraceConnector::kWebSocketTableNum]; }; @@ -311,6 +326,7 @@ TEST_F(SocketTraceConnectorWebSocketTest, K8sExecSessionProducesCommandRows) { "\r\n"; constexpr std::string_view kPrompt = "\x82\x05\x01/ # "sv; constexpr std::string_view kStdinId = "\x82\x03\x00id"sv; + constexpr std::string_view kEchoId = "\x82\x03\x01id"sv; constexpr std::string_view kStdinEnter = "\x82\x02\x00\r"sv; constexpr std::string_view kStdout = "\x82\x0e\x01\r\nuid=0\r\n/ # "sv; constexpr std::string_view kStatus = @@ -324,6 +340,7 @@ TEST_F(SocketTraceConnectorWebSocketTest, K8sExecSessionProducesCommandRows) { event_gen_.InitRecvEvent(absl::StrCat(kExecResp, kPrompt))); connector_->TransferData(ctx_.get()); source_->AcceptDataEvent(event_gen_.InitSendEvent(kStdinId)); + source_->AcceptDataEvent(event_gen_.InitRecvEvent(kEchoId)); source_->AcceptDataEvent(event_gen_.InitSendEvent(kStdinEnter)); source_->AcceptDataEvent(event_gen_.InitRecvEvent(kStdout)); source_->AcceptDataEvent(event_gen_.InitRecvEvent(kStatus)); @@ -340,6 +357,32 @@ TEST_F(SocketTraceConnectorWebSocketTest, K8sExecSessionProducesCommandRows) { EXPECT_THAT(ToStringVector(records[kWebSocketOutputIdx]), ElementsAre("", "uid=0\n", "")); } +TEST_F(SocketTraceConnectorWebSocketTest, LargeBinaryPayloadIsTruncatedBeforeEscaping) { + std::string frame = {'\x82', '\x7e', '\x0f', '\xa0'}; + frame.append(4000, '\x01'); + + RecordBatch records = TransferUpgradedServerFrames(frame); + + ASSERT_THAT(records, RecordBatchSizeIs(1)); + std::string payload = records[kWebSocketPayloadIdx]->Get(0); + EXPECT_TRUE(absl::StartsWith(payload, "\\x01\\x01")); + EXPECT_TRUE(absl::EndsWith(payload, DataTable::kTruncatedMsg)); + EXPECT_LE(payload.size(), FLAGS_max_body_bytes + strlen(DataTable::kTruncatedMsg)); + EXPECT_THAT(ToIntVector(records[kWebSocketPayloadSizeIdx]), + ElementsAre(4000)); +} + +TEST_F(SocketTraceConnectorWebSocketTest, CompressedPayloadIsRemoved) { + using std::string_view_literals::operator""sv; + constexpr std::string_view kCompressedText = "\xc1\x07\xf2\x48\xcd\xc9\xc9\x07\x00"sv; + + RecordBatch records = TransferUpgradedServerFrames(kCompressedText); + + ASSERT_THAT(records, RecordBatchSizeIs(1)); + EXPECT_THAT(ToStringVector(records[kWebSocketPayloadIdx]), ElementsAre("")); + EXPECT_THAT(ToIntVector(records[kWebSocketPayloadSizeIdx]), ElementsAre(7)); +} + TEST_F(SocketTraceConnectorTest, HTTPDelayedRespBody) { struct socket_control_event_t conn = event_gen_.InitConn(); std::unique_ptr event0_req = event_gen_.InitSendEvent(kReq4); From c64f1e9dae21b3fbec72a948f4395fe0b9451b0a Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 17:11:20 +0100 Subject: [PATCH 23/51] Bound WebSocket payload capture and redact unechoed exec input Signed-off-by: entlein --- .../protocols/websocket/k8s_exec.cc | 144 ++++++++++----- .../protocols/websocket/k8s_exec.h | 2 + .../protocols/websocket/parse.cc | 171 ++++++++++++++---- .../socket_tracer/protocols/websocket/parse.h | 8 + .../protocols/websocket/stitcher.cc | 21 ++- .../socket_tracer/protocols/websocket/types.h | 20 +- .../socket_tracer/socket_trace_connector.cc | 20 +- 7 files changed, 283 insertions(+), 103 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc index d8aba56da66..d0d2b5163d9 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc @@ -52,8 +52,9 @@ constexpr char kDelete = '\x7f'; constexpr char kCtrlC = '\x03'; constexpr char kCtrlD = '\x04'; constexpr char kCtrlU = '\x15'; +constexpr std::string_view kNoEchoPlaceholder = ""; +constexpr std::string_view kTarTruncatedLine = "[TRUNCATED]\n"; constexpr size_t kTarBlockSize = 512; -constexpr size_t kTarMaxEntries = 1024; constexpr size_t kTarHeadSize = 64; constexpr size_t kTarMaxLongName = 4096; constexpr std::string_view kTarMagic = "ustar"; @@ -158,6 +159,11 @@ std::string StripEscapeSequences(std::string_view text) { return out; } +void AppendCapped(std::string* buffer, std::string_view data) { + const size_t room = kMaxBufferedOutput - std::min(kMaxBufferedOutput, buffer->size()); + buffer->append(data.substr(0, room)); +} + std::string_view CString(std::string_view field) { return field.substr(0, field.find('\0')); } uint64_t ParseOctal(std::string_view field) { @@ -176,6 +182,18 @@ uint64_t RoundUpToBlock(uint64_t size) { return (size + kTarBlockSize - 1) / kTarBlockSize * kTarBlockSize; } +void FlushTarEntry(TarStream* tar) { + if (!tar->entry.has_value()) { + return; + } + const TarEntryInfo& entry = tar->entry.value(); + AppendCapped(&tar->manifest, + absl::Substitute("$0 mode=$1 size=$2 head=\"$3\"\n", entry.name, + absl::StrFormat("%04o", entry.mode), entry.size, + absl::CEscape(entry.head))); + tar->entry.reset(); +} + void ParseTarHeader(std::string_view header, TarStream* tar) { if (std::all_of(header.begin(), header.end(), [](char c) { return c == '\0'; }) || header.substr(kTarMagicOffset, kTarMagic.size()) != kTarMagic) { @@ -203,17 +221,48 @@ void ParseTarHeader(std::string_view header, TarStream* tar) { } else if (!prefix.empty()) { name = absl::StrCat(prefix, "/", name); } - if (tar->entries.size() >= kTarMaxEntries) { + if (tar->manifest.size() >= kMaxBufferedOutput) { return; } - tar->entries.push_back( - {std::move(name), ParseOctal(header.substr(kTarModeOffset, kTarModeSize)), size, ""}); + tar->entry = + TarEntryInfo{std::move(name), ParseOctal(header.substr(kTarModeOffset, kTarModeSize)), size, + ""}; tar->capture_left = std::min(size, kTarHeadSize); + if (tar->capture_left == 0) { + FlushTarEntry(tar); + } +} + +void LoseTarBytes(TarStream* tar, uint64_t lost, std::string* out) { + if (lost == 0 || tar->done || (tar->checked && !tar->is_tar)) { + return; + } + if (!tar->checked) { + tar->checked = true; + AppendCapped(out, tar->held); + tar->held.clear(); + return; + } + if (!tar->held.empty() || tar->skip < lost) { + FlushTarEntry(tar); + tar->done = true; + tar->truncated = true; + return; + } + tar->skip -= lost; + if (tar->capture_left > 0) { + tar->capture_left = 0; + FlushTarEntry(tar); + } + if (tar->skip == 0) { + tar->long_name = false; + } } -std::string FeedTar(TarStream* tar, std::string_view data) { +void FeedTar(TarStream* tar, std::string_view data, uint64_t lost, std::string* out) { if (tar->checked && !tar->is_tar) { - return std::string(data); + AppendCapped(out, data); + return; } size_t pos = 0; while (pos < data.size() && !tar->done) { @@ -221,9 +270,12 @@ std::string FeedTar(TarStream* tar, std::string_view data) { const size_t n = std::min(tar->skip, data.size() - pos); const size_t captured = std::min(n, tar->capture_left); if (captured > 0) { - std::string* target = tar->long_name ? &tar->next_name : &tar->entries.back().head; + std::string* target = tar->long_name ? &tar->next_name : &tar->entry->head; target->append(data.substr(pos, captured)); tar->capture_left -= captured; + if (tar->capture_left == 0 && !tar->long_name) { + FlushTarEntry(tar); + } } tar->skip -= n; pos += n; @@ -242,38 +294,34 @@ std::string FeedTar(TarStream* tar, std::string_view data) { tar->checked = true; tar->is_tar = tar->held.substr(kTarMagicOffset, kTarMagic.size()) == kTarMagic; if (!tar->is_tar) { - std::string passthrough = absl::StrCat(tar->held, data.substr(pos)); + AppendCapped(out, tar->held); + AppendCapped(out, data.substr(pos)); tar->held.clear(); - return passthrough; + return; } } ParseTarHeader(tar->held, tar); tar->held.clear(); } - return ""; -} - -std::string TarManifest(const TarStream& tar) { - std::string manifest; - for (const TarEntryInfo& entry : tar.entries) { - absl::StrAppend(&manifest, absl::Substitute("$0 mode=$1 size=$2 head=\"$3\"\n", entry.name, - absl::StrFormat("%04o", entry.mode), entry.size, - absl::CEscape(entry.head))); - } - return manifest; + LoseTarBytes(tar, lost, out); } std::string DrainStream(TarStream* tar, std::string* buffer) { - std::string out = absl::StrCat(*buffer, tar->is_tar ? TarManifest(*tar) : tar->held); - tar->held.clear(); + if (!tar->is_tar) { + std::string out = std::move(*buffer); + AppendCapped(&out, tar->held); + tar->held.clear(); + return out; + } + FlushTarEntry(tar); + std::string out = absl::StrCat(*buffer, tar->manifest); + if (tar->truncated) { + out.append(kTarTruncatedLine); + } + tar->manifest.clear(); return out; } -void AppendCapped(std::string* buffer, std::string_view data) { - const size_t room = kMaxBufferedOutput - std::min(kMaxBufferedOutput, buffer->size()); - buffer->append(data.substr(0, room)); -} - Record MakeRecord(RecordKind kind, message_type_t type, uint64_t timestamp_ns, std::string payload) { Record record; @@ -283,7 +331,7 @@ Record MakeRecord(RecordKind kind, message_type_t type, uint64_t timestamp_ns, record.msg.opcode = Opcode::kBinary; record.msg.fragments = 1; record.msg.payload = std::move(payload); - record.payload_size = record.msg.payload.size(); + record.msg.payload_size = record.msg.payload.size(); return record; } @@ -307,7 +355,7 @@ void EmitStdin(ExecState* state, std::vector* records) { Record record = MakeRecord(RecordKind::kInput, message_type_t::kRequest, state->stdin_timestamp_ns, DrainStream(&state->stdin_tar, &state->stdin_data)); - record.payload_size = state->stdin_size; + record.msg.payload_size = state->stdin_size; records->push_back(std::move(record)); state->stdin_data.clear(); state->stdin_size = 0; @@ -317,8 +365,14 @@ void EmitPending(ExecState* state, std::vector* records) { if (!state->pending.has_value()) { return; } - Record record = MakeRecord(RecordKind::kInput, message_type_t::kRequest, - state->pending->timestamp_ns, std::move(state->pending->line)); + PendingInput& pending = state->pending.value(); + if (absl::StartsWith(state->output, pending.line)) { + state->output.erase(0, pending.line.size()); + } else if (!pending.echoed) { + pending.line = kNoEchoPlaceholder; + } + Record record = MakeRecord(RecordKind::kInput, message_type_t::kRequest, pending.timestamp_ns, + std::move(pending.line)); TakeOutput(state, &record); records->push_back(std::move(record)); state->pending.reset(); @@ -326,7 +380,9 @@ void EmitPending(ExecState* state, std::vector* records) { void SubmitLine(ExecState* state, std::string_view suffix, std::vector* records) { EmitPending(state, records); - state->pending = PendingInput{state->line_timestamp_ns, absl::StrCat(state->line, suffix)}; + state->pending = PendingInput{state->line_timestamp_ns, absl::StrCat(state->line, suffix), + state->echoed || state->line.empty()}; + state->echoed = false; state->line.clear(); state->output.clear(); state->output_size = 0; @@ -352,6 +408,7 @@ void HandleStdin(uint64_t timestamp_ns, std::string_view data, ExecState* state, break; case kCtrlU: state->line.clear(); + state->echoed = false; break; case kCtrlC: if (!state->line.empty()) { @@ -368,7 +425,9 @@ void HandleStdin(uint64_t timestamp_ns, std::string_view data, ExecState* state, if (state->line.empty()) { state->line_timestamp_ns = timestamp_ns; } - state->line.push_back(c); + if (state->line.size() < kMaxBufferedOutput) { + state->line.push_back(c); + } break; } } @@ -439,6 +498,7 @@ void DecodeK8sExec(std::string_view path, std::vector messages, ExecSta } const uint8_t channel = msg.payload[0]; std::string_view data = std::string_view(msg.payload).substr(1); + const uint64_t lost = msg.payload_size - std::min(msg.payload_size, msg.payload.size()); if (msg.type == message_type_t::kRequest) { if (channel != kStdinChannel) { continue; @@ -449,25 +509,27 @@ void DecodeK8sExec(std::string_view path, std::vector messages, ExecSta if (state->stdin_size == 0) { state->stdin_timestamp_ns = msg.timestamp_ns; } - state->stdin_size += data.size(); - AppendCapped(&state->stdin_data, FeedTar(&state->stdin_tar, data)); + state->stdin_size += data.size() + lost; + FeedTar(&state->stdin_tar, data, lost, &state->stdin_data); } continue; } switch (channel) { case kStdoutChannel: - if (state->tty) { - if (state->line.empty()) { - AppendOutput(state, data); - } + if (!state->tty) { + state->output_size += data.size() + lost; + FeedTar(&state->stdout_tar, data, lost, &state->output); + } else if (state->line.empty()) { + AppendOutput(state, data); } else { - state->output_size += data.size(); - AppendCapped(&state->output, FeedTar(&state->stdout_tar, data)); + state->echoed = true; } break; case kStderrChannel: if (!state->tty || state->line.empty()) { AppendOutput(state, data); + } else { + state->echoed = true; } break; case kStatusChannel: { diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h index 4b2679fbecc..a885e28b7af 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h @@ -29,6 +29,8 @@ namespace stirling { namespace protocols { namespace websocket { +constexpr size_t kK8sChannelPayloadLimitBytes = 64 * 1024; + bool IsK8sChannelProtocol(std::string_view subprotocol); std::string K8sExecCommand(std::string_view path); diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc index 2d2c8f76c9b..75dbee2bb89 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc @@ -18,11 +18,17 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h" +#include #include #include +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h" #include "src/stirling/utils/binary_decoder.h" +DEFINE_uint32(websocket_payload_limit_bytes, + gflags::Uint32FromEnv("PX_STIRLING_WEBSOCKET_PAYLOAD_LIMIT_BYTES", 1024), + "The amount of a WebSocket frame payload that will be returned on a parse"); + namespace px { namespace stirling { namespace protocols { @@ -32,6 +38,7 @@ namespace { constexpr uint8_t kFinBit = 0x80; constexpr uint8_t kRsvBits = 0x70; +constexpr uint8_t kUnsupportedRsvBits = 0x30; constexpr uint8_t kRsvShift = 4; constexpr uint8_t kOpcodeBits = 0x0f; constexpr uint8_t kMaskBit = 0x80; @@ -42,71 +49,159 @@ constexpr uint64_t kPayloadLength64MSB = 1ULL << 63; constexpr uint64_t kMaxControlPayloadLength = 125; constexpr size_t kMaskingKeySize = 4; -} // namespace -} // namespace websocket +struct Header { + bool fin = false; + uint8_t rsv = 0; + Opcode opcode = Opcode::kContinuation; + bool masked = false; + uint64_t payload_length = 0; + std::string_view masking_key; +}; -template <> -ParseState ParseFrame(message_type_t, std::string_view* buf, websocket::Frame* frame, - websocket::StateWrapper*) { - using websocket::Opcode; +ParseState ParseHeader(BinaryDecoder* decoder, Header* header) { + PX_ASSIGN_OR(uint8_t b0, decoder->ExtractBEInt(), return ParseState::kNeedsMoreData); + PX_ASSIGN_OR(uint8_t b1, decoder->ExtractBEInt(), return ParseState::kNeedsMoreData); - BinaryDecoder decoder(*buf); - PX_ASSIGN_OR(uint8_t b0, decoder.ExtractBEInt(), return ParseState::kNeedsMoreData); - PX_ASSIGN_OR(uint8_t b1, decoder.ExtractBEInt(), return ParseState::kNeedsMoreData); - - std::optional opcode = magic_enum::enum_cast(b0 & websocket::kOpcodeBits); - if (!opcode.has_value()) { + std::optional opcode = magic_enum::enum_cast(b0 & kOpcodeBits); + if (!opcode.has_value() || (b0 & kUnsupportedRsvBits)) { return ParseState::kInvalid; } - const bool fin = b0 & websocket::kFinBit; - const bool control = websocket::IsControl(opcode.value()); - if (control && !fin) { + header->fin = b0 & kFinBit; + const bool control = IsControl(opcode.value()); + if (control && !header->fin) { return ParseState::kInvalid; } - uint64_t payload_length = b1 & websocket::kPayloadLengthBits; - if (payload_length == websocket::kPayloadLength16) { - PX_ASSIGN_OR(payload_length, decoder.ExtractBEInt(), + uint64_t payload_length = b1 & kPayloadLengthBits; + if (payload_length == kPayloadLength16) { + PX_ASSIGN_OR(payload_length, decoder->ExtractBEInt(), return ParseState::kNeedsMoreData); - } else if (payload_length == websocket::kPayloadLength64) { - PX_ASSIGN_OR(payload_length, decoder.ExtractBEInt(), + } else if (payload_length == kPayloadLength64) { + PX_ASSIGN_OR(payload_length, decoder->ExtractBEInt(), return ParseState::kNeedsMoreData); - if (payload_length & websocket::kPayloadLength64MSB) { + if (payload_length & kPayloadLength64MSB) { return ParseState::kInvalid; } } - if (control && payload_length > websocket::kMaxControlPayloadLength) { + if (control && payload_length > kMaxControlPayloadLength) { return ParseState::kInvalid; } - const bool masked = b1 & websocket::kMaskBit; - std::string_view masking_key; - if (masked) { - PX_ASSIGN_OR(masking_key, decoder.ExtractString(websocket::kMaskingKeySize), + header->masked = b1 & kMaskBit; + if (header->masked) { + PX_ASSIGN_OR(header->masking_key, decoder->ExtractString(kMaskingKeySize), return ParseState::kNeedsMoreData); } - PX_ASSIGN_OR(std::string_view payload, decoder.ExtractString(payload_length), - return ParseState::kNeedsMoreData); + header->rsv = (b0 & kRsvBits) >> kRsvShift; + header->opcode = opcode.value(); + header->payload_length = payload_length; + return ParseState::kSuccess; +} + +DirectionState* Direction(message_type_t type, StateWrapper* state) { + if (state == nullptr) { + return nullptr; + } + return type == message_type_t::kRequest ? &state->send : &state->recv; +} + +ParseState CheckHeaderAt(message_type_t type, std::string_view buf, uint64_t* frame_size) { + BinaryDecoder decoder(buf); + Header header; + ParseState s = ParseHeader(&decoder, &header); + if (s != ParseState::kSuccess) { + return s; + } + if (header.masked != (type == message_type_t::kRequest)) { + return ParseState::kInvalid; + } + *frame_size = buf.size() - decoder.BufSize() + header.payload_length; + return ParseState::kSuccess; +} + +bool IsFrameBoundary(message_type_t type, std::string_view buf, size_t pos) { + uint64_t frame_size = 0; + if (CheckHeaderAt(type, buf.substr(pos), &frame_size) != ParseState::kSuccess) { + return false; + } + const size_t remaining = buf.size() - pos; + if (frame_size >= remaining) { + return frame_size == remaining; + } + uint64_t next_frame_size = 0; + return CheckHeaderAt(type, buf.substr(pos + frame_size), &next_frame_size) != + ParseState::kInvalid; +} - frame->fin = fin; - frame->rsv = (b0 & websocket::kRsvBits) >> websocket::kRsvShift; - frame->opcode = opcode.value(); - frame->masked = masked; - frame->payload_length = payload_length; +} // namespace + +size_t PayloadLimitBytes(const StateWrapper* state) { + if (state != nullptr && IsK8sChannelProtocol(state->global.subprotocol)) { + return kK8sChannelPayloadLimitBytes; + } + return FLAGS_websocket_payload_limit_bytes; +} + +} // namespace websocket + +template <> +ParseState ParseFrame(message_type_t type, std::string_view* buf, websocket::Frame* frame, + websocket::StateWrapper* state) { + websocket::DirectionState* direction = websocket::Direction(type, state); + if (direction != nullptr && direction->skip > 0) { + const size_t skipped = std::min(direction->skip, buf->size()); + buf->remove_prefix(skipped); + direction->skip -= skipped; + return ParseState::kIgnored; + } + + BinaryDecoder decoder(*buf); + websocket::Header header; + ParseState s = websocket::ParseHeader(&decoder, &header); + if (s != ParseState::kSuccess) { + return s; + } + + const uint64_t captured = + direction == nullptr + ? header.payload_length + : std::min(header.payload_length, websocket::PayloadLimitBytes(state)); + PX_ASSIGN_OR(std::string_view payload, decoder.ExtractString(captured), + return ParseState::kNeedsMoreData); + const uint64_t uncaptured = header.payload_length - captured; + const size_t consumed = std::min(uncaptured, decoder.BufSize()); + + frame->fin = header.fin; + frame->rsv = header.rsv; + frame->opcode = header.opcode; + frame->masked = header.masked; + frame->payload_length = header.payload_length; frame->payload.assign(payload); - if (masked) { + if (header.masked) { for (size_t i = 0; i < frame->payload.size(); ++i) { - frame->payload[i] ^= masking_key[i % websocket::kMaskingKeySize]; + frame->payload[i] ^= header.masking_key[i % websocket::kMaskingKeySize]; } } - buf->remove_prefix(buf->size() - decoder.BufSize()); + buf->remove_prefix(buf->size() - decoder.BufSize() + consumed); + if (direction != nullptr) { + direction->skip = uncaptured - consumed; + } return ParseState::kSuccess; } template <> -size_t FindFrameBoundary(message_type_t, std::string_view, size_t, - websocket::StateWrapper*) { +size_t FindFrameBoundary(message_type_t type, std::string_view buf, + size_t start_pos, websocket::StateWrapper* state) { + websocket::DirectionState* direction = websocket::Direction(type, state); + if (direction != nullptr) { + direction->skip = 0; + } + for (size_t pos = start_pos; pos < buf.size(); ++pos) { + if (websocket::IsFrameBoundary(type, buf, pos)) { + return pos; + } + } return std::string_view::npos; } diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h index 09353a63916..af8619d8d8c 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h @@ -23,10 +23,18 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/common/interface.h" #include "src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h" +DECLARE_uint32(websocket_payload_limit_bytes); + namespace px { namespace stirling { namespace protocols { +namespace websocket { + +size_t PayloadLimitBytes(const StateWrapper* state); + +} // namespace websocket + template <> ParseState ParseFrame(message_type_t type, std::string_view* buf, websocket::Frame* frame, websocket::StateWrapper* state); diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc index 3212b3d0a20..964a5a117d4 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc @@ -20,9 +20,11 @@ #include #include +#include #include #include "src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.h" namespace px { namespace stirling { @@ -32,6 +34,7 @@ namespace websocket { namespace { constexpr uint8_t kRsv1 = 0x4; +constexpr std::string_view kCompressedPlaceholder = ""; Message StartMessage(message_type_t type, Frame* frame) { Message msg; @@ -41,10 +44,11 @@ Message StartMessage(message_type_t type, Frame* frame) { msg.compressed = frame->rsv & kRsv1; msg.fragments = 1; msg.payload = std::move(frame->payload); + msg.payload_size = frame->payload_length; return msg; } -int StitchDirection(message_type_t type, std::deque* frames, +int StitchDirection(message_type_t type, size_t payload_limit, std::deque* frames, std::vector* messages) { int error_count = 0; std::deque pending; @@ -72,7 +76,9 @@ int StitchDirection(message_type_t type, std::deque* frames, } Message msg = StartMessage(type, &pending.front()); for (size_t i = 1; i < pending.size(); ++i) { - msg.payload.append(pending[i].payload); + const size_t room = payload_limit - std::min(payload_limit, msg.payload.size()); + msg.payload.append(pending[i].payload, 0, room); + msg.payload_size += pending[i].payload_length; ++msg.fragments; } messages->push_back(std::move(msg)); @@ -92,9 +98,11 @@ RecordsWithErrorCount StitchFrames(std::deque result; std::vector messages; - result.error_count += websocket::StitchDirection(message_type_t::kRequest, req_frames, &messages); - result.error_count += - websocket::StitchDirection(message_type_t::kResponse, resp_frames, &messages); + const size_t payload_limit = websocket::PayloadLimitBytes(state); + result.error_count += websocket::StitchDirection(message_type_t::kRequest, payload_limit, + req_frames, &messages); + result.error_count += websocket::StitchDirection(message_type_t::kResponse, payload_limit, + resp_frames, &messages); websocket::State empty_state; websocket::State* global = state == nullptr ? &empty_state : &state->global; @@ -106,6 +114,9 @@ RecordsWithErrorCount StitchFrames(std::dequepath, std::move(messages), &global->exec, &result.records); } else { for (websocket::Message& msg : messages) { + if (msg.compressed) { + msg.payload = websocket::kCompressedPlaceholder; + } websocket::Record record; record.msg = std::move(msg); result.records.push_back(std::move(record)); diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h index 65e69964a26..02ffcc18556 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h @@ -21,8 +21,6 @@ #include #include #include -#include -#include #include "src/common/base/base.h" #include "src/stirling/source_connectors/socket_tracer/protocols/common/event_parser.h" @@ -68,12 +66,13 @@ struct Message { bool compressed = false; size_t fragments = 0; std::string payload; + size_t payload_size = 0; std::string ToString() const { return absl::Substitute( "Message: {type: $0, opcode: $1, compressed: $2, fragments: $3, len: $4}", magic_enum::enum_name(type), magic_enum::enum_name(opcode), compressed, fragments, - payload.size()); + payload_size); } }; @@ -102,7 +101,6 @@ struct Record { Message msg; RecordKind kind = RecordKind::kFrame; std::string subprotocol; - size_t payload_size = 0; std::string output; size_t output_size = 0; @@ -123,23 +121,27 @@ struct TarStream { bool checked = false; bool is_tar = false; bool done = false; + bool truncated = false; bool long_name = false; std::string held; uint64_t skip = 0; uint64_t capture_left = 0; std::string next_name; - std::vector entries; + std::optional entry; + std::string manifest; }; struct PendingInput { uint64_t timestamp_ns = 0; std::string line; + bool echoed = false; }; struct ExecState { bool started = false; bool tty = false; bool last_cr = false; + bool echoed = false; std::string line; uint64_t line_timestamp_ns = 0; std::optional pending; @@ -158,10 +160,14 @@ struct State { ExecState exec; }; +struct DirectionState { + uint64_t skip = 0; +}; + struct StateWrapper { State global; - std::monostate send; - std::monostate recv; + DirectionState send; + DirectionState recv; }; struct ProtocolTraits : public BaseProtocolTraits { diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index c366de2ea3a..18299d7b340 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -1795,9 +1795,6 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke md::UPID upid(ctx->GetASID(), conn_tracker.conn_id().upid.pid, conn_tracker.conn_id().upid.start_time_ticks); - const size_t payload_size = record.kind == protocols::websocket::RecordKind::kFrame - ? msg.payload.size() - : record.payload_size; DataTable::RecordBuilder<&kWebSocketTable> r(data_table, msg.timestamp_ns); r.Append(msg.timestamp_ns); r.Append(upid.value()); @@ -1813,18 +1810,17 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke r.Append(static_cast(msg.opcode)); r.Append(msg.compressed); r.Append(msg.fragments); - if (record.kind != protocols::websocket::RecordKind::kFrame) { - r.Append(protocols::websocket::Printable(msg.payload), - FLAGS_max_body_bytes); - } else if (msg.opcode == protocols::websocket::Opcode::kText) { + auto printable = [](std::string_view data) { + return protocols::websocket::Printable(data.substr(0, FLAGS_max_body_bytes)); + }; + if (record.kind == protocols::websocket::RecordKind::kFrame && + msg.opcode == protocols::websocket::Opcode::kText) { r.Append(std::move(msg.payload), FLAGS_max_body_bytes); } else { - r.Append(BytesToString(msg.payload), - FLAGS_max_body_bytes); + r.Append(printable(msg.payload), FLAGS_max_body_bytes); } - r.Append(payload_size); - r.Append(protocols::websocket::Printable(record.output), - FLAGS_max_body_bytes); + r.Append(msg.payload_size); + r.Append(printable(record.output), FLAGS_max_body_bytes); r.Append(record.output_size); #ifndef NDEBUG r.Append(PXInfoString(conn_tracker, record)); From e8124da448a4ac9f1e88b9ffaf53b4e322034007 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 16:33:21 +0000 Subject: [PATCH 24/51] format Signed-off-by: entlein --- .../protocols/websocket/k8s_exec.cc | 12 +++---- .../protocols/websocket/k8s_exec_test.cc | 33 ++++++++++++------- .../protocols/websocket/stitcher.cc | 10 +++--- .../socket_trace_connector_test.cc | 7 ++-- 4 files changed, 35 insertions(+), 27 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc index d0d2b5163d9..ca69dfa861c 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc @@ -187,10 +187,9 @@ void FlushTarEntry(TarStream* tar) { return; } const TarEntryInfo& entry = tar->entry.value(); - AppendCapped(&tar->manifest, - absl::Substitute("$0 mode=$1 size=$2 head=\"$3\"\n", entry.name, - absl::StrFormat("%04o", entry.mode), entry.size, - absl::CEscape(entry.head))); + AppendCapped(&tar->manifest, absl::Substitute("$0 mode=$1 size=$2 head=\"$3\"\n", entry.name, + absl::StrFormat("%04o", entry.mode), entry.size, + absl::CEscape(entry.head))); tar->entry.reset(); } @@ -224,9 +223,8 @@ void ParseTarHeader(std::string_view header, TarStream* tar) { if (tar->manifest.size() >= kMaxBufferedOutput) { return; } - tar->entry = - TarEntryInfo{std::move(name), ParseOctal(header.substr(kTarModeOffset, kTarModeSize)), size, - ""}; + tar->entry = TarEntryInfo{std::move(name), + ParseOctal(header.substr(kTarModeOffset, kTarModeSize)), size, ""}; tar->capture_left = std::min(size, kTarHeadSize); if (tar->capture_left == 0) { FlushTarEntry(tar); diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc index 5b40595191a..25d7092b53b 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc @@ -169,10 +169,18 @@ TEST(K8sExecTest, TTYSessionBecomesOneRowPerCommand) { TEST(K8sExecTest, LineEditingIsApplied) { std::vector messages = { - In(1, "\x00lx"sv), Out(2, "\x01lx"), In(3, "\x00\x7f"sv), - Out(4, "\x01\b \b"), In(5, "\x00s"sv), Out(6, "\x01s"), - In(7, "\x00\r"sv), Out(8, "\x01\r\nbin\r\n/ # "), In(9, "\x00junk"sv), - Out(10, "\x01junk"), In(11, "\x00\x15"sv), In(12, "\x00pwd\r"sv), + In(1, "\x00lx"sv), + Out(2, "\x01lx"), + In(3, "\x00\x7f"sv), + Out(4, "\x01\b \b"), + In(5, "\x00s"sv), + Out(6, "\x01s"), + In(7, "\x00\r"sv), + Out(8, "\x01\r\nbin\r\n/ # "), + In(9, "\x00junk"sv), + Out(10, "\x01junk"), + In(11, "\x00\x15"sv), + In(12, "\x00pwd\r"sv), Out(13, "\x01\r\n/\r\n/ # "), }; ExecState state; @@ -423,7 +431,10 @@ TEST(K8sExecTest, InputLineIsBounded) { std::vector records; DecodeK8sExec(kKubeletTTYPath, - {In(1, absl::StrCat(std::string(1, '\0'), typed)), Out(2, "\x01" "aaaa"), + {In(1, absl::StrCat(std::string(1, '\0'), typed)), + Out(2, + "\x01" + "aaaa"), In(3, "\x00\r"sv), Out(4, absl::StrCat("\x03", kStatusSuccess))}, &state, &records); @@ -479,9 +490,8 @@ TEST(K8sExecTest, TarLossAcrossHeaderIsMarked) { &state, &records); ASSERT_EQ(records.size(), 2U); - EXPECT_EQ(records[1].output, - absl::StrCat("big.bin mode=0644 size=5000 head=\"", std::string(64, 'b'), "\"\n", - "[TRUNCATED]\n")); + EXPECT_EQ(records[1].output, absl::StrCat("big.bin mode=0644 size=5000 head=\"", + std::string(64, 'b'), "\"\n", "[TRUNCATED]\n")); } TEST(K8sExecTest, TarManifestIsBounded) { @@ -493,9 +503,10 @@ TEST(K8sExecTest, TarManifestIsBounded) { ExecState state; std::vector records; - DecodeK8sExec(kTarStdoutPath, - {Out(1, absl::StrCat("\x01", archive)), Out(2, absl::StrCat("\x03", kStatusSuccess))}, - &state, &records); + DecodeK8sExec( + kTarStdoutPath, + {Out(1, absl::StrCat("\x01", archive)), Out(2, absl::StrCat("\x03", kStatusSuccess))}, &state, + &records); ASSERT_EQ(records.size(), 2U); EXPECT_LE(records[1].output.size(), 4096U); diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc index 964a5a117d4..bc583b86104 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc @@ -19,8 +19,8 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.h" #include -#include #include +#include #include #include "src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h" @@ -99,10 +99,10 @@ RecordsWithErrorCount StitchFrames(std::deque result; std::vector messages; const size_t payload_limit = websocket::PayloadLimitBytes(state); - result.error_count += websocket::StitchDirection(message_type_t::kRequest, payload_limit, - req_frames, &messages); - result.error_count += websocket::StitchDirection(message_type_t::kResponse, payload_limit, - resp_frames, &messages); + result.error_count += + websocket::StitchDirection(message_type_t::kRequest, payload_limit, req_frames, &messages); + result.error_count += + websocket::StitchDirection(message_type_t::kResponse, payload_limit, resp_frames, &messages); websocket::State empty_state; websocket::State* global = state == nullptr ? &empty_state : &state->global; diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc index cc1e7571313..af9d29c111d 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc @@ -238,8 +238,8 @@ class SocketTraceConnectorWebSocketTest : public SocketTraceConnectorTest { RecordBatch TransferUpgradedServerFrames(std::string_view frames) { source_->AcceptControlEvent(event_gen_.InitConn()); source_->AcceptDataEvent(event_gen_.InitSendEvent(testing::kHTTPUpgradeReq)); - source_->AcceptDataEvent(event_gen_.InitRecvEvent( - absl::StrCat(testing::kHTTPUpgradeResp, frames))); + source_->AcceptDataEvent( + event_gen_.InitRecvEvent(absl::StrCat(testing::kHTTPUpgradeResp, frames))); connector_->TransferData(ctx_.get()); connector_->TransferData(ctx_.get()); std::vector tablets = websocket_table_->ConsumeRecords(); @@ -368,8 +368,7 @@ TEST_F(SocketTraceConnectorWebSocketTest, LargeBinaryPayloadIsTruncatedBeforeEsc EXPECT_TRUE(absl::StartsWith(payload, "\\x01\\x01")); EXPECT_TRUE(absl::EndsWith(payload, DataTable::kTruncatedMsg)); EXPECT_LE(payload.size(), FLAGS_max_body_bytes + strlen(DataTable::kTruncatedMsg)); - EXPECT_THAT(ToIntVector(records[kWebSocketPayloadSizeIdx]), - ElementsAre(4000)); + EXPECT_THAT(ToIntVector(records[kWebSocketPayloadSizeIdx]), ElementsAre(4000)); } TEST_F(SocketTraceConnectorWebSocketTest, CompressedPayloadIsRemoved) { From 43aa0546cddea7d3c5e181d3bb02218772299f33 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 17:39:22 +0100 Subject: [PATCH 25/51] Add a WebSocket trace BPF test with plain and TLS echo sessions Signed-off-by: entlein --- .../socket_tracer/BUILD.bazel | 15 +++ .../testing/container_images/BUILD.bazel | 16 +++ .../go_websocket_client_container.h | 45 +++++++++ .../go_websocket_server_container.h | 45 +++++++++ .../socket_tracer/websocket_table.h | 2 + .../socket_tracer/websocket_trace_bpf_test.cc | 99 +++++++++++++++++++ .../demo_apps/go_websocket/client/BUILD.bazel | 38 +++++++ .../go_websocket/client/websocket_client.go | 83 ++++++++++++++++ .../demo_apps/go_websocket/server/BUILD.bazel | 61 ++++++++++++ .../go_websocket/server/websocket_server.go | 60 +++++++++++ 10 files changed, 464 insertions(+) create mode 100644 src/stirling/source_connectors/socket_tracer/testing/container_images/go_websocket_client_container.h create mode 100644 src/stirling/source_connectors/socket_tracer/testing/container_images/go_websocket_server_container.h create mode 100644 src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc create mode 100644 src/stirling/testing/demo_apps/go_websocket/client/BUILD.bazel create mode 100644 src/stirling/testing/demo_apps/go_websocket/client/websocket_client.go create mode 100644 src/stirling/testing/demo_apps/go_websocket/server/BUILD.bazel create mode 100644 src/stirling/testing/demo_apps/go_websocket/server/websocket_server.go diff --git a/src/stirling/source_connectors/socket_tracer/BUILD.bazel b/src/stirling/source_connectors/socket_tracer/BUILD.bazel index 76a9ca13b77..5120a7f2f30 100644 --- a/src/stirling/source_connectors/socket_tracer/BUILD.bazel +++ b/src/stirling/source_connectors/socket_tracer/BUILD.bazel @@ -560,6 +560,21 @@ pl_cc_bpf_test( ], ) +pl_cc_bpf_test( + name = "websocket_trace_bpf_test", + timeout = "moderate", + srcs = ["websocket_trace_bpf_test.cc"], + tags = ["requires_bpf"], + deps = [ + ":cc_library", + "//src/common/testing/test_utils:cc_library", + "//src/stirling/source_connectors/socket_tracer/testing:cc_library", + "//src/stirling/source_connectors/socket_tracer/testing/container_images:go_websocket_client_container", + "//src/stirling/source_connectors/socket_tracer/testing/container_images:go_websocket_server_container", + "//src/stirling/testing:cc_library", + ], +) + pl_cc_bpf_test( name = "amqp_trace_bpf_test", timeout = "moderate", diff --git a/src/stirling/source_connectors/socket_tracer/testing/container_images/BUILD.bazel b/src/stirling/source_connectors/socket_tracer/testing/container_images/BUILD.bazel index c8cbb13ed52..6a1e982d04d 100644 --- a/src/stirling/source_connectors/socket_tracer/testing/container_images/BUILD.bazel +++ b/src/stirling/source_connectors/socket_tracer/testing/container_images/BUILD.bazel @@ -380,3 +380,19 @@ container_image( layers = [":clickhouse_config_layer"], visibility = ["//visibility:public"], ) + +pl_cc_test_library( + name = "go_websocket_server_container", + srcs = [], + hdrs = ["go_websocket_server_container.h"], + data = ["//src/stirling/testing/demo_apps/go_websocket/server:websocket_server_image.tar"], + deps = ["//src/common/testing/test_utils:cc_library"], +) + +pl_cc_test_library( + name = "go_websocket_client_container", + srcs = [], + hdrs = ["go_websocket_client_container.h"], + data = ["//src/stirling/testing/demo_apps/go_websocket/client:websocket_client_image.tar"], + deps = ["//src/common/testing/test_utils:cc_library"], +) diff --git a/src/stirling/source_connectors/socket_tracer/testing/container_images/go_websocket_client_container.h b/src/stirling/source_connectors/socket_tracer/testing/container_images/go_websocket_client_container.h new file mode 100644 index 00000000000..9e5dcf2d44d --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/testing/container_images/go_websocket_client_container.h @@ -0,0 +1,45 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include + +#include "src/common/testing/test_environment.h" +#include "src/common/testing/test_utils/container_runner.h" + +namespace px { +namespace stirling { +namespace testing { + +class GoWebSocketClientContainer : public ContainerRunner { + public: + GoWebSocketClientContainer() + : ContainerRunner(::px::testing::BazelRunfilePath(kBazelImageTar), kContainerNamePrefix, + kReadyMessage) {} + + private: + static constexpr std::string_view kBazelImageTar = + "src/stirling/testing/demo_apps/go_websocket/client/websocket_client_image.tar"; + static constexpr std::string_view kContainerNamePrefix = "websocket_client"; + static constexpr std::string_view kReadyMessage = ""; +}; + +} // namespace testing +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/testing/container_images/go_websocket_server_container.h b/src/stirling/source_connectors/socket_tracer/testing/container_images/go_websocket_server_container.h new file mode 100644 index 00000000000..b84dfdc705b --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/testing/container_images/go_websocket_server_container.h @@ -0,0 +1,45 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include + +#include "src/common/testing/test_environment.h" +#include "src/common/testing/test_utils/container_runner.h" + +namespace px { +namespace stirling { +namespace testing { + +class GoWebSocketServerContainer : public ContainerRunner { + public: + GoWebSocketServerContainer() + : ContainerRunner(::px::testing::BazelRunfilePath(kBazelImageTar), kContainerNamePrefix, + kReadyMessage) {} + + private: + static constexpr std::string_view kBazelImageTar = + "src/stirling/testing/demo_apps/go_websocket/server/websocket_server_image.tar"; + static constexpr std::string_view kContainerNamePrefix = "websocket_server"; + static constexpr std::string_view kReadyMessage = "Starting WebSocket service"; +}; + +} // namespace testing +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/websocket_table.h b/src/stirling/source_connectors/socket_tracer/websocket_table.h index e3a7ba4ecec..d6cf1507433 100644 --- a/src/stirling/source_connectors/socket_tracer/websocket_table.h +++ b/src/stirling/source_connectors/socket_tracer/websocket_table.h @@ -86,6 +86,8 @@ static constexpr auto kWebSocketTable = DataTableSchema("websocket_events", "WebSocket messages", kWebSocketElements); DEFINE_PRINT_TABLE(WebSocket) +constexpr int kWebSocketUPIDIdx = kWebSocketTable.ColIndex("upid"); +constexpr int kWebSocketEncryptedIdx = kWebSocketTable.ColIndex("encrypted"); constexpr int kWebSocketSubprotocolIdx = kWebSocketTable.ColIndex("subprotocol"); constexpr int kWebSocketKindIdx = kWebSocketTable.ColIndex("kind"); constexpr int kWebSocketDirectionIdx = kWebSocketTable.ColIndex("direction"); diff --git a/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc b/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc new file mode 100644 index 00000000000..82b59994c11 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc @@ -0,0 +1,99 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include + +#include +#include + +#include + +#include "src/common/testing/testing.h" +#include "src/stirling/source_connectors/socket_tracer/testing/container_images/go_websocket_client_container.h" +#include "src/stirling/source_connectors/socket_tracer/testing/container_images/go_websocket_server_container.h" +#include "src/stirling/source_connectors/socket_tracer/testing/socket_trace_bpf_test_fixture.h" +#include "src/stirling/testing/common.h" + +namespace px { +namespace stirling { + +using ::px::stirling::testing::FindRecordIdxMatchesPID; +using ::testing::Each; +using ::testing::IsSupersetOf; + +class WebSocketTraceTest : public testing::SocketTraceBPFTestFixture { + protected: + WebSocketTraceTest() { + FLAGS_stirling_enable_websocket_tracing = TraceMode::On; + PX_CHECK_OK(server_.Run(std::chrono::seconds{60}, {})); + } + + ~WebSocketTraceTest() override { FLAGS_stirling_enable_websocket_tracing = TraceMode::Off; } + + ::px::stirling::testing::GoWebSocketServerContainer server_; + ::px::stirling::testing::GoWebSocketClientContainer client_; +}; + +std::string Row(const types::ColumnWrapperRecordBatch& records, size_t i) { + return absl::Substitute("encrypted=$0 direction=$1 opcode=$2 payload=$3", + records[kWebSocketEncryptedIdx]->Get(i).val, + records[kWebSocketDirectionIdx]->Get(i).val, + records[kWebSocketOpcodeIdx]->Get(i).val, + records[kWebSocketPayloadIdx]->Get(i)); +} + +TEST_F(WebSocketTraceTest, PlainAndTLSEchoSessions) { + StartTransferDataThread(); + + PX_CHECK_OK(client_.Run(std::chrono::seconds{10}, + {absl::Substitute("--network=container:$0", server_.container_name())}, + {"--iters=2"})); + client_.Wait(); + + StopTransferDataThread(); + + std::vector tablets = ConsumeRecords(SocketTraceConnector::kWebSocketTableNum); + ASSERT_NOT_EMPTY_AND_GET_RECORDS(const types::ColumnWrapperRecordBatch& record_batch, tablets); + + const std::vector indices = + FindRecordIdxMatchesPID(record_batch, kWebSocketUPIDIdx, server_.process_pid()); + std::vector rows; + std::vector subprotocols; + for (size_t i : indices) { + rows.push_back(Row(record_batch, i)); + subprotocols.push_back(record_batch[kWebSocketSubprotocolIdx]->Get(i)); + } + + std::vector expected; + for (bool encrypted : {false, true}) { + for (std::string_view payload : {"hello-0", "hello-1"}) { + expected.push_back( + absl::Substitute("encrypted=$0 direction=1 opcode=1 payload=$1", encrypted, payload)); + expected.push_back( + absl::Substitute("encrypted=$0 direction=2 opcode=1 payload=$1", encrypted, payload)); + } + expected.push_back( + absl::Substitute("encrypted=$0 direction=1 opcode=2 payload=\\x01\\x02hi", encrypted)); + } + EXPECT_THAT(rows, IsSupersetOf(expected)); + EXPECT_THAT(subprotocols, Each(std::string("echo.pixie"))); +} + +} // namespace stirling +} // namespace px diff --git a/src/stirling/testing/demo_apps/go_websocket/client/BUILD.bazel b/src/stirling/testing/demo_apps/go_websocket/client/BUILD.bazel new file mode 100644 index 00000000000..0f92be59f7c --- /dev/null +++ b/src/stirling/testing/demo_apps/go_websocket/client/BUILD.bazel @@ -0,0 +1,38 @@ +# Copyright 2018- The Pixie Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + + +load("@io_bazel_rules_go//go:def.bzl", "go_library") +load("//bazel:pl_build_system.bzl", "pl_go_binary", "pl_go_image") + +package(default_visibility = ["//src/stirling:__subpackages__"]) + +go_library( + name = "client_lib", + srcs = ["websocket_client.go"], + importpath = "px.dev/pixie/src/stirling/testing/demo_apps/go_websocket/client", + deps = ["@org_golang_x_net//websocket"], +) + +pl_go_binary( + name = "client", + embed = [":client_lib"], +) + +pl_go_image( + name = "websocket_client_image", + binary = ":client", +) diff --git a/src/stirling/testing/demo_apps/go_websocket/client/websocket_client.go b/src/stirling/testing/demo_apps/go_websocket/client/websocket_client.go new file mode 100644 index 00000000000..9f38a3f0690 --- /dev/null +++ b/src/stirling/testing/demo_apps/go_websocket/client/websocket_client.go @@ -0,0 +1,83 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package main + +import ( + "bytes" + "crypto/tls" + "flag" + "fmt" + "log" + + "golang.org/x/net/websocket" +) + +const subprotocol = "echo.pixie" + +func exchange(url string, iters int) { + config, err := websocket.NewConfig(url, "http://localhost/") + if err != nil { + log.Fatal(err) + } + config.Protocol = []string{subprotocol} + config.TlsConfig = &tls.Config{InsecureSkipVerify: true} + ws, err := websocket.DialConfig(config) + if err != nil { + log.Fatal(err) + } + defer ws.Close() + + for i := 0; i < iters; i++ { + msg := fmt.Sprintf("hello-%d", i) + if err := websocket.Message.Send(ws, msg); err != nil { + log.Fatal(err) + } + var reply string + if err := websocket.Message.Receive(ws, &reply); err != nil { + log.Fatal(err) + } + if reply != msg { + log.Fatalf("got %q, want %q", reply, msg) + } + } + + binary := []byte{0x01, 0x02, 'h', 'i'} + if err := websocket.Message.Send(ws, binary); err != nil { + log.Fatal(err) + } + var reply []byte + if err := websocket.Message.Receive(ws, &reply); err != nil { + log.Fatal(err) + } + if !bytes.Equal(reply, binary) { + log.Fatalf("got %q, want %q", reply, binary) + } +} + +func main() { + address := flag.String("address", "127.0.0.1", "Server address.") + wsPort := flag.Int("ws_port", 50200, "Port of the plaintext WebSocket listener.") + wssPort := flag.Int("wss_port", 50201, "Port of the TLS WebSocket listener.") + iters := flag.Int("iters", 3, "Number of text messages per connection.") + flag.Parse() + + exchange(fmt.Sprintf("ws://%s:%d/echo", *address, *wsPort), *iters) + exchange(fmt.Sprintf("wss://%s:%d/echo", *address, *wssPort), *iters) + log.Print("WebSocket client done") +} diff --git a/src/stirling/testing/demo_apps/go_websocket/server/BUILD.bazel b/src/stirling/testing/demo_apps/go_websocket/server/BUILD.bazel new file mode 100644 index 00000000000..f8c3f144b05 --- /dev/null +++ b/src/stirling/testing/demo_apps/go_websocket/server/BUILD.bazel @@ -0,0 +1,61 @@ +# Copyright 2018- The Pixie Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + + +load("@io_bazel_rules_docker//container:container.bzl", "container_image") +load("@io_bazel_rules_go//go:def.bzl", "go_library") +load("//bazel:pl_build_system.bzl", "pl_go_binary") + +package(default_visibility = ["//src/stirling:__subpackages__"]) + +go_library( + name = "server_lib", + srcs = ["websocket_server.go"], + importpath = "px.dev/pixie/src/stirling/testing/demo_apps/go_websocket/server", + deps = ["@org_golang_x_net//websocket"], +) + +pl_go_binary( + name = "server", + embed = [":server_lib"], +) + +genrule( + name = "certs", + outs = [ + "server.crt", + "server.key", + ], + cmd = """ + openssl ecparam -genkey -name secp384r1 -out $(location server.key) && \ + openssl req -new -x509 -sha256 -key $(location server.key) -subj "/CN=127.0.0.1" -out $(location server.crt) -days 365 + """, +) + +container_image( + name = "websocket_server_image", + base = "//:pl_go_base_image", + entrypoint = [ + "./server", + "--cert=server.crt", + "--key=server.key", + ], + files = [ + ":server", + ":server.crt", + ":server.key", + ], +) diff --git a/src/stirling/testing/demo_apps/go_websocket/server/websocket_server.go b/src/stirling/testing/demo_apps/go_websocket/server/websocket_server.go new file mode 100644 index 00000000000..e1026188cfa --- /dev/null +++ b/src/stirling/testing/demo_apps/go_websocket/server/websocket_server.go @@ -0,0 +1,60 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package main + +import ( + "flag" + "fmt" + "io" + "log" + "net" + "net/http" + + "golang.org/x/net/websocket" +) + +func echo(ws *websocket.Conn) { + if _, err := io.Copy(ws, ws); err != nil { + log.Printf("echo: %v", err) + } +} + +func main() { + wsPort := flag.Int("ws_port", 50200, "Port of the plaintext WebSocket listener.") + wssPort := flag.Int("wss_port", 50201, "Port of the TLS WebSocket listener.") + certPath := flag.String("cert", "", "Path to the .crt file.") + keyPath := flag.String("key", "", "Path to the .key file.") + flag.Parse() + + http.Handle("/echo", websocket.Handler(echo)) + + wsListener, err := net.Listen("tcp", fmt.Sprintf(":%d", *wsPort)) + if err != nil { + log.Fatal(err) + } + wssListener, err := net.Listen("tcp", fmt.Sprintf(":%d", *wssPort)) + if err != nil { + log.Fatal(err) + } + go func() { + log.Fatal(http.ServeTLS(wssListener, nil, *certPath, *keyPath)) + }() + log.Printf("Starting WebSocket service on ports %d and %d", *wsPort, *wssPort) + log.Fatal(http.Serve(wsListener, nil)) +} From 49ca006c0a3b90bc020460f717ee52c38333db8f Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 17:42:30 +0100 Subject: [PATCH 26/51] Test flushing Kubernetes exec sessions that close without a status Signed-off-by: entlein --- .../socket_tracer/conn_tracker_test.cc | 55 +++++++++++++++++++ .../protocols/websocket/k8s_exec_test.cc | 48 ++++++++++++++++ .../protocols/websocket/stitcher_test.cc | 34 ++++++++++++ 3 files changed, 137 insertions(+) diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc index d7fdccdcbc4..fb22fe9cd73 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc @@ -440,6 +440,61 @@ TEST_F(ConnTrackerTest, TrackerWebSocketUpgradeKeepsSubprotocol) { EXPECT_EQ(ws_records[0].msg.payload, "hostname"); } +TEST_F(ConnTrackerTest, TrackerWebSocketSessionClosedWithoutStatusIsFlushed) { + constexpr std::string_view kExecReq = + "GET /exec/ns/pod/ctr?command=hostname&output=1 HTTP/1.1\r\n" + "Connection: Upgrade\r\n" + "Upgrade: websocket\r\n" + "Sec-WebSocket-Protocol: v5.channel.k8s.io\r\n" + "\r\n"; + constexpr std::string_view kExecResp = + "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Protocol: v5.channel.k8s.io\r\n" + "\r\n"; + constexpr std::string_view kStdout = "\x82\x05\x01pod\n"sv; + + ConnTracker tracker; + tracker.InitProtocolState(); + tracker.AddControlEvent(event_gen_.InitConn()); + tracker.AddDataEvent(event_gen_.InitSendEvent(kExecReq)); + tracker.AddDataEvent( + event_gen_.InitRecvEvent(absl::StrCat(kExecResp, kStdout))); + tracker.AddControlEvent(event_gen_.InitClose()); + tracker.ProcessToRecords(); + ASSERT_TRUE(tracker.MaybeUpgradeToWebSocket()); + tracker.IterationPostTick(); + + std::vector first = tracker.ProcessToRecords(); + ASSERT_THAT(first, SizeIs(1)); + EXPECT_EQ(first[0].kind, websocket::RecordKind::kExec); + + std::vector second = tracker.ProcessToRecords(); + ASSERT_THAT(second, SizeIs(1)); + EXPECT_EQ(second[0].kind, websocket::RecordKind::kExit); + EXPECT_EQ(second[0].msg.payload, ""); + EXPECT_EQ(second[0].output, "pod\n"); + + EXPECT_THAT(tracker.ProcessToRecords(), IsEmpty()); +} + +TEST_F(ConnTrackerTest, TrackerWebSocketCloseAfterUpgradeIsRecorded) { + struct socket_control_event_t conn = event_gen_.InitConn(); + ConnTracker tracker; + tracker.InitProtocolState(); + tracker.AddControlEvent(conn); + tracker.AddDataEvent(event_gen_.InitSendEvent(kHTTPUpgradeReq)); + tracker.AddDataEvent(event_gen_.InitRecvEvent(kHTTPUpgradeResp)); + tracker.ProcessToRecords(); + ASSERT_TRUE(tracker.MaybeUpgradeToWebSocket()); + EXPECT_FALSE(tracker.protocol_state()->global.conn_closed); + + tracker.AddControlEvent(event_gen_.InitClose()); + + EXPECT_TRUE(tracker.protocol_state()->global.conn_closed); +} + TEST_F(ConnTrackerTest, TrackerHTTPUpgradeRejectedStaysHTTP) { constexpr std::string_view kRejectResp = "HTTP/1.1 403 Forbidden\r\n" diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc index 25d7092b53b..d8c7c6090b4 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc @@ -514,6 +514,54 @@ TEST(K8sExecTest, TarManifestIsBounded) { EXPECT_EQ(records[1].output_size, archive.size()); } +TEST(K8sExecTest, FinishFlushesSessionWithoutStatus) { + constexpr std::string_view kPath = + "/api/v1/namespaces/ns/pods/pod/exec?command=tar&command=cf&command=-&command=%2Ftmp&" + "stdout=true"; + const std::string archive = TarArchive({TarEntry("tmp/a", 0644, "a\n")}); + ExecState state; + std::vector records; + + DecodeK8sExec(kPath, {Out(5, absl::StrCat("\x01", archive))}, &state, &records); + FinishK8sExec(&state, &records); + FinishK8sExec(&state, &records); + + EXPECT_THAT(records, + ElementsAre(IsRecord(RecordKind::kExec, "tar cf - /tmp", ""), + IsRecord(RecordKind::kExit, "", "tmp/a mode=0644 size=2 head=\"a\\n\"\n"))); + EXPECT_EQ(records[1].msg.timestamp_ns, 5U); + EXPECT_EQ(records[1].output_size, archive.size()); +} + +TEST(K8sExecTest, FinishFlushesPendingTTYInput) { + ExecState state; + std::vector records; + + DecodeK8sExec(kKubeletTTYPath, + {Out(1, "\x01/ # "), In(2, "\x00id"sv), Out(3, "\x01id"), In(4, "\x00\r"sv), + Out(5, "\x01\r\nuid=0\r\n/ # ")}, + &state, &records); + FinishK8sExec(&state, &records); + + EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "sh", ""), + IsRecord(RecordKind::kInput, "id", "uid=0\n"), + IsRecord(RecordKind::kExit, "", ""))); +} + +TEST(K8sExecTest, FinishWithoutSessionOrAfterStatusIsNoop) { + ExecState idle; + std::vector records; + FinishK8sExec(&idle, &records); + EXPECT_THAT(records, IsEmpty()); + + ExecState done; + DecodeK8sExec(kKubeletTTYPath, {Out(1, "\x01/ # "), Out(2, absl::StrCat("\x03", kStatusSuccess))}, + &done, &records); + ASSERT_EQ(records.size(), 2U); + FinishK8sExec(&done, &records); + EXPECT_EQ(records.size(), 2U); +} + } // namespace websocket } // namespace protocols } // namespace stirling diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc index 043f48cbc59..d3af1a8a9f4 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc @@ -216,6 +216,40 @@ TEST_F(WebSocketStitcherTest, K8sExecSessionIsDecoded) { EXPECT_TRUE(resp_frames_.empty()); } +TEST_F(WebSocketStitcherTest, K8sSessionClosedWithoutStatusIsFlushedOnce) { + state_.global.subprotocol = "v5.channel.k8s.io"; + state_.global.path = "/api/v1/namespaces/ns/pods/pod/exec?command=hostname&stdout=true"; + state_.global.conn_closed = true; + resp_frames_.push_back(MakeFrame(Opcode::kBinary, true, "\x01pod\n", 7)); + + RecordsWithErrorCount first = Stitch(); + ASSERT_EQ(first.records.size(), 1U); + EXPECT_EQ(first.records[0].kind, RecordKind::kExec); + + RecordsWithErrorCount second = Stitch(); + ASSERT_EQ(second.records.size(), 1U); + EXPECT_EQ(second.records[0].kind, RecordKind::kExit); + EXPECT_EQ(second.records[0].msg.payload, ""); + EXPECT_EQ(second.records[0].msg.timestamp_ns, 7U); + EXPECT_EQ(second.records[0].output, "pod\n"); + EXPECT_EQ(second.records[0].subprotocol, "v5.channel.k8s.io"); + + EXPECT_TRUE(Stitch().records.empty()); +} + +TEST_F(WebSocketStitcherTest, K8sSessionWithStatusIsNotFlushedAgain) { + state_.global.subprotocol = "v5.channel.k8s.io"; + state_.global.path = "/api/v1/namespaces/ns/pods/pod/exec?command=hostname&stdout=true"; + state_.global.conn_closed = true; + resp_frames_.push_back(MakeFrame(Opcode::kBinary, true, "\x01pod\n", 1)); + resp_frames_.push_back( + MakeFrame(Opcode::kBinary, true, "\x03{\"metadata\":{},\"status\":\"Success\"}", 2)); + + ASSERT_EQ(Stitch().records.size(), 2U); + EXPECT_TRUE(Stitch().records.empty()); + EXPECT_TRUE(Stitch().records.empty()); +} + } // namespace websocket } // namespace protocols } // namespace stirling From a75b45992851b541ea057617c744d16769f21593 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 17:42:57 +0100 Subject: [PATCH 27/51] Flush Kubernetes exec sessions that close without a status Signed-off-by: entlein --- .../socket_tracer/conn_tracker.cc | 7 +++++ .../protocols/websocket/k8s_exec.cc | 29 ++++++++++++++----- .../protocols/websocket/k8s_exec.h | 2 ++ .../protocols/websocket/stitcher.cc | 5 ++++ .../socket_tracer/protocols/websocket/types.h | 4 +++ 5 files changed, 39 insertions(+), 8 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker.cc index 0b35536fad6..a2405b31247 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker.cc @@ -132,6 +132,12 @@ void ConnTracker::AddConnCloseEvent(const socket_control_event_t& event) { } state_ptr->global.conn_closed = true; } + if (protocol() == traffic_protocol_t::kProtocolWebSocket) { + auto* state_ptr = protocol_state(); + if (state_ptr != nullptr) { + state_ptr->global.conn_closed = true; + } + } send_data_.set_conn_closed(); recv_data_.set_conn_closed(); @@ -825,6 +831,7 @@ bool ConnTracker::MaybeUpgradeToWebSocket() { protocols::websocket::StateWrapper ws_state; ws_state.global.path = std::move(state->global.websocket_path); ws_state.global.subprotocol = std::move(state->global.websocket_subprotocol); + ws_state.global.conn_closed = state->global.conn_closed; CONN_TRACE(1) << "Protocol upgraded: HTTP->WebSocket"; upgraded_from_ = protocol_; diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc index ca69dfa861c..bb03ba4b81a 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc @@ -376,6 +376,17 @@ void EmitPending(ExecState* state, std::vector* records) { state->pending.reset(); } +void EmitExit(ExecState* state, uint64_t timestamp_ns, std::string status, + std::vector* records) { + EmitPending(state, records); + EmitStdin(state, records); + Record record = + MakeRecord(RecordKind::kExit, message_type_t::kResponse, timestamp_ns, std::move(status)); + TakeOutput(state, &record); + records->push_back(std::move(record)); + state->exited = true; +} + void SubmitLine(ExecState* state, std::string_view suffix, std::vector* records) { EmitPending(state, records); state->pending = PendingInput{state->line_timestamp_ns, absl::StrCat(state->line, suffix), @@ -488,6 +499,7 @@ void DecodeK8sExec(std::string_view path, std::vector messages, ExecSta if (IsControl(msg.opcode) || msg.payload.empty()) { continue; } + state->last_timestamp_ns = msg.timestamp_ns; if (!state->started) { state->started = true; state->tty = K8sExecTTY(path); @@ -530,21 +542,22 @@ void DecodeK8sExec(std::string_view path, std::vector messages, ExecSta state->echoed = true; } break; - case kStatusChannel: { - EmitPending(state, records); - EmitStdin(state, records); - Record record = MakeRecord(RecordKind::kExit, message_type_t::kResponse, msg.timestamp_ns, - std::string(data)); - TakeOutput(state, &record); - records->push_back(std::move(record)); + case kStatusChannel: + EmitExit(state, msg.timestamp_ns, std::string(data), records); break; - } default: break; } } } +void FinishK8sExec(ExecState* state, std::vector* records) { + if (!state->started || state->exited) { + return; + } + EmitExit(state, state->last_timestamp_ns, "", records); +} + } // namespace websocket } // namespace protocols } // namespace stirling diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h index a885e28b7af..e30d403f110 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h @@ -44,6 +44,8 @@ std::string Printable(std::string_view data); void DecodeK8sExec(std::string_view path, std::vector messages, ExecState* state, std::vector* records); +void FinishK8sExec(ExecState* state, std::vector* records); + } // namespace websocket } // namespace protocols } // namespace stirling diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc index bc583b86104..ac951152150 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc @@ -34,6 +34,7 @@ namespace websocket { namespace { constexpr uint8_t kRsv1 = 0x4; +constexpr uint32_t kStitchesBeforeCloseFlush = 2; constexpr std::string_view kCompressedPlaceholder = ""; Message StartMessage(message_type_t type, Frame* frame) { @@ -112,6 +113,10 @@ RecordsWithErrorCount StitchFrames(std::dequepath, std::move(messages), &global->exec, &result.records); + if (global->conn_closed && + ++global->stitches_since_close >= websocket::kStitchesBeforeCloseFlush) { + websocket::FinishK8sExec(&global->exec, &result.records); + } } else { for (websocket::Message& msg : messages) { if (msg.compressed) { diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h index 02ffcc18556..1df6e85c160 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h @@ -139,6 +139,8 @@ struct PendingInput { struct ExecState { bool started = false; + bool exited = false; + uint64_t last_timestamp_ns = 0; bool tty = false; bool last_cr = false; bool echoed = false; @@ -157,6 +159,8 @@ struct ExecState { struct State { std::string path; std::string subprotocol; + bool conn_closed = false; + uint32_t stitches_since_close = 0; ExecState exec; }; From c8edd778d882700577f39d4143d3d929d17253c4 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 16:47:13 +0000 Subject: [PATCH 28/51] format Signed-off-by: entlein --- .../source_connectors/socket_tracer/conn_tracker_test.cc | 3 +-- .../socket_tracer/protocols/websocket/k8s_exec_test.cc | 6 +++--- .../socket_tracer/websocket_trace_bpf_test.cc | 3 ++- .../testing/demo_apps/go_websocket/client/BUILD.bazel | 1 - .../testing/demo_apps/go_websocket/server/BUILD.bazel | 1 - 5 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc index fb22fe9cd73..325cb1ed701 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc @@ -459,8 +459,7 @@ TEST_F(ConnTrackerTest, TrackerWebSocketSessionClosedWithoutStatusIsFlushed) { tracker.InitProtocolState(); tracker.AddControlEvent(event_gen_.InitConn()); tracker.AddDataEvent(event_gen_.InitSendEvent(kExecReq)); - tracker.AddDataEvent( - event_gen_.InitRecvEvent(absl::StrCat(kExecResp, kStdout))); + tracker.AddDataEvent(event_gen_.InitRecvEvent(absl::StrCat(kExecResp, kStdout))); tracker.AddControlEvent(event_gen_.InitClose()); tracker.ProcessToRecords(); ASSERT_TRUE(tracker.MaybeUpgradeToWebSocket()); diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc index d8c7c6090b4..6c0c9238588 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc @@ -526,9 +526,9 @@ TEST(K8sExecTest, FinishFlushesSessionWithoutStatus) { FinishK8sExec(&state, &records); FinishK8sExec(&state, &records); - EXPECT_THAT(records, - ElementsAre(IsRecord(RecordKind::kExec, "tar cf - /tmp", ""), - IsRecord(RecordKind::kExit, "", "tmp/a mode=0644 size=2 head=\"a\\n\"\n"))); + EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "tar cf - /tmp", ""), + IsRecord(RecordKind::kExit, "", + "tmp/a mode=0644 size=2 head=\"a\\n\"\n"))); EXPECT_EQ(records[1].msg.timestamp_ns, 5U); EXPECT_EQ(records[1].output_size, archive.size()); } diff --git a/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc b/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc index 82b59994c11..6a44380f3be 100644 --- a/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc +++ b/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc @@ -37,7 +37,8 @@ using ::px::stirling::testing::FindRecordIdxMatchesPID; using ::testing::Each; using ::testing::IsSupersetOf; -class WebSocketTraceTest : public testing::SocketTraceBPFTestFixture { +class WebSocketTraceTest + : public testing::SocketTraceBPFTestFixture { protected: WebSocketTraceTest() { FLAGS_stirling_enable_websocket_tracing = TraceMode::On; diff --git a/src/stirling/testing/demo_apps/go_websocket/client/BUILD.bazel b/src/stirling/testing/demo_apps/go_websocket/client/BUILD.bazel index 0f92be59f7c..4afe0b64262 100644 --- a/src/stirling/testing/demo_apps/go_websocket/client/BUILD.bazel +++ b/src/stirling/testing/demo_apps/go_websocket/client/BUILD.bazel @@ -14,7 +14,6 @@ # # SPDX-License-Identifier: Apache-2.0 - load("@io_bazel_rules_go//go:def.bzl", "go_library") load("//bazel:pl_build_system.bzl", "pl_go_binary", "pl_go_image") diff --git a/src/stirling/testing/demo_apps/go_websocket/server/BUILD.bazel b/src/stirling/testing/demo_apps/go_websocket/server/BUILD.bazel index f8c3f144b05..63cc86735e4 100644 --- a/src/stirling/testing/demo_apps/go_websocket/server/BUILD.bazel +++ b/src/stirling/testing/demo_apps/go_websocket/server/BUILD.bazel @@ -14,7 +14,6 @@ # # SPDX-License-Identifier: Apache-2.0 - load("@io_bazel_rules_docker//container:container.bzl", "container_image") load("@io_bazel_rules_go//go:def.bzl", "go_library") load("//bazel:pl_build_system.bzl", "pl_go_binary") From 15460376dc70092533b20c9317011d270914b509 Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 17:53:19 +0100 Subject: [PATCH 29/51] Check the HTTP upgrade and trace the server in the WebSocket BPF test Signed-off-by: entlein --- .../socket_tracer/websocket_trace_bpf_test.cc | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc b/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc index 6a44380f3be..8749ef83337 100644 --- a/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc +++ b/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -35,6 +36,7 @@ namespace stirling { using ::px::stirling::testing::FindRecordIdxMatchesPID; using ::testing::Each; +using ::testing::ElementsAre; using ::testing::IsSupersetOf; class WebSocketTraceTest @@ -60,15 +62,26 @@ std::string Row(const types::ColumnWrapperRecordBatch& records, size_t i) { } TEST_F(WebSocketTraceTest, PlainAndTLSEchoSessions) { + PX_SET_FOR_SCOPE(FLAGS_stirling_conn_trace_pid, server_.process_pid()); StartTransferDataThread(); PX_CHECK_OK(client_.Run(std::chrono::seconds{10}, {absl::Substitute("--network=container:$0", server_.container_name())}, {"--iters=2"})); client_.Wait(); + std::this_thread::sleep_for(5 * kTransferDataPeriod); StopTransferDataThread(); + std::vector http_tablets = ConsumeRecords(SocketTraceConnector::kHTTPTableNum); + ASSERT_NOT_EMPTY_AND_GET_RECORDS(const types::ColumnWrapperRecordBatch& http_batch, http_tablets); + std::vector upgrades; + for (size_t i : FindRecordIdxMatchesPID(http_batch, kHTTPUPIDIdx, server_.process_pid())) { + upgrades.push_back(absl::Substitute("$0 $1", http_batch[kHTTPReqPathIdx]->Get(i), + http_batch[kHTTPRespStatusIdx]->Get(i).val)); + } + ASSERT_THAT(upgrades, ElementsAre("/echo 101", "/echo 101")); + std::vector tablets = ConsumeRecords(SocketTraceConnector::kWebSocketTableNum); ASSERT_NOT_EMPTY_AND_GET_RECORDS(const types::ColumnWrapperRecordBatch& record_batch, tablets); From 3ee7495ba4c273d5855b16d3a8a36c9f7865db7d Mon Sep 17 00:00:00 2001 From: entlein Date: Thu, 19 Nov 2026 18:38:37 +0000 Subject: [PATCH 30/51] format Signed-off-by: entlein --- .../socket_tracer/websocket_trace_bpf_test.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc b/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc index 8749ef83337..19a02b69365 100644 --- a/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc +++ b/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc @@ -77,8 +77,9 @@ TEST_F(WebSocketTraceTest, PlainAndTLSEchoSessions) { ASSERT_NOT_EMPTY_AND_GET_RECORDS(const types::ColumnWrapperRecordBatch& http_batch, http_tablets); std::vector upgrades; for (size_t i : FindRecordIdxMatchesPID(http_batch, kHTTPUPIDIdx, server_.process_pid())) { - upgrades.push_back(absl::Substitute("$0 $1", http_batch[kHTTPReqPathIdx]->Get(i), - http_batch[kHTTPRespStatusIdx]->Get(i).val)); + upgrades.push_back( + absl::Substitute("$0 $1", http_batch[kHTTPReqPathIdx]->Get(i), + http_batch[kHTTPRespStatusIdx]->Get(i).val)); } ASSERT_THAT(upgrades, ElementsAre("/echo 101", "/echo 101")); From d981d7d49d698a25876472a47a2836d873c50314 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 01:53:01 +0100 Subject: [PATCH 31/51] Test that credentials are redacted before they reach tables Signed-off-by: entlein --- .../socket_tracer/protocols/http/BUILD.bazel | 8 + .../protocols/http/credentials.cc | 39 ++++ .../protocols/http/credentials.h | 52 +++++ .../protocols/http/credentials_test.cc | 177 ++++++++++++++++++ .../socket_trace_connector_test.cc | 46 +++++ 5 files changed, 322 insertions(+) create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/http/credentials.h create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/BUILD.bazel b/src/stirling/source_connectors/socket_tracer/protocols/http/BUILD.bazel index 883e2672b4f..636526858c3 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/BUILD.bazel +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/BUILD.bazel @@ -61,6 +61,14 @@ pl_cc_binary( ], ) +pl_cc_test( + name = "credentials_test", + srcs = ["credentials_test.cc"], + deps = [ + ":cc_library", + ], +) + pl_cc_test( name = "parse_test", srcs = ["parse_test.cc"], diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc new file mode 100644 index 00000000000..f75b439e7f4 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc @@ -0,0 +1,39 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "src/stirling/source_connectors/socket_tracer/protocols/http/credentials.h" + +namespace px { +namespace stirling { +namespace protocols { +namespace http { + +std::string CredentialFingerprint(std::string_view) { return ""; } + +std::optional RedactCredentialHeader(std::string_view, std::string_view) { + return std::nullopt; +} + +std::string RedactCredentialPath(std::string_view path) { return std::string(path); } + +std::string RedactCredentialBody(std::string_view body) { return std::string(body); } + +} // namespace http +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.h b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.h new file mode 100644 index 00000000000..6737e3de2b8 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.h @@ -0,0 +1,52 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include +#include + +namespace px { +namespace stirling { +namespace protocols { +namespace http { + +std::string CredentialFingerprint(std::string_view secret); + +std::optional RedactCredentialHeader(std::string_view name, std::string_view value); + +std::string RedactCredentialPath(std::string_view path); + +std::string RedactCredentialBody(std::string_view body); + +template +void RedactCredentials(THeaders* headers) { + for (auto& [name, value] : *headers) { + std::optional redacted = RedactCredentialHeader(name, value); + if (redacted.has_value()) { + value = std::move(redacted.value()); + } + } +} + +} // namespace http +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc new file mode 100644 index 00000000000..25f6bd32de3 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc @@ -0,0 +1,177 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "src/stirling/source_connectors/socket_tracer/protocols/http/credentials.h" + +#include +#include + +#include +#include + +#include "src/common/testing/testing.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/http/types.h" + +namespace px { +namespace stirling { +namespace protocols { +namespace http { + +std::string Redacted(std::string_view secret) { + return absl::StrCat(""); +} + +std::string Jwt(std::string_view header, std::string_view payload) { + return absl::StrCat(absl::WebSafeBase64Escape(header), ".", absl::WebSafeBase64Escape(payload), + ".c2lnbmF0dXJl"); +} + +TEST(CredentialsTest, FingerprintIsSha256Prefix) { + EXPECT_EQ(CredentialFingerprint("abc"), "ba7816bf8f01cfea"); +} + +TEST(CredentialsTest, BearerJwtKeepsClaimsAndDropsToken) { + const std::string token = + Jwt(R"({"alg":"RS256","kid":"k1"})", + R"({"iss":"https://kubernetes.default.svc","sub":"system:serviceaccount:credscope:sa-over",)" + R"("aud":["https://kubernetes.default.svc"],"exp":1763600000,"iat":1763599400,)" + R"("kubernetes.io":{"namespace":"credscope"},"canary":"cs-canary-1"})"); + + std::optional redacted = + RedactCredentialHeader("Authorization", absl::StrCat("Bearer ", token)); + + ASSERT_TRUE(redacted.has_value()); + EXPECT_EQ(redacted.value(), + absl::StrCat("Bearer )")); +} + +TEST(CredentialsTest, OauthScopesAreKept) { + const std::string token = + Jwt(R"({"alg":"ES256"})", + R"({"iss":"https://idp","sub":"orders-client","azp":"orders","client_id":"orders",)" + R"("scope":"orders:read admin","scp":["orders:read"],"nbf":1,"exp":2})"); + + EXPECT_EQ(RedactCredentialHeader("authorization", absl::StrCat("bearer ", token)), + absl::StrCat("bearer )")); +} + +TEST(CredentialsTest, OpaqueBearerIsFingerprinted) { + EXPECT_EQ(RedactCredentialHeader("Authorization", "Bearer sk-canary-123"), + absl::StrCat("Bearer ", Redacted("sk-canary-123"))); +} + +TEST(CredentialsTest, MalformedJwtIsFingerprinted) { + EXPECT_EQ(RedactCredentialHeader("Authorization", "Bearer a.b.c"), + absl::StrCat("Bearer ", Redacted("a.b.c"))); +} + +TEST(CredentialsTest, BasicKeepsUser) { + const std::string encoded = absl::Base64Escape("alice:cs-canary-2"); + EXPECT_EQ(RedactCredentialHeader("Proxy-Authorization", absl::StrCat("Basic ", encoded)), + absl::StrCat("Basic ")); +} + +TEST(CredentialsTest, SchemelessValueIsFingerprinted) { + EXPECT_EQ(RedactCredentialHeader("Authorization", "cs-canary-3"), Redacted("cs-canary-3")); +} + +TEST(CredentialsTest, ApiKeyHeadersAreFingerprinted) { + EXPECT_EQ(RedactCredentialHeader("X-Api-Key", "cs-canary-4"), Redacted("cs-canary-4")); + EXPECT_EQ(RedactCredentialHeader("x-auth-token", "cs-canary-5"), Redacted("cs-canary-5")); +} + +TEST(CredentialsTest, CookieValuesAreFingerprinted) { + EXPECT_EQ(RedactCredentialHeader("Cookie", "theme=dark; session=cs-canary-6"), + absl::StrCat("theme=", Redacted("dark"), "; session=", Redacted("cs-canary-6"))); +} + +TEST(CredentialsTest, SetCookieKeepsAttributes) { + EXPECT_EQ(RedactCredentialHeader("Set-Cookie", "session=cs-canary-7; Path=/; HttpOnly"), + absl::StrCat("session=", Redacted("cs-canary-7"), "; Path=/; HttpOnly")); +} + +TEST(CredentialsTest, OtherHeadersAreKept) { + EXPECT_EQ(RedactCredentialHeader("Content-Type", "application/json"), std::nullopt); + EXPECT_EQ(RedactCredentialHeader("Audit-Id", "6f1c"), std::nullopt); +} + +TEST(CredentialsTest, QueryCredentialsAreFingerprinted) { + EXPECT_EQ(RedactCredentialPath("/ws?room=1&access_token=cs-canary-8&API_KEY=cs-canary-9#frag"), + absl::StrCat("/ws?room=1&access_token=", Redacted("cs-canary-8"), + "&API_KEY=", Redacted("cs-canary-9"), "#frag")); + EXPECT_EQ(RedactCredentialPath("/api/v1/pods?watch=1"), "/api/v1/pods?watch=1"); +} + +TEST(CredentialsTest, UrlHeadersAreRedacted) { + EXPECT_EQ(RedactCredentialHeader("Referer", "https://app/cb?code=1&id_token=cs-canary-10"), + absl::StrCat("https://app/cb?code=1&id_token=", Redacted("cs-canary-10"))); +} + +TEST(CredentialsTest, JsonFieldsAreFingerprinted) { + EXPECT_EQ(RedactCredentialBody( + R"({"token_type":"Bearer","access_token":"cs-canary-11","expires_in":600,)" + R"("Password" : "a\"b"})"), + absl::StrCat(R"({"token_type":"Bearer","access_token":")", Redacted("cs-canary-11"), + R"(","expires_in":600,"Password" : ")", Redacted(R"(a\"b)"), R"("})")); +} + +TEST(CredentialsTest, TruncatedJsonFieldIsFingerprinted) { + EXPECT_EQ(RedactCredentialBody(R"({"refresh_token":"cs-canary-1)"), + absl::StrCat(R"({"refresh_token":")", Redacted("cs-canary-1"))); +} + +TEST(CredentialsTest, TextProtoFieldsAreFingerprinted) { + EXPECT_EQ(RedactCredentialBody(R"(client_secret: "cs-canary-12" name: "x")"), + absl::StrCat(R"(client_secret: ")", Redacted("cs-canary-12"), R"(" name: "x")")); +} + +TEST(CredentialsTest, FormFieldsAreFingerprinted) { + EXPECT_EQ(RedactCredentialBody("grant_type=client_credentials&client_secret=cs-canary-13"), + absl::StrCat("grant_type=client_credentials&client_secret=", Redacted("cs-canary-13"))); +} + +TEST(CredentialsTest, NonCredentialFieldsAreKept) { + EXPECT_EQ(RedactCredentialBody(R"({"tokens":3,"user":"bob","my_password_hint":"x"})"), + R"({"tokens":3,"user":"bob","my_password_hint":"x"})"); +} + +TEST(CredentialsTest, HeaderMapsAreRedacted) { + HeadersMap headers = {{"Authorization", "Bearer cs-canary-14"}, {"Accept", "*/*"}}; + RedactCredentials(&headers); + EXPECT_EQ(headers.find("authorization")->second, absl::StrCat("Bearer ", Redacted("cs-canary-14"))); + EXPECT_EQ(headers.find("accept")->second, "*/*"); + + std::multimap nv = {{":path", "/svc.Orders/Get?token=cs-canary-15"}, + {"authorization", "Bearer cs-canary-16"}}; + RedactCredentials(&nv); + EXPECT_EQ(nv.find(":path")->second, + absl::StrCat("/svc.Orders/Get?token=", Redacted("cs-canary-15"))); + EXPECT_EQ(nv.find("authorization")->second, absl::StrCat("Bearer ", Redacted("cs-canary-16"))); +} + +} // namespace http +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc index af9d29c111d..b8760564df7 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc @@ -43,7 +43,10 @@ namespace stirling { namespace http = protocols::http; +using ::testing::AllOf; using ::testing::ElementsAre; +using ::testing::HasSubstr; +using ::testing::Not; using ::px::stirling::testing::RecordBatchSizeIs; @@ -226,6 +229,41 @@ TEST_F(SocketTraceConnectorTest, Basic) { EXPECT_THAT(ToStringVector(records[kHTTPRespBodyIdx]), ElementsAre("foo")); } +TEST_F(SocketTraceConnectorTest, HTTPCredentialsAreRedacted) { + const std::string_view kCredReq = + "POST /login?access_token=cs-canary-20 HTTP/1.1\r\n" + "Host: auth\r\n" + "Authorization: Bearer cs-canary-21\r\n" + "Content-Type: application/json\r\n" + "Content-Length: 27\r\n" + "\r\n" + "{\"password\":\"cs-canary-22\"}"; + const std::string_view kCredResp = + "HTTP/1.1 200 OK\r\n" + "Content-Type: application/json\r\n" + "Set-Cookie: session=cs-canary-23; HttpOnly\r\n" + "Content-Length: 31\r\n" + "\r\n" + "{\"access_token\":\"cs-canary-24\"}"; + + source_->AcceptControlEvent(event_gen_.InitConn()); + source_->AcceptDataEvent(event_gen_.InitSendEvent(kCredReq)); + source_->AcceptDataEvent(event_gen_.InitRecvEvent(kCredResp)); + source_->AcceptControlEvent(event_gen_.InitClose()); + + connector_->TransferData(ctx_.get()); + + std::vector tablets = http_table_->ConsumeRecords(); + ASSERT_NOT_EMPTY_AND_GET_RECORDS(RecordBatch & records, tablets); + ASSERT_THAT(records, RecordBatchSizeIs(1)); + for (int idx : {kHTTPReqHeadersIdx, kHTTPReqPathIdx, kHTTPReqBodyIdx, kHTTPRespHeadersIdx, + kHTTPRespBodyIdx}) { + EXPECT_THAT(ToStringVector(records[idx]), ElementsAre(Not(HasSubstr("cs-canary")))); + } + EXPECT_THAT(ToStringVector(records[kHTTPReqHeadersIdx]), + ElementsAre(HasSubstr("Bearer (records[kWebSocketPayloadSizeIdx]), ElementsAre(2, 5)); } +TEST_F(SocketTraceConnectorWebSocketTest, TextPayloadCredentialsAreRedacted) { + RecordBatch records = TransferUpgradedServerFrames( + absl::StrCat("\x81\x18", R"({"token":"cs-canary-25"})")); + ASSERT_THAT(records, RecordBatchSizeIs(1)); + EXPECT_THAT(ToStringVector(records[kWebSocketPayloadIdx]), + ElementsAre(AllOf(HasSubstr(" Date: Fri, 20 Nov 2026 01:55:28 +0100 Subject: [PATCH 32/51] Redact credentials in HTTP and WebSocket rows Signed-off-by: entlein --- .../socket_tracer/protocols/http/BUILD.bazel | 2 + .../protocols/http/credentials.cc | 234 +++++++++++++++++- .../socket_tracer/socket_trace_connector.cc | 30 ++- 3 files changed, 256 insertions(+), 10 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/BUILD.bazel b/src/stirling/source_connectors/socket_tracer/protocols/http/BUILD.bazel index 636526858c3..e772c105ae2 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/BUILD.bazel +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/BUILD.bazel @@ -39,7 +39,9 @@ pl_cc_library( "//src/common/zlib:cc_library", "//src/stirling/source_connectors/socket_tracer/protocols/common:cc_library", "//src/stirling/utils:cc_library", + "@boringssl//:crypto", "@com_github_h2o_picohttpparser//:picohttpparser", + "@com_github_tencent_rapidjson//:rapidjson", ], ) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc index f75b439e7f4..0e67cfdac14 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc @@ -18,20 +18,246 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/http/credentials.h" +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + namespace px { namespace stirling { namespace protocols { namespace http { -std::string CredentialFingerprint(std::string_view) { return ""; } +namespace { + +constexpr size_t kFingerprintBytes = 8; +constexpr std::array kAuthorizationHeaders = {"authorization", + "proxy-authorization"}; +constexpr std::array kTokenHeaders = {"x-api-key", "x-auth-token", "api-key"}; +constexpr std::array kUrlHeaders = {":path", "referer", "location"}; +constexpr std::array kCredentialFields = { + "access_token", "id_token", "refresh_token", "token", "api_key", + "apikey", "client_secret", "password", "secret"}; +constexpr std::array kJwtClaims = { + "iss", "sub", "aud", "azp", "client_id", "scope", "scp", "exp", "iat", "nbf", "kubernetes.io"}; + +template +bool Contains(const std::array& names, std::string_view name) { + return std::any_of(names.begin(), names.end(), + [name](std::string_view n) { return absl::EqualsIgnoreCase(n, name); }); +} + +std::string Marker(std::string_view secret, std::string_view details = "") { + return absl::StrCat(""); +} + +bool DecodeJwtPart(std::string_view part, rapidjson::Document* doc) { + std::string json; + if (!absl::WebSafeBase64Unescape(part, &json)) { + return false; + } + doc->Parse(json.data(), json.size()); + return !doc->HasParseError() && doc->IsObject(); +} + +std::optional JwtClaims(std::string_view token) { + std::vector parts = absl::StrSplit(token, '.'); + rapidjson::Document header; + rapidjson::Document payload; + if (parts.size() != 3 || !DecodeJwtPart(parts[0], &header) || + !DecodeJwtPart(parts[1], &payload)) { + return std::nullopt; + } + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + writer.StartObject(); + auto alg = header.FindMember("alg"); + if (alg != header.MemberEnd()) { + writer.Key("alg"); + alg->value.Accept(writer); + } + for (std::string_view claim : kJwtClaims) { + auto it = payload.FindMember(rapidjson::StringRef(claim.data(), claim.size())); + if (it != payload.MemberEnd()) { + writer.Key(claim.data(), claim.size()); + it->value.Accept(writer); + } + } + writer.EndObject(); + return std::string(buffer.GetString(), buffer.GetSize()); +} + +std::string RedactAuthorization(std::string_view value) { + std::string_view trimmed = absl::StripAsciiWhitespace(value); + const size_t space = trimmed.find(' '); + if (space == std::string_view::npos) { + return Marker(trimmed); + } + std::string_view scheme = trimmed.substr(0, space); + std::string_view credential = absl::StripLeadingAsciiWhitespace(trimmed.substr(space + 1)); + std::string details; + if (absl::EqualsIgnoreCase(scheme, "bearer")) { + std::optional claims = JwtClaims(credential); + if (claims.has_value()) { + details = absl::StrCat(" jwt=", claims.value()); + } + } else if (absl::EqualsIgnoreCase(scheme, "basic")) { + std::string decoded; + if (absl::Base64Unescape(credential, &decoded)) { + const size_t colon = decoded.find(':'); + if (colon != std::string::npos) { + details = absl::StrCat(" user=", decoded.substr(0, colon)); + } + } + } + return absl::StrCat(scheme, " ", Marker(credential, details)); +} + +std::string RedactCookie(std::string_view cookie) { + std::string_view pair = absl::StripLeadingAsciiWhitespace(cookie); + const size_t eq = pair.find('='); + if (eq == std::string_view::npos) { + return std::string(pair); + } + return absl::StrCat(pair.substr(0, eq + 1), Marker(pair.substr(eq + 1))); +} + +std::string RedactCookies(std::string_view value) { + std::vector cookies; + for (std::string_view cookie : absl::StrSplit(value, ';')) { + cookies.push_back(RedactCookie(cookie)); + } + return absl::StrJoin(cookies, "; "); +} + +std::string RedactSetCookie(std::string_view value) { + const size_t attributes = std::min(value.find(';'), value.size()); + return absl::StrCat(RedactCookie(value.substr(0, attributes)), value.substr(attributes)); +} + +std::string RedactParams(std::string_view params) { + std::vector pairs; + for (std::string_view pair : absl::StrSplit(params, '&')) { + const size_t eq = pair.find('='); + if (eq != std::string_view::npos && Contains(kCredentialFields, pair.substr(0, eq))) { + pairs.push_back(absl::StrCat(pair.substr(0, eq + 1), Marker(pair.substr(eq + 1)))); + } else { + pairs.emplace_back(pair); + } + } + return absl::StrJoin(pairs, "&"); +} + +bool IsNameChar(char c) { return absl::ascii_isalnum(c) || c == '_' || c == '-' || c == '.'; } + +size_t SkipSpaces(std::string_view text, size_t pos) { + while (pos < text.size() && absl::ascii_isspace(text[pos])) { + ++pos; + } + return pos; +} + +std::string RedactCredentialFields(std::string_view text) { + std::string out; + size_t copied = 0; + size_t i = 0; + while (i < text.size()) { + if (!IsNameChar(text[i]) || (i > 0 && IsNameChar(text[i - 1]))) { + ++i; + continue; + } + size_t end = i; + while (end < text.size() && IsNameChar(text[end])) { + ++end; + } + if (!Contains(kCredentialFields, text.substr(i, end - i))) { + i = end; + continue; + } + size_t pos = end < text.size() && text[end] == '"' ? end + 1 : end; + pos = SkipSpaces(text, pos); + if (pos >= text.size() || text[pos] != ':') { + i = end; + continue; + } + pos = SkipSpaces(text, pos + 1); + if (pos >= text.size() || text[pos] != '"') { + i = end; + continue; + } + const size_t begin = pos + 1; + size_t close = begin; + while (close < text.size() && text[close] != '"') { + close += text[close] == '\\' ? 2 : 1; + } + close = std::min(close, text.size()); + absl::StrAppend(&out, text.substr(copied, begin - copied), + Marker(text.substr(begin, close - begin))); + copied = close; + i = close; + } + absl::StrAppend(&out, text.substr(copied)); + return out; +} + +} // namespace -std::optional RedactCredentialHeader(std::string_view, std::string_view) { +std::string CredentialFingerprint(std::string_view secret) { + std::array digest; + SHA256(reinterpret_cast(secret.data()), secret.size(), digest.data()); + return absl::BytesToHexString( + std::string_view(reinterpret_cast(digest.data()), kFingerprintBytes)); +} + +std::optional RedactCredentialHeader(std::string_view name, std::string_view value) { + if (Contains(kAuthorizationHeaders, name)) { + return RedactAuthorization(value); + } + if (Contains(kTokenHeaders, name)) { + return Marker(value); + } + if (absl::EqualsIgnoreCase(name, "cookie")) { + return RedactCookies(value); + } + if (absl::EqualsIgnoreCase(name, "set-cookie")) { + return RedactSetCookie(value); + } + if (Contains(kUrlHeaders, name)) { + return RedactCredentialPath(value); + } return std::nullopt; } -std::string RedactCredentialPath(std::string_view path) { return std::string(path); } +std::string RedactCredentialPath(std::string_view path) { + const size_t query = path.find('?'); + if (query == std::string_view::npos) { + return std::string(path); + } + const size_t fragment = std::min(path.find('#', query), path.size()); + return absl::StrCat(path.substr(0, query + 1), + RedactParams(path.substr(query + 1, fragment - query - 1)), + path.substr(fragment)); +} -std::string RedactCredentialBody(std::string_view body) { return std::string(body); } +std::string RedactCredentialBody(std::string_view body) { + if (body.find('"') == std::string_view::npos) { + return RedactParams(body); + } + return RedactCredentialFields(body); +} } // namespace http } // namespace protocols diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index 18299d7b340..568b5c609c1 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -24,6 +24,7 @@ #include #include +#include #include #include @@ -45,6 +46,7 @@ #include "src/stirling/source_connectors/socket_tracer/bcc_bpf_intf/socket_trace.hpp" #include "src/stirling/source_connectors/socket_tracer/conn_stats.h" #include "src/stirling/source_connectors/socket_tracer/proto/sock_event.pb.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/http/credentials.h" #include "src/stirling/source_connectors/socket_tracer/protocols/http/utils.h" #include "src/stirling/source_connectors/socket_tracer/protocols/http2/grpc.h" #include "src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.h" @@ -1340,6 +1342,16 @@ int64_t AMQPCalculateLatency(const int64_t req_timestamp_ns, const int64_t resp_ return latency_ns; } +constexpr size_t kRedactedSize = std::numeric_limits::max(); + +std::string RedactedBody(std::string_view body) { + if (body.size() <= FLAGS_max_body_bytes) { + return protocols::http::RedactCredentialBody(body); + } + return absl::StrCat(protocols::http::RedactCredentialBody(body.substr(0, FLAGS_max_body_bytes)), + DataTable::kTruncatedMsg); +} + template std::string PXInfoString(const ConnTracker& conn_tracker, const TRecordType& record) { return absl::Substitute("conn_tracker=$0 record=$1", conn_tracker.ToString(), record.ToString()); @@ -1357,6 +1369,8 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke // Note that we do this after filtering to avoid burning CPU cycles unnecessarily. protocols::http::PreProcessRespMessage(&resp_message); protocols::http::PreProcessReqMessage(&req_message); + protocols::http::RedactCredentials(&req_message.headers); + protocols::http::RedactCredentials(&resp_message.headers); md::UPID upid(ctx->GetASID(), conn_tracker.conn_id().upid.pid, conn_tracker.conn_id().upid.start_time_ticks); @@ -1382,14 +1396,14 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke r.Append(static_cast(content_type)); r.Append(ToJSONString(req_message.headers), kMaxHTTPHeadersBytes); r.Append(std::move(req_message.req_method)); - r.Append(std::move(req_message.req_path)); + r.Append(protocols::http::RedactCredentialPath(req_message.req_path)); r.Append(req_message.body_size); - r.Append(std::move(req_message.body), FLAGS_max_body_bytes); + r.Append(RedactedBody(req_message.body), kRedactedSize); r.Append(ToJSONString(resp_message.headers), kMaxHTTPHeadersBytes); r.Append(resp_message.resp_status); r.Append(std::move(resp_message.resp_message)); r.Append(resp_message.body_size); - r.Append(std::move(resp_message.body), FLAGS_max_body_bytes); + r.Append(RedactedBody(resp_message.body), kRedactedSize); r.Append( CalculateLatency(req_message.timestamp_ns, resp_message.timestamp_ns)); #ifndef NDEBUG @@ -1424,6 +1438,8 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke md::UPID upid(ctx->GetASID(), conn_tracker.conn_id().upid.pid, conn_tracker.conn_id().upid.start_time_ticks); + protocols::http::RedactCredentials(req_stream->mutable_headers()); + protocols::http::RedactCredentials(resp_stream->mutable_headers()); std::string path = req_stream->headers().ValueByKey(protocols::http2::headers::kPath); HTTPContentType content_type = HTTPContentType::kUnknown; @@ -1458,9 +1474,11 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke // Do not apply truncation at this point, as the truncation was already done on serialized // protobuf message. This might result into longer text format data here, but the increase is // minimal. - r.Append(req_stream->ConsumeData()); + r.Append( + protocols::http::RedactCredentialBody(req_stream->ConsumeData())); r.Append(resp_stream->original_data_size()); - r.Append(resp_stream->ConsumeData()); + r.Append( + protocols::http::RedactCredentialBody(resp_stream->ConsumeData())); int64_t latency_ns = CalculateLatency(req_stream->timestamp_ns, resp_stream->timestamp_ns); r.Append(latency_ns); // TODO(yzhao): Remove once http2::Record::bpf_timestamp_ns is removed. @@ -1815,7 +1833,7 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke }; if (record.kind == protocols::websocket::RecordKind::kFrame && msg.opcode == protocols::websocket::Opcode::kText) { - r.Append(std::move(msg.payload), FLAGS_max_body_bytes); + r.Append(RedactedBody(msg.payload), kRedactedSize); } else { r.Append(printable(msg.payload), FLAGS_max_body_bytes); } From 347b85fae016c94ab108ae1498a7f3e8e5e45765 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 01:55:36 +0100 Subject: [PATCH 33/51] Test that bearer tokens in WebSocket subprotocols are redacted Signed-off-by: entlein --- .../protocols/http/credentials_test.cc | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc index 25f6bd32de3..65894c6917f 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc @@ -112,6 +112,20 @@ TEST(CredentialsTest, SetCookieKeepsAttributes) { absl::StrCat("session=", Redacted("cs-canary-7"), "; Path=/; HttpOnly")); } +TEST(CredentialsTest, WebSocketBearerSubprotocolIsRedacted) { + const std::string token = Jwt(R"({"alg":"RS256"})", R"({"sub":"system:serviceaccount:a:b"})"); + const std::string encoded = absl::WebSafeBase64Escape(token); + EXPECT_EQ( + RedactCredentialHeader("Sec-WebSocket-Protocol", + absl::StrCat("v5.channel.k8s.io, base64url.bearer.authorization.k8s.io.", + encoded)), + absl::StrCat("v5.channel.k8s.io, base64url.bearer.authorization.k8s.io.)")); + EXPECT_EQ(RedactCredentialHeader("sec-websocket-protocol", "v4.channel.k8s.io"), + "v4.channel.k8s.io"); +} + TEST(CredentialsTest, OtherHeadersAreKept) { EXPECT_EQ(RedactCredentialHeader("Content-Type", "application/json"), std::nullopt); EXPECT_EQ(RedactCredentialHeader("Audit-Id", "6f1c"), std::nullopt); From 3db81b1d7375253ea6da0f11d2dc262ca8fe1c58 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 01:55:47 +0100 Subject: [PATCH 34/51] Redact bearer tokens in WebSocket subprotocols Signed-off-by: entlein --- .../protocols/http/credentials.cc | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc index 0e67cfdac14..97e9b2d019b 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc @@ -48,6 +48,7 @@ constexpr std::array kAuthorizationHeaders = {"authorizatio "proxy-authorization"}; constexpr std::array kTokenHeaders = {"x-api-key", "x-auth-token", "api-key"}; constexpr std::array kUrlHeaders = {":path", "referer", "location"}; +constexpr std::string_view kBearerSubprotocol = "base64url.bearer.authorization.k8s.io."; constexpr std::array kCredentialFields = { "access_token", "id_token", "refresh_token", "token", "api_key", "apikey", "client_secret", "password", "secret"}; @@ -126,6 +127,27 @@ std::string RedactAuthorization(std::string_view value) { return absl::StrCat(scheme, " ", Marker(credential, details)); } +std::string RedactSubprotocols(std::string_view value) { + std::vector protocols; + for (std::string_view protocol : absl::StrSplit(value, ',')) { + const size_t start = protocol.find(kBearerSubprotocol); + if (start == std::string_view::npos) { + protocols.emplace_back(protocol); + continue; + } + std::string_view encoded = protocol.substr(start + kBearerSubprotocol.size()); + std::string token; + std::optional claims; + if (absl::WebSafeBase64Unescape(encoded, &token)) { + claims = JwtClaims(token); + } + protocols.push_back(absl::StrCat( + protocol.substr(0, start + kBearerSubprotocol.size()), + Marker(encoded, claims.has_value() ? absl::StrCat(" jwt=", claims.value()) : ""))); + } + return absl::StrJoin(protocols, ","); +} + std::string RedactCookie(std::string_view cookie) { std::string_view pair = absl::StripLeadingAsciiWhitespace(cookie); const size_t eq = pair.find('='); @@ -235,6 +257,9 @@ std::optional RedactCredentialHeader(std::string_view name, std::st if (absl::EqualsIgnoreCase(name, "set-cookie")) { return RedactSetCookie(value); } + if (absl::EqualsIgnoreCase(name, "sec-websocket-protocol")) { + return RedactSubprotocols(value); + } if (Contains(kUrlHeaders, name)) { return RedactCredentialPath(value); } From cb2aadd3ece71085d764a6fd1ed0aa43707f529c Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 02:12:42 +0100 Subject: [PATCH 35/51] Test that HTTP2 bodies follow the body size limit Signed-off-by: entlein --- .../socket_tracer/conn_tracker.h | 1 + .../socket_tracer/conn_tracker_http2_test.cc | 39 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker.h b/src/stirling/source_connectors/socket_tracer/conn_tracker.h index 19e2d45989f..8309554f1fc 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker.h +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker.h @@ -45,6 +45,7 @@ #include "src/stirling/utils/stat_counter.h" DECLARE_bool(treat_loopback_as_in_cluster); +DECLARE_uint64(max_body_bytes); constexpr int64_t kUnsetPIDFD = -1; DECLARE_int64(stirling_conn_trace_pid); DECLARE_int64(stirling_conn_trace_fd); diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker_http2_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_http2_test.cc index d22832212ad..9df7f63f232 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_http2_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_http2_test.cc @@ -21,7 +21,10 @@ #include #include +#include + #include "src/common/base/types.h" +#include "src/common/testing/test_environment.h" #include "src/stirling/source_connectors/socket_tracer/testing/http2_stream_generator.h" namespace px { @@ -84,6 +87,42 @@ TEST_F(ConnTrackerHTTP2Test, BasicData) { EXPECT_EQ(records[0].recv.data(), "Response"); } +TEST_F(ConnTrackerHTTP2Test, DataIsKeptUpToTheBodyLimit) { + PX_SET_FOR_SCOPE(FLAGS_max_body_bytes, 16384); + const std::string kOrder(2000, 'o'); + auto frame_generator = testing::StreamEventGenerator(&mock_clock_, kConnID, 7); + + tracker_.AddHTTP2Header(frame_generator.GenHeader(":method", "POST")); + tracker_.AddHTTP2Data(frame_generator.GenDataFrame(kOrder, true)); + tracker_.AddHTTP2Data(frame_generator.GenDataFrame("ok", true)); + tracker_.AddHTTP2Header(frame_generator.GenHeader(":status", "200")); + + std::vector records = tracker_.ProcessToRecords(); + + ASSERT_EQ(records.size(), 1); + EXPECT_EQ(records[0].send.data(), kOrder); + EXPECT_FALSE(records[0].send.data_truncated()); +} + +TEST_F(ConnTrackerHTTP2Test, DataBeyondTheBodyLimitIsTruncated) { + PX_SET_FOR_SCOPE(FLAGS_max_body_bytes, 100); + auto frame_generator = testing::StreamEventGenerator(&mock_clock_, kConnID, 7); + + tracker_.AddHTTP2Header(frame_generator.GenHeader(":method", "POST")); + tracker_.AddHTTP2Data(frame_generator.GenDataFrame(std::string(60, 'a'))); + tracker_.AddHTTP2Data( + frame_generator.GenDataFrame(std::string(90, 'b'), true)); + tracker_.AddHTTP2Data(frame_generator.GenDataFrame("ok", true)); + tracker_.AddHTTP2Header(frame_generator.GenHeader(":status", "200")); + + std::vector records = tracker_.ProcessToRecords(); + + ASSERT_EQ(records.size(), 1); + EXPECT_EQ(records[0].send.data(), std::string(60, 'a') + std::string(40, 'b')); + EXPECT_TRUE(records[0].send.data_truncated()); + EXPECT_EQ(records[0].send.original_data_size(), 150); +} + TEST_F(ConnTrackerHTTP2Test, BasicHeader) { const int kStreamID = 7; auto frame_generator = testing::StreamEventGenerator(&mock_clock_, kConnID, kStreamID); From d4d5ef14207d69160c691b353fdd8c9af8a00ff3 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 02:12:56 +0100 Subject: [PATCH 36/51] Keep HTTP2 bodies up to the body size limit Signed-off-by: entlein --- .../socket_tracer/conn_tracker.cc | 2 +- .../socket_tracer/conn_tracker_http2_test.cc | 16 ++++++++-------- .../socket_tracer/protocols/http2/types.h | 9 +++------ .../socket_tracer/socket_trace_connector.cc | 12 ++++++------ 4 files changed, 18 insertions(+), 21 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker.cc index a2405b31247..a4bdf86d791 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker.cc @@ -382,7 +382,7 @@ void ConnTracker::AddHTTP2Data(std::unique_ptr data) { ::ToString(data->attr.conn_id)); } - half_stream_ptr->AddData(data->payload); + half_stream_ptr->AddData(data->payload, FLAGS_max_body_bytes); if (data->attr.end_stream) { half_stream_ptr->AddEndStream(); } diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker_http2_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_http2_test.cc index 9df7f63f232..4b9c10cb3d5 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_http2_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_http2_test.cc @@ -400,20 +400,20 @@ TEST_F(ConnTrackerHTTP2Test, StreamIDJumpAhead) { expected_record0.send.AddHeader(":method", "post"); expected_record0.send.AddHeader(":host", "pixie.ai"); expected_record0.send.AddHeader(":path", "/magic"); - expected_record0.send.AddData("Request"); + expected_record0.send.AddData("Request", FLAGS_max_body_bytes); expected_record0.send.AddEndStream(); expected_record0.recv.AddHeader(":status", "200"); - expected_record0.recv.AddData("Response"); + expected_record0.recv.AddData("Response", FLAGS_max_body_bytes); expected_record0.recv.AddEndStream(); http2::Record expected_record1; expected_record1.send.AddHeader(":method", "post"); expected_record1.send.AddHeader(":host", "pixie.ai"); expected_record1.send.AddHeader(":path", "/wormhole"); - expected_record1.send.AddData("Request"); + expected_record1.send.AddData("Request", FLAGS_max_body_bytes); expected_record1.send.AddEndStream(); expected_record1.recv.AddHeader(":status", "200"); - expected_record1.recv.AddData("Long ways from home"); + expected_record1.recv.AddData("Long ways from home", FLAGS_max_body_bytes); expected_record1.recv.AddEndStream(); EXPECT_THAT(records, UnorderedElementsAre(EqHTTP2Record(expected_record0), @@ -490,20 +490,20 @@ TEST_F(ConnTrackerHTTP2Test, StreamIDJumpBack) { expected_record0.send.AddHeader(":method", "post"); expected_record0.send.AddHeader(":host", "pixie.ai"); expected_record0.send.AddHeader(":path", "/magic"); - expected_record0.send.AddData("Request"); + expected_record0.send.AddData("Request", FLAGS_max_body_bytes); expected_record0.send.AddEndStream(); expected_record0.recv.AddHeader(":status", "200"); - expected_record0.recv.AddData("Response"); + expected_record0.recv.AddData("Response", FLAGS_max_body_bytes); expected_record0.recv.AddEndStream(); http2::Record expected_record1; expected_record1.send.AddHeader(":method", "post"); expected_record1.send.AddHeader(":host", "pixie.ai"); expected_record1.send.AddHeader(":path", "/wormhole"); - expected_record1.send.AddData("Request"); + expected_record1.send.AddData("Request", FLAGS_max_body_bytes); expected_record1.send.AddEndStream(); expected_record1.recv.AddHeader(":status", "200"); - expected_record1.recv.AddData("Long ways from home"); + expected_record1.recv.AddData("Long ways from home", FLAGS_max_body_bytes); expected_record1.recv.AddEndStream(); EXPECT_THAT(records, UnorderedElementsAre(EqHTTP2Record(expected_record0), diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http2/types.h b/src/stirling/source_connectors/socket_tracer/protocols/http2/types.h index 9545c0f5995..62396322d06 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http2/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/http2/types.h @@ -117,16 +117,13 @@ struct HalfStream { trailers_.emplace(std::move(key), std::move(val)); } - void AddData(std::string_view val) { - // Only sample the head of the body, to save space. - constexpr size_t kMaxBodyBytes = 512; - + void AddData(std::string_view val, size_t max_body_bytes) { original_data_size_ += val.size(); size_t size_to_add = val.size(); - if (size_to_add + data_.size() > kMaxBodyBytes) { - size_to_add = kMaxBodyBytes - data_.size(); + if (size_to_add + data_.size() > max_body_bytes) { + size_to_add = max_body_bytes > data_.size() ? max_body_bytes - data_.size() : 0; data_truncated_ = true; } diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index 568b5c609c1..df1e6a1a729 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -1342,7 +1342,7 @@ int64_t AMQPCalculateLatency(const int64_t req_timestamp_ns, const int64_t resp_ return latency_ns; } -constexpr size_t kRedactedSize = std::numeric_limits::max(); +constexpr size_t kNoTruncation = std::numeric_limits::max(); std::string RedactedBody(std::string_view body) { if (body.size() <= FLAGS_max_body_bytes) { @@ -1398,12 +1398,12 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke r.Append(std::move(req_message.req_method)); r.Append(protocols::http::RedactCredentialPath(req_message.req_path)); r.Append(req_message.body_size); - r.Append(RedactedBody(req_message.body), kRedactedSize); + r.Append(RedactedBody(req_message.body), kNoTruncation); r.Append(ToJSONString(resp_message.headers), kMaxHTTPHeadersBytes); r.Append(resp_message.resp_status); r.Append(std::move(resp_message.resp_message)); r.Append(resp_message.body_size); - r.Append(RedactedBody(resp_message.body), kRedactedSize); + r.Append(RedactedBody(resp_message.body), kNoTruncation); r.Append( CalculateLatency(req_message.timestamp_ns, resp_message.timestamp_ns)); #ifndef NDEBUG @@ -1475,10 +1475,10 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke // protobuf message. This might result into longer text format data here, but the increase is // minimal. r.Append( - protocols::http::RedactCredentialBody(req_stream->ConsumeData())); + protocols::http::RedactCredentialBody(req_stream->ConsumeData()), kNoTruncation); r.Append(resp_stream->original_data_size()); r.Append( - protocols::http::RedactCredentialBody(resp_stream->ConsumeData())); + protocols::http::RedactCredentialBody(resp_stream->ConsumeData()), kNoTruncation); int64_t latency_ns = CalculateLatency(req_stream->timestamp_ns, resp_stream->timestamp_ns); r.Append(latency_ns); // TODO(yzhao): Remove once http2::Record::bpf_timestamp_ns is removed. @@ -1833,7 +1833,7 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke }; if (record.kind == protocols::websocket::RecordKind::kFrame && msg.opcode == protocols::websocket::Opcode::kText) { - r.Append(RedactedBody(msg.payload), kRedactedSize); + r.Append(RedactedBody(msg.payload), kNoTruncation); } else { r.Append(printable(msg.payload), FLAGS_max_body_bytes); } From 7d27812ccb39ab72467ff4ce605e0fb53782bb76 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 02:14:21 +0100 Subject: [PATCH 37/51] Test that TLS handshakes report version, cipher, group and ALPN Signed-off-by: entlein --- .../socket_tracer/protocols/tls/parse_test.cc | 9 ++++++++- .../socket_tracer/tls_trace_bpf_test.cc | 7 +++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/tls/parse_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse_test.cc index 9dc84c46a60..cc74c0827ab 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/tls/parse_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse_test.cc @@ -315,7 +315,8 @@ TEST_F(TLSParserTest, ParseValidClientHello) { ASSERT_GT(frame.session_id.size(), 0); // Validate the SNI extension was parsed properly - ASSERT_EQ(frame.body, R"({"extensions":{"server_name":["argocd-cluster-repo-server"]}})"); + ASSERT_EQ(frame.body, + R"({"extensions":{"server_name":["argocd-cluster-repo-server"],"alpn":["h2"]}})"); ASSERT_EQ(state, ParseState::kSuccess); } @@ -334,6 +335,9 @@ TEST_F(TLSParserTest, ParseValidServerHello) { ASSERT_EQ(frame.handshake_version, tls::LegacyVersion::kTLS1_2); ASSERT_GT(frame.session_id.size(), 0); ASSERT_EQ(state, ParseState::kSuccess); + EXPECT_EQ( + frame.body, + R"({"version":"TLSv1.3","cipher_suite":"TLS_AES_128_GCM_SHA256","key_share_group":"x25519"})"); } TEST_F(TLSParserTest, ServerHelloExtsWithZeroLenExtension) { @@ -347,6 +351,9 @@ TEST_F(TLSParserTest, ServerHelloExtsWithZeroLenExtension) { ASSERT_EQ(frame.handshake_type, tls::HandshakeType::kServerHello); ASSERT_EQ(state, ParseState::kSuccess); + EXPECT_EQ(frame.body, + R"({"version":"TLSv1.2","cipher_suite":"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",)" + R"("alpn":["http/1.1"]})"); } } // namespace protocols diff --git a/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc b/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc index 7931cc9f53e..10e55442b00 100644 --- a/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc +++ b/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc @@ -43,6 +43,7 @@ using ::px::stirling::testing::GetTargetRecords; using ::px::stirling::testing::SocketTraceBPFTestFixture; using ::px::stirling::testing::ToRecordVector; +using ::testing::HasSubstr; using ::testing::IsTrue; using ::testing::SizeIs; using ::testing::StrEq; @@ -114,8 +115,10 @@ class TLSVersionParameterizedTest auto records = this->GetTraceRecords(this->server_.PID()); EXPECT_THAT(records, SizeIs(1)); EXPECT_GT(records[0].req.body.size(), 0); - auto sni_str = R"({"extensions":{"server_name":["test-host"]}})"; - EXPECT_THAT(records[0].req.body, StrEq(sni_str)); + EXPECT_THAT(records[0].req.body, HasSubstr(R"("server_name":["test-host"])")); + EXPECT_THAT(records[0].req.body, HasSubstr(R"("alpn":[)")); + EXPECT_THAT(records[0].resp.body, HasSubstr(R"("version":"TLSv1.2")")); + EXPECT_THAT(records[0].resp.body, HasSubstr(R"("cipher_suite":"TLS_)")); } // Returns the trace records of the process specified by the input pid. From c19395db0ac695b165746feb8e97a6d69eda377e Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 02:15:05 +0100 Subject: [PATCH 38/51] Report TLS version, cipher suite, key share group and ALPN Signed-off-by: entlein --- .../socket_tracer/protocols/tls/parse.cc | 125 ++++++++++++++++-- .../socket_tracer/protocols/tls/types.h | 7 + .../socket_tracer/tls_trace_bpf_test.cc | 1 - 3 files changed, 123 insertions(+), 10 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc index d435772271f..421689ae103 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc @@ -18,11 +18,13 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/tls/parse.h" #include +#include #include #include #include #include +#include #include #include "src/stirling/utils/binary_decoder.h" @@ -42,6 +44,100 @@ constexpr size_t kSNIExtensionMinimumLength = 3; // In TLS 1.2 and earlier, gmt_unix_time is 4 bytes and Random is 28 bytes. constexpr size_t kRandomStructLength = 32; +constexpr uint16_t kSNIExtension = 0x0000; +constexpr uint16_t kALPNExtension = 0x0010; +constexpr uint16_t kSupportedVersionsExtension = 0x002b; +constexpr uint16_t kKeyShareExtension = 0x0033; + +constexpr std::pair kVersionNames[] = { + {0x0300, "SSLv3"}, {0x0301, "TLSv1.0"}, {0x0302, "TLSv1.1"}, + {0x0303, "TLSv1.2"}, {0x0304, "TLSv1.3"}, +}; + +constexpr std::pair kCipherSuiteNames[] = { + {0x1301, "TLS_AES_128_GCM_SHA256"}, + {0x1302, "TLS_AES_256_GCM_SHA384"}, + {0x1303, "TLS_CHACHA20_POLY1305_SHA256"}, + {0xc02b, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"}, + {0xc02c, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"}, + {0xc02f, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"}, + {0xc030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"}, + {0xcca8, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"}, + {0xcca9, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"}, + {0xc009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"}, + {0xc00a, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"}, + {0xc013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"}, + {0xc014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"}, + {0x009c, "TLS_RSA_WITH_AES_128_GCM_SHA256"}, + {0x009d, "TLS_RSA_WITH_AES_256_GCM_SHA384"}, + {0x002f, "TLS_RSA_WITH_AES_128_CBC_SHA"}, + {0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA"}, + {0x000a, "TLS_RSA_WITH_3DES_EDE_CBC_SHA"}, +}; + +constexpr std::pair kGroupNames[] = { + {0x0017, "secp256r1"}, {0x0018, "secp384r1"}, + {0x0019, "secp521r1"}, {0x001d, "x25519"}, + {0x001e, "x448"}, {0x0100, "ffdhe2048"}, + {0x0101, "ffdhe3072"}, {0x0200, "MLKEM512"}, + {0x0201, "MLKEM768"}, {0x0202, "MLKEM1024"}, + {0x11eb, "SecP256r1MLKEM768"}, {0x11ec, "X25519MLKEM768"}, + {0x6399, "X25519Kyber768Draft00"}, +}; + +template +std::string CodeName(const std::pair (&names)[N], uint16_t code) { + for (const auto& [value, name] : names) { + if (value == code) { + return std::string(name); + } + } + return absl::StrFormat("0x%04x", code); +} + +std::optional> ExtractALPN(std::string_view data) { + BinaryDecoder decoder(data); + PX_ASSIGN_OR(auto list_length, decoder.ExtractBEInt(), return std::nullopt); + if (list_length != decoder.BufSize()) { + return std::nullopt; + } + std::vector protocols; + while (decoder.BufSize() > 0) { + PX_ASSIGN_OR(auto length, decoder.ExtractBEInt(), return std::nullopt); + PX_ASSIGN_OR(auto protocol, decoder.ExtractString(length), return std::nullopt); + protocols.emplace_back(protocol); + } + return protocols; +} + +std::optional ExtractLeadingU16(std::string_view data) { + BinaryDecoder decoder(data); + PX_ASSIGN_OR(auto value, decoder.ExtractBEInt(), return std::nullopt); + return value; +} + +void ExtractServerHelloExtension(SharedExtensions* exts, uint16_t type, std::string_view data) { + if (type == kSupportedVersionsExtension) { + exts->selected_version = ExtractLeadingU16(data); + } else if (type == kKeyShareExtension) { + exts->key_share_group = ExtractLeadingU16(data); + } +} + +std::string ServerHelloBody(const SharedExtensions& exts, uint16_t handshake_version, + uint16_t cipher_suite) { + JSONObjectBuilder builder; + builder.WriteKV("version", CodeName(kVersionNames, exts.selected_version.value_or(handshake_version))); + builder.WriteKV("cipher_suite", CodeName(kCipherSuiteNames, cipher_suite)); + if (exts.key_share_group.has_value()) { + builder.WriteKV("key_share_group", CodeName(kGroupNames, exts.key_share_group.value())); + } + if (!exts.alpn.empty()) { + builder.WriteKV("alpn", exts.alpn); + } + return builder.GetString(); +} + StatusOr ExtractSNIExtension(SharedExtensions* exts, BinaryDecoder* decoder) { PX_ASSIGN_OR(auto server_name_list_length, decoder->ExtractBEInt(), return ParseState::kInvalid); @@ -146,6 +242,17 @@ ParseState ParseFullFrame(SharedExtensions* extensions, BinaryDecoder* decoder, return ParseState::kInvalid; } } + const bool server_hello = frame->handshake_type == HandshakeType::kServerHello; + auto finish = [&]() { + if (server_hello) { + frame->body = ServerHelloBody(*extensions, raw_handshake_version, cipher_suite_length); + } else { + JSONObjectBuilder body_builder; + body_builder.WriteKVRecursive("extensions", *extensions); + frame->body = body_builder.GetString(); + } + return ParseState::kSuccess; + }; PX_ASSIGN_OR(auto compression_methods_length, decoder->ExtractBEInt(), return ParseState::kInvalid); @@ -159,7 +266,7 @@ ParseState ParseFullFrame(SharedExtensions* extensions, BinaryDecoder* decoder, PX_ASSIGN_OR(auto extensions_length, decoder->ExtractBEInt(), return ParseState::kInvalid); if (extensions_length == 0) { - return ParseState::kSuccess; + return finish(); } while (extensions_length > 0) { @@ -169,24 +276,24 @@ ParseState ParseFullFrame(SharedExtensions* extensions, BinaryDecoder* decoder, return ParseState::kInvalid); if (extension_length > 0) { - if (extension_type == 0x00) { + if (extension_type == kSNIExtension) { if (!ExtractSNIExtension(extensions, decoder).ok()) { return ParseState::kInvalid; } } else { - if (!decoder->ExtractBufIgnore(extension_length).ok()) { - return ParseState::kInvalid; + PX_ASSIGN_OR(auto data, decoder->ExtractString(extension_length), + return ParseState::kInvalid); + if (extension_type == kALPNExtension) { + extensions->alpn = ExtractALPN(data).value_or(std::vector{}); + } else if (server_hello) { + ExtractServerHelloExtension(extensions, extension_type, data); } } } extensions_length -= kExtensionMinimumLength + extension_length; } - JSONObjectBuilder body_builder; - body_builder.WriteKVRecursive("extensions", *extensions); - frame->body = body_builder.GetString(); - - return ParseState::kSuccess; + return finish(); } } // namespace tls diff --git a/src/stirling/source_connectors/socket_tracer/protocols/tls/types.h b/src/stirling/source_connectors/socket_tracer/protocols/tls/types.h index fdf65e6d95f..f14db7c7bbe 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/tls/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/tls/types.h @@ -19,6 +19,7 @@ #pragma once #include +#include #include #include @@ -188,6 +189,9 @@ enum class ExtensionType : uint16_t { // of a TLS handshake struct SharedExtensions { std::vector server_names; + std::vector alpn; + std::optional selected_version; + std::optional key_share_group; virtual void ToJSON(::px::utils::JSONObjectBuilder* /*builder*/) const {} virtual ~SharedExtensions() = default; @@ -197,6 +201,9 @@ struct ReqExtensions : public SharedExtensions { void ToJSON(::px::utils::JSONObjectBuilder* builder) const override { SharedExtensions::ToJSON(builder); builder->WriteKV("server_name", server_names); + if (!alpn.empty()) { + builder->WriteKV("alpn", alpn); + } } }; diff --git a/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc b/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc index 10e55442b00..a64c21e0d16 100644 --- a/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc +++ b/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc @@ -46,7 +46,6 @@ using ::px::stirling::testing::ToRecordVector; using ::testing::HasSubstr; using ::testing::IsTrue; using ::testing::SizeIs; -using ::testing::StrEq; using ::testing::UnorderedElementsAre; class NginxOpenSSL_3_0_8_ContainerWrapper From 6c38eb8583c46daf7356da9e1e72ba2af9b4fa24 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 02:34:16 +0100 Subject: [PATCH 39/51] Test that TLS handshakes hand over to the decrypted protocol Signed-off-by: entlein --- .../socket_tracer/conn_tracker.h | 2 + .../socket_tracer/conn_tracker_test.cc | 77 +++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker.h b/src/stirling/source_connectors/socket_tracer/conn_tracker.h index 8309554f1fc..8b9a96b9d33 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker.h +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker.h @@ -328,6 +328,8 @@ class ConnTracker : NotCopyMoveable { } const conn_id_t& conn_id() const { return conn_id_; } + bool MaybeHandOverFromTLS() { return false; } + traffic_protocol_t protocol() const { return protocol_; } endpoint_role_t role() const { return role_; } bool ssl() const { return ssl_; } diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc index 325cb1ed701..b1e4b3f9498 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc @@ -19,6 +19,7 @@ #include "src/stirling/source_connectors/socket_tracer/conn_tracker.h" #include +#include #include #include @@ -33,6 +34,7 @@ #include "src/stirling/source_connectors/socket_tracer/conn_stats.h" #include "src/stirling/source_connectors/socket_tracer/protocols/http/types.h" #include "src/stirling/source_connectors/socket_tracer/protocols/mysql/test_utils.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/tls/types.h" #include "src/stirling/source_connectors/socket_tracer/testing/event_generator.h" #include "src/stirling/testing/common.h" @@ -494,6 +496,81 @@ TEST_F(ConnTrackerTest, TrackerWebSocketCloseAfterUpgradeIsRecorded) { EXPECT_TRUE(tracker.protocol_state()->global.conn_closed); } +std::string TLSRecord(uint8_t handshake_type, std::string_view body) { + std::string handshake = absl::StrCat(std::string(1, static_cast(handshake_type)), + std::string(1, '\0'), + std::string(1, static_cast(body.size() >> 8)), + std::string(1, static_cast(body.size() & 0xff)), body); + return absl::StrCat("\x16\x03\x01"sv, std::string(1, static_cast(handshake.size() >> 8)), + std::string(1, static_cast(handshake.size() & 0xff)), handshake); +} + +std::string ClientHello() { + return TLSRecord(1, absl::StrCat("\x03\x03"sv, std::string(32, 'r'), + "\x00\x00\x02\x13\x01\x01\x00\x00\x00"sv)); +} + +std::string ServerHello() { + return TLSRecord(2, absl::StrCat("\x03\x03"sv, std::string(32, 'r'), + "\x00\x13\x01\x00\x00\x0c" + "\x00\x2b\x00\x02\x03\x04" + "\x00\x33\x00\x02\x11\xec"sv)); +} + +TEST_F(ConnTrackerTest, TLSHandshakeIsHandedOverToDecryptedHTTP) { + ConnTracker tracker; + tracker.AddControlEvent(event_gen_.InitConn()); + tracker.AddDataEvent(event_gen_.InitSendEvent(ClientHello())); + tracker.AddDataEvent(event_gen_.InitRecvEvent(ServerHello())); + std::unique_ptr req = event_gen_.InitSendEvent(kHTTPReq0); + req->attr.ssl = true; + std::unique_ptr resp = event_gen_.InitRecvEvent(kHTTPResp0); + resp->attr.ssl = true; + tracker.AddDataEvent(std::move(req)); + tracker.AddDataEvent(std::move(resp)); + + std::vector handshakes = tracker.ProcessToRecords(); + ASSERT_THAT(handshakes, SizeIs(1)); + EXPECT_EQ(handshakes[0].resp.body, + R"({"version":"TLSv1.3","cipher_suite":"TLS_AES_128_GCM_SHA256",)" + R"("key_share_group":"X25519MLKEM768"})"); + + ASSERT_TRUE(tracker.MaybeHandOverFromTLS()); + EXPECT_EQ(tracker.protocol(), kProtocolHTTP); + EXPECT_TRUE(tracker.ssl()); + + tracker.InitProtocolState(); + std::vector records = tracker.ProcessToRecords(); + ASSERT_THAT(records, SizeIs(1)); + EXPECT_EQ(records[0].req.req_path, "/index.html"); +} + +TEST_F(ConnTrackerTest, TLSWithoutDecryptedDataStaysTLS) { + ConnTracker tracker; + tracker.AddControlEvent(event_gen_.InitConn()); + tracker.AddDataEvent(event_gen_.InitSendEvent(ClientHello())); + tracker.AddDataEvent(event_gen_.InitRecvEvent(ServerHello())); + + EXPECT_THAT(tracker.ProcessToRecords(), SizeIs(1)); + EXPECT_FALSE(tracker.MaybeHandOverFromTLS()); + EXPECT_EQ(tracker.protocol(), kProtocolTLS); +} + +TEST_F(ConnTrackerTest, TLSClientHandshakesAreCollected) { + struct socket_control_event_t conn = event_gen_.InitConn(); + testing::SetIPv4RemoteAddr(&conn, "1.2.3.4"); + + CIDRBlock cidr; + ASSERT_OK(ParseCIDRBlock("1.2.3.4/14", &cidr)); + + ConnTracker tracker; + tracker.AddControlEvent(conn); + tracker.SetProtocol(kProtocolTLS, "testing"); + tracker.SetRole(kRoleClient, "testing"); + tracker.IterationPreTick(now(), {cidr}, /*proc_parser*/ nullptr, /*connections*/ nullptr); + EXPECT_EQ(tracker.state(), ConnTracker::State::kTransferring); +} + TEST_F(ConnTrackerTest, TrackerHTTPUpgradeRejectedStaysHTTP) { constexpr std::string_view kRejectResp = "HTTP/1.1 403 Forbidden\r\n" From e9d45f2a5ff4d75cea2736af5d7eb82e970b1fff Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 02:35:31 +0100 Subject: [PATCH 40/51] Hand TLS connections over to the decrypted protocol Signed-off-by: entlein --- .../socket_tracer/bcc_bpf/socket_trace.c | 12 ++++- .../socket_tracer/conn_tracker.cc | 45 ++++++++++++++++++- .../socket_tracer/conn_tracker.h | 7 ++- .../socket_tracer/socket_trace_connector.cc | 1 + 4 files changed, 62 insertions(+), 3 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/bcc_bpf/socket_trace.c b/src/stirling/source_connectors/socket_tracer/bcc_bpf/socket_trace.c index 68a23dda923..e38fb148694 100644 --- a/src/stirling/source_connectors/socket_tracer/bcc_bpf/socket_trace.c +++ b/src/stirling/source_connectors/socket_tracer/bcc_bpf/socket_trace.c @@ -832,6 +832,10 @@ static __inline void process_data(const bool vecs, struct pt_regs* ctx, uint64_t // Only process plaintext data. if (conn_info->ssl == ssl) { + if (ENABLE_TLS_TRACING && ssl && conn_info->protocol == kProtocolTLS) { + conn_info->protocol = kProtocolUnknown; + } + // TODO(yzhao): Split the interface such that the singular buf case and multiple bufs in msghdr // are handled separately without mixed interface. The plan is to factor out helper functions // for lower-level functionalities, and call them separately for each case. @@ -854,7 +858,13 @@ static __inline void process_data(const bool vecs, struct pt_regs* ctx, uint64_t } } - if (should_send_data(tgid, conn_disabled_tsid, force_trace_tgid, conn_info)) { + bool skip_tls_payload = false; + if (ENABLE_TLS_TRACING && !vecs && !ssl && conn_info->protocol == kProtocolTLS) { + skip_tls_payload = infer_tls_message(args->buf, bytes_count) == kUnknown; + } + + if (!skip_tls_payload && + should_send_data(tgid, conn_disabled_tsid, force_trace_tgid, conn_info)) { struct socket_data_event_t* event = fill_socket_data_event(args->source_fn, direction, conn_info); if (event == NULL) { diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker.cc index a4bdf86d791..e0b88110bee 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker.cc @@ -152,6 +152,13 @@ void ConnTracker::AddDataEvent(std::unique_ptr event) { SetProtocol(event->attr.protocol, "inferred from data_event"); SetSSL(event->attr.ssl, event->attr.ssl_source, "inferred from data_event"); + if (protocol_ == kProtocolTLS && event->attr.ssl && event->attr.protocol != kProtocolTLS && + event->attr.protocol != kProtocolUnknown) { + tls_handover_protocol_ = event->attr.protocol; + tls_handover_events_.push_back(std::move(event)); + return; + } + CheckTracker(); UpdateTimestamps(event->attr.timestamp_ns); UpdateDataStats(*event); @@ -251,6 +258,11 @@ endpoint_role_t InferHTTP2Role(bool write_event, const std::unique_ptr hdr) { + if (protocol_ == kProtocolTLS) { + tls_handover_protocol_ = kProtocolHTTP2; + tls_handover_events_.push_back(std::move(hdr)); + return; + } SetProtocol(kProtocolHTTP2, "inferred from http2 headers"); if (protocol_ != kProtocolHTTP2) { @@ -328,6 +340,11 @@ void ConnTracker::AddHTTP2Header(std::unique_ptr hdr) { } void ConnTracker::AddHTTP2Data(std::unique_ptr data) { + if (protocol_ == kProtocolTLS) { + tls_handover_protocol_ = kProtocolHTTP2; + tls_handover_events_.push_back(std::move(data)); + return; + } SetProtocol(kProtocolHTTP2, "inferred from http2 data"); if (protocol_ != kProtocolHTTP2) { @@ -680,7 +697,7 @@ auto CreateTraceRoles() { res.Set(kProtocolKafka, {kRoleServer}); res.Set(kProtocolMux, {kRoleServer}); res.Set(kProtocolAMQP, {kRoleServer}); - res.Set(kProtocolTLS, {kRoleServer}); + res.Set(kProtocolTLS, {kRoleClient, kRoleServer}); res.Set(kProtocolWebSocket, {kRoleServer}); DCHECK(res.AreAllKeysSet()); @@ -842,6 +859,32 @@ bool ConnTracker::MaybeUpgradeToWebSocket() { return true; } +bool ConnTracker::MaybeHandOverFromTLS() { + if (protocol_ != kProtocolTLS || tls_handover_protocol_ == kProtocolUnknown) { + return false; + } + + CONN_TRACE(1) << absl::Substitute("Protocol handed over: TLS->$0", + magic_enum::enum_name(tls_handover_protocol_)); + protocol_ = tls_handover_protocol_; + tls_handover_protocol_ = kProtocolUnknown; + send_data_.SwitchProtocol(protocol_); + recv_data_.SwitchProtocol(protocol_); + + auto events = std::move(tls_handover_events_); + tls_handover_events_.clear(); + for (auto& event : events) { + if (auto* data = std::get_if>(&event)) { + AddDataEvent(std::move(*data)); + } else if (auto* hdr = std::get_if>(&event)) { + AddHTTP2Header(std::move(*hdr)); + } else { + AddHTTP2Data(std::move(std::get>(event))); + } + } + return true; +} + void ConnTracker::IterationPostTick() { if (death_countdown_ > 0) { --death_countdown_; diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker.h b/src/stirling/source_connectors/socket_tracer/conn_tracker.h index 8b9a96b9d33..a88bbb9528f 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker.h +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker.h @@ -328,7 +328,7 @@ class ConnTracker : NotCopyMoveable { } const conn_id_t& conn_id() const { return conn_id_; } - bool MaybeHandOverFromTLS() { return false; } + bool MaybeHandOverFromTLS(); traffic_protocol_t protocol() const { return protocol_; } endpoint_role_t role() const { return role_; } @@ -709,6 +709,11 @@ class ConnTracker : NotCopyMoveable { traffic_protocol_t protocol_ = kProtocolUnknown; traffic_protocol_t upgraded_from_ = kProtocolUnknown; + + traffic_protocol_t tls_handover_protocol_ = kProtocolUnknown; + std::vector, std::unique_ptr, + std::unique_ptr>> + tls_handover_events_; endpoint_role_t role_ = kRoleUnknown; bool ssl_ = false; ssl_source_t ssl_source_ = kSSLNone; diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index df1e6a1a729..5bc3b601a2f 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -880,6 +880,7 @@ void SocketTraceConnector::TransferDataImpl(ConnectorContext* ctx) { if (protocol_transfer_specs_[kProtocolWebSocket].enabled) { conn_tracker->MaybeUpgradeToWebSocket(); } + conn_tracker->MaybeHandOverFromTLS(); } else { // If there's no transfer function, then the tracker should not be holding any data. // http::ProtocolTraits is used as a placeholder; the frames deque is expected to be From f4f0b8565c0c7670564684565b4090289758eb59 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 02:36:06 +0100 Subject: [PATCH 41/51] Test that decrypted HTTP is kept when TLS tracing is on Signed-off-by: entlein --- .../socket_tracer/tls_trace_bpf_test.cc | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc b/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc index a64c21e0d16..bd599a64ec5 100644 --- a/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc +++ b/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc @@ -20,6 +20,7 @@ #include #include +#include #include "src/common/base/base.h" #include "src/common/exec/exec.h" @@ -118,6 +119,18 @@ class TLSVersionParameterizedTest EXPECT_THAT(records[0].req.body, HasSubstr(R"("alpn":[)")); EXPECT_THAT(records[0].resp.body, HasSubstr(R"("version":"TLSv1.2")")); EXPECT_THAT(records[0].resp.body, HasSubstr(R"("cipher_suite":"TLS_)")); + + std::vector http_tablets = + this->ConsumeRecords(SocketTraceConnector::kHTTPTableNum); + ASSERT_FALSE(http_tablets.empty()); + types::ColumnWrapperRecordBatch http_batch = http_tablets[0].records; + std::vector http_indices = + FindRecordIdxMatchesPID(http_batch, kHTTPUPIDIdx, this->server_.PID()); + ASSERT_FALSE(http_indices.empty()); + for (size_t idx : http_indices) { + EXPECT_TRUE(http_batch[kHTTPEncryptedIdx]->Get(idx).val); + EXPECT_EQ(http_batch[kHTTPReqPathIdx]->Get(idx), "/index.html"); + } } // Returns the trace records of the process specified by the input pid. From c1e3c8ae3a0b030d61fb2b21b9f0881a785db3cd Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 02:36:47 +0100 Subject: [PATCH 42/51] Test that ClientHellos report offered groups Signed-off-by: entlein --- .../socket_tracer/protocols/tls/parse_test.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/tls/parse_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse_test.cc index cc74c0827ab..29d1a55b094 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/tls/parse_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse_test.cc @@ -316,7 +316,9 @@ TEST_F(TLSParserTest, ParseValidClientHello) { // Validate the SNI extension was parsed properly ASSERT_EQ(frame.body, - R"({"extensions":{"server_name":["argocd-cluster-repo-server"],"alpn":["h2"]}})"); + R"({"extensions":{"server_name":["argocd-cluster-repo-server"],"alpn":["h2"],)" + R"("supported_groups":["x25519","secp256r1","secp384r1","secp521r1"],)" + R"("key_share_groups":["x25519"]}})"); ASSERT_EQ(state, ParseState::kSuccess); } From 2e2c63c2e9a49590ddd3a225f07d69c656cd7337 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 02:36:47 +0100 Subject: [PATCH 43/51] Report the groups a TLS client offers Signed-off-by: entlein --- .../socket_tracer/protocols/tls/parse.cc | 43 +++++++++++++++++++ .../socket_tracer/protocols/tls/types.h | 8 ++++ 2 files changed, 51 insertions(+) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc index 421689ae103..551312b1073 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc @@ -46,6 +46,7 @@ constexpr size_t kRandomStructLength = 32; constexpr uint16_t kSNIExtension = 0x0000; constexpr uint16_t kALPNExtension = 0x0010; +constexpr uint16_t kSupportedGroupsExtension = 0x000a; constexpr uint16_t kSupportedVersionsExtension = 0x002b; constexpr uint16_t kKeyShareExtension = 0x0033; @@ -116,6 +117,46 @@ std::optional ExtractLeadingU16(std::string_view data) { return value; } +std::vector ExtractGroups(std::string_view data) { + BinaryDecoder decoder(data); + std::vector groups; + PX_ASSIGN_OR(auto list_length, decoder.ExtractBEInt(), return groups); + if (list_length != decoder.BufSize()) { + return groups; + } + while (decoder.BufSize() >= sizeof(uint16_t)) { + PX_ASSIGN_OR(auto group, decoder.ExtractBEInt(), return groups); + groups.push_back(CodeName(kGroupNames, group)); + } + return groups; +} + +std::vector ExtractKeyShareGroups(std::string_view data) { + BinaryDecoder decoder(data); + std::vector groups; + PX_ASSIGN_OR(auto list_length, decoder.ExtractBEInt(), return groups); + if (list_length != decoder.BufSize()) { + return groups; + } + while (decoder.BufSize() > 0) { + PX_ASSIGN_OR(auto group, decoder.ExtractBEInt(), return groups); + PX_ASSIGN_OR(auto key_length, decoder.ExtractBEInt(), return groups); + if (!decoder.ExtractBufIgnore(key_length).ok()) { + return groups; + } + groups.push_back(CodeName(kGroupNames, group)); + } + return groups; +} + +void ExtractClientHelloExtension(SharedExtensions* exts, uint16_t type, std::string_view data) { + if (type == kSupportedGroupsExtension) { + exts->supported_groups = ExtractGroups(data); + } else if (type == kKeyShareExtension) { + exts->key_share_groups = ExtractKeyShareGroups(data); + } +} + void ExtractServerHelloExtension(SharedExtensions* exts, uint16_t type, std::string_view data) { if (type == kSupportedVersionsExtension) { exts->selected_version = ExtractLeadingU16(data); @@ -287,6 +328,8 @@ ParseState ParseFullFrame(SharedExtensions* extensions, BinaryDecoder* decoder, extensions->alpn = ExtractALPN(data).value_or(std::vector{}); } else if (server_hello) { ExtractServerHelloExtension(extensions, extension_type, data); + } else if (frame->handshake_type == HandshakeType::kClientHello) { + ExtractClientHelloExtension(extensions, extension_type, data); } } } diff --git a/src/stirling/source_connectors/socket_tracer/protocols/tls/types.h b/src/stirling/source_connectors/socket_tracer/protocols/tls/types.h index f14db7c7bbe..6954e5e6d7b 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/tls/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/tls/types.h @@ -190,6 +190,8 @@ enum class ExtensionType : uint16_t { struct SharedExtensions { std::vector server_names; std::vector alpn; + std::vector supported_groups; + std::vector key_share_groups; std::optional selected_version; std::optional key_share_group; @@ -204,6 +206,12 @@ struct ReqExtensions : public SharedExtensions { if (!alpn.empty()) { builder->WriteKV("alpn", alpn); } + if (!supported_groups.empty()) { + builder->WriteKV("supported_groups", supported_groups); + } + if (!key_share_groups.empty()) { + builder->WriteKV("key_share_groups", key_share_groups); + } } }; From 4e1a6ea574fe4b5aa493eeb18ab1fa6832643f9a Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 09:54:12 +0100 Subject: [PATCH 44/51] Alias the TLS protocol namespace in conn tracker tests Signed-off-by: entlein --- .../source_connectors/socket_tracer/conn_tracker_test.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc index b1e4b3f9498..f3d7d3517e4 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc @@ -46,6 +46,7 @@ using ::px::operator<<; namespace http = protocols::http; namespace mysql = protocols::mysql; +namespace tls = protocols::tls; namespace websocket = protocols::websocket; using ::testing::Field; From aa706055108c24029801325e5245b0727375f1a8 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 12:54:44 +0100 Subject: [PATCH 45/51] Test that a TLS connection closed in one poll yields its decrypted HTTP row Signed-off-by: entlein --- .../socket_tracer/conn_tracker_test.cc | 23 +------ .../socket_tracer/protocols/tls/test_utils.h | 60 +++++++++++++++++++ .../socket_trace_connector_test.cc | 34 +++++++++++ 3 files changed, 97 insertions(+), 20 deletions(-) create mode 100644 src/stirling/source_connectors/socket_tracer/protocols/tls/test_utils.h diff --git a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc index f3d7d3517e4..5feacf4b2f5 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc @@ -34,6 +34,7 @@ #include "src/stirling/source_connectors/socket_tracer/conn_stats.h" #include "src/stirling/source_connectors/socket_tracer/protocols/http/types.h" #include "src/stirling/source_connectors/socket_tracer/protocols/mysql/test_utils.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/tls/test_utils.h" #include "src/stirling/source_connectors/socket_tracer/protocols/tls/types.h" #include "src/stirling/source_connectors/socket_tracer/testing/event_generator.h" #include "src/stirling/testing/common.h" @@ -497,26 +498,8 @@ TEST_F(ConnTrackerTest, TrackerWebSocketCloseAfterUpgradeIsRecorded) { EXPECT_TRUE(tracker.protocol_state()->global.conn_closed); } -std::string TLSRecord(uint8_t handshake_type, std::string_view body) { - std::string handshake = absl::StrCat(std::string(1, static_cast(handshake_type)), - std::string(1, '\0'), - std::string(1, static_cast(body.size() >> 8)), - std::string(1, static_cast(body.size() & 0xff)), body); - return absl::StrCat("\x16\x03\x01"sv, std::string(1, static_cast(handshake.size() >> 8)), - std::string(1, static_cast(handshake.size() & 0xff)), handshake); -} - -std::string ClientHello() { - return TLSRecord(1, absl::StrCat("\x03\x03"sv, std::string(32, 'r'), - "\x00\x00\x02\x13\x01\x01\x00\x00\x00"sv)); -} - -std::string ServerHello() { - return TLSRecord(2, absl::StrCat("\x03\x03"sv, std::string(32, 'r'), - "\x00\x13\x01\x00\x00\x0c" - "\x00\x2b\x00\x02\x03\x04" - "\x00\x33\x00\x02\x11\xec"sv)); -} +using tls::testutils::ClientHello; +using tls::testutils::ServerHello; TEST_F(ConnTrackerTest, TLSHandshakeIsHandedOverToDecryptedHTTP) { ConnTracker tracker; diff --git a/src/stirling/source_connectors/socket_tracer/protocols/tls/test_utils.h b/src/stirling/source_connectors/socket_tracer/protocols/tls/test_utils.h new file mode 100644 index 00000000000..68e3d2e9826 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/tls/test_utils.h @@ -0,0 +1,60 @@ +/* + * Copyright 2018- The Pixie Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include + +#include + +namespace px { +namespace stirling { +namespace protocols { +namespace tls { +namespace testutils { + +inline std::string TLSRecord(uint8_t handshake_type, std::string_view body) { + using std::string_view_literals::operator""sv; + std::string handshake = absl::StrCat(std::string(1, static_cast(handshake_type)), + std::string(1, '\0'), + std::string(1, static_cast(body.size() >> 8)), + std::string(1, static_cast(body.size() & 0xff)), body); + return absl::StrCat("\x16\x03\x01"sv, std::string(1, static_cast(handshake.size() >> 8)), + std::string(1, static_cast(handshake.size() & 0xff)), handshake); +} + +inline std::string ClientHello() { + using std::string_view_literals::operator""sv; + return TLSRecord(1, absl::StrCat("\x03\x03"sv, std::string(32, 'r'), + "\x00\x00\x02\x13\x01\x01\x00\x00\x00"sv)); +} + +inline std::string ServerHello() { + using std::string_view_literals::operator""sv; + return TLSRecord(2, absl::StrCat("\x03\x03"sv, std::string(32, 'r'), + "\x00\x13\x01\x00\x00\x0c" + "\x00\x2b\x00\x02\x03\x04" + "\x00\x33\x00\x02\x11\xec"sv)); +} + +} // namespace testutils +} // namespace tls +} // namespace protocols +} // namespace stirling +} // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc index b8760564df7..58baa94b088 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc @@ -34,6 +34,7 @@ #include "src/stirling/core/connector_context.h" #include "src/stirling/core/data_tables.h" #include "src/stirling/source_connectors/socket_tracer/protocols/cql/test_utils.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/tls/test_utils.h" #include "src/stirling/source_connectors/socket_tracer/testing/event_generator.h" #include "src/stirling/source_connectors/socket_tracer/testing/socket_trace_connector_friend.h" #include "src/stirling/testing/common.h" @@ -264,6 +265,39 @@ TEST_F(SocketTraceConnectorTest, HTTPCredentialsAreRedacted) { ElementsAre(HasSubstr("Bearer AcceptControlEvent(event_gen_.InitConn()); + source_->AcceptDataEvent( + event_gen_.InitSendEvent(protocols::tls::testutils::ClientHello())); + source_->AcceptDataEvent( + event_gen_.InitRecvEvent(protocols::tls::testutils::ServerHello())); + std::unique_ptr req = event_gen_.InitSendEvent(kReq3); + req->attr.ssl = true; + std::unique_ptr resp = event_gen_.InitRecvEvent(kJSONResp); + resp->attr.ssl = true; + source_->AcceptDataEvent(std::move(req)); + source_->AcceptDataEvent(std::move(resp)); + source_->AcceptControlEvent(event_gen_.InitClose()); + + connector_->TransferData(ctx_.get()); + + std::vector tablets = http_table_->ConsumeRecords(); + ASSERT_NOT_EMPTY_AND_GET_RECORDS(RecordBatch & records, tablets); + ASSERT_THAT(records, RecordBatchSizeIs(1)); + EXPECT_THAT(ToStringVector(records[kHTTPReqBodyIdx]), ElementsAre("I have a message body")); + EXPECT_THAT(ToIntVector(records[kHTTPEncryptedIdx]), ElementsAre(1)); +} + class SocketTraceConnectorWebSocketTest : public SocketTraceConnectorTest { protected: void SetUp() override { From 80c64c63e05e64cf190e19871c02dc6370966201 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 12:55:09 +0100 Subject: [PATCH 46/51] Transfer handed-over TLS connections in the same iteration Signed-off-by: entlein --- .../socket_tracer/socket_trace_connector.cc | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index 5bc3b601a2f..6054756aba7 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -852,13 +852,12 @@ void SocketTraceConnector::TransferDataImpl(ConnectorContext* ctx) { } size_t current_conn_tracker_buffer_size = 0; + auto table_for = [this](const TransferSpec& spec) -> DataTable* { + return spec.enabled ? data_tables_[spec.table_num] : nullptr; + }; for (const auto& conn_tracker : conn_trackers_mgr_.active_trackers()) { const auto& transfer_spec = protocol_transfer_specs_[conn_tracker->protocol()]; - - DataTable* data_table = nullptr; - if (transfer_spec.enabled) { - data_table = data_tables_[transfer_spec.table_num]; - } + DataTable* data_table = table_for(transfer_spec); UpdateTrackerTraceLevel(conn_tracker); @@ -880,7 +879,15 @@ void SocketTraceConnector::TransferDataImpl(ConnectorContext* ctx) { if (protocol_transfer_specs_[kProtocolWebSocket].enabled) { conn_tracker->MaybeUpgradeToWebSocket(); } - conn_tracker->MaybeHandOverFromTLS(); + if (conn_tracker->MaybeHandOverFromTLS()) { + conn_tracker->IterationPreTick(iteration_time_, cluster_cidrs, proc_parser_.get(), + socket_info_mgr_.get()); + const auto& handed_over_spec = protocol_transfer_specs_[conn_tracker->protocol()]; + if (handed_over_spec.transfer_fn != nullptr) { + current_conn_tracker_buffer_size += handed_over_spec.transfer_fn( + *this, ctx, conn_tracker, table_for(handed_over_spec)); + } + } } else { // If there's no transfer function, then the tracker should not be holding any data. // http::ProtocolTraits is used as a placeholder; the frames deque is expected to be From 44cb3e8b85b6ae72daec1ef9a0e9bd207b6e3311 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 12:55:09 +0100 Subject: [PATCH 47/51] Send all TLS records to user space Signed-off-by: entlein --- .../socket_tracer/bcc_bpf/socket_trace.c | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/bcc_bpf/socket_trace.c b/src/stirling/source_connectors/socket_tracer/bcc_bpf/socket_trace.c index e38fb148694..8055f682b74 100644 --- a/src/stirling/source_connectors/socket_tracer/bcc_bpf/socket_trace.c +++ b/src/stirling/source_connectors/socket_tracer/bcc_bpf/socket_trace.c @@ -858,13 +858,7 @@ static __inline void process_data(const bool vecs, struct pt_regs* ctx, uint64_t } } - bool skip_tls_payload = false; - if (ENABLE_TLS_TRACING && !vecs && !ssl && conn_info->protocol == kProtocolTLS) { - skip_tls_payload = infer_tls_message(args->buf, bytes_count) == kUnknown; - } - - if (!skip_tls_payload && - should_send_data(tgid, conn_disabled_tsid, force_trace_tgid, conn_info)) { + if (should_send_data(tgid, conn_disabled_tsid, force_trace_tgid, conn_info)) { struct socket_data_event_t* event = fill_socket_data_event(args->source_fn, direction, conn_info); if (event == NULL) { From e9eb9e30919d1a7f2c63bcadd862963612f4bb8c Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 16:11:12 +0100 Subject: [PATCH 48/51] Format the socket tracer sources Signed-off-by: entlein --- .../protocols/http/credentials.cc | 2 +- .../protocols/http/credentials_test.cc | 26 +++++++++---------- .../socket_tracer/protocols/tls/parse.cc | 23 ++++++++++------ .../socket_tracer/protocols/tls/test_utils.h | 8 +++--- .../socket_tracer/socket_trace_connector.cc | 8 +++--- .../socket_trace_connector_test.cc | 4 +-- 6 files changed, 39 insertions(+), 32 deletions(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc index 97e9b2d019b..fa7ba14cff3 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc @@ -50,7 +50,7 @@ constexpr std::array kTokenHeaders = {"x-api-key", "x-auth- constexpr std::array kUrlHeaders = {":path", "referer", "location"}; constexpr std::string_view kBearerSubprotocol = "base64url.bearer.authorization.k8s.io."; constexpr std::array kCredentialFields = { - "access_token", "id_token", "refresh_token", "token", "api_key", + "access_token", "id_token", "refresh_token", "token", "api_key", "apikey", "client_secret", "password", "secret"}; constexpr std::array kJwtClaims = { "iss", "sub", "aud", "azp", "client_id", "scope", "scp", "exp", "iat", "nbf", "kubernetes.io"}; diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc index 65894c6917f..9c09c474eea 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc @@ -46,11 +46,11 @@ TEST(CredentialsTest, FingerprintIsSha256Prefix) { } TEST(CredentialsTest, BearerJwtKeepsClaimsAndDropsToken) { - const std::string token = - Jwt(R"({"alg":"RS256","kid":"k1"})", - R"({"iss":"https://kubernetes.default.svc","sub":"system:serviceaccount:credscope:sa-over",)" - R"("aud":["https://kubernetes.default.svc"],"exp":1763600000,"iat":1763599400,)" - R"("kubernetes.io":{"namespace":"credscope"},"canary":"cs-canary-1"})"); + const std::string token = Jwt( + R"({"alg":"RS256","kid":"k1"})", + R"({"iss":"https://kubernetes.default.svc","sub":"system:serviceaccount:credscope:sa-over",)" + R"("aud":["https://kubernetes.default.svc"],"exp":1763600000,"iat":1763599400,)" + R"("kubernetes.io":{"namespace":"credscope"},"canary":"cs-canary-1"})"); std::optional redacted = RedactCredentialHeader("Authorization", absl::StrCat("Bearer ", token)); @@ -115,13 +115,12 @@ TEST(CredentialsTest, SetCookieKeepsAttributes) { TEST(CredentialsTest, WebSocketBearerSubprotocolIsRedacted) { const std::string token = Jwt(R"({"alg":"RS256"})", R"({"sub":"system:serviceaccount:a:b"})"); const std::string encoded = absl::WebSafeBase64Escape(token); - EXPECT_EQ( - RedactCredentialHeader("Sec-WebSocket-Protocol", - absl::StrCat("v5.channel.k8s.io, base64url.bearer.authorization.k8s.io.", - encoded)), - absl::StrCat("v5.channel.k8s.io, base64url.bearer.authorization.k8s.io.)")); + EXPECT_EQ(RedactCredentialHeader( + "Sec-WebSocket-Protocol", + absl::StrCat("v5.channel.k8s.io, base64url.bearer.authorization.k8s.io.", encoded)), + absl::StrCat("v5.channel.k8s.io, base64url.bearer.authorization.k8s.io.)")); EXPECT_EQ(RedactCredentialHeader("sec-websocket-protocol", "v4.channel.k8s.io"), "v4.channel.k8s.io"); } @@ -174,7 +173,8 @@ TEST(CredentialsTest, NonCredentialFieldsAreKept) { TEST(CredentialsTest, HeaderMapsAreRedacted) { HeadersMap headers = {{"Authorization", "Bearer cs-canary-14"}, {"Accept", "*/*"}}; RedactCredentials(&headers); - EXPECT_EQ(headers.find("authorization")->second, absl::StrCat("Bearer ", Redacted("cs-canary-14"))); + EXPECT_EQ(headers.find("authorization")->second, + absl::StrCat("Bearer ", Redacted("cs-canary-14"))); EXPECT_EQ(headers.find("accept")->second, "*/*"); std::multimap nv = {{":path", "/svc.Orders/Get?token=cs-canary-15"}, diff --git a/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc index 551312b1073..5f1660a1a75 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc @@ -18,8 +18,8 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/tls/parse.h" #include -#include #include +#include #include #include #include @@ -77,12 +77,18 @@ constexpr std::pair kCipherSuiteNames[] = { }; constexpr std::pair kGroupNames[] = { - {0x0017, "secp256r1"}, {0x0018, "secp384r1"}, - {0x0019, "secp521r1"}, {0x001d, "x25519"}, - {0x001e, "x448"}, {0x0100, "ffdhe2048"}, - {0x0101, "ffdhe3072"}, {0x0200, "MLKEM512"}, - {0x0201, "MLKEM768"}, {0x0202, "MLKEM1024"}, - {0x11eb, "SecP256r1MLKEM768"}, {0x11ec, "X25519MLKEM768"}, + {0x0017, "secp256r1"}, + {0x0018, "secp384r1"}, + {0x0019, "secp521r1"}, + {0x001d, "x25519"}, + {0x001e, "x448"}, + {0x0100, "ffdhe2048"}, + {0x0101, "ffdhe3072"}, + {0x0200, "MLKEM512"}, + {0x0201, "MLKEM768"}, + {0x0202, "MLKEM1024"}, + {0x11eb, "SecP256r1MLKEM768"}, + {0x11ec, "X25519MLKEM768"}, {0x6399, "X25519Kyber768Draft00"}, }; @@ -168,7 +174,8 @@ void ExtractServerHelloExtension(SharedExtensions* exts, uint16_t type, std::str std::string ServerHelloBody(const SharedExtensions& exts, uint16_t handshake_version, uint16_t cipher_suite) { JSONObjectBuilder builder; - builder.WriteKV("version", CodeName(kVersionNames, exts.selected_version.value_or(handshake_version))); + builder.WriteKV("version", + CodeName(kVersionNames, exts.selected_version.value_or(handshake_version))); builder.WriteKV("cipher_suite", CodeName(kCipherSuiteNames, cipher_suite)); if (exts.key_share_group.has_value()) { builder.WriteKV("key_share_group", CodeName(kGroupNames, exts.key_share_group.value())); diff --git a/src/stirling/source_connectors/socket_tracer/protocols/tls/test_utils.h b/src/stirling/source_connectors/socket_tracer/protocols/tls/test_utils.h index 68e3d2e9826..2aa2a798821 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/tls/test_utils.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/tls/test_utils.h @@ -31,10 +31,10 @@ namespace testutils { inline std::string TLSRecord(uint8_t handshake_type, std::string_view body) { using std::string_view_literals::operator""sv; - std::string handshake = absl::StrCat(std::string(1, static_cast(handshake_type)), - std::string(1, '\0'), - std::string(1, static_cast(body.size() >> 8)), - std::string(1, static_cast(body.size() & 0xff)), body); + std::string handshake = + absl::StrCat(std::string(1, static_cast(handshake_type)), std::string(1, '\0'), + std::string(1, static_cast(body.size() >> 8)), + std::string(1, static_cast(body.size() & 0xff)), body); return absl::StrCat("\x16\x03\x01"sv, std::string(1, static_cast(handshake.size() >> 8)), std::string(1, static_cast(handshake.size() & 0xff)), handshake); } diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index 6054756aba7..11fd19cbab9 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -884,8 +884,8 @@ void SocketTraceConnector::TransferDataImpl(ConnectorContext* ctx) { socket_info_mgr_.get()); const auto& handed_over_spec = protocol_transfer_specs_[conn_tracker->protocol()]; if (handed_over_spec.transfer_fn != nullptr) { - current_conn_tracker_buffer_size += handed_over_spec.transfer_fn( - *this, ctx, conn_tracker, table_for(handed_over_spec)); + current_conn_tracker_buffer_size += + handed_over_spec.transfer_fn(*this, ctx, conn_tracker, table_for(handed_over_spec)); } } } else { @@ -1482,8 +1482,8 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke // Do not apply truncation at this point, as the truncation was already done on serialized // protobuf message. This might result into longer text format data here, but the increase is // minimal. - r.Append( - protocols::http::RedactCredentialBody(req_stream->ConsumeData()), kNoTruncation); + r.Append(protocols::http::RedactCredentialBody(req_stream->ConsumeData()), + kNoTruncation); r.Append(resp_stream->original_data_size()); r.Append( protocols::http::RedactCredentialBody(resp_stream->ConsumeData()), kNoTruncation); diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc index 58baa94b088..1bc3a6fc2b1 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector_test.cc @@ -358,8 +358,8 @@ TEST_F(SocketTraceConnectorWebSocketTest, UpgradedConnectionProducesWebSocketEve } TEST_F(SocketTraceConnectorWebSocketTest, TextPayloadCredentialsAreRedacted) { - RecordBatch records = TransferUpgradedServerFrames( - absl::StrCat("\x81\x18", R"({"token":"cs-canary-25"})")); + RecordBatch records = + TransferUpgradedServerFrames(absl::StrCat("\x81\x18", R"({"token":"cs-canary-25"})")); ASSERT_THAT(records, RecordBatchSizeIs(1)); EXPECT_THAT(ToStringVector(records[kWebSocketPayloadIdx]), ElementsAre(AllOf(HasSubstr(" Date: Fri, 20 Nov 2026 16:30:02 +0100 Subject: [PATCH 49/51] Drop a redundant include from the HTTP parser Signed-off-by: entlein --- .../source_connectors/socket_tracer/protocols/http/parse.cc | 1 - 1 file changed, 1 deletion(-) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc index b97c625dd84..470519d2441 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc @@ -19,7 +19,6 @@ #include "src/stirling/source_connectors/socket_tracer/protocols/http/parse.h" #include "src/stirling/source_connectors/socket_tracer/protocols/http/body_decoder.h" -#include #include #include From d6c8416b415c62cb3d59da6a8361a128e51225f6 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 22:06:16 +0100 Subject: [PATCH 50/51] Test that WebSocket records carry the request path Signed-off-by: entlein --- .../protocols/websocket/stitcher_test.cc | 12 ++++++++++++ .../socket_tracer/protocols/websocket/types.h | 1 + 2 files changed, 13 insertions(+) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc index d3af1a8a9f4..0dc186d2bc5 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc @@ -197,6 +197,16 @@ TEST_F(WebSocketStitcherTest, RawFramesCarrySubprotocol) { EXPECT_EQ(result.records[0].subprotocol, "graphql-transport-ws"); } +TEST_F(WebSocketStitcherTest, RawFramesCarryRequestPath) { + state_.global.path = "/echo?room=1"; + req_frames_.push_back(MakeFrame(Opcode::kText, true, "hi", 1)); + + RecordsWithErrorCount result = Stitch(); + + ASSERT_EQ(result.records.size(), 1U); + EXPECT_EQ(result.records[0].req_path, "/echo?room=1"); +} + TEST_F(WebSocketStitcherTest, K8sExecSessionIsDecoded) { state_.global.subprotocol = "v5.channel.k8s.io"; state_.global.path = "/api/v1/namespaces/ns/pods/pod/exec?command=hostname&stdout=true"; @@ -213,6 +223,8 @@ TEST_F(WebSocketStitcherTest, K8sExecSessionIsDecoded) { EXPECT_EQ(result.records[1].kind, RecordKind::kExit); EXPECT_EQ(result.records[1].output, "pod\n"); EXPECT_EQ(result.records[1].subprotocol, "v5.channel.k8s.io"); + EXPECT_EQ(result.records[1].req_path, + "/api/v1/namespaces/ns/pods/pod/exec?command=hostname&stdout=true"); EXPECT_TRUE(resp_frames_.empty()); } diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h index 1df6e85c160..6d222a537c4 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h @@ -101,6 +101,7 @@ struct Record { Message msg; RecordKind kind = RecordKind::kFrame; std::string subprotocol; + std::string req_path; std::string output; size_t output_size = 0; From 75022c0fbefa694eb69cd855a0118cd454f34611 Mon Sep 17 00:00:00 2001 From: entlein Date: Fri, 20 Nov 2026 22:06:16 +0100 Subject: [PATCH 51/51] Add the request path to WebSocket records Signed-off-by: entlein --- .../socket_tracer/protocols/websocket/stitcher.cc | 1 + .../socket_tracer/socket_trace_connector.cc | 1 + .../source_connectors/socket_tracer/websocket_table.h | 5 +++++ .../socket_tracer/websocket_trace_bpf_test.cc | 3 +++ 4 files changed, 10 insertions(+) diff --git a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc index ac951152150..da284dcfcb8 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc @@ -129,6 +129,7 @@ RecordsWithErrorCount StitchFrames(std::dequesubprotocol; + record.req_path = global->path; } return result; } diff --git a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc index 11fd19cbab9..570c62ba7d1 100644 --- a/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc +++ b/src/stirling/source_connectors/socket_tracer/socket_trace_connector.cc @@ -1848,6 +1848,7 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke r.Append(msg.payload_size); r.Append(printable(record.output), FLAGS_max_body_bytes); r.Append(record.output_size); + r.Append(protocols::http::RedactCredentialPath(record.req_path)); #ifndef NDEBUG r.Append(PXInfoString(conn_tracker, record)); #endif diff --git a/src/stirling/source_connectors/socket_tracer/websocket_table.h b/src/stirling/source_connectors/socket_tracer/websocket_table.h index d6cf1507433..792383a4faf 100644 --- a/src/stirling/source_connectors/socket_tracer/websocket_table.h +++ b/src/stirling/source_connectors/socket_tracer/websocket_table.h @@ -76,6 +76,10 @@ static constexpr DataElement kWebSocketElements[] = { types::DataType::INT64, types::SemanticType::ST_BYTES, types::PatternType::METRIC_GAUGE}, + {"req_path", "Request path of the HTTP request that opened the connection", + types::DataType::STRING, + types::SemanticType::ST_NONE, + types::PatternType::GENERAL}, #ifndef NDEBUG canonical_data_elements::kPXInfo, #endif @@ -96,6 +100,7 @@ constexpr int kWebSocketPayloadIdx = kWebSocketTable.ColIndex("payload"); constexpr int kWebSocketPayloadSizeIdx = kWebSocketTable.ColIndex("payload_size"); constexpr int kWebSocketOutputIdx = kWebSocketTable.ColIndex("output"); constexpr int kWebSocketOutputSizeIdx = kWebSocketTable.ColIndex("output_size"); +constexpr int kWebSocketReqPathIdx = kWebSocketTable.ColIndex("req_path"); } // namespace stirling } // namespace px diff --git a/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc b/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc index 19a02b69365..d3a6483c781 100644 --- a/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc +++ b/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc @@ -90,9 +90,11 @@ TEST_F(WebSocketTraceTest, PlainAndTLSEchoSessions) { FindRecordIdxMatchesPID(record_batch, kWebSocketUPIDIdx, server_.process_pid()); std::vector rows; std::vector subprotocols; + std::vector req_paths; for (size_t i : indices) { rows.push_back(Row(record_batch, i)); subprotocols.push_back(record_batch[kWebSocketSubprotocolIdx]->Get(i)); + req_paths.push_back(record_batch[kWebSocketReqPathIdx]->Get(i)); } std::vector expected; @@ -108,6 +110,7 @@ TEST_F(WebSocketTraceTest, PlainAndTLSEchoSessions) { } EXPECT_THAT(rows, IsSupersetOf(expected)); EXPECT_THAT(subprotocols, Each(std::string("echo.pixie"))); + EXPECT_THAT(req_paths, Each(std::string("/echo"))); } } // namespace stirling