Beispiel #1
0
 def setUp(self):
     self.s = univ.Choice(componentType=namedtype.NamedTypes(
         namedtype.NamedType('place-holder', univ.Null('')),
         namedtype.NamedType('number', univ.Integer(0)),
         namedtype.NamedType('string', univ.OctetString())
         ))
Beispiel #2
0
 def setUp(self):
     self.s = univ.Sequence(componentType=namedtype.NamedTypes(
         namedtype.NamedType('place-holder', univ.Null(null)),
         namedtype.OptionalNamedType('first-name', univ.OctetString(null)),
         namedtype.DefaultedNamedType('age', univ.Integer(33)),
     ))
Beispiel #3
0
 def __initWithDefaulted(self):
     self.s.clear()
     self.s.setComponentByPosition(0, univ.Null(null))
     self.s.setComponentByPosition(2, univ.Integer(1))
     self.s.setDefaultComponents()
Beispiel #4
0
 def testFilled(self):
     self.s.setComponentByPosition(0, univ.Null(''))
     assert encoder.encode(self.s) == ints2octs((5, 0))
Beispiel #5
0
    namedtype.NamedType('dhMAC',
                        univ.BitString().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))),
    namedtype.NamedType('agreeMAC',
                        PKMACValue().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3))),
    namedtype.NamedType('encryptedKey', rfc3852.EnvelopedData().subtype(
        implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 4)))
)


class ProofOfPossession(univ.Choice):
    pass


ProofOfPossession.componentType = namedtype.NamedTypes(
    namedtype.NamedType('raVerified',
                        univ.Null().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))),
    namedtype.NamedType('signature', POPOSigningKey().subtype(
        implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1))),
    namedtype.NamedType('keyEncipherment',
                        POPOPrivKey().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2))),
    namedtype.NamedType('keyAgreement',
                        POPOPrivKey().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3)))
)


class OptionalValidity(univ.Sequence):
    pass


OptionalValidity.componentType = namedtype.NamedTypes(
    namedtype.OptionalNamedType('notBefore', rfc3280.Time().subtype(
Beispiel #6
0
class AsyncCommandGenerator:
    _null = univ.Null('')

    def _getCmdCache(self, snmpEngine):
        if 'cmdgen' not in snmpEngine.cache:
            snmpEngine.cache['cmdgen'] = { 
                'auth': {},
                'parm': {},
                'tran': {},
                'addr': {},
           }
        if 'mibViewController' not in snmpEngine.cache['cmdgen']:
            snmpEngine.cache['cmdgen']['mibViewController'] = view.MibViewController(snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder)

        return snmpEngine.cache['cmdgen']

    def cfgCmdGen(self, snmpEngine, authData, transportTarget):
        cache = self._getCmdCache(snmpEngine)
        if isinstance(authData, CommunityData):
            if authData.communityIndex not in cache['auth']:
                config.addV1System(
                    snmpEngine,
                    authData.communityIndex,
                    authData.communityName,
                    authData.contextEngineId,
                    authData.contextName,
                    authData.tag,
                    authData.securityName
                )
                cache['auth'][authData.communityIndex] = authData
        elif isinstance(authData, UsmUserData):
            authDataKey = authData.userName, authData.securityEngineId
            if authDataKey not in cache['auth']:
                config.addV3User(
                    snmpEngine,
                    authData.userName,
                    authData.authProtocol, authData.authKey,
                    authData.privProtocol, authData.privKey,
                    authData.securityEngineId,
                    securityName=authData.securityName
                )
                cache['auth'][authDataKey] = authData
        else:
            raise error.PySnmpError('Unsupported authentication object')

        paramsKey = authData.securityName, \
                    authData.securityLevel, \
                    authData.mpModel
        if paramsKey in cache['parm']:
            paramsName, useCount = cache['parm'][paramsKey]
            cache['parm'][paramsKey] = paramsName, useCount + 1
        else:
            paramsName = 'p%s' % nextID()
            config.addTargetParams(
                snmpEngine, paramsName,
                authData.securityName, authData.securityLevel, authData.mpModel
            )
            cache['parm'][paramsKey] = paramsName, 1

        if transportTarget.transportDomain in cache['tran']:
            transport, useCount = cache['tran'][transportTarget.transportDomain]
            transportTarget.verifyDispatcherCompatibility(snmpEngine)
            cache['tran'][transportTarget.transportDomain] = transport, useCount + 1
        elif config.getTransport(snmpEngine, transportTarget.transportDomain):
            transportTarget.verifyDispatcherCompatibility(snmpEngine)
        else:
            transport = transportTarget.openClientMode()
            config.addTransport(
                snmpEngine,
                transportTarget.transportDomain,
                transport
            )
            cache['tran'][transportTarget.transportDomain] = transport, 1

        transportKey = ( paramsName,
                         transportTarget.transportDomain,
                         transportTarget.transportAddr,
                         transportTarget.tagList )

        if transportKey in cache['addr']:
            addrName, useCount = cache['addr'][transportKey]
            cache['addr'][transportKey] = addrName, useCount + 1
        else:
            addrName = 'a%s' % nextID()
            config.addTargetAddr(
                snmpEngine, addrName,
                transportTarget.transportDomain,
                transportTarget.transportAddr,
                paramsName,
                transportTarget.timeout * 100,
                transportTarget.retries,
                transportTarget.tagList
            )
            cache['addr'][transportKey] = addrName, 1

        return addrName, paramsName

    def uncfgCmdGen(self, snmpEngine, authData=None):
        cache = self._getCmdCache(snmpEngine)
        if authData:
            if isinstance(authData, CommunityData):
                authDataKey = authData.communityIndex
            elif isinstance(authData, UsmUserData):
                authDataKey = authData.userName, authData.securityEngineId
            else:
                raise error.PySnmpError('Unsupported authentication object')
            if authDataKey in cache['auth']:
                authDataKeys = ( authDataKey, )
            else:
                raise error.PySnmpError('Unknown authData %s' % (authData,))
        else:
            authDataKeys = list(cache['auth'].keys())

        addrNames, paramsNames = set(), set()

        for authDataKey in authDataKeys:
            authDataX = cache['auth'][authDataKey] 
            del cache['auth'][authDataKey]
            if isinstance(authDataX, CommunityData):
                config.delV1System(
                    snmpEngine,
                    authDataX.communityIndex
                )
            elif isinstance(authDataX, UsmUserData):
                config.delV3User(
                    snmpEngine,
                    authDataX.userName, 
                    authDataX.securityEngineId
                )
            else:
                raise error.PySnmpError('Unsupported authentication object')

            paramsKey = authDataX.securityName, \
                        authDataX.securityLevel, \
                        authDataX.mpModel
            if paramsKey in cache['parm']:
                paramsName, useCount = cache['parm'][paramsKey]
                useCount -= 1
                if useCount:
                    cache['parm'][paramsKey] = paramsName, useCount
                else:
                    del cache['parm'][paramsKey]
                    config.delTargetParams(
                        snmpEngine, paramsName
                    )
                    paramsNames.add(paramsName)
            else:
                raise error.PySnmpError('Unknown target %s' % (paramsKey,))

            addrKeys = [ x for x in cache['addr'] if x[0] == paramsName ]

            for addrKey in addrKeys:
                addrName, useCount = cache['addr'][addrKey]
                useCount -= 1
                if useCount:
                    cache['addr'][addrKey] = addrName, useCount
                else:
                    config.delTargetAddr(snmpEngine, addrName)

                    addrNames.add(addrKey)

                    if addrKey[1] in cache['tran']:
                        transport, useCount = cache['tran'][addrKey[1]]
                        if useCount > 1:
                            useCount -= 1
                            cache['tran'][addrKey[1]] = transport, useCount
                        else:
                            config.delTransport(snmpEngine, addrKey[1])
                            transport.closeTransport()
                            del cache['tran'][addrKey[1]]

        return addrNames, paramsNames

    def makeVarBinds(self, snmpEngine, varBinds, oidOnly=False):
        cache = self._getCmdCache(snmpEngine)
        mibViewController = cache['mibViewController']
        __varBinds = []
        for varName, varVal in varBinds:
            if isinstance(varName, MibVariable):
                if oidOnly or isinstance(varVal, base.AbstractSimpleAsn1Item):
                    varName.resolveWithMib(mibViewController, oidOnly=True)
                else:
                    varName.resolveWithMib(mibViewController)
                    varVal = varName.getMibNode().getSyntax().clone(varVal)
            elif isinstance(varName[0], tuple):  # legacy
                varName = MibVariable(varName[0][0], varName[0][1], *varName[1:]).resolveWithMib(mibViewController)
                if not oidOnly and \
                        not isinstance(varVal, base.AbstractSimpleAsn1Item):
                    varVal = varName.getMibNode().getSyntax().clone(varVal)
            else:
                if oidOnly or isinstance(varVal, base.AbstractSimpleAsn1Item):
                    varName = MibVariable(varName).resolveWithMib(mibViewController, oidOnly=True)
                else:
                    varName = MibVariable(varName).resolveWithMib(mibViewController)
                    varVal = varName.getMibNode().getSyntax().clone(varVal)

            __varBinds.append((varName, varVal))

        return __varBinds

    def unmakeVarBinds(self, snmpEngine, varBinds, lookupNames, lookupValues):
        if lookupNames or lookupValues:
            cache = self._getCmdCache(snmpEngine)
            mibViewController = cache['mibViewController']            
            _varBinds = []
            for name, value in varBinds:
                varName = MibVariable(name).resolveWithMib(mibViewController)
                if lookupNames:
                    name = varName
                if lookupValues:
                    if value.tagSet not in (rfc1905.NoSuchObject.tagSet,
                                            rfc1905.NoSuchInstance.tagSet,
                                            rfc1905.EndOfMibView.tagSet):
                        if varName.isFullyResolved():
                            value = varName.getMibNode().getSyntax().clone(value)
                _varBinds.append((name, value))
            return _varBinds
        else:
            return varBinds

    def makeVarBindsHead(self, snmpEngine, varNames):
        return [ 
            x[0] for x in self.makeVarBinds(
                snmpEngine,
                [ (x, univ.Null('')) for x in varNames ], oidOnly=True
            )
        ]


    # Async SNMP apps

    def getCmd(self, snmpEngine, authData, transportTarget, varNames, cbInfo,
               lookupNames=False, lookupValues=False,
               contextEngineId=None, contextName=null):
        def __cbFun(sendRequestHandle,
                    errorIndication, errorStatus, errorIndex,
                    varBinds, cbCtx):
            lookupNames, lookupValues, cbFun, cbCtx = cbCtx
            return cbFun(
                sendRequestHandle,
                errorIndication,
                errorStatus,
                errorIndex,
                self.unmakeVarBinds(
                    snmpEngine, varBinds, lookupNames, lookupValues
                ),
                cbCtx
            )
        
        (cbFun, cbCtx) = cbInfo
        addrName, paramsName = self.cfgCmdGen(
            snmpEngine, authData, transportTarget
        )

        return cmdgen.GetCommandGenerator().sendReq(
            snmpEngine,
            addrName,
            self.makeVarBinds(snmpEngine, [(x, self._null) for x in varNames]),
            __cbFun,
            (lookupNames, lookupValues, cbFun, cbCtx),
            contextEngineId, contextName
        )
    
    def setCmd(self, snmpEngine, authData, transportTarget, varBinds, cbInfo,
               lookupNames=False, lookupValues=False,
               contextEngineId=None, contextName=null):
        def __cbFun(sendRequestHandle,
                    errorIndication, errorStatus, errorIndex,
                    varBinds, cbCtx):
            lookupNames, lookupValues, cbFun, cbCtx = cbCtx
            return cbFun(
                sendRequestHandle,
                errorIndication,
                errorStatus,
                errorIndex,
                self.unmakeVarBinds(
                    snmpEngine, varBinds, lookupNames, lookupValues
                ),
                cbCtx
            )

        (cbFun, cbCtx) = cbInfo
        addrName, paramsName = self.cfgCmdGen(
            snmpEngine, authData, transportTarget
        )

        return cmdgen.SetCommandGenerator().sendReq(
            snmpEngine,
            addrName,
            self.makeVarBinds(snmpEngine, varBinds),
            __cbFun,
            (lookupNames, lookupValues, cbFun, cbCtx),
            contextEngineId, contextName
        )
    
    def nextCmd(self, snmpEngine, authData, transportTarget, varNames, cbInfo,
                lookupNames=False, lookupValues=False,
                contextEngineId=None, contextName=null):
        def __cbFun(sendRequestHandle,
                    errorIndication, errorStatus, errorIndex,
                    varBindTable, cbCtx):
            lookupNames, lookupValues, cbFun, cbCtx = cbCtx
            return cbFun(
                sendRequestHandle,
                errorIndication,
                errorStatus,
                errorIndex,
                [ self.unmakeVarBinds(snmpEngine, varBindTableRow, lookupNames, lookupValues) for varBindTableRow in varBindTable ],
                cbCtx
            )

        (cbFun, cbCtx) = cbInfo
        addrName, paramsName = self.cfgCmdGen(
            snmpEngine, authData, transportTarget
        )
        return cmdgen.NextCommandGenerator().sendReq(
            snmpEngine,
            addrName,
            self.makeVarBinds(snmpEngine, [(x, self._null) for x in varNames]),
            __cbFun,
            (lookupNames, lookupValues, cbFun, cbCtx),
            contextEngineId, contextName
        )

    def bulkCmd(self, snmpEngine, authData, transportTarget,
                nonRepeaters, maxRepetitions, varNames, cbInfo,
                lookupNames=False, lookupValues=False,
                contextEngineId=None, contextName=null):
        def __cbFun(sendRequestHandle,
                    errorIndication, errorStatus, errorIndex,
                    varBindTable, cbCtx):
            lookupNames, lookupValues, cbFun, cbCtx = cbCtx
            return cbFun(
                sendRequestHandle,
                errorIndication,
                errorStatus,
                errorIndex,
                [ self.unmakeVarBinds(snmpEngine, varBindTableRow, lookupNames, lookupValues) for varBindTableRow in varBindTable ],
                cbCtx
            )

        (cbFun, cbCtx) = cbInfo
        addrName, paramsName = self.cfgCmdGen(
            snmpEngine, authData, transportTarget
        )
        return cmdgen.BulkCommandGenerator().sendReq(
            snmpEngine,
            addrName,
            nonRepeaters, maxRepetitions,
            self.makeVarBinds(snmpEngine, [(x, self._null) for x in varNames]),
            __cbFun,
            (lookupNames, lookupValues, cbFun, cbCtx),
            contextEngineId, contextName
        )
Beispiel #7
0
class EcpkParameters(univ.Choice):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('ecParameters', ECParameters()),
        namedtype.NamedType('namedCurve', univ.ObjectIdentifier()),
        namedtype.NamedType('implicitlyCA', univ.Null())
    )
Beispiel #8
0

class TerseOrVerbose(univ.Enumerated):
    pass

TerseOrVerbose.namedValues = namedval.NamedValues(
    ('terse', 1),
    ('verbose', 2)
)


class HardwareSerialEntry(univ.Choice):
    pass

HardwareSerialEntry.componentType = namedtype.NamedTypes(
    namedtype.NamedType('all', univ.Null()),
    namedtype.NamedType('single', univ.OctetString()),
    namedtype.NamedType('block', univ.Sequence(componentType=namedtype.NamedTypes(
        namedtype.NamedType('low', univ.OctetString()),
        namedtype.NamedType('high', univ.OctetString())
    ))
    )
)


class HardwareModules(univ.Sequence):
    pass

HardwareModules.componentType = namedtype.NamedTypes(
    namedtype.NamedType('hwType', univ.ObjectIdentifier()),
    namedtype.NamedType('hwSerialEntries', univ.SequenceOf(
Beispiel #9
0
class AsynCommandGenerator:
    _null = univ.Null('')

    vbProcessor = CommandGeneratorVarBinds()
    lcd = CommandGeneratorLcdConfigurator()

    def __init__(self, snmpEngine=None):
        if snmpEngine is None:
            self.snmpEngine = snmpEngine = SnmpEngine()
        else:
            self.snmpEngine = snmpEngine

        self.mibViewController = self.vbProcessor.getMibViewController(self.snmpEngine)

    def __del__(self):
        self.lcd.unconfigure(self.snmpEngine)

    def cfgCmdGen(self, authData, transportTarget):
        return self.lcd.configure(
            self.snmpEngine, authData, transportTarget
        )

    def uncfgCmdGen(self, authData=None):
        return self.lcd.unconfigure(
            self.snmpEngine, authData
        )

    # compatibility stub
    def makeReadVarBinds(self, varNames):
        return self.makeVarBinds(
            [ (x, self._null) for x in varNames ]
        )

    def makeVarBinds(self, varBinds):
        return self.vbProcessor.makeVarBinds(
            self.snmpEngine, varBinds
        )

    def unmakeVarBinds(self, varBinds, lookupNames, lookupValues):
        return self.vbProcessor.unmakeVarBinds(
            self.snmpEngine, varBinds, lookupNames or lookupValues
        )

    def getCmd(self, authData, transportTarget, varNames, cbInfo,
               lookupNames=False, lookupValues=False,
               contextEngineId=None, contextName=null):

        def __cbFun(snmpEngine, sendRequestHandle,
                    errorIndication, errorStatus, errorIndex,
                    varBindTable, cbInfo):
            cbFun, cbCtx = cbInfo
            cbFun(sendRequestHandle,
                  errorIndication, errorStatus, errorIndex,
                  varBindTable, cbCtx)

        # for backward compatibility
        if contextName is null and authData.contextName:
            contextName = authData.contextName

        return getCmd(
            self.snmpEngine, 
            authData, transportTarget,
            ContextData(contextEngineId, contextName),
            *[(x, self._null) for x in varNames],
            **dict(cbFun=__cbFun, cbCtx=cbInfo,
                   lookupMib=lookupNames or lookupValues)
        )

    asyncGetCmd = getCmd

    def setCmd(self, authData, transportTarget, varBinds, cbInfo,
               lookupNames=False, lookupValues=False,
               contextEngineId=None, contextName=null):

        def __cbFun(snmpEngine, sendRequestHandle,
                    errorIndication, errorStatus, errorIndex,
                    varBindTable, cbInfo):
            cbFun, cbCtx = cbInfo
            cbFun(sendRequestHandle,
                  errorIndication, errorStatus, errorIndex,
                  varBindTable, cbCtx)

        # for backward compatibility
        if contextName is null and authData.contextName:
            contextName = authData.contextName

        
        return setCmd(
            self.snmpEngine,
            authData, transportTarget,
            ContextData(contextEngineId, contextName),
            *varBinds, 
            **dict(cbFun=__cbFun, cbCtx=cbInfo,
                   lookupMib=lookupNames or lookupValues)
        )

    asyncSetCmd = setCmd

    def nextCmd(self, authData, transportTarget, varNames, cbInfo,
                lookupNames=False, lookupValues=False,
                contextEngineId=None, contextName=null):

        def __cbFun(snmpEngine, sendRequestHandle,
                    errorIndication, errorStatus, errorIndex,
                    varBindTable, cbInfo):
            cbFun, cbCtx = cbInfo
            return cbFun(sendRequestHandle,
                         errorIndication, errorStatus, errorIndex,
                         varBindTable, cbCtx)

        # for backward compatibility
        if contextName is null and authData.contextName:
            contextName = authData.contextName

        return nextCmd(
            self.snmpEngine,
            authData, transportTarget,
            ContextData(contextEngineId, contextName),
            *[(x, self._null) for x in varNames],
            **dict(cbFun=__cbFun, cbCtx=cbInfo,
                   lookupMib=lookupNames or lookupValues)
        )

    asyncNextCmd = nextCmd

    def bulkCmd(self, authData, transportTarget,
                nonRepeaters, maxRepetitions, varNames, cbInfo,
                lookupNames=False, lookupValues=False,
                contextEngineId=None, contextName=null):

        def __cbFun(snmpEngine, sendRequestHandle,
                    errorIndication, errorStatus, errorIndex,
                    varBindTable, cbInfo):
            cbFun, cbCtx = cbInfo
            return cbFun(sendRequestHandle,
                         errorIndication, errorStatus, errorIndex,
                         varBindTable, cbCtx)

        # for backward compatibility
        if contextName is null and authData.contextName:
            contextName = authData.contextName

        return bulkCmd(
            self.snmpEngine, 
            authData, transportTarget,
            ContextData(contextEngineId, contextName),
            nonRepeaters, maxRepetitions,
            *[(x, self._null) for x in varNames],
            **dict(cbFun=__cbFun, cbCtx=cbInfo,
                   lookupMib=lookupNames or lookupValues)
        )

    asyncBulkCmd = bulkCmd
Beispiel #10
0
def Create(signer=None,
           response_status=0,
           response_type='1.3.6.1.5.5.7.48.1.1',
           signature=None,
           version=1,
           responder=None,
           responses=None,
           extensions=None,
           certs=None,
           sigAlg='sha1'):
  ocsp = rfc2560.OCSPResponse()
  ocsp.setComponentByName('responseStatus', response_status)

  if response_status != 0:
    return ocsp

  tbs = rfc2560.ResponseData()
  if version != 1:
    tbs.setComponentByName('version', version)

  if not signer:
    signer = CA
  if not responder:
    responder = GetName(signer)
  tbs.setComponentByName('responderID', responder)
  tbs.setComponentByName('producedAt',
                         useful.GeneralizedTime(
                             PRODUCED_DATE.strftime('%Y%m%d%H%M%SZ')))
  rlist = tbs.setComponentByName('responses').getComponentByName('responses')
  if responses == None:
    responses = [CreateSingleResponse(CERT, 0)]
  if responses:
    for i in range(len(responses)):
      rlist.setComponentByPosition(i, responses[i])

  if extensions:
    elist = tbs.setComponentByName('responseExtensions').getComponentByName(
        'responseExtensions')
    for i in range(len(extensions)):
      elist.setComponentByPosition(i, extensions[i])

  sa = rfc2459.AlgorithmIdentifier()
  sa.setComponentByName('algorithm', SigAlgOid(sigAlg))
  sa.setComponentByName('parameters', univ.Null())

  basic = rfc2560.BasicOCSPResponse()
  basic.setComponentByName('tbsResponseData', tbs)
  basic.setComponentByName('signatureAlgorithm', sa)
  if not signature:
    signature = crypto.sign(signer[2], encoder.encode(tbs), sigAlg)
  basic.setComponentByName('signature',
                           univ.BitString("'%s'H" % (signature.encode('hex'))))
  if certs:
    cs = basic.setComponentByName('certs').getComponentByName('certs')
    for i in range(len(certs)):
      cs.setComponentByPosition(i, certs[i][0])

  rbytes = ocsp.componentType.getTypeByPosition(1)
  rbytes.setComponentByName('responseType',
                            univ.ObjectIdentifier(response_type))
  rbytes.setComponentByName('response', encoder.encode(basic))

  ocsp.setComponentByName('responseBytes', rbytes)
  return ocsp
Beispiel #11
0
class ProofOfPossession(univ.Choice):
    componentType = namedtype.NamedTypes(namedtype.NamedType('raVerified', univ.Null().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.NamedType('signature', POPOSigningKey().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1))), namedtype.NamedType('keyEncipherment', POPOPrivKey().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2))), namedtype.NamedType('keyAgreement', POPOPrivKey().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3))))
Beispiel #12
0
 def setUp(self):
     c = univ.Choice(componentType=namedtype.NamedTypes(
         namedtype.NamedType('actual', univ.Boolean(0))))
     self.s = univ.Set(componentType=namedtype.NamedTypes(
         namedtype.NamedType('place-holder', univ.Null('')),
         namedtype.NamedType('status', c)))
Beispiel #13
0
class CommandGenerator(object):
    _null = univ.Null('')

    def __init__(self, **options):
        self.__options = options
        self.__pendingReqs = {}

    def processResponsePdu(self, snmpEngine, messageProcessingModel,
                           securityModel, securityName, securityLevel,
                           contextEngineId, contextName, pduVersion,
                           PDU, statusInformation, sendPduHandle, cbCtx):
        origSendRequestHandle, cbFun, cbCtx = cbCtx

        # 3.1.1
        if sendPduHandle not in self.__pendingReqs:
            raise error.PySnmpError('Missing sendPduHandle %s' % sendPduHandle)

        (origTransportDomain, origTransportAddress,
         origMessageProcessingModel, origSecurityModel,
         origSecurityName, origSecurityLevel, origContextEngineId,
         origContextName, origPduVersion, origPdu,
         origTimeout, origRetryCount,
         origRetries, origDiscoveryRetries) = self.__pendingReqs.pop(sendPduHandle)

        snmpEngine.transportDispatcher.jobFinished(id(self))

        # 3.1.3
        if statusInformation:
            debug.logger & debug.flagApp and debug.logger(
                'processResponsePdu: sendPduHandle %s, statusInformation %s' % (sendPduHandle, statusInformation))

            errorIndication = statusInformation['errorIndication']

            if errorIndication in (errind.notInTimeWindow, errind.unknownEngineID):
                origDiscoveryRetries += 1
                origRetries = 0
            else:
                origDiscoveryRetries = 0
                origRetries += 1

            if origRetries > origRetryCount or origDiscoveryRetries > self.__options.get('discoveryRetries', 4):
                debug.logger & debug.flagApp and debug.logger(
                    'processResponsePdu: sendPduHandle %s, retry count %d exceeded' % (sendPduHandle, origRetries))
                cbFun(snmpEngine, origSendRequestHandle, errorIndication, None, cbCtx)
                return

            # User-side API assumes SMIv2
            if origMessageProcessingModel == 0:
                reqPDU = rfc2576.v2ToV1(origPdu)
                pduVersion = 0
            else:
                reqPDU = origPdu
                pduVersion = 1

            try:
                sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu(
                    snmpEngine, origTransportDomain, origTransportAddress,
                    origMessageProcessingModel, origSecurityModel,
                    origSecurityName, origSecurityLevel, origContextEngineId,
                    origContextName, pduVersion, reqPDU,
                    True, origTimeout, self.processResponsePdu,
                    (origSendRequestHandle, cbFun, cbCtx))

                snmpEngine.transportDispatcher.jobStarted(id(self))

                self.__pendingReqs[sendPduHandle] = (
                    origTransportDomain, origTransportAddress,
                    origMessageProcessingModel, origSecurityModel,
                    origSecurityName, origSecurityLevel, origContextEngineId,
                    origContextName, origPduVersion, origPdu, origTimeout,
                    origRetryCount, origRetries, origDiscoveryRetries
                )
                return

            except StatusInformation:
                statusInformation = sys.exc_info()[1]
                debug.logger & debug.flagApp and debug.logger(
                    'processResponsePdu: origSendRequestHandle %s, _sendPdu() failed with %r' % (
                    sendPduHandle, statusInformation))
                cbFun(snmpEngine, origSendRequestHandle,
                      statusInformation['errorIndication'],
                      None, cbCtx)
                return

        if (origMessageProcessingModel != messageProcessingModel or
                origSecurityModel != securityModel or
                origSecurityName != origSecurityName or
                origContextEngineId and origContextEngineId != contextEngineId or
                origContextName and origContextName != contextName or
                origPduVersion != pduVersion):
            debug.logger & debug.flagApp and debug.logger(
                'processResponsePdu: sendPduHandle %s, request/response data mismatch' % sendPduHandle)

            cbFun(snmpEngine, origSendRequestHandle,
                  'badResponse', None, cbCtx)
            return

        # User-side API assumes SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v1ToV2(PDU, origPdu)

        # 3.1.2
        if v2c.apiPDU.getRequestID(PDU) != v2c.apiPDU.getRequestID(origPdu):
            debug.logger & debug.flagApp and debug.logger(
                'processResponsePdu: sendPduHandle %s, request-id/response-id mismatch' % sendPduHandle)
            cbFun(snmpEngine, origSendRequestHandle,
                  'badResponse', None, cbCtx)
            return

        cbFun(snmpEngine, origSendRequestHandle, None, PDU, cbCtx)

    def sendPdu(self, snmpEngine, targetName, contextEngineId,
                contextName, PDU, cbFun, cbCtx):
        (transportDomain, transportAddress, timeout,
         retryCount, messageProcessingModel, securityModel,
         securityName,
         securityLevel) = config.getTargetInfo(snmpEngine, targetName)

        # Convert timeout in seconds into timeout in timer ticks
        timeoutInTicks = float(timeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution()

        SnmpEngineID, SnmpAdminString = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols(
            'SNMP-FRAMEWORK-MIB', 'SnmpEngineID', 'SnmpAdminString')

        # Cast possible strings into bytes
        if contextEngineId:
            contextEngineId = SnmpEngineID(contextEngineId)
        contextName = SnmpAdminString(contextName)

        origPDU = PDU

        # User-side API assumes SMIv2
        if messageProcessingModel == 0:
            PDU = rfc2576.v2ToV1(PDU)
            pduVersion = 0
        else:
            pduVersion = 1

        sendRequestHandle = getNextHandle()

        # 3.1
        sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu(
            snmpEngine, transportDomain, transportAddress,
            messageProcessingModel, securityModel, securityName,
            securityLevel, contextEngineId, contextName,
            pduVersion, PDU, True, timeoutInTicks, self.processResponsePdu,
            (sendRequestHandle, cbFun, cbCtx)
        )

        snmpEngine.transportDispatcher.jobStarted(id(self))

        self.__pendingReqs[sendPduHandle] = (
            transportDomain, transportAddress, messageProcessingModel,
            securityModel, securityName, securityLevel, contextEngineId,
            contextName, pduVersion, origPDU, timeoutInTicks,
            retryCount, 0, 0
        )

        debug.logger & debug.flagApp and debug.logger(
            'sendPdu: sendPduHandle %s, timeout %d*10 ms/%d ticks, retry 0 of %d' % (
                sendPduHandle, timeout, timeoutInTicks, retryCount))

        return sendRequestHandle
Beispiel #14
0
#
# Copyright (c) 2005-2017, Ilya Etingof <*****@*****.**>
# License: http://snmplabs.com/pysnmp/license.html
#
import sys
from pysnmp.entity.rfc3413 import config
from pysnmp.proto import rfc1905, errind
from pysnmp.proto.api import v2c
from pysnmp.proto.proxy import rfc2576
from pysnmp import error, nextid, debug
from pysnmp.proto.error import StatusInformation
from pyasn1.type import univ

getNextHandle = nextid.Integer(0x7fffffff)

__null = univ.Null('')


def getNextVarBinds(varBinds, origVarBinds=None):
    errorIndication = None
    idx = nonNulls = len(varBinds)
    rspVarBinds = []
    while idx:
        idx -= 1
        if varBinds[idx][1].tagSet in (rfc1905.NoSuchObject.tagSet,
                                       rfc1905.NoSuchInstance.tagSet,
                                       rfc1905.EndOfMibView.tagSet):
            nonNulls -= 1
        elif origVarBinds is not None:
            if v2c.ObjectIdentifier(origVarBinds[idx][0]).asTuple() >= varBinds[idx][0].asTuple():
                errorIndication = errind.oidNotIncreasing
Beispiel #15
0
 def testGetPositionByType(self):
     assert self.s1.getComponentPositionByType(univ.Null().getTagSet()) == 1
Beispiel #16
0
class CommandGenerator:
    _null = univ.Null('')
    def __init__(self, snmpEngine=None, asynCmdGen=None):
        # compatibility attributes
        self.snmpEngine = snmpEngine or SnmpEngine()

    def getCmd(self, authData, transportTarget, *varNames, **kwargs):
        if 'lookupNames' not in kwargs:
            kwargs['lookupNames'] = False
        if 'lookupValues' not in kwargs:
            kwargs['lookupValues'] = False
        for x in sync.getCmd(self.snmpEngine, authData, transportTarget,
                             ContextData(kwargs.get('contextEngineId'),
                                         kwargs.get('contextName', null)),
                             *[ (x, self._null) for x in varNames ],
                             **kwargs):
            return x

    def setCmd(self, authData, transportTarget, *varBinds, **kwargs):
        if 'lookupNames' not in kwargs:
            kwargs['lookupNames'] = False
        if 'lookupValues' not in kwargs:
            kwargs['lookupValues'] = False
        for x in sync.setCmd(self.snmpEngine, authData, transportTarget,
                             ContextData(kwargs.get('contextEngineId'),
                                         kwargs.get('contextName', null)),
                             *varBinds,
                             **kwargs):
            return x

    def nextCmd(self, authData, transportTarget, *varNames, **kwargs):
        if 'lookupNames' not in kwargs:
            kwargs['lookupNames'] = False
        if 'lookupValues' not in kwargs:
            kwargs['lookupValues'] = False
        if 'lexicographicMode' not in kwargs:
            kwargs['lexicographicMode'] = False
        varBindTable = []
        for errorIndication, \
                errorStatus, errorIndex, \
                varBinds \
                in sync.nextCmd(self.snmpEngine, authData, transportTarget,
                                ContextData(kwargs.get('contextEngineId'),
                                            kwargs.get('contextName', null)),
                                *[ (x, self._null) for x in varNames ],
                                **kwargs):
            if errorIndication or errorStatus:
                return errorIndication, errorStatus, errorIndex, varBinds

            varBindTable.append(varBinds)

        return errorIndication, errorStatus, errorIndex, varBindTable

    def bulkCmd(self, authData, transportTarget,
                nonRepeaters, maxRepetitions, *varNames, **kwargs):
        if 'lookupNames' not in kwargs:
            kwargs['lookupNames'] = False
        if 'lookupValues' not in kwargs:
            kwargs['lookupValues'] = False
        if 'lexicographicMode' not in kwargs:
            kwargs['lexicographicMode'] = False
        varBindTable = []
        for errorIndication, \
                errorStatus, errorIndex, \
                varBinds \
                in sync.bulkCmd(self.snmpEngine, authData,
                                transportTarget,
                                ContextData(kwargs.get('contextEngineId'),
                                            kwargs.get('contextName', null)),
                                nonRepeaters, maxRepetitions,
                                *[ (x, self._null) for x in varNames ],
                                **kwargs):
            if errorIndication or errorStatus:
                return errorIndication, errorStatus, errorIndex, varBinds

            varBindTable.append(varBinds)

        return errorIndication, errorStatus, errorIndex, varBindTable
Beispiel #17
0
class SimpleSyntax(univ.Choice):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('number', univ.Integer()),
        namedtype.NamedType('string', univ.OctetString()),
        namedtype.NamedType('object', univ.ObjectIdentifier()),
        namedtype.NamedType('empty', univ.Null()))
Beispiel #18
0
class PubKeyHeader(univ.Sequence):
    """OpenSSL Public Key Header"""
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('oid', univ.ObjectIdentifier()),
        namedtype.NamedType('parameters', univ.Null()),
    )
Beispiel #19
0
 def makeReadVarBinds(self, varNames):
     return self.makeVarBinds(
         [ (x, univ.Null('')) for x in varNames ], oidOnly=True
     )
Beispiel #20
0
 def testStr(self):
     assert str(univ.Null('')) == '', 'str() fails'
Beispiel #21
0
 def testNull(self):
     assert encoder.encode(univ.Null('')) == ints2octs((5, 0))
Beispiel #22
0
 def testRepr(self):
     assert eval(repr(univ.Null()),
                 {'Null': univ.Null}) == univ.Null(), 'repr() fails'
Beispiel #23
0
 def testTagged(self):
     s = self.s.subtype(
         explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 4)
     )
     s.setComponentByPosition(0, univ.Null(''))
     assert encoder.encode(s) == ints2octs((164, 2, 5, 0))
Beispiel #24
0
 def testTag(self):
     assert univ.Null().getTagSet() == tag.TagSet(
         (), tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x05))
    def testOpenTypes(self):
        class ClientInformation(univ.Sequence):
            pass

        ClientInformation.componentType = namedtype.NamedTypes(
            namedtype.NamedType('clientId', univ.Integer()),
            namedtype.NamedType('MachineName', char.UTF8String()),
            namedtype.NamedType('UserName', char.UTF8String()),
            namedtype.NamedType('ProcessName', char.UTF8String()))

        class EnrollmentCSP(univ.Sequence):
            pass

        EnrollmentCSP.componentType = namedtype.NamedTypes(
            namedtype.NamedType('KeySpec', univ.Integer()),
            namedtype.NamedType('Name', char.BMPString()),
            namedtype.NamedType('Signature', univ.BitString()))

        openTypeMap = {
            # attributes
            univ.ObjectIdentifier('1.3.6.1.4.1.311.13.2.3'):
            char.IA5String(),
            univ.ObjectIdentifier('1.3.6.1.4.1.311.13.2.2'):
            EnrollmentCSP(),
            univ.ObjectIdentifier('1.3.6.1.4.1.311.21.20'):
            ClientInformation(),
            # algorithm identifier parameters
            univ.ObjectIdentifier('1.2.840.113549.1.1.1'):
            univ.Null(""),
            univ.ObjectIdentifier('1.2.840.113549.1.1.5'):
            univ.Null(""),
            univ.ObjectIdentifier('1.2.840.113549.1.1.11'):
            univ.Null(""),
        }

        openTypeMap.update(opentypemap.get('cmsAttributesMap'))
        openTypeMap.update(opentypemap.get('cmcControlAttributesMap'))

        substrate = pem.readBase64fromText(self.pem_text)
        asn1Object, rest = der_decoder(substrate,
                                       asn1Spec=rfc5652.ContentInfo(),
                                       decodeOpenTypes=True)
        self.assertFalse(rest)
        self.assertTrue(asn1Object.prettyPrint())
        self.assertEqual(substrate, der_encoder(asn1Object))

        eci = asn1Object['content']['encapContentInfo']

        cmsContentTypesMap = opentypemap.get('cmsContentTypesMap')
        self.assertIn(eci['eContentType'], cmsContentTypesMap)
        self.assertEqual(rfc6402.id_cct_PKIData, eci['eContentType'])

        pkid, rest = der_decoder(
            eci['eContent'],
            asn1Spec=cmsContentTypesMap[eci['eContentType']],
            openTypes=openTypeMap,
            decodeOpenTypes=True)

        self.assertFalse(rest)
        self.assertTrue(pkid.prettyPrint())
        self.assertEqual(eci['eContent'], der_encoder(pkid))

        for req in pkid['reqSequence']:
            cr = req['tcr']['certificationRequest']

            sig_alg = cr['signatureAlgorithm']

            self.assertIn(sig_alg['algorithm'], openTypeMap)
            self.assertEqual(univ.Null(""), sig_alg['parameters'])

            cri = cr['certificationRequestInfo']
            spki_alg = cri['subjectPublicKeyInfo']['algorithm']

            self.assertIn(spki_alg['algorithm'], openTypeMap)
            self.assertEqual(univ.Null(""), spki_alg['parameters'])

            attrs = cr['certificationRequestInfo']['attributes']

            for attr in attrs:
                self.assertIn(attr['attrType'], openTypeMap)

                if attr['attrType'] == univ.ObjectIdentifier(
                        '1.3.6.1.4.1.311.13.2.3'):
                    self.assertEqual("6.2.9200.2", attr['attrValues'][0])

                else:
                    self.assertTrue(attr['attrValues'][0].hasValue())
Beispiel #26
0
 def setUp(self):
     self.s1 = univ.Set(componentType=namedtype.NamedTypes(
         namedtype.NamedType('name', univ.OctetString('')),
         namedtype.OptionalNamedType('null', univ.Null('')),
         namedtype.DefaultedNamedType('age', univ.Integer(34))))
     self.s2 = self.s1.clone()
Beispiel #27
0
 def __init(self):
     self.s.clear()
     self.s.setComponentByPosition(0, univ.Null(null))
     self.s.setDefaultComponents()
Beispiel #28
0
 def testGetComponentTagMap(self):
     assert self.s1.getComponentTagMap().getPosMap() == {
         univ.OctetString.tagSet: univ.OctetString(''),
         univ.Null.tagSet: univ.Null(''),
         univ.Integer.tagSet: univ.Integer(34)
     }
Beispiel #29
0
 def __initWithOptionalAndDefaulted(self):
     self.s.clear()
     self.s.setComponentByPosition(0, univ.Null(null))
     self.s.setComponentByPosition(1, univ.OctetString('quick brown'))
     self.s.setComponentByPosition(2, univ.Integer(1))
     self.s.setDefaultComponents()
Beispiel #30
0
 def testNull(self):
     assert encoder.encode(univ.Null('')) is None