Ejemplo n.º 1
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)
Ejemplo n.º 2
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()
Ejemplo n.º 3
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")
Ejemplo n.º 4
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")
Ejemplo n.º 5
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)
Ejemplo n.º 6
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()
Ejemplo n.º 7
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()
Ejemplo n.º 8
0
 def execute(self):
     """Execute the test."""
     TLog.generic(
         "Connecting to the the serial port ({}) with baud ({})".format(
             self.args.port, self.args.baud))
     TLog.generic("Using chars({}) and length({})".format(
         self.args.chars, self.args.length))
     found = False
     reason = "Couldn't find a valid command"
     commands = []
     tries = 0
     sock = None
     try:
         sock = Serial(self.args.port,
                       self.args.baud,
                       timeout=self.args.timeout)
         for word in itertools.product(self.args.chars,
                                       repeat=self.args.length):
             cmd = self.args.prefix + "".join(word) + self.args.append
             sock.write(cmd.encode())
             received_data = sock.readfull(self.args.buffsize)
             sock.flush()
             tries += 1
             if tries % 20 == 0:
                 # Print something to engage the user :)
                 TLog.generic("Tried {} commands till now".format(tries))
             if self.args.verbose is True:
                 TLog.trydo("Command=({}) response({})".format(
                     cmd.rstrip(), received_data))
             if self.args.match is not None:
                 if self.args.match.lower() in received_data.decode().lower(
                 ):
                     TLog.success(
                         "Command=({}) found. --match criteria in Response=({})"
                         .format(cmd.rstrip(), received_data))
                     found = True
                     commands.append(cmd.rstrip())
                     if self.args.stop is True:
                         break
             elif self.args.nomatch is not None:
                 if self.args.nomatch.lower() not in received_data.decode(
                 ).lower():
                     TLog.success(
                         "Command=({}) found. --nomatch criteria in response=({})"
                         .format(cmd.rstrip(), received_data))
                     found = True
                     commands.append(cmd.rstrip())
                     if self.args.stop is True:
                         break
     except:  # noqa: E722
         reason = "Exception caught: {}".format(sysexcinfo())
     finally:
         if sock:
             sock.close()
     if found is True:
         TLog.success("Valid commands found: ({})".format(commands))
     else:
         self.result.setstatus(passed=False, reason=reason)
Ejemplo n.º 9
0
    def execute(self):
        """Execute the test."""
        TLog.generic(
            "Attempting to send file ({}) to DICOM server ({}) on port ({})".
            format(self.args.file, self.args.rhost, self.args.rport))
        TLog.generic("Using Calling AET ({}) Called AET ({})".format(
            self.args.aetscu, self.args.aetscp))
        file = None
        assoc = None
        try:
            app_entity = AE(ae_title=self.args.aetscu)
            app_entity.requested_contexts = StoragePresentationContexts
            input_file = open(self.args.file, "rb")
            dataset = dcmread(input_file, force=True)

            # 0 means assign random port in pynetdicom
            if self.args.lport != 0:
                TLog.generic("Using source port number ({})".format(
                    self.args.lport))
                if (self.args.lport < 1024) and (os.geteuid() != 0):
                    TLog.fail("Oops! Need to run as root for privileged port")
                    raise ValueError(
                        "Using privileged port ({}) without root privileges".
                        format(self.args.lport))
            assoc = app_entity.associate(
                self.args.rhost,
                self.args.rport,
                bind_address=("", self.args.lport),
                ae_title=self.args.aetscp,
            )
            TLog.trydo("Server implementation version name ({})".format(
                assoc.acceptor.implementation_version_name))
            TLog.trydo("Server implementation class UID ({})".format(
                assoc.acceptor.implementation_class_uid))
            if assoc.is_established:
                status = assoc.send_c_store(dataset)
                if status.Status == 0x0000:
                    TLog.success("C-STORE Success (status=0x{0:04x})".format(
                        status.Status))
                else:
                    reason = "C-STORE Failed to store file (status=0x{0:04x})".format(
                        status.Status)
                    TLog.fail(reason)
                    self.result.setstatus(passed=False, reason=reason)
            else:
                self.result.setstatus(
                    passed=False,
                    reason="Could not establish association with the server",
                )
        except:  # noqa: E722
            self.result.exception()
        finally:
            if assoc:
                assoc.release()
            if file:
                file.close()
Ejemplo n.º 10
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()
Ejemplo n.º 11
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")))
Ejemplo n.º 12
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()
Ejemplo n.º 13
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"]
Ejemplo n.º 14
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()
Ejemplo n.º 15
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)
Ejemplo n.º 16
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()
Ejemplo n.º 17
0
 def execute(self):
     """Execute the test."""
     TLog.generic(
         "Reading data from SPI flash at address({}) using device ({})".format(
             self.args.addr, self.args.url
         )
     )
     device = None
     try:
         device = SpiFlashManager.get_flash_device(
             self.args.url, freq=self.args.freq
         )
         length = self.args.length or (len(device) - self.args.addr)
         TLog.success(
             "(chip found={})(chip size={} bytes)(using frequency={})".format(
                 device, len(device), int(device.spi_frequency)
             )
         )
         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))
             local_file = open(self.args.wfile, "w+b")
             data.tofile(local_file)
             local_file.close()
         else:
             TLog.success("(data={})".format([hex(x) for x in data]))
         TLog.success(
             "Done. Total bytes read ({}) Time taken to read = {} s".format(
                 len(data), round(end_time - start_time, 2)
             )
         )
     except:  # noqa: E722
         self.result.exception()
     finally:
         SpiFlashManager.close(device)
Ejemplo n.º 18
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)
Ejemplo n.º 19
0
 def execute(self):
     """Execute the test."""
     TLog.generic(
         "Reading data from SPI flash at address({}) using device ({})".format(
             self.args.addr, self.args.url
         )
     )
     device = None
     try:
         device = SpiFlashManager.get_flash_device(
             self.args.url, freq=self.args.freq
         )
         length = self.args.length or (len(device) - self.args.addr)
         self.output_handler(chip=device, size=len(device),
                             frequency=int(device.spi_frequency))
         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))
             local_file = open(self.args.wfile, "w+b")
             data.tofile(local_file)
             local_file.close()
         else:
             self.output_handler(msg="data: {}".format([hex(x) for x in data]),
                                 logkwargs=LOGNO,
                                 data=data)
         self.output_handler(bytes_read=len(data),
                             time_taken_secs=round(end_time - start_time, 2))
     except:  # noqa: E722
         self.result.exception()
     finally:
         SpiFlashManager.close(device)
Ejemplo n.º 20
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.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:
             self.output_handler(msg="data: {}".format(
                 [hex(x) for x in data]),
                                 logkwargs=LOGNO,
                                 data=data)
         self.output_handler(chip_size=len(device),
                             bytes_read=len(data),
                             time_taken_secs=round(end_time - start_time,
                                                   2))
     except:  # noqa: E722
         self.result.exception()
     finally:
         I2cEepromManager.close(device)
Ejemplo n.º 21
0
    def execute(self):
        """Execute the mDNS discovery."""

        service_names = list(MDNS_SERVICE_TYPES)
        if self.args.list:
            TLog.trydo("Supported Device types")
            for name in service_names:
                TLog.success("{}".format(name))
            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
                TLog.success("Device {}".format(cnt))
                TLog.success("  (name={})".format(device.name))
                TLog.success("  (address={})".format(device.address))
                TLog.success("  (port={})".format(device.port))
                TLog.success("  (server={})".format(device.server))
                TLog.success("  (type={})".format(device.type))
                TLog.success("  (priority={})".format(device.priority))
                TLog.success("  (weight={})".format(device.weight))
                TLog.success("  (properties={})".format(device.properties))
                TLog.success("")
        TLog.success("Total devices discovered = {}".format(cnt))
Ejemplo n.º 22
0
    def execute(self):
        """Execute the test."""
        TLog.generic(
            "Attempting to connect with DICOM server ({}) on port ({})".format(
                self.args.rhost, self.args.rport))
        TLog.generic("Using Calling AET ({}) Called AET ({})".format(
            self.args.aetscu, self.args.aetscp))

        assoc = None
        try:
            app_entity = AE(ae_title=self.args.aetscu)
            app_entity.requested_contexts = VerificationPresentationContexts

            assoc = app_entity.associate(self.args.rhost,
                                         self.args.rport,
                                         ae_title=self.args.aetscp)
            TLog.trydo("Server implementation version name ({})".format(
                assoc.acceptor.implementation_version_name))
            TLog.trydo("Server implementation class UID ({})".format(
                assoc.acceptor.implementation_class_uid))
            if assoc.is_established:
                data_set = assoc.send_c_echo()
                if data_set:
                    TLog.success("C-ECHO response status (0x{0:04x})".format(
                        data_set.Status))
            else:
                self.result.setstatus(
                    passed=False,
                    reason="Could not establish association with the server",
                )

        except:  # noqa: E722
            self.result.exception()
        finally:
            if assoc:
                assoc.release()
Ejemplo n.º 23
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()
Ejemplo n.º 24
0
    def execute(self):
        TLog.generic(
            "Writing data to spi flash at address({}) using device({})".format(
                self.args.addr, self.args.url))
        d = 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 = SpiFlashManager.get_flash_device(self.args.url,
                                                 freq=self.args.freq)
            TLog.success(
                "(chip found={})(chip size={} bytes)(using frequency={})".
                format(d, len(d), int(d.spi_frequency)))

            ln = len(data)
            eaddr = saddr + ln - 1
            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")
            # We can't write on any arbitrary address for an aritrary length unless it is aligned to the page size
            # Get erase page size, start/end enclosing page addresses and length
            esz = d.get_erase_size()
            spaddr = saddr - saddr % esz
            epaddr = eaddr + esz - (eaddr % esz) - 1
            pln = epaddr - spaddr + 1
            TLog.trydo(
                "Page aligned start address({}) end address({}) lenght({})".
                format(spaddr, epaddr, pln))
            # Backup the data from chip
            stime = time()
            tmpdata = d.read(spaddr, pln)
            etime = time()
            TLog.success(
                "Backed up page aligned {} byte(s) from address {}. Time taken {} secs"
                .format(pln, spaddr, round(etime - stime, 2)))
            tmpdata = tmpdata.tobytes()
            # We can only write on erased data
            # Now erase the enclosing pages (of the start and end addresses)
            d.unlock()
            stime = time()
            d.erase(spaddr, pln)
            etime = time()
            TLog.success(
                "Erased {} byte(s) of data from address {}. Time taken {} secs"
                .format(pln, spaddr, round(etime - stime, 2)))
            # Now overwrite with the updated data i.e. backedup data containing the changes
            wdata = tmpdata[0:saddr % esz] + data + tmpdata[saddr % esz + ln:]
            stime = time()
            d.write(spaddr, wdata)
            etime = time()
            TLog.success(
                "wrote {} byte(s) of data from address {}. Time taken {} secs".
                format(pln, spaddr, round(etime - stime, 2)))
        except:
            self.result.exception()
        finally:
            SpiFlashManager.close(d)
Ejemplo n.º 25
0
    def execute(self):
        """Execute the test."""
        TLog.generic(
            "Writing data to SPI flash 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))
                local_file = open(self.args.rfile, "r+b")
                data = local_file.read()
                local_file.close()
            elif self.args.data:
                data = bytes.fromhex(self.args.data)
            else:
                raise AttributeError(
                    "Specify either --data or --rfile (but not both)")

            device = SpiFlashManager.get_flash_device(self.args.url,
                                                      freq=self.args.freq)
            self.output_handler(chip=device,
                                size=len(device),
                                frequency=int(device.spi_frequency))
            data_length = len(data)
            end_address = start_address + data_length - 1
            TLog.trydo("Writing {} byte(s) at start address {}".format(
                data_length, start_address))
            if self.args.addr + data_length > len(device):
                raise IndexError("Length is out of range of the chip size")
            # We can't write on any arbitrary address for an arbitrary length
            # unless it is aligned to the page size
            # Get erase page size, start/end enclosing page addresses and length
            esz = device.get_erase_size()
            spaddr = start_address - start_address % esz
            epaddr = end_address + esz - (end_address % esz) - 1
            pln = epaddr - spaddr + 1
            TLog.trydo(
                "Page aligned start address({}) end address({}) length({})".
                format(spaddr, epaddr, pln))
            # Backup the data from chip
            start_time = time()
            tmpdata = device.read(spaddr, pln)
            end_time = time()
            self.output_handler(bytes_backedup_page_aligned=pln,
                                from_address=spaddr,
                                time_taken_secs=round(end_time - start_time,
                                                      2))

            # commenting below line as pyspiflash 0.6.3 read() returns bytes instead
            # of ByteArray (array) sept 2020
            # tmpdata = tmpdata.tobytes()
            # We can only write on erased data
            # Now erase the enclosing pages (of the start and end addresses)
            device.unlock()
            start_time = time()
            device.erase(spaddr, pln)
            end_time = time()
            self.output_handler(bytes_erased=pln,
                                from_address=spaddr,
                                time_taken_secs=round(end_time - start_time,
                                                      2))
            # Now overwrite with the updated data i.e. backed up data containing the changes
            wdata = (tmpdata[0:start_address % esz] + data +
                     tmpdata[start_address % esz + data_length:])
            start_time = time()
            device.write(spaddr, wdata)
            end_time = time()
            self.output_handler(bytes_written=pln,
                                from_address=spaddr,
                                time_taken_secs=round(end_time - start_time,
                                                      2))
        except:  # noqa: E722
            self.result.exception()
        finally:
            SpiFlashManager.close(device)
Ejemplo n.º 26
0
 def execute(self):
     """Execute the test."""
     TLog.generic(
         "Attempting to search for patient ({}) on DICOM server ({}) on port ({})"
         .format(self.args.name, self.args.rhost, self.args.rport))
     TLog.generic(
         "Using Calling AET ({}) Called AET ({}) Information model ({})".
         format(self.args.aetscu, self.args.aetscp, self.args.model))
     assoc = None
     try:
         app_entity = AE(ae_title=self.args.aetscu)
         app_entity.requested_contexts = (
             QueryRetrievePresentationContexts +
             BasicWorklistManagementPresentationContexts)
         data_set = Dataset()
         data_set.PatientName = self.args.name
         # May need to move this as cmdline argument for other SOP Class UIDs
         data_set.QueryRetrieveLevel = "PATIENT"
         # 0 means assign random port in pynetdicom
         if self.args.lport != 0:
             TLog.generic("Using source port number ({})".format(
                 self.args.lport))
             if (self.args.lport < 1024) and (os.geteuid() != 0):
                 TLog.fail("Oops! Need to run as root for privileged port")
                 raise ValueError(
                     "Using privileged port ({}) without root privileges".
                     format(self.args.lport))
         assoc = app_entity.associate(
             self.args.rhost,
             self.args.rport,
             bind_address=("", self.args.lport),
             ae_title=self.args.aetscp,
         )
         TLog.trydo("Server implementation version name ({})".format(
             assoc.acceptor.implementation_version_name))
         TLog.trydo("Server implementation class UID ({})".format(
             assoc.acceptor.implementation_class_uid))
         if assoc.is_established:
             responses = assoc.send_c_find(data_set,
                                           query_model=self.args.model)
             if responses:
                 for (status, identifier) in responses:
                     TLog.success("C-FIND query status: (0x{0:04x})".format(
                         status.Status))
                     # As per pynetdicom if status is either of below, then responses contain valid identifier
                     # datasets, else None. Ref: pynetdicom/pynetdicom/apps/findscu/findscu.py
                     if status.Status in (0xFF00, 0xFF01):
                         TLog.success(
                             "C-FIND query Identifier: ({})".format(
                                 identifier))
             else:
                 reason = "Did not receive any response data sets"
                 TLog.fail(reason)
                 self.result.setstatus(passed=False, reason=reason)
         else:
             self.result.setstatus(
                 passed=False,
                 reason="Could not establish association with the server",
             )
     except:  # noqa: E722
         self.result.exception()
     finally:
         if assoc:
             assoc.release()