PracticeDev/study_python/tcp_relay-master/test.py.bak

107 lines
2.4 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_payload_len = total_len - iphdr_len - tcp_hdrlen
return tcp_payload_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_payload_len =calculate_tcp_length(pkt)
total_length = tcp_hdrlen + tcp_payload_len
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("!4s4sBBH",
source_ip,
destination_ip,
reserved,
protocol,
total_length
)
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
pkt = str(pkt[IP])
tcp_header = pkt[iphdr_len:iphdr_len+20]
tcp_payload = pkt[iphdr_len+tcp_hdrlen:]
print(hexdump(tcp_header))
print(hexdump(tcp_payload))
tcp = psh + tcp_header + tcp_payload
print(hexdump(tcp))
res = hmac.new(keyd, tcp, hashlib.md5).digest()
print(hexdump(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()