Question

I'm running the code example below against a remote PLC with Wireshark running. Why do I only get the query (I should get the response too)? It seems that the PLC sends the response, since the output of Scapy says Received 1 packets, got 1 answers, remaining 0 packets.

Any ideas of why is this happening?

I also performed the sniffing using the sniff() function from Scapy but the result is the same (only get the query).

#! /usr/bin/env python

import logging
logging.getLogger("scapy").setLevel(1)

from scapy import *
from modLib import *

# IP for all transmissions
ip = IP(dst="192.168.10.131")

# Sets up the session with a TCP three-way handshake
# Send the syn, receive the syn/ack
tcp = TCP( flags = 'S', window = 65535, sport = RandShort(), dport = 502, options = [('MSS', 1360 ), ('NOP', 1), ('NOP', 1), ('SAckOK', '')])
synAck = sr1 ( ip / tcp )

# Send the ack
tcp.flags = 'A'
tcp.sport = synAck[TCP].dport
tcp.seq = synAck[TCP].ack
tcp.ack = synAck[TCP].seq + 1
tcp.options = ''
send( ip / tcp )

# Creates and sends the Modbus Read Holding Registers command packet
# Send the ack/push i.e. the request, receive the data i.e. the response
tcp.flags = 'AP'
adu = ModbusADU()
pdu = ModbusPDU03()
adu = adu / pdu
tcp = tcp / adu
data = sr1(( ip / tcp ), timeout = 2)
data.show()

# Acknowledges the response
# Ack the data response
# TODO: note, the 17 below should be replaced with a read packet length method...
tcp.flags = 'A'
tcp.seq = data[TCP].ack
tcp.ack = data[TCP] + 17
tcp.payload = ''
finAck = sr1( ip / tcp )
Was it helpful?

Solution

First, you have a bug in your code (which is present in the original version http://www.digitalbond.com/scadapedia/security-controls/scapy-modbus-extensions/), you need to add .seq there: tcp.ack = data[TCP].seq + 17.

As said in the comment, you could write tcp.ack = data[TCP].seq + len(data[TCP].payload).

Anyway it's generally useless to do the TCP stack's work for the kind of things you try to do.

I would do something like that:

from scapy import *
from modLib import *
import socket

sock = socket.socket()
sock.connect(("192.168.10.131", 502))
s = StreamSocket(sock, basecls=ModbusADU)

ans, unans = s.sr(ModbusADU()/ModbusPDU03())
ans.show()

Does this work better?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top