Python pyasn1.codec.ber.decoder.decode() Examples
The following are 30
code examples of pyasn1.codec.ber.decoder.decode().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pyasn1.codec.ber.decoder
, or try the search function
.
Example #1
Source File: ber.py From asn1tools with MIT License | 6 votes |
def libsnmp_encode_decode(): try: import libsnmp.rfc1905 as libsnmp_rfc1905 def decode(): libsnmp_rfc1905.Message().decode(ENCODED_MESSAGE) encode_time = float('inf') decode_time = timeit.timeit(decode, number=ITERATIONS) except ImportError: encode_time = float('inf') decode_time = float('inf') print('Unable to import libsnmp.') except SyntaxError: encode_time = float('inf') decode_time = float('inf') print('Syntax error in libsnmp.') return encode_time, decode_time
Example #2
Source File: kerberoast.py From kerberoast with Apache License 2.0 | 6 votes |
def updateusernameinencpart(key, rawticket, username, debug=False, verbose=False): try: ramticket, extra = decoder.decode(rawticket) serverticket = ramticket.getComponentByPosition(2) localticket = ramticket.getComponentByPosition(3) encserverticket = serverticket.getComponentByPosition(0).getComponentByPosition(3).getComponentByPosition(2).asOctets() except: raise ValueError('Unable to decode ticket. Invalid file.') if verbose: print('Ticket succesfully decoded') decserverticketraw, nonce = kerberos.decrypt(key, 2, encserverticket) a = decoder.decode(decserverticketraw)[0] a[3][1][0]._value = username e = encoder.encode(a) newencserverticket = kerberos.encrypt(key, 2, e, nonce) ramticket.getComponentByPosition(2).getComponentByPosition(0).getComponentByPosition(3).getComponentByPosition(2)._value = newencserverticket return ramticket
Example #3
Source File: kerberos.py From kerberoast with Apache License 2.0 | 6 votes |
def rc4crypt(key, data): x = 0 box = list(range(256)) for i in range(256): x = (x + box[i] + (key[i % len(key)])) % 256 box[i], box[x] = box[x], box[i] x = 0 y = 0 out = b'' for char in data: x = (x + 1) % 256 y = (y + box[x]) % 256 box[x], box[y] = box[y], box[x] out += bytes([char ^ box[(box[x] + box[y]) % 256]]) return out #print decoder.decode(enc) #define KERB_ETYPE_RC4_HMAC 23
Example #4
Source File: kerberos.py From kerberoast with Apache License 2.0 | 6 votes |
def printdecode(kerbpayload, ktype=2): d = decoder.decode(kerbpayload) if ktype == 32: #print "Protocol Version (pvno): " + str(d[0][0]) print("Message Type: " + str(d[0][1])) print("Realm: " + str(d[0][2])) print("Principal: " + str(d[0][3][1][0])) print("Ticket Version (tkt-vno): " + str(d[0][4][0])) print("Ticket Realm: " + str(d[0][4][1])) #print "Name-Type (Service & Instance): " + str(d[0][4][2][0]) print("Server, Name: " + str(d[0][4][2][1][0])) print("Server, Name: " + str(d[0][4][2][1][1])) #print "Data: " + str(d[0][4][3][2]).encode('hex') #print "Encryption Type: : " + str(d[0][5][0]) #print "Data: " + str(d[0]) #print "Server Realm: " + str(d[0][4][2][4]) elif ktype == 2: print("a")
Example #5
Source File: service.py From vitrage with Apache License 2.0 | 6 votes |
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)
Example #6
Source File: ldap.py From Slackor with GNU General Public License v3.0 | 6 votes |
def _handleControls(self, requestControls, responseControls): done = True if requestControls is not None: for requestControl in requestControls: if responseControls is not None: for responseControl in responseControls: if requestControl['controlType'] == CONTROL_PAGEDRESULTS: if responseControl['controlType'] == CONTROL_PAGEDRESULTS: if hasattr(responseControl, 'getCookie') is not True: responseControl = decoder.decode(encoder.encode(responseControl), asn1Spec=KNOWN_CONTROLS[CONTROL_PAGEDRESULTS]())[0] if responseControl.getCookie(): done = False requestControl.setCookie(responseControl.getCookie()) break else: # handle different controls here pass return done
Example #7
Source File: as2utils.py From pyas2 with GNU General Public License v2.0 | 6 votes |
def check_binary_sig(signature, boundary, content): """ Function checks for binary signature and replaces with base64""" # Check if the signature is base64 or not try: raw_sig = signature.get_payload().encode('ascii').strip() except UnicodeDecodeError: # If not decode to base64 and replace in raw message raw_sig = signature.get_payload().encode('base64').strip() signature.set_payload(raw_sig) content_pts = content.split(boundary) content_pts[-2] = '\r\n%s\r\n' % mimetostring(signature, 78) content = boundary.join(content_pts) # return the contents and raw signature return content, raw_sig
Example #8
Source File: as2utils.py From pyas2 with GNU General Public License v2.0 | 6 votes |
def safe_unicode(value): """ For errors: return best possible unicode...should never lead to errors.""" try: if isinstance(value, unicode): # is already unicode, just return return value elif isinstance(value, str): # string, encoding unknown. for charset in ['utf_8', 'latin_1']: try: return value.decode(charset, 'strict') # decode strict except: continue return value.decode('utf_8', 'ignore') # decode as if it is utf-8, ignore errors. else: return unicode(value) except: try: return repr(value) except: return u'Error while displaying error' # **********************************************************/** # ************** Exception classes *************************** # **********************************************************/**
Example #9
Source File: drsuapi.py From Slackor with GNU General Public License v3.0 | 6 votes |
def OidFromAttid(prefixTable, attr): # separate the ATTRTYP into two parts upperWord = attr // 65536 lowerWord = attr % 65536 # search in the prefix table to find the upperWord, if found, # construct the binary OID by appending lowerWord to the end of # found prefix. binaryOID = None for j, item in enumerate(prefixTable): if item['ndx'] == upperWord: binaryOID = item['prefix']['elements'][:item['prefix']['length']] if lowerWord < 128: binaryOID.append(pack('B',lowerWord)) else: if lowerWord >= 32768: lowerWord -= 32768 binaryOID.append(pack('B',(((lowerWord//128) % 128)+128))) binaryOID.append(pack('B',(lowerWord%128))) break if binaryOID is None: return None return str(decoder.decode(b'\x06' + pack('B',(len(binaryOID))) + b''.join(binaryOID), asn1Spec = univ.ObjectIdentifier())[0])
Example #10
Source File: discovery.py From PRET with GNU General Public License v2.0 | 6 votes |
def recv(dispatcher, domain, address, msg): while msg: msg_recv, msg = decoder.decode(msg, asn1Spec=pmod.Message()) pdu_recv = pmod.apiMessage.getPDU(msg_recv) # match response to request as we're broadcasting if pmod.apiPDU.getRequestID(pdu_send) == pmod.apiPDU.getRequestID(pdu_recv): ipaddr = address[0]; device = '?'; uptime = '?'; status = '?'; prstat = 0 # retrieve device properties for oid, val in pmod.apiPDU.getVarBinds(pdu_recv): oid, val = oid.prettyPrint(), val.prettyPrint() # skip non-printer devices if oid == '1.3.6.1.2.1.25.3.2.1.2.1' and val != '1.3.6.1.2.1.25.3.1.5': return # harvest device information if oid == '1.3.6.1.2.1.25.3.2.1.3.1': device = val if oid == '1.3.6.1.2.1.1.3.0': uptime = conv().elapsed(val, 100, True) if oid == '1.3.6.1.2.1.43.16.5.1.2.1.1': status = val if oid == '1.3.6.1.2.1.25.3.2.1.5.1' and val: prstat = val[:1] dispatcher.jobFinished(1) results[ipaddr] = [device, uptime, status, prstat]
Example #11
Source File: ldap.py From cracke-dit with MIT License | 6 votes |
def _handleControls(self, requestControls, responseControls): done = True if requestControls is not None: for requestControl in requestControls: if responseControls is not None: for responseControl in responseControls: if requestControl['controlType'] == CONTROL_PAGEDRESULTS: if responseControl['controlType'] == CONTROL_PAGEDRESULTS: if hasattr(responseControl, 'getCookie') is not True: responseControl = decoder.decode(encoder.encode(responseControl), asn1Spec=KNOWN_CONTROLS[CONTROL_PAGEDRESULTS]())[0] if responseControl.getCookie(): done = False requestControl.setCookie(responseControl.getCookie()) break else: # handle different controls here pass return done
Example #12
Source File: ber.py From asn1tools with MIT License | 6 votes |
def pyasn1_encode_decode(): try: from pysnmp.proto import api from pyasn1.codec.ber import decoder snmp_v1 = api.protoModules[api.protoVersion1].Message() def decode(): decoder.decode(ENCODED_MESSAGE, asn1Spec=snmp_v1) encode_time = float('inf') decode_time = timeit.timeit(decode, number=ITERATIONS) except ImportError: encode_time = float('inf') decode_time = float('inf') print('Unable to import pyasn1.') return encode_time, decode_time
Example #13
Source File: service_account.py From data with GNU General Public License v3.0 | 5 votes |
def _get_private_key(private_key_pkcs8_text): """Get an RSA private key object from a pkcs8 representation.""" private_key_pkcs8_text = _to_bytes(private_key_pkcs8_text) der = rsa.pem.load_pem(private_key_pkcs8_text, 'PRIVATE KEY') asn1_private_key, _ = decoder.decode(der, asn1Spec=PrivateKeyInfo()) return rsa.PrivateKey.load_pkcs1( asn1_private_key.getComponentByName('privateKey').asOctets(), format='DER')
Example #14
Source File: ldapasn1.py From Slackor with GNU General Public License v3.0 | 5 votes |
def decodeControlValue(self): decodedControlValue, _ = decoder.decode(self['controlValue'], asn1Spec=SimplePagedResultsControlValue()) self._size, self._cookie = decodedControlValue[0], decodedControlValue[1] return decodedControlValue
Example #15
Source File: ldapasn1.py From Slackor with GNU General Public License v3.0 | 5 votes |
def decodeControlValue(self): decodedControlValue, _ = decoder.decode(self['controlValue'], asn1Spec=SDFlagsControlValue()) self._flags = decodedControlValue[0] return decodedControlValue
Example #16
Source File: service_account.py From data with GNU General Public License v3.0 | 5 votes |
def _get_private_key(private_key_pkcs8_text): """Get an RSA private key object from a pkcs8 representation.""" private_key_pkcs8_text = _to_bytes(private_key_pkcs8_text) der = rsa.pem.load_pem(private_key_pkcs8_text, 'PRIVATE KEY') asn1_private_key, _ = decoder.decode(der, asn1Spec=PrivateKeyInfo()) return rsa.PrivateKey.load_pkcs1( asn1_private_key.getComponentByName('privateKey').asOctets(), format='DER')
Example #17
Source File: ldap.py From Slackor with GNU General Public License v3.0 | 5 votes |
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) data = remaining self._messageId += 1 return response
Example #18
Source File: ldap.py From PiBunny with MIT License | 5 votes |
def recv(self): REQUEST_SIZE = 8192 data = '' 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) data = remaining self._messageId += 1 return response
Example #19
Source File: ldapasn1.py From PiBunny with MIT License | 5 votes |
def decodeControlValue(self): decodedControlValue, _ = decoder.decode(self['controlValue'], asn1Spec=SimplePagedResultsControlValue()) self._size, self._cookie = decodedControlValue[0], decodedControlValue[1] return decodedControlValue
Example #20
Source File: asn1.py From peach with Mozilla Public License 2.0 | 5 votes |
def analyzeAsn1(self, codec, data): decoder = eval("pyasn1.codec.%s.decoder" % codec) asn1Obj = decoder.decode(data)[0] return self.Asn12Peach(codec, asn1Obj)
Example #21
Source File: service.py From vitrage with Apache License 2.0 | 5 votes |
def _convert_obj_to_unicode(val): if sys.version_info[0] < 3: return str(val).decode('iso-8859-1') return str(val)
Example #22
Source File: drsuapi.py From PiBunny with MIT License | 5 votes |
def OidFromAttid(prefixTable, attr): # separate the ATTRTYP into two parts upperWord = attr / 65536 lowerWord = attr % 65536 # search in the prefix table to find the upperWord, if found, # construct the binary OID by appending lowerWord to the end of # found prefix. binaryOID = None for j, item in enumerate(prefixTable): if item['ndx'] == upperWord: binaryOID = item['prefix']['elements'][:item['prefix']['length']] if lowerWord < 128: binaryOID.append(chr(lowerWord)) else: if lowerWord >= 32768: lowerWord -= 32768 binaryOID.append(chr(((lowerWord/128) % 128)+128)) binaryOID.append(chr(lowerWord%128)) break if binaryOID is None: return None return str(decoder.decode('\x06' + chr(len(binaryOID)) + ''.join(binaryOID), asn1Spec = univ.ObjectIdentifier())[0])
Example #23
Source File: ber.py From asn1tools with MIT License | 5 votes |
def asn1tools_encode_decode(): snmp_v1 = asn1tools.compile_files(SNMP_V1_ASN_PATHS) def encode(): snmp_v1.encode('Message', DECODED_MESSAGE_ASN1TOOLS, check_types=False) def decode(): snmp_v1.decode('Message', ENCODED_MESSAGE) encode_time = timeit.timeit(encode, number=ITERATIONS) decode_time = timeit.timeit(decode, number=ITERATIONS) return encode_time, decode_time
Example #24
Source File: kerberoast.py From kerberoast with Apache License 2.0 | 5 votes |
def getpac(key, rawticket, debug=False, verbose=False): # attempt decoding of ticket try: ramticket, extra = decoder.decode(rawticket) serverticket = ramticket.getComponentByPosition(2) localticket = ramticket.getComponentByPosition(3) encserverticket = serverticket.getComponentByPosition(0).getComponentByPosition(3).getComponentByPosition(2).asOctets() except: raise ValueError('Unable to decode ticket. Invalid file.') if verbose: print('Ticket succesfully decoded') decserverticketraw, nonce = kerberos.decrypt(key, 2, encserverticket) if decserverticketraw == None: raise ValueError('Unable to decrypt ticket. Invalid key.') elif verbose: print('Decryption successful') decserverticket, extra = decoder.decode(decserverticketraw) # have two here because I was using one to verify that the rewrite matched # This stuff should be removed, if it is still here Tim forgot...again origdecserverticket, extra = decoder.decode(decserverticketraw) # change the validity times in the server ticket updatetimestampsserverticket(decserverticket, str(decserverticket[5]), str(decserverticket[6]), str(decserverticket[7]), str(decserverticket[8])) adifrelevant, extra = decoder.decode(decserverticket[9][0][1]) pac = str(adifrelevant.getComponentByPosition(0).getComponentByPosition(1)) return pac
Example #25
Source File: metrics.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def as_metric_with_inferred_type(value): # type: (Any) -> Optional[MetricDefinition] if is_counter(value): return {'type': 'rate', 'value': int(value)} if is_gauge(value): return {'type': 'gauge', 'value': int(value)} if is_opaque(value): # Arbitrary ASN.1 syntax encoded as an octet string. Let's try to decode it as a float. # See: http://snmplabs.com/pysnmp/docs/api-reference.html#opaque-type try: decoded, _ = pyasn1_decode(bytes(value)) value = float(decoded) except Exception: pass else: return {'type': 'gauge', 'value': value} # Fallback for unknown SNMP types. try: number = float(value) except ValueError: return None else: return {'type': 'gauge', 'value': number}
Example #26
Source File: drsuapi.py From cracke-dit with MIT License | 5 votes |
def OidFromAttid(prefixTable, attr): # separate the ATTRTYP into two parts upperWord = attr / 65536 lowerWord = attr % 65536 # search in the prefix table to find the upperWord, if found, # construct the binary OID by appending lowerWord to the end of # found prefix. binaryOID = None for j, item in enumerate(prefixTable): if item['ndx'] == upperWord: binaryOID = item['prefix']['elements'][:item['prefix']['length']] if lowerWord < 128: binaryOID.append(chr(lowerWord)) else: if lowerWord >= 32768: lowerWord -= 32768 binaryOID.append(chr(((lowerWord/128) % 128)+128)) binaryOID.append(chr(lowerWord%128)) break if binaryOID is None: return None return str(decoder.decode('\x06' + chr(len(binaryOID)) + ''.join(binaryOID), asn1Spec = univ.ObjectIdentifier())[0])
Example #27
Source File: ber.py From asn1tools with MIT License | 5 votes |
def pycrate_encode_decode(): try: import rfc1155_1157_pycrate snmp_v1 = rfc1155_1157_pycrate.RFC1157_SNMP.Message snmp_v1._SAFE_INIT = False snmp_v1._SAFE_VAL = False snmp_v1._SAFE_BND = False snmp_v1._SAFE_BNDTAB = False def encode(): snmp_v1.set_val(DECODED_MESSAGE_PYCRATE) snmp_v1.to_ber() def decode(): snmp_v1.from_ber(ENCODED_MESSAGE) snmp_v1() encode_time = timeit.timeit(encode, number=ITERATIONS) decode_time = timeit.timeit(decode, number=ITERATIONS) except ImportError: encode_time = float('inf') decode_time = float('inf') print('Unable to import pycrate.') except Exception as e: encode_time = float('inf') decode_time = float('inf') print('pycrate error:', str(e)) return encode_time, decode_time
Example #28
Source File: service_account.py From earthengine with MIT License | 5 votes |
def _get_private_key(private_key_pkcs8_text): """Get an RSA private key object from a pkcs8 representation.""" der = rsa.pem.load_pem(private_key_pkcs8_text, 'PRIVATE KEY') asn1_private_key, _ = decoder.decode(der, asn1Spec=PrivateKeyInfo()) return rsa.PrivateKey.load_pkcs1( asn1_private_key.getComponentByName('privateKey').asOctets(), format='DER')
Example #29
Source File: ldap.py From CVE-2017-7494 with GNU General Public License v3.0 | 5 votes |
def recv(self): REQUEST_SIZE = 8192 data = '' 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) data = remaining self._messageId += 1 return response
Example #30
Source File: ldapasn1.py From CVE-2017-7494 with GNU General Public License v3.0 | 5 votes |
def decodeControlValue(self): decodedControlValue, _ = decoder.decode(self['controlValue'], asn1Spec=SimplePagedResultsControlValue()) self._size, self._cookie = decodedControlValue[0], decodedControlValue[1] return decodedControlValue