Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Raw socket - IP_HDRINCL option

Tags:

python

sockets

According to the manual page of raw sockets,

The IPv4 layer generates an IP header when sending a packet unless the IP_HDRINCL socket option is enabled on the socket. When it is enabled, the packet must contain an IP header. For receiving the IP header is always included in the packet.

I'm using python to test the IP_HDRINCL socket option, so i have generated an IP Header but after enabling the option, unfortunately the sendto() method doesn't seems to be worked, i got the following error

Traceback (most recent call last): File "./test.py", line 35, in s.sendto(pkt, (dip , 0 )) socket.error: [Errno 1] Operation not permitted

just keep in mind that i'm running the program with the uid 0 (root)

Note:

I don't want to use raw socket along with the PACKET FAMILY, i still want to make use of the TCP/IP stack implemented in the kernel

Here is the sample i created:

#!/usr/bin/env python
import socket
import struct
def IP():
    version = 4
    ihl = 5
    DF = 0
    Tlen = 0
    ID = 0
    Flag = 0
    Fragment = 0
    TTL = 64
    Proto = socket.IPPROTO_TCP
    ip_checksum = 0
    SIP = socket.inet_aton("172.16.122.2")
    DIP = socket.inet_aton("172.16.122.1")
    ver_ihl = (version << 4) + ihl
    f_f = (Flag << 13) + Fragment
    ip_hdr =  struct.pack("!BBHHHBBH4s4s", ver_ihl,DF,Tlen,ID,f_f,TTL,Proto,ip_checksum,SIP,DIP)
    return ip_hdr
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)

# the error occurs only when the IP_HDRINCL is enabled 

s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
dip = "172.16.122.1"
pkt = IP() + "Hello"
s.sendto(pkt, (dip , 0 ))
like image 907
Th3carpenter Avatar asked Jul 11 '26 04:07

Th3carpenter


1 Answers

Have you tried using s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)instead?

You're setting the protocol to TCP but not writing the header. Perhaps when you set the IP_HDRINCL option there is some validation going on?

like image 148
chemdt Avatar answered Jul 16 '26 11:07

chemdt