Вопрос по – инструмент воспроизведения потока tcp
Я ищу инструмент для записи и воспроизведения одной стороны потока TCP для тестирования. Я вижу инструменты, которые записывают весь поток TCP (как серверный, так и клиентский) для тестирования межсетевых экранов и тому подобного, но я ищу инструмент, который бы записывал только трафик, представленный клиентом (с информацией о синхронизации), а затем повторно отправлял его на сервер для тестирования.
Запишите захват пакета полной связи TCP / клиент / сервер. Затем вы можете использоватьtcpliveplay воспроизвести только клиентскую часть связи на реальном сервере. tcpliveplay сгенерирует новые порядковые номера, IP-адреса, MAC-адреса и т. д., поэтому связь будет проходить правильно.
Посмотрите на WirePlaycode.google.com/p/wireplay или жеgithub.com/abhisek/wireplay который обещает воспроизвести на клиентской или серверной стороне захваченный сеанс TCP с изменением всех порядковых номеров SYN / ACK по мере необходимости.
Я не знаю, доступны ли какие-либо бинарные сборки, вам нужно будет скомпилировать их самостоятельно.
Обратите внимание, я еще не пробовал это сам, но изучаю это.
которым TCP обрабатывает повторные передачи, порядковые номера,SACK
и это может быть более сложной задачей, чем вы себе представляете.
Обычно люди используютtcpreplay для воспроизведения пакетов; однако этоне поддерживает синхронизацию порядковых номеров TCP, Поскольку вам необходим двунаправленный поток TCP (а для этого нужна синхронизация нумерации последовательностей), используйте один из следующих параметров:
If this is a very interactive client / server protocol, you could use scapy
to strip out the TCP contents of your stream, parse for timing and interactivity. Next use this information, open a new TCP socket to your server and deserialize that data into the new TCP socket. Parsing the original stream with scapy
could be tricky, if you run into TCP retransmissions and windowing dynamics. Writing the bytes into a new TCP socket will not require dealing with sequence numbering yourself... the OS will take care of that.
If this is a simple stream and you could do without timing (or want to insert timing information manually), you can use wireshark to get the raw bytes from a TCP steam without worrying about parsing with scapy
. After you have the raw bytes, write these bytes into a new TCP socket (accounting for interactivity as required). Writing the bytes into a new TCP socket will not require dealing with sequence numbering yourself... the OS will take care of that.
If your stream is strictly text (but not html or xml) commands, such as a telnet session, an Expect-like solution could be easier than the aforementioned parsing. In this solution, you would not open a TCP socket directly from your code, using expect to spawn
a telnet (or whatever) session and replay the text commands with send
/ expect
. Your expect library / underlying OS would take care of seq numbering.
If you're testing a web service, I suspect it would be much easier to simulate a real web client clicking through links with Selenium
or Splinter
. Your http library / underlying OS would take care of seq numbering in the new stream.
Я хотел что-то подобное, поэтому я немного поработал с scapy и нашел решение, которое сработало для меня. Моей целью было воспроизвести клиентскую часть захваченного файла pcap. Я был заинтересован в получении ответов от сервера - не обязательно с таймингами. Ниже мое решение от scapy - оно ни в коем случае не проверено и не завершено, но оно сделало то, что я хотел. Надеюсь, это хороший пример того, как воспроизвести поток TCP, используя scapy.
from scapy.all import *
import sys
#NOTE - This script assumes that there is only 1 TCP stream in the PCAP file and that
# you wish to replay the role of the client
#acks
ACK = 0x10
#client closing the connection
RSTACK = 0x14
def replay(infile, inface):
recvSeqNum = 0
first = True
targetIp = None
#send will put the correct src ip and mac in
#this assumes that the client portion of the stream is being replayed
for p in rdpcap(infile):
if 'IP' in p and 'TCP' in p:
ip = p[IP]
eth = p[Ether]
tcp = p[TCP]
if targetIp == None:
#figure out the target ip we're interested in
targetIp = ip.dst
print(targetIp)
elif ip.dst != targetIp:
# don't replay a packet that isn't to our target ip
continue
# delete checksums so that they are recalculated
del ip.chksum
del tcp.chksum
if tcp.flags == ACK or tcp.flags == RSTACK:
tcp.ack = recvSeqNum+1
if first or tcp.flags == RSTACK:
# don't expect a response from these
sendp(p, iface=inface)
first=False
continue
rcv = srp1(p, iface=inface)
recvSeqNum = rcv[TCP].seq
def printUsage(prog):
print("%s <pcapPath> <interface>" % prog)
if __name__ == "__main__":
if 3 != len(sys.argv):
printUsage(sys.argv[0])
exit(1)
replay(sys.argv[1], sys.argv[2])
iptables -A OUTPUT -p tcp --tcp-flags RST RST -o $INTERFACE -j DROP