'Crafting TCP SYN packet with Python3, impacket library and socket

I want to create a TCP SYN packet and send it using a socket. I am using impacket to help me craft the whole packet so I don't have to handle the whole packet creation process by myself.

I capture traffic in Wireshark and there I can see the following error for my TCP packets: Bogus TCP header length (0, must be at least 20)

Following code was used, I cannot see what causes the problem with TCP header. I know that Scapy would solve this problem but it is not an option for me. I am using macOS and Python3.10.

from impacket import ImpactPacket
from socket import socket, AF_INET, SOCK_RAW, IPPROTO_TCP

# IP layer
ip = ImpactPacket.IP()
ip.set_ip_dst("192.168.0.80")
# TCP layer
tcp = ImpactPacket.TCP()
tcp.set_th_dport(80)
tcp.set_th_seq(1)
tcp.set_th_ack(1)
tcp.set_th_flags(0x02) # SYN Flag
tcp.set_th_win(64)
tcp.contains(ImpactPacket.Data(b"A"*128))
ip.contains(tcp)  # add TCP to IP

sock = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)  # create socket
seq_id = 0

for _ in range(5):
    seq_id += 1
    tcp.set_th_seq(seq_id)
    tcp.calculate_checksum()
    sock.sendto(ip.get_packet(), ("192.168.0.80", 80))

sock.close()


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source