Using Pack instead of Pack_into in Python 2.4.3 - python

The following code is for simulating a Modbus interface on an embedded device. Unfortunely, it has an older Python (2.4.3). The code works on 2.7, but not 2.4.3 because the the version Python I am using does not support struct.pack_into, only struct.pack. Could I get some advice on how to fix this? I think I need to use a string maybe and convert to a byte buffer. This talks to non-Python code, so pickle can not be used I believe.
import socket
import sys
import array
import struct
def hexdump(src, length=16):
FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)])
lines = []
for c in xrange(0, len(src), length):
chars = src[c:c+length]
hex = ' '.join(["%02x" % ord(x) for x in chars])
printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or '.') for x in chars])
lines.append("%04x %-*s %s\n" % (c, length*3, hex, printable))
return ''.join(lines)
HOST = '192.168.1.187'
PORT = 502
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
data = []
datatran = array.array('B', '\x00' * 14)
data = conn.recv(1024)
print 'Connect by', addr
while (data):
sys.stdout.write(hexdump(data))
TransID , ProtoColID, PacketLength, UnitID, FC, StartAddress, RegisterCount = struct.unpack_from(">hhhBBhh", data)
print TransID, ProtoColID, PacketLength, UnitID
print FC, StartAddress, RegisterCount
struct.pack_into(">hhhBBBh", datatran, 0, TransID , ProtoColID, PacketLength+2, UnitID, FC, 2, 51)
conn.sendall(datatran)
data = conn.recv(1024)
conn.close()
s.close()
Thanks

With a bit of size calculation it should be possible to use pack and unpack instead:
import socket
import sys
import array
import struct
def hexdump(src, length=16):
FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)])
lines = []
for c in xrange(0, len(src), length):
chars = src[c:c+length]
hex = ' '.join(["%02x" % ord(x) for x in chars])
printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or '.') for x in chars])
lines.append("%04x %-*s %s\n" % (c, length*3, hex, printable))
return ''.join(lines)
HOST = '192.168.1.187'
PORT = 502
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
datatranStruct = '>hhhBBBh'
datatranStructSize = struct.calcsize(datatranStruct)
datatranFormat = '%s%dx' % (datatranStruct, 14 - datatranStructSize)
recvStruct = '>hhhBBhh'
recvStructSize = struct.calcsize(recvStruct)
data = conn.recv(1024)
print 'Connect by', addr
while (data):
sys.stdout.write(hexdump(data))
recvFormat = '%s%dx' % (recvStruct, len(data) - recvStructSize)
TransID , ProtoColID, PacketLength, UnitID, FC, StartAddress, RegisterCount = struct.unpack(recvFormat, data)
print TransID, ProtoColID, PacketLength, UnitID
print FC, StartAddress, RegisterCount
datatran = struct.pack(datatranFormat, TransID , ProtoColID, PacketLength+2, UnitID, FC, 2, 51)
conn.sendall(datatran)
data = conn.recv(1024)
conn.close()
s.close()

Related

struct.pack raises "struct.error: required argument is not an integer"

I am trying to make a network proxy which will forward packets to another IP. I can sniff a packet, unpack it, and view, print, and manipulate its contents. But when I want to pack the bytes to forward it to some other IP, it gives this error:
struct.error: required argument is not an integer
The error is raised on this line of code:
ip_header = struct.pack('!BBHHHBBH4s4s' ,version_IHL, TOS, totalLength, ID,flags, TTL,protocolNR, checksum,sourceAddress,destinationAddress)
Here is the code. Bold stuff in code are comments in my code.
import socket
import sys
import struct
import re
import logging
import struct
from scapy.all import *
import Functions
logging.basicConfig(filename='example.log',level=logging.DEBUG)
hold = "192.168.0.125"
print ("\n\t\t\t**************************")
print ("\t\t\t*****SettingUp Server*****")
print ("\t\t\t**************************\n\n")
print("\t*****Implementing DHKE")
print ("\t*****Generating server public & private keypairs now . . .")
(e,n), private = Functions.generate_keypair(7, 11)
print ("*****Public Key: {} , {} ", e,n)
print ("*****Private key: {} ", private)
public = (e,n)
ip = '192.168.0.125'
port = 5001
# the public network interface
#HOST = socket.gethostbyname(socket.gethostname())
#..............................................................................................
# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind(('192.168.0.117',5001))
# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('format=%(asctime)s %(message)s')
# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
#..............................................................................................
data = Functions.recievedata(s)
logging.info('**Packet Recieved')
print("Packet Recieved")
#function_data = tuple(struct.unpack(data))
unpacked_data = struct.unpack('!BBHHHBBH4s4s',data[:20])
listunpacked = list(unpacked_data)
logging.info('--> Unpacking packet')
version_IHL = unpacked_data[0]
version = version_IHL >>4
IHL = version_IHL & 0xF
TOS = unpacked_data[1]
totalLength = unpacked_data[2]
ID = unpacked_data[3]
flags = unpacked_data[4]
fragmentOffset = unpacked_data[4] & 0x1FFF
TTL = unpacked_data[5]
protocolNR = unpacked_data[6]
checksum = unpacked_data[7]
sourceAddress = socket.inet_ntoa(unpacked_data[8])
destinationAddress = socket.inet_ntoa(unpacked_data[9])
#..............................................................................................
print("An IP packet with the size %i is captured.", (totalLength))
print("Raw data: "+ str(data))
print("\nParsed data")
print("Version:\t\t"+ str(version))
print("Header length:\t\t"+ str(IHL*4)+'bytes')
print("Type of service:\t\t" + str(Functions.getTOS(TOS)))
print("Length:\t\t\t"+str(totalLength))
print("ID:\t\t\t"+str(hex(ID)) + ' {' + str(ID) + '}')
print("Flags:\t\t\t" + Functions.getFlags(flags))
print("Fragment offset:\t" + str(fragmentOffset))
print( "TTL:\t\t\t"+str(TTL))
print("Protocol:\t\t" + Functions.getProtocol(protocolNR))
print("Checksum:\t\t" + str(checksum))
print("Source:\t\t\t" + sourceAddress)
print("Destination:\t\t" + destinationAddress)
print("Payload:\n"+str(data[20:]))
# receive a package
#print(s.recvfrom(65565))
#IP = input("Enter IP address to send: ")
#port = int(input("Port: "))
#..............................................................................................
print("\tOld Destination: "+ destinationAddress)
listunpacked[9] = hold
unpacked_data = tuple(listunpacked)
print("\n\t\tNew Address is: "+ unpacked_data[9])
print()
#s.inet_aton(unpacked_data[9]) = hold
#unpacked_data = tuple(listunpacked)
#unpacked_data = bytes(unpacked_data)
#destinationAddress = socket.inet_ntoa(unpacked_data[9])
#..............................................................................................
# tcp header fields
tcp_source = 80 # source port
tcp_dest = 5001 # destination port
tcp_seq = 454
tcp_ack_seq = 0
tcp_doff = 5 # 4 bit field, size of tcp header, 5 * 4 = 20 bytes
# tcp flags
tcp_fin = 0
tcp_syn = 1
tcp_rst = 0
tcp_psh = 0
tcp_ack = 0
tcp_urg = 0
tcp_window = socket.htons(5840) # maximum allowed window size
tcp_check = 0
tcp_urg_ptr = 0
tcp_offset_res = (tcp_doff << 4) + 0
tcp_flags = tcp_fin + (tcp_syn << 1) + (tcp_rst << 2) + (tcp_psh << 3) + (tcp_ack << 4) + (tcp_urg << 5)
# the ! in the pack format string means network order
tcp_header = tuple(struct.pack('!HHLLBBHHH', tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window,tcp_check, tcp_urg_ptr))
#p =(data+tcp_header)
#hold = bytes(hold,"utf-8")
#hold = socket.inet_aton ( hold )
#checksum = bytes(checksum,"utf-8")
#destinationAddress = c_int(listunpacked[9])
checksum = bytes(str(checksum),"utf-8")
#ip_header = struct.pack('!BBHHHBBH4s4s' , version_IHL, TOS, totalLength, ID,flags, TTL,protocolNR, checksum,sourceAddress,destinationAddress)
#tcp_header = struct.pack('!HHLLBBH' , tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window) + struct.pack('H' , tcp_check) + struct.pack('!H' , tcp_urg_ptr)
#packet = ip_header + tcp_header + str(data[20:])
message = "How are you"
#data = bytes(unpacked_data,"utf-8") + tcp_header + message
ip_header = struct.pack('!BBHHHBBH4s4s' ,version_IHL, TOS, totalLength, ID,flags, TTL,protocolNR, checksum,sourceAddress,destinationAddress)
data = bytes(unpacked_data) + data[20:]
s.sendto(data, ("192.168.0.125" , 5001))
print("Packet sent")
# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
ip_header = struct.pack('!BBHHHBBH4s4s' ,version_IHL, TOS, totalLength, ID,flags, TTL,protocolNR, checksum,sourceAddress,destinationAddress)
Both the B and H formats require integer arguments (or non-integer objects that implement the __index__ method) (see Format Characters).
The checksum argument is now of type bytes because you set it here before packing:
checksum = bytes(str(checksum),"utf-8")
And bytes objects do not implement the __index__ method.
You can check this using dir(checksum).
That's why you're getting the struct.error exception.
When packing a value x using one of the integer formats ('b', 'B',
'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q'), if x is outside the valid
range for that format then struct.error is raised.
Either:
Use a different variable for the bytes(str(checksum),"utf-8") output
Pass an int type object for the checksum value

Python client server socket send and recv problems

I have successful sending and receiving between test_client and test_server for a few sends and receives. But when I input more than 4 or 5 data and click enter after each at the input() function the program hangs. I think I've narrowed the problem down to likely be either the rdt_rcv() or udt_send() function. I've highlighted with comments the rdt_rcv() function for both sender and receiver and added a comment above the udt_send() function. But I can't see what's wrong with the functions. Of course it could be something else but I think the problem is one of the two functions I mentioned above. Try running the programs by running test_server first and test_client second with rdt.py in the same folder as the 2 test modules.
test_client.py
import socket, rdt, sys
TCP_IP = 'localhost'
TCP_PORT = 10000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
InitialSeqNumber = 0
NextSeqNum = InitialSeqNumber
SendBase = InitialSeqNumber
while 1:
d = input("Input data: ")
data = rdt.rdt_send(d)
data = int(data)
if rdt.rdt_send_called == 1:
checksum = 0xFFFF - data # Assuming 28 byte data
sndpkt = rdt.packet(NextSeqNum, 0, checksum, data)
rdt.udt_send(sndpkt, s)
NextSeqNum = NextSeqNum + sys.getsizeof(data)
#####################################
seq, ack, check, dat = rdt.rdt_rcv(s)
#####################################
rdt.rdt_send_called = 0
print ("Sequence Number: " + str(seq))
print ("ACK Number: " + str(ack))
print ("Checksum Value: " + hex(check))
print ("Data: " + str(dat))
print ('\n')
s.close()
rdt.py
rdt_send_called = None
timeout_event = None
ACK_received = None
BUFFER_SIZE = 1024
class packet:
def __init__(self, seq_num, ack_num, checksum, data):
self.seq_num = seq_num
self.ack_num = ack_num
self.checksum = checksum
self.data = data
def rdt_send(data):
d = data
global rdt_send_called
rdt_send_called = 1
return d
# PROBLEM MAY BE WITH THIS FUNCTION
def udt_send(sndpkt, s):
s.send((str(sndpkt.seq_num)).encode())
s.send((str(sndpkt.ack_num)).encode())
s.send((str(sndpkt.checksum)).encode())
s.send((str(sndpkt.data)).encode())
# PROBLEM IS MOST LIKELY WITH THIS FUNCTION
def rdt_rcv(conn):
field1 = conn.recv(BUFFER_SIZE)
field1 = int(field1)
field2 = conn.recv(BUFFER_SIZE)
field2 = int(field2)
#if field2 != 0:
#global ACK_received
#ACK_received = 1
field3 = (conn.recv(BUFFER_SIZE))
field3 = int(field3)
field4 = (conn.recv(BUFFER_SIZE))
field4 = int(field4)
return field1, field2, field3, field4
def deliver_data(data):
pass
def timeout():
global timeout_event
timeout_event = 1
test_server.py
import socket, rdt, sys
TCP_IP = '127.0.0.1'
TCP_PORT = 10000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
while 1:
dont_send_ACK = 0
#####################################################
seq_num, ack_num, check_sum, data = rdt.rdt_rcv(conn)
#####################################################
print ("Sequence Number: " + str(seq_num))
print ("ACK number: " + str(ack_num))
print ("Checksum Value: " + hex(check_sum))
print ("Data: " + hex(data))
print ('\n')
if data + check_sum != 0xFFFF:
dont_send_ACK = 1 # sender will timeout
else:
rdt.deliver_data(data)
if dont_send_ACK == 0:
ACK = seq_num + sys.getsizeof(data)
checksum = 0xFFFF - ACK
sndpkt = rdt.packet(0, ACK, checksum, 0)
rdt.udt_send(sndpkt, conn)
conn.close()

Porting a python 2 code to Python 3: ICMP Scan with errors

import random
import socket
import time
import ipaddress
import struct
from threading import Thread
def checksum(source_string):
sum = 0
count_to = (len(source_string) / 2) * 2
count = 0
while count < count_to:
this_val = ord(source_string[count + 1]) * 256 + ord(source_string[count])
sum = sum + this_val
sum = sum & 0xffffffff
count = count + 2
if count_to < len(source_string):
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def create_packet(id):
header = struct.pack('bbHHh', 8, 0, 0, id, 1)
data = 192 * 'Q'
my_checksum = checksum(header + data)
header = struct.pack('bbHHh', 8, 0, socket.htons(my_checksum), id, 1)
return header + data
def ping(addr, timeout=1):
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
except Exception as e:
print (e)
packet_id = int((id(timeout) * random.random()) % 65535)
packet = create_packet(packet_id)
my_socket.connect((addr, 80))
my_socket.sendall(packet)
my_socket.close()
def rotate(addr, file_name, wait, responses):
print ("Sending Packets", time.strftime("%X %x %Z"))
for ip in addr:
ping(str(ip))
time.sleep(wait)
print ("All packets sent", time.strftime("%X %x %Z"))
print ("Waiting for all responses")
time.sleep(2)
# Stoping listen
global SIGNAL
SIGNAL = False
ping('127.0.0.1') # Final ping to trigger the false signal in listen
print (len(responses), "hosts found!")
print ("Writing File")
hosts = []
for response in sorted(responses):
ip = struct.unpack('BBBB', response)
ip = str(ip[0]) + "." + str(ip[1]) + "." + str(ip[2]) + "." + str(ip[3])
hosts.append(ip)
file = open(file_name, 'w')
file.write(str(hosts))
print ("Done", time.strftime("%X %x %Z"))
def listen(responses):
global SIGNAL
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
s.bind(('', 1))
print ("Listening")
while SIGNAL:
packet = s.recv(1024)[:20][-8:-4]
responses.append(packet)
print ("Stop Listening")
s.close()
SIGNAL = True
responses = []
ips = '200.131.0.0/20' # Internet network
wait = 0.002 # Adjust this based in your bandwidth (Faster link is Lower wait)
file_name = 'log1.txt'
ip_network = ipaddress.ip_network(unicode(ips), strict=False)
t_server = Thread(target=listen, args=[responses])
t_server.start()
t_ping = Thread(target=rotate, args=[ip_network, file_name, wait, responses])
t_ping.start()
I tried:
ip_network = ipaddress.ip_network( ips, strict=False) instead of ip_network = ipaddress.ip_network(unicode(ips), strict=False)
because of the error: ""NameError: name 'unicode' is not defined"
after:
I got: my_checksum = checksum(header + data) -> TypeError: can't concat bytes to str
so I tried:
data = bytes(192 * 'Q').encode('utf8') instead of data = 192 * 'Q'
Now, the error is : ""data = bytes (192 * 'Q').encode('utf8') TypeError: string argument without an encoding"
Could anyone help me to port the code to Python 3 ?
import random
import socket
import time
import ipaddress
import struct
from threading import Thread
def checksum(source_string):
sum = 0
count_to = (len(source_string) / 2) * 2
count = 0
while count < count_to:
this_val = source_string[count + 1] * 256 + source_string[count]
sum = sum + this_val
sum = sum & 0xffffffff
count = count + 2
if count_to < len(source_string):
sum = sum + source_string[len(source_string) - 1]
sum = sum & 0xffffffff
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def create_packet(id):
header = struct.pack('bbHHh', 8, 0, 0, id, 1)
data = 192 * b'Q'
my_checksum = checksum(header + data)
header = struct.pack('bbHHh', 8, 0, socket.htons(my_checksum), id, 1)
return header + data
def ping(addr, timeout=1):
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
except Exception as e:
print (e)
packet_id = int((id(timeout) * random.random()) % 65535)
packet = create_packet(packet_id)
my_socket.connect((addr, 80))
my_socket.sendall(packet)
my_socket.close()
def rotate(addr, file_name, wait, responses):
print ("Sending Packets", time.strftime("%X %x %Z"))
for ip in addr:
ping(str(ip))
time.sleep(wait)
print ("All packets sent", time.strftime("%X %x %Z"))
print ("Waiting for all responses")
time.sleep(2)
# Stoping listen
global SIGNAL
SIGNAL = False
ping('127.0.0.1') # Final ping to trigger the false signal in listen
print (len(responses), "hosts found!")
print ("Writing File")
hosts = set()
for response in sorted(responses):
ip = struct.unpack('BBBB', response)
ip = str(ip[0]) + "." + str(ip[1]) + "." + str(ip[2]) + "." + str(ip[3])
hosts.add(ip)
with open(file_name, 'w') as file:
file.write('\n'.join(sorted(hosts, key=lambda item: socket.inet_aton(item))))
print ("Done", time.strftime("%X %x %Z"))
def listen(responses):
global SIGNAL
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
s.bind(('', 1))
print ("Listening")
while SIGNAL:
packet = s.recv(1024)[:20][-8:-4]
responses.append(packet)
print ("Stop Listening")
s.close()
SIGNAL = True
responses = []
ips = '192.168.1.0/28' # Internet network
wait = 0.002 # Adjust this based in your bandwidth (Faster link is Lower wait)
file_name = 'log1.txt'
ip_network = ipaddress.ip_network(ips, strict=False)
t_server = Thread(target=listen, args=[responses])
t_server.start()
t_ping = Thread(target=rotate, args=[ip_network, file_name, wait, responses])
t_ping.start()

how to scan ble device based on the mac address stored in database using python

I am using for loop to get the mac address from database but the loop printed the ble mac address 17 times. I tried using if else to compare the mac address with the mac address stored in database but the output scan nothing. Is there any other way to filter out other ble mac address?
import os
import sys
import struct
import bluetooth._bluetooth as bluez
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","DB_USER","DB_PASSWORD","DB_NAME" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT * FROM Mac_address"
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
NAME = row[0]
mac_address = row[1]
time = row[2]
LE_META_EVENT = 0x3e
LE_PUBLIC_ADDRESS=0x00
LE_RANDOM_ADDRESS=0x01
LE_SET_SCAN_PARAMETERS_CP_SIZE=7
OGF_LE_CTL=0x08
OCF_LE_SET_SCAN_PARAMETERS=0x000B
OCF_LE_SET_SCAN_ENABLE=0x000C
OCF_LE_CREATE_CONN=0x000D
LE_ROLE_MASTER = 0x00
LE_ROLE_SLAVE = 0x01
# these are actually subevents of LE_META_EVENT
EVT_LE_CONN_COMPLETE=0x01
EVT_LE_ADVERTISING_REPORT=0x02
EVT_LE_CONN_UPDATE_COMPLETE=0x03
EVT_LE_READ_REMOTE_USED_FEATURES_COMPLETE=0x04
# Advertisment event types
ADV_IND=0x00
ADV_DIRECT_IND=0x01
ADV_SCAN_IND=0x02
ADV_NONCONN_IND=0x03
ADV_SCAN_RSP=0x04
def returnnumberpacket(pkt):
myInteger = 0
multiple = 256
for c in pkt:
myInteger += struct.unpack("B",c)[0] * multiple
multiple = 1
return myInteger
def returnstringpacket(pkt):
myString = "";
for c in pkt:
myString += "%02x" %struct.unpack("B",c)[0]
return myString
def printpacket(pkt):
for c in pkt:
sys.stdout.write("%02x " % struct.unpack("B",c)[0])
def get_packed_bdaddr(bdaddr_string):
packable_addr = []
addr = bdaddr_string.split(':')
addr.reverse()
for b in addr:
packable_addr.append(int(b, 16))
return struct.pack("<BBBBBB", *packable_addr)
def packed_bdaddr_to_string(bdaddr_packed):
return ':'.join('%02x'%i for i in struct.unpack("<BBBBBB", bdaddr_packed[::-1]))
def hci_enable_le_scan(sock):
hci_toggle_le_scan(sock, 0x01)
def hci_disable_le_scan(sock):
hci_toggle_le_scan(sock, 0x00)
def hci_toggle_le_scan(sock, enable)
cmd_pkt = struct.pack("<BB", enable, 0x00)
bluez.hci_send_cmd(sock, OGF_LE_CTL, OCF_LE_SET_SCAN_ENABLE, cmd_pkt)
def hci_le_set_scan_parameters(sock):
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
SCAN_RANDOM = 0x01
OWN_TYPE = SCAN_RANDOM
SCAN_TYPE = 0x01
def parse_events(sock, loop_count=100):
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# perform a device inquiry on bluetooth device #0
# The inquiry should last 8 * 1.28 = 10.24 seconds
# before the inquiry is performed, bluez should flush its cache of
# previously discovered devices
flt = bluez.hci_filter_new()
bluez.hci_filter_all_events(flt)
bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT)
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt )
done = False
results = []
myFullList = []
for i in range(0, loop_count):
pkt = sock.recv(255)
ptype, event, plen = struct.unpack("BBB", pkt[:3])
#print "--------------"
if event == bluez.EVT_INQUIRY_RESULT_WITH_RSSI:
i =0
elif event == bluez.EVT_NUM_COMP_PKTS:
i =0
elif event == bluez.EVT_DISCONN_COMPLETE:
i =0
elif event == LE_META_EVENT:
subevent, = struct.unpack("B", pkt[3])
pkt = pkt[4:]
if subevent == EVT_LE_CONN_COMPLETE:
le_handle_connection_complete(pkt)
elif subevent == EVT_LE_ADVERTISING_REPORT:
#print "advertising report"
num_reports = struct.unpack("B", pkt[0])[0]
report_pkt_offset = 0
for i in range(0, num_reports):
Mac = packed_bdaddr_to_string(pkt[report_pkt_offset + 3:report_pkt_offset + 9])
for Mac in row[1]:
print "-------------"
#print "\tfullpacket: ", printpacket(pkt)
print "\tMAC address: ", row[1] # commented out - don't know what this byte is. It's NOT TXPower
txpower, = struct.unpack("b", pkt[report_pkt_offset -2])
print "\t(Unknown):", txpower
rssi, = struct.unpack("b", pkt[report_pkt_offset -1])
print "\tRSSI:", rssi
break
# build the return string
Adstring = packed_bdaddr_to_string(pkt[report_pkt_offset + 3:report_pkt_offset + 9])
Adstring += ","
Adstring += returnstringpacket(pkt[report_pkt_offset -22: report_pkt_offset - 6])
Adstring += ","
Adstring += "%i" % returnnumberpacket(pkt[report_pkt_offset -6: report_pkt_offset - 4])
Adstring += ","
Adstring += "%i" % returnnumberpacket(pkt[report_pkt_offset -4: report_pkt_offset - 2])
Adstring += ","
Adstring += "%i" % struct.unpack("b", pkt[report_pkt_offset -2])
Adstring += ","
Adstring += "%i" % struct.unpack("b", pkt[report_pkt_offset -1])
#print "\tAdstring=", Adstring
myFullList.append(Adstring)
done = True
sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, old_filter )
return myFullList
db.close()
The above is save as blescan.py. I run this file below to do a ble scan.
import blescan
import sys
import bluetooth._bluetooth as bluez
dev_id = 0
try:
sock = bluez.hci_open_dev(dev_id)
print "ble thread started"
except:
print "error accessing bluetooth device..."
sys.exit(1)
blescan.hci_le_set_scan_parameters(sock)
blescan.hci_enable_le_scan(sock)
while True:
returnedList = blescan.parse_events(sock, 10)
print "----------"

reading DNS packets in Python

I'm playing around with Python sockets, and decided to see if I could implement a very basic name server (i.e. a lookup table for a domain name to an IP address). So I've set up my server so far to just dump the received data.
#!/usr/bin/python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = ''
port = 53
size = 512
s.bind((host, port))
while True:
data, addr = s.recvfrom(size)
print repr(data)
When I run the above code and point my DNS to 127.0.0.1 I get something akin to the following:
'Y\x04\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01'
'J\xaa\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x1c\x00\x01'
'Y\x04\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x03com\x00\x00\x01\x00\x01'
I'm assuming that it is something to do with the DNS question packet structure, but I'm not to sure.
A) Are the above escape characters? A specific text encoding? Or simply just bytes?
B) How can I interpret the data and work with it?
EDIT: Changing the socket to take raw instead of datagrams results in the following:
'E\x00$\x00\xe4\x96\x00\x00#\x01\x00\x00\x7f\x00\x00\x01\x7f\x00\x00\x01\x03\x03X\xb6\x00\x00\x00\x00E\x00V\x00m\x82\x00\x00\xff\x11\x00\x00\x7f\x00\x00\x01\x7f\x00\x00\x01\xf3\xe1\x005\x00B\x00\x00'
You could start with something like this:
#!/usr/bin/env python
import pprint
import socket
import struct
def decode_labels(message, offset):
labels = []
while True:
length, = struct.unpack_from("!B", message, offset)
if (length & 0xC0) == 0xC0:
pointer, = struct.unpack_from("!H", message, offset)
offset += 2
return labels + decode_labels(message, pointer & 0x3FFF), offset
if (length & 0xC0) != 0x00:
raise StandardError("unknown label encoding")
offset += 1
if length == 0:
return labels, offset
labels.append(*struct.unpack_from("!%ds" % length, message, offset))
offset += length
DNS_QUERY_SECTION_FORMAT = struct.Struct("!2H")
def decode_question_section(message, offset, qdcount):
questions = []
for _ in range(qdcount):
qname, offset = decode_labels(message, offset)
qtype, qclass = DNS_QUERY_SECTION_FORMAT.unpack_from(message, offset)
offset += DNS_QUERY_SECTION_FORMAT.size
question = {"domain_name": qname,
"query_type": qtype,
"query_class": qclass}
questions.append(question)
return questions, offset
DNS_QUERY_MESSAGE_HEADER = struct.Struct("!6H")
def decode_dns_message(message):
id, misc, qdcount, ancount, nscount, arcount = DNS_QUERY_MESSAGE_HEADER.unpack_from(message)
qr = (misc & 0x8000) != 0
opcode = (misc & 0x7800) >> 11
aa = (misc & 0x0400) != 0
tc = (misc & 0x200) != 0
rd = (misc & 0x100) != 0
ra = (misc & 0x80) != 0
z = (misc & 0x70) >> 4
rcode = misc & 0xF
offset = DNS_QUERY_MESSAGE_HEADER.size
questions, offset = decode_question_section(message, offset, qdcount)
result = {"id": id,
"is_response": qr,
"opcode": opcode,
"is_authoritative": aa,
"is_truncated": tc,
"recursion_desired": rd,
"recursion_available": ra,
"reserved": z,
"response_code": rcode,
"question_count": qdcount,
"answer_count": ancount,
"authority_count": nscount,
"additional_count": arcount,
"questions": questions}
return result
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = ''
port = 53
size = 512
s.bind((host, port))
while True:
data, addr = s.recvfrom(size)
pprint.pprint(decode_dns_message(data))
And then fill in the decoding functions for the remaining records.
Here's an example to send and receive dns packets using socket and dnslib:
import socket
from dnslib import DNSRecord
forward_addr = ("8.8.8.8", 53) # dns and port
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
qname = "duckgo.com" # query
q = DNSRecord.question(qname)
client.sendto(bytes(q.pack()), forward_addr)
data, _ = client.recvfrom(1024)
d = DNSRecord.parse(data)
print("r", str(d.rr[0].rdata)) # prints the A record of duckgo.com

Categories

Resources