Exemplo n.º 1
0
    def Request(self, functionId, data=''):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(self.timeout)

        sock.connect((self.ip,self.port))

        sock.send(ModbusPacket(0, self.uid, functionId, data).pack())

        if debug_mode:
            print "\n------------------send package:"
            print hexdump(ModbusPacket(0, self.uid, functionId, data).pack())

        reply = sock.recv(1024)

        if debug_mode:
            print "\n------------------recv package:"
            print hexdump(reply)

        if not reply:
            raise ModbusError(0)

        response = ModbusPacket().unpack(reply)

        if response.unitId != self.uid:
            raise ModbusProtocolError('Unexpected unit ID or incorrect packet', reply)

        if response.functionId != functionId:
            raise ModbusError(ord(response.data[0]))

        return response.data
Exemplo n.º 2
0
    def Request(self, functionId, data=''):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(self.timeout)

        sock.connect((self.ip, self.port))

        sock.send(ModbusPacket(0, self.uid, functionId, data).pack())

        if debug_mode:
            print "\n------------------send package:"
            print hexdump(ModbusPacket(0, self.uid, functionId, data).pack())

        reply = sock.recv(1024)

        if debug_mode:
            print "\n------------------recv package:"
            print hexdump(reply)

        if not reply:
            raise ModbusError(0)

        response = ModbusPacket().unpack(reply)

        if response.unitId != self.uid:
            raise ModbusProtocolError('Unexpected unit ID or incorrect packet',
                                      reply)

        if response.functionId != functionId:
            raise ModbusError(ord(response.data[0]))

        return response.data
Exemplo n.º 3
0
    def connect(self, hwaddr):
        p = (
            bluetooth.HCI_Hdr()
            / bluetooth.HCI_Command_Hdr(opcode=0x200d)
            / bluetooth.HCI_Cmd_LE_Create_Connection(
                interval=96,
                window=48,
                filter=0,
                patype=1,
                paddr=hwaddr,
                atype=1,
                min_interval=24,
                max_interval=40,
                latency=0,
                timeout=500,
                min_ce=0,
                max_ce=0,
            )
        )
        self._send(p)
        while True:
            p = self.socket.recv()
            if self.debug:
                hexdump(p)

            if p.type == 4:
                if p.code == 0x3e and p.event == 1 and p.status == 0:
                    if self.debug:
                        print(f"Connected with handle {p.handle}")
                    self.connection_handle = p.handle
                    return
Exemplo n.º 4
0
Arquivo: demo.py Projeto: lt90s/Python
    def show_pkt(pkt):
        from scapy.layers import inet, l2
        from scapy.utils import hexdump
        payload = pkt.get_payload()
        ip = inet.IP(payload)
        print '%s to %s' %(ip.src, ip.dst)
        hexdump(ip)
#pkt.drop()
        pkt.accept()
Exemplo n.º 5
0
 def hexdump(self, lfilter=None):
     """Same as nsummary(), except that packets are also hexdumped
     lfilter: a truth function that decides whether a packet must be displayed"""
     for i, res in enumerate(self.res):
         p = self._elt2pkt(res)
         if lfilter is not None and not lfilter(p):
             continue
         print "%s %s %s" % (conf.color_theme.id(
             i, fmt="%04i"), p.sprintf("%.time%"), self._elt2sum(res))
         hexdump(p)
Exemplo n.º 6
0
 def padding(self, lfilter=None):
     """Same as hexraw(), for Padding layer"""
     for i, res in enumerate(self.res):
         p = self._elt2pkt(res)
         if p.haslayer(conf.padding_layer):
             if lfilter is None or lfilter(p):
                 print "%s %s %s" % (conf.color_theme.id(
                     i,
                     fmt="%04i"), p.sprintf("%.time%"), self._elt2sum(res))
                 hexdump(p.getlayer(conf.padding_layer).load)
Exemplo n.º 7
0
 def padding(self, lfilter=None):
     """Same as hexraw(), for Padding layer"""
     for i, res in enumerate(self.res):
         p = self._elt2pkt(res)
         if p.haslayer(conf.padding_layer):
             if lfilter is None or lfilter(p):
                 print "%s %s %s" % (conf.color_theme.id(i,fmt="%04i"),
                                     p.sprintf("%.time%"),
                                     self._elt2sum(res))
                 hexdump(p.getlayer(conf.padding_layer).load)
Exemplo n.º 8
0
 def hexdump(self, lfilter=None):
     """Same as nsummary(), except that packets are also hexdumped
     lfilter: a truth function that decides whether a packet must be displayed"""
     for i, res in enumerate(self.res):
         p = self._elt2pkt(res)
         if lfilter is not None and not lfilter(p):
             continue
         print "%s %s %s" % (conf.color_theme.id(i,fmt="%04i"),
                             p.sprintf("%.time%"),
                             self._elt2sum(res))
         hexdump(p)
Exemplo n.º 9
0
def ppp(headline, packet):
    """ Return string containing the output of scapy packet.show() call. """
    o = StringIO()
    old_stdout = sys.stdout
    sys.stdout = o
    print(headline)
    hexdump(packet)
    print("")
    packet.show()
    sys.stdout = old_stdout
    return o.getvalue()
Exemplo n.º 10
0
 def hexraw(self, lfilter=None):
     """Same as nsummary(), except that if a packet has a Raw layer, it will be hexdumped
     lfilter: a truth function that decides whether a packet must be displayed"""
     for i, res in enumerate(self.res):
         p = self._elt2pkt(res)
         if lfilter is not None and not lfilter(p):
             continue
         print "%s %s %s" % (conf.color_theme.id(
             i, fmt="%04i"), p.sprintf("%.time%"), self._elt2sum(res))
         if p.haslayer(conf.raw_layer):
             hexdump(p.getlayer(conf.raw_layer).load)
Exemplo n.º 11
0
 def hexraw(self, lfilter=None):
     """Same as nsummary(), except that if a packet has a Raw layer, it will be hexdumped
     lfilter: a truth function that decides whether a packet must be displayed"""
     for i, res in enumerate(self.res):
         p = self._elt2pkt(res)
         if lfilter is not None and not lfilter(p):
             continue
         print "%s %s %s" % (conf.color_theme.id(i,fmt="%04i"),
                             p.sprintf("%.time%"),
                             self._elt2sum(res))
         if p.haslayer(conf.raw_layer):
             hexdump(p.getlayer(conf.raw_layer).load)
Exemplo n.º 12
0
    def return_info(self):
        """Returns an information request response"""
        self.logger.debug("Returning information request")

        info_clients = []
        for client in list(self.server.clients.values()):
            info_client = SAPRouterInfoClient(id=client.id)
            info_client.address = client.address
            if client.routed:
                info_client.partner = client.partner
                info_client.service = client.service
            info_client.connected_on = unix_time(client.connected_on)

            info_client.flag_traced = client.traced
            info_client.flag_routed = client.routed
            info_client.flag_connected = client.connected

            info_clients.append(info_client)

        info_clients = "".join([str(client) for client in info_clients])
        info_pkt = Raw(info_clients)
        self.request.send(info_pkt)
        self.session.add_event("Returned information request", response=str(info_pkt))

        __, server_port = self.server.server_address

        info_pkt = SAPRouterInfoServer(pid=self.pid,
                                       ppid=self.parent_pid,
                                       started_on=unix_time(self.time_started),
                                       port=server_port,
                                       pport=self.parent_port)
        hexdump(info_pkt)
        self.request.send(info_pkt)
        self.session.add_event("Returned information request", data={"packet": "info_packet"},
                               response=str(info_pkt))

        info_pkt = Raw("Total no. of clients: %d\x00" % len(self.server.clients))
        self.request.send(info_pkt)
        self.session.add_event("Returned information request", data={"packet": "total_no_clients"},
                               response=str(info_pkt))

        info_pkt = Raw("Working directory   : %s\x00" % self.route_table_working_directory)
        self.request.send(info_pkt)
        self.session.add_event("Returned information request", data={"packet": "working_directory"},
                               response=str(info_pkt))

        info_pkt = Raw("Routtab             : %s\x00" % self.route_table_filename)
        self.request.send(info_pkt)
        self.session.add_event("Returned information request", data={"packet": "routtab"},
                               response=str(info_pkt))

        self.request.close()
Exemplo n.º 13
0
 def nzpadding(self, lfilter=None):
     """Same as padding() but only non null padding"""
     for i, res in enumerate(self.res):
         p = self._elt2pkt(res)
         if p.haslayer(conf.padding_layer):
             pad = p.getlayer(conf.padding_layer).load
             if pad == pad[0]*len(pad):
                 continue
             if lfilter is None or lfilter(p):
                 print "%s %s %s" % (conf.color_theme.id(i,fmt="%04i"),
                                     p.sprintf("%.time%"),
                                     self._elt2sum(res))
                 hexdump(p.getlayer(conf.padding_layer).load)
Exemplo n.º 14
0
 def padding(self, lfilter=None):
     # type: (Optional[Callable[..., bool]]) -> None
     """Same as hexraw(), for Padding layer"""
     for i, res in enumerate(self.res):
         p = self._elt2pkt(res)
         if p.haslayer(conf.padding_layer):
             if lfilter is None or lfilter(p):
                 print("%s %s %s" %
                       (conf.color_theme.id(i, fmt="%04i"),
                        p.sprintf("%.time%"), self._elt2sum(res)))
                 hexdump(
                     p.getlayer(conf.padding_layer).load  # type: ignore
                 )
Exemplo n.º 15
0
 def nzpadding(self, lfilter=None):
     """Same as padding() but only non null padding"""
     for i, res in enumerate(self.res):
         p = self._elt2pkt(res)
         if p.haslayer(conf.padding_layer):
             pad = p.getlayer(conf.padding_layer).load
             if pad == pad[0] * len(pad):
                 continue
             if lfilter is None or lfilter(p):
                 print "%s %s %s" % (conf.color_theme.id(
                     i,
                     fmt="%04i"), p.sprintf("%.time%"), self._elt2sum(res))
                 hexdump(p.getlayer(conf.padding_layer).load)
Exemplo n.º 16
0
 def __str__(self):
     assert (self.valid)
     old_stdout = sys.stdout
     sys.stdout = buffer = StringIO()
     hexdump(self.exp_pkt)
     print('mask =', end=' ')
     for i in range(0, len(self.mask), 16):
         if i > 0: print('%04x  ' % i, end=' ')
         print(' '.join('%02x' % (x) for x in self.mask[i:i + 8]), end=' ')
         print('', end=' ')
         print(' '.join('%02x' % (x) for x in self.mask[i + 8:i + 16]))
     sys.stdout = old_stdout
     return buffer.getvalue()
Exemplo n.º 17
0
def arpleak(target, plen=255, hwlen=255, **kargs):
    # type: (str, int, int, **Any) -> Tuple[SndRcvList, PacketList]
    """Exploit ARP leak flaws, like NetBSD-SA2017-002.

https://ftp.netbsd.org/pub/NetBSD/security/advisories/NetBSD-SA2017-002.txt.asc

    """
    # We want explicit packets
    pkts_iface = {}  # type: Dict[str, List[Ether]]
    for pkt in ARP(pdst=target):
        # We have to do some of Scapy's work since we mess with
        # important values
        iface = conf.route.route(pkt.pdst)[0]
        psrc = get_if_addr(iface)
        hwsrc = get_if_hwaddr(iface)
        pkt.plen = plen
        pkt.hwlen = hwlen
        if plen == 4:
            pkt.psrc = psrc
        else:
            pkt.psrc = inet_aton(psrc)[:plen]
            pkt.pdst = inet_aton(pkt.pdst)[:plen]
        if hwlen == 6:
            pkt.hwsrc = hwsrc
        else:
            pkt.hwsrc = mac2str(hwsrc)[:hwlen]
        pkts_iface.setdefault(iface, []).append(
            Ether(src=hwsrc, dst=ETHER_BROADCAST) / pkt
        )
    ans, unans = SndRcvList(), PacketList(name="Unanswered")
    for iface, pkts in viewitems(pkts_iface):
        ans_new, unans_new = srp(pkts, iface=iface, filter="arp", **kargs)
        ans += ans_new
        unans += unans_new
        ans.listname = "Results"
        unans.listname = "Unanswered"
    for _, rcv in ans:
        if ARP not in rcv:
            continue
        rcv = rcv[ARP]
        psrc = rcv.get_field('psrc').i2m(rcv, rcv.psrc)
        if plen > 4 and len(psrc) > 4:
            print("psrc")
            hexdump(psrc[4:])
            print()
        hwsrc = rcv.get_field('hwsrc').i2m(rcv, rcv.hwsrc)
        if hwlen > 6 and len(hwsrc) > 6:
            print("hwsrc")
            hexdump(hwsrc[6:])
            print()
    return ans, unans
Exemplo n.º 18
0
def ModScan(ip, port, options):
    global debug_mode
    global func_fuzzing
    global di_scan

    debug_mode = False
    func_fuzzing = False
    di_scan = False
    res = False
    if options.debug:
        debug_mode = True
    if options.func_fuzzing:
        func_fuzzing = True
    if options.device_info_scan:
        di_scan = True

    try:
        data = options.modbus_data.decode(
            "string-escape") if options.modbus_data else ''

        if options.brute_uid:
            uids = [0, 255] + range(1, 255)
        elif options.modbus_uid:
            uids = [int(uid.strip()) for uid in options.modbus_uid.split(',')]
        elif options.func_fuzzing:
            uids = [0]
        else:
            uids = [0, 255]

        for uid in uids:
            unitInfo = ScanUnit(ip, port, uid, options.modbus_timeout,
                                options.modbus_function, data)
            if unitInfo:
                if not res:
                    print "%s:%d Modbus/TCP" % (ip, port)
                    res = True
                print "Unit ID:%d" % uid
                for line in unitInfo:
                    print "   %s" % line

        return res

    except ModbusProtocolError as e:
        print "%s:%d Modbus protocol error: %s (packet: %s)" % (
            ip, port, e.message, e.packet.encode('hex'))
        if debug_mode:
            print hexdump(e.packet)
        return res
    except socket.error as e:
        print "%s:%d %s" % (ip, port, e)
        return res
Exemplo n.º 19
0
def arpleak(target, plen=255, hwlen=255, **kargs):
    """Exploit ARP leak flaws, like NetBSD-SA2017-002.

https://ftp.netbsd.org/pub/NetBSD/security/advisories/NetBSD-SA2017-002.txt.asc

    """
    # We want explicit packets
    pkts_iface = {}
    for pkt in ARP(pdst=target):
        # We have to do some of Scapy's work since we mess with
        # important values
        iface = conf.route.route(pkt.pdst)[0]
        psrc = get_if_addr(iface)
        hwsrc = get_if_hwaddr(iface)
        pkt.plen = plen
        pkt.hwlen = hwlen
        if plen == 4:
            pkt.psrc = psrc
        else:
            pkt.psrc = inet_aton(psrc)[:plen]
            pkt.pdst = inet_aton(pkt.pdst)[:plen]
        if hwlen == 6:
            pkt.hwsrc = hwsrc
        else:
            pkt.hwsrc = mac2str(hwsrc)[:hwlen]
        pkts_iface.setdefault(iface, []).append(
            Ether(src=hwsrc, dst=ETHER_BROADCAST) / pkt
        )
    ans, unans = SndRcvList(), PacketList(name="Unanswered")
    for iface, pkts in viewitems(pkts_iface):
        ans_new, unans_new = srp(pkts, iface=iface, filter="arp", **kargs)
        ans += ans_new
        unans += unans_new
        ans.listname = "Results"
        unans.listname = "Unanswered"
    for _, rcv in ans:
        if ARP not in rcv:
            continue
        rcv = rcv[ARP]
        psrc = rcv.get_field('psrc').i2m(rcv, rcv.psrc)
        if plen > 4 and len(psrc) > 4:
            print("psrc")
            hexdump(psrc[4:])
            print()
        hwsrc = rcv.get_field('hwsrc').i2m(rcv, rcv.hwsrc)
        if hwlen > 6 and len(hwsrc) > 6:
            print("hwsrc")
            hexdump(hwsrc[6:])
            print()
    return ans, unans
Exemplo n.º 20
0
 def __str__(self):
     assert self.valid
     old_stdout = sys.stdout
     sys.stdout = buffer = StringIO()
     hexdump(self.exp_pkt)
     print("mask =", end=" ")
     for i in range(0, len(self.mask), 16):
         if i > 0:
             print("%04x  " % i, end=" ")
         print(" ".join("%02x" % (x) for x in self.mask[i : i + 8]), end=" ")
         print("", end=" ")
         print(" ".join("%02x" % (x) for x in self.mask[i + 8 : i + 16]))
     sys.stdout = old_stdout
     return buffer.getvalue()
Exemplo n.º 21
0
def ModScan(ip, port, options):
    global debug_mode
    global func_fuzzing
    global di_scan

    debug_mode = False
    func_fuzzing = False
    di_scan = False
    res = False
    if options.debug:
        debug_mode = True
    if options.func_fuzzing:
        func_fuzzing = True
    if options.device_info_scan:
        di_scan = True

    try:
        data = options.modbus_data.decode("string-escape") if options.modbus_data else ''

        if options.brute_uid:
            uids = [0,255] + range(1,255)
        elif options.modbus_uid:
            uids = [int(uid.strip()) for uid in options.modbus_uid.split(',')]
        elif options.func_fuzzing:
            uids = [0]
        else:
            uids = [0,255]

        for uid in uids:
            unitInfo = ScanUnit(ip, port, uid, options.modbus_timeout, options.modbus_function, data)
            if unitInfo:
                if not res:
                    print "%s:%d Modbus/TCP" % (ip, port)
                    res = True
                print "Unit ID:%d" % uid
                for line in unitInfo:
                    print "   %s" % line

        return res

    except ModbusProtocolError as e:
        print "%s:%d Modbus protocol error: %s (packet: %s)" % (ip, port, e.message, e.packet.encode('hex'))
        if debug_mode:
            print hexdump(e.packet)
        return res
    except socket.error as e:
        print "%s:%d %s" % (ip, port, e)
        return res
Exemplo n.º 22
0
    def extract_iv(self, pkt):
        # Get IV
        TSC, _, _ = parse_TKIP_hdr(pkt)
        iv = TSC[0] | (TSC[1] << 8) | (TSC[2] << 16) | (TSC[3] << 24) | \
             (TSC[4] << 32) | (TSC[5] << 40)
        log_runtime.info("Got a packet with IV: %s", hex(iv))

        if self.last_iv is None:
            self.last_iv = iv
        else:
            if iv <= self.last_iv:
                log_runtime.warning("IV re-use!! Client seems to be "
                                    "vulnerable to handshake 3/4 replay "
                                    "(CVE-2017-13077)"
                )

        data_clear = None

        # Normal decoding
        data = parse_data_pkt(pkt, self.tk)
        try:
            data_clear = check_MIC_ICV(data, self.mic_sta_to_ap, pkt.addr2,
                                       pkt.addr3)
        except (ICVError, MICError):
            pass

        # Decoding with a 0's TK
        if data_clear is None:
            data = parse_data_pkt(pkt, "\x00" * len(self.tk))
            try:
                mic_key = "\x00" * len(self.mic_sta_to_ap)
                data_clear = check_MIC_ICV(data, mic_key, pkt.addr2, pkt.addr3)
                log_runtime.warning("Client has installed an all zero "
                                    "encryption key (TK)!!")
            except (ICVError, MICError):
                pass

        if data_clear is None:
            log_runtime.warning("Unable to decode the packet, something went "
                                "wrong")
            log_runtime.debug(hexdump(pkt, dump=True))
            self.deal_common_pkt(pkt)
            return

        log_runtime.debug(hexdump(data_clear, dump=True))
        pkt = LLC(data_clear)
        log_runtime.debug(repr(pkt))
        self.deal_common_pkt(pkt)
Exemplo n.º 23
0
 def load_pkts(self, pkts):
     self.view.clear_info()
     for p in pkts:
         self.view.add_pkt(
             dict(pkt_summary=p.summary(),
                  pkt_hex=hexdump(p, dump=True),
                  pkt_detail=p.show(dump=True)))
Exemplo n.º 24
0
    def check_arp_reply(self, pkt):
        data = parse_data_pkt(pkt, self.tk)
        try:
            data_clear = check_MIC_ICV(data, self.mic_sta_to_ap, pkt.addr2,
                                       pkt.addr3)
        except (ICVError, MICError):
            return

        decoded_pkt = LLC(data_clear)
        log_runtime.debug(hexdump(decoded_pkt, dump=True))
        log_runtime.debug(repr(decoded_pkt))
        self.deal_common_pkt(decoded_pkt)
        if ARP not in decoded_pkt:
            return

        # ARP.op 2: is-at
        if decoded_pkt[ARP].op == 2 and \
           decoded_pkt[ARP].psrc == self.arp_target_ip and \
           decoded_pkt[ARP].pdst == self.arp_source_ip:
            # Got the expected ARP
            if self.krack_state & 4 == 0:
                # First time, normal behavior
                log_runtime.info("Got ARP reply, this is normal")
                self.krack_state |= 4
                log_runtime.info("Trying to trigger CVE-2017-13080")
                raise self.RENEW_GTK()
            else:
                # Second time, the packet has been accepted twice!
                log_runtime.warning("Broadcast packet accepted twice!! "
                                    "(CVE-2017-13080)")
Exemplo n.º 25
0
    def check_arp_reply(self, pkt):
        data = parse_data_pkt(pkt, self.tk)
        try:
            data_clear = check_MIC_ICV(data, self.mic_sta_to_ap, pkt.addr2,
                                       pkt.addr3)
        except (ICVError, MICError):
            return

        decoded_pkt = LLC(data_clear)
        log_runtime.debug(hexdump(decoded_pkt, dump=True))
        log_runtime.debug(repr(decoded_pkt))
        self.deal_common_pkt(decoded_pkt)
        if ARP not in decoded_pkt:
            return

        # ARP.op 2: is-at
        if decoded_pkt[ARP].op == 2 and \
           decoded_pkt[ARP].psrc == self.arp_target_ip and \
           decoded_pkt[ARP].pdst == self.arp_source_ip:
            # Got the expected ARP
            if self.krack_state & 4 == 0:
                # First time, normal behavior
                log_runtime.info("Got ARP reply, this is normal")
                self.krack_state |= 4
                log_runtime.info("Trying to trigger CVE-2017-13080")
                raise self.RENEW_GTK()
            else:
                # Second time, the packet has been accepted twice!
                log_runtime.warning("Broadcast packet accepted twice!! "
                                    "(CVE-2017-13080)")
Exemplo n.º 26
0
def ppp(headline, packet):
    """Return string containing headline and output of scapy packet.show()"""
    return "%s\n%s\n\n%s\n" % (
        headline,
        hexdump(packet, dump=True),
        packet.show(dump=True),
    )
Exemplo n.º 27
0
    def generate_someip_based_tcp(self, s_ip, d_ip, s_port, d_port, seq=2496318543, ack=594476641, flags="PA",
                                  matrix=None):
        vlan = Dot1Q(vlan=4)
        ip = IP(src=s_ip, dst=d_ip)

        tcp = TCP(flags=flags, sport=s_port, dport=d_port, seq=seq, ack=ack)
        if flags == "PA":  # PSH+ACK
            if matrix is None:
                matrix = {}
            srv_id = matrix.get("srv_id", 0xffff)
            method_id = matrix.get("method_id", 65535)
            session_id = matrix.get("session_id", 1)
            msg_type = matrix.get("msg_type", SOMEIP.TYPE_NOTIFICATION)
            req_data = matrix.get("req_data", [])
            someip = SOMEIP(srv_id=srv_id, sub_id=0x0,
                            method_id=method_id, event_id=0,
                            client_id=method_id, session_id=session_id,
                            msg_type=msg_type)
            packet = b''.join([bytes().fromhex(i) for i in req_data])
            target = ip / tcp / someip / packet
        elif flags == "A":  # ACK
            target = ip / tcp
        else:
            target = ip / tcp

        payload_length = len(target)
        hex_target = hexdump(target, True)
        results = hex_target.split("\n")
        finalResult = []
        for item in results:
            finalResult.append(item.split("  ")[1])
        x = " ".join(finalResult)
        x_list = x.split(" ")
        return payload_length, x_list
 def escape_packets(self):
     # Messy...
     self.escaped_packets = list()
     bad_packet_indices_indices = list()
     for idx, packet in enumerate(self.packets):
         print(
             f"\n= UNESCAPE PACKET {idx} ===================================="
         )
         hexdump(packet)
         unescaped_packet = bytearray()
         escaped = False
         drop_packet = False
         for byte_idx, byte in enumerate(packet[:-1]):
             if escaped:
                 if byte == 0x5E:
                     byte = 0x7E
                 elif byte == 0x5D:
                     byte = 0x7D
                 elif 0x40 > byte >= 0x20:
                     byte = byte - 0x20
                 else:
                     print(
                         f"[ERROR] Incorrect byte escape value ({hex(byte)}) on byte {hex(byte_idx)} in packet {idx}... dropping packet"
                     )
                     # bad_packet_indices_indices.append(idx)
                     drop_packet = True
                     break
                 escaped = False
                 unescaped_packet.append(byte)
             elif byte == 0x7D:
                 escaped = True
             else:
                 unescaped_packet.append(byte)
         if drop_packet:
             continue
         if escaped:
             print(f"[WARN] ends with 0x7D")
         unescaped_packet.extend(packet[-1:])
         calculated_crc = FCS16.calculate(unescaped_packet[1:-3]).hex()
         extracted_crc = unescaped_packet[-3:-1].hex()
         if calculated_crc != extracted_crc:
             print(f"[WARN] - CRC mismatch!")
             print(f"    CALCULATED FCS: {calculated_crc}")
             print(f"    EXTRACTED FCS: {extracted_crc}")
         self.escaped_packets.append(unescaped_packet)
     for idx in bad_packet_indices_indices:
         del self.packet_start_indices[idx]
Exemplo n.º 29
0
 def pkt_handler(self, pkt):
     self.content = pkt.show(dump=True)
     self.summary = pkt.summary()
     self.find_src(self.content)
     self.find_dest(self.content)
     self.find_size(self.content)
     self.find_proto(self.content)
     self.hexinfo = utils.hexdump(pkt, dump=True)
Exemplo n.º 30
0
    def handle_probe_response(self, pkt):
        """Process 802.11 Probe Response Frame for WPS IE."""
        try:
            mgt = self.rtDecoder.get_protocol(dot11.Dot11ManagementFrame)
            probe = self.rtDecoder.get_protocol(dot11.Dot11ManagementProbeResponse)
            bssid = get_addr_from_list(mgt.get_bssid())
            essid = probe.get_ssid()

            # If null byte in the SSID IE, its cloacked.
            if essid is None or essid.find("\x00") != -1:
                essid = "<No ssid>"

            if bssid in self.aps:
                return

            rt = self.rtDecoder.get_protocol(dot11.RadioTap)
            freq = rt.get_channel()[0]
            channel = frequencies_dict[freq]
            vendor = get_vendor(bssid)
            vendorIEs = probe.get_vendor_specific()
            wps = self.wps_parser.has_wps(vendorIEs)

            # print 'checking wps info'
            if self.wps_parser.has_wps(vendorIEs):
                hexdump(vendorIEs)
                wpsInfo = self.wps_parser.parse_wps(vendorIEs)

                if wpsInfo:
                    self.wps_aps[bssid] = wpsInfo
                    print("[%s] - [%s]\t%s'\nWPS Information" % (bssid, essid, vendor))
                    for key, value in wpsInfo.items():
                        print("[WPSINFO]  * %s: %s" % (key, repr(value)))

                self.wps_parser.parse_probe_response(pkt)

            enc = self.get_security(pkt)
            self.aps[bssid] = (channel, essid, enc, wps)
            self.logger.info(
                '[+] AP discovered! ProbeResponse channel: %s ESSID: %s Encryption: %s WPS: %s Vendor: %s' %
                (channel, _green(essid), _colorize_security(enc), _colorize_wps(wps), _green(get_vendor(bssid))))

        except Exception:
            print('Error while parsing probe responsse')
            print(str(sys.exc_info()))
            return
Exemplo n.º 31
0
 def packet_info(self):
     self.curr_idx = len(p_list)
     for i in range(self.prev_idx, self.curr_idx):
         self.emit(
             'packet_info',
             dict(pkt_summary=p_list[i].summary(),
                  pkt_detail=p_list[i].show(dump=True),
                  pkt_hex=hexdump(p_list[i], dump=True)))
     self.prev_idx = self.curr_idx
def pkt_handler(pkt):
    content = pkt.show(dump=True)
    summary = pkt.summary()
    hex = utils.hexdump(pkt, dump=True)
    print(content)
    print(summary)
    find_src(summary)
    find_dest(summary)
    print(hex)
Exemplo n.º 33
0
 def print_data(self, data):
     print("Source MAC: " + data["source_mac"])
     print("Destination MAC: " + data["destination_mac"])
     print("Source IP: " + data["source_ip"])
     print("Destination IP: " + data["destination_ip"])
     print("SPORT: " + str(data["sport"]))
     print("DPORT: " + str(data["dport"]))
     print("PACKET DATA\n\n")
     print(hexdump(data["load"]))
     print("*" * 100)
Exemplo n.º 34
0
 def save_data(self, data):
     load_data = str(hexdump(data["load"], dump=True))
     save_data = "\nSource MAC: " + str(
         data["source_mac"]) + "\nDestination MAC: " + str(
             data["destination_mac"]) + "\nSource IP: " + str(
                 data["source_ip"]) + "\nDestination IP: " + str(
                     data["destination_ip"]) + "\nSPORT: " + str(
                         data["sport"]) + "\nDPORT: " + str(
                             data["dport"]
                         ) + "\nPACKET DATA\n\n" + load_data + "\n\n" + str(
                             "*" * 100)
     self.file.write(save_data)
Exemplo n.º 35
0
 def moreinfo(self):
     self.S3.config(state=NORMAL)
     hi = self.variable.get().split(":")
     pos = int(hi[1])
     if pos > 25:
         print("Out of bounds")
         self.S3.config(state=DISABLED)
     else:
         neu = int(pos - 1)
         print(hexdump(a[neu]))
         print(data)
         self.S3.config(state=DISABLED)
Exemplo n.º 36
0
def handle_pkt(pkt):
    # print "got the probe"
    # pkt.show()
    str = hexdump(pkt, dump=True)
    print str
    str_list = str.split('\n')
    hex_str = ""
    for str in str_list:
        p1 = str.find(' ')
        p2 = str.find(' ', p1 + 2)
        hex_str += str[p1 + 2:p2]
    extract_metadata(hex_str)
    sys.stdout.flush()
Exemplo n.º 37
0
def cdp_monitor_callback(pkt):   
    print("Ejecutando método cdp_monitor_callback")
    #print(pkt.summary())                            #802.3 00:da:55:77:5b:22 > 01:00:0c:cc:cc:cc / LLC / SNAP / CDPv2_HDR
    #print(pkt[LLC].summary())                       #LLC / SNAP / CDPv2_HDR
    #pkt[LLC].show()                                 #Show all packet in columns
    #print(pkt[SNAP].summary())                      #SNAP / CDPv2_HDR
    #print(pkt[CDPv2_HDR].summary())                 #CDPv2_HDR
    pkt[CDPv2_HDR].fields["msg"]
    #pkt[Raw].fields
    hexdump(pkt)                                     #Show information in Hexadecimal
    #hexdump(raw)                                    #Show information in Hexadecimal
    #e = pkt[Raw].fields   
    print("Deciphering...")     
    time.sleep(2)        
    
    #pkt.command()    
    #pkt.show(dump = True)    
    #string = pkt.show(dump = True)    
    #print(string)
    #pkt.display()       

    #miDevice = open("miDevice.txt", "w")
    #miDevice.write(string)
    #miDevice.close()       
         

    hostname = pkt["CDPMsgDeviceID"].val.decode('utf-8')
    ip = pkt["CDPAddrRecordIPv4"].addr
    interface = pkt["CDPMsgPortID"].iface.decode('utf-8')       
    conjunto = "Hostname: "+ hostname + " IP: " + ip + " PortID: " + interface
    print(conjunto)
    
   
    miDevice = open("miDevice.txt", "w")
    miDevice.write(conjunto)
    miDevice.close()    
    
    time.sleep(50)   
Exemplo n.º 38
0
 def render(self, context):
     res = []
     packet_count = 0
     for p in context['packets']:
         layers = p.layers()
         subcontext = {'p': p.summary, 'num': packet_count}
         if TCP in layers:
             subcontext['border'] = 'border-success'
         elif UDP in layers:
             subcontext['border'] = 'border-primary'
         else:
             subcontext['border'] = 'border-danger'
         if IP in layers:
             subcontext['ip_version'] = p['IP'].version
             subcontext['ip_len'] = p['IP'].len
             subcontext['ip_id'] = p['IP'].id
             subcontext['ip_flags'] = p['IP'].flags
             subcontext['ip_ttl'] = p['IP'].ttl
             subcontext['ip_chksum'] = p['IP'].chksum
         if TCP in layers:
             subcontext['tcp_sport'] = p['TCP'].sport
             subcontext['tcp_dport'] = p['TCP'].dport
             subcontext['tcp_seq'] = p['TCP'].seq
             subcontext['tcp_ack'] = p['TCP'].ack
             subcontext['tcp_flags'] = p['TCP'].flags
             subcontext['tcp_chksum'] = p['TCP'].chksum
         if UDP in layers:
             subcontext['udp_sport'] = p['UDP'].sport
             subcontext['udp_dport'] = p['UDP'].dport
             subcontext['udp_len'] = p['UDP'].len
             subcontext['udp_chksum'] = p['UDP'].chksum
         if Raw in layers:
             subcontext['raw_load'] = hexdump(p['Raw'].load, dump=True)
         if Padding in layers:
             subcontext['padding'] = p['Padding'].load
         if Ether in layers:
             subcontext['ether_src'] = p['Ether'].src
             subcontext['ether_dst'] = p['Ether'].dst
             subcontext['ether_type'] = p['Ether'].type
         res.append(render_to_string('pcap_parsing/snippets/packet_snippet.html', subcontext))
         packet_count += 1
         # Debug.
         if settings.DEBUG:
             for l in layers:
                 if l not in [UDP, TCP, Ether, Raw, IP, Padding]:
                     print("{} Not currently supported. Please open an issue at "
                           "https://github.com/TheToddLuci0/ISELab_Debugger/issues/new?assignees=TheToddLuci0&labels"
                           "=Packet+Layer+Request%2C+enhancement&template=add-packet-layer.md&title=Add+Packet+Layer"
                           "+LAYER_NAME".format(l))
     return '\n'.join(res)
Exemplo n.º 39
0
    def privacy_monitoring_engine(dest_mac, src_mac, raw_data, src, target):

        pkt = Packet(raw_data)
        raw = pkt.lastlayer()

        Source_IP = src
        Destination_IP = target
        Source_MAC = src_mac
        Destination_MAC = dest_mac

        # Call the Shannon entropy Test here and pass the hexdump(raw)
        if (Privacy_Engine.entropy(str(hexdump(raw))) >= 3.5):
            lg.privacy_logger.info(
                str(datetime.datetime.now()) + ' Encrypted payload')
            lg.privacy_logger.info(
                str(datetime.datetime.now()) + ' Source IP: ' + str(Source_IP))
            lg.privacy_logger.info(
                str(datetime.datetime.now()) + ' Destination IP: ' +
                str(Destination_IP))
            lg.privacy_logger.info(
                str(datetime.datetime.now()) + ' Source MAC: ' +
                str(Source_MAC))
            lg.privacy_logger.info(
                str(datetime.datetime.now()) + ' Destination MAC: ' +
                str(Destination_MAC))
        else:
            lg.privacy_logger.info(
                str(datetime.datetime.now()) + ' Plain text found')
            lg.privacy_logger.info(
                str(datetime.datetime.now()) + ' Source IP: ' + str(Source_IP))
            lg.privacy_logger.info(
                str(datetime.datetime.now()) + ' Destination IP: ' +
                str(Destination_IP))
            lg.privacy_logger.info(
                str(datetime.datetime.now()) + ' Source MAC: ' +
                str(Source_MAC))
            lg.privacy_logger.info(
                str(datetime.datetime.now()) + ' Destination MAC: ' +
                str(Destination_MAC))
            Privacy_Engine.user_privacy_alerts(str(datetime.datetime.now()),
                                               str(Source_IP), str(Source_MAC))
Exemplo n.º 40
0
    def stop(self):
        logging.debug("tcpdump:stop()")
        self.device.get_tcpdump_file(self.file_path, self.out_filepath)

        obj = {
            'plugin': 'tcpdump',
            'file_path': self.out_filepath,
            'summary': '',
            'show': '',
            'hexdump': ''
        }

        if os.path.isfile(self.out_filepath):
            packets = rdpcap(self.out_filepath)

            for packet in packets:
                obj['summary'] = packet.summary()
                obj['show'] = packet.show(dump=True)
                obj['hexdump'] = "\n" + hexdump(packet, dump=True)

                TCPDumpPlugin.parse(self.module, obj, '')
        else:
            print(f"{self.out_filepath} does not exist")
Exemplo n.º 41
0
0xcb, 0x23, 0xeb, 0x9f, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x02, 0x55, 0x55, 0x55, 0x55,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0xff, 0x40, 0xf8, 0x00, 0x00, 0x00, 0x3c,
0x00, 0x00, 0x00, 0x04, 0x00, 0x10, 0x12, 0x00,
0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00
]))

senddata5 = bytes(bytearray([
0xe0, 0x7b, 0xca, 0x60, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x02, 0x55, 0x55, 0x55, 0x55,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0xff, 0x40, 0xf8, 0x00, 0x00, 0x00, 0x3c,
0x00, 0x00, 0x00, 0x04, 0x00, 0x10, 0x12, 0x00,
0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00
]))
data = senddata2
print "-------------send data:"
print hexdump(data)

sock.sendto(data, addr)


recvdata, addr = sock.recvfrom(4096)
print "-------------recv data:"
print hexdump(recvdata)
Exemplo n.º 42
0
 def dump(self):
     """Prints the stream."""
     hexdump(self.stream[self.offset:])
Exemplo n.º 43
0
if __name__ == "__main__":

    print "test float encoding"
    from math import log
    max_expected_error = 1.0 / (2<<3) # four bit precision
    p = IGMPv3()
    for v in range(0, 31745):
        c = p.encode_float(v)
        d = p.decode_float(c)
        rel_err = float(v-d)/v if v!=0 else 0.0
        assert rel_err <= max_expected_error

    print "construct membership query - general query"
    mq = IGMPv3(type=IGMP_TYPE_MEMBERSHIP_QUERY, max_resp_code=120)
    hexdump(str(mq))

    print "construct membership query - group-specific query"
    mq = IGMPv3(type=IGMP_TYPE_MEMBERSHIP_QUERY, max_resp_code=120,
                gaddr="224.0.0.1")
    hexdump(str(mq))

    print "construct membership query - group-and-source-specific query"
    mq = IGMPv3(type=IGMP_TYPE_MEMBERSHIP_QUERY, max_resp_code=120,
                gaddr="224.0.0.1")
    mq.srcs = ['1.2.3.4', '5.6.7.8']
    hexdump(str(mq))

    print "fixup"
    mq = IGMPv3(type=IGMP_TYPE_MEMBERSHIP_QUERY)
    mq.srcs = ['1.2.3.4', '5.6.7.8']
Exemplo n.º 44
0
Arquivo: parser.py Projeto: 0x90/wpsik
    def parse_wps(self, IEs):
        "Returns dictionary with WPS Information."
        ret = {}

        # TODO: improve parsing
        try:
            for element in IEs:
                offset = 0
                data = element[1]
                offset += 1

                dataLength = len(data)
                # print('dataLength %s' % dataLength)
                while offset < dataLength:
                    tagType = struct.unpack("!H", data[offset:offset + 2])[0]
                    offset += 2
                    tagLen = struct.unpack("!H", data[offset:offset + 2])[0]
                    offset += 2
                    tagData = data[offset:offset + tagLen]
                    offset += tagLen

                    # Get the Tag Type
                    if self.WPS_DATA_ELEMENTS.has_key(tagType):
                        tagType = self.WPS_DATA_ELEMENTS[tagType]
                    else:
                        tagType = None

                    if tagType == "Wi-Fi Protected Setup State":
                        if tagData == '\x01':
                            tagData = "Not Configured"
                        elif tagData == '\x02':
                            tagData = "Configured"
                        else:
                            tagData = 'Reserved'

                    if tagType == "UUID-E":
                        aux = ''
                        for c in tagData:
                            aux += "%02X" % ord(c)
                        tagData = aux

                    if tagType == "Response Type":
                        if tagData == '\x00':
                            tagData = 'Enrollee, Info Only'
                        elif tagData == '\x01':
                            tagData = 'Enrollee, open 802.1X'
                        elif tagData == '\x02':
                            tagData = 'Registrar'
                        elif tagData == '\x03':
                            tagData = 'AP'
                        else:
                            tagData = '<unkwon>'

                    if tagType == "Primary Device Type":
                        category = struct.unpack("!H", tagData[0:2])[0]
                        subCategory = struct.unpack("!H", tagData[6:8])[0]
                        if category == 1:
                            category = "Computer"
                            if subCategory == 1:
                                subCategory = "PC"
                            elif subCategory == 2:
                                subCategory = "Server"
                            elif subCategory == 3:
                                subCategory = "Media Center"
                            else:
                                subCategory = "<unkwon>"
                        elif category == 2:
                            category = "Input Device"
                            subCategory = "<unkwon>"
                        elif category == 3:
                            category = "Printers, Scanners, Faxes and Copiers"
                            if subCategory == 1:
                                subCategory = "Printer"
                            elif subCategory == 2:
                                subCategory = "Scanner"
                            else:
                                subCategory = "<unkwon>"
                        elif category == 4:
                            category = "Camera"
                            if subCategory == 1:
                                subCategory = "Digital Still Camera"
                            else:
                                subCategory = "<unkwon>"
                        elif category == 5:
                            category = "Storage"
                            if subCategory == 1:
                                subCategory = "NAS"
                            else:
                                subCategory = "<unkwon>"
                        elif category == 6:
                            category = "Network Infrastructure"
                            if subCategory == 1:
                                subCategory = "AP"
                            elif subCategory == 2:
                                subCategory = "Router"
                            elif subCategory == 3:
                                subCategory = "Switch"
                            else:
                                subCategory = "<unkwon>"
                        elif category == 7:
                            category = "Display"
                            if subCategory == 1:
                                subCategory = "Television"
                            elif subCategory == 2:
                                subCategory = "Electronic Picture Frame"
                            elif subCategory == 3:
                                subCategory = "Projector"
                            else:
                                subCategory = "<unkwon>"
                        elif category == 8:
                            category = "Multimedia Devices"
                            if subCategory == 1:
                                subCategory = "DAR"
                            elif subCategory == 2:
                                subCategory = "PVR"
                            elif subCategory == 3:
                                subCategory = "MCX"
                            else:
                                subCategory = "<unkwon>"
                        elif category == 9:
                            category = "Gaming Devices"
                            if subCategory == 1:
                                subCategory = "Xbox"
                            elif subCategory == 2:
                                subCategory = "Xbox360"
                            elif subCategory == 3:
                                subCategory = "Playstation"
                            else:
                                subCategory = "<unkwon>"
                        elif category == 10:
                            category = "Telephone"
                            if subCategory == 1:
                                subCategory = "Windows Mobile"
                            else:
                                subCategory = "<unkwon>"
                        else:
                            category = "<unkwon>"
                            subCategory = "<unkwon>"
                        tagData = "%s - %s" % (category, subCategory)

                        if tagType == "Version":
                            tagData = struct.unpack("B", tagData)[0]
                            major = tagData >> 4
                            minor = tagData & 0x0F
                            tagData = "%d.%d" % (major, minor)

                        if tagType == "Config Methods":
                            methods = {
                                0x0001: "USB",
                                0x0002: "Ethernet",
                                0x0004: "Label",
                                0x0008: "Display",
                                0x0010: "External NFC Token",
                                0x0020: "Integrated NFC Token",
                                0x0040: "NFC Interface",
                                0x0080: "PushButton",
                                0x0100: "Keypad"
                            }
                            result = []
                            tagData = struct.unpack("!H", tagData)[0]
                            for key, value in methods.items():
                                if key & tagData:
                                    result.append(value)
                            tagData = ", ".join(result)

                    if tagType:
                        ret[tagType] = tagData

            return ret
        except:
            print('Error parsing vendor specific fields!')
            hexdump(IEs)
            return None
Exemplo n.º 45
0
    def DeviceInfo(self):

        if func_fuzzing:
            #readDeviceId = bytearray([0x01, 0x02, 0x03, 0x04])
            #objectId = bytearray([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06])
            for rd in range(4,4+1):
                for ob in range(0x80,0xff+1):
#                     res = self.Request(0x2b, bytes(bytearray(0x0e, str(rd), str(o))))
#                     if res and len(res)>5:
#                         objectCount = ord(res[5])
#                         data = res[6:]
#                         info = ''
#                         for i in range(0, objectCount):
#                             info += data[2:2+ord(data[1])]
#                             info += ' '
#                             data = data[2+ord(data[1]):]
#                             return info
#                         else:
#                             raise ModbusProtocolError('Packet format (reply for device info) wrong', res)
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    sock.connect((self.ip, self.port))
                    senddata = bytes(bytearray([0x00,0x00,0x00,0x00,0x00,0x05,0x00,0x2b,0x0e,rd,ob]))
                    print "+++++++++++++++++send"
                    print hexdump(senddata)
                    sock.send(senddata)
                    recv = sock.recv(1024)
                    print "+++++++++++++++++recv"
                    print hexdump(recv)

                    time.sleep(1)

                    if not recv:
                        raise ModbusError(0)

                    resp = ModbusPacket().unpack(recv)

                    if resp.unitId != self.uid:
                        print 'recv.unitId != self.uid'

                    if resp.functionId != 43:
                        print 'recv.functionId != 43'
                        if resp.functionId == 171:
                            print 'Read Device Identification Error, error code:%r' % resp.data[0]
            exit()

        elif di_scan:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((self.ip, self.port))
            senddata = bytes(bytearray([0x00, 0x0f, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x5a, 0x00, 0x20, 0x00, 0x14, 0x00, 0x64, 0x00, 0x00, 0x00, 0xf6, 0x00]))
            print "------------send"
            print hexdump(senddata)
            sock.send(senddata)
            recv = sock.recv(1024)
            print "------------recv"
            print hexdump(recv)
            exit()
        else:
            res = self.Request(0x2b, '\x0e\x01\00')

            if res and len(res)>5:
                objectsCount = ord(res[5])
                data = res[6:]
                info = ''
                for i in range(0, objectsCount):
                    info += data[2:2+ord(data[1])]
                    info += ' '
                    data = data[2+ord(data[1]):]
                    return info
                else:
                    raise ModbusProtocolError('Packet format (reply for device info) wrong', res)
Exemplo n.º 46
0
Arquivo: util.py Projeto: chrisy/vpp
def ppp(headline, packet):
    """ Return string containing the output of scapy packet.show() call. """
    return '%s\n%s\n\n%s\n' % (headline,
                               hexdump(packet, dump=True),
                               packet.show(dump=True))
Exemplo n.º 47
0
 def rawhexdump(self):
     """Prints an hexadecimal dump of each packet in the list"""
     for p in self:
         hexdump(self._elt2pkt(p))