Ruby Raw Sockets

F

Filipe Manana

Hello,

I am trying to do packet injection through a Ruby socket, like this:

PF_PACKET = 17 # linux/socket.h
AF_PACKET = PF_PACKET # linux/socket.h
ETH_P_ALL = 0x03_00 # linux/if_ether.h (but in network byte order)
SIOCGIFINDEX = 0x89_33 # bits/ioctls.h


def inject(interface, packet_bytes)

sock = Socket.new(PF_PACKET, Socket::SOCK_DGRAM, ETH_P_ALL)

# struct ifreq in net/if.h
ifreq = [interface.dup].pack 'a32'
sock.ioctl(SIOCGIFINDEX, ifreq)

# struct sockaddr_ll in linux/if_packet.h
sll = [AF_PACKET].pack 's'
sll << ( [ETH_P_ALL].pack 's' )
sll << ifreq[16..20]
sll << ("\x00" * 12)
sock.bind sll

sock.send(packet_bytes, 0)
# sock.write(packet_bytes) # doesn't work either
end


Unfortunately this fails when sending the packet (of type String). I get
the exception Errno::EINVAL (message "Invalid argument").

this code is based in the C code at:
(http) security-freak.net/packet-injection/PacketInjection_ethernet.c

What am I doing wrong?

Thanks
 
F

Filipe Manana

Forget it... found the error Socket::SOCK_DGRAM.. Must use
Socket::SOCK_RAW..

def inject(interface, packet_bytes)

sock = Socket.new(PF_PACKET, Socket::SOCK_DGRAM, ETH_P_ALL)

# struct ifreq in net/if.h
ifreq = [interface.dup].pack 'a32'
sock.ioctl(SIOCGIFINDEX, ifreq)

# struct sockaddr_ll in linux/if_packet.h
sll = [AF_PACKET].pack 's'
sll << ( [ETH_P_ALL].pack 's' )
sll << ifreq[16..20]
sll << ("\x00" * 12)
sock.bind sll

sock.write(packet_bytes) #
end
 
J

Joel VanderWerf

Filipe said:
Hello,

I am trying to do packet injection through a Ruby socket, like this:

PF_PACKET = 17 # linux/socket.h
AF_PACKET = PF_PACKET # linux/socket.h
ETH_P_ALL = 0x03_00 # linux/if_ether.h (but in network byte order)
SIOCGIFINDEX = 0x89_33 # bits/ioctls.h

Unsolicited suggestion: if you're doing a lot of packing, byte swapping,
etc, take a look at my bit-struct lib for constructing packets[1]. There
are even a couple of basic raw IP examples, though you seem to have
gotten well beyond the basics.

[1] http://raa.ruby-lang.org/project/bit-struct/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,044
Members
48,769
Latest member
Clifft

Latest Threads

Top