Dpkt lib - how to add timestamp to packet - python

So I am trying to create my own pcap file, I've created a msg using dpkt but I am not understanding how to maneuver timestamp, from what I've seen it is the 3rd parameter in writepkt but I don't understand how to initial the variable.. this is a part of my code
output_pcapfile = dpkt.pcap.Writer(open(__file__+'.pcap','wb'))
tcpSrc.data = 'Some data\r\n'
ipSrc.data = tcpSrc
ipSrc.len = len(str(ipSrc))
ethSrc.data = ipSrc
packet_count = 1
output_pcapfile.writepkt(ethSrc,packet_count) # somehow get timestamp for third parameter!!
Anyone has an idea? thanks !

looking at the 1.7 source for pcap.py,
I see:
def writepkt(self, pkt, ts=None):
if ts is None:
ts = time.time()
#some more code..
This function takes two non-self arguments
The timestamp will be created if you only pass in the pkt itself, e.g.
output_pcapfile.writepkt(ethSrc)

Related

Getting position data from UBX protocol

I am working on a project which is use ublox .ubx protocol to getting position information. I'm using serial communication to connect my GPS module and getting position information to python sketch. I used Serial and pyubx2 libraries my sketch as follows,
from serial import Serial
from pyubx2 import UBXReader
stream = Serial('COM8', 38400)
while True:
ubr = UBXReader(stream)
(raw_data, parsed_data) = ubr.read()
print(parsed_data)
Then I have received information from GPS module as follows. It is continuously sending many of information in every second like as follows,
<UBX(NAV-SOL, iTOW=00:11:43, fTOW=-215069, week=0, gpsFix=0, gpsfixOK=0, diffSoln=0, wknSet=0, towSet=0, ecefX=637813700, ecefY=0, ecefZ=0, pAcc=649523840, ecefVX=0, ecefVY=0, ecefVZ=0, sAcc=2000, pDOP=99.99, reserved1=2, numSV=0, reserved2=215800)>
<UBX(NAV-PVT, iTOW=00:11:43, year=2015, month=10, day=18, hour=0, min=12, second=1, validDate=0, validTime=0, fullyResolved=0, validMag=0, tAcc=4294967295, nano=-215068, fixType=0, gnssFixOk=0, difSoln=0, psmState=0, headVehValid=0, carrSoln=0, confirmedAvai=0, confirmedDate=0, confirmedTime=0, numSV=0, lon=0.0, lat=0.0, height=0, hMSL=-17000, hAcc=4294967295, vAcc=3750027776, velN=0, velE=0, velD=0, gSpeed=0, headMot=0.0, sAcc=20000, headAcc=180.0, pDOP=99.99, invalidLlh=0, lastCorrectionAge=0, reserved0=2312952, headVeh=0.0, magDec=0.0, magAcc=0.0)>
I want to assign those position information (latitude, longitude, altitude etc.) into variables and hope to do some analysis part in further. So how can I derive positional information individually from this type of sentences.
Try something like this (press CTRL-C to terminate) ...
from serial import Serial
from pyubx2 import UBXReader
try:
stream = Serial('COM8', 38400)
while True:
ubr = UBXReader(stream)
(raw_data, parsed_data) = ubr.read()
# print(parsed_data)
if parsed_data.identity == "NAV-PVT":
lat, lon, alt = parsed_data.lat, parsed_data.lon, parsed_data.hMSL
print(f"lat = {lat}, lon = {lon}, alt = {alt/1000} m")
except KeyboardInterrupt:
print("Terminated by user")
For further assistance, refer to https://github.com/semuconsulting/pyubx2 (there are several example Python scripts in the /examples folder).

How to create a python dictionary containing an ARP table?

I have created a python script to detect an ARP attack. I have already initiated a ARP spoof attack and stored the wireshark capture in a pcap file. Once the code is executed, the code is designed to alert of any possible attack based on the MAC value change.
But how do I create a dictionary in the first place to store the MAC--IP mappings, and then detect when there is a change of values to indicate an alert?
Can anyone guide me please?
from scapy.all import *
mac_table = {}
def main():
pkts = rdpcap('/root/Desktop/arp_capture.pcap')
for packet in pkts:
if packet.haslayer(ARP):
if packet[ARP].op == 2:
try:
original_mac = req_mac(packet[ARP].psrc)
new_mac = packet[ARP].hwsrc
if original_mac != new_mac:
print(f"[**] ATTACK ALERT !!!!!! CHECK ARP TABLES !!![**]")
except IndexError:
pass
def req_mac(ip):
arp_req = ARP(pdst=ip)
bcst_req = Ether(dst='ff:ff:ff:ff:ff:ff')
p = bcst_req/arp_req
result = srp(p, timeout=3, verbose=False)[0]
return result[0][1].hwsrc
if __name__ == "__main__":
main()

Compute uniswap pair address via python

I`m trying to compute (off-line, i.e. without an http requests) address of an Uniswap pair,
with python, web3 and eth-abi libraries, based on this solidity
example.
address factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address token0 = 0xCAFE000000000000000000000000000000000000; // change me!
address token1 = 0xF00D000000000000000000000000000000000000; // change me!
address pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
Have some thoughts:
hexadem_ ='0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
hexadem_1 = 0xff
abiEncoded_1 = encode_abi_packed(['address', 'address'], ( token_0, token_1 ))
salt_ = web3.Web3.solidityKeccak(['bytes'], ['0x' +abiEncoded_1.hex()])
abiEncoded_2 = encode_abi_packed(['bytes', 'address', 'bytes32'], (bytes(hexadem_1), factory, salt_))
resPair = web3.Web3.solidityKeccak(['bytes','bytes'], ['0x' +abiEncoded_2.hex(), hexadem_])
Can somebody suggest me, what is wrong, which way it should be considered?
Firstly, resPair is too long to be a contract address.
The rules can be explained by reading this: https://eips.ethereum.org/EIPS/eip-1014
Also make sure you enter the two addresses in alphabetical order. Use the .sort() function to do this.
Here is the correct code:
hexadem_ ='0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
hexadem_1 = 0xff
factory = '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f'
abiEncoded_1 = encode_abi_packed(['address', 'address'], ('0x7825e833d495f3d1c28872415a4aee339d26ac88', '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2' )) #these two addresses to be changed as fit. Currently they are TLOS and WETH
salt_ = w3.solidityKeccak(['bytes'], ['0x' +abiEncoded_1.hex()])
abiEncoded_2 = encode_abi_packed([ 'address', 'bytes32'], ( factory, salt_))
resPair = w3.solidityKeccak(['bytes','bytes'], ['0xff' + abiEncoded_2.hex(), hexadem_])[12:]
resPair
You are using wrong hexadem_
Use this one:
hexadem_ = 0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5
See line 298 in the contract source of PancakeRouter
https://bscscan.com/address/0x10ED43C718714eb63d5aA57B78B54704E256024E#code

Python Paraview

How to extract data from server to the client in Paraview parallel running mode
my script is:
def getNumberOfBlocks(px):
data1 = servermanager.Fetch(px,0)
data2 = servermanager.Fetch(px,1)
group = vtk.vtkMultiBlockDataGroupFilter()
group.AddInputConnection(group.GetOutputPortn())
group.AddInputConnection(group.GetOutputPort())
group.Update()
group.AddInputConnection(transformer2.GetOutputPort())
data3 = group.GetOutputPort()
data = vtk.vtkMultiBlockDataGroupFilter.SafeDownCast(data3)
return data.GetNumberOfBlocks()
px is a proxy from where i am getting data.
there are two port , i need to fetch the data from these port all at a time.
thanks for help.
I'm a little confused by your script - won't it always return 3?
If you just want to get the number of blocks and px is of type vtkSMSourceProxy, you can use the following:
def getNumberOfBlocks(px):
di = GetDataInformation()
cdi = di.GetCompositeDataInformation()
return cdi.GetNumberOfChildren()

Raw socket python packet sniffer

I have created a simple RAW socket based packet sniffer. But when I run it, it rarely captures up a packet. First I created this to capture packets in 1 second time intervals, but seeing no packets are captured I commented that line. I was connected to internet and a lot of http traffic are going here and there, but I could not capture a one. Is there a problem in this in the code where I created the socket? Please someone give me a solution. I am fairly new to python programming and could not understand how to solve this.
import socket, binascii, struct
import time
sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x800))
print "Waiting.."
pkt = sock.recv(2048)
print "received"
def processEth(data):
#some code to process source mac and dest. mac
return [smac, dmac]
def processIP(data):
sip = str(binascii.hexlify(data[1]))
dip = str(binascii.hexlify(data[2]))
return [sip, dip]
def processTCP(data):
sport = str(data[0])
dport = str(data[1])
return [sport, dport]
while len(pkt) > 0 :
if(len(pkt)) > 54:
pkt = sock.recv(2048)
ethHeader = pkt[0][0:14]
ipHeader = pkt[0][14:34]
tcpHeader = pkt[0][34:54]
ethH = struct.unpack("!6s6s2s",ethHeader)
ethdata = processEth(ethH)
ipH = struct.unpack("!12s4s4s",ipHeader)
ipdata = processIP(ipH)
tcpH = struct.unpack("!HH16", tcpHeader)
tcpdata = processTCP(tcpH)
print "S.mac "+ethdata[0]+" D.mac "+ethdata[1]+" from: "+ipdata[0]+":"+tcpdata[0]+" to: "+ipdata[1]+":"+tcpdata[1]
#time.sleep(1);
else:
continue
If you showed all the code, you are running into an endless loop.
Whenever a paket is coming in which has not a length greater then 54 bytes, you end up reading the same packet all the time.
Additionally, socket.recv() returns a string/byte sequence; your approach of accessing the data is wrong. pkt[0] returns a string with length 1; pkt[0][x:y] will not return something useful.
I am not familiar with using sockets, but with some changes I got output that might look similar to what you intended (there is something missing in processEth() I think...).
[...]
while len(pkt) > 0:
print "Waiting.."
pkt = sock.recv(2048)
print "received"
if(len(pkt)) > 54:
ethHeader = pkt[0:14]
ipHeader = pkt[14:34]
tcpHeader = pkt[34:38]
ethH = struct.unpack("!6s6s2s",ethHeader)
ethdata = processEth(ethH)
ipH = struct.unpack("!12s4s4s",ipHeader)
ipdata = processIP(ipH)
tcpH = struct.unpack("!HH16", tcpHeader)
tcpdata = processTCP(tcpH)
print "S.mac "+ethdata[0]+" D.mac "+ethdata[1]+" from: "+ipdata[0]+":"+tcpdata[0]+" to: "+ipdata[1]+":"+tcpdata[1]
#time.sleep(1);
else:
continue

Categories