def _parse(self, contents):
     self._rawdata = contents
     self._tlvdata = TLV_utils.unpack(contents)
     
     tmp = TLV_utils.tlv_find_tag(self._tlvdata, 0xEA, num_results = 1)
     if len(tmp) == 0:
         raise ValueError, "Can't parse information file, tag 0xEA not found"
     tmp = TLV_utils.tlv_find_tag(tmp, 0x85, num_results = 1)
     if len(tmp) == 0:
         raise ValueError, "Can't parse information file, tag 0x85 not found"
     self._mainblob = tmp[0][2]
     
     tmp = self._mainblob
     some_id, tmp = tmp[:4], tmp[4:]
     
     ascii_field_len = ord(tmp[0])
     tmp = tmp[1:]
     
     ascii_field, tmp = tmp[:ascii_field_len], tmp[ascii_field_len:]
     self._maindata = ascii_field.split(" ")
     
     if len(tmp) > 0:
         if tmp[0] == "\x01":
             tmp = tmp[1:]
             birthdate_bin, tmp = tmp[:4], tmp[4:]
             
             birthdate = binascii.b2a_hex(birthdate_bin)
             self._birthdate = datetime.date( int(birthdate[0:4]), int(birthdate[4:6]), int(birthdate[6:8]) )
     
     if len(tmp) > 0:
         print "Warning: unparsed data trailing: %r" % tmp
Exemple #2
0
    def _parse(self, contents):
        self._rawdata = contents
        self._tlvdata = TLV_utils.unpack(contents)

        tmp = TLV_utils.tlv_find_tag(self._tlvdata, 0xEA, num_results=1)
        if len(tmp) == 0:
            raise ValueError, "Can't parse information file, tag 0xEA not found"
        tmp = TLV_utils.tlv_find_tag(tmp, 0x85, num_results=1)
        if len(tmp) == 0:
            raise ValueError, "Can't parse information file, tag 0x85 not found"
        self._mainblob = tmp[0][2]

        tmp = self._mainblob
        some_id, tmp = tmp[:4], tmp[4:]

        ascii_field_len = ord(tmp[0])
        tmp = tmp[1:]

        ascii_field, tmp = tmp[:ascii_field_len], tmp[ascii_field_len:]
        self._maindata = ascii_field.split(" ")

        if len(tmp) > 0:
            if tmp[0] == "\x01":
                tmp = tmp[1:]
                birthdate_bin, tmp = tmp[:4], tmp[4:]

                birthdate = binascii.b2a_hex(birthdate_bin)
                self._birthdate = datetime.date(int(birthdate[0:4]),
                                                int(birthdate[4:6]),
                                                int(birthdate[6:8]))

        if len(tmp) > 0:
            print "Warning: unparsed data trailing: %r" % tmp
 def parse_DG1(self, contents):
     structure = TLV_utils.unpack(contents)
     try:
         mrz = TLV_utils.tlv_find_tag(structure, 0x5F1F, 1)[0][2]
     except IndexError:
         raise PassportParseError, "Could not find MRZ information in DG1"
     # Length of an MRZ line is either 30+5 or 31+5 or 39+5, depending on document type. (LDS technical report 2004, section 16.1)
     mrz_data = (mrz[:len(mrz)/2], mrz[len(mrz)/2:])
     self.dg1_mrz = mrz_data
     self._parse_mrz(mrz_data)
Exemple #4
0
 def parse_DG1(self, contents):
     structure = TLV_utils.unpack(contents)
     try:
         mrz = TLV_utils.tlv_find_tag(structure, 0x5F1F, 1)[0][2]
     except IndexError:
         raise PassportParseError, "Could not find MRZ information in DG1"
     # Length of an MRZ line is either 30+5 or 31+5 or 39+5, depending on document type. (LDS technical report 2004, section 16.1)
     mrz_data = (mrz[:len(mrz) / 2], mrz[len(mrz) / 2:])
     self.dg1_mrz = mrz_data
     self._parse_mrz(mrz_data)
Exemple #5
0
 def process_apdu(self, apdu):
     if apdu.cla & 0x0c in (0x0c, 0x08):
         tlv_data = TLV_utils.unpack(apdu.data, with_marks = apdu.marks, include_filler=True)
         
         tlv_data = self.encrypt_command(tlv_data)
         tlv_data = self.authenticate_command(apdu, tlv_data)
         
         data = TLV_utils.pack(tlv_data, recalculate_length = True)
         new_apdu = C_APDU(apdu, data = data)
         
         return new_apdu
     else:
         return apdu
Exemple #6
0
 def process_rapdu(self, rapdu):
     result = rapdu
     if self.last_c_apdu.cla & 0x0c in (0x0c, 0x08):
         tlv_c_data = TLV_utils.unpack(self.last_c_apdu.data)
         
         must_authenticate = False
         must_decrypt = False
         for data in tlv_c_data:
             if data[0] & ~0x01 == 0xBA:
                 for response_template in data[2]:
                     if response_template[0] == 0x8E:
                         must_authenticate = True
                     if response_template[0] & ~0x01 in (0x84, 0x86):
                         must_decrypt = True
         
         if must_authenticate or must_decrypt:
             tlv_data = TLV_utils.unpack(rapdu.data, include_filler=True)
             
             try:
                 if must_authenticate:
                     tlv_data = self.authenticate_response(tlv_data)
                 
                 if must_decrypt:
                     tlv_data = self.decrypt_response(tlv_data)
                 
                 #data = TLV_utils.pack(tlv_data, recalculate_length = True)
                 data, sw = self.deformat_response(tlv_data, rapdu.sw)
                 new_apdu = R_APDU(rapdu, data = data, sw = sw)
                 
                 result = new_apdu
             except ValueError:
                 print "Warning: Can't authenticate/decrypt response due to exception being raised"
                 traceback.print_exc(limit=2)
         
     
     return result
    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
Exemple #8
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
Exemple #9
0
 def list_x(self, x):
     "Get a list of x objects, where x is one of 0 (DFs) or 1 (EFs) or 2 (DFs and EFs)"
     ## FIXME I just guessed this information
     result = self.send_apdu(C_APDU(self.APDU_LIST_X, p1=x))
     
     files = []
     unpacked = TLV_utils.unpack(result.data)
     for tag, length, value in unpacked:
         if isinstance(value, list):
             for tag, length, value in value:
                 if tag == 0x86:
                     files.append(value)
         else:
             if tag == 0x86:
                 files.append(value)
     
     return files
Exemple #10
0
 def parse(self, config):
     structure = TLV_utils.unpack(config)
     for data in structure:
         tag, length, value = data
         if tag == 0x80:
             self.mode = ord(value[0]) & 1
             algorithm = (ord(value[0]) >> 2) & 0x7
             self.algorithm = algorithm
         elif tag in (0x83, 0x84):
             self.keyref = ord(value)
             self.keytype = tag
         elif tag == 0x85:
             self.iv = "\x00" * 8
         elif tag == 0x87:
             self.iv = value
         elif tag == 0x88:
             self.iv = None ## FIXME
         else:
             print "Warning: Unknown MSE parameters: tag 0x%02x, length 0x%02x, value: %s" % (tag, length, utils.hexdump(value, short=True))
 def from_data(cls, data, offset = 0, length = None, **kwargs):
     if length is None:
         length = len(data) - offset
     structure = TLV_utils.unpack(data[offset:offset+length])
     return cls(structure=structure, **kwargs)
    def verify_cms(self, data):
        """Verify a pkcs7 SMIME message"""    
        from M2Crypto import SMIME, X509, BIO
        import base64, TLV_utils,  os

        data3 = "-----BEGIN PKCS7-----\n"
        data3 += base64.encodestring(data)
        data3 += "-----END PKCS7-----"    
        #print data3
        
        p7_bio = BIO.MemoryBuffer(data3)

        # Instantiate an SMIME object.
        s = SMIME.SMIME()
        
        # TODO: ugly hack for M2Crypto
        body = TLV_utils.tlv_find_tag(TLV_utils.unpack(data), 0xA0,  1)[0][2]
        thecert = TLV_utils.tlv_find_tag(body, 0xA0,  2)[1][2]

        cert_bio = BIO.MemoryBuffer(TLV_utils.pack(thecert))
        
        # Load the signer's cert.
        x509 = X509.load_cert_bio(cert_bio,  format=0)
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)
        country = str(x509.get_issuer()).split('/')[1][2:]
        #print country
        
        cacert = country + "-cacert.der"
        #print cacert
        
        msgErr =  "couldn't parse certificate to determine URL for CACert, search the intertubes,"
        msg =  "download CACert (convert to DER if necessary) and save it as \n\"%s\"" % cacert
        
        if not os.path.isfile(cacert):
            try:
                v = x509.get_ext("certificatePolicies").get_value()
                start = v.find("CPS: ")
                if start != -1:
                    url = v[start + 5:-1]
                    print "visit %s" % url,  msg
                else:
                    print msgErr,  msg
            except Exception:
                print msgErr,  msg
            return ""
            
        # Load the signer's CA cert. 
        st = X509.X509_Store()
        #st.load_info('main')
        x509CA = X509.load_cert(cacert,  format=0)
        st.add_x509(x509CA)
        s.set_x509_store(st)

        # Load the data, verify it.
        #p7, data = SMIME.smime_load_pkcs7_bio(p7_bio)
        p7 = SMIME.load_pkcs7_bio(p7_bio)
        
        v = s.verify(p7)
        return v
 def parse_DG7(self, contents):
     self.dg7_tlv = TLV_utils.unpack(contents)
Exemple #14
0
 def from_data(cls, data, offset=0, length=None, **kwargs):
     if length is None:
         length = len(data) - offset
     structure = TLV_utils.unpack(data[offset:offset + length])
     return cls(structure=structure, **kwargs)
Exemple #15
0
    def verify_cms(self, data):
        """Verify a pkcs7 SMIME message"""
        from M2Crypto import SMIME, X509, BIO
        import base64, TLV_utils, os

        data3 = "-----BEGIN PKCS7-----\n"
        data3 += base64.encodestring(data)
        data3 += "-----END PKCS7-----"
        #print data3

        p7_bio = BIO.MemoryBuffer(data3)

        # Instantiate an SMIME object.
        s = SMIME.SMIME()

        # TODO: ugly hack for M2Crypto
        body = TLV_utils.tlv_find_tag(TLV_utils.unpack(data), 0xA0, 1)[0][2]
        thecert = TLV_utils.tlv_find_tag(body, 0xA0, 2)[1][2]

        cert_bio = BIO.MemoryBuffer(TLV_utils.pack(thecert))

        # Load the signer's cert.
        x509 = X509.load_cert_bio(cert_bio, format=0)
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)
        country = str(x509.get_issuer()).split('/')[1][2:]
        #print country

        cacert = country + "-cacert.der"
        #print cacert

        msgErr = "couldn't parse certificate to determine URL for CACert, search the intertubes,"
        msg = "download CACert (convert to DER if necessary) and save it as \n\"%s\"" % cacert

        if not os.path.isfile(cacert):
            try:
                v = x509.get_ext("certificatePolicies").get_value()
                start = v.find("CPS: ")
                if start != -1:
                    url = v[start + 5:-1]
                    print "visit %s" % url, msg
                else:
                    print msgErr, msg
            except Exception:
                print msgErr, msg
            return ""

        # Load the signer's CA cert.
        st = X509.X509_Store()
        #st.load_info('main')
        x509CA = X509.load_cert(cacert, format=0)
        st.add_x509(x509CA)
        s.set_x509_store(st)

        # Load the data, verify it.
        #p7, data = SMIME.smime_load_pkcs7_bio(p7_bio)
        p7 = SMIME.load_pkcs7_bio(p7_bio)

        v = s.verify(p7)
        return v
Exemple #16
0
 def parse_DG7(self, contents):
     self.dg7_tlv = TLV_utils.unpack(contents)