简体   繁体   中英

Injecting raw TCP packets with Python

What would be a suitable way to inject a raw TCP packet with Python? For example, I have the payload consisting of hexadecimal numbers and I want to send that sequence of hexadecimal numbers to a network daemon: so that if I choose to send 'abcdef', I see 'abcdef' on the wire too. But not '6162636566' as in the case of:

new = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new.connect(('127.0.0.1', 9999))
new.send('abcdef')

Can I use Python's SOCK_RAW for this purpose? If so, can you give me an example of sending raw TCP packets with SOCK_RAW (since I did not get it working myself)

Thanks!

Evgeniy

Try scapy , a powerful interactive packet manipulation program.

Example:

%> sudo scapy

>>> packet1 = IP(dst='127.0.0.1')/TCP(dport=9999)
>>> packet1.payload = 'abcdef'
>>> send(packet1)
.
Sent 1 packets.
>>> packet1.show()
###[ IP ]###
  version= 4
  ihl= None
  tos= 0x0
  len= None
  id= 1
  flags= 
  frag= 0
  ttl= 64
  proto= ip
  chksum= None
  src= 127.0.0.1
  dst= 127.0.0.1
  \options\
###[ Raw ]###
     load= 'abcdef'
>>> 

Sounds like you might be confused about python character strings. For example, try:

new.send('\x0a\x0b\x0c\x0d\x0e\x0f')

Why not just converting your string to hex before sending it?

new = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new.connect(('127.0.0.1', 9999))
mydata = 'abcdef'
new.send(mydata.encode('hex'))

For raw sockets, SOCK_RAW is the way to go. Remember that when you are using SOCK_RAW, you cant just send the payload. You will have to do the header formation as well. After you get this right, you could face problems with Operating System. While doing Raw Sockets on Windows XP, we faced some problems due to security issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM