Пример #1
0
    def test_whoIs(self):
        request = WhoIsRequest(
            deviceInstanceRangeLowLimit=500, deviceInstanceRangeHighLimit=50000
        )
        apdu = APDU()
        request.encode(apdu)
        pdu = PDU()
        apdu.encode(pdu)
        buf_size = 1024
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.sendto(pdu.pduData, self.address)
        data = s.recvfrom(buf_size)
        s.close()
        received_data = data[0]

        expected = IAmRequest()
        expected.pduDestination = GlobalBroadcast()
        expected.iAmDeviceIdentifier = 36113
        expected.maxAPDULengthAccepted = 1024
        expected.segmentationSupported = "segmentedBoth"
        expected.vendorID = 15

        exp_apdu = APDU()
        expected.encode(exp_apdu)
        exp_pdu = PDU()
        exp_apdu.encode(exp_pdu)

        self.assertEqual(exp_pdu.pduData, received_data)
Пример #2
0
    def test_read_foreign_device_table_ack(self):
        """Test the ReadForeignDeviceTableAck encoding and decoding."""
        if _debug: TestAnnexJCodec._debug("test_read_foreign_device_table_ack")

        # read returns an empty table
        pdu_bytes = xtob('81.07.0004')

        self.request(ReadForeignDeviceTableAck([]))
        self.indication(pduData=pdu_bytes)

        self.response(PDU(pdu_bytes))
        self.confirmation(ReadForeignDeviceTableAck, bvlciFDT=[])

        # read returns a table with one entry
        fdte = FDTEntry()
        fdte.fdAddress = Address("192.168.0.10")
        fdte.fdTTL = 30
        fdte.fdRemain = 15
        pdu_bytes = xtob('81.07.000e'  # bvlci
                         'c0.a8.00.0a.ba.c0'  # address
                         '001e.000f'  # ttl and remaining
                         )

        self.request(ReadForeignDeviceTableAck([fdte]))
        self.indication(pduData=pdu_bytes)

        self.response(PDU(pdu_bytes))
        self.confirmation(ReadForeignDeviceTableAck, bvlciFDT=[fdte])
Пример #3
0
    def test_write_broadcast_distribution_table(self):
        """Test the WriteBroadcastDistributionTable encoding and decoding."""
        if _debug:
            TestAnnexJCodec._debug("test_write_broadcast_distribution_table")

        # write an empty table
        pdu_bytes = xtob('81.01.0004')

        self.request(WriteBroadcastDistributionTable([]))
        self.indication(pduData=pdu_bytes)

        self.response(PDU(pdu_bytes))
        self.confirmation(WriteBroadcastDistributionTable, bvlciBDT=[])

        # write a table with an element
        addr = Address('192.168.0.254/24')
        pdu_bytes = xtob('81.01.000e'
                         'c0.a8.00.fe.ba.c0 ff.ff.ff.00'  # address and mask
                         )

        self.request(WriteBroadcastDistributionTable([addr]))
        self.indication(pduData=pdu_bytes)

        self.response(PDU(pdu_bytes))
        self.confirmation(WriteBroadcastDistributionTable, bvlciBDT=[addr])
Пример #4
0
    def test_whoHas(self):
        request_object = WhoHasObject()
        request_object.objectIdentifier = ("binaryInput", 12)
        request = WhoHasRequest(object=request_object)
        apdu = APDU()
        request.encode(apdu)
        pdu = PDU()
        apdu.encode(pdu)
        buf_size = 1024
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.sendto(pdu.pduData, self.address)
        data = s.recvfrom(buf_size)
        s.close()
        received_data = data[0]

        expected = IHaveRequest()
        expected.pduDestination = GlobalBroadcast()
        expected.deviceIdentifier = 36113
        expected.objectIdentifier = 12
        expected.objectName = "BI 01"

        exp_apdu = APDU()
        expected.encode(exp_apdu)
        exp_pdu = PDU()
        exp_apdu.encode(exp_pdu)
        self.assertEqual(exp_pdu.pduData, received_data)
Пример #5
0
    def test_readProperty(self):
        request = ReadPropertyRequest(
            objectIdentifier=("analogInput", 14), propertyIdentifier=85
        )
        request.apduMaxResp = 1024
        request.apduInvokeID = 101
        apdu = APDU()
        request.encode(apdu)
        pdu = PDU()
        apdu.encode(pdu)
        buf_size = 1024
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.sendto(pdu.pduData, self.address)
        data = s.recvfrom(buf_size)
        s.close()
        received_data = data[0]

        expected = ReadPropertyACK()
        expected.pduDestination = GlobalBroadcast()
        expected.apduInvokeID = 101
        expected.objectIdentifier = 14
        expected.objectName = "AI 01"
        expected.propertyIdentifier = 85
        expected.propertyValue = Any(Real(68.0))

        exp_apdu = APDU()
        expected.encode(exp_apdu)
        exp_pdu = PDU()
        exp_apdu.encode(exp_pdu)

        self.assertEqual(exp_pdu.pduData, received_data)
Пример #6
0
 def handle(self, data, address):
     session = conpot_core.get_session(
         "bacnet",
         address[0],
         address[1],
         get_interface_ip(address[0]),
         self.server.server_port,
     )
     logger.info("New Bacnet connection from %s:%d. (%s)", address[0],
                 address[1], session.id)
     session.add_event({"type": "NEW_CONNECTION"})
     # I'm not sure if gevent DatagramServer handles issues where the
     # received data is over the MTU -> fragmentation
     if data:
         pdu = PDU()
         pdu.pduData = bytearray(data)
         apdu = APDU()
         try:
             apdu.decode(pdu)
         except DecodingError:
             logger.warning("DecodingError - PDU: {}".format(pdu))
             return
         self.bacnet_app.indication(apdu, address, self.thisDevice)
         # send an appropriate response from BACnet app to the attacker
         self.bacnet_app.response(self.bacnet_app._response, address)
     logger.info("Bacnet client disconnected %s:%d. (%s)", address[0],
                 address[1], session.id)
Пример #7
0
    def test_send_receive(self):
        """Test that a node can send a message to another node and use
        events to continue with the messages.
        """
        if _debug: TestVLAN._debug("test_send_receive")

        # two element network
        tnet = TNetwork(2)
        tnode1, tnode2 = tnet.state_machines

        # make a PDU from node 1 to node 2
        dead_pdu = PDU(b'dead', source=1, destination=2)
        if _debug: TestVLAN._debug("    - dead_pdu: %r", dead_pdu)

        # make a PDU from node 1 to node 2
        beef_pdu = PDU(b'beef', source=1, destination=2)
        if _debug: TestVLAN._debug("    - beef_pdu: %r", beef_pdu)

        # node 1 sends dead_pdu, waits for event, sends beef_pdu
        tnode1.start_state \
            .send(dead_pdu).wait_event('e') \
            .send(beef_pdu).success()

        # node 2 receives dead_pdu, sets event, waits for beef_pdu
        tnode2.start_state \
            .receive(PDU, pduData=b'dead').set_event('e') \
            .receive(PDU, pduData=b'beef').success()

        # run the group
        tnet.run()
Пример #8
0
    def test_read_broadcast_distribution_table_ack(self):
        """Test the ReadBroadcastDistributionTableAck encoding and decoding."""
        if _debug:
            TestAnnexJCodec._debug(
                "test_read_broadcast_distribution_table_ack")

        # read returns an empty table
        pdu_bytes = xtob('81.03.0004')

        self.request(ReadBroadcastDistributionTableAck([]))
        self.indication(pduData=pdu_bytes)

        self.response(PDU(pdu_bytes))
        self.confirmation(ReadBroadcastDistributionTableAck, bvlciBDT=[])

        # read returns a table with an element
        addr = Address('192.168.0.254/24')
        pdu_bytes = xtob('81.03.000e'  # bvlci
                         'c0.a8.00.fe.ba.c0 ff.ff.ff.00'  # address and mask
                         )

        self.request(ReadBroadcastDistributionTableAck([addr]))
        self.indication(pduData=pdu_bytes)

        self.response(PDU(pdu_bytes))
        self.confirmation(ReadBroadcastDistributionTableAck, bvlciBDT=[addr])
    def handle(self, data, address):
        session = conpot_core.get_session('bacnet', address[0], address[1])
        logger.info('New Bacnet connection from %s:%d. (%s)', address[0],
                    address[1], session.id)
        session.add_event({'type': 'NEW_CONNECTION'})
        # I'm not sure if gevent DatagramServer handles issues where the
        # received data is over the MTU -> fragmentation
        if data:
            pdu = PDU()
            pdu.pduData = data
            apdu = APDU()
            npdu = NPDU()
            bvlpdu = BVLPDU()
            try:
                bvlpdu.decode(pdu)
                npdu.decode(bvlpdu)
                apdu.decode(npdu)

            except DecodingError as e:
                logger.error("DecodingError: %s", e)
                logger.error("PDU: " + format(pdu))
                return
            self.bacnet_app.indication(apdu, address, self.thisDevice)
            self.bacnet_app.response(self.bacnet_app._response, npdu, bvlpdu,
                                     address)
        logger.info('Bacnet client disconnected %s:%d. (%s)', address[0],
                    address[1], session.id)
    def test_whoHas(self):
        request_object = WhoHasObject()
        request_object.objectIdentifier = ('binaryInput', 12)
        request = WhoHasRequest(object=request_object)
        apdu = APDU()
        request.encode(apdu)
        pdu = PDU()
        apdu.encode(pdu)
        buf_size = 1024
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.sendto(pdu.pduData, ('127.0.0.1', self.bacnet_server.server.server_port))
        data = s.recvfrom(buf_size)

        received_data = data[0]

        expected = IHaveRequest()
        expected.pduDestination = GlobalBroadcast()
        expected.deviceIdentifier = 36113
        expected.objectIdentifier = 12
        expected.objectName = 'BI 01'

        exp_apdu = APDU()
        expected.encode(exp_apdu)
        exp_pdu = PDU()
        exp_apdu.encode(exp_pdu)

        self.assertEquals(exp_pdu.pduData, received_data)
Пример #11
0
    def on_message(self, client, userdata, msg):
        """Callback for when a PUBLISH message is received from the server.
        """
        if _debug:
            MQTTClient._debug("on_message %r, %s", msg.topic, btox(msg.payload, "."))

        # wrap it up and decode it
        pdu = PDU(msg.payload)
        bvlpdu = BVLPDU()
        bvlpdu.decode(pdu)
        if _debug:
            MQTTClient._debug("    - bvlpdu: %r", bvlpdu)

        # decode the next layer
        xpdu = bvl_pdu_types[bvlpdu.bvlciFunction]()
        xpdu.decode(bvlpdu)
        if _debug:
            MQTTClient._debug("    - xpdu: %r", xpdu)

        if isinstance(xpdu, OriginalUnicastNPDU):
            # from ourselves?
            if xpdu.bvlciAddress == self.client:
                if _debug:
                    MQTTClient._debug("    - from ourselves")
                return

            # build a PDU with the client address
            ypdu = PDU(
                xpdu.pduData,
                source=xpdu.bvlciAddress,
                destination=self.client,
                user_data=xpdu.pduUserData,
            )
            if _debug:
                MQTTClient._debug("    - upstream ypdu: %r", ypdu)

            deferred(self.response, ypdu)

        elif isinstance(xpdu, OriginalBroadcastNPDU):
            # from ourselves?
            if xpdu.bvlciAddress == self.client:
                if _debug:
                    MQTTClient._debug("    - from ourselves")
                return

            # build a PDU with a local broadcast address
            ypdu = PDU(
                xpdu.pduData,
                source=xpdu.bvlciAddress,
                destination=LocalBroadcast(),
                user_data=xpdu.pduUserData,
            )
            if _debug:
                MQTTClient._debug("    - upstream ypdu: %r", ypdu)

            deferred(self.response, ypdu)
Пример #12
0
    def test_send_receive(self):
        """Test that a node can send a message to another node on
        a different network.
        """
        if _debug: TestRouter._debug("test_send_receive")

        # unpack the state machines
        csm_10_2, csm_10_3, csm_20_2, csm_20_3 = self.smg.state_machines

        # make a PDU from network 10 node 1 to network 20 node 2
        pdu = PDU(
            b'data',
            source=('192.168.10.2', 47808),
            destination=('192.168.20.3', 47808),
        )
        if _debug: TestVLAN._debug("    - pdu: %r", pdu)

        # node 1 sends the pdu, mode 2 gets it
        csm_10_2.start_state.send(pdu).success()
        csm_20_3.start_state.receive(
            PDU,
            pduSource=('192.168.10.2', 47808),
        ).success()

        # other nodes get nothing
        csm_10_3.start_state.timeout(1).success()
        csm_20_2.start_state.timeout(1).success()
Пример #13
0
    def test_promiscuous_pass(self):
        """Test 'promiscuous mode' of a node which allows it to receive every
        packet sent on the network.  This is like the network is a hub, or
        the node is connected to a 'monitor' port on a managed switch.
        """
        if _debug: TestVLAN._debug("test_promiscuous_pass")

        # three element network
        tnet = TNetwork(3, "192.168.6.{}/24")
        tnode1, tnode2, tnode3 = tnet.state_machines

        # reach into the network and enable promiscuous mode
        tnet.vlan.nodes[2].promiscuous = True

        # make a PDU from node 1 to node 2
        pdu = PDU(
            b'data',
            source=('192.168.6.1', 47808),
            destination=('192.168.6.2', 47808),
        )

        # node 1 sends the pdu to node 2, node 3 also gets a copy
        tnode1.start_state.send(pdu).success()
        tnode2.start_state.receive(
            PDU,
            pduSource=('192.168.6.1', 47808),
        ).success()
        tnode3.start_state.receive(
            PDU,
            pduDestination=('192.168.6.2', 47808),
        ).success()

        # run the group
        tnet.run()
Пример #14
0
    def test_spoof_pass(self):
        """Test allowing a node to send out packets with a source address
        other than its own, see also test_spoof_fail().
        """
        if _debug: TestVLAN._debug("test_spoof_pass")

        # one node network
        tnet = TNetwork(1, "192.168.5.{}/24")
        tnode1, = tnet.state_machines

        # reach into the network and enable spoofing for the node
        tnet.vlan.nodes[0].spoofing = True

        # make a unicast PDU from a fictitious node
        pdu = PDU(
            b'data',
            source=('192.168.5.3', 47808),
            destination=('192.168.5.1', 47808),
        )

        # node 1 sends the pdu, but gets it back as if it was from node 3
        tnode1.start_state.send(pdu).receive(
            PDU,
            pduSource=('192.168.5.3', 47808),
        ).success()

        # run the group
        tnet.run()
Пример #15
0
    def test_broadcast(self):
        """Test that a node can send out a 'local broadcast' message which will
        be received by every other node.
        """
        if _debug: TestVLAN._debug("test_broadcast")

        # three element network
        tnet = TNetwork(3, "192.168.3.{}/24")
        tnode1, tnode2, tnode3 = tnet.state_machines

        # make a broadcast PDU
        pdu = PDU(
            b'data',
            source=('192.168.3.1', 47808),
            destination=('192.168.3.255', 47808),
        )
        if _debug: TestVLAN._debug("    - pdu: %r", pdu)

        # node 1 sends the pdu, node 2 and 3 each get it
        tnode1.start_state.send(pdu).success()
        tnode2.start_state.receive(
            PDU,
            pduSource=('192.168.3.1', 47808),
        ).success()
        tnode3.start_state.receive(PDU,
                                   pduSource=('192.168.3.1', 47808)).success()

        # run the group
        tnet.run()
Пример #16
0
    def test_remote_broadcast(self):
        """Test that a node can send a message to all of the other nodes on
        a different network.
        """
        if _debug: TestRouter._debug("test_remote_broadcast")

        # unpack the state machines
        csm_10_2, csm_10_3, csm_20_2, csm_20_3 = self.smg.state_machines

        # make a PDU from network 10 node 1 to network 20 node 2
        pdu = PDU(
            b'data',
            source=('192.168.10.2', 47808),
            destination=('192.168.20.255', 47808),
        )
        if _debug: TestVLAN._debug("    - pdu: %r", pdu)

        # node 10-2 sends the pdu, node 10-3 gets nothing, nodes 20-2 and 20-3 get it
        csm_10_2.start_state.send(pdu).success()
        csm_10_3.start_state.timeout(1).success()
        csm_20_2.start_state.receive(
            PDU,
            pduSource=('192.168.10.2', 47808),
        ).success()
        csm_20_3.start_state.receive(
            PDU,
            pduSource=('192.168.10.2', 47808),
        ).success()
Пример #17
0
    def indication(self, pdu):
        if _debug: MiddleMan._debug('indication %r', pdu)

        # empty downstream packets mean EOF
        if not pdu.pduData:
            stop()
            return

        # decode the line and trim off the eol
        line = str(pdu.pduData.decode('utf-8'))[:-1]
        if _debug: MiddleMan._debug('    - line: %r', line)

        line_parts = line.split(' ', 1)
        if _debug: MiddleMan._debug('    - line_parts: %r', line_parts)
        if len(line_parts) != 2:
            sys.stderr.write("err: invalid line: %r\n" % (line, ))
            return

        addr, msg = line_parts

        # check the address
        dest = Address(addr)
        if _debug: MiddleMan._debug('    - dest: %r', dest)

        # send it along
        try:
            self.request(PDU(msg.encode('utf_8'), destination=dest))
        except Exception as err:
            sys.stderr.write("err: %r\n" % (err, ))
            return
Пример #18
0
 def response(self, response_apdu, address):
     if response_apdu is None:
         return
     apdu = APDU()
     response_apdu.encode(apdu)
     pdu = PDU()
     apdu.encode(pdu)
     if isinstance(response_apdu, RejectPDU) or isinstance(
             response_apdu, ErrorPDU):
         self.datagram_server.sendto(pdu.pduData, address)
     else:
         apdu_type = apdu_types.get(response_apdu.apduType)
         if pdu.pduDestination == "*:*":
             # broadcast
             # sendto operates under lock
             self.datagram_server.sendto(pdu.pduData, ("", address[1]))
         else:
             # sendto operates under lock
             self.datagram_server.sendto(pdu.pduData, address)
         logger.info(
             "Bacnet response sent to %s (%s:%s)",
             response_apdu.pduDestination,
             apdu_type.__name__,
             self._response_service,
         )
Пример #19
0
    def test_send_receive(self):
        """Test that a node can send a message to another node.
        """
        if _debug: TestVLAN._debug("test_send_receive")

        # two element network
        tnet = TNetwork(2, "192.168.2.{}/24")
        tnode1, tnode2 = tnet.state_machines

        # make a PDU from node 1 to node 2
        pdu = PDU(
            b'data',
            source=('192.168.2.1', 47808),
            destination=('192.168.2.2', 47808),
        )
        if _debug: TestVLAN._debug("    - pdu: %r", pdu)

        # node 1 sends the pdu, mode 2 gets it
        tnode1.start_state.send(pdu).success()
        tnode2.start_state.receive(
            PDU,
            pduSource=('192.168.2.1', 47808),
        ).success()

        # run the group
        tnet.run()
Пример #20
0
    def test_broadcast(self):
        """Test a broadcast message from TD to IUT."""
        if _debug: TestSimple._debug("test_broadcast")

        # create a network
        tnet = TNetwork()

        # make a PDU from node 1 to node 2
        pdu_data = xtob('dead.beef')
        pdu = PDU(pdu_data,
                  source=tnet.td.address,
                  destination=LocalBroadcast())
        if _debug: TestSimple._debug("    - pdu: %r", pdu)

        # test device sends it, iut gets it
        tnet.td.start_state.send(pdu).success()
        tnet.iut.start_state.receive(PDU, pduSource=tnet.td.address).success()

        # sniffer sees message on the wire
        tnet.sniffer.start_state.receive(
            OriginalBroadcastNPDU,
            pduSource=tnet.td.address.addrTuple,
            #           pduDestination=('192.168.4.255', 47808),
            pduData=pdu_data,
        ).timeout(1.0).success()

        # run the group
        tnet.run()
Пример #21
0
    def test_promiscuous_fail(self):
        if _debug: TestVLAN._debug("test_promiscuous_fail")

        # three element network
        tnet = TNetwork(3, "192.168.7.{}/24")
        tnode1, tnode2, tnode3 = tnet.state_machines

        # make a PDU from node 1 to node 2
        pdu = PDU(
            b'data',
            source=('192.168.7.1', 47808),
            destination=('192.168.7.2', 47808),
        )

        # node 1 sends the pdu to node 2, node 3 waits and gets nothing
        tnode1.start_state.send(pdu).success()
        tnode2.start_state.receive(
            PDU,
            pduSource=('192.168.7.1', 47808),
        ).success()

        # if node 3 receives anything it will trigger unexpected receive and fail
        tnode3.start_state.timeout(1).success()

        # run the group
        tnet.run()
    def response(self, response_apdu, npdu, bvlpdu, address):
        if response_apdu is None:
            return
        apdu = APDU()
        response_apdu.encode(apdu)
        apdu.encode(npdu)
        npdu.encode(bvlpdu)
        pdu = PDU()
        bvlpdu.bvlciLength = len(bvlpdu.pduData) + 4
        bvlpdu.encode(pdu)

        apdu_type = apdu_types.get(response_apdu.apduType)

        if isinstance(response_apdu, RejectPDU) or isinstance(
                response_apdu, ErrorPDU):
            self.datagram_server.sendto(pdu.pduData, address)
            logger.info('Bacnet Error or Reject response sent to %s (%s:%s)',
                        response_apdu.pduDestination, apdu_type.__name__,
                        self._response_service)

        else:
            if pdu.pduDestination == '*:*':
                # broadcast
                # sendto operates under lock
                self.datagram_server.sendto(pdu.pduData, ('', address[1]))
            else:
                # sendto operates under lock
                self.datagram_server.sendto(pdu.pduData, address)
            logger.info('Bacnet response sent to %s (%s:%s)',
                        response_apdu.pduDestination, apdu_type.__name__,
                        self._response_service)
Пример #23
0
    def test_unicast(self):
        """Test a unicast message from TD to IUT."""
        if _debug: TestSimple._debug("test_unicast")

        # create a network
        tnet = TNetwork()

        # make a PDU from node 1 to node 2
        pdu_data = xtob('dead.beef')
        pdu = PDU(pdu_data,
                  source=tnet.td.address,
                  destination=tnet.iut.address)
        if _debug: TestSimple._debug("    - pdu: %r", pdu)

        # test device sends it, iut gets it
        tnet.td.start_state.send(pdu).success()
        tnet.iut.start_state.receive(PDU, pduSource=tnet.td.address).success()

        # sniffer sees message on the wire
        tnet.sniffer.start_state.receive(
            PDU,
            pduSource=tnet.td.address.addrTuple,
            pduDestination=tnet.iut.address.addrTuple,
            pduData=xtob('81.0a.0008'  # original unicast bvlci
                         'deadbeef'  # PDU being unicast
                         ),
        ).timeout(1.0).success()

        # run the group
        tnet.run()
Пример #24
0
def decode_packet(data):
    """decode the data, return some kind of PDU."""
    if _debug: decode_packet._debug("decode_packet %r", data)

    # convert the hex data to an octet string
    data = ''.join(chr(int(data[i:i + 2], 16)) for i in range(0, len(data), 2))

    # build a PDU
    pdu = PDU(data)

    # check for a BVLL header
    if (pdu.pduData[0] == '\x81'):
        if _debug: decode_packet._debug("    - BVLL header found")

        xpdu = BVLPDU()
        xpdu.decode(pdu)
        if _debug: decode_packet._debug("    - xpdu: %r", xpdu)
        pdu = xpdu

        # make a more focused interpretation
        atype = bvl_pdu_types.get(pdu.bvlciFunction)
        if not atype:
            if _debug:
                decode_packet._debug("    - unknown BVLL type: %r",
                                     pdu.bvlciFunction)
            return pdu

        # decode it as one of the basic types
        try:
            xpdu = pdu
            bpdu = atype()
            bpdu.decode(pdu)
            if _debug: decode_packet._debug("    - bpdu: %r", bpdu)

            pdu = bpdu

            # lift the address for forwarded NPDU's
            if atype is ForwardedNPDU:
                pdu.pduSource = bpdu.bvlciAddress
            # no deeper decoding for some
            elif atype not in (DistributeBroadcastToNetwork,
                               OriginalUnicastNPDU, OriginalBroadcastNPDU):
                return pdu

        except Exception, err:
            if _debug: decode_packet._debug("    - decoding Error: %r", err)
            return xpdu
Пример #25
0
    def test_broadcast(self):
        """Test a broadcast message from the foreign device to the bbmd."""
        if _debug: TestForeign._debug("test_broadcast")

        # create a network
        tnet = TNetwork()

        # make a broadcast pdu
        pdu_data = xtob('dead.beef')
        pdu = PDU(pdu_data, destination=LocalBroadcast())
        if _debug: TestForeign._debug("    - pdu: %r", pdu)

        # register, wait for ack, send some beef
        tnet.fd.start_state.doc("4-1-0") \
            .call(tnet.fd.bip.register, tnet.bbmd.address, 60).doc("4-1-1") \
            .wait_event('4-registered').doc("4-1-2") \
            .send(pdu).doc("4-1-3") \
            .success()

        # the bbmd is happy when it gets the pdu
        tnet.bbmd.start_state \
            .receive(PDU, pduSource=tnet.fd.address, pduData=pdu_data) \
            .success()

        # home sniffer node
        home_node = SimpleNode("192.168.5.254/24", tnet.home_vlan)
        tnet.append(home_node)

        # home node happy when getting the pdu, broadcast by the bbmd
        home_node.start_state.doc("4-2-0") \
            .receive(PDU, pduSource=tnet.fd.address, pduData=pdu_data).doc("4-2-1") \
            .success()

        # remote sniffer node
        remote_sniffer = SnifferNode("192.168.6.254/24", tnet.remote_vlan)
        tnet.append(remote_sniffer)

        # sniffer pieces
        registration_request = xtob('81.05.0006'  # bvlci
                                    '003c'  # time-to-live (60)
                                    )
        registration_ack = xtob('81.00.0006.0000')  # simple ack
        distribute_pdu = xtob('81.09.0008'  # bvlci
                              'deadbeef'  # PDU to broadcast
                              )

        # remote sniffer sees registration
        remote_sniffer.start_state.doc("4-3-0") \
            .receive(PDU, pduData=registration_request).doc("4-3-1") \
            .receive(PDU, pduData=registration_ack).doc("4-3-2") \
            .set_event('4-registered') \
            .receive(PDU, pduData=distribute_pdu).doc("4-3-3") \
            .success()

        # run the group
        tnet.run(4.0)
Пример #26
0
 def handle(self, data, address):
     session = conpot_core.get_session('bacnet', address[0], address[1])
     logger.info('New Bacnet connection from %s:%d. (%s)', address[0], address[1], session.id)
     session.add_event({'type': 'NEW_CONNECTION'})
     # I'm not sure if gevent DatagramServer handles issues where the
     # received data is over the MTU -> fragmentation
     if data:
         pdu = PDU()
         pdu.pduData = data
         apdu = APDU()
         try:
             apdu.decode(pdu)
         except DecodingError as e:
             logger.error("DecodingError: %s", e)
             logger.error("PDU: " + format(pdu))
             return
         self.bacnet_app.indication(apdu, address, self.thisDevice)
         self.bacnet_app.response(self.bacnet_app._response, address)
     logger.info('Bacnet client disconnected %s:%d. (%s)', address[0], address[1], session.id)
Пример #27
0
 def handle(self, data, address):
     session = conpot_core.get_session('bacnet', address[0], address[1], get_interface_ip(address[0]), self.server.server_port)
     logger.info('New Bacnet connection from %s:%d. (%s)', address[0], address[1], session.id)
     session.add_event({'type': 'NEW_CONNECTION'})
     # I'm not sure if gevent DatagramServer handles issues where the
     # received data is over the MTU -> fragmentation
     if data:
         pdu = PDU()
         pdu.pduData = bytearray(data)
         apdu = APDU()
         try:
             apdu.decode(pdu)
         except DecodingError:
             logger.warning("DecodingError - PDU: {}".format(pdu))
             return
         self.bacnet_app.indication(apdu, address, self.thisDevice)
         # send an appropriate response from BACnet app to the attacker
         self.bacnet_app.response(self.bacnet_app._response, address)
     logger.info('Bacnet client disconnected %s:%d. (%s)', address[0], address[1], session.id)
Пример #28
0
    def as_bytes(self):
        if _debug: BVLPDU._debug("as_bytes")

        bvlpdu = BVLPDU()
        self.encode(bvlpdu)

        pdu = PDU()
        bvlpdu.encode(pdu)

        return pdu.pduData
Пример #29
0
    def test_read_foreign_device_table(self):
        """Test the ReadForeignDeviceTable encoding and decoding."""
        if _debug: TestAnnexJCodec._debug("test_read_foreign_device_table")

        # read returns an empty table
        pdu_bytes = xtob('81.06.0004')

        self.request(ReadForeignDeviceTable())
        self.indication(pduData=pdu_bytes)

        self.response(PDU(pdu_bytes))
        self.confirmation(ReadForeignDeviceTable)
Пример #30
0
    def test_result(self):
        """Test the Result encoding and decoding."""
        if _debug: TestAnnexJCodec._debug("test_codec_01")

        # Request successful
        pdu_bytes = xtob('81.00.0006.0000')

        self.request(Result(0))
        self.indication(pduData=pdu_bytes)

        self.response(PDU(pdu_bytes))
        self.confirmation(Result, bvlciResultCode=0)

        # Request error condition
        pdu_bytes = xtob('81.00.0006.0001')

        self.request(Result(1))
        self.indication(pduData=pdu_bytes)

        self.response(PDU(pdu_bytes))
        self.confirmation(Result, bvlciResultCode=1)
Пример #31
0
    def test_read_broadcast_distribution_table(self):
        """Test the ReadBroadcastDistributionTable encoding and decoding."""
        if _debug:
            TestAnnexJCodec._debug("test_read_broadcast_distribution_table")

        # read the table
        pdu_bytes = xtob('81.02.0004')

        self.request(ReadBroadcastDistributionTable())
        self.indication(pduData=pdu_bytes)

        self.response(PDU(pdu_bytes))
        self.confirmation(ReadBroadcastDistributionTable)
Пример #32
0
    def test_who_is_router_to_network(self):
        """Test the Result encoding and decoding."""
        if _debug: TestNPDUCodec._debug("test_who_is_router_to_network")

        # Request successful
        pdu_bytes = xtob('01.80'  # version, network layer message
                         '00 0001'  # message type and network
                         )

        self.request(WhoIsRouterToNetwork(1))
        self.indication(pduData=pdu_bytes)

        self.response(PDU(pdu_bytes))
        self.confirmation(WhoIsRouterToNetwork, wirtnNetwork=1)