Skip to content

Instantly share code, notes, and snippets.

@HirbodBehnam
Created April 29, 2024 20:14
Show Gist options
  • Save HirbodBehnam/7912acaac13d349eb08bfd3708fa1f12 to your computer and use it in GitHub Desktop.
Save HirbodBehnam/7912acaac13d349eb08bfd3708fa1f12 to your computer and use it in GitHub Desktop.
Send a TCP syn using raw sockets
from socket import *
import struct
import random
def get_checksum(data: bytes) -> int:
sum = 0
for index in range(0, len(data), 2):
word = (data[index] << 8) + (data[index+1])
sum = sum + word
sum = (sum >> 16) + (sum & 0xffff)
sum = ~sum & 0xffff
return sum
# Options
from_ip = [192, 168, 1, 100]
to_ip = [1, 1, 1, 1]
source_port = 53317
destination_port = 11000
sequence_number = random.randint(0, 2 ** 32 - 1)
print("Seq is", sequence_number)
ack_number = 0
data_offset = 5 # 5 * 4 = 20 bytes header length
data_offset_and_reserved = data_offset << 4
flags = 1 << 1 # only syn is set
window_size = 5840
checksum = 0
urgent_pointer = 0
# The packet itself
tcp_packet = struct.pack('!HHLLBBHHH', source_port, destination_port, sequence_number, ack_number, data_offset_and_reserved, flags, window_size, checksum, urgent_pointer)
print(tcp_packet)
# Constructing pseudo header for checksum calculation
pseudo_hdr = struct.pack('!4s4sBBH', bytes(from_ip), bytes(to_ip), 0, IPPROTO_TCP, len(tcp_packet))
print(pseudo_hdr)
# Calculate checksum
checksum = get_checksum(pseudo_hdr + tcp_packet)
print("Checksum calculated as", hex(checksum))
tcp_packet = struct.pack('!HHLLBBHHH', source_port, destination_port, sequence_number, ack_number, data_offset_and_reserved, flags, window_size, checksum, urgent_pointer)
print(tcp_packet)
with socket(AF_INET, SOCK_RAW, IPPROTO_TCP) as s:
s.sendto(tcp_packet, ('.'.join(map(str, to_ip)), 0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment