예제 #1
0
파일: test.py 프로젝트: emanonchen/ICSwiki
    def exception(self):
        """Set passed to False and reason to the exception message.

        :return:
        """
        self.passed = False
        self.reason = "Exception caught: [{}]".format(sysexcinfo())
예제 #2
0
    def execute(self):
        """Execute the test."""

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

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

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

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

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

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

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

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

                if packetcount == count:
                    break

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

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

            # Turn OFF radio sniffer and exit
            if radio:
                # Execution Done
                self.output_handler(
                    packets_received=radio.get_received_packets())
                radio.sniffer_off()
예제 #3
0
    def execute(self):
        """Execute the test."""
        dst_pan = None
        send_packet = False
        pcap_reader = None
        radio = None

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

        delay_sec = self.args.delay / 1000

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

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

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

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

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

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

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

            # Turn OFF radio and exit
            if radio:
                self.output_handler(
                    packets_received=radio.get_received_packets(),
                    packets_transmitted=radio.get_transmitted_packets())
                radio.radio_off()
예제 #4
0
파일: baudscan.py 프로젝트: ufwt/expliot
    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)
예제 #5
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"
예제 #6
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"
예제 #7
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)
예제 #8
0
    def execute(self):
        """
        Execute the plugin.
        Enumerate the services and/or characteristics of the specified BLE device.

        Returns:
            Nothing
        """
        # Documentation is wrong, the first keyword argument is deviceAddr instead of
        # deviceAddress. http://ianharvey.github.io/bluepy-doc/
        if self.args.services is False and self.args.chars is False:
            reason = "Incomplete args. Enumerate what? Either or both - services, chars"
            self.result.setstatus(passed=False, reason=reason)
            return
        TLog.generic(
            "Enumerating services/characteristics of the device {}".format(
                self.args.addr
            )
        )
        device = BlePeripheral()
        try:
            device.connect(
                self.args.addr,
                addrType=(
                    ADDR_TYPE_RANDOM
                    if self.args.randaddrtype
                    else ADDR_TYPE_PUBLIC
                ),
            )
            if self.args.services is True:
                services = device.getServices()
                for service in services:
                    self.output_handler(service_uuid=str(service.uuid),
                                        service_uuid_name=service.uuid.getCommonName(),
                                        handle_start=hex(service.hndStart),
                                        handle_end=hex(service.hndEnd))
            if self.args.chars is True:
                chars = device.getCharacteristics()
                for char in chars:
                    chardict = {"char_uuid": str(char.uuid),
                                "char_uuid_name": char.uuid.getCommonName(),
                                "handle": hex(char.getHandle()),
                                "supported_properties": char.propertiesToString()}
                    if char.supportsRead():
                        chardict["readvalue"] = char.read()
                    self.output_handler(**chardict)
        except:  # noqa: E722
            self.result.setstatus(passed=False,
                                  reason="Exception caught: {}".format(sysexcinfo()))
        finally:
            device.disconnect()
예제 #9
0
파일: baudscan.py 프로젝트: ufwt/expliot
    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"]
예제 #10
0
    def enumerate(self):
        """
        Enumerate the services and/or characteristsics of the specified BLE device

        :return:
        """
        # documentation is wrong, the first keyword argument is deviceAddr instead of deviceAddress as per the doc
        # Doc: 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))
        d = BlePeripheral()
        try:
            d.connect(self.args.addr,
                      addrType=(Ble.ADDR_TYPE_RANDOM if self.args.randaddrtype
                                else Ble.ADDR_TYPE_PUBLIC))
            self.found = True
            if self.args.services is True:
                svcs = d.getServices()
                for s in svcs:
                    TLog.success(
                        "(service uuid={})(handlestart={})(handleend={})".
                        format(s.uuid, hex(s.hndStart), hex(s.hndEnd)))
            if self.args.chars is True:
                chrs = d.getCharacteristics()
                for c in chrs:
                    TLog.success("(characteristic uuid={})(handle={})".format(
                        c.uuid, hex(c.getHandle())))
                    if self.args.verbose is True:
                        sr = c.supportsRead()
                        TLog.success("    (supports_read={})".format(sr))
                        if sr is True:
                            TLog.success("    (value={})".format(c.read()))
        except:
            self.reason = "Exception caught: {}".format(sysexcinfo())
        finally:
            d.disconnect()
        if self.found is False and self.reason is None:
            self.reason = "Couldnt find any devices"
예제 #11
0
    def execute(self):
        """
        Execute the plugin.
        Scan for BLE devices in the proximity.

        Returns:
            Nothing
        """
        found = False
        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:
                found = True
                outdict = {
                    "name": device.getValueText(Ble.ADTYPE_NAME) or "Unknown",
                    "addr": device.addr,
                    "addrtype": device.addrType,
                    "rssi": "{} dBm".format(device.rssi),
                    "connectable": device.connectable,
                    "adtype_data": []
                }
                for scan_data in device.getScanData():
                    outdict["adtype_data"].append({
                        "adtype": scan_data[0],
                        "description": scan_data[1],
                        "value": scan_data[2]
                    })
                self.output_handler(**outdict)
        except:  # noqa: E722
            self.result.setstatus(passed=False,
                                  reason="Exception caught: {}".format(
                                      sysexcinfo()))

        if found is False:
            TLog.fail("No BLE devices found")
예제 #12
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
        percentage_ascii = -1
        TLog.success("Checking baud rate: {}".format(baud))
        try:
            sock = Serial(self.args.port, baud, timeout=self.args.timeout)
            received = sock.read(self.args.count)
            sock.flush()
            ascii_data = "".join([
                chr(entry) for entry in received
                if chr(entry) in string.printable
            ])
            received_length = len(received)
            ascii_length = len(ascii_data)
            if received_length == 0:
                TLog.fail("\tNo data received")
            else:
                percentage_ascii = round(ascii_length / received_length * 100,
                                         2)
                if self.args.verbose:
                    TLog.success("\tdata: {}, ASCII: {}".format(
                        received, ascii_data))
                TLog.success("\tASCII ratio: {}/{}, {} %".format(
                    ascii_length, received_length, percentage_ascii))
        except:  # noqa: E722
            TLog.fail("\tError: {}".format(sysexcinfo()))
        finally:
            if sock:
                sock.close()
        return percentage_ascii
예제 #13
0
    def execute(self):
        """Execute the test."""
        if self.args.start < 11 or self.args.start > 26:
            self.result.setstatus(passed=False, reason="Invalid start channel")
            return

        if self.args.end < 11 or self.args.end > 26:
            self.result.setstatus(passed=False, reason="Invalid end channel")
            return

        if self.args.end < self.args.start:
            self.result.setstatus(passed=False,
                                  reason="Invalid start or end channel")
            return

        if self.args.filepath is not None:
            self.filename = self.args.filepath

        # Print user input
        TLog.generic("{:<13}: ({})".format("Start channel", self.args.start))
        TLog.generic("{:<13}: ({})".format("End channel", self.args.end))
        if self.filename is not None:
            TLog.generic("{:<13}: ({})".format("Log file", self.filename))

        TLog.generic("")

        # get channel mask
        ch_mask = self.get_channel_mask()

        try:
            # Get Network Scanner
            nwkscanner = ZigbeeNetworkScan()

            # Capture the scan start time
            start_time = time.time()

            # Start network scan with channel mask
            result_dict = nwkscanner.scan(ch_mask)

            # Capture the scan start time
            end_time = time.time()

            if result_dict is not None:
                self.found = True
                self.output_handler(logkwargs=LOGNO, **result_dict)
                # Display result on console
                self.display_scan_result(result_dict)

                TLog.success("{:<17} {}".format("Scan duration",
                                                end_time - start_time))
                TLog.generic("")

                # Write result in log file
                if self.filename is not None:
                    self.write_result_to_logfile(result_dict)
            else:
                self.found = False
                self.reason = "Couldn't find any Zigbee device on network"

        except:  # noqa: E722
            self.found = False
            self.reason = "Exception caught: {}".format(sysexcinfo())

        finally:
            self.result.setstatus(passed=self.found, reason=self.reason)