Beispiel #1
0
    def _execute_command(self, command, sql):
        if not self.socket:
            raise InterfaceError("(0, '')")

        # If the last query was unbuffered, make sure it finishes before
        # sending new commands
        if self._result is not None and self._result.unbuffered_active:
            self._result._finish_unbuffered_query()

        if isinstance(sql, text_type):
            sql = sql.encode(self.encoding)

        chunk_size = min(MAX_PACKET_LEN, len(sql) + 1)  # +1 is for command

        prelude = struct.pack('<i', chunk_size) + int2byte(command)
        self._write_bytes(prelude + sql[:chunk_size - 1])
        if DEBUG: dump_packet(prelude + sql)

        if chunk_size < MAX_PACKET_LEN:
            return

        seq_id = 1
        sql = sql[chunk_size - 1:]
        while True:
            chunk_size = min(MAX_PACKET_LEN, len(sql))
            prelude = struct.pack('<i', chunk_size)[:3]
            data = prelude + int2byte(seq_id % 256) + sql[:chunk_size]
            self._write_bytes(data)
            if DEBUG: dump_packet(data)
            sql = sql[chunk_size:]
            if not sql and chunk_size < MAX_PACKET_LEN:
                break
            seq_id += 1
Beispiel #2
0
    def _execute_command(self, command, sql):
        # if not self.socket:
        #     raise InterfaceError("(0, '')")

        # If the last query was unbuffered, make sure it finishes before
        # sending new commands
        if self._result is not None and self._result.unbuffered_active:
            self._result._finish_unbuffered_query()

        if isinstance(sql, text_type):
            sql = sql.encode(self.encoding)

        chunk_size = min(MAX_PACKET_LEN, len(sql) + 1)  # +1 is for command

        prelude = struct.pack("<i", chunk_size) + int2byte(command)
        yield self.stream.write(prelude + sql[: chunk_size - 1])
        if DEBUG:
            dump_packet(prelude + sql)

        if chunk_size < MAX_PACKET_LEN:
            raise Return()

        seq_id = 1
        sql = sql[chunk_size - 1 :]
        while True:
            chunk_size = min(MAX_PACKET_LEN, len(sql))
            prelude = struct.pack("<i", chunk_size)[:3]
            data = prelude + int2byte(seq_id % 256) + sql[:chunk_size]
            yield self.stream.write(data)
            if DEBUG:
                dump_packet(data)
            sql = sql[chunk_size:]
            if not sql and chunk_size < MAX_PACKET_LEN:
                break
            seq_id += 1
Beispiel #3
0
  def __recv_packet(self, socket):
    """Parse the packet header and read entire packet payload into buffer."""
    packet_header = socket.recv(4)
    while len(packet_header) < 4:
        d = socket.recv(4 - len(packet_header))
        if len(d) == 0:
            raise OperationalError(2013, "Lost connection to MySQL server during query")
        packet_header += d

    if DEBUG: dump_packet(packet_header)
    packet_length_bin = packet_header[:3]
    self.__packet_number = byte2int(packet_header[3])
    # TODO: check packet_num is correct (+1 from last packet)

    bin_length = packet_length_bin + int2byte(0)  # pad little-endian number
    bytes_to_read = struct.unpack('<I', bin_length)[0]

    payload_buff = []  # this is faster than cStringIO
    while bytes_to_read > 0:
      recv_data = socket.recv(bytes_to_read)
      if len(recv_data) == 0:
            raise OperationalError(2013, "Lost connection to MySQL server during query")
      if DEBUG: dump_packet(recv_data)
      payload_buff.append(recv_data)
      bytes_to_read -= len(recv_data)
    self.__data = join_bytes(payload_buff)
Beispiel #4
0
 def close(self):
     ''' Send the quit message and close the socket '''
     send_data = struct.pack('<i',1) + int2byte(COM_QUIT)
     #self.socket.send(send_data)        # JAWBONE - OLD - PREFER SENDALL
     self.socket.sendall(send_data)      # JAWBONE - NEW - PREFER SENDALL
     self.socket.close()
     self.socket = None
Beispiel #5
0
    def _get_server_information(self):
        i = 0
        packet = MysqlPacket(self)
        data = packet.get_all_data()

        if DEBUG: dump_packet(data)
        #packet_len = byte2int(data[i:i+1])
        #i += 4
        self.protocol_version = byte2int(data[i:i+1])

        i += 1
        server_end = data.find(int2byte(0), i)
        # TODO: is this the correct charset? should it be default_charset?
        self.server_version = data[i:server_end].decode(self.charset)

        i = server_end + 1
        self.server_thread_id = struct.unpack('<h', data[i:i+2])

        i += 4
        self.salt = data[i:i+8]

        i += 9
        if len(data) >= i + 1:
            i += 1

        self.server_capabilities = struct.unpack('<h', data[i:i+2])[0]

        i += 1
        self.server_language = byte2int(data[i:i+1])
        self.server_charset = charset_by_id(self.server_language).name

        i += 16
        if len(data) >= i+12-1:
            rest_salt = data[i:i+12]
            self.salt += rest_salt
Beispiel #6
0
    def _decrypt(self, cipher):
        """Decrypts a cipher string using self.key as the key and the first 16 byte of the cipher as the IV"""
        if not crypto_installed:
            sys.exit("Error: PyCrypto is not installed.")
        if not cipher:
            return ""
        crypto = AES.new(self.key, AES.MODE_CBC, cipher[:16])
        try:
            plain = crypto.decrypt(cipher[16:])
        except ValueError:
            util.prompt(
                "ERROR: Your journal file seems to be corrupted. You do have a backup, don't you?"
            )
            sys.exit(1)

        padding_length = util.byte2int(plain[-1])
        if padding_length > AES.block_size and padding_length != 32:
            # 32 is the space character and is kept for backwards compatibility
            return None
        elif padding_length == 32:
            plain = plain.strip()
        elif plain[-padding_length:] != util.int2byte(
                padding_length) * padding_length:
            # Invalid padding!
            return None
        else:
            plain = plain[:-padding_length]
        return plain.decode("utf-8")
    def _get_server_information(self):
        i = 0
        packet = MysqlPacket(self)
        data = packet.get_all_data()

        if DEBUG: dump_packet(data)
        #packet_len = byte2int(data[i:i+1])
        #i += 4
        self.protocol_version = byte2int(data[i:i + 1])

        i += 1
        server_end = data.find(int2byte(0), i)
        # TODO: is this the correct charset? should it be default_charset?
        self.server_version = data[i:server_end].decode(self.charset)

        i = server_end + 1
        self.server_thread_id = struct.unpack('<h', data[i:i + 2])

        i += 4
        self.salt = data[i:i + 8]

        i += 9
        if len(data) >= i + 1:
            i += 1

        self.server_capabilities = struct.unpack('<h', data[i:i + 2])[0]

        i += 1
        self.server_language = byte2int(data[i:i + 1])
        self.server_charset = charset_by_id(self.server_language).name

        i += 16
        if len(data) >= i + 12 - 1:
            rest_salt = data[i:i + 12]
            self.salt += rest_salt
Beispiel #8
0
def _scramble_323(password, message):
    hash_pass = _hash_password_323(password)
    hash_message = _hash_password_323(message[:SCRAMBLE_LENGTH_323])
    hash_pass_n = struct.unpack(">LL", hash_pass)
    hash_message_n = struct.unpack(">LL", hash_message)

    rand_st = RandStruct_323(hash_pass_n[0] ^ hash_message_n[0], hash_pass_n[1] ^ hash_message_n[1])
    outbuf = io.BytesIO()
    for _ in range_type(min(SCRAMBLE_LENGTH_323, len(message))):
        outbuf.write(int2byte(int(rand_st.my_rnd() * 31) + 64))
    extra = int2byte(int(rand_st.my_rnd() * 31))
    out = outbuf.getvalue()
    outbuf = io.BytesIO()
    for c in out:
        outbuf.write(int2byte(byte2int(c) ^ byte2int(extra)))
    return outbuf.getvalue()
Beispiel #9
0
  def __recv_packet(self, socket):
    """Parse the packet header and read entire packet payload into buffer."""
    packet_header = socket.recv(4)
    while len(packet_header) < 4:
        d = socket.recv(4 - len(packet_header))
        if len(d) == 0:
            raise OperationalError(2013, "Lost connection to MySQL server during query")
        packet_header += d

    if DEBUG: dump_packet(packet_header)
    packet_length_bin = packet_header[:3]
    self.__packet_number = byte2int(packet_header[3])
    # TODO: check packet_num is correct (+1 from last packet)

    bin_length = packet_length_bin + int2byte(0)  # pad little-endian number
    bytes_to_read = struct.unpack('<I', bin_length)[0]

    payload_buff = []  # this is faster than cStringIO
    while bytes_to_read > 0:
      recv_data = socket.recv(bytes_to_read)
      if len(recv_data) == 0:
            raise OperationalError(2013, "Lost connection to MySQL server during query")
      if DEBUG: dump_packet(recv_data)
      payload_buff.append(recv_data)
      bytes_to_read -= len(recv_data)
    self.__data = join_bytes(payload_buff)
Beispiel #10
0
 def sum_checksum(self):
     src_guid_hex = binascii.a2b_hex(self.src_guid)
     dst_guid_hex = binascii.a2b_hex(self.dst_guid)
     service_type_hex = binascii.a2b_hex(self.service_type)
     header_len_hex = binascii.a2b_hex(int2byte(self.header_len,8))
     other = src_guid_hex + dst_guid_hex + service_type_hex + header_len_hex
     return self.checksum(other)
Beispiel #11
0
 def checksum(self, data):
     length = len(data)
     checksum = 0
     for i in range(0, length):
         checksum += int.from_bytes(data[i:i + 1], 'little', signed=False)
     checksum &= 0xffff
     checksum_hex = int2byte(checksum,16)
     return checksum_hex
Beispiel #12
0
def _scramble_323(password, message):
    hash_pass = _hash_password_323(password)
    hash_message = _hash_password_323(message[:SCRAMBLE_LENGTH_323])
    hash_pass_n = struct.unpack(">LL", hash_pass)
    hash_message_n = struct.unpack(">LL", hash_message)

    rand_st = RandStruct_323(hash_pass_n[0] ^ hash_message_n[0],
                             hash_pass_n[1] ^ hash_message_n[1])
    outbuf = io.BytesIO()
    for _ in range_type(min(SCRAMBLE_LENGTH_323, len(message))):
        outbuf.write(int2byte(int(rand_st.my_rnd() * 31) + 64))
    extra = int2byte(int(rand_st.my_rnd() * 31))
    out = outbuf.getvalue()
    outbuf = io.BytesIO()
    for c in out:
        outbuf.write(int2byte(byte2int(c) ^ byte2int(extra)))
    return outbuf.getvalue()
Beispiel #13
0
 def icn2byte(self):
     src_guid_hex = binascii.a2b_hex(self.src_guid)
     dst_guid_hex = binascii.a2b_hex(self.dst_guid)
     service_type_hex = binascii.a2b_hex(self.service_type)
     header_len_hex = binascii.a2b_hex(int2byte(self.header_len, 8))
     header_checksum_hex = binascii.a2b_hex(self.header_checksum)
     #hex_result =   service_type_hex + header_len_hex + header_checksum_hex + src_guid_hex + dst_guid_hex  + self.tlv + self.payload
     hex_result = service_type_hex + header_len_hex + header_checksum_hex + src_guid_hex + dst_guid_hex + self.tlv + self.payload
     return hex_result
Beispiel #14
0
 def close(self):
     ''' Send the quit message and close the socket '''
     send_data = struct.pack('<i',1) + int2byte(COM_QUIT)
     self.wfile.write(send_data)
     self.rfile.close()
     self.wfile.close()
     self.socket.close()
     self.socket = None
     self.rfile = None
     self.wfile = None
def _scramble(password, message):
    if password == None or len(password) == 0:
        return int2byte(0)
    if DEBUG: print 'password=' + password
    stage1 = sha_new(password).digest()
    stage2 = sha_new(stage1).digest()
    s = sha_new()
    s.update(message)
    s.update(stage2)
    result = s.digest()
    return _my_crypt(result, stage1)
Beispiel #16
0
 def _encrypt(self, plain):
     """Encrypt a plaintext string using self.key as the key"""
     if not crypto_installed:
         sys.exit("Error: PyCrypto is not installed.")
     Random.atfork()  # A seed for PyCrypto
     iv = Random.new().read(AES.block_size)
     crypto = AES.new(self.key, AES.MODE_CBC, iv)
     plain = plain.encode("utf-8")
     padding_length = AES.block_size - len(plain) % AES.block_size
     plain += util.int2byte(padding_length) * padding_length
     return iv + crypto.encrypt(plain)
Beispiel #17
0
def _scramble(password, message):
    if password == None or len(password) == 0:
        return int2byte(0)
    if DEBUG: print 'password=' + password
    stage1 = sha_new(password).digest()
    stage2 = sha_new(stage1).digest()
    s = sha_new()
    s.update(message)
    s.update(stage2)
    result = s.digest()
    return _my_crypt(result, stage1)
Beispiel #18
0
    def _send_command(self, command, sql):
        #send_data = struct.pack('<i', len(sql) + 1) + command + sql
        # could probably be more efficient, at least it's correct
        if not self.socket:
            self.errorhandler(None, InterfaceError, "(0, '')")

        if isinstance(sql, unicode):
            sql = sql.encode(self.charset)

        buf = int2byte(command) + sql
        pckt_no = 0
        while len(buf) >= MAX_PACKET_LENGTH:
            header = struct.pack('<i', MAX_PACKET_LENGTH)[:-1]+int2byte(pckt_no)
            send_data = header + buf[:MAX_PACKET_LENGTH]
            self.socket.send(send_data)
            if DEBUG: dump_packet(send_data)
            buf = buf[MAX_PACKET_LENGTH:]
            pckt_no += 1
        header = struct.pack('<i', len(buf))[:-1]+int2byte(pckt_no)
        self.socket.send(header+buf)
Beispiel #19
0
 def close(self):
     ''' Send the quit message and close the socket '''
     if self.socket is None:
         raise Error("Already closed")
     send_data = struct.pack('<i',1) + int2byte(COM_QUIT)
     self.wfile.write(send_data)
     self.wfile.close()
     self.rfile.close()
     self.socket.close()
     self.socket = None
     self.rfile = None
     self.wfile = None
Beispiel #20
0
 def close(self):
     """ Send the quit message and close the socket """
     if self.stream.closed():
         raise Error("Already closed")
     send_data = struct.pack("<i", 1) + int2byte(COM_QUIT)
     try:
         yield self.stream.write(send_data)
     except Exception:
         pass
     finally:
         self.stream.close()
         self.stream = None
 def close(self):
     ''' Send the quit message and close the socket '''
     if self.socket is None:
         raise Error("Already closed")
     send_data = struct.pack('<i', 1) + int2byte(COM_QUIT)
     self.wfile.write(send_data)
     self.wfile.close()
     self.rfile.close()
     self.socket.close()
     self.socket = None
     self.rfile = None
     self.wfile = None
Beispiel #22
0
    def _request_authentication(self):
        self.client_flag |= CAPABILITIES
        if self.server_version.startswith('5'):
            self.client_flag |= MULTI_RESULTS

        if self.user is None:
            raise ValueError("Did not specify a username")

        charset_id = charset_by_name(self.charset).id
        if isinstance(self.user, text_type):
            self.user = self.user.encode(self.encoding)

        data_init = struct.pack('<i', self.client_flag) + struct.pack("<I", 1) + \
            int2byte(charset_id) + int2byte(0)*23

        next_packet = 1

        if self.ssl:
            data = pack_int24(
                len(data_init)) + int2byte(next_packet) + data_init
            next_packet += 1

            if DEBUG: dump_packet(data)

            self._write_bytes(data)
            self.socket = ssl.wrap_socket(self.socket,
                                          keyfile=self.key,
                                          certfile=self.cert,
                                          ssl_version=ssl.PROTOCOL_TLSv1,
                                          cert_reqs=ssl.CERT_REQUIRED,
                                          ca_certs=self.ca)
            self._rfile = _makefile(self.socket, 'rb')

        data = data_init + self.user + b'\0' + \
         _scramble(self.password.encode('latin1'), self.salt)

        if self.db:
            if isinstance(self.db, text_type):
                self.db = self.db.encode(self.encoding)
            data += self.db + int2byte(0)

        data = pack_int24(len(data)) + int2byte(next_packet) + data
        next_packet += 2

        if DEBUG: dump_packet(data)

        self._write_bytes(data)

        auth_packet = self._read_packet()

        # if old_passwords is enabled the packet will be 1 byte long and
        # have the octet 254

        if auth_packet.is_eof_packet():
            # send legacy handshake
            data = _scramble_323(self.password.encode('latin1'),
                                 self.salt) + b'\0'
            data = pack_int24(len(data)) + int2byte(next_packet) + data
            self._write_bytes(data)
            auth_packet = self._read_packet()
Beispiel #23
0
    def _send_command(self, command, sql):
        #send_data = struct.pack('<i', len(sql) + 1) + command + sql
        # could probably be more efficient, at least it's correct
        if not self.socket:
            self.errorhandler(None, InterfaceError, "(0, '')")

        if isinstance(sql, unicode):
            sql = sql.encode(self.charset)

        prelude = struct.pack('<i', len(sql)+1) + int2byte(command)
        self.wfile.write(prelude + sql)
        self.wfile.flush()
        if DEBUG: dump_packet(prelude + sql)
Beispiel #24
0
    def _send_command(self, command, sql):
        #send_data = struct.pack('<i', len(sql) + 1) + command + sql
        # could probably be more efficient, at least it's correct
        if not self.socket:
            self.errorhandler(None, InterfaceError, "(0, '')")

        if isinstance(sql, unicode):
            sql = sql.encode(self.charset)

        prelude = struct.pack('<i', len(sql) + 1) + int2byte(command)
        self.wfile.write(prelude + sql)
        self.wfile.flush()
        if DEBUG: dump_packet(prelude + sql)
Beispiel #25
0
 def close(self):
     ''' Send the quit message and close the socket '''
     if self.socket is None:
         raise Error("Already closed")
     send_data = struct.pack('<i', 1) + int2byte(COM_QUIT)
     try:
         self._write_bytes(send_data)
     except Exception:
         pass
     finally:
         sock = self.socket
         self.socket = None
         self._rfile = None
         sock.close()
Beispiel #26
0
    def _get_server_information(self):
        i = 0
        packet = MysqlPacket(self)
        yield packet.recv_packet()
        packet.check_error()
        data = packet.get_all_data()

        if DEBUG:
            dump_packet(data)
        self.protocol_version = byte2int(data[i : i + 1])
        i += 1

        server_end = data.find(int2byte(0), i)
        self.server_version = data[i:server_end].decode("latin1")
        i = server_end + 1

        self.server_thread_id = struct.unpack("<I", data[i : i + 4])
        i += 4

        self.salt = data[i : i + 8]
        i += 9  # 8 + 1(filler)

        self.server_capabilities = struct.unpack("<H", data[i : i + 2])[0]
        i += 2

        if len(data) >= i + 6:
            lang, stat, cap_h, salt_len = struct.unpack("<BHHB", data[i : i + 6])
            i += 6
            self.server_language = lang
            self.server_charset = charset_by_id(lang).name

            self.server_status = stat
            if DEBUG:
                print("server_status: %x" % stat)

            self.server_capabilities |= cap_h << 16
            if DEBUG:
                print("salt_len:", salt_len)
            salt_len = max(12, salt_len - 9)

        # reserved
        i += 10

        if len(data) >= i + salt_len:
            self.salt += data[i : i + salt_len]  # salt_len includes auth_plugin_data_part_1 and filler
Beispiel #27
0
  def __recv_packet(self):
    """Parse the packet header and read entire packet payload into buffer."""
    packet_header = self.connection.rfile.read(4)
    if len(packet_header) < 4:
        raise OperationalError(2013, "Lost connection to MySQL server during query")

    if DEBUG: dump_packet(packet_header)
    packet_length_bin = packet_header[:3]
    self.__packet_number = byte2int(packet_header[3])
    # TODO: check packet_num is correct (+1 from last packet)

    bin_length = packet_length_bin + int2byte(0)  # pad little-endian number
    bytes_to_read = struct.unpack('<I', bin_length)[0]
    recv_data = self.connection.rfile.read(bytes_to_read)
    if len(recv_data) < bytes_to_read:
        raise OperationalError(2013, "Lost connection to MySQL server during query")
    if DEBUG: dump_packet(recv_data)
    self.__data = recv_data
Beispiel #28
0
  def __recv_packet(self):
    """Parse the packet header and read entire packet payload into buffer."""
    packet_header = self.connection.rfile.read(4)
    if len(packet_header) < 4:
        raise OperationalError(2013, "Lost connection to MySQL server during query")

    if DEBUG: dump_packet(packet_header)
    packet_length_bin = packet_header[:3]
    self.__packet_number = byte2int(packet_header[3])
    # TODO: check packet_num is correct (+1 from last packet)

    bin_length = packet_length_bin + int2byte(0)  # pad little-endian number
    bytes_to_read = struct.unpack('<I', bin_length)[0]
    recv_data = self.connection.rfile.read(bytes_to_read)
    if len(recv_data) < bytes_to_read:
        raise OperationalError(2013, "Lost connection to MySQL server during query")
    if DEBUG: dump_packet(recv_data)
    self.__data = recv_data
    def _send_command(self, command, sql):
        #send_data = struct.pack('<i', len(sql) + 1) + command + sql
        # could probably be more efficient, at least it's correct
        if not self.socket:
            self.errorhandler(None, InterfaceError, "(0, '')")

        # If the last query was unbuffered, make sure it finishes before
        # sending new commands
        if self._result is not None and self._result.unbuffered_active:
            self._result._finish_unbuffered_query()

        if isinstance(sql, unicode):
            sql = sql.encode(self.charset)

        prelude = struct.pack('<i', len(sql) + 1) + int2byte(command)
        self.wfile.write(prelude + sql)
        self.wfile.flush()
        if DEBUG: dump_packet(prelude + sql)
Beispiel #30
0
    def _send_command(self, command, sql):
        #send_data = struct.pack('<i', len(sql) + 1) + command + sql
        # could probably be more efficient, at least it's correct
        if not self.socket:
            self.errorhandler(None, InterfaceError, "(0, '')")

        # If the last query was unbuffered, make sure it finishes before
        # sending new commands
        if self._result is not None and self._result.unbuffered_active:
            self._result._finish_unbuffered_query()

        if isinstance(sql, unicode):
            sql = sql.encode(self.charset)

        prelude = struct.pack('<i', len(sql)+1) + int2byte(command)
        self.wfile.write(prelude + sql)
        self.wfile.flush()
        if DEBUG: dump_packet(prelude + sql)
Beispiel #31
0
    def _get_server_information(self):
        i = 0
        packet = self._read_packet()
        data = packet.get_all_data()

        if DEBUG: dump_packet(data)
        self.protocol_version = byte2int(data[i:i + 1])
        i += 1

        server_end = data.find(int2byte(0), i)
        self.server_version = data[i:server_end].decode('latin1')
        i = server_end + 1

        self.server_thread_id = struct.unpack('<I', data[i:i + 4])
        i += 4

        self.salt = data[i:i + 8]
        i += 9  # 8 + 1(filler)

        self.server_capabilities = struct.unpack('<H', data[i:i + 2])[0]
        i += 2

        if len(data) >= i + 6:
            lang, stat, cap_h, salt_len = struct.unpack('<BHHB', data[i:i + 6])
            i += 6
            self.server_language = lang
            self.server_charset = charset_by_id(lang).name

            self.server_status = stat
            if DEBUG: print("server_status: %x" % stat)

            self.server_capabilities |= cap_h << 16
            if DEBUG: print("salt_len:", salt_len)
            salt_len = max(12, salt_len - 9)

        # reserved
        i += 10

        if len(data) >= i + salt_len:
            self.salt += data[
                i:i +
                salt_len]  # salt_len includes auth_plugin_data_part_1 and filler
Beispiel #32
0
    def _send_command(self, command, sql):
        #send_data = struct.pack('<i', len(sql) + 1) + command + sql
        # could probably be more efficient, at least it's correct
        if not self.socket:
            self.errorhandler(None, InterfaceError, "(0, '')")

        if isinstance(sql, unicode):
            sql = sql.encode(self.charset)

        prelude = struct.pack('<i', len(sql)+1) + int2byte(command)
        if len(sql) <= (MAX_PACKET_LENGTH-5):
            #self.socket.send(prelude + sql)        # JAWBONE - OLD - PREFER SENDALL
            self.socket.sendall(prelude + sql)      # JAWBONE - NEW - PREFER SENDALL
            if DEBUG: dump_packet(prelude + sql)
        else:
            #self.socket.send(prelude)              # JAWBONE - OLD - PREFER SENDALL
            self.socket.sendall(prelude)            # JAWBONE - OLD - PREFER SENDALL
            if DEBUG: dump_packet(send_data)
            while len(sql) > MAX_PACKET_LENGTH:
                self.socket.sendall(sql[:MAX_PACKET_LENGTH])
                if DEBUG: dump_packet(sql[:MAX_PACKET_LENGTH])
                sql = sql[MAX_PACKET_LENGTH:]
            if len(sql) > 0:
                self.socket.sendall(sql)
Beispiel #33
0
 def close(self):
     ''' Send the quit message and close the socket '''
     send_data = struct.pack('<i',1) + int2byte(COM_QUIT)
     self.socket.send(send_data)
     self.socket.close()
     self.socket = None
    def _send_authentication(self):
        self.client_flag |= CAPABILITIES
        if self.server_version.startswith('5'):
            self.client_flag |= MULTI_RESULTS

        if self.user is None:
            raise ValueError, "Did not specify a username"

        charset_id = charset_by_name(self.charset).id
        self.user = self.user.encode(self.charset)

        data_init = struct.pack('<i', self.client_flag) + struct.pack("<I", 1) + \
                     int2byte(charset_id) + int2byte(0)*23

        next_packet = 1

        if self.ssl:
            data = pack_int24(
                len(data_init)) + int2byte(next_packet) + data_init
            next_packet += 1

            if DEBUG: dump_packet(data)

            self.wfile.write(data)
            self.wfile.flush()
            self.socket = ssl.wrap_self.socketet(
                self.socket,
                keyfile=self.key,
                certfile=self.cert,
                ssl_version=ssl.PROTOCOL_TLSv1,
                cert_reqs=ssl.CERT_REQUIRED,
                ca_certs=self.ca)
            self.rfile = self.socket.makefile("rb")
            self.wfile = self.socket.makefile("wb")

        data = data_init + self.user + int2byte(0) + _scramble(
            self.password.encode(self.charset), self.salt)

        if self.db:
            self.db = self.db.encode(self.charset)
            data += self.db + int2byte(0)

        data = pack_int24(len(data)) + int2byte(next_packet) + data
        next_packet += 2

        if DEBUG: dump_packet(data)

        self.wfile.write(data)
        self.wfile.flush()

        auth_packet = MysqlPacket(self)
        auth_packet.check_error()
        if DEBUG: auth_packet.dump()

        # if old_passwords is enabled the packet will be 1 byte long and
        # have the octet 254

        if auth_packet.is_eof_packet():
            # send legacy handshake
            #raise NotImplementedError, "old_passwords are not supported. Check to see if mysqld was started with --old-passwords, if old-passwords=1 in a my.cnf file, or if there are some short hashes in your mysql.user table."
            # TODO: is this the correct charset?
            data = _scramble_323(self.password.encode(self.charset),
                                 self.salt.encode(self.charset)) + int2byte(0)
            data = pack_int24(len(data)) + int2byte(next_packet) + data

            self.wfile.write(data)
            self.wfile.flush()
            auth_packet = MysqlPacket(self)
            auth_packet.check_error()
            if DEBUG: auth_packet.dump()
Beispiel #35
0
    def _request_authentication(self):
        self.client_flag |= CAPABILITIES
        if self.server_version.startswith("5"):
            self.client_flag |= MULTI_RESULTS

        if self.user is None:
            raise ValueError("Did not specify a username")

        charset_id = charset_by_name(self.charset).id
        if isinstance(self.user, text_type):
            self.user = self.user.encode(self.encoding)

        data_init = struct.pack("<i", self.client_flag) + struct.pack("<I", 1) + int2byte(charset_id) + int2byte(0) * 23

        next_packet = 1

        if self.ssl:
            data = pack_int24(len(data_init)) + int2byte(next_packet) + data_init
            next_packet += 1

            if DEBUG:
                dump_packet(data)

            yield self.stream.write(data)
            self.socket = ssl.wrap_socket(
                self.socket,
                keyfile=self.key,
                certfile=self.cert,
                ssl_version=ssl.PROTOCOL_TLSv1,
                cert_reqs=ssl.CERT_REQUIRED,
                ca_certs=self.ca,
            )
            self._rfile = _makefile(self.socket, "rb")

        data = data_init + self.user + b"\0" + _scramble(self.password.encode("latin1"), self.salt)

        if self.db:
            if isinstance(self.db, text_type):
                self.db = self.db.encode(self.encoding)
            data += self.db + int2byte(0)

        data = pack_int24(len(data)) + int2byte(next_packet) + data
        next_packet += 2

        if DEBUG:
            dump_packet(data)

        yield self.stream.write(data)

        auth_packet = MysqlPacket(self)
        yield auth_packet.recv_packet()
        auth_packet.check_error()
        if DEBUG:
            auth_packet.dump()

        # if old_passwords is enabled the packet will be 1 byte long and
        # have the octet 254

        if auth_packet.is_eof_packet():
            # send legacy handshake
            data = _scramble_323(self.password.encode("latin1"), self.salt) + b"\0"
            data = pack_int24(len(data)) + int2byte(next_packet) + data

            self.stream.write(data)
            auth_packet = MysqlPacket(self)
            yield auth_packet.recv_packet()
            auth_packet.check_error()
            if DEBUG:
                auth_packet.dump()
Beispiel #36
0
    def _send_authentication(self):
        self.client_flag |= CAPABILITIES
        if self.server_version.startswith('5'):
            self.client_flag |= MULTI_RESULTS

        if self.user is None:
            raise ValueError, "Did not specify a username"

        charset_id = charset_by_name(self.charset).id
        self.user = self.user.encode(self.charset)

        data_init = struct.pack('<i', self.client_flag) + struct.pack("<I", 1) + \
                     int2byte(charset_id) + int2byte(0)*23

        next_packet = 1

        if self.ssl:
            data = pack_int24(len(data_init)) + int2byte(next_packet) + data_init
            next_packet += 1

            if DEBUG: dump_packet(data)

            self.wfile.write(data)
            self.wfile.flush()
            self.socket = ssl.wrap_self.socketet(self.socket, keyfile=self.key,
                                                 certfile=self.cert,
                                                 ssl_version=ssl.PROTOCOL_TLSv1,
                                                 cert_reqs=ssl.CERT_REQUIRED,
                                                 ca_certs=self.ca)
            self.rfile = self.socket.makefile("rb")
            self.wfile = self.socket.makefile("wb")

        data = data_init + self.user+int2byte(0) + _scramble(self.password.encode(self.charset), self.salt)

        if self.db:
            self.db = self.db.encode(self.charset)
            data += self.db + int2byte(0)

        data = pack_int24(len(data)) + int2byte(next_packet) + data
        next_packet += 2

        if DEBUG: dump_packet(data)

        self.wfile.write(data)
        self.wfile.flush()

        auth_packet = MysqlPacket(self)
        auth_packet.check_error()
        if DEBUG: auth_packet.dump()

        # if old_passwords is enabled the packet will be 1 byte long and
        # have the octet 254

        if auth_packet.is_eof_packet():
            # send legacy handshake
            #raise NotImplementedError, "old_passwords are not supported. Check to see if mysqld was started with --old-passwords, if old-passwords=1 in a my.cnf file, or if there are some short hashes in your mysql.user table."
            # TODO: is this the correct charset?
            data = _scramble_323(self.password.encode(self.charset), self.salt.encode(self.charset)) + int2byte(0)
            data = pack_int24(len(data)) + int2byte(next_packet) + data

            self.wfile.write(data)
            self.wfile.flush()
            auth_packet = MysqlPacket(self)
            auth_packet.check_error()
            if DEBUG: auth_packet.dump()