# This script is developed strictly for educational purpose.
# It demonstrates how ModbusTCP transmits unencrypted packets over the network.
# The purpose of this demonstration is to simulate and analyze attacks,
# such as Denial of Service (DoS) and sniffing, in a controlled environment (GNS3 Virtual Lab).
# The code should not be used for any malicious activities or unauthorized testing.

from pymodbus.server.sync import ModbusTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock, ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusSocketFramer
import logging

# Configure logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)

def run_async_server():
    nreg = 200
    # initialize data store
    store = ModbusSlaveContext(
        di=ModbusSequentialDataBlock(0, [15]*nreg),
        co=ModbusSequentialDataBlock(0, [16]*nreg),
        hr=ModbusSequentialDataBlock(0, [17]*nreg),
        ir=ModbusSequentialDataBlock(0, [18]*nreg))
    context = ModbusServerContext(slaves=store, single=True)

    # initialize the server information
    identity = ModbusDeviceIdentification()
    identity.VendorName = 'APMonitor'
    identity.ProductCode = 'APM'
    identity.VendorUrl = 'https://apmonitor.com'
    identity.ProductName = 'Modbus Server'
    identity.ModelName = 'Modbus Server'
    identity.MajorMinorRevision = '3.0.2'

    # TCP Server
    server = ModbusTcpServer(context, identity=identity, address=("192.168.122.109", 502))
    server.serve_forever()

if __name__ == "__main__":
    print('Modbus server started on 192.168.122.109 port 502')
    run_async_server()
