def Signature(pe): try: security = pe.OPTIONAL_HEADER.DATA_DIRECTORY[ pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']] except IndexError: print(' No signature') return address = security.VirtualAddress size = security.Size if address == 0: print(' No signature') return signature = pe.write()[address + 8:address + size] if len(signature) != size - 8: print( ' Unable to extract full signature, file is most likely truncated') print(' Extracted: %d bytes' % len(signature)) print(' Expected: %d bytes' % (size - 8)) return try: from pyasn1.codec.der import decoder as der_decoder except ImportError: print(' Signature present but error importing pyasn1 module') return try: from pyasn1_modules import rfc2315 except ImportError: print(' Signature present but error importing pyasn1_modules module') return signatureArg = C2SIP2(signature) contentInfo, _ = der_decoder.decode(signatureArg, asn1Spec=rfc2315.ContentInfo()) contentType = contentInfo.getComponentByName('contentType') contentInfoMap = { (1, 2, 840, 113549, 1, 7, 1): rfc2315.Data(), (1, 2, 840, 113549, 1, 7, 2): rfc2315.SignedData(), (1, 2, 840, 113549, 1, 7, 3): rfc2315.EnvelopedData(), (1, 2, 840, 113549, 1, 7, 4): rfc2315.SignedAndEnvelopedData(), (1, 2, 840, 113549, 1, 7, 5): rfc2315.DigestedData(), (1, 2, 840, 113549, 1, 7, 6): rfc2315.EncryptedData() } content, _ = der_decoder.decode(contentInfo.getComponentByName('content'), asn1Spec=contentInfoMap[contentType]) for line in content.prettyPrint().split('\n'): print(line) oMatch = re.match('( *)value=0x....(.+)', line) if oMatch != None: if sys.version_info[0] > 2: print(oMatch.groups()[0] + ' ' + repr(binascii.a2b_hex(oMatch.groups()[1]).decode())) else: print(oMatch.groups()[0] + ' ' + repr(binascii.a2b_hex(oMatch.groups()[1])))
def testDerCodec(self): substrate = pem.readBase64fromText(self.pem_text_unordered) asn1Object, rest = der_decoder.decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encoder.encode(asn1Object) == substrate contentType = asn1Object['contentType'] substrate = asn1Object['content'] contentInfoMap = { (1, 2, 840, 113549, 1, 7, 1): rfc2315.Data(), (1, 2, 840, 113549, 1, 7, 2): rfc2315.SignedData(), (1, 2, 840, 113549, 1, 7, 3): rfc2315.EnvelopedData(), (1, 2, 840, 113549, 1, 7, 4): rfc2315.SignedAndEnvelopedData(), (1, 2, 840, 113549, 1, 7, 5): rfc2315.DigestedData(), (1, 2, 840, 113549, 1, 7, 6): rfc2315.EncryptedData() } innerAsn1Object, rest = der_decoder.decode( substrate, asn1Spec=contentInfoMap[contentType]) asn1Object['content'] = der_encoder.encode(innerAsn1Object) substrate = pem.readBase64fromText(self.pem_text_reordered) assert not rest assert asn1Object.prettyPrint() assert der_encoder.encode(asn1Object) == substrate
def apk_signatures(cert_file_object): """ returns a 3-tuple with the hexstring md5, sha1, sha256 hashes of the first certificate of a pkcs7 signature, intended for apk signatures cert_file_object is a file-like object in binary mode """ # TODO zipfile objects don't have the b in the mode even though they are # binary so we can't check mode content_info, _ = der_decoder.decode(cert_file_object.read(), asn1Spec=rfc2315.ContentInfo()) content_type = content_info.getComponentByName("contentType") content_info_map = { (1, 2, 840, 113549, 1, 7, 1): rfc2315.Data(), (1, 2, 840, 113549, 1, 7, 2): rfc2315.SignedData(), (1, 2, 840, 113549, 1, 7, 3): rfc2315.EnvelopedData(), (1, 2, 840, 113549, 1, 7, 4): rfc2315.SignedAndEnvelopedData(), (1, 2, 840, 113549, 1, 7, 5): rfc2315.DigestedData(), (1, 2, 840, 113549, 1, 7, 6): rfc2315.EncryptedData() } content, _ = der_decoder.decode(content_info.getComponentByName("content"), asn1Spec=content_info_map[content_type]) certs = content.getComponentByName("certificates") der = der_encoder.encode(certs[0]) return file_hashes(io.BytesIO(der))
def Signature(pe): try: security = pe.OPTIONAL_HEADER.DATA_DIRECTORY[ pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']] except IndexError: print(' No signature') return address = security.VirtualAddress size = security.Size if address == 0: print(' No signature') return signature = pe.write()[address + 8:address + size] try: from pyasn1.codec.der import decoder as der_decoder except: print(' Signature present but error importing pyasn1 module') return try: from pyasn1_modules import rfc2315 except: print(' Signature present but error importing pyasn1_modules module') return contentInfo, _ = der_decoder.decode(str(signature), asn1Spec=rfc2315.ContentInfo()) contentType = contentInfo.getComponentByName('contentType') contentInfoMap = { (1, 2, 840, 113549, 1, 7, 1): rfc2315.Data(), (1, 2, 840, 113549, 1, 7, 2): rfc2315.SignedData(), (1, 2, 840, 113549, 1, 7, 3): rfc2315.EnvelopedData(), (1, 2, 840, 113549, 1, 7, 4): rfc2315.SignedAndEnvelopedData(), (1, 2, 840, 113549, 1, 7, 5): rfc2315.DigestedData(), (1, 2, 840, 113549, 1, 7, 6): rfc2315.EncryptedData() } content, _ = der_decoder.decode(contentInfo.getComponentByName('content'), asn1Spec=contentInfoMap[contentType]) for line in content.prettyPrint().split('\n'): print(line) oMatch = re.match('( *)value=0x....(.+)', line) if oMatch != None: print(oMatch.groups()[0] + ' ' + repr(binascii.a2b_hex(oMatch.groups()[1])))
def decode(signature): contentInfo, _ = der_decoder.decode(signature, asn1Spec=rfc2315.ContentInfo()) contentType = contentInfo.getComponentByName('contentType') contentInfoMap = { (1, 2, 840, 113549, 1, 7, 1): rfc2315.Data(), (1, 2, 840, 113549, 1, 7, 2): rfc2315.SignedData(), (1, 2, 840, 113549, 1, 7, 3): rfc2315.EnvelopedData(), (1, 2, 840, 113549, 1, 7, 4): rfc2315.SignedAndEnvelopedData(), (1, 2, 840, 113549, 1, 7, 5): rfc2315.DigestedData(), (1, 2, 840, 113549, 1, 7, 6): rfc2315.EncryptedData() } content, _ = der_decoder.decode(contentInfo.getComponentByName('content'), asn1Spec=contentInfoMap[contentType]) return content
def _extract_certs_from_authenticode_blob(buf): contentInfo, _ = der_decoder.decode(buf, asn1Spec=rfc2315.ContentInfo()) contentType = contentInfo.getComponentByName('contentType') contentInfoMap = { (1, 2, 840, 113549, 1, 7, 1): rfc2315.Data(), (1, 2, 840, 113549, 1, 7, 2): rfc2315.SignedData(), (1, 2, 840, 113549, 1, 7, 3): rfc2315.EnvelopedData(), (1, 2, 840, 113549, 1, 7, 4): rfc2315.SignedAndEnvelopedData(), (1, 2, 840, 113549, 1, 7, 5): rfc2315.DigestedData(), (1, 2, 840, 113549, 1, 7, 6): rfc2315.EncryptedData() } content, _ = der_decoder.decode(contentInfo.getComponentByName('content'), asn1Spec=contentInfoMap[contentType]) certs = [] for cert in content['certificates']: tbscert = cert['certificate']['tbsCertificate'] certs.append(_extract_authenticode_tbscerts(tbscert)) for c in content['signerInfos']: tbscert = c['issuerAndSerialNumber'] certs.append(_extract_authenticode_tbscerts(tbscert)) return certs
sys.stdin, ('-----BEGIN PKCS7-----', '-----END PKCS7-----') ) assert substrate, 'bad PKCS7 data on input' contentInfo, rest = decoder.decode(substrate, asn1Spec=rfc2315.ContentInfo()) if rest: substrate = substrate[:-len(rest)] print(contentInfo.prettyPrint()) assert encoder.encode(contentInfo) == substrate, 're-encode fails' contentType = contentInfo.getComponentByName('contentType') contentInfoMap = { (1, 2, 840, 113549, 1, 7, 1): rfc2315.Data(), (1, 2, 840, 113549, 1, 7, 2): rfc2315.SignedData(), (1, 2, 840, 113549, 1, 7, 3): rfc2315.EnvelopedData(), (1, 2, 840, 113549, 1, 7, 4): rfc2315.SignedAndEnvelopedData(), (1, 2, 840, 113549, 1, 7, 5): rfc2315.DigestedData(), (1, 2, 840, 113549, 1, 7, 6): rfc2315.EncryptedData() } content, _ = decoder.decode( contentInfo.getComponentByName('content'), asn1Spec=contentInfoMap[contentType] ) print(content.prettyPrint())
def _create_pkcs7(cert, csr, private_key): """Creates the PKCS7 structure and signs it""" content_info = rfc2315.ContentInfo() content_info.setComponentByName('contentType', rfc2315.data) content_info.setComponentByName('content', encoder.encode(rfc2315.Data(csr))) issuer_and_serial = rfc2315.IssuerAndSerialNumber() issuer_and_serial.setComponentByName('issuer', cert[0]['tbsCertificate']['issuer']) issuer_and_serial.setComponentByName( 'serialNumber', cert[0]['tbsCertificate']['serialNumber']) raw_signature, _ = _sign(private_key, csr) signature = rfc2314.univ.OctetString( hexValue=binascii.hexlify(raw_signature).decode('ascii')) # Microsoft adds parameters with ASN.1 NULL encoding here, # but according to rfc5754 they should be absent: # "Implementations MUST generate SHA2 AlgorithmIdentifiers with absent parameters." sha2 = rfc2315.AlgorithmIdentifier() sha2.setComponentByName('algorithm', (2, 16, 840, 1, 101, 3, 4, 2, 1)) alg_from_cert = cert[0]['tbsCertificate']['subjectPublicKeyInfo'][ 'algorithm']['algorithm'] digest_encryption_algorithm = rfc2315.AlgorithmIdentifier() digest_encryption_algorithm.setComponentByName('algorithm', alg_from_cert) digest_encryption_algorithm.setComponentByName('parameters', '\x05\x00') signer_info = rfc2315.SignerInfo() signer_info.setComponentByName('version', 1) signer_info.setComponentByName('issuerAndSerialNumber', issuer_and_serial) signer_info.setComponentByName('digestAlgorithm', sha2) signer_info.setComponentByName('digestEncryptionAlgorithm', digest_encryption_algorithm) signer_info.setComponentByName('encryptedDigest', signature) signer_infos = rfc2315.SignerInfos().setComponents(signer_info) digest_algorithms = rfc2315.DigestAlgorithmIdentifiers().setComponents( sha2) extended_cert_or_cert = rfc2315.ExtendedCertificateOrCertificate() extended_cert_or_cert.setComponentByName('certificate', cert[0]) extended_certs_and_cert = rfc2315.ExtendedCertificatesAndCertificates( ).subtype(implicitTag=rfc2315.tag.Tag(rfc2315.tag.tagClassContext, rfc2315.tag.tagFormatConstructed, 0)) extended_certs_and_cert.setComponents(extended_cert_or_cert) signed_data = rfc2315.SignedData() signed_data.setComponentByName('version', 1) signed_data.setComponentByName('digestAlgorithms', digest_algorithms) signed_data.setComponentByName('contentInfo', content_info) signed_data.setComponentByName('certificates', extended_certs_and_cert) signed_data.setComponentByName('signerInfos', signer_infos) outer_content_info = rfc2315.ContentInfo() outer_content_info.setComponentByName('contentType', rfc2315.signedData) outer_content_info.setComponentByName('content', encoder.encode(signed_data)) return encoder.encode(outer_content_info)
def print_rsa(file_name): file = open(file_name,"r") buffer = file.read() buffer_base = base64.b64encode(buffer) file.close() file = open(file_name + ".pem","w") file.write('-----BEGIN PKCS7-----\n') file.write(buffer_base) file.write('\n-----END PKCS7-----\n') file.close() file = open(file_name + ".pem","r") idx, substrate = pem.readPemBlocksFromFile( file, ('-----BEGIN PKCS7-----', '-----END PKCS7-----') ) file.close() assert substrate, 'bad PKCS7 data on input' contentInfo, rest = decoder.decode(substrate, asn1Spec=rfc2315.ContentInfo()) if rest: substrate = substrate[:-len(rest)] #/home/retme/Desktop/xx/SIGN.RSA #print contentInfo #ContentInfo print(contentInfo.prettyPrint()) buf = contentInfo.getComponentByName('content') assert encoder.encode(contentInfo, defMode=False) == substrate or \ encoder.encode(contentInfo, defMode=True) == substrate, \ 're-encode fails' contentType = contentInfo.getComponentByName('contentType') #print contentInfo #certificates = contentInfo.getComponentByName('certificates') #certificates.prettyPrint() #print certificates contentInfoMap = { (1, 2, 840, 113549, 1, 7, 1): rfc2315.Data(), (1, 2, 840, 113549, 1, 7, 2): rfc2315.SignedData(), (1, 2, 840, 113549, 1, 7, 3): rfc2315.EnvelopedData(), (1, 2, 840, 113549, 1, 7, 4): rfc2315.SignedAndEnvelopedData(), (1, 2, 840, 113549, 1, 7, 5): rfc2315.DigestedData(), (1, 2, 840, 113549, 1, 7, 6): rfc2315.EncryptedData() } content, _ = decoder.decode( contentInfo.getComponentByName('content'), asn1Spec=contentInfoMap[contentType] ) #content.getComponentByName('certificates').setComponentByPosition(1) #print content.getComponentByName('certificates').getComponentByPosition(0).getComponentByName('certificate').getComponentByName('tbsCertificate').getComponentByName('serialNumber') #print content print(content.prettyPrint())