Пример #1
0
    def cmd_parse_cc(self):
        "Read and parse the CC (Capability Container) EF"
        result = self.open_file("\xe1\x03")
        if self.check_sw(result.sw):
            contents, sw = self.read_binary_file()
            if len(contents) > 0:
                print utils.hexdump(contents, linelen=self.HEXDUMP_LINELEN)

                if len(contents) < 0xf:
                    print "Invalid CC EF, can't parse (too short: 0x%x bytes)" % len(
                        contents)
                else:
                    cclen, version, MLe, MLc, ndef_control_tlv = struct.unpack(
                        '>HBHH8s', contents[:0xf])

                    print "      CC length: %i (0x%x)%s" % (
                        cclen, cclen, cclen == 0xffff and ", RFU" or "")
                    print "Mapping version: %i.%i" % (version >> 4,
                                                      version & 0xf)
                    print "     Maximum Le: %i (0x%x)%s" % (
                        MLe, MLe, MLe <= 0xe and ", RFU" or "")
                    print "     Maximum Lc: %i (0x%x)%s" % (
                        MLc, MLc, MLc == 0x0 and ", RFU" or "")

                    print "NDEF File Control TLV: %s" % utils.hexdump(
                        ndef_control_tlv, short=True)
                    if len(contents) > 0xf:
                        print "More TLV blocks: %s" % utils.hexdump(
                            contents[0xf:], short=True)
Пример #2
0
 def cmd_fancy(self, *args):
     "Parse a fancy APDU and print the result"
     apdu = utils.C_APDU.parse_fancy(*args)
     data = apdu.render()
     if hasattr(self, "card"):
         self.card.last_result = utils.R_APDU(data+"\x00\x00")
     print utils.hexdump(data)
Пример #3
0
 def cmd_status(self):
     """STATUS Command."""
     apdu = C_APDU(self.APDU_STATUS, data="\xff")
     result = self.send_apdu(apdu)
     if len(result.data) > 0:
         print utils.hexdump(result.data)
         print self.sel_ret_decode(result.data)
Пример #4
0
async def proxy(reader, writer, index, init_close):
    l_arrow, l_name, r_arrow, r_name = '[<==]', 'local', '[==>]', 'remote'
    peer = writer.get_extra_info('peername')
    if index == 1:
        l_arrow, l_name, r_arrow, r_name = r_arrow, r_name, l_arrow, l_name
    while True:
        try:
            data = await reader.read(4096)
            len_buf = len(data)
            if len_buf == 0:  # FYN received
                print(f"{r_arrow} Connection Closed by {l_name} host.")
                init_close[(index + 1) % 2] = 1
                if init_close[index] == 1:
                    writer.close()
                elif init_close[index] == 0:
                    writer.write_eof()
                return

            print(f"{r_arrow} Received {len_buf} bytes from {l_name} host")
            hexdump(data)
            # check if FYN
            # hexdump it
            print(f"{r_arrow} sent to {r_name} host {peer}")
            writer.write(data)
            await writer.drain()
        except ConnectionResetError as e:
            init_close[(index + 1) % 2] = -1
            if reader.exception():
                writer.close()
            return
Пример #5
0
    def handle_write(self):
        # This conditional stuff could really stand to be cleaned up
        sent = ""
        modified_data = self.receiver.from_remote_buffer

        # Perform search/replace as appropriate
        if sr_request:
            # Check if regex
            if sr_request[0]:
                if len(re.findall(sr_request[1], self.receiver.from_remote_buffer)) > 0:
                    modified_data = re.sub(sr_request[1], sr_request[2], self.receiver.from_remote_buffer)
                    print(term.render("${YELLOW}Sender: Replacing regex %s with %s:${NORMAL}" % (repr(sr_request[1]), repr(sr_request[2]))))
            else:
                if sr_request[1] in self.receiver.from_remote_buffer:
                    modified_data = self.receiver.from_remote_buffer.replace(sr_request[1], sr_request[2])
                    print(term.render("${YELLOW}Sender: Replacing literal %s with %s:${NORMAL}" % (repr(sr_request[1]), repr(sr_request[2]))))

        # Check if we want to fuzz the request or not
        if(fuzz_request):
            modified_data = self.fuzzer.mutate(modified_data)

        sent = self.send(modified_data)

        # Store REQUEST and time of request for logging
        # Msg received from the server (i.e. SMTP request "EHLO foobar.com")
        if self.logdata:
            self.logdata.request_data += modified_data
            if(not self.logdata.request_time):
                self.logdata.request_time = postgres_datetime_ms()

        if(debug == 1 or debug == 4 or debug == 5):
            print(term.render('${BOLD}${RED}Sender: %i bytes sent:${NORMAL}') % sent)
        if(debug == 4 or debug >= 5):
            print hexdump(modified_data, indent=False)
        self.receiver.from_remote_buffer = self.receiver.from_remote_buffer[sent:]
Пример #6
0
def parse_file(fname):
    fp = file(fname)
    
    in_block = False
    is_rfid = False
    line_no = 0
    direction = 0
    data = []
    last_was_transfer_buffer = False
    
    for line in fp.readlines():
        if not in_block:
            if last_was_transfer_buffer:
                parts = line.split(":")
                if parts[0] == "    00000000":
                    if parts[1][:3] == " 6f":
                        in_block = True
                        direction = 0
                        line_no = 0
                        is_rfid = False
                        data = []
                    elif parts[1][:3] == " 80":
                        in_block = True
                        direction = 1
                        line_no = 0
                        is_rfid = False
                        data = []
                    elif parts[1][:3] == " 6b":
                        in_block = True
                        direction = 0
                        line_no = 0
                        is_rfid = True
                        data = []
                    elif parts[1][:3] == " 83":
                        in_block = True
                        direction = 1
                        line_no = 0
                        is_rfid = True
                        data = []
            if in_block and (not is_rfid or line_no > 0):
                data = [ parts[1][31:] ]
        else:
            if not ":" in line:
                in_block = False
                data_binary = binascii.a2b_hex("".join("".join(data).split()))
                if not is_rfid:
                    print (direction and "<< " or ">> ") + utils.hexdump(data_binary, indent=3)
                    if direction == 1: print
                elif len("".join(data).strip()) > (direction == 0 and 8 or 2) and data_binary not in ("\x00"*5, "\x70\x08\x35\x2d\x66\x76", "\x43\x4f\x53\x73\x01\x02\x01"):
                    print (direction and "лл " or "╗╗ ") + utils.hexdump(data_binary, indent=3)
                    if direction == 1: print
            else:
                line_no = line_no + 1
                if (not is_rfid or line_no > 1):
                    data.append( line.split(":")[1] )
                elif is_rfid and line_no == 1:
                    data.append( line.split(":")[1][6:] )
        
        last_was_transfer_buffer = "TransferBufferMDL" in line
Пример #7
0
    def split_guess(self, attr_list, verbose=False):
        """Split the content of the Get_Attribute_List response with the known attribute list

        Return a list of (attr, value) tuples, or None if an error occured
        """
        content = self.content
        offset = 0
        idx = 0
        result = []
        while offset < len(content):
            attr, status = struct.unpack("<HH", content[offset:offset + 4])
            if attr not in attr_list:
                if verbose:
                    sys.stderr.write(
                        "Error: Get_Attribute_List response contains an unknown attribute\n"
                    )
                    sys.stderr.write("... all attrs " +
                                     ','.join(hex(a)
                                              for a in attr_list) + '\n')
                    sys.stderr.write(
                        utils.hexdump(content[offset:], indentlvl="... ") +
                        "\n")
                return
            if attr != attr_list[idx]:
                if verbose:
                    sys.stderr.write(
                        "Error: attr {:#x} not in position {} of attr list\n".
                        format(attr, idx))
                    sys.stderr.write("... all attrs " +
                                     ','.join(hex(a)
                                              for a in attr_list) + '\n')
                return
            offset += 4
            attr_len = None
            if idx == len(attr_list) - 1:
                # Last attribute
                attr_len = len(content) - offset
            else:
                # Find next attribute header
                nexthdr = struct.pack('<HH', attr_list[idx + 1], 0)
                for i in range(offset + 1, len(content) - 4):
                    if content[i:i + 4] == nexthdr:
                        attr_len = i - offset
                        break
            if attr_len is None:
                if verbose:
                    sys.stderr.write(
                        "Error: length not found. Here is the remaining\n")
                    sys.stderr.write("... all attrs " +
                                     ','.join(hex(a)
                                              for a in attr_list) + '\n')
                    sys.stderr.write(
                        utils.hexdump(content[offset:], indentlvl="... ") +
                        "\n")
                return
            result.append((attr, content[offset:offset + attr_len]))
            offset += attr_len
            idx += 1
        return result
Пример #8
0
    def handle_read(self):
        read = self.recv(4096)
        if debug == 1 or debug == 4 or debug == 5:
            print (term.render("    ${BOLD}${CYAN}Sender: %i bytes read:${NORMAL}") % len(read))
        if debug == 4 or debug >= 5:
            print hexdump(read, indent=True)

        self.receiver.to_remote_buffer += read
Пример #9
0
    def handle_read(self):
        read = self.recv(4096)
        if(debug == 1 or debug == 4 or debug == 5):
            print(term.render('    ${BOLD}${CYAN}Sender: %i bytes read:${NORMAL}') % len(read))
        if(debug == 4 or debug >= 5):
            print hexdump(read, indent=True)

        self.receiver.to_remote_buffer += read
Пример #10
0
 def cmd_pn532(self, *cmd):
     "Transmit a command to the PN532 and receive the response"
     result = self.pn532_transceive(binascii.unhexlify("".join("".join(cmd).split())))
     print utils.hexdump(result.data)
     
     parsed = self.pn532_parse(result.data)
     if len(parsed) > 0:
         print "\n".join(parsed) + "\n"
Пример #11
0
    def cmd_pn532(self, *cmd):
        "Transmit a command to the PN532 and receive the response"
        result = self.pn532_transceive(
            binascii.unhexlify("".join("".join(cmd).split())))
        print utils.hexdump(result.data)

        parsed = self.pn532_parse(result.data)
        if len(parsed) > 0:
            print "\n".join(parsed) + "\n"
Пример #12
0
    def cmd_selectfile(self, fid):
        """Select a file on the card."""

        fid = binascii.a2b_hex("".join(fid.split()))

        result = self.select_file(0, 0, fid)
        if len(result.data) > 0:
            print utils.hexdump(result.data)
            print self.sel_ret_decode(result.data)
Пример #13
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 in range(len(self.res)):
         p = self._elt2pkt(self.res[i])
         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(self.res[i]))
         hexdump(p)
Пример #14
0
 def padding(self, lfilter=None):
     """Same as hexraw(), for Padding layer"""
     for i in range(len(self.res)):
         p = self._elt2pkt(self.res[i])
         if p.haslayer(Padding):
             if lfilter is None or lfilter(p):
                 print "%s %s %s" % (conf.color_theme.id(i,fmt="%04i"),
                                     p.sprintf("%.time%"),
                                     self._elt2sum(self.res[i]))
                 hexdump(p.getlayer(Padding).load)
Пример #15
0
 def padding(self, lfilter=None):
     """Same as hexraw(), for Padding layer"""
     for i in range(len(self.res)):
         p = self._elt2pkt(self.res[i])
         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(self.res[i]))
                 hexdump(p.getlayer(conf.padding_layer).load)
Пример #16
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 in range(len(self.res)):
         p = self._elt2pkt(self.res[i])
         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(self.res[i]))
         if p.haslayer(conf.raw_layer):
             hexdump(p.getlayer(conf.raw_layer).load)
Пример #17
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)
Пример #18
0
 def padding(self, lfilter=None):
     """Same as hexraw(), for Padding layer"""
     for i 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)
Пример #19
0
def decode(data, context=None, level=0, tags=tags):
    result = []
    while len(data) > 0:
        if ord(data[0]) in (0x00, 0xFF):
            data = data[1:]
            continue

        ber_class, constructed, tag, length, value, data = tlv_unpack(data)

        interpretation = tags.get(context, tags.get(None, {})).get(tag, None)
        if interpretation is None:
            if not constructed: interpretation = [binary, "Unknown field"]
            else:
                interpretation = [
                    recurse, "Unknown structure",
                    ber_class in (0, 1) and context or None
                ]

            interpretation[1] = "%s (%s class)" % (interpretation[1],
                                                   BER_CLASSES[ber_class])
            interpretation = tuple(interpretation)

        current = ["\t" * level]
        current.append("Tag 0x%02X, Len 0x%02X, '%s':" %
                       (tag, length, interpretation[1]))

        if interpretation[0] is recurse:
            current.append("\n")
            current.append(
                decode(value, interpretation[2], level + 1, tags=tags))
        elif interpretation[0] is number:
            num = 0
            for i in value:
                num = num * 256
                num = num + ord(i)
            current.append(" 0x%02x (%i)" % (num, num))
        elif interpretation[0] is ascii:
            current.append(" %s" % value)
        elif interpretation[0] is utf8:
            current.append(" %s" % unicode(value, "utf-8"))
        elif interpretation[0] is binary:
            if len(value) < 0x10:
                current.append(" %s" % utils.hexdump(value, short=True))
            else:
                current.append("\n" + "\t" * (level + 1))
                current.append(("\n" + "\t" * (level + 1)).join(
                    utils.hexdump(value).splitlines()))
        elif callable(interpretation[0]):
            current.append(("\n" + "\t" * (level + 1)).join(
                interpretation[0](value).splitlines()))

        result.append("".join(current))

    return "\n".join(result)
Пример #20
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)
Пример #21
0
def dump(data):
    print "Dump following (%i bytes)" % (len(data))
    print utils.hexdump(data)
    try:
        print "Trying TLV parse:"
        print TLV_utils.decode(data, tags=card.TLV_OBJECTS, context = card.DEFAULT_CONTEXT)
        print "TLV parsed successfully"
    except (SystemExit, KeyboardInterrupt):
        raise
    except:
        print "TLV error"
        pass
Пример #22
0
 def nzpadding(self, lfilter=None):
     """Same as padding() but only non null padding"""
     for i in range(len(self.res)):
         p = self._elt2pkt(self.res[i])
         if p.haslayer(Padding):
             pad = p.getlayer(Padding).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(self.res[i]))
                 hexdump(p.getlayer(Padding).load)
Пример #23
0
 def nzpadding(self, lfilter=None):
     """Same as padding() but only non null padding"""
     for i in range(len(self.res)):
         p = self._elt2pkt(self.res[i])
         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(self.res[i]))
                 hexdump(p.getlayer(conf.padding_layer).load)
Пример #24
0
 def cmd_enc(self, *args):
     "Encrypt or decrypt with openssl-like interface"
     
     args = list(args)
     
     MODE_DECRYPT = "-d"
     MODE_ENCRYPT = "-e"
     mode = MODE_ENCRYPT
     if "-d" in args:
         mode = MODE_DECRYPT
     
     input = None
     if "-in" in args:
         i = args.index("-in")
         input = args[i+1]
     
     if "-K" not in args:
         raise ValueError, "Must specify key with -K"
     i = args.index("-K")
     key = args[i+1]
     key = binascii.a2b_hex("".join(key.split()))
     
     iv = None
     if "-iv" in args:
         i = args.index("-iv")
         iv = args[i+1]
         iv = binascii.a2b_hex("".join(iv.split()))
     
     cipher = "des"
     if args[0][0] != "-":
         cipher = args[0]
     
     text = None
     if "-text" in args:
         if input is not None:
             raise ValueError, "Can't give -in and -text"
         i = args.index("-text")
         text = binascii.a2b_hex("".join(args[i+1].split()))
     
     if text is None:
         if input is None:
             text = self.card.last_result.data
         else:
             fp = file(input)
             text = fp.read()
             fp.close()
     
     result = crypto_utils.cipher(mode == MODE_ENCRYPT, cipher, key, text, iv)
     
     self.card.last_result = utils.R_APDU(result+"\x00\x00")
     print utils.hexdump(result)
Пример #25
0
 def encrypt_command(self, tlv_data):
     config = self.get_config(SE_APDU, TEMPLATE_CT)
     
     if config.algorithm is None: ## FIXME: Find out the correct way to determine this
         return tlv_data
     
     result = []
     for data in tlv_data:
         tag, length, value, marks = data
         if self.MARK_ENCRYPT in marks and tag not in (0xff, 0x00):
             t = tag & ~(0x01)
             if t == 0x84:
                 value_ = self.pad(value)
                 if generic_card.DEBUG:
                     print "| Tag 0x%02x, length 0x%02x, encrypting (with ISO padding): " % (tag, length)
                     print "|| " + "\n|| ".join( utils.hexdump( value_ ).splitlines() )
                 
                 value = crypto_utils.cipher( True, 
                     self.get_cipherspec(config),
                     self.get_key(config),
                     value_,
                     self.get_iv(config) )
                 
                 if generic_card.DEBUG:
                     print "| Encrypted result of length 0x%02x:" % len(value)
                     print "|| " + "\n|| ".join( utils.hexdump(value).splitlines() )
                     print
             elif t == 0x86:
                 pi = value[0]
                 value_ = self.pad(value[1:], ord(pi))
                 if generic_card.DEBUG:
                     print "| Tag 0x%02x, length 0x%02x, encrypting (with padding type %x): " % (tag, length, ord(pi))
                     print "|| " + "\n|| ".join( utils.hexdump( value_ ).splitlines() )
                 
                 value = pi + crypto_utils.cipher( True,
                     self.get_cipherspec(config),
                     self.get_key(config),
                     value_,
                     self.get_iv(config) )
                 
                 if generic_card.DEBUG:
                     print "| Encrypted result of length 0x%02x:" % len(value)
                     print "|| " + "\n|| ".join( utils.hexdump(value).splitlines() )
                     print
             
             result.append( (tag, length, value) )
         else: # Ignore
             result.append(data[:3])
     
     return result
Пример #26
0
    def _real_send(self, apdu):
        apdu_binary = apdu.render()

        if DEBUG:
            print ">> " + utils.hexdump(apdu_binary, indent=3)

        result_binary = self.reader.transceive(apdu_binary)
        result = apdu.RESPONSE_CLASS(result_binary)

        self.last_apdu = apdu

        if DEBUG:
            print "<< " + utils.hexdump(result_binary, indent=3)
        return result
Пример #27
0
def generate_package(bid=0, bulkstate=1, dbg=False):
    # Generate bulk_info array
    bulk_info_array = ""
    for i in range(0, 2):
        bulk_info = init_bulk_info(i, bulkstate)
        bulk_info_array += buffer(bulk_info)[:]

    # Generate botbulk_info
    botbulk_info = init_botbulk_info(1, i+1)

    # Generate bot_rheader
    size = 20 + 8 * botbulk_info.logsize
    bot_rheader = init_bot_rheader(bid, size)

    # Construct data package
    data = buffer(bot_rheader)[:] \
            + pencrypt(buffer(botbulk_info)[:] + bulk_info_array, bot_rheader.size)

    # Print package content
    if dbg:
        cprint("BOT_RHEADER\n", "yellow"); print hexdump(buffer(bot_rheader)[:])
        cprint("BOTBULK_INFO\n", "yellow"); print hexdump(buffer(botbulk_info)[:])
        cprint("BULK_INFO\n", "yellow"); print hexdump(buffer(bulk_info_array)[:])
        cprint("Data Package\n", "yellow"); print hexdump(data)

    return data
Пример #28
0
 def _real_send(self, apdu):
     apdu_binary = apdu.render()
     
     if DEBUG:
         print ">> " + utils.hexdump(apdu_binary, indent = 3)
     
     result_binary = self.reader.transceive(apdu_binary)
     result = apdu.RESPONSE_CLASS(result_binary)
     
     self.last_apdu = apdu
     
     if DEBUG:
         print "<< " + utils.hexdump(result_binary, indent = 3)
     return result
Пример #29
0
    def cmd_passive_auth(self, verbose=1):
        "Perform passive authentication"

        hashes = {}
        result = ""
        i = 0

        for name in ("DG1", "DG2", "SOD"):
            fid = None
            for n, f in self.INTERESTING_FILES:
                if n == name:
                    fid = f
                    break
            if fid is None:
                return

            i += 1
            result = self.open_file(fid, 0x0c)
            if self.check_sw(result.sw):
                contents, sw = self.read_binary_file()
                #self.last_result = R_APDU(contents + self.last_sw)

                if name != "SOD":
                    hashes[i] = crypto_utils.hash("SHA", contents)
                else:
                    result = self.verify_cms(contents[4:])

        #print hexdump(result)
        #print "DG1: %s" % hexdump(hashes[i])
        #print "DG2: %s" % hexdump(hashes[2])

        res = TLV_utils.tlv_find_tag(TLV_utils.unpack(result), 0x04)
        if len(res) == 0:
            print "failed to verify EF.SOD"
            return
        else:
            print "verified EF.SOD"

        i = 0
        for tag, length, hash in res:
            i += 1
            if hexdump(hashes[i]) == hexdump(hash):
                print "DG%d hash verified: %s" % (i, binascii.b2a_hex(hash))
            else:
                print "DG%d hash failed:" % i
                print "was:      %s" % binascii.b2a_hex(hashes[i])
                print "expected: %s" % binascii.b2a_hex(hash)
                return
    def cmd_passive_auth(self, verbose=1):
        "Perform passive authentication"

        hashes = {}
        result = ""
        i = 0
        
        for name in ("DG1",  "DG2",  "SOD"):
            fid = None
            for n, f in self.INTERESTING_FILES:
                if n == name: 
                    fid = f
                    break
            if fid is None:
                return

            i += 1
            result = self.open_file(fid, 0x0c)
            if self.check_sw(result.sw):
                contents, sw = self.read_binary_file()
                #self.last_result = R_APDU(contents + self.last_sw)
                
                if name != "SOD":
                    hashes[i] = crypto_utils.hash("SHA", contents)
                else:
                    result = self.verify_cms(contents[4:])
        
        #print hexdump(result)
        #print "DG1: %s" % hexdump(hashes[i])
        #print "DG2: %s" % hexdump(hashes[2])
        
        res = TLV_utils.tlv_find_tag(TLV_utils.unpack(result), 0x04)
        if len(res) == 0:
            print "failed to verify EF.SOD"
            return
        else:
            print "verified EF.SOD"
            
        i = 0
        for tag, length, hash in res:
            i += 1
            if hexdump(hashes[i]) == hexdump(hash):
                print "DG%d hash verified: %s" % (i, binascii.b2a_hex(hash))
            else:
                print "DG%d hash failed:" % i
                print "was:      %s" % binascii.b2a_hex(hashes[i])
                print "expected: %s" % binascii.b2a_hex(hash)
                return
Пример #31
0
 def writePPPControlFrame(self, frame):
     logging.debug('PPP control frame received (%s bytes).' % len(frame))
     logging.log(VERBOSE, hexdump(frame))
     if self.state == SERVER_CALL_CONNECTED_PENDING or \
             self.state == SERVER_CALL_CONNECTED:
         packet = SSTPDataPacket(frame)
         packet.writeTo(self.transport.write)
Пример #32
0
    def _decode_df_name(self, value):
        result = " " + utils.hexdump(value, short=True)
        info = None

        if self.APPLICATIONS.has_key(value):
            info = self.APPLICATIONS[value]
        else:
            for aid, i in self.APPLICATIONS.items():
                if not len(i) > 2 or not i[2].has_key("significant_length"):
                    continue
                if aid[:i[2]["significant_length"]] == value[:i[2][
                        "significant_length"]]:
                    info = i
                    break

        result_array = []
        if info is not None:
            if info[0] is not None:
                result_array.append(("Name", info[0]))

            if len(info) > 1 and not info[1] is None:
                result_array.append(("Description", info[1]))

        if self.VENDORS.has_key(value[:5]):
            result_array.append(("Vendor", self.VENDORS[value[:5]][0]))

        if len(result_array) > 0:
            max_len = max([len(a) for a, b in result_array] + [11]) + 1
            result = result + "\n" + "\n".join([("%%-%is %%s" % max_len) %
                                                (a + ":", b)
                                                for a, b in result_array])
        return result
Пример #33
0
 def writePPPDataFrame(self, frame):
     if __debug__:
         logging.debug('PPP data frame received (%s bytes).' % len(frame))
         logging.log(VERBOSE, hexdump(frame))
     if self.state == SERVER_CALL_CONNECTED:
         packet = SSTPDataPacket(frame)
         packet.writeTo(self.transport.write)
Пример #34
0
 def _conn_text(self, conn):
     txt = []
     txt.extend(
         format_keyvals(
             [(h+":", v) for (h, v) in sorted(conn.headers.itemPairs())],
             key = "header",
             val = "text"
         )
     )
     txt.append("\n\n")
     if conn.content:
         if self.binary or utils.isBin(conn.content):
             for offset, hex, s in utils.hexdump(conn.content):
                 txt.extend([
                     ("offset", offset),
                     " ",
                     ("text", hex),
                     "   ",
                     ("text", s),
                     "\n"
                 ])
         else:
             for i in conn.content.splitlines():
                 txt.append(
                     ("text", i),
                 )
                 txt.append(
                     ("text", "\n"),
                 )
     return urwid.ListBox([urwid.Text(txt)])
Пример #35
0
 def writePPPControlFrame(self, frame):
     logging.debug('PPP control frame received (%s bytes).' % len(frame))
     logging.log(VERBOSE, hexdump(frame))
     if self.state == SERVER_CALL_CONNECTED_PENDING or \
             self.state == SERVER_CALL_CONNECTED:
         packet = SSTPDataPacket(frame)
         packet.writeTo(self.transport.write)
Пример #36
0
 def sstpDataPacketReceived(self, data):
     logging.debug('Forwarding SSTP data to pppd (%s bytes).' % len(data))
     logging.log(VERBOSE, hexdump(data))
     if self.pppd is None:
         print('pppd is None.')
         return
     self.pppd.writeFrame(data)
Пример #37
0
 def writePPPDataFrame(self, frame):
     if __debug__:
         logging.debug('PPP data frame received (%s bytes).' % len(frame))
         logging.log(VERBOSE, hexdump(frame))
     if self.state == SERVER_CALL_CONNECTED:
         packet = SSTPDataPacket(frame)
         packet.writeTo(self.transport.write)
	def FileTreeDoubleClick(self, event): 
		'''
		Event Listener for Double Click on a File Tree Item.  This method will display the hexdump of the clicked item in a new notebook tab. 
		'''
		item = self.fileTree.selection()[0]

		#check that clicked item is a file
		if os.path.isfile(item): 
			self.evtLogger.logEvent(self, "Open Hexview of file: "+item)

			#create new frame
			self.fileViewFrame = Frame(self.nb)
			self.fileViewFrame.grid(row=0, column=0, columnspan=2, sticky='new')

			#create scrolled text box to display hex dump
			self.fileViewText = ScrolledText(self.fileViewFrame, height=40)
			self.fileViewText.grid(row=0, column=0, sticky='nsew', pady=5, padx=5)

			#read in contents of selected item
			with open(item, 'rb') as f: 
				content = f.read() 
				text = u.hexdump(content)

				#display contents in new scrolled text box
				self.fileViewText.insert(END, text)
				self.fileViewText.config(state=DISABLED)

			#add Frame to notebook
			self.nb.add(self.fileViewFrame, text=self.fileTree.item(item, "text"))
			#select newly added tab
			self.selectCurrentTab()
Пример #39
0
 def _real_send(self, apdu):
     apdu_binary = apdu.render()
     
     if DEBUG:
         print ">> " + utils.hexdump(apdu_binary, indent = 3)
     
     result_binary = self.reader.transceive(apdu_binary)
     result = R_APDU(result_binary)
     
     self.last_apdu = apdu
     self.last_sw = result.sw
     self.sw_changed = True
     
     if DEBUG:
         print "<< " + utils.hexdump(result_binary, indent = 3)
     return result
Пример #40
0
 def cmd_read(self, address, n):
     cout("Reading %d bytes of Flash starting at 0x%04X:\n" % (n, address))
     mem = ""
     a = address
     col = 0
     while n:
         al = (a & 0x00FF) >> 0
         ah = (a & 0xFF00) >> 8
         l = min(n, 64)
         self.serial.tx('f' + chr(al) + chr(ah) + chr(l) + '\n')
         r = self.serial.rx(l + 1)
         if len(r) == l + 1 and r[-1] == '$':
             if col == 64:
                 cout('\n')
                 col = 0
             cout('.')
             flushout()
             col += 1
             mem += r[:-1]
             n -= l
             a += l
         else:
             cout("Error reading %d bytes of Flash starting at 0x%04X.\n" %
                  (l, a))
             break
     cout('\n')
     cout(hexdump(address, mem) + '\n')
Пример #41
0
 def outReceived(self, data):
     if __debug__:
         logging.log(VERBOSE, "Raw data: %s", hexdump(data))
     frames, self.frameBuffer, self.frameEscaped = \
             unescape(data, self.frameBuffer, self.frameEscaped)
     for frame in frames:
         self.pppFrameReceived(frame)
Пример #42
0
 def _decode_df_name(self, value):
     result = " " + utils.hexdump(value, short=True)
     info = None
     
     if self.APPLICATIONS.has_key(value):
         info = self.APPLICATIONS[value]
     else:
         for aid, i in self.APPLICATIONS.items():
             if not len(i) > 2 or not i[2].has_key("significant_length"):
                 continue
             if aid[ :i[2]["significant_length"] ] == value[ :i[2]["significant_length"] ]:
                 info = i
                 break
     
     result_array = []
     if info is not None:
         if info[0] is not None:
             result_array.append( ("Name", info[0]) )
         
         if len(info) > 1 and not info[1] is None:
             result_array.append( ("Description", info[1] ) )
     
     if self.VENDORS.has_key(value[:5]):
         result_array.append( ("Vendor", self.VENDORS[ value[:5] ][0]) )
     
     if len(result_array) > 0:
         max_len = max( [len(a) for a,b in result_array] + [11] ) + 1
         result = result + "\n" + "\n".join( [("%%-%is %%s" % max_len) % (a+":",b) for a,b in result_array] )
     return result
Пример #43
0
Файл: main.py Проект: duparq/hwa
 def cmd_read(self, address, n):
     cout("Reading %d bytes of Flash starting at 0x%04X:\n" % (n,address))
     mem = ""
     a = address
     col = 0
     while n:
         al = (a & 0x00FF) >> 0
         ah = (a & 0xFF00) >> 8
         l = min(n, 64)
         self.serial.tx('f'+chr(al)+chr(ah)+chr(l)+'\n')
         r = self.serial.rx(l+1)
         if len(r) == l+1 and r[-1]=='$':
             if col == 64:
                 cout('\n')
                 col = 0
             cout('.')
             flushout()
             col += 1
             mem += r[:-1]
             n -= l
             a += l
         else:
             cout("Error reading %d bytes of Flash starting at 0x%04X.\n" % (l,a))
             break
     cout('\n')
     cout(hexdump(address, mem)+'\n')
Пример #44
0
 def outReceived(self, data):
     if __debug__:
         logging.log(VERBOSE, "Raw data: %s", hexdump(data))
     frames, self.frameBuffer, self.frameEscaped = \
             unescape(data, self.frameBuffer, self.frameEscaped)
     for frame in frames:
         self.pppFrameReceived(frame)
Пример #45
0
 def do_block(buffer, block):
     block_ = self.pad("".join(block), pi = PI_ISO)
     offset = sum( [len(b) for b in buffer] )
     buffer.append(block_)
     del block[:]
     if print_buffer:
         print "|| " + "\n|| ".join( utils.hexdump( block_, offset = offset ).splitlines() )
Пример #46
0
    def _process_flow(self, f):
        if self.filt and not f.match(self.filt):
            return

        if f.response:
            sz = utils.pretty_size(len(f.response.content))
            if self.o.verbosity > 0:
                result = " << %s %s" % (str_response(f.response), sz)
            if self.o.verbosity > 1:
                result = result + "\n\n" + self.indent(4, f.response.headers)
            if self.o.verbosity > 2:
                if utils.isBin(f.response.content):
                    d = utils.hexdump(f.response.content)
                    d = "\n".join("%s\t%s %s" % i for i in d)
                    cont = self.indent(4, d)
                elif f.response.content:
                    cont = self.indent(4, f.response.content)
                else:
                    cont = ""
                result = result + "\n\n" + cont
        elif f.error:
            result = " << %s" % f.error.msg

        if self.o.verbosity == 1:
            print >> self.outfile, str_request(f.request)
            print >> self.outfile, result
        elif self.o.verbosity == 2:
            print >> self.outfile, str_request(f.request)
            print >> self.outfile, self.indent(4, f.request.headers)
            print >> self.outfile
            print >> self.outfile, result
            print >> self.outfile, "\n"
        elif self.o.verbosity >= 3:
            print >> self.outfile, str_request(f.request)
            print >> self.outfile, self.indent(4, f.request.headers)
            if utils.isBin(f.request.content):
                print >> self.outfile, self.indent(
                    4, utils.hexdump(f.request.content))
            elif f.request.content:
                print >> self.outfile, self.indent(4, f.request.content)
            print >> self.outfile
            print >> self.outfile, result
            print >> self.outfile, "\n"

        self.state.delete_flow(f)
        if self.o.wfile:
            self.fwriter.add(f)
Пример #47
0
 def cmd_read_identification_zone(self):
     "Read the identification zone"
     data = self._get_binary(0x0948, length=0x60)
     
     chaine_initiale = binascii.b2a_hex(data[4:])
     print "chaine initiale", chaine_initiale
     #suppression_des_3 = re.sub(r'x', '3', re.sub(r'3', '', re.sub(r'33', "x", chaine_initiale) ) )
     #suppression_des_3 = "".join(chaine_initiale.split("3")) + "0"
     suppression_des_3 = []
     still_there = True
     for index,char in enumerate(chaine_initiale):
         if still_there and index % 8 == 0:
             if char == "3":
                 continue
             else:
                 still_there = False
         suppression_des_3.append(char)
     suppression_des_3 = "".join(suppression_des_3)
     
     print "suppression des 3", suppression_des_3
     new_data = binascii.a2b_hex(suppression_des_3)
     print utils.hexdump(new_data)
     
     fields = [
         (None, 2),
         ("card number", 19),
         ("usage code", 3),
         ("valid from", 4),
         ("language code", 3),
         ("valid till", 4),
         ("currency code", 3),
         ("denomination", 1),
         ("(unknown)", 3),
         ("card holder", 26*2)
     ]
     
     print "Decoding:"
     pos = 0
     for name, length in fields:
         value = suppression_des_3[pos:pos+length]
         pos = pos+length
         if name is None:
             continue
         print "\t%20s: %s" % (name, value)
     
     print "\t%20s '%s'" % ("", binascii.a2b_hex(value))
Пример #48
0
    def _process_flow(self, f):
        if self.filt and not f.match(self.filt):
            return

        if f.response:
            sz = utils.pretty_size(len(f.response.content))
            if self.o.verbosity > 0:
                result = " << %s %s"%(str_response(f.response), sz)
            if self.o.verbosity > 1:
                result = result + "\n\n" + self.indent(4, f.response.headers)
            if self.o.verbosity > 2:
                if utils.isBin(f.response.content):
                    d = utils.hexdump(f.response.content)
                    d = "\n".join("%s\t%s %s"%i for i in d)
                    cont = self.indent(4, d)
                elif f.response.content:
                    cont = self.indent(4, f.response.content)
                else:
                    cont = ""
                result = result + "\n\n" + cont
        elif f.error:
            result = " << %s"%f.error.msg

        if self.o.verbosity == 1:
            print >> self.outfile, str_request(f.request)
            print >> self.outfile, result
        elif self.o.verbosity == 2:
            print >> self.outfile, str_request(f.request)
            print >> self.outfile, self.indent(4, f.request.headers)
            print >> self.outfile
            print >> self.outfile, result
            print >> self.outfile, "\n"
        elif self.o.verbosity >= 3:
            print >> self.outfile, str_request(f.request)
            print >> self.outfile, self.indent(4, f.request.headers)
            if utils.isBin(f.request.content):
                print >> self.outfile, self.indent(4, utils.hexdump(f.request.content))
            elif f.request.content:
                print >> self.outfile, self.indent(4, f.request.content)
            print >> self.outfile
            print >> self.outfile, result
            print >> self.outfile, "\n"

        self.state.delete_flow(f)
        if self.o.wfile:
            self.fwriter.add(f)
Пример #49
0
 def sstpDataPacketReceived(self, data):
     if __debug__:
         logging.debug('Forwarding SSTP data to pppd (%s bytes).' % len(data))
         logging.log(VERBOSE, hexdump(data))
     if self.pppd is None:
         print('pppd is None.')
         return
     self.pppd.writeFrame(data)
Пример #50
0
def decode(data, context = None, level = 0, tags=tags):
    result = []
    while len(data) > 0:
        if ord(data[0]) in (0x00, 0xFF):
            data = data[1:]
            continue
        
        ber_class, constructed, tag, length, value, data = tlv_unpack(data)
        
        interpretation = tags.get(context, tags.get(None, {})).get(tag, None)
        if interpretation is None:
            if not constructed: interpretation = [binary, "Unknown field"]
            else: interpretation = [recurse, "Unknown structure", ber_class in (0, 1) and context or None]
            
            interpretation[1] = "%s (%s class)" % (interpretation[1], BER_CLASSES[ber_class])
            interpretation = tuple(interpretation)
        
        current = ["\t"*level]
        current.append("Tag 0x%02X, Len 0x%02X, '%s':" % (tag, length, interpretation[1]))
        
        if interpretation[0] is recurse:
            current.append("\n")
            current.append( decode(value, interpretation[2], level+1, tags=tags) )
        elif interpretation[0] is number:
            num = 0
            for i in value:
                num = num * 256
                num = num + ord(i)
            current.append( " 0x%02x (%i)" % (num, num))
        elif interpretation[0] is ascii:
            current.append( " %s" % value)
        elif interpretation[0] is utf8:
            current.append( " %s" % unicode(value, "utf-8"))
        elif interpretation[0] is binary:
            if len(value) < 0x10:
                current.append( " %s" % utils.hexdump(value, short=True))
            else:
                current.append( "\n" + "\t"*(level+1) )
                current.append( ("\n" + "\t"*(level+1)).join( utils.hexdump(value).splitlines() ) )
        elif callable(interpretation[0]):
            current.append( ("\n"+"\t"*(level+1)).join(interpretation[0](value).splitlines()) )
        
        result.append( "".join(current) )
    
    return "\n".join(result)
Пример #51
0
    def handle_write(self):
        # This conditional stuff could really stand to be cleaned up
        sent = ""
        modified_data = self.receiver.from_remote_buffer

        # Perform search/replace as appropriate
        if sr_request:
            # Check if regex
            if sr_request[0]:
                if len(re.findall(sr_request[1], self.receiver.from_remote_buffer)) > 0:
                    modified_data = re.sub(sr_request[1], sr_request[2], self.receiver.from_remote_buffer)
                    print (
                        term.render(
                            "${YELLOW}Sender: Replacing regex %s with %s:${NORMAL}"
                            % (repr(sr_request[1]), repr(sr_request[2]))
                        )
                    )
            else:
                if sr_request[1] in self.receiver.from_remote_buffer:
                    modified_data = self.receiver.from_remote_buffer.replace(sr_request[1], sr_request[2])
                    print (
                        term.render(
                            "${YELLOW}Sender: Replacing literal %s with %s:${NORMAL}"
                            % (repr(sr_request[1]), repr(sr_request[2]))
                        )
                    )

        # Check if we want to fuzz the request or not
        if fuzz_request:
            modified_data = self.fuzzer.mutate(modified_data)

        sent = self.send(modified_data)

        # Store REQUEST and time of request for logging
        # Msg received from the server (i.e. SMTP request "EHLO foobar.com")
        if self.logdata:
            self.logdata.request_data += modified_data
            if not self.logdata.request_time:
                self.logdata.request_time = postgres_datetime_ms()

        if debug == 1 or debug == 4 or debug == 5:
            print (term.render("${BOLD}${RED}Sender: %i bytes sent:${NORMAL}") % sent)
        if debug == 4 or debug >= 5:
            print hexdump(modified_data, indent=False)
        self.receiver.from_remote_buffer = self.receiver.from_remote_buffer[sent:]
    def showDecodeProgress(self, detail=False):
        utils.logger.info("")
        if detail:
            utils.logger.info(
                utils.hexdump(self.contents, hasDecoded=self._hasDecoded))

        percDecoded = (self._hasDecoded.count(True) /
                       float(len(self._hasDecoded))) * 100.0
        utils.logger.info("")
        utils.logger.info("%3.3f %% Decoded" % percDecoded)
        utils.logger.info("")
        utils.logger.info(
            "Inst#  Addr    Bytes                                Assembly")
        utils.logger.info(
            "▔▔▔▔▔  ▔▔▔▔    ▔▔▔▔▔                                ▔▔▔▔▔▔▔▔")

        sortedInstructionKeys = sorted(self.instructionKeys)
        for idx, instKey in enumerate(sortedInstructionKeys):
            startIdx, instLen = instKey

            # check if there are skipped bytes...

            if idx > 0:
                lastStartIdx, lastInstLen = sortedInstructionKeys[idx - 1]
                if False in self._hasDecoded[lastStartIdx +
                                             lastInstLen:startIdx]:
                    self._showUnknownBytes(lastStartIdx + lastInstLen,
                                           startIdx)

            instruction = self.instructions[instKey]
            #instructionBytes = repr(self.contents[startIdx:startIdx+instLen])
            instructionBytes = ' '.join(
                '{:02x}'.format(x)
                for x in self.objectSource[startIdx:startIdx + instLen])
            prefix, postfix = utils.colors.NORMAL, utils.colors.NORMAL
            if instruction == UNKNOWN_INSTRUCTION:
                prefix = utils.colors.RED
            addr = hex(startIdx)
            if addr in self.labelAddresses:
                label = "label_%s" % addr
                utils.logger.info("       %-5s   %-30s ▏  %s:" %
                                  ("", "", label))
            utils.logger.info(" %s%-3s   %-5s   %-30s ▏     %s%s" %
                              (prefix, idx + 1, addr, instructionBytes,
                               instruction, postfix))

        if self.runningErrorIdx != None:
            startIdx, instLen = self.runningErrorIdx[0], len(
                self.runningErrorIdx)
            self._showUnknownBytes(startIdx, startIdx + instLen,
                                   utils.colors.RED)
        elif False in self._hasDecoded:
            startIdx, instLen = sortedInstructionKeys[-1]
            unknownStartIdx = startIdx + instLen
            endIdx = len(self.objectSource)
            self._showUnknownBytes(unknownStartIdx, endIdx,
                                   utils.colors.YELLOW)
Пример #53
0
    def split_guess(self, attr_list, verbose=False):
        """Split the content of the Get_Attribute_List response with the known attribute list

        Return a list of (attr, value) tuples, or None if an error occurred
        """
        content = self.content
        offset = 0
        idx = 0
        result = []
        while offset < len(content):
            attr, status = struct.unpack("<HH", content[offset:offset + 4])
            if attr not in attr_list:
                if verbose:
                    sys.stderr.write("Error: Get_Attribute_List response contains an unknown attribute\n")
                    sys.stderr.write("... all attrs " + ','.join(hex(a) for a in attr_list) + '\n')
                    sys.stderr.write(utils.hexdump(content[offset:], indentlvl="... ") + "\n")
                return
            if attr != attr_list[idx]:
                if verbose:
                    sys.stderr.write("Error: attr {:#x} not in position {} of attr list\n".format(attr, idx))
                    sys.stderr.write("... all attrs " + ','.join(hex(a) for a in attr_list) + '\n')
                return
            offset += 4
            attr_len = None
            if idx == len(attr_list) - 1:
                # Last attribute
                attr_len = len(content) - offset
            else:
                # Find next attribute header
                nexthdr = struct.pack('<HH', attr_list[idx + 1], 0)
                for i in range(offset + 1, len(content) - 4):
                    if content[i:i + 4] == nexthdr:
                        attr_len = i - offset
                        break
            if attr_len is None:
                if verbose:
                    sys.stderr.write("Error: length not found. Here is the remaining\n")
                    sys.stderr.write("... all attrs " + ','.join(hex(a) for a in attr_list) + '\n')
                    sys.stderr.write(utils.hexdump(content[offset:], indentlvl="... ") + "\n")
                return
            result.append((attr, content[offset:offset + attr_len]))
            offset += attr_len
            idx += 1
        return result
Пример #54
0
    def cmd_list(self, *options):
        """List all EFs and DFs in current DF. Call with -l for verbose information (caution: deselects current file)"""
        dirs = self.list_x(self.LIST_X_DF)
        files = self.list_x(self.LIST_X_EF)

        if "-l" in options:
            response_DF = {}
            response_EF = {}
            for DF in dirs:
                response_DF[DF] = self.select_file(0x01, self.SELECT_P2, DF)
                self.select_file(0x03, 0x00, "")
            for EF in files:
                response_EF[EF] = self.select_file(0x02, self.SELECT_P2, EF)

        self.sw_changed = False
        self.last_delta = None

        if "-l" in options:
            print self._ls_l_template % {
                "name": "Name",
                "type": "Type",
                "size": "Size"
            }
            dirs.sort()
            files.sort()
            for FID in dirs:
                name = "[" + utils.hexdump(FID, short=True) + "]"
                type = "DF"
                size = ""
                print self._ls_l_template % locals()
            for FID in files:
                name = " " + utils.hexdump(FID, short=True) + " "
                type = "EF"
                v = self._find_recursive(self.LS_L_SIZE_TAG,
                                         response_EF[FID].data)
                if v:
                    size = self._str_to_long(v)
                else:
                    size = "n/a"
                print self._ls_l_template % locals()
        else:
            print "\n".join(
                ["[%s]" % utils.hexdump(a, short=True) for a in dirs] +
                [" %s " % utils.hexdump(a, short=True) for a in files])
 def derive_seed(mrz2, verbose=0):
     """Derive Kseed from the second line of the MRZ according to TR-PKI mrtds ICC read-only access v1.1 annex F.1.1"""
     if verbose:
         print "MRZ_information: '%s' + '%s' + '%s'" % (mrz2[0:10], mrz2[13:20], mrz2[21:28])
     MRZ_information = mrz2[0:10] + mrz2[13:20] + mrz2[21:28]
     H = sha1(MRZ_information).digest()
     Kseed = H[:16]
     if verbose:
         print "SHA1('%s')[:16] =\nKseed   = %s" % (MRZ_information, hexdump(Kseed))
     return Kseed