/src/PcapPlusPlus/Packet++/header/MySqlLayer.h
Line | Count | Source |
1 | | #pragma once |
2 | | |
3 | | #include "Layer.h" |
4 | | #include "PointerVector.h" |
5 | | #include <algorithm> |
6 | | #include <initializer_list> |
7 | | #include <iterator> |
8 | | #include <memory> |
9 | | #include <ostream> |
10 | | #include <unordered_map> |
11 | | |
12 | | /// @file |
13 | | |
14 | | /// @namespace pcpp |
15 | | /// @brief The main namespace for the PcapPlusPlus lib |
16 | | namespace pcpp |
17 | | { |
18 | | |
19 | | /// @enum MySqlMessageOrigin |
20 | | /// Indicates whether the message is from the client or server |
21 | | enum class MySqlMessageOrigin |
22 | | { |
23 | | /// Message is from the MySQL client |
24 | | Client, |
25 | | /// Message is from the MySQL server |
26 | | Server |
27 | | }; |
28 | | |
29 | | /// @class MySqlMessageType |
30 | | /// Represents MySQL message types |
31 | | class MySqlMessageType |
32 | | { |
33 | | public: |
34 | | /// Define enum types for MySQL message types |
35 | | enum Value : uint8_t |
36 | | { |
37 | | /// Handshake response |
38 | | Client_HandshakeResponse, |
39 | | /// COM_SLEEP command |
40 | | Client_Sleep, |
41 | | /// COM_QUIT command - close connection |
42 | | Client_Quit, |
43 | | /// COM_INIT_DB command - change default database |
44 | | Client_InitDb, |
45 | | /// COM_QUERY command - execute SQL query |
46 | | Client_Query, |
47 | | /// COM_FIELD_LIST command - get field information for a table |
48 | | Client_FieldList, |
49 | | /// COM_CREATE_DB command |
50 | | Client_CreateDb, |
51 | | /// COM_DROP_DB command |
52 | | Client_DropDb, |
53 | | /// COM_REFRESH command - flush tables, caches, or logs |
54 | | Client_Refresh, |
55 | | /// COM_SHUTDOWN command - shutdown the server |
56 | | Client_Shutdown, |
57 | | /// COM_STATISTICS command - get server status information |
58 | | Client_Statistics, |
59 | | /// COM_PROCESS_INFO command - get list of active threads |
60 | | Client_ProcessInfo, |
61 | | /// COM_CONNECT command - connect to server (internal use) |
62 | | Client_Connect, |
63 | | /// COM_PROCESS_KILL command - kill a server thread |
64 | | Client_ProcessKill, |
65 | | /// COM_DEBUG command - send debug info to server |
66 | | Client_Debug, |
67 | | /// COM_PING command - check server availability |
68 | | Client_Ping, |
69 | | /// COM_TIME command |
70 | | Client_Time, |
71 | | /// COM_DELAYED_INSERT command |
72 | | Client_DelayedInsert, |
73 | | /// COM_CHANGE_USER command - change user and database |
74 | | Client_ChangeUser, |
75 | | /// COM_BINLOG_DUMP command - start binary log dump (slave replication) |
76 | | Client_BinlogDump, |
77 | | /// COM_TABLE_DUMP command - dump table data (slave replication) |
78 | | Client_TableDump, |
79 | | /// COM_CONNECT_OUT command - slave connecting to master (internal use) |
80 | | Client_ConnectOut, |
81 | | /// COM_REGISTER_SLAVE command - register slave with master |
82 | | Client_RegisterSlave, |
83 | | /// COM_STMT_PREPARE command - prepare statement |
84 | | Client_StmtPrepare, |
85 | | /// COM_STMT_EXECUTE command - execute prepared statement |
86 | | Client_StmtExecute, |
87 | | /// COM_STMT_FETCH command - fetch rows from prepared statement |
88 | | Client_StmtFetch, |
89 | | /// COM_STMT_CLOSE command - close prepared statement |
90 | | Client_StmtClose, |
91 | | /// COM_STMT_RESET command - reset prepared statement data |
92 | | Client_StmtReset, |
93 | | /// COM_SET_OPTION command - set option (e.g., multi-statements) |
94 | | Client_SetOption, |
95 | | /// COM_STMT_SEND_LONG_DATA command - send long data for prepared statement |
96 | | Client_StmtSendLongData, |
97 | | /// COM_DAEMON command |
98 | | Client_Daemon, |
99 | | /// COM_BINLOG_DUMP_GTID command - start GTID-based binary log dump |
100 | | Client_BinlogDumpGtid, |
101 | | /// COM_RESET_CONNECTION command - reset connection without re-authentication |
102 | | Client_ResetConnection, |
103 | | /// COM_CLONE command |
104 | | Client_Clone, |
105 | | |
106 | | /// Initial handshake |
107 | | Server_Handshake, |
108 | | /// OK packet - successful response from server |
109 | | Server_Ok, |
110 | | /// AuthSwitchRequest packet - server requests authentication method switch |
111 | | Server_AuthSwitchRequest, |
112 | | /// EOF message |
113 | | Server_EOF, |
114 | | /// Error packet - error response from server |
115 | | Server_Error, |
116 | | /// Server message that contains data (could be column definition, row data, result set header, etc.) |
117 | | Server_Data, |
118 | | |
119 | | /// Unknown message |
120 | | Unknown |
121 | | }; |
122 | | |
123 | | constexpr MySqlMessageType() : m_Value(Unknown) |
124 | 0 | {} |
125 | | |
126 | | // cppcheck-suppress noExplicitConstructor |
127 | | /// @brief Constructs a MySqlMessageType object from a Value enum |
128 | | /// @param[in] value The Value enum value |
129 | 0 | constexpr MySqlMessageType(Value value) : m_Value(value) |
130 | 0 | {} |
131 | | |
132 | | /// @brief Returns a string representation of the message type |
133 | | /// @return A string representation of the message type |
134 | | std::string toString() const; |
135 | | |
136 | | /// @brief Stream operator for MySqlMessageType |
137 | | /// @param[in] os The output stream |
138 | | /// @param[in] messageType The message type to print |
139 | | /// @return The output stream |
140 | | friend std::ostream& operator<<(std::ostream& os, const MySqlMessageType& messageType) |
141 | 0 | { |
142 | 0 | os << messageType.toString(); |
143 | 0 | return os; |
144 | 0 | } |
145 | | |
146 | | /// @brief Converts the message type to a string |
147 | | /// @return The message type as a string |
148 | | explicit operator std::string() const |
149 | 0 | { |
150 | 0 | return toString(); |
151 | 0 | } |
152 | | |
153 | | /// @brief Returns the origin of the message (client or server) |
154 | | /// @return The message origin |
155 | | MySqlMessageOrigin getOrigin() const; |
156 | | |
157 | | // Allow switch and comparisons |
158 | | constexpr operator Value() const |
159 | 0 | { |
160 | 0 | return m_Value; |
161 | 0 | } |
162 | | |
163 | | // Prevent usage: if(MySqlMessageType) |
164 | | explicit operator bool() const = delete; |
165 | | |
166 | | private: |
167 | | Value m_Value; |
168 | | }; |
169 | | |
170 | | /// @class MySqlMessage |
171 | | /// Represents a MySQL message (base class) |
172 | | class MySqlMessage |
173 | | { |
174 | | public: |
175 | 0 | virtual ~MySqlMessage() = default; |
176 | | |
177 | | /// @brief Parse a MySQL message from raw data |
178 | | /// @param[in] data A pointer to the raw data |
179 | | /// @param[in] dataLen Size of the data in bytes |
180 | | /// @param[in] origin The message origin (client or server) |
181 | | /// @return A unique pointer to the parsed MySqlMessage, or nullptr if parsing fails |
182 | | static std::unique_ptr<MySqlMessage> parseMySqlMessage(const uint8_t* data, size_t dataLen, |
183 | | MySqlMessageOrigin origin); |
184 | | |
185 | | /// @return The message type |
186 | | MySqlMessageType getMessageType() const |
187 | 0 | { |
188 | 0 | return m_MessageType; |
189 | 0 | } |
190 | | |
191 | | /// @return The message origin (client or server) |
192 | | MySqlMessageOrigin getMessageOrigin() const |
193 | 0 | { |
194 | 0 | return m_MessageOrigin; |
195 | 0 | } |
196 | | |
197 | | /// @brief Returns the length of the message payload |
198 | | /// @return The message length |
199 | | virtual uint32_t getMessageLength() const; |
200 | | |
201 | | /// @brief Returns the packet number |
202 | | /// @return The packet number |
203 | | uint8_t getPacketNumber() const; |
204 | | |
205 | | /// @brief Returns the total length of the message including the length field |
206 | | /// @return The total message length in bytes |
207 | | size_t getTotalMessageLength() const |
208 | 0 | { |
209 | 0 | return m_DataLen; |
210 | 0 | } |
211 | | |
212 | | /// @brief Returns the raw payload bytes of the message |
213 | | /// @return The raw payload bytes of the message |
214 | | virtual std::vector<uint8_t> getRawPayload() const; |
215 | | |
216 | | protected: |
217 | | MySqlMessage(const uint8_t* data, size_t dataLen, const MySqlMessageType& messageType, |
218 | | MySqlMessageOrigin origin) |
219 | 0 | : m_Data(data), m_DataLen(dataLen), m_MessageType(messageType), m_MessageOrigin(origin) |
220 | 0 | {} |
221 | | |
222 | | static constexpr int basicMessageLength = 4; |
223 | | static constexpr int commandLength = 1; |
224 | | static constexpr int packetNumberIndex = 3; |
225 | | static constexpr int commandIndex = packetNumberIndex + 1; |
226 | | |
227 | | const uint8_t* m_Data; |
228 | | size_t m_DataLen; |
229 | | MySqlMessageType m_MessageType; |
230 | | MySqlMessageOrigin m_MessageOrigin; |
231 | | }; |
232 | | |
233 | | /// @class MySqlCommandMessage |
234 | | /// Represents a MySQL messages that are commands such as Query (3), StatementPrepare (22), etc. |
235 | | /// Or that messages that have response code such as Ok (0), Error (0xFF) |
236 | | class MySqlCommandMessage : public MySqlMessage |
237 | | { |
238 | | friend class MySqlMessage; |
239 | | |
240 | | public: |
241 | | uint32_t getMessageLength() const override; |
242 | | std::vector<uint8_t> getRawPayload() const override; |
243 | | |
244 | | protected: |
245 | | MySqlCommandMessage(const uint8_t* data, size_t dataLen, const MySqlMessageType& messageType, |
246 | | MySqlMessageOrigin origin) |
247 | 0 | : MySqlMessage(data, dataLen, messageType, origin) |
248 | 0 | {} |
249 | | }; |
250 | | |
251 | | /// @class MySqlQueryMessage |
252 | | /// Represents a MySQL query command message |
253 | | class MySqlQueryMessage : public MySqlCommandMessage |
254 | | { |
255 | | friend class MySqlMessage; |
256 | | |
257 | | public: |
258 | | /// @return The SQL query string |
259 | | std::string getQuery() const; |
260 | | |
261 | | protected: |
262 | | MySqlQueryMessage(const uint8_t* data, size_t dataLen) |
263 | 0 | : MySqlCommandMessage(data, dataLen, MySqlMessageType::Client_Query, MySqlMessageOrigin::Client) |
264 | 0 | {} |
265 | | |
266 | | private: |
267 | | static constexpr int statementIndex = commandIndex + 3; |
268 | | }; |
269 | | |
270 | | /// @class MySqlErrorMessage |
271 | | /// Represents a MySQL error message from the server |
272 | | class MySqlErrorMessage : public MySqlCommandMessage |
273 | | { |
274 | | friend class MySqlMessage; |
275 | | |
276 | | public: |
277 | | /// @return The MySQL error code |
278 | | uint16_t getErrorCode() const; |
279 | | |
280 | | /// @return The SQL state string (5 characters) |
281 | | std::string getSqlState() const; |
282 | | |
283 | | /// @return The error message string |
284 | | std::string getErrorMessage() const; |
285 | | |
286 | | protected: |
287 | | MySqlErrorMessage(const uint8_t* data, size_t dataLen) |
288 | 0 | : MySqlCommandMessage(data, dataLen, MySqlMessageType::Server_Error, MySqlMessageOrigin::Server) |
289 | 0 | {} |
290 | | |
291 | | private: |
292 | | static constexpr int errorCodeIndex = commandIndex + 1; |
293 | | static constexpr int sqlStateIndex = errorCodeIndex + sizeof(uint16_t) + 1; |
294 | | static constexpr int sqlStateSize = 5; |
295 | | static constexpr int errorMessageIndex = sqlStateIndex + sqlStateSize; |
296 | | }; |
297 | | |
298 | | /// @class MySqlLayer |
299 | | /// Represents a MySQL protocol layer |
300 | | class MySqlLayer : public Layer |
301 | | { |
302 | | public: |
303 | | /// @brief Destructor for this layer |
304 | 0 | ~MySqlLayer() override = default; |
305 | | |
306 | | /// @brief Check whether the port is considered as MySQL |
307 | | /// @param[in] port The port number to be checked |
308 | | /// @return True if the port is 3306 (MySQL default port), false otherwise |
309 | | static bool isMySqlPort(uint16_t port) |
310 | 0 | { |
311 | 0 | return port == 3306; |
312 | 0 | } |
313 | | |
314 | | /// @brief Parse a MySQL client message |
315 | | /// @param[in] data A pointer to the raw data |
316 | | /// @param[in] dataLen Size of the data in bytes |
317 | | /// @param[in] prevLayer The previous layer |
318 | | /// @param[in] packet The packet being parsed |
319 | | /// @return A pointer to the parsed MySqlLayer, or nullptr if parsing fails |
320 | | static MySqlLayer* parseMySqlClientMessage(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet); |
321 | | |
322 | | /// @brief Parse a MySQL server message |
323 | | /// @param[in] data A pointer to the raw data |
324 | | /// @param[in] dataLen Size of the data in bytes |
325 | | /// @param[in] prevLayer The previous layer |
326 | | /// @param[in] packet The packet being parsed |
327 | | /// @return A pointer to the parsed MySqlLayer, or nullptr if parsing fails |
328 | | static MySqlLayer* parseMySqlServerMessage(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet); |
329 | | |
330 | | /// @return The message origin (client or server) |
331 | | MySqlMessageOrigin getMySqlOrigin() const |
332 | 0 | { |
333 | 0 | return m_MessageOrigin; |
334 | 0 | } |
335 | | |
336 | | /// @return A vector of all MySQL messages in this layer |
337 | | const PointerVector<MySqlMessage>& getMySqlMessages() const; |
338 | | |
339 | | /// @brief Get a MySQL message by its type |
340 | | /// @param[in] messageType The type of message to retrieve |
341 | | /// @return A pointer to the message, or nullptr if not found |
342 | | const MySqlMessage* getMySqlMessage(const MySqlMessageType& messageType) const; |
343 | | |
344 | | /// @brief Get a MySQL message by its type (template version) |
345 | | /// @tparam TMessage The message type to retrieve (must derive from MySqlMessage) |
346 | | /// @return A pointer to the message of the specified type, or nullptr if not found |
347 | | template <class TMessage, std::enable_if_t<std::is_base_of<MySqlMessage, TMessage>::value, bool> = nullptr> |
348 | | const TMessage* getMySqlMessage() const |
349 | | { |
350 | | const auto& messages = getMySqlMessages(); |
351 | | for (const auto& msg : messages) |
352 | | { |
353 | | auto result = dynamic_cast<const TMessage*>(msg); |
354 | | if (result != nullptr) |
355 | | { |
356 | | return result; |
357 | | } |
358 | | } |
359 | | return nullptr; |
360 | | } |
361 | | |
362 | | // Overridden methods |
363 | | |
364 | | /// @return The size of the MySQL layer header in bytes |
365 | | size_t getHeaderLen() const override |
366 | 0 | { |
367 | 0 | return m_DataLen; |
368 | 0 | } |
369 | | |
370 | | /// Does nothing for this layer, MySQL is always last |
371 | | void parseNextLayer() override |
372 | 0 | {} |
373 | | |
374 | | /// Does nothing for this layer |
375 | | void computeCalculateFields() override |
376 | 0 | {} |
377 | | |
378 | | /// @return The OSI layer level of MySQL (Application Layer). |
379 | | OsiModelLayer getOsiModelLayer() const override |
380 | 0 | { |
381 | 0 | return OsiModelApplicationLayer; |
382 | 0 | } |
383 | | |
384 | | /// @return Returns the protocol info as readable string |
385 | | std::string toString() const override; |
386 | | |
387 | | /// @struct SerializedFields |
388 | | /// Fields written in addition to Layer::SerializedFields. |
389 | | struct SerializedFields : Layer::SerializedFields |
390 | | { |
391 | | /// @return All top-level MySQL layer field descriptors. |
392 | | static std::vector<FieldDescriptor> all() |
393 | 0 | { |
394 | 0 | auto result = Layer::SerializedFields::all(); |
395 | 0 | std::initializer_list<FieldDescriptor> extra{ Origin, Messages }; |
396 | 0 | std::copy(extra.begin(), extra.end(), std::back_inserter(result)); |
397 | 0 | return result; |
398 | 0 | } |
399 | | |
400 | | /// @struct MessageFields |
401 | | /// Fields common to all MySQL messages. |
402 | | struct MessageFields |
403 | | { |
404 | | /// @return The field descriptors common to all messages. |
405 | | static std::vector<FieldDescriptor> all() |
406 | 0 | { |
407 | 0 | return { Type, PacketNumber, PayloadLength }; |
408 | 0 | } |
409 | | |
410 | | /// @brief Message type string as returned by MySqlMessageType::toString(). |
411 | | static const FieldDescriptor Type; |
412 | | /// @brief One-byte MySQL packet sequence number. |
413 | | static const FieldDescriptor PacketNumber; |
414 | | /// @brief Payload length in bytes, excluding the four-byte message header and including any command |
415 | | /// byte. |
416 | | static const FieldDescriptor PayloadLength; |
417 | | }; |
418 | | |
419 | | /// @struct MessageObject |
420 | | /// Fields of a message with no type-specific fields. |
421 | | struct MessageObject : ObjectFieldDescriptor<MessageObject>, MessageFields |
422 | | { |
423 | | using ObjectFieldDescriptor::ObjectFieldDescriptor; |
424 | | }; |
425 | | |
426 | | /// @struct ErrorMessageObject |
427 | | /// Fields of a server error message. |
428 | | struct ErrorMessageObject : ObjectFieldDescriptor<ErrorMessageObject>, MessageFields |
429 | | { |
430 | | using ObjectFieldDescriptor::ObjectFieldDescriptor; |
431 | | |
432 | | /// @return All field descriptors for an error message. |
433 | | static std::vector<FieldDescriptor> all() |
434 | 0 | { |
435 | 0 | auto result = MessageFields::all(); |
436 | 0 | std::initializer_list<FieldDescriptor> extra{ ErrorCode, SqlState, ErrorMessage }; |
437 | 0 | std::copy(extra.begin(), extra.end(), std::back_inserter(result)); |
438 | 0 | return result; |
439 | 0 | } |
440 | | |
441 | | /// @brief Numeric MySQL error code in host byte order. |
442 | | static const FieldDescriptor ErrorCode; |
443 | | /// @brief SQL state, empty if unavailable. |
444 | | static const FieldDescriptor SqlState; |
445 | | /// @brief Error text as returned by MySqlErrorMessage::getErrorMessage(). |
446 | | static const FieldDescriptor ErrorMessage; |
447 | | }; |
448 | | |
449 | | /// @struct QueryMessageObject |
450 | | /// Fields of a client COM_QUERY message. |
451 | | struct QueryMessageObject : ObjectFieldDescriptor<QueryMessageObject>, MessageFields |
452 | | { |
453 | | using ObjectFieldDescriptor::ObjectFieldDescriptor; |
454 | | |
455 | | /// @return All field descriptors for a query message. |
456 | | static std::vector<FieldDescriptor> all() |
457 | 0 | { |
458 | 0 | auto result = MessageFields::all(); |
459 | 0 | std::initializer_list<FieldDescriptor> extra{ Query }; |
460 | 0 | std::copy(extra.begin(), extra.end(), std::back_inserter(result)); |
461 | 0 | return result; |
462 | 0 | } |
463 | | |
464 | | /// @brief SQL text as returned by MySqlQueryMessage::getQuery(). |
465 | | static const FieldDescriptor Query; |
466 | | }; |
467 | | |
468 | | /// @brief Message direction, written as "client" or "server". |
469 | | static const FieldDescriptor Origin; |
470 | | /// @brief Parsed messages in wire order, using Message, ErrorMessage, or QueryMessage for each element. |
471 | | static const FieldDescriptor Messages; |
472 | | |
473 | | /// @brief Array element for a message with no type-specific fields. |
474 | | static const MessageObject Message; |
475 | | /// @brief Array element for a server error message. |
476 | | static const ErrorMessageObject ErrorMessage; |
477 | | /// @brief Array element for a client COM_QUERY message. |
478 | | static const QueryMessageObject QueryMessage; |
479 | | }; |
480 | | |
481 | | protected: |
482 | | void serializeLayer(ObjectScope& serializer) const override; |
483 | | |
484 | | private: |
485 | | MySqlMessageOrigin m_MessageOrigin; |
486 | | mutable PointerVector<MySqlMessage> m_Messages; |
487 | | mutable bool m_MessagesInitialized = false; |
488 | | |
489 | | MySqlLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet, MySqlMessageOrigin origin) |
490 | 0 | : Layer(data, dataLen, prevLayer, packet, MySQL), m_MessageOrigin(origin) |
491 | 0 | {} |
492 | | }; |
493 | | |
494 | | } // namespace pcpp |