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

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

        TLog.generic(
            "Reading from Notify handle ({}) on BLE device ({})".format(
                hex(self.args.handle), self.args.addr))
        timer = Timer(self.args.timeout)
        ndelegate = BleNotifyDelegate(self.notifycb)
        device = BlePeripheral()
        try:
            device.connect(
                self.args.addr,
                addrType=(ADDR_TYPE_RANDOM
                          if self.args.randaddrtype else ADDR_TYPE_PUBLIC),
            )
            TLog.generic("Enabling Notify on the handle")
            device.enable_notify(ndelegate,
                                 self.args.handle,
                                 write_response=True)
            while not timer.is_timeout():
                device.waitForNotifications(1)
            if ndelegate.count() > 0:
                TLog.success("Total notification data received {}".format(
                    ndelegate.count()))
            else:
                self.result.setstatus(
                    passed=False,
                    reason="No notification data received from BLE peripheral")
        except:  # noqa: E722
            self.result.exception()
        finally:
            device.disconnect()
Beispiel #9
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")
Beispiel #10
0
 def execute(self):
     """Execute the plugin."""
     TLog.generic(
         "Publishing message on topic ({}) to MQTT Broker ({}) on port "
         "({})".format(self.args.topic, self.args.rhost, self.args.rport))
     try:
         client = MqttClient(client_id=self.args.id)
         client.easy_config(
             user=self.args.user,
             passwd=self.args.passwd,
             on_connect=client.on_connectcb,
             on_publish=client.on_publishcb,
         )
         client.connect(self.args.rhost, self.args.rport)
         client.publish(self.args.topic, self.args.msg, 1)
         client.loop_forever()
         if client.connect_rc != MQTT_ERR_SUCCESS:
             self.result.setstatus(passed=False,
                                   reason=client.rcstr(client.connect_rc))
             TLog.fail("MQTT Connection Failed. Return code ({}:{})".format(
                 client.connect_rc, client.rcstr(client.connect_rc)))
         else:
             TLog.success("Message published")
     except:  # noqa: E722
         self.result.exception()
Beispiel #11
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()
Beispiel #12
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))
Beispiel #13
0
    def execute(self):
        c = ModbusTcpClient(self.args.rhost, port=self.args.rport)
        try:
            values = None
            # Check what to read i.e. coils, holding registers etc
            if self.args.item < 0 or self.args.item >= len(self.ITEMS):
                raise AttributeError("Unknown --item specified ({})".format(
                    self.args.item))

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

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

            TLog.generic(
                "Sending read command to Modbus Server ({}) on port ({})".
                format(self.args.rhost, self.args.rport))
            TLog.generic("(item={})(address={})(count={})(unit={})".format(
                READ_ITEMS[self.args.item],
                self.args.address,
                self.args.count,
                self.args.unit,
            ))
            modbus_client.connect()
            if self.args.item == self.COIL:
                response = modbus_client.read_coils(self.args.address,
                                                    self.args.count,
                                                    unit=self.args.unit)
                if response.isError() is True:
                    raise Exception(str(response))
                values = response.bits
            elif self.args.item == self.DINPUT:
                response = modbus_client.read_discrete_inputs(
                    self.args.address, self.args.count, unit=self.args.unit)
                if response.isError() is True:
                    raise Exception(str(response))
                values = response.bits
            elif self.args.item == self.HREG:
                response = modbus_client.read_holding_registers(
                    self.args.address, self.args.count, unit=self.args.unit)
                if response.isError() is True:
                    raise Exception(str(response))
                values = response.registers
            elif self.args.item == self.IREG:
                response = modbus_client.read_input_registers(
                    self.args.address, self.args.count, unit=self.args.unit)
                if response.isError() is True:
                    raise Exception(str(response))
                values = response.registers
            else:
                raise AttributeError("Unknown --item specified ({})".format(
                    self.args.item))
            for entry in range(0, self.args.count):
                TLog.success("({}[{}]={})".format(
                    READ_ITEMS[self.args.item],
                    self.args.address + entry,
                    values[entry],
                ))
        except:  # noqa: E722
            self.result.exception()
        finally:
            modbus_client.close()
Beispiel #16
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()
Beispiel #17
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())
Beispiel #18
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()
Beispiel #19
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"
Beispiel #20
0
    def enumerate(self):
        """
        Enumerate the services and/or characteristics of the specified BLE device.

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

        TLog.generic(
            "Enumerating services/characteristics of the device {}".format(
                self.args.addr
            )
        )
        device = BlePeripheral()
        try:
            device.connect(
                self.args.addr,
                addrType=(
                    ADDR_TYPE_RANDOM
                    if self.args.randaddrtype
                    else ADDR_TYPE_PUBLIC
                ),
            )
            self.found = True
            if self.args.services is True:
                services = device.getServices()
                for service in services:
                    TLog.success(
                        "(service uuid={})(handlestart={})(handleend={})".format(
                            service.uuid, hex(service.hndStart), hex(service.hndEnd)
                        )
                    )
            if self.args.chars is True:
                chars = device.getCharacteristics()
                for char in chars:
                    TLog.success(
                        "(characteristic uuid={})(handle={})".format(
                            char.uuid, hex(char.getHandle())
                        )
                    )
                    if self.args.verbose is True:
                        support_property = char.propertiesToString()
                        supports_read = char.supportsRead()
                        TLog.success("    (supported_properties={})".format(support_property))
                        if supports_read is True:
                            TLog.success("    (value={})".format(char.read()))
        except:  # noqa: E722
            self.reason = "Exception caught: {}".format(sysexcinfo())
        finally:
            device.disconnect()
        if self.found is False and self.reason is None:
            self.reason = "Couldn't find any devices"
Beispiel #21
0
    def execute(self):
        """Execute the UPNP discovery."""

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

        for dev in scanner.devices():
            count += 1
            TLog.generic("")
            TLog.success("Device {}:".format(count))
            self.output_handler(logkwargs=LOGNO, **dev)
            recurse_list_dict(dev, self.log_callback, None)
        self.output_handler(total_devices_discovered=count)
Beispiel #22
0
    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()
Beispiel #23
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"]
Beispiel #24
0
    def execute(self):
        """Execute the test."""

        TLog.generic(
            "Publishing message on topic ({}) to 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
        try:
            thing = AwsMqttClient(self.args.id,
                                  use_websocket=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.publish(self.args.topic, self.args.msg, 1)
            TLog.success("Message ({}) published on topic ({})".format(
                self.args.msg, self.args.topic))
        except:  # noqa: E722
            self.result.exception()
        finally:
            if thing:
                thing.easy_disconnect()
Beispiel #25
0
 def execute(self):
     """Execute the test."""
     try:
         if self.args.addr:
             TLog.generic(
                 "Tapplock BLE Address specified ({})".format(self.args.addr)
             )
             self.unlock(self.args.addr)
         else:
             TLog.generic("Scanning for Tapplocks...")
             devices = Ble.scan(iface=self.args.iface, tout=self.args.timeout)
             for device in devices:
                 name = device.getValueText(Ble.ADTYPE_NAME)
                 if name is not None and name[0:6] == self.TNAMEPREFIX:
                     TLog.success("Found Tapplock")
                     self.unlock(device.addr, name=name)
     except:  # noqa: E722
         self.result.exception()
Beispiel #26
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))
Beispiel #27
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)
Beispiel #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()
Beispiel #29
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)
Beispiel #30
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)