Example #1
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()
Example #2
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()
Example #3
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)
            ncount = ndelegate.count()
            if ncount > 0:
                self.output_handler(msg="Total notification data received {}".format(ncount),
                                    logkwargs=LOGNO,
                                    ndata=ncount)
            else:
                self.result.setstatus(passed=False, reason="No notification data received from BLE peripheral")
        except:  # noqa: E722
            self.result.exception()
        finally:
            device.disconnect()
Example #4
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()
Example #5
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()
Example #6
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()
Example #7
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"
Example #8
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()
Example #9
0
    def send_receive(self, ip_addr, port, message):
        """
        Send and then receive encrypted data to/from the smart plug.

        Args:
            ip_addr(str): The IP address of the smartplug
            port(int): Port number of the listening service
            message(str): The plaintext message
        Returns:
            bytes: The response received from the smart plug
        """
        response = None
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            sock.connect((ip_addr, port))
            sock.settimeout(20)
            sock.send(self.encrypt_decrypt(message))
            response = sock.recv(1024)
            response = self.encrypt_decrypt(response, encrypt=False)
        except:  # noqa: E722
            TLog.fail("Couldn't receive/decrypt response.")
            raise
        finally:
            sock.close()
        return response
Example #10
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()
Example #11
0
    def execute(self):
        """Execute the test."""
        TLog.generic(
            "Connecting to the the serial port ({}) timeout ({})".format(
                self.args.port, self.args.timeout))
        TLog.generic("Scanning for baud rates: {}".format(self.args.bauds))
        reason = "No good baud rate found"
        best = {"baud_rate": 0, "percentage_ascii": 0}
        try:
            for baud in self.args.bauds.split(","):
                percentage_ascii = self.check_baud(int(baud))
                if percentage_ascii == 100:
                    TLog.success("Found correct baud rate: {}".format(baud))
                    return
                if percentage_ascii > best["percentage_ascii"]:
                    best["percentage_ascii"] = percentage_ascii
                    best["baud_rate"] = int(baud)
            if best["percentage_ascii"] > 90:
                TLog.success(
                    "Found good baud rate {} with {}% ASCII data".format(
                        best["baud_rate"], best["percentage_ascii"]))
                return

            TLog.generic(
                "Baud rate {} has max. ASCII percentage of {} %".format(
                    best["baud_rate"], best["percentage_ascii"]))
        except:  # noqa: E722
            reason = "Exception caught: {}".format(sysexcinfo())
        self.result.setstatus(passed=False, reason=reason)
Example #12
0
    def main(cls):
        """
        Run a single command given on the command line or run the main command
        loop of the console if no command line arguments given.

        :return:
        """
        TLog.init()

        parser = argparse.ArgumentParser(
            description="Expliot - Internet Of Things Security Testing and "
            "Exploitation Framework Command Line Interface.")

        parser.add_argument(
            "cmd",
            nargs="?",
            help="Command to execute. If no command is given, it enters an "
            "interactive console. To see the list of available commands "
            "use the help command",
        )
        parser.add_argument(
            "cmd_args",
            nargs=argparse.REMAINDER,
            help="Sub-command and/or (optional) arguments",
        )

        args = parser.parse_args()

        if args.cmd:
            # Execute a single command and exit
            cls.cli.onecmd_plus_hooks("{} {}".format(args.cmd,
                                                     " ".join(args.cmd_args)))
        else:
            # No command line argument specified, drop into interactive mode
            cls.cli.cmdloop()
Example #13
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)
Example #14
0
    def execute(self):
        """Execute the test."""
        sock_tcp = None
        try:
            # Step 1 : Connect to socket host:port
            sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock_tcp.connect((self.args.rhost, self.args.rport))

            # Step 2 : Send encrypted data and save response
            data = crypto.encrypt(self.args.data)
            sock_tcp.settimeout(10.0)
            sock_tcp.send(data)
            data_tp = sock_tcp.recv(2048)
            # Step 3 : Check for Empty or no response
            if not data_tp:
                self.result.setstatus(passed=False,
                                      reason="Empty or no response received")
            else:
                # Step 4 : Convert bytes array to hex string
                data_tp = "".join(map(chr, list(data_tp)))
                data_tp = [hex(ord(b))[2:] for b in list(data_tp)]
                data_tp = [i if len(i) == 2 else "0" + i for i in data_tp]
                data_tp = "".join(data_tp)
                # Step 5 : Decrypt the hex string
                decrypted = crypto.decrypt(data_tp)
                self.output_handler(response_raw=data_tp, response_decrypted=decrypted)
                jsondata = json.loads(decrypted)
                # Step 6 : Check for reason of failture
                if jsondata.get("system") and \
                        jsondata.get("system").get("err_msg"):
                    reason = jsondata.get("system").get("err_msg")
                    self.result.setstatus(passed=False, reason=reason)
                elif jsondata.get("system") and \
                        not jsondata.get("system").get("err_msg") and \
                        jsondata.get("system").get("set_relay_state") and \
                        jsondata.get("system").get("set_relay_state").get("err_msg"):
                    reason = jsondata.get("system").get("set_relay_state").get("err_msg")
                    self.result.setstatus(passed=False, reason=reason)
                elif jsondata.get("system") and \
                        not jsondata.get("system").get("err_msg") and \
                        jsondata.get("system").get("set_relay_state") and \
                        not jsondata.get("system").get("set_relay_state").get("err_msg"):

                    TLog.success("Json data successfully received by the device.")
                else:
                    self.result.setstatus(passed=False, reason="Invalid Response")
        except socket.timeout:
            self.result.setstatus(passed=False, reason="Connection timed out")
        except socket.error:
            self.result.setstatus(
                passed=False,
                reason="Could not connect to host {}:{}".format(
                    self.args.rhost,
                    str(self.args.rport)
                )
            )
        finally:
            if sock_tcp:
                sock_tcp.close()
Example #15
0
 def subcb(cls, client, userdata, message):
     """
     A callback method that is called when the thing
     receives a message on the subscribed topic from
     an AWS IoT endpoint.
     """
     TLog.success("(topic={})(payload={})".format(message.topic,
                                                  message.payload))
Example #16
0
    def notifycb(handle, data):
        """Notification data read callback.

        Args:
            handle (int): The handle of the characteristic whose data is received.
            data (bytes): The data that is received from the BLE device.
        Returns:
            Nothing
        """
        TLog.success(data.hex())
Example #17
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()
Example #18
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)
Example #19
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()
Example #20
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()
Example #21
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()
Example #22
0
File: cmd.py Project: ufwt/expliot
    def execute(self):
        """Execute the test."""

        TLog.success("nmap arguments = ({})".format(self.args.args))
        try:
            nmp = Nmap()
            out, err = nmp.run_xmltodict_output(self.args.args,
                                                timeout=self.args.timeout
                                                or None)
            if err:
                self.result.setstatus(passed=False, reason=err)
            else:
                self.output_handler(**out)
        except:  # noqa: E722
            self.result.exception()
Example #23
0
    def execute(self):
        """Execute the plugin."""

        TLog.generic(
            "Subscribing to topic ({}) on AWS IoT endpoint ({}) on port ({})".
            format(self.args.topic, self.args.rhost, self.args.rport))
        if not self.args.websocket:
            # As of Christmas eve 2019, only two connection types are available
            # 1. TLSv1.2 Mutual Authentication
            #   - X.509 certificate-based secured MQTT connection to AWS IoT
            # 2. Websocket SigV4
            #   - IAM credential-based secured MQTT connection over Websocket
            #      to AWS IoT
            # Source: https://s3.amazonaws.com/aws-iot-device-sdk-python-docs/html/index.html
            if not self.args.privatekey:
                raise FileNotFoundError("Thing Private Key file not specified")
            if not self.args.cert:
                raise FileNotFoundError("Thing Certificate file not specified")
        thing = None
        timer = Timer(self.args.timeout)
        try:
            thing = AwsMqttClient(self.args.id,
                                  useWebsocket=self.args.websocket)
            thing.easy_config(
                host=self.args.rhost,
                port=self.args.rport,
                use_websocket=self.args.websocket,
                rootca=self.args.rootca,
                privatekey=self.args.privatekey,
                cert=self.args.cert,
                user=self.args.user,
                passwd=self.args.passwd,
                timeout=self.args.timeout,
            )
            if self.args.user and self.args.passwd:
                TLog.trydo(
                    "Using authentication (username={})(password={})".format(
                        self.args.user, self.args.passwd))
            thing.connect()
            thing.subscribe(self.args.topic, 1, self.subcb)
            while not timer.is_timeout():
                sleep(1)
        except:  # noqa: E722
            self.result.exception()
        finally:
            if thing:
                thing.easy_disconnect()
Example #24
0
    def check_baud(self, baud):
        """
        Scan a serial connection for ASCII data with a given baud rate.

        :param baud: The baud rate to use for the serial connection
        :return: Percentage of ASCII characters present in the received data
        """
        sock = None
        output = {
            "baud": baud,
            "ascii_percent": -1,
            "received_data": None,
            "ascii_data": None,
            "status": None,
            "exception": None
        }
        TLog.trydo("Checking baud rate: {}".format(baud))
        try:
            sock = Serial(self.args.port, baud, timeout=self.args.timeout)
            output["received_data"] = sock.read(self.args.count)
            sock.flush()
            output["ascii_data"] = "".join([
                chr(entry) for entry in output["received_data"]
                if chr(entry) in string.printable
            ])
            received_length = len(output["received_data"])
            ascii_length = len(output["ascii_data"])
            if received_length == 0:
                output["status"] = "No data received"
                TLog.fail("\t{}".format(output["status"]))
            else:
                output["status"] = "Data received"
                output["ascii_percent"] = round(
                    ascii_length / received_length * 100, 2)
                if self.args.verbose:
                    TLog.success("\tdata: {}, ASCII: {}".format(
                        output["received_data"], output["ascii_data"]))
                TLog.success("\tASCII ratio: {}/{}, {} %".format(
                    ascii_length, received_length, output["ascii_percent"]))
        except:  # noqa: E722
            output["exception"] = sysexcinfo()
            TLog.fail("\tError: {}".format(output["exception"]))
        finally:
            if sock:
                sock.close()
            self.output_handler(logkwargs=LOGNO, **output)
        return output["ascii_percent"]
Example #25
0
 def execute(self):
     """Execute the test."""
     TLog.generic("Sending GET request for URI Path ({}) "
                  "to CoAP Server {} on port {}".format(
                      self.args.path, self.args.rhost, self.args.rport))
     try:
         client = CoapClient(self.args.rhost, port=self.args.rport)
         response = client.get(path=self.args.path)
         if not response.code.is_successful():
             self.result.setstatus(passed=False,
                                   reason="Error Response: {}".format(
                                       CoapClient.response_dict(response)))
             return
         self.output_handler(response_code=int(response.code),
                             response_code_str=str(response.code),
                             response_payload=response.payload)
     except:  # noqa: E722
         self.result.exception()
Example #26
0
    def execute(self):
        TLog.generic(
            "Writing data to i2c eeprom at address({}) using device({})".
            format(self.args.addr, self.args.url))
        d = None
        f = None
        try:
            stime = None
            etime = None
            data = None
            saddr = self.args.addr
            if self.args.rfile:
                TLog.trydo("Reading data from the file ({})".format(
                    self.args.rfile))
                f = open(self.args.rfile, "r+b")
                data = f.read()
                f.close()
            elif self.args.data:
                data = bytes.fromhex(self.args.data)
            else:
                raise AttributeError(
                    "Specify either --data or --rfile (but not both)")

            d = I2cEepromManager.get_flash_device(self.args.url,
                                                  self.args.chip,
                                                  address=self.slaveaddr)
            TLog.success("(chip size={} bytes)".format(len(d)))

            ln = len(data)
            TLog.trydo("Writing {} byte(s) at start address {}".format(
                ln, saddr))
            if self.args.addr + ln > len(d):
                raise IndexError("Length is out of range of the chip size")
            stime = time()
            d.write(saddr, data)
            etime = time()
            TLog.success(
                "wrote {} byte(s) of data from address {}. Time taken {} secs".
                format(len(data), saddr, round(etime - stime, 2)))
        except:
            self.result.exception()
        finally:
            I2cEepromManager.close(d)
Example #27
0
    def on_msg(client, userdata, message):
        """
        Custom on_message callback for MqttClient. It just logs the topic
        and the message received.

        Args:
            client (MqttClient) - The MQTT client object. This is not
                used as it is the same as self.
            userdata (caller defined): Callback specific data passed in
                __init__(). This is not used as we use self members to
                pass information.
            message (MQTTMessage): Contains topic, payload, qos, retain
                for the message received from the broker.

        Returns:
            Nothing.
        """
        TLog.success("(topic={})(payload={})".format(message.topic,
                                                     message.payload))
Example #28
0
    def execute(self):
        c = ModbusTcpClient(self.args.rhost, port=self.args.rport)
        try:
            # Check what to write to i.e. coils, registers etc
            if self.args.item < 0 or self.args.item >= len(self.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(
                self.ITEMS[self.args.item], self.args.address, self.args.count,
                self.args.unit))
            c.connect()
            if self.args.item == self.COIL:
                val = True if self.args.value != 0 else False
                TLog.trydo("Writing value(s) ({})".format(val))
                # below r = class pymodbus.bit_write_message.WriteMultipleCoilsResponse
                r = c.write_coils(self.args.address, [val] * self.args.count,
                                  unit=self.args.unit)
                if r.isError() == True:
                    raise Exception(str(r))
            elif self.args.item == self.REG:
                TLog.trydo("Writing value(s) ({})".format(self.args.value))
                # below r = class pymodbus.register_write_message.WriteMultipleRegistersResponse
                r = c.write_registers(self.args.address,
                                      [self.args.value] * self.args.count,
                                      unit=self.args.unit)
                if r.isError() == True:
                    raise Exception(str(r))
            else:
                raise AttributeError("Unknown --item specified ({})".format(
                    self.args.item))
            TLog.success("Values successfully written")
        except:
            self.result.exception()
        finally:
            c.close()
Example #29
0
    def unlock(self, mac):
        """
        Unlock the specified Tapplock.

        :param mac: The BLE address of the Tapplock
        :return:
        """
        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)
            TLog.trydo("Sending pair data({})".format(pairing_data))
            device.writeCharacteristic(self.UNLOCKHNDL,
                                       bytes.fromhex(pairing_data))
            TLog.trydo("Sending unlock command({})".format(self.UNLOCKCMD))
            device.writeCharacteristic(self.UNLOCKHNDL,
                                       bytes.fromhex(self.UNLOCKCMD))
        finally:
            device.disconnect()
Example #30
0
    def execute(self):
        """Execute the test."""
        TLog.generic(
            "Writing data to i2c eeprom at address({}) using device({})".
            format(self.args.addr, self.args.url))
        device = None
        try:
            start_address = self.args.addr
            if self.args.rfile:
                TLog.trydo("Reading data from the file ({})".format(
                    self.args.rfile))
                input_file = open(self.args.rfile, "r+b")
                data = input_file.read()
                input_file.close()
            elif self.args.data:
                data = bytes.fromhex(self.args.data)
            else:
                raise AttributeError(
                    "Specify either --data or --rfile (but not both)")

            device = I2cEepromManager.get_flash_device(self.args.url,
                                                       self.args.chip,
                                                       address=self.slaveaddr)
            TLog.success("(chip size={} bytes)".format(len(device)))

            length_data = len(data)
            TLog.trydo("Writing {} byte(s) at start address {}".format(
                length_data, start_address))
            if self.args.addr + length_data > len(device):
                raise IndexError("Length is out of range of the chip size")
            start_time = time()
            device.write(start_address, data)
            end_time = time()
            TLog.success(
                "wrote {} byte(s) of data from address {}. Time taken {} secs".
                format(len(data), start_address, round(end_time - start_time,
                                                       2)))
        except:  # noqa: E722
            self.result.exception()
        finally:
            I2cEepromManager.close(device)