Ruby Raw Sockets

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

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

Filipe Manana wrote:

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/

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs