Python pyasn1.codec.ber.encoder.encode() Examples

The following are 30 code examples of pyasn1.codec.ber.encoder.encode(). 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.encoder , or try the search function .
Example #1
Source File: hp_imc_7_3_10002_download_backups.py    From poc with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def send_dbman_msg(self, opcode, msg):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((self.target_ip, self.dbman_port))

        encodedMsg = encoder.encode(msg, defMode=True)
        msgLen = len(encodedMsg)
        values = (opcode, msgLen, encodedMsg)
        s = struct.Struct(">ii%ds" % msgLen)
        packed_data = s.pack(*values)

        sock.send(packed_data)

        res = sock.recv(1024)
        if res is not None:
            print "Received 10002 response..."
        sock.close() 
Example #2
Source File: ldap.py    From cracke-dit with MIT License 6 votes vote down vote up
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 #3
Source File: protocol.py    From snmpfwd with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _preparePingPongData(reqType, msgId, serial, secret):
    msg = Message()
    msg['version'] = PROTOCOL_VERSION
    msg['msg-id'] = msgId
    msg['content-id'] = reqType

    if msg['content-id'] == MSG_TYPE_PING:
        r = Ping()
    elif msg['content-id'] == MSG_TYPE_PONG:
        r = Pong()
    else:
        raise SnmpfwdError('not a ping-pong message')

    r['serial'] = serial

    msg['payload'] = encoder.encode(r)
    if secret:
        msg['payload'] = crypto.encrypt(secret, encoder.encode(r))
    else:
        msg['payload'] = encoder.encode(r)
    return encoder.encode(msg) 
Example #4
Source File: kerberoast.py    From kerberoast with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: dom.py    From peach with Mozilla Public License 2.0 6 votes vote down vote up
def getInternalValue(self, sout, parent):
        """
        Return the internal value of this date element.  This
        value comes before any modifications such as packing,
        padding, truncating, etc.

        For Numbers this is the python int value.
        """

        if parent is None:
            return u""

        value = ""
        for c in self:
            if isinstance(c, DataElement):
                value = c.getValue()
                break

        if self.xmlNamespace is not None:
            attrib = "{%s}%s" % (self.xmlNamespace, self.attributeName)
        else:
            attrib = self.attributeName
        parent.set(attrib, value.decode('latin-1').encode('utf8'))

        return None 
Example #6
Source File: keys.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def fingerprint(self):
        """
        Get the user presentation of the fingerprint of this L{Key}.  As
        described by U{RFC 4716 section
        4<http://tools.ietf.org/html/rfc4716#section-4>}::

            The fingerprint of a public key consists of the output of the MD5
            message-digest algorithm [RFC1321].  The input to the algorithm is
            the public key data as specified by [RFC4253].  (...)  The output
            of the (MD5) algorithm is presented to the user as a sequence of 16
            octets printed as hexadecimal with lowercase letters and separated
            by colons.

        @since: 8.2

        @return: the user presentation of this L{Key}'s fingerprint, as a
        string.

        @rtype: L{str}
        """
        return ':'.join([x.encode('hex') for x in md5(self.blob()).digest()]) 
Example #7
Source File: ldap.py    From Slackor with GNU General Public License v3.0 6 votes vote down vote up
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 #8
Source File: as2utils.py    From pyas2 with GNU General Public License v2.0 6 votes vote down vote up
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 #9
Source File: ldapasn1.py    From Slackor with GNU General Public License v3.0 5 votes vote down vote up
def encodeControlValue(self):
        self['controlValue'] = encoder.encode(SimplePagedResultsControlValue().setComponents(self._size, self._cookie)) 
Example #10
Source File: rfc2576.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def generateRequestMsg(
        self,
        snmpEngine,
        messageProcessingModel,
        globalData,
        maxMessageSize,
        securityModel,
        securityEngineId,
        securityName,
        securityLevel,
        scopedPDU
        ):
        msg, = globalData
        contextEngineId, contextName, pdu = scopedPDU
        
        # rfc2576: 5.2.3
        communityName = self._sec2com(snmpEngine,
                                      securityName,
                                      contextEngineId,
                                      contextName)

        debug.logger & debug.flagSM and debug.logger('generateRequestMsg: using community %r for securityModel %r, securityName %r, contextEngineId %r contextName %r' % (communityName, securityModel, securityName, contextEngineId, contextName))

        securityParameters = communityName
            
        msg.setComponentByPosition(1, securityParameters)
        msg.setComponentByPosition(2)
        msg.getComponentByPosition(2).setComponentByType(
            pdu.tagSet, pdu, verifyConstraints=False
        )

        debug.logger & debug.flagMP and debug.logger('generateRequestMsg: %s' % (msg.prettyPrint(),))

        try:
            return securityParameters, encoder.encode(msg)
        except PyAsn1Error:
            debug.logger & debug.flagMP and debug.logger('generateRequestMsg: serialization failure: %s' % sys.exc_info()[1])
            raise error.StatusInformation(
                errorIndication = errind.serializationError
            ) 
Example #11
Source File: rfc2576.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def generateResponseMsg(
        self,
        snmpEngine,
        messageProcessingModel,
        globalData,
        maxMessageSize,
        securityModel,
        securityEngineID,
        securityName,
        securityLevel,
        scopedPDU,
        securityStateReference
        ):
        # rfc2576: 5.2.2
        msg, = globalData
        contextEngineId, contextName, pdu = scopedPDU
        cachedSecurityData = self._cache.pop(securityStateReference)
        communityName = cachedSecurityData['communityName']

        debug.logger & debug.flagSM and debug.logger('generateResponseMsg: recovered community %r by securityStateReference %s' % (communityName, securityStateReference))
        
        msg.setComponentByPosition(1, communityName)
        msg.setComponentByPosition(2)
        msg.getComponentByPosition(2).setComponentByType(
            pdu.tagSet, pdu, verifyConstraints=False
            )

        debug.logger & debug.flagMP and debug.logger('generateResponseMsg: %s' % (msg.prettyPrint(),))

        try:
            return communityName, encoder.encode(msg)
        except PyAsn1Error:
            debug.logger & debug.flagMP and debug.logger('generateResponseMsg: serialization failure: %s' % sys.exc_info()[1])
            raise error.StatusInformation(
                errorIndication = errind.serializationError
            ) 
Example #12
Source File: dom.py    From peach with Mozilla Public License 2.0 5 votes vote down vote up
def pack(self, num):
        """
        Pack a number into proper format for this Number
        """

        # 1. Get the transformer we need
        isSigned = 0
        if self.signed:
            isSigned = 1

        isLittleEndian = 0
        if self.endian == 'little':
            isLittleEndian = 1

        if self.size == 8:
            trans = Transformers.Type.Integer.AsInt8(isSigned, isLittleEndian)
        elif self.size == 16:
            trans = Transformers.Type.Integer.AsInt16(isSigned, isLittleEndian)
        elif self.size == 24:
            trans = Transformers.Type.Integer.AsInt24(isSigned, isLittleEndian)
        elif self.size == 32:
            trans = Transformers.Type.Integer.AsInt32(isSigned, isLittleEndian)
        elif self.size == 64:
            trans = Transformers.Type.Integer.AsInt64(isSigned, isLittleEndian)

        # 2. Encode number

        try:
            # This could fail if our override was not
            # a number or empty ('')
            num = int(num)
        except:
            num = 0

        return trans.encode(int(num)) 
Example #13
Source File: dom.py    From peach with Mozilla Public License 2.0 5 votes vote down vote up
def asCType(self):

        if self.type == 'wchar':
            return ctypes.c_wchar_p(self.getInternalValue())
        else:
            return ctypes.c_char_p(self.getInternalValue().encode(self.EncodeAs[self.type])) 
Example #14
Source File: ldap.py    From Slackor with GNU General Public License v3.0 5 votes vote down vote up
def send(self, request, controls=None):
        message = LDAPMessage()
        message['messageID'] = self._messageId
        message['protocolOp'].setComponentByType(request.getTagSet(), request)
        if controls is not None:
            message['controls'].setComponents(*controls)

        data = encoder.encode(message)

        return self._socket.sendall(data) 
Example #15
Source File: ldapasn1.py    From Slackor with GNU General Public License v3.0 5 votes vote down vote up
def encodeControlValue(self):
        self['controlValue'] = encoder.encode(
            SDFlagsControlValue().setComponents(self.flags)) 
Example #16
Source File: ldapasn1.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def encodeControlValue(self):
        self['controlValue'] = encoder.encode(SimplePagedResultsControlValue().setComponents(self._size, self._cookie)) 
Example #17
Source File: protocol.py    From snmpfwd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def prepareRequestData(msgId, req, secret):
    r = Request()

    r['callflow-id'] = req['callflow-id']

    for k in ('snmp-engine-id',
              'snmp-transport-domain',
              'snmp-peer-address',
              'snmp-peer-port',
              'snmp-bind-address',
              'snmp-bind-port',
              'snmp-security-model',
              'snmp-security-level',
              'snmp-security-name',
              'snmp-security-engine-id',
              'snmp-context-engine-id',
              'snmp-context-name',
              'snmp-credentials-id',
              'snmp-context-id',
              'snmp-content-id',
              'snmp-peer-id'):
        r[k] = req[k]

    r['snmp-pdu'] = encoder.encode(req['snmp-pdu'])

    msg = Message()
    msg['version'] = PROTOCOL_VERSION
    msg['msg-id'] = msgId
    msg['content-id'] = 'request'

    if secret:
        msg['payload'] = crypto.encrypt(secret, encoder.encode(r))
    else:
        msg['payload'] = encoder.encode(r)

    return encoder.encode(msg) 
Example #18
Source File: protocol.py    From snmpfwd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def prepareResponseData(msgId, rsp, secret):
    r = Response()
    r['error-indication'] = str(rsp.get('error-indication', ''))
    r['snmp-pdu'] = rsp['snmp-pdu'] and encoder.encode(rsp['snmp-pdu']) or ''

    msg = Message()
    msg['version'] = PROTOCOL_VERSION
    msg['msg-id'] = msgId
    msg['content-id'] = 'response'
    msg['payload'] = encoder.encode(r)
    if secret:
        msg['payload'] = crypto.encrypt(secret, encoder.encode(r))
    else:
        msg['payload'] = encoder.encode(r)
    return encoder.encode(msg) 
Example #19
Source File: protocol.py    From snmpfwd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def prepareAnnouncementData(trunkId, secret):
    r = Announcement()
    r['trunk-id'] = trunkId

    msg = Message()
    msg['version'] = PROTOCOL_VERSION
    msg['msg-id'] = 0
    msg['content-id'] = 'announcement'
    msg['payload'] = encoder.encode(r)
    if secret:
        msg['payload'] = crypto.encrypt(secret, encoder.encode(r))
    else:
        msg['payload'] = encoder.encode(r)
    return encoder.encode(msg) 
Example #20
Source File: ldap.py    From PiBunny with MIT License 5 votes vote down vote up
def send(self, request, controls=None):
        message = LDAPMessage()
        message['messageID'] = self._messageId
        message['protocolOp'].setComponentByType(request.getTagSet(), request)
        if controls is not None:
            message['controls'].setComponents(*controls)

        data = encoder.encode(message)

        return self._socket.sendall(data) 
Example #21
Source File: ldapasn1.py    From PiBunny with MIT License 5 votes vote down vote up
def encodeControlValue(self):
        self['controlValue'] = encoder.encode(SimplePagedResultsControlValue().setComponents(self._size, self._cookie)) 
Example #22
Source File: walk.py    From snmpsim with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _opaque_filter(value):
        if value.upper().startswith('FLOAT: '):
            return encoder.encode(univ.Real(float(value[7:])))

        else:
            return [int(y, 16) for y in value.split(' ')] 
Example #23
Source File: ldap.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def send(self, request, controls=None):
        message = LDAPMessage()
        message['messageID'] = self._messageId
        message['protocolOp'].setComponentByType(request.getTagSet(), request)
        if controls is not None:
            message['controls'].setComponents(*controls)

        data = encoder.encode(message)

        return self._socket.sendall(data) 
Example #24
Source File: ldap.py    From cracke-dit with MIT License 5 votes vote down vote up
def send(self, request, controls=None):
        message = LDAPMessage()
        message['messageID'] = self._messageId
        message['protocolOp'].setComponentByType(request.getTagSet(), request)
        if controls is not None:
            message['controls'].setComponents(*controls)

        data = encoder.encode(message)

        return self._socket.sendall(data) 
Example #25
Source File: ldapasn1.py    From cracke-dit with MIT License 5 votes vote down vote up
def encodeControlValue(self):
        self['controlValue'] = encoder.encode(
            SDFlagsControlValue().setComponents(self.flags)) 
Example #26
Source File: ldapasn1.py    From cracke-dit with MIT License 5 votes vote down vote up
def encodeControlValue(self):
        self['controlValue'] = encoder.encode(SimplePagedResultsControlValue().setComponents(self._size, self._cookie)) 
Example #27
Source File: keys.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def fromString(cls, data, type=None, passphrase=None):
        """
        Return a Key object corresponding to the string data.
        type is optionally the type of string, matching a _fromString_*
        method.  Otherwise, the _guessStringType() classmethod will be used
        to guess a type.  If the key is encrypted, passphrase is used as
        the decryption key.

        @type data: L{bytes}
        @param data: The key data.

        @type type: L{str} or L{None}
        @param type: A string describing the format the key data is in, or
        L{None} to attempt detection of the type.

        @type passphrase: L{bytes} or L{None}
        @param passphrase: The passphrase the key is encrypted with, or L{None}
        if there is no encryption.

        @rtype: L{Key}
        @return: The loaded key.
        """
        if isinstance(data, unicode):
            data = data.encode("utf-8")
        if isinstance(passphrase, unicode):
            passphrase = passphrase.encode("utf-8")
        if type is None:
            type = cls._guessStringType(data)
        if type is None:
            raise BadKeyError('cannot guess the type of %r' % (data,))
        method = getattr(cls, '_fromString_%s' % (type.upper(),), None)
        if method is None:
            raise BadKeyError('no _fromString method for %s' % (type,))
        if method.__code__.co_argcount == 2:  # No passphrase
            if passphrase:
                raise BadKeyError('key not encrypted')
            return method(data)
        else:
            return method(data, passphrase) 
Example #28
Source File: keys.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def sshType(self):
        """
        Get the type of the object we wrap as defined in the SSH protocol,
        defined in RFC 4253, Section 6.6. Currently this can only be b'ssh-rsa',
        b'ssh-dss' or b'ecdsa-sha2-[identifier]'.

        identifier is the standard NIST curve name

        @return: The key type format.
        @rtype: L{bytes}
        """
        if self.type() == 'EC':
            return b'ecdsa-sha2-' + _secToNist[self._keyObject.curve.name.encode('ascii')]
        else:
            return {'RSA': b'ssh-rsa', 'DSA': b'ssh-dss'}[self.type()] 
Example #29
Source File: keys.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def toString(self, type, extra=None):
        """
        Create a string representation of this key.  If the key is a private
        key and you want the representation of its public key, use
        C{key.public().toString()}.  type maps to a _toString_* method.

        @param type: The type of string to emit.  Currently supported values
            are C{'OPENSSH'}, C{'LSH'}, and C{'AGENTV3'}.
        @type type: L{str}

        @param extra: Any extra data supported by the selected format which
            is not part of the key itself.  For public OpenSSH keys, this is
            a comment.  For private OpenSSH keys, this is a passphrase to
            encrypt with.
        @type extra: L{bytes} or L{unicode} or L{None}

        @rtype: L{bytes}
        """
        if isinstance(extra, unicode):
            extra = extra.encode("utf-8")
        method = getattr(self, '_toString_%s' % (type.upper(),), None)
        if method is None:
            raise BadKeyError('unknown key type: %s' % (type,))
        if method.__code__.co_argcount == 2:
            return method(extra)
        else:
            return method() 
Example #30
Source File: as2utils.py    From pyas2 with GNU General Public License v2.0 5 votes vote down vote up
def compress_payload(payload):
    cdata_attr = CompressedDataAttr()
    cdata_attr.setComponentByName('compressionAlgorithm', (1, 2, 840, 113549, 1, 9, 16, 3, 8))
    cdata_payload = CompressedDataPayload()
    cdata_payload.setComponentByName('content-type', (1, 2, 840, 113549, 1, 7, 1))
    cdata_payload.setComponentByName('content',
                                     Content(univ.OctetString(hexValue=zlib.compress(payload).encode('hex'))))
    cdata = CompressedData()
    cdata.setComponentByName('version', 0)
    cdata.setComponentByName('attributes', cdata_attr)
    cdata.setComponentByName('payload', cdata_payload)
    cdata_main = CompressedDataMain()
    cdata_main.setComponentByName('id-ct-compressedData', (1, 2, 840, 113549, 1, 9, 16, 1, 9))
    cdata_main.setComponentByName('compressedData', cdata)
    return encoder.encode(cdata_main, defMode=False).encode('base64')