Beispiel #1
0
 def __init__(self, template, template_directory, args, timeout=0):
     self.timeout = timeout
     self.command_responder = CommandResponder(template)
     self.server_active = True
     self.server = None
     conpot_core.get_databus().observe_value('reboot_signal', self.reboot)
     logger.info('Kamstrup protocol server initialized.')
Beispiel #2
0
 def iterate_blocks(self):
     """
     遍历所有的block,缓存执行序列,并订阅点值的写入
     """
     for slave in self.slaves:
         for block in slave.blocks:
             if block.range_type == 'COILS':
                 self.executions.append(
                     (self.read_coils, block.starting_address, block.size,
                      slave.slave_id, block.points))
                 for point in block.points:
                     if not point.readonly:
                         conpot_core.get_databus().observe_value(
                             'w ' + point.point_id,
                             lambda key: self.write_coils(key))
             elif block.range_type == 'DISCRETE_INPUTS':
                 self.executions.append(
                     (self.read_discrete_inputs, block.starting_address,
                      block.size, slave.slave_id, block.points))
             elif block.range_type == 'HOLDING_REGISTERS':
                 self.executions.append(
                     (self.read_holding_registers, block.starting_address,
                      block.size, slave.slave_id, block.points))
                 for point in block.points:
                     if not point.readonly:
                         conpot_core.get_databus().observe_value(
                             'w ' + point.point_id,
                             lambda key: self.write_registers(key))
             elif block.range_type == 'INPUT_REGISTERS':
                 self.executions.append(
                     (self.read_input_registers, block.starting_address,
                      block.size, slave.slave_id, block.points))
Beispiel #3
0
 def __init__(self, template, template_directory, args, timeout=0):
     self.timeout = timeout
     self.command_responder = CommandResponder(template)
     self.server_active = True
     self.server = None
     conpot_core.get_databus().observe_value('reboot_signal', self.reboot)
     logger.info('Kamstrup protocol server initialized.')
Beispiel #4
0
    def start(self, host, port):
        return None
        self.host = host
        self.port = port
        while 1:
            try:
                if self.closed:
                    break
                if not self.connected:
                    self.connect()

                header_1_msg = self.sock.recv(1)
                recv_msg = self.recv_msg(header_1_msg, '\x13', '\x27')
                if recv_msg:
                    header, order_no, oder_step, state, checksum = recv_msg
                    self.order_dict[order_no] = True
                    logger.info('订单已确认,订单号: ' + str(order_no))
                    conpot_core.get_databus().set_value(
                        'r ns=1;s=SSAgv.ConfirmedEvent', order_no, forced=True)
                    continue
                recv_msg = self.recv_msg(header_1_msg, '\x15', '\x27')
                if recv_msg:
                    header, order_no, oder_step, vno, checksum = recv_msg
                    if order_no in self.order_dict:
                        self.order_dict.pop(order_no)
                    logger.info('订单已完成,订单号: ' + str(order_no))
                    conpot_core.get_databus().set_value(
                        'r ns=1;s=SSAgv.CompletedEvent', order_no, forced=True)
                    self.confirm_order(order_no)
            except socket.error, e:
                logger.error('Error because: %s' % e)
                self.connected = False
Beispiel #5
0
    def start(self, host, port):
        return None
        self.host = host
        self.port = port
        while 1:
            try:
                if self.closed:
                    break
                if not self.connected:
                    self.connect()

                header_1_msg = self.sock.recv(1)
                recv_msg = self.recv_msg(header_1_msg, '\x13', '\x27')
                if recv_msg:
                    header, order_no, oder_step, state, checksum = recv_msg
                    self.order_dict[order_no] = True
                    logger.info('订单已确认,订单号: ' + str(order_no))
                    conpot_core.get_databus().set_value('r ns=1;s=SSAgv.ConfirmedEvent', order_no, forced=True)
                    continue
                recv_msg = self.recv_msg(header_1_msg, '\x15', '\x27')
                if recv_msg:
                    header, order_no, oder_step, vno, checksum = recv_msg
                    if order_no in self.order_dict:
                        self.order_dict.pop(order_no)
                    logger.info('订单已完成,订单号: ' + str(order_no))
                    conpot_core.get_databus().set_value('r ns=1;s=SSAgv.CompletedEvent', order_no, forced=True)
                    self.confirm_order(order_no)
            except socket.error, e:
                logger.error('Error because: %s' % e)
                self.connected = False
Beispiel #6
0
    def setUp(self):
        # clean up before we start...
        conpot_core.get_sessionManager().purge_sessions()
        # get the current directory

        dir_name = os.path.dirname(conpot.__file__)
        args = namedtuple('FakeArgs', 'port')
        args.port = 0
        conpot_core.get_databus().initialize(dir_name + '/templates/default/template.xml')
        self.ipmi_server = IpmiServer(dir_name + '/templates/default/ipmi/ipmi.xml',
                                      dir_name + '/templates/default/', args)
        self.greenlet = gevent.spawn(self.ipmi_server.start, '127.0.0.1', 0)
        gevent.sleep(1)
Beispiel #7
0
    def setUp(self):
        # clean up before we start...
        conpot_core.get_sessionManager().purge_sessions()
        # get the current directory

        dir_name = os.path.dirname(conpot.__file__)
        args = namedtuple('FakeArgs', 'port')
        args.port = 0
        conpot_core.get_databus().initialize(dir_name +
                                             '/templates/default/template.xml')
        self.ipmi_server = IpmiServer(
            dir_name + '/templates/default/ipmi/ipmi.xml',
            dir_name + '/templates/default/', args)
        self.greenlet = gevent.spawn(self.ipmi_server.start, '127.0.0.1', 0)
        gevent.sleep(1)
    def __init__(self, oid_mappings):
        """ initiate variables """

        self.evasion_table = {}             # stores the number of requests
        self.start_time = datetime.now()
        self.oid_map = oid_mappings         # mapping between OIDs and databus keys
        self.databus = conpot_core.get_databus()
Beispiel #9
0
    def __init__(self, template, template_directory, args):
        dom = etree.parse(template)
        databus = conpot_core.get_databus()
        self.device_name = databus.get_value(dom.xpath('//ipmi/device_info/device_name/text()')[0])
        self.host = ''
        self.port = 623
        if hasattr(args, 'port'):
            self.port = args.port
        self.sessions = dict()

        self.uuid = uuid.uuid4()
        self.kg = None

        self.authdata = collections.OrderedDict()

        lanchannel = 1
        authtype = 0b10000000
        authstatus = 0b00000100
        chancap = 0b00000010
        oemdata = (0, 0, 0, 0)
        self.authcap = struct.pack('BBBBBBBBB', 0, lanchannel, authtype, authstatus, chancap, *oemdata)

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.setblocking(1)
        self.sock.bind(('', self.port))
        self.bmc = self._configure_users(dom)
        logger.info('Conpot IPMI initialized using %s template', template)
Beispiel #10
0
 def setUp(self):
     self.databus = conpot_core.get_databus()
     self.databus.initialize('conpot/templates/default.xml')
     S7_instance = S7Server('conpot/templates/default.xml')
     self.S7_server = S7_instance.get_server('localhost', 0)
     self.S7_server.start()
     self.server_port = self.S7_server.server_port
Beispiel #11
0
    def __init__(self, template, template_directory, args):
        # Create a TCP/IP socket
        self.sock = None
        self.host = DEFAULT_HOST
        self.port = DEFAULT_PORT
        self.current_site = 1
        self.source_site = 1
        self.target_site = 1
        self.state = State.waiting
        self.load_state = LoadState.no_load
        self.errors = set()
        self.connected = False
        self.closed = False

        # 绑定callback
        conpot_core.get_databus().observe_value('w ns=1;s=KYRgv.Go', lambda key: self.bind_go(key))
    def serialize(self, message=None):
        if not message:
            message = []
        message.append(0x10)

        for register in self.registers:
            # each register must be packed: (ushort registerId, byte units, byte length, byte unknown)
            # and the following $length payload with the register value
            message.append(register.name >> 8)
            message.append(register.name & 0xff)
            message.append(register.units)
            message.append(register.length)
            # mystery byte
            message.append(register.unknown)

            low_endian_value_packed = []
            register_value = conpot_core.get_databus().get_value(register.databus_key)
            for _ in range(register.length):
                # get least significant
                low_endian_value_packed.append(register_value & 0xff)
                register_value >>= 8

            # reverse to get pack high endian
            for b in reversed(low_endian_value_packed):
                message.append(b)

        # add leading/trailing magic and escape as appropriate
        serialized_message = super(KamstrupResponseRegister, self).serialize(message)
        return bytearray(serialized_message)
Beispiel #13
0
 def __init__(self, template, template_directory, args):
     self.timeout = conpot_core.get_databus().get_value('T_0')
     self.device_data_controller = DeviceDataController(template)
     self.server_active = True
     self.server = None
     logger.info('IEC 104 Server up')
     self.template = template
Beispiel #14
0
    def setUp(self):
        self.databus = conpot_core.get_databus()

        self.iec104_inst, self.greenlet = spawn_test_server(
            IEC104_server.IEC104Server, "IEC104", "IEC104", port=2404)

        self.coa = self.iec104_inst.device_data_controller.common_address
Beispiel #15
0
 def __init__(self, template, template_directory, args):
     self.timeout = conpot_core.get_databus().get_value("T_0")
     self.device_data_controller = DeviceDataController(template)
     self.server_active = True
     self.server = None
     logger.info("IEC 104 Server up")
     self.template = template
Beispiel #16
0
    def run(self, params=None):
        databus = conpot_core.get_databus()
        cmd_ok = ""
        if params:
            params_split = params.split(" ")
            cmd_ok = "OK"

            kap_port = parse_port(params_split[0])
            if kap_port != 0:
                databus.set_value("kap_a_server_port", kap_port)

            if len(params_split) > 1:
                cha_port = parse_port(params_split[1])
                if cha_port != 0:
                    databus.set_value("channel_a_port", cha_port)

            if len(params_split) > 2:
                chb_port = parse_port(params_split[2])
                if chb_port != 0:
                    databus.set_value("channel_b_port", chb_port)

            # FIXME: how do we change the port we are connected to?
            #if len(params_split) > 3:
                #cfg_port = parse_port(params_split[3])
                #if cfg_port != 0:
                    #databus.set_value("", cfg_port)

        return self.CMD_OUTPUT.format(cmd_ok,
            databus.get_value("kap_a_server_port"),
            databus.get_value("channel_a_port"),
            databus.get_value("channel_b_port"),
            50100)  # FIXME: see above
Beispiel #17
0
 def run(self, params=None):
     databus = conpot_core.get_databus()
     output_prefix = ''
     output_postfix = ''
     if not params:
         if databus.get_value('alarm_server_status') == 'DISABLED':
             output = 'DISABLED'
         else:
             output = '{0}:{1}'.format(
                 databus.get_value('alarm_server_ip'),
                 databus.get_value('alarm_server_port'))
     else:
         output_prefix = '\r\nOK'
         # in this case the command has CRLF... really funky...
         output_postfix = '\r\n'
         databus.set_value('alarm_server_status', 'ENABLED')
         params_split = params.split(' ')
         databus.set_value('alarm_server_ip', parse_ip(params_split[0]))
         # port provided also
         if len(params_split) > 1:
             port = parse_port(params_split[1])
             if port != 0:
                 databus.set_value('alarm_server_port', port)
         output = '{0}:{1}'.format(databus.get_value('alarm_server_ip'),
                                   databus.get_value('alarm_server_port'))
     return output_prefix + self.CMD_OUTPUT.format(
         alarm_server_output=output) + output_postfix
Beispiel #18
0
 def setUp(self):
     self.databus = conpot_core.get_databus()
     self.databus.initialize('conpot/templates/default.xml')
     S7_instance = S7Server('conpot/templates/default.xml')
     self.S7_server = S7_instance.get_server('localhost', 0)
     self.S7_server.start()
     self.server_port = self.S7_server.server_port
Beispiel #19
0
    def __init__(self, template, template_directory, args):
        self.dom = etree.parse(template)
        databus = conpot_core.get_databus()
        device_info_root = self.dom.xpath('//bacnet/device_info')[0]

        name_key = databus.get_value(device_info_root.xpath('./device_name/text()')[0])
        id_key = device_info_root.xpath('./device_identifier/text()')[0]
        vendor_name_key = device_info_root.xpath('./vendor_name/text()')[0]
        vendor_identifier_key = device_info_root.xpath(
            './vendor_identifier/text()')[0]
        apdu_length_key = device_info_root.xpath(
            './max_apdu_length_accepted/text()')[0]
        segmentation_key = device_info_root.xpath(
            './segmentation_supported/text()')[0]

        # self.local_device_address = dom.xpath('./@*[name()="host" or name()="port"]')

        self.thisDevice = LocalDeviceObject(
            objectName=name_key,
            objectIdentifier=int(id_key),
            maxApduLengthAccepted=int(apdu_length_key),
            segmentationSupported=segmentation_key,
            vendorName=vendor_name_key,
            vendorIdentifier=int(vendor_identifier_key)
        )
        self.bacnet_app = None

        logger.info('Conpot Bacnet initialized using the %s template.', template)
    def handle(self, sock, address):
        session = conpot_core.get_session('kamstrup_management_protocol', address[0], address[1])
        logger.info('New connection from {0}:{1}. ({2})'.format(address[0], address[1], session.id))

        try:
            sock.send(self.banner.format(
                conpot_core.get_databus().get_value("mac_address")))

            while True:
                request = sock.recv(1024)
                if not request:
                    logger.info('Client disconnected. ({0})'.format(session.id))
                    break

                logdata = {'request': request}
                response = self.command_responder.respond(request)
                logdata['response'] = response
                logger.debug('Kamstrup management traffic from {0}: {1} ({2})'.format(address[0], logdata, session.id))
                session.add_event(logdata)
                gevent.sleep(0.25)  # TODO measure delay and/or RTT

                if response is None:
                    break
                sock.send(response)

        except socket.timeout:
            logger.debug('Socket timeout, remote: {0}. ({1})'.format(address[0], session.id))

        sock.close()
Beispiel #21
0
    def __init__(self, pdu_type=0, reserved=0, request_id=0, result_info=0, parameters='', data=''):
        self.magic = 0x32
        self.pdu_type = pdu_type
        self.reserved = reserved
        self.request_id = request_id
        # sometimes "parameters" happen to be of type int, not str
        self.param_length = len(str(parameters))
        self.data_length = len(data)
        self.result_info = result_info
        self.parameters = parameters
        self.data = data

        # param codes (http://www.bj-ig.de/147.html):
        # maps request types to methods
        self.param_mapping = {0x00: ('diagnostics', self.request_diagnostics),
                              0x04: ('read', self.request_not_implemented),
                              0x05: ('write', self.request_not_implemented),
                              0x1a: ('request_download', self.request_not_implemented),
                              0x1b: ('download_block', self.request_not_implemented),
                              0x1c: ('end_download', self.request_not_implemented),
                              0x1d: ('start_upload', self.request_not_implemented),
                              0x1e: ('upload', self.request_not_implemented),
                              0x1f: ('end_upload', self.request_not_implemented),
                              0x28: ('insert_block', self.request_not_implemented)}

        # maps valid pdu codes to name
        self.pdu_mapping = {0x01: set('request_pdu'),
                            0x02: set('known_but_unindentified_pdu'),
                            0x03: set('response_pdu'),
                            0x07: set('system_status_list')}

        self.data_bus = conpot_core.get_databus()
Beispiel #22
0
    def write_registers(self, key):
        point = self.point_dict.get(key[2:])
        if point:
            value = conpot_core.get_databus().get_value(key)
            if not point.encoding == 'none':
                endian = Endian.Auto
                if point.endian == 'Little':
                    endian = Endian.Little
                elif point.endian == 'Big':
                    endian = Endian.Big
                builder = BinaryPayloadBuilder(endian=endian)
                builder_map = {
                    'bits': builder.add_bits,
                    '8unit': builder.add_8bit_uint,
                    '16unit': builder.add_16bit_uint,
                    '32unit': builder.add_32bit_uint,
                    '64unit': builder.add_64bit_uint,
                    '8int': builder.add_8bit_int,
                    '16int': builder.add_16bit_int,
                    '32int': builder.add_32bit_int,
                    '64int': builder.add_64bit_int,
                    '32float': builder.add_32bit_float,
                    '64float': builder.add_64bit_float,
                    'string': builder.add_string
                }
                builder_map[point.encoding](value)

                payload = [unpack(endian + 'H', x)[0] for x in builder.build()]
                with lock:
                    return self.modbus_client.write_registers(
                        point.address, payload, unit=point.slave_id)
            else:
                with lock:
                    return self.modbus_client.write_registers(
                        point.address, [value], unit=point.slave_id)
Beispiel #23
0
    def setUp(self):

        # clean up before we start...
        conpot_core.get_sessionManager().purge_sessions()

        # get the conpot directory
        self.dir_name = os.path.dirname(conpot.__file__)
        self.kamstrup_management_server = KamstrupServer(
            self.dir_name + "/templates/kamstrup_382/kamstrup_meter/kamstrup_meter.xml",
            None,
            None,
        )
        self.server_greenlet = gevent.spawn(
            self.kamstrup_management_server.start, "127.0.0.1", 0
        )

        # initialize the databus
        self.databus = conpot_core.get_databus()
        self.databus.initialize(self.dir_name + "/templates/kamstrup_382/template.xml")
        gevent.sleep(1)

        self.request_parser = request_parser.KamstrupRequestParser()
        self.command_responder = CommandResponder(
            self.dir_name + "/templates/kamstrup_382/kamstrup_meter/kamstrup_meter.xml"
        )
Beispiel #24
0
    def xml_mib_config(self, dom, mibpaths, rawmibs_dirs):
        try:
            mibs = dom.xpath("//snmp/mibs/*")
            tmp_mib_dir = tempfile.mkdtemp()
            mibpaths.append(tmp_mib_dir)
            available_mibs = find_mibs(rawmibs_dirs)

            databus = conpot_core.get_databus()
            # parse mibs and oid tables
            for mib in mibs:
                mib_name = mib.attrib["name"]
                # compile the mib file if it is found and not already loaded.
                if mib_name in available_mibs and not self.cmd_responder.has_mib(mib_name):
                    compile_mib(mib_name, tmp_mib_dir)
                for symbol in mib:
                    symbol_name = symbol.attrib["name"]

                    # retrieve instance from template
                    if "instance" in symbol.attrib:
                        # convert instance to (int-)tuple
                        symbol_instance = symbol.attrib["instance"].split(".")
                        symbol_instance = tuple(map(int, symbol_instance))
                    else:
                        # use default instance (0)
                        symbol_instance = (0,)

                    # retrieve value from databus
                    value = databus.get_value(symbol.xpath("./value/text()")[0])
                    profile_map_name = symbol.xpath("./value/text()")[0]

                    # register this MIB instance to the command responder
                    self.cmd_responder.register(mib_name, symbol_name, symbol_instance, value, profile_map_name)
        finally:
            # cleanup compiled mib files
            shutil.rmtree(tmp_mib_dir)
Beispiel #25
0
    def initialize(self):
        # we need the databus initialized before we can probe values

        databus = conpot_core.get_databus()
        databus.initialized.wait()

        self.conpot_name = databus.get_value("conpot_name")
        self.gridpotmodel_file = databus.get_value("gridpotmodel_file")
        self.gridlabd_ip = databus.get_value("gridlabd_ip")
        self.gridlabd_port = databus.get_value("gridlabd_port")

        databus.set_value("gridpot_obj",
                          self)  #save the reference in the databus
        #databus.set_value('register_1', self._get_energy_in_lowres)

        request = 'http://' + self.gridlabd_ip + ':' + str(
            self.gridlabd_port) + '/output/' + self.gridpotmodel_file
        print request
        response = urllib2.urlopen(request)
        self.gridpotmodel = response.read()
        print self.gridpotmodel
        if self.gridpotmodel != None:
            self.setup_gl_objects()
        else:
            print "Could not get the .GPM model from GridLAB-D"
            exit(0)

        gevent.spawn(self.poll_gridlabd)
    def __init__(self, dbs):
        self.data_bus = conpot_core.get_databus()
        self.dbs = dbs

        self.cb_func_map = {
            0x00000001: self._construct_server_stopped_data,
            0x00000002: self._construct_server_stopped_data,
            0x00000004: self._construct_listener_cannot_start_data,
            0x00000008: self._construct_client_added_data,
            0x00000010: self._construct_client_rejected_data,
            0x00000020: self._construct_client_no_room_data,
            0x00000040: self._construct_client_exception_data,
            0x00000080: self._construct_client_disconnected_data,
            0x00000100: self._construct_client_terminated_data,
            0x00000200: self._construct_client_dropped_data,
            0x00040000: self._construct_write_db_data,
            0x00010000: self._construct_get_pdu_incoming_data,
            0x00080000: self._construct_get_pdu_size_data,
            0x00100000: self._construct_read_szl_request_data,
            0x00200000: self._construct_clock_data,
            0x00400000: self._construct_upload_data,
            0x00800000: self._construct_download_data,
            0x01000000: self._construct_directory_data,
            0x02000000: self._construct_security_data,
            0x04000000: self._construct_control_data,
            0x08000000: self._construct_group_programmer_data,
            0x10000000: self._construct_group_cyclic_data_data
        }

        self.read_cb_func_map = {
            0x00020000: self._construct_read_db_data
        }
Beispiel #27
0
    def __init__(self, template, template_directory, args):
        dom = etree.parse(template)
        databus = conpot_core.get_databus()
        self.device_name = databus.get_value(
            dom.xpath("//ipmi/device_info/device_name/text()")[0]
        )
        self.port = None
        self.sessions = dict()

        self.uuid = uuid.uuid4()
        self.kg = None
        self.sock = None
        self.authdata = collections.OrderedDict()
        lanchannel = 1
        authtype = 0b10000000
        authstatus = 0b00000100
        chancap = 0b00000010
        oemdata = (0, 0, 0, 0)
        self.authcap = struct.pack(
            "BBBBBBBBB", 0, lanchannel, authtype, authstatus, chancap, *oemdata
        )
        self.server = None
        self.session = None
        self.bmc = self._configure_users(dom)
        logger.info("Conpot IPMI initialized using %s template", template)
Beispiel #28
0
 def initialize(self):
     # we need the databus initialized before we can probe values
     
     
     databus = conpot_core.get_databus()
     databus.initialized.wait()
     
     self.conpot_name = databus.get_value("conpot_name")
     self.gridpotmodel_file = databus.get_value("gridpotmodel_file")
     self.gridlabd_ip = databus.get_value("gridlabd_ip")
     self.gridlabd_port = databus.get_value("gridlabd_port")
     
     
     databus.set_value("gridpot_obj", self)#save the reference in the databus
     #databus.set_value('register_1', self._get_energy_in_lowres)
     
     request = 'http://' + self.gridlabd_ip + ':' + str(self.gridlabd_port) + '/output/' + self.gridpotmodel_file
     print request
     response = urllib2.urlopen(request)
     self.gridpotmodel = response.read()
     print self.gridpotmodel
     if self.gridpotmodel != None:
         self.setup_gl_objects()
     else:
         print "Could not get the .GPM model from GridLAB-D"
         exit(0)
     
     gevent.spawn(self.poll_gridlabd)
    def handle(self, sock, address):
        session = conpot_core.get_session('kamstrup_management_protocol', address[0], address[1])
        logger.info('New connection from {0}:{1}. ({2})'.format(address[0], address[1], session.id))

        try:
            sock.send(self.banner.format(
                conpot_core.get_databus().get_value("mac_address")))

            while True:
                request = sock.recv(1024)
                if not request:
                    logger.info('Client disconnected. ({0})'.format(session.id))
                    break

                logdata = {'request': request}
                response = self.command_responder.respond(request)
                logdata['response'] = response
                logger.debug('Kamstrup management traffic from {0}: {1} ({2})'.format(address[0], logdata, session.id))
                session.add_event(logdata)
                gevent.sleep(0.25)  # TODO measure delay and/or RTT

                if response is None:
                    break
                sock.send(response)

        except socket.timeout:
            logger.debug('Socket timeout, remote: {0}. ({1})'.format(address[0], session.id))

        sock.close()
Beispiel #30
0
    def __init__(self, template, template_directory, args):
        dom = etree.parse(template)
        databus = conpot_core.get_databus()
        self.device_name = databus.get_value(dom.xpath('//ipmi/device_info/device_name/text()')[0])
        self.host = ''
        self.port = 623
        self.sessions = dict()

        self.uuid = uuid.uuid4()
        self.kg = None

        self.authdata = collections.OrderedDict()

        lanchannel = 1
        authtype = 0b10000000
        authstatus = 0b00000100
        chancap = 0b00000010
        oemdata = (0, 0, 0, 0)
        self.authcap = struct.pack('BBBBBBBBB', 0, lanchannel, authtype, authstatus, chancap, *oemdata)

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.setblocking(1)
        self.sock.bind(('', 623))
        self.bmc = self._configure_users(dom)
        logger.info('Conpot IPMI initialized using %s template', template)
Beispiel #31
0
    def run(self, params=None):
        output = "\r\n"
        databus = conpot_core.get_databus()

        if params is not None:
            params_split = params.split(" ")

            if len(params_split) > 0:
                # meh, actually the real value is non-existing. If you supply a larger value the smart meter
                # just overwrite memory and starts writing to the next memory location - yep, you heard it here first!
                watchdog_value = str(try_parse_uint(params_split[0], min_value=5, max_value=4294967295))
                databus.set_value('software_watchdog', watchdog_value)
                if len(params_split) > 1:
                    kap_missing = str(try_parse_uint(params_split[1], min_value=0, max_value=4294967295))
                    databus.set_value('kap_missing_warning', kap_missing)
                if len(params_split) > 2:
                    keep_alive_timer = str(try_parse_uint(params_split[2], min_value=0, max_value=4294967295))
                    databus.set_value('keep_alive_timer', keep_alive_timer)
                output = "\r\nOK" + output

        return_values = [databus.get_value('software_watchdog'),
                         databus.get_value('kap_missing_warning'),
                         databus.get_value('keep_alive_timer')]

        for i in range(0, len(return_values)):
            if return_values[i] == '0':
                return_values[i] = 'DISABLED {0}'.format(return_values[i])
            else:
                return_values[i] = 'ENABLED {0}'.format(return_values[i])

        output += SetWatchdogCommand.CMD_OUTPUT.format(return_values[0],
                                                       return_values[1],
                                                       return_values[2])

        return output.format(databus.get_value('kap_server_lookup'))
Beispiel #32
0
    def __init__(self, pdu_type=0, reserved=0, request_id=0, result_info=0, parameters='', data=''):
        self.magic = 0x32
        self.pdu_type = pdu_type
        self.reserved = reserved
        self.request_id = request_id
        self.param_length = len(parameters)
        self.data_length = len(data)
        self.result_info = result_info
        self.parameters = parameters
        self.data = data

        # param codes (http://www.bj-ig.de/147.html):
        # maps request types to methods
        self.param_mapping = {0x00: ('diagnostics', self.request_diagnostics),
                              0x04: ('read', self.request_not_implemented),
                              0x05: ('write', self.request_not_implemented),
                              0x1a: ('request_download', self.request_not_implemented),
                              0x1b: ('download_block', self.request_not_implemented),
                              0x1c: ('end_download', self.request_not_implemented),
                              0x1d: ('start_upload', self.request_not_implemented),
                              0x1e: ('upload', self.request_not_implemented),
                              0x1f: ('end_upload', self.request_not_implemented),
                              0x28: ('insert_block', self.request_not_implemented)}

        # maps valid pdu codes to name
        self.pdu_mapping = {0x01: set('request_pdu'),
                            0x02: set('know_but_unindentified_pdu'),
                            0x03: set('response_pdu'),
                            0x07: set('system_status_list')}

        self.data_bus = conpot_core.get_databus()
Beispiel #33
0
 def set_access_ip(self, number, ip_string):
     databus = conpot_core.get_databus()
     if ip_string.count('.') == 3:
         if any(x in number for x in ['1', '2', '3', '4', '5']):
             acl_number = int(number)
             final_ip = parse_ip(ip_string)
             databus.set_value('access_control_{0}'.format(acl_number), final_ip)
Beispiel #34
0
    def write_registers(self, key):
        point = self.point_dict.get(key[2:])
        if point:
            value = conpot_core.get_databus().get_value(key)
            if not point.encoding == 'none':
                endian = Endian.Auto
                if point.endian == 'Little':
                    endian = Endian.Little
                elif point.endian == 'Big':
                    endian = Endian.Big
                builder = BinaryPayloadBuilder(endian=endian)
                builder_map = {'bits': builder.add_bits,
                               '8unit': builder.add_8bit_uint,
                               '16unit': builder.add_16bit_uint,
                               '32unit': builder.add_32bit_uint,
                               '64unit': builder.add_64bit_uint,
                               '8int': builder.add_8bit_int,
                               '16int': builder.add_16bit_int,
                               '32int': builder.add_32bit_int,
                               '64int': builder.add_64bit_int,
                               '32float': builder.add_32bit_float,
                               '64float': builder.add_64bit_float,
                               'string': builder.add_string}
                builder_map[point.encoding](value)

                payload = [unpack(endian + 'H', x)[0] for x in builder.build()]
                with lock:
                    return self.modbus_client.write_registers(point.address,
                                                              payload,
                                                              unit=point.slave_id)
            else:
                with lock:
                    return self.modbus_client.write_registers(point.address, [value], unit=point.slave_id)
Beispiel #35
0
    def xml_mib_config(self):
        mibs = self.dom.xpath("//snmp/mibs/*")

        # parse mibs and oid tables
        for mib in mibs:
            mib_name = mib.attrib["name"]

            for symbol in mib:
                symbol_name = symbol.attrib["name"]

                # retrieve instance from template
                if "instance" in symbol.attrib:
                    # convert instance to (int-)tuple
                    symbol_instance = symbol.attrib["instance"].split(".")
                    symbol_instance = tuple(map(int, symbol_instance))
                else:
                    # use default instance (0)
                    symbol_instance = (0, )

                # retrieve value from databus
                value = conpot_core.get_databus().get_value(
                    symbol.xpath("./value/text()")[0])
                profile_map_name = symbol.xpath("./value/text()")[0]

                # register this MIB instance to the command responder
                self.cmd_responder.register(mib_name, symbol_name,
                                            symbol_instance, value,
                                            profile_map_name)
Beispiel #36
0
    def setUp(self):
        # clean up before we start...
        conpot_core.get_sessionManager().purge_sessions()

        # make paths platform-independent
        template = reduce(os.path.join,
                          'conpot/templates/default/template.xml'.split('/'))
        modbus_template = reduce(
            os.path.join,
            'conpot/templates/default/modbus/modbus.xml'.split('/'))

        self.databus = conpot_core.get_databus()
        self.databus.initialize(template)
        args = namedtuple('FakeArgs', 'mibpaths raw_mib')
        self.modbus = modbus_server.ModbusServer(modbus_template,
                                                 'none',
                                                 args,
                                                 timeout=2)
        self.modbus_server = StreamServer(('127.0.0.1', 0), self.modbus.handle)
        self.modbus_server.start()

        # We have to use different slave IDs under different modes. In tcp mode,
        # only 255 and 0 make sense. However, modbus_tcp.TcpMaster explicitly
        # ignores slave ID 0. Therefore we can only use 255 in tcp mode.
        self.target_slave_id = 1 if self.modbus.mode == 'serial' else 255
Beispiel #37
0
    def __init__(self, dbs, filters):
        self.data_bus = conpot_core.get_databus()
        self.dbs = dbs
        self.ignored_events = filters
        self.edc = EventDataConstructor(dbs)

        self._set_initial_values()
Beispiel #38
0
    def run(self, params=None):
        databus = conpot_core.get_databus()
        cmd_ok = ""
        if params:
            cmd_ok = "OK"
            params_split = params.split(" ")
            databus.set_value("kap_b_server_ip", parse_ip(params_split[0]))
            if len(params_split) > 1:
                port = parse_port(params_split[1])
                if port != 0:
                    databus.set_value("kap_b_server_port", params_split[1])

        if databus.get_value("kap_b_server_ip") == "0.0.0.0":
            return self.CMD_OUTPUT_SINGLE.format(
                cmd_ok,
                databus.get_value("kap_a_server_ip"),
                databus.get_value("kap_a_server_port"),
            )
        return self.CMD_OUTPUT_DOUBLE.format(
            cmd_ok,
            databus.get_value("kap_a_server_ip"),
            databus.get_value("kap_a_server_port"),
            databus.get_value("kap_b_server_ip"),
            databus.get_value("kap_b_server_port"),
        )
Beispiel #39
0
    def run(self, params=None):
        databus = conpot_core.get_databus()
        if params:
            params_split = params.split(" ")
            if len(params_split) >= 10:

                if params_split[0] == "1":
                    databus.set_value("use_dhcp", "YES")
                else:
                    databus.set_value("use_dhcp", "NO")
                    databus.set_value("ip_addr", parse_ip(params_split[1]))
                    databus.set_value("ip_subnet", parse_ip(params_split[2]))
                    databus.set_value("ip_gateway", parse_ip(params_split[3]))

                databus.set_value("nameserver_1", parse_ip(params_split[4]))
                databus.set_value("nameserver_2", parse_ip(params_split[5]))
                databus.set_value("nameserver_3", parse_ip(params_split[6]))

                if params_split[9] == "0":
                    databus.set_value("kap_a_server_ip", parse_ip(params_split[7]))
                    databus.set_value("kap_a_server_hostname", "0 - none")
                else:
                    databus.set_value("kap_a_server_hostname", params_split[9])
                    # FIXME: server IP should be resolved from the hostname
                    # using nameserver_1, nameserver_2, nameserver_3
                    databus.set_value("kap_a_server_ip", parse_ip(params_split[7]))

                device_name = params_split[8]
                if len(device_name) > 20:
                    device_name = device_name[0:20]
                databus.set_value("device_name", device_name)

        databus.set_value("reboot_signal", 1)
Beispiel #40
0
 def set_access_ip(self, number, ip_string):
     databus = conpot_core.get_databus()
     if ip_string.count(".") == 3:
         if any(x in number for x in ["1", "2", "3", "4", "5"]):
             acl_number = int(number)
             final_ip = parse_ip(ip_string)
             databus.set_value("access_control_{0}".format(acl_number), final_ip)
Beispiel #41
0
 def run(self, params=None):
     databus = conpot_core.get_databus()
     output_prefix = ""
     output_postfix = ""
     if not params:
         if databus.get_value("alarm_server_status") == "DISABLED":
             output = "DISABLED"
         else:
             output = "{0}:{1}".format(
                 databus.get_value("alarm_server_ip"),
                 databus.get_value("alarm_server_port"),
             )
     else:
         output_prefix = "\r\nOK"
         # in this case the command has CRLF... really funky...
         output_postfix = "\r\n"
         databus.set_value("alarm_server_status", "ENABLED")
         params_split = params.split(" ")
         databus.set_value("alarm_server_ip", parse_ip(params_split[0]))
         # port provided also
         if len(params_split) > 1:
             port = parse_port(params_split[1])
             if port != 0:
                 databus.set_value("alarm_server_port", port)
         output = "{0}:{1}".format(
             databus.get_value("alarm_server_ip"),
             databus.get_value("alarm_server_port"),
         )
     return (
         output_prefix
         + self.CMD_OUTPUT.format(alarm_server_output=output)
         + output_postfix
     )
Beispiel #42
0
    def __init__(self, oid_mappings):
        """ initiate variables """

        self.evasion_table = {}  # stores the number of requests
        self.start_time = datetime.now()
        self.oid_map = oid_mappings  # mapping between OIDs and databus keys
        self.databus = conpot_core.get_databus()
Beispiel #43
0
    def run(self, params=None):
        databus = conpot_core.get_databus()
        if params:
            params_split = params.split(" ")
            if len(params_split) >= 10:

                if params_split[0] == "1":
                    databus.set_value("use_dhcp", "YES")
                else:
                    databus.set_value("use_dhcp", "NO")
                    databus.set_value("ip_addr", parse_ip(params_split[1]))
                    databus.set_value("ip_subnet", parse_ip(params_split[2]))
                    databus.set_value("ip_gateway", parse_ip(params_split[3]))

                databus.set_value("nameserver_1", parse_ip(params_split[4]))
                databus.set_value("nameserver_2", parse_ip(params_split[5]))
                databus.set_value("nameserver_3", parse_ip(params_split[6]))

                if params_split[9] == "0":
                    databus.set_value("kap_a_server_ip", parse_ip(params_split[7]))
                    databus.set_value("kap_a_server_hostname", "0 - none")
                else:
                    databus.set_value("kap_a_server_hostname", params_split[9])
                    # FIXME: server IP should be resolved from the hostname
                    # using nameserver_1, nameserver_2, nameserver_3
                    databus.set_value("kap_a_server_ip", parse_ip(params_split[7]))

                device_name = params_split[8]
                if len(device_name) > 20:
                    device_name = device_name[0:20]
                databus.set_value("device_name", device_name)

        databus.set_value("reboot_signal", 1)
Beispiel #44
0
    def __init__(self, template, template_directory, args):
        self.dom = etree.parse(template)
        databus = conpot_core.get_databus()
        device_info_root = self.dom.xpath('//bacnet/device_info')[0]

        name_key = databus.get_value(
            device_info_root.xpath('./device_name/text()')[0])
        id_key = device_info_root.xpath('./device_identifier/text()')[0]
        vendor_name_key = device_info_root.xpath('./vendor_name/text()')[0]
        vendor_identifier_key = device_info_root.xpath(
            './vendor_identifier/text()')[0]
        apdu_length_key = device_info_root.xpath(
            './max_apdu_length_accepted/text()')[0]
        segmentation_key = device_info_root.xpath(
            './segmentation_supported/text()')[0]

        # self.local_device_address = dom.xpath('./@*[name()="host" or name()="port"]')

        self.thisDevice = LocalDeviceObject(
            objectName=name_key,
            objectIdentifier=int(id_key),
            maxApduLengthAccepted=int(apdu_length_key),
            segmentationSupported=segmentation_key,
            vendorName=vendor_name_key,
            vendorIdentifier=int(vendor_identifier_key))
        self.bacnet_app = None

        logger.info('Conpot Bacnet initialized using the %s template.',
                    template)
Beispiel #45
0
    def run(self, params=None):
        databus = conpot_core.get_databus()
        cmd_ok = ""
        if params:
            params_split = params.split(" ")
            cmd_ok = "OK"

            kap_port = parse_port(params_split[0])
            if kap_port != 0:
                databus.set_value("kap_a_server_port", kap_port)

            if len(params_split) > 1:
                cha_port = parse_port(params_split[1])
                if cha_port != 0:
                    databus.set_value("channel_a_port", cha_port)

            if len(params_split) > 2:
                chb_port = parse_port(params_split[2])
                if chb_port != 0:
                    databus.set_value("channel_b_port", chb_port)

            # FIXME: how do we change the port we are connected to?
            # if len(params_split) > 3:
            # cfg_port = parse_port(params_split[3])
            # if cfg_port != 0:
            # databus.set_value("", cfg_port)

        return self.CMD_OUTPUT.format(
            cmd_ok,
            databus.get_value("kap_a_server_port"),
            databus.get_value("channel_a_port"),
            databus.get_value("channel_b_port"),
            50100,
        )  # FIXME: see above
Beispiel #46
0
    def __init__(self, template, template_directory, args):
        # Create a TCP/IP socket
        self.sock = None
        self.host = DEFAULT_HOST
        self.port = DEFAULT_PORT
        self.current_site = 1
        self.source_site = 1
        self.target_site = 1
        self.state = State.waiting
        self.load_state = LoadState.no_load
        self.errors = set()
        self.connected = False
        self.closed = False

        # 绑定callback
        conpot_core.get_databus().observe_value('w ns=1;s=KYRgv.Go',
                                                lambda key: self.bind_go(key))
 def setUp(self):
     self.tmp_dir = tempfile.mkdtemp()
     self.host = '127.0.0.1'
     databus = conpot_core.get_databus()
     databus.initialize('conpot/templates/default.xml')
     self.snmp_server = SNMPServer(self.host, 0, 'conpot/templates/default.xml', [self.tmp_dir], [self.tmp_dir])
     self.port = self.snmp_server.get_port()
     self.server_greenlet = gevent.spawn(self.snmp_server.start)
Beispiel #48
0
 def bind_send_order(self, key):
     order_no, source_site, target_site = conpot_core.get_databus().get_value(key)
     try:
         return self.send_order(order_no, source_site, target_site)
     except TimeoutError:
         if order_no in self.order_dict:
             self.order_dict.pop(order_no)
         return False
Beispiel #49
0
 def __init__(self, data):
     self.databus = conpot_core.get_databus()
     if type(data) == bytes:
         data = data.decode()
     self.data = data
     HTMLParser.__init__(self)
     self.payload = self.data
     self.feed(self.data)
 def __init__(self, databus_key, starting_address, size):
     """
     Constructor: defines the address range and creates the array of values
     """
     self.starting_address = starting_address
     # self._data = [0]*size
     self.databus_key = databus_key
     self.size = len(conpot_core.get_databus().get_value(self.databus_key))
Beispiel #51
0
 def __init__(self, data):
     self.databus = conpot_core.get_databus()
     if type(data) == bytes:
         data = data.decode()
     self.data = data
     HTMLParser.__init__(self)
     self.payload = self.data
     self.feed(self.data)
Beispiel #52
0
 def __init__(self, device_data_controller, sock, address, session_id):
     self.sock = sock
     self.address = address
     self.session_id = session_id
     self.T_1 = conpot_core.get_databus().get_value('T_1')
     self.timeout_t1 = gevent.Timeout(self.T_1, gevent.Timeout)
     self.T_2 = conpot_core.get_databus().get_value('T_2')
     self.w = conpot_core.get_databus().get_value('w')
     self.device_data_controller = device_data_controller
     self.ssn = 0
     self.rsn = 0
     self.ack = 0
     self.allow_DT = False
     self.t2_caller = None
     self.telegram_count = 0
     self.sentmsgs = list()
     self.send_buffer = list()
Beispiel #53
0
 def setUp(self):
     self.databus = conpot_core.get_databus()
     self.databus.initialize('conpot/templates/default/template.xml')
     args = namedtuple('FakeArgs', '')
     self.s7_instance = S7Server('conpot/templates/default/s7comm/s7comm.xml', 'none', args)
     gevent.spawn(self.s7_instance.start, '127.0.0.1', 0)
     gevent.sleep(0.5)
     self.server_port = self.s7_instance.server.server_port
    def setUp(self):

        # clean up before we start...
        conpot_core.get_sessionManager().purge_sessions()

        self.databus = conpot_core.get_databus()
        self.databus.initialize('conpot/templates/kamstrup_382/template.xml')
        self.request_parser = request_parser.KamstrupRequestParser()
        self.command_responder = CommandResponder('conpot/templates/kamstrup_382/kamstrup_meter/kamstrup_meter.xml')
Beispiel #55
0
    def unpack_state(self, msg_bytes):
        if len(msg_bytes) != 13:    # 未正确返回数据,直接返回
            return
        self.errors.clear()   # 先清除之前的错误信息
        # 错误信息
        if msg_bytes[4] & SysState.sys_error.value == SysState.sys_error.value:
            self.errors.add(ERRORS[SysState.sys_error.value])
        if msg_bytes[4] & RobotState.robot_error.value == RobotState.robot_error.value:
            self.errors.add(ERRORS[RobotState.robot_error.value])
        if msg_bytes[4] & RobotState.robot_alarm.value == RobotState.robot_alarm.value:
            self.errors.add(ERRORS[RobotState.robot_alarm.value])
        # print 'errors:', self.errors

        if len(self.errors):
            self.hasErrors = True
        else:
            self.hasErrors = False

        conpot_core.get_databus().set_value('r ns=1;s=KYWeldRobot.hasErrors', self.hasErrors)

        # 伺服驱动ON,操作可进行
        if msg_bytes[3] & DriveState.servo.value == DriveState.servo.value:
            self.servo_ON = True
        else:
            self.servo_ON = False
        # print 'servo ON? : ', self.servo_ON

        conpot_core.get_databus().set_value('r ns=1;s=KYWeldRobot.servo_ON', self.servo_ON)

        # 焊接机器人工作状态(手动示教/自动再生)
        if msg_bytes[4] & WorkState.teaching.value == WorkState.teaching.value:
            self.state = WorkState.teaching
        elif msg_bytes[4] & WorkState.repeating.value == WorkState.repeating.value:
            self.state = WorkState.repeating
            TIME_REPEAT.append(time.time())
            if msg_bytes[4] & WorkState.repeat_halting.value == WorkState.repeat_halting.value:
                self.state = WorkState.repeat_halting
                TIME_HALT_OR_END.append(time.time())
        elif msg_bytes[4] & WorkState.repeating_end_normally.value == WorkState.repeating_end_normally.value:
            self.state = WorkState.repeating_end_normally
            TIME_HALT_OR_END.append(time.time())
        # print 'KYWeldRobot working state:', self.state.name

        conpot_core.get_databus().set_value('r ns=1;s=KYWeldRobot.State', self.state.name)

        # 是否正在进行焊接
        if msg_bytes[4] & WorkState.electric_arc.value == WorkState.electric_arc.value:
            self.isWelding = True
        else:
            self.isWelding = False
        # print 'Welding? : ', self.isWelding

        conpot_core.get_databus().set_value('r ns=1;s=KYWeldRobot.isWelding', self.isWelding)
    def setUp(self):

        # clean up before we start...
        conpot_core.get_sessionManager().purge_sessions()

        self.databus = conpot_core.get_databus()
        self.databus.initialize('conpot/templates/default.xml')
        modbus = modbus_server.ModbusServer('conpot/templates/default.xml', timeout=2)
        self.modbus_server = StreamServer(('127.0.0.1', 0), modbus.handle)
        self.modbus_server.start()
Beispiel #57
0
 def test_snmp_set(self):
     """
     Objective: Test if we can set data via snmp_set
     """
     client = snmp_client.SNMPClient(self.host, self.port)
     # syslocation
     oid = ((1, 3, 6, 1, 2, 1, 1, 6, 0), rfc1902.OctetString('TESTVALUE'))
     client.set_command(oid, callback=self.mock_callback)
     databus = conpot_core.get_databus()
     self.assertEqual('TESTVALUE', databus.get_value('sysLocation'))
Beispiel #58
0
    def setUp(self):

        # clean up before we start...
        conpot_core.get_sessionManager().purge_sessions()

        self.databus = conpot_core.get_databus()
        self.databus.initialize('conpot/templates/default/template.xml')
        args = namedtuple('FakeArgs', 'mibpaths raw_mib')
        modbus = modbus_server.ModbusServer('conpot/templates/default/modbus/modbus.xml', 'none', args, timeout=2)
        self.modbus_server = StreamServer(('127.0.0.1', 0), modbus.handle)
        self.modbus_server.start()
Beispiel #59
0
    def setUp(self):
        self.dir_name = os.path.dirname(conpot.__file__)
        template = self.dir_name + '/templates/IEC104/template.xml'
        iec104_template = self.dir_name + '/templates/IEC104/IEC104/IEC104.xml'

        self.databus = conpot_core.get_databus()
        self.databus.initialize(template)
        args = namedtuple('FakeArgs', 'mibpaths raw_mib')
        self.iec104_inst = IEC104_server.IEC104Server(iec104_template, 'none', args)
        self.iec104_server = StreamServer(('127.0.0.1', 2404), self.iec104_inst.handle)
        self.iec104_server.start()