How to use the pyasn1.codec.ber.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 etingof / pyasn1 / tests / codec / ber / test_decoder.py View on Github external
def testDontDecodeOpenTypesChoiceOne(self):
        s, r = decoder.decode(
            ints2octs((48, 6, 2, 1, 1, 2, 1, 12)), asn1Spec=self.s
        )
        assert not r
        assert s[0] == 1
        assert s[1] == ints2octs((2, 1, 12))
github magnumripper / JohnTheRipper / run / kirbi2john.py View on Github external
from pyasn1.codec.ber import decoder
import sys

if __name__ == '__main__':
    m = "exported mimikatz kerberos tickets / extracttgsrepfrompcap.py output"

    if len(sys.argv) < 2:
        sys.stderr.write("Usage: %s <%s>\n" % (sys.argv[0], m))
        sys.exit(-1)

    for f in sys.argv[1:]:
        with open(f, 'rb') as fd:
            data = fd.read()
            if data[0] == '\x76':  # process .kirbi
                # rem dump
                etype = str(decoder.decode(data)[0][2][0][3][0])
                if etype != "23":
                    sys.stderr.write("Unsupported etype %s seen! Please report this to us.\n" % etype)
                et = str(decoder.decode(data)[0][2][0][3][2])
                sys.stdout.write("$krb5tgs$unknown:$krb5tgs$%s$" % etype + et[:16].encode("hex") +
                                 "$" + et[16:].encode("hex") + "\n")
            elif data[:2] == '6d':  # extracttgsrepfrompcap.py output
                for ticket in data.strip().split('\n'):
                    etype = str(decoder.decode(ticket.decode('hex'))[0][4][3][0])
                    if etype != "23":
                        sys.stderr.write("Unsupported etype %s found. Such hashes can't be cracked it seems.\n" % etype)
                    et = str(decoder.decode(ticket.decode('hex'))[0][4][3][2])
                    sys.stdout.write("$krb5tgs$unknown:$krb5tgs$%s$" % etype + et[:16].encode("hex") +
                                     "$" + et[16:].encode("hex") + "\n")
github ropnop / impacket_static_binaries / examples / addcomputer.py View on Github external
tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(serverName, domain, kdcHost, tgt, cipher,
                                                                    sessionKey)
        else:
            tgs = TGS['KDC_REP']
            cipher = TGS['cipher']
            sessionKey = TGS['sessionKey']

            # Let's build a NegTokenInit with a Kerberos REQ_AP

        blob = SPNEGO_NegTokenInit()

        # Kerberos
        blob['MechTypes'] = [TypesMech['MS KRB5 - Microsoft Kerberos 5']]

        # Let's extract the ticket from the TGS
        tgs = decoder.decode(tgs, asn1Spec=TGS_REP())[0]
        ticket = Ticket()
        ticket.from_asn1(tgs['ticket'])

        # Now let's build the AP_REQ
        apReq = AP_REQ()
        apReq['pvno'] = 5
        apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)

        opts = []
        apReq['ap-options'] = constants.encodeFlags(opts)
        seq_set(apReq, 'ticket', ticket.to_asn1)

        authenticator = Authenticator()
        authenticator['authenticator-vno'] = 5
        authenticator['crealm'] = domain
        seq_set(authenticator, 'cname', userName.components_to_asn1)
github GoSecure / pyrdp / rdpy / security / x509.py View on Github external
def extractRSAKeyFromASN1(subjectPublicKey):
    rsaKey = decoder.decode(subjectPublicKey, asn1Spec=RSAPublicKey())[0]
    return rsaKey.getComponentByName('modulus')._value , rsaKey.getComponentByName('publicExponent')._value
github edraizen / molmimic / molmimic / generate_data / map_residues.py View on Github external
def decode_residues(job, pdb, chain, res, row=None):
    if not pdb or pdb == np.NaN or not isinstance(pdb, str):
        raise InvalidSIFTS

    residues = []

    if res.startswith("0x"):
        res = res[2:]
    try:
        res = binascii.unhexlify(res)
    except:
        pass

    try:
        code, rest = decoder.decode(zlib.decompress(res, 16 + zlib.MAX_WBITS))
    except Exception as e:
        if type(res, str) and "," in res:
            return res
        else:
            return np.NaN

    for i in xrange(len(code)):
        c = code[i]
        range_from, range_to, gi = tuple([c[j] for j in range(len(c))])
        for x in xrange(range_from, range_to + 1):
            residues.append(x)

    try:
        return ",".join(map(str, mmdb_to_pdb_resi(pdb, chain, residues, job=job)))
    except Exception as error:
        print "Error mapping mmdb for", pdb, chain, error, row
github openstack / vitrage / vitrage / snmp_parsing / service.py View on Github external
def callback_func(self, transport_dispatcher, transport_domain,
                      transport_address, whole_msg):
        while whole_msg:
            msg_ver = int(snmp_api.decodeMessageVersion(whole_msg))
            if msg_ver in snmp_api.protoModules:
                p_mod = snmp_api.protoModules[msg_ver]
            else:
                LOG.error('Unsupported SNMP version %s.' % msg_ver)
                return
            req_msg, whole_msg = decoder.decode(
                whole_msg, asn1Spec=p_mod.Message(),
            )
            req_pdu = p_mod.apiMessage.getPDU(req_msg)
            if req_pdu.isSameTypeWith(p_mod.TrapPDU()):
                ver_binds = p_mod.apiTrapPDU.getVarBinds(req_pdu) \
                    if msg_ver == snmp_api.protoVersion1 \
                    else p_mod.apiPDU.getVarBinds(req_pdu)

                binds_dict = self._convert_binds_to_dict(ver_binds)
                LOG.debug('Receive binds info after convert: %s' % binds_dict)
                self._send_snmp_to_queue(binds_dict)
github nocproject / noc / sa / trapcollector.py View on Github external
return ""
            v=v[-1]
            if type(v)==tuple:
                return oid_to_str(v)
            return bin_quote(str(v))

        if not self.check_source_address(address):
            return
        while whole_msg:
            msg_version = int(api.decodeMessageVersion(whole_msg))
            if api.protoModules.has_key(msg_version):
                p_mod = api.protoModules[msg_version]
            else:
                self.error('Unsupported SNMP version %s from %s'%(msg_version,address))
                return
            req_msg,whole_msg=decoder.decode(whole_msg,asn1Spec=p_mod.Message())
            req_pdu = p_mod.apiMessage.getPDU(req_msg)
            if req_pdu.isSameTypeWith(p_mod.TrapPDU()):
                body={"source":"SNMP Trap","collector":self.collector_signature}
                if msg_version==api.protoVersion1:
                    oid=oid_to_str(p_mod.apiTrapPDU.getEnterprise(req_pdu))
                    body["1.3.6.1.6.3.1.1.4.1.0"]=oid # snmpTrapOID.0
                    var_binds=p_mod.apiTrapPDU.getVarBindList(req_pdu)
                else:
                    var_binds=p_mod.apiPDU.getVarBindList(req_pdu)
                ts=int(time.time())
                for o,v in var_binds:
                    body[oid_to_str(o._value)]=extract(v)
                self.process_event(ts,address,body)
github ropnop / impacket_static_binaries / impacket / ldap / ldap.py View on Github external
def recv(self):
        REQUEST_SIZE = 8192
        data = b''
        done = False
        while not done:
            recvData = self._socket.recv(REQUEST_SIZE)
            if len(recvData) < REQUEST_SIZE:
                done = True
            data += recvData

        response = []
        while len(data) > 0:
            try:
                message, remaining = decoder.decode(data, asn1Spec=LDAPMessage())
            except SubstrateUnderrunError:
                # We need more data
                remaining = data + self._socket.recv(REQUEST_SIZE)
            else:
                if message['messageID'] == 0:  # unsolicited notification
                    name = message['protocolOp']['extendedResp']['responseName'] or message['responseName']
                    notification = KNOWN_NOTIFICATIONS.get(name, "Unsolicited Notification '%s'" % name)
                    if name == NOTIFICATION_DISCONNECT:  # Server has disconnected
                        self.close()
                    raise LDAPSessionError(
                        error=int(message['protocolOp']['extendedResp']['resultCode']),
                        errorString='%s -> %s: %s' % (notification,
                                                      message['protocolOp']['extendedResp']['resultCode'].prettyPrint(),
                                                      message['protocolOp']['extendedResp']['diagnosticMessage'])
                    )
                response.append(message)
github anthrotype / verify-sigs / auth_data.py View on Github external
def __init__(self, content):
    self.container, rest = decoder.decode(content,
                                          asn1Spec=pkcs7.ContentInfo())
    if rest:
      self.trailing_data = rest

    self.signed_data, rest = decoder.decode(self.container['content'],
                                            asn1Spec=pkcs7.SignedData())
    if rest: raise Asn1Error('Extra unparsed content.')

    digest_algorithm_oid = self.signed_data['digestAlgorithms'][0]['algorithm']
    self.digest_algorithm = oids.OID_TO_CLASS.get(digest_algorithm_oid)

    spc_blob = self.signed_data['contentInfo']['content']
    self.spc_info, rest = decoder.decode(spc_blob,
                                         asn1Spec=spc.SpcIndirectDataContent())
    if rest: raise Asn1Error('Extra unparsed content.')
    # Currently not parsing the SpcIndirectDataContent 'data' field.
    # It used to contain information about the software publisher, but now
    # is set to default content, or under Vista+, may hold page hashes.

    self.certificates = self._ParseCerts(self.signed_data['certificates'])
github anthrotype / verify-sigs / auth_data.py View on Github external
def _ParseCountersig(self, unauth_attrs):
    attr = unauth_attrs[0]
    if oids.OID_TO_CLASS.get(attr['type']) is not pkcs7.CountersignInfo:
      raise Asn1Error('Unexpected countersign OID.')
    values = attr['values']
    if len(values) != 1:
      raise Asn1Error('Expected one CS value, got %d.' % len(values))
    counter_sig_info, rest = decoder.decode(values[0],
                                            asn1Spec=pkcs7.CountersignInfo())
    if rest: raise Asn1Error('Extra unparsed content.')
    return counter_sig_info