How to use the pyasn1.codec.der.decoder.decode function in pyasn1

To help you get started, we’ve selected a few pyasn1 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github SecureAuthCorp / impacket / examples / ticketer.py View on Github external
if self.__options.hashes is not None:
                lmhash, nthash = self.__options.hashes.split(':')
            else:
                lmhash = ''
                nthash = ''
            userName = Principal(self.__options.user, type=PrincipalNameType.NT_PRINCIPAL.value)
            tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(userName, self.__password, self.__domain,
                                                                    unhexlify(lmhash), unhexlify(nthash), None,
                                                                    self.__options.dc_ip)
            if self.__domain == self.__server:
                kdcRep = decoder.decode(tgt, asn1Spec=AS_REP())[0]
            else:
                serverName = Principal(self.__options.spn, type=PrincipalNameType.NT_SRV_INST.value)
                tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName, self.__domain, None, tgt, cipher,
                                                                        sessionKey)
                kdcRep = decoder.decode(tgs, asn1Spec=TGS_REP())[0]

            # Let's check we have all the necessary data based on the ciphers used. Boring checks
            ticketCipher = int(kdcRep['ticket']['enc-part']['etype'])
            encPartCipher = int(kdcRep['enc-part']['etype'])

            if (ticketCipher == EncryptionTypes.rc4_hmac.value or encPartCipher == EncryptionTypes.rc4_hmac.value) and \
                            self.__options.nthash is None:
                logging.critical('rc4_hmac is used in this ticket and you haven\'t specified the -nthash parameter. '
                                 'Can\'t continue ( or try running again w/o the -request option)')
                return None, None

            if (ticketCipher == EncryptionTypes.aes128_cts_hmac_sha1_96.value or
                encPartCipher == EncryptionTypes.aes128_cts_hmac_sha1_96.value) and \
                self.__options.aesKey is None:
                logging.critical(
                    'aes128_cts_hmac_sha1_96 is used in this ticket and you haven\'t specified the -aesKey parameter. '
github AlessandroZ / LaZagne / Windows / lazagne / softwares / browsers / mozilla.py View on Github external
def extract_secret_key(self, key_data, global_salt, master_password, entry_salt):

        if unhexlify('f8000000000000000000000000000001') not in key_data:
            return None

        priv_key_entry = key_data[unhexlify('f8000000000000000000000000000001')]
        salt_len = char_to_int(priv_key_entry[1])
        name_len = char_to_int(priv_key_entry[2])
        priv_key_entry_asn1 = decoder.decode(priv_key_entry[3 + salt_len + name_len:])
        data = priv_key_entry[3 + salt_len + name_len:]
        # self.print_asn1(data, len(data), 0)

        # See https://github.com/philsmd/pswRecovery4Moz/blob/master/pswRecovery4Moz.txt
        entry_salt = priv_key_entry_asn1[0][0][1][0].asOctets()
        priv_key_data = priv_key_entry_asn1[0][1].asOctets()
        priv_key = self.decrypt_3des(global_salt, master_password, entry_salt, priv_key_data)
        # self.print_asn1(priv_key, len(priv_key), 0)
        priv_key_asn1 = decoder.decode(priv_key)
        pr_key = priv_key_asn1[0][2].asOctets()
        # self.print_asn1(pr_key, len(pr_key), 0)
        pr_key_asn1 = decoder.decode(pr_key)
        # id = pr_key_asn1[0][1]
        key = long_to_bytes(pr_key_asn1[0][3])
        return key
github latchset / kdcproxy / kdcproxy / parse_pyasn1.py View on Github external
def try_decode(data, cls):
    try:
        req, tail = decoder.decode(data, asn1Spec=cls())
    except error.PyAsn1Error as e:
        raise ASN1ParsingError(e)
    if tail:
        raise ParsingError("%s request has %d extra bytes." %
                           (cls.pretty_name, len(tail)))
    return cls.pretty_name
github mehulj94 / BrainDamage / Echoes / Mozilla.py View on Github external
masterPassword = self.found_masterpassword()
                        if not masterPassword:
                            return

                            # get user secret key
                    key = self.extractSecretKey(globalSalt, masterPassword, entrySalt)
                    if not key:
                        return

                    # everything is ready to decrypt password
                    for host, user, passw in credentials:
                        values = {}
                        values["Website"] = host

                        # Login
                        loginASN1 = decoder.decode(b64decode(user))
                        iv = loginASN1[0][1][1].asOctets()
                        ciphertext = loginASN1[0][2].asOctets()
                        login = DES3.new(key, DES3.MODE_CBC, iv).decrypt(ciphertext)
                        # remove bad character at the end
                        try:
                            nb = unpack('B', login[-1])[0]
                            values["Username"] = login[:-nb]
                        except:
                            values["Username"] = login

                        # Password
                        passwdASN1 = decoder.decode(b64decode(passw))
                        iv = passwdASN1[0][1][1].asOctets()
                        ciphertext = passwdASN1[0][2].asOctets()
                        password = DES3.new(key, DES3.MODE_CBC, iv).decrypt(ciphertext)
                        # remove bad character at the end
github AlessandroZ / LaZagneForensic / LaZagneForensic / lazagne / softwares / browsers / mozilla.py View on Github external
globalSalt 	= key_data[0] # Item1
				item2 		= key_data[1]
				self.printASN1(item2, len(item2), 0)
				"""
				SEQUENCE {
					SEQUENCE {
						OBJECTIDENTIFIER 1.2.840.113549.1.12.5.1.3
						SEQUENCE {
							OCTETSTRING entry_salt_for_passwd_check
							INTEGER 01
						}
					}
					OCTETSTRING encrypted_password_check
				}
				"""
				decodedItem2 	= decoder.decode(item2) 
				entrySalt 		= decodedItem2[0][0][1][0].asOctets()
				encryptedPasswd	= decodedItem2[0][1].asOctets()
			
			cleartextData 	= self.decrypt3DES(globalSalt, master_password, entrySalt, encryptedPasswd)
			if cleartextData != 'password-check\x02\x02':
				return ('', '', '')

			return (globalSalt, master_password, entrySalt)
		except:
			return ('', '', '')
github plotly / arduino-api / plotly_yun / Linino / requests / packages / urllib3 / contrib / pyopenssl.py View on Github external
def get_subj_alt_name(peer_cert):
    # Search through extensions
    dns_name = []
    if not SUBJ_ALT_NAME_SUPPORT:
        return dns_name

    general_names = SubjectAltName()
    for i in range(peer_cert.get_extension_count()):
        ext = peer_cert.get_extension(i)
        ext_name = ext.get_short_name()
        if ext_name != 'subjectAltName':
            continue

        # PyOpenSSL returns extension data in ASN.1 encoded form
        ext_dat = ext.get_data()
        decoded_dat = der_decoder.decode(ext_dat,
                                         asn1Spec=general_names)

        for name in decoded_dat:
            if not isinstance(name, SubjectAltName):
                continue
            for entry in range(len(name)):
                component = name.getComponentByPosition(entry)
                if component.getName() != 'dNSName':
                    continue
                dns_name.append(str(component.getComponent()))

    return dns_name
github snowflakedb / snowflake-connector-python / ocsp_pyasn1.py View on Github external
def _encode_cert_id_key(hkey):
    issuer_name_hash, issuer_key_hash, serial_number = hkey
    issuer_name_hash, _ = der_decoder.decode(issuer_name_hash)
    issuer_key_hash, _ = der_decoder.decode(issuer_key_hash)
    serial_number, _ = der_decoder.decode(serial_number)
    cert_id = CertID()
    cert_id['hashAlgorithm'] = rfc2459.AlgorithmIdentifier().setComponentByName(
        'algorithm', rfc2437.id_sha1)
    cert_id['issuerNameHash'] = issuer_name_hash
    cert_id['issuerKeyHash'] = issuer_key_hash
    cert_id['serialNumber'] = serial_number
    return cert_id
github janeczku / calibre-web / vendor / requests / packages / urllib3 / contrib / pyopenssl.py View on Github external
def get_subj_alt_name(peer_cert):
    # Search through extensions
    dns_name = []
    if not SUBJ_ALT_NAME_SUPPORT:
        return dns_name

    general_names = SubjectAltName()
    for i in range(peer_cert.get_extension_count()):
        ext = peer_cert.get_extension(i)
        ext_name = ext.get_short_name()
        if ext_name != 'subjectAltName':
            continue

        # PyOpenSSL returns extension data in ASN.1 encoded form
        ext_dat = ext.get_data()
        decoded_dat = der_decoder.decode(ext_dat,
                                         asn1Spec=general_names)

        for name in decoded_dat:
            if not isinstance(name, SubjectAltName):
                continue
            for entry in range(len(name)):
                component = name.getComponentByPosition(entry)
                if component.getName() != 'dNSName':
                    continue
                dns_name.append(str(component.getComponent()))

    return dns_name
github fritzy / SleekXMPP / sleekxmpp / xmlstream / cert.py View on Github external
def extract_dates(raw_cert):
    if not HAVE_PYASN1:
        log.warning("Could not find pyasn1 and pyasn1_modules. " + \
                    "SSL certificate expiration COULD NOT BE VERIFIED.")
        return None, None

    cert = decoder.decode(raw_cert, asn1Spec=Certificate())[0]
    tbs = cert.getComponentByName('tbsCertificate')
    validity = tbs.getComponentByName('validity')

    not_before = validity.getComponentByName('notBefore')
    not_before = str(not_before.getComponent())

    not_after = validity.getComponentByName('notAfter')
    not_after = str(not_after.getComponent())

    if HAVE_PYASN1_4:
        not_before = datetime.strptime(not_before, '%y%m%d%H%M%SZ')
        not_after = datetime.strptime(not_after, '%y%m%d%H%M%SZ')
    else:
        not_before = datetime.strptime(not_before, '%Y%m%d%H%M%SZ')
        not_after = datetime.strptime(not_after, '%Y%m%d%H%M%SZ')
github openstack / octavia / octavia / common / tls_utils / cert_parser.py View on Github external
:param substrate: The substrate to be processed
    :returns: A list of DER-encoded X509 certificates
    """
    try:
        contentInfo, _ = der_decoder.decode(substrate,
                                            asn1Spec=rfc2315.ContentInfo())
        contentType = contentInfo.getComponentByName('contentType')
    except Exception:
        LOG.exception('Unreadable Certificate.')
        raise exceptions.UnreadableCert
    if contentType != rfc2315.signedData:
        LOG.exception('Unreadable Certificate.')
        raise exceptions.UnreadableCert

    try:
        content, _ = der_decoder.decode(
            contentInfo.getComponentByName('content'),
            asn1Spec=rfc2315.SignedData())
    except Exception:
        LOG.exception('Unreadable Certificate.')
        raise exceptions.UnreadableCert

    for cert in content.getComponentByName('certificates'):
        yield der_encoder.encode(cert)