Python uses Raw Socket for Ethernet frame injection and pythonraw
1. Frame Injection
For introduction to Ethernet frames and Raw sockets, refer to a previous blog post that uses Raw Socket for Ethernet frame sniffing. Frame injection features:
2. Code Experiment
To enter the python runtime environment, add the root permission. (sudo python
).
>>>
>>> Import socket
>>> Import struct
>>>
>>>
>>> RawSocket = socket. socket (socket. PF_PACKET, socket. SOCK_RAW, socket. htons (0x0800 ))
>>>
>>> RawSocket. bind ("eth0", socket. htons (0x0800 )))
>>> Packet = struct. pack ("! 6s6s2s ", '\ xaa', '\ xbb', '\ x08 \ x00 ')
>>>
>>> Packet
'\ Xaa \ xbb \ x08 \ x00'
>>>
>>> Len (packet)
14
>>>
>>> RawSocket. send (packet + "hello, there .")
27
>>>
The PF_PACKET protocol family is still used here. It is bound to the eth0 network interface and the port number is 0x0800. Use the pack () function of the struct module to encapsulate frames. The Ethernet frame header consists of 14 bytes, which are 6-byte destination mac address, 6-byte source mac address, and 2-byte Protocol ."! In 6s6s2s"!
Indicates group packages by network order. The len () function is used to calculate the packet length, which is exactly 14 bytes. Add the content we want to send to the network where the data is sent, and the returned result is the length of the sent data.
Use tcpdump or wireshark to view the data we sent. Here I use tcpdump, and enter the following command in the terminal (I use Ubuntu Server and ssh connection. Filter out data with port 22 for ease of viewing. Remove messy data), and then resend the data:
$ sudo tcpdump -i eth0 -vv -XX "not port 22 and not arp and not udp"
The second packet in the result shows that our random data has been injected into the network.