Last active
May 18, 2023 15:02
-
-
Save hadi2f244/6f6e561b9727abbfe340a310ca8fa539 to your computer and use it in GitHub Desktop.
sudo python3 main.py 172.16.16.181 2233 172.16.23.20 4444
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import struct | |
import array | |
import argparse | |
# Instantiate the parser | |
parser = argparse.ArgumentParser(description='Send custom tcp packet') | |
parser.add_argument('src_ip', type=str, | |
help='Source IP address') | |
parser.add_argument('src_port', type=int, | |
help='Source Port') | |
parser.add_argument('dst_ip', type=str, | |
help='Destination IP address') | |
parser.add_argument('dst_port', type=int, | |
help='Destination Port') | |
args = parser.parse_args() | |
class TCPPacket: | |
def __init__(self, | |
src_host: str, | |
src_port: int, | |
dst_host: str, | |
dst_port: int, | |
flags: int = 0): | |
self.src_host = src_host | |
self.src_port = src_port | |
self.dst_host = dst_host | |
self.dst_port = dst_port | |
self.flags = flags | |
def build(self) -> bytes: | |
packet = struct.pack( | |
'!HHIIBBHHH', | |
self.src_port, # Source Port | |
self.dst_port, # Destination Port | |
0, # Sequence Number | |
0, # Acknoledgement Number | |
5 << 4, # Data Offset | |
self.flags, # Flags | |
8192, # Window | |
0, # Checksum (initial value) | |
0 # Urgent pointer | |
) | |
pseudo_hdr = struct.pack( | |
'!4s4sHH', | |
socket.inet_aton(self.src_host), # Source Address | |
socket.inet_aton(self.dst_host), # Destination Address | |
socket.IPPROTO_TCP, # PTCL | |
len(packet) # TCP Length | |
) | |
checksum = self.chksum(pseudo_hdr + packet) | |
packet = packet[:16] + struct.pack('H', checksum) + packet[18:] | |
return packet | |
def chksum(self, packet: bytes) -> int: | |
if len(packet) % 2 != 0: | |
packet += b'\0' | |
res = sum(array.array("H", packet)) | |
res = (res >> 16) + (res & 0xffff) | |
res += res >> 16 | |
return (~res) & 0xffff | |
pak = TCPPacket( | |
args.src_ip, | |
args.src_port, | |
args.dst_ip, | |
args.dst_port, | |
0b000101001 # Merry Christmas! | |
) | |
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP) | |
s.sendto(pak.build(), (args.dst_ip, 0)) | |
BUFFER_SIZE = 10240 | |
data = s.recv(BUFFER_SIZE) | |
s.close() | |
print ("received data:", data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment