parsemysql.py: Extract SQL commands from MySQL TCP data streams

#########################################################
# Python script to parse MySQL data streams and extract #
# SQL statements.                                       #
#                                                       #
# parsemysql.py v2013.03.25                             #
# https://malwaremusings.com/scripts/parsemysql-py       #
#                                                       #
# usage: parsemysql.py <tcpflowfilename>                #
#   where tcpflowfilename is a file containing the TCP  #
#   data from a MySQL network connection.               #
#########################################################

#
# MySQL packet documentation
# http://dev.mysql.com/doc/internals/en/overview.html#mysql-packet
#

import sys
import struct

mysqlfile = open(sys.argv[1],"r")
mysqldata = mysqlfile.read()

# Offset from the start of the MySQL stream
off = 0

# Until we reach the end of the MySQL data stream...
while (off < len(mysqldata)):

  ###
  # A. Extract packet length, sequence number, and MySQL command
  ###

  pktlen = struct.unpack("<L",mysqldata[off:off + 4])[0] & 0x00ffffff
  pktseq = ord(mysqldata[off + 3])

  # first byte of payload
  pktcmd = ord(mysqldata[off + 4])

  ###
  # B. Process COM_QUIT command
  ###

  if (pktcmd == 0x01):
    print("quit")

  ###
  # C. Process COM_QUERY command
  ###

  elif (pktcmd == 0x03):

    ###
    # C.1 extract MySQL query and print it
    #     (off + 4) is start of MySQL packet data payload
    #     which is the command followed by query in this case
    ###

    pktqry = mysqldata[off + 5:off + 4 + pktlen]
    print("%s" % pktqry)
  else:

    ###
    # D. Print message about unknown commands
    ###

    print("-- unknown command #: 0x%x" % pktcmd)

  ###
  # E. Increment offset to point to start of next MySQL packet
  ###

  off += int(pktlen) + 4  # len is length of payload and doesn't include packet header

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s