PracticeDev/study_python/tcp_relay-master/test.py

122 lines
2.6 KiB
Python
Raw Normal View History

2022-12-20 17:31:11 +08:00
from scapy.all import *
import socket
import struct
import hmac
import hashlib
keyd = '123'
def calculate_tcp_length(pkt):
iphdr_len = pkt[IP].ihl * 4
total_len = pkt[IP].len
tcp_hdrlen = pkt[TCP].dataofs * 4
tcp_len = total_len - iphdr_len
return tcp_len
def refill_tcp_pseudo_header(pkt):
destination = pkt[IP].dst
source = pkt[IP].src
reserved = 0
protocol = socket.IPPROTO_TCP
tcp_hdrlen = pkt[TCP].dataofs *4
tcp_len =calculate_tcp_length(pkt)
print("!!!!!!!!!!!!!!!!!!!!!!!!")
print(destination)
print(source)
destination_ip = int(socket.inet_aton(destination).encode('hex'),16)
source_ip = int(socket.inet_aton(source).encode('hex'),16)
print("%%%%%%%%%%%%%%%%%%%")
print(destination_ip)
destination_ip = struct.pack("!I",destination_ip)
print(repr(destination_ip))
print(source_ip)
source_ip = struct.pack("!I",source_ip)
print(repr(source_ip))
print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
#pseudo header
psh = struct.pack(
"!4s4sBBBB",
source_ip,
destination_ip,
reserved,
protocol,
reserved,
tcp_len # tcp length = ip len - ip header len
)
print(hexdump(psh))
return psh
def get_tcp_header(pkt):
pkt = pkt[IP]
iphdr_len = pkt[IP].ihl * 4
tcp_header = pkt[iphdr_len:iphdr_len+20]
tcp_payload = pkt[iphdr_len+20:]
def analysis_pkt(pkt):
ip = pkt[IP]
print(repr(ip))
print("#####################")
print(hexdump(ip))
tcp = pkt[TCP]
print(repr(tcp))
print("#####################")
tcp_options = pkt[TCP].options
print(repr(tcp_options))
print("#####################")
tcp_load = pkt[TCP].payload
print(repr(tcp_load))
print("#####################")
psh = refill_tcp_pseudo_header(pkt)
iphdr_len = pkt[IP].ihl * 4
tcp_hdrlen = pkt[TCP].dataofs * 4
pkt[TCP].chksum = 0
print "tcp_hdrlen=%d"%tcp_hdrlen
pkt = str(pkt[IP])
tcp_header = pkt[iphdr_len:iphdr_len+20]
tcp_payload = pkt[iphdr_len+tcp_hdrlen:]
print("!!!!!!!!!!!!!!!!!!!!")
print(hexdump(tcp_header))
print("@@@@@@@@@@@@@@@@@@@")
print(hexdump(tcp_payload))
tcp = psh + tcp_header + tcp_payload + keyd # pseudo-heaer + tcp_header(no option) + tcp_payload + key
print("##################")
print(hexdump(tcp))
print("##################")
print(repr(tcp))
ha_m5 = hashlib.md5()
ha_m5.update(tcp)
res = ha_m5.hexdigest()
print("$$$$$$$$$$$$$$$$$$$$")
print res
def main():
try:
pkts = rdpcap('test.pcap')
print("len=",len(pkts))
print("len=",len(str(pkts[0])))
for pktno in range(len(pkts)):
print(repr(pkts[pktno]))
print("#####################")
analysis_pkt(pkts[pktno])
except Scapy_Exception as e:
print(e)
if __name__=="__main__":
main()