Exemplo n.º 1
0
def probe_oper_status(player):
    switch = current_app.config['SWITCHES'][player]
    address = switch['address']
    port = switch['port']
    logger.info("Probing status for player %d on switch %s:%d", player,
                address)
    engine = SnmpEngine()
    auth_data = CommunityData(switch['community'], mpModel=1)
    transport = UdpTransportTarget((address, port))
    interfaces = switch['interfaces']
    oper_states = []
    for chunk in chunked(
        (ObjectType(ObjectIdentity(ifOperStatus.oid + (index, )), Null())
         for index in interfaces), 24):
        cmd = getCmd(engine, auth_data, transport, ContextData(), *chunk)
        errorIndication, errorStatus, errorIndex, varBinds = next(cmd)
        if errorIndication is not None:
            raise Exception("SNMP error returned")
        oper_states.extend(
            ifOperStatus(int(value)) for identity, value in varBinds)
    with StateLock:
        for cell_state, (index,
                         oper_state) in zip(current_app.cell_state[player],
                                            enumerate(oper_states)):
            if oper_state == ifOperStatus.down and cell_state != CellState.EMPTY:
                current_app.cell_state[player][index] = CellState.PRESENT

            if oper_state == ifOperStatus.up and cell_state != CellState.EMPTY:
                current_app.cell_state[player][index] = CellState.HIT
        if not any(cell_state == CellState.PRESENT
                   for cell_state in current_app.cell_state[player]):
            current_app.game_state = GameState.OVER
            return True
    return False
Exemplo n.º 2
0
class AlgorithmIdentifier(Sequence):
    """
    Define an AlgorithmIdentifier.

    AlgorithmIdentifier is a custom ASN1 sequence type
    containing an algortihm OID and any optional parameters.
    In this case the parameters are always null.
    """

    componentType = NamedTypes(
        NamedType("algorithm", ObjectIdentifier()),
        NamedType("parameters", Null()),
    )
Exemplo n.º 3
0
    def encode(rsa_key: object, **kwargs):
        seq = Sequence()
        seq.setComponentByPosition(
            0, ObjectIdentifier([1, 2, 840, 113549, 1, 1, 1]))
        seq.setComponentByPosition(1, Null())

        param_bs = X509RSASubjectPublicKey.encode(rsa_key)

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, seq)
        top_seq.setComponentByPosition(1, param_bs)

        encoded = encoder.encode(top_seq)
        return X509RSAPublicKey.transport_encode(encoded, **kwargs)
Exemplo n.º 4
0
    def encode(rsa_key: object, **kwargs):
        alg_id = Sequence()
        alg_id.setComponentByPosition(0, ObjectIdentifier([1, 2, 840, 113549, 1, 1, 1]))
        alg_id.setComponentByPosition(1, Null())

        param_oct = OctetString(PKCS1RSAPrivateKey.encode(rsa_key, encode_pem=False))

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, Integer(0))
        top_seq.setComponentByPosition(1, alg_id)
        top_seq.setComponentByPosition(2, param_oct)

        encoded = encoder.encode(top_seq)
        encoded = PKCS8RSAPrivateKey.transport_encode(encoded, **kwargs)
        return encoded
Exemplo n.º 5
0
def makeRSAPublicKey(modulus, publicExponent):

    algorithm = AlgorithmIdentifier()
    algorithm['algorithm'] = '1.2.840.113549.1.1.1'  # rsaEncription
    algorithm['parameters'] = Null('')

    subjectPublicKey = RSAPublicKey()
    subjectPublicKey['modulus'] = modulus
    subjectPublicKey['publicExponent'] = publicExponent

    subjectPublicKeyInfo = SubjectPublicKeyInfo()
    subjectPublicKeyInfo['algorithm'] = algorithm
    # int.from_bytes()
    subjectPublicKeyInfo['subjectPublicKey'] = BitString(
        hexValue=encode(subjectPublicKey).hex())

    return b64encode(encode(subjectPublicKeyInfo))
Exemplo n.º 6
0
    def pkcs7_enveloped_msg(self, msg, data, iv="0123456789012345"):
        """WIP: PKCS#7 envelop msg, data with cert"""
        oi_pkcs7_rsa_enc = ObjectIdentifier((1, 2, 840, 113549, 1, 1, 1))
        oi_pkcs7_data = ObjectIdentifier((1, 2, 840, 113549, 1, 7, 1))
        oi_seed_cbc = ObjectIdentifier(id_seed_cbc)

        der = Sequence().setComponentByPosition(
            0, ObjectIdentifier(id_pkcs7_enveloped_data))

        data_set = Sequence().setComponentByPosition(0, Integer(0))
        data_set = data_set.setComponentByPosition(
            1,
            Sequence().setComponentByPosition(
                0, self.pub_cert[0][3]).setComponentByPosition(
                    1, self.pub_cert[0][1]))
        data_set = data_set.setComponentByPosition(
            2,
            Sequence().setComponentByPosition(
                0, oi_pkcs7_rsa_enc).setComponentByPosition(1, Null('')))
        data_set = data_set.setComponentByPosition(
            3, OctetString(hexValue=msg.encode('hex')))

        data_seq = Sequence().setComponentByPosition(0, oi_pkcs7_data)
        data_seq = data_seq.setComponentByPosition(
            1,
            Sequence().setComponentByPosition(
                0, oi_seed_cbc).setComponentByPosition(
                    1, OctetString(hexValue=iv.encode('hex'))))
        data_seq = data_seq.setComponentByPosition(
            2,
            OctetString(
                hexValue=data.encode('hex')).subtype(implicitTag=tag.Tag(
                    tag.tagClassContext, tag.tagFormatSimple, 0)))

        data = Sequence().setComponentByPosition(0, Integer(0))
        data = data.setComponentByPosition(
            1,
            Set().setComponentByPosition(0, data_set))
        data = data.setComponentByPosition(2, data_seq)

        der = der.setComponentByPosition(
            1,
            Sequence().subtype(
                implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple,
                                    0)).setComponentByPosition(0, data))
        return der_encoder.encode(der)
Exemplo n.º 7
0
    def sign(self, plaintext: bytes) -> Bytes:
        """
        Signs the `plaintext`.

        Parameters:
            plaintext (bytes): Plaintext to sign.
        
        Returns:
            Bytes: Signature.
        """
        alg_id = Sequence()
        alg_id.setComponentByPosition(0, HASH_OID_LOOKUP[type(self.hash_obj)])
        alg_id.setComponentByPosition(1, Null())

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, alg_id)
        top_seq.setComponentByPosition(
            1, OctetString(self.hash_obj.hash(plaintext)))

        der_encoded = encoder.encode(top_seq)
        return self.rsa.decrypt(self.padder.pad(der_encoded)).zfill(
            (self.rsa.n.bit_length() + 7) // 8)
Exemplo n.º 8
0
def bulkCmd(snmpDispatcher, authData, transportTarget,
            nonRepeaters, maxRepetitions, *varBinds, **options):
    """Creates a generator to perform one or more SNMP GETBULK queries.

    On each iteration, new SNMP GETBULK request is send
    (:RFC:`1905#section-4.2.3`). The iterator blocks waiting for response
    to arrive or error to occur.

    Parameters
    ----------
    snmpDispatcher : :py:class:`~pysnmp.hlapi.snmpDispatcher`
        Class instance representing SNMP engine.

    authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
        Class instance representing SNMP credentials.

    transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
        Class instance representing transport type along with SNMP peer address.

    nonRepeaters : int
        One MIB variable is requested in response for the first
        `nonRepeaters` MIB variables in request.

    maxRepetitions : int
        `maxRepetitions` MIB variables are requested in response for each
        of the remaining MIB variables in the request (e.g. excluding
        `nonRepeaters`). Remote SNMP engine may choose lesser value than
        requested.

    \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
        One or more class instances representing MIB variables to place
        into SNMP request.

    Other Parameters
    ----------------
    \*\*options :
        Request options:

            * `lookupMib` - load MIB and resolve response MIB variables at
              the cost of slightly reduced performance. Default is `True`.
              Default is `True`.
            * `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
              otherwise (if `False`) stop iteration when all response MIB
              variables leave the scope of initial MIB variables in
              `varBinds`. Default is `True`.
            * `ignoreNonIncreasingOid` - continue iteration even if response
              MIB variables (OIDs) are not greater then request MIB variables.
              Be aware that setting it to `True` may cause infinite loop between
              SNMP management and agent applications. Default is `False`.
            * `maxRows` - stop iteration once this generator instance processed
              `maxRows` of SNMP conceptual table. Default is `0` (no limit).
            * `maxCalls` - stop iteration once this generator instance processed
              `maxCalls` responses. Default is 0 (no limit).

    Yields
    ------
    errorIndication : str
        True value indicates SNMP engine error.
    errorStatus : str
        True value indicates SNMP PDU error.
    errorIndex : int
        Non-zero value refers to \*varBinds[errorIndex-1]
    varBinds: tuple
        A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
        instances representing MIB variables returned in SNMP response.

    Raises
    ------
    PySnmpError
        Or its derivative indicating that an error occurred while
        performing SNMP operation.

    Notes
    -----
    The `bulkCmd` generator will be exhausted on any of the following
    conditions:

    * SNMP engine error occurs thus `errorIndication` is `True`
    * SNMP PDU `errorStatus` is reported as `True`
    * SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
      (also known as *SNMP exception values*) are reported for all
      MIB variables in `varBinds`
    * *lexicographicMode* option is `True` and SNMP agent reports
      end-of-mib or *lexicographicMode* is `False` and all
      response MIB variables leave the scope of `varBinds`

    At any moment a new sequence of `varBinds` could be send back into
    running generator (supported since Python 2.6).

    Setting `maxRepetitions` value to 15..50 might significantly improve
    system performance, as many MIB variables get packed into a single
    response message at once.

    Examples
    --------
    >>> from pysnmp.hlapi.v1arch import *
    >>>
    >>> g = bulkCmd(snmpDispatcher(),
    >>>             CommunityData('public'),
    >>>             UdpTransportTarget(('demo.snmplabs.com', 161)),
    >>>             0, 25,
    >>>             ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
    >>> next(g)
    (None, 0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]])
    >>> g.send([ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets'))])
    (None, 0, 0, [[(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))]])
    """

    def cbFun(*args, **kwargs):
        response[:] = args + (kwargs.get('nextVarBinds', ()),)

    options['cbFun'] = cbFun

    lexicographicMode = options.pop('lexicographicMode', True)
    maxRows = options.pop('maxRows', 0)
    maxCalls = options.pop('maxCalls', 0)

    initialVarBinds = vbProcessor.makeVarBinds(snmpDispatcher.cache, varBinds)

    nullVarBinds = [False] * len(initialVarBinds)

    totalRows = totalCalls = 0

    errorIndication, errorStatus, errorIndex, varBindTable = None, 0, 0, ()
    response = []

    stopFlag = False

    while not stopFlag:
        if not varBinds:
            yield (errorIndication, errorStatus, errorIndex, varBinds)
            return

        if maxRows and totalRows < maxRows:
            maxRepetitions = min(maxRepetitions, maxRows - totalRows)

        cmdgen.bulkCmd(snmpDispatcher, authData, transportTarget,
                       nonRepeaters, maxRepetitions,
                       *[(x[0], Null('')) for x in varBinds], **options)

        snmpDispatcher.transportDispatcher.runDispatcher()

        errorIndication, errorStatus, errorIndex, varBindTable, varBinds = response

        if errorIndication:
            yield (errorIndication, errorStatus, errorIndex, ())
            return

        elif errorStatus:
            if errorStatus == 2:
                # Hide SNMPv1 noSuchName error which leaks in here
                # from SNMPv1 Agent through internal pysnmp proxy.
                errorStatus = errorStatus.clone(0)
                errorIndex = errorIndex.clone(0)
            yield (errorIndication, errorStatus, errorIndex, varBindTable and varBindTable[0] or [])
            return

        else:
            for rowIdx, varBindRow in enumerate(varBindTable):
                stopFlag = True
                if len(varBindRow) != len(initialVarBinds):
                    varBindTable = rowIdx and varBindTable[:rowIdx - 1] or []
                    break

                for colIdx, varBind in enumerate(varBindRow):
                    name, val = varBind
                    if nullVarBinds[colIdx]:
                        varBindRow[colIdx] = name, endOfMibView
                        continue

                    stopFlag = False

                    if isinstance(val, Null):
                        nullVarBinds[colIdx] = True

                    elif not lexicographicMode and not initialVarBinds[colIdx][0].isPrefixOf(name):
                        varBindRow[colIdx] = name, endOfMibView
                        nullVarBinds[colIdx] = True

                if stopFlag:
                    varBindTable = rowIdx and varBindTable[:rowIdx - 1] or []
                    break

            totalRows += len(varBindTable)
            totalCalls += 1

            if maxRows and totalRows >= maxRows:
                if totalRows > maxRows:
                    varBindTable = varBindTable[:-(totalRows - maxRows)]
                stopFlag = True

            if maxCalls and totalCalls >= maxCalls:
                stopFlag = True

            for varBindRow in varBindTable:
                nextVarBinds = (yield errorIndication, errorStatus, errorIndex, varBindRow)

                if nextVarBinds:
                    initialVarBinds = varBinds = vbProcessor.makeVarBinds(snmpDispatcher.cache, nextVarBinds)
Exemplo n.º 9
0
def bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters,
            maxRepetitions, *varBinds, **options):
    """Creates a generator to perform one or more SNMP GETBULK queries.

    On each iteration, new SNMP GETBULK request is send
    (:RFC:`1905#section-4.2.3`). The iterator blocks waiting for response
    to arrive or error to occur.

    Parameters
    ----------
    snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine`
        Class instance representing SNMP engine.

    authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
        Class instance representing SNMP credentials.

    transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
        Class instance representing transport type along with SNMP peer address.

    contextData : :py:class:`~pysnmp.hlapi.ContextData`
        Class instance representing SNMP ContextEngineId and ContextName values.

    nonRepeaters : int
        One MIB variable is requested in response for the first
        `nonRepeaters` MIB variables in request.

    maxRepetitions : int
        `maxRepetitions` MIB variables are requested in response for each
        of the remaining MIB variables in the request (e.g. excluding
        `nonRepeaters`). Remote SNMP engine may choose lesser value than
        requested.

    \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
        One or more class instances representing MIB variables to place
        into SNMP request.

    Other Parameters
    ----------------
    \*\*options :
        Request options:

            * `lookupMib` - load MIB and resolve response MIB variables at
              the cost of slightly reduced performance. Default is `True`.
              Default is `True`.
            * `lexicographicMode` - stop iteration when all response MIB
              variables leave the scope of initial MIB variables in
              `varBinds`. Default is `True`.
            * `ignoreNonIncreasingOid` - continue iteration even if response
              MIB variables (OIDs) are not greater then request MIB variables.
              Default is `False`.
            * `maxRows` - stop iteration once this generator instance processed
              `maxRows` of SNMP conceptual table. Default is `0` (no limit).
            * `maxCalls` - stop iteration once this generator instance processed
              `maxCalls` responses. Default is 0 (no limit).

    Yields
    ------
    errorIndication : str
        True value indicates SNMP engine error.
    errorStatus : str
        True value indicates SNMP PDU error.
    errorIndex : int
        Non-zero value refers to \*varBinds[errorIndex-1]
    varBinds : tuple
        A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
        instances representing MIB variables returned in SNMP response.

    Raises
    ------
    PySnmpError
        Or its derivative indicating that an error occurred while
        performing SNMP operation.

    Notes
    -----
    The `bulkCmd` generator will be exhausted on any of the following
    conditions:

    * SNMP engine error occurs thus `errorIndication` is `True`
    * SNMP PDU `errorStatus` is reported as `True`
    * SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
      (also known as *SNMP exception values*) are reported for all
      MIB variables in `varBinds`
    * *lexicographicMode* option is set to `False` and all
      response MIB variables leave the scope of `varBinds`

    At any moment a new sequence of `varBinds` could be send back into
    running generator (supported since Python 2.6).

    Setting `maxRepetitions` value to 15..50 might significantly improve
    system performance, as many MIB variables get packed into a single
    response message at once.

    Examples
    --------
    >>> from pysnmp.hlapi import *
    >>> g = bulkCmd(SnmpEngine(),
    ...             CommunityData('public'),
    ...             UdpTransportTarget(('demo.snmplabs.com', 161)),
    ...             ContextData(),
    ...             0, 25,
    ...             ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
    >>> next(g)
    (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))])
    >>> g.send( [ ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets')) ] )
    (None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))])
    """

    # noinspection PyShadowingNames
    def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus,
              errorIndex, varBindTable, cbCtx):
        cbCtx['errorIndication'] = errorIndication
        cbCtx['errorStatus'] = errorStatus
        cbCtx['errorIndex'] = errorIndex
        cbCtx['varBindTable'] = varBindTable

    lexicographicMode = options.get('lexicographicMode', True)
    ignoreNonIncreasingOid = options.get('ignoreNonIncreasingOid', False)
    maxRows = options.get('maxRows', 0)
    maxCalls = options.get('maxCalls', 0)

    cbCtx = {}

    vbProcessor = CommandGeneratorVarBinds()

    initialVars = [
        x[0] for x in vbProcessor.makeVarBinds(snmpEngine, varBinds)
    ]
    nullVarBinds = [False] * len(initialVars)

    totalRows = totalCalls = 0
    stopFlag = False

    while not stopFlag:
        if maxRows and totalRows < maxRows:
            maxRepetitions = min(maxRepetitions, maxRows - totalRows)

        cmdgen.bulkCmd(
            snmpEngine, authData, transportTarget, contextData, nonRepeaters,
            maxRepetitions, *[(x[0], Null()) for x in varBinds],
            **dict(cbFun=cbFun,
                   cbCtx=cbCtx,
                   lookupMib=options.get('lookupMib', True)))

        snmpEngine.transportDispatcher.runDispatcher()

        errorIndication = cbCtx['errorIndication']
        errorStatus = cbCtx['errorStatus']
        errorIndex = cbCtx['errorIndex']
        varBindTable = cbCtx['varBindTable']

        if ignoreNonIncreasingOid and errorIndication and \
                isinstance(errorIndication, errind.OidNotIncreasing):
            errorIndication = None

        if errorIndication:
            yield (errorIndication, errorStatus, errorIndex,
                   varBindTable and varBindTable[0] or [])
            if errorIndication != errind.requestTimedOut:
                return
        elif errorStatus:
            if errorStatus == 2:
                # Hide SNMPv1 noSuchName error which leaks in here
                # from SNMPv1 Agent through internal pysnmp proxy.
                errorStatus = errorStatus.clone(0)
                errorIndex = errorIndex.clone(0)
            yield (errorIndication, errorStatus, errorIndex,
                   varBindTable and varBindTable[0] or [])
            return
        else:
            for i in range(len(varBindTable)):
                stopFlag = True
                if len(varBindTable[i]) != len(initialVars):
                    varBindTable = i and varBindTable[:i - 1] or []
                    break
                for j in range(len(varBindTable[i])):
                    name, val = varBindTable[i][j]
                    if nullVarBinds[j]:
                        varBindTable[i][j] = name, endOfMibView
                        continue
                    stopFlag = False
                    if isinstance(val, Null):
                        nullVarBinds[j] = True
                    elif not lexicographicMode and \
                            not initialVars[j].isPrefixOf(name):
                        varBindTable[i][j] = name, endOfMibView
                        nullVarBinds[j] = True
                if stopFlag:
                    varBindTable = i and varBindTable[:i - 1] or []
                    break

            totalRows += len(varBindTable)
            totalCalls += 1

            if maxRows and totalRows >= maxRows:
                if totalRows > maxRows:
                    varBindTable = varBindTable[:-(totalRows - maxRows)]
                stopFlag = True

            if maxCalls and totalCalls >= maxCalls:
                stopFlag = True

            for varBinds in varBindTable:
                initialVarBinds = (yield errorIndication, errorStatus,
                                   errorIndex, varBinds)

                if initialVarBinds:
                    varBinds = initialVarBinds
                    initialVars = [
                        x[0] for x in vbProcessor.makeVarBinds(
                            snmpEngine, varBinds)
                    ]
Exemplo n.º 10
0
def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds,
            **options):
    """Creates a generator to perform one or more SNMP GETNEXT queries.

    On each iteration, new SNMP GETNEXT request is send
    (:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response
    to arrive or error to occur.

    Parameters
    ----------
    snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine`
        Class instance representing SNMP engine.

    authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
        Class instance representing SNMP credentials.

    transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
        Class instance representing transport type along with SNMP peer address.

    contextData : :py:class:`~pysnmp.hlapi.ContextData`
        Class instance representing SNMP ContextEngineId and ContextName values.

    \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
        One or more class instances representing MIB variables to place
        into SNMP request.

    Other Parameters
    ----------------
    \*\*options :
        Request options:

            * `lookupMib` - load MIB and resolve response MIB variables at
              the cost of slightly reduced performance. Default is `True`.
              Default is `True`.
            * `lexicographicMode` - stop iteration when all response MIB
              variables leave the scope of initial MIB variables in
              `varBinds`. Default is `True`.
            * `ignoreNonIncreasingOid` - continue iteration even if response
              MIB variables (OIDs) are not greater then request MIB variables.
              Default is `False`.
            * `maxRows` - stop iteration once this generator instance processed
              `maxRows` of SNMP conceptual table. Default is `0` (no limit).
            * `maxCalls` - stop iteration once this generator instance processed
              `maxCalls` responses. Default is 0 (no limit).

    Yields
    ------
    errorIndication : str
        True value indicates SNMP engine error.
    errorStatus : str
        True value indicates SNMP PDU error.
    errorIndex : int
        Non-zero value refers to `varBinds[errorIndex-1]`
    varBinds : tuple
        A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
        instances representing MIB variables returned in SNMP response.

    Raises
    ------
    PySnmpError
        Or its derivative indicating that an error occurred while
        performing SNMP operation.

    Notes
    -----
    The `nextCmd` generator will be exhausted on any of the following
    conditions:

    * SNMP engine error occurs thus `errorIndication` is `True`
    * SNMP PDU `errorStatus` is reported as `True`
    * SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
      (also known as *SNMP exception values*) are reported for all
      MIB variables in `varBinds`
    * *lexicographicMode* option is set to `False` and all
      response MIB variables leave the scope of `varBinds`

    At any moment a new sequence of `varBinds` could be send back into
    running generator (supported since Python 2.6).

    Examples
    --------
    >>> from pysnmp.hlapi import *
    >>> g = nextCmd(SnmpEngine(),
    ...             CommunityData('public'),
    ...             UdpTransportTarget(('demo.snmplabs.com', 161)),
    ...             ContextData(),
    ...             ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
    >>> next(g)
    (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))])
    >>> g.send( [ ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets')) ] )
    (None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))])
    """

    # noinspection PyShadowingNames
    def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus,
              errorIndex, varBindTable, cbCtx):
        cbCtx['errorIndication'] = errorIndication
        cbCtx['errorStatus'] = errorStatus
        cbCtx['errorIndex'] = errorIndex
        cbCtx['varBindTable'] = varBindTable

    lexicographicMode = options.get('lexicographicMode', True)
    ignoreNonIncreasingOid = options.get('ignoreNonIncreasingOid', False)
    maxRows = options.get('maxRows', 0)
    maxCalls = options.get('maxCalls', 0)

    cbCtx = {}

    vbProcessor = CommandGeneratorVarBinds()

    initialVars = [
        x[0] for x in vbProcessor.makeVarBinds(snmpEngine, varBinds)
    ]

    totalRows = totalCalls = 0

    while True:
        if varBinds:
            cmdgen.nextCmd(
                snmpEngine, authData, transportTarget, contextData,
                *[(x[0], Null()) for x in varBinds],
                **dict(cbFun=cbFun,
                       cbCtx=cbCtx,
                       lookupMib=options.get('lookupMib', True)))

            snmpEngine.transportDispatcher.runDispatcher()

            errorIndication = cbCtx['errorIndication']
            errorStatus = cbCtx['errorStatus']
            errorIndex = cbCtx['errorIndex']

            if ignoreNonIncreasingOid and errorIndication and \
                    isinstance(errorIndication, errind.OidNotIncreasing):
                errorIndication = None

            if errorIndication:
                yield (errorIndication, errorStatus, errorIndex, varBinds)
                return
            elif errorStatus:
                if errorStatus == 2:
                    # Hide SNMPv1 noSuchName error which leaks in here
                    # from SNMPv1 Agent through internal pysnmp proxy.
                    errorStatus = errorStatus.clone(0)
                    errorIndex = errorIndex.clone(0)
                yield (errorIndication, errorStatus, errorIndex, varBinds)
                return
            else:
                varBinds = cbCtx['varBindTable'] and cbCtx['varBindTable'][0]
                for idx, varBind in enumerate(varBinds):
                    name, val = varBind
                    if not isinstance(val, Null):
                        if lexicographicMode or initialVars[idx].isPrefixOf(
                                name):
                            break
                else:
                    return

                totalRows += 1
                totalCalls += 1
        else:
            errorIndication = errorStatus = errorIndex = None
            varBinds = []

        initialVarBinds = (yield errorIndication, errorStatus, errorIndex,
                           varBinds)

        if initialVarBinds:
            varBinds = initialVarBinds
            initialVars = [
                x[0] for x in vbProcessor.makeVarBinds(snmpEngine, varBinds)
            ]

        if maxRows and totalRows >= maxRows or \
                maxCalls and totalCalls >= maxCalls:
            return
Exemplo n.º 11
0
def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds,
            **options):
    # noinspection PyShadowingNames
    def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus,
              errorIndex, varBindTable, cbCtx):
        cbCtx['errorIndication'] = errorIndication
        cbCtx['errorStatus'] = errorStatus
        cbCtx['errorIndex'] = errorIndex
        cbCtx['varBindTable'] = varBindTable

    lexicographicMode = options.get('lexicographicMode', True)
    ignoreNonIncreasingOid = options.get('ignoreNonIncreasingOid', False)
    maxRows = options.get('maxRows', 0)
    maxCalls = options.get('maxCalls', 0)

    cbCtx = {}

    vbProcessor = CommandGeneratorVarBinds()

    initialVars = [
        x[0] for x in vbProcessor.makeVarBinds(snmpEngine, varBinds)
    ]

    totalRows = totalCalls = 0

    while True:
        cmdgen.nextCmd(
            snmpEngine, authData, transportTarget, contextData,
            *[(x[0], Null()) for x in varBinds],
            **dict(cbFun=cbFun,
                   cbCtx=cbCtx,
                   lookupMib=options.get('lookupMib', True)))

        snmpEngine.transportDispatcher.runDispatcher()

        errorIndication = cbCtx['errorIndication']
        errorStatus = cbCtx['errorStatus']
        errorIndex = cbCtx['errorIndex']

        if ignoreNonIncreasingOid and errorIndication and \
                isinstance(errorIndication, errind.OidNotIncreasing):
            errorIndication = None

        if errorIndication:
            yield errorIndication, errorStatus, errorIndex, varBinds
            if errorIndication != errind.requestTimedOut:
                return
        elif errorStatus:
            if errorStatus == 2:
                # Hide SNMPv1 noSuchName error which leaks in here
                # from SNMPv1 Agent through internal pysnmp proxy.
                errorStatus = errorStatus.clone(0)
                errorIndex = errorIndex.clone(0)
            yield errorIndication, errorStatus, errorIndex, varBinds
            return
        else:
            varBinds = cbCtx['varBindTable'] and cbCtx['varBindTable'][0]
            for idx, varBind in enumerate(varBinds):
                name, val = varBind
                if not isinstance(val, Null):
                    if lexicographicMode or initialVars[idx].isPrefixOf(name):
                        break
            else:
                return

            totalRows += 1
            totalCalls += 1

            yield errorIndication, errorStatus, errorIndex, varBinds

            if maxRows and totalRows >= maxRows or \
                    maxCalls and totalCalls >= maxCalls:
                return
Exemplo n.º 12
0
def bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters,
            maxRepetitions, *varBinds, **options):
    # noinspection PyShadowingNames
    def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus,
              errorIndex, varBindTable, cbCtx):
        cbCtx['errorIndication'] = errorIndication
        cbCtx['errorStatus'] = errorStatus
        cbCtx['errorIndex'] = errorIndex
        cbCtx['varBindTable'] = varBindTable

    lexicographicMode = options.get('lexicographicMode', True)
    ignoreNonIncreasingOid = options.get('ignoreNonIncreasingOid', False)
    maxRows = options.get('maxRows', 0)
    maxCalls = options.get('maxCalls', 0)

    cbCtx = {}

    vbProcessor = CommandGeneratorVarBinds()

    initialVars = [
        x[0] for x in vbProcessor.makeVarBinds(snmpEngine, varBinds)
    ]
    nullVarBinds = [False] * len(initialVars)

    totalRows = totalCalls = 0
    stopFlag = False

    while not stopFlag:
        if maxRows and totalRows < maxRows:
            maxRepetitions = min(maxRepetitions, maxRows - totalRows)

        cmdgen.bulkCmd(
            snmpEngine, authData, transportTarget, contextData, nonRepeaters,
            maxRepetitions, *[(x[0], Null()) for x in varBinds],
            **dict(cbFun=cbFun,
                   cbCtx=cbCtx,
                   lookupMib=options.get('lookupMib', True)))

        snmpEngine.transportDispatcher.runDispatcher()

        errorIndication = cbCtx['errorIndication']
        errorStatus = cbCtx['errorStatus']
        errorIndex = cbCtx['errorIndex']
        varBindTable = cbCtx['varBindTable']

        if ignoreNonIncreasingOid and errorIndication and \
                isinstance(errorIndication, errind.OidNotIncreasing):
            errorIndication = None

        if errorIndication:
            yield (errorIndication, errorStatus, errorIndex,
                   varBindTable and varBindTable[0] or [])
            if errorIndication != errind.requestTimedOut:
                return
        elif errorStatus:
            if errorStatus == 2:
                # Hide SNMPv1 noSuchName error which leaks in here
                # from SNMPv1 Agent through internal pysnmp proxy.
                errorStatus = errorStatus.clone(0)
                errorIndex = errorIndex.clone(0)
            yield (errorIndication, errorStatus, errorIndex,
                   varBindTable and varBindTable[0] or [])
            return
        else:
            for i in range(len(varBindTable)):
                stopFlag = True
                if len(varBindTable[i]) != len(initialVars):
                    varBindTable = i and varBindTable[:i - 1] or []
                    break
                for j in range(len(varBindTable[i])):
                    name, val = varBindTable[i][j]
                    if nullVarBinds[j]:
                        varBindTable[i][j] = name, endOfMibView
                        continue
                    stopFlag = False
                    if isinstance(val, Null):
                        nullVarBinds[j] = True
                    elif not lexicographicMode and \
                            not initialVars[j].isPrefixOf(name):
                        varBindTable[i][j] = name, endOfMibView
                        nullVarBinds[j] = True
                if stopFlag:
                    varBindTable = i and varBindTable[:i - 1] or []
                    break

            totalRows += len(varBindTable)
            totalCalls += 1

            if maxRows and totalRows >= maxRows:
                if totalRows > maxRows:
                    varBindTable = varBindTable[:-(totalRows - maxRows)]
                stopFlag = True

            if maxCalls and totalCalls >= maxCalls:
                stopFlag = True

            for varBinds in varBindTable:
                yield errorIndication, errorStatus, errorIndex, varBinds
Exemplo n.º 13
0
class NPKIPlainPrivateKeyInfo(Sequence):
    componentType = NamedTypes(NamedType('oid', ObjectIdentifier()),
                               NamedType('null', Null()))
Exemplo n.º 14
0
    def pkcs7_signed_msg(self, msg: bytes):
        """PKCS#7 signed with certificate
        Sign and encapsulate message
        """
        signed = self.sign(msg)

        owner_cert_pub = der_decoder.decode(self.pub_data)[0]

        # signedData (PKCS #7)
        oi_pkcs7_signed = ObjectIdentifier((1, 2, 840, 113549, 1, 7, 2))
        oi_pkcs7_data = ObjectIdentifier((1, 2, 840, 113549, 1, 7, 1))
        oi_sha256 = ObjectIdentifier((2, 16, 840, 1, 101, 3, 4, 2, 1))
        oi_pkcs7_rsa_enc = ObjectIdentifier((1, 2, 840, 113549, 1, 1, 1))

        der = Sequence().setComponentByPosition(0, oi_pkcs7_signed)

        data = Sequence()
        data = data.setComponentByPosition(0, Integer(1))
        data = data.setComponentByPosition(
            1,
            Set().setComponentByPosition(
                0,
                Sequence().setComponentByPosition(
                    0, oi_sha256).setComponentByPosition(1, Null(''))))
        data = data.setComponentByPosition(
            2,
            Sequence().setComponentByPosition(
                0, oi_pkcs7_data).setComponentByPosition(
                    1,
                    Sequence().subtype(implicitTag=tag.Tag(
                        tag.tagClassContext, tag.tagFormatSimple,
                        0)).setComponentByPosition(
                            0, OctetString(hexValue=msg.hex()))))
        data = data.setComponentByPosition(
            3,
            Sequence().subtype(
                implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple,
                                    0)).setComponentByPosition(
                                        0, owner_cert_pub))

        data4001 = Sequence().setComponentByPosition(0, owner_cert_pub[0][3])
        data4001 = data4001.setComponentByPosition(1, owner_cert_pub[0][1])
        data4002 = Sequence().setComponentByPosition(
            0, oi_sha256).setComponentByPosition(1, Null(''))
        data4003 = Sequence().setComponentByPosition(
            0, oi_pkcs7_rsa_enc).setComponentByPosition(1, Null(''))
        data4004 = OctetString(hexValue=signed.hex())

        data = data.setComponentByPosition(
            4,
            Set().setComponentByPosition(
                0,
                Sequence().setComponentByPosition(
                    0, Integer(1)).setComponentByPosition(
                        1, data4001).setComponentByPosition(
                            2, data4002).setComponentByPosition(
                                3,
                                data4003).setComponentByPosition(4, data4004)))

        der = der.setComponentByPosition(
            1,
            Sequence().subtype(
                implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple,
                                    0)).setComponentByPosition(0, data))

        return der_encoder.encode(der)
Exemplo n.º 15
0
        "NB : The command assumes the current directory to be the root of the BearSSL git structure."
    )
    exit(-1)

# change TBS signature algorithm if an algorithm is given
if args['sign_algorithm']:
    cert["tbsCertificate"]["signature"]["algorithm"] = ObjectIdentifier(
        DilithiumSignAlgoToOID[args['sign_algorithm']])

# change TBS public key type
cert["tbsCertificate"]["subjectPublicKeyInfo"]["algorithm"][
    "algorithm"] = ObjectIdentifier(DilithiumOIDKeyDict[args["pub_key_type"]])

# Force Null TBS public key params (in case of EC certificate mainly)
cert["tbsCertificate"]["subjectPublicKeyInfo"]["algorithm"][
    "parameters"] = Null("")

# Load the raw DER Dilithium public key from the PEM file
dilithium_substrate = b''
for line in open(args['pub_key'], 'r').readlines():
    if not line.startswith('-'):
        dilithium_substrate += line.rstrip().encode()
dilithium_public_key = decoder.decode(
    binascii.a2b_base64(dilithium_substrate))[0]['field-2']

# Replace the existing public key with the new Dilithium public key
cert["tbsCertificate"]["subjectPublicKeyInfo"][
    "subjectPublicKey"] = dilithium_public_key

# Derivate the TBS hash according to the relevant signature algorithm
tbs_der = encoder.encode(cert["tbsCertificate"])
Exemplo n.º 16
0
class AuthorizationList(Sequence):
    """Properties of the key pair as in the Keymaster hardware abstraction layer.

    References:
      * https://developer.android.com/training/articles/security-key-attestation#certificate_schema_authorizationlist
    """
    componentType = NamedTypes(
        OptionalNamedType(
            'purpose',
            SetOf(Integer()).subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 1))),
        OptionalNamedType(
            'algorithm',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 2))),
        OptionalNamedType(
            'keySize',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 3))),
        OptionalNamedType(
            'digest',
            SetOf(Integer()).subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 5))),
        OptionalNamedType(
            'padding',
            SetOf(Integer()).subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 6))),
        OptionalNamedType(
            'ecCurve',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 10))),
        OptionalNamedType(
            'rsaPublicExponent',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 200))),
        OptionalNamedType(
            'rollbackResistance',
            Null().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 303))),
        OptionalNamedType(
            'activeDateTime',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 400))),
        OptionalNamedType(
            'originationExpireDateTime',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 401))),
        OptionalNamedType(
            'usageExpireDateTime',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 402))),
        OptionalNamedType(
            'noAuthRequired',
            Null().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 503))),
        OptionalNamedType(
            'userAuthType',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 504))),
        OptionalNamedType(
            'authTimeout',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 505))),
        OptionalNamedType(
            'allowWhileOnBody',
            Null().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 506))),
        OptionalNamedType(
            'trustedUserPresenceRequired',
            Null().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 507))),
        OptionalNamedType(
            'trustedConfirmationRequired',
            Null().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 508))),
        OptionalNamedType(
            'unlockedDeviceRequired',
            Null().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 509))),
        OptionalNamedType(
            'allApplications',
            Null().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 600))),
        OptionalNamedType(
            'applicationId',
            OctetString().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 601))),
        OptionalNamedType(
            'creationDateTime',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 701))),
        OptionalNamedType(
            'origin',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 702))),
        OptionalNamedType(
            'rollbackResistant',
            Null().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 703))),
        OptionalNamedType(
            'rootOfTrust',
            RootOfTrust().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 704))),
        OptionalNamedType(
            'osVersion',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 705))),
        OptionalNamedType(
            'osPatchLevel',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 706))),
        OptionalNamedType(
            'attestationApplicationId',
            OctetString().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 709))),
        OptionalNamedType(
            'attestationIdBrand',
            OctetString().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 710))),
        OptionalNamedType(
            'attestationIdDevice',
            OctetString().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 711))),
        OptionalNamedType(
            'attestationIdProduct',
            OctetString().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 712))),
        OptionalNamedType(
            'attestationIdSerial',
            OctetString().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 713))),
        OptionalNamedType(
            'attestationIdImei',
            OctetString().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 714))),
        OptionalNamedType(
            'attestationIdMeid',
            OctetString().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 715))),
        OptionalNamedType(
            'attestationIdManufacturer',
            OctetString().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 716))),
        OptionalNamedType(
            'attestationIdModel',
            OctetString().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 717))),
        OptionalNamedType(
            'vendorPatchLevel',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 718))),
        OptionalNamedType(
            'bootPatchLevel',
            Integer().subtype(
                explicitTag=Tag(tagClassContext, tagFormatSimple, 719))),
    )