I want to be able to display hex data from a StreamSocket in scapy. This is my current scapy code
from scapy.all import socket, StreamSocket, Raw
import data_packets, returned_data
data = data_packets.client_to_server_init()
mysocket = socket.socket()
mysocket.connect((args.IP_Address, args.dPort))
myStream = StreamSocket(mysocket)
result=myStream.sr1(Raw(data))
result.show()
The result is similar to that shown below
###[ Raw ]###
load = '\x00\x00\x02\x99R\x92\x05R\xec\x02R\xe9\x02R...
Basically I want everything to be in hex whereas currently the returned data is coming back as a mix of hex and ASCII characters as you can see from the output above (Notice the capital R's that are mixed in between, those are \x52 being converted to ASCII)
NOTE: I've tried creating my own show() function but it hasn't changed anything. That code is below
def my_show(packet):
for f in packet.fields_desc:
fvalue = packet.getfieldval(f.name)
reprval = f.i2repr(packet,fvalue)
return "%s" % (reprval)
You could try taking a page from Python: print a string as hex bytes?
and use encode('hex') on your outpt as part of my_show:
return ':'.join(x.encode('hex') for x in fvalue)
Related
I've been going by the 802.11-2020 standard document to code up calculating the pairwise transient key (PTK) of a client joining a known network (SSID/PSK). I've validated the PTK through debugs of wpa_supplicant (-dd -K switches) on a Linux box. So, given the correct key and generating the nonce and AAD from information in the 802.11/CCMP headers, I should be able to drop the last 4 bytes (FCS) take the next to last 8 bytes as the MAC and decrypt the payload and verify using the MAC. My code fails the integrity check of either the decrypt_and_verify() or decrypt() followed by verify(). However, the output of decrypt() is in fact the clear text frame payload with padded 0's. If I re-encrypt that, I get the same encrypted data but with a different MAC. So, I'm trying to figure out why it's failing the original integrity check as well as why the decrypted data comes back padded with zeros. In Annex J of the standard document, there is sample data and my code works just fine for the sample data. Here's my code with hardcoded sample data from my lab (need pycryptodome and latest scapy from github):
import binascii
from Crypto.Cipher import AES
from scapy.all import *
#hardcoded data from lab setup
key = binascii.a2b_hex('43e3229c41fec8fb81222388c0b5d3d3')
nonce = binascii.a2b_hex('03380e4dc29a0d000000000001')
aad = binascii.a2b_hex('8842687f748e4979380e4dc29a0d70ca9b3b67ff00000300')
header = binascii.a2b_hex('880a2c00687f748e4979380e4dc29a0d70ca9b3b67ff00000300') #header for constructing clear text frame
payload = binascii.a2b_hex('b1df4bb514f0fe2c8415690ee0f6340cce486bab2ca4188ff0be70432d6d9548c4cd7ca4e49e6b1298b16ec958b453862f3cf582743f77f8b1ab49f41c6d')
#grab actual encrypted payload
cipherdata = payload[:-12]
#grab MAC
tag = payload[len(payload)-12:len(payload)-4]
#decrypt payload
cipher = AES.new(key, AES.MODE_CCM, nonce, mac_len=8, msg_len=len(cipherdata), assoc_len=len(aad))
cipher.update(aad)
data = cipher.decrypt(cipherdata)
#construct RadioTap packet
mypacket = RadioTap()
mypacket.payload = header + data
mypacket.decode_payload_as(Dot11)
mypacket.show() #see a nice ARP frame
#wireshark(mypacket) #uncomment to see frame in Wireshark
try:
cipher.verify(tag)
except Exception as ex:
print(ex)
#reencrypt clear data
cipher2 = AES.new(key, AES.MODE_CCM, nonce, mac_len=8, msg_len=len(data), assoc_len=len(aad))
cipher2.update(aad)
cipherdata2, tag2 = cipher2.encrypt_and_digest(data)
print(f'cipherdata = {cipherdata.hex()}')
print(f'tag = {tag.hex()}')
print(f'cipherdata2 = {cipherdata2.hex()}') #will be the same as cipherdata
print(f'tag2 = {tag2.hex()}') #will be different than tag
I am trying to extract some Client Hello information from a network packet.
I am actually printing some values just for testing.
def parse_client_hello(handshake):
if isinstance(handshake.data, dpkt.ssl.TLSClientHello):
client = dpkt.ssl.TLSClientHello(str(handshake.data))
print(client.random)
print(client.version)
The result is as the above :
Is the printed out data represented in ASCII?
Why is the data printed out in ASCII when in fact the captured packet is in binary?
How can I print it in another form , for ex. in hexadecimal?
Thank you!
New in Python version 3.5: bytes.hex():
...
print(client.random.hex())
print(client.version)
If you're on anything older than that, binascii.hexlify will work:
from binascii import hexlify
...
...
print(hexlify(client.random))
print(client.version)
Or a bilingual solution:
if hasattr(bytes, 'hex'):
b2h = bytes.hex
else:
from binascii import hexlify as b2h
...
...
print(b2h(client.random))
print(client.version)
Im using the following subprocess call c = subprocess.Popen("wmic nic where 'netconnectionid like '%οπικ%' and PhysicalAdapter=True' get netconnectionid",stdout=subprocess.PIPE). What i want to do is pass the netconnectionid (aka network adapter name) so i can pass it into a variable and use it here
ip = self.ip_list.currentText()
subprocess.Popen('netsh interface ipv4 set address name="' + sk + '"
static 192.168.131.' + ip + ' 255.255.255.0 192.168.131.1')
Im doing this because adapter names differ in different pcs. The problem is here :
os = c.stdout.read()
sk = os.splitlines()[2].strip().decode('cp437')
The result is 'Τοπική σύνδεση'.Im trying to convert the bytes to greek letters.I have tried utf-8 and it doesnt work. I tried printing the sk variable with .decode('cp437') and its the only decoding option that does right but after that,the netsh command wont work anyway.I tried renaming the adapter with english letters and decoding with utf-8 and it works so well.This is what i basically want to convert :
b'\xe7?\xe3??? \xe5??\xeb\xee\xe5?'
Any ideas on how to make this work?
Try using encoding utf-8.
greek_string = 'Τοπική σύνδεση'
encoded_string = greek_string.encode('utf-8')
decoded_string = encoded_string.decode()
print('Original: {}\n\nEncoded: {}\nDecoded: {}'.format(greek_string,
encoded_string,
decoded_string))
Output:
Original: Τοπική σύνδεση
Encoded: b'\xce\xa4\xce\xbf\xcf\x80\xce\xb9\xce\xba\xce\xae \xcf\x83\xcf\x8d\xce\xbd\xce\xb4\xce\xb5\xcf\x83\xce\xb7'
Decoded: Τοπική σύνδεση
I have a script that sends a JSON UTF-8 encoded Byte string to a socket. (A github project: https://github.com/alios/raildriver). Now I'm writing the python script that needs to read the incoming data. Right now I can receive the data and print it to the terminal. With the following script: https://www.binarytides.com/code-telnet-client-sockets-python/
Output:
data = '{"Current": 117.42609405517578, "Accelerometer": -5.394751071929932, "SpeedometerKPH": 67.12493133544922, "Ammeter": 117.3575210571289, "Amp": 117.35590362548828, "Acceleration": -0.03285316377878189, "TractiveEffort": -5.394751071929932, "Effort": 48.72163772583008, "RawTargetDistance": 3993.927734375, "TargetDistanceBar": 0.9777777791023254, "TargetDistanceDigits100": -1.0, "TargetDistanceDigits1000": -1.0}'
The problem is that I can't find how to read the JSON array. For example read "Ammeter" and return its value 117.357521057289 to a new variable.
All the data is being received in the variable data
The code I have right now:
decodedjson = data.decode('utf-8')
dumpedjson = json.dumps(decodedjson)
loadedjson = json.loads(dumpedjson)
Can you please help me?
You are encoding to JSON then decoding again. SImply not encode, remove the second line:
decodedjson = data.decode('utf-8')
loadedjson = json.loads(decodedjson)
If you are using Python 3.6 or newer, you don't actually have to decode from UTF-8, as the json.loads() function knows how to deal with UTF-encoded JSON data directly. The same applies to Python 2:
loadedjson = json.loads(data)
Demo using Python 3.7:
>>> data = b'{"Current": 117.42609405517578, "Accelerometer": -5.394751071929932, "SpeedometerKPH": 67.12493133544922, "Ammeter": 117.3575210571289, "Amp": 117.35590362548828, "Acceleration": -0.03285316377878189, "TractiveEffort": -5.394751071929932, "Effort": 48.72163772583008, "RawTargetDistance": 3993.927734375, "TargetDistanceBar": 0.9777777791023254, "TargetDistanceDigits100": -1.0, "TargetDistanceDigits1000": -1.0}'
>>> loadedjson = json.loads(data)
>>> loadedjson['Ammeter']
117.3575210571289
I'm trying to rewrite a pcap file with different IP and IPv6 addresses. But after I extract a packt by PcapReader and change its IP adresses, the packets in the output pcap file is cut short (that is to say the payload of the packet is lost).
Here's the example code:
from scapy.all import PcapReader
from scapy.all import PcapWriter
def test():
f = "input.pcap"
writers = PcapWriter("output.pcap")
with PcapReader(f) as pcap_reader:
for pkt in pcap_reader:
# somehow change the IP address
writers.write(pkt=pkt)
test()
When I open the .pcap file with WireShark, it shows "The capture file appears to have been cut short in the middle of a packet".
Is there any solution in scapy to maintain the payload or is there any other python packets to recommand?
here I did not change anything and the results are like this:
input file:
enter image description here
output file:
enter image description here
I think the problem must be in the code you use to modify the packet (and which you did not show) or that your source file already had short packets (i.e. snaplen less than packet len). The following code works for me without problems:
from scapy.all import PcapReader,PcapWriter,IP
writer = PcapWriter('output.pcap')
for pkt in PcapReader('input.pcap'):
# somehow change the IP address
pkt[IP].dst = '1.2.3.4'
pkt[IP].src = '5.6.7.8'
writer.write(pkt=pkt)