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/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/bcc_bpf/socket_trace.c b/src/stirling/source_connectors/socket_tracer/bcc_bpf/socket_trace.c index 68a23dda923..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 @@ -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. 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..e0b88110bee 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(); @@ -146,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); @@ -158,7 +171,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; } @@ -245,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) { @@ -322,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) { @@ -376,7 +399,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(); } @@ -674,7 +697,8 @@ 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()); return res; @@ -812,6 +836,55 @@ void ConnTracker::IterationPreTick( UpdateState(cluster_cidrs); } +bool ConnTracker::MaybeUpgradeToWebSocket() { + if (protocol_ != kProtocolHTTP) { + return false; + } + auto* state = protocol_state(); + if (state == nullptr || !state->global.websocket_upgrade_accepted) { + 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); + ws_state.global.conn_closed = state->global.conn_closed; + + CONN_TRACE(1) << "Protocol upgraded: HTTP->WebSocket"; + upgraded_from_ = protocol_; + protocol_ = kProtocolWebSocket; + protocol_state_ = std::move(ws_state); + send_data_.SwitchProtocol(protocol_); + recv_data_.SwitchProtocol(protocol_); + 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 3a272e4b2c1..a88bbb9528f 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); @@ -327,6 +328,8 @@ class ConnTracker : NotCopyMoveable { } const conn_id_t& conn_id() const { return conn_id_; } + bool MaybeHandOverFromTLS(); + traffic_protocol_t protocol() const { return protocol_; } endpoint_role_t role() const { return role_; } bool ssl() const { return ssl_; } @@ -481,6 +484,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, @@ -703,6 +708,12 @@ class ConnTracker : NotCopyMoveable { bool is_tracked_upid_ = false; 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/conn_tracker_http2_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_http2_test.cc index d22832212ad..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 @@ -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); @@ -361,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), @@ -451,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/conn_tracker_test.cc b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc index 66917a1c3f6..5feacf4b2f5 100644 --- a/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc +++ b/src/stirling/source_connectors/socket_tracer/conn_tracker_test.cc @@ -19,18 +19,23 @@ #include "src/stirling/source_connectors/socket_tracer/conn_tracker.h" #include +#include +#include #include #include #include #include +#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/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" @@ -42,10 +47,13 @@ using ::px::operator<<; namespace http = protocols::http; namespace mysql = protocols::mysql; +namespace tls = protocols::tls; +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 +359,235 @@ 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, 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, 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); +} + +using tls::testutils::ClientHello; +using tls::testutils::ServerHello; + +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" + "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..a1f00a68856 100644 --- a/src/stirling/source_connectors/socket_tracer/data_stream.cc +++ b/src/stirling/source_connectors/socket_tracer/data_stream.cc @@ -219,6 +219,11 @@ template void DataStream::ProcessBytesToFrames< template void DataStream::ProcessBytesToFrames(message_type_t type, protocols::NoState* state); +template void +DataStream::ProcessBytesToFrames( + 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/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/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/http/BUILD.bazel b/src/stirling/source_connectors/socket_tracer/protocols/http/BUILD.bazel index 883e2672b4f..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", ], ) @@ -61,6 +63,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..fa7ba14cff3 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials.cc @@ -0,0 +1,290 @@ +/* + * 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 +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace px { +namespace stirling { +namespace protocols { +namespace http { + +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::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"}; +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 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('='); + 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::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 (absl::EqualsIgnoreCase(name, "sec-websocket-protocol")) { + return RedactSubprotocols(value); + } + if (Contains(kUrlHeaders, name)) { + return RedactCredentialPath(value); + } + return std::nullopt; +} + +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) { + if (body.find('"') == std::string_view::npos) { + return RedactParams(body); + } + return RedactCredentialFields(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..9c09c474eea --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/credentials_test.cc @@ -0,0 +1,191 @@ +/* + * 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, 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); +} + +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/protocols/http/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc index ae377dc2e77..470519d2441 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/parse.cc @@ -34,6 +34,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 +193,14 @@ 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; + const auto subprotocol_iter = result->headers.find(kSecWebSocketProtocol); + if (subprotocol_iter != result->headers.end()) { + state->websocket_subprotocol = subprotocol_iter->second; + } + return ParseState::kEOS; + } LOG(WARNING) << "HTTP upgrades are not yet supported"; return ParseState::kEOS; @@ -267,10 +285,24 @@ 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; + state->websocket_path = result->req_path; + } + 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/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 b7345329e3d..9ddead8c9a9 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" @@ -45,6 +46,8 @@ 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"; +inline constexpr char kSecWebSocketProtocol[] = "Sec-WebSocket-Protocol"; struct Message : public FrameBase { message_type_t type = message_type_t::kUnknown; @@ -102,6 +105,10 @@ struct Record { 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/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/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/tls/parse.cc b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc index d435772271f..5f1660a1a75 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc +++ b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse.cc @@ -19,10 +19,12 @@ #include #include +#include #include #include #include +#include #include #include "src/stirling/utils/binary_decoder.h" @@ -42,6 +44,148 @@ 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 kSupportedGroupsExtension = 0x000a; +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; +} + +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); + } 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 +290,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 +314,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 +324,26 @@ 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); + } else if (frame->handshake_type == HandshakeType::kClientHello) { + ExtractClientHelloExtension(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/parse_test.cc b/src/stirling/source_connectors/socket_tracer/protocols/tls/parse_test.cc index 9dc84c46a60..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 @@ -315,7 +315,10 @@ 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"],)" + R"("supported_groups":["x25519","secp256r1","secp384r1","secp521r1"],)" + R"("key_share_groups":["x25519"]}})"); ASSERT_EQ(state, ParseState::kSuccess); } @@ -334,6 +337,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 +353,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/protocols/tls/test_utils.h b/src/stirling/source_connectors/socket_tracer/protocols/tls/test_utils.h new file mode 100644 index 00000000000..2aa2a798821 --- /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/protocols/tls/types.h b/src/stirling/source_connectors/socket_tracer/protocols/tls/types.h index fdf65e6d95f..6954e5e6d7b 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,11 @@ enum class ExtensionType : uint16_t { // of a TLS handshake 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; virtual void ToJSON(::px::utils::JSONObjectBuilder* /*builder*/) const {} virtual ~SharedExtensions() = default; @@ -197,6 +203,15 @@ 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); + } + if (!supported_groups.empty()) { + builder->WriteKV("supported_groups", supported_groups); + } + if (!key_share_groups.empty()) { + builder->WriteKV("key_share_groups", key_share_groups); + } } }; 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/protocols/websocket/BUILD.bazel b/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel new file mode 100644 index 00000000000..e0f3c5f6d6b --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/BUILD.bazel @@ -0,0 +1,53 @@ +# 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"], +) + +pl_cc_test( + name = "stitcher_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..bb03ba4b81a --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.cc @@ -0,0 +1,564 @@ +/* + * 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 +#include +#include +#include +#include + +#include "src/common/base/base.h" + +namespace px { +namespace stirling { +namespace protocols { +namespace websocket { + +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'; +constexpr std::string_view kNoEchoPlaceholder = ""; +constexpr std::string_view kTarTruncatedLine = "[TRUNCATED]\n"; +constexpr size_t kTarBlockSize = 512; +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') { + 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; +} + +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) { + 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 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) { + 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->manifest.size() >= kMaxBufferedOutput) { + return; + } + 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; + } +} + +void FeedTar(TarStream* tar, std::string_view data, uint64_t lost, std::string* out) { + if (tar->checked && !tar->is_tar) { + AppendCapped(out, data); + return; + } + 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->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; + 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) { + AppendCapped(out, tar->held); + AppendCapped(out, data.substr(pos)); + tar->held.clear(); + return; + } + } + ParseTarHeader(tar->held, tar); + tar->held.clear(); + } + LoseTarBytes(tar, lost, out); +} + +std::string DrainStream(TarStream* tar, std::string* buffer) { + 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; +} + +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); + record.msg.payload_size = record.msg.payload.size(); + return record; +} + +void TakeOutput(ExecState* state, Record* record) { + 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; +} + +void AppendOutput(ExecState* state, std::string_view data) { + state->output_size += data.size(); + 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.msg.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) { + if (!state->pending.has_value()) { + return; + } + 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(); +} + +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), + state->echoed || state->line.empty()}; + state->echoed = false; + 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(); + state->echoed = false; + 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; + } + if (state->line.size() < kMaxBufferedOutput) { + 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 path) { + return absl::StrJoin(QueryValues(path, "command"), " "); +} + +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 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) { + 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 path, std::vector messages, ExecState* state, + std::vector* records) { + for (Message& msg : messages) { + 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); + 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); + 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; + } + 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() + lost; + FeedTar(&state->stdin_tar, data, lost, &state->stdin_data); + } + continue; + } + switch (channel) { + case kStdoutChannel: + 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->echoed = true; + } + break; + case kStderrChannel: + if (!state->tty || state->line.empty()) { + AppendOutput(state, data); + } else { + state->echoed = true; + } + break; + 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 +} // 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..e30d403f110 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec.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 "src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h" + +namespace px { +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); + +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); + +void FinishK8sExec(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..6c0c9238588 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/k8s_exec_test.cc @@ -0,0 +1,568 @@ +/* + * 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 +#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); + msg.payload_size = msg.payload.size(); + 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), + 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; + + 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/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; + + DecodeK8sExec(kKubeletTTYPath, std::move(messages), &state, &records); + + EXPECT_THAT(records, ElementsAre(IsRecord(RecordKind::kExec, "sh", ""), + IsRecord(RecordKind::kInput, "cat /etc/hosts^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), Out(3, "\x01i")}, &state, + &records); + DecodeK8sExec(kKubeletTTYPath, + {In(4, + "\x00" + "d\r"sv), + Out(5, "\x01\r\nuid=0\r\n/ # ")}, + &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"), + 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()); +} + +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/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)))); + } + 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/group 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].msg.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].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()); +} + +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 +} // 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 new file mode 100644 index 00000000000..75dbee2bb89 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.cc @@ -0,0 +1,210 @@ +/* + * 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 +#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 { + +namespace websocket { +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; +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; + +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; +}; + +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); + + std::optional opcode = magic_enum::enum_cast(b0 & kOpcodeBits); + if (!opcode.has_value() || (b0 & kUnsupportedRsvBits)) { + return ParseState::kInvalid; + } + header->fin = b0 & kFinBit; + const bool control = IsControl(opcode.value()); + if (control && !header->fin) { + return ParseState::kInvalid; + } + + uint64_t payload_length = b1 & kPayloadLengthBits; + if (payload_length == kPayloadLength16) { + PX_ASSIGN_OR(payload_length, decoder->ExtractBEInt(), + return ParseState::kNeedsMoreData); + } else if (payload_length == kPayloadLength64) { + PX_ASSIGN_OR(payload_length, decoder->ExtractBEInt(), + return ParseState::kNeedsMoreData); + if (payload_length & kPayloadLength64MSB) { + return ParseState::kInvalid; + } + } + if (control && payload_length > kMaxControlPayloadLength) { + return ParseState::kInvalid; + } + + header->masked = b1 & kMaskBit; + if (header->masked) { + PX_ASSIGN_OR(header->masking_key, decoder->ExtractString(kMaskingKeySize), + 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; +} + +} // 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 (header.masked) { + for (size_t i = 0; i < frame->payload.size(); ++i) { + frame->payload[i] ^= header.masking_key[i % websocket::kMaskingKeySize]; + } + } + + 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 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; +} + +} // 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..af8619d8d8c --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.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 "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); + +template <> +size_t FindFrameBoundary(message_type_t type, std::string_view buf, + size_t start_pos, websocket::StateWrapper* 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..afdaf348bb5 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/parse_test.cc @@ -0,0 +1,302 @@ +/* + * 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_; + StateWrapper 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(), FLAGS_websocket_payload_limit_bytes); + 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); + + 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) { + 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); +} + +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 +} // namespace px 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..da284dcfcb8 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher.cc @@ -0,0 +1,139 @@ +/* + * 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 +#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 { +namespace protocols { + +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) { + 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); + msg.payload_size = frame->payload_length; + return msg; +} + +int StitchDirection(message_type_t type, size_t payload_limit, std::deque* frames, + std::vector* messages) { + int error_count = 0; + std::deque pending; + + for (Frame& frame : *frames) { + if (IsControl(frame.opcode)) { + messages->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) { + 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)); + pending.clear(); + } + + *frames = std::move(pending); + return error_count; +} + +} // namespace +} // namespace websocket + +template <> +RecordsWithErrorCount StitchFrames(std::deque* req_frames, + std::deque* resp_frames, + websocket::StateWrapper* state) { + RecordsWithErrorCount 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); + + 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); + 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) { + msg.payload = websocket::kCompressedPlaceholder; + } + websocket::Record record; + record.msg = std::move(msg); + result.records.push_back(std::move(record)); + } + } + for (websocket::Record& record : result.records) { + record.subprotocol = global->subprotocol; + record.req_path = global->path; + } + return result; +} + +} // 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..c2db5f9e07f --- /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, + websocket::StateWrapper* 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..0dc186d2bc5 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/stitcher_test.cc @@ -0,0 +1,268 @@ +/* + * 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 + +#include "src/common/testing/testing.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/websocket/parse.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_; + StateWrapper 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)); + 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.payload_size, 5U); + EXPECT_EQ(result.records[0].msg.timestamp_ns, 1U); + EXPECT_EQ(result.records[0].msg.fragments, 2U); + 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)); + 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()); +} + +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, 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"; + 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_EQ(result.records[1].req_path, + "/api/v1/namespaces/ns/pods/pod/exec?command=hostname&stdout=true"); + 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 +} // 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..6d222a537c4 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/protocols/websocket/types.h @@ -0,0 +1,192 @@ +/* + * 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/common/base/base.h" +#include "src/stirling/source_connectors/socket_tracer/protocols/common/event_parser.h" + +namespace px { +namespace stirling { +namespace protocols { +namespace websocket { + +using stream_id_t = uint16_t; + +enum class Opcode : uint8_t { + kContinuation = 0x0, + kText = 0x1, + kBinary = 0x2, + kClose = 0x8, + kPing = 0x9, + kPong = 0xa, +}; + +inline bool IsControl(Opcode opcode) { return static_cast(opcode) & 0x8; } + +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); + } +}; + +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; + 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); + } +}; + +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 req_path; + 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 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 truncated = false; + bool long_name = false; + std::string held; + uint64_t skip = 0; + uint64_t capture_left = 0; + std::string next_name; + 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 exited = false; + uint64_t last_timestamp_ns = 0; + bool tty = false; + bool last_cr = false; + bool echoed = false; + std::string line; + uint64_t line_timestamp_ns = 0; + 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 { + std::string path; + std::string subprotocol; + bool conn_closed = false; + uint32_t stitches_since_close = 0; + ExecState exec; +}; + +struct DirectionState { + uint64_t skip = 0; +}; + +struct StateWrapper { + State global; + DirectionState send; + DirectionState recv; +}; + +struct ProtocolTraits : public BaseProtocolTraits { + using frame_type = Frame; + using record_type = Record; + using state_type = StateWrapper; + 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 +} // namespace px 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..570c62ba7d1 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,8 +46,10 @@ #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" #include "src/stirling/utils/linux_headers.h" #include "src/stirling/utils/proc_path_tools.h" @@ -122,6 +125,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,6 +311,10 @@ void SocketTraceConnector::InitProtocolTransferSpecs() { kTLSTableNum, {kRoleClient, kRoleServer}, TRANSFER_STREAM_PROTOCOL(tls)}}, + {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 */ {}, @@ -840,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); @@ -865,6 +876,18 @@ 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(); + } + 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 @@ -1327,6 +1350,16 @@ int64_t AMQPCalculateLatency(const int64_t req_timestamp_ns, const int64_t resp_ return latency_ns; } +constexpr size_t kNoTruncation = 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()); @@ -1344,6 +1377,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); @@ -1369,14 +1404,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), 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(std::move(resp_message.body), FLAGS_max_body_bytes); + r.Append(RedactedBody(resp_message.body), kNoTruncation); r.Append( CalculateLatency(req_message.timestamp_ns, resp_message.timestamp_ns)); #ifndef NDEBUG @@ -1411,6 +1446,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; @@ -1445,9 +1482,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()), + kNoTruncation); r.Append(resp_stream->original_data_size()); - r.Append(resp_stream->ConsumeData()); + r.Append( + 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. @@ -1773,6 +1812,48 @@ void SocketTraceConnector::AppendMessage(ConnectorContext* ctx, const ConnTracke #endif } +template <> +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); + + 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(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); + 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(RedactedBody(msg.payload), kNoTruncation); + } else { + r.Append(printable(msg.payload), FLAGS_max_body_bytes); + } + 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 +} + 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..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 @@ -19,8 +19,11 @@ #include "src/stirling/source_connectors/socket_tracer/socket_trace_connector.h" #include +#include #include +#include +#include #include #include @@ -31,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" @@ -40,7 +44,10 @@ namespace stirling { namespace http = protocols::http; +using ::testing::AllOf; using ::testing::ElementsAre; +using ::testing::HasSubstr; +using ::testing::Not; using ::px::stirling::testing::RecordBatchSizeIs; @@ -223,6 +230,238 @@ 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 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 { + FLAGS_stirling_enable_websocket_tracing = TraceMode::On; + SocketTraceConnectorTest::SetUp(); + } + + 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]; +}; + +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("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)); +} + +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(" 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(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 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 = + "\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_.InitRecvEvent(kEchoId)); + 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(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); 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/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/tls_trace_bpf_test.cc b/src/stirling/source_connectors/socket_tracer/tls_trace_bpf_test.cc index 7931cc9f53e..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" @@ -43,9 +44,9 @@ 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; using ::testing::UnorderedElementsAre; class NginxOpenSSL_3_0_8_ContainerWrapper @@ -114,8 +115,22 @@ 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_)")); + + 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. 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..792383a4faf --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/websocket_table.h @@ -0,0 +1,106 @@ +/* + * 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, + {"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, + 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}, + {"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}, + {"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 +}; +// clang-format on + +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"); +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"); +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 new file mode 100644 index 00000000000..d3a6483c781 --- /dev/null +++ b/src/stirling/source_connectors/socket_tracer/websocket_trace_bpf_test.cc @@ -0,0 +1,117 @@ +/* + * 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 + +#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::ElementsAre; +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) { + 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); + + const std::vector indices = + 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; + 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"))); + EXPECT_THAT(req_paths, Each(std::string("/echo"))); +} + +} // 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..4afe0b64262 --- /dev/null +++ b/src/stirling/testing/demo_apps/go_websocket/client/BUILD.bazel @@ -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 + +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..63cc86735e4 --- /dev/null +++ b/src/stirling/testing/demo_apps/go_websocket/server/BUILD.bazel @@ -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 + +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)) +}