summaryrefslogtreecommitdiff
path: root/pysnmp/proto
diff options
context:
space:
mode:
authorIlya Etingof <etingof@gmail.com>2019-02-10 16:38:35 +0100
committerGitHub <noreply@github.com>2019-02-10 16:38:35 +0100
commit588b9b902d191d8010cb6b247fcb07887d59542c (patch)
tree419b01d2598e91331db784ac3a6675324aba8c24 /pysnmp/proto
parent9664858b145140a4fbb2a22b633c1ab41c2555bd (diff)
downloadpysnmp-git-588b9b902d191d8010cb6b247fcb07887d59542c.tar.gz
Uppercase global constants (#238)
This is a massive patch essentially upper-casing global/class attributes that mean to be constants. Some previously exposed constants have been preserved for compatibility reasons (notably, in `hlapi`), though the rest might break user code relying on pysnmp 4.
Diffstat (limited to 'pysnmp/proto')
-rw-r--r--pysnmp/proto/acmod/rfc3415.py4
-rw-r--r--pysnmp/proto/acmod/void.py4
-rw-r--r--pysnmp/proto/api/__init__.py6
-rw-r--r--pysnmp/proto/api/verdec.py5
-rw-r--r--pysnmp/proto/errind.py40
-rw-r--r--pysnmp/proto/error.py2
-rw-r--r--pysnmp/proto/mpmod/base.py4
-rw-r--r--pysnmp/proto/mpmod/rfc2576.py48
-rw-r--r--pysnmp/proto/mpmod/rfc3412.py83
-rw-r--r--pysnmp/proto/proxy/rfc2576.py74
-rw-r--r--pysnmp/proto/rfc1155.py1
-rw-r--r--pysnmp/proto/rfc3411.py68
-rw-r--r--pysnmp/proto/rfc3412.py42
-rw-r--r--pysnmp/proto/secmod/base.py2
-rw-r--r--pysnmp/proto/secmod/eso/priv/aes192.py8
-rw-r--r--pysnmp/proto/secmod/eso/priv/aes256.py8
-rw-r--r--pysnmp/proto/secmod/eso/priv/aesbase.py33
-rw-r--r--pysnmp/proto/secmod/eso/priv/des3.py43
-rw-r--r--pysnmp/proto/secmod/rfc2576.py54
-rw-r--r--pysnmp/proto/secmod/rfc3414/auth/base.py2
-rw-r--r--pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py29
-rw-r--r--pysnmp/proto/secmod/rfc3414/auth/hmacsha.py28
-rw-r--r--pysnmp/proto/secmod/rfc3414/auth/noauth.py2
-rw-r--r--pysnmp/proto/secmod/rfc3414/priv/base.py4
-rw-r--r--pysnmp/proto/secmod/rfc3414/priv/des.py42
-rw-r--r--pysnmp/proto/secmod/rfc3414/priv/nopriv.py2
-rw-r--r--pysnmp/proto/secmod/rfc3414/service.py199
-rw-r--r--pysnmp/proto/secmod/rfc3826/priv/aes.py53
-rw-r--r--pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py51
29 files changed, 502 insertions, 439 deletions
diff --git a/pysnmp/proto/acmod/rfc3415.py b/pysnmp/proto/acmod/rfc3415.py
index cf020d9f..0d093c4b 100644
--- a/pysnmp/proto/acmod/rfc3415.py
+++ b/pysnmp/proto/acmod/rfc3415.py
@@ -12,7 +12,7 @@ from pysnmp import debug
# 3.2
class Vacm(object):
"""View-based Access Control Model"""
- accessModelID = 3
+ ACCESS_MODEL_ID = 3
_powOfTwoSeq = (128, 64, 32, 16, 8, 4, 2, 1)
@@ -26,7 +26,7 @@ class Vacm(object):
variableName):
mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController
- debug.logger & debug.flagACL and debug.logger(
+ debug.logger & debug.FLAG_ACL and debug.logger(
'isAccessAllowed: securityModel %s, securityName %s, securityLevel %s, viewType %s, contextName %s for variableName %s' % (
securityModel, securityName, securityLevel, viewType, contextName, variableName))
diff --git a/pysnmp/proto/acmod/void.py b/pysnmp/proto/acmod/void.py
index ecc4c4b6..677103b9 100644
--- a/pysnmp/proto/acmod/void.py
+++ b/pysnmp/proto/acmod/void.py
@@ -12,7 +12,7 @@ from pysnmp import debug
# noinspection PyUnusedLocal
class Vacm(object):
"""Void Access Control Model"""
- accessModelID = 0
+ ACCESS_MODEL_ID = 0
def isAccessAllowed(self,
snmpEngine,
@@ -22,7 +22,7 @@ class Vacm(object):
viewType,
contextName,
variableName):
- debug.logger & debug.flagACL and debug.logger(
+ debug.logger & debug.FLAG_ACL and debug.logger(
'isAccessAllowed: viewType %s for variableName %s - OK' % (viewType, variableName)
)
diff --git a/pysnmp/proto/api/__init__.py b/pysnmp/proto/api/__init__.py
index d742ecc7..fd404e5c 100644
--- a/pysnmp/proto/api/__init__.py
+++ b/pysnmp/proto/api/__init__.py
@@ -7,8 +7,8 @@
from pysnmp.proto.api import v1, v2c, verdec
# Protocol versions
-protoVersion1 = 0
-protoVersion2c = 1
-protoModules = {protoVersion1: v1, protoVersion2c: v2c}
+SNMP_VERSION_1 = 0
+SNMP_VERSION_2C = 1
+PROTOCOL_MODULES = {SNMP_VERSION_1: v1, SNMP_VERSION_2C: v2c}
decodeMessageVersion = verdec.decodeMessageVersion
diff --git a/pysnmp/proto/api/verdec.py b/pysnmp/proto/api/verdec.py
index 7076e63c..9bbb73bd 100644
--- a/pysnmp/proto/api/verdec.py
+++ b/pysnmp/proto/api/verdec.py
@@ -23,5 +23,6 @@ def decodeMessageVersion(wholeMsg):
if eoo.endOfOctets.isSameTypeWith(ver):
raise ProtocolError('EOO at SNMP version component')
return ver
- except PyAsn1Error:
- raise ProtocolError('Invalid BER at SNMP version component')
+
+ except PyAsn1Error as exc:
+ raise ProtocolError('Invalid BER at SNMP version component: %s' % exc)
diff --git a/pysnmp/proto/errind.py b/pysnmp/proto/errind.py
index b300d324..0c0dcb80 100644
--- a/pysnmp/proto/errind.py
+++ b/pysnmp/proto/errind.py
@@ -41,90 +41,105 @@ class ErrorIndication(Exception):
class SerializationError(ErrorIndication):
pass
+
serializationError = SerializationError('SNMP message serialization error')
class DeserializationError(ErrorIndication):
pass
+
deserializationError = DeserializationError('SNMP message deserialization error')
class ParseError(DeserializationError):
pass
+
parseError = ParseError('SNMP message deserialization error')
class UnsupportedMsgProcessingModel(ErrorIndication):
pass
+
unsupportedMsgProcessingModel = UnsupportedMsgProcessingModel('Unknown SNMP message processing model ID encountered')
class UnknownPDUHandler(ErrorIndication):
pass
+
unknownPDUHandler = UnknownPDUHandler('Unhandled PDU type encountered')
class UnsupportedPDUtype(ErrorIndication):
pass
+
unsupportedPDUtype = UnsupportedPDUtype('Unsupported SNMP PDU type encountered')
class RequestTimedOut(ErrorIndication):
pass
+
requestTimedOut = RequestTimedOut('No SNMP response received before timeout')
class EmptyResponse(ErrorIndication):
pass
+
emptyResponse = EmptyResponse('Empty SNMP response message')
class NonReportable(ErrorIndication):
pass
+
nonReportable = NonReportable('Report PDU generation not attempted')
class DataMismatch(ErrorIndication):
pass
+
dataMismatch = DataMismatch('SNMP request/response parameters mismatched')
class EngineIDMismatch(ErrorIndication):
pass
+
engineIDMismatch = EngineIDMismatch('SNMP engine ID mismatch encountered')
class UnknownEngineID(ErrorIndication):
pass
+
unknownEngineID = UnknownEngineID('Unknown SNMP engine ID encountered')
class TooBig(ErrorIndication):
pass
+
tooBig = TooBig('SNMP message will be too big')
class LoopTerminated(ErrorIndication):
pass
+
loopTerminated = LoopTerminated('Infinite SNMP entities talk terminated')
class InvalidMsg(ErrorIndication):
pass
+
invalidMsg = InvalidMsg('Invalid SNMP message header parameters encountered')
@@ -133,96 +148,112 @@ invalidMsg = InvalidMsg('Invalid SNMP message header parameters encountered')
class UnknownCommunityName(ErrorIndication):
pass
+
unknownCommunityName = UnknownCommunityName('Unknown SNMP community name encountered')
class NoEncryption(ErrorIndication):
pass
+
noEncryption = NoEncryption('No encryption services configured')
class EncryptionError(ErrorIndication):
pass
+
encryptionError = EncryptionError('Ciphering services not available')
class DecryptionError(ErrorIndication):
pass
+
decryptionError = DecryptionError('Ciphering services not available or ciphertext is broken')
class NoAuthentication(ErrorIndication):
pass
+
noAuthentication = NoAuthentication('No authentication services configured')
class AuthenticationError(ErrorIndication):
pass
+
authenticationError = AuthenticationError('Ciphering services not available or bad parameters')
class AuthenticationFailure(ErrorIndication):
pass
+
authenticationFailure = AuthenticationFailure('Authenticator mismatched')
class UnsupportedAuthProtocol(ErrorIndication):
pass
+
unsupportedAuthProtocol = UnsupportedAuthProtocol('Authentication protocol is not supported')
class UnsupportedPrivProtocol(ErrorIndication):
pass
+
unsupportedPrivProtocol = UnsupportedPrivProtocol('Privacy protocol is not supported')
class UnknownSecurityName(ErrorIndication):
pass
+
unknownSecurityName = UnknownSecurityName('Unknown SNMP security name encountered')
class UnsupportedSecurityModel(ErrorIndication):
pass
+
unsupportedSecurityModel = UnsupportedSecurityModel('Unsupported SNMP security model')
class UnsupportedSecurityLevel(ErrorIndication):
pass
+
unsupportedSecurityLevel = UnsupportedSecurityLevel('Unsupported SNMP security level')
class NotInTimeWindow(ErrorIndication):
pass
+
notInTimeWindow = NotInTimeWindow('SNMP message timing parameters not in windows of trust')
class UnknownUserName(ErrorIndication):
pass
+
unknownUserName = UnknownUserName('Unknown USM user')
class WrongDigest(ErrorIndication):
pass
+
wrongDigest = WrongDigest('Wrong SNMP PDU digest')
class ReportPduReceived(ErrorIndication):
pass
+
reportPduReceived = ReportPduReceived('Remote SNMP engine reported error')
@@ -231,42 +262,50 @@ reportPduReceived = ReportPduReceived('Remote SNMP engine reported error')
class NoSuchView(ErrorIndication):
pass
+
noSuchView = NoSuchView('No such MIB view currently exists')
class NoAccessEntry(ErrorIndication):
pass
+
+
noAccessEntry = NoAccessEntry('Access to MIB node denined')
class NoGroupName(ErrorIndication):
pass
+
noGroupName = NoGroupName('No such VACM group configured')
class NoSuchContext(ErrorIndication):
pass
+
noSuchContext = NoSuchContext('SNMP context now found')
class NotInView(ErrorIndication):
pass
+
notInView = NotInView('Requested OID is out of MIB view')
class AccessAllowed(ErrorIndication):
pass
+
accessAllowed = AccessAllowed()
class OtherError(ErrorIndication):
pass
+
otherError = OtherError('Unspecified SNMP engine error occurred')
@@ -275,4 +314,5 @@ otherError = OtherError('Unspecified SNMP engine error occurred')
class OidNotIncreasing(ErrorIndication):
pass
+
oidNotIncreasing = OidNotIncreasing('OID not increasing')
diff --git a/pysnmp/proto/error.py b/pysnmp/proto/error.py
index 14e6b737..6d10b0c1 100644
--- a/pysnmp/proto/error.py
+++ b/pysnmp/proto/error.py
@@ -23,7 +23,7 @@ class StatusInformation(SnmpV3Error):
def __init__(self, **kwargs):
SnmpV3Error.__init__(self)
self.__errorIndication = kwargs
- debug.logger & (debug.flagDsp | debug.flagMP | debug.flagSM | debug.flagACL) and debug.logger(
+ debug.logger & (debug.FLAG_DSP | debug.FLAG_MP | debug.FLAG_SM | debug.FLAG_ACL) and debug.logger(
'StatusInformation: %s' % kwargs)
def __str__(self):
diff --git a/pysnmp/proto/mpmod/base.py b/pysnmp/proto/mpmod/base.py
index 620ccf89..0a9f9f6a 100644
--- a/pysnmp/proto/mpmod/base.py
+++ b/pysnmp/proto/mpmod/base.py
@@ -9,10 +9,10 @@ from pysnmp.proto import error
class AbstractMessageProcessingModel(object):
- snmpMsgSpec = NotImplementedError
+ SNMP_MSG_SPEC = NotImplementedError
def __init__(self):
- self._snmpMsgSpec = self.snmpMsgSpec() # local copy
+ self._snmpMsgSpec = self.SNMP_MSG_SPEC() # local copy
self._cache = cache.Cache()
def prepareOutgoingMessage(self, snmpEngine, transportDomain,
diff --git a/pysnmp/proto/mpmod/rfc2576.py b/pysnmp/proto/mpmod/rfc2576.py
index 9c050430..3872ce9a 100644
--- a/pysnmp/proto/mpmod/rfc2576.py
+++ b/pysnmp/proto/mpmod/rfc2576.py
@@ -20,8 +20,8 @@ from pysnmp import debug
# references here goes to RFC3412.
class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
- messageProcessingModelID = univ.Integer(0) # SNMPv1
- snmpMsgSpec = v1.Message
+ MESSAGE_PROCESSING_MODEL_ID = univ.Integer(0) # SNMPv1
+ SNMP_MSG_SPEC = v1.Message
# rfc3412: 7.1
def prepareOutgoingMessage(self, snmpEngine, transportDomain,
@@ -35,11 +35,11 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
snmpEngineId = snmpEngineId.syntax
# rfc3412: 7.1.1b
- if pdu.tagSet in rfc3411.confirmedClassPDUs:
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
# serve unique PDU request-id
msgID = self._cache.newMsgID()
reqID = pdu.getComponentByPosition(0)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareOutgoingMessage: PDU request-id %s replaced with unique ID %s' % (reqID, msgID))
# rfc3412: 7.1.4
@@ -52,14 +52,14 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
if not contextName:
contextName = null
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareOutgoingMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName))
# rfc3412: 7.1.6
scopedPDU = (contextEngineId, contextName, pdu)
msg = self._snmpMsgSpec
- msg.setComponentByPosition(0, self.messageProcessingModelID)
+ msg.setComponentByPosition(0, self.MESSAGE_PROCESSING_MODEL_ID)
msg.setComponentByPosition(2)
msg.getComponentByPosition(2).setComponentByType(
pdu.tagSet, pdu, verifyConstraints=False, matchTags=False, matchConstraints=False
@@ -82,25 +82,25 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
'snmpEngineMaxMessageSize')
# fix unique request-id right prior PDU serialization
- if pdu.tagSet in rfc3411.confirmedClassPDUs:
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
# noinspection PyUnboundLocalVariable
pdu.setComponentByPosition(0, msgID)
# rfc3412: 7.1.9.b
(securityParameters,
wholeMsg) = smHandler.generateRequestMsg(
- snmpEngine, self.messageProcessingModelID, globalData,
+ snmpEngine, self.MESSAGE_PROCESSING_MODEL_ID, globalData,
snmpEngineMaxMessageSize.syntax, securityModel,
snmpEngineId, securityName, securityLevel, scopedPDU
)
# return original request-id right after PDU serialization
- if pdu.tagSet in rfc3411.confirmedClassPDUs:
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
# noinspection PyUnboundLocalVariable
pdu.setComponentByPosition(0, reqID)
# rfc3412: 7.1.9.c
- if pdu.tagSet in rfc3411.confirmedClassPDUs:
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
# XXX rfc bug? why stateReference should be created?
self._cache.pushByMsgId(int(msgID), sendPduHandle=sendPduHandle,
reqID=reqID, snmpEngineId=snmpEngineId,
@@ -161,7 +161,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
transportDomain = cachedParams['transportDomain']
transportAddress = cachedParams['transportAddress']
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareResponseMessage: cache read msgID %s transportDomain %s transportAddress %s by stateReference %s' % (
msgID, transportDomain, transportAddress, stateReference))
@@ -185,7 +185,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.1.6
scopedPDU = (contextEngineId, contextName, pdu)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareResponseMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName))
msg = self._snmpMsgSpec
@@ -213,7 +213,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.1.8.a
(securityParameters, wholeMsg) = smHandler.generateResponseMsg(
- snmpEngine, self.messageProcessingModelID, globalData,
+ snmpEngine, self.MESSAGE_PROCESSING_MODEL_ID, globalData,
maxMessageSize, securityModel, snmpEngineId, securityName,
securityLevel, scopedPDU, securityStateReference
)
@@ -249,7 +249,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.2.2
msg, restOfWholeMsg = decoder.decode(wholeMsg, asn1Spec=self._snmpMsgSpec)
- debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),))
+ debug.logger & debug.FLAG_MP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),))
if eoo.endOfOctets.isSameTypeWith(msg):
raise error.StatusInformation(errorIndication=errind.parseError)
@@ -289,7 +289,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
securityModel, securityLevel, wholeMsg, msg
)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: SM returned securityEngineId %r securityName %r' % (securityEngineId, securityName))
except error.StatusInformation as exc:
@@ -322,7 +322,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.2.8, 7.2.9 -> no-op
# rfc3412: 7.2.10
- if pduType in rfc3411.responseClassPDUs:
+ if pduType in rfc3411.RESPONSE_CLASS_PDUS:
# get unique PDU request-id
msgID = pdu.getComponentByPosition(0)
@@ -336,7 +336,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# recover original PDU request-id to return to app
pdu.setComponentByPosition(0, cachedReqParams['reqID'])
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: unique PDU request-id %s replaced with original ID %s' % (
msgID, cachedReqParams['reqID']))
@@ -351,7 +351,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.2.11 -> no-op
# rfc3412: 7.2.12
- if pduType in rfc3411.responseClassPDUs:
+ if pduType in rfc3411.RESPONSE_CLASS_PDUS:
# rfc3412: 7.2.12a -> no-op
# rfc3412: 7.2.12b
# noinspection PyUnboundLocalVariable
@@ -393,12 +393,12 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
stateReference)
# rfc3412: 7.2.13
- if pduType in rfc3411.confirmedClassPDUs:
+ if pduType in rfc3411.CONFIRMED_CLASS_PDUS:
# store original PDU request-id and replace it with a unique one
reqID = pdu.getComponentByPosition(0)
msgID = self._cache.newMsgID()
pdu.setComponentByPosition(0, msgID)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: received PDU request-id %s replaced with unique ID %s' % (reqID, msgID))
# rfc3412: 7.2.13a
@@ -440,7 +440,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
snmpEngine, 'rfc2576.prepareDataElements:confirmed'
)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: cached by new stateReference %s' % stateReference)
# rfc3412: 7.2.13c
@@ -451,7 +451,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
stateReference)
# rfc3412: 7.2.14
- if pduType in rfc3411.unconfirmedClassPDUs:
+ if pduType in rfc3411.UNCONFIRMED_CLASS_PDUS:
# Pass new stateReference to let app browse request details
stateReference = self._cache.newStateReference()
@@ -486,5 +486,5 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
class SnmpV2cMessageProcessingModel(SnmpV1MessageProcessingModel):
- messageProcessingModelID = univ.Integer(1) # SNMPv2c
- snmpMsgSpec = v2c.Message
+ MESSAGE_PROCESSING_MODEL_ID = univ.Integer(1) # SNMPv2c
+ SNMP_MSG_SPEC = v2c.Message
diff --git a/pysnmp/proto/mpmod/rfc3412.py b/pysnmp/proto/mpmod/rfc3412.py
index bda72cd9..fe736cac 100644
--- a/pysnmp/proto/mpmod/rfc3412.py
+++ b/pysnmp/proto/mpmod/rfc3412.py
@@ -13,7 +13,7 @@ from pyasn1.error import PyAsn1Error
from pysnmp import debug
# API to rfc1905 protocol objects
-pMod = api.protoModules[api.protoVersion2c]
+pMod = api.PROTOCOL_MODULES[api.SNMP_VERSION_2C]
# SNMPv3 message format
@@ -68,8 +68,9 @@ _snmpErrors = {(1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0): errind.unsupportedSecurityLev
class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
- messageProcessingModelID = univ.Integer(3) # SNMPv3
- snmpMsgSpec = SNMPv3Message
+ MESSAGE_PROCESSING_MODEL_ID = univ.Integer(3) # SNMPv3
+ SNMP_MSG_SPEC = SNMPv3Message
+
_emptyStr = univ.OctetString('')
_msgFlags = {0: univ.OctetString('\x00'),
1: univ.OctetString('\x01'),
@@ -107,7 +108,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.1b
msgID = self._cache.newMsgID()
- debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: new msgID %s' % msgID)
+ debug.logger & debug.FLAG_MP and debug.logger('prepareOutgoingMessage: new msgID %s' % msgID)
k = (transportDomain, transportAddress)
if k in self.__engineIdCache:
@@ -115,7 +116,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
else:
peerSnmpEngineData = None
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareOutgoingMessage: peer SNMP engine data %s for transport %s, address %s' % (
peerSnmpEngineData, transportDomain, transportAddress))
@@ -134,7 +135,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
if not contextName:
contextName = self._emptyStr
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareOutgoingMessage: using contextEngineId %r, contextName %r' % (contextEngineId, contextName))
# 7.1.6
@@ -151,7 +152,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.7a
msg.setComponentByPosition(
- 0, self.messageProcessingModelID, verifyConstraints=False, matchTags=False, matchConstraints=False
+ 0, self.MESSAGE_PROCESSING_MODEL_ID, verifyConstraints=False, matchTags=False, matchConstraints=False
)
headerData = msg.setComponentByPosition(1).getComponentByPosition(1)
@@ -180,7 +181,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
'Unknown securityLevel %s' % securityLevel
)
- if pdu.tagSet in rfc3411.confirmedClassPDUs:
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
msgFlags |= 0x04
headerData.setComponentByPosition(
@@ -191,7 +192,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# XXX need to coerce MIB value as it has incompatible constraints set
headerData.setComponentByPosition(3, int(securityModel))
- debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: %s' % (msg.prettyPrint(),))
+ debug.logger & debug.FLAG_MP and debug.logger('prepareOutgoingMessage: %s' % (msg.prettyPrint(),))
if securityModel in snmpEngine.securityModels:
smHandler = snmpEngine.securityModels[securityModel]
@@ -201,7 +202,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
)
# 7.1.9.a
- if pdu.tagSet in rfc3411.unconfirmedClassPDUs:
+ if pdu.tagSet in rfc3411.UNCONFIRMED_CLASS_PDUS:
securityEngineId = snmpEngineID
else:
if peerSnmpEngineData is None:
@@ -227,18 +228,18 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
scopedPDU.getComponentByPosition(2).setComponentByType(
emptyPdu.tagSet, emptyPdu, verifyConstraints=False, matchTags=False, matchConstraints=False
)
- debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: force engineID discovery')
+ debug.logger & debug.FLAG_MP and debug.logger('prepareOutgoingMessage: force engineID discovery')
else:
securityEngineId = peerSnmpEngineData['securityEngineId']
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareOutgoingMessage: securityModel %r, securityEngineId %r, securityName %r, securityLevel %r' % (
securityModel, securityEngineId, securityName, securityLevel))
# 7.1.9.b
(securityParameters,
wholeMsg) = smHandler.generateRequestMsg(
- snmpEngine, self.messageProcessingModelID, msg,
+ snmpEngine, self.MESSAGE_PROCESSING_MODEL_ID, msg,
snmpEngineMaxMessageSize.syntax, securityModel,
securityEngineId, securityName, securityLevel, scopedPDU
)
@@ -248,7 +249,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
raise error.StatusInformation(errorIndication=errind.tooBig)
# 7.1.9.c
- if pdu.tagSet in rfc3411.confirmedClassPDUs:
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
# XXX rfc bug? why stateReference should be created?
self._cache.pushByMsgId(msgID, sendPduHandle=sendPduHandle,
msgID=msgID, snmpEngineID=snmpEngineID,
@@ -300,7 +301,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
transportDomain = cachedParams['transportDomain']
transportAddress = cachedParams['transportAddress']
- debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: stateReference %s' % stateReference)
+ debug.logger & debug.FLAG_MP and debug.logger('prepareResponseMessage: stateReference %s' % stateReference)
# 7.1.3
if statusInformation is not None and 'oid' in statusInformation:
@@ -314,7 +315,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.3b
if (pdu is None and not reportableFlag or
pduType is not None and
- pduType not in rfc3411.confirmedClassPDUs):
+ pduType not in rfc3411.CONFIRMED_CLASS_PDUS):
raise error.StatusInformation(
errorIndication=errind.loopTerminated
)
@@ -351,7 +352,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.3e
pdu = reportPDU
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareResponseMessage: prepare report PDU for statusInformation %s' % statusInformation)
# 7.1.4
if not contextEngineId:
@@ -361,7 +362,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
if not contextName:
contextName = self._emptyStr
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareResponseMessage: using contextEngineId %r, contextName %r' % (contextEngineId, contextName))
# 7.1.6
@@ -378,7 +379,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.7a
msg.setComponentByPosition(
- 0, self.messageProcessingModelID, verifyConstraints=False, matchTags=False, matchConstraints=False
+ 0, self.MESSAGE_PROCESSING_MODEL_ID, verifyConstraints=False, matchTags=False, matchConstraints=False
)
headerData = msg.setComponentByPosition(1).getComponentByPosition(1)
@@ -406,7 +407,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
else:
raise error.ProtocolError('Unknown securityLevel %s' % securityLevel)
- if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX not needed?
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS: # XXX not needed?
msgFlags |= 0x04
headerData.setComponentByPosition(
@@ -418,14 +419,14 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
3, securityModel, verifyConstraints=False, matchTags=False, matchConstraints=False
)
- debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: %s' % (msg.prettyPrint(),))
+ debug.logger & debug.FLAG_MP and debug.logger('prepareResponseMessage: %s' % (msg.prettyPrint(),))
if securityModel in snmpEngine.securityModels:
smHandler = snmpEngine.securityModels[securityModel]
else:
raise error.StatusInformation(errorIndication=errind.unsupportedSecurityModel)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareResponseMessage: securityModel %r, securityEngineId %r, securityName %r, securityLevel %r' % (
securityModel, snmpEngineID, securityName, securityLevel))
@@ -433,7 +434,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
try:
(securityParameters,
wholeMsg) = smHandler.generateResponseMsg(
- snmpEngine, self.messageProcessingModelID, msg,
+ snmpEngine, self.MESSAGE_PROCESSING_MODEL_ID, msg,
snmpEngineMaxMessageSize.syntax, securityModel,
snmpEngineID, securityName, securityLevel, scopedPDU,
securityStateReference
@@ -442,7 +443,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.8.b
raise
- debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: SM finished')
+ debug.logger & debug.FLAG_MP and debug.logger('prepareResponseMessage: SM finished')
# Message size constraint verification
if len(wholeMsg) > min(snmpEngineMaxMessageSize.syntax, maxMessageSize):
@@ -474,7 +475,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.2.2
msg, restOfwholeMsg = decoder.decode(wholeMsg, asn1Spec=self._snmpMsgSpec)
- debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),))
+ debug.logger & debug.FLAG_MP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),))
if eoo.endOfOctets.isSameTypeWith(msg):
raise error.StatusInformation(errorIndication=errind.parseError)
@@ -488,7 +489,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
securityModel = headerData.getComponentByPosition(3)
securityParameters = msg.getComponentByPosition(2)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: msg data msgVersion %s msgID %s securityModel %s' % (
msgVersion, msgID, securityModel))
@@ -528,12 +529,12 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
securityParameters, securityModel, securityLevel,
wholeMsg, msg
)
- debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM succeeded')
+ debug.logger & debug.FLAG_MP and debug.logger('prepareDataElements: SM succeeded')
except error.StatusInformation as exc:
statusInformation = exc
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: SM failed, statusInformation %s' % statusInformation)
snmpEngine.observer.storeExecutionContext(
@@ -590,7 +591,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
except error.StatusInformation:
pass
- debug.logger & debug.flagMP and debug.logger('prepareDataElements: error reported')
+ debug.logger & debug.FLAG_MP and debug.logger('prepareDataElements: error reported')
# 7.2.6b
if sys.version_info[0] <= 2:
@@ -615,7 +616,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
pdu = pdus.getComponent()
# Here we assume that authentic/default EngineIDs
# come only in the course of engine-to-engine communication.
- if pdu.tagSet in rfc3411.internalClassPDUs:
+ if pdu.tagSet in rfc3411.INTERNAL_CLASS_PDUS:
self.__engineIdCache[k] = {
'securityEngineId': securityEngineId,
'contextEngineId': contextEngineId,
@@ -627,7 +628,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
self.__engineIdCacheExpQueue[expireAt] = []
self.__engineIdCacheExpQueue[expireAt].append(k)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: cache securityEngineId %r for %r %r' % (
securityEngineId, transportDomain, transportAddress))
@@ -642,14 +643,14 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
pdu = pdu.getComponent() # PDUs
# 7.2.8
- pduVersion = api.protoVersion2c
+ pduVersion = api.SNMP_VERSION_2C
# 7.2.9
pduType = pdu.tagSet
# 7.2.10
- if (pduType in rfc3411.responseClassPDUs or
- pduType in rfc3411.internalClassPDUs):
+ if (pduType in rfc3411.RESPONSE_CLASS_PDUS or
+ pduType in rfc3411.INTERNAL_CLASS_PDUS):
# 7.2.10a
try:
cachedReqParams = self._cache.popByMsgId(msgID)
@@ -663,11 +664,11 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
else:
sendPduHandle = None
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: using sendPduHandle %s for msgID %s' % (sendPduHandle, msgID))
# 7.2.11
- if pduType in rfc3411.internalClassPDUs:
+ if pduType in rfc3411.INTERNAL_CLASS_PDUS:
# 7.2.11a
varBinds = pMod.apiPDU.getVarBinds(pdu)
if varBinds:
@@ -711,7 +712,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
statusInformation = None # no errors ahead
# 7.2.12
- if pduType in rfc3411.responseClassPDUs:
+ if pduType in rfc3411.RESPONSE_CLASS_PDUS:
# 7.2.12a -> no-op
# 7.2.12b
@@ -754,7 +755,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
stateReference)
# 7.2.13
- if pduType in rfc3411.confirmedClassPDUs:
+ if pduType in rfc3411.CONFIRMED_CLASS_PDUS:
# 7.2.13a
if securityEngineId != snmpEngineID:
smHandler.releaseStateInformation(securityStateReference)
@@ -776,7 +777,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
transportAddress=transportAddress
)
- debug.logger & debug.flagMP and debug.logger('prepareDataElements: new stateReference %s' % stateReference)
+ debug.logger & debug.FLAG_MP and debug.logger('prepareDataElements: new stateReference %s' % stateReference)
snmpEngine.observer.storeExecutionContext(
snmpEngine, 'rfc3412.prepareDataElements:confirmed',
@@ -802,7 +803,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
stateReference)
# 7.2.14
- if pduType in rfc3411.unconfirmedClassPDUs:
+ if pduType in rfc3411.UNCONFIRMED_CLASS_PDUS:
# Pass new stateReference to let app browse request details
stateReference = self._cache.newStateReference()
@@ -840,7 +841,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
if self.__expirationTimer in self.__engineIdCacheExpQueue:
for engineKey in self.__engineIdCacheExpQueue[self.__expirationTimer]:
del self.__engineIdCache[engineKey]
- debug.logger & debug.flagMP and debug.logger('__expireEnginesInfo: expiring %r' % (engineKey,))
+ debug.logger & debug.FLAG_MP and debug.logger('__expireEnginesInfo: expiring %r' % (engineKey,))
del self.__engineIdCacheExpQueue[self.__expirationTimer]
self.__expirationTimer += 1
diff --git a/pysnmp/proto/proxy/rfc2576.py b/pysnmp/proto/proxy/rfc2576.py
index 6b1dfcbb..4391a54f 100644
--- a/pysnmp/proto/proxy/rfc2576.py
+++ b/pysnmp/proto/proxy/rfc2576.py
@@ -10,7 +10,7 @@ from pysnmp import debug
# 2.1.1
-__v1ToV2ValueMap = {
+V1_TO_V2_VALUE_MAP = {
v1.Integer.tagSet: v2c.Integer32(),
v1.OctetString.tagSet: v2c.OctetString(),
v1.Null.tagSet: v2c.Null(),
@@ -22,7 +22,7 @@ __v1ToV2ValueMap = {
v1.Opaque.tagSet: v2c.Opaque()
}
-__v2ToV1ValueMap = { # XXX do not re-create same-type items?
+V2_TO_V1_VALUE_MAP = { # XXX do not re-create same-type items?
v2c.Integer32.tagSet: v1.Integer(),
v2c.OctetString.tagSet: v1.OctetString(),
v2c.Null.tagSet: v1.Null(),
@@ -36,7 +36,7 @@ __v2ToV1ValueMap = { # XXX do not re-create same-type items?
# PDU map
-__v1ToV2PduMap = {
+V1_TO_V2_PDU_MAP = {
v1.GetRequestPDU.tagSet: v2c.GetRequestPDU(),
v1.GetNextRequestPDU.tagSet: v2c.GetNextRequestPDU(),
v1.SetRequestPDU.tagSet: v2c.SetRequestPDU(),
@@ -44,7 +44,7 @@ __v1ToV2PduMap = {
v1.TrapPDU.tagSet: v2c.SNMPv2TrapPDU()
}
-__v2ToV1PduMap = {
+V2_TO_V1_PDU_MAP = {
v2c.GetRequestPDU.tagSet: v1.GetRequestPDU(),
v2c.GetNextRequestPDU.tagSet: v1.GetNextRequestPDU(),
v2c.SetRequestPDU.tagSet: v1.SetRequestPDU(),
@@ -55,7 +55,7 @@ __v2ToV1PduMap = {
# Trap map
-__v1ToV2TrapMap = {
+V1_TO_V2_TRAP_MAP = {
0: (1, 3, 6, 1, 6, 3, 1, 1, 5, 1),
1: (1, 3, 6, 1, 6, 3, 1, 1, 5, 2),
2: (1, 3, 6, 1, 6, 3, 1, 1, 5, 3),
@@ -64,7 +64,7 @@ __v1ToV2TrapMap = {
5: (1, 3, 6, 1, 6, 3, 1, 1, 5, 6)
}
-__v2ToV1TrapMap = {
+V2_TO_V1_TRAP_MAP = {
(1, 3, 6, 1, 6, 3, 1, 1, 5, 1): 0,
(1, 3, 6, 1, 6, 3, 1, 1, 5, 2): 1,
(1, 3, 6, 1, 6, 3, 1, 1, 5, 3): 2,
@@ -75,7 +75,7 @@ __v2ToV1TrapMap = {
# 4.3
-__v2ToV1ErrorMap = {
+V2_TO_V1_ERROR_MAP = {
0: 0,
1: 1,
5: 5,
@@ -94,19 +94,17 @@ __v2ToV1ErrorMap = {
16: 2
}
-__zeroInt = v1.Integer(0)
-
def v1ToV2(v1Pdu, origV2Pdu=None, snmpTrapCommunity=''):
pduType = v1Pdu.tagSet
- v2Pdu = __v1ToV2PduMap[pduType].clone()
+ v2Pdu = V1_TO_V2_PDU_MAP[pduType].clone()
- debug.logger & debug.flagPrx and debug.logger('v1ToV2: v1Pdu %s' % v1Pdu.prettyPrint())
+ debug.logger & debug.FLAG_PRX and debug.logger('v1ToV2: v1Pdu %s' % v1Pdu.prettyPrint())
v2VarBinds = []
# 3.1
- if pduType in rfc3411.notificationClassPDUs:
+ if pduType in rfc3411.NOTIFICATION_CLASS_PDUS:
# 3.1.1
sysUpTime = v1.apiTrapPDU.getTimeStamp(v1Pdu)
@@ -117,7 +115,7 @@ def v1ToV2(v1Pdu, origV2Pdu=None, snmpTrapCommunity=''):
# 3.1.3
else:
- snmpTrapOIDParam = v2c.ObjectIdentifier(__v1ToV2TrapMap[genericTrap])
+ snmpTrapOIDParam = v2c.ObjectIdentifier(V1_TO_V2_TRAP_MAP[genericTrap])
# 3.1.4
v2VarBinds.append((v2c.apiTrapPDU.sysUpTime, sysUpTime))
@@ -139,10 +137,10 @@ def v1ToV2(v1Pdu, origV2Pdu=None, snmpTrapCommunity=''):
if v1Val.tagSet == v1.NetworkAddress.tagSet:
v1Val = v1Val.getComponent()
v2VarBinds.append(
- (oid, __v1ToV2ValueMap[v1Val.tagSet].clone(v1Val))
+ (oid, V1_TO_V2_VALUE_MAP[v1Val.tagSet].clone(v1Val))
)
- if pduType in rfc3411.responseClassPDUs:
+ if pduType in rfc3411.RESPONSE_CLASS_PDUS:
# 4.1.2.2.1&2
errorStatus = int(v1.apiPDU.getErrorStatus(v1Pdu))
errorIndex = int(v1.apiPDU.getErrorIndex(v1Pdu, muteErrors=True))
@@ -158,41 +156,43 @@ def v1ToV2(v1Pdu, origV2Pdu=None, snmpTrapCommunity=''):
# 4.1.2.1 --> no-op
- elif pduType in rfc3411.confirmedClassPDUs:
+ elif pduType in rfc3411.CONFIRMED_CLASS_PDUS:
v2c.apiPDU.setErrorStatus(v2Pdu, 0)
v2c.apiPDU.setErrorIndex(v2Pdu, 0)
- if pduType not in rfc3411.notificationClassPDUs:
+ if pduType not in rfc3411.NOTIFICATION_CLASS_PDUS:
v2c.apiPDU.setRequestID(v2Pdu, int(v1.apiPDU.getRequestID(v1Pdu)))
v2c.apiPDU.setVarBinds(v2Pdu, v2VarBinds)
- debug.logger & debug.flagPrx and debug.logger('v1ToV2: v2Pdu %s' % v2Pdu.prettyPrint())
+ debug.logger & debug.FLAG_PRX and debug.logger('v1ToV2: v2Pdu %s' % v2Pdu.prettyPrint())
return v2Pdu
def v2ToV1(v2Pdu, origV1Pdu=None):
- debug.logger & debug.flagPrx and debug.logger('v2ToV1: v2Pdu %s' % v2Pdu.prettyPrint())
+ debug.logger & debug.FLAG_PRX and debug.logger('v2ToV1: v2Pdu %s' % v2Pdu.prettyPrint())
pduType = v2Pdu.tagSet
- if pduType in __v2ToV1PduMap:
- v1Pdu = __v2ToV1PduMap[pduType].clone()
+ if pduType in V2_TO_V1_PDU_MAP:
+ v1Pdu = V2_TO_V1_PDU_MAP[pduType].clone()
else:
raise error.ProtocolError('Unsupported PDU type')
v2VarBinds = v2c.apiPDU.getVarBinds(v2Pdu)
v1VarBinds = []
+ zeroInt = v1.Integer(0)
+
# 3.2
- if pduType in rfc3411.notificationClassPDUs:
+ if pduType in rfc3411.NOTIFICATION_CLASS_PDUS:
# 3.2.1
snmpTrapOID, snmpTrapOIDParam = v2VarBinds[1]
if snmpTrapOID != v2c.apiTrapPDU.snmpTrapOID:
raise error.ProtocolError('Second OID not snmpTrapOID')
snmpTrapOID, snmpTrapOIDParam = v2VarBinds[1]
- if snmpTrapOIDParam in __v2ToV1TrapMap:
+ if snmpTrapOIDParam in V2_TO_V1_TRAP_MAP:
for oid, val in v2VarBinds:
if oid == v2c.apiTrapPDU.snmpTrapEnterprise:
v1.apiTrapPDU.setEnterprise(v1Pdu, val)
@@ -216,14 +216,14 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
v1.apiTrapPDU.setAgentAddr(v1Pdu, v1.IpAddress('0.0.0.0'))
# 3.2.3
- if snmpTrapOIDParam in __v2ToV1TrapMap:
- v1.apiTrapPDU.setGenericTrap(v1Pdu, __v2ToV1TrapMap[snmpTrapOIDParam])
+ if snmpTrapOIDParam in V2_TO_V1_TRAP_MAP:
+ v1.apiTrapPDU.setGenericTrap(v1Pdu, V2_TO_V1_TRAP_MAP[snmpTrapOIDParam])
else:
v1.apiTrapPDU.setGenericTrap(v1Pdu, 6)
# 3.2.4
- if snmpTrapOIDParam in __v2ToV1TrapMap:
- v1.apiTrapPDU.setSpecificTrap(v1Pdu, __zeroInt)
+ if snmpTrapOIDParam in V2_TO_V1_TRAP_MAP:
+ v1.apiTrapPDU.setSpecificTrap(v1Pdu, zeroInt)
else:
v1.apiTrapPDU.setSpecificTrap(v1Pdu, snmpTrapOIDParam[-1])
@@ -232,7 +232,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
__v2VarBinds = []
for oid, val in v2VarBinds[2:]:
- if oid in __v2ToV1TrapMap or \
+ if oid in V2_TO_V1_TRAP_MAP or \
oid in (v2c.apiTrapPDU.sysUpTime,
v2c.apiTrapPDU.snmpTrapAddress,
v2c.apiTrapPDU.snmpTrapEnterprise):
@@ -243,10 +243,10 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
# 3.2.6 --> done below
else:
- v1.apiPDU.setErrorStatus(v1Pdu, __zeroInt)
- v1.apiPDU.setErrorIndex(v1Pdu, __zeroInt)
+ v1.apiPDU.setErrorStatus(v1Pdu, zeroInt)
+ v1.apiPDU.setErrorIndex(v1Pdu, zeroInt)
- if pduType in rfc3411.responseClassPDUs:
+ if pduType in rfc3411.RESPONSE_CLASS_PDUS:
idx = len(v2VarBinds) - 1
while idx >= 0:
# 4.1.2.1
@@ -274,25 +274,25 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
v2ErrorStatus = v2c.apiPDU.getErrorStatus(v2Pdu)
if v2ErrorStatus:
v1.apiPDU.setErrorStatus(
- v1Pdu, __v2ToV1ErrorMap.get(v2ErrorStatus, 5)
+ v1Pdu, V2_TO_V1_ERROR_MAP.get(v2ErrorStatus, 5)
)
v1.apiPDU.setErrorIndex(v1Pdu, v2c.apiPDU.getErrorIndex(v2Pdu, muteErrors=True))
- elif pduType in rfc3411.confirmedClassPDUs:
+ elif pduType in rfc3411.CONFIRMED_CLASS_PDUS:
v1.apiPDU.setErrorStatus(v1Pdu, 0)
v1.apiPDU.setErrorIndex(v1Pdu, 0)
# Translate Var-Binds
- if (pduType in rfc3411.responseClassPDUs and
+ if (pduType in rfc3411.RESPONSE_CLASS_PDUS and
v1.apiPDU.getErrorStatus(v1Pdu)):
v1VarBinds = v1.apiPDU.getVarBinds(origV1Pdu)
else:
for oid, v2Val in v2VarBinds:
v1VarBinds.append(
- (oid, __v2ToV1ValueMap[v2Val.tagSet].clone(v2Val))
+ (oid, V2_TO_V1_VALUE_MAP[v2Val.tagSet].clone(v2Val))
)
- if pduType in rfc3411.notificationClassPDUs:
+ if pduType in rfc3411.NOTIFICATION_CLASS_PDUS:
v1.apiTrapPDU.setVarBinds(v1Pdu, v1VarBinds)
else:
v1.apiPDU.setVarBinds(v1Pdu, v1VarBinds)
@@ -301,6 +301,6 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
v1Pdu, v2c.apiPDU.getRequestID(v2Pdu)
)
- debug.logger & debug.flagPrx and debug.logger('v2ToV1: v1Pdu %s' % v1Pdu.prettyPrint())
+ debug.logger & debug.FLAG_PRX and debug.logger('v2ToV1: v1Pdu %s' % v1Pdu.prettyPrint())
return v1Pdu
diff --git a/pysnmp/proto/rfc1155.py b/pysnmp/proto/rfc1155.py
index 8fb48e8c..b9a2eb25 100644
--- a/pysnmp/proto/rfc1155.py
+++ b/pysnmp/proto/rfc1155.py
@@ -105,7 +105,6 @@ class NetworkAddress(univ.Choice):
raise SmiError('unknown NetworkAddress type %r' % (kind,))
-
class Gauge(univ.Integer):
tagSet = univ.Integer.tagSet.tagImplicitly(
tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02)
diff --git a/pysnmp/proto/rfc3411.py b/pysnmp/proto/rfc3411.py
index bd4d40d3..3c0fd645 100644
--- a/pysnmp/proto/rfc3411.py
+++ b/pysnmp/proto/rfc3411.py
@@ -6,50 +6,50 @@
#
from pysnmp.proto import rfc1157, rfc1905
-readClassPDUs = {
- rfc1157.GetRequestPDU.tagSet: 1,
- rfc1157.GetNextRequestPDU.tagSet: 1,
- rfc1905.GetRequestPDU.tagSet: 1,
- rfc1905.GetNextRequestPDU.tagSet: 1,
- rfc1905.GetBulkRequestPDU.tagSet: 1
+READ_CLASS_PDUS = {
+ rfc1157.GetRequestPDU.tagSet,
+ rfc1157.GetNextRequestPDU.tagSet,
+ rfc1905.GetRequestPDU.tagSet,
+ rfc1905.GetNextRequestPDU.tagSet,
+ rfc1905.GetBulkRequestPDU.tagSet
}
-writeClassPDUs = {
- rfc1157.SetRequestPDU.tagSet: 1,
- rfc1905.SetRequestPDU.tagSet: 1
+WRITE_CLASS_PDUS = {
+ rfc1157.SetRequestPDU.tagSet,
+ rfc1905.SetRequestPDU.tagSet
}
-responseClassPDUs = {
- rfc1157.GetResponsePDU.tagSet: 1,
- rfc1905.ResponsePDU.tagSet: 1,
- rfc1905.ReportPDU.tagSet: 1
+RESPONSE_CLASS_PDUS = {
+ rfc1157.GetResponsePDU.tagSet,
+ rfc1905.ResponsePDU.tagSet,
+ rfc1905.ReportPDU.tagSet
}
-notificationClassPDUs = {
- rfc1157.TrapPDU.tagSet: 1,
- rfc1905.SNMPv2TrapPDU.tagSet: 1,
- rfc1905.InformRequestPDU.tagSet: 1
+NOTIFICATION_CLASS_PDUS = {
+ rfc1157.TrapPDU.tagSet,
+ rfc1905.SNMPv2TrapPDU.tagSet,
+ rfc1905.InformRequestPDU.tagSet
}
-internalClassPDUs = {
- rfc1905.ReportPDU.tagSet: 1
+INTERNAL_CLASS_PDUS = {
+ rfc1905.ReportPDU.tagSet
}
-confirmedClassPDUs = {
- rfc1157.GetRequestPDU.tagSet: 1,
- rfc1157.GetNextRequestPDU.tagSet: 1,
- rfc1157.SetRequestPDU.tagSet: 1,
- rfc1905.GetRequestPDU.tagSet: 1,
- rfc1905.GetNextRequestPDU.tagSet: 1,
- rfc1905.GetBulkRequestPDU.tagSet: 1,
- rfc1905.SetRequestPDU.tagSet: 1,
- rfc1905.InformRequestPDU.tagSet: 1
+CONFIRMED_CLASS_PDUS = {
+ rfc1157.GetRequestPDU.tagSet,
+ rfc1157.GetNextRequestPDU.tagSet,
+ rfc1157.SetRequestPDU.tagSet,
+ rfc1905.GetRequestPDU.tagSet,
+ rfc1905.GetNextRequestPDU.tagSet,
+ rfc1905.GetBulkRequestPDU.tagSet,
+ rfc1905.SetRequestPDU.tagSet,
+ rfc1905.InformRequestPDU.tagSet
}
-unconfirmedClassPDUs = {
- rfc1157.GetResponsePDU.tagSet: 1,
- rfc1905.ResponsePDU.tagSet: 1,
- rfc1157.TrapPDU.tagSet: 1,
- rfc1905.ReportPDU.tagSet: 1,
- rfc1905.SNMPv2TrapPDU.tagSet: 1
+UNCONFIRMED_CLASS_PDUS = {
+ rfc1157.GetResponsePDU.tagSet,
+ rfc1905.ResponsePDU.tagSet,
+ rfc1157.TrapPDU.tagSet,
+ rfc1905.ReportPDU.tagSet,
+ rfc1905.SNMPv2TrapPDU.tagSet
}
diff --git a/pysnmp/proto/rfc3412.py b/pysnmp/proto/rfc3412.py
index 11194984..aaef10d9 100644
--- a/pysnmp/proto/rfc3412.py
+++ b/pysnmp/proto/rfc3412.py
@@ -71,7 +71,7 @@ class MsgAndPduDispatcher(object):
# 4.3.4
self.__appsRegistration[k] = processPdu
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'registerContextEngineId: contextEngineId %r pduTypes %s' % (contextEngineId, pduTypes))
# 4.4.1
@@ -88,7 +88,7 @@ class MsgAndPduDispatcher(object):
if k in self.__appsRegistration:
del self.__appsRegistration[k]
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'unregisterContextEngineId: contextEngineId %r pduTypes %s' % (contextEngineId, pduTypes))
def getRegisteredApp(self, contextEngineId, pduType):
@@ -118,7 +118,7 @@ class MsgAndPduDispatcher(object):
errorIndication=errind.unsupportedMsgProcessingModel
)
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'sendPdu: securityName %s, PDU\n%s' % (securityName, PDU.prettyPrint()))
# 4.1.1.3
@@ -133,10 +133,10 @@ class MsgAndPduDispatcher(object):
cbCtx=cbCtx
)
- debug.logger & debug.flagDsp and debug.logger('sendPdu: current time %d ticks, one tick is %s seconds' % (
+ debug.logger & debug.FLAG_DSP and debug.logger('sendPdu: current time %d ticks, one tick is %s seconds' % (
snmpEngine.transportDispatcher.getTimerTicks(), snmpEngine.transportDispatcher.getTimerResolution()))
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'sendPdu: new sendPduHandle %s, timeout %s ticks, cbFun %s' % (sendPduHandle, timeout, cbFun))
origTransportDomain = transportDomain
@@ -153,7 +153,7 @@ class MsgAndPduDispatcher(object):
pduVersion, PDU, expectResponse, sendPduHandle
)
- debug.logger & debug.flagDsp and debug.logger('sendPdu: MP succeeded')
+ debug.logger & debug.FLAG_DSP and debug.logger('sendPdu: MP succeeded')
except PySnmpError:
if expectResponse:
self.__cache.pop(sendPduHandle)
@@ -222,7 +222,7 @@ class MsgAndPduDispatcher(object):
errorIndication=errind.unsupportedMsgProcessingModel
)
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'returnResponsePdu: PDU %s' % (PDU and PDU.prettyPrint() or "<empty>",))
# 4.1.2.2
@@ -236,7 +236,7 @@ class MsgAndPduDispatcher(object):
statusInformation
)
- debug.logger & debug.flagDsp and debug.logger('returnResponsePdu: MP suceeded')
+ debug.logger & debug.FLAG_DSP and debug.logger('returnResponsePdu: MP suceeded')
except error.StatusInformation:
# 4.1.2.3
@@ -296,7 +296,7 @@ class MsgAndPduDispatcher(object):
snmpInASNParseErrs.syntax += 1
return null # n.b the whole buffer gets dropped
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: msgVersion %s, msg decoded' % msgVersion)
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: msgVersion %s, msg decoded' % msgVersion)
messageProcessingModel = msgVersion
@@ -328,14 +328,14 @@ class MsgAndPduDispatcher(object):
snmpEngine, transportDomain, transportAddress, wholeMsg
)
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP succeded')
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: MP succeded')
except error.StatusInformation as exc:
statusInformation = exc
if 'sendPduHandle' in statusInformation:
# Dropped REPORT -- re-run pending reqs queue as some
# of them may be waiting for this REPORT
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'receiveMessage: MP failed, statusInformation %s, forcing a retry' % statusInformation)
self.__expireRequest(
statusInformation['sendPduHandle'],
@@ -346,19 +346,19 @@ class MsgAndPduDispatcher(object):
return restOfWholeMsg
except PyAsn1Error as exc:
- debug.logger & debug.flagMP and debug.logger('receiveMessage: %s' % exc)
+ debug.logger & debug.FLAG_MP and debug.logger('receiveMessage: %s' % exc)
snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs')
snmpInASNParseErrs.syntax += 1
return restOfWholeMsg
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: PDU %s' % PDU.prettyPrint())
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: PDU %s' % PDU.prettyPrint())
# 4.2.2
if sendPduHandle is None:
# 4.2.2.1 (request or notification)
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: pduType %s' % pduType)
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: pduType %s' % pduType)
# 4.2.2.1.1
processPdu = self.getRegisteredApp(contextEngineId, pduType)
@@ -376,7 +376,7 @@ class MsgAndPduDispatcher(object):
'val': snmpUnknownPDUHandlers.syntax
}
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: unhandled PDU type')
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: unhandled PDU type')
# 4.2.2.1.2.c
try:
@@ -396,11 +396,11 @@ class MsgAndPduDispatcher(object):
)
except PySnmpError as exc:
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'receiveMessage: report failed, statusInformation %s' % exc)
else:
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: reporting succeeded')
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: reporting succeeded')
# 4.2.2.1.2.d
return restOfWholeMsg
@@ -440,7 +440,7 @@ class MsgAndPduDispatcher(object):
if stateReference is not None:
del self.__transportInfo[stateReference]
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: processPdu initiated')
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: processPdu initiated')
return restOfWholeMsg
else:
# 4.2.2.2 (response)
@@ -455,7 +455,7 @@ class MsgAndPduDispatcher(object):
snmpUnknownPDUHandlers.syntax += 1
return restOfWholeMsg
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'receiveMessage: cache read by sendPduHandle %s' % sendPduHandle)
# 4.2.2.2.3
@@ -489,7 +489,7 @@ class MsgAndPduDispatcher(object):
snmpEngine, 'rfc3412.receiveMessage:response'
)
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: processResponsePdu succeeded')
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: processResponsePdu succeeded')
return restOfWholeMsg
@@ -515,7 +515,7 @@ class MsgAndPduDispatcher(object):
processResponsePdu = cachedParams['cbFun']
- debug.logger & debug.flagDsp and debug.logger('__expireRequest: req cachedParams %s' % cachedParams)
+ debug.logger & debug.FLAG_DSP and debug.logger('__expireRequest: req cachedParams %s' % cachedParams)
# Fail timed-out requests
if not statusInformation:
diff --git a/pysnmp/proto/secmod/base.py b/pysnmp/proto/secmod/base.py
index 63df39c7..70850bcf 100644
--- a/pysnmp/proto/secmod/base.py
+++ b/pysnmp/proto/secmod/base.py
@@ -9,7 +9,7 @@ from pysnmp.proto import error
class AbstractSecurityModel(object):
- securityModelID = None
+ SECURITY_MODEL_ID = None
def __init__(self):
self._cache = cache.Cache()
diff --git a/pysnmp/proto/secmod/eso/priv/aes192.py b/pysnmp/proto/secmod/eso/priv/aes192.py
index 399a225b..7df0a0f5 100644
--- a/pysnmp/proto/secmod/eso/priv/aes192.py
+++ b/pysnmp/proto/secmod/eso/priv/aes192.py
@@ -14,8 +14,8 @@ class AesBlumenthal192(aesbase.AbstractAesBlumenthal):
http://tools.ietf.org/html/draft-blumenthal-aes-usm-04
"""
- serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 1) # cusmAESCfb192PrivProtocol
- keySize = 24
+ SERVICE_ID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 1) # cusmAESCfb192PrivProtocol
+ KEY_SIZE = 24
class Aes192(aesbase.AbstractAesReeder):
@@ -29,5 +29,5 @@ class Aes192(aesbase.AbstractAesReeder):
Known to be used by many vendors including Cisco and others.
"""
- serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 101) # cusmAESCfb192PrivProtocol (non-standard OID)
- keySize = 24
+ SERVICE_ID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 101) # cusmAESCfb192PrivProtocol (non-standard OID)
+ KEY_SIZE = 24
diff --git a/pysnmp/proto/secmod/eso/priv/aes256.py b/pysnmp/proto/secmod/eso/priv/aes256.py
index 360f26c3..94a255ff 100644
--- a/pysnmp/proto/secmod/eso/priv/aes256.py
+++ b/pysnmp/proto/secmod/eso/priv/aes256.py
@@ -12,8 +12,8 @@ class AesBlumenthal256(aesbase.AbstractAesBlumenthal):
http://tools.ietf.org/html/draft-blumenthal-aes-usm-04
"""
- serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 2) # cusmAESCfb256PrivProtocol
- keySize = 32
+ SERVICE_ID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 2) # cusmAESCfb256PrivProtocol
+ KEY_SIZE = 32
class Aes256(aesbase.AbstractAesReeder):
@@ -27,5 +27,5 @@ class Aes256(aesbase.AbstractAesReeder):
Known to be used by many vendors including Cisco and others.
"""
- serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 102) # cusmAESCfb256PrivProtocol (non-standard OID)
- keySize = 32
+ SERVICE_ID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 102) # cusmAESCfb256PrivProtocol (non-standard OID)
+ KEY_SIZE = 32
diff --git a/pysnmp/proto/secmod/eso/priv/aesbase.py b/pysnmp/proto/secmod/eso/priv/aesbase.py
index 676afbbb..f2527cec 100644
--- a/pysnmp/proto/secmod/eso/priv/aesbase.py
+++ b/pysnmp/proto/secmod/eso/priv/aesbase.py
@@ -13,6 +13,7 @@ from math import ceil
try:
from hashlib import md5, sha1
+
except ImportError:
import md5
import sha
@@ -22,17 +23,17 @@ except ImportError:
class AbstractAesBlumenthal(aes.Aes):
- serviceID = ()
- keySize = 0
+ SERVICE_ID = ()
+ KEY_SIZE = 0
# 3.1.2.1
def localizeKey(self, authProtocol, privKey, snmpEngineID):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
@@ -41,10 +42,10 @@ class AbstractAesBlumenthal(aes.Aes):
localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo)
# now extend this key if too short by repeating steps that includes the hashPassphrase step
- for count in range(1, int(ceil(self.keySize * 1.0 / len(localPrivKey)))):
+ for count in range(1, int(ceil(self.KEY_SIZE * 1.0 / len(localPrivKey)))):
localPrivKey += hashAlgo(localPrivKey).digest()
- return localPrivKey[:self.keySize]
+ return localPrivKey[:self.KEY_SIZE]
class AbstractAesReeder(aes.Aes):
@@ -62,17 +63,17 @@ class AbstractAesReeder(aes.Aes):
The difference between the two is that the Reeder draft does key extension by repeating
the steps in the password to key algorithm (hash phrase, then localize with SNMPEngine ID).
"""
- serviceID = ()
- keySize = 0
+ SERVICE_ID = ()
+ KEY_SIZE = 0
# 2.1 of https://tools.itef.org/pdf/draft_bluementhal-aes-usm-04.txt
def localizeKey(self, authProtocol, privKey, snmpEngineID):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
@@ -81,9 +82,9 @@ class AbstractAesReeder(aes.Aes):
localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo)
# now extend this key if too short by repeating steps that includes the hashPassphrase step
- while len(localPrivKey) < self.keySize:
+ while len(localPrivKey) < self.KEY_SIZE:
# this is the difference between reeder and bluementhal
newKey = localkey.hashPassphrase(localPrivKey, hashAlgo)
localPrivKey += localkey.localizeKey(newKey, snmpEngineID, hashAlgo)
- return localPrivKey[:self.keySize]
+ return localPrivKey[:self.KEY_SIZE]
diff --git a/pysnmp/proto/secmod/eso/priv/des3.py b/pysnmp/proto/secmod/eso/priv/des3.py
index fa6e20b9..bb3f8516 100644
--- a/pysnmp/proto/secmod/eso/priv/des3.py
+++ b/pysnmp/proto/secmod/eso/priv/des3.py
@@ -5,8 +5,10 @@
# License: http://snmplabs.com/pysnmp/license.html
#
import random
+
try:
from hashlib import md5, sha1
+
except ImportError:
import md5
import sha
@@ -39,17 +41,18 @@ class Des3(base.AbstractEncryptionService):
https://tools.ietf.org/html/draft-reeder-snmpv3-usm-3desede-00
"""
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 3) # usm3DESEDEPrivProtocol
- keySize = 32
- _localInt = random.randrange(0, 0xffffffff)
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 3) # usm3DESEDEPrivProtocol
+ KEY_SIZE = 32
+
+ local_int = random.randrange(0, 0xffffffff)
def hashPassphrase(self, authProtocol, privKey):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
@@ -58,12 +61,12 @@ class Des3(base.AbstractEncryptionService):
# 2.1
def localizeKey(self, authProtocol, privKey, snmpEngineID):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
@@ -71,12 +74,12 @@ class Des3(base.AbstractEncryptionService):
localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo)
# now extend this key if too short by repeating steps that includes the hashPassphrase step
- while len(localPrivKey) < self.keySize:
+ while len(localPrivKey) < self.KEY_SIZE:
# this is the difference between reeder and bluementhal
newKey = localkey.hashPassphrase(localPrivKey, hashAlgo)
localPrivKey += localkey.localizeKey(newKey, snmpEngineID, hashAlgo)
- return localPrivKey[:self.keySize]
+ return localPrivKey[:self.KEY_SIZE]
# 5.1.1.1
def __getEncryptionKey(self, privKey, snmpEngineBoots):
@@ -91,15 +94,15 @@ class Des3(base.AbstractEncryptionService):
securityEngineBoots >> 16 & 0xff,
securityEngineBoots >> 8 & 0xff,
securityEngineBoots & 0xff,
- self._localInt >> 24 & 0xff,
- self._localInt >> 16 & 0xff,
- self._localInt >> 8 & 0xff,
- self._localInt & 0xff
+ self.local_int >> 24 & 0xff,
+ self.local_int >> 16 & 0xff,
+ self.local_int >> 8 & 0xff,
+ self.local_int & 0xff
]
- if self._localInt == 0xffffffff:
- self._localInt = 0
+ if self.local_int == 0xffffffff:
+ self.local_int = 0
else:
- self._localInt += 1
+ self.local_int += 1
# salt not yet hashed XXX
diff --git a/pysnmp/proto/secmod/rfc2576.py b/pysnmp/proto/secmod/rfc2576.py
index 4b49b83a..392294f9 100644
--- a/pysnmp/proto/secmod/rfc2576.py
+++ b/pysnmp/proto/secmod/rfc2576.py
@@ -15,7 +15,7 @@ from pysnmp import debug
class SnmpV1SecurityModel(base.AbstractSecurityModel):
- securityModelID = 1
+ SECURITY_MODEL_ID = 1
# According to rfc2576, community name <-> contextEngineId/contextName
# mapping is up to MP module for notifications but belongs to secmod
@@ -56,7 +56,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__nameToModelMap[nextMibNode.syntax].add(mibNode.syntax)
except PyAsn1Error:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_sec2com: table entries %r/%r hashing failed' % (
nextMibNode.syntax, mibNode.syntax)
)
@@ -103,7 +103,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
_contextName)] = nextMibNode.syntax
except PyAsn1Error:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_sec2com: table entries %r/%r/%r hashing failed' % (
_securityName, _contextEngineId, _contextName)
)
@@ -111,7 +111,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__securityBranchId = snmpCommunityName.branchVersionId
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_sec2com: built securityName to communityName map, version %s: %s' % (
self.__securityBranchId, self.__securityMap))
@@ -154,11 +154,11 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
targetAddrTDomain = tuple(targetAddrTDomain)
- if targetAddrTDomain[:len(udp.snmpUDPDomain)] == udp.snmpUDPDomain:
+ if targetAddrTDomain[:len(udp.SNMP_UDP_DOMAIN)] == udp.SNMP_UDP_DOMAIN:
SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM',
'SnmpUDPAddress')
targetAddrTAddress = tuple(SnmpUDPAddress(targetAddrTAddress))
- elif targetAddrTDomain[:len(udp6.snmpUDP6Domain)] == udp6.snmpUDP6Domain:
+ elif targetAddrTDomain[:len(udp6.SNMP_UDP6_DOMAIN)] == udp6.SNMP_UDP6_DOMAIN:
TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols(
'TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6')
targetAddrTAddress = tuple(TransportAddressIPv6(targetAddrTAddress))
@@ -180,7 +180,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__transportToTagMap[targetAddr].add(self.__emptyTag)
except PyAsn1Error:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: table entries %r/%r hashing failed' % (
targetAddr, targetAddrTagList)
)
@@ -188,7 +188,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__transportBranchId = snmpTargetAddrTAddress.branchVersionId
- debug.logger & debug.flagSM and debug.logger('_com2sec: built transport-to-tag map version %s: %s' % (
+ debug.logger & debug.FLAG_SM and debug.logger('_com2sec: built transport-to-tag map version %s: %s' % (
self.__transportBranchId, self.__transportToTagMap))
snmpTargetParamsSecurityName, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols(
@@ -220,7 +220,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__nameToModelMap[nextMibNode.syntax].add(mibNode.syntax)
except PyAsn1Error:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: table entries %r/%r hashing failed' % (
nextMibNode.syntax, mibNode.syntax)
)
@@ -231,7 +231,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
# invalidate next map as it include this one
self.__communityBranchId = -1
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: built securityName to securityModel map, version %s: %s' % (
self.__paramsBranchId, self.__nameToModelMap))
@@ -285,7 +285,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__communityToTagMap[nextMibNode.syntax].add(transportTag)
except PyAsn1Error:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: table entries %r/%r hashing failed' % (
_tagAndCommunity, nextMibNode.syntax)
)
@@ -293,13 +293,13 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__communityBranchId = snmpCommunityName.branchVersionId
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: built communityName to tag map (securityModel %s), version %s: %s' % (
- self.securityModelID, self.__communityBranchId, self.__communityToTagMap))
+ self.SECURITY_MODEL_ID, self.__communityBranchId, self.__communityToTagMap))
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: built tag & community to securityName map (securityModel %s), version %s: %s' % (
- self.securityModelID, self.__communityBranchId, self.__tagAndCommunityToSecurityMap))
+ self.SECURITY_MODEL_ID, self.__communityBranchId, self.__tagAndCommunityToSecurityMap))
if communityName in self.__communityToTagMap:
if transportInformation in self.__transportToTagMap:
@@ -319,11 +319,11 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
# Picks first match but favors entries already in targets table
if candidateSecurityNames:
candidateSecurityNames.sort(
- key=lambda x, m=self.__nameToModelMap, v=self.securityModelID: (
+ key=lambda x, m=self.__nameToModelMap, v=self.SECURITY_MODEL_ID: (
not int(x[0] in m and v in m[x[0]]), str(x[0]))
)
chosenSecurityName = candidateSecurityNames[0] # min()
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: securityName candidates for communityName \'%s\' are %s; choosing securityName \'%s\'' % (
communityName, candidateSecurityNames, chosenSecurityName[0]))
return chosenSecurityName
@@ -341,7 +341,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
communityName = self._sec2com(snmpEngine, securityName,
contextEngineId, contextName)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'generateRequestMsg: using community %r for securityModel %r, securityName %r, contextEngineId %r contextName %r' % (
communityName, securityModel, securityName, contextEngineId, contextName))
@@ -353,13 +353,13 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
pdu.tagSet, pdu, verifyConstraints=False, matchTags=False, matchConstraints=False
)
- debug.logger & debug.flagMP and debug.logger('generateRequestMsg: %s' % (msg.prettyPrint(),))
+ debug.logger & debug.FLAG_MP and debug.logger('generateRequestMsg: %s' % (msg.prettyPrint(),))
try:
return securityParameters, encoder.encode(msg)
except PyAsn1Error as exc:
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'generateRequestMsg: serialization failure: %s' % exc)
raise error.StatusInformation(errorIndication=errind.serializationError)
@@ -373,7 +373,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
cachedSecurityData = self._cache.pop(securityStateReference)
communityName = cachedSecurityData['communityName']
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'generateResponseMsg: recovered community %r by securityStateReference %s' % (
communityName, securityStateReference))
@@ -383,13 +383,13 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
pdu.tagSet, pdu, verifyConstraints=False, matchTags=False, matchConstraints=False
)
- debug.logger & debug.flagMP and debug.logger('generateResponseMsg: %s' % (msg.prettyPrint(),))
+ debug.logger & debug.FLAG_MP and debug.logger('generateResponseMsg: %s' % (msg.prettyPrint(),))
try:
return communityName, encoder.encode(msg)
except PyAsn1Error as exc:
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'generateResponseMsg: serialization failure: %s' % exc)
raise error.StatusInformation(errorIndication=errind.serializationError)
@@ -442,9 +442,9 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
snmpEngine, 'rfc2576.processIncomingMsg'
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: looked up securityName %r securityModel %r contextEngineId %r contextName %r by communityName %r AND transportInformation %r' % (
- securityName, self.securityModelID, contextEngineId, contextName, communityName, transportInformation))
+ securityName, self.SECURITY_MODEL_ID, contextEngineId, contextName, communityName, transportInformation))
stateReference = self._cache.push(communityName=communityName)
@@ -453,7 +453,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
maxSizeResponseScopedPDU = maxMessageSize - 128
securityStateReference = stateReference
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: generated maxSizeResponseScopedPDU %s securityStateReference %s' % (
maxSizeResponseScopedPDU, securityStateReference))
@@ -462,7 +462,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
class SnmpV2cSecurityModel(SnmpV1SecurityModel):
- securityModelID = 2
+ SECURITY_MODEL_ID = 2
# XXX
# contextEngineId/contextName goes to globalData
diff --git a/pysnmp/proto/secmod/rfc3414/auth/base.py b/pysnmp/proto/secmod/rfc3414/auth/base.py
index 3ff8778f..1c019aea 100644
--- a/pysnmp/proto/secmod/rfc3414/auth/base.py
+++ b/pysnmp/proto/secmod/rfc3414/auth/base.py
@@ -8,7 +8,7 @@ from pysnmp.proto import errind, error
class AbstractAuthenticationService(object):
- serviceID = None
+ SERVICE_ID = None
def hashPassphrase(self, authKey):
raise error.ProtocolError(errind.noAuthentication)
diff --git a/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py b/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py
index 761bf3d9..3ce12da2 100644
--- a/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py
+++ b/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py
@@ -6,25 +6,28 @@
#
try:
from hashlib import md5
+
except ImportError:
import md5
md5 = md5.new
+
from pyasn1.type import univ
from pysnmp.proto.secmod.rfc3414.auth import base
from pysnmp.proto.secmod.rfc3414 import localkey
from pysnmp.proto import errind, error
-_twelveZeros = univ.OctetString((0,) * 12).asOctets()
-_fortyEightZeros = (0,) * 48
+TWELVE_ZEROS = univ.OctetString((0,) * 12).asOctets()
+FORTY_EIGHT_ZEROS = (0,) * 48
# rfc3414: 6.2.4
class HmacMd5(base.AbstractAuthenticationService):
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 2) # usmHMACMD5AuthProtocol
- __ipad = [0x36] * 64
- __opad = [0x5C] * 64
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 2) # usmHMACMD5AuthProtocol
+
+ IPAD = [0x36] * 64
+ OPAD = [0x5C] * 64
def hashPassphrase(self, authKey):
return localkey.hashPassphraseMD5(authKey)
@@ -42,7 +45,7 @@ class HmacMd5(base.AbstractAuthenticationService):
# should be in the substrate. Also, it pre-sets digest placeholder
# so we hash wholeMsg out of the box.
# Yes, that's ugly but that's rfc...
- l = wholeMsg.find(_twelveZeros)
+ l = wholeMsg.find(TWELVE_ZEROS)
if l == -1:
raise error.ProtocolError('Cant locate digest placeholder')
wholeHead = wholeMsg[:l]
@@ -51,20 +54,20 @@ class HmacMd5(base.AbstractAuthenticationService):
# 6.3.1.1
# 6.3.1.2a
- extendedAuthKey = authKey.asNumbers() + _fortyEightZeros
+ extendedAuthKey = authKey.asNumbers() + FORTY_EIGHT_ZEROS
# 6.3.1.2b --> no-op
# 6.3.1.2c
k1 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__ipad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.IPAD)
)
# 6.3.1.2d --> no-op
# 6.3.1.2e
k2 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__opad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.OPAD)
)
# 6.3.1.3
@@ -93,23 +96,23 @@ class HmacMd5(base.AbstractAuthenticationService):
raise error.ProtocolError('Cant locate digest in wholeMsg')
wholeHead = wholeMsg[:l]
wholeTail = wholeMsg[l + 12:]
- authenticatedWholeMsg = wholeHead + _twelveZeros + wholeTail
+ authenticatedWholeMsg = wholeHead + TWELVE_ZEROS + wholeTail
# 6.3.2.4a
- extendedAuthKey = authKey.asNumbers() + _fortyEightZeros
+ extendedAuthKey = authKey.asNumbers() + FORTY_EIGHT_ZEROS
# 6.3.2.4b --> no-op
# 6.3.2.4c
k1 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__ipad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.IPAD)
)
# 6.3.2.4d --> no-op
# 6.3.2.4e
k2 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__opad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.OPAD)
)
# 6.3.2.5a
diff --git a/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py b/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py
index 3efe9c49..8776f6fb 100644
--- a/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py
+++ b/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py
@@ -10,21 +10,23 @@ except ImportError:
import sha
sha1 = sha.new
+
from pyasn1.type import univ
from pysnmp.proto.secmod.rfc3414.auth import base
from pysnmp.proto.secmod.rfc3414 import localkey
from pysnmp.proto import errind, error
-_twelveZeros = univ.OctetString((0,) * 12).asOctets()
-_fortyFourZeros = (0,) * 44
+TWELVE_ZEROS = univ.OctetString((0,) * 12).asOctets()
+FORTY_FOUR_ZEROS = (0,) * 44
# 7.2.4
class HmacSha(base.AbstractAuthenticationService):
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 3) # usmHMACSHAAuthProtocol
- __ipad = [0x36] * 64
- __opad = [0x5C] * 64
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 3) # usmHMACSHAAuthProtocol
+
+ IPAD = [0x36] * 64
+ OPAD = [0x5C] * 64
def hashPassphrase(self, authKey):
return localkey.hashPassphraseSHA(authKey)
@@ -43,27 +45,27 @@ class HmacSha(base.AbstractAuthenticationService):
# should be in the substrate. Also, it pre-sets digest placeholder
# so we hash wholeMsg out of the box.
# Yes, that's ugly but that's rfc...
- l = wholeMsg.find(_twelveZeros)
+ l = wholeMsg.find(TWELVE_ZEROS)
if l == -1:
raise error.ProtocolError('Cant locate digest placeholder')
wholeHead = wholeMsg[:l]
wholeTail = wholeMsg[l + 12:]
# 7.3.1.2a
- extendedAuthKey = authKey.asNumbers() + _fortyFourZeros
+ extendedAuthKey = authKey.asNumbers() + FORTY_FOUR_ZEROS
# 7.3.1.2b -- no-op
# 7.3.1.2c
k1 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__ipad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.IPAD)
)
# 7.3.1.2d -- no-op
# 7.3.1.2e
k2 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__opad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.OPAD)
)
# 7.3.1.3
@@ -90,23 +92,23 @@ class HmacSha(base.AbstractAuthenticationService):
raise error.ProtocolError('Cant locate digest in wholeMsg')
wholeHead = wholeMsg[:l]
wholeTail = wholeMsg[l + 12:]
- authenticatedWholeMsg = wholeHead + _twelveZeros + wholeTail
+ authenticatedWholeMsg = wholeHead + TWELVE_ZEROS + wholeTail
# 7.3.2.4a
- extendedAuthKey = authKey.asNumbers() + _fortyFourZeros
+ extendedAuthKey = authKey.asNumbers() + FORTY_FOUR_ZEROS
# 7.3.2.4b --> no-op
# 7.3.2.4c
k1 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__ipad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.IPAD)
)
# 7.3.2.4d --> no-op
# 7.3.2.4e
k2 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__opad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.OPAD)
)
# 7.3.2.5a
diff --git a/pysnmp/proto/secmod/rfc3414/auth/noauth.py b/pysnmp/proto/secmod/rfc3414/auth/noauth.py
index d1dea4f5..d97d4888 100644
--- a/pysnmp/proto/secmod/rfc3414/auth/noauth.py
+++ b/pysnmp/proto/secmod/rfc3414/auth/noauth.py
@@ -9,7 +9,7 @@ from pysnmp.proto import errind, error
class NoAuth(base.AbstractAuthenticationService):
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 1) # usmNoAuthProtocol
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 1) # usmNoAuthProtocol
def hashPassphrase(self, authKey):
return
diff --git a/pysnmp/proto/secmod/rfc3414/priv/base.py b/pysnmp/proto/secmod/rfc3414/priv/base.py
index a7c68a11..08c2930d 100644
--- a/pysnmp/proto/secmod/rfc3414/priv/base.py
+++ b/pysnmp/proto/secmod/rfc3414/priv/base.py
@@ -8,8 +8,8 @@ from pysnmp.proto import error
class AbstractEncryptionService(object):
- serviceID = None
- keySize = 0
+ SERVICE_ID = None
+ KEY_SIZE = 0
def hashPassphrase(self, authProtocol, privKey):
raise error.ProtocolError('no encryption')
diff --git a/pysnmp/proto/secmod/rfc3414/priv/des.py b/pysnmp/proto/secmod/rfc3414/priv/des.py
index 881989be..c9b483a2 100644
--- a/pysnmp/proto/secmod/rfc3414/priv/des.py
+++ b/pysnmp/proto/secmod/rfc3414/priv/des.py
@@ -5,8 +5,10 @@
# License: http://snmplabs.com/pysnmp/license.html
#
import random
+
try:
from hashlib import md5, sha1
+
except ImportError:
import md5
import sha
@@ -36,21 +38,21 @@ random.seed()
# 8.2.4
class Des(base.AbstractEncryptionService):
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 2) # usmDESPrivProtocol
- keySize = 16
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 2) # usmDESPrivProtocol
+ KEY_SIZE = 16
if version_info < (2, 3):
- _localInt = int(random.random() * 0xffffffff)
+ local_int = int(random.random() * 0xffffffff)
else:
- _localInt = random.randrange(0, 0xffffffff)
+ local_int = random.randrange(0, 0xffffffff)
def hashPassphrase(self, authProtocol, privKey):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
@@ -58,18 +60,18 @@ class Des(base.AbstractEncryptionService):
return localkey.hashPassphrase(privKey, hashAlgo)
def localizeKey(self, authProtocol, privKey, snmpEngineID):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
)
localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo)
- return localPrivKey[:self.keySize]
+ return localPrivKey[:self.KEY_SIZE]
# 8.1.1.1
def __getEncryptionKey(self, privKey, snmpEngineBoots):
@@ -82,14 +84,14 @@ class Des(base.AbstractEncryptionService):
securityEngineBoots >> 16 & 0xff,
securityEngineBoots >> 8 & 0xff,
securityEngineBoots & 0xff,
- self._localInt >> 24 & 0xff,
- self._localInt >> 16 & 0xff,
- self._localInt >> 8 & 0xff,
- self._localInt & 0xff]
- if self._localInt == 0xffffffff:
- self._localInt = 0
+ self.local_int >> 24 & 0xff,
+ self.local_int >> 16 & 0xff,
+ self.local_int >> 8 & 0xff,
+ self.local_int & 0xff]
+ if self.local_int == 0xffffffff:
+ self.local_int = 0
else:
- self._localInt += 1
+ self.local_int += 1
return (desKey.asOctets(),
univ.OctetString(salt).asOctets(),
diff --git a/pysnmp/proto/secmod/rfc3414/priv/nopriv.py b/pysnmp/proto/secmod/rfc3414/priv/nopriv.py
index 6721153b..7283e6ec 100644
--- a/pysnmp/proto/secmod/rfc3414/priv/nopriv.py
+++ b/pysnmp/proto/secmod/rfc3414/priv/nopriv.py
@@ -9,7 +9,7 @@ from pysnmp.proto import errind, error
class NoPriv(base.AbstractEncryptionService):
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 1) # usmNoPrivProtocol
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 1) # usmNoPrivProtocol
def hashPassphrase(self, authProtocol, privKey):
return
diff --git a/pysnmp/proto/secmod/rfc3414/service.py b/pysnmp/proto/secmod/rfc3414/service.py
index b9fa9a2c..a09b98ed 100644
--- a/pysnmp/proto/secmod/rfc3414/service.py
+++ b/pysnmp/proto/secmod/rfc3414/service.py
@@ -38,23 +38,28 @@ class UsmSecurityParameters(rfc1155.TypeCoercionHackMixIn, univ.Sequence):
class SnmpUSMSecurityModel(AbstractSecurityModel):
- securityModelID = 3
- authServices = {hmacmd5.HmacMd5.serviceID: hmacmd5.HmacMd5(),
- hmacsha.HmacSha.serviceID: hmacsha.HmacSha(),
- hmacsha2.HmacSha2.sha224ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha224ServiceID),
- hmacsha2.HmacSha2.sha256ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha256ServiceID),
- hmacsha2.HmacSha2.sha384ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha384ServiceID),
- hmacsha2.HmacSha2.sha512ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha512ServiceID),
- noauth.NoAuth.serviceID: noauth.NoAuth(),
- }
- privServices = {des.Des.serviceID: des.Des(),
- des3.Des3.serviceID: des3.Des3(),
- aes.Aes.serviceID: aes.Aes(),
- aes192.AesBlumenthal192.serviceID: aes192.AesBlumenthal192(),
- aes256.AesBlumenthal256.serviceID: aes256.AesBlumenthal256(),
- aes192.Aes192.serviceID: aes192.Aes192(), # non-standard
- aes256.Aes256.serviceID: aes256.Aes256(), # non-standard
- nopriv.NoPriv.serviceID: nopriv.NoPriv()}
+ SECURITY_MODEL_ID = 3
+
+ AUTH_SERVICES = {
+ hmacmd5.HmacMd5.SERVICE_ID: hmacmd5.HmacMd5(),
+ hmacsha.HmacSha.SERVICE_ID: hmacsha.HmacSha(),
+ hmacsha2.HmacSha2.SHA224_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA224_SERVICE_ID),
+ hmacsha2.HmacSha2.SHA256_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA256_SERVICE_ID),
+ hmacsha2.HmacSha2.SHA384_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA384_SERVICE_ID),
+ hmacsha2.HmacSha2.SHA512_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA512_SERVICE_ID),
+ noauth.NoAuth.SERVICE_ID: noauth.NoAuth(),
+ }
+
+ PRIV_SERVICES = {
+ des.Des.SERVICE_ID: des.Des(),
+ des3.Des3.SERVICE_ID: des3.Des3(),
+ aes.Aes.SERVICE_ID: aes.Aes(),
+ aes192.AesBlumenthal192.SERVICE_ID: aes192.AesBlumenthal192(),
+ aes256.AesBlumenthal256.SERVICE_ID: aes256.AesBlumenthal256(),
+ aes192.Aes192.SERVICE_ID: aes192.Aes192(), # non-standard
+ aes256.Aes256.SERVICE_ID: aes256.Aes256(), # non-standard
+ nopriv.NoPriv.SERVICE_ID: nopriv.NoPriv()
+ }
def __init__(self):
AbstractSecurityModel.__init__(self)
@@ -82,7 +87,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
except NoSuchInstanceError:
self.__paramsBranchId = usmUserEngineID.branchVersionId
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_sec2usr: built snmpEngineId + securityName to userName map, version %s: %r' % (
self.__paramsBranchId, self.__securityToUserMap))
break
@@ -106,11 +111,11 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
try:
userName = self.__securityToUserMap[(securityEngineID, securityName)]
except KeyError:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_sec2usr: no entry exists for snmpEngineId %r, securityName %r' % (securityEngineID, securityName))
raise NoSuchInstanceError() # emulate MIB lookup
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_sec2usr: using userName %r for snmpEngineId %r, securityName %r' % (
userName, securityEngineID, securityName))
@@ -196,8 +201,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode(
pysnmpUsmKeyEntry.name + (1,) + tblIdx2
)
- if usmUserAuthProtocol.syntax in self.authServices:
- localizeKey = self.authServices[usmUserAuthProtocol.syntax].localizeKey
+ if usmUserAuthProtocol.syntax in self.AUTH_SERVICES:
+ localizeKey = self.AUTH_SERVICES[usmUserAuthProtocol.syntax].localizeKey
localAuthKey = localizeKey(pysnmpUsmKeyAuth.syntax,
securityEngineID)
else:
@@ -209,8 +214,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
pysnmpUsmKeyPrivLocalized = pysnmpUsmKeyEntry.getNode(
pysnmpUsmKeyEntry.name + (2,) + tblIdx2
)
- if usmUserPrivProtocol.syntax in self.privServices:
- localizeKey = self.privServices[usmUserPrivProtocol.syntax].localizeKey
+ if usmUserPrivProtocol.syntax in self.PRIV_SERVICES:
+ localizeKey = self.PRIV_SERVICES[usmUserPrivProtocol.syntax].localizeKey
localPrivKey = localizeKey(usmUserAuthProtocol.syntax,
pysnmpUsmKeyPriv.syntax,
securityEngineID)
@@ -243,7 +248,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
if 'usmUserAuthProtocol' in cachedSecurityData:
usmUserAuthProtocol = cachedSecurityData['usmUserAuthProtocol']
else:
- usmUserAuthProtocol = noauth.NoAuth.serviceID
+ usmUserAuthProtocol = noauth.NoAuth.SERVICE_ID
if 'usmUserAuthKeyLocalized' in cachedSecurityData:
usmUserAuthKeyLocalized = cachedSecurityData['usmUserAuthKeyLocalized']
else:
@@ -251,13 +256,13 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
if 'usmUserPrivProtocol' in cachedSecurityData:
usmUserPrivProtocol = cachedSecurityData['usmUserPrivProtocol']
else:
- usmUserPrivProtocol = nopriv.NoPriv.serviceID
+ usmUserPrivProtocol = nopriv.NoPriv.SERVICE_ID
if 'usmUserPrivKeyLocalized' in cachedSecurityData:
usmUserPrivKeyLocalized = cachedSecurityData['usmUserPrivKeyLocalized']
else:
usmUserPrivKeyLocalized = None
securityEngineID = snmpEngineID
- debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: user info read from cache')
+ debug.logger & debug.FLAG_SM and debug.logger('__generateRequestOrResponseMsg: user info read from cache')
elif securityName:
# 3.1.1b
try:
@@ -268,7 +273,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
securityEngineID,
self.__sec2usr(snmpEngine, securityName, securityEngineID)
)
- debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read user info')
+ debug.logger & debug.FLAG_SM and debug.logger('__generateRequestOrResponseMsg: read user info')
except NoSuchInstanceError:
pysnmpUsmDiscovery, = mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscovery')
@@ -292,10 +297,10 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
errorIndication=errind.unknownSecurityName
)
- debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: clone user info')
+ debug.logger & debug.FLAG_SM and debug.logger('__generateRequestOrResponseMsg: clone user info')
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: %s' % exc)
snmpInGenErrs, = mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInGenErrs')
snmpInGenErrs.syntax += 1
@@ -305,13 +310,13 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
else:
# empty username used for engineID discovery
usmUserName = usmUserSecurityName = null
- usmUserAuthProtocol = noauth.NoAuth.serviceID
- usmUserPrivProtocol = nopriv.NoPriv.serviceID
+ usmUserAuthProtocol = noauth.NoAuth.SERVICE_ID
+ usmUserPrivProtocol = nopriv.NoPriv.SERVICE_ID
usmUserAuthKeyLocalized = usmUserPrivKeyLocalized = None
- debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: use empty USM data')
+ debug.logger & debug.FLAG_SM and debug.logger('__generateRequestOrResponseMsg: use empty USM data')
# noinspection PyUnboundLocalVariable
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: local usmUserName %r usmUserSecurityName %r usmUserAuthProtocol %s usmUserPrivProtocol %s securityEngineID %r securityName %r' % (
usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserPrivProtocol, securityEngineID, securityName))
@@ -319,15 +324,15 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.1.2
if securityLevel == 3:
- if (usmUserAuthProtocol == noauth.NoAuth.serviceID or
- usmUserPrivProtocol == nopriv.NoPriv.serviceID):
+ if (usmUserAuthProtocol == noauth.NoAuth.SERVICE_ID or
+ usmUserPrivProtocol == nopriv.NoPriv.SERVICE_ID):
raise error.StatusInformation(
errorIndication=errind.unsupportedSecurityLevel
)
# 3.1.3
if securityLevel == 3 or securityLevel == 2:
- if usmUserAuthProtocol == noauth.NoAuth.serviceID:
+ if usmUserAuthProtocol == noauth.NoAuth.SERVICE_ID:
raise error.StatusInformation(
errorIndication=errind.unsupportedSecurityLevel
)
@@ -345,14 +350,14 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
pdu = scopedPDU.getComponentByPosition(2).getComponent()
# 3.1.6.b
- if pdu.tagSet in rfc3411.unconfirmedClassPDUs:
+ if pdu.tagSet in rfc3411.UNCONFIRMED_CLASS_PDUS:
(snmpEngineBoots,
snmpEngineTime) = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime')
snmpEngineBoots = snmpEngineBoots.syntax
snmpEngineTime = snmpEngineTime.syntax.clone()
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from LCD')
# 3.1.6a
@@ -362,41 +367,41 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
latestReceivedEngineTime,
latestUpdateTimestamp) = self.__timeline[securityEngineID]
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from timeline')
# 3.1.6.c
else:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: assuming zero snmpEngineBoots, snmpEngineTime')
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: use snmpEngineBoots %s snmpEngineTime %s for securityEngineID %r' % (
snmpEngineBoots, snmpEngineTime, securityEngineID))
# 3.1.4a
if securityLevel == 3:
- if usmUserPrivProtocol in self.privServices:
- privHandler = self.privServices[usmUserPrivProtocol]
+ if usmUserPrivProtocol in self.PRIV_SERVICES:
+ privHandler = self.PRIV_SERVICES[usmUserPrivProtocol]
else:
raise error.StatusInformation(
errorIndication=errind.encryptionError
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: scopedPDU %s' % scopedPDU.prettyPrint())
try:
dataToEncrypt = encoder.encode(scopedPDU)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: scopedPDU serialization error: %s' % exc)
raise error.StatusInformation(
errorIndication=errind.serializationError
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: scopedPDU encoded into %s' % debug.hexdump(dataToEncrypt))
# noinspection PyUnboundLocalVariable
@@ -413,14 +418,14 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
1, encryptedData, verifyConstraints=False, matchTags=False, matchConstraints=False
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: scopedPDU ciphered into %s' % debug.hexdump(encryptedData))
# 3.1.4b
elif securityLevel == 1 or securityLevel == 2:
securityParameters.setComponentByPosition(5, '')
- debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % scopedPDUData.prettyPrint())
+ debug.logger & debug.FLAG_SM and debug.logger('__generateRequestOrResponseMsg: %s' % scopedPDUData.prettyPrint())
# 3.1.5
securityParameters.setComponentByPosition(
@@ -440,8 +445,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.1.8a
if securityLevel == 3 or securityLevel == 2:
- if usmUserAuthProtocol in self.authServices:
- authHandler = self.authServices[usmUserAuthProtocol]
+ if usmUserAuthProtocol in self.AUTH_SERVICES:
+ authHandler = self.AUTH_SERVICES[usmUserAuthProtocol]
else:
raise error.StatusInformation(
errorIndication=errind.authenticationFailure
@@ -452,27 +457,27 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
4, '\x00' * authHandler.digestLength
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),))
try:
msg.setComponentByPosition(2, encoder.encode(securityParameters), verifyConstraints=False)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: securityParameters serialization error: %s' % exc)
raise error.StatusInformation(
errorIndication=errind.serializationError
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: auth outgoing msg: %s' % msg.prettyPrint())
try:
wholeMsg = encoder.encode(msg)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: msg serialization error: %s' % exc)
raise error.StatusInformation(
errorIndication=errind.serializationError
@@ -489,32 +494,32 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
4, '', verifyConstraints=False, matchTags=False, matchConstraints=False
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),))
try:
msg.setComponentByPosition(2, encoder.encode(securityParameters), verifyConstraints=False, matchTags=False, matchConstraints=False)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: secutiryParameters serialization error: %s' % exc)
raise error.StatusInformation(
errorIndication=errind.serializationError
)
try:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: plain outgoing msg: %s' % msg.prettyPrint())
authenticatedWholeMsg = encoder.encode(msg)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: msg serialization error: %s' % exc)
raise error.StatusInformation(
errorIndication=errind.serializationError
)
- debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s outgoing msg: %s' % (
+ debug.logger & debug.FLAG_SM and debug.logger('__generateRequestOrResponseMsg: %s outgoing msg: %s' % (
securityLevel > 1 and "authenticated" or "plain", debug.hexdump(authenticatedWholeMsg)))
# 3.1.9
@@ -556,7 +561,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# (48 - maximum SNMPv3 header length)
maxSizeResponseScopedPDU = int(maxMessageSize) - len(securityParameters) - 48
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: securityParameters %s' % debug.hexdump(securityParameters))
# 3.2.1
@@ -564,7 +569,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
securityParameters, asn1Spec=self.__securityParametersSpec
)
- debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (securityParameters.prettyPrint(),))
+ debug.logger & debug.FLAG_SM and debug.logger('processIncomingMsg: %s' % (securityParameters.prettyPrint(),))
if eoo.endOfOctets.isSameTypeWith(securityParameters):
raise error.StatusInformation(errorIndication=errind.parseError)
@@ -575,7 +580,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
msgUserName=securityParameters.getComponentByPosition(3)
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: cache write securityStateReference %s by msgUserName %s' % (
securityStateReference, securityParameters.getComponentByPosition(3)))
@@ -593,26 +598,26 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
if (msgAuthoritativeEngineId and
4 < len(msgAuthoritativeEngineId) < 33):
# 3.2.3a - cloned user when request was sent
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: non-synchronized securityEngineID %r' % (msgAuthoritativeEngineId,))
else:
# 3.2.3b
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: peer requested snmpEngineID discovery')
usmStatsUnknownEngineIDs, = mibBuilder.importSymbols(
'__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownEngineIDs')
usmStatsUnknownEngineIDs.syntax += 1
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: null or malformed msgAuthoritativeEngineId')
pysnmpUsmDiscoverable, = mibBuilder.importSymbols(
'__PYSNMP-USM-MIB', 'pysnmpUsmDiscoverable')
if pysnmpUsmDiscoverable.syntax:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: starting snmpEngineID discovery procedure')
# Report original contextName
if scopedPduData.getName() != 'plaintext':
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: scopedPduData not plaintext %s' % scopedPduData.prettyPrint())
raise error.StatusInformation(
errorIndication=errind.unknownEngineID
@@ -635,7 +640,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
maxSizeResponseScopedPDU=maxSizeResponseScopedPDU
)
else:
- debug.logger & debug.flagSM and debug.logger('processIncomingMsg: will not discover EngineID')
+ debug.logger & debug.FLAG_SM and debug.logger('processIncomingMsg: will not discover EngineID')
# free securityStateReference XXX
raise error.StatusInformation(
errorIndication=errind.unknownEngineID
@@ -643,7 +648,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
msgUserName = securityParameters.getComponentByPosition(3)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: read from securityParams msgAuthoritativeEngineId %r msgUserName %r' % (
msgAuthoritativeEngineId, msgUserName))
@@ -659,10 +664,10 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
snmpEngine.msgAndPduDsp.mibInstrumController,
msgAuthoritativeEngineId, msgUserName
)
- debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read user info from LCD')
+ debug.logger & debug.FLAG_SM and debug.logger('processIncomingMsg: read user info from LCD')
except NoSuchInstanceError:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: unknown securityEngineID %r msgUserName %r' % (
msgAuthoritativeEngineId, msgUserName))
@@ -683,18 +688,18 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % exc)
+ debug.logger & debug.FLAG_SM and debug.logger('processIncomingMsg: %s' % exc)
snmpInGenErrs, = mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInGenErrs')
snmpInGenErrs.syntax += 1
raise error.StatusInformation(errorIndication=errind.invalidMsg)
else:
# empty username used for engineID discovery
usmUserName = usmUserSecurityName = null
- usmUserAuthProtocol = noauth.NoAuth.serviceID
- usmUserPrivProtocol = nopriv.NoPriv.serviceID
+ usmUserAuthProtocol = noauth.NoAuth.SERVICE_ID
+ usmUserPrivProtocol = nopriv.NoPriv.SERVICE_ID
usmUserAuthKeyLocalized = usmUserPrivKeyLocalized = None
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: now have usmUserName %r usmUserSecurityName %r usmUserAuthProtocol %r usmUserPrivProtocol %r for msgUserName %r' % (
usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserPrivProtocol, msgUserName))
@@ -733,28 +738,28 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# Authoritative SNMP engine: make sure securityLevel is sufficient
badSecIndication = None
if securityLevel == 3:
- if usmUserAuthProtocol == noauth.NoAuth.serviceID:
+ if usmUserAuthProtocol == noauth.NoAuth.SERVICE_ID:
badSecIndication = 'authPriv wanted while auth not expected'
- if usmUserPrivProtocol == nopriv.NoPriv.serviceID:
+ if usmUserPrivProtocol == nopriv.NoPriv.SERVICE_ID:
badSecIndication = 'authPriv wanted while priv not expected'
elif securityLevel == 2:
- if usmUserAuthProtocol == noauth.NoAuth.serviceID:
+ if usmUserAuthProtocol == noauth.NoAuth.SERVICE_ID:
badSecIndication = 'authNoPriv wanted while auth not expected'
- if usmUserPrivProtocol != nopriv.NoPriv.serviceID:
+ if usmUserPrivProtocol != nopriv.NoPriv.SERVICE_ID:
# 4 (discovery phase always uses authenticated messages)
if msgAuthoritativeEngineBoots or msgAuthoritativeEngineTime:
badSecIndication = 'authNoPriv wanted while priv expected'
elif securityLevel == 1:
- if usmUserAuthProtocol != noauth.NoAuth.serviceID:
+ if usmUserAuthProtocol != noauth.NoAuth.SERVICE_ID:
badSecIndication = 'noAuthNoPriv wanted while auth expected'
- if usmUserPrivProtocol != nopriv.NoPriv.serviceID:
+ if usmUserPrivProtocol != nopriv.NoPriv.SERVICE_ID:
badSecIndication = 'noAuthNoPriv wanted while priv expected'
if badSecIndication:
usmStatsUnsupportedSecLevels, = mibBuilder.importSymbols(
'__SNMP-USER-BASED-SM-MIB', 'usmStatsUnsupportedSecLevels')
usmStatsUnsupportedSecLevels.syntax += 1
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: reporting inappropriate security level for user %s: %s' % (
msgUserName, badSecIndication))
raise error.StatusInformation(
@@ -771,8 +776,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.2.6
if securityLevel == 3 or securityLevel == 2:
- if usmUserAuthProtocol in self.authServices:
- authHandler = self.authServices[usmUserAuthProtocol]
+ if usmUserAuthProtocol in self.AUTH_SERVICES:
+ authHandler = self.AUTH_SERVICES[usmUserAuthProtocol]
else:
raise error.StatusInformation(
errorIndication=errind.authenticationFailure
@@ -801,7 +806,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
maxSizeResponseScopedPDU=maxSizeResponseScopedPDU
)
- debug.logger & debug.flagSM and debug.logger('processIncomingMsg: incoming msg authenticated')
+ debug.logger & debug.FLAG_SM and debug.logger('processIncomingMsg: incoming msg authenticated')
# synchronize time with authed peer
self.__timeline[msgAuthoritativeEngineId] = (
@@ -817,7 +822,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
self.__timelineExpQueue[expireAt] = []
self.__timelineExpQueue[expireAt].append(msgAuthoritativeEngineId)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: store timeline for securityEngineID %r' % (msgAuthoritativeEngineId,))
# 3.2.7
@@ -830,7 +835,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
snmpEngineBoots = snmpEngineBoots.syntax
snmpEngineTime = snmpEngineTime.syntax.clone()
idleTime = 0
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: read snmpEngineBoots (%s), snmpEngineTime (%s) from LCD' % (
snmpEngineBoots, snmpEngineTime))
else:
@@ -843,7 +848,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
]
# time passed since last talk with this SNMP engine
idleTime = int(time.time()) - latestUpdateTimestamp
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: read timeline snmpEngineBoots %s snmpEngineTime %s for msgAuthoritativeEngineId %r, idle time %s secs' % (
snmpEngineBoots, snmpEngineTime, msgAuthoritativeEngineId, idleTime))
else:
@@ -888,7 +893,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
self.__timelineExpQueue[expireAt] = []
self.__timelineExpQueue[expireAt].append(msgAuthoritativeEngineId)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: stored timeline msgAuthoritativeEngineBoots %s msgAuthoritativeEngineTime %s for msgAuthoritativeEngineId %r' % (
msgAuthoritativeEngineBoots, msgAuthoritativeEngineTime, msgAuthoritativeEngineId))
@@ -904,8 +909,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.2.8a
if securityLevel == 3:
- if usmUserPrivProtocol in self.privServices:
- privHandler = self.privServices[usmUserPrivProtocol]
+ if usmUserPrivProtocol in self.PRIV_SERVICES:
+ privHandler = self.PRIV_SERVICES[usmUserPrivProtocol]
else:
raise error.StatusInformation(
errorIndication=errind.decryptionError,
@@ -926,7 +931,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
securityParameters.getComponentByPosition(5)),
encryptedPDU
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: PDU deciphered into %s' % debug.hexdump(decryptedData))
except error.StatusInformation:
@@ -949,7 +954,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
scopedPDU, rest = decoder.decode(decryptedData, asn1Spec=scopedPduSpec)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: scopedPDU decoder failed %s' % exc)
raise error.StatusInformation(
errorIndication=errind.decryptionError,
@@ -970,13 +975,13 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
msgUserName=msgUserName
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: scopedPDU decoded %s' % scopedPDU.prettyPrint())
# 3.2.10
securityName = usmUserSecurityName
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: cached msgUserName %s info by securityStateReference %s' % (
msgUserName, securityStateReference))
@@ -1008,7 +1013,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
for engineIdKey in self.__timelineExpQueue[self.__expirationTimer]:
if engineIdKey in self.__timeline:
del self.__timeline[engineIdKey]
- debug.logger & debug.flagSM and debug.logger('__expireTimelineInfo: expiring %r' % (engineIdKey,))
+ debug.logger & debug.FLAG_SM and debug.logger('__expireTimelineInfo: expiring %r' % (engineIdKey,))
del self.__timelineExpQueue[self.__expirationTimer]
self.__expirationTimer += 1
diff --git a/pysnmp/proto/secmod/rfc3826/priv/aes.py b/pysnmp/proto/secmod/rfc3826/priv/aes.py
index b7e32684..8a67ecc2 100644
--- a/pysnmp/proto/secmod/rfc3826/priv/aes.py
+++ b/pysnmp/proto/secmod/rfc3826/priv/aes.py
@@ -5,8 +5,10 @@
# License: http://snmplabs.com/pysnmp/license.html
#
import random
+
try:
from hashlib import md5, sha1
+
except ImportError:
import md5
import sha
@@ -36,25 +38,26 @@ random.seed()
#
class Aes(base.AbstractEncryptionService):
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 4) # usmAesCfb128Protocol
- keySize = 16
- _localInt = random.randrange(0, 0xffffffffffffffff)
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 4) # usmAesCfb128Protocol
+ KEY_SIZE = 16
+
+ local_int = random.randrange(0, 0xffffffffffffffff)
# 3.1.2.1
def __getEncryptionKey(self, privKey, snmpEngineBoots, snmpEngineTime):
- salt = [self._localInt >> 56 & 0xff,
- self._localInt >> 48 & 0xff,
- self._localInt >> 40 & 0xff,
- self._localInt >> 32 & 0xff,
- self._localInt >> 24 & 0xff,
- self._localInt >> 16 & 0xff,
- self._localInt >> 8 & 0xff,
- self._localInt & 0xff]
-
- if self._localInt == 0xffffffffffffffff:
- self._localInt = 0
+ salt = [self.local_int >> 56 & 0xff,
+ self.local_int >> 48 & 0xff,
+ self.local_int >> 40 & 0xff,
+ self.local_int >> 32 & 0xff,
+ self.local_int >> 24 & 0xff,
+ self.local_int >> 16 & 0xff,
+ self.local_int >> 8 & 0xff,
+ self.local_int & 0xff]
+
+ if self.local_int == 0xffffffffffffffff:
+ self.local_int = 0
else:
- self._localInt += 1
+ self.local_int += 1
return self.__getDecryptionKey(privKey, snmpEngineBoots, snmpEngineTime, salt) + (
univ.OctetString(salt).asOctets(),)
@@ -74,15 +77,15 @@ class Aes(base.AbstractEncryptionService):
snmpEngineTime >> 8 & 0xff,
snmpEngineTime & 0xff] + salt
- return privKey[:self.keySize].asOctets(), univ.OctetString(iv).asOctets()
+ return privKey[:self.KEY_SIZE].asOctets(), univ.OctetString(iv).asOctets()
def hashPassphrase(self, authProtocol, privKey):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
@@ -90,18 +93,18 @@ class Aes(base.AbstractEncryptionService):
return localkey.hashPassphrase(privKey, hashAlgo)
def localizeKey(self, authProtocol, privKey, snmpEngineID):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
)
localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo)
- return localPrivKey[:self.keySize]
+ return localPrivKey[:self.KEY_SIZE]
# 3.2.4.1
def encryptData(self, encryptKey, privParameters, dataToEncrypt):
diff --git a/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py b/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py
index 219b90d6..495f8fcd 100644
--- a/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py
+++ b/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py
@@ -26,37 +26,40 @@ from pysnmp.proto import errind, error
# 7.2.4
class HmacSha2(base.AbstractAuthenticationService):
- sha224ServiceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 4) # usmHMAC128SHA224AuthProtocol
- sha256ServiceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 5) # usmHMAC192SHA256AuthProtocol
- sha384ServiceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 6) # usmHMAC256SHA384AuthProtocol
- sha512ServiceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 7) # usmHMAC384SHA512AuthProtocol
- keyLengths = {
- sha224ServiceID: 28,
- sha256ServiceID: 32,
- sha384ServiceID: 48,
- sha512ServiceID: 64
+ SHA224_SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 4) # usmHMAC128SHA224AuthProtocol
+ SHA256_SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 5) # usmHMAC192SHA256AuthProtocol
+ SHA384_SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 6) # usmHMAC256SHA384AuthProtocol
+ SHA512_SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 7) # usmHMAC384SHA512AuthProtocol
+
+ KEY_LENGTH = {
+ SHA224_SERVICE_ID: 28,
+ SHA256_SERVICE_ID: 32,
+ SHA384_SERVICE_ID: 48,
+ SHA512_SERVICE_ID: 64
}
- digestLengths = {
- sha224ServiceID: 16,
- sha256ServiceID: 24,
- sha384ServiceID: 32,
- sha512ServiceID: 48
+
+ DIGEST_LENGTH = {
+ SHA224_SERVICE_ID: 16,
+ SHA256_SERVICE_ID: 24,
+ SHA384_SERVICE_ID: 32,
+ SHA512_SERVICE_ID: 48
}
- hashAlgorithms = {
- sha224ServiceID: sha224,
- sha256ServiceID: sha256,
- sha384ServiceID: sha384,
- sha512ServiceID: sha512
+
+ HASH_ALGORITHM = {
+ SHA224_SERVICE_ID: sha224,
+ SHA256_SERVICE_ID: sha256,
+ SHA384_SERVICE_ID: sha384,
+ SHA512_SERVICE_ID: sha512
}
- __ipad = [0x36] * 64
- __opad = [0x5C] * 64
+ IPAD = [0x36] * 64
+ OPAD = [0x5C] * 64
def __init__(self, oid):
- if oid not in self.hashAlgorithms:
+ if oid not in self.HASH_ALGORITHM:
raise error.ProtocolError('No SHA-2 authentication algorithm %s available' % (oid,))
- self.__hashAlgo = self.hashAlgorithms[oid]
- self.__digestLength = self.digestLengths[oid]
+ self.__hashAlgo = self.HASH_ALGORITHM[oid]
+ self.__digestLength = self.DIGEST_LENGTH[oid]
self.__placeHolder = univ.OctetString((0,) * self.__digestLength).asOctets()
def hashPassphrase(self, authKey):