Пример #1
0
 def execute(self):
     """Execute the test."""
     TLog.generic(
         "Fuzz Writing to CANbus on interface({}), arbitration id(0x{:x}), "
         "extended?({}) data({})".format(self.args.iface, self.args.arbitid,
                                         self.args.exid, self.args.data))
     bus = None
     try:
         if self.args.count < 1:
             raise ValueError("Illegal count value {}".format(
                 self.args.count))
         if self.args.wait < 0:
             raise ValueError("Illegal wait value {}".format(
                 self.args.wait))
         bus = CanBus(bustype="socketcan", channel=self.args.iface)
         for count in range(self.args.count):
             datacan = self.args.data
             while datacan.find("xx") >= 0:
                 datacan = datacan.replace("xx", "{:02x}".format(
                     randint(0,
                             0xFF)), 1)  # main fuzzing magic with randint
             message = CanMessage(arbitration_id=self.args.arbitid,
                                  extended_id=self.args.exid,
                                  data=list(bytes.fromhex(datacan)))
             bus.send(message)
             TLog.success("{} : Wrote message {}  ".format(count, datacan))
             if self.args.wait > 0:
                 sleep(self.args.wait)
     except BaseException:
         self.result.exception()
     finally:
         if bus:
             bus.shutdown()
Пример #2
0
    def execute(self):
        """Execute the test."""
        TLog.generic(
            "Reading ({}) messages from CANbus on interface({})".format(
                self.args.count, self.args.iface))

        bus = None
        try:
            if self.args.count < 1:
                raise ValueError("Illegal count value {}".format(
                    self.args.count))
            bus = CanBus(bustype="socketcan", channel=self.args.iface)
            for cnt in range(1, self.args.count + 1):
                message = bus.recv(timeout=self.args.timeout)
                if message is None:
                    raise TimeoutError(
                        "Timed out while waiting for CAN message")
                if self.args.arbitid:
                    if self.args.arbitid == message.arbitration_id:
                        self.output_handler(logkwargs=LOGNORMAL,
                                            count=cnt,
                                            data=hexlify(
                                                message.data).decode())
                else:
                    self.output_handler(logkwargs=LOGNORMAL,
                                        count=cnt,
                                        arbitration_id="0x{:x}".format(
                                            message.arbitration_id),
                                        data=hexlify(message.data).decode())
        except:  # noqa: E722
            self.result.exception()
        finally:
            if bus:
                bus.shutdown()
Пример #3
0
    def scan(self):
        """
        Scan for BLE devices in the proximity.

        :return:
        """
        TLog.generic("Scanning BLE devices for {} second(s)".format(
            self.args.timeout))
        try:
            devices = Ble.scan(iface=self.args.iface, tout=self.args.timeout)
            for device in devices:
                self.found = True
                TLog.success("(name={})(address={})".format(
                    device.getValueText(Ble.ADTYPE_NAME) or "Unknown",
                    device.addr))
                if self.args.verbose is True:
                    TLog.success("    (rssi={}dB)".format(device.rssi))
                    TLog.success("    (connectable={})".format(
                        device.connectable))
                    for scan_data in device.getScanData():
                        TLog.success("    ({}={})".format(
                            scan_data[1], scan_data[2]))
        except:  # noqa: E722
            self.reason = "Exception caught: {}".format(sysexcinfo())

        if self.found is False and self.reason is None:
            self.reason = "No BLE devices found"
Пример #4
0
 def execute(self):
     """Execute the test."""
     TLog.generic(
         "Publishing message on topic ({}) to MQTT Broker ({}) on port "
         "({})".format(self.args.rhost, self.args.topic, self.args.rport))
     credentials = None
     if self.args.user and self.args.passwd:
         credentials = {
             "username": self.args.user,
             "password": self.args.passwd
         }
         TLog.trydo(
             "Using authentication (username={})(password={})".format(
                 self.args.user, self.args.passwd))
     try:
         SimpleMqttClient.pub(
             self.args.topic,
             payload=self.args.msg,
             hostname=self.args.rhost,
             port=self.args.rport,
             auth=credentials,
             client_id=self.args.id,
         )
         TLog.success("Done")
     except:  # noqa: E722
         self.result.exception()
Пример #5
0
    def execute(self):
        """Execute the test."""
        TLog.generic(
            "Subscribing to topic ({}) on MQTT broker ({}) on port ({})".
            format(self.args.topic, self.args.rhost, self.args.rport))
        try:
            credentials = None
            if self.args.user and self.args.passwd:
                credentials = {
                    "username": self.args.user,
                    "password": self.args.passwd
                }
                TLog.trydo(
                    "Using authentication (username={})(password={})".format(
                        self.args.user, self.args.passwd))

            messages = SimpleMqttClient.sub(
                self.args.topic,
                hostname=self.args.rhost,
                port=self.args.rport,
                client_id=self.args.id,
                auth=credentials,
                msg_count=self.args.count,
            )
            for message in messages:
                TLog.success("(topic={})(payload={})".format(
                    message.topic, str(message.payload)))
        except:  # noqa: E722
            self.result.exception()
Пример #6
0
    def execute(self):
        TLog.generic(
            "Reading ({}) messages from CANbus on interface({})".format(
                self.args.count, self.args.iface))

        bus = None
        try:
            if self.args.count < 1:
                raise ValueError("Illegal count value {}".format(
                    self.args.count))
            bus = CanBus(bustype="socketcan", channel=self.args.iface)
            for cnt in range(1, self.args.count + 1):
                m = bus.recv(timeout=self.args.timeout)
                if m is None:
                    raise TimeoutError(
                        "Timed out while waiting for CAN message")
                if self.args.arbitid:
                    if self.args.arbitid == m.arbitration_id:
                        TLog.success("(msg={})(data={})".format(
                            cnt,
                            hexlify(m.data).decode()))
                else:
                    TLog.success(
                        "(msg={})(arbitration_id=0x{:x})(data={})".format(
                            cnt, m.arbitration_id,
                            hexlify(m.data).decode()))
        except:
            self.result.exception()
        finally:
            if bus:
                bus.shutdown()
Пример #7
0
    def execute(self):
        """Execute the test."""

        TLog.generic(
            "Reading from Notify handle ({}) on BLE device ({})".format(
                hex(self.args.handle), self.args.addr))
        timer = Timer(self.args.timeout)
        ndelegate = BleNotifyDelegate(self.notifycb)
        device = BlePeripheral()
        try:
            device.connect(
                self.args.addr,
                addrType=(ADDR_TYPE_RANDOM
                          if self.args.randaddrtype else ADDR_TYPE_PUBLIC),
            )
            TLog.generic("Enabling Notify on the handle")
            device.enable_notify(ndelegate,
                                 self.args.handle,
                                 write_response=True)
            while not timer.is_timeout():
                device.waitForNotifications(1)
            if ndelegate.count() > 0:
                TLog.success("Total notification data received {}".format(
                    ndelegate.count()))
            else:
                self.result.setstatus(
                    passed=False,
                    reason="No notification data received from BLE peripheral")
        except:  # noqa: E722
            self.result.exception()
        finally:
            device.disconnect()
Пример #8
0
 def execute(self):
     """Execute tht test."""
     TLog.generic(
         "Writing to CANbus on interface({}), arbitration id(0x{:x}), "
         "extended?({}) data({})".format(self.args.iface, self.args.arbitid,
                                         self.args.exid, self.args.data))
     bus = None
     try:
         if self.args.count < 1:
             raise ValueError("Illegal count value {}".format(
                 self.args.count))
         bus = CanBus(bustype="socketcan", channel=self.args.iface)
         message = CanMessage(
             arbitration_id=self.args.arbitid,
             extended_id=self.args.exid,
             data=list(bytes.fromhex(self.args.data)),
         )
         for count in range(1, self.args.count + 1):
             bus.send(message)
             TLog.success("Wrote message {}".format(count))
             if self.args.wait and count < self.args.count:
                 sleep(self.args.wait)
     except:  # noqa: E722
         self.result.exception()
     finally:
         if bus:
             bus.shutdown()
Пример #9
0
    def execute(self):
        """Execute the mDNS discovery."""

        service_names = list(MDNS_SERVICE_TYPES)
        if self.args.list:
            self.output_handler(supported_device_types=service_names)
            return
        TLog.generic("Search local network for mDNS enabled devices")

        if self.args.device:
            if self.args.device not in service_names:
                self.result.setstatus(passed=False, reason="Unknown device type specified")
                return
            service_names = [self.args.device]
        cnt = 0
        for name in service_names:
            if self.args.verbose:
                TLog.trydo("Looking for {} devices".format(name))
            details = MdnsDiscovery(name, scan_timeout=self.args.timeout)
            details.scan()
            for device in details.devices:
                cnt += 1
                self.output_handler(device_number=cnt,
                                    name=device.name,
                                    address=device.address,
                                    port=device.port,
                                    server=device.server,
                                    type=device.type,
                                    priority=device.priority,
                                    weight=device.weight,
                                    properties=device.properties)
        self.output_handler(total_devices_discovered=cnt)
Пример #10
0
    def execute(self):
        """Execute the test."""
        dst_pan = None
        send_packet = False
        pcap_reader = None
        radio = None

        # Get Destination PAN address
        if self.args.pan:
            dst_pan = self.args.pan

        delay_sec = self.args.delay / 1000

        TLog.generic("{:<13}: ({})".format("Channel", self.args.channel))
        TLog.generic("{:<13}: ({})".format("File", self.args.pcapfile))
        TLog.generic("{:<13}: ({})".format("Delay (seconds)", delay_sec))
        if dst_pan:
            TLog.generic("{:<15}: ({})".format("Destination PAN",
                                               hex(dst_pan)))
        TLog.generic("")

        try:
            radio = Dot154Radio()
            pcap_reader = PcapDumpReader(self.args.pcapfile)

            radio.radio_on()
            radio.set_channel(self.args.channel)

            while True:
                packet = pcap_reader.read_next_packet()
                if packet:
                    if not dst_pan and not is_ack_packet(packet):
                        send_packet = True
                    elif dst_pan and dst_pan == get_dst_pan_from_packet(
                            packet):
                        send_packet = True

                    if send_packet:
                        radio.inject_raw_packet(packet[0:-2])
                        send_packet = False
                        time.sleep(delay_sec)
                else:
                    break

        except:  # noqa: E722
            self.result.setstatus(passed=False,
                                  reason="Exception caught: {}".format(
                                      sysexcinfo()))

        finally:
            # Close file handler
            if pcap_reader:
                pcap_reader.close()

            # Turn OFF radio and exit
            if radio:
                self.output_handler(
                    packets_received=radio.get_received_packets(),
                    packets_transmitted=radio.get_transmitted_packets())
                radio.radio_off()
Пример #11
0
 def execute(self):
     """Execute the test."""
     TLog.generic(
         "Writing the value ({}) to handle ({}) on BLE device ({})".format(
             self.args.value, hex(self.args.handle), self.args.addr
         )
     )
     device = BlePeripheral()
     try:
         device.connect(
             self.args.addr,
             addrType=(
                 ADDR_TYPE_RANDOM
                 if self.args.randaddrtype
                 else ADDR_TYPE_PUBLIC
             ),
         )
         device.writeCharacteristic(
             self.args.handle,
             bytes.fromhex(self.args.value),
             withResponse=(not self.args.noresponse),
         )
     except:  # noqa: E722
         self.result.exception()
     finally:
         device.disconnect()
Пример #12
0
    def display_uart_scan_result(result_list):
        """Displays uart scan result.

        Args:
            result_dict (dict): Dict of UART port scan result
        Returns:
           Nothing
        Raises:
            Nothing
        """

        TLog.success("UART port scan result:")

        for ports in result_list:
            TLog.success("{:<8}: {}".format("BaudRate", ports["baud"]))

            pins = ports["pins"]

            TLog.success("UART pins:")
            if len(pins) == 1:
                TLog.success("\tTx pin: {}, Rx pin: {}".format(
                    pins[0]["tx"], pins[0]["rx"]))
            else:
                TLog.success("\tPossible pin combinations:")

                for index, pin in enumerate(pins):
                    TLog.success("\t{}. Tx pin: {}, Rx pin: {}".format(
                        index + 1, pin["tx"], pin["rx"]))

            TLog.generic("")
Пример #13
0
 def execute(self):
     """Execute the plugin."""
     TLog.generic(
         "Publishing message on topic ({}) to MQTT Broker ({}) on port "
         "({})".format(self.args.topic, self.args.rhost, self.args.rport))
     try:
         client = MqttClient(client_id=self.args.id)
         client.easy_config(
             user=self.args.user,
             passwd=self.args.passwd,
             on_connect=client.on_connectcb,
             on_publish=client.on_publishcb,
         )
         client.connect(self.args.rhost, self.args.rport)
         client.publish(self.args.topic, self.args.msg, 1)
         client.loop_forever()
         if client.connect_rc != MQTT_ERR_SUCCESS:
             self.result.setstatus(passed=False,
                                   reason=client.rcstr(client.connect_rc))
             TLog.fail("MQTT Connection Failed. Return code ({}:{})".format(
                 client.connect_rc, client.rcstr(client.connect_rc)))
         else:
             TLog.success("Message published")
     except:  # noqa: E722
         self.result.exception()
Пример #14
0
 def execute(self):
     """Execute the test."""
     TLog.generic(
         "Reading data from i2c eeprom at address({}) using device({})".
         format(self.args.addr, self.args.url))
     device = None
     try:
         device = I2cEepromManager.get_flash_device(self.args.url,
                                                    self.args.chip,
                                                    address=self.slaveaddr)
         length = self.args.length or (len(device) - self.args.addr)
         TLog.success("(chip size={} bytes)".format(len(device)))
         TLog.trydo("Reading {} bytes from start address {}".format(
             length, self.args.addr))
         if self.args.addr + length > len(device):
             raise IndexError("Length is out of range of the chip size")
         start_time = time()
         data = device.read(self.args.addr, length)
         end_time = time()
         if self.args.wfile:
             TLog.trydo("Writing data to the file ({})".format(
                 self.args.wfile))
             output_file = open(self.args.wfile, "w+b")
             output_file.write(data)
             output_file.close()
         else:
             TLog.success("(data={})".format([hex(x) for x in data]))
         TLog.success(
             "Done. Total bytes read ({}) Time taken to read = {} secs".
             format(len(data), round(end_time - start_time, 2)))
     except:  # noqa: E722
         self.result.exception()
     finally:
         I2cEepromManager.close(device)
Пример #15
0
 def execute(self):
     """Execute the test."""
     TLog.generic(
         "Reading from handle ({}) on BLE device ({})".format(
             hex(self.args.handle), self.args.addr
         )
     )
     device = BlePeripheral()
     try:
         device.connect(
             self.args.addr,
             addrType=(
                 ADDR_TYPE_RANDOM
                 if self.args.randaddrtype
                 else ADDR_TYPE_PUBLIC
             ),
         )
         TLog.success(
             " (value={})".format(
                 device.readCharacteristic(
                     self.args.handle)))
     except:  # noqa: E722
         self.result.exception()
     finally:
         device.disconnect()
Пример #16
0
    def execute(self):
        """Execute the test."""
        TLog.generic(
            "Fuzzing the value ({}), iterations ({}) for handle ({}) on BLE device ({})"
            .format(self.args.value, self.args.iter, hex(self.args.handle),
                    self.args.addr))
        try:
            device = BlePeripheral()
            device.connect(
                self.args.addr,
                addrType=(Ble.ADDR_TYPE_RANDOM
                          if self.args.randaddrtype else Ble.ADDR_TYPE_PUBLIC),
            )
            for _ in range(self.args.iter):
                value = self.args.value
                while value.find("xx") >= 0:
                    value = value.replace(
                        "xx",
                        "{:02x}".format(randint(0, 0xFF)),
                        1  # nosec
                    )

                TLog.trydo("Writing the fuzzed value ({})".format(value))
                device.writeCharacteristic(
                    self.args.handle,
                    bytes.fromhex(value),
                    withResponse=(not self.args.noresponse),
                )
        except:  # noqa: E722
            self.result.exception()
        finally:
            device.disconnect()
Пример #17
0
    def enumerate(self):
        """
        Enumerate the services and/or characteristics of the specified BLE device.

        :return:
        """
        # Documentation is wrong, the first keyword argument is deviceAddr instead of
        # deviceAddress. http://ianharvey.github.io/bluepy-doc/
        if self.args.services is False and self.args.chars is False:
            TLog.fail(
                "Specify the enumerations option(s). Either or both - services, chars"
            )
            self.reason = "Incomplete arguments"
            return

        TLog.generic(
            "Enumerating services/characteristics of the device {}".format(
                self.args.addr
            )
        )
        device = BlePeripheral()
        try:
            device.connect(
                self.args.addr,
                addrType=(
                    ADDR_TYPE_RANDOM
                    if self.args.randaddrtype
                    else ADDR_TYPE_PUBLIC
                ),
            )
            self.found = True
            if self.args.services is True:
                services = device.getServices()
                for service in services:
                    TLog.success(
                        "(service uuid={})(handlestart={})(handleend={})".format(
                            service.uuid, hex(service.hndStart), hex(service.hndEnd)
                        )
                    )
            if self.args.chars is True:
                chars = device.getCharacteristics()
                for char in chars:
                    TLog.success(
                        "(characteristic uuid={})(handle={})".format(
                            char.uuid, hex(char.getHandle())
                        )
                    )
                    if self.args.verbose is True:
                        support_property = char.propertiesToString()
                        supports_read = char.supportsRead()
                        TLog.success("    (supported_properties={})".format(support_property))
                        if supports_read is True:
                            TLog.success("    (value={})".format(char.read()))
        except:  # noqa: E722
            self.reason = "Exception caught: {}".format(sysexcinfo())
        finally:
            device.disconnect()
        if self.found is False and self.reason is None:
            self.reason = "Couldn't find any devices"
Пример #18
0
    def execute(self):
        c = ModbusTcpClient(self.args.rhost, port=self.args.rport)
        try:
            values = None
            # Check what to read i.e. coils, holding registers etc
            if self.args.item < 0 or self.args.item >= len(self.ITEMS):
                raise AttributeError("Unknown --item specified ({})".format(
                    self.args.item))

            TLog.generic(
                "Sending read command to Modbus Server ({}) on port ({})".
                format(self.args.rhost, self.args.rport))
            TLog.generic("(item={})(address={})(count={})(unit={})".format(
                self.ITEMS[self.args.item], self.args.address, self.args.count,
                self.args.unit))
            c.connect()
            if self.args.item == self.COIL:
                r = c.read_coils(self.args.address,
                                 self.args.count,
                                 unit=self.args.unit)
                if r.isError() == True:
                    raise Exception(str(r))
                values = r.bits
            elif self.args.item == self.DINPUT:
                # below r = class pymodbus.bit_read_message.ReadDiscreteInputsResponse
                r = c.read_discrete_inputs(self.args.address,
                                           self.args.count,
                                           unit=self.args.unit)
                if r.isError() == True:
                    raise Exception(str(r))
                values = r.bits
            elif self.args.item == self.HREG:
                # below r = class pymodbus.register_read_message.ReadHoldingRegistersResponse
                r = c.read_holding_registers(self.args.address,
                                             self.args.count,
                                             unit=self.args.unit)
                if r.isError() == True:
                    raise Exception(str(r))
                values = r.registers
            elif self.args.item == self.IREG:
                # below r = class pymodbus.register_read_message.ReadInputRegistersResponse
                r = c.read_input_registers(self.args.address,
                                           self.args.count,
                                           unit=self.args.unit)
                if r.isError() == True:
                    raise Exception(str(r))
                values = r.registers
            else:
                raise AttributeError("Unknown --item specified ({})".format(
                    self.args.item))
            for i in range(0, self.args.count):
                TLog.success("({}[{}]={})".format(self.ITEMS[self.args.item],
                                                  self.args.address + i,
                                                  values[i]))
        except:
            self.result.exception()
        finally:
            c.close()
Пример #19
0
 def execute(self):
     """Execute the test."""
     TLog.generic(
         "Attempting to authenticate with the MQTT broker ({}) on port "
         "({})".format(self.args.rhost, self.args.rport))
     found = False
     try:
         if self.args.pfile and self.args.user:
             for password in readlines(self.args.pfile):
                 if self.args.verbose:
                     TLog.generic(
                         "Checking username {} with password {}".format(
                             self.args.user, password))
                 return_code, state = SimpleMqttClient.connauth(
                     self.args.rhost,
                     client_id=self.args.id,
                     user=self.args.user,
                     passwd=password,
                     port=self.args.rport,
                 )
                 if return_code == 0:
                     TLog.success(
                         "FOUND - (user={})(passwd={})(return code={}:{})".
                         format(self.args.user, password, return_code,
                                state))
                     found = True
                     break
                 elif self.args.verbose:
                     TLog.fail(
                         "Auth failed - (user={})(passwd={})(return code={}:{})"
                         .format(self.args.user, password, return_code,
                                 state))
             if found is False:
                 self.result.setstatus(
                     passed=False, reason="Auth failed for all passwords")
         else:
             return_code, state = SimpleMqttClient.connauth(
                 self.args.rhost,
                 client_id=self.args.id,
                 user=self.args.user,
                 passwd=self.args.passwd,
                 port=self.args.rport,
             )
             if return_code == 0:
                 TLog.success(
                     "FOUND - (user={})(passwd={})(return code={}:{})".
                     format(self.args.user, self.args.passwd, return_code,
                            state))
             else:
                 self.result.setstatus(passed=False, reason=state)
                 if self.args.verbose:
                     TLog.fail(
                         "Auth failed - (user={})(passwd={})(return code={}:{})"
                         .format(self.args.user, self.args.passwd,
                                 return_code, state))
     except:  # noqa: E722
         self.result.exception()
Пример #20
0
    def execute(self):
        """Execute the test."""
        modbus_client = ModbusTcpClient(self.args.rhost, port=self.args.rport)

        try:
            if self.args.item < 0 or self.args.item >= len(READ_ITEMS):
                raise AttributeError("Unknown --item specified ({})".format(
                    self.args.item))

            TLog.generic(
                "Sending read command to Modbus Server ({}) on port ({})".
                format(self.args.rhost, self.args.rport))
            TLog.generic("(item={})(address={})(count={})(unit={})".format(
                READ_ITEMS[self.args.item],
                self.args.address,
                self.args.count,
                self.args.unit,
            ))
            modbus_client.connect()
            if self.args.item == self.COIL:
                response = modbus_client.read_coils(self.args.address,
                                                    self.args.count,
                                                    unit=self.args.unit)
                if response.isError() is True:
                    raise Exception(str(response))
                values = response.bits
            elif self.args.item == self.DINPUT:
                response = modbus_client.read_discrete_inputs(
                    self.args.address, self.args.count, unit=self.args.unit)
                if response.isError() is True:
                    raise Exception(str(response))
                values = response.bits
            elif self.args.item == self.HREG:
                response = modbus_client.read_holding_registers(
                    self.args.address, self.args.count, unit=self.args.unit)
                if response.isError() is True:
                    raise Exception(str(response))
                values = response.registers
            elif self.args.item == self.IREG:
                response = modbus_client.read_input_registers(
                    self.args.address, self.args.count, unit=self.args.unit)
                if response.isError() is True:
                    raise Exception(str(response))
                values = response.registers
            else:
                raise AttributeError("Unknown --item specified ({})".format(
                    self.args.item))
            for entry in range(0, self.args.count):
                TLog.success("({}[{}]={})".format(
                    READ_ITEMS[self.args.item],
                    self.args.address + entry,
                    values[entry],
                ))
        except:  # noqa: E722
            self.result.exception()
        finally:
            modbus_client.close()
Пример #21
0
    def execute(self):
        """Execute the test."""
        modbus_client = ModbusTcpClient(self.args.rhost, port=self.args.rport)

        try:
            if self.args.item < 0 or self.args.item >= len(WRITE_ITEMS):
                raise AttributeError(
                    "Unknown --item specified ({})".format(self.args.item)
                )
            if self.args.count < 1:
                raise AttributeError(
                    "Invalid --count specified ({})".format(self.args.count)
                )

            TLog.generic(
                "Sending write command to Modbus Server ({}) on port ({})".format(
                    self.args.rhost, self.args.rport
                )
            )
            TLog.generic(
                "(item={})(address={})(count={})(unit={})".format(
                    WRITE_ITEMS[self.args.item],
                    self.args.address,
                    self.args.count,
                    self.args.unit,
                )
            )
            modbus_client.connect()
            if self.args.item == COIL:
                value = bool(self.args.value != 0)
                TLog.trydo("Writing value(s): {}".format(value))
                response = modbus_client.write_coils(
                    self.args.address, [value] * self.args.count, unit=self.args.unit
                )
                if response.isError() is True:
                    raise Exception(str(response))
            elif self.args.item == REG:
                TLog.trydo("Writing value(s): {}".format(self.args.value))
                response = modbus_client.write_registers(
                    self.args.address,
                    [self.args.value] * self.args.count,
                    unit=self.args.unit,
                )
                if response.isError() is True:
                    raise Exception(str(response))
            else:
                raise AttributeError(
                    "Unknown --item specified ({})".format(self.args.item)
                )
            TLog.success("Values successfully written")
        except:  # noqa: E722
            self.result.exception()
        finally:
            modbus_client.close()
Пример #22
0
    def execute(self):
        """Execute the test."""
        TLog.generic(
            "Sending Unauthorized command ({}) to Kankun smart plug on ({}) port ({})"
            .format(self.args.cmd, self.args.rhost, self.args.rport))
        op = None
        print("--cmd ({}) cmd is on? ({})".format(self.args.cmd,
                                                  (self.args.cmd == "on")))
        if self.args.cmd.lower() == "on":
            op = "open"
        elif self.args.cmd.lower() == "off":
            op = "close"
        else:
            self.result.setstatus(passed=False,
                                  reason="Unknown --cmd ({})".format(
                                      self.args.cmd))
            return
        m = self.createmsg(op)
        ret = None
        TLog.trydo("Sending {} command: ({})".format(op, m))
        # Step 1: Send command and receive the confirmation ID response
        ret = self.send_recv(self.args.rhost, self.args.rport, m)
        if ret is None:
            self.result.setstatus(
                passed=False,
                reason="Communication error while sending message({})".format(
                    m),
            )
            return

        TLog.success("Received response: ({})".format(ret.decode("utf-8")))
        # Get the confirmation ID
        cid = self.get_confirmid(ret)
        if cid is None:
            self.result.setstatus(
                passed=False,
                reason="Couldn't extract confirmation id from ({})".format(
                    ret),
            )
            return
        TLog.success("Received Confirmation ID: ({})".format(cid))
        m = self.createmsg("confirm", cid)
        TLog.trydo("Sending confirm command: ({})".format(m))
        # Step 2: Send Confirmation command with the confirmation ID and receive ack response
        ret = self.send_recv(self.args.rhost, self.args.rport, m)
        if ret is None:
            self.result.setstatus(
                passed=False,
                reason="Communication error while sending message({})".format(
                    m),
            )
            return
        TLog.success("Received response: ({})".format(ret.decode("utf-8")))
Пример #23
0
    def unlock(self, mac, name=None):
        """
        Unlock the specified Tapplock.

        Args:
            mac(str): The BLE address of the Tapplock
            name(str): The name of the Tapplock as advertised over BLE

        Returns:
            Nothing
        """
        device = BlePeripheral()
        try:
            TLog.trydo("Unlocking Tapplock ({})".format(mac))
            # Get key1 and serial
            pairing_data = None
            if self.args.default is False:
                remote_mac = ":".join(mac.upper().split(":")[::-1])
                md5_hash = md5(remote_mac.encode()).hexdigest()  # nosec
                key1 = md5_hash[0:8]
                serial = md5_hash[16:24]
                TLog.generic(
                    "(Calculated hash={})(key1={})(serial={})".format(
                        md5_hash, key1, serial
                    )
                )
                pairing_data = self.PAIRPREXIX + key1 + serial
            else:
                TLog.generic(
                    "(default key1={})(default serial={})".format(
                        self.DEFKEY, self.DEFSERIAL
                    )
                )
                pairing_data = self.DEFPAIR
            # Calculate the checksum
            checksum = 0
            for byte in bytes.fromhex(pairing_data):
                checksum = checksum + (byte % 255)
            checksum_string = "{:04x}".format(checksum)
            # Create the pairing data
            pairing_data = pairing_data + checksum_string[2:4] + checksum_string[0:2]
            device.connect(mac, addrType=ADDR_TYPE_RANDOM)
            device.writeCharacteristic(self.UNLOCKHNDL, bytes.fromhex(pairing_data))
            device.writeCharacteristic(self.UNLOCKHNDL, bytes.fromhex(self.UNLOCKCMD))
            self.output_handler(tlogtype=TLog.TRYDO,
                                logkwargs=LOGPRETTY,
                                name=name,
                                addr=device.addr,
                                sent_pair_data=pairing_data,
                                sent_unlock_cmd=self.UNLOCKCMD)
        finally:
            device.disconnect()
Пример #24
0
    def execute(self):
        """Execute the test."""
        TLog.generic("Sending unauthorized command ({}) to Kankun smart "
                     "plug on ({}) port ({})".format(self.args.cmd,
                                                     self.args.rhost,
                                                     self.args.rport))
        if self.args.cmd.lower() == "on":
            operation = "open"
        elif self.args.cmd.lower() == "off":
            operation = "close"
        else:
            self.result.setstatus(passed=False,
                                  reason="Unknown --cmd ({})".format(
                                      self.args.cmd))
            return

        message = self.create_message(operation)
        # Step 1: Send command and receive the confirmation ID response
        response = self.send_receive(self.args.rhost, self.args.rport, message)

        if response is None:
            self.result.setstatus(
                passed=False,
                reason="Communication error while sending message({})".format(
                    message),
            )
            return
        # Get the confirmation ID
        cid = self.get_confirm_id(response)

        if cid is None:
            self.result.setstatus(
                passed=False,
                reason="Couldn't extract confirmation ID from ({})".format(
                    response),
            )
            return
        self.output_handler(command=message,
                            response=response,
                            received_confirmation_id=cid)
        message = self.create_message("confirm", cid)
        # Step 2: Send confirmation command with the confirmation ID and receive ACK response
        response = self.send_receive(self.args.rhost, self.args.rport, message)
        if response is None:
            self.result.setstatus(
                passed=False,
                reason="Communication error while sending message({})".format(
                    message),
            )
            return
        self.output_handler(command2=message, response2=response)
Пример #25
0
    def execute(self):
        """
        Execute the plugin.
        Enumerate the services and/or characteristics of the specified BLE device.

        Returns:
            Nothing
        """
        # Documentation is wrong, the first keyword argument is deviceAddr instead of
        # deviceAddress. http://ianharvey.github.io/bluepy-doc/
        if self.args.services is False and self.args.chars is False:
            reason = "Incomplete args. Enumerate what? Either or both - services, chars"
            self.result.setstatus(passed=False, reason=reason)
            return
        TLog.generic(
            "Enumerating services/characteristics of the device {}".format(
                self.args.addr
            )
        )
        device = BlePeripheral()
        try:
            device.connect(
                self.args.addr,
                addrType=(
                    ADDR_TYPE_RANDOM
                    if self.args.randaddrtype
                    else ADDR_TYPE_PUBLIC
                ),
            )
            if self.args.services is True:
                services = device.getServices()
                for service in services:
                    self.output_handler(service_uuid=str(service.uuid),
                                        service_uuid_name=service.uuid.getCommonName(),
                                        handle_start=hex(service.hndStart),
                                        handle_end=hex(service.hndEnd))
            if self.args.chars is True:
                chars = device.getCharacteristics()
                for char in chars:
                    chardict = {"char_uuid": str(char.uuid),
                                "char_uuid_name": char.uuid.getCommonName(),
                                "handle": hex(char.getHandle()),
                                "supported_properties": char.propertiesToString()}
                    if char.supportsRead():
                        chardict["readvalue"] = char.read()
                    self.output_handler(**chardict)
        except:  # noqa: E722
            self.result.setstatus(passed=False,
                                  reason="Exception caught: {}".format(sysexcinfo()))
        finally:
            device.disconnect()
Пример #26
0
 def execute(self):
     """Execute the test."""
     TLog.generic("Sending GET request to CoRE discovery URI Path ({}) "
                  "to CoAP Server {} on port {}".format(
                      WKRPATH, self.args.rhost, self.args.rport))
     try:
         scanner = CoapDiscovery(self.args.rhost, port=self.args.rport)
         scanner.scan()
         resources = scanner.services()
         for resource in resources:
             self.output_handler(**resource)
         self.output_handler(total_resources=len(resources))
     except:  # noqa: E722
         self.result.exception()
Пример #27
0
 def execute(self):
     """Execute the test."""
     TLog.generic(
         "Sending request to server({}) on port({})".format(
             self.args.rhost, self.args.rport
         )
     )
     TLog.trydo("Searching imaginary database")
     TLog.success("Found matching entry in database - ({})".format("FooEntry"))
     snd = "GET / HTTP/1.1"
     TLog.generic(
         "Sending command to server ({}) on port ({})".format(
             self.args.rhost, self.args.rport
         )
     )
     if self.args.verbose is True:
         TLog.generic("More verbose output. Sending payload ({})".format(snd))
     TLog.fail("No response received")
     TLog.generic("Re-sending command")
     response = "Response received from the server"
     # In case of failure (Nothing to do in case of success)
     if response:
         self.result.setstatus(passed=True, reason="Server is vulnerable")
     else:
         self.result.setstatus(passed=False, reason="Server is not vulnerable")
Пример #28
0
 def execute(self):
     """Execute the test."""
     TLog.generic("Sending request to server({}) on port({})".format(
         self.args.rhost, self.args.rport))
     TLog.trydo("Searching imaginary database")
     self.output_handler(found_entry_in_db="FooEntry")
     # Or if you need to print extra message for only the console
     # but not required for the actual result output (chaining plugins)
     self.output_handler(
         msg="Found matching entry in database - ({})".format("FooEntry"),
         logkwargs=LOGNO,
         found_entry_in_db="FooEntry2")
     snd = "GET / HTTP/1.1"
     TLog.generic("Sending command to server ({}) on port ({})".format(
         self.args.rhost, self.args.rport))
     if self.args.verbose is True:
         TLog.generic(
             "More verbose output. Sending payload ({})".format(snd))
     TLog.fail("No response received")
     TLog.generic("Re-sending command")
     response = "Response received from the server"
     # In case of failure (Nothing to do in case of success)
     if response:
         self.output_handler(status="Server is vulnerable",
                             services_available=["ssh", "foo"])
     else:
         self.result.setstatus(passed=False,
                               reason="Server is not vulnerable")
Пример #29
0
    def execute(self):
        """Execute the test."""

        count = self.args.count
        timeout = self.args.timeout
        packetcount = 0
        pcap_writer = None
        radio = None

        TLog.generic("{:<13}: ({})".format("Channel", self.args.channel))
        TLog.generic("{:<13}: ({})".format("File", self.args.filepath))
        TLog.generic("{:<13}: ({})".format("Count", count))
        TLog.generic("{:<13}: ({})".format("Time-Out", timeout))

        try:
            # Get the Sniffer interface driver
            radio = Dot154Radio()

            # Create pcap file to dump the packet
            pcap_writer = PcapDumper(PCAP_DLT_IEEE802_15_4, self.args.filepath)

            # Turn ON radio sniffer
            radio.sniffer_on(self.args.channel)

            # kick start timer, if user set some timeout
            if timeout != 0:
                # Create Timer for timeout check
                timer = Timer()
                timer.timeout = timeout

            while True:
                packet = radio.read_raw_packet()
                if packet is not None:
                    packetcount += 1
                    pcap_frame = PcapFrame(packet)
                    pcap_writer.write_to_pcapfile(pcap_frame.get_pcap_frame())

                if timeout != 0:
                    if timer.is_timeout():
                        break

                if packetcount == count:
                    break

        except:  # noqa: E722
            self.result.setstatus(passed=False,
                                  reason="Exception caught: {}".format(
                                      sysexcinfo()))

        finally:
            # Close file handler
            if pcap_writer:
                pcap_writer.close()

            # Turn OFF radio sniffer and exit
            if radio:
                # Execution Done
                self.output_handler(
                    packets_received=radio.get_received_packets())
                radio.sniffer_off()
Пример #30
0
    def execute(self):
        """Execute the UPNP discovery."""

        TLog.generic("Search local network for UPNP enabled devices")
        scanner = UpnpDiscovery(timeout=self.args.timeout)
        scanner.scan()
        count = 0

        for dev in scanner.devices():
            count += 1
            TLog.generic("")
            TLog.success("Device {}:".format(count))
            self.output_handler(logkwargs=LOGNO, **dev)
            recurse_list_dict(dev, self.log_callback, None)
        self.output_handler(total_devices_discovered=count)